Skip to content

Commit

Permalink
Support for mysql in the visualizer (#36)
Browse files Browse the repository at this point in the history
* add mysql support in visualizer
  • Loading branch information
rphlmr authored Nov 25, 2024
1 parent ce1539c commit 38febff
Show file tree
Hide file tree
Showing 13 changed files with 306 additions and 23 deletions.
22 changes: 22 additions & 0 deletions apps/cli/example/mysql/drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* This is the configuration for the server-side database.
*/

import { defineConfig } from "drizzle-kit";

const base = "./example/mysql";

export default defineConfig({
dialect: "mysql",
dbCredentials: {
url: process.env.ADMIN_DATABASE_URL!,
},
schema: `${base}/schema.ts`,
out: `${base}/migrations`,
verbose: false,
schemaFilter: ["public"],
casing: "snake_case",
migrations: {
prefix: "timestamp",
},
});
105 changes: 105 additions & 0 deletions apps/cli/example/mysql/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { randomUUID } from "crypto";

import { relations, sql, getTableColumns } from "drizzle-orm";
import {
mysqlTable,
serial,
text,
int,
timestamp,
json,
foreignKey,
primaryKey,
check,
mysqlView,
} from "drizzle-orm/mysql-core";

export const users = mysqlTable("users", {
id: serial("id").primaryKey(),
name: text("name"),
});

export const usersRelations = relations(users, ({ many }) => ({
author: many(posts, { relationName: "author" }),
reviewer: many(posts, { relationName: "reviewer" }),
}));

function generateSlug() {
return randomUUID();
}

type PostMetadata = {
source: "mobile_app" | "web_app";
value: {
id: string;
tags: string[];
};
};

export const posts = mysqlTable(
"posts",
{
id: serial("id"),
slug: text("slug")
.notNull()
.$default(() => generateSlug()),
status: text("status", { enum: ["draft", "published"] })
.default("draft")
.notNull(),
content: text("content"),
authorId: int("author_id")
.references(() => users.id)
.notNull(),
reviewerId: int("reviewer_id"),
createdAt: timestamp("created_at", {
mode: "string",
}).defaultNow(),
metadata: json("metadata").$type<PostMetadata>(),
metadata2: json("metadata2")
.$type<PostMetadata>()
.default({
source: "mobile_app",
value: {
id: "123",
tags: ["tag1", "tag2"],
},
}),
},
(t) => ({
p: primaryKey({ name: "my pk", columns: [t.id, t.slug] }),
f: foreignKey({
name: "my fk",
columns: [t.authorId],
foreignColumns: [users.id],
}),
c: check("not draft", sql`status <> 'draft'`),
})
);
export const postsView = mysqlView("posts_view").as((qb) =>
qb
.select({
...getTableColumns(posts),
})
.from(posts)
);

export const postsViewUnsecured = mysqlView("posts_view_unsecured").as((qb) =>
qb
.select({
...getTableColumns(posts),
})
.from(posts)
);

export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
relationName: "author",
}),
reviewer: one(users, {
fields: [posts.reviewerId],
references: [users.id],
relationName: "reviewer",
}),
}));
2 changes: 1 addition & 1 deletion apps/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "drizzle-lab",
"version": "0.7.0",
"version": "0.8.0",
"description": "Drizzle Lab CLI",
"sideEffects": false,
"type": "module",
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

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

4 changes: 2 additions & 2 deletions packages/api/src/mysql/loader/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export async function importFromDatabase(
indexes: {},
foreignKeys: {},
uniqueConstraints: {},
checkConstraint: {},
checkConstraints: {},
relations: [],
schema,
};
Expand Down Expand Up @@ -414,7 +414,7 @@ AND

const tableInResult = result[tableName];
// if (typeof tableInResult === 'undefined') continue;
tableInResult.checkConstraint[constraintName] = {
tableInResult.checkConstraints[constraintName] = {
name: constraintName,
value: constraintValue,
};
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/mysql/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ const table = object({
foreignKeys: record(string(), fk),
compositePrimaryKeys: record(string(), compositePK),
uniqueConstraints: record(string(), uniqueConstraint).default({}),
checkConstraint: record(string(), checkConstraint).default({}),
checkConstraints: record(string(), checkConstraint).default({}),
/* lab extension */
schema: string(),
relations: array(relation).default([]),
Expand Down Expand Up @@ -411,7 +411,7 @@ export const squashSnapshot = (json: Snapshot): SnapshotSquashed => {
);

const squashedCheckConstraints = mapValues(
it[1].checkConstraint,
it[1].checkConstraints,
(check) => {
return MySqlSquasher.squashCheck(check);
},
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/mysql/serializer/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ export function drizzleObjectsToSnapshot(
foreignKeys: foreignKeysObject,
compositePrimaryKeys: primaryKeysObject,
uniqueConstraints: uniqueConstraintObject,
checkConstraint: checkConstraintObject,
checkConstraints: checkConstraintObject,
/* lab extension */
description,
relations: tableRelations,
Expand Down
8 changes: 5 additions & 3 deletions packages/api/src/mysql/serializer/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,9 @@ export function snapshotToTypeScript(snapshot: Snapshot, casing: Casing) {
const uniqueImports = Object.values(it.uniqueConstraints).map(
() => "unique",
);
const checkImports = Object.values(it.checkConstraint).map(() => "check");
const checkImports = Object.values(it.checkConstraints).map(
() => "check",
);

res.mysql.push(...idxImports);
res.mysql.push(...fkImpots);
Expand Down Expand Up @@ -267,7 +269,7 @@ export function snapshotToTypeScript(snapshot: Snapshot, casing: Casing) {
filteredFKs.length > 0 ||
Object.keys(table.compositePrimaryKeys).length > 0 ||
Object.keys(table.uniqueConstraints).length > 0 ||
Object.keys(table.checkConstraint).length > 0
Object.keys(table.checkConstraints).length > 0
) {
statement += ",\n";
statement += "(table) => {\n";
Expand All @@ -287,7 +289,7 @@ export function snapshotToTypeScript(snapshot: Snapshot, casing: Casing) {
withCasing,
);
statement += createTableChecks(
Object.values(table.checkConstraint),
Object.values(table.checkConstraints),
withCasing,
);
statement += "\t}\n";
Expand Down
Loading

0 comments on commit 38febff

Please sign in to comment.