MCPcopy Create free account
hub / github.com/sqlchat/sqlchat / getTableSchema

Function getTableSchema

src/lib/connectors/postgres/index.ts:95–139  ·  view source on GitHub ↗
(connection: Connection, databaseName: string)

Source from the content-addressed store, hash-verified

93};
94
95const getTableSchema = async (connection: Connection, databaseName: string): Promise<Schema[]> => {
96 connection.database = databaseName;
97 const client = await newPostgresClient(connection);
98 const { rows } = await client.query(
99 `SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema NOT IN (${systemSchemas}) AND table_name NOT IN (${systemTables}) AND (table_type='BASE TABLE' or table_type='VIEW') AND table_catalog=$1;`,
100 [databaseName]
101 );
102
103 const schemaList: Schema[] = [];
104 for (const row of rows) {
105 if (row["table_name"]) {
106 const schema = schemaList.find((schema) => schema.name === row["table_schema"]);
107 if (schema) {
108 schema.tables.push({ name: row["table_name"] as string, structure: "" } as Table);
109 } else {
110 schemaList.push({
111 name: row["table_schema"],
112 tables: [{ name: row["table_name"], structure: "" } as Table],
113 });
114 }
115 }
116 }
117
118 for (const schema of schemaList) {
119 for (const table of schema.tables) {
120 const { rows: result } = await client.query(
121 `SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema NOT IN (${systemSchemas}) AND table_name=$1 AND table_schema=$2;`,
122 [table.name, schema.name]
123 );
124 const columnList = [];
125 // TODO(steven): transform it to standard schema string.
126 for (const row of result) {
127 columnList.push(
128 `${row["column_name"]} ${row["data_type"].toUpperCase()} ${String(row["is_nullable"]).toUpperCase() === "NO" ? "NOT NULL" : ""}`
129 );
130 }
131
132 let fullTableName = schema.name == "public" ? `"${table.name}"` : `"${schema.name}"."${table.name}"`;
133 table.structure = `CREATE TABLE ${fullTableName} (\n${columnList.join(",\n")}\n);`;
134 }
135 }
136
137 await client.end();
138 return schemaList;
139};
140
141const newConnector = (connection: Connection): Connector => {
142 return {

Callers 1

newConnectorFunction · 0.70

Calls 1

newPostgresClientFunction · 0.85

Tested by

no test coverage detected