Skip to content

Commit

Permalink
feat(packages/drizzledb-pg): drizzle relational queries (#40)
Browse files Browse the repository at this point in the history
* setup drizzle client to accept relations by passing
  in schemas
* definie relations in drizzle schema files
* add new findBy query using relational queries
  • Loading branch information
mpellegrini authored Apr 10, 2024
1 parent 8c3a578 commit f1c58a7
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 29 deletions.
4 changes: 3 additions & 1 deletion packages/drizzledb-pg/src/client/pg-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { drizzle } from 'drizzle-orm/node-postgres'
import pg from 'pg'
import { parseEnv, z } from 'znv'

import * as schema from '../schema/index.js'

import 'dotenv/config'

const { DB_CONNECTION_STRING, DB_MAX_CONNECTIONS } = parseEnv(process.env, {
Expand Down Expand Up @@ -34,4 +36,4 @@ connection.on('connect', () => console.log(`Connected`))
connection.on('acquire', () => console.log('acquired a connection from the pool'))
connection.on('release', () => console.log('released the connection to the pool'))

export const db = drizzle(connection)
export const db = drizzle(connection, { schema })
34 changes: 34 additions & 0 deletions packages/drizzledb-pg/src/schema/auth-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { relations } from 'drizzle-orm'
import { pgSchema, text, timestamp, uuid } from 'drizzle-orm/pg-core'

import { citext } from './custom-types.js'

export const authSchema = pgSchema('auth')

export const users = authSchema.table('users', {
id: uuid('id').primaryKey().defaultRandom(),
username: citext('username').notNull().unique(),
hashedPassword: text('hashed_password').notNull(),
})

export const sessions = authSchema.table('sessions', {
id: text('id').primaryKey(),
userId: uuid('user_id')
.notNull()
.references(() => users.id),
expiresAt: timestamp('expires_at', {
withTimezone: true,
mode: 'date',
}).notNull(),
})

export const usersRelations = relations(users, ({ many }) => ({
sessions: many(sessions),
}))

export const sessionsRelations = relations(sessions, ({ one }) => ({
user: one(users, {
fields: [sessions.userId],
references: [users.id],
}),
}))
25 changes: 1 addition & 24 deletions packages/drizzledb-pg/src/schema/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1 @@
import { pgSchema, text, timestamp, uuid } from 'drizzle-orm/pg-core'

import { citext } from './custom-types.js'

export { count } from 'drizzle-orm'

export const authSchema = pgSchema('auth')

export const users = authSchema.table('users', {
id: uuid('id').primaryKey().defaultRandom(),
username: citext('username').notNull().unique(),
hashedPassword: text('hashed_password').notNull(),
})

export const sessions = authSchema.table('sessions', {
id: text('id').primaryKey(),
userId: uuid('user_id')
.notNull()
.references(() => users.id),
expiresAt: timestamp('expires_at', {
withTimezone: true,
mode: 'date',
}).notNull(),
})
export * from './auth-schema.js'
21 changes: 17 additions & 4 deletions packages/lucia-auth/src/repository/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
import { Argon2id } from 'oslo/password'

import { db } from '@packages/drizzledb-pg/client'
import * as schema from '@packages/drizzledb-pg/schema'
import { users } from '@packages/drizzledb-pg/schema'

export type NewUser = Omit<typeof schema.users.$inferInsert, 'id' | 'hashedPassword'> & {
export type NewUser = Omit<typeof users.$inferInsert, 'id' | 'hashedPassword'> & {
password: string
}

export type User = typeof schema.users.$inferSelect
export type User = typeof users.$inferSelect

export const findByUsername = async (username: string): Promise<User | undefined> => {
return db.query.users.findFirst({
columns: { id: true, username: true, hashedPassword: true },
where: (col, { eq }) => eq(col.username, username),
})
}

export const createUser = async (user: NewUser): Promise<string | undefined> => {
const hashedPassword = await new Argon2id().hash(user.password)

await db.query.users.findMany({
with: {
sessions: true,
},
})

return db
.insert(schema.users)
.insert(users)
.values({ username: user.username, hashedPassword })
.returning({ id: users.id })
.then((res) => res[0]?.id)
Expand Down

0 comments on commit f1c58a7

Please sign in to comment.