Add recordTypes table with relations and auto-created indexes.

This commit is contained in:
themodrnhakr 2025-09-25 15:04:27 -05:00
parent 86fdbb9ac5
commit 6df86a1691
2 changed files with 38 additions and 0 deletions

View File

@ -1,6 +1,12 @@
import { relations } from "drizzle-orm";
import { sqliteTable, integer, text } from "drizzle-orm/sqlite-core"; import { sqliteTable, integer, text } from "drizzle-orm/sqlite-core";
import { records } from "./records";
export const recordTypes = sqliteTable('record_types', { export const recordTypes = sqliteTable('record_types', {
id: integer('id').primaryKey({autoIncrement: true}), id: integer('id').primaryKey({autoIncrement: true}),
type: text('type') type: text('type')
}) })
export const recordTypesRelations = relations(recordTypes, ({many}) => ({
records: many(records)
}))

View File

@ -0,0 +1,32 @@
import { integer, text, sqliteTable, index, type IndexBuilder } from "drizzle-orm/sqlite-core";
import { recordTypes } from "./recordTypes";
import { relations, sql } from "drizzle-orm";
type RecordTypeIndexConfig = Array<{
dbId: number,
name: string
}>
const recordTypeIndexConfig: RecordTypeIndexConfig = [
{dbId: 1, name: "chores"},
{dbId: 2, name: "project"},
{dbId: 3, name: "ticket"},
]
type RecordTypeIndexGenerator = (x: RecordTypeIndexConfig, y) => Array<IndexBuilder>
const recordTypeIndexGenerator: RecordTypeIndexGenerator = (x, y) => x.map(
entry => index(`${entry.name}_index`).on(y.recordId).where(sql`type_id = ${entry.dbId}`)
)
export const records = sqliteTable("records", {
id: integer("id").primaryKey({ autoIncrement: true }),
recordId: text("record_id").unique().notNull(),
typeId: integer("type_id").notNull().references(() => recordTypes.id)
}, (table) => [
...recordTypeIndexGenerator(recordTypeIndexConfig, table)
])
export const recordsRelations = relations(records, ({ one }) => ({
type: one(recordTypes, {
fields: [records.typeId],
references: [recordTypes.id]
})
}))