refactor: migrate to sqlite as database

This commit is contained in:
Meier Lukas
2023-12-09 00:32:45 +01:00
parent f6094c6ae2
commit 41e54d940b
13 changed files with 244 additions and 179 deletions

View File

@@ -3,21 +3,8 @@ import type { Config } from "drizzle-kit";
dotenv.config({ path: "../../.env" });
const uri = [
"mysql://",
process.env.DB_USERNAME,
":",
process.env.DB_PASSWORD,
"@",
process.env.DB_HOST,
":3306/",
process.env.DB_NAME,
'?ssl={"rejectUnauthorized":true}',
].join("");
export default {
schema: "./schema",
driver: "mysql2",
dbCredentials: { uri },
tablesFilter: ["t3turbo_*"],
driver: "better-sqlite",
dbCredentials: { url: process.env.DB_URL! },
} satisfies Config;

View File

@@ -1,20 +1,13 @@
import { Client } from "@planetscale/database";
import { drizzle } from "drizzle-orm/planetscale-serverless";
import Database from 'better-sqlite3';
import { drizzle } from "drizzle-orm/better-sqlite3";
import * as auth from "./schema/auth";
import * as post from "./schema/post";
import * as sqliteSchema from "./schema/sqlite";
export const schema = { ...auth, ...post };
export { mySqlTable as tableCreator } from "./schema/_table";
export const schema = sqliteSchema;
export * from "drizzle-orm";
export const db = drizzle(
new Client({
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
}).connection(),
{ schema },
);
const sqlite = new Database(process.env.DB_URL!);
export const db = drizzle(sqlite, { schema });

View File

