Skip to content

Commit

Permalink
feat: improved DB-utils (#237)
Browse files Browse the repository at this point in the history
  • Loading branch information
FilipHarald authored Dec 13, 2024
1 parent 1dad9f9 commit c0c544e
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 141 deletions.
12 changes: 0 additions & 12 deletions docs/clear_live_db.md

This file was deleted.

2 changes: 2 additions & 0 deletions k8s/local/aztec-listener/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ spec:
value: "admin"
- name: POSTGRES_PASSWORD
value: "secret-local-password"
- name: TOTAL_DB_RESET
value: "true"
containers:
- image: aztec-listener:latest
resources:
Expand Down
2 changes: 2 additions & 0 deletions k8s/local/explorer-api/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ spec:
value: "admin"
- name: POSTGRES_PASSWORD
value: "secret-local-password"
- name: TOTAL_DB_RESET
value: "false"
containers:
- image: explorer-api:latest
resources:
Expand Down
6 changes: 5 additions & 1 deletion packages/backend-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@
},
"dependencies": {
"@aztec/aztec.js": "0.67.0",
"@chicmoz-pkg/types": "workspace:^"
"@chicmoz-pkg/types": "workspace:^",
"drizzle-orm": "0.33.0",
"exponential-backoff": "3.1.1",
"pg": "8.11.3"
},
"devDependencies": {
"@types/pg": "8.11.8",
"@typescript-eslint/eslint-plugin": "6.11.0",
"@typescript-eslint/parser": "6.11.0",
"eslint": "8.53.0",
Expand Down
1 change: 1 addition & 0 deletions packages/backend-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./parse-block.js";
export * from "./migrate-db.js";
87 changes: 87 additions & 0 deletions packages/backend-utils/src/migrate-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/* eslint-disable no-console */
import { Logger } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { backOff } from "exponential-backoff";
import pg, { PoolClient } from "pg";

class MyLogger implements Logger {
logQuery(query: string): void {
console.log("QUERY:", query);
}
}

const TOTAL_DB_RESET = process.env.TOTAL_DB_RESET === "true";

const retries = 50;

async function printTableList(client: PoolClient, ID: string): Promise<void> {
const res = await client.query(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name"
);
console.log(`=========== ${ID} ============`);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
res.rows.forEach((row) => console.log(row.table_name));
console.log("==============================");
}

async function tryMigrate(pool: pg.Pool, db: ReturnType<typeof drizzle>) {
const client = await pool.connect();
await printTableList(client, "BEFORE MIGRATION");
if (TOTAL_DB_RESET) await dropAllTables(client);

await migrate(db, { migrationsFolder: "./migrations" });
await printTableList(client, "AFTER MIGRATION");
client.release();
console.log("👌 Client released");
}

async function run(
dbCredentials: pg.PoolConfig,
db: ReturnType<typeof drizzle>
) {
console.log("🥸 Running migrations...");
console.log(
`host: ${dbCredentials.host} port: ${dbCredentials.port} db: ${dbCredentials.database} user: ${dbCredentials.user}`
);
await backOff(() => tryMigrate(new pg.Pool(dbCredentials), db), {
maxDelay: 10000,
numOfAttempts: retries,
retry: (e, attemptNumber: number) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (e.code === "ECONNREFUSED") {
console.log(`Retrying attempt ${attemptNumber} of ${retries}...`);
return true;
}
console.error(e);
return false;
},
});
console.log("🤩 Migrations complete!");
if (TOTAL_DB_RESET) console.log("🔥🔥🔥 Total DB reset!");
}

async function dropAllTables(client: PoolClient) {
console.log("🔥 Dropping all tables...");
const res1 = await client.query("DROP SCHEMA public CASCADE");
console.log(`💣 ${res1.command} ${res1.rowCount}`);
const res2 = await client.query("CREATE SCHEMA public");
console.log(`💣 ${res2.command} ${res2.rowCount}`);
const res3 = await client.query("DROP SCHEMA drizzle CASCADE");
console.log(`💣 ${res3.command} ${res3.rowCount}`);
}

