Sql scheme (#30)

* Initial commit

* Add exportschema

* Remove unused code

* Add exported schema to clipboard as well

* WIP

* WIP
This commit is contained in:
Rikard Bartholf
2025-11-06 13:33:17 +01:00
committed by GitHub
parent 7e50d5eb54
commit d65c9f3933
5 changed files with 324 additions and 3988 deletions
+1
View File
@@ -2,3 +2,4 @@
node_modules
build
.vscode
photowall_schema.json
+2
View File
@@ -40,12 +40,14 @@
"enquirer": "^2.4.1",
"gluegun": "latest",
"lodash.snakecase": "^4.1.1",
"pg": "^8.11.3",
"strip-ansi": "^7.1.0",
"terminal-table-output": "^1.4.0"
},
"devDependencies": {
"@types/jest": "^30.0.0",
"@types/node": "^24.0.3",
"@types/pg": "^8.10.9",
"@typescript-eslint/eslint-plugin": "^8.34.0",
"@typescript-eslint/parser": "^8.34.0",
"eslint": "^9.29.0",
@@ -0,0 +1,138 @@
import { GluegunMenuToolbox } from '@lenne.tech/gluegun-menu';
import chalk = require('chalk');
import { exportDatabaseSchema } from '../../../common/schema-exporter';
const clipboardy = require('clipboardy');
module.exports = {
name: 'exportschema',
alias: ['es'],
description: 'Export PostgreSQL database schema (es)',
hidden: false,
run: async (toolbox: GluegunMenuToolbox) => {
const { print } = toolbox;
print.info(chalk.cyan('🗄️ Exporting Database Schema...'));
print.info('');
// Hardcoded values as per requirements
const dbName = 'photowall';
const dbUser = 'photowall';
const dbHost = 'localhost';
const dbPort = 5432;
print.info(chalk.gray(`Database: ${dbName}`));
print.info(chalk.gray(`User: ${dbUser}`));
print.info(chalk.gray(`Host: ${dbHost}:${dbPort}`));
print.info(
chalk.gray(
'Auth: Using PostgreSQL default methods (.pgpass or PGPASSWORD)',
),
);
print.info('');
// Check for .pgpass file
const fs = require('fs');
const os = require('os');
const path = require('path');
const pgpassPath = path.join(os.homedir(), '.pgpass');
if (!fs.existsSync(pgpassPath)) {
print.warning(
chalk.yellow(`⚠️ Warning: .pgpass file not found at ${pgpassPath}`),
);
print.info(
chalk.gray(
' Ensure PGPASSWORD environment variable is set or .pgpass exists.',
),
);
print.info('');
}
const spinner = print.spin('Connecting to database...');
try {
const result = await exportDatabaseSchema(
dbName,
dbUser,
dbHost,
dbPort,
'/tmp',
);
spinner.stop();
if (result.success && result.outputPath) {
// Read the exported file and copy to clipboard
try {
const schemaContent = fs.readFileSync(result.outputPath, 'utf8');
await clipboardy.write(schemaContent);
print.success(
chalk.green(
`✅ Schema exported successfully to: ${result.outputPath}`,
),
);
print.success(chalk.green('📋 Schema has been copied to clipboard!'));
} catch (clipError) {
print.success(
chalk.green(
`✅ Schema exported successfully to: ${result.outputPath}`,
),
);
print.warning(
chalk.yellow(
`⚠️ Could not copy to clipboard: ${clipError instanceof Error ? clipError.message : String(clipError)}`,
),
);
}
print.info('');
print.info(
chalk.cyan(
'💡 Use this schema file as context for AI-assisted database queries',
),
);
} else {
print.error(chalk.red(`❌ Export failed: ${result.error}`));
print.info('');
if (
result.error &&
result.error.includes('password authentication failed')
) {
print.info(chalk.yellow('💡 Troubleshooting steps:'));
print.info(
chalk.gray(
` 1. Add an entry to ~/.pgpass file (format: ${dbHost}:${dbPort}:${dbName}:${dbUser}:password)`,
),
);
print.info(
chalk.gray(
` 2. Or set environment variable: export PGPASSWORD=your_password`,
),
);
print.info(
chalk.gray(
` 3. Or use trust authentication in PostgreSQL's pg_hba.conf`,
),
);
print.info('');
print.info(
chalk.gray(
` Current .pgpass location: ${pgpassPath}${fs.existsSync(pgpassPath) ? ' (exists)' : ' (not found)'}`,
),
);
}
}
} catch (error) {
spinner.stop();
print.error(
chalk.red(
`❌ Unexpected error: ${error instanceof Error ? error.message : String(error)}`,
),
);
}
// Return to the AI menu
print.info('');
await toolbox.menu.showMenu('ai');
},
};
+183
View File
@@ -0,0 +1,183 @@
import { Client } from 'pg';
import * as fs from 'fs';
import * as path from 'path';
interface Column {
name: string;
type: string;
nullable: boolean;
isPrimaryKey: boolean;
isForeignKey: boolean;
}
interface Relation {
columnName: string;
referencedTable: string;
referencedColumn: string;
}
interface Table {
name: string;
schema: string;
columns: Column[];
relations: Relation[];
}
interface DatabaseSchema {
database: string;
exportedAt: string;
tables: Table[];
}
async function fetchTables(client: Client): Promise<string[]> {
const query = `
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
ORDER BY table_name;
`;
const result = await client.query(query);
return result.rows.map((row) => row.table_name);
}
async function fetchColumns(
client: Client,
tableName: string,
): Promise<Column[]> {
const query = `
SELECT
c.column_name,
c.data_type,
c.is_nullable,
c.column_default,
CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_primary_key,
CASE WHEN fk.column_name IS NOT NULL THEN true ELSE false END as is_foreign_key
FROM information_schema.columns c
LEFT JOIN (
SELECT ku.column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage ku
ON tc.constraint_name = ku.constraint_name
AND tc.table_schema = ku.table_schema
WHERE tc.constraint_type = 'PRIMARY KEY'
AND tc.table_name = $1
AND tc.table_schema = 'public'
) pk ON c.column_name = pk.column_name
LEFT JOIN (
SELECT ku.column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage ku
ON tc.constraint_name = ku.constraint_name
AND tc.table_schema = ku.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_name = $1
AND tc.table_schema = 'public'
) fk ON c.column_name = fk.column_name
WHERE c.table_name = $1
AND c.table_schema = 'public'
ORDER BY c.ordinal_position;
`;
const result = await client.query(query, [tableName]);
return result.rows.map((row) => ({
name: row.column_name,
type: row.data_type,
nullable: row.is_nullable === 'YES',
isPrimaryKey: row.is_primary_key,
isForeignKey: row.is_foreign_key,
}));
}
async function fetchRelations(
client: Client,
tableName: string,
): Promise<Relation[]> {
const query = `
SELECT
tc.constraint_name,
kcu.column_name,
ccu.table_name AS referenced_table,
ccu.column_name AS referenced_column,
rc.delete_rule AS on_delete,
rc.update_rule AS on_update
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.referential_constraints rc
ON tc.constraint_name = rc.constraint_name
AND tc.table_schema = rc.constraint_schema
JOIN information_schema.key_column_usage ccu
ON ccu.constraint_name = rc.unique_constraint_name
AND ccu.table_schema = rc.unique_constraint_schema
AND ccu.ordinal_position = kcu.position_in_unique_constraint
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_name = $1
AND tc.table_schema = 'public'
ORDER BY tc.constraint_name, kcu.ordinal_position;
`;
const result = await client.query(query, [tableName]);
return result.rows.map((row) => ({
columnName: row.column_name,
referencedTable: row.referenced_table,
referencedColumn: row.referenced_column,
}));
}
export async function exportDatabaseSchema(
dbName: string,
dbUser: string,
dbHost: string = 'localhost',
dbPort: number = 5432,
outputDir?: string,
): Promise<{ success: boolean; outputPath?: string; error?: string }> {
const client = new Client({
host: dbHost,
port: dbPort,
database: dbName,
user: dbUser,
});
try {
await client.connect();
const tables = await fetchTables(client);
const schema: DatabaseSchema = {
database: dbName,
exportedAt: new Date().toISOString(),
tables: [],
};
for (const tableName of tables) {
const columns = await fetchColumns(client, tableName);
const relations = await fetchRelations(client, tableName);
schema.tables.push({
name: tableName,
schema: 'public',
columns,
relations,
});
}
const outputPath = path.join(
outputDir || process.cwd(),
`${dbName}_schema.json`,
);
fs.writeFileSync(outputPath, JSON.stringify(schema, null, 2));
await client.end();
return {
success: true,
outputPath,
};
} catch (error) {
await client.end();
return {
success: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
-3988
View File
File diff suppressed because it is too large Load Diff