Add CLI admin panel
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
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: any) {
|
||||
console.error(error.message);
|
||||
}
|
||||
|
||||
db.close();
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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";
|
||||
|
||||
type Params = { db: Database };
|
||||
|
||||
type ColumnInfo = {
|
||||
cid: number;
|
||||
name: string;
|
||||
type: string;
|
||||
notnull: number;
|
||||
dflt_value: string | null;
|
||||
pk: number;
|
||||
};
|
||||
|
||||
export default async function listTables({ db }: Params) {
|
||||
const tables = db
|
||||
.query<{ table_name: string }, []>(
|
||||
`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<ColumnInfo, []>(`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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { input } from "@inquirer/prompts";
|
||||
import chalk from "chalk";
|
||||
|
||||
type Params = { db: Database };
|
||||
|
||||
export default async function runSQL({ db }: Params) {
|
||||
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: any) {
|
||||
console.error(chalk.red(`\nSQL Error: ${error.message}\n`));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import chalk from "chalk";
|
||||
import { select, input } from "@inquirer/prompts";
|
||||
|
||||
type Params = { db: Database; tableName: string };
|
||||
type ColumnInfo = { cid: number; name: string };
|
||||
|
||||
const LIMIT = 50;
|
||||
|
||||
export default async function showEntries({ db, tableName }: Params) {
|
||||
let page = 0;
|
||||
let searchField: string | null = null;
|
||||
let searchTerm: string | null = 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()
|
||||
) as { count: number };
|
||||
|
||||
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: { name: string; value: string }[] = [];
|
||||
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<ColumnInfo, []>(`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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user