All files / core/blong-gogo/src/adapter/schema/knex schemaTable.ts

89.24% Statements 166/186
63.63% Branches 28/44
66.66% Functions 2/3
89.24% Lines 166/186

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 1871x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 162x 162x 162x 162x 162x 162x 162x 162x 162x 161x 161x 161x 161x 161x 161x 1x 1x 1x 1x 1x 1x 1x 1x 3x         3x 3x 3x 3x 3x 3x 3x 1x 3x 3x 3x 3x 1x   3x 3x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 93x 61x 61x 93x 32x 32x 32x 32x 93x 151x 151x 151x 50x 50x 50x 50x 50x 50x 50x 151x 151x 151x 24x 32x 32x 32x 32x 32x 24x 151x 151x 151x 134x 185x 185x 185x 185x 185x 185x 185x 185x 185x 185x 185x 185x 185x 134x 151x 151x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                  
import {type Knex} from '@feasibleone/blong/types';
import {type TObject} from 'typebox';
import {type IColumnSchema, type ITableConstraints} from './types.ts';
import {addColumn, declaredWidth, methodId, propType} from './utils.ts';
 
/**
 * Create or synchronise a database table from a TypeBox `TObject` schema.
 *
 * - If the table does **not** exist it is created.
 * - If it does, columns present in the schema but absent from the table are
 *   added.  Existing columns are never modified.
 * - Columns absent from the schema are dropped only when `dropColumns: true`.
 *
 * The operation is idempotent: a second call without schema changes produces
 * no SQL.
 *
 * Table-level constraints (composite PKs, unique, foreign key, indexes) should
 * be applied in a **second pass** via {@link schemaTableConstraintSyncImpl}
 * after all tables exist, so foreign-key target tables are guaranteed present.
 *
 * Constraints are declared via the TypeBox `TObject` options parameter:
 *
 * ```ts
 * type.Object({...columns}, {
 *     constraints: {
 *         primaryKey: {columns: ['colA', 'colB']},
 *         unique: {typeAlias: {}},
 *         foreign: {typeId: 'core.type.typeId'},
 *         index: {resourceName: {}},
 *     },
 * })
 * ```
 */
export async function schemaTableSyncImpl(
    knex: Knex,
    tableName: string,
    schema: TObject,
    options: {dropColumns?: boolean} = {},
): Promise<{created: boolean; added: string[]; dropped: string[]; widened: string[]}> {
    const required = new Set(schema.required ?? []);
    const schemaProps = Object.keys(schema.properties);
    const exists = await knex.schema.hasTable(tableName);
    if (!exists) {
        await knex.schema.createTable(tableName, table => {
            for (const [name, prop] of Object.entries(schema.properties))
                addColumn(table, name, prop as IColumnSchema, !required.has(name));
        });
        return {created: true, added: schemaProps, dropped: [], widened: []};
    }
    const columnInfo = await knex(tableName).columnInfo();
    const existingColumns = new Set(Object.keys(columnInfo));
    const added: string[] = [];
    const dropped: string[] = [];
    const widened: string[] = [];
    const info = columnInfo as Record<string, {maxLength?: number; type?: string}>;
    await knex.schema.alterTable(tableName, table => {
        for (const [name, prop] of Object.entries(schema.properties)) {
            if (!existingColumns.has(name)) {
                addColumn(table, name, prop as IColumnSchema, true);
                added.push(name);
                continue;
            }
            // A declared string wider than the stored one is the one change a sync used to skip: the
            // column keeps the width it was created with, and a payload that grew fails the write that
            // records it (`@@F-672`).
            const declared = prop as IColumnSchema;
            // Only a string has a width worth widening. A `uid` or a `varchar` that a key is built on
            // must not be rewritten here: an altered column loses what it was part of.
            if (propType(declared) !== 'string') continue;
            const stored = info[name];
            const storedType = String(stored?.type ?? '').toLowerCase();
            if (!['varchar', 'char', 'text', 'mediumtext', 'longtext'].includes(storedType)) continue;
            const storedWidth = typeof stored?.maxLength === 'number' ? stored.maxLength : undefined;
            if (storedWidth === undefined) continue;
            if (declaredWidth(declared) <= storedWidth) continue;
            addColumn(table, name, declared, !required.has(name))?.alter();
            widened.push(name);
        }
        if (options.dropColumns) {
            for (const col of existingColumns) {
                if (!schemaProps.includes(col)) {
                    table.dropColumn(col);
                    dropped.push(col);
                }
            }
        }
    });
    return {created: false, added, dropped, widened};
}
 
