Files
bun-mariadb/src/lib/schema/run-schema-query.ts
T
tbenandClaude Opus 5.5 ddf431e866 Add tests, schema sync safeguards, and query/handler improvements
- 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]>
2026-10-14 02:27:59 +01:00

124 lines
3.0 KiB
TypeScript

import type { BunMariaDBConfig } from "../../types";
import dbHandler from "../db-handler";
type SchemaRunState = {
/** Record statements instead of executing them */
dryRun: boolean;
statements: string[];
/**
* Destructive statements that may run. `true` allows all of them;
* otherwise only exact matches are allowed.
*/
allowDestructive: true | Set<string>;
};
let schemaRunState: SchemaRunState | null = null;
/**
* Statements that discard stored data (tables or column values).
*/
export function isDestructiveSchemaStatement(query: string): boolean {
return /^\s*DROP\s+TABLE\b/i.test(query) || /\bDROP\s+COLUMN\b/i.test(query);
}
/**
* Run `fn` with schema statements recorded but not executed.
* Reads (information_schema) still run, so the plan is a close approximation:
* steps that depend on earlier changes (e.g. after a table rename) may differ.
*/
export async function planSchemaQueries(
fn: () => Promise<unknown>,
): Promise<string[]> {
const previous = schemaRunState;
schemaRunState = { dryRun: true, statements: [], allowDestructive: true };
try {
await fn();
return schemaRunState.statements;
} finally {
schemaRunState = previous;
}
}
/**
* Run `fn`, refusing any destructive statement that was not approved.
*/
export async function runSchemaQueriesGuarded(
fn: () => Promise<unknown>,
allowDestructive: true | Set<string>,
): Promise<void> {
const previous = schemaRunState;
schemaRunState = { dryRun: false, statements: [], allowDestructive };
try {
await fn();
} finally {
schemaRunState = previous;
}
}
export default async function runSchemaQuery({
query,
values,
config,
}: {
query: string;
values?: any[];
config?: BunMariaDBConfig;
}): Promise<void> {
if (schemaRunState) {
schemaRunState.statements.push(query);
if (schemaRunState.dryRun) {
return;
}
const allowed = schemaRunState.allowDestructive;
if (
allowed !== true &&
isDestructiveSchemaStatement(query) &&
!allowed.has(query)
) {
throw new Error(
`Refusing unapproved destructive statement: ${query}. Re-run with --dry-run to review, or --yes to allow it.`,
);
}
}
const res = await dbHandler({
query,
values,
config,
});
if (!res.success) {
throw new Error(
`Database query failed: ${query} ... ERROR: ${res.error || res.msg}`,
);
}
}
export async function querySchemaRows<T extends Record<string, any>>({
query,
values,
config,
}: {
query: string;
values?: any[];
config?: BunMariaDBConfig;
}): Promise<T[]> {
const res = await dbHandler<T>({
query,
values,
config,
});
if (!res.success) {
throw new Error(
`Database query failed: ${query} ... ERROR: ${res.error || res.msg}`,
);
}
return (res.payload || []) as T[];
}