collate-data-diff 0.11.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. collate_data_diff-0.11.2.dist-info/LICENSE +18 -0
  2. collate_data_diff-0.11.2.dist-info/METADATA +77 -0
  3. collate_data_diff-0.11.2.dist-info/RECORD +54 -0
  4. collate_data_diff-0.11.2.dist-info/WHEEL +4 -0
  5. collate_data_diff-0.11.2.dist-info/entry_points.txt +3 -0
  6. data_diff/__init__.py +180 -0
  7. data_diff/__main__.py +618 -0
  8. data_diff/abcs/__init__.py +0 -0
  9. data_diff/abcs/compiler.py +13 -0
  10. data_diff/abcs/database_types.py +308 -0
  11. data_diff/cloud/__init__.py +2 -0
  12. data_diff/cloud/data_source.py +318 -0
  13. data_diff/cloud/datafold_api.py +304 -0
  14. data_diff/config.py +127 -0
  15. data_diff/databases/__init__.py +17 -0
  16. data_diff/databases/_connect.py +306 -0
  17. data_diff/databases/base.py +1291 -0
  18. data_diff/databases/bigquery.py +315 -0
  19. data_diff/databases/clickhouse.py +203 -0
  20. data_diff/databases/databricks.py +248 -0
  21. data_diff/databases/duckdb.py +192 -0
  22. data_diff/databases/mssql.py +229 -0
  23. data_diff/databases/mysql.py +159 -0
  24. data_diff/databases/oracle.py +195 -0
  25. data_diff/databases/postgresql.py +258 -0
  26. data_diff/databases/presto.py +197 -0
  27. data_diff/databases/redshift.py +217 -0
  28. data_diff/databases/snowflake.py +207 -0
  29. data_diff/databases/trino.py +50 -0
  30. data_diff/databases/vertica.py +160 -0
  31. data_diff/dbt.py +604 -0
  32. data_diff/dbt_config_validators.py +65 -0
  33. data_diff/dbt_parser.py +523 -0
  34. data_diff/diff_tables.py +416 -0
  35. data_diff/errors.py +74 -0
  36. data_diff/format.py +359 -0
  37. data_diff/hashdiff_tables.py +264 -0
  38. data_diff/info_tree.py +62 -0
  39. data_diff/joindiff_tables.py +399 -0
  40. data_diff/lexicographic_space.py +240 -0
  41. data_diff/parse_time.py +74 -0
  42. data_diff/py.typed +0 -0
  43. data_diff/queries/__init__.py +0 -0
  44. data_diff/queries/api.py +200 -0
  45. data_diff/queries/ast_classes.py +798 -0
  46. data_diff/queries/base.py +24 -0
  47. data_diff/queries/extras.py +29 -0
  48. data_diff/query_utils.py +56 -0
  49. data_diff/schema.py +52 -0
  50. data_diff/table_segment.py +286 -0
  51. data_diff/thread_utils.py +98 -0
  52. data_diff/tracking.py +237 -0
  53. data_diff/utils.py +625 -0
  54. data_diff/version.py +1 -0
