Skip to content

Commit 6f74949

Browse files
committed
update schema after every query run
1 parent ed1a14a commit 6f74949

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/components/editor.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
editorSchemaAtom,
1111
queryAtom,
1212
queryResultAtom,
13+
schemaAtom,
1314
showCommandPaletteAtom,
1415
} from '@/utils/atoms';
1516
import { useAtom } from 'jotai';
@@ -29,6 +30,7 @@ export const Editor = () => {
2930
);
3031
const [hasConfiguredDatabase] = useAtom(connectionStringAtom);
3132
const [editorSchema] = useAtom(editorSchemaAtom);
33+
const [schema, setSchema] = useAtom(schemaAtom);
3234
const queryClient = useQueryClient();
3335

3436
const { mutate, isLoading } = useMutation(
@@ -38,6 +40,7 @@ export const Editor = () => {
3840
onSuccess: (data) => {
3941
// @ts-ignore
4042
setQueryResult(data);
43+
setSchema(data.databaseSchema);
4144
queryClient.invalidateQueries({ queryKey: ['schema'] });
4245
},
4346
onError: (error) => {

src/utils/query.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,32 @@ export const runQuery = async ({ connectionString, query }: queryOptions) => {
1515

1616
const { rows, rowCount, fields } = await client.query(query);
1717

18+
const { rows: schemaRows } = await client.query(
19+
` SELECT table_name, array_agg(column_name || ' ' || data_type) AS columns_and_types FROM information_schema.columns WHERE table_schema = 'public' GROUP BY table_name ORDER BY table_name;`
20+
);
21+
22+
// transform into CSV
23+
const databaseSchema = schemaRows
24+
.map((table) => {
25+
const columns = table.columns_and_types
26+
// @ts-ignore
27+
.map((column) => {
28+
const [name, type] = column.split(' ');
29+
return `${name} ${type}`;
30+
})
31+
.join(', ');
32+
33+
return `${table.table_name} (${columns});`;
34+
})
35+
.join('\n');
36+
1837
client.end();
1938

2039
// get query execution time
2140
startTime = Date.now();
2241

2342
return {
43+
databaseSchema,
2444
rows: rows ?? [],
2545
rowCount: rowCount ?? 0,
2646
columns: fields?.map((field) => field.name) ?? [],

0 commit comments

Comments
 (0)