- init() loads config, schema and the SQLite client once into globals - all CRUD queries go through lib/db-handler.ts (optional per-call config) - split db-schema-manager.ts into lib/schema/* with FK-aware table ordering - add bun:test tests for schema ordering, FK constraints and schema sync - config/schema files can be .ts/.js/.json/.yaml/.yml; db_schema_file_name is now optional (defaults to schema.* in db_dir) - add export/import commands (database snapshot + schema archives) - package exports map, type re-exports, hardened publish.sh - validate table name in delete Co-Authored-By: Claude Opus 5.5 <[email protected]>
54 lines
1.6 KiB
TypeScript
54 lines
1.6 KiB
TypeScript
import type { Database } from "bun:sqlite";
|
|
import type { BUN_SQLITE_TableSchemaType } from "../../types";
|
|
import { sqlQuoteIdent as q } from "../../utils/sql-safe";
|
|
|
|
type Params = {
|
|
db: Database;
|
|
table: BUN_SQLITE_TableSchemaType;
|
|
};
|
|
|
|
/**
|
|
* Sync indexes for a table
|
|
*/
|
|
export default function syncIndexes({ db, table }: Params) {
|
|
if (!table.indexes || table.indexes.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const existingIndexes = (
|
|
db
|
|
.query(
|
|
`SELECT name FROM sqlite_master WHERE type='index' AND tbl_name=? AND name NOT LIKE 'sqlite_%'`,
|
|
)
|
|
.all(table.tableName) as { name: string }[]
|
|
).map((r) => r.name);
|
|
|
|
// Drop indexes not in schema
|
|
for (const indexName of existingIndexes) {
|
|
const stillExists = table.indexes.some(
|
|
(idx) => idx.indexName === indexName,
|
|
);
|
|
if (!stillExists) {
|
|
console.log(`Dropping index: ${indexName}`);
|
|
db.run(`DROP INDEX IF EXISTS ${q(indexName)}`);
|
|
}
|
|
}
|
|
|
|
// Create new indexes
|
|
for (const index of table.indexes) {
|
|
if (!index.indexName || !index.indexTableFields?.length) {
|
|
continue;
|
|
}
|
|
|
|
if (!existingIndexes.includes(index.indexName)) {
|
|
console.log(`Creating index: ${index.indexName}`);
|
|
const fields = index.indexTableFields
|
|
.map((f) => q(String(f)))
|
|
.join(", ");
|
|
db.run(
|
|
`CREATE INDEX ${q(index.indexName)} ON ${q(table.tableName)} (${fields})`,
|
|
);
|
|
}
|
|
}
|
|
}
|