import { Scope } from '../Scope' ; import { Store } from '../Store' ; import { Run } from './Run' ; import * as Knex from 'knex' ; import * as Bluebird from 'bluebird' ; export class Migration { type { Scope } private entityManager : Scope ; type { { } [ ] } private builders : Array < { store : string ; schemaBuilder : Knex . SchemaBuilder ; knex : Knex ; } > = [ ] ; type { Function } private migration : Function ; type { Run } private migrationRun : Run ; type { boolean } private promise : boolean = false ; param { Function } migration param { Run } run public constructor ( migration , run ) { this . migration = migration ; this . entityManager = run . getEntityManager ( ) ; this . migrationRun = run ; this . prepare ( ) ; } param { string } store returns { Knex . SchemaBuilder } public getSchemaBuilder ( store ? ) { return this . getBuilder ( store ) . schema ; } param { string } storeName returns { Bluebird < Knex . Transaction > } public getTransaction ( storeName ? ) { return this . migrationRun . getTransaction ( storeName ) ; } param { string } store returns { { schema : Knex . SchemaBuilder , knex : Knex } } public getBuilder ( store ? ) { const connection = this . getConnection ( store ) ; const schemaBuilder = connection . schema ; this . builders . push ( { store , schemaBuilder , knex : connection } ) ; return { schema : schemaBuilder , knex : connection } ; } returns { string } public getSQL ( ) { if ( this . promise ) { throw new Error ( 'It\'s not possible to get SQL for a promise based migration.' ) ; } return this . builders . map ( builder => builder . schemaBuilder . toString ( ) ) . join ( '\n' ) ; } returns { Bluebird < any > } public run ( ) { return Bluebird . each ( this . builders , builder => { return this . getTransaction ( builder . store ) . then ( transaction => { return builder . schemaBuilder [ 'transacting' ] ( transaction ) . then ( ) ; } ) ; } ) ; } /**
     * Prepare the migration by running it.
     */ private prepare ( ) { const prepared = this . migration ( this ) ; if ( prepared && 'then' in prepared ) { this . promise = true ; } } param { string } store returns { knex } private getConnection ( store ? ) { return this . entityManager . getStore ( store ) . getConnection ( Store . ROLE_MASTER ) ; } }