keep createSession raw writes on primary when replicas are enabled
This commit is contained in:
1 parent
7a176e10bc
commit
4c4071b270
3 files changed
+148
-10
No files matched your search
@@ -0,0 +1,82 @@
|
||||
import { beforeAll, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
process.env.DATABASE_URL ??= 'postgresql://user:pass@localhost:5432/umami?schema=public';
|
||||
delete process.env.DATABASE_REPLICA_URL;
|
||||
|
||||
vi.mock('@prisma/adapter-pg', () => ({
|
||||
PrismaPg: class PrismaPg {},
|
||||
}));
|
||||
|
||||
vi.mock('@prisma/extension-read-replicas', () => ({
|
||||
readReplicas: () => () => ({}),
|
||||
}));
|
||||
|
||||
vi.mock('@/generated/prisma/client', () => ({
|
||||
PrismaClient: class PrismaClient {
|
||||
$executeRawUnsafe = vi.fn();
|
||||
$queryRawUnsafe = vi.fn();
|
||||
$transaction = vi.fn();
|
||||
$on = vi.fn();
|
||||
$extends() {
|
||||
return this;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
let getRawQueryClient!: typeof import('./prisma').getRawQueryClient;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ getRawQueryClient } = await import('./prisma'));
|
||||
});
|
||||
|
||||
interface RawQueryClient {
|
||||
$executeRawUnsafe: (query: string, ...params: any[]) => unknown;
|
||||
$queryRawUnsafe: (query: string, ...params: any[]) => unknown;
|
||||
$primary?: () => unknown;
|
||||
$replica?: () => unknown;
|
||||
}
|
||||
|
||||
function createClient(): RawQueryClient {
|
||||
return {
|
||||
$executeRawUnsafe: vi.fn(),
|
||||
$queryRawUnsafe: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('getRawQueryClient', () => {
|
||||
test('uses a replica client for read queries when replicas are enabled', () => {
|
||||
const replica = createClient();
|
||||
const client = {
|
||||
...createClient(),
|
||||
$replica: vi.fn(() => replica),
|
||||
};
|
||||
|
||||
expect(getRawQueryClient(client, { useReplica: true })).toBe(replica);
|
||||
});
|
||||
|
||||
test('keeps read queries on the primary client when replicas are disabled', () => {
|
||||
const client = {
|
||||
...createClient(),
|
||||
$replica: vi.fn(() => createClient()),
|
||||
};
|
||||
|
||||
expect(getRawQueryClient(client, { useReplica: false })).toBe(client);
|
||||
});
|
||||
|
||||
test('uses the primary client for raw writes when available', () => {
|
||||
const primary = createClient();
|
||||
const client = {
|
||||
...createClient(),
|
||||
$primary: vi.fn(() => primary),
|
||||
$replica: vi.fn(() => createClient()),
|
||||
};
|
||||
|
||||
expect(getRawQueryClient(client, { useReplica: true, write: true })).toBe(primary);
|
||||
});
|
||||
|
||||
test('falls back to the current client for raw writes without a primary helper', () => {
|
||||
const client = createClient();
|
||||
|
||||
expect(getRawQueryClient(client, { write: true })).toBe(client);
|
||||
});
|
||||
});
|
||||
+64
-8
@@ -29,6 +29,46 @@ const PRISMA_LOG_OPTIONS = {
|
||||
],
|
||||
};
|
||||
|
||||
export interface RawQueryExecutor {
|
||||
$executeRawUnsafe: (query: string, ...params: any[]) => unknown;
|
||||
$queryRawUnsafe: (query: string, ...params: any[]) => unknown;
|
||||
}
|
||||
|
||||
export interface RawQueryClient extends RawQueryExecutor {
|
||||
$primary?: () => unknown;
|
||||
$replica?: () => unknown;
|
||||
}
|
||||
|
||||
function isRawQueryExecutor(value: unknown): value is RawQueryExecutor {
|
||||
return !!value && typeof value === 'object' && '$executeRawUnsafe' in value && '$queryRawUnsafe' in value;
|
||||
}
|
||||
|
||||
export function getRawQueryClient(
|
||||
client: RawQueryClient,
|
||||
{
|
||||
useReplica = false,
|
||||
write = false,
|
||||
}: {
|
||||
useReplica?: boolean;
|
||||
write?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
if (write) {
|
||||
const primary = typeof client.$primary === 'function' ? client.$primary() : null;
|
||||
return isRawQueryExecutor(primary) ? primary : client;
|
||||
}
|
||||
|
||||
if (useReplica && typeof client.$replica === 'function') {
|
||||
const replica = client.$replica();
|
||||
|
||||
if (isRawQueryExecutor(replica)) {
|
||||
return replica;
|
||||
}
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
const DATE_FORMATS = {
|
||||
minute: 'YYYY-MM-DD HH24:MI:00',
|
||||
hour: 'YYYY-MM-DD HH24:00:00',
|
||||
@@ -410,7 +450,12 @@ function getPropertyFilterQuery(
|
||||
return { sql: parts.join('\n'), params };
|
||||
}
|
||||
|
||||
async function rawQuery(sql: string, data: Record<string, any>, name?: string): Promise<any> {
|
||||
async function executeRawQuery(
|
||||
sql: string,
|
||||
data: Record<string, any>,
|
||||
name?: string,
|
||||
write = false,
|
||||
): Promise<any> {
|
||||
if (process.env.LOG_QUERY) {
|
||||
log('QUERY:\n', sql);
|
||||
log('PARAMETERS:\n', data);
|
||||
@@ -419,10 +464,6 @@ async function rawQuery(sql: string, data: Record<string, any>, name?: string):
|
||||
const params = [];
|
||||
const schema = getSchema();
|
||||
|
||||
if (schema) {
|
||||
await client.$executeRawUnsafe(`SET search_path TO "${schema}";`);
|
||||
}
|
||||
|
||||
const query = sql?.replaceAll(/\{\{\s*(\w+)(::\w+)?\s*}}/g, (...args) => {
|
||||
const [, name, type] = args;
|
||||
|
||||
@@ -433,10 +474,24 @@ async function rawQuery(sql: string, data: Record<string, any>, name?: string):
|
||||
return `$${params.length}${type ?? ''}`;
|
||||
});
|
||||
|
||||
if (process.env.DATABASE_REPLICA_URL && '$replica' in client) {
|
||||
return client.$replica().$queryRawUnsafe(query, ...params);
|
||||
const queryClient = getRawQueryClient(client, {
|
||||
useReplica: !!process.env.DATABASE_REPLICA_URL,
|
||||
write,
|
||||
});
|
||||
|
||||
if (schema) {
|
||||
await queryClient.$executeRawUnsafe(`SET search_path TO "${schema}";`);
|
||||
}
|
||||
return client.$queryRawUnsafe(query, ...params);
|
||||
|
||||
return queryClient.$queryRawUnsafe(query, ...params);
|
||||
}
|
||||
|
||||
async function rawQuery(sql: string, data: Record<string, any>, name?: string): Promise<any> {
|
||||
return executeRawQuery(sql, data, name);
|
||||
}
|
||||
|
||||
async function writeRawQuery(sql: string, data: Record<string, any>, name?: string): Promise<any> {
|
||||
return executeRawQuery(sql, data, name, true);
|
||||
}
|
||||
|
||||
async function pagedQuery<T>(model: string, criteria: T, filters?: QueryFilters) {
|
||||
@@ -613,4 +668,5 @@ export default {
|
||||
pagedRawQuery,
|
||||
parseFilters,
|
||||
rawQuery,
|
||||
writeRawQuery,
|
||||
};
|
||||
@@ -6,7 +6,7 @@ import prisma from '@/lib/prisma';
|
||||
const FUNCTION_NAME = 'createSession';
|
||||
|
||||
export async function createSession(data: Prisma.SessionCreateInput) {
|
||||
const { rawQuery } = prisma;
|
||||
const { writeRawQuery } = prisma;
|
||||
const normalizedData: Prisma.SessionCreateInput = {
|
||||
...data,
|
||||
browser: truncateString(data.browser, FIELD_LENGTH.browser),
|
||||
@@ -20,7 +20,7 @@ export async function createSession(data: Prisma.SessionCreateInput) {
|
||||
distinctId: truncateString(data.distinctId, FIELD_LENGTH.distinctId),
|
||||
};
|
||||
|
||||
await rawQuery(
|
||||
await writeRawQuery(
|
||||
`
|
||||
insert into session (
|
||||
session_id,
|
||||
|
||||
Reference in new issue
Block a user