-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathsql.py
1786 lines (1459 loc) · 60.3 KB
/
sql.py
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
"""Common SQL connectors for Streams and Sinks."""
from __future__ import annotations
import functools
import logging
import sys
import typing as t
import warnings
from collections import UserString
from contextlib import contextmanager
from datetime import datetime
from functools import lru_cache
import sqlalchemy as sa
from sqlalchemy.engine import reflection
from singer_sdk import typing as th
from singer_sdk._singerlib import CatalogEntry, MetadataMapping, Schema
from singer_sdk.exceptions import ConfigValidationError
from singer_sdk.helpers._compat import SingerSDKDeprecationWarning
from singer_sdk.helpers._util import dump_json, load_json
from singer_sdk.helpers.capabilities import TargetLoadMethods
if sys.version_info < (3, 13):
from typing_extensions import deprecated
else:
from warnings import deprecated
if sys.version_info < (3, 10):
from typing_extensions import TypeAlias
else:
from typing import TypeAlias # noqa: ICN003
if t.TYPE_CHECKING:
from sqlalchemy.engine import Engine
from sqlalchemy.engine.reflection import Inspector
class FullyQualifiedName(UserString):
"""A fully qualified table name.
This class provides a simple way to represent a fully qualified table name
as a single object. The string representation of this object is the fully
qualified table name, with the parts separated by periods.
The parts of the fully qualified table name are:
- database
- schema
- table
The database and schema are optional. If only the table name is provided,
the string representation of the object will be the table name alone.
Example:
```
table_name = FullyQualifiedName("my_table", "my_schema", "my_db")
print(table_name) # my_db.my_schema.my_table
```
"""
def __init__(
self,
*,
table: str = "",
schema: str | None = None,
database: str | None = None,
delimiter: str = ".",
) -> None:
"""Initialize the fully qualified table name.
Args:
table: The name of the table.
schema: The name of the schema. Defaults to None.
database: The name of the database. Defaults to None.
delimiter: The delimiter to use between parts. Defaults to '.'.
Raises:
ValueError: If the fully qualified name could not be generated.
"""
self.table = table
self.schema = schema
self.database = database
self.delimiter = delimiter
parts = []
if self.database:
parts.append(self.prepare_part(self.database))
if self.schema:
parts.append(self.prepare_part(self.schema))
if self.table:
parts.append(self.prepare_part(self.table))
if not parts:
raise ValueError(
"Could not generate fully qualified name: "
+ ":".join(
[
self.database or "(unknown-db)",
self.schema or "(unknown-schema)",
self.table or "(unknown-table-name)",
],
),
)
super().__init__(self.delimiter.join(parts))
def prepare_part(self, part: str) -> str: # noqa: PLR6301
"""Prepare a part of the fully qualified name.
Args:
part: The part to prepare.
Returns:
The prepared part.
"""
return part
class SQLToJSONSchema:
"""SQLAlchemy to JSON Schema type mapping helper.
This class provides a mapping from SQLAlchemy types to JSON Schema types.
.. versionadded:: 0.41.0
.. versionchanged:: 0.43.0
Added the :meth:`singer_sdk.connectors.sql.SQLToJSONSchema.from_config` class
method.
"""
@classmethod
def from_config(cls: type[SQLToJSONSchema], config: dict) -> SQLToJSONSchema: # noqa: ARG003
"""Create a new instance from a configuration dictionary.
Override this to instantiate this converter with values from the tap's
configuration dictionary.
.. code-block:: python
class CustomSQLToJSONSchema(SQLToJSONSchema):
def __init__(self, *, my_custom_option, **kwargs):
super().__init__(**kwargs)
self.my_custom_option = my_custom_option
@classmethod
def from_config(cls, config):
return cls(my_custom_option=config.get("my_custom_option"))
Args:
config: The configuration dictionary.
Returns:
A new instance of the class.
"""
return cls()
@functools.singledispatchmethod
def to_jsonschema(self, column_type: sa.types.TypeEngine) -> dict: # noqa: ARG002, D102, PLR6301
return th.StringType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def datetime_to_jsonschema(self, column_type: sa.types.DateTime) -> dict: # noqa: ARG002, PLR6301
"""Return a JSON Schema representation of a generic datetime type.
Args:
column_type (:column_type:`DateTime`): The column type.
"""
return th.DateTimeType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def date_to_jsonschema(self, column_type: sa.types.Date) -> dict: # noqa: ARG002, PLR6301
"""Return a JSON Schema representation of a date type.
Args:
column_type (:column_type:`Date`): The column type.
"""
return th.DateType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def time_to_jsonschema(self, column_type: sa.types.Time) -> dict: # noqa: ARG002, PLR6301
"""Return a JSON Schema representation of a time type.
Args:
column_type (:column_type:`Time`): The column type.
"""
return th.TimeType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def integer_to_jsonschema(self, column_type: sa.types.Integer) -> dict: # noqa: ARG002, PLR6301
"""Return a JSON Schema representation of a an integer type.
Args:
column_type (:column_type:`Integer`): The column type.
"""
return th.IntegerType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def float_to_jsonschema(self, column_type: sa.types.Numeric) -> dict: # noqa: ARG002, PLR6301
"""Return a JSON Schema representation of a generic number type.
Args:
column_type (:column_type:`Numeric`): The column type.
"""
return th.NumberType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def string_to_jsonschema(self, column_type: sa.types.String) -> dict: # noqa: PLR6301
"""Return a JSON Schema representation of a generic string type.
Args:
column_type (:column_type:`String`): The column type.
.. versionchanged:: 0.41.0
The :column_type:`length <String.params.length>` attribute is now used to
determine the maximum length of the string type.
"""
if column_type.length:
return th.StringType(max_length=column_type.length).type_dict # type: ignore[no-any-return]
return th.StringType.type_dict # type: ignore[no-any-return]
@to_jsonschema.register
def boolean_to_jsonschema(self, column_type: sa.types.Boolean) -> dict: # noqa: ARG002, PLR6301
"""Return a JSON Schema representation of a boolean type.
Args:
column_type (:column_type:`Boolean`): The column type.
"""
return th.BooleanType.type_dict # type: ignore[no-any-return]
JSONtoSQLHandler: TypeAlias = t.Union[
type[sa.types.TypeEngine],
t.Callable[[dict], sa.types.TypeEngine],
]
class JSONSchemaToSQL:
"""A configurable mapper for converting JSON Schema types to SQLAlchemy types.
This class provides a mapping from JSON Schema types to SQLAlchemy types.
.. versionadded:: 0.42.0
.. versionchanged:: 0.44.0
Added the
:meth:`singer_sdk.connectors.sql.JSONSchemaToSQL.register_sql_datatype_handler`
method to map custom ``x-sql-datatype`` annotations into SQLAlchemy types.
"""
def __init__(self, *, max_varchar_length: int | None = None) -> None:
"""Initialize the mapper with default type mappings.
Args:
max_varchar_length: The absolute maximum length for VARCHAR columns that
the database supports.
"""
self._max_varchar_length = max_varchar_length
# Default type mappings
self._type_mapping: dict[str, JSONtoSQLHandler] = {
"string": self._handle_string_type,
"integer": sa.types.INTEGER,
"number": sa.types.DECIMAL,
"boolean": sa.types.BOOLEAN,
"object": sa.types.VARCHAR,
"array": sa.types.VARCHAR,
}
# Format handlers for string types
self._format_handlers: dict[str, JSONtoSQLHandler] = {
# Default date-like formats
"date-time": sa.types.DATETIME,
"time": sa.types.TIME,
"date": sa.types.DATE,
# Common string formats with sensible defaults
"uuid": sa.types.UUID,
"email": lambda _: sa.types.VARCHAR(254), # RFC 5321
"uri": lambda _: sa.types.VARCHAR(2083), # Common browser limit
"hostname": lambda _: sa.types.VARCHAR(253), # RFC 1035
"ipv4": lambda _: sa.types.VARCHAR(15),
"ipv6": lambda _: sa.types.VARCHAR(45),
}
self._sql_datatype_mapping: dict[str, JSONtoSQLHandler] = {}
self._fallback_type: type[sa.types.TypeEngine] = sa.types.VARCHAR
def _invoke_handler( # noqa: PLR6301
self,
handler: JSONtoSQLHandler,
schema: dict,
) -> sa.types.TypeEngine:
"""Invoke a handler, handling both type classes and callables.
Args:
handler: The handler to invoke.
schema: The schema to pass to callable handlers.
Returns:
The resulting SQLAlchemy type.
"""
if isinstance(handler, type):
return handler() # type: ignore[no-any-return]
return handler(schema)
@property
def fallback_type(self) -> type[sa.types.TypeEngine]:
"""Return the fallback type.
Returns:
The fallback type.
"""
return self._fallback_type
@fallback_type.setter
def fallback_type(self, value: type[sa.types.TypeEngine]) -> None:
"""Set the fallback type.
Args:
value: The new fallback type.
"""
self._fallback_type = value
def register_type_handler(self, json_type: str, handler: JSONtoSQLHandler) -> None:
"""Register a custom type handler.
Args:
json_type: The JSON Schema type to handle.
handler: Either a SQLAlchemy type class or a callable that takes a schema
dict and returns a SQLAlchemy type instance.
"""
self._type_mapping[json_type] = handler
def register_format_handler(
self,
format_name: str,
handler: JSONtoSQLHandler,
) -> None:
"""Register a custom format handler.
Args:
format_name: The format string (e.g., "date-time", "email", "custom-format").
handler: Either a SQLAlchemy type class or a callable that takes a schema
dict and returns a SQLAlchemy type instance.
""" # noqa: E501
self._format_handlers[format_name] = handler
def register_sql_datatype_handler(
self,
sql_datatype: str,
handler: JSONtoSQLHandler,
) -> None:
"""Register a custom ``x-sql-datatype`` handler.
Args:
sql_datatype: The x-sql-datatype string.
handler: Either a SQLAlchemy type class or a callable that takes a schema
dict and returns a SQLAlchemy type instance.
Example:
>>> from sqlalchemy.types import SMALLINT
>>> to_sql = JSONSchemaToSQL()
>>> to_sql.register_sql_datatype_handler("smallint", SMALLINT)
"""
self._sql_datatype_mapping[sql_datatype] = handler
def handle_multiple_types(self, types: t.Sequence[str]) -> sa.types.TypeEngine: # noqa: ARG002, PLR6301
"""Handle multiple types by returning a VARCHAR.
Args:
types: The list of types to handle.
Returns:
A VARCHAR type.
"""
return sa.types.VARCHAR()
def handle_raw_string(self, schema: dict) -> sa.types.TypeEngine:
"""Handle a string type generically.
Args:
schema: The JSON Schema object.
Returns:
Appropriate SQLAlchemy type.
"""
max_length: int | None = schema.get("maxLength")
if max_length and self._max_varchar_length:
max_length = min(max_length, self._max_varchar_length)
return sa.types.VARCHAR(max_length)
def _get_type_from_schema(self, schema: dict) -> sa.types.TypeEngine | None:
"""Try to get a SQL type from a single schema object.
Args:
schema: The JSON Schema object.
Returns:
SQL type if one can be determined, None otherwise.
"""
# Check x-sql-datatype first
if x_sql_datatype := schema.get("x-sql-datatype"):
if handler := self._sql_datatype_mapping.get(x_sql_datatype):
return self._invoke_handler(handler, schema)
warnings.warn(
f"This target does not support the x-sql-datatype '{x_sql_datatype}'",
UserWarning,
stacklevel=2,
)
# Check if this is a string with format then
if schema.get("type") == "string" and "format" in schema: # noqa: SIM102
if (format_type := self._handle_format(schema)) is not None:
return format_type
# Then check regular types
if schema_type := schema.get("type"):
if isinstance(schema_type, (list, tuple)):
# Filter out null type if present
non_null_types = [t for t in schema_type if t != "null"]
# If we have multiple non-null types, use VARCHAR
if len(non_null_types) > 1:
self.handle_multiple_types(non_null_types)
# If we have exactly one non-null type, use its handler
if len(non_null_types) == 1 and non_null_types[0] in self._type_mapping:
handler = self._type_mapping[non_null_types[0]]
return self._invoke_handler(handler, schema)
elif type_handler := self._type_mapping.get(schema_type):
return self._invoke_handler(type_handler, schema)
return None
def _handle_format(self, schema: dict) -> sa.types.TypeEngine | None:
"""Handle format-specific type conversion.
Args:
schema: The JSON Schema object.
Returns:
The format-specific SQL type if applicable, None otherwise.
"""
if "format" not in schema:
return None
format_string: str = schema["format"]
if handler := self._format_handlers.get(format_string):
return self._invoke_handler(handler, schema)
return None
def _handle_string_type(self, schema: dict) -> sa.types.TypeEngine:
"""Handle string type conversion with special cases for formats.
Args:
schema: The JSON Schema object.
Returns:
Appropriate SQLAlchemy type.
"""
# Check for format-specific handling first
if format_type := self._handle_format(schema):
return format_type
return self.handle_raw_string(schema)
def to_sql_type(self, schema: dict) -> sa.types.TypeEngine:
"""Convert a JSON Schema type definition to a SQLAlchemy type.
Args:
schema: The JSON Schema object.
Returns:
The corresponding SQLAlchemy type.
"""
if sql_type := self._get_type_from_schema(schema):
return sql_type
# Handle anyOf
if "anyOf" in schema:
for subschema in schema["anyOf"]:
# Skip null types in anyOf
if subschema.get("type") == "null":
continue
if sql_type := self._get_type_from_schema(subschema):
return sql_type
# Fallback
return self.fallback_type()
class SQLConnector: # noqa: PLR0904
"""Base class for SQLAlchemy-based connectors.
The connector class serves as a wrapper around the SQL connection.
The functions of the connector are:
- connecting to the source
- generating SQLAlchemy connection and engine objects
- discovering schema catalog entries
- performing type conversions to/from JSONSchema types
- dialect-specific functions, such as escaping and fully qualified names
"""
allow_column_add: bool = True # Whether ADD COLUMN is supported.
allow_column_rename: bool = True # Whether RENAME COLUMN is supported.
allow_column_alter: bool = False # Whether altering column types is supported.
allow_merge_upsert: bool = False # Whether MERGE UPSERT is supported.
allow_overwrite: bool = False # Whether overwrite load method is supported.
allow_temp_tables: bool = True # Whether temp tables are supported.
_cached_engine: Engine | None = None
#: The absolute maximum length for VARCHAR columns that the database supports.
max_varchar_length: int | None = None
#: The SQL-to-JSON type mapper class for this SQL connector. Override this property
#: with a subclass of :class:`~singer_sdk.connectors.sql.SQLToJSONSchema` to provide
#: a custom mapping for your SQL dialect.
sql_to_jsonschema_converter: type[SQLToJSONSchema] = SQLToJSONSchema
def __init__(
self,
config: dict | None = None,
sqlalchemy_url: str | None = None,
) -> None:
"""Initialize the SQL connector.
Args:
config: The parent tap or target object's config.
sqlalchemy_url: Optional URL for the connection.
"""
self._config: dict[str, t.Any] = config or {}
self._sqlalchemy_url: str | None = sqlalchemy_url or None
@property
def config(self) -> dict:
"""If set, provides access to the tap or target config.
Returns:
The settings as a dict.
"""
return self._config
@property
def logger(self) -> logging.Logger:
"""Get logger.
Returns:
Plugin logger.
"""
return logging.getLogger("sqlconnector")
@functools.cached_property
def sql_to_jsonschema(self) -> SQLToJSONSchema:
"""The SQL-to-JSON type mapper object for this SQL connector.
Override this property to provide a custom mapping for your SQL dialect.
.. versionadded:: 0.41.0
"""
return self.sql_to_jsonschema_converter.from_config(self.config)
@functools.cached_property
def jsonschema_to_sql(self) -> JSONSchemaToSQL:
"""The JSON-to-SQL type mapper object for this SQL connector.
Override this property to provide a custom mapping for your SQL dialect.
.. versionadded:: 0.42.0
"""
return JSONSchemaToSQL(max_varchar_length=self.max_varchar_length)
@contextmanager
def _connect(self) -> t.Iterator[sa.engine.Connection]:
with self._engine.connect().execution_options(stream_results=True) as conn:
yield conn
@deprecated(
"`SQLConnector.create_sqlalchemy_connection` is deprecated. "
"If you need to execute something that isn't available "
"on the connector currently, make a child class and "
"add your required method on that connector.",
category=DeprecationWarning,
stacklevel=1,
)
def create_sqlalchemy_connection(self) -> sa.engine.Connection:
"""(DEPRECATED) Return a new SQLAlchemy connection using the provided config.
Do not use the SQLConnector's connection directly. Instead, if you need
to execute something that isn't available on the connector currently,
make a child class and add a method on that connector.
By default this will create using the sqlalchemy `stream_results=True` option
described here:
https://docs.sqlalchemy.org/en/14/core/connections.html#using-server-side-cursors-a-k-a-stream-results
Developers may override this method if their provider does not support
server side cursors (`stream_results`) or in order to use different
configurations options when creating the connection object.
Returns:
A newly created SQLAlchemy engine object.
"""
return self._engine.connect().execution_options(stream_results=True)
@deprecated(
"`SQLConnector.create_sqlalchemy_engine` is deprecated. Override "
"`_engine` or `sqlalchemy_url` instead.",
category=DeprecationWarning,
stacklevel=1,
)
def create_sqlalchemy_engine(self) -> Engine:
"""(DEPRECATED) Return a new SQLAlchemy engine using the provided config.
Developers can generally override just one of the following:
`sqlalchemy_engine`, sqlalchemy_url`.
Returns:
A newly created SQLAlchemy engine object.
"""
return self._engine
@property
def connection(self) -> sa.engine.Connection:
"""(DEPRECATED) Return or set the SQLAlchemy connection object.
Do not use the SQLConnector's connection directly. Instead, if you need
to execute something that isn't available on the connector currently,
make a child class and add a method on that connector.
Returns:
The active SQLAlchemy connection object.
"""
warnings.warn(
"`SQLConnector.connection` is deprecated. If you need to execute something "
"that isn't available on the connector currently, make a child "
"class and add your required method on that connector.",
DeprecationWarning,
stacklevel=2,
)
return self.create_sqlalchemy_connection()
@property
def sqlalchemy_url(self) -> str:
"""Return the SQLAlchemy URL string.
Returns:
The URL as a string.
"""
if not self._sqlalchemy_url:
self._sqlalchemy_url = self.get_sqlalchemy_url(self.config)
return self._sqlalchemy_url
def get_sqlalchemy_url(self, config: dict[str, t.Any]) -> str: # noqa: PLR6301
"""Return the SQLAlchemy URL string.
Developers can generally override just one of the following:
`sqlalchemy_engine`, `get_sqlalchemy_url`.
Args:
config: A dictionary of settings from the tap or target config.
Returns:
The URL as a string.
Raises:
ConfigValidationError: If no valid sqlalchemy_url can be found.
"""
if "sqlalchemy_url" not in config:
msg = "Could not find or create 'sqlalchemy_url' for connection."
raise ConfigValidationError(msg)
return t.cast("str", config["sqlalchemy_url"])
def to_jsonschema_type(
self,
sql_type: (
str # noqa: ANN401
| sa.types.TypeEngine
| type[sa.types.TypeEngine]
| t.Any
),
) -> dict:
"""Return a JSON Schema representation of the provided type.
By default will call `typing.to_jsonschema_type()` for strings and SQLAlchemy
types.
Developers may override this method to accept additional input argument types,
to support non-standard types, or to provide custom typing logic.
Args:
sql_type: The string representation of the SQL type, a SQLAlchemy
TypeEngine class or object, or a custom-specified object.
Raises:
ValueError: If the type received could not be translated to jsonschema.
Returns:
The JSON Schema representation of the provided type.
.. versionchanged:: 0.40.0
Support for SQLAlchemy type classes and strings in the ``sql_type`` argument
was deprecated. Please pass a SQLAlchemy type object instead.
"""
if isinstance(sql_type, sa.types.TypeEngine):
return self.sql_to_jsonschema.to_jsonschema(sql_type)
if isinstance(sql_type, str): # pragma: no cover
warnings.warn(
"Passing string types to `to_jsonschema_type` is deprecated. "
"Please pass a SQLAlchemy type object instead.",
DeprecationWarning,
stacklevel=2,
)
return th.to_jsonschema_type(sql_type)
if isinstance(sql_type, type): # pragma: no cover
warnings.warn(
"Passing type classes to `to_jsonschema_type` is deprecated. "
"Please pass a SQLAlchemy type object instead.",
DeprecationWarning,
stacklevel=2,
)
if issubclass(sql_type, sa.types.TypeEngine):
return th.to_jsonschema_type(sql_type)
msg = f"Unexpected type received: '{sql_type.__name__}'"
raise ValueError(msg)
msg = f"Unexpected type received: '{type(sql_type).__name__}'"
raise ValueError(msg)
def to_sql_type(self, jsonschema_type: dict) -> sa.types.TypeEngine:
"""Return a JSON Schema representation of the provided type.
By default will call `typing.to_sql_type()`.
Developers may override this method to accept additional input argument types,
to support non-standard types, or to provide custom typing logic.
If overriding this method, developers should call the default implementation
from the base class for all unhandled cases.
Args:
jsonschema_type: The JSON Schema representation of the source type.
Returns:
The SQLAlchemy type representation of the data type.
"""
return self.jsonschema_to_sql.to_sql_type(jsonschema_type)
@staticmethod
def get_fully_qualified_name(
table_name: str | None = None,
schema_name: str | None = None,
db_name: str | None = None,
delimiter: str = ".",
) -> FullyQualifiedName:
"""Concatenates a fully qualified name from the parts.
Args:
table_name: The name of the table.
schema_name: The name of the schema. Defaults to None.
db_name: The name of the database. Defaults to None.
delimiter: Generally: '.' for SQL names and '-' for Singer names.
Returns:
The fully qualified name as a string.
.. versionchanged:: 0.40.0
A ``FullyQualifiedName`` object is now returned.
"""
return FullyQualifiedName(
table=table_name, # type: ignore[arg-type]
schema=schema_name,
database=db_name,
delimiter=delimiter,
)
@property
def _dialect(self) -> sa.engine.Dialect:
"""Return the dialect object.
Returns:
The dialect object.
"""
return self._engine.dialect
@property
def _engine(self) -> Engine:
"""Return the engine object.
This is the correct way to access the Connector's engine, if needed
(e.g. to inspect tables).
Returns:
The SQLAlchemy Engine that's attached to this SQLConnector instance.
"""
if not self._cached_engine:
self._cached_engine = self.create_engine()
return self._cached_engine
def create_engine(self) -> Engine:
"""Creates and returns a new engine. Do not call outside of _engine.
NOTE: Do not call this method. The only place that this method should
be called is inside the self._engine method. If you'd like to access
the engine on a connector, use self._engine.
This method exists solely so that tap/target developers can override it
on their subclass of SQLConnector to perform custom engine creation
logic.
Returns:
A new SQLAlchemy Engine.
"""
try:
return sa.create_engine(
self.sqlalchemy_url,
echo=False,
pool_pre_ping=True,
json_serializer=self.serialize_json,
json_deserializer=self.deserialize_json,
)
except TypeError:
self.logger.exception(
"Retrying engine creation with fewer arguments due to TypeError.",
)
return sa.create_engine(
self.sqlalchemy_url,
echo=False,
pool_pre_ping=True,
)
@deprecated(
"This method is deprecated. Use or override `FullyQualifiedName` instead.",
category=SingerSDKDeprecationWarning,
)
def quote(self, name: str) -> str:
"""Quote a name if it needs quoting, using '.' as a name-part delimiter.
Examples:
"my_table" => "`my_table`"
"my_schema.my_table" => "`my_schema`.`my_table`"
Args:
name: The unquoted name.
Returns:
str: The quoted name.
"""
return ".".join( # pragma: no cover
[
self._dialect.identifier_preparer.quote(name_part)
for name_part in name.split(".")
],
)
@lru_cache # noqa: B019
def _warn_no_view_detection(self) -> None:
"""Print a warning, but only the first time."""
self.logger.warning(
"Provider does not support get_view_names(). "
"Streams list may be incomplete or `is_view` may be unpopulated.",
)
def get_schema_names( # noqa: PLR6301
self,
engine: Engine, # noqa: ARG002
inspected: Inspector,
) -> list[str]:
"""Return a list of schema names in DB.
Args:
engine: SQLAlchemy engine
inspected: SQLAlchemy inspector instance for engine
Returns:
List of schema names
"""
return inspected.get_schema_names()
@deprecated(
"This method is deprecated.",
category=SingerSDKDeprecationWarning,
stacklevel=1,
)
def get_object_names( # pragma: no cover
self,
engine: Engine, # noqa: ARG002
inspected: Inspector,
schema_name: str,
) -> list[tuple[str, bool]]:
"""Return a list of syncable objects.
Args:
engine: SQLAlchemy engine
inspected: SQLAlchemy inspector instance for engine
schema_name: Schema name to inspect
Returns:
List of tuples (<table_or_view_name>, <is_view>)
"""
# Get list of tables and views
table_names = inspected.get_table_names(schema=schema_name)
try:
view_names = inspected.get_view_names(schema=schema_name)
except NotImplementedError:
# Some DB providers do not understand 'views'
self._warn_no_view_detection()
view_names = []
return [(t, False) for t in table_names] + [(v, True) for v in view_names]
# TODO maybe should be split into smaller parts?
def discover_catalog_entry(
self,
engine: Engine, # noqa: ARG002
inspected: Inspector, # noqa: ARG002
schema_name: str | None,
table_name: str,
is_view: bool, # noqa: FBT001
*,
reflected_columns: list[reflection.ReflectedColumn] | None = None,
reflected_pk: reflection.ReflectedPrimaryKeyConstraint | None = None,
reflected_indices: list[reflection.ReflectedIndex] | None = None,
) -> CatalogEntry:
"""Create `CatalogEntry` object for the given table or a view.
Args:
engine: SQLAlchemy engine
inspected: SQLAlchemy inspector instance for engine
schema_name: Schema name to inspect
table_name: Name of the table or a view
is_view: Flag whether this object is a view, returned by `get_object_names`
reflect_indices: Whether to reflect indices
reflected_columns: List of reflected columns
reflected_pk: Reflected primary key
reflected_indices: List of reflected indices
Returns:
`CatalogEntry` object for the given table or a view
"""
# Initialize unique stream name
unique_stream_id = f"{schema_name}-{table_name}" if schema_name else table_name
# Backwards-compatibility
reflected_columns = reflected_columns or []
reflected_indices = reflected_indices or []
# Detect key properties
possible_primary_keys: list[list[str]] = []
if reflected_pk and "constrained_columns" in reflected_pk:
possible_primary_keys.append(reflected_pk["constrained_columns"])
# An element of the columns list is ``None`` if it's an expression and is
# returned in the ``expressions`` list of the reflected index.
possible_primary_keys.extend(
index_def["column_names"] # type: ignore[misc]
for index_def in reflected_indices
if index_def.get("unique", False)
)
key_properties = next(iter(possible_primary_keys), [])
# Initialize columns list
properties = [
th.Property(
name=column["name"],
wrapped=th.CustomType(self.to_jsonschema_type(column["type"])),
nullable=column.get("nullable", False),
required=column["name"] in key_properties,
description=column.get("comment"),
)
for column in reflected_columns
]
schema = th.PropertiesList(*properties).to_dict()
# Initialize available replication methods
addl_replication_methods: list[str] = [""] # By default an empty list.
# Notes regarding replication methods:
# - 'INCREMENTAL' replication must be enabled by the user by specifying
# a replication_key value.
# - 'LOG_BASED' replication must be enabled by the developer, according
# to source-specific implementation capabilities.
replication_method = next(reversed(["FULL_TABLE", *addl_replication_methods]))
# Create the catalog entry object
return CatalogEntry(
tap_stream_id=unique_stream_id,
stream=unique_stream_id,
table=table_name,
key_properties=key_properties,