Drizzle/tests/database.ts

57 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

import dotenv from "dotenv";
import postgres from "postgres";
import {drizzle} from "drizzle-orm/postgres-js";
import {sql} from "drizzle-orm";
import * as InvoicesSchema from "./schema/invoices";
// Load configuration from environment variables.
dotenv.config({
path: ".env.test",
});
const queryClient = postgres(`postgres://${process.env.POSTGRES_USERNAME}:${process.env.POSTGRES_PASSWORD}@${process.env.POSTGRES_HOST}:${process.env.POSTGRES_PORT}/${process.env.POSTGRES_DATABASE}`);
export const database = drizzle(queryClient, {
schema: {
...InvoicesSchema,
},
});
/**
* Initialize database schema for tests.
*/
export async function initializeDatabase(): Promise<void>
{
await database.execute(sql`
DROP TABLE IF EXISTS invoices;
CREATE TABLE invoices(
id SERIAL PRIMARY KEY,
date TIMESTAMP WITH TIME ZONE,
amount NUMERIC(12, 2),
client_name VARCHAR,
client_address TEXT
);
`);
}
/**
* Add default invoices for tests.
*/
export async function setupDefaultInvoices(): Promise<void>
{
await database.execute(sql`TRUNCATE invoices RESTART IDENTITY;`);
await database.insert(InvoicesSchema.invoices).values([
{
date: new Date("1997-10-09"),
amount: "5450.12",
clientName: "test name",
clientAddress: "test test test",
},
{
date: new Date(),
amount: "1122.54",
clientName: "another name",
clientAddress: "foo bar baz",
},
]);
}