Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drizzle multi project schema #92

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 23 additions & 11 deletions src/commands/add/auth/next-auth/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ export const libAuthUtilsTs = (
dbType: DBType | null,
orm: ORMType,
) => {
const { multiProjectSchema } = readConfigFile();
const { shared } = getFilePaths();
const dbIndex = getDbIndexPath();
const providersToUse = providers.map((provider) => {
Expand All @@ -161,7 +162,7 @@ export const libAuthUtilsTs = (

return `${
dbType !== null
? `import { db } from "${formatFilePath(dbIndex, {
? `import { db${multiProjectSchema ? ", mysqlTable" : ""} } from "${formatFilePath(dbIndex, {
prefix: "alias",
removeExtension: true,
})}";
Expand Down Expand Up @@ -204,7 +205,7 @@ export type AuthSession = {
export const authOptions: NextAuthOptions = {
${
dbType !== null
? `adapter: ${AuthDriver[orm].adapter}(db),`
? `adapter: ${AuthDriver[orm].adapter}(db${multiProjectSchema ? ", mysqlTable" : ""}),`
: "// adapter: yourDBAdapterHere"
}
callbacks: {
Expand Down Expand Up @@ -234,7 +235,8 @@ export const checkAuth = async () => {

// 4. create lib/db/schema/auth.ts
export const createDrizzleAuthSchema = (dbType: DBType) => {
const { provider } = readConfigFile();
const { provider, multiProjectSchema } = readConfigFile();
const { drizzle } = getFilePaths();
switch (dbType) {
case "pg":
return `import {
Expand Down Expand Up @@ -272,7 +274,9 @@ export const accounts = pgTable(
session_state: text("session_state"),
},
(account) => ({
compoundKey: primaryKey(account.provider, account.providerAccountId),
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
})
);

Expand All @@ -292,19 +296,23 @@ export const verificationTokens = pgTable(
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(vt) => ({
compoundKey: primaryKey(vt.identifier, vt.token),
compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
})
);
`;
case "mysql":
return `import {
int,
timestamp,
mysqlTable,
timestamp,${multiProjectSchema === true ? "" : "\n mysqlTable,"}
primaryKey,
varchar,${provider === "planetscale" ? "\n text" : "\n references"},
} from "drizzle-orm/mysql-core";
import type { AdapterAccount } from "@auth/core/adapters";
${multiProjectSchema === true ? 'import { mysqlTable } from "' +
formatFilePath(drizzle.dbIndex, {
prefix: "alias",
removeExtension: true,
}) + '";' : ""}

export const users = mysqlTable("user", {
id: varchar("id", { length: 255 }).notNull().primaryKey(),
Expand Down Expand Up @@ -344,7 +352,9 @@ export const accounts = mysqlTable(
session_state: varchar("session_state", { length: 255 }),
},
(account) => ({
compoundKey: primaryKey(account.provider, account.providerAccountId),
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
})
);

Expand All @@ -367,7 +377,7 @@ export const verificationTokens = mysqlTable(
expires: timestamp("expires", { mode: "date" }).notNull(),
},
(vt) => ({
compoundKey: primaryKey(vt.identifier, vt.token),
compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
})
);`;
case "sqlite":
Expand Down Expand Up @@ -405,7 +415,9 @@ export const accounts = sqliteTable(
session_state: text("session_state"),
},
(account) => ({
compoundKey: primaryKey(account.provider, account.providerAccountId),
compoundKey: primaryKey({
columns: [account.provider, account.providerAccountId],
}),
})
);

Expand All @@ -425,7 +437,7 @@ export const verificationTokens = sqliteTable(
expires: integer("expires", { mode: "timestamp_ms" }).notNull(),
},
(vt) => ({
compoundKey: primaryKey(vt.identifier, vt.token),
compoundKey: primaryKey({ columns: [vt.identifier, vt.token] }),
})
);`;
default:
Expand Down
16 changes: 11 additions & 5 deletions src/commands/add/misc/stripe/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,8 @@ export const generateSubscriptionsDrizzleSchema = (
driver: DBType,
auth: AuthType,
) => {
const { multiProjectSchema } = readConfigFile();
const { drizzle } = getFilePaths();
const authSubtype = AuthSubTypeMapping[auth];
// add references for pg and sqlite
switch (driver) {
Expand Down Expand Up @@ -975,18 +977,22 @@ export const subscriptions = pgTable(
},
(table) => {
return {
pk: primaryKey(table.userId, table.stripeCustomerId),
pk: primaryKey({ columns: [table.userId, table.stripeCustomerId] }),
};
}
);
`;
case "mysql":
return `import {
mysqlTable,
return `import {${multiProjectSchema === true ? "" : "\n mysqlTable,"}
primaryKey,
timestamp,
varchar,
} from "drizzle-orm/mysql-core";
${multiProjectSchema === true ? 'import { mysqlTable } from "' +
formatFilePath(drizzle.dbIndex, {
prefix: "alias",
removeExtension: true,
}) + '";' : ""}

export const subscriptions = mysqlTable(
"subscriptions",
Expand All @@ -1001,7 +1007,7 @@ export const subscriptions = mysqlTable(
},
(table) => {
return {
pk: primaryKey(table.userId, table.stripeCustomerId),
pk: primaryKey({ columns: [table.userId, table.stripeCustomerId] }),
};
}
);
Expand Down Expand Up @@ -1034,7 +1040,7 @@ export const subscriptions = sqliteTable(
},
(table) => {
return {
pk: primaryKey(table.userId, table.stripeCustomerId),
pk: primaryKey({ columns: [table.userId, table.stripeCustomerId] }),
};
}
);
Expand Down
33 changes: 29 additions & 4 deletions src/commands/add/orm/drizzle/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const configDriverMappings = {
};

export const createDrizzleConfig = (libPath: string, provider: DBProvider) => {
const { multiProjectSchema } = readConfigFile();
const {
shared: {
init: { envMjs },
Expand All @@ -60,12 +61,13 @@ export default {
? "url: env.DATABASE_URL"
: "connectionString: env.DATABASE_URL"
}${provider === "vercel-pg" ? '.concat("?sslmode=require")' : ""},
}
},${multiProjectSchema === true ? "\n tablesFilter: ['kirimase_*']," : ""}
} satisfies Config;`
);
};

export const createIndexTs = (dbProvider: DBProvider) => {
const { multiProjectSchema } = readConfigFile();
const {
shared: {
init: { envMjs },
Expand Down Expand Up @@ -163,11 +165,21 @@ import { env } from "${formatFilePath(envMjs, {
removeExtension: false,
prefix: "alias",
})}";

${
multiProjectSchema === true
? "import { mysqlTableCreator } from 'drizzle-orm/mysql-core';"
: ""
}

// create the connection
export const connection = connect({
url: env.DATABASE_URL
});
${
multiProjectSchema === true
? "export const mysqlTable = mysqlTableCreator((name) => `kirimase_${name}`);"
: ""
}

export const db = drizzle(connection);
`;
Expand Down Expand Up @@ -394,11 +406,12 @@ runMigrate().catch((err) => {
};

export const createInitSchema = (libPath?: string, dbType?: DBType) => {
const { packages, driver, rootPath } = readConfigFile();
const { packages, driver, rootPath, multiProjectSchema } = readConfigFile();
const {
shared: {
auth: { authSchema },
},
drizzle,
} = getFilePaths();
const path = `${rootPath}lib/db/schema/computers.ts`;
const dbDriver = dbType ?? driver;
Expand Down Expand Up @@ -426,14 +439,26 @@ export const computers = pgTable("computers", {
break;

case "mysql":
initModel = `import { mysqlTable, serial, varchar, int } from "drizzle-orm/mysql-core";${
initModel = `import { ${
multiProjectSchema === true ? "" : "\n mysqlTable,"
} serial, varchar, int } from "drizzle-orm/mysql-core";${
packages.includes("next-auth")
? `\nimport { users } from "${formatFilePath(authSchema, {
removeExtension: true,
prefix: "alias",
})}";`
: ""
}
${
multiProjectSchema === true
? 'import { mysqlTable } from "' +
formatFilePath(drizzle.dbIndex, {
prefix: "alias",
removeExtension: true,
}) +
'";'
: ""
}

export const computers = mysqlTable("computers", {
id: serial("id").primaryKey(),
Expand Down
17 changes: 15 additions & 2 deletions src/commands/add/orm/drizzle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ export const addDrizzle = async (initOptions?: InitOptions) => {
],
})) as DBType);

