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]>
This commit is contained in:
Vendored
+92
-58
@@ -1,37 +1,38 @@
|
||||
import dbHandler from "../db-handler";
|
||||
import _ from "lodash";
|
||||
import dbHandler, { resolveClient } from "../db-handler";
|
||||
import sqlGenerator from "../../utils/sql-generator";
|
||||
import sanitizeHtmlFields from "../../utils/sanitize-html-fields";
|
||||
function quoteIdentifier(identifier) {
|
||||
return `\`${identifier.replace(/`/g, "``")}\``;
|
||||
import { quoteIdentifier } from "../../utils/sql-identifier";
|
||||
import sqlValuePlaceholder from "../../utils/sql-value-placeholder";
|
||||
import grabTableFields from "../../utils/grab-table-fields";
|
||||
/** Thrown inside the transaction to roll back and return a response */
|
||||
class UpdateAbort extends Error {
|
||||
response;
|
||||
constructor(response) {
|
||||
super(response.msg || response.error || "Update aborted");
|
||||
this.response = response;
|
||||
}
|
||||
}
|
||||
export default async function DbUpdate({ table, data, query, targetId, config, }) {
|
||||
let sqlObj = { string: "", values: [] };
|
||||
let sqlObj = {
|
||||
string: "",
|
||||
values: [],
|
||||
where: "",
|
||||
whereValues: [],
|
||||
};
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = _.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: Number(targetId),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const finalQuery = query || {};
|
||||
const sqlQueryObj = sqlGenerator({
|
||||
tableName: quoteIdentifier(table),
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
targetId,
|
||||
});
|
||||
const whereClause = sqlQueryObj.string.match(/WHERE .*/)?.[0];
|
||||
const whereClause = sqlQueryObj.where;
|
||||
if (!whereClause) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No WHERE clause`,
|
||||
};
|
||||
}
|
||||
let values = [];
|
||||
let sql = ``;
|
||||
sql += `UPDATE ${quoteIdentifier(table)} SET`;
|
||||
const sanitizedData = sanitizeHtmlFields({
|
||||
table,
|
||||
data,
|
||||
@@ -41,48 +42,81 @@ export default async function DbUpdate({ table, data, query, targetId, config, }
|
||||
updated_at: Date.now(),
|
||||
...sanitizedData,
|
||||
};
|
||||
const keys = Object.keys(finalData);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
if (!key)
|
||||
continue;
|
||||
const isLast = i == keys.length - 1;
|
||||
sql += ` ${quoteIdentifier(key)}=?`;
|
||||
values.push(finalData[key] ?? null);
|
||||
if (!isLast) {
|
||||
sql += `,`;
|
||||
const fieldsMap = new Map(grabTableFields(table).map((f) => [f.fieldName, f]));
|
||||
const setParts = [];
|
||||
const setValues = [];
|
||||
for (const key of Object.keys(finalData)) {
|
||||
const { placeholder, value } = sqlValuePlaceholder({
|
||||
value: finalData[key],
|
||||
field: fieldsMap.get(key),
|
||||
});
|
||||
setParts.push(`${quoteIdentifier(key)}=${placeholder}`);
|
||||
setValues.push(value);
|
||||
}
|
||||
const CLIENT = resolveClient(config);
|
||||
if (!CLIENT) {
|
||||
throw new Error(`Couldn't grab MariaDB Client.`);
|
||||
}
|
||||
/**
|
||||
* Lock the matching rows, update them by id, and re-fetch them by id,
|
||||
* all in one transaction. Re-fetching by id still works when the update
|
||||
* changes a column used in the WHERE clause.
|
||||
*/
|
||||
return await CLIENT.begin(async (tx) => {
|
||||
const matched_res = await dbHandler({
|
||||
query: `SELECT id FROM ${quoteIdentifier(table)} ${whereClause} FOR UPDATE`,
|
||||
values: sqlQueryObj.whereValues,
|
||||
client: tx,
|
||||
});
|
||||
if (!matched_res.success) {
|
||||
throw new UpdateAbort({
|
||||
...matched_res,
|
||||
success: false,
|
||||
debug: { sqlObj: sqlQueryObj },
|
||||
});
|
||||
}
|
||||
}
|
||||
sql += ` ${whereClause}`;
|
||||
values = [...values, ...sqlQueryObj.values];
|
||||
const res = await dbHandler({
|
||||
query: sql,
|
||||
values: values,
|
||||
config,
|
||||
const matched_ids = (matched_res.payload || [])
|
||||
.map((row) => row.id)
|
||||
.filter((id) => id !== undefined && id !== null);
|
||||
if (matched_ids.length === 0) {
|
||||
throw new UpdateAbort({
|
||||
success: false,
|
||||
msg: "No rows matched the update query",
|
||||
payload: [],
|
||||
debug: { sqlObj: sqlQueryObj },
|
||||
});
|
||||
}
|
||||
const idPlaceholders = matched_ids.map(() => "?").join(",");
|
||||
const sql = `UPDATE ${quoteIdentifier(table)} SET ${setParts.join(", ")} WHERE id IN (${idPlaceholders})`;
|
||||
const values = [...setValues, ...matched_ids];
|
||||
sqlObj.string = sql;
|
||||
sqlObj.values = values;
|
||||
const res = await dbHandler({
|
||||
query: sql,
|
||||
values: values,
|
||||
client: tx,
|
||||
});
|
||||
if (!res.success) {
|
||||
throw new UpdateAbort({ ...res, debug: { sqlObj } });
|
||||
}
|
||||
const updated_res = await dbHandler({
|
||||
query: `SELECT * FROM ${quoteIdentifier(table)} WHERE id IN (${idPlaceholders})`,
|
||||
values: matched_ids,
|
||||
client: tx,
|
||||
});
|
||||
return {
|
||||
...updated_res,
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
db_res: res.db_res,
|
||||
};
|
||||
});
|
||||
if (res.error) {
|
||||
return res;
|
||||
}
|
||||
sqlObj.string = sql;
|
||||
sqlObj.values = values;
|
||||
let updated_sql = ``;
|
||||
let updated_sql_values = [];
|
||||
updated_sql += `SELECT * FROM ${quoteIdentifier(table)} ${whereClause}`;
|
||||
updated_sql_values = [...sqlQueryObj.values];
|
||||
const updated_res = await dbHandler({
|
||||
query: updated_sql,
|
||||
values: updated_sql_values,
|
||||
config,
|
||||
});
|
||||
return {
|
||||
...updated_res,
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
db_res: res.db_res,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof UpdateAbort) {
|
||||
return error.response;
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
|
||||
Reference in New Issue
Block a user