Add CLI admin panel
This commit is contained in:
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import { Command } from "commander";
|
||||
export default function (): Command;
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
import { Command } from "commander";
|
||||
import init from "../../functions/init";
|
||||
import grabDBDir from "../../utils/grab-db-dir";
|
||||
import chalk from "chalk";
|
||||
import { select } from "@inquirer/prompts";
|
||||
import { Database } from "bun:sqlite";
|
||||
import listTables from "./list-tables";
|
||||
import runSQL from "./run-sql";
|
||||
export default function () {
|
||||
return new Command("admin")
|
||||
.description("View Tables and Data, Run SQL Queries, Etc.")
|
||||
.action(async () => {
|
||||
const { config } = await init();
|
||||
const { db_file_path } = grabDBDir({ config });
|
||||
const db = new Database(db_file_path);
|
||||
console.log(chalk.bold(chalk.blue("\nBun SQLite Admin\n")));
|
||||
try {
|
||||
while (true) {
|
||||
const paradigm = await select({
|
||||
message: "Choose an action:",
|
||||
choices: [
|
||||
{ name: "List Tables", value: "list_tables" },
|
||||
{ name: "Run SQL", value: "run_sql" },
|
||||
{ name: chalk.dim("✕ Exit"), value: "exit" },
|
||||
],
|
||||
});
|
||||
if (paradigm === "exit")
|
||||
break;
|
||||
if (paradigm === "list_tables")
|
||||
await listTables({ db });
|
||||
if (paradigm === "run_sql")
|
||||
await runSQL({ db });
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error(error.message);
|
||||
}
|
||||
db.close();
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
type Params = {
|
||||
db: Database;
|
||||
};
|
||||
export default function listTables({ db }: Params): Promise<void>;
|
||||
export {};
|
||||
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import chalk from "chalk";
|
||||
import { select } from "@inquirer/prompts";
|
||||
import { AppData } from "../../data/app-data";
|
||||
import showEntries from "./show-entries";
|
||||
export default async function listTables({ db }) {
|
||||
const tables = db
|
||||
.query(`SELECT table_name FROM ${AppData["DbSchemaManagerTableName"]}`)
|
||||
.all();
|
||||
if (!tables.length) {
|
||||
console.log(chalk.yellow("\nNo tables found.\n"));
|
||||
return;
|
||||
}
|
||||
// Level 1: table selection loop
|
||||
while (true) {
|
||||
const tableName = await select({
|
||||
message: "Select a table:",
|
||||
choices: [
|
||||
...tables.map((t) => ({ name: t.table_name, value: t.table_name })),
|
||||
{ name: chalk.dim("← Go Back"), value: "__back__" },
|
||||
],
|
||||
});
|
||||
if (tableName === "__back__")
|
||||
break;
|
||||
// Level 2: action loop — stays here until "Go Back"
|
||||
while (true) {
|
||||
const action = await select({
|
||||
message: `"${tableName}" — choose an action:`,
|
||||
choices: [
|
||||
{ name: "Show Entries", value: "entries" },
|
||||
{ name: "Show Schema", value: "schema" },
|
||||
{ name: chalk.dim("← Go Back"), value: "__back__" },
|
||||
],
|
||||
});
|
||||
if (action === "__back__")
|
||||
break;
|
||||
if (action === "entries") {
|
||||
await showEntries({ db, tableName });
|
||||
}
|
||||
if (action === "schema") {
|
||||
const columns = db
|
||||
.query(`PRAGMA table_info("${tableName}")`)
|
||||
.all();
|
||||
console.log(`\n${chalk.bold(`Schema for "${tableName}":`)} \n`);
|
||||
console.table(columns.map((c) => ({
|
||||
"#": c.cid,
|
||||
Name: c.name,
|
||||
Type: c.type,
|
||||
"Not Null": c.notnull ? "YES" : "NO",
|
||||
Default: c.dflt_value ?? "(none)",
|
||||
"Primary Key": c.pk ? "YES" : "NO",
|
||||
})));
|
||||
console.log();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
type Params = {
|
||||
db: Database;
|
||||
};
|
||||
export default function runSQL({ db }: Params): Promise<void>;
|
||||
export {};
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { input } from "@inquirer/prompts";
|
||||
import chalk from "chalk";
|
||||
export default async function runSQL({ db }) {
|
||||
const sql = await input({
|
||||
message: "Enter SQL query:",
|
||||
validate: (val) => val.trim().length > 0 || "Query cannot be empty",
|
||||
});
|
||||
try {
|
||||
const isSelect = /^select/i.test(sql.trim());
|
||||
if (isSelect) {
|
||||
const rows = db.query(sql).all();
|
||||
console.log(`\n${chalk.bold(`Result (${rows.length} row${rows.length !== 1 ? "s" : ""}):`)} \n`);
|
||||
if (rows.length)
|
||||
console.table(rows);
|
||||
else
|
||||
console.log(chalk.yellow("No rows returned.\n"));
|
||||
}
|
||||
else {
|
||||
const result = db.run(sql);
|
||||
console.log(chalk.green(`\nSuccess! Affected rows: ${result.changes}, Last insert ID: ${result.lastInsertRowid}\n`));
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error(chalk.red(`\nSQL Error: ${error.message}\n`));
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
type Params = {
|
||||
db: Database;
|
||||
tableName: string;
|
||||
};
|
||||
export default function showEntries({ db, tableName }: Params): Promise<void>;
|
||||
export {};
|
||||
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import chalk from "chalk";
|
||||
import { select, input } from "@inquirer/prompts";
|
||||
const LIMIT = 50;
|
||||
export default async function showEntries({ db, tableName }) {
|
||||
let page = 0;
|
||||
let searchField = null;
|
||||
let searchTerm = null;
|
||||
while (true) {
|
||||
const offset = page * LIMIT;
|
||||
const rows = searchTerm
|
||||
? db
|
||||
.query(`SELECT * FROM "${tableName}" WHERE "${searchField}" LIKE ? LIMIT ${LIMIT} OFFSET ${offset}`)
|
||||
.all(`%${searchTerm}%`)
|
||||
: db
|
||||
.query(`SELECT * FROM "${tableName}" LIMIT ${LIMIT} OFFSET ${offset}`)
|
||||
.all();
|
||||
const countRow = (searchTerm
|
||||
? db
|
||||
.query(`SELECT COUNT(*) as count FROM "${tableName}" WHERE "${searchField}" LIKE ?`)
|
||||
.get(`%${searchTerm}%`)
|
||||
: db
|
||||
.query(`SELECT COUNT(*) as count FROM "${tableName}"`)
|
||||
.get());
|
||||
const total = countRow.count;
|
||||
const searchInfo = searchTerm
|
||||
? chalk.dim(` · searching "${searchField}" = "${searchTerm}"`)
|
||||
: "";
|
||||
console.log(`\n${chalk.bold(tableName)} — Page ${page + 1}${searchInfo} (${rows.length} of ${total}):\n`);
|
||||
if (rows.length)
|
||||
console.table(rows);
|
||||
else
|
||||
console.log(chalk.yellow("No rows found."));
|
||||
console.log();
|
||||
const choices = [];
|
||||
if (page > 0)
|
||||
choices.push({ name: "← Previous Page", value: "prev" });
|
||||
if (offset + rows.length < total)
|
||||
choices.push({ name: "Next Page →", value: "next" });
|
||||
choices.push({ name: "Search by Field", value: "search" });
|
||||
if (searchTerm)
|
||||
choices.push({ name: "Clear Search", value: "clear_search" });
|
||||
choices.push({ name: chalk.dim("← Go Back"), value: "__back__" });
|
||||
const action = await select({ message: "Navigate:", choices });
|
||||
if (action === "__back__")
|
||||
break;
|
||||
if (action === "next")
|
||||
page++;
|
||||
if (action === "prev")
|
||||
page--;
|
||||
if (action === "clear_search") {
|
||||
searchField = null;
|
||||
searchTerm = null;
|
||||
page = 0;
|
||||
}
|
||||
if (action === "search") {
|
||||
const columns = db
|
||||
.query(`PRAGMA table_info("${tableName}")`)
|
||||
.all();
|
||||
searchField = await select({
|
||||
message: "Search by field:",
|
||||
choices: columns.map((c) => ({ name: c.name, value: c.name })),
|
||||
});
|
||||
searchTerm = await input({
|
||||
message: `Search term for "${searchField}":`,
|
||||
validate: (v) => v.trim().length > 0 || "Cannot be empty",
|
||||
});
|
||||
page = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+2
@@ -4,6 +4,7 @@ import schema from "./schema";
|
||||
import typedef from "./typedef";
|
||||
import backup from "./backup";
|
||||
import restore from "./restore";
|
||||
import admin from "./admin";
|
||||
/**
|
||||
* # Describe Program
|
||||
*/
|
||||
@@ -18,6 +19,7 @@ program.addCommand(schema());
|
||||
program.addCommand(typedef());
|
||||
program.addCommand(backup());
|
||||
program.addCommand(restore());
|
||||
program.addCommand(admin());
|
||||
/**
|
||||
* # Handle Unavailable Commands
|
||||
*/
|
||||
|
||||
Vendored
+1
@@ -2,4 +2,5 @@ export declare const AppData: {
|
||||
readonly ConfigFileName: "bun-sqlite.config.ts";
|
||||
readonly MaxBackups: 10;
|
||||
readonly DefaultBackupDirName: ".backups";
|
||||
readonly DbSchemaManagerTableName: "__db_schema_manager__";
|
||||
};
|
||||
|
||||
Vendored
+1
@@ -2,4 +2,5 @@ export const AppData = {
|
||||
ConfigFileName: "bun-sqlite.config.ts",
|
||||
MaxBackups: 10,
|
||||
DefaultBackupDirName: ".backups",
|
||||
DbSchemaManagerTableName: "__db_schema_manager__",
|
||||
};
|
||||
|
||||
Vendored
+2
-1
@@ -2,6 +2,7 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import _ from "lodash";
|
||||
import DbClient from ".";
|
||||
import { AppData } from "../../data/app-data";
|
||||
// Schema Manager Class
|
||||
class SQLiteSchemaManager {
|
||||
db;
|
||||
@@ -10,7 +11,7 @@ class SQLiteSchemaManager {
|
||||
db_schema;
|
||||
constructor({ schema, recreate_vector_table = false, }) {
|
||||
this.db = DbClient;
|
||||
this.db_manager_table_name = "__db_schema_manager__";
|
||||
this.db_manager_table_name = AppData["DbSchemaManagerTableName"];
|
||||
this.db.run("PRAGMA foreign_keys = ON;");
|
||||
this.recreate_vector_table = recreate_vector_table;
|
||||
this.createDbManagerTable();
|
||||
|
||||
Reference in New Issue
Block a user