Knex: UUID and MD5 generated

Created on 12 Jun 2016  ·  5Comments  ·  Source: knex/knex

how to generate a new uuid or md5 random to save on postgresql, for example:

screen shot 2016-06-12 at 5 10 36 pm

But the 'knex.raw('uuid_generate_v4()')' does not work, I wonder how can I do to generate a random hash and save automatic when creating a new record?

and it also seems that uuid-v4 can not generate random because of migration that is static and unchanged for each request.

screen shot 2016-06-12 at 5 23 16 pm

Sorry I'm studying node due to own and my only help is google and github, I thank you for your help.

Most helpful comment

You need to make sure the extension is available:

knex.raw('create extension if not exists "uuid-ossp"')

then you can do

table.string('hash').defaultTo(knex.raw('uuid_generate_v4()'))

don't forget down migration:

knex.raw('drop extension if exists "uuid-ossp"')

Edit: You can use uuid type instead of string when using pg, e.g:

await knex.schema.createTable('Users', t => {
  t.uuid('id').defaultTo(knex.raw('uuid_generate_v4()'))
  // ...
})

All 5 comments

What is the reason why

But the 'knex.raw('uuid_generate_v4()')'

Doesn't work? Does that work with postgrsql when you try to use it with plain sql wirhout knex?

Try also running your code with DEBUG=knex:* evironment variable set to get more info whats going on with your queries.

@anzileiro, you should not use uuis-v4 package in migrations, but in your models, for example before saving a new model, set its property hash to the value of uuid() and then save it

You need to make sure the extension is available:

knex.raw('create extension if not exists "uuid-ossp"')

then you can do

table.string('hash').defaultTo(knex.raw('uuid_generate_v4()'))

don't forget down migration:

knex.raw('drop extension if exists "uuid-ossp"')

Edit: You can use uuid type instead of string when using pg, e.g:

await knex.schema.createTable('Users', t => {
  t.uuid('id').defaultTo(knex.raw('uuid_generate_v4()'))
  // ...
})

Thanks @fl0w, case closed ☺️

Thanks guys!

👍

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nklhrstv picture nklhrstv  ·  3Comments

sandrocsimas picture sandrocsimas  ·  3Comments

saurabhghewari picture saurabhghewari  ·  3Comments

koskimas picture koskimas  ·  3Comments

mishitpatel picture mishitpatel  ·  3Comments