Initial commit

This commit is contained in:
Cadence Ember 2025-03-31 17:51:14 +13:00
parent 5a8186a46c
commit 15ff7e5b47
25 changed files with 2703 additions and 0 deletions

45
db/migrate.js Normal file
View file

@ -0,0 +1,45 @@
// @ts-check
const fs = require("fs")
const {join} = require("path")
async function migrate(db) {
let files = fs.readdirSync(join(__dirname, "migrations"))
files = files.sort()
db.prepare("CREATE TABLE IF NOT EXISTS _migration (filename TEXT NOT NULL, PRIMARY KEY (filename)) WITHOUT ROWID").run()
/** @type {string} */
let progress = db.prepare("SELECT * FROM _migration").pluck().get()
if (!progress) {
progress = ""
db.prepare("INSERT INTO _migration VALUES ('')").run()
}
let migrationRan = false
for (const filename of files) {
if (progress >= filename) continue
console.log(`Applying database migration ${filename}`)
if (filename.endsWith(".sql")) {
const sql = fs.readFileSync(join(__dirname, "migrations", filename), "utf8")
db.exec(sql)
} else if (filename.endsWith(".js")) {
await require("./" + join("migrations", filename))(db)
} else {
continue
}
migrationRan = true
db.transaction(() => {
db.prepare("DELETE FROM _migration").run()
db.prepare("INSERT INTO _migration VALUES (?)").run(filename)
})()
}
if (migrationRan) {
console.log("Database migrations all done.")
}
db.pragma("foreign_keys = on")
}
module.exports.migrate = migrate

View file

@ -0,0 +1,49 @@
BEGIN TRANSACTION;
CREATE TABLE item (
item_id INTEGER NOT NULL,
item_type TEXT NOT NULL,
band_id INTEGER NOT NULL,
added INTEGER NOT NULL,
updated INTEGER NOT NULL,
purchased INTEGER NOT NULL,
featured_track INTEGER,
why TEXT,
also_collected_count INTEGER NOT NULL,
item_title TEXT NOT NULL,
item_url TEXT NOT NULL,
item_art_url TEXT NOT NULL,
band_name TEXT NOT NULL,
band_url TEXT NOT NULL,
featured_track_title TEXT,
featured_track_number INTEGER,
featured_track_duration NUMERIC,
album_id INTEGER,
album_title TEXT,
price INTEGER NOT NULL,
currency STRING NOT NULL,
label TEXT,
label_id INTEGER,
PRIMARY KEY (item_id)
) WITHOUT ROWID;
CREATE TABLE track (
item_id INTEGER NOT NULL,
track_id INTEGER NOT NULL,
title TEXT NOT NULL,
artist TEXT NOT NULL,
track_number INTEGER,
duration NUMERIC NOT NULL,
mp3 TEXT,
PRIMARY KEY (item_id, track_id),
FOREIGN KEY (item_id) REFERENCES item (item_id) ON DELETE CASCADE
) WITHOUT ROWID;
CREATE TABLE item_tag (
item_id INTEGER NOT NULL,
tag TEXT NOT NULL,
PRIMARY KEY (item_id, tag),
FOREIGN KEY (item_id) REFERENCES item (item_id) ON DELETE CASCADE
) WITHOUT ROWID;
COMMIT;

57
db/orm-defs.d.ts vendored Normal file
View file

@ -0,0 +1,57 @@
export type Models = {
item: {
item_id: number
item_type: string
band_id: number
added: number
updated: number
purchased: string
featured_track: number | null
why: string | null
also_collected_count: number
item_title: string
item_url: string
item_art_url: string
band_name: string
band_url: string
featured_track_title: string | null
featured_track_number: number | null
featured_track_duration: number | null
album_id: number | null
album_title: string | null
price: number
currency: string
label: string | null
label_id: number | null
}
track: {
item_id: number
track_id: number
title: string
artist: string
track_number: number | null
duration: number
mp3: string | null
}
item_tag: {
item_id: number
tag: string
}
}
export type Prepared<Row> = {
pluck: () => Prepared<Row[keyof Row]>
safeIntegers: () => Prepared<{[K in keyof Row]: Row[K] extends number ? BigInt : Row[K]}>
raw: () => Prepared<Row[keyof Row][]>
all: (..._: any[]) => Row[]
get: (..._: any[]) => Row | null | undefined
}
export type AllKeys<U> = U extends any ? keyof U : never
export type PickTypeOf<T, K extends AllKeys<T>> = T extends { [k in K]?: any } ? T[K] : never
export type Merge<U> = {[x in AllKeys<U>]: PickTypeOf<U, x>}
export type Nullable<T> = {[k in keyof T]: T[k] | null}
export type Numberish<T> = {[k in keyof T]: T[k] extends number ? (number | bigint) : T[k]}
export type ValueOrArray<T> = {[k in keyof T]: T[k][] | T[k]}

