Documentation / @zerotal/orm / index / createReadWriteRouter
Function: createReadWriteRouter()
createReadWriteRouter(
primary,replicas):SQLInstance
Defined in: packages/orm/src/db/ReadWriteRouter.ts:28
Transparent read/write routing for Bun SQL connections.
createReadWriteRouter() returns a SQLInstance-compatible proxy that:
- Routes SELECT / WITH / EXPLAIN / PRAGMA / SHOW / DESCRIBE → round-robin replica pool.
- Routes everything else (INSERT, UPDATE, DELETE, DDL, transactions) → primary.
- Delegates
begin()(transactions) exclusively to the primary. - Closes all unique connections on
end().
The returned value is structurally identical to SQLInstance, so it is a
drop-in replacement everywhere a connection is expected — DB.table(),
BaseModel, and DB.raw() all route automatically with no code changes.
Parameters
primary
The writable primary/master connection.
replicas
One or more read-replica connections. Load-balanced round-robin. When empty, the primary is returned as-is (no overhead).
Returns
Example
const primary = new SQL(env('DATABASE_URL'));
const replica = new SQL(env('REPLICA_URL'));
const router = createReadWriteRouter(primary, [replica]);
// Drop-in: pass router wherever you'd pass a SQL connection
DB.table('users') // SELECT → replica, mutating → primary