{{{
  exports({ to: app.migrationsPath(`${new Date().getTime()}_create_media_table.ts`) })
}}}
import { BaseSchema } from '@adonisjs/lucid/schema'

/**
 * The 'media' table for the @adonis-agora/media 'lucid' store. JSON payloads ('custom_properties',
 * 'conversions') are stored as TEXT — the store (de)serializes them — and timestamps as epoch-ms
 * integers, so the schema is portable across SQLite / Postgres / MySQL.
 */
/**
 * The database schema the table lives in: the same value as 'schema' in stores.lucid(). Leave it
 * undefined to use the connection's current schema. On MySQL a schema is a database.
 */
const schema: string | undefined = undefined

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

  async up() {
    if (schema) {
      const create = this.db.dialect.name === 'mysql' ? 'CREATE DATABASE' : 'CREATE SCHEMA'
      this.schema.raw(this.db.knexRawQuery(create + ' IF NOT EXISTS ??', [schema]).toQuery())
    }
    this.builder().createTable(this.tableName, (table) => {
      table.string('id').primary()
      table.string('owner_type').notNullable()
      table.string('owner_id').notNullable()
      table.string('collection').notNullable()
      table.string('name').notNullable()
      table.string('file_name').notNullable()
      table.string('mime_type').notNullable()
      table.bigInteger('size').notNullable()
      table.string('disk').notNullable()
      table.text('path').notNullable()
      table.integer('order').notNullable().defaultTo(0)
      table.text('custom_properties')
      table.text('conversions')
      table.bigInteger('created_at').notNullable()
      table.bigInteger('updated_at').notNullable()
      table.index(['owner_type', 'owner_id', 'collection'], 'media_owner_collection_idx')
      table.index(['created_at', 'id'], 'media_created_idx')
      table.index(['collection', 'created_at', 'id'], 'media_collection_created_idx')
    })
  }

  async down() {
    this.builder().dropTable(this.tableName)
  }

  /** The schema builder, pointed at 'schema' when it is set. */
  private builder() {
    return schema ? this.schema.withSchema(schema) : this.schema
  }
}
