Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: validate all tables have primary keys #6005

Merged
merged 2 commits into from
Jan 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/test/e2e/migrator.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { IDBOption } from '../../lib/types';

log.setLogLevel('error');

const schema = 'up_n_down_migrations_test';

async function initSchema(db: IDBOption): Promise<void> {
const client = new Client(db);
await client.connect();
Expand All @@ -15,13 +17,42 @@ async function initSchema(db: IDBOption): Promise<void> {
await client.end();
}

async function validateTablesHavePrimaryKeys(db: IDBOption) {
const client = new Client(db);
await client.connect();
const tables = await client.query<{ table_name: string }>(
`SELECT
t.table_name
FROM
information_schema.tables t
LEFT JOIN
information_schema.table_constraints tc ON t.table_schema = tc.table_schema
AND t.table_name = tc.table_name
AND tc.constraint_type = 'PRIMARY KEY'
WHERE
t.table_type = 'BASE TABLE'
AND t.table_schema = '${schema}'
AND t.table_schema NOT IN ('pg_catalog', 'information_schema')
AND tc.constraint_name IS NULL;
`,
);
await client.end();
if ((tables.rowCount ?? 0) > 0) {
throw new Error(
`The following tables do not have a primary key defined: ${tables.rows
.map((r) => r.table_name)
.join(', ')}`,
);
}
}

test('Up & down migrations work', async () => {
jest.setTimeout(15000);
const config = createTestConfig({
db: {
...getDbConfig(),
pool: { min: 1, max: 4 },
schema: 'up_n_down_migrations_test',
schema: schema,
ssl: false,
},
});
Expand All @@ -42,5 +73,6 @@ test('Up & down migrations work', async () => {
});

await dbm.up();
await validateTablesHavePrimaryKeys(config.db);
await dbm.reset();
});
Loading