Skip to content

Commit

Permalink
Merge pull request #543 from contember/refactor/migrations-seq
Browse files Browse the repository at this point in the history
migration tables: do not use sequences
  • Loading branch information
matej21 authored Jul 12, 2024
2 parents 67b8e1d + 6f6e62a commit bb5e09f
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 17 deletions.
17 changes: 13 additions & 4 deletions packages/database-migrations/src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,20 @@ const ensureMigrationsTable = async (db: Connection.ConnectionLike, options: Run
const fullTableName = getMigrationsTableName(options)
await db.query(`
CREATE TABLE IF NOT EXISTS ${fullTableName} (
id SERIAL PRIMARY KEY,
id INT PRIMARY KEY,
name varchar(255) NOT NULL,
run_on timestamp NOT NULL
)`,
)
await db.query(`ALTER TABLE ${fullTableName} ADD COLUMN IF NOT EXISTS "group" TEXT DEFAULT NULL`)

await db.query(`ALTER TABLE ${fullTableName} ALTER id DROP DEFAULT`)
const seqName = (await db.query<{seq_name: string}>(`
SELECT pg_get_serial_sequence('${fullTableName}', 'id') as seq_name
`)).rows[0].seq_name
if (seqName) {
await db.query(`DROP SEQUENCE ${seqName}`)
}
} catch (err) {
if (!(err instanceof Error)) {
throw err
Expand Down Expand Up @@ -112,10 +120,11 @@ export default async <Args>(
for (const sql of steps) {
await trx.query(sql)
}

const maxId = await trx.query<{id: number}>(`SELECT MAX(id) as id FROM ${getMigrationsTableName(options)}`)
const nextId = (maxId.rows[0]?.id ?? 0) + 1
await trx.query(
`INSERT INTO ${getMigrationsTableName(options)} (name, run_on, "group") VALUES (?, NOW(), ?);`,
[migration.name, migration.group],
`INSERT INTO ${getMigrationsTableName(options)} (id, name, run_on, "group") VALUES (?, ?, NOW(), ?);`,
[nextId, migration.name, migration.group],
)
logger(` Done`)
} catch (e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { MigrationBuilder } from '@contember/database-migrations'

const sql = `
ALTER TABLE schema_migration ALTER id DROP DEFAULT;
DO LANGUAGE plpgsql
$$
BEGIN
EXECUTE FORMAT('DROP SEQUENCE %s', PG_GET_SERIAL_SEQUENCE('schema_migration', 'id'));
END
$$
`

export default async function (builder: MigrationBuilder) {
builder.sql(sql)
}
2 changes: 2 additions & 0 deletions packages/engine-system-api/src/migrations/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import _20221003110000tableondelete from './2022-10-03-110000-table-on-delete'
import _20230911174000fixondelete from './2023-09-11-174000-fix-on-delete'
import _20231019173000fixunique from './2023-10-19-173000-fix-unique'
import _20231024140000schemanullablechecksum from './2023-10-24-140000-schema-nullable-checksum'
import _20240628150000migrationsdropsequence from './2024-06-28-150000-migrations-drop-sequence'
import snapshot from './snapshot'

import { Connection, createDatabaseIfNotExists, DatabaseConfig, DatabaseMetadataResolver } from '@contember/database'
Expand Down Expand Up @@ -54,6 +55,7 @@ const migrations = {
'2023-09-11-174000-fix-on-delete': _20230911174000fixondelete,
'2023-10-19-173000-fix-unique': _20231019173000fixunique,
'2023-10-24-140000-schema-nullable-checksum': _20231024140000schemanullablechecksum,
'2024-06-28-150000-migrations-drop-sequence': _20240628150000migrationsdropsequence,
}


Expand Down
9 changes: 0 additions & 9 deletions packages/engine-system-api/src/migrations/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,6 @@ CREATE TABLE "schema_migration" (
"executed_at" timestamp with time zone DEFAULT "now"() NOT NULL,
"type" "schema_migration_type" DEFAULT 'schema'::"schema_migration_type" NOT NULL
);
CREATE SEQUENCE "schema_migration_id_seq"
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER SEQUENCE "schema_migration_id_seq" OWNED BY "schema_migration"."id";
CREATE TABLE "stage" (
"id" "uuid" NOT NULL,
"name" "text" NOT NULL,
Expand All @@ -143,7 +135,6 @@ CREATE TABLE "stage_transaction" (
"stage_id" "uuid" NOT NULL,
"applied_at" timestamp with time zone NOT NULL
);
ALTER TABLE ONLY "schema_migration" ALTER COLUMN "id" SET DEFAULT "nextval"('"schema_migration_id_seq"'::"regclass");
ALTER TABLE ONLY "event_data"
ADD CONSTRAINT "event_data_pkey" PRIMARY KEY ("id");
ALTER TABLE ONLY "schema_migration"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { InsertBuilder, QueryBuilder } from '@contember/database'
import { InsertBuilder, Literal, QueryBuilder, SelectBuilder } from '@contember/database'
import { calculateMigrationChecksum } from '@contember/schema-migrations'
import { Command } from '../Command'
import { MigrationInput } from '../../migrations/MigrationInput'
Expand All @@ -22,12 +22,18 @@ export class SaveMigrationCommand implements Command<number> {
checksum: this.migration.type === 'schema' ? calculateMigrationChecksum(this.migration) : null,
}

const latestId = (await SelectBuilder.create<{ id: number }>()
.from('schema_migration')
.select(new Literal('max(id)'), 'id')
.getResult(db)
)[0]?.id ?? 0

const newId = latestId + 1
const result = await InsertBuilder.create()
.into('schema_migration')
.values(values)
.returning<{id: number}>('id')
.values({ id: newId, ...values })
.execute(db)

return result[0].id
return newId
}
}

0 comments on commit bb5e09f

Please sign in to comment.