1
9import { describe, expect, it } from "vitest";
10import { createDatabaseClients } from "./index.js";
11
12const PRIMARY = "postgresql://factory:factory@localhost:5432/factory";
13const REPLICA = "postgresql://factory:factory@localhost:5433/factory";
14
15describe("createDatabaseClients routing (TASK-0135)", () => {
16 it("with a replica URL: read() → replica, write() → primary, hasReplica true", () => {
17 const db = createDatabaseClients({ databaseUrl: PRIMARY, databaseReplicaUrl: REPLICA });
18 try {
19 expect(db.hasReplica).toBe(true);
20 expect(db.write()).toBe(db.primary);
21 expect(db.read()).toBe(db.reader);
22 expect(db.reader).not.toBe(db.primary);
23 } finally {
24 void db.disconnect();
25 }
26 });
27
28 it("without a replica URL: the reader IS the primary (single-node dev/CI)", () => {
29 const db = createDatabaseClients({ databaseUrl: PRIMARY });
30 try {
31 expect(db.hasReplica).toBe(false);
32 expect(db.read()).toBe(db.primary);
33 expect(db.write()).toBe(db.primary);
34 expect(db.reader).toBe(db.primary);
35 } finally {
36 void db.disconnect();
37 }
38 });
39
40 it("write() is ALWAYS the primary, regardless of replica config", () => {
41 for (const replica of [REPLICA, undefined, ""]) {
42 const db = createDatabaseClients({ databaseUrl: PRIMARY, databaseReplicaUrl: replica });
43 try {
44 expect(db.write()).toBe(db.primary);
45 } finally {
46 void db.disconnect();
47 }
48 }
49 });
50});
51