How to use UUID as primary key postgre

Hello, my name is Patrick, and this is my first post in this forum, i have a problem, on my project i I would like to turn a UUID column as primary key using Postgre, after various hours of search on internet, I did not find a solution

My Schema is this:

'use strict'

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')

class CoreUserCategorySchema extends Schema {
  up () {
    this.create('core_user_category', (table) => {
      table
        .uuid('id')
        .primary()
      table.string('title')
      table.timestamps()
    })
  }

  down () {
    this.drop('core_user_category')
  }
}

module.exports = CoreUserCategorySchema

I did find this issue on github, but after trying this, i get this response:

You can help me?

Thanks xD

1 Like

Yes, i’m currently using the package uuid from node, i use this for make my primary key before add on database, you see problem this?

Hi @patrickalima98

You can make migration, that generates UUID on database

// First you have to enable extension
async up () {
  await this.db.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
}

And then in new migrations you can set database to automatically generate new UUIDs on each insert. Then you don’t have to worry about it in application layer

this.create('users', (table) => {
  table.uuid('uuid').primary().defaultTo(this.db.raw('uuid_generate_v4()'))
})
2 Likes

I never used this uuid stuff, thank you for sharing

1 Like

@McSneaky Thank you so much, for answer my question, I tried now and functioned perfectly xD