@@ -0,0 +1,248 @@
1
+ import math
2
+ from typing import Any, ClassVar, Dict, Sequence, Type
3
+ import logging
4
+
5
+ import attrs
6
+
7
+ from data_diff.abcs.database_types import (
8
+ Date,
9
+ Integer,
10
+ Float,
11
+ Decimal,
12
+ Timestamp,
13
+ Text,
14
+ TemporalType,
15
+ NumericType,
16
+ DbPath,
17
+ ColType,
18
+ UnknownColType,
19
+ Boolean,
20
+ )
21
+ from data_diff.databases.base import (
22
+ MD5_HEXDIGITS,
23
+ CHECKSUM_HEXDIGITS,
24
+ CHECKSUM_OFFSET,
25
+ BaseDialect,
26
+ ThreadedDatabase,
27
+ import_helper,
28
+ parse_table_name,
29
+ )
30
+ from data_diff.schema import RawColumnInfo
31
+
32
+
33
+ @import_helper(text="You can install it using 'pip install databricks-sql-connector'")
34
+ def import_databricks():
35
+ import databricks.sql
36
+
37
+ return databricks
38
+
39
+
40
+ @attrs.define(frozen=False)
41
+ class Dialect(BaseDialect):
42
+ name = "Databricks"
43
+ ROUNDS_ON_PREC_LOSS = True
44
+ TYPE_CLASSES = {
45
+ # Numbers
46
+ "INT": Integer,
47
+ "SMALLINT": Integer,
48
+ "TINYINT": Integer,
49
+ "BIGINT": Integer,
50
+ "FLOAT": Float,
51
+ "DOUBLE": Float,
52
+ "DECIMAL": Decimal,
53
+ # Timestamps
54
+ "TIMESTAMP": Timestamp,
55
+ "TIMESTAMP_NTZ": Timestamp,
56
+ "DATE": Date,
57
+ # Text
58
+ "STRING": Text,
59
+ "VARCHAR": Text,
60
+ # Boolean
61
+ "BOOLEAN": Boolean,
62
+ }
63
+
64
+ def type_repr(self, t) -> str:
65
+ try:
66
+ return {str: "STRING"}[t]
67
+ except KeyError:
68
+ return super().type_repr(t)
69
+
70
+ def quote(self, s: str) -> str:
71
+ return f"`{s}`"
72
+
73
+ def to_string(self, s: str) -> str:
74
+ return f"cast({s} as string)"
75
+
76
+ def _convert_db_precision_to_digits(self, p: int) -> int:
77
+ # Subtracting 2 due to wierd precision issues
78
+ return max(super()._convert_db_precision_to_digits(p) - 2, 0)
79
+
80
+ def set_timezone_to_utc(self) -> str:
81
+ return "SET TIME ZONE 'UTC'"
82
+
83
+ def parse_table_name(self, name: str) -> DbPath:
84
+ path = parse_table_name(name)
85
+ return tuple(i for i in path if i is not None)
86
+
87
+ def md5_as_int(self, s: str) -> str:
88
+ return f"cast(conv(substr(md5({s}), {1+MD5_HEXDIGITS-CHECKSUM_HEXDIGITS}), 16, 10) as decimal(38, 0)) - {CHECKSUM_OFFSET}"
89
+
90
+ def md5_as_hex(self, s: str) -> str:
91
+ return f"md5({s})"
92
+
93
+ def normalize_timestamp(self, value: str, coltype: TemporalType) -> str:
94
+ """Databricks timestamp contains no more than 6 digits in precision"""
95
+ try:
96
+ is_date = coltype.is_date
97
+ except:
98
+ is_date = False
99
+ if isinstance(coltype, Date) or is_date:
100
+ return f"date_format({value}, 'yyyy-MM-dd')"
101
+ if coltype.rounds:
102
+ # cast to timestamp due to unix_micros() requiring timestamp
103
+ timestamp = f"cast(round(unix_micros(cast({value} as timestamp)) / 1000000, {coltype.precision}) * 1000000 as bigint)"
104
+ return f"date_format(timestamp_micros({timestamp}), 'yyyy-MM-dd HH:mm:ss.SSSSSS')"
105
+
106
+ precision_format = "S" * coltype.precision + "0" * (6 - coltype.precision)
107
+ return f"date_format({value}, 'yyyy-MM-dd HH:mm:ss.{precision_format}')"
108
+
109
+ def normalize_number(self, value: str, coltype: NumericType) -> str:
110
+ value = f"cast({value} as decimal(38, {coltype.precision}))"
111
+ if coltype.precision > 0:
112
+ value = f"format_number({value}, {coltype.precision})"
113
+ return f"replace({self.to_string(value)}, ',', '')"
114
+
115
+ def normalize_boolean(self, value: str, _coltype: Boolean) -> str:
116
+ return self.to_string(f"cast ({value} as int)")
117
+
118
+
119
+ @attrs.define(frozen=False, init=False, kw_only=True)
120
+ class Databricks(ThreadedDatabase):
121
+ DIALECT_CLASS: ClassVar[Type[BaseDialect]] = Dialect
122
+ CONNECT_URI_HELP = "databricks://:<access_token>@<server_hostname>/<http_path>"
123
+ CONNECT_URI_PARAMS = ["catalog", "schema"]
124
+
125
+ catalog: str
126
+ _args: Dict[str, Any]
127
+
128
+ def __init__(self, *, thread_count, **kw) -> None:
129
+ super().__init__(thread_count=thread_count)
130
+ logging.getLogger("databricks.sql").setLevel(logging.WARNING)
131
+
132
+ self._args = kw
133
+ self.default_schema = kw.get("schema", "default")
134
+ self.catalog = kw.get("catalog", "hive_metastore")
135
+
136
+ def create_connection(self):
137
+ databricks = import_databricks()
138
+
139
+ try:
140
+ return databricks.sql.connect(
141
+ server_hostname=self._args["server_hostname"],
142
+ http_path=self._args["http_path"],
143
+ access_token=self._args["access_token"],
144
+ catalog=self.catalog,
145
+ )
146
+ except databricks.sql.exc.Error as e:
147
+ raise ConnectionError(*e.args) from e
148
+
149
+ def query_table_schema(self, path: DbPath) -> Dict[str, RawColumnInfo]:
150
+ # Databricks has INFORMATION_SCHEMA only for Databricks Runtime, not for Databricks SQL.
151
+ # https://docs.databricks.com/spark/latest/spark-sql/language-manual/information-schema/columns.html
152
+ # So, to obtain information about schema, we should use another approach.
153
+
154
+ conn = self.create_connection()
155
+
156
+ catalog, schema, table = self._normalize_table_path(path)
157
+ with conn.cursor() as cursor:
158
+ cursor.columns(catalog_name=catalog, schema_name=schema, table_name=table)
159
+ try:
160
+ rows = cursor.fetchall()
161
+ finally:
162
+ conn.close()
163
+ if not rows:
164
+ raise RuntimeError(f"{self.name}: Table '{'.'.join(path)}' does not exist, or has no columns")
165
+
166
+ d = {
167
+ r.COLUMN_NAME: RawColumnInfo(
168
+ column_name=r.COLUMN_NAME, data_type=r.TYPE_NAME, numeric_precision=r.DECIMAL_DIGITS
169
+ )
170
+ for r in rows
171
+ }
172
+ assert len(d) == len(rows)
173
+ return d
174
+
175
+ # def select_table_schema(self, path: DbPath) -> str:
176
+ # """Provide SQL for selecting the table schema as (name, type, date_prec, num_prec)"""
177
+ # database, schema, name = self._normalize_table_path(path)
178
+ # info_schema_path = ["information_schema", "columns"]
179
+ # if database:
180
+ # info_schema_path.insert(0, database)
181
+
182
+ # return (
183
+ # "SELECT column_name, data_type, datetime_precision, numeric_precision, numeric_scale "
184
+ # f"FROM {'.'.join(info_schema_path)} "
185
+ # f"WHERE table_name = '{name}' AND table_schema = '{schema}'"
186
+ # )
187
+
188
+ def _process_table_schema(
189
+ self, path: DbPath, raw_schema: Dict[str, RawColumnInfo], filter_columns: Sequence[str], where: str = None
190
+ ):
191
+ accept = {i.lower() for i in filter_columns}
192
+ col_infos = [row for name, row in raw_schema.items() if name.lower() in accept]
193
+
194
+ resulted_rows = []
195
+ for info in col_infos:
196
+ raw_data_type = info.data_type
197
+ row_type = info.data_type.split("(")[0]
198
+ info = attrs.evolve(info, data_type=row_type)
199
+ type_cls = self.dialect.TYPE_CLASSES.get(row_type, UnknownColType)
200
+
201
+ if issubclass(type_cls, Integer):
202
+ info = attrs.evolve(info, numeric_scale=0)
203
+
204
+ elif issubclass(type_cls, Float):
205
+ numeric_precision = math.ceil(info.numeric_precision / math.log(2, 10))
206
+ info = attrs.evolve(info, numeric_precision=numeric_precision)
207
+
208
+ elif issubclass(type_cls, Decimal):
209
+ items = raw_data_type[8:].rstrip(")").split(",")
210
+ numeric_precision, numeric_scale = int(items[0]), int(items[1])
211
+ info = attrs.evolve(
212
+ info,
213
+ numeric_precision=numeric_precision,
214
+ numeric_scale=numeric_scale,
215
+ )
216
+
217
+ elif issubclass(type_cls, Timestamp):
218
+ info = attrs.evolve(
219
+ info,
220
+ datetime_precision=info.numeric_precision,
221
+ numeric_precision=None,
222
+ )
223
+
224
+ else:
225
+ info = attrs.evolve(info, numeric_precision=None)
226
+
227
+ resulted_rows.append(info)
228
+
229
+ col_dict: Dict[str, ColType] = {info.column_name: self.dialect.parse_type(path, info) for info in resulted_rows}
230
+
231
+ self._refine_coltypes(path, col_dict, where)
232
+ return col_dict
233
+
234
+ @property
235
+ def is_autocommit(self) -> bool:
236
+ return True
237
+
238
+ def _normalize_table_path(self, path: DbPath) -> DbPath:
239
+ if len(path) == 1:
240
+ return self.catalog, self.default_schema, path[0]
241
+ elif len(path) == 2:
242
+ return self.catalog, path[0], path[1]
243
+ elif len(path) == 3:
244
+ return path
245
+
246
+ raise ValueError(
247
+ f"{self.name}: Bad table path for {self}: '{'.'.join(path)}'. Expected format: table, schema.table, or catalog.schema.table"
248
+ )
@@ -0,0 +1,192 @@
1
+ from typing import Any, ClassVar, Dict, Union, Type
2
+
3
+ import attrs
4
+ from packaging.version import parse as parse_version
5
+
6
+ from data_diff.schema import RawColumnInfo
7
+ from data_diff.utils import match_regexps
8
+ from data_diff.abcs.database_types import (
9
+ Timestamp,
10
+ TimestampTZ,
11
+ DbPath,
12
+ ColType,
13
+ Float,
14
+ Decimal,
15
+ Integer,
16
+ TemporalType,
17
+ Native_UUID,
18
+ Text,
19
+ FractionalType,
20
+ Boolean,
21
+ )
22
+ from data_diff.databases.base import (
23
+ Database,
24
+ BaseDialect,
25
+ import_helper,
26
+ ConnectError,
27
+ ThreadLocalInterpreter,
28
+ TIMESTAMP_PRECISION_POS,
29
+ CHECKSUM_OFFSET,
30
+ )
31
+ from data_diff.databases.base import MD5_HEXDIGITS, CHECKSUM_HEXDIGITS
32
+ from data_diff.version import __version__
33
+
34
+
35
+ @import_helper("duckdb")
36
+ def import_duckdb():
37
+ import duckdb
38
+
39
+ return duckdb
40
+
41
+
42
+ @attrs.define(frozen=False)
43
+ class Dialect(BaseDialect):
44
+ name = "DuckDB"
45
+ ROUNDS_ON_PREC_LOSS = False
46
+ SUPPORTS_PRIMARY_KEY = True
47
+ SUPPORTS_INDEXES = True
48
+
49
+ # https://duckdb.org/docs/sql/data_types/numeric#fixed-point-decimals
50
+ # The default WIDTH and SCALE is DECIMAL(18, 3), if none are specified.
51
+ DEFAULT_NUMERIC_PRECISION = 3
52
+
53
+ TYPE_CLASSES = {
54
+ # Timestamps
55
+ "TIMESTAMP WITH TIME ZONE": TimestampTZ,
56
+ "TIMESTAMP": Timestamp,
57
+ # Numbers
58
+ "DOUBLE": Float,
59
+ "FLOAT": Float,
60
+ "DECIMAL": Decimal,
61
+ "INTEGER": Integer,
62
+ "BIGINT": Integer,
63
+ # Text
64
+ "VARCHAR": Text,
65
+ "TEXT": Text,
66
+ # UUID
67
+ "UUID": Native_UUID,
68
+ # Bool
69
+ "BOOLEAN": Boolean,
70
+ }
71
+
72
+ def quote(self, s: str):
73
+ return f'"{s}"'
74
+
75
+ def to_string(self, s: str):
76
+ return f"{s}::VARCHAR"
77
+
78
+ def _convert_db_precision_to_digits(self, p: int) -> int:
79
+ # Subtracting 2 due to wierd precision issues in PostgreSQL
80
+ return super()._convert_db_precision_to_digits(p) - 2
81
+
82
+ def parse_type(self, table_path: DbPath, info: RawColumnInfo) -> ColType:
83
+ regexps = {
84
+ r"DECIMAL\((\d+),(\d+)\)": Decimal,
85
+ }
86
+
87
+ for m, t_cls in match_regexps(regexps, info.data_type):
88
+ precision = int(m.group(2))
89
+ return t_cls(precision=precision)
90
+
91
+ return super().parse_type(table_path, info)
92
+
93
+ def set_timezone_to_utc(self) -> str:
94
+ return "SET GLOBAL TimeZone='UTC'"
95
+
96
+ def current_timestamp(self) -> str:
97
+ return "current_timestamp"
98
+
99
+ def md5_as_int(self, s: str) -> str:
100
+ return f"('0x' || SUBSTRING(md5({s}), {1+MD5_HEXDIGITS-CHECKSUM_HEXDIGITS},{CHECKSUM_HEXDIGITS}))::BIGINT - {CHECKSUM_OFFSET}"
101
+
102
+ def md5_as_hex(self, s: str) -> str:
103
+ return f"md5({s})"
104
+
105
+ def normalize_timestamp(self, value: str, coltype: TemporalType) -> str:
106
+ # It's precision 6 by default. If precision is less than 6 -> we remove the trailing numbers.
107
+ if coltype.rounds and coltype.precision > 0:
108
+ return f"CONCAT(SUBSTRING(STRFTIME({value}::TIMESTAMP, '%Y-%m-%d %H:%M:%S.'),1,23), LPAD(((ROUND(strftime({value}::timestamp, '%f')::DECIMAL(15,7)/100000,{coltype.precision-1})*100000)::INT)::VARCHAR,6,'0'))"
109
+
110
+ return f"rpad(substring(strftime({value}::timestamp, '%Y-%m-%d %H:%M:%S.%f'),1,{TIMESTAMP_PRECISION_POS+coltype.precision}),26,'0')"
111
+
112
+ def normalize_number(self, value: str, coltype: FractionalType) -> str:
113
+ return self.to_string(f"{value}::DECIMAL(38, {coltype.precision})")
114
+
115
+ def normalize_boolean(self, value: str, _coltype: Boolean) -> str:
116
+ return self.to_string(f"{value}::INTEGER")
117
+
118
+
119
+ @attrs.define(frozen=False, init=False, kw_only=True)
120
+ class DuckDB(Database):
121
+ DIALECT_CLASS: ClassVar[Type[BaseDialect]] = Dialect
122
+ SUPPORTS_UNIQUE_CONSTAINT = False # Temporary, until we implement it
123
+ CONNECT_URI_HELP = "duckdb://<dbname>@<filepath>"
124
+ CONNECT_URI_PARAMS = ["database", "dbpath"]
125
+
126
+ _args: Dict[str, Any] = attrs.field(init=False)
127
+ _conn: Any = attrs.field(init=False)
128
+
129
+ def __init__(self, **kw) -> None:
130
+ super().__init__()
131
+ self._args = kw
132
+ self._conn = self.create_connection()
133
+ self.default_schema = "main"
134
+
135
+ @property
136
+ def is_autocommit(self) -> bool:
137
+ return True
138
+
139
+ def _query(self, sql_code: Union[str, ThreadLocalInterpreter]):
140
+ "Uses the standard SQL cursor interface"
141
+ return self._query_conn(self._conn, sql_code)
142
+
143
+ def close(self):
144
+ super().close()
145
+ self._conn.close()
146
+
147
+ def create_connection(self):
148
+ ddb = import_duckdb()
149
+ try:
150
+ # custom_user_agent is only available in duckdb >= 0.9.2
151
+ if parse_version(ddb.__version__) >= parse_version("0.9.2"):
152
+ custom_user_agent = f"data-diff/v{__version__}"
153
+ config = {"custom_user_agent": custom_user_agent}
154
+ connection = ddb.connect(database=self._args["filepath"], config=config)
155
+ custom_user_agent_results = connection.sql("PRAGMA USER_AGENT;").fetchall()
156
+ custom_user_agent_filtered = custom_user_agent_results[0][0]
157
+ assert custom_user_agent in custom_user_agent_filtered
158
+ else:
159
+ connection = ddb.connect(database=self._args["filepath"])
160
+ return connection
161
+ except ddb.OperationalError as e:
162
+ raise ConnectError(*e.args) from e
163
+ except AssertionError:
164
+ raise ConnectError("Assertion failed: Custom user agent is invalid.") from None
165
+
166
+ def select_table_schema(self, path: DbPath) -> str:
167
+ database, schema, table = self._normalize_table_path(path)
168
+
169
+ info_schema_path = ["information_schema", "columns"]
170
+
171
+ if database:
172
+ info_schema_path.insert(0, database)
173
+ dynamic_database_clause = f"'{database}'"
174
+ else:
175
+ dynamic_database_clause = "current_catalog()"
176
+
177
+ return (
178
+ f"SELECT column_name, data_type, datetime_precision, numeric_precision, numeric_scale FROM {'.'.join(info_schema_path)} "
179
+ f"WHERE table_name = '{table}' AND table_schema = '{schema}' and table_catalog = {dynamic_database_clause}"
180
+ )
181
+
182
+ def _normalize_table_path(self, path: DbPath) -> DbPath:
183
+ if len(path) == 1:
184
+ return None, self.default_schema, path[0]
185
+ elif len(path) == 2:
186
+ return None, path[0], path[1]
187
+ elif len(path) == 3:
188
+ return path
189
+
190
+ raise ValueError(
191
+ f"{self.name}: Bad table path for {self}: '{'.'.join(path)}'. Expected format: table, schema.table, or database.schema.table"
192
+ )
@@ -0,0 +1,229 @@
1
+ from typing import Any, ClassVar, Dict, Optional, Type
2
+
3
+ import attrs
4
+
5
+ from data_diff.databases.base import (
6
+ CHECKSUM_HEXDIGITS,
7
+ CHECKSUM_OFFSET,
8
+ QueryError,
9
+ ThreadedDatabase,
10
+ import_helper,
11
+ ConnectError,
12
+ BaseDialect,
13
+ )
14
+ from data_diff.abcs.database_types import (
15
+ JSON,
16
+ NumericType,
17
+ Timestamp,
18
+ TimestampTZ,
19
+ DbPath,
20
+ Float,
21
+ Decimal,
22
+ Integer,
23
+ TemporalType,
24
+ Native_UUID,
25
+ Text,
26
+ Boolean,
27
+ Date,
28
+ Time,
29
+ )
30
+
31
+
32
+ @import_helper("mssql")
33
+ def import_mssql():
34
+ import pyodbc
35
+
36
+ return pyodbc
37
+
38
+
39
+ @attrs.define(frozen=False)
40
+ class Dialect(BaseDialect):
41
+ name = "MsSQL"
42
+ ROUNDS_ON_PREC_LOSS = True
43
+ SUPPORTS_PRIMARY_KEY: ClassVar[bool] = True
44
+ SUPPORTS_INDEXES = True
45
+ TYPE_CLASSES = {
46
+ # Timestamps
47
+ "datetimeoffset": TimestampTZ,
48
+ "datetime": Timestamp,
49
+ "datetime2": Timestamp,
50
+ "smalldatetime": Timestamp,
51
+ "date": Date,
52
+ "time": Time,
53
+ # Numbers
54
+ "float": Float,
55
+ "real": Float,
56
+ "decimal": Decimal,
57
+ "money": Decimal,
58
+ "smallmoney": Decimal,
59
+ # int
60
+ "int": Integer,
61
+ "bigint": Integer,
62
+ "tinyint": Integer,
63
+ "smallint": Integer,
64
+ # Text
65
+ "varchar": Text,
66
+ "char": Text,
67
+ "text": Text,
68
+ "ntext": Text,
69
+ "nvarchar": Text,
70
+ "nchar": Text,
71
+ "binary": Text,
72
+ "varbinary": Text,
73
+ "xml": Text,
74
+ # UUID
75
+ "uniqueidentifier": Native_UUID,
76
+ # Bool
77
+ "bit": Boolean,
78
+ # JSON
79
+ "json": JSON,
80
+ }
81
+
82
+ def quote(self, s: str) -> str:
83
+ return f"[{s}]"
84
+
85
+ def set_timezone_to_utc(self) -> str:
86
+ raise NotImplementedError("MsSQL does not support a session timezone setting.")
87
+
88
+ def current_timestamp(self) -> str:
89
+ return "GETDATE()"
90
+
91
+ def current_database(self) -> str:
92
+ return "DB_NAME()"
93
+
94
+ def current_schema(self) -> str:
95
+ return """default_schema_name
96
+ FROM sys.database_principals
97
+ WHERE name = CURRENT_USER"""
98
+
99
+ def to_string(self, s: str) -> str:
100
+ # Both convert(varchar(max), …) and convert(text, …) do work.
101
+ return f"CONVERT(VARCHAR(MAX), {s})"
102
+
103
+ def type_repr(self, t) -> str:
104
+ try:
105
+ return {bool: "bit", str: "text"}[t]
106
+ except KeyError:
107
+ return super().type_repr(t)
108
+
109
+ def random(self) -> str:
110
+ return "rand()"
111
+
112
+ def is_distinct_from(self, a: str, b: str) -> str:
113
+ # IS (NOT) DISTINCT FROM is available only since SQLServer 2022.
114
+ # See: https://stackoverflow.com/a/18684859/857383
115
+ return f"(({a}<>{b} OR {a} IS NULL OR {b} IS NULL) AND NOT({a} IS NULL AND {b} IS NULL))"
116
+
117
+ def limit_select(
118
+ self,
119
+ select_query: str,
120
+ offset: Optional[int] = None,
121
+ limit: Optional[int] = None,
122
+ has_order_by: Optional[bool] = None,
123
+ ) -> str:
124
+ if offset:
125
+ raise NotImplementedError("No support for OFFSET in query")
126
+ result = ""
127
+ if not has_order_by:
128
+ result += "ORDER BY 1"
129
+
130
+ result += f" OFFSET 0 ROWS FETCH NEXT {limit} ROWS ONLY"
131
+
132
+ # mssql requires that subquery columns are all aliased, so
133
+ # don't wrap in an outer select
134
+ return f"{select_query} {result}"
135
+
136
+ def constant_values(self, rows) -> str:
137
+ values = ", ".join("(%s)" % ", ".join(self._constant_value(v) for v in row) for row in rows)
138
+ return f"VALUES {values}"
139
+
140
+ def normalize_timestamp(self, value: str, coltype: TemporalType) -> str:
141
+ if coltype.precision > 0:
142
+ formatted_value = (
143
+ f"FORMAT({value}, 'yyyy-MM-dd HH:mm:ss') + '.' + "
144
+ f"SUBSTRING(FORMAT({value}, 'fffffff'), 1, {coltype.precision})"
145
+ )
146
+ else:
147
+ formatted_value = f"FORMAT({value}, 'yyyy-MM-dd HH:mm:ss')"
148
+
149
+ return formatted_value
150
+
151
+ def normalize_number(self, value: str, coltype: NumericType) -> str:
152
+ if coltype.precision == 0:
153
+ return f"CAST(FLOOR({value}) AS VARCHAR)"
154
+
155
+ return f"FORMAT({value}, 'N{coltype.precision}')"
156
+
157
+ def md5_as_int(self, s: str) -> str:
158
+ return f"convert(bigint, convert(varbinary, '0x' + RIGHT(CONVERT(NVARCHAR(32), HashBytes('MD5', {s}), 2), {CHECKSUM_HEXDIGITS}), 1)) - {CHECKSUM_OFFSET}"
159
+
160
+ def md5_as_hex(self, s: str) -> str:
161
+ return f"HashBytes('MD5', {s})"
162
+
163
+
164
+ @attrs.define(frozen=False, init=False, kw_only=True)
165
+ class MsSQL(ThreadedDatabase):
166
+ DIALECT_CLASS: ClassVar[Type[BaseDialect]] = Dialect
167
+ CONNECT_URI_HELP = "mssql://<user>:<password>@<host>/<database>/<schema>"
168
+ CONNECT_URI_PARAMS = ["database", "schema"]
169
+
170
+ default_database: str
171
+ _args: Dict[str, Any]
172
+ _mssql: Any
173
+
174
+ def __init__(self, host, port, user, password, *, database, thread_count, **kw) -> None:
175
+ super().__init__(thread_count=thread_count)
176
+
177
+ args = dict(server=host, port=port, database=database, user=user, password=password, **kw)
178
+ self._args = {k: v for k, v in args.items() if v is not None}
179
+ self._args["driver"] = "{ODBC Driver 18 for SQL Server}"
180
+
181
+ # TODO temp dev debug
182
+ self._args["TrustServerCertificate"] = "yes"
183
+
184
+ try:
185
+ self.default_database = self._args["database"]
186
+ self.default_schema = self._args["schema"]
187
+ except KeyError:
188
+ raise ValueError("Specify a default database and schema.")
189
+
190
+ self._mssql = None
191
+
192
+ def create_connection(self):
193
+ self._mssql = import_mssql()
194
+ try:
195
+ connection = self._mssql.connect(**self._args)
196
+ return connection
197
+ except self._mssql.Error as error:
198
+ raise ConnectError(*error.args) from error
199
+
200
+ def select_table_schema(self, path: DbPath) -> str:
201
+ """Provide SQL for selecting the table schema as (name, type, date_prec, num_prec)"""
202
+ database, schema, name = self._normalize_table_path(path)
203
+ info_schema_path = ["information_schema", "columns"]
204
+ if database:
205
+ info_schema_path.insert(0, self.dialect.quote(database))
206
+
207
+ return (
208
+ "SELECT column_name, data_type, datetime_precision, numeric_precision, numeric_scale, collation_name "
209
+ f"FROM {'.'.join(info_schema_path)} "
210
+ f"WHERE table_name = '{name}' AND table_schema = '{schema}'"
211
+ )
212
+
213
+ def _normalize_table_path(self, path: DbPath) -> DbPath:
214
+ if len(path) == 1:
215
+ return self.default_database, self.default_schema, path[0]
216
+ elif len(path) == 2:
217
+ return self.default_database, path[0], path[1]
218
+ elif len(path) == 3:
219
+ return path
220
+
221
+ raise ValueError(
222
+ f"{self.name}: Bad table path for {self}: '{'.'.join(path)}'. Expected format: table, schema.table, or database.schema.table"
223
+ )
224
+
225
+ def _query_cursor(self, c, sql_code: str):
226
+ try:
227
+ return super()._query_cursor(c, sql_code)
228
+ except self._mssql.DatabaseError as e:
229
+ raise QueryError(e)