adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.03k stars 189 forks source link

Is it possible to define indexes inside a model definition ? #908

Closed assaad97 closed 1 year ago

assaad97 commented 1 year ago

Hello, im using lucid with adonisJs 5, and im trying to define indexes inside my models, i don't want to do it via migrations since the database that im using is already populated.

RomainLanz commented 1 year ago

Hello @assaad97! 👋🏻

Unfortunately, it is not possible for a model to take into account whether a field has an index or not. However, even if your database is already populated, you can use migrations to add indexes to specific fields as needed.

Example:

import BaseSchema from '@ioc:Adonis/Lucid/Schema'

export default class extends BaseSchema {
  protected tableName = 'X'

  public async up() {
    this.schema.alterTable(this.tableName, (table) => {
      table.integer('type').notNullable().index().alter()
      table.index(['type', 'user_id'])
    })
  }

  public async down() {
    this.schema.alterTable(this.tableName, (table) => {
      table.integer('type').nullable().alter()
      table.dropIndex(['type', 'user_id'])
    })
  }
}