@@ -9,12 +9,13 @@
"clean": "rm -rf .turbo node_modules",
"lint": "eslint .",
"format": "prettier --check . --ignore-path ../../.gitignore",
"push": "drizzle-kit push:mysql",
"push": "drizzle-kit push:sqlite",
"studio": "drizzle-kit studio",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@planetscale/database": "^1.11.0",
"@types/better-sqlite3": "^7.6.8",
"better-sqlite3": "^9.2.2",
"drizzle-orm": "^0.29.1"
},
"devDependencies": {

View File

@@ -1,9 +0,0 @@
import { mysqlTableCreator } from "drizzle-orm/mysql-core";
/**
* This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same
* database instance for multiple projects.
*
* @see https://orm.drizzle.team/docs/goodies#multi-project-schema
*/
export const mySqlTable = mysqlTableCreator((name) => `t3turbo_${name}`);

View File

@@ -1,84 +0,0 @@
import type { AdapterAccount } from "@auth/core/adapters";
import { relations, sql } from "drizzle-orm";
import {
index,
int,
primaryKey,
text,
timestamp,
varchar,
} from "drizzle-orm/mysql-core";
import { mySqlTable } from "./_table";
export const users = mySqlTable("user", {
id: varchar("id", { length: 255 }).notNull().primaryKey(),
name: varchar("name", { length: 255 }),
email: varchar("email", { length: 255 }).notNull(),
emailVerified: timestamp("emailVerified", {
mode: "date",
fsp: 3,
}).default(sql`CURRENT_TIMESTAMP(3)`),
image: varchar("image", { length: 255 }),
});
export const usersRelations = relations(users, ({ many }) => ({
accounts: many(accounts),
}));
export const accounts = mySqlTable(
"account",
{
userId: varchar("userId", { length: 255 }).notNull(),
type: varchar("type", { length: 255 })
.$type<AdapterAccount["type"]>()
.notNull(),
provider: varchar("provider", { length: 255 }).notNull(),
providerAccountId: varchar("providerAccountId", { length: 255 }).notNull(),
refresh_token: varchar("refresh_token", { length: 255 }),
access_token: varchar("access_token", { length: 255 }),
expires_at: int("expires_at"),
token_type: varchar("token_type", { length: 255 }),
scope: varchar("scope", { length: 255 }),
id_token: text("id_token"),
session_state: varchar("session_state", { length: 255 }),
},
(account) => ({
compoundKey: primaryKey(account.provider, account.providerAccountId),
userIdIdx: index("userId_idx").on(account.userId),
}),
);
export const accountsRelations = relations(accounts, ({ one }) => ({
user: one(users, { fields: [accounts.userId], references: [users.id] }),
}));
export const sessions = mySqlTable(
"session",
{
sessionToken: varchar("sessionToken", { length: 255 })
.notNull()
.primaryKey(),
userId: varchar("userId", { length: 255 }).notNull(),
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(session) => ({
userIdIdx: index("userId_idx").on(session.userId),
}),
);
export const sessionsRelations = relations(sessions, ({ one }) => ({
user: one(users, { fields: [sessions.userId], references: [users.id] }),
}));
export const verificationTokens = mySqlTable(
"verificationToken",
{
identifier: varchar("identifier", { length: 255 }).notNull(),
token: varchar("token", { length: 255 }).notNull(),
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(vt) => ({
compoundKey: primaryKey(vt.identifier, vt.token),
}),
);

View File

@@ -1,14 +0,0 @@
import { sql } from "drizzle-orm";
import { serial, timestamp, varchar } from "drizzle-orm/mysql-core";
import { mySqlTable } from "./_table";
export const post = mySqlTable("post", {
id: serial("id").primaryKey(),
title: varchar("name", { length: 256 }).notNull(),
content: varchar("content", { length: 256 }).notNull(),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updatedAt").onUpdateNow(),
});

View File

@@ -0,0 +1,79 @@
import type { AdapterAccount } from '@auth/core/adapters';
import type { InferSelectModel } from 'drizzle-orm';
import { relations } from 'drizzle-orm';
import { index, integer, primaryKey, sqliteTable, text } from 'drizzle-orm/sqlite-core';
export const users = sqliteTable('user', {
id: text('id').notNull().primaryKey(),
name: text('name'),
email: text('email'),
emailVerified: integer('emailVerified', { mode: 'timestamp_ms' }),
image: text('image'),
password: text('password'),
salt: text('salt'),
});
export const accounts = sqliteTable(
'account',
{
userId: text('userId')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
type: text('type').$type<AdapterAccount['type']>().notNull(),
provider: text('provider').notNull(),
providerAccountId: text('providerAccountId').notNull(),
refresh_token: text('refresh_token'),
access_token: text('access_token'),
expires_at: integer('expires_at'),
token_type: text('token_type'),
scope: text('scope'),
id_token: text('id_token'),
session_state: text('session_state'),
},
(account) => ({
compoundKey: primaryKey({ columns: [account.provider, account.providerAccountId] }),
userIdIdx: index('userId_idx').on(account.userId),
})
);
export const sessions = sqliteTable(
'session',
{
sessionToken: text('sessionToken').notNull().primaryKey(),
userId: text('userId')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expires: integer('expires', { mode: 'timestamp_ms' }).notNull(),
},
(session) => ({
userIdIdx: index('user_id_idx').on(session.userId),
})
);
export const verificationTokens = sqliteTable(
'verificationToken',
{
identifier: text('identifier').notNull(),
token: text('token').notNull(),
expires: integer('expires', { mode: 'timestamp_ms' }).notNull(),
},
(vt) => ({
compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
})
);
export const accountRelations = relations(accounts, ({ one }) => ({
user: one(users, {
fields: [accounts.userId],
references: [users.id],
}),
}));
export const userRelations = relations(users, ({ many }) => ({
accounts: many(accounts),
}));
export type User = InferSelectModel<typeof users>;
export type Account = InferSelectModel<typeof accounts>;
export type Session = InferSelectModel<typeof sessions>;
export type VerificationToken = InferSelectModel<typeof verificationTokens>;