sqerge 1.0.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 ADDED
@@ -0,0 +1,67 @@
1
+ # sqerge
2
+
3
+ A forward only PostgreSQL migration tool. Uses [Postgres.js](https://github.com/porsager/postgres) library under the hood.
4
+
5
+ ## Get Started
6
+
7
+ 1. Install to devDependencies
8
+ ```sh
9
+ npm i sqerge -D
10
+ ```
11
+ 2. Choose a migration directory
12
+ ```sh
13
+ mkdir foo
14
+ ```
15
+ 3. Create some migration files
16
+
17
+ 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.
18
+
19
+ ```sql
20
+ -- file: ./foo/1-bar.sql
21
+
22
+ CREATE TABLE person (
23
+ "id" SERIAL PRIMARY KEY,
24
+ "name" text NOT NULL
25
+ );
26
+ ```
27
+
28
+ ```sql
29
+ -- file: ./foo/2-biz.sql
30
+
31
+ ALTER TABLE person
32
+ ADD COLUMN "age" smallint;
33
+ ```
34
+
35
+ In addition to **.sql**, migration files can also end in **.js** or **.mjs** for ES Modules. JavaScript files must **default export a function**. The 1st argument is a [Postgres.js](https://github.com/porsager/postgres) instance.
36
+
37
+ ```js
38
+ // file: ./foo/3-baz.js
39
+
40
+ module.exports = async (sql) => {
41
+ await sql`
42
+ INSERT INTO person
43
+ ("name", "age")
44
+ VALUES
45
+ ('Luke Skywalker', '21');
46
+ `;
47
+ };
48
+ ```
49
+
50
+ 4. Execute migration
51
+
52
+ Command:
53
+
54
+ **Note:** Use [environment variables](https://www.postgresql.org/docs/current/libpq-envars.html) for your database connection. Supported environment variables are at the discretion of [Postgres.js](https://github.com/porsager/postgres).
55
+
56
+ ```sh
57
+ PGHOST=localhost PGPORT=5438 PGUSER=jonathan PGPASSWORD=iliketurtles PGDATABASE=dev npx sqerge ./foo
58
+ ```
59
+
60
+ Output:
61
+
62
+ ```sh
63
+ [sqerge] 3 file(s) found in '/Users/jonathan/Desktop/foo'
64
+ [sqerge] file 1 (1-bar.sql): executed
65
+ [sqerge] file 2 (2-biz.sql): executed
66
+ [sqerge] file 3 (3-baz.js): executed
67
+ ```
package/bin.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('./dist/bootstrap.js');
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,66 @@
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 (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ const node_path_1 = require("node:path");
27
+ const postgres_1 = __importStar(require("postgres"));
28
+ const index_1 = __importStar(require("./index"));
29
+ (async function main() {
30
+ const log = (message, ...args) => console.log(`\u001b[35m[\u001b[39m\u001b[36msqerge\u001b[39m\u001b[35m]\u001b[39m ${message}`, ...args);
31
+ const logError = (message, ...args) => log(`\u001b[1m\u001b[31m(error)\u001b[39m\u001b[22m ${message}`, ...args);
32
+ try {
33
+ const dir = (0, node_path_1.resolve)(process.argv[2] ?? './');
34
+ const sql = (0, postgres_1.default)({
35
+ onnotice: () => { },
36
+ });
37
+ process.on('exit', async () => {
38
+ await sql.end();
39
+ });
40
+ await (0, index_1.default)(sql, dir, log);
41
+ process.exit(0);
42
+ }
43
+ catch (error) {
44
+ if (isNodeError(error, Error)) {
45
+ if (error instanceof index_1.SqergeError || error instanceof postgres_1.PostgresError) {
46
+ logError(error.message);
47
+ }
48
+ else if (error.code === 'ECONNREFUSED') {
49
+ logError('database connection refused at %O', error.message.split('ECONNREFUSED ')[1]);
50
+ }
51
+ else if (error.code === 'ENOTFOUND') {
52
+ logError('database host not found at %O', error.message.split('ENOTFOUND ')[1]);
53
+ }
54
+ else {
55
+ console.error(error);
56
+ }
57
+ }
58
+ else {
59
+ console.error(error);
60
+ }
61
+ process.exit(1);
62
+ }
63
+ })();
64
+ function isNodeError(value, errorType) {
65
+ return value instanceof errorType;
66
+ }
@@ -0,0 +1,6 @@
1
+ import { Sql } from 'postgres';
2
+ export default function migrate(sql: Sql<{}>, fileDir: string, log?: typeof console.log): Promise<void>;
3
+ export declare class SqergeError extends Error {
4
+ code: string;
5
+ constructor(code: string, message: string, ...args: any);
6
+ }
package/dist/index.js ADDED
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SqergeError = void 0;
4
+ const fs_1 = require("fs");
5
+ const node_path_1 = require("node:path");
6
+ const node_util_1 = require("node:util");
7
+ const postgres_1 = require("postgres");
8
+ async function migrate(sql, fileDir, log) {
9
+ const fileList = getFileList(fileDir);
10
+ log && log('%O file(s) found in %O', fileList.length, fileDir);
11
+ if (fileList.length === 0)
12
+ return;
13
+ await sql.begin(async (sql) => {
14
+ await createMigrationTable(sql);
15
+ const migrationList = await getMigrations(sql);
16
+ for (let i = 0; i < fileList.length; i++) {
17
+ const count = i + 1;
18
+ const { prefix, file } = fileList[i];
19
+ if (i < migrationList.length) {
20
+ const row = migrationList[i];
21
+ if (file !== row.file) {
22
+ throw new SqergeError('filename_mismatch', fileMessage(count, file, 'filename does not match %O in migration history', row.file));
23
+ }
24
+ log && log(fileMessage(count, file, 'already migrated'));
25
+ }
26
+ else {
27
+ const filePath = (0, node_path_1.resolve)(fileDir, file);
28
+ try {
29
+ await insertMigration(sql, prefix, file);
30
+ if (file.endsWith('sql')) {
31
+ await sql.file(filePath);
32
+ }
33
+ else {
34
+ await executeJsMigrationFile(sql, filePath);
35
+ }
36
+ }
37
+ catch (error) {
38
+ log && count > 0 && log('rollback...');
39
+ if (error instanceof postgres_1.PostgresError) {
40
+ if (error.code === '23505' &&
41
+ error.constraint_name === 'sqerge_migration_prefix_key') {
42
+ throw new SqergeError('duplicate_prefix', fileMessage(count, file, 'prefix (%O) in filename is already in use', prefix));
43
+ }
44
+ throw new SqergeError('sql_error', fileMessage(count, file, `(sql execution) ${error.message}`));
45
+ }
46
+ else {
47
+ throw error;
48
+ }
49
+ }
50
+ log && log(fileMessage(count, file, 'executed'));
51
+ }
52
+ }
53
+ });
54
+ }
55
+ exports.default = migrate;
56
+ class SqergeError extends Error {
57
+ constructor(code, message, ...args) {
58
+ super((0, node_util_1.formatWithOptions)({ colors: true }, message, ...args));
59
+ this.code = code;
60
+ }
61
+ }
62
+ exports.SqergeError = SqergeError;
63
+ function getFileList(dir) {
64
+ const filePattern = /^(\d+)-.*[.](sql|js|mjs)$/;
65
+ try {
66
+ return (0, fs_1.readdirSync)(dir)
67
+ .filter((file) => filePattern.test(file))
68
+ .map((file) => ({ prefix: parseInt(file.split('-')[0]), file }))
69
+ .sort((a, b) => a.prefix - b.prefix);
70
+ }
71
+ catch (error) {
72
+ if (error?.code === 'ENOENT') {
73
+ throw new SqergeError('dir_not_found', 'directory not found: %O', dir);
74
+ }
75
+ throw error;
76
+ }
77
+ }
78
+ function createMigrationTable(sql) {
79
+ return sql `
80
+ CREATE TABLE IF NOT EXISTS sqerge_migration (
81
+ id SERIAL NOT NULL PRIMARY KEY,
82
+ prefix int NOT NULL UNIQUE,
83
+ file text NOT NULL UNIQUE,
84
+ "createdAt" timestamptz NOT NULL DEFAULT now()
85
+ );
86
+ `;
87
+ }
88
+ function getMigrations(sql) {
89
+ return sql `
90
+ SELECT * FROM sqerge_migration ORDER BY "id";
91
+ `;
92
+ }
93
+ function insertMigration(sql, prefix, file) {
94
+ return sql `INSERT INTO sqerge_migration ("prefix", "file") VALUES (${prefix}, ${file});`;
95
+ }
96
+ async function executeJsMigrationFile(sql, filePath) {
97
+ const module = await import(filePath);
98
+ if (typeof module.default === 'function') {
99
+ await module.default(sql);
100
+ }
101
+ else {
102
+ throw new SqergeError('invalid_js_migration_file', 'file %O default export must be a function', filePath);
103
+ }
104
+ }
105
+ function fileMessage(count, file, message, ...args) {
106
+ return (0, node_util_1.formatWithOptions)({ colors: true }, `file %O (\u001b[32m${file}\u001b[39m): ${message}`, count, ...args);
107
+ }
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "sqerge",
3
+ "version": "1.0.0",
4
+ "description": "A forward only PostgreSQL migration tool.",
5
+ "keywords": [
6
+ "postgres",
7
+ "postgresql",
8
+ "sql",
9
+ "migrate",
10
+ "migration"
11
+ ],
12
+ "homepage": "https://github.com/eezing/sqerge#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/eezing/sqerge/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/eezing/sqerge.git"
19
+ },
20
+ "license": "ISC",
21
+ "author": "Eric Zingeler <eezing@gmail.com>",
22
+ "main": "dist/index.js",
23
+ "types": "dist/index.d.ts",
24
+ "bin": "bin.js",
25
+ "scripts": {
26
+ "build": "rm -rf dist && tsc --build",
27
+ "dev": "tsc -w",
28
+ "dev:postgres": "node ./scripts/dev-postgres.js",
29
+ "prepare": "husky install",
30
+ "test": "npm run test:prettier && npm run test:jest",
31
+ "test:jest": "jest",
32
+ "test:jest:watch": "jest --watch",
33
+ "test:prettier": "prettier -c ."
34
+ },
35
+ "prettier": {
36
+ "bracketSpacing": true,
37
+ "semi": true,
38
+ "singleQuote": true
39
+ },
40
+ "jest": {
41
+ "collectCoverageFrom": [
42
+ "<rootDir>/src"
43
+ ],
44
+ "preset": "ts-jest",
45
+ "testEnvironment": "node",
46
+ "testMatch": [
47
+ "<rootDir>/src/**/__tests__/*.test.ts"
48
+ ]
49
+ },
50
+ "devDependencies": {
51
+ "@types/jest": "^29.1.2",
52
+ "@types/node": "^16.11.59",
53
+ "husky": "^8.0.0",
54
+ "jest": "^29.1.2",
55
+ "prettier": "^2.7.1",
56
+ "ts-jest": "^29.0.3",
57
+ "typescript": "^4.8.4"
58
+ },
59
+ "peerDependencies": {
60
+ "postgres": "^3.x"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "postgres": {
64
+ "optional": false
65
+ }
66
+ },
67
+ "engines": {
68
+ "node": ">=14 <=18"
69
+ }
70
+ }