/**
 * Apply table-level constraints (composite PKs, unique, indexes, foreign keys)
 * for an **existing** table via `alterTable`.  This is a separate step so it
 * can be called **after** all tables have been created, guaranteeing that
 * foreign-key target tables exist.
 *
 * Already-present constraints/indexes are skipped (idempotent).
 */
export async function schemaTableConstraintSyncImpl(
    knex: Knex,
    tableName: string,
    constraints: ITableConstraints,
): Promise<void> {
    const existingConstraints = (
        await knex('information_schema.TABLE_CONSTRAINTS').select('CONSTRAINT_NAME').where({
            TABLE_SCHEMA: knex.client.database(),
            TABLE_NAME: tableName,
        })
    ).map(c => (c.CONSTRAINT_NAME === 'PRIMARY' ? `${tableName}_pk` : c.CONSTRAINT_NAME));
    const existingIndexes = (
        await knex('information_schema.STATISTICS').select('INDEX_NAME').where({
            TABLE_SCHEMA: knex.client.database(),
            TABLE_NAME: tableName,
        })
    ).map(i => i.INDEX_NAME);
 
    await knex.schema.table(tableName, table => {
        // Composite primary key
        if (constraints.primaryKey) {
            if (typeof constraints.primaryKey === 'string') {
                if (!existingConstraints.includes(`${tableName}_pk`))
                    table.primary([constraints.primaryKey], `${tableName}_pk`);
            } else {
                const name = constraints.primaryKey.constraintName ?? `${tableName}_pk`;
                if (!existingConstraints.includes(name))
                    table.primary([...constraints.primaryKey.columns], name);
            }
        }
 
        // Unique constraints
        if (constraints.unique) {
            for (const [key, def] of Object.entries(constraints.unique)) {
                const name = `${tableName}_ux_${key}`;
                if (existingConstraints.includes(name)) continue;
                const cols = def.columns ?? [key];
                table.unique(cols, {indexName: name});
            }
        }
 
        // Indexes
        if (constraints.index) {
            for (const [key, def] of Object.entries(constraints.index)) {
                const name = `${tableName}_idx_${key}`;
                if (existingIndexes.includes(name)) continue;
                const cols = def.columns ?? [key];
                table.index(cols, name, def.indexType);
            }
        }
 
        // Foreign key constraints
        if (constraints.foreign) {
            for (const [key, def] of Object.entries(constraints.foreign)) {
                const name = `${tableName}_fk_${key}`;
                if (existingConstraints.includes(name)) continue;
                const ref = typeof def === 'string' ? {references: def} : def;
                const lastDot = ref.references.lastIndexOf('.');
                const refTable = ref.references.slice(0, lastDot).replaceAll('.', '_');
                const refCol = ref.references.slice(lastDot + 1);
                const cols = typeof def === 'string' ? [key] : (def.columns ?? [key]);
                const fk = table.foreign(cols, name);
                const fkr = fk.references(cols.map(() => refCol));
                fkr.inTable(refTable);
                if (ref.onDelete) fkr.onDelete(ref.onDelete);
                if (ref.onUpdate) fkr.onUpdate(ref.onUpdate);
            }
        }
    });
}
 
/**
 * Store each handler from `handlersMap` on `self` under two keys so it can be
 * reached via both framework dispatch and `super` calls:
 *
 * - `methodId(name)` (e.g. `"sqlitemadd"`) — used by `findHandler`
 * - `name`           (e.g. `"sqlItemAdd"`) — used by `super.name` in
 *                    object-form realm handler overrides
 */
export function attachHandlers(
    self: Record<string, unknown>,
    handlersMap: Record<string, unknown>,
): void {
    for (const [name, fn] of Object.entries(handlersMap)) {
        self[methodId(name)] = fn;
        self[name] = fn;
    }
}