I'd like to create tables on the db initialization stage which look like this:
CREATE TABLE IF NOT EXISTS users (
"id" SERIAL PRIMARY KEY,
"created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
"name" TEXT NOT NULL,
)
It would be trivial to do in the normal server setup (even async one), but nextjs doesn't have a centralized "init" stage. So far I came up with this wrapper:
import { setupTables } from "./tables";
import { getDBSingleton } from "./init";
let isInitialized = false;
export async function getDB() {
const scope = getDBSingleton();
if (!isInitialized) {
await setupTables(scope.db);
isInitialized = true;
}
return scope;
}
getDBSingleton()
is the function from this response:
Where should I initialize pg-promise
This wrapper does work, but requires calling await getDB()
into every single function which does DB call, as opposed to once per module.
Is there a better way to handle this?
The real solution is to move migrations to a separate script and run it before the build.