Update .gitignore, add dist directory

This commit is contained in:
2026-07-20 21:43:05 +01:00
parent 9f2db66760
commit 3bbf00cdb0
153 changed files with 6280 additions and 1 deletions
+2
View File
@@ -0,0 +1,2 @@
import { Command } from "commander";
export default function (): Command;
+37
View File
@@ -0,0 +1,37 @@
import { Command } from "commander";
import chalk from "chalk";
import { select } from "@inquirer/prompts";
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 () => {
console.log(chalk.bold(chalk.blue("\nBun MariaDB Admin\n")));
try {
while (true) {
const paradigm = await select({
message: "Choose an action:",
choices: [
{ name: "Tables", value: "list_tables" },
{ name: "SQL", value: "run_sql" },
{ name: chalk.dim("✕ Exit"), value: "exit" },
],
});
if (paradigm === "exit")
break;
if (paradigm === "list_tables") {
const result = await listTables();
if (result === "__exit__")
break;
}
if (paradigm === "run_sql")
await runSQL();
}
}
catch (error) {
console.error(error.message);
}
process.exit();
});
}
+3
View File
@@ -0,0 +1,3 @@
type Params = {};
export default function listTables(params?: Params): Promise<"__exit__" | void>;
export {};
+81
View File
@@ -0,0 +1,81 @@
import chalk from "chalk";
import { select } from "@inquirer/prompts";
import { AppData } from "../../data/app-data";
import showEntries from "./show-entries";
import showFields from "./show-fields";
import dbHandler from "../../lib/db-handler";
import MariaDBQuoteGen from "../../lib/schema/mariadb-quote-gen";
export default async function listTables(params) {
const tables = (await dbHandler({
query: `SELECT table_name FROM ${MariaDBQuoteGen(AppData["DbSchemaManagerTableName"])}`,
})).payload;
if (!tables?.length) {
console.log(chalk.yellow("\nNo tables found.\n"));
return;
}
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__" },
{ name: chalk.dim("✕ Exit"), value: "__exit__" },
],
});
if (tableName === "__back__")
break;
if (tableName === "__exit__")
return "__exit__";
while (true) {
const action = await select({
message: `"${tableName}" — choose an action:`,
choices: [
{ name: "Entries", value: "entries" },
{ name: "Fields", value: "fields" },
{ name: "Schema", value: "schema" },
{ name: chalk.dim("← Go Back"), value: "__back__" },
{ name: chalk.dim("✕ Exit"), value: "__exit__" },
],
});
if (action === "__back__")
break;
if (action === "__exit__")
return "__exit__";
if (action === "entries") {
const result = await showEntries({ tableName });
if (result === "__exit__")
return "__exit__";
}
if (action === "fields") {
const result = await showFields({ tableName });
if (result === "__exit__")
return "__exit__";
}
if (action === "schema") {
const columns = (await dbHandler({
query: `SELECT ORDINAL_POSITION, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION`,
values: [tableName],
})).payload;
console.log(`\n${chalk.bold(`Schema for "${tableName}":`)} \n`);
if (columns?.length) {
console.table(columns.map((c) => ({
"#": c.ORDINAL_POSITION,
Name: c.COLUMN_NAME,
Type: c.COLUMN_TYPE,
Nullable: c.IS_NULLABLE,
Default: c.COLUMN_DEFAULT ?? "(none)",
Key: c.COLUMN_KEY || "",
Extra: c.EXTRA || "",
})));
}
else {
console.log(chalk.yellow("No columns found."));
}
console.log();
}
}
}
}
+3
View File
@@ -0,0 +1,3 @@
type Params = {};
export default function runSQL(params?: Params): Promise<void>;
export {};
+25
View File
@@ -0,0 +1,25 @@
import { input } from "@inquirer/prompts";
import chalk from "chalk";
import dbHandler from "../../lib/db-handler";
export default async function runSQL(params) {
const sql = await input({
message: "Enter SQL query:",
validate: (val) => val.trim().length > 0 || "Query cannot be empty",
});
try {
const res = await dbHandler({ query: sql });
if (res.payload?.length) {
console.log(`\n${chalk.bold(`Result (${res.payload.length} row${res.payload.length !== 1 ? "s" : ""}):`)} \n`);
console.table(res.payload);
}
else if (res.success) {
console.log(chalk.green(`\nSuccess! Affected rows: ${res.insert_return?.affected_rows ?? res.count ?? 0}, Last insert ID: ${res.insert_return?.last_insert_id ?? "—"}\n`));
}
else {
console.error(chalk.red(`\nSQL Error: ${res.error || res.msg}\n`));
}
}
catch (error) {
console.error(chalk.red(`\nSQL Error: ${error.message}\n`));
}
}
+5
View File
@@ -0,0 +1,5 @@
type Params = {
tableName: string;
};
export default function showEntries({ tableName }: Params): Promise<"__exit__" | undefined>;
export {};
+91
View File
@@ -0,0 +1,91 @@
import chalk from "chalk";
import { select, input } from "@inquirer/prompts";
import dbHandler from "../../lib/db-handler";
import MariaDBQuoteGen from "../../lib/schema/mariadb-quote-gen";
const LIMIT = 50;
export default async function showEntries({ tableName }) {
let page = 0;
let searchField = null;
let searchTerm = null;
const quotedTable = MariaDBQuoteGen(tableName);
while (true) {
const offset = page * LIMIT;
const rows = searchTerm
? (await dbHandler({
query: `SELECT * FROM ${quotedTable} WHERE ${MariaDBQuoteGen(searchField)} LIKE ? LIMIT ${LIMIT} OFFSET ${offset}`,
values: [`%${searchTerm}%`],
})).payload
: (await dbHandler({
query: `SELECT * FROM ${quotedTable} LIMIT ${LIMIT} OFFSET ${offset}`,
})).payload;
const countRow = searchTerm
? (await dbHandler({
query: `SELECT COUNT(*) as count FROM ${quotedTable} WHERE ${MariaDBQuoteGen(searchField)} LIKE ?`,
values: [`%${searchTerm}%`],
})).payload
: (await dbHandler({
query: `SELECT COUNT(*) as count FROM ${quotedTable}`,
})).payload;
const total = Number(countRow?.[0]?.count || 0);
const searchInfo = searchTerm
? chalk.dim(` · searching "${searchField}" = "${searchTerm}"`)
: "";
if (!rows) {
return;
}
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__" });
choices.push({ name: chalk.dim("✕ Exit"), value: "__exit__" });
const action = await select({ message: "Navigate:", choices });
if (action === "__back__")
break;
if (action === "__exit__")
return "__exit__";
if (action === "next")
page++;
if (action === "prev")
page--;
if (action === "clear_search") {
searchField = null;
searchTerm = null;
page = 0;
}
if (action === "search") {
const columns = (await dbHandler({
query: `SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION`,
values: [tableName],
})).payload;
if (!columns?.length) {
console.log(chalk.yellow("No columns found for search."));
continue;
}
searchField = await select({
message: "Search by field:",
choices: columns.map((c) => ({
name: c.COLUMN_NAME,
value: c.COLUMN_NAME,
})),
});
searchTerm = await input({
message: `Search term for "${searchField}":`,
validate: (v) => v.trim().length > 0 || "Cannot be empty",
});
page = 0;
}
}
}
+5
View File
@@ -0,0 +1,5 @@
type Params = {
tableName: string;
};
export default function showFields({ tableName, }: Params): Promise<"__exit__" | void>;
export {};
+60
View File
@@ -0,0 +1,60 @@
import chalk from "chalk";
import { select } from "@inquirer/prompts";
import dbHandler from "../../lib/db-handler";
export default async function showFields({ tableName, }) {
const columns = (await dbHandler({
query: `SELECT ORDINAL_POSITION, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION`,
values: [tableName],
})).payload;
if (!columns?.length) {
console.log(chalk.yellow(`\nNo columns found for "${tableName}".\n`));
return;
}
const indexes = (await dbHandler({
query: `SELECT INDEX_NAME, COLUMN_NAME, NON_UNIQUE, INDEX_TYPE FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY INDEX_NAME, SEQ_IN_INDEX`,
values: [tableName],
})).payload;
const foreignKeys = (await dbHandler({
query: `SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,
values: [tableName],
})).payload;
while (true) {
const fieldName = await select({
message: `"${tableName}" — select a field:`,
choices: [
...columns.map((c) => ({
name: c.COLUMN_NAME,
value: c.COLUMN_NAME,
})),
{ name: chalk.dim("← Go Back"), value: "__back__" },
{ name: chalk.dim("✕ Exit"), value: "__exit__" },
],
});
if (fieldName === "__back__")
break;
if (fieldName === "__exit__")
return "__exit__";
const col = columns.find((c) => c.COLUMN_NAME === fieldName);
const colIndexes = indexes?.filter((i) => i.COLUMN_NAME === fieldName) || [];
const fk = foreignKeys?.find((f) => f.COLUMN_NAME === fieldName);
console.log(`\n${chalk.bold(`Field: "${fieldName}"`)}\n`);
console.log(` ${chalk.dim("Table")} ${tableName}`);
console.log(` ${chalk.dim("Column #")} ${col.ORDINAL_POSITION}`);
console.log(` ${chalk.dim("Type")} ${col.COLUMN_TYPE}`);
console.log(` ${chalk.dim("Primary Key")} ${col.COLUMN_KEY === "PRI" ? chalk.green("YES") : "NO"}`);
console.log(` ${chalk.dim("Not Null")} ${col.IS_NULLABLE === "NO" ? chalk.yellow("YES") : "NO"}`);
console.log(` ${chalk.dim("Default")} ${col.COLUMN_DEFAULT ?? chalk.italic("(none)")}`);
console.log(` ${chalk.dim("Extra")} ${col.EXTRA || chalk.italic("(none)")}`);
console.log(` ${chalk.dim("Indexed")} ${colIndexes.length ? chalk.cyan(colIndexes.map((i) => i.INDEX_NAME).join(", ")) : "NO"}`);
if (fk) {
console.log(` ${chalk.dim("Foreign Key")} ${chalk.magenta(`${fk.REFERENCED_TABLE_NAME}(${fk.REFERENCED_COLUMN_NAME})`)}`);
}
else {
console.log(` ${chalk.dim("Foreign Key")} NO`);
}
if (col.COLUMN_COMMENT) {
console.log(` ${chalk.dim("Comment")} ${col.COLUMN_COMMENT}`);
}
console.log();
}
}