feat: add drizzle

This commit is contained in:
Max Koon
2025-10-14 19:06:52 -04:00
parent 032f38b711
commit e27a48edb5
20 changed files with 920 additions and 77 deletions

10
shared/src/db/client.ts Normal file
View File

@@ -0,0 +1,10 @@
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "./schema";
export const getDb = ({ connectionString }: { connectionString: string }) => {
const pool = new Pool({ connectionString, max: 5 });
return drizzle(pool, {
schema,
});
};

6
shared/src/db/index.ts Normal file
View File

@@ -0,0 +1,6 @@
import * as drizzleSchema from "./schema";
export * from "./schema";
export * from "./client";
export { drizzleSchema };

View File

@@ -0,0 +1,2 @@
export * from "./public";
export * from "./private";

View File

@@ -0,0 +1,94 @@
import { relations } from "drizzle-orm";
import {
index,
pgTable,
text,
timestamp,
uniqueIndex,
} from "drizzle-orm/pg-core";
import { users } from "./public";
export const accounts = pgTable(
"account",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
idToken: text("id_token"),
password: text("password"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
},
(table) => [
uniqueIndex("account_provider_account_unique").on(
table.providerId,
table.accountId,
),
index("account_user_id_idx").on(table.userId),
],
);
export const accountRelations = relations(accounts, ({ one }) => ({
user: one(users, {
fields: [accounts.userId],
references: [users.id],
}),
}));
export const sessions = pgTable(
"session",
{
id: text("id").primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
token: text("token").notNull(),
expiresAt: timestamp("expires_at").notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
},
(table) => [
uniqueIndex("session_token_unique").on(table.token),
index("session_user_id_idx").on(table.userId),
],
);
export const sessionRelations = relations(sessions, ({ one }) => ({
user: one(users, {
fields: [sessions.userId],
references: [users.id],
}),
}));
export const verifications = pgTable(
"verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
},
(table) => [index("verification_identifier_idx").on(table.identifier)],
);
export const auditLogs = pgTable("audit_log", {
id: text("id").primaryKey(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
action: text("action").notNull(),
});

View File

@@ -0,0 +1,24 @@
import { integer, pgTable, text, boolean, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
export const users = pgTable(
"user",
{
id: text("id").primaryKey(),
name: text("name"),
email: text("email").notNull(),
emailVerified: boolean("email_verified").notNull().default(false),
image: text("image"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
},
(table) => [uniqueIndex("user_email_unique").on(table.email)],
);
export const transaction = pgTable("transaction", {
id: text("id").primaryKey(),
user_id: text("user_id").notNull(),
name: text("name").notNull(),
amount: integer("amount").notNull(),
});

View File

@@ -1,4 +1,4 @@
export * from "./schema";
export * from "./queries";
export * from "./mutators";
export * from "./zero-schema.gen";
export * from "./zql";

View File

@@ -16,6 +16,12 @@ export function createMutators(authData: AuthData | null) {
name,
amount,
})
},
async deleteAll(tx: Tx) {
const t = await tx.query.transaction.limit(10);
for (const i of t) {
await tx.mutate.transaction.delete({ id: i.id });
}
}
}
} as const;

View File

@@ -1,7 +1,7 @@
import { syncedQueryWithContext } from "@rocicorp/zero";
import { z } from "zod";
import { builder } from "@money/shared";
import type { AuthData } from "./auth";
import { type AuthData } from "./auth";
import { isLoggedIn } from "./zql";
export const queries = {
@@ -12,4 +12,10 @@ export const queries = {
.limit(10)
}
),
me: syncedQueryWithContext('me', z.tuple([]), (authData: AuthData | null) => {
isLoggedIn(authData);
return builder.users
.where('id', '=', authData.user.id)
.one();
})
};

View File

@@ -1,31 +1,10 @@
import { type Schema as ZeroSchema, createSchema, table, string, number, createBuilder, definePermissions } from "@rocicorp/zero";
const transaction = table('transaction')
.columns({
id: string(),
user_id: string(),
name: string(),
amount: number(),
})
.primaryKey('id').schema;
import { type Schema as ZeroSchema, definePermissions } from "@rocicorp/zero";
import { schema as genSchema } from "./zero-schema.gen";
export const schema = {
tables: { transaction },
relationships: {},
...genSchema,
enableLegacyMutators: false,
enableLegacyQueries: false,
} satisfies ZeroSchema;
// export const schema = createSchema({
// tables: [transaction],
// enableLegacyMutators: false,
// enableLegacyQueries: false,
// });
export const builder = createBuilder(schema);
export const permissions = definePermissions(schema, () => ({}));
export type Schema = typeof schema;

View File

@@ -0,0 +1,165 @@
/* eslint-disable */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// This file was automatically generated by drizzle-zero.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import type { Row } from "@rocicorp/zero";
import { createBuilder } from "@rocicorp/zero";
import type { DrizzleToZeroSchema, ZeroCustomType } from "drizzle-zero";
import type * as drizzleSchema from "./db/schema/public";
type ZeroSchema = DrizzleToZeroSchema<typeof drizzleSchema>;
/**
* The Zero schema object.
* This type is auto-generated from your Drizzle schema definition.
*/
export const schema = {
tables: {
transaction: {
name: "transaction",
columns: {
id: {
type: "string",
optional: false,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"transaction",
"id"
>,
},
user_id: {
type: "string",
optional: false,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"transaction",
"user_id"
>,
},
name: {
type: "string",
optional: false,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"transaction",
"name"
>,
},
amount: {
type: "number",
optional: false,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"transaction",
"amount"
>,
},
},
primaryKey: ["id"],
},
users: {
name: "users",
columns: {
id: {
type: "string",
optional: false,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"id"
>,
},
name: {
type: "string",
optional: true,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"name"
>,
},
email: {
type: "string",
optional: false,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"email"
>,
},
emailVerified: {
type: "boolean",
optional: true,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"emailVerified"
>,
serverName: "email_verified",
},
image: {
type: "string",
optional: true,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"image"
>,
},
createdAt: {
type: "number",
optional: true,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"createdAt"
>,
serverName: "created_at",
},
updatedAt: {
type: "number",
optional: true,
customType: null as unknown as ZeroCustomType<
ZeroSchema,
"users",
"updatedAt"
>,
serverName: "updated_at",
},
},
primaryKey: ["id"],
serverName: "user",
},
},
relationships: {},
enableLegacyQueries: true,
enableLegacyMutators: true,
} as const;
/**
* Represents the Zero schema type.
* This type is auto-generated from your Drizzle schema definition.
*/
export type Schema = typeof schema;
/**
* Represents a row from the "transaction" table.
* This type is auto-generated from your Drizzle schema definition.
*/
export type Transaction = Row<Schema["tables"]["transaction"]>;
/**
* Represents a row from the "users" table.
* This type is auto-generated from your Drizzle schema definition.
*/
export type User = Row<Schema["tables"]["users"]>;
/**
* Represents the Zero schema query builder.
* This type is auto-generated from your Drizzle schema definition.
*/
export const builder = createBuilder(schema);