First stable version
This commit is contained in:
parent
7bbd179fa4
commit
3a4ba2ca6f
55
dist/commands/backup.js
vendored
55
dist/commands/backup.js
vendored
@ -1,22 +1,37 @@
|
||||
import { Command } from "commander";
|
||||
import init from "../functions/init";
|
||||
import path from "path";
|
||||
import grabDBDir from "../utils/grab-db-dir";
|
||||
import fs from "fs";
|
||||
import grabDBBackupFileName from "../utils/grab-db-backup-file-name";
|
||||
import chalk from "chalk";
|
||||
import trimBackups from "../utils/trim-backups";
|
||||
export default function () {
|
||||
return new Command("backup")
|
||||
.description("Backup Database")
|
||||
.action(async (opts) => {
|
||||
console.log(`Backing up database ...`);
|
||||
const { config } = await init();
|
||||
const { backup_dir, db_file_path } = grabDBDir({ config });
|
||||
const new_db_file_name = grabDBBackupFileName({ config });
|
||||
fs.cpSync(db_file_path, path.join(backup_dir, new_db_file_name));
|
||||
trimBackups({ config });
|
||||
console.log(`${chalk.bold(chalk.green(`DB Backup Success!`))}`);
|
||||
process.exit();
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const commander_1 = require("commander");
|
||||
const init_1 = __importDefault(require("../functions/init"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_db_dir_1 = __importDefault(require("../utils/grab-db-dir"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_db_backup_file_name_1 = __importDefault(require("../utils/grab-db-backup-file-name"));
|
||||
const chalk_1 = __importDefault(require("chalk"));
|
||||
const trim_backups_1 = __importDefault(require("../utils/trim-backups"));
|
||||
function default_1() {
|
||||
return new commander_1.Command("backup")
|
||||
.description("Backup Database")
|
||||
.action((opts) => __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Backing up database ...`);
|
||||
const { config } = yield (0, init_1.default)();
|
||||
const { backup_dir, db_file_path } = (0, grab_db_dir_1.default)({ config });
|
||||
const new_db_file_name = (0, grab_db_backup_file_name_1.default)({ config });
|
||||
fs_1.default.cpSync(db_file_path, path_1.default.join(backup_dir, new_db_file_name));
|
||||
(0, trim_backups_1.default)({ config });
|
||||
console.log(`${chalk_1.default.bold(chalk_1.default.green(`DB Backup Success!`))}`);
|
||||
process.exit();
|
||||
}));
|
||||
}
|
||||
|
||||
31
dist/commands/index.js
vendored
31
dist/commands/index.js
vendored
@ -1,31 +1,36 @@
|
||||
#!/usr/bin/env bun
|
||||
import { program } from "commander";
|
||||
import schema from "./schema";
|
||||
import typedef from "./typedef";
|
||||
import backup from "./backup";
|
||||
import restore from "./restore";
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const commander_1 = require("commander");
|
||||
const schema_1 = __importDefault(require("./schema"));
|
||||
const typedef_1 = __importDefault(require("./typedef"));
|
||||
const backup_1 = __importDefault(require("./backup"));
|
||||
const restore_1 = __importDefault(require("./restore"));
|
||||
/**
|
||||
* # Describe Program
|
||||
*/
|
||||
program
|
||||
commander_1.program
|
||||
.name(`bun-sqlite`)
|
||||
.description(`SQLite manager for Bun`)
|
||||
.version(`1.0.0`);
|
||||
/**
|
||||
* # Declare Commands
|
||||
*/
|
||||
program.addCommand(schema());
|
||||
program.addCommand(typedef());
|
||||
program.addCommand(backup());
|
||||
program.addCommand(restore());
|
||||
commander_1.program.addCommand((0, schema_1.default)());
|
||||
commander_1.program.addCommand((0, typedef_1.default)());
|
||||
commander_1.program.addCommand((0, backup_1.default)());
|
||||
commander_1.program.addCommand((0, restore_1.default)());
|
||||
/**
|
||||
* # Handle Unavailable Commands
|
||||
*/
|
||||
program.on("command:*", () => {
|
||||
console.error("Invalid command: %s\nSee --help for a list of available commands.", program.args.join(" "));
|
||||
commander_1.program.on("command:*", () => {
|
||||
console.error("Invalid command: %s\nSee --help for a list of available commands.", commander_1.program.args.join(" "));
|
||||
process.exit(1);
|
||||
});
|
||||
/**
|
||||
* # Parse Arguments
|
||||
*/
|
||||
program.parse(Bun.argv);
|
||||
commander_1.program.parse(process.argv);
|
||||
|
||||
57
dist/commands/restore.js
vendored
57
dist/commands/restore.js
vendored
@ -1,29 +1,44 @@
|
||||
import { Command } from "commander";
|
||||
import init from "../functions/init";
|
||||
import grabDBDir from "../utils/grab-db-dir";
|
||||
import fs from "fs";
|
||||
import chalk from "chalk";
|
||||
import grabSortedBackups from "../utils/grab-sorted-backups";
|
||||
import { select } from "@inquirer/prompts";
|
||||
import grabBackupData from "../utils/grab-backup-data";
|
||||
import path from "path";
|
||||
export default function () {
|
||||
return new Command("restore")
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const commander_1 = require("commander");
|
||||
const init_1 = __importDefault(require("../functions/init"));
|
||||
const grab_db_dir_1 = __importDefault(require("../utils/grab-db-dir"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const chalk_1 = __importDefault(require("chalk"));
|
||||
const grab_sorted_backups_1 = __importDefault(require("../utils/grab-sorted-backups"));
|
||||
const prompts_1 = require("@inquirer/prompts");
|
||||
const grab_backup_data_1 = __importDefault(require("../utils/grab-backup-data"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
function default_1() {
|
||||
return new commander_1.Command("restore")
|
||||
.description("Restore Database")
|
||||
.action(async (opts) => {
|
||||
.action((opts) => __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Restoring up database ...`);
|
||||
const { config } = await init();
|
||||
const { backup_dir, db_file_path } = grabDBDir({ config });
|
||||
const backups = grabSortedBackups({ config });
|
||||
if (!backups?.[0]) {
|
||||
const { config } = yield (0, init_1.default)();
|
||||
const { backup_dir, db_file_path } = (0, grab_db_dir_1.default)({ config });
|
||||
const backups = (0, grab_sorted_backups_1.default)({ config });
|
||||
if (!(backups === null || backups === void 0 ? void 0 : backups[0])) {
|
||||
console.error(`No Backups to restore. Use the \`backup\` command to create a backup`);
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
const selected_backup = await select({
|
||||
const selected_backup = yield (0, prompts_1.select)({
|
||||
message: "Select a backup:",
|
||||
choices: backups.map((b, i) => {
|
||||
const { backup_date } = grabBackupData({
|
||||
const { backup_date } = (0, grab_backup_data_1.default)({
|
||||
backup_name: b,
|
||||
});
|
||||
return {
|
||||
@ -32,13 +47,13 @@ export default function () {
|
||||
};
|
||||
}),
|
||||
});
|
||||
fs.cpSync(path.join(backup_dir, selected_backup), db_file_path);
|
||||
console.log(`${chalk.bold(chalk.green(`DB Restore Success!`))}`);
|
||||
fs_1.default.cpSync(path_1.default.join(backup_dir, selected_backup), db_file_path);
|
||||
console.log(`${chalk_1.default.bold(chalk_1.default.green(`DB Restore Success!`))}`);
|
||||
process.exit();
|
||||
}
|
||||
catch (error) {
|
||||
console.error(`Backup Restore ERROR => ${error.message}`);
|
||||
process.exit();
|
||||
}
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
56
dist/commands/schema.js
vendored
56
dist/commands/schema.js
vendored
@ -1,38 +1,52 @@
|
||||
import { Command } from "commander";
|
||||
import { SQLiteSchemaManager } from "../lib/sqlite/db-schema-manager";
|
||||
import init from "../functions/init";
|
||||
import grabDirNames from "../data/grab-dir-names";
|
||||
import path from "path";
|
||||
import dbSchemaToTypeDef from "../lib/sqlite/schema-to-typedef";
|
||||
import _ from "lodash";
|
||||
import appendDefaultFieldsToDbSchema from "../utils/append-default-fields-to-db-schema";
|
||||
import chalk from "chalk";
|
||||
export default function () {
|
||||
return new Command("schema")
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const commander_1 = require("commander");
|
||||
const db_schema_manager_1 = require("../lib/sqlite/db-schema-manager");
|
||||
const init_1 = __importDefault(require("../functions/init"));
|
||||
const grab_dir_names_1 = __importDefault(require("../data/grab-dir-names"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const schema_to_typedef_1 = __importDefault(require("../lib/sqlite/schema-to-typedef"));
|
||||
const append_default_fields_to_db_schema_1 = __importDefault(require("../utils/append-default-fields-to-db-schema"));
|
||||
const chalk_1 = __importDefault(require("chalk"));
|
||||
function default_1() {
|
||||
return new commander_1.Command("schema")
|
||||
.description("Build DB From Schema")
|
||||
.option("-v, --vector", "Recreate Vector Tables. This will drop and rebuild all vector tables")
|
||||
.option("-t, --typedef", "Generate typescript type definitions")
|
||||
.action(async (opts) => {
|
||||
.action((opts) => __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Starting process ...`);
|
||||
const { config, dbSchema } = await init();
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
const { config, dbSchema } = yield (0, init_1.default)();
|
||||
const { ROOT_DIR } = (0, grab_dir_names_1.default)();
|
||||
const isVector = Boolean(opts.vector || opts.v);
|
||||
const isTypeDef = Boolean(opts.typedef || opts.t);
|
||||
const finaldbSchema = appendDefaultFieldsToDbSchema({ dbSchema });
|
||||
const manager = new SQLiteSchemaManager({
|
||||
const finaldbSchema = (0, append_default_fields_to_db_schema_1.default)({ dbSchema });
|
||||
const manager = new db_schema_manager_1.SQLiteSchemaManager({
|
||||
schema: finaldbSchema,
|
||||
recreate_vector_table: isVector,
|
||||
});
|
||||
await manager.syncSchema();
|
||||
yield manager.syncSchema();
|
||||
manager.close();
|
||||
if (isTypeDef && config.typedef_file_path) {
|
||||
const out_file = path.resolve(ROOT_DIR, config.typedef_file_path);
|
||||
dbSchemaToTypeDef({
|
||||
const out_file = path_1.default.resolve(ROOT_DIR, config.typedef_file_path);
|
||||
(0, schema_to_typedef_1.default)({
|
||||
dbSchema: finaldbSchema,
|
||||
dst_file: out_file,
|
||||
});
|
||||
}
|
||||
console.log(`${chalk.bold(chalk.green(`DB Schema setup success!`))}`);
|
||||
console.log(`${chalk_1.default.bold(chalk_1.default.green(`DB Schema setup success!`))}`);
|
||||
process.exit();
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
49
dist/commands/typedef.js
vendored
49
dist/commands/typedef.js
vendored
@ -1,21 +1,36 @@
|
||||
import { Command } from "commander";
|
||||
import init from "../functions/init";
|
||||
import dbSchemaToTypeDef from "../lib/sqlite/schema-to-typedef";
|
||||
import path from "path";
|
||||
import grabDirNames from "../data/grab-dir-names";
|
||||
import appendDefaultFieldsToDbSchema from "../utils/append-default-fields-to-db-schema";
|
||||
import chalk from "chalk";
|
||||
export default function () {
|
||||
return new Command("typedef")
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const commander_1 = require("commander");
|
||||
const init_1 = __importDefault(require("../functions/init"));
|
||||
const schema_to_typedef_1 = __importDefault(require("../lib/sqlite/schema-to-typedef"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_dir_names_1 = __importDefault(require("../data/grab-dir-names"));
|
||||
const append_default_fields_to_db_schema_1 = __importDefault(require("../utils/append-default-fields-to-db-schema"));
|
||||
const chalk_1 = __importDefault(require("chalk"));
|
||||
function default_1() {
|
||||
return new commander_1.Command("typedef")
|
||||
.description("Build DB From Schema")
|
||||
.action(async (opts) => {
|
||||
.action((opts) => __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Creating Type Definition From DB Schema ...`);
|
||||
const { config, dbSchema } = await init();
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
const finaldbSchema = appendDefaultFieldsToDbSchema({ dbSchema });
|
||||
const { config, dbSchema } = yield (0, init_1.default)();
|
||||
const { ROOT_DIR } = (0, grab_dir_names_1.default)();
|
||||
const finaldbSchema = (0, append_default_fields_to_db_schema_1.default)({ dbSchema });
|
||||
if (config.typedef_file_path) {
|
||||
const out_file = path.resolve(ROOT_DIR, config.typedef_file_path);
|
||||
dbSchemaToTypeDef({
|
||||
const out_file = path_1.default.resolve(ROOT_DIR, config.typedef_file_path);
|
||||
(0, schema_to_typedef_1.default)({
|
||||
dbSchema: finaldbSchema,
|
||||
dst_file: out_file,
|
||||
});
|
||||
@ -24,7 +39,7 @@ export default function () {
|
||||
console.error(``);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`${chalk.bold(chalk.green(`Typedef gen success!`))}`);
|
||||
console.log(`${chalk_1.default.bold(chalk_1.default.green(`Typedef gen success!`))}`);
|
||||
process.exit();
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
5
dist/data/app-data.js
vendored
5
dist/data/app-data.js
vendored
@ -1,4 +1,7 @@
|
||||
export const AppData = {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AppData = void 0;
|
||||
exports.AppData = {
|
||||
ConfigFileName: "bun-sqlite.config.ts",
|
||||
MaxBackups: 10,
|
||||
DefaultBackupDirName: ".backups",
|
||||
|
||||
6
dist/data/grab-dir-names.js
vendored
6
dist/data/grab-dir-names.js
vendored
@ -1,5 +1,7 @@
|
||||
import path from "path";
|
||||
export default function grabDirNames() {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabDirNames;
|
||||
function grabDirNames() {
|
||||
const ROOT_DIR = process.cwd();
|
||||
return {
|
||||
ROOT_DIR,
|
||||
|
||||
2
dist/functions/init.d.ts
vendored
2
dist/functions/init.d.ts
vendored
@ -1,2 +1,2 @@
|
||||
import type { BunSQLiteConfigReturn } from "../types";
|
||||
export default function init(): Promise<BunSQLiteConfigReturn>;
|
||||
export default function init(): BunSQLiteConfigReturn;
|
||||
|
||||
44
dist/functions/init.js
vendored
44
dist/functions/init.js
vendored
@ -1,18 +1,24 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import { AppData } from "../data/app-data";
|
||||
import grabDirNames from "../data/grab-dir-names";
|
||||
export default async function init() {
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = init;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const app_data_1 = require("../data/app-data");
|
||||
const grab_dir_names_1 = __importDefault(require("../data/grab-dir-names"));
|
||||
function init() {
|
||||
try {
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
const { ConfigFileName } = AppData;
|
||||
const ConfigFilePath = path.join(ROOT_DIR, ConfigFileName);
|
||||
if (!fs.existsSync(ConfigFilePath)) {
|
||||
const { ROOT_DIR } = (0, grab_dir_names_1.default)();
|
||||
const { ConfigFileName } = app_data_1.AppData;
|
||||
const ConfigFilePath = path_1.default.join(ROOT_DIR, ConfigFileName);
|
||||
if (!fs_1.default.existsSync(ConfigFilePath)) {
|
||||
console.log("ConfigFilePath", ConfigFilePath);
|
||||
console.error(`Please create a \`${ConfigFileName}\` file at the root of your project.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const ConfigImport = await import(ConfigFilePath);
|
||||
const ConfigImport = require(ConfigFilePath);
|
||||
const Config = ConfigImport["default"];
|
||||
if (!Config.db_name) {
|
||||
console.error(`\`db_name\` is required in your config`);
|
||||
@ -24,18 +30,18 @@ export default async function init() {
|
||||
}
|
||||
let db_dir = ROOT_DIR;
|
||||
if (Config.db_dir) {
|
||||
db_dir = path.resolve(ROOT_DIR, Config.db_dir);
|
||||
if (!fs.existsSync(Config.db_dir)) {
|
||||
fs.mkdirSync(Config.db_dir, { recursive: true });
|
||||
db_dir = path_1.default.resolve(ROOT_DIR, Config.db_dir);
|
||||
if (!fs_1.default.existsSync(Config.db_dir)) {
|
||||
fs_1.default.mkdirSync(Config.db_dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
const DBSchemaFilePath = path.join(db_dir, Config.db_schema_file_name);
|
||||
const DbSchemaImport = await import(DBSchemaFilePath);
|
||||
const DBSchemaFilePath = path_1.default.join(db_dir, Config.db_schema_file_name);
|
||||
const DbSchemaImport = require(DBSchemaFilePath);
|
||||
const DbSchema = DbSchemaImport["default"];
|
||||
const backup_dir = Config.db_backup_dir || AppData["DefaultBackupDirName"];
|
||||
const BackupDir = path.resolve(db_dir, backup_dir);
|
||||
if (!fs.existsSync(BackupDir)) {
|
||||
fs.mkdirSync(BackupDir, { recursive: true });
|
||||
const backup_dir = Config.db_backup_dir || app_data_1.AppData["DefaultBackupDirName"];
|
||||
const BackupDir = path_1.default.resolve(db_dir, backup_dir);
|
||||
if (!fs_1.default.existsSync(BackupDir)) {
|
||||
fs_1.default.mkdirSync(BackupDir, { recursive: true });
|
||||
}
|
||||
return { config: Config, dbSchema: DbSchema };
|
||||
}
|
||||
|
||||
4
dist/index.d.ts
vendored
4
dist/index.d.ts
vendored
@ -3,11 +3,11 @@ import DbInsert from "./lib/sqlite/db-insert";
|
||||
import DbSelect from "./lib/sqlite/db-select";
|
||||
import DbSQL from "./lib/sqlite/db-sql";
|
||||
import DbUpdate from "./lib/sqlite/db-update";
|
||||
declare const BunSQLite: {
|
||||
declare const NodeSQLite: {
|
||||
readonly select: typeof DbSelect;
|
||||
readonly insert: typeof DbInsert;
|
||||
readonly update: typeof DbUpdate;
|
||||
readonly delete: typeof DbDelete;
|
||||
readonly sql: typeof DbSQL;
|
||||
};
|
||||
export default BunSQLite;
|
||||
export default NodeSQLite;
|
||||
|
||||
29
dist/index.js
vendored
29
dist/index.js
vendored
@ -1,13 +1,18 @@
|
||||
import DbDelete from "./lib/sqlite/db-delete";
|
||||
import DbInsert from "./lib/sqlite/db-insert";
|
||||
import DbSelect from "./lib/sqlite/db-select";
|
||||
import DbSQL from "./lib/sqlite/db-sql";
|
||||
import DbUpdate from "./lib/sqlite/db-update";
|
||||
const BunSQLite = {
|
||||
select: DbSelect,
|
||||
insert: DbInsert,
|
||||
update: DbUpdate,
|
||||
delete: DbDelete,
|
||||
sql: DbSQL,
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
export default BunSQLite;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const db_delete_1 = __importDefault(require("./lib/sqlite/db-delete"));
|
||||
const db_insert_1 = __importDefault(require("./lib/sqlite/db-insert"));
|
||||
const db_select_1 = __importDefault(require("./lib/sqlite/db-select"));
|
||||
const db_sql_1 = __importDefault(require("./lib/sqlite/db-sql"));
|
||||
const db_update_1 = __importDefault(require("./lib/sqlite/db-update"));
|
||||
const NodeSQLite = {
|
||||
select: db_select_1.default,
|
||||
insert: db_insert_1.default,
|
||||
update: db_update_1.default,
|
||||
delete: db_delete_1.default,
|
||||
sql: db_sql_1.default,
|
||||
};
|
||||
exports.default = NodeSQLite;
|
||||
|
||||
100
dist/lib/sqlite/db-delete.js
vendored
100
dist/lib/sqlite/db-delete.js
vendored
@ -1,49 +1,67 @@
|
||||
import DbClient from ".";
|
||||
import _ from "lodash";
|
||||
import sqlGenerator from "../../utils/sql-generator";
|
||||
export default async function DbDelete({ table, query, targetId, }) {
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = _.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: String(targetId),
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = DbDelete;
|
||||
const _1 = __importDefault(require("."));
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const sql_generator_1 = __importDefault(require("../../utils/sql-generator"));
|
||||
function DbDelete(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ table, query, targetId, }) {
|
||||
var _b;
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = lodash_1.default.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: String(targetId),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const sqlQueryObj = (0, sql_generator_1.default)({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
});
|
||||
const whereClause = (_b = sqlQueryObj.string.match(/WHERE .*/)) === null || _b === void 0 ? void 0 : _b[0];
|
||||
if (whereClause) {
|
||||
let sql = `DELETE FROM ${table} ${whereClause}`;
|
||||
const res = _1.default.prepare(sql).run(...sqlQueryObj.values);
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sql,
|
||||
values: sqlQueryObj.values,
|
||||
},
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No WHERE clause`,
|
||||
};
|
||||
}
|
||||
}
|
||||
const sqlQueryObj = sqlGenerator({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
});
|
||||
const whereClause = sqlQueryObj.string.match(/WHERE .*/)?.[0];
|
||||
if (whereClause) {
|
||||
let sql = `DELETE FROM ${table} ${whereClause}`;
|
||||
const res = DbClient.run(sql, sqlQueryObj.values);
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sql,
|
||||
values: sqlQueryObj.values,
|
||||
},
|
||||
};
|
||||
}
|
||||
else {
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No WHERE clause`,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
27
dist/lib/sqlite/db-generate-type-defs.js
vendored
27
dist/lib/sqlite/db-generate-type-defs.js
vendored
@ -1,4 +1,7 @@
|
||||
export default function generateTypeDefinition({ paradigm, table, query, typeDefName, allValuesOptional, addExport, dbName, }) {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = generateTypeDefinition;
|
||||
function generateTypeDefinition({ paradigm, table, query, typeDefName, allValuesOptional, addExport, dbName, }) {
|
||||
let typeDefinition = ``;
|
||||
let tdName = ``;
|
||||
try {
|
||||
@ -9,21 +12,25 @@ export default function generateTypeDefinition({ paradigm, table, query, typeDef
|
||||
: `BUN_SQLITE_${query.single}_${query.single_table}`.toUpperCase();
|
||||
const fields = table.fields;
|
||||
function typeMap(schemaType) {
|
||||
var _a, _b, _c;
|
||||
if (schemaType.options && schemaType.options.length > 0) {
|
||||
return schemaType.options
|
||||
.map((opt) => schemaType.dataType?.match(/int/i) ||
|
||||
typeof opt == "number"
|
||||
? `${opt}`
|
||||
: `"${opt}"`)
|
||||
.map((opt) => {
|
||||
var _a;
|
||||
return ((_a = schemaType.dataType) === null || _a === void 0 ? void 0 : _a.match(/int/i)) ||
|
||||
typeof opt == "number"
|
||||
? `${opt}`
|
||||
: `"${opt}"`;
|
||||
})
|
||||
.join(" | ");
|
||||
}
|
||||
if (schemaType.dataType?.match(/int|double|decimal/i)) {
|
||||
if ((_a = schemaType.dataType) === null || _a === void 0 ? void 0 : _a.match(/int|double|decimal/i)) {
|
||||
return "number";
|
||||
}
|
||||
if (schemaType.dataType?.match(/text|varchar|timestamp/i)) {
|
||||
if ((_b = schemaType.dataType) === null || _b === void 0 ? void 0 : _b.match(/text|varchar|timestamp/i)) {
|
||||
return "string";
|
||||
}
|
||||
if (schemaType.dataType?.match(/boolean/i)) {
|
||||
if ((_c = schemaType.dataType) === null || _c === void 0 ? void 0 : _c.match(/boolean/i)) {
|
||||
return "0 | 1";
|
||||
}
|
||||
return "string";
|
||||
@ -46,10 +53,10 @@ export default function generateTypeDefinition({ paradigm, table, query, typeDef
|
||||
});
|
||||
typesArrayTypeScript.push(`}`);
|
||||
typesArrayJavascript.push(` */`);
|
||||
if (paradigm?.match(/javascript/i)) {
|
||||
if (paradigm === null || paradigm === void 0 ? void 0 : paradigm.match(/javascript/i)) {
|
||||
typeDefinition = typesArrayJavascript.join("\n");
|
||||
}
|
||||
if (paradigm?.match(/typescript/i)) {
|
||||
if (paradigm === null || paradigm === void 0 ? void 0 : paradigm.match(/typescript/i)) {
|
||||
typeDefinition = typesArrayTypeScript.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
75
dist/lib/sqlite/db-insert.js
vendored
75
dist/lib/sqlite/db-insert.js
vendored
@ -1,32 +1,45 @@
|
||||
import DbClient from ".";
|
||||
import sqlInsertGenerator from "../../utils/sql-insert-generator";
|
||||
export default async function DbInsert({ table, data }) {
|
||||
try {
|
||||
const finalData = data.map((d) => ({
|
||||
...d,
|
||||
created_at: Date.now(),
|
||||
updated_at: Date.now(),
|
||||
}));
|
||||
const sqlObj = sqlInsertGenerator({
|
||||
tableName: table,
|
||||
data: finalData,
|
||||
});
|
||||
const res = DbClient.run(sqlObj?.query || "", sqlObj?.values || []);
|
||||
return {
|
||||
success: Boolean(Number(res.lastInsertRowid)),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = DbInsert;
|
||||
const _1 = __importDefault(require("."));
|
||||
const sql_insert_generator_1 = __importDefault(require("../../utils/sql-insert-generator"));
|
||||
function DbInsert(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ table, data }) {
|
||||
try {
|
||||
const finalData = data.map((d) => (Object.assign(Object.assign({}, d), { created_at: Date.now(), updated_at: Date.now() })));
|
||||
const sqlObj = (0, sql_insert_generator_1.default)({
|
||||
tableName: table,
|
||||
data: finalData,
|
||||
});
|
||||
const res = _1.default.prepare((sqlObj === null || sqlObj === void 0 ? void 0 : sqlObj.query) || "").run(...((sqlObj === null || sqlObj === void 0 ? void 0 : sqlObj.values) || []));
|
||||
return {
|
||||
success: Boolean(Number(res.lastInsertRowid)),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
569
dist/lib/sqlite/db-schema-manager.js
vendored
569
dist/lib/sqlite/db-schema-manager.js
vendored
@ -1,23 +1,33 @@
|
||||
#!/usr/bin/env bun
|
||||
import { Database } from "bun:sqlite";
|
||||
import _ from "lodash";
|
||||
import DbClient from ".";
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SQLiteSchemaManager = void 0;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const _1 = __importDefault(require("."));
|
||||
// Schema Manager Class
|
||||
class SQLiteSchemaManager {
|
||||
db;
|
||||
db_manager_table_name;
|
||||
recreate_vector_table;
|
||||
db_schema;
|
||||
constructor({ schema, recreate_vector_table = false, }) {
|
||||
this.db = DbClient;
|
||||
this.db = _1.default;
|
||||
this.db_manager_table_name = "__db_schema_manager__";
|
||||
this.db.run("PRAGMA foreign_keys = ON;");
|
||||
this.db.exec("PRAGMA foreign_keys = ON;");
|
||||
this.recreate_vector_table = recreate_vector_table;
|
||||
this.createDbManagerTable();
|
||||
this.db_schema = schema;
|
||||
}
|
||||
createDbManagerTable() {
|
||||
this.db.run(`
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${this.db_manager_table_name} (
|
||||
table_name TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
@ -26,214 +36,234 @@ class SQLiteSchemaManager {
|
||||
`);
|
||||
}
|
||||
insertDbManagerTable(tableName) {
|
||||
this.db.run(`INSERT INTO ${this.db_manager_table_name} (table_name,created_at,updated_at) VALUES (?, ?, ?)`, [tableName, Date.now(), Date.now()]);
|
||||
this.db
|
||||
.prepare(`INSERT INTO ${this.db_manager_table_name} (table_name,created_at,updated_at) VALUES (?, ?, ?)`)
|
||||
.run(...[tableName, Date.now(), Date.now()]);
|
||||
}
|
||||
removeDbManagerTable(tableName) {
|
||||
this.db.run(`DELETE FROM ${this.db_manager_table_name} WHERE table_name = ?`, [tableName]);
|
||||
this.db
|
||||
.prepare(`DELETE FROM ${this.db_manager_table_name} WHERE table_name = ?`)
|
||||
.run(...[tableName]);
|
||||
}
|
||||
/**
|
||||
* Main synchronization method
|
||||
*/
|
||||
async syncSchema() {
|
||||
console.log("Starting schema synchronization...");
|
||||
const existingTables = this.getExistingTables();
|
||||
const schemaTables = this.db_schema.tables.map((t) => t.tableName);
|
||||
// 2. Create or update tables
|
||||
for (const table of this.db_schema.tables) {
|
||||
await this.syncTable(table, existingTables);
|
||||
}
|
||||
// 1. Drop tables that no longer exist in schema
|
||||
await this.dropRemovedTables(existingTables, schemaTables);
|
||||
console.log("Schema synchronization complete!");
|
||||
syncSchema() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
console.log("Starting schema synchronization...");
|
||||
const existingTables = this.getExistingTables();
|
||||
const schemaTables = this.db_schema.tables.map((t) => t.tableName);
|
||||
// 2. Create or update tables
|
||||
for (const table of this.db_schema.tables) {
|
||||
yield this.syncTable(table, existingTables);
|
||||
}
|
||||
// 1. Drop tables that no longer exist in schema
|
||||
yield this.dropRemovedTables(existingTables, schemaTables);
|
||||
console.log("Schema synchronization complete!");
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Get list of existing tables in the database
|
||||
*/
|
||||
getExistingTables() {
|
||||
let sql = `SELECT table_name FROM ${this.db_manager_table_name}`;
|
||||
const query = this.db.query(sql);
|
||||
const query = this.db.prepare(sql);
|
||||
const results = query.all();
|
||||
return results.map((r) => r.table_name);
|
||||
}
|
||||
/**
|
||||
* Drop tables that are no longer in the schema
|
||||
*/
|
||||
async dropRemovedTables(existingTables, schemaTables) {
|
||||
const tablesToDrop = existingTables.filter((t) => !schemaTables.includes(t) &&
|
||||
!schemaTables.find((scT) => t.startsWith(scT + "_")));
|
||||
for (const tableName of tablesToDrop) {
|
||||
console.log(`Dropping table: ${tableName}`);
|
||||
this.db.run(`DROP TABLE IF EXISTS "${tableName}"`);
|
||||
this.db.run(`DELETE FROM ${this.db_manager_table_name} WHERE table_name = "${tableName}"`);
|
||||
}
|
||||
dropRemovedTables(existingTables, schemaTables) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const tablesToDrop = existingTables.filter((t) => !schemaTables.includes(t) &&
|
||||
!schemaTables.find((scT) => t.startsWith(scT + "_")));
|
||||
for (const tableName of tablesToDrop) {
|
||||
console.log(`Dropping table: ${tableName}`);
|
||||
this.db.exec(`DROP TABLE IF EXISTS "${tableName}"`);
|
||||
this.db.exec(`DELETE FROM ${this.db_manager_table_name} WHERE table_name = "${tableName}"`);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Sync a single table (create or update)
|
||||
*/
|
||||
async syncTable(table, existingTables) {
|
||||
let tableExists = existingTables.includes(table.tableName);
|
||||
// Handle table rename
|
||||
if (table.tableNameOld && table.tableNameOld !== table.tableName) {
|
||||
if (existingTables.includes(table.tableNameOld)) {
|
||||
console.log(`Renaming table: ${table.tableNameOld} -> ${table.tableName}`);
|
||||
this.db.run(`ALTER TABLE "${table.tableNameOld}" RENAME TO "${table.tableName}"`);
|
||||
this.insertDbManagerTable(table.tableName);
|
||||
this.removeDbManagerTable(table.tableNameOld);
|
||||
tableExists = true;
|
||||
syncTable(table, existingTables) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let tableExists = existingTables.includes(table.tableName);
|
||||
// Handle table rename
|
||||
if (table.tableNameOld && table.tableNameOld !== table.tableName) {
|
||||
if (existingTables.includes(table.tableNameOld)) {
|
||||
console.log(`Renaming table: ${table.tableNameOld} -> ${table.tableName}`);
|
||||
this.db.exec(`ALTER TABLE "${table.tableNameOld}" RENAME TO "${table.tableName}"`);
|
||||
this.insertDbManagerTable(table.tableName);
|
||||
this.removeDbManagerTable(table.tableNameOld);
|
||||
tableExists = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!tableExists) {
|
||||
// Create new table
|
||||
await this.createTable(table);
|
||||
this.insertDbManagerTable(table.tableName);
|
||||
}
|
||||
else {
|
||||
// Update existing table
|
||||
await this.updateTable(table);
|
||||
}
|
||||
// Sync indexes
|
||||
await this.syncIndexes(table);
|
||||
if (!tableExists) {
|
||||
// Create new table
|
||||
yield this.createTable(table);
|
||||
this.insertDbManagerTable(table.tableName);
|
||||
}
|
||||
else {
|
||||
// Update existing table
|
||||
yield this.updateTable(table);
|
||||
}
|
||||
// Sync indexes
|
||||
yield this.syncIndexes(table);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Create a new table
|
||||
*/
|
||||
async createTable(table) {
|
||||
console.log(`Creating table: ${table.tableName}`);
|
||||
let new_table = _.cloneDeep(table);
|
||||
if (new_table.parentTableName) {
|
||||
const parent_table = this.db_schema.tables.find((t) => t.tableName === new_table.parentTableName);
|
||||
if (!parent_table) {
|
||||
throw new Error(`Parent table \`${new_table.parentTableName}\` not found for \`${new_table.tableName}\``);
|
||||
createTable(table) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Creating table: ${table.tableName}`);
|
||||
let new_table = lodash_1.default.cloneDeep(table);
|
||||
if (new_table.parentTableName) {
|
||||
const parent_table = this.db_schema.tables.find((t) => t.tableName === new_table.parentTableName);
|
||||
if (!parent_table) {
|
||||
throw new Error(`Parent table \`${new_table.parentTableName}\` not found for \`${new_table.tableName}\``);
|
||||
}
|
||||
new_table = lodash_1.default.merge(parent_table, {
|
||||
tableName: new_table.tableName,
|
||||
tableDescription: new_table.tableDescription,
|
||||
});
|
||||
}
|
||||
new_table = _.merge(parent_table, {
|
||||
tableName: new_table.tableName,
|
||||
tableDescription: new_table.tableDescription,
|
||||
});
|
||||
}
|
||||
const columns = [];
|
||||
const foreignKeys = [];
|
||||
for (const field of new_table.fields) {
|
||||
const columnDef = this.buildColumnDefinition(field);
|
||||
columns.push(columnDef);
|
||||
if (field.foreignKey) {
|
||||
foreignKeys.push(this.buildForeignKeyConstraint(field));
|
||||
}
|
||||
}
|
||||
// Add unique constraints
|
||||
if (new_table.uniqueConstraints) {
|
||||
for (const constraint of new_table.uniqueConstraints) {
|
||||
if (constraint.constraintTableFields &&
|
||||
constraint.constraintTableFields.length > 0) {
|
||||
const fields = constraint.constraintTableFields
|
||||
.map((f) => `"${f.value}"`)
|
||||
.join(", ");
|
||||
const constraintName = constraint.constraintName ||
|
||||
`unique_${fields.replace(/"/g, "")}`;
|
||||
columns.push(`CONSTRAINT "${constraintName}" UNIQUE (${fields})`);
|
||||
const columns = [];
|
||||
const foreignKeys = [];
|
||||
for (const field of new_table.fields) {
|
||||
const columnDef = this.buildColumnDefinition(field);
|
||||
columns.push(columnDef);
|
||||
if (field.foreignKey) {
|
||||
foreignKeys.push(this.buildForeignKeyConstraint(field));
|
||||
}
|
||||
}
|
||||
}
|
||||
const allConstraints = [...columns, ...foreignKeys];
|
||||
const sql = new_table.isVector
|
||||
? `CREATE VIRTUAL TABLE "${new_table.tableName}" USING ${new_table.vectorType || "vec0"}(${allConstraints.join(", ")})`
|
||||
: `CREATE TABLE "${new_table.tableName}" (${allConstraints.join(", ")})`;
|
||||
this.db.run(sql);
|
||||
// Add unique constraints
|
||||
if (new_table.uniqueConstraints) {
|
||||
for (const constraint of new_table.uniqueConstraints) {
|
||||
if (constraint.constraintTableFields &&
|
||||
constraint.constraintTableFields.length > 0) {
|
||||
const fields = constraint.constraintTableFields
|
||||
.map((f) => `"${f.value}"`)
|
||||
.join(", ");
|
||||
const constraintName = constraint.constraintName ||
|
||||
`unique_${fields.replace(/"/g, "")}`;
|
||||
columns.push(`CONSTRAINT "${constraintName}" UNIQUE (${fields})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const allConstraints = [...columns, ...foreignKeys];
|
||||
const sql = new_table.isVector
|
||||
? `CREATE VIRTUAL TABLE "${new_table.tableName}" USING ${new_table.vectorType || "vec0"}(${allConstraints.join(", ")})`
|
||||
: `CREATE TABLE "${new_table.tableName}" (${allConstraints.join(", ")})`;
|
||||
this.db.exec(sql);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Update an existing table
|
||||
*/
|
||||
async updateTable(table) {
|
||||
console.log(`Updating table: ${table.tableName}`);
|
||||
const existingColumns = this.getTableColumns(table.tableName);
|
||||
const schemaColumns = table.fields.map((f) => f.fieldName || "");
|
||||
// SQLite has limited ALTER TABLE support
|
||||
// We need to use the recreation strategy for complex changes
|
||||
const columnsToAdd = table.fields.filter((f) => f.fieldName &&
|
||||
!existingColumns.find((c) => c.name == f.fieldName && c.type == this.mapDataType(f)));
|
||||
const columnsToRemove = existingColumns.filter((c) => !schemaColumns.includes(c.name));
|
||||
const columnsToUpdate = table.fields.filter((f) => f.fieldName &&
|
||||
f.updatedField &&
|
||||
existingColumns.find((c) => c.name == f.fieldName && c.type == this.mapDataType(f)));
|
||||
// Simple case: only adding columns
|
||||
if (columnsToRemove.length === 0 && columnsToUpdate.length === 0) {
|
||||
for (const field of columnsToAdd) {
|
||||
await this.addColumn(table.tableName, field);
|
||||
updateTable(table) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Updating table: ${table.tableName}`);
|
||||
const existingColumns = this.getTableColumns(table.tableName);
|
||||
const schemaColumns = table.fields.map((f) => f.fieldName || "");
|
||||
// SQLite has limited ALTER TABLE support
|
||||
// We need to use the recreation strategy for complex changes
|
||||
const columnsToAdd = table.fields.filter((f) => f.fieldName &&
|
||||
!existingColumns.find((c) => c.name == f.fieldName && c.type == this.mapDataType(f)));
|
||||
const columnsToRemove = existingColumns.filter((c) => !schemaColumns.includes(c.name));
|
||||
const columnsToUpdate = table.fields.filter((f) => f.fieldName &&
|
||||
f.updatedField &&
|
||||
existingColumns.find((c) => c.name == f.fieldName && c.type == this.mapDataType(f)));
|
||||
// Simple case: only adding columns
|
||||
if (columnsToRemove.length === 0 && columnsToUpdate.length === 0) {
|
||||
for (const field of columnsToAdd) {
|
||||
yield this.addColumn(table.tableName, field);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Complex case: need to recreate table
|
||||
await this.recreateTable(table);
|
||||
}
|
||||
else {
|
||||
// Complex case: need to recreate table
|
||||
yield this.recreateTable(table);
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Get existing columns for a table
|
||||
*/
|
||||
getTableColumns(tableName) {
|
||||
const query = this.db.query(`PRAGMA table_info("${tableName}")`);
|
||||
const query = this.db.prepare(`PRAGMA table_info("${tableName}")`);
|
||||
const results = query.all();
|
||||
return results;
|
||||
}
|
||||
/**
|
||||
* Add a new column to existing table
|
||||
*/
|
||||
async addColumn(tableName, field) {
|
||||
console.log(`Adding column: ${tableName}.${field.fieldName}`);
|
||||
const columnDef = this.buildColumnDefinition(field);
|
||||
// Remove PRIMARY KEY and UNIQUE constraints for ALTER TABLE ADD COLUMN
|
||||
const cleanDef = columnDef
|
||||
.replace(/PRIMARY KEY/gi, "")
|
||||
.replace(/AUTOINCREMENT/gi, "")
|
||||
.replace(/UNIQUE/gi, "")
|
||||
.trim();
|
||||
const sql = `ALTER TABLE "${tableName}" ADD COLUMN ${cleanDef}`;
|
||||
this.db.run(sql);
|
||||
addColumn(tableName, field) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(`Adding column: ${tableName}.${field.fieldName}`);
|
||||
const columnDef = this.buildColumnDefinition(field);
|
||||
// Remove PRIMARY KEY and UNIQUE constraints for ALTER TABLE ADD COLUMN
|
||||
const cleanDef = columnDef
|
||||
.replace(/PRIMARY KEY/gi, "")
|
||||
.replace(/AUTOINCREMENT/gi, "")
|
||||
.replace(/UNIQUE/gi, "")
|
||||
.trim();
|
||||
const sql = `ALTER TABLE "${tableName}" ADD COLUMN ${cleanDef}`;
|
||||
this.db.exec(sql);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Recreate table (for complex schema changes)
|
||||
*/
|
||||
async recreateTable(table) {
|
||||
if (table.isVector) {
|
||||
if (!this.recreate_vector_table) {
|
||||
recreateTable(table) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (table.isVector) {
|
||||
if (!this.recreate_vector_table) {
|
||||
return;
|
||||
}
|
||||
console.log(`Recreating vector table: ${table.tableName}`);
|
||||
const existingRows = this.db
|
||||
.prepare(`SELECT * FROM "${table.tableName}"`)
|
||||
.all();
|
||||
this.db.exec(`DROP TABLE "${table.tableName}"`);
|
||||
yield this.createTable(table);
|
||||
if (existingRows.length > 0) {
|
||||
for (let i = 0; i < existingRows.length; i++) {
|
||||
const row = existingRows[i];
|
||||
if (!row)
|
||||
continue;
|
||||
const columns = Object.keys(row);
|
||||
const placeholders = columns.map(() => "?").join(", ");
|
||||
this.db
|
||||
.prepare(`INSERT INTO "${table.tableName}" (${columns.join(", ")}) VALUES (${placeholders})`)
|
||||
.run(...Object.values(row));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
console.log(`Recreating vector table: ${table.tableName}`);
|
||||
const existingRows = this.db
|
||||
.query(`SELECT * FROM "${table.tableName}"`)
|
||||
.all();
|
||||
this.db.run(`DROP TABLE "${table.tableName}"`);
|
||||
await this.createTable(table);
|
||||
if (existingRows.length > 0) {
|
||||
for (let i = 0; i < existingRows.length; i++) {
|
||||
const row = existingRows[i];
|
||||
if (!row)
|
||||
continue;
|
||||
const columns = Object.keys(row);
|
||||
const placeholders = columns.map(() => "?").join(", ");
|
||||
this.db.run(`INSERT INTO "${table.tableName}" (${columns.join(", ")}) VALUES (${placeholders})`, Object.values(row));
|
||||
}
|
||||
const tempTableName = `${table.tableName}_temp_${Date.now()}`;
|
||||
// Get existing data
|
||||
const existingColumns = this.getTableColumns(table.tableName);
|
||||
const columnsToKeep = table.fields
|
||||
.filter((f) => f.fieldName &&
|
||||
existingColumns.find((c) => c.name == f.fieldName &&
|
||||
c.type == this.mapDataType(f)))
|
||||
.map((f) => f.fieldName);
|
||||
// Create temp table with new schema
|
||||
const tempTable = Object.assign(Object.assign({}, table), { tableName: tempTableName });
|
||||
yield this.createTable(tempTable);
|
||||
// Copy data if there are common columns
|
||||
if (columnsToKeep.length > 0) {
|
||||
const columnList = columnsToKeep.map((c) => `"${c}"`).join(", ");
|
||||
this.db.exec(`INSERT INTO "${tempTableName}" (${columnList}) SELECT ${columnList} FROM "${table.tableName}"`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const tempTableName = `${table.tableName}_temp_${Date.now()}`;
|
||||
// Get existing data
|
||||
const existingColumns = this.getTableColumns(table.tableName);
|
||||
const columnsToKeep = table.fields
|
||||
.filter((f) => f.fieldName &&
|
||||
existingColumns.find((c) => c.name == f.fieldName &&
|
||||
c.type == this.mapDataType(f)))
|
||||
.map((f) => f.fieldName);
|
||||
// Create temp table with new schema
|
||||
const tempTable = { ...table, tableName: tempTableName };
|
||||
await this.createTable(tempTable);
|
||||
// Copy data if there are common columns
|
||||
if (columnsToKeep.length > 0) {
|
||||
const columnList = columnsToKeep.map((c) => `"${c}"`).join(", ");
|
||||
this.db.run(`INSERT INTO "${tempTableName}" (${columnList}) SELECT ${columnList} FROM "${table.tableName}"`);
|
||||
}
|
||||
// Drop old table
|
||||
this.db.run(`DROP TABLE "${table.tableName}"`);
|
||||
// Rename temp table
|
||||
this.db.run(`ALTER TABLE "${tempTableName}" RENAME TO "${table.tableName}"`);
|
||||
// Drop old table
|
||||
this.db.exec(`DROP TABLE "${table.tableName}"`);
|
||||
// Rename temp table
|
||||
this.db.exec(`ALTER TABLE "${tempTableName}" RENAME TO "${table.tableName}"`);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Build column definition SQL
|
||||
@ -286,7 +316,8 @@ class SQLiteSchemaManager {
|
||||
* Map DSQL data types to SQLite types
|
||||
*/
|
||||
mapDataType(field) {
|
||||
const dataType = field.dataType?.toLowerCase() || "text";
|
||||
var _a;
|
||||
const dataType = ((_a = field.dataType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || "text";
|
||||
const vectorSize = field.vectorSize || 1536;
|
||||
// Vector Embeddings
|
||||
if (field.isVector) {
|
||||
@ -339,37 +370,39 @@ class SQLiteSchemaManager {
|
||||
/**
|
||||
* Sync indexes for a table
|
||||
*/
|
||||
async syncIndexes(table) {
|
||||
if (!table.indexes || table.indexes.length === 0) {
|
||||
return;
|
||||
}
|
||||
// Get existing indexes
|
||||
const query = this.db.query(`SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='${table.tableName}' AND name NOT LIKE 'sqlite_%'`);
|
||||
const existingIndexes = query.all().map((r) => r.name);
|
||||
// Drop indexes not in schema
|
||||
for (const indexName of existingIndexes) {
|
||||
const stillExists = table.indexes.some((idx) => idx.indexName === indexName);
|
||||
if (!stillExists) {
|
||||
console.log(`Dropping index: ${indexName}`);
|
||||
this.db.run(`DROP INDEX IF EXISTS "${indexName}"`);
|
||||
syncIndexes(table) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!table.indexes || table.indexes.length === 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Create new indexes
|
||||
for (const index of table.indexes) {
|
||||
if (!index.indexName ||
|
||||
!index.indexTableFields ||
|
||||
index.indexTableFields.length === 0) {
|
||||
continue;
|
||||
// Get existing indexes
|
||||
const query = this.db.prepare(`SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='${table.tableName}' AND name NOT LIKE 'sqlite_%'`);
|
||||
const existingIndexes = query.all().map((r) => r.name);
|
||||
// Drop indexes not in schema
|
||||
for (const indexName of existingIndexes) {
|
||||
const stillExists = table.indexes.some((idx) => idx.indexName === indexName);
|
||||
if (!stillExists) {
|
||||
console.log(`Dropping index: ${indexName}`);
|
||||
this.db.exec(`DROP INDEX IF EXISTS "${indexName}"`);
|
||||
}
|
||||
}
|
||||
if (!existingIndexes.includes(index.indexName)) {
|
||||
console.log(`Creating index: ${index.indexName}`);
|
||||
const fields = index.indexTableFields
|
||||
.map((f) => `"${f.value}"`)
|
||||
.join(", ");
|
||||
const unique = index.indexType === "regular" ? "" : ""; // SQLite doesn't have FULLTEXT in CREATE INDEX
|
||||
this.db.run(`CREATE ${unique}INDEX "${index.indexName}" ON "${table.tableName}" (${fields})`);
|
||||
// Create new indexes
|
||||
for (const index of table.indexes) {
|
||||
if (!index.indexName ||
|
||||
!index.indexTableFields ||
|
||||
index.indexTableFields.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (!existingIndexes.includes(index.indexName)) {
|
||||
console.log(`Creating index: ${index.indexName}`);
|
||||
const fields = index.indexTableFields
|
||||
.map((f) => `"${f.value}"`)
|
||||
.join(", ");
|
||||
const unique = index.indexType === "regular" ? "" : ""; // SQLite doesn't have FULLTEXT in CREATE INDEX
|
||||
this.db.exec(`CREATE ${unique}INDEX "${index.indexName}" ON "${table.tableName}" (${fields})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Close database connection
|
||||
@ -378,79 +411,81 @@ class SQLiteSchemaManager {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
exports.SQLiteSchemaManager = SQLiteSchemaManager;
|
||||
// Example usage
|
||||
async function main() {
|
||||
const schema = {
|
||||
dbName: "example_db",
|
||||
tables: [
|
||||
{
|
||||
tableName: "users",
|
||||
tableDescription: "User accounts",
|
||||
fields: [
|
||||
{
|
||||
fieldName: "id",
|
||||
dataType: "INTEGER",
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
{
|
||||
fieldName: "username",
|
||||
dataType: "TEXT",
|
||||
notNullValue: true,
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
fieldName: "email",
|
||||
dataType: "TEXT",
|
||||
notNullValue: true,
|
||||
},
|
||||
{
|
||||
fieldName: "created_at",
|
||||
dataType: "TEXT",
|
||||
defaultValueLiteral: "CURRENT_TIMESTAMP",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_users_email",
|
||||
indexType: "regular",
|
||||
indexTableFields: [
|
||||
{ value: "email", dataType: "TEXT" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "posts",
|
||||
fields: [
|
||||
{
|
||||
fieldName: "id",
|
||||
dataType: "INTEGER",
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
dataType: "INTEGER",
|
||||
notNullValue: true,
|
||||
foreignKey: {
|
||||
destinationTableName: "users",
|
||||
destinationTableColumnName: "id",
|
||||
cascadeDelete: true,
|
||||
function main() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const schema = {
|
||||
dbName: "example_db",
|
||||
tables: [
|
||||
{
|
||||
tableName: "users",
|
||||
tableDescription: "User accounts",
|
||||
fields: [
|
||||
{
|
||||
fieldName: "id",
|
||||
dataType: "INTEGER",
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "title",
|
||||
dataType: "TEXT",
|
||||
notNullValue: true,
|
||||
},
|
||||
{
|
||||
fieldName: "content",
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
{
|
||||
fieldName: "username",
|
||||
dataType: "TEXT",
|
||||
notNullValue: true,
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
fieldName: "email",
|
||||
dataType: "TEXT",
|
||||
notNullValue: true,
|
||||
},
|
||||
{
|
||||
fieldName: "created_at",
|
||||
dataType: "TEXT",
|
||||
defaultValueLiteral: "CURRENT_TIMESTAMP",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_users_email",
|
||||
indexType: "regular",
|
||||
indexTableFields: [
|
||||
{ value: "email", dataType: "TEXT" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "posts",
|
||||
fields: [
|
||||
{
|
||||
fieldName: "id",
|
||||
dataType: "INTEGER",
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
dataType: "INTEGER",
|
||||
notNullValue: true,
|
||||
foreignKey: {
|
||||
destinationTableName: "users",
|
||||
destinationTableColumnName: "id",
|
||||
cascadeDelete: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "title",
|
||||
dataType: "TEXT",
|
||||
notNullValue: true,
|
||||
},
|
||||
{
|
||||
fieldName: "content",
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
}
|
||||
export { SQLiteSchemaManager };
|
||||
|
||||
30
dist/lib/sqlite/db-schema-to-typedef.js
vendored
30
dist/lib/sqlite/db-schema-to-typedef.js
vendored
@ -1,43 +1,49 @@
|
||||
import _ from "lodash";
|
||||
import generateTypeDefinition from "./db-generate-type-defs";
|
||||
export default function dbSchemaToType(params) {
|
||||
let datasquirelSchema = params?.dbSchema;
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = dbSchemaToType;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const db_generate_type_defs_1 = __importDefault(require("./db-generate-type-defs"));
|
||||
function dbSchemaToType(params) {
|
||||
var _a;
|
||||
let datasquirelSchema = params === null || params === void 0 ? void 0 : params.dbSchema;
|
||||
if (!datasquirelSchema)
|
||||
return;
|
||||
let tableNames = `export const BunSQLiteTables = [\n${datasquirelSchema.tables
|
||||
.map((tbl) => ` "${tbl.tableName}",`)
|
||||
.join("\n")}\n] as const`;
|
||||
const dbTablesSchemas = datasquirelSchema.tables;
|
||||
const defDbName = datasquirelSchema.dbName
|
||||
?.toUpperCase()
|
||||
.replace(/ |\-/g, "_");
|
||||
const defDbName = (_a = datasquirelSchema.dbName) === null || _a === void 0 ? void 0 : _a.toUpperCase().replace(/ |\-/g, "_");
|
||||
const defNames = [];
|
||||
const schemas = dbTablesSchemas
|
||||
.map((table) => {
|
||||
let final_table = _.cloneDeep(table);
|
||||
var _a;
|
||||
let final_table = lodash_1.default.cloneDeep(table);
|
||||
if (final_table.parentTableName) {
|
||||
const parent_table = dbTablesSchemas.find((t) => t.tableName === final_table.parentTableName);
|
||||
if (parent_table) {
|
||||
final_table = _.merge(parent_table, {
|
||||
final_table = lodash_1.default.merge(parent_table, {
|
||||
tableName: final_table.tableName,
|
||||
tableDescription: final_table.tableDescription,
|
||||
});
|
||||
}
|
||||
}
|
||||
const defObj = generateTypeDefinition({
|
||||
const defObj = (0, db_generate_type_defs_1.default)({
|
||||
paradigm: "TypeScript",
|
||||
table: final_table,
|
||||
typeDefName: `BUN_SQLITE_${defDbName}_${final_table.tableName.toUpperCase()}`,
|
||||
allValuesOptional: true,
|
||||
addExport: true,
|
||||
});
|
||||
if (defObj.tdName?.match(/./)) {
|
||||
if ((_a = defObj.tdName) === null || _a === void 0 ? void 0 : _a.match(/./)) {
|
||||
defNames.push(defObj.tdName);
|
||||
}
|
||||
return defObj.typeDefinition;
|
||||
})
|
||||
.filter((schm) => typeof schm == "string");
|
||||
const allTd = defNames?.[0]
|
||||
const allTd = (defNames === null || defNames === void 0 ? void 0 : defNames[0])
|
||||
? `export type BUN_SQLITE_${defDbName}_ALL_TYPEDEFS = ${defNames.join(` & `)}`
|
||||
: ``;
|
||||
return [tableNames, ...schemas, allTd];
|
||||
|
||||
103
dist/lib/sqlite/db-select.js
vendored
103
dist/lib/sqlite/db-select.js
vendored
@ -1,48 +1,65 @@
|
||||
import mysql from "mysql";
|
||||
import DbClient from ".";
|
||||
import _ from "lodash";
|
||||
import sqlGenerator from "../../utils/sql-generator";
|
||||
export default async function DbSelect({ table, query, count, targetId, }) {
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = _.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: String(targetId),
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = DbSelect;
|
||||
const mysql_1 = __importDefault(require("mysql"));
|
||||
const _1 = __importDefault(require("."));
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const sql_generator_1 = __importDefault(require("../../utils/sql-generator"));
|
||||
function DbSelect(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ table, query, count, targetId, }) {
|
||||
var _b;
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = lodash_1.default.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: String(targetId),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const sqlObj = (0, sql_generator_1.default)({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
count,
|
||||
});
|
||||
const sql = mysql_1.default.format(sqlObj.string, sqlObj.values);
|
||||
const batchRes = _1.default.prepare(sql).all();
|
||||
let resp = {
|
||||
success: Boolean(batchRes[0]),
|
||||
payload: batchRes,
|
||||
singleRes: batchRes[0],
|
||||
debug: {
|
||||
sqlObj,
|
||||
sql,
|
||||
},
|
||||
};
|
||||
if (count) {
|
||||
const count_val = count ? (_b = batchRes[0]) === null || _b === void 0 ? void 0 : _b["COUNT(*)"] : undefined;
|
||||
resp["count"] = Number(count_val);
|
||||
delete resp.payload;
|
||||
delete resp.singleRes;
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
const sqlObj = sqlGenerator({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
count,
|
||||
});
|
||||
const sql = mysql.format(sqlObj.string, sqlObj.values);
|
||||
const res = DbClient.query(sql);
|
||||
const batchRes = res.all();
|
||||
let resp = {
|
||||
success: Boolean(batchRes[0]),
|
||||
payload: batchRes,
|
||||
singleRes: batchRes[0],
|
||||
debug: {
|
||||
sqlObj,
|
||||
sql,
|
||||
},
|
||||
};
|
||||
if (count) {
|
||||
const count_val = count ? batchRes[0]?.["COUNT(*)"] : undefined;
|
||||
resp["count"] = Number(count_val);
|
||||
delete resp.payload;
|
||||
delete resp.singleRes;
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
76
dist/lib/sqlite/db-sql.js
vendored
76
dist/lib/sqlite/db-sql.js
vendored
@ -1,33 +1,49 @@
|
||||
import DbClient from ".";
|
||||
import _ from "lodash";
|
||||
export default async function DbSQL({ sql, values }) {
|
||||
try {
|
||||
const res = sql.match(/^select/i)
|
||||
? DbClient.query(sql).all(...(values || []))
|
||||
: DbClient.run(sql, values || []);
|
||||
return {
|
||||
success: true,
|
||||
payload: Array.isArray(res) ? res : undefined,
|
||||
singleRes: Array.isArray(res) ? res?.[0] : undefined,
|
||||
postInsertReturn: Array.isArray(res)
|
||||
? undefined
|
||||
: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sqlObj: {
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = DbSQL;
|
||||
const _1 = __importDefault(require("."));
|
||||
function DbSQL(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ sql, values }) {
|
||||
try {
|
||||
const res = sql.match(/^select/i)
|
||||
? _1.default.prepare(sql).all(...(values || []))
|
||||
: _1.default.prepare(sql).run(...(values || []));
|
||||
return {
|
||||
success: true,
|
||||
payload: Array.isArray(res) ? res : undefined,
|
||||
singleRes: Array.isArray(res) ? res === null || res === void 0 ? void 0 : res[0] : undefined,
|
||||
postInsertReturn: Array.isArray(res)
|
||||
? undefined
|
||||
: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sqlObj: {
|
||||
sql,
|
||||
values,
|
||||
},
|
||||
sql,
|
||||
values,
|
||||
},
|
||||
sql,
|
||||
},
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
135
dist/lib/sqlite/db-update.js
vendored
135
dist/lib/sqlite/db-update.js
vendored
@ -1,68 +1,83 @@
|
||||
import DbClient from ".";
|
||||
import _ from "lodash";
|
||||
import sqlGenerator from "../../utils/sql-generator";
|
||||
export default async function DbUpdate({ table, data, query, targetId, }) {
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = _.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: String(targetId),
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = DbUpdate;
|
||||
const _1 = __importDefault(require("."));
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const sql_generator_1 = __importDefault(require("../../utils/sql-generator"));
|
||||
function DbUpdate(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ table, data, query, targetId, }) {
|
||||
var _b;
|
||||
try {
|
||||
let finalQuery = query || {};
|
||||
if (targetId) {
|
||||
finalQuery = lodash_1.default.merge(finalQuery, {
|
||||
query: {
|
||||
id: {
|
||||
value: String(targetId),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const sqlQueryObj = sqlGenerator({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
});
|
||||
let values = [];
|
||||
const whereClause = sqlQueryObj.string.match(/WHERE .*/)?.[0];
|
||||
if (whereClause) {
|
||||
let sql = `UPDATE ${table} SET`;
|
||||
const finalData = {
|
||||
...data,
|
||||
updated_at: Date.now(),
|
||||
};
|
||||
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 += ` ${key}=?`;
|
||||
values.push(String(finalData[key]));
|
||||
if (!isLast) {
|
||||
sql += `,`;
|
||||
}
|
||||
});
|
||||
}
|
||||
const sqlQueryObj = (0, sql_generator_1.default)({
|
||||
tableName: table,
|
||||
genObject: finalQuery,
|
||||
});
|
||||
let values = [];
|
||||
const whereClause = (_b = sqlQueryObj.string.match(/WHERE .*/)) === null || _b === void 0 ? void 0 : _b[0];
|
||||
if (whereClause) {
|
||||
let sql = `UPDATE ${table} SET`;
|
||||
const finalData = Object.assign(Object.assign({}, data), { updated_at: Date.now() });
|
||||
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 += ` ${key}=?`;
|
||||
values.push(String(finalData[key]));
|
||||
if (!isLast) {
|
||||
sql += `,`;
|
||||
}
|
||||
}
|
||||
sql += ` ${whereClause}`;
|
||||
values = [...values, ...sqlQueryObj.values];
|
||||
const res = _1.default.prepare(sql).run(...values);
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sql,
|
||||
values,
|
||||
},
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No WHERE clause`,
|
||||
};
|
||||
}
|
||||
sql += ` ${whereClause}`;
|
||||
values = [...values, ...sqlQueryObj.values];
|
||||
const res = DbClient.run(sql, values);
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sql,
|
||||
values,
|
||||
},
|
||||
};
|
||||
}
|
||||
else {
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No WHERE clause`,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
4
dist/lib/sqlite/index.d.ts
vendored
4
dist/lib/sqlite/index.d.ts
vendored
@ -1,3 +1,3 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
declare const DbClient: Database;
|
||||
import { type Database as DatabaseType } from "better-sqlite3";
|
||||
declare const DbClient: DatabaseType;
|
||||
export default DbClient;
|
||||
|
||||
60
dist/lib/sqlite/index.js
vendored
60
dist/lib/sqlite/index.js
vendored
@ -1,17 +1,55 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import * as sqliteVec from "sqlite-vec";
|
||||
import grabDirNames from "../../data/grab-dir-names";
|
||||
import init from "../../functions/init";
|
||||
import grabDBDir from "../../utils/grab-db-dir";
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
const { config } = await init();
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
|
||||
const sqliteVec = __importStar(require("sqlite-vec"));
|
||||
const grab_dir_names_1 = __importDefault(require("../../data/grab-dir-names"));
|
||||
const init_1 = __importDefault(require("../../functions/init"));
|
||||
const grab_db_dir_1 = __importDefault(require("../../utils/grab-db-dir"));
|
||||
const { ROOT_DIR } = (0, grab_dir_names_1.default)();
|
||||
const { config } = (0, init_1.default)();
|
||||
let db_dir = ROOT_DIR;
|
||||
if (config.db_dir) {
|
||||
db_dir = config.db_dir;
|
||||
}
|
||||
const { db_file_path } = grabDBDir({ config });
|
||||
const DbClient = new Database(db_file_path, {
|
||||
create: true,
|
||||
const { db_file_path } = (0, grab_db_dir_1.default)({ config });
|
||||
const DbClient = new better_sqlite3_1.default(db_file_path, {
|
||||
fileMustExist: false,
|
||||
});
|
||||
sqliteVec.load(DbClient);
|
||||
export default DbClient;
|
||||
exports.default = DbClient;
|
||||
|
||||
24
dist/lib/sqlite/schema-to-typedef.js
vendored
24
dist/lib/sqlite/schema-to-typedef.js
vendored
@ -1,16 +1,22 @@
|
||||
import path from "node:path";
|
||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import dbSchemaToType from "./db-schema-to-typedef";
|
||||
export default function dbSchemaToTypeDef({ dbSchema, dst_file }) {
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = dbSchemaToTypeDef;
|
||||
const node_path_1 = __importDefault(require("node:path"));
|
||||
const node_fs_1 = require("node:fs");
|
||||
const db_schema_to_typedef_1 = __importDefault(require("./db-schema-to-typedef"));
|
||||
function dbSchemaToTypeDef({ dbSchema, dst_file }) {
|
||||
try {
|
||||
if (!dbSchema)
|
||||
throw new Error("No schema found");
|
||||
const definitions = dbSchemaToType({ dbSchema });
|
||||
const ourfileDir = path.dirname(dst_file);
|
||||
if (!existsSync(ourfileDir)) {
|
||||
mkdirSync(ourfileDir, { recursive: true });
|
||||
const definitions = (0, db_schema_to_typedef_1.default)({ dbSchema });
|
||||
const ourfileDir = node_path_1.default.dirname(dst_file);
|
||||
if (!(0, node_fs_1.existsSync)(ourfileDir)) {
|
||||
(0, node_fs_1.mkdirSync)(ourfileDir, { recursive: true });
|
||||
}
|
||||
writeFileSync(dst_file, definitions?.join("\n\n") || "", "utf-8");
|
||||
(0, node_fs_1.writeFileSync)(dst_file, (definitions === null || definitions === void 0 ? void 0 : definitions.join("\n\n")) || "", "utf-8");
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Schema to Typedef Error =>`, error.message);
|
||||
|
||||
6
dist/lib/sqlite/schema.js
vendored
6
dist/lib/sqlite/schema.js
vendored
@ -1,5 +1,7 @@
|
||||
import _ from "lodash";
|
||||
export const DbSchema = {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DbSchema = void 0;
|
||||
exports.DbSchema = {
|
||||
dbName: "travis-ai",
|
||||
tables: [],
|
||||
};
|
||||
|
||||
29
dist/types/index.js
vendored
29
dist/types/index.js
vendored
@ -1,4 +1,7 @@
|
||||
export const UsersOmitedFields = [
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DefaultFields = exports.IndexTypes = exports.DockerComposeServices = exports.QueryFields = exports.DsqlCrudActions = exports.DataCrudRequestMethodsLowerCase = exports.DataCrudRequestMethods = exports.ServerQueryEqualities = exports.ServerQueryOperators = exports.BUN_SQLITE_DATATYPES = exports.TextFieldTypesArray = exports.MariaDBCollations = exports.UsersOmitedFields = void 0;
|
||||
exports.UsersOmitedFields = [
|
||||
"password",
|
||||
"social_id",
|
||||
"verification_status",
|
||||
@ -9,11 +12,11 @@ export const UsersOmitedFields = [
|
||||
"date_updated_code",
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
export const MariaDBCollations = [
|
||||
exports.MariaDBCollations = [
|
||||
"utf8mb4_bin",
|
||||
"utf8mb4_unicode_520_ci",
|
||||
];
|
||||
export const TextFieldTypesArray = [
|
||||
exports.TextFieldTypesArray = [
|
||||
{ title: "Plain Text", value: "plain" },
|
||||
{ title: "Rich Text", value: "richText" },
|
||||
{ title: "Markdown", value: "markdown" },
|
||||
@ -25,12 +28,12 @@ export const TextFieldTypesArray = [
|
||||
{ title: "Shell", value: "shell" },
|
||||
{ title: "Code", value: "code" },
|
||||
];
|
||||
export const BUN_SQLITE_DATATYPES = [
|
||||
exports.BUN_SQLITE_DATATYPES = [
|
||||
{ value: "TEXT" },
|
||||
{ value: "INTEGER" },
|
||||
];
|
||||
export const ServerQueryOperators = ["AND", "OR"];
|
||||
export const ServerQueryEqualities = [
|
||||
exports.ServerQueryOperators = ["AND", "OR"];
|
||||
exports.ServerQueryEqualities = [
|
||||
"EQUAL",
|
||||
"LIKE",
|
||||
"LIKE_RAW",
|
||||
@ -58,7 +61,7 @@ export const ServerQueryEqualities = [
|
||||
"MATCH",
|
||||
"MATCH_BOOLEAN",
|
||||
];
|
||||
export const DataCrudRequestMethods = [
|
||||
exports.DataCrudRequestMethods = [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
@ -66,7 +69,7 @@ export const DataCrudRequestMethods = [
|
||||
"DELETE",
|
||||
"OPTIONS",
|
||||
];
|
||||
export const DataCrudRequestMethodsLowerCase = [
|
||||
exports.DataCrudRequestMethodsLowerCase = [
|
||||
"get",
|
||||
"post",
|
||||
"put",
|
||||
@ -74,8 +77,8 @@ export const DataCrudRequestMethodsLowerCase = [
|
||||
"delete",
|
||||
"options",
|
||||
];
|
||||
export const DsqlCrudActions = ["insert", "update", "delete", "get"];
|
||||
export const QueryFields = [
|
||||
exports.DsqlCrudActions = ["insert", "update", "delete", "get"];
|
||||
exports.QueryFields = [
|
||||
"duplicate",
|
||||
"user_id",
|
||||
"delegated_user_id",
|
||||
@ -83,7 +86,7 @@ export const QueryFields = [
|
||||
"table_id",
|
||||
"db_slug",
|
||||
];
|
||||
export const DockerComposeServices = [
|
||||
exports.DockerComposeServices = [
|
||||
"setup",
|
||||
"cron",
|
||||
"reverse-proxy",
|
||||
@ -100,8 +103,8 @@ export const DockerComposeServices = [
|
||||
"db-cron",
|
||||
"web-app-post-db-setup",
|
||||
];
|
||||
export const IndexTypes = ["regular", "full_text", "vector"];
|
||||
export const DefaultFields = [
|
||||
exports.IndexTypes = ["regular", "full_text", "vector"];
|
||||
exports.DefaultFields = [
|
||||
{
|
||||
fieldName: "id",
|
||||
dataType: "INTEGER",
|
||||
|
||||
20
dist/utils/append-default-fields-to-db-schema.js
vendored
20
dist/utils/append-default-fields-to-db-schema.js
vendored
@ -1,11 +1,17 @@
|
||||
import _ from "lodash";
|
||||
import { DefaultFields } from "../types";
|
||||
export default function ({ dbSchema }) {
|
||||
const finaldbSchema = _.cloneDeep(dbSchema);
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const types_1 = require("../types");
|
||||
function default_1({ dbSchema }) {
|
||||
const finaldbSchema = lodash_1.default.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);
|
||||
const newTable = lodash_1.default.cloneDeep(t);
|
||||
newTable.fields = newTable.fields.filter((f) => { var _a; return !((_a = f.fieldName) === null || _a === void 0 ? void 0 : _a.match(/^(id|created_at|updated_at)$/)); });
|
||||
newTable.fields.unshift(...types_1.DefaultFields);
|
||||
return newTable;
|
||||
});
|
||||
return finaldbSchema;
|
||||
|
||||
5
dist/utils/grab-backup-data.js
vendored
5
dist/utils/grab-backup-data.js
vendored
@ -1,4 +1,7 @@
|
||||
export default function grabBackupData({ backup_name }) {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabBackupData;
|
||||
function grabBackupData({ backup_name }) {
|
||||
const backup_parts = backup_name.split("-");
|
||||
const backup_date_timestamp = Number(backup_parts.pop());
|
||||
const origin_backup_name = backup_parts.join("-");
|
||||
|
||||
5
dist/utils/grab-db-backup-file-name.js
vendored
5
dist/utils/grab-db-backup-file-name.js
vendored
@ -1,4 +1,7 @@
|
||||
export default function grabDBBackupFileName({ config }) {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabDBBackupFileName;
|
||||
function grabDBBackupFileName({ config }) {
|
||||
const new_db_file_name = `${config.db_name}-${Date.now()}`;
|
||||
return new_db_file_name;
|
||||
}
|
||||
|
||||
22
dist/utils/grab-db-dir.js
vendored
22
dist/utils/grab-db-dir.js
vendored
@ -1,14 +1,20 @@
|
||||
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();
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabDBDir;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_dir_names_1 = __importDefault(require("../data/grab-dir-names"));
|
||||
const app_data_1 = require("../data/app-data");
|
||||
function grabDBDir({ config }) {
|
||||
const { ROOT_DIR } = (0, grab_dir_names_1.default)();
|
||||
let db_dir = ROOT_DIR;
|
||||
if (config.db_dir) {
|
||||
db_dir = config.db_dir;
|
||||
}
|
||||
const backup_dir_name = config.db_backup_dir || AppData["DefaultBackupDirName"];
|
||||
const backup_dir = path.resolve(db_dir, backup_dir_name);
|
||||
const db_file_path = path.resolve(db_dir, config.db_name);
|
||||
const backup_dir_name = config.db_backup_dir || app_data_1.AppData["DefaultBackupDirName"];
|
||||
const backup_dir = path_1.default.resolve(db_dir, backup_dir_name);
|
||||
const db_file_path = path_1.default.resolve(db_dir, config.db_name);
|
||||
return { db_dir, backup_dir, db_file_path };
|
||||
}
|
||||
|
||||
16
dist/utils/grab-sorted-backups.js
vendored
16
dist/utils/grab-sorted-backups.js
vendored
@ -1,8 +1,14 @@
|
||||
import grabDBDir from "../utils/grab-db-dir";
|
||||
import fs from "fs";
|
||||
export default function grabSortedBackups({ config }) {
|
||||
const { backup_dir } = grabDBDir({ config });
|
||||
const backups = fs.readdirSync(backup_dir);
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabSortedBackups;
|
||||
const grab_db_dir_1 = __importDefault(require("../utils/grab-db-dir"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
function grabSortedBackups({ config }) {
|
||||
const { backup_dir } = (0, grab_db_dir_1.default)({ config });
|
||||
const backups = fs_1.default.readdirSync(backup_dir);
|
||||
/**
|
||||
* Order Backups. Most recent first.
|
||||
*/
|
||||
|
||||
6
dist/utils/sql-equality-parser.js
vendored
6
dist/utils/sql-equality-parser.js
vendored
@ -1,5 +1,7 @@
|
||||
import { ServerQueryEqualities } from "../types";
|
||||
export default function sqlEqualityParser(eq) {
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sqlEqualityParser;
|
||||
function sqlEqualityParser(eq) {
|
||||
switch (eq) {
|
||||
case "EQUAL":
|
||||
return "=";
|
||||
|
||||
14
dist/utils/sql-gen-operator-gen.js
vendored
14
dist/utils/sql-gen-operator-gen.js
vendored
@ -1,9 +1,15 @@
|
||||
import sqlEqualityParser from "./sql-equality-parser";
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sqlGenOperatorGen;
|
||||
const sql_equality_parser_1 = __importDefault(require("./sql-equality-parser"));
|
||||
/**
|
||||
* # SQL Gen Operator Gen
|
||||
* @description Generates an SQL operator for node module `mysql` or `serverless-mysql`
|
||||
*/
|
||||
export default function sqlGenOperatorGen({ fieldName, value, equality, queryObj, isValueFieldValue, }) {
|
||||
function sqlGenOperatorGen({ fieldName, value, equality, queryObj, isValueFieldValue, }) {
|
||||
if (queryObj.nullValue) {
|
||||
return { str: `${fieldName} IS NULL` };
|
||||
}
|
||||
@ -93,7 +99,7 @@ export default function sqlGenOperatorGen({ fieldName, value, equality, queryObj
|
||||
}
|
||||
else if (equality) {
|
||||
return {
|
||||
str: `${fieldName} ${sqlEqualityParser(equality)} ${finalValue}`,
|
||||
str: `${fieldName} ${(0, sql_equality_parser_1.default)(equality)} ${finalValue}`,
|
||||
param: finalParams,
|
||||
};
|
||||
}
|
||||
@ -113,7 +119,7 @@ export default function sqlGenOperatorGen({ fieldName, value, equality, queryObj
|
||||
}
|
||||
else if (equality) {
|
||||
return {
|
||||
str: `${fieldName} ${sqlEqualityParser(equality)} ?`,
|
||||
str: `${fieldName} ${(0, sql_equality_parser_1.default)(equality)} ?`,
|
||||
param: value,
|
||||
};
|
||||
}
|
||||
|
||||
90
dist/utils/sql-generator.js
vendored
90
dist/utils/sql-generator.js
vendored
@ -1,11 +1,17 @@
|
||||
import { isUndefined } from "lodash";
|
||||
import sqlGenOperatorGen from "./sql-gen-operator-gen";
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sqlGenerator;
|
||||
const lodash_1 = require("lodash");
|
||||
const sql_gen_operator_gen_1 = __importDefault(require("./sql-gen-operator-gen"));
|
||||
/**
|
||||
* # SQL Query Generator
|
||||
* @description Generates an SQL Query for node module `mysql` or `serverless-mysql`
|
||||
*/
|
||||
export default function sqlGenerator({ tableName, genObject, dbFullName, count }) {
|
||||
const finalQuery = genObject?.query ? genObject.query : undefined;
|
||||
function sqlGenerator({ tableName, genObject, dbFullName, count }) {
|
||||
const finalQuery = (genObject === null || genObject === void 0 ? void 0 : genObject.query) ? genObject.query : undefined;
|
||||
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
|
||||
const sqlSearhValues = [];
|
||||
const finalDbName = dbFullName ? `${dbFullName}.` : "";
|
||||
@ -14,7 +20,7 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
*/
|
||||
function genSqlSrchStr({ queryObj, join, field, }) {
|
||||
const finalFieldName = (() => {
|
||||
if (queryObj?.tableName) {
|
||||
if (queryObj === null || queryObj === void 0 ? void 0 : queryObj.tableName) {
|
||||
return `${finalDbName}${queryObj.tableName}.${field}`;
|
||||
}
|
||||
if (join) {
|
||||
@ -24,6 +30,7 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
})();
|
||||
let str = `${finalFieldName}=?`;
|
||||
function grabValue(val) {
|
||||
var _a;
|
||||
const valueParsed = val;
|
||||
if (!valueParsed)
|
||||
return;
|
||||
@ -32,16 +39,16 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
: valueParsed
|
||||
? valueParsed.fieldName && valueParsed.tableName
|
||||
? `${valueParsed.tableName}.${valueParsed.fieldName}`
|
||||
: valueParsed.value?.toString()
|
||||
: (_a = valueParsed.value) === null || _a === void 0 ? void 0 : _a.toString()
|
||||
: undefined;
|
||||
const valueEquality = typeof valueParsed == "object"
|
||||
? valueParsed.equality || queryObj.equality
|
||||
: queryObj.equality;
|
||||
const operatorStrParam = sqlGenOperatorGen({
|
||||
const operatorStrParam = (0, sql_gen_operator_gen_1.default)({
|
||||
queryObj,
|
||||
equality: valueEquality,
|
||||
fieldName: finalFieldName || "",
|
||||
value: valueString?.toString() || "",
|
||||
value: (valueString === null || valueString === void 0 ? void 0 : valueString.toString()) || "",
|
||||
isValueFieldValue: Boolean(typeof valueParsed == "object" &&
|
||||
valueParsed.fieldName &&
|
||||
valueParsed.tableName),
|
||||
@ -66,7 +73,7 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
}
|
||||
else if (typeof queryObj.value == "object") {
|
||||
const operatorStrParam = grabValue(queryObj.value);
|
||||
if (operatorStrParam?.str) {
|
||||
if (operatorStrParam === null || operatorStrParam === void 0 ? void 0 : operatorStrParam.str) {
|
||||
str = operatorStrParam.str;
|
||||
if (operatorStrParam.param) {
|
||||
sqlSearhValues.push(operatorStrParam.param);
|
||||
@ -77,7 +84,7 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
const valueParsed = queryObj.value
|
||||
? String(queryObj.value)
|
||||
: undefined;
|
||||
const operatorStrParam = sqlGenOperatorGen({
|
||||
const operatorStrParam = (0, sql_gen_operator_gen_1.default)({
|
||||
equality: queryObj.equality,
|
||||
fieldName: finalFieldName || "",
|
||||
value: valueParsed,
|
||||
@ -128,49 +135,46 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
: mtch.target}`;
|
||||
})()}`;
|
||||
}
|
||||
let fullTextMatchStr = genObject?.fullTextSearch
|
||||
let fullTextMatchStr = (genObject === null || genObject === void 0 ? void 0 : 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
|
||||
const fullTextSearchStr = (genObject === null || genObject === void 0 ? void 0 : genObject.fullTextSearch)
|
||||
? genObject.fullTextSearch.searchTerm
|
||||
.split(` `)
|
||||
.map((t) => `${t}`)
|
||||
.join(" ")
|
||||
: undefined;
|
||||
let queryString = (() => {
|
||||
var _a, _b, _c;
|
||||
let str = "SELECT";
|
||||
if (count) {
|
||||
str += ` COUNT(*)`;
|
||||
}
|
||||
else if (genObject?.selectFields?.[0]) {
|
||||
else if ((_a = genObject === null || genObject === void 0 ? void 0 : genObject.selectFields) === null || _a === void 0 ? void 0 : _a[0]) {
|
||||
if (genObject.join) {
|
||||
str += ` ${genObject.selectFields
|
||||
?.map((fld) => typeof fld == "object"
|
||||
str += ` ${(_b = genObject.selectFields) === null || _b === void 0 ? void 0 : _b.map((fld) => typeof fld == "object"
|
||||
? `${finalDbName}${tableName}.${fld.fieldName.toString()}` +
|
||||
(fld.alias ? ` as ${fld.alias}` : ``)
|
||||
: `${finalDbName}${tableName}.${String(fld)}`)
|
||||
.join(",")}`;
|
||||
: `${finalDbName}${tableName}.${String(fld)}`).join(",")}`;
|
||||
}
|
||||
else {
|
||||
str += ` ${genObject.selectFields
|
||||
?.map((fld) => typeof fld == "object"
|
||||
str += ` ${(_c = genObject.selectFields) === null || _c === void 0 ? void 0 : _c.map((fld) => typeof fld == "object"
|
||||
? `${fld.fieldName.toString()}` +
|
||||
(fld.alias ? ` as ${fld.alias}` : ``)
|
||||
: fld)
|
||||
.join(",")}`;
|
||||
: fld).join(",")}`;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (genObject?.join) {
|
||||
if (genObject === null || genObject === void 0 ? void 0 : genObject.join) {
|
||||
str += ` ${finalDbName}${tableName}.*`;
|
||||
}
|
||||
else {
|
||||
str += " *";
|
||||
}
|
||||
}
|
||||
if (genObject?.countSubQueries) {
|
||||
if (genObject === null || genObject === void 0 ? void 0 : genObject.countSubQueries) {
|
||||
let countSqls = [];
|
||||
for (let i = 0; i < genObject.countSubQueries.length; i++) {
|
||||
const countSubQuery = genObject.countSubQueries[i];
|
||||
@ -201,13 +205,13 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
}
|
||||
str += `, ${countSqls.join(",")}`;
|
||||
}
|
||||
if (genObject?.join && !count) {
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.join) && !count) {
|
||||
const existingJoinTableNames = [tableName];
|
||||
str +=
|
||||
"," +
|
||||
genObject.join
|
||||
.flat()
|
||||
.filter((j) => !isUndefined(j))
|
||||
.filter((j) => !(0, lodash_1.isUndefined)(j))
|
||||
.map((joinObj) => {
|
||||
const joinTableName = joinObj.alias
|
||||
? joinObj.alias
|
||||
@ -239,19 +243,19 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
.filter((_) => Boolean(_))
|
||||
.join(",");
|
||||
}
|
||||
if (genObject?.fullTextSearch &&
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.fullTextSearch) &&
|
||||
fullTextMatchStr &&
|
||||
fullTextSearchStr) {
|
||||
str += `, ${fullTextMatchStr} AS ${genObject.fullTextSearch.scoreAlias}`;
|
||||
sqlSearhValues.push(fullTextSearchStr);
|
||||
}
|
||||
str += ` FROM ${finalDbName}${tableName}`;
|
||||
if (genObject?.join) {
|
||||
if (genObject === null || genObject === void 0 ? void 0 : genObject.join) {
|
||||
str +=
|
||||
" " +
|
||||
genObject.join
|
||||
.flat()
|
||||
.filter((j) => !isUndefined(j))
|
||||
.filter((j) => !(0, lodash_1.isUndefined)(j))
|
||||
.map((join) => {
|
||||
return (join.joinType +
|
||||
" " +
|
||||
@ -280,20 +284,20 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
}
|
||||
return str;
|
||||
})();
|
||||
const sqlSearhString = queryKeys?.map((field) => {
|
||||
const queryObj = finalQuery?.[field];
|
||||
const sqlSearhString = queryKeys === null || queryKeys === void 0 ? void 0 : queryKeys.map((field) => {
|
||||
const queryObj = finalQuery === null || finalQuery === void 0 ? void 0 : 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];
|
||||
const newSubQueryObj = subQueryGroup === null || subQueryGroup === void 0 ? void 0 : subQueryGroup[_field];
|
||||
if (newSubQueryObj) {
|
||||
return genSqlSrchStr({
|
||||
queryObj: newSubQueryObj,
|
||||
field: newSubQueryObj.fieldName || _field,
|
||||
join: genObject?.join,
|
||||
join: genObject === null || genObject === void 0 ? void 0 : genObject.join,
|
||||
});
|
||||
}
|
||||
});
|
||||
@ -304,20 +308,20 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
return genSqlSrchStr({
|
||||
queryObj,
|
||||
field: queryObj.fieldName || field,
|
||||
join: genObject?.join,
|
||||
join: genObject === null || genObject === void 0 ? void 0 : genObject.join,
|
||||
});
|
||||
});
|
||||
const cleanedUpSearchStr = sqlSearhString?.filter((str) => typeof str == "string");
|
||||
const isSearchStr = cleanedUpSearchStr?.[0] && cleanedUpSearchStr.find((str) => str);
|
||||
const cleanedUpSearchStr = sqlSearhString === null || sqlSearhString === void 0 ? void 0 : sqlSearhString.filter((str) => typeof str == "string");
|
||||
const isSearchStr = (cleanedUpSearchStr === null || cleanedUpSearchStr === void 0 ? void 0 : cleanedUpSearchStr[0]) && cleanedUpSearchStr.find((str) => str);
|
||||
if (isSearchStr) {
|
||||
const stringOperator = genObject?.searchOperator || "AND";
|
||||
const stringOperator = (genObject === null || genObject === void 0 ? void 0 : genObject.searchOperator) || "AND";
|
||||
queryString += ` WHERE ${cleanedUpSearchStr.join(` ${stringOperator} `)}`;
|
||||
}
|
||||
if (genObject?.fullTextSearch && fullTextSearchStr && fullTextMatchStr) {
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.fullTextSearch) && fullTextSearchStr && fullTextMatchStr) {
|
||||
queryString += `${isSearchStr ? " AND" : " WHERE"} ${fullTextMatchStr}`;
|
||||
sqlSearhValues.push(fullTextSearchStr);
|
||||
}
|
||||
if (genObject?.group) {
|
||||
if (genObject === null || genObject === void 0 ? void 0 : genObject.group) {
|
||||
let group_by_txt = ``;
|
||||
if (typeof genObject.group == "string") {
|
||||
group_by_txt = genObject.group;
|
||||
@ -352,10 +356,10 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
function grabOrderString(order) {
|
||||
let orderFields = [];
|
||||
let orderSrt = ``;
|
||||
if (genObject?.fullTextSearch && genObject.fullTextSearch.scoreAlias) {
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.fullTextSearch) && genObject.fullTextSearch.scoreAlias) {
|
||||
orderFields.push(genObject.fullTextSearch.scoreAlias);
|
||||
}
|
||||
else if (genObject?.join) {
|
||||
else if (genObject === null || genObject === void 0 ? void 0 : genObject.join) {
|
||||
orderFields.push(`${finalDbName}${tableName}.${String(order.field)}`);
|
||||
}
|
||||
else {
|
||||
@ -364,7 +368,7 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
orderSrt += ` ${orderFields.join(", ")} ${order.strategy}`;
|
||||
return orderSrt;
|
||||
}
|
||||
if (genObject?.order && !count) {
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.order) && !count) {
|
||||
let orderSrt = ` ORDER BY`;
|
||||
if (Array.isArray(genObject.order)) {
|
||||
for (let i = 0; i < genObject.order.length; i++) {
|
||||
@ -381,9 +385,9 @@ export default function sqlGenerator({ tableName, genObject, dbFullName, count }
|
||||
}
|
||||
queryString += ` ${orderSrt}`;
|
||||
}
|
||||
if (genObject?.limit && !count)
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.limit) && !count)
|
||||
queryString += ` LIMIT ${genObject.limit}`;
|
||||
if (genObject?.offset && !count)
|
||||
if ((genObject === null || genObject === void 0 ? void 0 : genObject.offset) && !count)
|
||||
queryString += ` OFFSET ${genObject.offset}`;
|
||||
return {
|
||||
string: queryString,
|
||||
|
||||
7
dist/utils/sql-insert-generator.js
vendored
7
dist/utils/sql-insert-generator.js
vendored
@ -1,10 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sqlInsertGenerator;
|
||||
/**
|
||||
* # SQL Insert Generator
|
||||
*/
|
||||
export default function sqlInsertGenerator({ tableName, data, dbFullName, }) {
|
||||
function sqlInsertGenerator({ tableName, data, dbFullName, }) {
|
||||
const finalDbName = dbFullName ? `${dbFullName}.` : "";
|
||||
try {
|
||||
if (Array.isArray(data) && data?.[0]) {
|
||||
if (Array.isArray(data) && (data === null || data === void 0 ? void 0 : data[0])) {
|
||||
let insertKeys = [];
|
||||
data.forEach((dt) => {
|
||||
const kys = Object.keys(dt);
|
||||
|
||||
28
dist/utils/trim-backups.js
vendored
28
dist/utils/trim-backups.js
vendored
@ -1,19 +1,25 @@
|
||||
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"];
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = trimBackups;
|
||||
const grab_db_dir_1 = __importDefault(require("../utils/grab-db-dir"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_sorted_backups_1 = __importDefault(require("./grab-sorted-backups"));
|
||||
const app_data_1 = require("../data/app-data");
|
||||
const path_1 = __importDefault(require("path"));
|
||||
function trimBackups({ config }) {
|
||||
const { backup_dir } = (0, grab_db_dir_1.default)({ config });
|
||||
const backups = (0, grab_sorted_backups_1.default)({ config });
|
||||
const max_backups = config.max_backups || app_data_1.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);
|
||||
const backup_file_to_unlink = path_1.default.join(backup_dir, backup_name);
|
||||
fs_1.default.unlinkSync(backup_file_to_unlink);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,14 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
msg="Updates"
|
||||
else
|
||||
msg="$1"
|
||||
fi
|
||||
|
||||
tsc --noEmit
|
||||
rm -rf dist
|
||||
tsc
|
||||
git add .
|
||||
|
||||
@ -8,7 +8,7 @@ import type {
|
||||
BUN_SQLITE_DatabaseSchemaType,
|
||||
} from "../types";
|
||||
|
||||
export default async function init(): Promise<BunSQLiteConfigReturn> {
|
||||
export default function init(): BunSQLiteConfigReturn {
|
||||
try {
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
const { ConfigFileName } = AppData;
|
||||
@ -24,7 +24,7 @@ export default async function init(): Promise<BunSQLiteConfigReturn> {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const ConfigImport = await import(ConfigFilePath);
|
||||
const ConfigImport = require(ConfigFilePath);
|
||||
const Config = ConfigImport["default"] as BunSQLiteConfig;
|
||||
|
||||
if (!Config.db_name) {
|
||||
@ -48,7 +48,7 @@ export default async function init(): Promise<BunSQLiteConfigReturn> {
|
||||
}
|
||||
|
||||
const DBSchemaFilePath = path.join(db_dir, Config.db_schema_file_name);
|
||||
const DbSchemaImport = await import(DBSchemaFilePath);
|
||||
const DbSchemaImport = require(DBSchemaFilePath);
|
||||
const DbSchema = DbSchemaImport[
|
||||
"default"
|
||||
] as BUN_SQLITE_DatabaseSchemaType;
|
||||
|
||||
@ -46,7 +46,7 @@ export default async function DbDelete<
|
||||
if (whereClause) {
|
||||
let sql = `DELETE FROM ${table} ${whereClause}`;
|
||||
|
||||
const res = DbClient.run(sql, sqlQueryObj.values);
|
||||
const res = DbClient.prepare(sql).run(...sqlQueryObj.values);
|
||||
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
|
||||
@ -26,7 +26,9 @@ export default async function DbInsert<
|
||||
data: finalData as any[],
|
||||
});
|
||||
|
||||
const res = DbClient.run(sqlObj?.query || "", sqlObj?.values || []);
|
||||
const res = DbClient.prepare(sqlObj?.query || "").run(
|
||||
...(sqlObj?.values || []),
|
||||
);
|
||||
|
||||
return {
|
||||
success: Boolean(Number(res.lastInsertRowid)),
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { Database } from "bun:sqlite";
|
||||
import { type Database } from "better-sqlite3";
|
||||
import _ from "lodash";
|
||||
import DbClient from ".";
|
||||
import type {
|
||||
@ -25,14 +25,14 @@ class SQLiteSchemaManager {
|
||||
}) {
|
||||
this.db = DbClient;
|
||||
this.db_manager_table_name = "__db_schema_manager__";
|
||||
this.db.run("PRAGMA foreign_keys = ON;");
|
||||
this.db.exec("PRAGMA foreign_keys = ON;");
|
||||
this.recreate_vector_table = recreate_vector_table;
|
||||
this.createDbManagerTable();
|
||||
this.db_schema = schema;
|
||||
}
|
||||
|
||||
private createDbManagerTable() {
|
||||
this.db.run(`
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS ${this.db_manager_table_name} (
|
||||
table_name TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
@ -42,17 +42,19 @@ class SQLiteSchemaManager {
|
||||
}
|
||||
|
||||
private insertDbManagerTable(tableName: string) {
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.db_manager_table_name} (table_name,created_at,updated_at) VALUES (?, ?, ?)`,
|
||||
[tableName, Date.now(), Date.now()],
|
||||
);
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO ${this.db_manager_table_name} (table_name,created_at,updated_at) VALUES (?, ?, ?)`,
|
||||
)
|
||||
.run(...[tableName, Date.now(), Date.now()]);
|
||||
}
|
||||
|
||||
private removeDbManagerTable(tableName: string) {
|
||||
this.db.run(
|
||||
`DELETE FROM ${this.db_manager_table_name} WHERE table_name = ?`,
|
||||
[tableName],
|
||||
);
|
||||
this.db
|
||||
.prepare(
|
||||
`DELETE FROM ${this.db_manager_table_name} WHERE table_name = ?`,
|
||||
)
|
||||
.run(...[tableName]);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -81,7 +83,7 @@ class SQLiteSchemaManager {
|
||||
private getExistingTables(): string[] {
|
||||
let sql = `SELECT table_name FROM ${this.db_manager_table_name}`;
|
||||
|
||||
const query = this.db.query(sql);
|
||||
const query = this.db.prepare(sql);
|
||||
const results = query.all() as { table_name: string }[];
|
||||
|
||||
return results.map((r) => r.table_name);
|
||||
@ -102,8 +104,8 @@ class SQLiteSchemaManager {
|
||||
|
||||
for (const tableName of tablesToDrop) {
|
||||
console.log(`Dropping table: ${tableName}`);
|
||||
this.db.run(`DROP TABLE IF EXISTS "${tableName}"`);
|
||||
this.db.run(
|
||||
this.db.exec(`DROP TABLE IF EXISTS "${tableName}"`);
|
||||
this.db.exec(
|
||||
`DELETE FROM ${this.db_manager_table_name} WHERE table_name = "${tableName}"`,
|
||||
);
|
||||
}
|
||||
@ -124,7 +126,7 @@ class SQLiteSchemaManager {
|
||||
console.log(
|
||||
`Renaming table: ${table.tableNameOld} -> ${table.tableName}`,
|
||||
);
|
||||
this.db.run(
|
||||
this.db.exec(
|
||||
`ALTER TABLE "${table.tableNameOld}" RENAME TO "${table.tableName}"`,
|
||||
);
|
||||
this.insertDbManagerTable(table.tableName);
|
||||
@ -211,7 +213,7 @@ class SQLiteSchemaManager {
|
||||
? `CREATE VIRTUAL TABLE "${new_table.tableName}" USING ${new_table.vectorType || "vec0"}(${allConstraints.join(", ")})`
|
||||
: `CREATE TABLE "${new_table.tableName}" (${allConstraints.join(", ")})`;
|
||||
|
||||
this.db.run(sql);
|
||||
this.db.exec(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -266,7 +268,7 @@ class SQLiteSchemaManager {
|
||||
private getTableColumns(
|
||||
tableName: string,
|
||||
): { name: string; type: string }[] {
|
||||
const query = this.db.query(`PRAGMA table_info("${tableName}")`);
|
||||
const query = this.db.prepare(`PRAGMA table_info("${tableName}")`);
|
||||
const results = query.all() as { name: string; type: string }[];
|
||||
return results;
|
||||
}
|
||||
@ -290,7 +292,7 @@ class SQLiteSchemaManager {
|
||||
|
||||
const sql = `ALTER TABLE "${tableName}" ADD COLUMN ${cleanDef}`;
|
||||
|
||||
this.db.run(sql);
|
||||
this.db.exec(sql);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -307,10 +309,10 @@ class SQLiteSchemaManager {
|
||||
console.log(`Recreating vector table: ${table.tableName}`);
|
||||
|
||||
const existingRows = this.db
|
||||
.query(`SELECT * FROM "${table.tableName}"`)
|
||||
.prepare(`SELECT * FROM "${table.tableName}"`)
|
||||
.all() as { [k: string]: any }[];
|
||||
|
||||
this.db.run(`DROP TABLE "${table.tableName}"`);
|
||||
this.db.exec(`DROP TABLE "${table.tableName}"`);
|
||||
await this.createTable(table);
|
||||
|
||||
if (existingRows.length > 0) {
|
||||
@ -321,10 +323,11 @@ class SQLiteSchemaManager {
|
||||
const columns = Object.keys(row);
|
||||
const placeholders = columns.map(() => "?").join(", ");
|
||||
|
||||
this.db.run(
|
||||
`INSERT INTO "${table.tableName}" (${columns.join(", ")}) VALUES (${placeholders})`,
|
||||
Object.values(row),
|
||||
);
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO "${table.tableName}" (${columns.join(", ")}) VALUES (${placeholders})`,
|
||||
)
|
||||
.run(...Object.values(row));
|
||||
}
|
||||
}
|
||||
|
||||
@ -354,16 +357,16 @@ class SQLiteSchemaManager {
|
||||
// Copy data if there are common columns
|
||||
if (columnsToKeep.length > 0) {
|
||||
const columnList = columnsToKeep.map((c) => `"${c}"`).join(", ");
|
||||
this.db.run(
|
||||
this.db.exec(
|
||||
`INSERT INTO "${tempTableName}" (${columnList}) SELECT ${columnList} FROM "${table.tableName}"`,
|
||||
);
|
||||
}
|
||||
|
||||
// Drop old table
|
||||
this.db.run(`DROP TABLE "${table.tableName}"`);
|
||||
this.db.exec(`DROP TABLE "${table.tableName}"`);
|
||||
|
||||
// Rename temp table
|
||||
this.db.run(
|
||||
this.db.exec(
|
||||
`ALTER TABLE "${tempTableName}" RENAME TO "${table.tableName}"`,
|
||||
);
|
||||
}
|
||||
@ -506,7 +509,7 @@ class SQLiteSchemaManager {
|
||||
}
|
||||
|
||||
// Get existing indexes
|
||||
const query = this.db.query(
|
||||
const query = this.db.prepare(
|
||||
`SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='${table.tableName}' AND name NOT LIKE 'sqlite_%'`,
|
||||
);
|
||||
const existingIndexes = (query.all() as { name: string }[]).map(
|
||||
@ -520,7 +523,7 @@ class SQLiteSchemaManager {
|
||||
);
|
||||
if (!stillExists) {
|
||||
console.log(`Dropping index: ${indexName}`);
|
||||
this.db.run(`DROP INDEX IF EXISTS "${indexName}"`);
|
||||
this.db.exec(`DROP INDEX IF EXISTS "${indexName}"`);
|
||||
}
|
||||
}
|
||||
|
||||
@ -540,7 +543,7 @@ class SQLiteSchemaManager {
|
||||
.map((f) => `"${f.value}"`)
|
||||
.join(", ");
|
||||
const unique = index.indexType === "regular" ? "" : ""; // SQLite doesn't have FULLTEXT in CREATE INDEX
|
||||
this.db.run(
|
||||
this.db.exec(
|
||||
`CREATE ${unique}INDEX "${index.indexName}" ON "${table.tableName}" (${fields})`,
|
||||
);
|
||||
}
|
||||
|
||||
@ -47,8 +47,7 @@ export default async function DbSelect<
|
||||
|
||||
const sql = mysql.format(sqlObj.string, sqlObj.values);
|
||||
|
||||
const res = DbClient.query<Schema, Schema[]>(sql);
|
||||
const batchRes = res.all();
|
||||
const batchRes = DbClient.prepare(sql).all() as Schema[];
|
||||
|
||||
let resp: APIResponseObject<Schema> = {
|
||||
success: Boolean(batchRes[0]),
|
||||
|
||||
@ -12,8 +12,8 @@ export default async function DbSQL<
|
||||
>({ sql, values }: Params): Promise<APIResponseObject<T>> {
|
||||
try {
|
||||
const res = sql.match(/^select/i)
|
||||
? DbClient.query(sql).all(...(values || []))
|
||||
: DbClient.run(sql, values || []);
|
||||
? DbClient.prepare(sql).all(...(values || []))
|
||||
: DbClient.prepare(sql).run(...(values || []));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@ -76,7 +76,7 @@ export default async function DbUpdate<
|
||||
sql += ` ${whereClause}`;
|
||||
values = [...values, ...sqlQueryObj.values];
|
||||
|
||||
const res = DbClient.run(sql, values);
|
||||
const res = DbClient.prepare(sql).run(...values);
|
||||
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
|
||||
@ -5,7 +5,7 @@ import init from "../../functions/init";
|
||||
import grabDBDir from "../../utils/grab-db-dir";
|
||||
|
||||
const { ROOT_DIR } = grabDirNames();
|
||||
const { config } = await init();
|
||||
const { config } = init();
|
||||
|
||||
let db_dir = ROOT_DIR;
|
||||
|
||||
|
||||
@ -1,13 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["ESNext"],
|
||||
"target": "ESNext",
|
||||
"module": "Preserve",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"target": "ES2015",
|
||||
"module": "commonjs",
|
||||
"moduleDetection": "auto",
|
||||
"allowJs": true,
|
||||
"moduleResolution": "bundler",
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleResolution": "node",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
@ -21,6 +19,7 @@
|
||||
"maxNodeModuleJsDepth": 10,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"incremental": true,
|
||||
"esModuleInterop": true,
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src"],
|
||||
|
||||
Loading…
Reference in New Issue
Block a user