1
db/orm-defs.js Normal file
View file

@ -0,0 +1 @@
module.exports = {}

189
db/orm.js Normal file
View file

@ -0,0 +1,189 @@
// @ts-check
const {db} = require("../passthrough")
const U = require("./orm-defs")
/**
* @template {keyof U.Models} Table
* @template {keyof U.Models[Table]} Col
* @param {Table} table
* @param {Col[] | Col} cols
* @param {Partial<U.ValueOrArray<U.Numberish<U.Models[Table]>>>} where
* @param {string} [e]
*/
function select(table, cols, where = {}, e = "") {
if (!Array.isArray(cols)) cols = [cols]
const parameters = []
const wheres = Object.entries(where).map(([col, value]) => {
if (Array.isArray(value)) {
parameters.push(...value)
return `"${col}" IN (` + Array(value.length).fill("?").join(", ") + ")"
} else {
parameters.push(value)
return `"${col}" = ?`
}
})
const whereString = wheres.length ? " WHERE " + wheres.join(" AND ") : ""
/** @type {U.Prepared<Pick<U.Models[Table], Col>>} */
const prepared = db.prepare(`SELECT ${cols.map(k => `"${String(k)}"`).join(", ")} FROM ${table} ${whereString} ${e}`)
prepared.get = prepared.get.bind(prepared, ...parameters)
prepared.all = prepared.all.bind(prepared, ...parameters)
return prepared
}
/**
* @template {keyof U.Models} Table
* @template {keyof U.Merge<U.Models[Table]>} Col
*/
class From {
/**
* @param {Table} table
*/
constructor(table) {
/** @private @type {Table[]} */
this.tables = [table]
/** @private */
this.directions = []
/** @private */
this.sql = ""
/** @private */
this.cols = []
/** @private */
this.makeColsSafe = true
/** @private */
this.using = []
/** @private */
this.isPluck = false
/** @private */
this.parameters = []
}
/**
* @template {keyof U.Models} Table2
* @param {Table2} table
* @param {Col & (keyof U.Models[Table2])} col
* @param {"inner" | "left"} [direction]
*/
join(table, col, direction = "inner") {
/** @type {From<Table | Table2, keyof U.Merge<U.Models[Table | Table2]>>} */
// @ts-ignore
const r = this
r.tables.push(table)
r.directions.push(direction.toUpperCase())
r.using.push(col)
return r
}
/**
* @template {Col} Select
* @param {Col[] | Select[]} cols
*/
select(...cols) {
/** @type {From<Table, Select>} */
const r = this
r.cols = cols
return r
}
selectUnsafe(...cols) {
this.cols = cols
this.makeColsSafe = false
return this
}
/**
* @template {Col} Select
* @param {Select} col
*/
pluck(col) {
/** @type {Pluck<Table, Select>} */
// @ts-ignore
const r = this
r.cols = [col]
r.isPluck = true
return r
}
/**
* @param {string} sql
*/
and(sql) {
this.sql += " " + sql
return this
}
/**
* @param {Partial<U.Numberish<U.Models[Table]>>} conditions
*/
where(conditions) {
const wheres = Object.entries(conditions).map(([col, value]) => {
this.parameters.push(value)
return `"${col}" = ?`
})
this.sql += " WHERE " + wheres.join(" AND ")
return this
}
prepare() {
if (this.makeColsSafe) this.cols = this.cols.map(k => `"${k}"`)
let sql = `SELECT ${this.cols.join(", ")} FROM ${this.tables[0]} `
for (let i = 1; i < this.tables.length; i++) {
const table = this.tables[i]
const col = this.using[i-1]
const direction = this.directions[i-1]
sql += `${direction} JOIN ${table} USING (${col}) `
}
sql += this.sql
/** @type {U.Prepared<Pick<U.Merge<U.Models[Table]>, Col>>} */
let prepared = db.prepare(sql)
if (this.isPluck) prepared = prepared.pluck()
return prepared
}
get(..._) {
const prepared = this.prepare()
return prepared.get(...this.parameters, ..._)
}
all(..._) {
const prepared = this.prepare()
return prepared.all(...this.parameters, ..._)
}
}
/* c8 ignore start - this code is only used for types and does not actually execute */
/**
* @template {keyof U.Models} Table
* @template {keyof U.Merge<U.Models[Table]>} Col
*/
class Pluck extends From {
// @ts-ignore
prepare() {
/** @type {U.Prepared<U.Merge<U.Models[Table]>[Col]>} */
// @ts-ignore
const prepared = super.prepare()
return prepared
}
get(..._) {
const prepared = this.prepare()
return prepared.get(..._)
}
all(..._) {
const prepared = this.prepare()
return prepared.all(..._)
}
}
/* c8 ignore stop */
/**
* @template {keyof U.Models} Table
* @param {Table} table
*/
function from(table) {
return new From(table)
}
module.exports.from = from
module.exports.select = select