Debian Codegraph @

src/harlequin_postgres/interactions.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from textwrap import dedent
4 from typing import TYPE_CHECKING, Literal, Sequence
5
6 from harlequin.catalog import CatalogItem
7 from harlequin.exception import HarlequinQueryError
8
9 if TYPE_CHECKING:
10 from harlequin.driver import HarlequinDriver
11
12 from harlequin_postgres.catalog import (
13 ColumnCatalogItem,
14 DatabaseCatalogItem,
15 RelationCatalogItem,
16 SchemaCatalogItem,
17 ViewCatalogItem,
18 )
19
20
21 def execute_use_statement(
22 item: "SchemaCatalogItem",
23 driver: "HarlequinDriver",
24 ) -> None:
25 if item.connection is None:
26 return
27 try:
28 item.connection.execute(f"set search_path to {item.qualified_identifier}")
29 except HarlequinQueryError:
30 driver.notify("Could not switch context", severity="error")
31 raise
32 else:
33 driver.notify(f"Editor context switched to {item.label}")
34
35
36 def execute_drop_schema_statement(
37 item: "SchemaCatalogItem",
38 driver: "HarlequinDriver",
39 ) -> None:
40 def _drop_schema() -> None:
41 if item.connection is None:
42 return
43 try:
44 item.connection.execute(f"drop schema {item.qualified_identifier} cascade")
45 except HarlequinQueryError:
46 driver.notify(f"Could not drop schema {item.label}", severity="error")
47 raise
48 else:
49 driver.notify(f"Dropped schema {item.label}")
50 driver.refresh_catalog()
51
52 if item.children or item.fetch_children():
53 driver.confirm_and_execute(callback=_drop_schema)
54 else:
55 _drop_schema()
56
57
58 def execute_drop_database_statement(
59 item: "DatabaseCatalogItem",
60 driver: "HarlequinDriver",
61 ) -> None:
62 def _drop_database() -> None:
63 if item.connection is None:
64 return
65 try:
66 item.connection.execute(f"drop database {item.qualified_identifier}")
67 except HarlequinQueryError:
68 driver.notify(f"Could not drop database {item.label}", severity="error")
69 raise
70 else:
71 driver.notify(f"Dropped database {item.label}")
72 driver.refresh_catalog()
73
74 if item.children or item.fetch_children():
75 driver.confirm_and_execute(callback=_drop_database)
76 else:
77 _drop_database()
78
79
80 def execute_drop_relation_statement(
81 item: "RelationCatalogItem",
82 driver: "HarlequinDriver",
83 relation_type: Literal["view", "table", "foreign table"],
84 ) -> None:
85 def _drop_relation() -> None:
86 if item.connection is None:
87 return
88 try:
89 item.connection.execute(f"drop {relation_type} {item.qualified_identifier}")
90 except HarlequinQueryError:
91 driver.notify(
92 f"Could not drop {relation_type} {item.label}", severity="error"
93 )
94 raise
95 else:
96 driver.notify(f"Dropped {relation_type} {item.label}")
97 driver.refresh_catalog()
98
99 driver.confirm_and_execute(callback=_drop_relation)
100
101
102 def execute_drop_table_statement(
103 item: "RelationCatalogItem", driver: "HarlequinDriver"
104 ) -> None:
105 execute_drop_relation_statement(item=item, driver=driver, relation_type="table")
106
107
108 def execute_drop_foreign_table_statement(
109 item: "RelationCatalogItem", driver: "HarlequinDriver"
110 ) -> None:
111 execute_drop_relation_statement(
112 item=item, driver=driver, relation_type="foreign table"
113 )
114
115
116 def execute_drop_view_statement(
117 item: "RelationCatalogItem", driver: "HarlequinDriver"
118 ) -> None:
119 execute_drop_relation_statement(item=item, driver=driver, relation_type="view")
120
121
122 def show_select_star(
123 item: "RelationCatalogItem",
124 driver: "HarlequinDriver",
125 ) -> None:
126 driver.insert_text_in_new_buffer(
127 dedent(
128 f"""
129 select *
130 from {item.qualified_identifier}
131 limit 100
132 """.strip("\n")
133 )
134 )
135
136
137 def show_list_objects(
138 item: "SchemaCatalogItem" | "DatabaseCatalogItem",
139 driver: "HarlequinDriver",
140 ) -> None:
141 # sourced from psql with -E, then the following command:
142 # \dtvmsE+ <schema>.*
143
144 # can't use isinstance due to circular reference
145 if type(item).__name__ == "SchemaCatalogItem":
146 where_clause = f"and n.nspname = '{item.label}'"
147 else:
148 where_clause = (
149 "and n.nspname not in ('pg_catalog', 'pg_toast', 'information_schema')"
150 )
151 driver.insert_text_in_new_buffer(
152 dedent(
153 f"""
154 select
155 n.nspname as "Schema",
156 c.relname as "Name",
157 case c.relkind
158 when 'r' then 'table'
159 when 'v' then 'view'
160 when 'm' then 'materialized view'
161 when 'S'
162 then 'sequence'
163 when 't' then 'TOAST table'
164 when 'f' then 'foreign table'
165 when 'p' then 'partitioned table'
166 end as "Type",
167 pg_catalog.pg_get_userbyid(c.relowner) as "Owner",
168 case c.relpersistence
169 when 'p' then 'permanent'
170 when 't' then 'temporary'
171 when 'u' then 'unlogged'
172 end as "Persistence",
173 am.amname as "Access method",
174 pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as "Size",
175 pg_catalog.obj_description(c.oid, 'pg_class') as "Description"
176 from pg_catalog.pg_class c
177 left join pg_catalog.pg_namespace n on n.oid = c.relnamespace
178 left join pg_catalog.pg_am am on am.oid = c.relam
179 where
180 c.relkind IN ('r','p','t','v','m', 's', 'S', 'f')
181 {where_clause}
182 order by 1,2;
183 """.strip("\n")
184 )
185 )
186
187
188 def show_list_indexes(
189 item: "SchemaCatalogItem" | "DatabaseCatalogItem",
190 driver: "HarlequinDriver",
191 ) -> None:
192 # sourced from psql with -E, then the following command:
193 # \dis+ <schema>.*
194
195 # can't use isinstance due to circular reference
196 if type(item).__name__ == "SchemaCatalogItem":
197 where_clause = f"and n.nspname = '{item.label}'"
198 else:
199 where_clause = (
200 "and n.nspname not in ('pg_catalog', 'pg_toast', 'information_schema')"
201 )
202 driver.insert_text_in_new_buffer(
203 dedent(
204 f"""
205 select
206 n.nspname as "Schema",
207 c.relname as "Name",
208 case
209 c.relkind
210 when 'i'
211 then 'index'
212 when 'I'
213 then 'partitioned index'
214 end as "Type",
215 pg_catalog.pg_get_userbyid(c.relowner) as "Owner",
216 c2.relname as "Table",
217 case
218 c.relpersistence
219 when 'p'
220 then 'permanent'
221 when 't'
222 then 'temporary'
223 when 'u'
224 then 'unlogged'
225 end as "Persistence",
226 am.amname as "Access method",
227 pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as "Size",
228 pg_catalog.obj_description(c.oid, 'pg_class') as "Description"
229 from pg_catalog.pg_class c
230 left join pg_catalog.pg_namespace n on n.oid = c.relnamespace
231 left join pg_catalog.pg_am am on am.oid = c.relam
232 left join pg_catalog.pg_index i on i.indexrelid = c.oid
233 left join pg_catalog.pg_class c2 on i.indrelid = c2.oid
234 where
235 c.relkind in ('i', 'I')
236 {where_clause}
237 order by 1,2;
238 """.strip("\n")
239 )
240 )
241
242
243 def show_describe_relation(
244 item: "RelationCatalogItem",
245 driver: "HarlequinDriver",
246 ) -> None:
247 # sourced from psql -E \d+ {my rel}
248 # see https://stackoverflow.com/questions/60155968/using-results-of-d-command-in-psql
249 if item.parent is None:
250 driver.notify(
251 f"Could not describe {item.label} due to missing schema reference.",
252 severity="error",
253 )
254 return
255 driver.insert_text_in_new_buffer(
256 dedent(
257 f"""
258 with
259 index_columns as (
260 select i.indexrelid, c.oid as rel_oid, unnest(i.indkey) as attnum
261 from pg_catalog.pg_index i
262 join pg_catalog.pg_class c on c.oid = i.indrelid
263 where c.relname = '{item.label}'
264 ),
265 index_column_counts as (
266 select rel_oid, attnum, count(*) as cnt
267 from index_columns
268 group by 1, 2
269 ),
270 constraint_columns as (
271 select con.oid, c.oid as rel_oid, unnest(con.conkey) as attnum
272 from pg_catalog.pg_constraint con
273 join pg_catalog.pg_class c on con.conrelid = c.oid
274 where c.relname = '{item.label}'
275 ),
276 constraint_column_counts as (
277 select rel_oid, attnum, count(*) as cnt
278 from constraint_columns
279 group by 1, 2
280 ),
281 fkey_columns as (
282 select
283 src.relname as src_name,
284 src.relnamespace::regnamespace as src_schema,
285 c.oid as rel_oid,
286 unnest(con.confkey) as attnum
287 from pg_catalog.pg_constraint con
288 join pg_catalog.pg_class c on con.confrelid = c.oid
289 join pg_catalog.pg_class src on con.conrelid = src.oid
290 where c.relname = '{item.label}'
291 ),
292 fkey_references as (
293 select
294 rel_oid,
295 attnum,
296 string_agg(src_schema || '.' || src_name, ', ') as sources
297 from fkey_columns
298 group by 1, 2
299 )
300 select
301 a.attname as "Column",
302 pg_catalog.format_type(a.atttypid, a.atttypmod) as "Type",
303 coll.collname as "Collation",
304 case
305 when a.attnotnull is true then 'not null'
306 else ''
307 end as "Nullable",
308 pg_catalog.pg_get_expr(d.adbin, d.adrelid, true) as "Default",
309 case
310 a.attstorage
311 when 'p'
312 then 'plain'
313 when 'x'
314 then 'extended'
315 when 'e'
316 then 'external'
317 when 'm'
318 then 'main'
319 else a.attstorage::text
320 end as "Storage",
321 case
322 a.attcompression
323 when 'p'
324 then 'pglz'
325 when 'l'
326 then 'LZ4'
327 else a.attcompression::text
328 end as "Compression",
329 case
330 when a.attstattarget = -1
331 then null
332 else a.attstattarget
333 end as "Stats target",
334 case
335 when index_column_counts.cnt > 0 then true else false
336 end as "Has Index",
337 case
338 when constraint_column_counts.cnt > 0 then true else false
339 end as "Has Constraint",
340 fkey_references.sources as "Referenced by",
341 pg_catalog.col_description(a.attrelid, a.attnum) as "Description"
342 from pg_catalog.pg_attribute a
343 join pg_catalog.pg_class c on a.attrelid = c.oid
344 left join pg_catalog.pg_namespace n on n.oid = c.relnamespace
345 left join pg_catalog.pg_collation coll on coll.oid = a.attcollation
346 left join
347 pg_catalog.pg_type t
348 on (t.oid = a.atttypid and t.typcollation <> a.attcollation)
349 left join
350 pg_catalog.pg_attrdef d
351 on (a.attrelid = d.adrelid and a.attnum = d.adnum and a.atthasdef)
352 left join
353 index_column_counts
354 on a.attnum = index_column_counts.attnum
355 and a.attrelid = index_column_counts.rel_oid
356 left join
357 constraint_column_counts
358 on a.attnum = constraint_column_counts.attnum
359 and a.attrelid = constraint_column_counts.rel_oid
360 left join
361 fkey_references
362 on a.attnum = fkey_references.attnum
363 and a.attrelid = fkey_references.rel_oid
364 where
365 c.relname = '{item.label}'
366 and n.nspname = '{item.parent.label}'
367 and a.attnum > 0
368 and not a.attisdropped
369 order by a.attnum
370 """.strip("\n")
371 )
372 )
373
374
375 def show_describe_table_indexes(
376 item: "RelationCatalogItem",
377 driver: "HarlequinDriver",
378 ) -> None:
379 if item.parent is None:
380 driver.notify(
381 f"Could not describe {item.label} due to missing schema reference.",
382 severity="error",
383 )
384 return
385 driver.insert_text_in_new_buffer(
386 dedent(
387 f"""
388 with
389 index_columns as (
390 select
391 i.indexrelid, c.oid as rel_oid, unnest(i.indkey) as attnum
392 from pg_catalog.pg_index i
393 join pg_catalog.pg_class c on c.oid = i.indrelid
394 where c.relname = '{item.label}'
395 ),
396 index_column_names as (
397 select
398 index_columns.indexrelid,
399 string_agg(pg_attribute.attname, ', ') as columns
400 from index_columns
401 join
402 pg_catalog.pg_attribute
403 on index_columns.rel_oid = pg_attribute.attrelid
404 and index_columns.attnum = pg_attribute.attnum
405 group by 1
406 )
407
408 select
409 c.relname as "Table",
410 i.indexrelid::regclass::text as "Index Name",
411 pg_am.amname as "Index Type",
412 index_column_names.columns as "Columns",
413 i.indisprimary as "Is PK",
414 i.indisunique as "Is Unique",
415 i.indisclustered as "Is Clustered",
416 i.indisvalid as "Is Valid"
417 from pg_catalog.pg_index i
418 join pg_catalog.pg_class c on c.oid = i.indrelid
419 left join pg_catalog.pg_namespace n on n.oid = c.relnamespace
420 join pg_catalog.pg_class ic on i.indexrelid = ic.oid
421 join pg_catalog.pg_am on ic.relam = pg_am.oid
422 left join
423 index_column_names on i.indexrelid = index_column_names.indexrelid
424 where
425 c.relname = '{item.label}'
426 and n.nspname = '{item.parent.label}'
427 """.strip("\n")
428 )
429 )
430
431
432 def show_describe_table_constraints(
433 item: "RelationCatalogItem",
434 driver: "HarlequinDriver",
435 ) -> None:
436 if item.parent is None:
437 driver.notify(
438 f"Could not describe {item.label} due to missing schema reference.",
439 severity="error",
440 )
441 return
442 driver.insert_text_in_new_buffer(
443 dedent(
444 f"""
445 with
446 constraint_columns as (
447 select con.oid, c.oid as rel_oid, unnest(con.conkey) as attnum
448 from pg_catalog.pg_constraint con
449 join pg_catalog.pg_class c on con.conrelid = c.oid
450 where c.relname = '{item.label}'
451 ),
452 constraint_column_names as (
453 select
454 constraint_columns.oid,
455 string_agg(pg_attribute.attname, ', ') as columns
456 from constraint_columns
457 join
458 pg_catalog.pg_attribute
459 on constraint_columns.rel_oid = pg_attribute.attrelid
460 and constraint_columns.attnum = pg_attribute.attnum
461 group by 1
462 ),
463 constraint_foreign_columns as (
464 select con.oid, c.oid as rel_oid, unnest(con.confkey) as attnum
465 from pg_catalog.pg_constraint con
466 join pg_catalog.pg_class c on con.conrelid = c.oid
467 where c.relname = '{item.label}'
468 ),
469 constraint_foreign_column_names as (
470 select
471 constraint_foreign_columns.oid,
472 string_agg(pg_attribute.attname, ', ') as columns
473 from constraint_foreign_columns
474 join
475 pg_catalog.pg_attribute
476 on constraint_foreign_columns.rel_oid = pg_attribute.attrelid
477 and constraint_foreign_columns.attnum = pg_attribute.attnum
478 group by 1
479 )
480
481 select
482 c.relname as "Table",
483 con.conname as "Constraint name",
484 case
485 con.contype
486 when 'c'
487 then 'Check'
488 when 'n'
489 then 'Not Null'
490 when 'p'
491 then 'Primary Key'
492 when 'f'
493 then 'Foreign Key'
494 when 'u'
495 then 'Unique'
496 when 't'
497 then 'Trigger'
498 when 'x'
499 then 'Exclusion'
500 else con.contype::text
501 end as "Constraint Type",
502 constraint_column_names.columns as "Columns",
503 c.relnamespace::regnamespace
504 || '.'
505 || fc.relname
506 || '('
507 || constraint_foreign_column_names.columns
508 || ')' as "References",
509 con.conislocal as "Is Local",
510 con.convalidated as "Is Validated",
511 case
512 con.confupdtype
513 when 'a'
514 then 'no action'
515 when 'r'
516 then 'restrict'
517 when 'c'
518 then 'cascade'
519 when 'n'
520 then 'set null'
521 when 'd'
522 then 'set default'
523 else con.confupdtype::text
524 end as "FK Update Type",
525 case
526 con.confdeltype
527 when 'a'
528 then 'no action'
529 when 'r'
530 then 'restrict'
531 when 'c'
532 then 'cascade'
533 when 'n'
534 then 'set null'
535 when 'd'
536 then 'set default'
537 else con.confdeltype::text
538 end as "FK Delete Type",
539 case
540 con.confmatchtype
541 when 's'
542 then 'simple'
543 when 'f'
544 then 'full'
545 when 'p'
546 then 'partial'
547 else con.confmatchtype::text
548 end as "FK Match Type"
549 from pg_catalog.pg_constraint con
550 join pg_catalog.pg_class c on con.conrelid = c.oid
551 join pg_catalog.pg_namespace n on n.oid = c.relnamespace
552 left join pg_catalog.pg_class fc on con.confrelid = fc.oid
553 left join
554 constraint_column_names on con.oid = constraint_column_names.oid
555 left join
556 constraint_foreign_column_names
557 on con.oid = constraint_foreign_column_names.oid
558 where
559 c.relname = '{item.label}'
560 and n.nspname = '{item.parent.label}'
561 """.strip("\n")
562 )
563 )
564
565
566 def show_view_definition(
567 item: "ViewCatalogItem",
568 driver: "HarlequinDriver",
569 ) -> None:
570 if item.connection is None or item.parent is None:
571 return
572 view_def_query = f"""
573 select pg_catalog.pg_get_viewdef(c.oid, true)
574 from pg_catalog.pg_class as c
575 left join pg_catalog.pg_namespace n on n.oid = c.relnamespace
576 where c.relname = '{item.label}' and n.nspname = '{item.parent.label}'
577 """.strip("\n")
578 cur = item.connection.execute(view_def_query)
579 if cur is None:
580 return
581 result = cur.fetchall()
582 if result is None:
583 return
584 view_def: str = result[0][0]
585 driver.insert_text_in_new_buffer(
586 f"-- View definition for {item.query_name}\n" + view_def
587 )
588
589
590 def insert_columns_at_cursor(
591 item: "RelationCatalogItem",
592 driver: "HarlequinDriver",
593 ) -> None:
594 if item.loaded:
595 cols: Sequence["CatalogItem" | "ColumnCatalogItem"] = item.children
596 else:
597 cols = item.fetch_children()
598 driver.insert_text_at_selection(text=",\n".join(c.query_name for c in cols))