Skip to content

Commit

Permalink
refactor: unify codestyle (#1130)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinigami92 authored Apr 27, 2024
1 parent 381d270 commit 11d5e57
Show file tree
Hide file tree
Showing 14 changed files with 60 additions and 56 deletions.
8 changes: 4 additions & 4 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 &&
Expand All @@ -58,7 +58,7 @@ const db = (

const beforeCloseListeners: any[] = [];

const createConnection: () => Promise<void> = () =>
const createConnection: DBConnection['createConnection'] = () =>
new Promise((resolve, reject) => {
if (isExternalClient || connectionStatus === ConnectionStatus.CONNECTED) {
resolve();
Expand Down Expand Up @@ -160,6 +160,6 @@ ${err}
}
},
};
};
}

export default db;
7 changes: 4 additions & 3 deletions src/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@ export function getTimestamp(logger: Logger, filename: string): number {

async function resolveSuffix(
directory: string,
{ language, ignorePattern }: CreateOptionsDefault
options: CreateOptionsDefault
): Promise<string> {
const { language, ignorePattern } = options;
return language || (await getLastSuffix(directory, ignorePattern)) || 'js';
}

Expand Down Expand Up @@ -251,8 +252,8 @@ export class Migration implements RunMigration {
this.logger.debug(`${sqlSteps.join('\n')}\n\n`);
}

return sqlSteps.reduce(
(promise: Promise<unknown>, sql) =>
return sqlSteps.reduce<Promise<unknown>>(
(promise, sql) =>
promise.then((): unknown => this.options.dryRun || this.db.query(sql)),
Promise.resolve()
);
Expand Down
57 changes: 30 additions & 27 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Migration[]> {
try {
let shorthands: ColumnDefinitions = {};
const files = await loadMigrationFiles(options.dir, options.ignorePattern);
Expand Down Expand Up @@ -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<void> => {
async function lock(db: DBConnection): Promise<void> {
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<void> => {
async function unlock(db: DBConnection): Promise<void> {
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<void> => {
): Promise<void> {
try {
const schema = getMigrationTableSchema(options);
const { migrationsTable } = options;
Expand Down Expand Up @@ -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<string[]> {
const schema = getMigrationTableSchema(options);
const { migrationsTable } = options;
const fullTableName = createSchemalize({
Expand All @@ -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<string | Migration> = runNames
.filter(
Expand Down Expand Up @@ -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) {
Expand All @@ -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<unknown>, migration) =>
promise.then(() => migration[method](direction)),
): Promise<unknown> {
return toRun.reduce<Promise<unknown>>(
(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;
Expand All @@ -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<RunMigration[]> => {
const logger = getLogger(options);
Expand Down
4 changes: 2 additions & 2 deletions src/sqlMigration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -40,7 +40,7 @@ export const getActions = (content: string): MigrationBuilderActions => {
pgm.sql(downSql);
},
};
};
}

export default async (sqlPath: string): Promise<MigrationBuilderActions> => {
const content = await readFile(sqlPath, 'utf-8');
Expand Down
10 changes: 5 additions & 5 deletions test/migrations/005_table_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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');
};
2 changes: 1 addition & 1 deletion test/migrations/022_add_type_test.js
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion test/migrations/024_add_type_attribute_test.js
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion test/migrations/026_set_type_attribute_test.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion test/migrations/030_rename_type_attribute_test.js
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 1 addition & 1 deletion test/migrations/032_drop_type_attribute_test.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion test/migrations/041_function_test.js
Original file line number Diff line number Diff line change
@@ -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');
}
Expand Down
2 changes: 1 addition & 1 deletion test/migrations/055_operator_test.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down
12 changes: 6 additions & 6 deletions test/operations/functions/createFunction.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;`
);
Expand All @@ -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
Expand All @@ -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'));
});
Expand All @@ -87,7 +87,7 @@ describe('operations', () => {
returns: 'integer',
language: 'SQL',
},
'select $1 + $2;'
'SELECT $1 + $2;'
);

expect(statement).toBeTypeOf('string');
Expand Down
4 changes: 2 additions & 2 deletions test/runner.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
});
Expand Down Expand Up @@ -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
});
Expand Down

0 comments on commit 11d5e57

Please sign in to comment.