Refactor drizzle and db folder

This commit is contained in:
Jared Palmer 2024-11-15 10:13:21 -05:00
parent e96dfb2d74
commit c493ac342b
31 changed files with 22 additions and 23 deletions

32
lib/db/migrate.ts Normal file
View file

@ -0,0 +1,32 @@
import { config } from 'dotenv';
import { drizzle } from 'drizzle-orm/postgres-js';
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import postgres from 'postgres';
config({
path: '.env.local',
});
const runMigrate = async () => {
if (!process.env.POSTGRES_URL) {
throw new Error('POSTGRES_URL is not defined');
}
const connection = postgres(process.env.POSTGRES_URL, { max: 1 });
const db = drizzle(connection);
console.log('⏳ Running migrations...');
const start = Date.now();
await migrate(db, { migrationsFolder: './lib/drizzle' });
const end = Date.now();
console.log('✅ Migrations completed in', end - start, 'ms');
process.exit(0);
};
runMigrate().catch((err) => {
console.error('❌ Migration failed');
console.error(err);
process.exit(1);
});

280
lib/db/queries.ts Normal file
View file

@ -0,0 +1,280 @@
'server-only';
import { genSaltSync, hashSync } from 'bcrypt-ts';
import { and, asc, desc, eq, gt } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import {
user,
chat,
User,
document,
Suggestion,
suggestion,
Message,
message,
vote,
} from './schema';
// Optionally, if not using email/pass login, you can
// use the Drizzle adapter for Auth.js / NextAuth
// https://authjs.dev/reference/adapter/drizzle
let client = postgres(`${process.env.POSTGRES_URL!}?sslmode=require`);
let db = drizzle(client);
export async function getUser(email: string): Promise<Array<User>> {
try {
return await db.select().from(user).where(eq(user.email, email));
} catch (error) {
console.error('Failed to get user from database');
throw error;
}
}
export async function createUser(email: string, password: string) {
let salt = genSaltSync(10);
let hash = hashSync(password, salt);
try {
return await db.insert(user).values({ email, password: hash });
} catch (error) {
console.error('Failed to create user in database');
throw error;
}
}
export async function saveChat({
id,
userId,
title,
}: {
id: string;
userId: string;
title: string;
}) {
try {
return await db.insert(chat).values({
id,
createdAt: new Date(),
userId,
title,
});
} catch (error) {
console.error('Failed to save chat in database');
throw error;
}
}
export async function deleteChatById({ id }: { id: string }) {
try {
await db.delete(vote).where(eq(vote.chatId, id));
await db.delete(message).where(eq(message.chatId, id));
return await db.delete(chat).where(eq(chat.id, id));
} catch (error) {
console.error('Failed to delete chat by id from database');
throw error;
}
}
export async function getChatsByUserId({ id }: { id: string }) {
try {
return await db
.select()
.from(chat)
.where(eq(chat.userId, id))
.orderBy(desc(chat.createdAt));
} catch (error) {
console.error('Failed to get chats by user from database');
throw error;
}
}
export async function getChatById({ id }: { id: string }) {
try {
const [selectedChat] = await db.select().from(chat).where(eq(chat.id, id));
return selectedChat;
} catch (error) {
console.error('Failed to get chat by id from database');
throw error;
}
}
export async function saveMessages({ messages }: { messages: Array<Message> }) {
try {
return await db.insert(message).values(messages);
} catch (error) {
console.error('Failed to save messages in database', error);
throw error;
}
}
export async function getMessagesByChatId({ id }: { id: string }) {
try {
return await db
.select()
.from(message)
.where(eq(message.chatId, id))
.orderBy(asc(message.createdAt));
} catch (error) {
console.error('Failed to get messages by chat id from database', error);
throw error;
}
}
export async function voteMessage({
chatId,
messageId,
type,
}: {
chatId: string;
messageId: string;
type: 'up' | 'down';
}) {
try {
const [existingVote] = await db
.select()
.from(vote)
.where(and(eq(vote.messageId, messageId)));
if (existingVote) {
return await db
.update(vote)
.set({ isUpvoted: type === 'up' ? true : false })
.where(and(eq(vote.messageId, messageId), eq(vote.chatId, chatId)));
} else {
return await db.insert(vote).values({
chatId,
messageId,
isUpvoted: type === 'up' ? true : false,
});
}
} catch (error) {
console.error('Failed to upvote message in database', error);
throw error;
}
}
export async function getVotesByChatId({ id }: { id: string }) {
try {
return await db.select().from(vote).where(eq(vote.chatId, id));
} catch (error) {
console.error('Failed to get votes by chat id from database', error);
throw error;
}
}
export async function saveDocument({
id,
title,
content,
userId,
}: {
id: string;
title: string;
content: string;
userId: string;
}) {
try {
return await db.insert(document).values({
id,
title,
content,
userId,
createdAt: new Date(),
});
} catch (error) {
console.error('Failed to save document in database');
throw error;
}
}
export async function getDocumentsById({ id }: { id: string }) {
try {
const documents = await db
.select()
.from(document)
.where(eq(document.id, id))
.orderBy(asc(document.createdAt));
return documents;
} catch (error) {
console.error('Failed to get document by id from database');
throw error;
}
}
export async function getDocumentById({ id }: { id: string }) {
try {
const [selectedDocument] = await db
.select()
.from(document)
.where(eq(document.id, id))
.orderBy(desc(document.createdAt));
return selectedDocument;
} catch (error) {
console.error('Failed to get document by id from database');
throw error;
}
}
export async function deleteDocumentsByIdAfterTimestamp({
id,
timestamp,
}: {
id: string;
timestamp: Date;
}) {
try {
await db
.delete(suggestion)
.where(
and(
eq(suggestion.documentId, id),
gt(suggestion.documentCreatedAt, timestamp)
)
);
return await db
.delete(document)
.where(and(eq(document.id, id), gt(document.createdAt, timestamp)));
} catch (error) {
console.error(
'Failed to delete documents by id after timestamp from database'
);
throw error;
}
}
export async function saveSuggestions({
suggestions,
}: {
suggestions: Array<Suggestion>;
}) {
try {
return await db.insert(suggestion).values(suggestions);
} catch (error) {
console.error('Failed to save suggestions in database');
throw error;
}
}
export async function getSuggestionsByDocumentId({
documentId,
}: {
documentId: string;
}) {
try {
return await db
.select()
.from(suggestion)
.where(and(eq(suggestion.documentId, documentId)));
} catch (error) {
console.error(
'Failed to get suggestions by document version from database'
);
throw error;
}
}

