From 11d5e572794e94aa4498a9dd72bb423d5b9c0611 Mon Sep 17 00:00:00 2001 From: Shinigami Date: Sat, 27 Apr 2024 09:01:46 +0200 Subject: [PATCH] refactor: unify codestyle (#1130) --- src/db.ts | 8 +-- src/migration.ts | 7 ++- src/runner.ts | 57 ++++++++++--------- src/sqlMigration.ts | 4 +- test/migrations/005_table_test.js | 10 ++-- test/migrations/022_add_type_test.js | 2 +- .../migrations/024_add_type_attribute_test.js | 2 +- .../migrations/026_set_type_attribute_test.js | 2 +- .../030_rename_type_attribute_test.js | 2 +- .../032_drop_type_attribute_test.js | 2 +- test/migrations/041_function_test.js | 2 +- test/migrations/055_operator_test.js | 2 +- .../functions/createFunction.spec.ts | 12 ++-- test/runner.spec.ts | 4 +- 14 files changed, 60 insertions(+), 56 deletions(-) diff --git a/src/db.ts b/src/db.ts index 04339c48..2fa29e9d 100644 --- a/src/db.ts +++ b/src/db.ts @@ -42,10 +42,10 @@ enum ConnectionStatus { ERROR = 'ERROR', } -const db = ( +function db( connection: ClientBase | string | ClientConfig, logger: Logger = console -): DBConnection => { +): DBConnection { const isExternalClient = typeof connection === 'object' && 'query' in connection && @@ -58,7 +58,7 @@ const db = ( const beforeCloseListeners: any[] = []; - const createConnection: () => Promise = () => + const createConnection: DBConnection['createConnection'] = () => new Promise((resolve, reject) => { if (isExternalClient || connectionStatus === ConnectionStatus.CONNECTED) { resolve(); @@ -160,6 +160,6 @@ ${err} } }, }; -}; +} export default db; diff --git a/src/migration.ts b/src/migration.ts index bf5b2934..2efac032 100644 --- a/src/migration.ts +++ b/src/migration.ts @@ -110,8 +110,9 @@ export function getTimestamp(logger: Logger, filename: string): number { async function resolveSuffix( directory: string, - { language, ignorePattern }: CreateOptionsDefault + options: CreateOptionsDefault ): Promise { + const { language, ignorePattern } = options; return language || (await getLastSuffix(directory, ignorePattern)) || 'js'; } @@ -251,8 +252,8 @@ export class Migration implements RunMigration { this.logger.debug(`${sqlSteps.join('\n')}\n\n`); } - return sqlSteps.reduce( - (promise: Promise, sql) => + return sqlSteps.reduce>( + (promise, sql) => promise.then((): unknown => this.options.dryRun || this.db.query(sql)), Promise.resolve() ); diff --git a/src/runner.ts b/src/runner.ts index d7322cb2..69ed71d5 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -24,11 +24,11 @@ const idColumn = 'id'; const nameColumn = 'name'; const runOnColumn = 'run_on'; -const loadMigrations = async ( +async function loadMigrations( db: DBConnection, options: RunnerOption, logger: Logger -) => { +): Promise { try { let shorthands: ColumnDefinitions = {}; const files = await loadMigrationFiles(options.dir, options.ignorePattern); @@ -68,32 +68,32 @@ const loadMigrations = async ( } catch (err: any) { throw new Error(`Can't get migration files: ${err.stack}`); } -}; +} -const lock = async (db: DBConnection): Promise => { +async function lock(db: DBConnection): Promise { const [result] = await db.select( - `select pg_try_advisory_lock(${PG_MIGRATE_LOCK_ID}) as "lockObtained"` + `SELECT pg_try_advisory_lock(${PG_MIGRATE_LOCK_ID}) AS "lockObtained"` ); if (!result.lockObtained) { throw new Error('Another migration is already running'); } -}; +} -const unlock = async (db: DBConnection): Promise => { +async function unlock(db: DBConnection): Promise { const [result] = await db.select( - `select pg_advisory_unlock(${PG_MIGRATE_LOCK_ID}) as "lockReleased"` + `SELECT pg_advisory_unlock(${PG_MIGRATE_LOCK_ID}) AS "lockReleased"` ); if (!result.lockReleased) { throw new Error('Failed to release migration lock'); } -}; +} -const ensureMigrationsTable = async ( +async function ensureMigrationsTable( db: DBConnection, options: RunnerOption -): Promise => { +): Promise { try { const schema = getMigrationTableSchema(options); const { migrationsTable } = options; @@ -121,16 +121,19 @@ const ensureMigrationsTable = async ( } } else { await db.query( - `CREATE TABLE ${fullTableName} ( ${idColumn} SERIAL PRIMARY KEY, ${nameColumn} varchar(255) NOT NULL, ${runOnColumn} timestamp NOT NULL)` + `CREATE TABLE ${fullTableName} (${idColumn} SERIAL PRIMARY KEY, ${nameColumn} varchar(255) NOT NULL, ${runOnColumn} timestamp NOT NULL)` ); } // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { throw new Error(`Unable to ensure migrations table: ${err.stack}`); } -}; +} -const getRunMigrations = async (db: DBConnection, options: RunnerOption) => { +async function getRunMigrations( + db: DBConnection, + options: RunnerOption +): Promise { const schema = getMigrationTableSchema(options); const { migrationsTable } = options; const fullTableName = createSchemalize({ @@ -145,13 +148,13 @@ const getRunMigrations = async (db: DBConnection, options: RunnerOption) => { nameColumn, `SELECT ${nameColumn} FROM ${fullTableName} ORDER BY ${runOnColumn}, ${idColumn}` ); -}; +} -const getMigrationsToRun = ( +function getMigrationsToRun( options: RunnerOption, runNames: string[], migrations: Migration[] -): Migration[] => { +): Migration[] { if (options.direction === 'down') { const downMigrations: Array = runNames .filter( @@ -197,9 +200,9 @@ const getMigrationsToRun = ( return options.timestamp ? upMigrations.filter(({ timestamp }) => timestamp <= count) : upMigrations.slice(0, Math.abs(count)); -}; +} -const checkOrder = (runNames: string[], migrations: Migration[]) => { +function checkOrder(runNames: string[], migrations: Migration[]): void { const len = Math.min(runNames.length, migrations.length); for (let i = 0; i < len; i += 1) { @@ -212,20 +215,20 @@ const checkOrder = (runNames: string[], migrations: Migration[]) => { ); } } -}; +} -const runMigrations = ( +function runMigrations( toRun: Migration[], method: 'markAsRun' | 'apply', direction: MigrationDirection -) => - toRun.reduce( - (promise: Promise, migration) => - promise.then(() => migration[method](direction)), +): Promise { + return toRun.reduce>( + (promise, migration) => promise.then(() => migration[method](direction)), Promise.resolve() ); +} -const getLogger: (options: RunnerOption) => Logger = (options) => { +function getLogger(options: RunnerOption): Logger { const { log, logger, verbose } = options; let loggerObject: Logger = console; @@ -249,7 +252,7 @@ const getLogger: (options: RunnerOption) => Logger = (options) => { warn: loggerObject.warn.bind(loggerObject), error: loggerObject.error.bind(loggerObject), }; -}; +} export default async (options: RunnerOption): Promise => { const logger = getLogger(options); diff --git a/src/sqlMigration.ts b/src/sqlMigration.ts index 38a707a0..faef6634 100644 --- a/src/sqlMigration.ts +++ b/src/sqlMigration.ts @@ -5,7 +5,7 @@ function createMigrationCommentRegex(direction: 'up' | 'down'): RegExp { return new RegExp(`^\\s*--[\\s-]*${direction}\\s+migration`, 'im'); } -export const getActions = (content: string): MigrationBuilderActions => { +export function getActions(content: string): MigrationBuilderActions { const upMigrationCommentRegex = createMigrationCommentRegex('up'); const downMigrationCommentRegex = createMigrationCommentRegex('down'); @@ -40,7 +40,7 @@ export const getActions = (content: string): MigrationBuilderActions => { pgm.sql(downSql); }, }; -}; +} export default async (sqlPath: string): Promise => { const content = await readFile(sqlPath, 'utf-8'); diff --git a/test/migrations/005_table_test.js b/test/migrations/005_table_test.js index 9a529003..7ce37974 100644 --- a/test/migrations/005_table_test.js +++ b/test/migrations/005_table_test.js @@ -4,9 +4,9 @@ const schema = process.env.SCHEMA || 'public'; exports.up = async (pgm) => { const [{ comment }] = await pgm.db.select( - `SELECT obj_description(c.oid) as "comment" - FROM pg_class c join pg_namespace n ON (c.relnamespace = n.oid) - WHERE c.relname = 't2' and c.relkind = 'r' and n.nspname = '${schema}'` + `SELECT obj_description(c.oid) AS "comment" + FROM pg_class c JOIN pg_namespace n ON (c.relnamespace = n.oid) + WHERE c.relname = 't2' AND c.relkind = 'r' AND n.nspname = '${schema}'` ); if (comment !== table.comment) { throw new Error('Comment not set'); @@ -47,6 +47,6 @@ exports.up = async (pgm) => { }; exports.down = (pgm) => { - pgm.sql('DELETE from t2'); - pgm.sql('DELETE from t1'); + pgm.sql('DELETE FROM t2'); + pgm.sql('DELETE FROM t1'); }; diff --git a/test/migrations/022_add_type_test.js b/test/migrations/022_add_type_test.js index bebf2151..f55430c6 100644 --- a/test/migrations/022_add_type_test.js +++ b/test/migrations/022_add_type_test.js @@ -1,7 +1,7 @@ exports.up = (pgm) => { pgm.sql('CREATE TEMPORARY TABLE t_list_1 (l list);'); pgm.sql("INSERT INTO t_list_1 (l) VALUES ('a');"); - pgm.sql('select (ROW(1)::obj).id;'); + pgm.sql('SELECT (ROW(1)::obj).id;'); }; exports.down = () => null; diff --git a/test/migrations/024_add_type_attribute_test.js b/test/migrations/024_add_type_attribute_test.js index 95167bd8..8309a559 100644 --- a/test/migrations/024_add_type_attribute_test.js +++ b/test/migrations/024_add_type_attribute_test.js @@ -1,5 +1,5 @@ exports.up = (pgm) => { - pgm.sql("select (ROW(1, 'x')::obj).string;"); + pgm.sql("SELECT (ROW(1, 'x')::obj).string;"); }; exports.down = () => null; diff --git a/test/migrations/026_set_type_attribute_test.js b/test/migrations/026_set_type_attribute_test.js index edeb70f9..83b7fb01 100644 --- a/test/migrations/026_set_type_attribute_test.js +++ b/test/migrations/026_set_type_attribute_test.js @@ -1,7 +1,7 @@ exports.up = async (pgm) => { await pgm.db.query('SAVEPOINT sp_smallint;'); try { - await pgm.db.query("select (ROW(2147483647, 'x')::obj).id;"); + await pgm.db.query("SELECT (ROW(2147483647, 'x')::obj).id;"); // eslint-disable-next-line @typescript-eslint/only-throw-error throw 1; } catch (err) { diff --git a/test/migrations/030_rename_type_attribute_test.js b/test/migrations/030_rename_type_attribute_test.js index 55492736..2cdffaa2 100644 --- a/test/migrations/030_rename_type_attribute_test.js +++ b/test/migrations/030_rename_type_attribute_test.js @@ -1,5 +1,5 @@ exports.up = (pgm) => { - pgm.sql("select (ROW(1, 'x')::obj).str;"); + pgm.sql("SELECT (ROW(1, 'x')::obj).str;"); }; exports.down = () => null; diff --git a/test/migrations/032_drop_type_attribute_test.js b/test/migrations/032_drop_type_attribute_test.js index 4e3e1a4e..6c522fd0 100644 --- a/test/migrations/032_drop_type_attribute_test.js +++ b/test/migrations/032_drop_type_attribute_test.js @@ -1,7 +1,7 @@ exports.up = async (pgm) => { await pgm.db.query('SAVEPOINT sp_attr;'); try { - await pgm.db.query("select (ROW(1, 'x')::obj).str;"); + await pgm.db.query("SELECT (ROW(1, 'x')::obj).str;"); // eslint-disable-next-line @typescript-eslint/only-throw-error throw 1; } catch (err) { diff --git a/test/migrations/041_function_test.js b/test/migrations/041_function_test.js index 24948d72..80f17d99 100644 --- a/test/migrations/041_function_test.js +++ b/test/migrations/041_function_test.js @@ -1,5 +1,5 @@ exports.up = async (pgm) => { - const [{ r }] = await pgm.db.select('SELECT add(1,2) as r'); + const [{ r }] = await pgm.db.select('SELECT add(1,2) AS r'); if (r !== 3) { throw new Error('Function does not work'); } diff --git a/test/migrations/055_operator_test.js b/test/migrations/055_operator_test.js index ac569886..ca594cf8 100644 --- a/test/migrations/055_operator_test.js +++ b/test/migrations/055_operator_test.js @@ -1,6 +1,6 @@ exports.up = async (pgm) => { const [{ sum }] = await pgm.db.select( - 'SELECT ROW(1,2)::complex + ROW(3,4)::complex as sum;' + 'SELECT ROW(1,2)::complex + ROW(3,4)::complex AS sum;' ); if (sum !== '(4,6)') { throw new Error('Bad sequence value'); diff --git a/test/operations/functions/createFunction.spec.ts b/test/operations/functions/createFunction.spec.ts index f08d7181..b63a963e 100644 --- a/test/operations/functions/createFunction.spec.ts +++ b/test/operations/functions/createFunction.spec.ts @@ -19,14 +19,14 @@ describe('operations', () => { returns: 'integer', language: 'SQL', }, - 'select $1 + $2;' + 'SELECT $1 + $2;' ); expect(statement).toBeTypeOf('string'); expect(statement).toBe( `CREATE FUNCTION "add"(integer, integer) RETURNS integer - AS $pga$select $1 + $2;$pga$ + AS $pga$SELECT $1 + $2;$pga$ VOLATILE LANGUAGE SQL;` ); @@ -44,14 +44,14 @@ describe('operations', () => { parallel: 'UNSAFE', replace: true, }, - 'select $1 + $2;' + 'SELECT $1 + $2;' ); expect(statement).toBeTypeOf('string'); expect(statement).toBe( `CREATE OR REPLACE FUNCTION "add"(integer, integer) RETURNS integer - AS $pga$select $1 + $2;$pga$ + AS $pga$SELECT $1 + $2;$pga$ VOLATILE LANGUAGE SQL WINDOW @@ -69,7 +69,7 @@ describe('operations', () => { { returns: 'integer', }, - 'select $1 + $2;' + 'SELECT $1 + $2;' ) ).toThrow(new Error('Language for function add have to be specified')); }); @@ -87,7 +87,7 @@ describe('operations', () => { returns: 'integer', language: 'SQL', }, - 'select $1 + $2;' + 'SELECT $1 + $2;' ); expect(statement).toBeTypeOf('string'); diff --git a/test/runner.spec.ts b/test/runner.spec.ts index 8e642bc3..10b46128 100644 --- a/test/runner.spec.ts +++ b/test/runner.spec.ts @@ -41,7 +41,7 @@ describe('runner', () => { const dbClient = { query: vi.fn((query) => { switch (query) { - case 'select pg_try_advisory_lock(7241865325823964) as "lockObtained"': { + case 'SELECT pg_try_advisory_lock(7241865325823964) AS "lockObtained"': { return Promise.resolve({ rows: [{ lockObtained: true }], // lock obtained }); @@ -125,7 +125,7 @@ describe('runner', () => { const dbClient = { query: vi.fn((query) => { switch (query) { - case 'select pg_try_advisory_lock(7241865325823964) as "lockObtained"': { + case 'SELECT pg_try_advisory_lock(7241865325823964) AS "lockObtained"': { return Promise.resolve({ rows: [{ lockObtained: true }], // lock obtained });