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

Add automatic row timestamps for Accounts and Groups tables #1674

Merged
merged 7 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
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
25 changes: 22 additions & 3 deletions migrations/00001_accounts/index.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,31 @@ DROP TABLE IF EXISTS groups,
accounts CASCADE;

CREATE TABLE
groups (id SERIAL PRIMARY KEY);
groups (
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

CREATE TABLE
accounts (
id SERIAL PRIMARY KEY,
group_id INTEGER REFERENCES groups (id),
group_id INTEGER REFERENCES groups (id) ON DELETE SET NULL,
address CHARACTER VARYING(42) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
UNIQUE (address)
);
);

CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE TRIGGER update_accounts_updated_at
BEFORE UPDATE ON accounts
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
81 changes: 77 additions & 4 deletions migrations/__tests__/00001_accounts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,22 @@ import { dbFactory } from '@/__tests__/db.factory';
import { PostgresDatabaseMigrator } from '@/datasources/db/postgres-database.migrator';
import { Sql } from 'postgres';

interface AccountRow {
id: number;
group_id: number;
created_at: Date;
updated_at: Date;
address: `0x${string}`;
}

describe('Migration 00001_accounts', () => {
const sql = dbFactory();
const migrator = new PostgresDatabaseMigrator(sql);

afterAll(async () => {
await sql.end();
});

it('runs successfully', async () => {
await sql`DROP TABLE IF EXISTS groups, accounts CASCADE;`;

Expand All @@ -32,20 +44,81 @@ describe('Migration 00001_accounts', () => {
columns: [
{ column_name: 'id' },
{ column_name: 'group_id' },
{ column_name: 'created_at' },
{ column_name: 'updated_at' },
{ column_name: 'address' },
],
rows: [],
},
groups: {
columns: [
{
column_name: 'id',
},
{ column_name: 'id' },
{ column_name: 'created_at' },
{ column_name: 'updated_at' },
],
rows: [],
},
});
});

await sql.end();
it('should add and update row timestamps', async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: let's add another test that then ensures the created_at doesn't change but updated_at does after as the after callback combines all queries in one transaction.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a test in b1a9b0f

await sql`DROP TABLE IF EXISTS groups, accounts CASCADE;`;

const result: {
before: unknown;
after: AccountRow[];
} = await migrator.test({
migration: '00001_accounts',
after: async (sql: Sql): Promise<AccountRow[]> => {
await sql`INSERT INTO groups (id) VALUES (1);`;
await sql`INSERT INTO accounts (id, group_id, address) VALUES (1, 1, '0x0000');`;
await sql`UPDATE accounts set address = '0x0001' WHERE id = 1;`;
return await sql<AccountRow[]>`SELECT * FROM accounts`;
},
});

const createdAt = new Date(result.after[0].created_at);
const updatedAt = new Date(result.after[0].updated_at);

expect(result.after).toStrictEqual(
expect.arrayContaining([
expect.objectContaining({
created_at: createdAt,
updated_at: updatedAt,
}),
]),
);

expect(updatedAt.getTime()).toBeGreaterThan(createdAt.getTime());
});

it('only updated_at should be updated on row changes', async () => {
await sql`DROP TABLE IF EXISTS groups, accounts CASCADE;`;

const result: {
before: unknown;
after: AccountRow[];
} = await migrator.test({
migration: '00001_accounts',
after: async (sql: Sql): Promise<AccountRow[]> => {
await sql`INSERT INTO groups (id) VALUES (1);`;
await sql`INSERT INTO accounts (id, group_id, address) VALUES (1, 1, '0x0000');`;
return await sql<AccountRow[]>`SELECT * FROM accounts`;
},
});

// created_at and updated_at should be the same after the row is created
const createdAt = new Date(result.after[0].created_at);
const updatedAt = new Date(result.after[0].updated_at);
expect(createdAt).toStrictEqual(updatedAt);

// only updated_at should be updated after the row is updated
await sql`UPDATE accounts set address = '0x0001' WHERE id = 1;`;
const afterUpdate = await sql<AccountRow[]>`SELECT * FROM accounts`;
const updatedAtAfterUpdate = new Date(afterUpdate[0].updated_at);
const createdAtAfterUpdate = new Date(afterUpdate[0].created_at);

expect(createdAtAfterUpdate).toStrictEqual(createdAt);
expect(updatedAtAfterUpdate.getTime()).toBeGreaterThan(createdAt.getTime());
});
});
4 changes: 4 additions & 0 deletions src/datasources/accounts/accounts.datasource.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ describe('AccountsDatasource tests', () => {
id: expect.any(Number),
group_id: null,
address,
created_at: expect.any(Date),
updated_at: expect.any(Date),
});
});

