@splendidlabz/db
v2.4.0
Published
Usage with Drizzle ORM
Readme
Usage with Drizzle ORM
import { db } from '@/db/client.js'
import { User } from '@/db/schema.js'
import { getDBEntry } from '@splendidlabz/db'
const entries = await getDBEntry(db, User, { email: '[email protected]' })Usage with the convenience DB Function
import { db as database } from '@splendidlabz/db'
import { db as drizzleDB } from '@/db/client.js'
export const db = database(drizzleDB)
// Usage
db.getEntries(User, { email: '[email protected]' })
db.getEntry(User, { email: '[email protected]' })Joining tables
Pass join for one table and joins for several. getEntry takes the same options as getEntries.
db.getEntry(Post, { id }, { join: { table: User, on: { user_id: User.id } } })
db.getEntries(
Post,
{},
{
joins: [
{ table: User, on: { user_id: User.id } },
{ table: Team, type: 'left', on: { team_id: Team.id } },
],
},
)Running operations in one transaction
batchOps hands your callback a batch db carrying the same methods. They build their query instead of running it, so one transaction covers all of them. All succeed or all fail.
const [workspace, user, sessions] = await db.batchOps(db => [
db.createEntry(Workspace, {
id: workspaceId,
owner_id: userId,
plan: 'free',
}),
db.updateEntry(User, { id: userId }, { onboarded: true }),
db.deleteEntries(Sessions, { user_id: userId }),
])Results come back in the order you returned them, with the single-entry methods unwrapped to the row and the plural ones left as arrays.
Every operation has to be built from the callback's argument. It shadows the outer db so the calls read the same either way — and a call on the outer one has already run by the time the batch sees it, so it is refused.
getOrCreateEntry cannot join a batch: it reads the table before it knows whether to write. Run it first and pass the entry in.
