初次提交
This commit is contained in:
35
src/util.ts
Normal file
35
src/util.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { DatabaseError } from "./error";
|
||||
|
||||
export function escapeID(...keys: string[]) {
|
||||
return keys.map(key => `"${key}"`).join(".");
|
||||
}
|
||||
|
||||
export function escapeValue(value: any) {
|
||||
if (typeof value === "number") return value.toString();
|
||||
else if (typeof value === "string") return `E'${(value).replaceAll("'", "\\x27")}'`;
|
||||
else if (typeof value === "boolean") return value.toString();
|
||||
else if (typeof value === "bigint") return value.toString();
|
||||
else if (value === null) return "null";
|
||||
else throw new DatabaseError("DB_QUERY_ESCAPE_VALUE_ERROR", "无法转义的值");
|
||||
}
|
||||
|
||||
|
||||
export function formatSQL(sql: string, args: any[] | Record<string, any>) {
|
||||
if (args instanceof Array) {
|
||||
const _args = [...args];
|
||||
return sql.replace(/\?/g, () => {
|
||||
const v = _args.shift();
|
||||
if (v === undefined) return "null";
|
||||
else if (v instanceof Array) return v.map(escapeValue).join(",");
|
||||
else return escapeValue(v);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return sql.replace(/\{:(\w+)\}/g, (match, key) => {
|
||||
const v = args[key];
|
||||
if (v === undefined) return "null";
|
||||
else if (v instanceof Array) return v.map(escapeValue).join(",");
|
||||
else return escapeValue(v);
|
||||
});
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user