Expand All @@ -67,6 +69,8 @@ describe('AccountsDatasource tests', () => {
id: expect.any(Number),
group_id: null,
address,
created_at: expect.any(Date),
updated_at: expect.any(Date),
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ export function accountBuilder(): IBuilder<Account> {
return new Builder<Account>()
.with('id', faker.number.int())
.with('group_id', faker.number.int())
.with('address', getAddress(faker.finance.ethereumAddress()));
.with('address', getAddress(faker.finance.ethereumAddress()))
.with('created_at', faker.date.recent())
.with('updated_at', faker.date.recent());
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ import { Group } from '@/datasources/accounts/entities/group.entity';
import { faker } from '@faker-js/faker';

export function groupBuilder(): IBuilder<Group> {
return new Builder<Group>().with('id', faker.number.int());
return new Builder<Group>()
.with('id', faker.number.int())
.with('created_at', faker.date.recent())
.with('updated_at', faker.date.recent());
}
14 changes: 14 additions & 0 deletions src/datasources/accounts/entities/account.entity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,20 @@ describe('AccountSchema', () => {
path: ['id'],
received: 'undefined',
},
{
code: 'invalid_type',
expected: 'date',
message: 'Required',
path: ['created_at'],
received: 'undefined',
},
{
code: 'invalid_type',
expected: 'date',
message: 'Required',
path: ['updated_at'],
received: 'undefined',
},
{
code: 'invalid_type',
expected: 'number',
Expand Down
4 changes: 2 additions & 2 deletions src/datasources/accounts/entities/account.entity.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { GroupSchema } from '@/datasources/accounts/entities/group.entity';
import { RowSchema } from '@/datasources/db/entities/row.entity';
import { AddressSchema } from '@/validation/entities/schemas/address.schema';
import { z } from 'zod';

export type Account = z.infer<typeof AccountSchema>;

export const AccountSchema = z.object({
id: z.number().int(),
export const AccountSchema = RowSchema.extend({
group_id: GroupSchema.shape.id,
address: AddressSchema,
});
14 changes: 14 additions & 0 deletions src/datasources/accounts/entities/group.entity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ describe('GroupSchema', () => {
path: ['id'],
received: 'undefined',
},
{
code: 'invalid_type',
expected: 'date',
message: 'Required',
path: ['created_at'],
received: 'undefined',
},
{
code: 'invalid_type',
expected: 'date',
message: 'Required',
path: ['updated_at'],
received: 'undefined',
},
]);
});
});
5 changes: 2 additions & 3 deletions src/datasources/accounts/entities/group.entity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { RowSchema } from '@/datasources/db/entities/row.entity';
import { z } from 'zod';

export type Group = z.infer<typeof GroupSchema>;

export const GroupSchema = z.object({
id: z.number().int(),
});
export const GroupSchema = RowSchema;
14 changes: 14 additions & 0 deletions src/datasources/db/entities/row.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { z } from 'zod';

export type Row = z.infer<typeof RowSchema>;

/**
* Note: this is a base schema for all entities that are meant to be persisted to the database.
* The 'id' field is a primary key, and the 'created_at' and 'updated_at' fields are timestamps.
* These fields shouldn't be modified by the application, and should be managed by the database.
*/
export const RowSchema = z.object({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: as we will be extending this for all tables, I would add some comments here as I've seen issues when using merge, e.g. outling that id is the primary key and caution should be taken when updating.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a comment in b1a9b0f

Please let me know if you want to rephrase it or add something else!

id: z.number().int(),
created_at: z.date(),
updated_at: z.date(),
});
15 changes: 10 additions & 5 deletions src/datasources/db/postgres-database.migrator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const migrations: Array<{
},
},
];
type TestRow = { a: string; b: number };
type ExtendedTestRow = { a: string; b: number; c: Date };