export async function runMigrations(dbCredentials: pg.PoolConfig) {
const pool = new pg.Pool(dbCredentials);
const db = drizzle(pool, { logger: new MyLogger() });
try {
await run(dbCredentials, db);
await pool.end();
console.log("👋 Pool closed!");
} catch (e) {
console.error(e);
await pool.end();
console.log("👋👋 Pool closed!");
process.exit(1);
}
}
1 change: 1 addition & 0 deletions services/aztec-listener/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"dependencies": {
"@aztec/aztec.js": "0.67.0",
"@aztec/circuits.js": "0.67.0",
"@chicmoz-pkg/backend-utils": "workspace:^",
"@chicmoz-pkg/logger-server": "workspace:^",
"@chicmoz-pkg/message-bus": "workspace:^",
"@chicmoz-pkg/message-registry": "workspace:^",
Expand Down
66 changes: 3 additions & 63 deletions services/aztec-listener/scripts/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,6 @@
/* eslint-disable no-console, @typescript-eslint/no-unsafe-member-access */

import { Logger } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { backOff } from "exponential-backoff";
import pg, { PoolClient } from "pg";
/* eslint-disable no-console */
import { dbCredentials } from "../src/constants.js";
import { runMigrations } from "@chicmoz-pkg/backend-utils";

class MyLogger implements Logger {
logQuery(query: string): void {
console.log("QUERY:", query);
}
}

const pool = new pg.Pool(dbCredentials);
const db = drizzle(pool, { logger: new MyLogger() });
const retries = 50;

async function printTableList(client: PoolClient, ID: string): Promise<void> {
const res = await client.query(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name"
);
console.log(`=========== ${ID} ============`);
res.rows.forEach((row) => console.log(row.table_name));
console.log("==============================");
}

async function tryMigrate() {
const client = await pool.connect();
await printTableList(client, "BEFORE MIGRATION");
await migrate(db, { migrationsFolder: "./migrations" });
await printTableList(client, "AFTER MIGRATION");
client.release();
console.log("👌 Client released");
}

async function runMigrations() {
console.log("🥸 Running migrations...");
console.log(
`host: ${dbCredentials.host} port: ${dbCredentials.port} db: ${dbCredentials.database} user: ${dbCredentials.user}`
);
await backOff(() => tryMigrate(), {
maxDelay: 10000,
numOfAttempts: retries,
retry: (e, attemptNumber: number) => {
if (e.code === "ECONNREFUSED") {
console.log(`Retrying attempt ${attemptNumber} of ${retries}...`);
return true;
}
console.error(e);
return false;
},
});
console.log("🤩 Migrations complete!");
await pool.end();
console.log("👋 Pool closed!");
}

runMigrations().catch(async (e) => {
console.error(e);
await pool.end();
console.log("👋 Pool closed!");
process.exit(1);
});
runMigrations(dbCredentials).catch(console.error);

1 change: 0 additions & 1 deletion services/explorer-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"@types/jest": "29.5.11",
"@types/morgan": "1.9.4",
"@types/node": "20.5.0",
"@types/pg": "8.11.8",
"@types/redis": "4.0.11",
"@types/supertest": "6.0.2",
"@types/uuid": "10.0.0",
Expand Down
66 changes: 3 additions & 63 deletions services/explorer-api/scripts/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,65 +1,5 @@
/* eslint-disable no-console, @typescript-eslint/no-unsafe-member-access */

import { Logger } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { backOff } from "exponential-backoff";
import pg, { PoolClient } from "pg";
/* eslint-disable no-console */
import { dbCredentials } from "../src/environment.js";
import { runMigrations } from "@chicmoz-pkg/backend-utils";

class MyLogger implements Logger {
logQuery(query: string): void {
console.log("QUERY:", query);
}
}

const pool = new pg.Pool(dbCredentials);
const db = drizzle(pool, { logger: new MyLogger() });
const retries = 50;

async function printTableList(client: PoolClient, ID: string): Promise<void> {
const res = await client.query(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name"
);
console.log(`=========== ${ID} ============`);
res.rows.forEach((row) => console.log(row.table_name));
console.log("==============================");
}

async function tryMigrate() {
const client = await pool.connect();
await printTableList(client, "BEFORE MIGRATION");
await migrate(db, { migrationsFolder: "./migrations" });
await printTableList(client, "AFTER MIGRATION");
client.release();
console.log("👌 Client released");
}

async function runMigrations() {
console.log("🥸 Running migrations...");
console.log(
`host: ${dbCredentials.host} port: ${dbCredentials.port} db: ${dbCredentials.database} user: ${dbCredentials.user}`
);
await backOff(() => tryMigrate(), {
maxDelay: 10000,
numOfAttempts: retries,
retry: (e, attemptNumber: number) => {
if (e.code === "ECONNREFUSED") {
console.log(`Retrying attempt ${attemptNumber} of ${retries}...`);
return true;
}
console.error(e);
return false;
},
});
console.log("🤩 Migrations complete!");
await pool.end();
console.log("👋 Pool closed!");
}

runMigrations().catch(async (e) => {
console.error(e);
await pool.end();
console.log("👋 Pool closed!");
process.exit(1);
});
runMigrations(dbCredentials).catch(console.error);
6 changes: 5 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -774,11 +774,15 @@ __metadata:
dependencies:
"@aztec/aztec.js": "npm:0.67.0"
"@chicmoz-pkg/types": "workspace:^"
"@types/pg": "npm:8.11.8"
"@typescript-eslint/eslint-plugin": "npm:6.11.0"
"@typescript-eslint/parser": "npm:6.11.0"
drizzle-orm: "npm:0.33.0"
eslint: "npm:8.53.0"
eslint-config-prettier: "npm:9.0.0"
eslint-plugin-import: "npm:2.29.0"
exponential-backoff: "npm:3.1.1"
pg: "npm:8.11.3"
prettier: "npm:3.1.0"
prettier-plugin-organize-imports: "npm:3.2.4"
prettier-plugin-sort-json: "npm:3.1.0"
Expand Down Expand Up @@ -930,6 +934,7 @@ __metadata:
dependencies:
"@aztec/aztec.js": "npm:0.67.0"
"@aztec/circuits.js": "npm:0.67.0"
"@chicmoz-pkg/backend-utils": "workspace:^"
"@chicmoz-pkg/logger-server": "workspace:^"
"@chicmoz-pkg/message-bus": "workspace:^"
"@chicmoz-pkg/message-registry": "workspace:^"
Expand Down Expand Up @@ -1044,7 +1049,6 @@ __metadata:
"@types/jest": "npm:29.5.11"
"@types/morgan": "npm:1.9.4"
"@types/node": "npm:20.5.0"
"@types/pg": "npm:8.11.8"
"@types/redis": "npm:4.0.11"
"@types/supertest": "npm:6.0.2"
"@types/uuid": "npm:10.0.0"
Expand Down

0 comments on commit c0c544e

Please sign in to comment.