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.
Files changed (53) hide show
  1. diffdb/__init__.py +179 -0
  2. diffdb/concurrency/__init__.py +10 -0
  3. diffdb/concurrency/pool.py +88 -0
  4. diffdb/concurrency/stream.py +111 -0
  5. diffdb/core/__init__.py +38 -0
  6. diffdb/core/differ.py +136 -0
  7. diffdb/core/hash_differ.py +390 -0
  8. diffdb/core/segment.py +323 -0
  9. diffdb/core/sql.py +81 -0
  10. diffdb/core/summary.py +179 -0
  11. diffdb/databases/__init__.py +59 -0
  12. diffdb/databases/_connect.py +210 -0
  13. diffdb/databases/base.py +266 -0
  14. diffdb/databases/bigquery.py +54 -0
  15. diffdb/databases/clickhouse.py +35 -0
  16. diffdb/databases/databricks.py +40 -0
  17. diffdb/databases/dialects/_base.yaml +182 -0
  18. diffdb/databases/dialects/bigquery.yaml +39 -0
  19. diffdb/databases/dialects/clickhouse.yaml +42 -0
  20. diffdb/databases/dialects/databricks.yaml +36 -0
  21. diffdb/databases/dialects/duckdb.yaml +48 -0
  22. diffdb/databases/dialects/mysql.yaml +45 -0
  23. diffdb/databases/dialects/oracle.yaml +44 -0
  24. diffdb/databases/dialects/postgresql.yaml +44 -0
  25. diffdb/databases/dialects/presto.yaml +37 -0
  26. diffdb/databases/dialects/redshift.yaml +11 -0
  27. diffdb/databases/dialects/snowflake.yaml +55 -0
  28. diffdb/databases/dialects/trino.yaml +5 -0
  29. diffdb/databases/dialects/vertica.yaml +39 -0
  30. diffdb/databases/duckdb.py +40 -0
  31. diffdb/databases/mysql.py +38 -0
  32. diffdb/databases/oracle.py +99 -0
  33. diffdb/databases/postgresql.py +34 -0
  34. diffdb/databases/presto.py +41 -0
  35. diffdb/databases/redshift.py +12 -0
  36. diffdb/databases/snowflake.py +55 -0
  37. diffdb/databases/trino.py +41 -0
  38. diffdb/databases/vertica.py +43 -0
  39. diffdb/databases/yaml_dialect.py +428 -0
  40. diffdb/geometry/__init__.py +42 -0
  41. diffdb/geometry/arithmetic.py +141 -0
  42. diffdb/geometry/bisection.py +100 -0
  43. diffdb/geometry/vector.py +42 -0
  44. diffdb/telemetry/__init__.py +11 -0
  45. diffdb/telemetry/info_tree.py +52 -0
  46. diffdb/telemetry/query_tracker.py +53 -0
  47. diffdb/types.py +302 -0
  48. diffdb/utils.py +121 -0
  49. diffdb_core-0.1.0.dist-info/METADATA +315 -0
  50. diffdb_core-0.1.0.dist-info/RECORD +53 -0
  51. diffdb_core-0.1.0.dist-info/WHEEL +5 -0
  52. diffdb_core-0.1.0.dist-info/licenses/LICENSE.md +87 -0
  53. diffdb_core-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,38 @@
