diffdb-core 0.1.0__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.
- diffdb/__init__.py +179 -0
- diffdb/concurrency/__init__.py +10 -0
- diffdb/concurrency/pool.py +88 -0
- diffdb/concurrency/stream.py +111 -0
- diffdb/core/__init__.py +38 -0
- diffdb/core/differ.py +136 -0
- diffdb/core/hash_differ.py +390 -0
- diffdb/core/segment.py +323 -0
- diffdb/core/sql.py +81 -0
- diffdb/core/summary.py +179 -0
- diffdb/databases/__init__.py +59 -0
- diffdb/databases/_connect.py +210 -0
- diffdb/databases/base.py +266 -0
- diffdb/databases/bigquery.py +54 -0
- diffdb/databases/clickhouse.py +35 -0
- diffdb/databases/databricks.py +40 -0
- diffdb/databases/dialects/_base.yaml +182 -0
- diffdb/databases/dialects/bigquery.yaml +39 -0
- diffdb/databases/dialects/clickhouse.yaml +42 -0
- diffdb/databases/dialects/databricks.yaml +36 -0
- diffdb/databases/dialects/duckdb.yaml +48 -0
- diffdb/databases/dialects/mysql.yaml +45 -0
- diffdb/databases/dialects/oracle.yaml +44 -0
- diffdb/databases/dialects/postgresql.yaml +44 -0
- diffdb/databases/dialects/presto.yaml +37 -0
- diffdb/databases/dialects/redshift.yaml +11 -0
- diffdb/databases/dialects/snowflake.yaml +55 -0
- diffdb/databases/dialects/trino.yaml +5 -0
- diffdb/databases/dialects/vertica.yaml +39 -0
- diffdb/databases/duckdb.py +40 -0
- diffdb/databases/mysql.py +38 -0
- diffdb/databases/oracle.py +99 -0
- diffdb/databases/postgresql.py +34 -0
- diffdb/databases/presto.py +41 -0
- diffdb/databases/redshift.py +12 -0
- diffdb/databases/snowflake.py +55 -0
- diffdb/databases/trino.py +41 -0
- diffdb/databases/vertica.py +43 -0
- diffdb/databases/yaml_dialect.py +428 -0
- diffdb/geometry/__init__.py +42 -0
- diffdb/geometry/arithmetic.py +141 -0
- diffdb/geometry/bisection.py +100 -0
- diffdb/geometry/vector.py +42 -0
- diffdb/telemetry/__init__.py +11 -0
- diffdb/telemetry/info_tree.py +52 -0
- diffdb/telemetry/query_tracker.py +53 -0
- diffdb/types.py +302 -0
- diffdb/utils.py +121 -0
- diffdb_core-0.1.0.dist-info/METADATA +315 -0
- diffdb_core-0.1.0.dist-info/RECORD +53 -0
- diffdb_core-0.1.0.dist-info/WHEEL +5 -0
- diffdb_core-0.1.0.dist-info/licenses/LICENSE.md +87 -0
- diffdb_core-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
# diffdb/databases/_connect.py
|
|
2
|
+
"""Connection dispatcher and factory for diffdb databases.
|
|
3
|
+
|
|
4
|
+
Handles URI parsing, connection pooling, and UTC session initialization.
|
|
5
|
+
Completely independent database connector framework.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import urllib.parse
|
|
10
|
+
from contextlib import suppress
|
|
11
|
+
from itertools import zip_longest
|
|
12
|
+
|
|
13
|
+
import dsnparse
|
|
14
|
+
|
|
15
|
+
from ..utils import WeakCache, dataclass
|
|
16
|
+
from .base import Database, ThreadedDatabase
|
|
17
|
+
from .bigquery import BigQuery
|
|
18
|
+
from .clickhouse import Clickhouse
|
|
19
|
+
from .databricks import Databricks
|
|
20
|
+
from .duckdb import DuckDB
|
|
21
|
+
from .mysql import MySQL
|
|
22
|
+
from .oracle import Oracle
|
|
23
|
+
from .postgresql import PostgreSQL
|
|
24
|
+
from .presto import Presto
|
|
25
|
+
from .redshift import Redshift
|
|
26
|
+
from .snowflake import Snowflake
|
|
27
|
+
from .trino import Trino
|
|
28
|
+
from .vertica import Vertica
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class MatchUriPath:
|
|
35
|
+
database_cls: type[Database]
|
|
36
|
+
|
|
37
|
+
def match_path(self, dsn):
|
|
38
|
+
help_str = getattr(self.database_cls, "CONNECT_URI_HELP", "")
|
|
39
|
+
params = getattr(self.database_cls, "CONNECT_URI_PARAMS", [])
|
|
40
|
+
kwparams = getattr(self.database_cls, "CONNECT_URI_KWPARAMS", [])
|
|
41
|
+
|
|
42
|
+
dsn_dict = dict(urllib.parse.parse_qsl(dsn.query)) if dsn.query else {}
|
|
43
|
+
matches = {}
|
|
44
|
+
for param, arg in zip_longest(params, dsn.paths):
|
|
45
|
+
if param is None:
|
|
46
|
+
raise ValueError(f"Too many parts to path. Expected format: {help_str}")
|
|
47
|
+
|
|
48
|
+
optional = param.endswith("?")
|
|
49
|
+
param = param.rstrip("?")
|
|
50
|
+
|
|
51
|
+
if arg is None:
|
|
52
|
+
try:
|
|
53
|
+
arg = dsn_dict.pop(param)
|
|
54
|
+
except KeyError:
|
|
55
|
+
if not optional:
|
|
56
|
+
raise ValueError(f"URI must specify '{param}'. Expected format: {help_str}")
|
|
57
|
+
arg = None
|
|
58
|
+
|
|
59
|
+
assert param and param not in matches
|
|
60
|
+
matches[param] = arg
|
|
61
|
+
|
|
62
|
+
for param in kwparams:
|
|
63
|
+
try:
|
|
64
|
+
arg = dsn_dict.pop(param)
|
|
65
|
+
except KeyError:
|
|
66
|
+
raise ValueError(f"URI must specify '{param}'. Expected format: {help_str}")
|
|
67
|
+
|
|
68
|
+
assert param and arg and param not in matches, (param, arg, matches.keys())
|
|
69
|
+
matches[param] = arg
|
|
70
|
+
|
|
71
|
+
for param, value in dsn_dict.items():
|
|
72
|
+
if param in matches:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
f"Parameter '{param}' already provided as positional argument. Expected format: {help_str}"
|
|
75
|
+
)
|
|
76
|
+
matches[param] = value
|
|
77
|
+
|
|
78
|
+
return matches
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
DATABASE_BY_SCHEME: dict[str, type[Database]] = {
|
|
82
|
+
"postgresql": PostgreSQL,
|
|
83
|
+
"mysql": MySQL,
|
|
84
|
+
"oracle": Oracle,
|
|
85
|
+
"redshift": Redshift,
|
|
86
|
+
"snowflake": Snowflake,
|
|
87
|
+
"presto": Presto,
|
|
88
|
+
"bigquery": BigQuery,
|
|
89
|
+
"databricks": Databricks,
|
|
90
|
+
"duckdb": DuckDB,
|
|
91
|
+
"trino": Trino,
|
|
92
|
+
"clickhouse": Clickhouse,
|
|
93
|
+
"vertica": Vertica,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Connect:
|
|
98
|
+
"""Provides methods for connecting to a supported database using a URL or connection dict."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, database_by_scheme: dict[str, type[Database]] = DATABASE_BY_SCHEME):
|
|
101
|
+
self.database_by_scheme = database_by_scheme
|
|
102
|
+
self.match_uri_path = {name: MatchUriPath(cls) for name, cls in database_by_scheme.items()}
|
|
103
|
+
self.conn_cache = WeakCache()
|
|
104
|
+
|
|
105
|
+
def connect_to_uri(self, db_uri: str, thread_count: int | None = 1) -> Database:
|
|
106
|
+
dsn = dsnparse.parse(db_uri)
|
|
107
|
+
if len(dsn.schemes) > 1:
|
|
108
|
+
raise NotImplementedError("No support for multiple schemes")
|
|
109
|
+
(scheme,) = dsn.schemes
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
matcher = self.match_uri_path[scheme]
|
|
113
|
+
except KeyError:
|
|
114
|
+
raise NotImplementedError(f"Scheme '{scheme}' currently not supported")
|
|
115
|
+
|
|
116
|
+
cls = matcher.database_cls
|
|
117
|
+
|
|
118
|
+
if scheme == "databricks":
|
|
119
|
+
assert not dsn.user
|
|
120
|
+
kw = {}
|
|
121
|
+
kw["access_token"] = dsn.password
|
|
122
|
+
kw["http_path"] = dsn.path
|
|
123
|
+
kw["server_hostname"] = dsn.host
|
|
124
|
+
kw.update(dsn.query)
|
|
125
|
+
elif scheme == "duckdb":
|
|
126
|
+
kw = {}
|
|
127
|
+
kw["filepath"] = dsn.dbname
|
|
128
|
+
kw["dbname"] = dsn.user
|
|
129
|
+
else:
|
|
130
|
+
kw = matcher.match_path(dsn)
|
|
131
|
+
|
|
132
|
+
if scheme == "bigquery":
|
|
133
|
+
kw["project"] = dsn.host
|
|
134
|
+
return cls(**kw)
|
|
135
|
+
|
|
136
|
+
if scheme == "snowflake":
|
|
137
|
+
kw["account"] = dsn.host
|
|
138
|
+
assert not dsn.port
|
|
139
|
+
kw["user"] = dsn.user
|
|
140
|
+
kw["password"] = dsn.password
|
|
141
|
+
else:
|
|
142
|
+
kw["host"] = dsn.host
|
|
143
|
+
kw["port"] = dsn.port
|
|
144
|
+
kw["user"] = dsn.user
|
|
145
|
+
if dsn.password:
|
|
146
|
+
kw["password"] = dsn.password
|
|
147
|
+
|
|
148
|
+
kw = {k: v for k, v in kw.items() if v is not None}
|
|
149
|
+
|
|
150
|
+
if issubclass(cls, ThreadedDatabase):
|
|
151
|
+
db = cls(thread_count=thread_count, **kw)
|
|
152
|
+
else:
|
|
153
|
+
db = cls(**kw)
|
|
154
|
+
|
|
155
|
+
return self._connection_created(db)
|
|
156
|
+
|
|
157
|
+
def connect_with_dict(self, d: dict, thread_count: int | None = 1) -> Database:
|
|
158
|
+
d = dict(d)
|
|
159
|
+
driver = d.pop("driver")
|
|
160
|
+
try:
|
|
161
|
+
matcher = self.match_uri_path[driver]
|
|
162
|
+
except KeyError:
|
|
163
|
+
raise NotImplementedError(f"Driver '{driver}' currently not supported")
|
|
164
|
+
|
|
165
|
+
cls = matcher.database_cls
|
|
166
|
+
if issubclass(cls, ThreadedDatabase):
|
|
167
|
+
db = cls(thread_count=thread_count, **d)
|
|
168
|
+
else:
|
|
169
|
+
db = cls(**d)
|
|
170
|
+
|
|
171
|
+
return self._connection_created(db)
|
|
172
|
+
|
|
173
|
+
def _connection_created(self, db: Database) -> Database:
|
|
174
|
+
db.setup_dialect() # per-connection dialect settings, e.g. Oracle's hash charset
|
|
175
|
+
return db
|
|
176
|
+
|
|
177
|
+
def __call__(
|
|
178
|
+
self, db_conf: str | dict, thread_count: int | None = 1, shared: bool = True
|
|
179
|
+
) -> Database:
|
|
180
|
+
if shared:
|
|
181
|
+
with suppress(KeyError):
|
|
182
|
+
conn = self.conn_cache.get(db_conf)
|
|
183
|
+
if not conn.is_closed:
|
|
184
|
+
return conn
|
|
185
|
+
|
|
186
|
+
if isinstance(db_conf, str):
|
|
187
|
+
conn = self.connect_to_uri(db_conf, thread_count)
|
|
188
|
+
elif isinstance(db_conf, dict):
|
|
189
|
+
conn = self.connect_with_dict(db_conf, thread_count)
|
|
190
|
+
else:
|
|
191
|
+
raise TypeError(f"db configuration must be a URI string or a dictionary. Instead got '{db_conf}'.")
|
|
192
|
+
|
|
193
|
+
if shared:
|
|
194
|
+
self.conn_cache.add(db_conf, conn)
|
|
195
|
+
return conn
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class UtcEnforcingConnect(Connect):
|
|
199
|
+
def _connection_created(self, db: Database) -> Database:
|
|
200
|
+
db = super()._connection_created(db)
|
|
201
|
+
try:
|
|
202
|
+
db.query(db.dialect.set_timezone_to_utc())
|
|
203
|
+
except (NotImplementedError, Exception):
|
|
204
|
+
logger.debug(
|
|
205
|
+
f"Database '{db}' does not allow setting timezone. We recommend making sure it's set to 'UTC'."
|
|
206
|
+
)
|
|
207
|
+
return db
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
connect = UtcEnforcingConnect(DATABASE_BY_SCHEME)
|
diffdb/databases/base.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# diffdb/databases/base.py
|
|
2
|
+
"""Core database abstractions and threaded execution engine for diffdb.
|
|
3
|
+
|
|
4
|
+
Completely independent database connector framework, leveraging YamlDialect for all
|
|
5
|
+
datatype, normalization, and syntax handling.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import threading
|
|
10
|
+
from abc import ABC, abstractmethod
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
13
|
+
from contextlib import suppress
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from functools import wraps
|
|
16
|
+
from typing import (
|
|
17
|
+
Any,
|
|
18
|
+
TypeVar,
|
|
19
|
+
get_args,
|
|
20
|
+
get_origin,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
from ..types import (
|
|
24
|
+
DbKey,
|
|
25
|
+
DbPath,
|
|
26
|
+
DbTime,
|
|
27
|
+
)
|
|
28
|
+
from ..utils import dataclass, strict_zip
|
|
29
|
+
from .yaml_dialect import YamlDialect
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"ConnectError",
|
|
35
|
+
"Database",
|
|
36
|
+
"DbKey",
|
|
37
|
+
"DbPath",
|
|
38
|
+
"DbTime",
|
|
39
|
+
"QueryError",
|
|
40
|
+
"QueryResult",
|
|
41
|
+
"ThreadedDatabase",
|
|
42
|
+
"import_helper",
|
|
43
|
+
"parse_table_name",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_table_name(t: str) -> DbPath:
|
|
48
|
+
return tuple(t.split("."))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def import_helper(package: str | None = None, text: str = ""):
|
|
52
|
+
def dec(f):
|
|
53
|
+
@wraps(f)
|
|
54
|
+
def _inner():
|
|
55
|
+
try:
|
|
56
|
+
return f()
|
|
57
|
+
except ModuleNotFoundError as e:
|
|
58
|
+
s = text
|
|
59
|
+
if package:
|
|
60
|
+
s += f"You can install it using 'pip install diffdb-core[{package}]'."
|
|
61
|
+
raise ModuleNotFoundError(f"{e}\n\n{s}\n")
|
|
62
|
+
|
|
63
|
+
return _inner
|
|
64
|
+
|
|
65
|
+
return dec
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ConnectError(Exception):
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class QueryError(Exception):
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _one(seq):
|
|
77
|
+
(x,) = seq
|
|
78
|
+
return x
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class QueryResult:
|
|
83
|
+
rows: list
|
|
84
|
+
columns: list = None
|
|
85
|
+
|
|
86
|
+
def __iter__(self):
|
|
87
|
+
return iter(self.rows)
|
|
88
|
+
|
|
89
|
+
def __len__(self):
|
|
90
|
+
return len(self.rows)
|
|
91
|
+
|
|
92
|
+
def __getitem__(self, i):
|
|
93
|
+
return self.rows[i]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
TRes = TypeVar("TRes")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Database(ABC):
|
|
100
|
+
"""Base class for database connections and queries.
|
|
101
|
+
|
|
102
|
+
A driver subclass sets `dialect`, `CONNECT_URI_HELP` (example URI for help and error messages) and
|
|
103
|
+
`CONNECT_URI_PARAMS` (parameters given in the path of the URI), and implements `_query`.
|
|
104
|
+
|
|
105
|
+
`dialect` is a class attribute shared by every connection of the class. A connection that needs its own
|
|
106
|
+
settings (e.g. Oracle's hash charset) overrides `configure_dialect`; `setup_dialect` then gives that
|
|
107
|
+
connection its own copy. `connect()` calls `setup_dialect` once, when the connection is created.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
dialect: YamlDialect
|
|
111
|
+
CONNECT_URI_HELP: str
|
|
112
|
+
CONNECT_URI_PARAMS: Sequence[str] = ()
|
|
113
|
+
default_schema: str | None = None
|
|
114
|
+
is_closed: bool = False
|
|
115
|
+
|
|
116
|
+
def configure_dialect(self, dialect: YamlDialect) -> YamlDialect:
|
|
117
|
+
"""Return the dialect this connection should use. Default: the shared class dialect, unchanged.
|
|
118
|
+
|
|
119
|
+
Override to adjust per-connection settings. Never mutate `dialect` (it is shared by every
|
|
120
|
+
connection of the class): return an adjusted copy instead.
|
|
121
|
+
"""
|
|
122
|
+
return dialect
|
|
123
|
+
|
|
124
|
+
def setup_dialect(self) -> None:
|
|
125
|
+
"""Apply `configure_dialect` to this connection (it may run queries, e.g. to read session settings)."""
|
|
126
|
+
dialect = self.configure_dialect(type(self).dialect)
|
|
127
|
+
if dialect is not type(self).dialect:
|
|
128
|
+
self.dialect = dialect
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def name(self):
|
|
132
|
+
return type(self).__name__
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def db_conf(self) -> dict:
|
|
136
|
+
return getattr(self, "_args", getattr(self, "kwargs", {}))
|
|
137
|
+
|
|
138
|
+
def query(self, sql_code: str, res_type: type[TRes] | None = None) -> Any:
|
|
139
|
+
"""Run a SQL statement and convert the result to `res_type` (int, str, tuple, list, list[tuple], ...)."""
|
|
140
|
+
res = self._query(sql_code)
|
|
141
|
+
|
|
142
|
+
if res_type is None:
|
|
143
|
+
pass
|
|
144
|
+
elif res is None:
|
|
145
|
+
assert res_type is not None
|
|
146
|
+
raise ValueError(f"Query returned NULL, but query() is expecting type {res_type}")
|
|
147
|
+
elif res_type is list:
|
|
148
|
+
return list(res)
|
|
149
|
+
elif res_type in (int, str):
|
|
150
|
+
if not res:
|
|
151
|
+
raise ValueError("Query returned 0 rows, expected 1")
|
|
152
|
+
row = _one(res)
|
|
153
|
+
if not row:
|
|
154
|
+
raise ValueError("Row is empty, expected 1 column")
|
|
155
|
+
res = _one(row)
|
|
156
|
+
if res is None:
|
|
157
|
+
return None
|
|
158
|
+
return res_type(res)
|
|
159
|
+
elif res_type is datetime:
|
|
160
|
+
res = _one(_one(res))
|
|
161
|
+
if isinstance(res, str):
|
|
162
|
+
res = datetime.fromisoformat(res[:23])
|
|
163
|
+
return res
|
|
164
|
+
elif res_type is tuple:
|
|
165
|
+
assert len(res) == 1, (sql_code, res)
|
|
166
|
+
return tuple(res[0])
|
|
167
|
+
else:
|
|
168
|
+
origin = get_origin(res_type) or res_type
|
|
169
|
+
args = get_args(res_type)
|
|
170
|
+
if origin in (list, Sequence) or (isinstance(origin, type) and origin is not Any and issubclass(origin, (list, Sequence))):
|
|
171
|
+
item_type = args[0] if args else Any
|
|
172
|
+
item_origin = get_origin(item_type) or item_type
|
|
173
|
+
if item_origin is Any:
|
|
174
|
+
return [tuple(row) for row in res]
|
|
175
|
+
elif isinstance(item_origin, type) and issubclass(item_origin, (int, str, bytes, float)):
|
|
176
|
+
return [_one(row) for row in res]
|
|
177
|
+
elif item_origin is tuple or (isinstance(item_origin, type) and issubclass(item_origin, tuple)):
|
|
178
|
+
return [tuple(row) for row in res]
|
|
179
|
+
elif item_origin is dict or (isinstance(item_origin, type) and issubclass(item_origin, dict)):
|
|
180
|
+
return [dict(strict_zip(res.columns, row)) for row in res]
|
|
181
|
+
elif isinstance(item_origin, type):
|
|
182
|
+
return [item_origin(**dict(strict_zip(res.columns, row))) for row in res]
|
|
183
|
+
else:
|
|
184
|
+
return [tuple(row) for row in res]
|
|
185
|
+
|
|
186
|
+
if len(res) == 0:
|
|
187
|
+
return None
|
|
188
|
+
assert len(res) == 1, len(res)
|
|
189
|
+
d = dict(strict_zip(res.columns, res[0]))
|
|
190
|
+
return res_type(**d)
|
|
191
|
+
return res
|
|
192
|
+
|
|
193
|
+
@abstractmethod
|
|
194
|
+
def _query(self, sql_code: str) -> list:
|
|
195
|
+
"Send a query to the database and return the result"
|
|
196
|
+
|
|
197
|
+
def parse_table_name(self, name: str) -> DbPath:
|
|
198
|
+
return parse_table_name(name)
|
|
199
|
+
|
|
200
|
+
def _query_cursor(self, c, sql_code: str) -> QueryResult | None:
|
|
201
|
+
logger.debug(f"{self.name} Executing SQL: {sql_code}")
|
|
202
|
+
c.execute(sql_code, ()) # empty parameter tuple, as before (the diff never binds parameters)
|
|
203
|
+
if sql_code.lstrip().lower().startswith(("select", "explain", "show", "with")):
|
|
204
|
+
columns = c.description and [col[0] for col in c.description]
|
|
205
|
+
return QueryResult(c.fetchall(), columns)
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
def _query_conn(self, conn, sql_code: str) -> QueryResult | None:
|
|
209
|
+
c = conn.cursor()
|
|
210
|
+
try:
|
|
211
|
+
return self._query_cursor(c, sql_code)
|
|
212
|
+
finally:
|
|
213
|
+
with suppress(Exception):
|
|
214
|
+
c.close()
|
|
215
|
+
|
|
216
|
+
def close(self):
|
|
217
|
+
self.is_closed = True
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class ThreadedDatabase(Database):
|
|
221
|
+
"""Access the database through singleton worker threads."""
|
|
222
|
+
|
|
223
|
+
def __init__(self, thread_count=1):
|
|
224
|
+
self._init_error = None
|
|
225
|
+
self._active_conns = []
|
|
226
|
+
self._conns_lock = threading.Lock()
|
|
227
|
+
self._queue = ThreadPoolExecutor(thread_count, initializer=self.set_conn)
|
|
228
|
+
self.thread_local = threading.local()
|
|
229
|
+
logger.info(f"[{self.name}] Starting a threadpool, size={thread_count}.")
|
|
230
|
+
|
|
231
|
+
def set_conn(self):
|
|
232
|
+
assert not hasattr(self.thread_local, "conn")
|
|
233
|
+
try:
|
|
234
|
+
conn = self.create_connection()
|
|
235
|
+
self.thread_local.conn = conn
|
|
236
|
+
with self._conns_lock:
|
|
237
|
+
self._active_conns.append(conn)
|
|
238
|
+
except Exception as e:
|
|
239
|
+
self._init_error = e
|
|
240
|
+
|
|
241
|
+
def _query(self, sql_code: str) -> QueryResult:
|
|
242
|
+
r = self._queue.submit(self._query_in_worker, sql_code)
|
|
243
|
+
return r.result()
|
|
244
|
+
|
|
245
|
+
def _query_in_worker(self, sql_code: str):
|
|
246
|
+
if self._init_error:
|
|
247
|
+
raise self._init_error
|
|
248
|
+
return self._query_conn(self.thread_local.conn, sql_code)
|
|
249
|
+
|
|
250
|
+
@abstractmethod
|
|
251
|
+
def create_connection(self):
|
|
252
|
+
"""Return a connection instance that supports the .cursor() method."""
|
|
253
|
+
|
|
254
|
+
def close(self):
|
|
255
|
+
self.is_closed = True
|
|
256
|
+
super().close()
|
|
257
|
+
try:
|
|
258
|
+
self._queue.shutdown(wait=False, cancel_futures=True)
|
|
259
|
+
except TypeError:
|
|
260
|
+
self._queue.shutdown(wait=False)
|
|
261
|
+
|
|
262
|
+
with self._conns_lock:
|
|
263
|
+
for conn in self._active_conns:
|
|
264
|
+
with suppress(Exception):
|
|
265
|
+
conn.close()
|
|
266
|
+
self._active_conns.clear()
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# diffdb/databases/bigquery.py
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from .base import (
|
|
5
|
+
Database,
|
|
6
|
+
QueryError,
|
|
7
|
+
QueryResult,
|
|
8
|
+
import_helper,
|
|
9
|
+
)
|
|
10
|
+
from .yaml_dialect import YamlDialect
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@import_helper("bigquery")
|
|
16
|
+
def import_bigquery():
|
|
17
|
+
import google.cloud.bigquery
|
|
18
|
+
return google.cloud.bigquery
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class BigQuery(Database):
|
|
22
|
+
dialect = YamlDialect.load("bigquery")
|
|
23
|
+
CONNECT_URI_HELP = "bigquery://<project>/<dataset>"
|
|
24
|
+
CONNECT_URI_PARAMS = ("dataset",)
|
|
25
|
+
|
|
26
|
+
def __init__(self, *, project: str, dataset: str, **kw):
|
|
27
|
+
self.default_schema = dataset
|
|
28
|
+
self.project = project
|
|
29
|
+
self._kw = kw
|
|
30
|
+
self._client = None
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def client(self):
|
|
34
|
+
if self._client is None:
|
|
35
|
+
bq = import_bigquery()
|
|
36
|
+
self._client = bq.Client(project=self.project, **self._kw)
|
|
37
|
+
return self._client
|
|
38
|
+
|
|
39
|
+
def close(self):
|
|
40
|
+
super().close()
|
|
41
|
+
if self._client:
|
|
42
|
+
self._client.close()
|
|
43
|
+
|
|
44
|
+
def _query(self, sql_code: str):
|
|
45
|
+
query_str = sql_code
|
|
46
|
+
logger.debug(f"{self.name} Executing SQL: {query_str}")
|
|
47
|
+
try:
|
|
48
|
+
job = self.client.query(query_str)
|
|
49
|
+
res = list(job.result())
|
|
50
|
+
columns = [field.name for field in job.schema] if job.schema else []
|
|
51
|
+
rows = [tuple(row.values()) for row in res]
|
|
52
|
+
return QueryResult(rows, columns)
|
|
53
|
+
except Exception as e:
|
|
54
|
+
raise QueryError(e) from e
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# diffdb/databases/clickhouse.py
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from .base import (
|
|
5
|
+
Database,
|
|
6
|
+
import_helper,
|
|
7
|
+
)
|
|
8
|
+
from .yaml_dialect import YamlDialect
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@import_helper("clickhouse")
|
|
14
|
+
def import_clickhouse():
|
|
15
|
+
import clickhouse_driver
|
|
16
|
+
return clickhouse_driver
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Clickhouse(Database):
|
|
20
|
+
dialect = YamlDialect.load("clickhouse")
|
|
21
|
+
default_schema = "default"
|
|
22
|
+
CONNECT_URI_HELP = "clickhouse://<user>:<password>@<host>:<port>/<database>"
|
|
23
|
+
CONNECT_URI_PARAMS = ("database?",)
|
|
24
|
+
|
|
25
|
+
def __init__(self, *, host: str = "localhost", port: int = 9000, user: str = "default", password: str = "", database: str = "default", **kw):
|
|
26
|
+
ch = import_clickhouse()
|
|
27
|
+
self.default_schema = database
|
|
28
|
+
self._conn = ch.connect(host=host, port=port, user=user, password=password, database=database, **kw)
|
|
29
|
+
|
|
30
|
+
def _query(self, sql_code: str):
|
|
31
|
+
return self._query_conn(self._conn, sql_code)
|
|
32
|
+
|
|
33
|
+
def close(self):
|
|
34
|
+
super().close()
|
|
35
|
+
self._conn.close()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# diffdb/databases/databricks.py
|
|
2
|
+
import logging
|
|
3
|
+
|
|
4
|
+
from .base import (
|
|
5
|
+
Database,
|
|
6
|
+
import_helper,
|
|
7
|
+
)
|
|
8
|
+
from .yaml_dialect import YamlDialect
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@import_helper("databricks")
|
|
14
|
+
def import_databricks():
|
|
15
|
+
from databricks import sql
|
|
16
|
+
return sql
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Databricks(Database):
|
|
20
|
+
dialect = YamlDialect.load("databricks")
|
|
21
|
+
default_schema = "default"
|
|
22
|
+
CONNECT_URI_HELP = "databricks://<token>@<host>/<path>?catalog=<CATALOG>&schema=<SCHEMA>"
|
|
23
|
+
|
|
24
|
+
def __init__(self, *, server_hostname: str, http_path: str, access_token: str, schema: str = "default", **kw):
|
|
25
|
+
sql = import_databricks()
|
|
26
|
+
self.default_schema = schema
|
|
27
|
+
self._conn = sql.connect(
|
|
28
|
+
server_hostname=server_hostname,
|
|
29
|
+
http_path=http_path,
|
|
30
|
+
access_token=access_token,
|
|
31
|
+
schema=schema,
|
|
32
|
+
**kw,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def _query(self, sql_code: str):
|
|
36
|
+
return self._query_conn(self._conn, sql_code)
|
|
37
|
+
|
|
38
|
+
def close(self):
|
|
39
|
+
super().close()
|
|
40
|
+
self._conn.close()
|