feat: PostgreSQL withTenant-Helper und ClickHouse-Client

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-17 08:20:25 +00:00
parent 7c7fc23b8c
commit 506197623a
4 changed files with 64 additions and 0 deletions

9
src/server/db/client.ts Normal file
View File

@@ -0,0 +1,9 @@
import { Pool } from 'pg'
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
export const db = {
execute: (sql: string) => pool.query(sql),
query: <T = Record<string, unknown>>(sql: string, params: unknown[]) =>
pool.query<T>(sql, params).then((r) => r.rows),
}

View File

@@ -0,0 +1,36 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('./client', () => ({
db: {
execute: vi.fn(),
query: vi.fn().mockResolvedValue([{ id: '1' }]),
},
}))
import { withTenant } from './tenant'
import { db } from './client'
describe('withTenant', () => {
beforeEach(() => vi.clearAllMocks())
it('setzt search_path auf tenant-Schema', async () => {
await withTenant('abc123', () => db.query('SELECT 1', []))
expect(db.execute).toHaveBeenCalledWith('SET search_path = tenant_abc123, public')
})
it('setzt search_path zurück auf public nach Ausführung', async () => {
await withTenant('abc123', () => db.query('SELECT 1', []))
expect(db.execute).toHaveBeenLastCalledWith('SET search_path = public')
})
it('setzt search_path zurück auch bei Fehler', async () => {
const fn = vi.fn().mockRejectedValue(new Error('DB-Fehler'))
await expect(withTenant('abc123', fn)).rejects.toThrow('DB-Fehler')
expect(db.execute).toHaveBeenLastCalledWith('SET search_path = public')
})
it('gibt Rückgabewert der Funktion zurück', async () => {
const result = await withTenant('abc123', async () => 'testdata')
expect(result).toBe('testdata')
})
})

11
src/server/db/tenant.ts Normal file
View File

@@ -0,0 +1,11 @@
import { db } from './client'
export async function withTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {
const schema = `tenant_${tenantId}`
await db.execute(`SET search_path = ${schema}, public`)
try {
return await fn()
} finally {
await db.execute(`SET search_path = public`)
}
}