const multiProjectSchema = (await select({
message: "Are you using a multi-project schema?",
choices: [
{ name: "No", value: false },
{ name: "Yes", value: true },
],
})) as boolean;

// const dbProviders = DBProviders[dbType].filter((p) => {
// if (preferredPackageManager === "bun") return p.value !== "better-sqlite3";
// else return p.value !== "bun-sqlite";
Expand Down Expand Up @@ -97,6 +105,13 @@ export const addDrizzle = async (initOptions?: InitOptions) => {
createFolder(`${hasSrc ? "src/" : ""}lib/api`);
}

updateConfigFile({
driver: dbType,
provider: dbProvider,
orm: "drizzle",
multiProjectSchema,
});

// dependent on dbtype and driver, create
createIndexTs(dbProvider);
createMigrateTs(libPath, dbType, dbProvider);
Expand Down Expand Up @@ -124,8 +139,6 @@ export const addDrizzle = async (initOptions?: InitOptions) => {
rootPath
);
await updateTsConfigTarget();

updateConfigFile({ driver: dbType, provider: dbProvider, orm: "drizzle" });
await installDependencies(dbProvider, preferredPackageManager);
addPackageToConfig("drizzle");
};
1 change: 1 addition & 0 deletions src/commands/init/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export async function initProject(options?: InitOptions) {
packages: [],
preferredPackageManager,
orm: undefined,
multiProjectSchema: undefined,
auth: undefined,
componentLib: undefined,
t3: false,
Expand Down
1 change: 1 addition & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export type Config = {
provider: DBProvider | null;
packages: AvailablePackage[];
orm: ORMType | null;
multiProjectSchema: boolean | null;
auth: AuthType | null;
componentLib: ComponentLibType | null;
t3: boolean;
Expand Down