All files / blong-gogo/src/adapter/server/knex utils.ts

57.34% Statements 82/143
62.06% Branches 18/29
62.5% Functions 5/8
57.34% Lines 82/143

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 1441x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 3x 4x 2x 2x 2x 2x 2x 2x 2x 1x 2x 4x     4x     4x 1x 1x 4x 4x     4x     4x 4x 1x 4x 4x 1x 1x                                                                                 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import {readFileSync, readdirSync} from 'node:fs';
import {basename, join} from 'node:path';
import {Type, type TSchema} from 'typebox';
import {type IColumnSchema} from './types.ts';
 
export {type IColumnSchema};
 
export function addColumn(
    table: Record<string, (columnName: string, size?: number) => unknown>,
    columnName: string,
    prop: IColumnSchema,
    isNullable: boolean,
): void {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let column: any;
    if (columnName.endsWith('Id') && prop.type === 'integer') {
        column = table.increments(columnName);
        return;
    }
    switch (prop.type) {
        case 'string':
            if (prop.format === 'date-time' || prop.format === 'datetime')
                column = table.dateTime(columnName);
            else if (prop.format === 'date') column = table.date(columnName);
            else if (prop.format === 'time') column = table.time(columnName);
            else if (prop.format === 'uuid') column = table.uuid(columnName);
            else if (prop.maxLength != null && prop.maxLength > 255)
                column = table.text(columnName);
            else column = table.string(columnName, prop.maxLength ?? 255);
            break;
        case 'number':
            column = table.double(columnName);
            break;
        case 'integer':
            column = table.integer(columnName);
            break;
        case 'boolean':
            column = table.boolean(columnName);
            break;
        case 'array':
        case 'object':
            column = table.json(columnName);
            break;
        default:
            column = table.text(columnName);
            break;
    }
    if (isNullable) column.nullable();
    else column.notNullable();
    if (prop.default !== undefined) column.defaultTo(prop.default);
}
 
export function sqlTypeToTypebox(sqlType: string): TSchema {
    switch (sqlType.toUpperCase()) {
        case 'VARCHAR':
        case 'CHAR':
        case 'TEXT':
        case 'MEDIUMTEXT':
        case 'LONGTEXT':
        case 'TINYTEXT':
        case 'ENUM':
        case 'SET':
            return Type.String();
        case 'INT':
        case 'INTEGER':
        case 'BIGINT':
        case 'SMALLINT':
        case 'TINYINT':
        case 'MEDIUMINT':
            return Type.Integer();
        case 'DECIMAL':
        case 'FLOAT':
        case 'DOUBLE':
        case 'NUMERIC':
        case 'REAL':
            return Type.Number();
        case 'BOOLEAN':
        case 'BOOL':
        case 'BIT':
            return Type.Boolean();
        case 'DATE':
            return Type.String({format: 'date'});
        case 'DATETIME':
        case 'TIMESTAMP':
            return Type.String({format: 'date-time'});
        case 'TIME':
            return Type.String({format: 'time'});
        case 'JSON':
            return Type.Unknown();
        default:
            return Type.String();
    }
}
 
export function snakeToCamel(str: string): string {
    return str.replace(/([-_]\w)/g, g => g[1].toUpperCase());
}
 
export function capitalize(str: string): string {
    return str.charAt(0).toUpperCase() + str.slice(1);
}
 
/** Normalise a handler name for registry look-up: remove dots, lowercase. */
export function methodId(name: string): string {
    return name.replace(/\./g, '').toLowerCase();
}
 
/**
 * Collapse whitespace and uppercase SQL for content comparison.
 * Line comments are stripped before collapsing.
 */
export function normalizeSQL(sql: string): string {
    return sql
        .replace(/--[^\n]*/g, '')
        .replace(/\s+/g, ' ')
        .trim()
        .toUpperCase();
}
 
/**
 * Extract the procedure body (BEGIN … END block) from a full CREATE PROCEDURE
 * statement so it can be compared against MySQL's `ROUTINE_DEFINITION` column,
 * which stores only the body.  Returns the full SQL if no BEGIN is found.
 */
export function extractProcedureBody(sql: string): string {
    const upper = sql.toUpperCase();
    const beginIdx = upper.indexOf('BEGIN');
    if (beginIdx === -1) return sql;
    const endIdx = upper.lastIndexOf('END');
    if (endIdx === -1) return sql;
    return sql.slice(beginIdx, endIdx + 3);
}
 
/**
 * Scan a directory for `.sql` files and return their base names and contents.
 */
export function readSqlFiles(dir: string): Array<{name: string; sql: string}> {
    const files = readdirSync(dir).filter(f => f.endsWith('.sql'));
    return files.map(f => ({
        name: basename(f, '.sql'),
        sql: readFileSync(join(dir, f), 'utf8'),
    }));
}