- Add bun test suite: SQL generator and value unit tests, plus MariaDB integration tests gated on BUN_MARIADB_TEST_DB - schema: add --dry-run and require confirmation (or --yes) before dropping tables/columns; block unapproved destructive statements - Always AND targetId with the query, regardless of searchOperator - Initialize lazily on first call; init throws instead of exiting - Generate IN (?, ?, ...) lists for IN / NOT IN - Share value binding between insert and update (booleans, embeddings, function values, "" -> NULL for non-text columns) - Keep Buffers and convert BigInt/Date without a JSON round-trip - DbSQL: report success for empty SELECT results - Run update() in a transaction with row locking - Key the client cache on the full connection config - Consolidate identifier quoting, drop dead code, merge column lookup - Read CLI version from package.json, pin @types/bun, chmod CLI on compile - Rebuild dist Co-Authored-By: Claude Opus 5.5 <[email protected]>
122 lines
3.3 KiB
TypeScript
122 lines
3.3 KiB
TypeScript
import grabMariaDBClient, {
|
|
mariadbClientCacheKey,
|
|
} from "../functions/grab-mariadb-client";
|
|
import type {
|
|
BunMariaDBConfig,
|
|
DBInsertReturn,
|
|
DBResponseObject,
|
|
} from "../types";
|
|
|
|
/** Anything that can run a raw query: a client or a transaction handle */
|
|
export type DBQueryRunner = {
|
|
unsafe: (query: string, values?: any[]) => Promise<any>;
|
|
};
|
|
|
|
type Param = {
|
|
query: string;
|
|
values?: any[];
|
|
config?: BunMariaDBConfig;
|
|
/** Run on this client / transaction instead of the shared client */
|
|
client?: DBQueryRunner;
|
|
};
|
|
|
|
/**
|
|
* Resolve a shared MariaDB client. Prefer the global client so schema sync
|
|
* and CRUD do not open a new connection per query.
|
|
*/
|
|
export function resolveClient(config?: BunMariaDBConfig): Bun.SQL | undefined {
|
|
if (!config) {
|
|
return global.MARIADB_CLIENT;
|
|
}
|
|
|
|
// Same connection config as the global client → reuse it
|
|
if (
|
|
global.MARIADB_CLIENT &&
|
|
(!global.CONFIG ||
|
|
mariadbClientCacheKey(config) ===
|
|
mariadbClientCacheKey(global.CONFIG))
|
|
) {
|
|
return global.MARIADB_CLIENT;
|
|
}
|
|
|
|
return grabMariaDBClient({ config });
|
|
}
|
|
|
|
/**
|
|
* Convert driver rows to plain objects.
|
|
* - BigInt -> number (or string when outside the safe integer range)
|
|
* - Date -> ISO string (matches the generated `string` typedefs)
|
|
* - Buffers / typed arrays (BLOB, VECTOR) are kept as-is
|
|
*/
|
|
function normalizeValue(value: unknown): unknown {
|
|
if (typeof value == "bigint") {
|
|
const num = Number(value);
|
|
return Number.isSafeInteger(num) ? num : value.toString();
|
|
}
|
|
|
|
if (value instanceof Date) {
|
|
return Number.isNaN(value.getTime()) ? null : value.toISOString();
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
function normalizeRows<T>(res: unknown): T[] | undefined {
|
|
if (!Array.isArray(res)) return undefined;
|
|
|
|
return res.map((row) => {
|
|
if (!row || typeof row != "object") return row;
|
|
|
|
const normalized: Record<string, unknown> = {};
|
|
for (const [key, value] of Object.entries(row)) {
|
|
normalized[key] = normalizeValue(value);
|
|
}
|
|
return normalized;
|
|
}) as T[];
|
|
}
|
|
|
|
/**
|
|
* # Main DB Handler Function
|
|
*/
|
|
export default async function dbHandler<
|
|
T extends { [k: string]: any } = { [k: string]: any },
|
|
>({ query, values, config, client }: Param): Promise<DBResponseObject<T>> {
|
|
try {
|
|
const CLIENT = client || resolveClient(config);
|
|
|
|
if (!CLIENT) {
|
|
throw new Error(`Couldn't grab MariaDB Client.`);
|
|
}
|
|
|
|
const res = await CLIENT.unsafe(query, values);
|
|
|
|
const count = res.count;
|
|
|
|
const res_array = normalizeRows<T>(res);
|
|
|
|
const last_insert_id = res_array?.[0] ? res_array[0]?.id : undefined;
|
|
const affected_rows = res_array?.[0] ? res_array.length : undefined;
|
|
|
|
const insert_return: DBInsertReturn = {
|
|
count,
|
|
last_insert_id,
|
|
affected_rows,
|
|
};
|
|
|
|
return {
|
|
success: true,
|
|
payload: res_array,
|
|
single_res: res_array?.[0],
|
|
insert_return,
|
|
count,
|
|
db_res: res,
|
|
};
|
|
} catch (error: any) {
|
|
return {
|
|
success: false,
|
|
error: "DB Handler Error => " + error.message,
|
|
msg: "DB Handler Error => " + error.message,
|
|
};
|
|
}
|
|
}
|