1
+ # diffdb/databases/mysql.py
2
+ import logging
3
+
4
+ from .base import ConnectError, ThreadedDatabase, import_helper
5
+ from .yaml_dialect import YamlDialect
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ @import_helper("mysql")
11
+ def import_mysql():
12
+ try:
13
+ import pymysql
14
+ return pymysql
15
+ except ImportError:
16
+ import mysql.connector
17
+ return mysql.connector
18
+
19
+
20
+ class MySQL(ThreadedDatabase):
21
+ dialect = YamlDialect.load("mysql")
22
+ CONNECT_URI_HELP = "mysql://<user>:<password>@<host>/<database>"
23
+ CONNECT_URI_PARAMS = ("database?",)
24
+
25
+ def __init__(self, *, thread_count=1, **kw):
26
+ self._args = dict(kw)
27
+ super().__init__(thread_count=thread_count)
28
+ try:
29
+ self.default_schema = kw["database"]
30
+ except KeyError:
31
+ raise ValueError("MySQL URL must specify a database")
32
+
33
+ def create_connection(self):
34
+ mysql = import_mysql()
35
+ try:
36
+ return mysql.connect(charset="utf8", use_unicode=True, **self._args)
37
+ except Exception as e:
38
+ raise ConnectError(*e.args) from e
@@ -0,0 +1,99 @@
1
+ # diffdb/databases/oracle.py
2
+ import copy
3
+ import logging
4
+
5
+ from .base import ConnectError, QueryError, ThreadedDatabase, import_helper
6
+ from .yaml_dialect import YamlDialect
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _with_hash_charset(dialect: YamlDialect, charset: str | None) -> YamlDialect:
12
+ """`dialect` with `hash_charset` set; a copy when it changes (the class dialect is shared)."""
13
+ if dialect.hash_charset == charset:
14
+ return dialect
15
+ configured = copy.deepcopy(dialect)
16
+ configured.hash_charset = charset
17
+ return configured
18
+
19
+
20
+ @import_helper("oracle")
21
+ def import_oracle():
22
+ try:
23
+ import oracledb
24
+ return oracledb
25
+ except ImportError:
26
+ import cx_Oracle
27
+ return cx_Oracle
28
+
29
+
30
+ class Oracle(ThreadedDatabase):
31
+ """Oracle connection.
32
+
33
+ Hash charset: rows are converted to AL32UTF8 before hashing (`normalization.hash_charset_wrap`) so
34
+ they hash like the UTF-8 target, unless the database already uses AL32UTF8. Pass `hash_charset=` to
35
+ set it explicitly; otherwise `setup_dialect()` (called by `connect()`) detects it from
36
+ NLS_CHARACTERSET. Each connection gets its own dialect copy, so different Oracle databases in one
37
+ process can hash differently.
38
+ """
39
+
40
+ dialect = YamlDialect.load("oracle")
41
+ CONNECT_URI_HELP = "oracle://<user>:<password>@<host>[:<port>]/<service name>"
42
+ CONNECT_URI_PARAMS = ("database?",)
43
+
44
+ def __init__(self, *, host=None, port=None, database=None, thread_count=1, **kw):
45
+ self.kwargs = dict(kw)
46
+ if "dsn" not in self.kwargs and host: # Easy Connect: host[:port][/service name]
47
+ address = f"{host}:{port}" if port else host
48
+ self.kwargs["dsn"] = f"{address}/{database}" if database else address
49
+
50
+ user = self.kwargs.get("user", "")
51
+ self.default_schema = user.upper() if user else "SYSTEM"
52
+ self.hash_charset: str | None = self.kwargs.pop("hash_charset", None) or self.kwargs.pop("charset", None)
53
+ self._db_characterset: str | None = None
54
+ if self.hash_charset: # explicit: no need to ask the database
55
+ self.dialect = _with_hash_charset(type(self).dialect, self.hash_charset)
56
+ super().__init__(thread_count=thread_count)
57
+
58
+ def get_database_characterset(self) -> str:
59
+ """Dynamically detect and cache Oracle NLS_CHARACTERSET."""
60
+ if self._db_characterset is None:
61
+ try:
62
+ rows = self.query(
63
+ "SELECT value FROM nls_database_parameters WHERE parameter = 'NLS_CHARACTERSET'",
64
+ list,
65
+ )
66
+ self._db_characterset = rows[0][0] if rows else "WE8ISO8859P1"
67
+ except Exception as e:
68
+ logger.warning(f"Failed to query NLS_CHARACTERSET: {e}; defaulting to WE8ISO8859P1")
69
+ self._db_characterset = "WE8ISO8859P1"
70
+ return self._db_characterset
71
+
72
+ def configure_dialect(self, dialect: YamlDialect) -> YamlDialect:
73
+ charset = self.hash_charset or self._detect_hash_charset()
74
+ return _with_hash_charset(dialect, charset)
75
+
76
+ def _detect_hash_charset(self) -> str | None:
77
+ """AL32UTF8 unless the database already stores AL32UTF8 (then no conversion is needed)."""
78
+ try:
79
+ db_charset = self.get_database_characterset()
80
+ except Exception as e:
81
+ logger.debug(f"Could not auto-detect NLS_CHARACTERSET: {e}; defaulting hash_charset to AL32UTF8")
82
+ return "AL32UTF8"
83
+ return None if db_charset == "AL32UTF8" else "AL32UTF8"
84
+
85
+ def create_connection(self):
86
+ self._oracle = import_oracle()
87
+ try:
88
+ return self._oracle.connect(**self.kwargs)
89
+ except Exception as e:
90
+ raise ConnectError(*e.args) from e
91
+
92
+ def _query_cursor(self, c, sql_code):
93
+ try:
94
+ return super()._query_cursor(c, sql_code)
95
+ except Exception as e:
96
+ oracle_mod = getattr(self, "_oracle", None) or import_oracle()
97
+ if hasattr(oracle_mod, "DatabaseError") and isinstance(e, oracle_mod.DatabaseError):
98
+ raise QueryError(e) from e
99
+ raise
@@ -0,0 +1,34 @@
1
+ # diffdb/databases/postgresql.py
2
+ import logging
3
+
4
+ from .base import ConnectError, ThreadedDatabase, import_helper
5
+ from .yaml_dialect import YamlDialect
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ @import_helper("postgresql")
11
+ def import_postgresql():
12
+ import psycopg2
13
+ import psycopg2.extras
14
+ return psycopg2
15
+
16
+
17
+ class PostgreSQL(ThreadedDatabase):
18
+ dialect = YamlDialect.load("postgresql")
19
+ CONNECT_URI_HELP = "postgresql://<user>:<password>@<host>/<database>"
20
+ CONNECT_URI_PARAMS = ("database?",)
21
+ default_schema = "public"
22
+
23
+ def __init__(self, *, thread_count=1, **kw):
24
+ self._args = dict(kw)
25
+ super().__init__(thread_count=thread_count)
26
+
27
+ def create_connection(self):
28
+ if not self._args:
29
+ self._args["host"] = None
30
+ pg = import_postgresql()
31
+ try:
32
+ return pg.connect(**self._args)
33
+ except pg.OperationalError as e:
34
+ raise ConnectError(*e.args) from e
@@ -0,0 +1,41 @@
1
+ # diffdb/databases/presto.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("presto")
14
+ def import_presto():
15
+ import prestodb
16
+ return prestodb
17
+
18
+
19
+ class Presto(Database):
20
+ dialect = YamlDialect.load("presto")
21
+ CONNECT_URI_HELP = "presto://<user>@<host>:<port>/<catalog>/<schema>"
22
+ CONNECT_URI_PARAMS = ("catalog", "schema")
23
+
24
+ def __init__(self, *, host: str, port: int, user: str, catalog: str, schema: str, **kw):
25
+ presto = import_presto()
26
+ self.default_schema = schema
27
+ self._conn = presto.dbapi.connect(
28
+ host=host,
29
+ port=port,
30
+ user=user,
31
+ catalog=catalog,
32
+ schema=schema,
33
+ **kw,
34
+ )
35
+
36
+ def _query(self, sql_code: str):
37
+ return self._query_conn(self._conn, sql_code)
38
+
39
+ def close(self):
40
+ super().close()
41
+ self._conn.close()
@@ -0,0 +1,12 @@
1
+ # diffdb/databases/redshift.py
2
+ import logging
3
+
4
+ from .postgresql import PostgreSQL
5
+ from .yaml_dialect import YamlDialect
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ class Redshift(PostgreSQL):
11
+ dialect = YamlDialect.load("redshift")
12
+ CONNECT_URI_HELP = "redshift://<user>:<password>@<host>/<database>"
@@ -0,0 +1,55 @@
1
+ # diffdb/databases/snowflake.py
2
+ import logging
3
+
4
+ from .base import (
5
+ ConnectError,
6
+ Database,
7
+ import_helper,
8
+ )
9
+ from .yaml_dialect import YamlDialect
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ @import_helper("snowflake")
15
+ def import_snowflake():
16
+ import snowflake.connector
17
+ from cryptography.hazmat.backends import default_backend
18
+ from cryptography.hazmat.primitives import serialization
19
+ return snowflake, serialization, default_backend
20
+
21
+
22
+ class Snowflake(Database):
23
+ dialect = YamlDialect.load("snowflake")
24
+ CONNECT_URI_HELP = "snowflake://<user>:<password>@<account>/<database>/<SCHEMA>?warehouse=<WAREHOUSE>"
25
+ CONNECT_URI_PARAMS = ("database", "schema")
26
+ CONNECT_URI_KWPARAMS = ("warehouse",)
27
+
28
+ def __init__(self, *, schema: str, **kw):
29
+ snowflake, serialization, default_backend = import_snowflake()
30
+ logging.getLogger("snowflake.connector").setLevel(logging.WARNING)
31
+ logging.getLogger("snowflake.connector.network").disabled = True
32
+
33
+ assert '"' not in schema, "Schema name should not contain quotes!"
34
+ if "key" in kw:
35
+ with open(kw.get("key"), "rb") as key:
36
+ if "password" in kw:
37
+ raise ConnectError("Cannot use password and key at the same time")
38
+ passphrase = kw.get("private_key_passphrase").encode() if kw.get("private_key_passphrase") else None
39
+ p_key = serialization.load_pem_private_key(key.read(), password=passphrase, backend=default_backend())
40
+ kw["private_key"] = p_key.private_bytes(
41
+ encoding=serialization.Encoding.DER,
42
+ format=serialization.PrivateFormat.PKCS8,
43
+ encryption_algorithm=serialization.NoEncryption(),
44
+ )
45
+
46
+ self._conn = snowflake.connector.connect(schema=f'"{schema}"', **kw)
47
+ self._conn.telemetry_enabled = False
48
+ self.default_schema = schema
49
+
50
+ def close(self):
51
+ super().close()
52
+ self._conn.close()
53
+
54
+ def _query(self, sql_code: str):
55
+ return self._query_conn(self._conn, sql_code)
@@ -0,0 +1,41 @@
1
+ # diffdb/databases/trino.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("trino")
14
+ def import_trino():
15
+ import trino
16
+ return trino
17
+
18
+
19
+ class Trino(Database):
20
+ dialect = YamlDialect.load("trino")
21
+ CONNECT_URI_HELP = "trino://<user>@<host>:<port>/<catalog>/<schema>"
22
+ CONNECT_URI_PARAMS = ("catalog", "schema")
23
+
24
+ def __init__(self, *, host: str, port: int, user: str, catalog: str, schema: str, **kw):
25
+ tr = import_trino()
26
+ self.default_schema = schema
27
+ self._conn = tr.dbapi.connect(
28
+ host=host,
29
+ port=port,
30
+ user=user,
31
+ catalog=catalog,
32
+ schema=schema,
33
+ **kw,
34
+ )
35
+
36
+ def _query(self, sql_code: str):
37
+ return self._query_conn(self._conn, sql_code)
38
+
39
+ def close(self):
40
+ super().close()
41
+ self._conn.close()
@@ -0,0 +1,43 @@
1
+ # diffdb/databases/vertica.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("vertica")
14
+ def import_vertica():
15
+ import vertica_python
16
+ return vertica_python
17
+
18
+
19
+ class Vertica(Database):
20
+ dialect = YamlDialect.load("vertica")
21
+ default_schema = "public"
22
+ CONNECT_URI_HELP = "vertica://<user>:<password>@<host>:<port>/<database>"
23
+ CONNECT_URI_PARAMS = ("database",)
24
+
25
+ def __init__(self, *, host: str, port: int = 5433, user: str = "dbadmin", password: str = "", database: str = "", **kw):
26
+ vertica = import_vertica()
27
+ conn_info = {
28
+ "host": host,
29
+ "port": port,
30
+ "user": user,
31
+ "password": password,
32
+ "database": database,
33
+ **kw,
34
+ }
35
+ self.default_schema = "public"
36
+ self._conn = vertica.connect(**conn_info)
37
+
38
+ def _query(self, sql_code: str):
39
+ return self._query_conn(self._conn, sql_code)
40
+
41
+ def close(self):
42
+ super().close()
43
+ self._conn.close()