@@ -140,6 +140,28 @@ export async function runMigrations(mc) {
140140 try {
141141 const migrationFiles = filterMigrationsToBeApplied ( mc ) ;
142142
143+ if ( mc . missingMigrationTable && migrationFiles . length > 0 ) {
144+ mc . missingMigrationTable = false ;
145+
146+ if (
147+ ! migrationFiles [ 0 ] ?. source . includes ( `migration_namespace_number_idx` )
148+ ) {
149+ // Automatically create the migration table
150+ await mc . sql . unsafe ( `
151+ CREATE TABLE IF NOT EXISTS migration
152+ (
153+ "namespace" varchar NOT NULL,
154+ "number" int,
155+ "name" varchar NOT NULL,
156+ "createdAt" timestamptz DEFAULT now(),
157+ "hash" varchar
158+ );
159+
160+ CREATE INDEX IF NOT EXISTS migration_namespace_number_idx ON "migration" ("namespace", "number");
161+ ` ) ;
162+ }
163+ }
164+
143165 for ( const migration of migrationFiles ) {
144166 current = migration ;
145167 await runMigration ( mc . sql , migration ) ;
@@ -175,7 +197,10 @@ export async function runMigrations(mc) {
175197export async function rebuildMigrations ( mc ) {
176198 try {
177199 await mc . sql . begin ( async ( sql ) => {
178- await sql `DELETE FROM "migration" WHERE 1 = 1` ;
200+ await sql `DELETE
201+ FROM "migration"
202+ WHERE
203+ 1 = 1` ;
179204
180205 for ( const file of mc . files ) {
181206 await runInsert ( sql , file ) ;
@@ -279,12 +304,14 @@ async function syncWithSchemaState(mc) {
279304 let rows = [ ] ;
280305 try {
281306 rows = await mc . sql `
282- SELECT DISTINCT ON (number) number, hash
283- FROM migration
284- ORDER BY number, "createdAt" DESC
285- ` ;
307+ SELECT DISTINCT ON (number) number, hash
308+ FROM migration
309+ ORDER BY number, "createdAt" DESC
310+ ` ;
286311 } catch ( /** @type {any } */ e ) {
287- if ( ( e . message ?? "" ) . indexOf ( `"migration" does not exist` ) === - 1 ) {
312+ if ( ( e . message ?? "" ) . includes ( `"migration" does not exist` ) ) {
313+ mc . missingMigrationTable = true ;
314+ } else {
288315 throw new AppError (
289316 "store.migrateSync.error" ,
290317 500 ,
0 commit comments