describe('PostgresDatabaseMigrator tests', () => {
let sql: postgres.Sql;
Expand Down Expand Up @@ -196,8 +198,9 @@ describe('PostgresDatabaseMigrator tests', () => {
await expect(
target.test({
migration: migration1.name,
before: (sql) => sql`SELECT * FROM test`,
after: (sql) => sql`SELECT * FROM test`,
before: (sql) => sql`SELECT * FROM test`.catch(() => undefined),
after: (sql): Promise<TestRow[]> =>
sql<TestRow[]>`SELECT * FROM test`,
folder,
}),
).resolves.toStrictEqual({
Expand Down Expand Up @@ -227,8 +230,10 @@ describe('PostgresDatabaseMigrator tests', () => {
await expect(
target.test({
migration: migration2.name,
before: (sql) => sql`SELECT * FROM test`,
after: (sql) => sql`SELECT * FROM test`,
before: (sql): Promise<TestRow[]> =>
sql<TestRow[]>`SELECT * FROM test`,
after: (sql): Promise<ExtendedTestRow[]> =>
sql<ExtendedTestRow[]>`SELECT * FROM test`,
folder,
}),
).resolves.toStrictEqual({
Expand Down Expand Up @@ -265,7 +270,7 @@ describe('PostgresDatabaseMigrator tests', () => {
target.test({
migration: migration3.name,
before: (sql) => sql`SELECT * FROM test`,
after: (sql) => sql`SELECT * FROM test`,
after: (sql) => sql`SELECT * FROM test`.catch(() => undefined),
folder,
}),
).resolves.toStrictEqual({
Expand Down
29 changes: 18 additions & 11 deletions src/datasources/db/postgres-database.migrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ type Migration = {
name: string;
};

type TestResult<BeforeType, AfterType> = {
before: BeforeType | undefined;
after: AfterType;
};

/**
* Migrates a Postgres database using SQL and JavaScript files.
*
Expand Down Expand Up @@ -51,7 +56,8 @@ export class PostgresDatabaseMigrator {
}

/**
* @private migrates up to/allows for querying before/after migration to test it.
* Migrates up to/allows for querying before/after migration to test it.
* Uses generics to allow the caller to specify the return type of the before/after functions.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love this!

*
* Note: each migration is ran in separate transaction to allow queries in between.
*
Expand All @@ -72,15 +78,12 @@ export class PostgresDatabaseMigrator {
* expect(result.after).toStrictEqual(expected);
* ```
*/
async test(args: {
async test<BeforeType, AfterType>(args: {
migration: string;
before?: (sql: Sql) => Promise<unknown>;
after: (sql: Sql) => Promise<unknown>;
before?: (sql: Sql) => Promise<BeforeType>;
after: (sql: Sql) => Promise<AfterType>;
folder?: string;
}): Promise<{
before: unknown;
after: unknown;
}> {
}): Promise<TestResult<BeforeType, AfterType>> {
const migrations = this.getMigrations(
args.folder ?? PostgresDatabaseMigrator.MIGRATIONS_FOLDER,
);
Expand All @@ -97,21 +100,25 @@ export class PostgresDatabaseMigrator {
// Get migrations up to the specified migration
const migrationsToTest = migrations.slice(0, migrationIndex + 1);

let before: unknown;
let before: BeforeType | undefined;

for await (const migration of migrationsToTest) {
const isMigrationBeingTested = migration.path.includes(args.migration);

if (isMigrationBeingTested && args.before) {
before = await args.before(this.sql).catch(() => undefined);
before = await args.before(this.sql).catch((err) => {
throw Error(`Error running before function: ${err}`);
});
}

await this.sql.begin((transaction) => {
return this.run({ transaction, migration });
});
}

const after = await args.after(this.sql).catch(() => undefined);
const after = await args.after(this.sql).catch((err) => {
throw Error(`Error running after function: ${err}`);
});

return { before, after };
}
Expand Down
Loading