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

Features/branded types #29

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
support primary keys
kauza-spanning committed Aug 15, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 6623c8237bb044af56aeea456bef509a42a8aef0
4 changes: 2 additions & 2 deletions main.test.ts
Original file line number Diff line number Diff line change
@@ -81,7 +81,7 @@ beforeAll(async function setup() {
});

await db.schema.withSchema("log").createTable("messages", (table) => {
table.increments("int").notNullable().primary();
table.increments("id").notNullable().primary();
table.text("notes");
table.timestamp("timestamp").notNullable();
table.integer("user_id").references("id").inTable("user").notNullable();
@@ -137,7 +137,7 @@ test("updateTypes", async function () {
};
export type LogMessages = {
int: number;
id: number & { __brand: "LogMessages" };
notes: string | null;
timestamp: Date;
user_id: number & { __brand: "User" };
10 changes: 8 additions & 2 deletions main.ts
Original file line number Diff line number Diff line change
@@ -152,7 +152,7 @@ export async function updateTypes(db: Knex, options: Options): Promise<void> {
.withSchema("information_schema")
.table("table_constraints")
.where("table_schema", schema)
.whereIn("constraint_type", ["FOREIGN KEY", "UNIQUE"])
.whereIn("constraint_type", ["FOREIGN KEY", "UNIQUE", "PRIMARY KEY"])
.select<{ constraint_name: string; constraint_type: string }[]>([
"constraint_name",
"constraint_type",
@@ -221,6 +221,12 @@ export async function updateTypes(db: Knex, options: Options): Promise<void> {
key.column === column.column &&
key.constraint_type === "UNIQUE"
),
is_primary_key: keys.some(
(key) =>
key.table === column.table &&
key.column === column.column &&
key.constraint_type === "PRIMARY KEY"
),
ref_schema: keys.find(
(key) =>
key.table === column.table &&
@@ -276,7 +282,7 @@ export async function updateTypes(db: Knex, options: Options): Promise<void> {
}

// branding the id columns (unique and foreign keys)
if (x.column === "id" && x.is_unique) {
if (x.column === "id" && (x.is_unique || x.is_primary_key)) {
const brandName = `${schemaName}${tableName}`;
type += ` & { __brand: "${brandName}" }`;
} else if (x.is_foreign_key && x.column.endsWith("id")) {