109
lib/db/schema.ts Normal file
View file

@ -0,0 +1,109 @@
import { InferSelectModel } from 'drizzle-orm';
import {
pgTable,
varchar,
timestamp,
json,
uuid,
text,
primaryKey,
foreignKey,
boolean,
} from 'drizzle-orm/pg-core';
export const user = pgTable('User', {
id: uuid('id').primaryKey().notNull().defaultRandom(),
email: varchar('email', { length: 64 }).notNull(),
password: varchar('password', { length: 64 }),
});
export type User = InferSelectModel<typeof user>;
export const chat = pgTable('Chat', {
id: uuid('id').primaryKey().notNull().defaultRandom(),
createdAt: timestamp('createdAt').notNull(),
title: text('title').notNull(),
userId: uuid('userId')
.notNull()
.references(() => user.id),
});
export type Chat = InferSelectModel<typeof chat>;
export const message = pgTable('Message', {
id: uuid('id').primaryKey().notNull().defaultRandom(),
chatId: uuid('chatId')
.notNull()
.references(() => chat.id),
role: varchar('role').notNull(),
content: json('content').notNull(),
createdAt: timestamp('createdAt').notNull(),
});
export type Message = InferSelectModel<typeof message>;
export const vote = pgTable(
'Vote',
{
chatId: uuid('chatId')
.notNull()
.references(() => chat.id),
messageId: uuid('messageId')
.notNull()
.references(() => message.id),
isUpvoted: boolean('isUpvoted').notNull(),
},
(table) => {
return {
pk: primaryKey({ columns: [table.chatId, table.messageId] }),
};
}
);
export type Vote = InferSelectModel<typeof vote>;
export const document = pgTable(
'Document',
{
id: uuid('id').notNull().defaultRandom(),
createdAt: timestamp('createdAt').notNull(),
title: text('title').notNull(),
content: text('content'),
userId: uuid('userId')
.notNull()
.references(() => user.id),
},
(table) => {
return {
pk: primaryKey({ columns: [table.id, table.createdAt] }),
};
}
);
export type Document = InferSelectModel<typeof document>;
export const suggestion = pgTable(
'Suggestion',
{
id: uuid('id').notNull().defaultRandom(),
documentId: uuid('documentId').notNull(),
documentCreatedAt: timestamp('documentCreatedAt').notNull(),
originalText: text('originalText').notNull(),
suggestedText: text('suggestedText').notNull(),
description: text('description'),
isResolved: boolean('isResolved').notNull().default(false),
userId: uuid('userId')
.notNull()
.references(() => user.id),
createdAt: timestamp('createdAt').notNull(),
},
(table) => ({
pk: primaryKey({ columns: [table.id] }),
documentRef: foreignKey({
columns: [table.documentId, table.documentCreatedAt],
foreignColumns: [document.id, document.createdAt],
}),
})
);
export type Suggestion = InferSelectModel<typeof suggestion>;

View file

@ -4,7 +4,7 @@ import { Decoration, DecorationSet, EditorView } from 'prosemirror-view';
import { createRoot } from 'react-dom/client';
import { Suggestion as PreviewSuggestion } from '@/components/custom/suggestion';
import { Suggestion } from '@/db/schema';
import { Suggestion } from '@/lib/db/schema';
export interface UISuggestion extends Suggestion {
selectionStart: number;

View file

@ -8,7 +8,7 @@ import {
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import { Message as DBMessage, Document } from '@/db/schema';
import { Message as DBMessage, Document } from '@/lib/db/schema';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));