sqerge 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,7 +22,7 @@ A forward only PostgreSQL migration tool. Uses [Postgres.js](https://github.com/
22
22
  ```
23
23
  4. Create some migration files
24
24
 
25
- The filename **prefix** represents the execution order, a unique integer followed by a hyphen. After the hyphen, it's all yours. Files not matching the prefix are ignored.
25
+ The filename **prefix** represents the execution order, a unique integer followed by a hyphen, such as `1-` or a timestamp like `20261123120000-`. After the hyphen, it's all yours. Files not matching the prefix are ignored.
26
26
 
27
27
  ```sql
28
28
  -- file: ./foo/1-bar.sql
@@ -72,6 +72,29 @@ A forward only PostgreSQL migration tool. Uses [Postgres.js](https://github.com/
72
72
  [sqerge] file 3 (3-baz.js): executed
73
73
  ```
74
74
 
75
+ ## Transactions
76
+
77
+ sqerge executes migration files in a single transaction, so if one fails, none of the files in that run are applied.
78
+
79
+ Some statements, such as `CREATE INDEX CONCURRENTLY`, can't run in a transaction. To execute a file outside of a transaction, add **.no-transaction** before the extension. This works for **.sql**, **.js** and **.mjs** files.
80
+
81
+ ```sql
82
+ -- file: ./foo/4-qux.no-transaction.sql
83
+
84
+ CREATE INDEX CONCURRENTLY person_name_idx ON person ("name");
85
+ ```
86
+
87
+ sqerge commits the files before a no-transaction file, executes it on its own, then starts a new transaction for the files after it.
88
+
89
+ - A no-transaction file can't be rolled back, and it's recorded as migrated only after it succeeds. If it fails, or sqerge stops before recording it, undo its changes, such as an invalid index, before you run sqerge again.
90
+ - sqerge sends a SQL file as one query, and PostgreSQL runs a query with more than one statement in a transaction. Put one statement in each `.no-transaction.sql` file, or use a `.no-transaction.js` or `.no-transaction.mjs` file, which runs each query on its own.
91
+
92
+ ## Concurrent Runs
93
+
94
+ sqerge holds a PostgreSQL advisory lock while it runs, so if you start it twice against the same database, such as from several app instances, the second run waits for the first to finish, then skips the files it already migrated.
95
+
96
+ The lock and ROLE need one database session for the whole run, so connect sqerge directly to PostgreSQL, or through a pooler in session mode, not transaction mode.
97
+
75
98
  ## Environment Variables
76
99
 
77
100
  - Use **Postgres.js** [environment variables](https://github.com/porsager/postgres#environmental-variables) for your database **connection**.
package/dist/bootstrap.js CHANGED
@@ -40,24 +40,39 @@ const index_1 = __importStar(require("./index"));
40
40
  async function bootstrap() {
41
41
  const log = (message, ...args) => console.log(`\u001b[35m[\u001b[39m\u001b[36msqerge\u001b[39m\u001b[35m]\u001b[39m ${message}`, ...args);
42
42
  const logError = (message, ...args) => console.error(`\u001b[35m[\u001b[39m\u001b[36msqerge\u001b[39m\u001b[35m]\u001b[39m \u001b[1m\u001b[31m(error)\u001b[39m\u001b[22m ${message}`, ...args);
43
+ // Exit with an error, instead of 0, if the process runs out of work before
44
+ // the migration settles.
45
+ let settled = false;
46
+ process.exitCode = 1;
47
+ process.on('exit', () => {
48
+ if (!settled)
49
+ logError('exited before the migration finished');
50
+ });
43
51
  try {
44
52
  const dir = (0, node_path_1.resolve)(process.argv[2] ?? './');
45
53
  const sql = (0, postgres_1.default)({
46
54
  onnotice: () => { },
47
55
  });
48
- process.on('exit', async () => {
49
- await sql.end();
50
- });
51
56
  await (0, index_1.default)(sql, dir, { log, role: process.env.ROLE });
57
+ settled = true;
58
+ process.exitCode = 0;
52
59
  await sql.end();
53
60
  }
54
61
  catch (error) {
62
+ settled = true;
55
63
  if (isNodeError(error, Error)) {
56
64
  if (error instanceof index_1.SqergeError || error instanceof postgres_1.PostgresError) {
57
65
  logError(error.message);
58
66
  }
59
67
  else if (error.code === 'ECONNREFUSED') {
60
- logError('database connection refused at %O', error.message.split('ECONNREFUSED ')[1]);
68
+ // Node tries each address of a host like localhost, and throws an
69
+ // AggregateError, with an empty message, if they all refuse.
70
+ const errors = error instanceof AggregateError ? error.errors : [error];
71
+ logError('database connection refused at %O', errors.map((e) => e.message.split('ECONNREFUSED ')[1]).join(', '));
72
+ }
73
+ else if (typeof error.code === 'string' &&
74
+ error.code.startsWith('CONNECTION_')) {
75
+ logError('database connection closed');
61
76
  }
62
77
  else if (error.code === 'ENOTFOUND') {
63
78
  logError('database host not found at %O', error.message.split('ENOTFOUND ')[1]);
package/dist/index.js CHANGED
@@ -1,63 +1,134 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  Object.defineProperty(exports, "__esModule", { value: true });
3
36
  exports.SqergeError = void 0;
4
37
  exports.default = migrate;
5
38
  const fs_1 = require("fs");
6
39
  const node_path_1 = require("node:path");
40
+ const promises_1 = require("node:timers/promises");
7
41
  const node_util_1 = require("node:util");
8
- const postgres_1 = require("postgres");
42
+ const postgres_1 = __importStar(require("postgres"));
43
+ // Advisory lock key: "sqerge" in ASCII.
44
+ const LOCK_KEY = 0x737165726765;
9
45
  async function migrate(sql, fileDir, options) {
10
46
  const log = options?.log;
11
47
  const fileList = getFileList(fileDir);
12
48
  log && log('%O file(s) found in %O', fileList.length, fileDir);
13
49
  if (fileList.length === 0)
14
50
  return;
15
- await sql.begin(async (trx) => {
16
- // TypeScript workaround for https://github.com/porsager/postgres/issues/1143
17
- const sql = trx;
51
+ if (!sql.options) {
52
+ throw new SqergeError('invalid_sql', 'sql must be an instance from postgres(), not a transaction or reserved connection');
53
+ }
54
+ // The caller may have SET these on its connection, rather than passing them
55
+ // as options, so the migration should still run with them.
56
+ const settings = await getSessionSettings(sql);
57
+ // Run the migration on a connection of its own, so the lock and role last
58
+ // for the whole run, and the caller's connections stay as they are.
59
+ let closed = false;
60
+ const db = (0, postgres_1.default)({
61
+ // postgres() accepts the parsed options of another instance.
62
+ ...sql.options,
63
+ max: 1,
64
+ idle_timeout: undefined,
65
+ max_lifetime: null,
66
+ // If the connection closes, end, so that later queries fail instead of
67
+ // reconnecting without the lock and role. Without a timeout, end() waits
68
+ // forever for a query that was running when the connection closed.
69
+ onclose: () => {
70
+ closed = true;
71
+ void db.end({ timeout: 0 });
72
+ },
73
+ });
74
+ const transaction = (fn) =>
75
+ // TypeScript workaround for https://github.com/porsager/postgres/issues/1143
76
+ db.begin((trx) => fn(trx));
77
+ // Executes files from index `start` up to the next no-transaction file, and
78
+ // returns the index of the file where it stopped.
79
+ const executeFiles = async (sql, start) => {
80
+ let i = start;
81
+ for (; i < fileList.length && !fileList[i].noTransaction; i++) {
82
+ await executeFile(sql, fileDir, fileList[i], i + 1, log);
83
+ }
84
+ return i;
85
+ };
86
+ try {
87
+ await lock(db, log);
18
88
  if (typeof options?.role === 'string') {
19
- await sql `set role ${sql(options.role)};`;
89
+ settings.push(['role', options.role]);
20
90
  }
21
- await createMigrationTable(sql);
22
- const migrationList = await getMigrations(sql);
23
- for (let i = 0; i < fileList.length; i++) {
24
- const count = i + 1;
25
- const { prefix, file } = fileList[i];
26
- if (i < migrationList.length) {
27
- const row = migrationList[i];
28
- if (file !== row.file) {
29
- throw new SqergeError('filename_mismatch', fileMessage(count, file, 'filename does not match %O in migration history', row.file));
91
+ for (const [name, value] of settings) {
92
+ await db `SELECT set_config(${name}, ${value}, false);`;
93
+ }
94
+ let next = await transaction(async (sql) => {
95
+ await createMigrationTable(sql);
96
+ await widenPrefixColumn(sql, fileList);
97
+ const migrationList = await getMigrations(sql);
98
+ for (let i = 0; i < fileList.length && i < migrationList.length; i++) {
99
+ const { file } = fileList[i];
100
+ if (file !== migrationList[i]) {
101
+ throw new SqergeError('filename_mismatch', fileMessage(i + 1, file, 'filename does not match %O in migration history', migrationList[i]));
30
102
  }
31
- log && log(fileMessage(count, file, 'already migrated'));
103
+ log && log(fileMessage(i + 1, file, 'already migrated'));
32
104
  }
33
- else {
34
- const filePath = (0, node_path_1.resolve)(fileDir, file);
35
- try {
36
- await insertMigration(sql, prefix, file);
37
- if (file.endsWith('sql')) {
38
- await sql.file(filePath);
39
- }
40
- else {
41
- await executeJsMigrationFile(sql, filePath);
42
- }
43
- }
44
- catch (error) {
45
- log && count > 0 && log('rollback...');
46
- if (error instanceof postgres_1.PostgresError) {
47
- if (error.code === '23505' &&
48
- error.constraint_name === 'sqerge_migration_prefix_key') {
49
- throw new SqergeError('duplicate_prefix', fileMessage(count, file, 'prefix (%O) in filename is already in use', prefix));
50
- }
51
- throw new SqergeError('sql_error', fileMessage(count, file, `(sql execution) ${error.message}`));
52
- }
53
- else {
54
- throw error;
55
- }
56
- }
57
- log && log(fileMessage(count, file, 'executed'));
105
+ return executeFiles(sql, migrationList.length);
106
+ });
107
+ // A no-transaction file runs after the files before it are committed, and
108
+ // the files after it run in a new transaction.
109
+ while (next < fileList.length) {
110
+ const start = next;
111
+ if (!fileList[start].noTransaction) {
112
+ next = await transaction((sql) => executeFiles(sql, start));
113
+ continue;
114
+ }
115
+ const { prefix, file } = fileList[start];
116
+ // A no-transaction file is recorded after it runs, so check for a
117
+ // duplicate prefix first. The previous file is recorded already.
118
+ if (start > 0 && fileList[start - 1].prefix === prefix) {
119
+ throw duplicatePrefixError(start + 1, file, prefix);
58
120
  }
121
+ await executeFile(db, fileDir, fileList[start], start + 1, log);
122
+ next++;
59
123
  }
60
- });
124
+ }
125
+ finally {
126
+ // Once the connection closed, it's ending already. Waiting for that lets
127
+ // postgres.js write to the dead socket and crash, e.g. with the ROLLBACK
128
+ // that begin() sends.
129
+ if (!closed)
130
+ await db.end();
131
+ }
61
132
  }
62
133
  class SqergeError extends Error {
63
134
  constructor(code, message, ...args) {
@@ -69,10 +140,20 @@ exports.SqergeError = SqergeError;
69
140
  function getFileList(dir) {
70
141
  const filePattern = /^(\d+)-.*[.](sql|js|mjs)$/;
71
142
  try {
72
- return (0, fs_1.readdirSync)(dir)
143
+ const fileList = (0, fs_1.readdirSync)(dir)
73
144
  .filter((file) => filePattern.test(file))
74
- .map((file) => ({ prefix: parseInt(file.split('-')[0]), file }))
145
+ .map((file) => ({
146
+ prefix: parseInt(file.split('-')[0]),
147
+ file,
148
+ noTransaction: /[.]no-transaction[.](sql|js|mjs)$/.test(file),
149
+ }))
75
150
  .sort((a, b) => a.prefix - b.prefix);
151
+ // Larger prefixes lose precision as JavaScript numbers.
152
+ const i = fileList.findIndex(({ prefix }) => !Number.isSafeInteger(prefix));
153
+ if (i >= 0) {
154
+ throw new SqergeError('prefix_out_of_range', fileMessage(i + 1, fileList[i].file, 'prefix in filename is larger than %O', Number.MAX_SAFE_INTEGER));
155
+ }
156
+ return fileList;
76
157
  }
77
158
  catch (error) {
78
159
  if (error?.code === 'ENOENT') {
@@ -81,24 +162,98 @@ function getFileList(dir) {
81
162
  throw error;
82
163
  }
83
164
  }
165
+ // sqerge reads its own queries with values() and as text, so that the caller's
166
+ // transform and type options, which postgres() passes on, can't change them.
167
+ // Returns [name, value] pairs of the settings changed with SET in the session.
168
+ async function getSessionSettings(sql) {
169
+ return sql `
170
+ SELECT name, setting FROM pg_settings WHERE source = 'session'
171
+ UNION ALL
172
+ SELECT 'role', current_setting('role') WHERE current_setting('role') <> 'none';
173
+ `.values();
174
+ }
175
+ // Waits for other sqerge runs on the database to finish. It polls, because a
176
+ // session waiting in pg_advisory_lock() holds a snapshot, which would block
177
+ // CREATE INDEX CONCURRENTLY in the run that has the lock.
178
+ async function lock(sql, log) {
179
+ for (let attempt = 0;; attempt++) {
180
+ const [[locked]] = await sql `SELECT pg_try_advisory_lock(${LOCK_KEY})::text;`.values();
181
+ if (locked === 'true')
182
+ return;
183
+ if (attempt === 0)
184
+ log && log('waiting for another migration to finish...');
185
+ await (0, promises_1.setTimeout)(1000);
186
+ }
187
+ }
84
188
  function createMigrationTable(sql) {
85
189
  return sql `
86
190
  CREATE TABLE IF NOT EXISTS sqerge_migration (
87
191
  id SERIAL NOT NULL PRIMARY KEY,
88
- prefix int NOT NULL UNIQUE,
192
+ prefix bigint NOT NULL UNIQUE,
89
193
  file text NOT NULL UNIQUE,
90
194
  "createdAt" timestamptz NOT NULL DEFAULT now()
91
195
  );
92
196
  `;
93
197
  }
94
- function getMigrations(sql) {
95
- return sql `
96
- SELECT * FROM sqerge_migration ORDER BY "id";
97
- `;
198
+ // Before 3.3, sqerge stored the prefix as an int. Widen the column only when a
199
+ // prefix needs it, since that takes owning the table.
200
+ async function widenPrefixColumn(sql, fileList) {
201
+ if (fileList.every(({ prefix }) => prefix <= 2147483647))
202
+ return;
203
+ const [[type]] = await sql `
204
+ SELECT atttypid::regtype::text FROM pg_attribute
205
+ WHERE attrelid = 'sqerge_migration'::regclass AND attname = 'prefix';
206
+ `.values();
207
+ if (type === 'integer') {
208
+ await sql `ALTER TABLE sqerge_migration ALTER COLUMN prefix TYPE bigint;`;
209
+ }
210
+ }
211
+ // Returns the migrated filenames, in the order they ran.
212
+ async function getMigrations(sql) {
213
+ const rows = await sql `
214
+ SELECT file FROM sqerge_migration ORDER BY "id";
215
+ `.values();
216
+ return rows.map(([file]) => file);
98
217
  }
99
218
  function insertMigration(sql, prefix, file) {
100
219
  return sql `INSERT INTO sqerge_migration ("prefix", "file") VALUES (${prefix}, ${file});`;
101
220
  }
221
+ async function executeFile(sql, fileDir, { prefix, file, noTransaction }, count, log) {
222
+ const filePath = (0, node_path_1.resolve)(fileDir, file);
223
+ try {
224
+ // In a transaction, insert first, so a duplicate prefix fails before the
225
+ // file runs. Without one, insert after, so a failed file isn't recorded.
226
+ if (!noTransaction)
227
+ await insertMigration(sql, prefix, file);
228
+ if (file.endsWith('sql')) {
229
+ await sql.file(filePath);
230
+ }
231
+ else {
232
+ await executeJsMigrationFile(sql, filePath);
233
+ }
234
+ if (noTransaction)
235
+ await insertMigration(sql, prefix, file);
236
+ }
237
+ catch (error) {
238
+ log && !noTransaction && log('rollback...');
239
+ if (error instanceof postgres_1.PostgresError) {
240
+ if (error.code === '23505' &&
241
+ error.constraint_name === 'sqerge_migration_prefix_key') {
242
+ throw duplicatePrefixError(count, file, prefix);
243
+ }
244
+ // PostgreSQL runs a query with more than one statement in a
245
+ // transaction, and sqerge sends a SQL file as one query.
246
+ const hint = noTransaction && file.endsWith('sql') && error.code === '25001'
247
+ ? '. PostgreSQL runs a SQL file with more than one statement in a transaction, so put this statement in a file of its own'
248
+ : '';
249
+ throw new SqergeError('sql_error', fileMessage(count, file, `(sql execution) ${error.message}${hint}`));
250
+ }
251
+ else {
252
+ throw error;
253
+ }
254
+ }
255
+ log && log(fileMessage(count, file, 'executed'));
256
+ }
102
257
  async function executeJsMigrationFile(sql, filePath) {
103
258
  const module = await import(filePath);
104
259
  if (typeof module.default === 'function') {
@@ -108,6 +263,9 @@ async function executeJsMigrationFile(sql, filePath) {
108
263
  throw new SqergeError('invalid_js_migration_file', 'file %O default export must be a function', filePath);
109
264
  }
110
265
  }
266
+ function duplicatePrefixError(count, file, prefix) {
267
+ return new SqergeError('duplicate_prefix', fileMessage(count, file, 'prefix (%O) in filename is already in use', prefix));
268
+ }
111
269
  function fileMessage(count, file, message, ...args) {
112
270
  return (0, node_util_1.formatWithOptions)({ colors: true }, `file %O (\u001b[32m${file}\u001b[39m): ${message}`, count, ...args);
113
271
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sqerge",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "A forward only PostgreSQL migration tool.",
5
5
  "keywords": [
6
6
  "postgres",
@@ -61,7 +61,7 @@
61
61
  "typescript": "^5.4.5"
62
62
  },
63
63
  "peerDependencies": {
64
- "postgres": "^3.x"
64
+ "postgres": "^3.4.0"
65
65
  },
66
66
  "peerDependenciesMeta": {
67
67
  "postgres": {
@@ -69,6 +69,6 @@
69
69
  }
70
70
  },
71
71
  "engines": {
72
- "node": ">=20"
72
+ "node": ">=22"
73
73
  }
74
74
  }