- 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]>
257 lines
7.4 KiB
TypeScript
257 lines
7.4 KiB
TypeScript
import type {
|
|
ServerQueryParam,
|
|
ServerQueryParamOrder,
|
|
SQLInsertGenValueType,
|
|
} from "../types";
|
|
import sqlGenGenSearchStr from "./sql-generator-gen-search-str";
|
|
import sqlGenGenQueryStr from "./sql-generator-gen-query-str";
|
|
import {
|
|
columnRef,
|
|
quoteIdentifier,
|
|
quoteQualified,
|
|
sqlLogicalOperator,
|
|
sqlNonNegativeInt,
|
|
sqlOrderStrategy,
|
|
} from "./sql-identifier";
|
|
|
|
type Param<T extends { [key: string]: any } = { [key: string]: any }> = {
|
|
genObject?: ServerQueryParam<T>;
|
|
/** Raw (unquoted) table name */
|
|
tableName: string;
|
|
dbFullName?: string;
|
|
count?: boolean;
|
|
/**
|
|
* Restrict to a single row id. Always combined with AND, regardless of
|
|
* `searchOperator`.
|
|
*/
|
|
targetId?: number | string;
|
|
};
|
|
|
|
type Return = {
|
|
string: string;
|
|
values: SQLInsertGenValueType[];
|
|
/** `WHERE ...` clause alone (empty string if none) */
|
|
where: string;
|
|
/** Values for the `where` clause placeholders only */
|
|
whereValues: SQLInsertGenValueType[];
|
|
};
|
|
|
|
/** MariaDB requires LIMIT before OFFSET; this is the documented "no limit" value */
|
|
const MAX_LIMIT = "18446744073709551615";
|
|
|
|
/**
|
|
* # SQL Query Generator
|
|
* @description Builds parameterized SELECT SQL for MariaDB
|
|
*/
|
|
export default function sqlGenerator<
|
|
T extends { [key: string]: any } = { [key: string]: any },
|
|
>({
|
|
tableName: rawTableName,
|
|
genObject,
|
|
dbFullName,
|
|
count,
|
|
targetId,
|
|
}: Param<T>): Return {
|
|
const tableName = quoteQualified(rawTableName);
|
|
|
|
const finalQuery = genObject?.query ? genObject.query : undefined;
|
|
|
|
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
|
|
|
|
const whereValues: SQLInsertGenValueType[] = [];
|
|
|
|
let fullTextMatchStr = genObject?.fullTextSearch
|
|
? ` MATCH(${genObject.fullTextSearch.fields
|
|
.map((f) =>
|
|
columnRef(
|
|
String(f),
|
|
genObject.join ? tableName : undefined,
|
|
),
|
|
)
|
|
.join(",")}) AGAINST (? IN BOOLEAN MODE)`
|
|
: undefined;
|
|
|
|
const fullTextSearchStr = genObject?.fullTextSearch
|
|
? genObject.fullTextSearch.searchTerm
|
|
.split(` `)
|
|
.map((t) => `${t}`)
|
|
.join(" ")
|
|
: undefined;
|
|
|
|
let { str: queryString, values: selectValues } = sqlGenGenQueryStr<T>({
|
|
table_name: tableName,
|
|
append_table_names: true,
|
|
full_text_match_str: fullTextMatchStr,
|
|
full_text_search_str: fullTextSearchStr,
|
|
genObject,
|
|
});
|
|
|
|
const sqlSearhString = queryKeys?.map((field) => {
|
|
const queryObj = finalQuery?.[field];
|
|
if (!queryObj) return;
|
|
|
|
if (queryObj.__query) {
|
|
const subQueryGroup = queryObj.__query;
|
|
|
|
const subSearchKeys = Object.keys(subQueryGroup);
|
|
const subSearchString = subSearchKeys
|
|
.map((_field) => {
|
|
const newSubQueryObj = subQueryGroup?.[_field];
|
|
|
|
if (newSubQueryObj) {
|
|
const { str, values } = sqlGenGenSearchStr({
|
|
queryObj: newSubQueryObj,
|
|
field: newSubQueryObj.fieldName || _field,
|
|
join: genObject?.join,
|
|
table_name: tableName,
|
|
});
|
|
|
|
whereValues.push(...values);
|
|
|
|
return str;
|
|
}
|
|
})
|
|
.filter((str) => typeof str == "string");
|
|
|
|
return (
|
|
"(" +
|
|
subSearchString.join(
|
|
` ${sqlLogicalOperator(queryObj.operator)} `,
|
|
) +
|
|
")"
|
|
);
|
|
}
|
|
|
|
const { str, values } = sqlGenGenSearchStr({
|
|
queryObj,
|
|
field: queryObj.fieldName || field,
|
|
join: genObject?.join,
|
|
table_name: tableName,
|
|
});
|
|
|
|
whereValues.push(...values);
|
|
|
|
return str;
|
|
});
|
|
|
|
const cleanedUpSearchStr = sqlSearhString?.filter(
|
|
(str) => typeof str == "string",
|
|
);
|
|
|
|
const isSearchStr =
|
|
cleanedUpSearchStr?.[0] && cleanedUpSearchStr.find((str) => str);
|
|
|
|
const whereConditions: string[] = [];
|
|
|
|
if (isSearchStr) {
|
|
const stringOperator = sqlLogicalOperator(genObject?.searchOperator);
|
|
whereConditions.push(
|
|
`(${cleanedUpSearchStr.join(` ${stringOperator} `)})`,
|
|
);
|
|
}
|
|
|
|
if (genObject?.fullTextSearch && fullTextSearchStr && fullTextMatchStr) {
|
|
whereConditions.push(fullTextMatchStr.trim());
|
|
whereValues.push(fullTextSearchStr);
|
|
}
|
|
|
|
if (targetId !== undefined && targetId !== null && targetId !== "") {
|
|
const id = Number(targetId);
|
|
if (!Number.isFinite(id)) {
|
|
throw new Error(`Invalid targetId: ${String(targetId)}`);
|
|
}
|
|
whereConditions.push(
|
|
`${columnRef("id", genObject?.join ? tableName : undefined)} = ?`,
|
|
);
|
|
whereValues.push(id);
|
|
}
|
|
|
|
const where = whereConditions.length
|
|
? `WHERE ${whereConditions.join(" AND ")}`
|
|
: ``;
|
|
|
|
if (where) {
|
|
queryString += ` ${where}`;
|
|
}
|
|
|
|
if (genObject?.group) {
|
|
const groupRef = (
|
|
group: string | { field: unknown; table?: string },
|
|
) =>
|
|
typeof group == "object"
|
|
? columnRef(String(group.field), group.table)
|
|
: columnRef(String(group));
|
|
|
|
let group_by_txt = ``;
|
|
|
|
if (Array.isArray(genObject.group)) {
|
|
group_by_txt = genObject.group
|
|
.map((group) => groupRef(group as any))
|
|
.join(",");
|
|
} else {
|
|
group_by_txt = groupRef(genObject.group as any);
|
|
}
|
|
|
|
queryString += ` GROUP BY ${group_by_txt}`;
|
|
}
|
|
|
|
function grabOrderString(order: ServerQueryParamOrder<T>) {
|
|
const scoreAlias = genObject?.fullTextSearch?.scoreAlias;
|
|
let orderField = ``;
|
|
|
|
if (scoreAlias && String(order.field) === scoreAlias) {
|
|
orderField = quoteIdentifier(scoreAlias);
|
|
} else {
|
|
orderField = columnRef(
|
|
String(order.field),
|
|
genObject?.join ? tableName : undefined,
|
|
);
|
|
}
|
|
|
|
return ` ${orderField} ${sqlOrderStrategy(order.strategy)}`;
|
|
}
|
|
|
|
if (genObject?.order) {
|
|
const orders = (
|
|
Array.isArray(genObject.order) ? genObject.order : [genObject.order]
|
|
).filter(Boolean);
|
|
|
|
if (orders.length) {
|
|
queryString += ` ORDER BY${orders.map(grabOrderString).join(",")}`;
|
|
}
|
|
}
|
|
|
|
if (!count) {
|
|
const limit =
|
|
genObject?.limit !== undefined && genObject.limit !== null
|
|
? sqlNonNegativeInt(genObject.limit, "limit")
|
|
: undefined;
|
|
|
|
let offset: number | undefined;
|
|
|
|
if (genObject?.offset !== undefined && genObject.offset !== null) {
|
|
offset = sqlNonNegativeInt(genObject.offset, "offset");
|
|
} else if (genObject?.page && limit) {
|
|
const page = sqlNonNegativeInt(genObject.page, "page");
|
|
offset = Math.max(page - 1, 0) * limit;
|
|
}
|
|
|
|
if (limit) {
|
|
queryString += ` LIMIT ${limit}`;
|
|
} else if (offset) {
|
|
queryString += ` LIMIT ${MAX_LIMIT}`;
|
|
}
|
|
|
|
if (offset) {
|
|
queryString += ` OFFSET ${offset}`;
|
|
}
|
|
}
|
|
|
|
return {
|
|
string: queryString,
|
|
values: [...selectValues, ...whereValues],
|
|
where,
|
|
whereValues,
|
|
};
|
|
}
|