forked from datajoint/datajoint-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.py
More file actions
1289 lines (1085 loc) · 34.3 KB
/
base.py
File metadata and controls
1289 lines (1085 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Abstract base class for database backend adapters.
This module defines the interface that all database adapters must implement
to support multiple database backends (MySQL, PostgreSQL, etc.) in DataJoint.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
class DatabaseAdapter(ABC):
"""
Abstract base class for database backend adapters.
Adapters provide database-specific implementations for SQL generation,
type mapping, error translation, and connection management.
"""
# =========================================================================
# Connection Management
# =========================================================================
@abstractmethod
def connect(
self,
host: str,
port: int,
user: str,
password: str,
**kwargs: Any,
) -> Any:
"""
Establish database connection.
Parameters
----------
host : str
Database server hostname.
port : int
Database server port.
user : str
Username for authentication.
password : str
Password for authentication.
**kwargs : Any
Additional backend-specific connection parameters.
Returns
-------
Any
Database connection object (backend-specific).
"""
...
@abstractmethod
def close(self, connection: Any) -> None:
"""
Close the database connection.
Parameters
----------
connection : Any
Database connection object to close.
"""
...
@abstractmethod
def ping(self, connection: Any) -> bool:
"""
Check if connection is alive.
Parameters
----------
connection : Any
Database connection object to check.
Returns
-------
bool
True if connection is alive, False otherwise.
"""
...
@abstractmethod
def get_connection_id(self, connection: Any) -> int:
"""
Get the current connection/backend process ID.
Parameters
----------
connection : Any
Database connection object.
Returns
-------
int
Connection or process ID.
"""
...
@property
@abstractmethod
def default_port(self) -> int:
"""
Default port for this database backend.
Returns
-------
int
Default port number (3306 for MySQL, 5432 for PostgreSQL).
"""
...
@property
@abstractmethod
def backend(self) -> str:
"""
Backend identifier string.
Returns
-------
str
Backend name: 'mysql' or 'postgresql'.
"""
...
@abstractmethod
def get_cursor(self, connection: Any, as_dict: bool = False) -> Any:
"""
Get a cursor from the database connection.
Parameters
----------
connection : Any
Database connection object.
as_dict : bool, optional
If True, return cursor that yields rows as dictionaries.
If False, return cursor that yields rows as tuples.
Default False.
Returns
-------
Any
Database cursor object (backend-specific).
"""
...
# =========================================================================
# SQL Syntax
# =========================================================================
@abstractmethod
def quote_identifier(self, name: str) -> str:
"""
Quote an identifier (table/column name) for this backend.
Parameters
----------
name : str
Identifier to quote.
Returns
-------
str
Quoted identifier (e.g., `name` for MySQL, "name" for PostgreSQL).
"""
...
@abstractmethod
def split_full_table_name(self, full_table_name: str) -> tuple[str, str]:
"""
Split a fully-qualified table name into schema and table components.
Inverse of quoting: strips backend-specific identifier quotes
and splits into (schema, table).
Parameters
----------
full_table_name : str
Quoted full table name (e.g., ```\\`schema\\`.\\`table\\` ``` or
``"schema"."table"``).
Returns
-------
tuple[str, str]
(schema_name, table_name) with quotes stripped.
"""
...
@abstractmethod
def quote_string(self, value: str) -> str:
"""
Quote a string literal for this backend.
Parameters
----------
value : str
String value to quote.
Returns
-------
str
Quoted string literal with proper escaping.
"""
...
@abstractmethod
def get_master_table_name(self, part_table: str) -> str | None:
"""
Extract master table name from a part table name.
Parameters
----------
part_table : str
Full table name (e.g., `schema`.`master__part` for MySQL,
"schema"."master__part" for PostgreSQL).
Returns
-------
str or None
Master table name if part_table is a part table, None otherwise.
"""
...
@property
@abstractmethod
def parameter_placeholder(self) -> str:
"""
Parameter placeholder style for this backend.
Returns
-------
str
Placeholder string (e.g., '%s' for MySQL/psycopg2, '?' for SQLite).
"""
...
def make_full_table_name(self, database: str, table_name: str) -> str:
"""
Construct a fully-qualified table name for this backend.
Default implementation produces a two-part name (``schema.table``).
Backends that require additional namespace levels (e.g., Databricks
``catalog.schema.table``) should override this method.
Parameters
----------
database : str
Schema/database name.
table_name : str
Table name (including tier prefix).
Returns
-------
str
Fully-qualified, quoted table name.
"""
return f"{self.quote_identifier(database)}.{self.quote_identifier(table_name)}"
@property
def foreign_key_action_clause(self) -> str:
"""
Referential action clause appended to FOREIGN KEY declarations.
Default: ``ON UPDATE CASCADE ON DELETE RESTRICT`` (MySQL/PostgreSQL).
Backends that don't support referential actions (e.g., Databricks)
should override to return ``""``.
"""
return " ON UPDATE CASCADE ON DELETE RESTRICT"
# =========================================================================
# Type Mapping
# =========================================================================
@abstractmethod
def core_type_to_sql(self, core_type: str) -> str:
"""
Convert a DataJoint core type to backend SQL type.
Parameters
----------
core_type : str
DataJoint core type (e.g., 'int64', 'float32', 'uuid').
Returns
-------
str
Backend SQL type (e.g., 'bigint', 'float', 'binary(16)').
Raises
------
ValueError
If core_type is not a valid DataJoint core type.
"""
...
@abstractmethod
def sql_type_to_core(self, sql_type: str) -> str | None:
"""
Convert a backend SQL type to DataJoint core type (if mappable).
Parameters
----------
sql_type : str
Backend SQL type.
Returns
-------
str or None
DataJoint core type if mappable, None otherwise.
"""
...
# =========================================================================
# DDL Generation
# =========================================================================
@abstractmethod
def create_schema_sql(self, schema_name: str) -> str:
"""
Generate CREATE SCHEMA/DATABASE statement.
Parameters
----------
schema_name : str
Name of schema/database to create.
Returns
-------
str
CREATE SCHEMA/DATABASE SQL statement.
"""
...
@abstractmethod
def drop_schema_sql(self, schema_name: str, if_exists: bool = True) -> str:
"""
Generate DROP SCHEMA/DATABASE statement.
Parameters
----------
schema_name : str
Name of schema/database to drop.
if_exists : bool, optional
Include IF EXISTS clause. Default True.
Returns
-------
str
DROP SCHEMA/DATABASE SQL statement.
"""
...
@abstractmethod
def create_table_sql(
self,
table_name: str,
columns: list[dict[str, Any]],
primary_key: list[str],
foreign_keys: list[dict[str, Any]],
indexes: list[dict[str, Any]],
comment: str | None = None,
) -> str:
"""
Generate CREATE TABLE statement.
Parameters
----------
table_name : str
Name of table to create.
columns : list[dict]
Column definitions with keys: name, type, nullable, default, comment.
primary_key : list[str]
List of primary key column names.
foreign_keys : list[dict]
Foreign key definitions with keys: columns, ref_table, ref_columns.
indexes : list[dict]
Index definitions with keys: columns, unique.
comment : str, optional
Table comment.
Returns
-------
str
CREATE TABLE SQL statement.
"""
...
@abstractmethod
def drop_table_sql(self, table_name: str, if_exists: bool = True) -> str:
"""
Generate DROP TABLE statement.
Parameters
----------
table_name : str
Name of table to drop.
if_exists : bool, optional
Include IF EXISTS clause. Default True.
Returns
-------
str
DROP TABLE SQL statement.
"""
...
@abstractmethod
def alter_table_sql(
self,
table_name: str,
add_columns: list[dict[str, Any]] | None = None,
drop_columns: list[str] | None = None,
modify_columns: list[dict[str, Any]] | None = None,
) -> str:
"""
Generate ALTER TABLE statement.
Parameters
----------
table_name : str
Name of table to alter.
add_columns : list[dict], optional
Columns to add with keys: name, type, nullable, default, comment.
drop_columns : list[str], optional
Column names to drop.
modify_columns : list[dict], optional
Columns to modify with keys: name, type, nullable, default, comment.
Returns
-------
str
ALTER TABLE SQL statement.
"""
...
@abstractmethod
def add_comment_sql(
self,
object_type: str,
object_name: str,
comment: str,
) -> str | None:
"""
Generate comment statement (may be None if embedded in CREATE).
Parameters
----------
object_type : str
Type of object ('table', 'column').
object_name : str
Fully qualified object name.
comment : str
Comment text.
Returns
-------
str or None
COMMENT statement, or None if comments are inline in CREATE.
"""
...
# =========================================================================
# DML Generation
# =========================================================================
@abstractmethod
def insert_sql(
self,
table_name: str,
columns: list[str],
on_duplicate: str | None = None,
) -> str:
"""
Generate INSERT statement.
Parameters
----------
table_name : str
Name of table to insert into.
columns : list[str]
Column names to insert.
on_duplicate : str, optional
Duplicate handling: 'ignore', 'replace', 'update', or None.
Returns
-------
str
INSERT SQL statement with parameter placeholders.
"""
...
@abstractmethod
def update_sql(
self,
table_name: str,
set_columns: list[str],
where_columns: list[str],
) -> str:
"""
Generate UPDATE statement.
Parameters
----------
table_name : str
Name of table to update.
set_columns : list[str]
Column names to set.
where_columns : list[str]
Column names for WHERE clause.
Returns
-------
str
UPDATE SQL statement with parameter placeholders.
"""
...
@abstractmethod
def delete_sql(self, table_name: str) -> str:
"""
Generate DELETE statement (WHERE clause added separately).
Parameters
----------
table_name : str
Name of table to delete from.
Returns
-------
str
DELETE SQL statement without WHERE clause.
"""
...
@abstractmethod
def upsert_on_duplicate_sql(
self,
table_name: str,
columns: list[str],
primary_key: list[str],
num_rows: int,
) -> str:
"""
Generate INSERT ... ON DUPLICATE KEY UPDATE (MySQL) or
INSERT ... ON CONFLICT ... DO UPDATE (PostgreSQL) statement.
Parameters
----------
table_name : str
Fully qualified table name (with quotes).
columns : list[str]
Column names to insert (unquoted).
primary_key : list[str]
Primary key column names (unquoted) for conflict detection.
num_rows : int
Number of rows to insert (for generating placeholders).
Returns
-------
str
Upsert SQL statement with placeholders.
Examples
--------
MySQL:
INSERT INTO `table` (a, b, c) VALUES (%s, %s, %s), (%s, %s, %s)
ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES(b), c = VALUES(c)
PostgreSQL:
INSERT INTO "table" (a, b, c) VALUES (%s, %s, %s), (%s, %s, %s)
ON CONFLICT (a) DO UPDATE SET b = EXCLUDED.b, c = EXCLUDED.c
"""
...
@abstractmethod
def skip_duplicates_clause(
self,
full_table_name: str,
primary_key: list[str],
) -> str:
"""
Generate clause to skip duplicate key insertions.
For MySQL: ON DUPLICATE KEY UPDATE pk=table.pk (no-op update)
For PostgreSQL: ON CONFLICT (pk_cols) DO NOTHING
Parameters
----------
full_table_name : str
Fully qualified table name (with quotes).
primary_key : list[str]
Primary key column names (unquoted).
Returns
-------
str
SQL clause to append to INSERT statement.
"""
...
@property
def supports_inline_indexes(self) -> bool:
"""
Whether this backend supports inline INDEX in CREATE TABLE.
MySQL supports inline index definitions in CREATE TABLE.
PostgreSQL requires separate CREATE INDEX statements.
Returns
-------
bool
True for MySQL, False for PostgreSQL.
"""
return True # Default for MySQL, override in PostgreSQL
def create_index_ddl(
self,
full_table_name: str,
columns: list[str],
unique: bool = False,
index_name: str | None = None,
) -> str:
"""
Generate CREATE INDEX statement.
Parameters
----------
full_table_name : str
Fully qualified table name (with quotes).
columns : list[str]
Column names to index (unquoted).
unique : bool, optional
If True, create a unique index.
index_name : str, optional
Custom index name. If None, auto-generate from table/columns.
Returns
-------
str
CREATE INDEX SQL statement.
"""
quoted_cols = ", ".join(self.quote_identifier(col) for col in columns)
# Generate index name from table and columns if not provided
if index_name is None:
# Extract table name from full_table_name for index naming
table_part = full_table_name.split(".")[-1].strip('`"')
col_part = "_".join(columns)[:30] # Truncate for long column lists
index_name = f"idx_{table_part}_{col_part}"
unique_clause = "UNIQUE " if unique else ""
return f"CREATE {unique_clause}INDEX {self.quote_identifier(index_name)} ON {full_table_name} ({quoted_cols})"
# =========================================================================
# Introspection
# =========================================================================
@abstractmethod
def list_schemas_sql(self) -> str:
"""
Generate query to list all schemas/databases.
Returns
-------
str
SQL query to list schemas.
"""
...
@abstractmethod
def schema_exists_sql(self, schema_name: str) -> str:
"""
Generate query to check if a schema exists.
Parameters
----------
schema_name : str
Name of schema to check.
Returns
-------
str
SQL query that returns a row if the schema exists.
"""
...
@abstractmethod
def list_tables_sql(self, schema_name: str, pattern: str | None = None) -> str:
"""
Generate query to list tables in a schema.
Parameters
----------
schema_name : str
Name of schema to list tables from.
pattern : str, optional
LIKE pattern to filter table names. Use %% for % in SQL.
Returns
-------
str
SQL query to list tables.
"""
...
@abstractmethod
def get_table_info_sql(self, schema_name: str, table_name: str) -> str:
"""
Generate query to get table metadata (comment, engine, etc.).
Parameters
----------
schema_name : str
Schema name.
table_name : str
Table name.
Returns
-------
str
SQL query to get table info.
"""
...
@abstractmethod
def get_columns_sql(self, schema_name: str, table_name: str) -> str:
"""
Generate query to get column definitions.
Parameters
----------
schema_name : str
Schema name.
table_name : str
Table name.
Returns
-------
str
SQL query to get column definitions.
"""
...
@abstractmethod
def get_primary_key_sql(self, schema_name: str, table_name: str) -> str:
"""
Generate query to get primary key columns.
Parameters
----------
schema_name : str
Schema name.
table_name : str
Table name.
Returns
-------
str
SQL query to get primary key columns.
"""
...
@abstractmethod
def get_foreign_keys_sql(self, schema_name: str, table_name: str) -> str:
"""
Generate query to get foreign key constraints.
Parameters
----------
schema_name : str
Schema name.
table_name : str
Table name.
Returns
-------
str
SQL query to get foreign key constraints.
"""
...
@abstractmethod
def load_primary_keys_sql(self, schemas_list: str, like_pattern: str) -> str:
"""
Generate query to load primary key columns for all tables across schemas.
Used by the dependency graph to build the schema graph.
Parameters
----------
schemas_list : str
Comma-separated, quoted schema names for an IN clause.
like_pattern : str
SQL LIKE pattern to exclude (e.g., "'~%%'" for internal tables).
Returns
-------
str
SQL query returning rows with columns:
- tab: fully qualified table name (quoted)
- column_name: primary key column name
"""
...
@abstractmethod
def load_foreign_keys_sql(self, schemas_list: str, like_pattern: str) -> str:
"""
Generate query to load foreign key relationships across schemas.
Used by the dependency graph to build the schema graph.
Parameters
----------
schemas_list : str
Comma-separated, quoted schema names for an IN clause.
like_pattern : str
SQL LIKE pattern to exclude (e.g., "'~%%'" for internal tables).
Returns
-------
str
SQL query returning rows (as dicts) with columns:
- constraint_name: FK constraint name
- referencing_table: fully qualified child table name (quoted)
- referenced_table: fully qualified parent table name (quoted)
- column_name: FK column in child table
- referenced_column_name: referenced column in parent table
"""
...
@abstractmethod
def get_constraint_info_sql(self, constraint_name: str, schema_name: str, table_name: str) -> str:
"""
Generate query to get foreign key constraint details from information_schema.
Used during cascade delete to determine FK columns when error message
doesn't provide full details.
Parameters
----------
constraint_name : str
Name of the foreign key constraint.
schema_name : str
Schema/database name of the child table.
table_name : str
Name of the child table.
Returns
-------
str
SQL query that returns rows with columns:
- fk_attrs: foreign key column name in child table
- parent: parent table name (quoted, with schema)
- pk_attrs: referenced column name in parent table
"""
...
@abstractmethod
def parse_foreign_key_error(self, error_message: str) -> dict[str, str | list[str] | None] | None:
"""
Parse a foreign key violation error message to extract constraint details.
Used during cascade delete to identify which child table is preventing
deletion and what columns are involved.
Parameters
----------
error_message : str
The error message from a foreign key constraint violation.
Returns
-------
dict or None
Dictionary with keys if successfully parsed:
- child: child table name (quoted with schema if available)
- name: constraint name (quoted)
- fk_attrs: list of foreign key column names (may be None if not in message)
- parent: parent table name (quoted, may be None if not in message)
- pk_attrs: list of parent key column names (may be None if not in message)
Returns None if error message doesn't match FK violation pattern.
Examples
--------
MySQL error:
"Cannot delete or update a parent row: a foreign key constraint fails
(`schema`.`child`, CONSTRAINT `fk_name` FOREIGN KEY (`child_col`)
REFERENCES `parent` (`parent_col`))"
PostgreSQL error:
"update or delete on table \"parent\" violates foreign key constraint
\"child_parent_id_fkey\" on table \"child\"
DETAIL: Key (parent_id)=(1) is still referenced from table \"child\"."
"""
...
@abstractmethod
def get_indexes_sql(self, schema_name: str, table_name: str) -> str:
"""
Generate query to get index definitions.
Parameters
----------
schema_name : str
Schema name.
table_name : str
Table name.
Returns
-------
str
SQL query to get index definitions.
"""
...
@abstractmethod
def parse_column_info(self, row: dict[str, Any]) -> dict[str, Any]:
"""
Parse a column info row into standardized format.
Parameters
----------
row : dict
Raw column info row from database introspection query.
Returns
-------
dict
Standardized column info with keys: name, type, nullable,
default, comment, etc.
"""
...
# =========================================================================
# Transactions
# =========================================================================
@abstractmethod
def start_transaction_sql(self, isolation_level: str | None = None) -> str:
"""
Generate START TRANSACTION statement.
Parameters
----------
isolation_level : str, optional
Transaction isolation level.
Returns
-------
str
START TRANSACTION SQL statement.
"""
...
@abstractmethod
def commit_sql(self) -> str:
"""
Generate COMMIT statement.
Returns
-------
str
COMMIT SQL statement.
"""
...
@abstractmethod
def rollback_sql(self) -> str:
"""
Generate ROLLBACK statement.
Returns
-------
str
ROLLBACK SQL statement.
"""
...
# =========================================================================
# Functions and Expressions
# =========================================================================
@abstractmethod
def current_timestamp_expr(self, precision: int | None = None) -> str:
"""
Expression for current timestamp.
Parameters
----------
precision : int, optional
Fractional seconds precision (0-6).
Returns
-------
str
SQL expression for current timestamp.
"""
...