Update .gitignore, add dist directory

This commit is contained in:
2026-07-20 21:43:05 +01:00
parent 9f2db66760
commit 3bbf00cdb0
153 changed files with 6280 additions and 1 deletions
+6
View File
@@ -0,0 +1,6 @@
import { type BUN_MARIADB_DatabaseSchemaType } from "../types";
type Params = {
dbSchema: BUN_MARIADB_DatabaseSchemaType;
};
export default function ({ dbSchema }: Params): BUN_MARIADB_DatabaseSchemaType;
export {};
+12
View File
@@ -0,0 +1,12 @@
import _ from "lodash";
import { DefaultFields } from "../types";
export default function ({ dbSchema }) {
const finaldbSchema = _.cloneDeep(dbSchema);
finaldbSchema.tables = finaldbSchema.tables.map((t) => {
const newTable = _.cloneDeep(t);
newTable.fields = newTable.fields.filter((f) => !f.fieldName?.match(/^(id|created_at|updated_at)$/));
newTable.fields.unshift(...DefaultFields);
return newTable;
});
return finaldbSchema;
}
+21
View File
@@ -0,0 +1,21 @@
export declare const ExportArchiveMembers: {
readonly SqlFileName: "dump.sql";
readonly SchemaFileName: "schema.ts";
};
export type ExportArchiveContents = {
sql: string;
schemaTs: string;
};
export declare function isArchivePath(filePath: string): boolean;
export declare function isSqlPath(filePath: string): boolean;
/**
* Create a portable export archive (tar / tar.gz / zip) with dump.sql + schema.ts.
*/
export declare function writeExportArchive({ contents, outPath, }: {
contents: ExportArchiveContents;
outPath: string;
}): Promise<void>;
/**
* Read a portable export archive (tar / tar.gz / zip).
*/
export declare function readExportArchive(archivePath: string): Promise<ExportArchiveContents>;
+159
View File
@@ -0,0 +1,159 @@
import fs from "fs";
import path from "path";
import { AppData } from "../data/app-data";
import grabDirNames from "../data/grab-dir-names";
export const ExportArchiveMembers = {
SqlFileName: "dump.sql",
SchemaFileName: AppData.DbSchemaFileName,
};
const ARCHIVE_EXTENSIONS = [".tar.gz", ".tgz", ".tar", ".zip"];
export function isArchivePath(filePath) {
const lower = filePath.toLowerCase();
return ARCHIVE_EXTENSIONS.some((ext) => lower.endsWith(ext));
}
export function isSqlPath(filePath) {
return filePath.toLowerCase().endsWith(".sql");
}
/**
* Create a portable export archive (tar / tar.gz / zip) with dump.sql + schema.ts.
*/
export async function writeExportArchive({ contents, outPath, }) {
const lower = outPath.toLowerCase();
if (lower.endsWith(".zip")) {
await writeZipArchive({ contents, outPath });
return;
}
const members = {
[ExportArchiveMembers.SqlFileName]: contents.sql,
[ExportArchiveMembers.SchemaFileName]: contents.schemaTs,
};
const gzip = lower.endsWith(".gz") || lower.endsWith(".tgz");
if (gzip) {
await Bun.Archive.write(outPath, members, { compress: "gzip" });
}
else {
await Bun.Archive.write(outPath, members);
}
}
/**
* Read a portable export archive (tar / tar.gz / zip).
*/
export async function readExportArchive(archivePath) {
const lower = archivePath.toLowerCase();
if (lower.endsWith(".zip")) {
return readZipArchive(archivePath);
}
const bytes = await Bun.file(archivePath).bytes();
const archive = new Bun.Archive(bytes);
const files = await archive.files();
const sql = (await readArchiveMember(files, ExportArchiveMembers.SqlFileName)) ??
(await readFirstMatching(files, (name) => name.endsWith(".sql")));
const schemaTs = (await readArchiveMember(files, ExportArchiveMembers.SchemaFileName)) ??
(await readFirstMatching(files, (name) => name.endsWith("schema.ts")));
if (!sql) {
throw new Error(`Archive is missing SQL dump (expected \`${ExportArchiveMembers.SqlFileName}\`)`);
}
if (!schemaTs) {
throw new Error(`Archive is missing schema TypeScript (expected \`${ExportArchiveMembers.SchemaFileName}\`)`);
}
return { sql, schemaTs };
}
async function readArchiveMember(files, name) {
// Exact match, or basename match for nested paths
for (const [entry, file] of files) {
if (entry === name || path.basename(entry) === name) {
return await file.text();
}
}
return null;
}
async function readFirstMatching(files, predicate) {
for (const [entry, file] of files) {
if (predicate(entry) || predicate(path.basename(entry))) {
return await file.text();
}
}
return null;
}
async function writeZipArchive({ contents, outPath, }) {
const { BUN_MARIADB_TEMP_DIR } = grabDirNames();
const tempDir = path.join(BUN_MARIADB_TEMP_DIR, `export-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.mkdirSync(tempDir, { recursive: true });
try {
const sqlPath = path.join(tempDir, ExportArchiveMembers.SqlFileName);
const schemaPath = path.join(tempDir, ExportArchiveMembers.SchemaFileName);
fs.writeFileSync(sqlPath, contents.sql, "utf-8");
fs.writeFileSync(schemaPath, contents.schemaTs, "utf-8");
const absOut = path.resolve(outPath);
const proc = Bun.spawn([
"zip",
"-q",
"-j",
absOut,
ExportArchiveMembers.SqlFileName,
ExportArchiveMembers.SchemaFileName,
], {
cwd: tempDir,
stdout: "pipe",
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([
new Response(proc.stderr).text(),
proc.exited,
]);
if (exitCode !== 0) {
throw new Error(`zip failed (exit ${exitCode}): ${stderr || "unknown error"}. Ensure \`zip\` is installed, or use .tar.gz.`);
}
}
finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}
async function readZipArchive(archivePath) {
const { BUN_MARIADB_TEMP_DIR } = grabDirNames();
const tempDir = path.join(BUN_MARIADB_TEMP_DIR, `import-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.mkdirSync(tempDir, { recursive: true });
try {
const absArchive = path.resolve(archivePath);
const proc = Bun.spawn(["unzip", "-q", "-o", absArchive, "-d", tempDir], {
stdout: "pipe",
stderr: "pipe",
});
const [stderr, exitCode] = await Promise.all([
new Response(proc.stderr).text(),
proc.exited,
]);
if (exitCode !== 0) {
throw new Error(`unzip failed (exit ${exitCode}): ${stderr || "unknown error"}. Ensure \`unzip\` is installed.`);
}
const sql = findFileContents(tempDir, (name) => name === ExportArchiveMembers.SqlFileName || name.endsWith(".sql"));
const schemaTs = findFileContents(tempDir, (name) => name === ExportArchiveMembers.SchemaFileName ||
name.endsWith("schema.ts"));
if (!sql) {
throw new Error(`Archive is missing SQL dump (expected \`${ExportArchiveMembers.SqlFileName}\`)`);
}
if (!schemaTs) {
throw new Error(`Archive is missing schema TypeScript (expected \`${ExportArchiveMembers.SchemaFileName}\`)`);
}
return { sql, schemaTs };
}
finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}
function findFileContents(dir, predicate) {
const stack = [dir];
while (stack.length) {
const current = stack.pop();
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
stack.push(full);
}
else if (predicate(entry.name)) {
return fs.readFileSync(full, "utf-8");
}
}
}
return null;
}
+12
View File
@@ -0,0 +1,12 @@
type Params = {
backup_name: string;
};
/**
* Parse timestamped backup/export names: `{db_name}-{timestamp}[.sql|.tar.gz|...]`
*/
export default function grabBackupData({ backup_name }: Params): {
backup_date: Date;
backup_date_timestamp: number;
origin_backup_name: string;
};
export {};
+33
View File
@@ -0,0 +1,33 @@
/**
* Strip known backup/export extensions from a file name.
*/
function stripBackupExtension(name) {
const lower = name.toLowerCase();
if (lower.endsWith(".tar.gz")) {
return name.slice(0, -7);
}
if (lower.endsWith(".tgz")) {
return name.slice(0, -4);
}
if (lower.endsWith(".tar")) {
return name.slice(0, -4);
}
if (lower.endsWith(".zip")) {
return name.slice(0, -4);
}
if (lower.endsWith(".sql")) {
return name.slice(0, -4);
}
return name;
}
/**
* Parse timestamped backup/export names: `{db_name}-{timestamp}[.sql|.tar.gz|...]`
*/
export default function grabBackupData({ backup_name }) {
const normalized = stripBackupExtension(backup_name);
const backup_parts = normalized.split("-");
const backup_date_timestamp = Number(backup_parts.pop());
const origin_backup_name = backup_parts.join("-");
const backup_date = new Date(backup_date_timestamp);
return { backup_date, backup_date_timestamp, origin_backup_name };
}
+6
View File
@@ -0,0 +1,6 @@
import type { BunMariaDBConfig } from "../types";
type Params = {
config: BunMariaDBConfig;
};
export default function grabDBBackupFileName({ config }: Params): string;
export {};
+3
View File
@@ -0,0 +1,3 @@
export default function grabDBBackupFileName({ config }) {
return `${config.db_name}-${Date.now()}.sql`;
}
+10
View File
@@ -0,0 +1,10 @@
import type { BunMariaDBConfig } from "../types";
type Params = {
config: BunMariaDBConfig;
};
export default function grabDBDir({ config }: Params): {
db_dir: string;
backup_dir: string;
export_dir: string;
};
export {};
+13
View File
@@ -0,0 +1,13 @@
import path from "path";
import grabDirNames from "../data/grab-dir-names";
import { AppData } from "../data/app-data";
export default function grabDBDir({ config }) {
const { ROOT_DIR } = grabDirNames();
const db_dir = config.db_dir
? path.resolve(ROOT_DIR, config.db_dir)
: ROOT_DIR;
const backup_dir_name = config.db_backup_dir || AppData["DefaultBackupDirName"];
const backup_dir = path.resolve(db_dir, backup_dir_name);
const export_dir = path.resolve(db_dir, AppData["DefaultExportDirName"]);
return { db_dir, backup_dir, export_dir };
}
+1
View File
@@ -0,0 +1 @@
export default function grabDbSchema(): Promise<import("..").BUN_MARIADB_DatabaseSchemaType>;
+5
View File
@@ -0,0 +1,5 @@
export default async function grabDbSchema() {
const config = global.CONFIG;
const dbSchema = global.DB_SCHEMA;
return dbSchema;
}
+7
View File
@@ -0,0 +1,7 @@
import type { BunMariaDBQueryFieldValues, ServerQueryParam } from "../types";
type Params<Q extends Record<string, any> = Record<string, any>> = {
query: ServerQueryParam<Q>;
ignore_select_fields?: boolean;
};
export default function grabJoinFieldsFromQueryObject<Q extends Record<string, any> = Record<string, any>, F extends string = string, T extends string = string>({ query, ignore_select_fields, }: Params<Q>): BunMariaDBQueryFieldValues<F, T>[];
export {};
+55
View File
@@ -0,0 +1,55 @@
import _ from "lodash";
export default function grabJoinFieldsFromQueryObject({ query, ignore_select_fields, }) {
const fields_values = [];
const new_query = _.cloneDeep(query);
if (new_query.join) {
for (let i = 0; i < new_query.join.length; i++) {
const join = new_query.join[i];
if (!join)
continue;
if (Array.isArray(join)) {
for (let i = 0; i < join.length; i++) {
const single_join = join[i];
fields_values.push(...grabSingleJoinData({
join: single_join,
ignore_select_fields,
}));
}
}
else {
fields_values.push(...grabSingleJoinData({
join: join,
ignore_select_fields,
}));
}
}
}
return fields_values;
}
function grabSingleJoinData({ join, ignore_select_fields, }) {
let values = [];
const join_select_fields = join?.selectFields;
if (!join_select_fields?.[0] && !ignore_select_fields) {
throw new Error(`\`selectFields\` required in joins. To ignore this error, pass the \`ignore_select_fields\` parameter`);
}
if (join_select_fields?.[0]) {
for (let i = 0; i < join_select_fields.length; i++) {
const select_field = join_select_fields[i];
if (select_field) {
values.push({
table: join.tableName,
field: typeof select_field == "object"
? String(select_field.field)
: String(select_field),
});
}
}
}
if (join.group_concat) {
values.push({
table: join.tableName,
field: join.group_concat.field,
});
}
return values;
}
+6
View File
@@ -0,0 +1,6 @@
import type { BunMariaDBConfig } from "../types";
type Params = {
config: BunMariaDBConfig;
};
export default function grabSortedBackups({ config }: Params): string[];
export {};
+32
View File
@@ -0,0 +1,32 @@
import grabDBDir from "../utils/grab-db-dir";
import fs from "fs";
function stripBackupExtension(name) {
const lower = name.toLowerCase();
if (lower.endsWith(".tar.gz"))
return name.slice(0, -7);
if (lower.endsWith(".tgz"))
return name.slice(0, -4);
if (lower.endsWith(".tar"))
return name.slice(0, -4);
if (lower.endsWith(".zip"))
return name.slice(0, -4);
if (lower.endsWith(".sql"))
return name.slice(0, -4);
return name;
}
function backupTimestamp(name) {
const base = stripBackupExtension(name);
const ts = Number(base.split("-").pop());
return Number.isFinite(ts) ? ts : 0;
}
export default function grabSortedBackups({ config }) {
const { backup_dir } = grabDBDir({ config });
if (!fs.existsSync(backup_dir)) {
return [];
}
const backups = fs.readdirSync(backup_dir);
/**
* Order Backups. Most recent first.
*/
return backups.sort((a, b) => backupTimestamp(b) - backupTimestamp(a));
}
+6
View File
@@ -0,0 +1,6 @@
import type { BunMariaDBConfig } from "../types";
type Params = {
config: BunMariaDBConfig;
};
export default function grabSortedExports({ config }: Params): string[];
export {};
+27
View File
@@ -0,0 +1,27 @@
import fs from "fs";
import grabDBDir from "./grab-db-dir";
function stripExportExtension(name) {
const lower = name.toLowerCase();
if (lower.endsWith(".tar.gz"))
return name.slice(0, -7);
if (lower.endsWith(".tgz"))
return name.slice(0, -4);
if (lower.endsWith(".tar"))
return name.slice(0, -4);
if (lower.endsWith(".zip"))
return name.slice(0, -4);
return name;
}
function exportTimestamp(name) {
const base = stripExportExtension(name);
const ts = Number(base.split("-").pop());
return Number.isFinite(ts) ? ts : 0;
}
export default function grabSortedExports({ config }) {
const { export_dir } = grabDBDir({ config });
if (!fs.existsSync(export_dir)) {
return [];
}
const exports = fs.readdirSync(export_dir);
return exports.sort((a, b) => exportTimestamp(b) - exportTimestamp(a));
}
+6
View File
@@ -0,0 +1,6 @@
/**
* Build env for mariadb / mariadb-dump child processes without putting
* the password on the process argv (visible via `ps`).
*/
export default function mariadbCliEnv(): NodeJS.ProcessEnv;
export declare function mariadbCliConnectionArgs(): string[];
+24
View File
@@ -0,0 +1,24 @@
/**
* Build env for mariadb / mariadb-dump child processes without putting
* the password on the process argv (visible via `ps`).
*/
export default function mariadbCliEnv() {
const env = { ...process.env };
const password = process.env.BUN_MARIADB_SERVER_PASSWORD;
if (password) {
// Standard MySQL/MariaDB client env vars (prefer not using -p on argv)
env.MYSQL_PWD = password;
env.MARIADB_PWD = password;
}
return env;
}
export function mariadbCliConnectionArgs() {
const host = process.env.BUN_MARIADB_SERVER_HOST || "127.0.0.1";
const user = process.env.BUN_MARIADB_SERVER_USERNAME || "root";
const port = process.env.BUN_MARIADB_SERVER_PORT;
return [
`-h${host}`,
`-u${user}`,
...(port ? [`-P${port}`] : []),
];
}
+17
View File
@@ -0,0 +1,17 @@
import type { BunMariaDBConfig } from "../types";
/**
* Prefer mariadb-dump, fall back to mysqldump.
*/
export declare function resolveDumpBinary(): string;
/**
* Prefer mariadb client, fall back to mysql.
*/
export declare function resolveClientBinary(): string;
/**
* Dump the configured database to an SQL string.
*/
export declare function dumpDatabase(config: BunMariaDBConfig): Promise<string>;
/**
* Restore an SQL dump into the configured database.
*/
export declare function restoreDatabase(config: BunMariaDBConfig, sql: string): Promise<void>;
+92
View File
@@ -0,0 +1,92 @@
import mariadbCliEnv, { mariadbCliConnectionArgs } from "./mariadb-cli-env";
/**
* Prefer mariadb-dump, fall back to mysqldump.
*/
export function resolveDumpBinary() {
const candidates = ["mariadb-dump", "mysqldump"];
for (const bin of candidates) {
try {
const result = Bun.spawnSync(["which", bin], {
stdout: "pipe",
stderr: "pipe",
});
if (result.exitCode === 0) {
return new TextDecoder().decode(result.stdout).trim() || bin;
}
}
catch {
// try next
}
}
return "mariadb-dump";
}
/**
* Prefer mariadb client, fall back to mysql.
*/
export function resolveClientBinary() {
const candidates = ["mariadb", "mysql"];
for (const bin of candidates) {
try {
const result = Bun.spawnSync(["which", bin], {
stdout: "pipe",
stderr: "pipe",
});
if (result.exitCode === 0) {
return new TextDecoder().decode(result.stdout).trim() || bin;
}
}
catch {
// try next
}
}
return "mariadb";
}
/**
* Dump the configured database to an SQL string.
*/
export async function dumpDatabase(config) {
const dumpBin = resolveDumpBinary();
const args = [
dumpBin,
...mariadbCliConnectionArgs(),
"--single-transaction",
"--routines",
"--triggers",
"--events",
config.db_name,
];
const proc = Bun.spawn(args, {
stdout: "pipe",
stderr: "pipe",
env: mariadbCliEnv(),
});
const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
if (exitCode !== 0) {
throw new Error(`Dump failed (exit ${exitCode}): ${stderr || "unknown error"}. Ensure \`mariadb-dump\` or \`mysqldump\` is installed.`);
}
return stdout;
}
/**
* Restore an SQL dump into the configured database.
*/
export async function restoreDatabase(config, sql) {
const clientBin = resolveClientBinary();
const args = [clientBin, ...mariadbCliConnectionArgs(), config.db_name];
const proc = Bun.spawn(args, {
stdin: new Blob([sql]),
stdout: "pipe",
stderr: "pipe",
env: mariadbCliEnv(),
});
const [stderr, exitCode] = await Promise.all([
new Response(proc.stderr).text(),
proc.exited,
]);
if (exitCode !== 0) {
throw new Error(`Restore failed (exit ${exitCode}): ${stderr || "unknown error"}. Ensure \`mariadb\` or \`mysql\` is installed.`);
}
}
+6
View File
@@ -0,0 +1,6 @@
import type { QueryRawValueType, ServerQueryObjectValue } from "../types";
type Params = {
query_value: ServerQueryObjectValue;
};
export default function queryValueParser({ query_value, }: Params): QueryRawValueType | QueryRawValueType[];
export {};
+21
View File
@@ -0,0 +1,21 @@
export default function queryValueParser({ query_value, }) {
if (typeof query_value == "string" || typeof query_value == "number") {
return query_value;
}
if (Array.isArray(query_value)) {
let values = [];
for (let i = 0; i < query_value.length; i++) {
const single_value = query_value[i];
if (single_value) {
const single_parsed_value = queryValueParser({
query_value: single_value,
});
if (!Array.isArray(single_parsed_value)) {
values.push(single_parsed_value);
}
}
}
return values;
}
return query_value?.value;
}
+18
View File
@@ -0,0 +1,18 @@
import type { BunMariaDBConfig } from "../types";
/**
* Sanitize string values ONLY for schema fields with explicit `html: true`.
* Other fields (including plain text that happens to contain HTML) are left untouched.
*/
export default function sanitizeHtmlFields<T extends Record<string, any> = Record<string, any>>({ table, data, config, }: {
table: string;
data: T;
config?: BunMariaDBConfig;
}): T;
/**
* Sanitize an array of row objects for insert.
*/
export declare function sanitizeHtmlFieldsBatch<T extends Record<string, any> = Record<string, any>>({ table, data, config, }: {
table: string;
data: T[];
config?: BunMariaDBConfig;
}): T[];
+54
View File
@@ -0,0 +1,54 @@
import sanitizeHtml from "sanitize-html";
import { readLiveSchema } from "../functions/live-schema";
import getSanitizeHtmlOptions from "./sanitize-html-options";
function grabTableFields(tableName) {
const dbSchema = global.DB_SCHEMA || readLiveSchema();
const tableSchema = dbSchema?.tables?.find((t) => t.tableName === tableName);
return tableSchema?.fields || [];
}
/**
* Only fields with an explicit `html: true` flag are sanitized.
* Missing / falsy / non-true values are never sanitized.
*/
function isExplicitHtmlField(field) {
return field?.html === true;
}
function sanitizeValue(value, config) {
if (typeof value !== "string") {
return value;
}
return sanitizeHtml(value, getSanitizeHtmlOptions(config));
}
/**
* Sanitize string values ONLY for schema fields with explicit `html: true`.
* Other fields (including plain text that happens to contain HTML) are left untouched.
*/
export default function sanitizeHtmlFields({ table, data, config, }) {
const fields = grabTableFields(table);
if (fields.length === 0) {
return data;
}
const htmlFieldNames = new Set(fields
.filter(isExplicitHtmlField)
.map((f) => f.fieldName)
.filter((name) => Boolean(name)));
// No explicitly marked html fields on this table — skip entirely
if (htmlFieldNames.size === 0) {
return data;
}
const sanitized = { ...data };
const resolvedConfig = config || global.CONFIG;
for (const key of Object.keys(sanitized)) {
// Only sanitize keys that map to fields with html: true
if (!htmlFieldNames.has(key))
continue;
sanitized[key] = sanitizeValue(sanitized[key], resolvedConfig);
}
return sanitized;
}
/**
* Sanitize an array of row objects for insert.
*/
export function sanitizeHtmlFieldsBatch({ table, data, config, }) {
return data.map((row) => sanitizeHtmlFields({ table, data: row, config }));
}
+7
View File
@@ -0,0 +1,7 @@
import type { IOptions } from "sanitize-html";
import type { BunMariaDBConfig } from "../types";
export declare const defaultSanitizeHtmlOptions: IOptions;
/**
* Build sanitize-html options, appending any tags/attributes from config.
*/
export default function getSanitizeHtmlOptions(config?: BunMariaDBConfig): IOptions;
+72
View File
@@ -0,0 +1,72 @@
export const defaultSanitizeHtmlOptions = {
allowedTags: [
"b",
"i",
"em",
"strong",
"a",
"p",
"span",
"ul",
"ol",
"li",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"img",
"div",
"button",
"pre",
"code",
"br",
"hr",
"blockquote",
"table",
"tr",
"td",
"th",
"thead",
"tbody",
"tfoot",
"caption",
"colgroup",
"col",
],
allowedAttributes: {
a: ["href", "title", "class", "style", "target", "rel"],
img: ["src", "alt", "width", "height", "class", "style"],
"*": ["style", "class", "title", "id"],
},
};
function uniqueStrings(values) {
return Array.from(new Set(values));
}
/**
* Build sanitize-html options, appending any tags/attributes from config.
*/
export default function getSanitizeHtmlOptions(config) {
const cfg = config || global.CONFIG;
const extra = cfg?.html_sanitize;
const baseTags = defaultSanitizeHtmlOptions.allowedTags || [];
const baseAttrs = {
...(defaultSanitizeHtmlOptions.allowedAttributes || {}),
};
const allowedTags = uniqueStrings([
...(Array.isArray(baseTags) ? baseTags : []),
...(extra?.allowed_tags || []),
]);
const allowedAttributes = { ...baseAttrs };
for (const [tag, attrs] of Object.entries(extra?.allowed_attributes || {})) {
allowedAttributes[tag] = uniqueStrings([
...(allowedAttributes[tag] || []),
...attrs,
]);
}
return {
allowedTags,
allowedAttributes,
};
}
+2
View File
@@ -0,0 +1,2 @@
import { ServerQueryEqualities } from "../types";
export default function sqlEqualityParser(eq: (typeof ServerQueryEqualities)[number]): string;
+41
View File
@@ -0,0 +1,41 @@
import { ServerQueryEqualities } from "../types";
export default function sqlEqualityParser(eq) {
switch (eq) {
case "EQUAL":
return "=";
case "LIKE":
return "LIKE";
case "NOT LIKE":
return "NOT LIKE";
case "NOT EQUAL":
return "<>";
case "IS NOT":
return "IS NOT";
case "IN":
return "IN";
case "NOT IN":
return "NOT IN";
case "BETWEEN":
return "BETWEEN";
case "NOT BETWEEN":
return "NOT BETWEEN";
case "IS NULL":
return "IS NULL";
case "IS NOT NULL":
return "IS NOT NULL";
case "EXISTS":
return "EXISTS";
case "NOT EXISTS":
return "NOT EXISTS";
case "GREATER THAN":
return ">";
case "GREATER THAN OR EQUAL":
return ">=";
case "LESS THAN":
return "<";
case "LESS THAN OR EQUAL":
return "<=";
default:
return "=";
}
}
+20
View File
@@ -0,0 +1,20 @@
import type { ServerQueryEqualities, ServerQueryObject, SQLInsertGenValueType } from "../types";
type Params = {
fieldName: string;
value?: SQLInsertGenValueType;
equality?: (typeof ServerQueryEqualities)[number];
queryObj: ServerQueryObject<{
[key: string]: any;
}, string>;
isValueFieldValue?: boolean;
};
type Return = {
str?: string;
param?: SQLInsertGenValueType;
};
/**
* # SQL Gen Operator Gen
* @description Maps query equality operators to MariaDB SQL fragments
*/
export default function sqlGenOperatorGen({ fieldName, value, equality, queryObj, isValueFieldValue, }: Params): Return;
export {};
+133
View File
@@ -0,0 +1,133 @@
import sqlEqualityParser from "./sql-equality-parser";
/**
* # SQL Gen Operator Gen
* @description Maps query equality operators to MariaDB SQL fragments
*/
export default function sqlGenOperatorGen({ fieldName, value, equality, queryObj, isValueFieldValue, }) {
if (queryObj.nullValue) {
return { str: `${fieldName} IS NULL` };
}
if (queryObj.notNullValue) {
return { str: `${fieldName} IS NOT NULL` };
}
if (value) {
const finalValue = isValueFieldValue ? value : "?";
const finalParams = isValueFieldValue ? undefined : value;
if (equality == "MATCH") {
return {
str: `MATCH(${fieldName}) AGAINST(${finalValue} IN NATURAL LANGUAGE MODE)`,
param: finalParams,
};
}
else if (equality == "MATCH_BOOLEAN") {
return {
str: `MATCH(${fieldName}) AGAINST(${finalValue} IN BOOLEAN MODE)`,
param: finalParams,
};
}
else if (equality == "LIKE_LOWER") {
return {
str: `LOWER(${fieldName}) LIKE LOWER(${finalValue})`,
param: `%${finalParams}%`,
};
}
else if (equality == "LIKE_LOWER_RAW") {
return {
str: `LOWER(${fieldName}) LIKE LOWER(${finalValue})`,
param: finalParams,
};
}
else if (equality == "LIKE") {
return {
str: `${fieldName} LIKE ${finalValue}`,
param: `%${finalParams}%`,
};
}
else if (equality == "LIKE_RAW") {
return {
str: `${fieldName} LIKE ${finalValue}`,
param: finalParams,
};
}
else if (equality == "NOT_LIKE_LOWER") {
return {
str: `LOWER(${fieldName}) NOT LIKE LOWER(${finalValue})`,
param: `%${finalParams}%`,
};
}
else if (equality == "NOT_LIKE_LOWER_RAW") {
return {
str: `LOWER(${fieldName}) NOT LIKE LOWER(${finalValue})`,
param: finalParams,
};
}
else if (equality == "NOT LIKE") {
return {
str: `${fieldName} NOT LIKE ${finalValue}`,
param: finalParams,
};
}
else if (equality == "NOT LIKE_RAW") {
return {
str: `${fieldName} NOT LIKE ${finalValue}`,
param: finalParams,
};
}
else if (equality == "REGEXP") {
return {
str: `LOWER(${fieldName}) REGEXP LOWER(${finalValue})`,
param: finalParams,
};
}
else if (equality == "FULLTEXT") {
return {
str: `MATCH(${fieldName}) AGAINST(${finalValue} IN BOOLEAN MODE)`,
param: finalParams,
};
}
else if (equality == "NOT EQUAL") {
return {
str: `${fieldName} != ${finalValue}`,
param: finalParams,
};
}
else if (equality == "IS NOT") {
return {
str: `${fieldName} IS NOT ${finalValue}`,
param: finalParams,
};
}
else if (equality) {
return {
str: `${fieldName} ${sqlEqualityParser(equality)} ${finalValue}`,
param: finalParams,
};
}
else {
return {
str: `${fieldName} = ${finalValue}`,
param: finalParams,
};
}
}
else {
if (equality == "IS NULL") {
return { str: `${fieldName} IS NULL` };
}
else if (equality == "IS NOT NULL") {
return { str: `${fieldName} IS NOT NULL` };
}
else if (equality) {
return {
str: `${fieldName} ${sqlEqualityParser(equality)} ?`,
param: value,
};
}
else {
return {
str: `${fieldName} = ?`,
param: value,
};
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import type { ServerQueryParamsJoin, ServerQueryParamsJoinMatchObject, SQLInsertGenValueType } from "../types";
type Param = {
mtch: ServerQueryParamsJoinMatchObject;
join: ServerQueryParamsJoin;
table_name: string;
};
export default function sqlGenGenJoinStr({ join, mtch, table_name }: Param): {
str: string;
values: SQLInsertGenValueType[];
};
export {};
+65
View File
@@ -0,0 +1,65 @@
export default function sqlGenGenJoinStr({ join, mtch, table_name }) {
let values = [];
if (mtch.__batch) {
let btch_mtch = ``;
btch_mtch += `(`;
for (let i = 0; i < mtch.__batch.matches.length; i++) {
const __mtch = mtch.__batch.matches[i];
const { str, values: batch_values } = sqlGenGenJoinStr({
join,
mtch: __mtch,
table_name,
});
btch_mtch += str;
values.push(...batch_values);
if (i < mtch.__batch.matches.length - 1) {
btch_mtch += ` ${mtch.__batch.operator || "OR"} `;
}
}
btch_mtch += `)`;
return {
str: btch_mtch,
values,
};
}
const equality = mtch.raw_equality || "=";
const lhs = `${typeof mtch.source == "object" ? mtch.source.tableName : table_name}.${typeof mtch.source == "object" ? mtch.source.fieldName : mtch.source}`;
const rhs = `${(() => {
if (mtch.targetLiteral) {
values.push(mtch.targetLiteral);
// if (typeof mtch.targetLiteral == "number") {
// return `${mtch.targetLiteral}`;
// }
// return `'${mtch.targetLiteral}'`;
return `?`;
}
if (join.alias) {
return `${typeof mtch.target == "object"
? mtch.target.tableName
: join.alias}.${typeof mtch.target == "object"
? mtch.target.fieldName
: mtch.target}`;
}
return `${typeof mtch.target == "object"
? mtch.target.tableName
: join.tableName}.${typeof mtch.target == "object" ? mtch.target.fieldName : mtch.target}`;
})()}`;
if (mtch.between) {
values.push(mtch.between.min, mtch.between.max);
return {
str: `${lhs} BETWEEN ? AND ?`,
values,
};
}
if (mtch.not_between) {
values.push(mtch.not_between.min, mtch.not_between.max);
return {
str: `${lhs} NOT BETWEEN ? AND ?`,
values,
};
}
return {
str: `${lhs} ${equality} ${rhs}`,
values,
};
}
+22
View File
@@ -0,0 +1,22 @@
import type { ServerQueryParam, TableSelectFieldsObject } from "../types";
type Param<T extends {
[key: string]: any;
} = {
[key: string]: any;
}> = {
genObject?: ServerQueryParam<T>;
selectFields?: (keyof T | TableSelectFieldsObject<T>)[];
append_table_names?: boolean;
table_name: string;
full_text_match_str?: string;
full_text_search_str?: string;
};
export default function sqlGenGenQueryStr<T extends {
[key: string]: any;
} = {
[key: string]: any;
}>(params: Param<T>): {
str: string;
values: any[];
};
export {};
+193
View File
@@ -0,0 +1,193 @@
import { isUndefined } from "lodash";
import sqlGenGrabConcatStr from "./sql-generator-grab-concat-str";
import sqlGenGenJoinStr from "./sql-generator-gen-join-str";
import sqlGenGrabSelectFieldSQL from "./sql-generator-grab-select-field-sql";
export default function sqlGenGenQueryStr(params) {
let str = "SELECT";
const genObject = params.genObject;
const table_name = params.table_name;
const full_text_match_str = params.full_text_match_str;
const full_text_search_str = params.full_text_search_str;
let sqlSearhValues = [];
if (genObject?.select_sql) {
str += ` ${genObject.select_sql}`;
}
else if (genObject?.selectFields?.[0]) {
if (genObject.join) {
str += sqlGenGrabSelectFieldSQL({
selectFields: genObject.selectFields,
append_table_names: true,
table_name,
});
}
else {
str += sqlGenGrabSelectFieldSQL({
selectFields: genObject.selectFields,
table_name,
});
}
}
else {
if (genObject?.join) {
str += ` ${table_name}.*`;
}
else {
str += " *";
}
}
if (genObject?.countSubQueries) {
let countSqls = [];
for (let i = 0; i < genObject.countSubQueries.length; i++) {
const countSubQuery = genObject.countSubQueries[i];
if (!countSubQuery)
continue;
const tableAlias = countSubQuery.table_alias;
let subQStr = `(SELECT COUNT(*)`;
subQStr += ` FROM ${countSubQuery.table}${tableAlias ? ` ${tableAlias}` : ""}`;
subQStr += ` WHERE (`;
for (let j = 0; j < countSubQuery.srcTrgMap.length; j++) {
const csqSrc = countSubQuery.srcTrgMap[j];
if (!csqSrc)
continue;
subQStr += ` ${tableAlias || countSubQuery.table}.${csqSrc.src}`;
if (typeof csqSrc.trg == "string") {
subQStr += ` = ?`;
sqlSearhValues.push(csqSrc.trg);
}
else if (typeof csqSrc.trg == "object") {
subQStr += ` = ${csqSrc.trg.table}.${csqSrc.trg.field}`;
}
if (j < countSubQuery.srcTrgMap.length - 1) {
subQStr += ` AND `;
}
}
subQStr += ` )) AS ${countSubQuery.alias}`;
countSqls.push(subQStr);
}
str += `, ${countSqls.join(",")}`;
}
if (genObject?.join) {
const existingJoinTableNames = [table_name];
str +=
"," +
genObject.join
.flat()
.filter((j) => !isUndefined(j))
.map((joinObj) => {
const joinTableName = joinObj.alias
? joinObj.alias
: joinObj.tableName;
if (existingJoinTableNames.includes(joinTableName))
return null;
existingJoinTableNames.push(joinTableName);
if (joinObj.group_concat) {
return sqlGenGrabConcatStr({
field: `${joinTableName}.${joinObj.group_concat.field}`,
alias: joinObj.group_concat.alias,
separator: joinObj.group_concat.separator,
});
}
else if (joinObj.selectFields) {
return joinObj.selectFields
.map((selectField) => {
if (typeof selectField == "string") {
return `${joinTableName}.${selectField}`;
}
else if (typeof selectField == "object") {
let aliasSelectField = `${joinTableName}.${selectField.field}`;
if (selectField.count) {
aliasSelectField = `COUNT(${joinTableName}.${selectField.field})`;
}
else if (selectField.sum) {
aliasSelectField = `SUM(${selectField.distinct ? "DISTINCT " : ""}${joinTableName}.${selectField.field})`;
}
else if (selectField.average) {
aliasSelectField = `AVERAGE(${joinTableName}.${selectField.field})`;
}
else if (selectField.max) {
aliasSelectField = `MAX(${joinTableName}.${selectField.field})`;
}
else if (selectField.min) {
aliasSelectField = `MIN(${joinTableName}.${selectField.field})`;
}
else if (selectField.group_concat &&
selectField.alias) {
return sqlGenGrabConcatStr({
field: `${joinTableName}.${selectField.field}`,
alias: selectField.alias,
separator: selectField.group_concat
.separator,
distinct: selectField.group_concat
.distinct,
});
}
else if (selectField.distinct) {
aliasSelectField = `DISTINCT ${joinTableName}.${selectField.field}`;
}
if (selectField.alias)
aliasSelectField += ` AS ${selectField.alias}`;
return aliasSelectField;
}
})
.join(",");
}
else {
return `${joinTableName}.*`;
}
})
.filter((_) => Boolean(_))
.join(",");
}
if (genObject?.fullTextSearch &&
full_text_match_str &&
full_text_search_str) {
str += `, ${full_text_match_str} AS ${genObject.fullTextSearch.scoreAlias}`;
sqlSearhValues.push(full_text_search_str);
}
str += ` FROM ${table_name}`;
if (genObject?.join) {
str +=
" " +
genObject.join
.flat()
.filter((j) => !isUndefined(j))
.map((join) => {
return (join.joinType +
" " +
(join.alias
? `${join.tableName}` + " " + join.alias
: `${join.tableName}`) +
" ON " +
(() => {
if (Array.isArray(join.match)) {
return ("(" +
join.match
.map((mtch) => {
const { str, values } = sqlGenGenJoinStr({
mtch,
join,
table_name,
});
sqlSearhValues.push(...values);
return str;
})
.join(join.operator
? ` ${join.operator} `
: " AND ") +
")");
}
else if (typeof join.match == "object") {
const { str, values } = sqlGenGenJoinStr({
mtch: join.match,
join,
table_name,
});
sqlSearhValues.push(...values);
return str;
}
})());
})
.join(" ");
}
return { str, values: sqlSearhValues };
}
+12
View File
@@ -0,0 +1,12 @@
import type { ServerQueryParamsJoin, ServerQueryQueryObject, SQLInsertGenValueType } from "../types";
type Param = {
queryObj: ServerQueryQueryObject[string];
join?: (ServerQueryParamsJoin | ServerQueryParamsJoin[] | undefined)[];
field?: string;
table_name: string;
};
export default function sqlGenGenSearchStr({ queryObj, join, field, table_name, }: Param): {
str: string;
values: SQLInsertGenValueType[];
};
export {};
+92
View File
@@ -0,0 +1,92 @@
import sqlGenOperatorGen from "./sql-gen-operator-gen";
export default function sqlGenGenSearchStr({ queryObj, join, field, table_name, }) {
let sqlSearhValues = [];
const finalFieldName = (() => {
if (queryObj?.tableName) {
return `${queryObj.tableName}.${field}`;
}
if (join) {
return `${table_name}.${field}`;
}
return field;
})();
let str = `${finalFieldName}=?`;
function grabValue(val) {
const valueParsed = val;
if (!valueParsed)
return;
const valueString = typeof valueParsed == "string" || typeof valueParsed == "number"
? valueParsed
: valueParsed
? valueParsed.fieldName && valueParsed.tableName
? `${valueParsed.tableName}.${valueParsed.fieldName}`
: valueParsed.value
: undefined;
const valueEquality = typeof valueParsed == "object"
? valueParsed.equality || queryObj.equality
: queryObj.equality;
const operatorStrParam = sqlGenOperatorGen({
queryObj,
equality: valueEquality,
fieldName: finalFieldName || "",
value: valueString || "",
isValueFieldValue: Boolean(typeof valueParsed == "object" &&
valueParsed.fieldName &&
valueParsed.tableName),
});
return operatorStrParam;
}
if (Array.isArray(queryObj.value)) {
const strArray = [];
queryObj.value.forEach((val) => {
const operatorStrParam = grabValue(val);
if (!operatorStrParam)
return;
if (operatorStrParam.str && operatorStrParam.param) {
strArray.push(operatorStrParam.str);
sqlSearhValues.push(operatorStrParam.param);
}
else if (operatorStrParam.str) {
strArray.push(operatorStrParam.str);
}
});
str = "(" + strArray.join(` ${queryObj.operator || "AND"} `) + ")";
}
else if (typeof queryObj.value == "object") {
const operatorStrParam = grabValue(queryObj.value);
if (operatorStrParam?.str) {
str = operatorStrParam.str;
if (operatorStrParam.param) {
sqlSearhValues.push(operatorStrParam.param);
}
}
}
else if (queryObj.raw_equality && queryObj.value) {
str = `${finalFieldName} ${queryObj.raw_equality} ?`;
sqlSearhValues.push(queryObj.value);
}
else if (queryObj.between) {
str = `${finalFieldName} BETWEEN ? AND ?`;
sqlSearhValues.push(queryObj.between.min, queryObj.between.max);
}
else {
const valueParsed = queryObj.value ? queryObj.value : undefined;
const operatorStrParam = sqlGenOperatorGen({
equality: queryObj.equality,
fieldName: finalFieldName || "",
value: valueParsed,
queryObj,
});
if (operatorStrParam.str && operatorStrParam.param) {
str = operatorStrParam.str;
sqlSearhValues.push(operatorStrParam.param);
}
else if (operatorStrParam.str && !operatorStrParam.str.match(/\?/)) {
str = operatorStrParam.str;
}
else {
sqlSearhValues.push(valueParsed || "");
}
}
return { str, values: sqlSearhValues };
}
+8
View File
@@ -0,0 +1,8 @@
type Param = {
field: string;
alias: string;
separator?: string;
distinct?: boolean;
};
export default function sqlGenGrabConcatStr({ alias, field, separator, distinct, }: Param): string;
export {};
+13
View File
@@ -0,0 +1,13 @@
export default function sqlGenGrabConcatStr({ alias, field, separator = ",", distinct, }) {
let gc = `GROUP_CONCAT(`;
if (distinct) {
gc += `DISTINCT `;
}
gc += `${field}`;
if (!distinct) {
gc += `, '${separator}'`;
}
gc += `)`;
gc += ` AS ${alias}`;
return gc;
}
+16
View File
@@ -0,0 +1,16 @@
import type { TableSelectFieldsObject } from "../types";
type Param<T extends {
[key: string]: any;
} = {
[key: string]: any;
}> = {
selectFields: (keyof T | TableSelectFieldsObject<T>)[];
append_table_names?: boolean;
table_name: string;
};
export default function sqlGenGrabSelectFieldSQL<T extends {
[key: string]: any;
} = {
[key: string]: any;
}>({ selectFields, append_table_names, table_name }: Param<T>): string;
export {};
+55
View File
@@ -0,0 +1,55 @@
import sqlGenGrabConcatStr from "./sql-generator-grab-concat-str";
export default function sqlGenGrabSelectFieldSQL({ selectFields, append_table_names, table_name }) {
let str = "";
str += ` ${selectFields
?.map((fld) => {
let fld_str = ``;
const final_fld_name = typeof fld == "object"
? append_table_names
? `${table_name}.${String(fld)}`
: `${String(fld.fieldName)}`
: `${String(fld)}`;
if (typeof fld == "object") {
const fld_name = `${String(fld.fieldName)}`;
if (fld.count) {
fld_str += `COUNT(${fld_name})`;
}
else if (fld.sum) {
fld_str += `SUM(${fld_name})`;
}
else if (fld.average) {
fld_str += `AVERAGE(${fld_name})`;
}
else if (fld.max) {
fld_str += `MAX(${fld_name})`;
}
else if (fld.min) {
fld_str += `MIN(${fld_name})`;
}
else if (fld.distinct) {
fld_str += `DISTINCT ${fld_name}`;
}
else if (fld.group_concat) {
fld_str += sqlGenGrabConcatStr({
field: fld_name,
alias: fld.group_concat.alias,
separator: fld.group_concat.separator,
distinct: fld.group_concat.distinct,
});
}
else {
fld_str +=
final_fld_name + (fld.alias ? ` as ${fld.alias}` : ``);
}
if (fld.alias) {
fld_str += ` AS ${fld.alias}`;
}
}
else {
fld_str += final_fld_name;
}
return fld_str;
})
.join(",")}`;
return str;
}
+25
View File
@@ -0,0 +1,25 @@
import type { ServerQueryParam, SQLInsertGenValueType } from "../types";
type Param<T extends {
[key: string]: any;
} = {
[key: string]: any;
}> = {
genObject?: ServerQueryParam<T>;
tableName: string;
dbFullName?: string;
count?: boolean;
};
type Return = {
string: string;
values: SQLInsertGenValueType[];
};
/**
* # SQL Query Generator
* @description Builds parameterized SELECT SQL for MariaDB
*/
export default function sqlGenerator<T extends {
[key: string]: any;
} = {
[key: string]: any;
}>({ tableName, genObject, dbFullName, count }: Param<T>): Return;
export {};
+303
View File
@@ -0,0 +1,303 @@
import sqlGenGenSearchStr from "./sql-generator-gen-search-str";
import sqlGenGenQueryStr from "./sql-generator-gen-query-str";
/**
* # SQL Query Generator
* @description Builds parameterized SELECT SQL for MariaDB
*/
export default function sqlGenerator({ tableName, genObject, dbFullName, count }) {
const finalQuery = genObject?.query ? genObject.query : undefined;
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
const sqlSearhValues = [];
let fullTextMatchStr = genObject?.fullTextSearch
? ` MATCH(${genObject.fullTextSearch.fields
.map((f) => genObject.join ? `${tableName}.${String(f)}` : `${String(f)}`)
.join(",")}) AGAINST (? IN BOOLEAN MODE)`
: undefined;
const fullTextSearchStr = genObject?.fullTextSearch
? genObject.fullTextSearch.searchTerm
.split(` `)
.map((t) => `${t}`)
.join(" ")
: undefined;
let { str: queryString, values } = sqlGenGenQueryStr({
table_name: tableName,
append_table_names: true,
full_text_match_str: fullTextMatchStr,
full_text_search_str: fullTextSearchStr,
genObject,
});
sqlSearhValues.push(...values);
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,
});
sqlSearhValues.push(...values);
return str;
}
});
return ("(" +
subSearchString.join(` ${queryObj.operator || "AND"} `) +
")");
}
const { str, values } = sqlGenGenSearchStr({
queryObj,
field: queryObj.fieldName || field,
join: genObject?.join,
table_name: tableName,
});
sqlSearhValues.push(...values);
return str;
});
const cleanedUpSearchStr = sqlSearhString?.filter((str) => typeof str == "string");
const isSearchStr = cleanedUpSearchStr?.[0] && cleanedUpSearchStr.find((str) => str);
if (isSearchStr) {
const stringOperator = genObject?.searchOperator || "AND";
queryString += ` WHERE ${cleanedUpSearchStr.join(` ${stringOperator} `)}`;
}
if (genObject?.fullTextSearch && fullTextSearchStr && fullTextMatchStr) {
queryString += `${isSearchStr ? " AND" : " WHERE"} ${fullTextMatchStr}`;
sqlSearhValues.push(fullTextSearchStr);
}
if (genObject?.group) {
let group_by_txt = ``;
if (typeof genObject.group == "string") {
group_by_txt = genObject.group;
}
else if (Array.isArray(genObject.group)) {
for (let i = 0; i < genObject.group.length; i++) {
const group = genObject.group[i];
if (typeof group == "string") {
group_by_txt += `\`${group.toString()}\``;
}
else if (typeof group == "object" && group.table) {
group_by_txt += `${group.table}.${String(group.field)}`;
}
else if (typeof group == "object") {
group_by_txt += `${String(group.field)}`;
}
if (i < genObject.group.length - 1) {
group_by_txt += ",";
}
}
}
else if (typeof genObject.group == "object") {
if (genObject.group.table) {
group_by_txt = `${genObject.group.table}.${String(genObject.group.field)}`;
}
else {
group_by_txt = `${String(genObject.group.field)}`;
}
}
queryString += ` GROUP BY ${group_by_txt}`;
}
function grabOrderString(order) {
let orderFields = [];
let orderSrt = ``;
if (genObject?.fullTextSearch && genObject.fullTextSearch.scoreAlias) {
orderFields.push(genObject.fullTextSearch.scoreAlias);
}
else if (genObject?.join) {
orderFields.push(`${tableName}.${String(order.field)}`);
}
else {
orderFields.push(order.field);
}
orderSrt += ` ${orderFields.join(", ")} ${order.strategy}`;
return orderSrt;
}
if (genObject?.order) {
let orderSrt = ` ORDER BY`;
if (Array.isArray(genObject.order)) {
for (let i = 0; i < genObject.order.length; i++) {
const order = genObject.order[i];
if (order) {
orderSrt +=
grabOrderString(order) +
(i < genObject.order.length - 1 ? `,` : "");
}
}
}
else {
orderSrt += grabOrderString(genObject.order);
}
queryString += ` ${orderSrt}`;
}
if (genObject?.limit && !count)
queryString += ` LIMIT ${genObject.limit}`;
if (genObject?.offset) {
queryString += ` OFFSET ${genObject.offset}`;
}
else if (genObject?.page && genObject.limit && !count) {
queryString += ` OFFSET ${(genObject.page - 1) * genObject.limit}`;
}
return {
string: queryString,
values: sqlSearhValues,
};
}
// let queryString = (() => {
// let str = "SELECT";
// if (genObject?.select_sql) {
// str += ` ${genObject.select_sql}`;
// } else if (genObject?.selectFields?.[0]) {
// if (genObject.join) {
// str += sqlGenGrabSelectFieldSQL<T>({
// selectFields: genObject.selectFields,
// append_table_names: true,
// table_name: tableName,
// });
// } else {
// str += sqlGenGrabSelectFieldSQL({
// selectFields: genObject.selectFields,
// table_name: tableName,
// });
// }
// } else {
// if (genObject?.join) {
// str += ` ${tableName}.*`;
// } else {
// str += " *";
// }
// }
// if (genObject?.countSubQueries) {
// let countSqls: string[] = [];
// for (let i = 0; i < genObject.countSubQueries.length; i++) {
// const countSubQuery = genObject.countSubQueries[i];
// if (!countSubQuery) continue;
// const tableAlias = countSubQuery.table_alias;
// let subQStr = `(SELECT COUNT(*)`;
// subQStr += ` FROM ${countSubQuery.table}${
// tableAlias ? ` ${tableAlias}` : ""
// }`;
// subQStr += ` WHERE (`;
// for (let j = 0; j < countSubQuery.srcTrgMap.length; j++) {
// const csqSrc = countSubQuery.srcTrgMap[j];
// if (!csqSrc) continue;
// subQStr += ` ${tableAlias || countSubQuery.table}.${
// csqSrc.src
// }`;
// if (typeof csqSrc.trg == "string") {
// subQStr += ` = ?`;
// sqlSearhValues.push(csqSrc.trg);
// } else if (typeof csqSrc.trg == "object") {
// subQStr += ` = ${csqSrc.trg.table}.${csqSrc.trg.field}`;
// }
// if (j < countSubQuery.srcTrgMap.length - 1) {
// subQStr += ` AND `;
// }
// }
// subQStr += ` )) AS ${countSubQuery.alias}`;
// countSqls.push(subQStr);
// }
// str += `, ${countSqls.join(",")}`;
// }
// if (genObject?.join) {
// const existingJoinTableNames: string[] = [tableName];
// str +=
// "," +
// genObject.join
// .flat()
// .filter((j) => !isUndefined(j))
// .map((joinObj) => {
// const joinTableName = joinObj.alias
// ? joinObj.alias
// : joinObj.tableName;
// if (existingJoinTableNames.includes(joinTableName))
// return null;
// existingJoinTableNames.push(joinTableName);
// if (joinObj.group_concat) {
// return sqlGenGrabConcatStr({
// field: `${joinTableName}.${joinObj.group_concat.field}`,
// alias: joinObj.group_concat.alias,
// separator: joinObj.group_concat.separator,
// });
// } else if (joinObj.selectFields) {
// return joinObj.selectFields
// .map((selectField) => {
// if (typeof selectField == "string") {
// return `${joinTableName}.${selectField}`;
// } else if (typeof selectField == "object") {
// let aliasSelectField = selectField.count
// ? `COUNT(${joinTableName}.${selectField.field})`
// : `${joinTableName}.${selectField.field}`;
// if (selectField.alias)
// aliasSelectField += ` AS ${selectField.alias}`;
// return aliasSelectField;
// }
// })
// .join(",");
// } else {
// return `${joinTableName}.*`;
// }
// })
// .filter((_) => Boolean(_))
// .join(",");
// }
// if (
// genObject?.fullTextSearch &&
// fullTextMatchStr &&
// fullTextSearchStr
// ) {
// str += `, ${fullTextMatchStr} AS ${genObject.fullTextSearch.scoreAlias}`;
// sqlSearhValues.push(fullTextSearchStr);
// }
// str += ` FROM ${tableName}`;
// if (genObject?.join) {
// str +=
// " " +
// genObject.join
// .flat()
// .filter((j) => !isUndefined(j))
// .map((join) => {
// return (
// join.joinType +
// " " +
// (join.alias
// ? `${join.tableName}` + " " + join.alias
// : `${join.tableName}`) +
// " ON " +
// (() => {
// if (Array.isArray(join.match)) {
// return (
// "(" +
// join.match
// .map((mtch) =>
// sqlGenGenJoinStr({
// mtch,
// join,
// table_name: tableName,
// }),
// )
// .join(
// join.operator
// ? ` ${join.operator} `
// : " AND ",
// ) +
// ")"
// );
// } else if (typeof join.match == "object") {
// return sqlGenGenJoinStr({
// mtch: join.match,
// join,
// table_name: tableName,
// });
// }
// })()
// );
// })
// .join(" ");
// }
// return str;
// })();
+5
View File
@@ -0,0 +1,5 @@
import type { SQLInsertGenParams, SQLInsertGenReturn } from "../types";
/**
* # SQL Insert Generator
*/
export default function sqlInsertGenerator({ tableName, data, dbFullName, }: SQLInsertGenParams): SQLInsertGenReturn | undefined;
+62
View File
@@ -0,0 +1,62 @@
function quoteIdentifier(identifier) {
return `\`${identifier.replace(/`/g, "``")}\``;
}
/**
* # SQL Insert Generator
*/
export default function sqlInsertGenerator({ tableName, data, dbFullName, }) {
const finalDbName = dbFullName ? `${quoteIdentifier(dbFullName)}.` : "";
try {
if (Array.isArray(data) && data?.[0]) {
let insertKeys = [];
data.forEach((dt) => {
const kys = Object.keys(dt);
kys.forEach((ky) => {
if (!insertKeys.includes(ky)) {
insertKeys.push(ky);
}
});
});
let queryBatches = [];
let queryValues = [];
data.forEach((item) => {
queryBatches.push(`(${insertKeys
.map((ky) => {
const value = item[ky];
const finalValue = typeof value == "string" ||
typeof value == "number"
? value
: typeof value == "function"
? value().value
: value
? value
: null;
if (!finalValue) {
queryValues.push(null);
return "?";
}
queryValues.push(finalValue);
const placeholder = typeof value == "function"
? value().placeholder
: "?";
return placeholder;
})
.filter((k) => Boolean(k))
.join(",")})`);
});
const insertColumns = insertKeys.map(quoteIdentifier).join(",");
let query = `INSERT INTO ${finalDbName}${quoteIdentifier(tableName)} (${insertColumns}) VALUES ${queryBatches.join(",")}`;
return {
query: query,
values: queryValues,
};
}
else {
return undefined;
}
}
catch ( /** @type {any} */error) {
console.log(`SQL insert gen ERROR: ${error.message}`);
return undefined;
}
}
+6
View File
@@ -0,0 +1,6 @@
import type { BunMariaDBConfig } from "../types";
type Params = {
config: BunMariaDBConfig;
};
export default function trimBackups({ config }: Params): void;
export {};
+19
View File
@@ -0,0 +1,19 @@
import grabDBDir from "../utils/grab-db-dir";
import fs from "fs";
import grabSortedBackups from "./grab-sorted-backups";
import { AppData } from "../data/app-data";
import path from "path";
export default function trimBackups({ config }) {
const { backup_dir } = grabDBDir({ config });
const backups = grabSortedBackups({ config });
const max_backups = config.max_backups || AppData["MaxBackups"];
for (let i = 0; i < backups.length; i++) {
const backup_name = backups[i];
if (!backup_name)
continue;
if (i > max_backups - 1) {
const backup_file_to_unlink = path.join(backup_dir, backup_name);
fs.unlinkSync(backup_file_to_unlink);
}
}
}
+6
View File
@@ -0,0 +1,6 @@
import type { BunMariaDBConfig } from "../types";
type Params = {
config: BunMariaDBConfig;
};
export default function trimExports({ config }: Params): void;
export {};
+18
View File
@@ -0,0 +1,18 @@
import fs from "fs";
import path from "path";
import { AppData } from "../data/app-data";
import grabDBDir from "./grab-db-dir";
import grabSortedExports from "./grab-sorted-exports";
export default function trimExports({ config }) {
const { export_dir } = grabDBDir({ config });
const exports = grabSortedExports({ config });
const max_exports = config.max_exports || AppData["MaxExports"];
for (let i = 0; i < exports.length; i++) {
const export_name = exports[i];
if (!export_name)
continue;
if (i > max_exports - 1) {
fs.unlinkSync(path.join(export_dir, export_name));
}
}
}