petja
petja
DTDrizzle Team
Created by petja on 8/16/2024 in #help
Is there more elegant way to infer enums?
This works: type TransactionReason = (typeof transactionReasonEnum)['enumValues'][number] But I wonder if Drizzle happen to have built-in way to infer TypeScript union from PostgreSQL enum.
2 replies
DTDrizzle Team
Created by petja on 4/2/2023 in #help
Mocking database
I want to mock the PostgreSQL database and access it with Drizzle ORM. I tried to write a TypeScript class that should work the same way as pg's Pool class, but instead of hitting an actual database, returns rows from an in-memory object. However when SELECT'ing from the table I had mocked, Drizzle returned an object with all keys having undefined values. Any help? 🙂
export class MockPool {
private mocks: Record<string, (params: any[]) => Record<string, any>[]> = {};

mockQuery(query: string, rows: (params: any[]) => Record<string, any>[]) {
this.mocks[query] = rows;
}

async query(
query: string | QueryConfig,
values?: any[]
): Promise<Partial<QueryResult>> {
let queryConfig: QueryConfig;

if (typeof query === "string") {
queryConfig = { text: query, values };
} else {
queryConfig = { ...query };

if (values) {
queryConfig.values = values;
}
}

const mock = this.mocks[queryConfig.text];

if (!mock) {
throw new Error(`Missing mock for query ${queryConfig.text}`);
}

const rows = mock(queryConfig.values ?? []);

return {
rowCount: rows.length,
rows,
};
}
}
export class MockPool {
private mocks: Record<string, (params: any[]) => Record<string, any>[]> = {};

mockQuery(query: string, rows: (params: any[]) => Record<string, any>[]) {
this.mocks[query] = rows;
}

async query(
query: string | QueryConfig,
values?: any[]
): Promise<Partial<QueryResult>> {
let queryConfig: QueryConfig;

if (typeof query === "string") {
queryConfig = { text: query, values };
} else {
queryConfig = { ...query };

if (values) {
queryConfig.values = values;
}
}

const mock = this.mocks[queryConfig.text];

if (!mock) {
throw new Error(`Missing mock for query ${queryConfig.text}`);
}

const rows = mock(queryConfig.values ?? []);

return {
rowCount: rows.length,
rows,
};
}
}
Using the mock pool:
import { drizzle } from "drizzle-orm/node-postgres";
const pool = new MockPool()
const db = drizzle(pool as any) // any, because we're not implementing whole Pool class

pool.mock('SELECT * FROM users', () => [{ id: '1234', name: 'Petja' }])

usersTable.select() // { id: undefined, name: undefined }
import { drizzle } from "drizzle-orm/node-postgres";
const pool = new MockPool()
const db = drizzle(pool as any) // any, because we're not implementing whole Pool class

pool.mock('SELECT * FROM users', () => [{ id: '1234', name: 'Petja' }])

usersTable.select() // { id: undefined, name: undefined }
11 replies