sqlalchemy-cratedb 0.43.0__tar.gz → 0.44.0__tar.gz

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 (50) hide show
  1. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/CHANGES.md +47 -3
  2. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/CLAUDE.md +1 -2
  3. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/DEVELOP.md +13 -0
  4. {sqlalchemy_cratedb-0.43.0/src/sqlalchemy_cratedb.egg-info → sqlalchemy_cratedb-0.44.0}/PKG-INFO +6 -8
  5. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/pyproject.toml +5 -7
  6. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/__init__.py +4 -0
  7. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/compiler.py +173 -12
  8. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/dialect.py +118 -32
  9. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/type/__init__.py +4 -0
  10. sqlalchemy_cratedb-0.44.0/src/sqlalchemy_cratedb/type/ip.py +22 -0
  11. sqlalchemy_cratedb-0.44.0/src/sqlalchemy_cratedb/type/unresolved.py +10 -0
  12. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0/src/sqlalchemy_cratedb.egg-info}/PKG-INFO +6 -8
  13. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb.egg-info/SOURCES.txt +4 -1
  14. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb.egg-info/requires.txt +5 -11
  15. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/tests/test_error_handling.py +1 -1
  16. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/tests/test_schema.py +3 -5
  17. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/tests/test_support_pandas.py +13 -29
  18. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/tests/test_support_polyfill.py +3 -3
  19. sqlalchemy_cratedb-0.44.0/tests/test_type_compilation.py +105 -0
  20. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/CODE_OF_CONDUCT.md +0 -0
  21. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/CONTRIBUTING.md +0 -0
  22. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/LICENSE +0 -0
  23. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/MANIFEST.in +0 -0
  24. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/NOTICE +0 -0
  25. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/README.md +0 -0
  26. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/backlog.md +0 -0
  27. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/docs/_extra/robots.txt +0 -0
  28. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/docs/requirements.txt +0 -0
  29. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/setup.cfg +0 -0
  30. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/setup.py +0 -0
  31. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/compat/__init__.py +0 -0
  32. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/compat/api13.py +0 -0
  33. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/compat/core10.py +0 -0
  34. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/compat/core14.py +0 -0
  35. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/compat/core20.py +0 -0
  36. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/predicate.py +0 -0
  37. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/sa_version.py +0 -0
  38. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/support/__init__.py +0 -0
  39. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/support/pandas.py +0 -0
  40. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/support/polyfill.py +0 -0
  41. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/support/util.py +0 -0
  42. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/type/array.py +0 -0
  43. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/type/geo.py +0 -0
  44. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/type/object.py +0 -0
  45. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/type/vector.py +0 -0
  46. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb/util.py +0 -0
  47. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb.egg-info/dependency_links.txt +0 -0
  48. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb.egg-info/entry_points.txt +0 -0
  49. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/src/sqlalchemy_cratedb.egg-info/top_level.txt +0 -0
  50. {sqlalchemy_cratedb-0.43.0 → sqlalchemy_cratedb-0.44.0}/tests/test_support_util.py +0 -0
@@ -1,5 +1,52 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+ - Dependencies: Replaced `cratedb-toolkit[testing]` with
5
+ `testcontainers>=4.15,<5` in the `test` extra
6
+ - Types: Fixed `UUID` columns rejecting every insert, since values were bound
7
+ as 32 hex digits while CrateDB's `UUID` type takes the dashed form. The
8
+ portable `Uuid` type keeps its `CHAR(32)` storage. Storing `UUID` requires
9
+ CrateDB 6.2 or later
10
+ - Types: Added `uuid` and `uuid_array` to the reflected type map
11
+ - Types: Fixed `CLOB`, `NCHAR`, `NVARCHAR`, `DATETIME`, and `DATE` compiling to
12
+ type names CrateDB cannot parse. They now map to `STRING`, `CHAR`, `VARCHAR`,
13
+ and `TIMESTAMP` respectively, matching their generic lower-case counterparts
14
+ - BREAKING: Types: `cast(x, Date)` now renders `CAST(x AS DATE)` instead of
15
+ `CAST(x AS TIMESTAMP)`.
16
+ - Types: Mapped `Numeric` and `DECIMAL` to CrateDB's `NUMERIC`, carrying the
17
+ declared precision and scale into DDL and casts, where they previously
18
+ compiled to `LONG` and `DOUBLE` and lost them. Declaring such a column
19
+ without a precision now raises `CompileError`, since CrateDB only stores
20
+ the type with one. Storing the type requires CrateDB 5.9 or later
21
+ - BREAKING: Types: Bound `Decimal` values now reach the driver unconverted,
22
+ which serializes them as strings, storing every digit instead of rounding to
23
+ float. A `LONG` column that an earlier release created from `Numeric` rejects
24
+ any such value written with a decimal point, `1.00` included, so those
25
+ columns need migrating to `NUMERIC`
26
+ - Types: Added `numeric` and `numeric_array` to the reflected type map, where
27
+ they previously resolved to an abstract type that could not be compiled
28
+ - Compiler: Fixed array indexes rendering as object keys, as in `arr['1']`.
29
+ Added support for array slices, and for columns and expressions as indexes
30
+ - Compiler: Fixed cached statements on `sa.JSON` and `ObjectArray` columns
31
+ reusing the subscript of an earlier statement, which returned values of
32
+ another key. Fixed object keys containing a quote
33
+ - BREAKING: Compiler: A statement with a literal subscript on an `sa.JSON`,
34
+ `ObjectArray` or `ARRAY` column can't run with `executemany()` on a cached
35
+ engine. For that, use `execution_options(compiled_cache=None)`
36
+ - BREAKING: Compiler: An integer subscript on a nested object renders as an
37
+ array position. Write the key as a string, as in `obj['n']['1']`
38
+ - Compiler: `bool`, `float` and `None` subscripts raise `CompileError`
39
+ - Types: Added `geo_point`, `geo_shape`, `ip` and `character` to the
40
+ reflected type map, and arrays of mapped types
41
+ - Types: Reflected `CHAR` and `VARCHAR` columns keep their declared length
42
+ - Types: A reflected column of an unknown type warns and becomes
43
+ `UnresolvedType`, which raises `CompileError` naming the column in DDL
44
+
45
+ ## 2026/06/22 0.43.1
46
+ - Compiler: Fixed `AttributeError: 'CrateCompilerSA20' object has no attribute
47
+ 'visit_on_conflict_do_update'` by forwarding calls to
48
+ `PGCompiler.visit_on_conflict_do_update`
49
+
3
50
  ## 2026/06/17 0.43.0
4
51
  - Types: Improved support for FLOAT type, converging to FLOAT vs. DOUBLE
5
52
  - Types: Added method `ObjectArray.as_generic` for better reverse type lookups
@@ -10,9 +57,6 @@
10
57
  newly introduced `sqltypes.{DOUBLE,DOUBLE_PRECISION}` types
11
58
  - Compiler: Made `CREATE INDEX` a no-op, only emitting `SELECT 1`, because CrateDB
12
59
  does not support that statement
13
- - Compiler: Fixed `AttributeError: 'CrateCompilerSA20' object has no attribute
14
- 'visit_on_conflict_do_update'` by forwarding calls to
15
- `PGCompiler.visit_on_conflict_do_update`
16
60
  - Dialect: Added methods concerned with isolation levels as no-ops
17
61
  - Types: Started emulating PostgreSQL's `JSON(B)` types using CrateDB's `OBJECT`
18
62
  - Dialect: now uses `paramstyle = "pyformat"` supported in crate-python 2.2.1.
@@ -13,7 +13,6 @@ source bootstrap.sh # Creates .venv with Python 3.11, installs all deps in edi
13
13
  ```
14
14
 
15
15
  Environment variables that influence bootstrap:
16
- - `CRATEDB_VERSION` (default: `5.5.1`) — CrateDB Docker image version
17
16
  - `SQLALCHEMY_VERSION` (default: `<2.2`) — SQLAlchemy version constraint
18
17
  - `PIP_ALLOW_PRERELEASE=true` — allow pre-release packages
19
18
 
@@ -34,7 +33,7 @@ pytest -k test_score
34
33
  python -m unittest -vvv tests/integration.py
35
34
  ```
36
35
 
37
- Tests require a live CrateDB instance via Docker (managed automatically by `cratedb_toolkit.testing.testcontainers`).
36
+ Most tests need the CrateDB node from `tests/docker-compose.yml` up and answering on port 4200 before pytest starts. Tests using the `cratedb_service` fixture run against a second node, which the fixture starts itself through `testcontainers.community.cratedb`. `CRATEDB_VERSION` picks the image tag for both (fixture default: `nightly`).
38
37
 
39
38
  ## Architecture
40
39
 
@@ -32,6 +32,19 @@ Format code:
32
32
 
33
33
  poe format
34
34
 
35
+ ## Pre-commit hooks
36
+
37
+ The repository ships a `.pre-commit-config.yaml` that runs the same linters
38
+ as CI (`ruff check` + `ruff format --check`) on every commit. To install:
39
+
40
+ pip install pre-commit
41
+ pre-commit install
42
+
43
+ After that, linting runs automatically before each `git commit`. To run it
44
+ manually across all files:
45
+
46
+ pre-commit run --all-files
47
+
35
48
 
36
49
  ## Preparing a release
37
50
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlalchemy-cratedb
3
- Version: 0.43.0
3
+ Version: 0.44.0
4
4
  Summary: SQLAlchemy dialect for CrateDB.
5
5
  Author-email: "Crate.io" <office@crate.io>
6
6
  License: Apache License 2.0
@@ -60,17 +60,14 @@ Requires-Python: >=3.10
60
60
  Description-Content-Type: text/markdown
61
61
  License-File: LICENSE
62
62
  License-File: NOTICE
63
- Requires-Dist: backports.zoneinfo<1; python_version < "3.9"
64
63
  Requires-Dist: crate<3,>=2.2.1
65
64
  Requires-Dist: geojson<4,>=2.5
66
- Requires-Dist: importlib-metadata; python_version < "3.8"
67
- Requires-Dist: importlib-resources; python_version < "3.9"
68
65
  Requires-Dist: sqlalchemy<2.2,>=1
69
- Requires-Dist: verlib2<0.4
66
+ Requires-Dist: verlib2<26.3
70
67
  Provides-Extra: all
71
68
  Requires-Dist: sqlalchemy-cratedb[vector]; extra == "all"
72
69
  Provides-Extra: develop
73
- Requires-Dist: mypy<1.20; extra == "develop"
70
+ Requires-Dist: mypy<2.4; extra == "develop"
74
71
  Requires-Dist: poethepoet<1; extra == "develop"
75
72
  Requires-Dist: pyproject-fmt<3; extra == "develop"
76
73
  Requires-Dist: ruff<0.16; extra == "develop"
@@ -80,15 +77,16 @@ Requires-Dist: crate-docs-theme>=0.26.5; extra == "doc"
80
77
  Requires-Dist: sphinx<10,>=3.5; extra == "doc"
81
78
  Provides-Extra: release
82
79
  Requires-Dist: build<2; extra == "release"
83
- Requires-Dist: twine<7; extra == "release"
80
+ Requires-Dist: twine<8; extra == "release"
84
81
  Provides-Extra: test
85
- Requires-Dist: cratedb-toolkit[testing]; extra == "test"
86
82
  Requires-Dist: dask[dataframe]; extra == "test"
83
+ Requires-Dist: httpx; extra == "test"
87
84
  Requires-Dist: pandas<2.4; extra == "test"
88
85
  Requires-Dist: pueblo>=0.0.7; extra == "test"
89
86
  Requires-Dist: pytest<10; extra == "test"
90
87
  Requires-Dist: pytest-cov<8; extra == "test"
91
88
  Requires-Dist: pytest-mock<4; extra == "test"
89
+ Requires-Dist: testcontainers<5,>=4.15; extra == "test"
92
90
  Provides-Extra: vector
93
91
  Requires-Dist: numpy; extra == "vector"
94
92
  Dynamic: license-file
@@ -78,19 +78,16 @@ dynamic = [
78
78
  "version",
79
79
  ]
80
80
  dependencies = [
81
- "backports.zoneinfo<1; python_version<'3.9'",
82
81
  "crate>=2.2.1,<3",
83
82
  "geojson>=2.5,<4",
84
- "importlib-metadata; python_version<'3.8'",
85
- "importlib-resources; python_version<'3.9'",
86
83
  "sqlalchemy>=1,<2.2",
87
- "verlib2<0.4",
84
+ "verlib2<26.3",
88
85
  ]
89
86
  optional-dependencies.all = [
90
87
  "sqlalchemy-cratedb[vector]",
91
88
  ]
92
89
  optional-dependencies.develop = [
93
- "mypy<1.20",
90
+ "mypy<2.4",
94
91
  "poethepoet<1",
95
92
  "pyproject-fmt<3",
96
93
  "ruff<0.16",
@@ -102,16 +99,17 @@ optional-dependencies.doc = [
102
99
  ]
103
100
  optional-dependencies.release = [
104
101
  "build<2",
105
- "twine<7",
102
+ "twine<8",
106
103
  ]
107
104
  optional-dependencies.test = [
108
- "cratedb-toolkit[testing]",
109
105
  "dask[dataframe]",
106
+ "httpx",
110
107
  "pandas<2.4",
111
108
  "pueblo>=0.0.7",
112
109
  "pytest<10",
113
110
  "pytest-cov<8",
114
111
  "pytest-mock<4",
112
+ "testcontainers>=4.15,<5",
115
113
  ]
116
114
  optional-dependencies.vector = [
117
115
  "numpy",
@@ -26,7 +26,9 @@ from .sa_version import SA_1_4, SA_VERSION
26
26
  from .support import insert_bulk
27
27
  from .type.array import ObjectArray
28
28
  from .type.geo import Geopoint, Geoshape
29
+ from .type.ip import IP
29
30
  from .type.object import ObjectType
31
+ from .type.unresolved import UnresolvedType
30
32
  from .type.vector import FloatVector, knn_match
31
33
 
32
34
  if SA_VERSION < SA_1_4:
@@ -72,8 +74,10 @@ __all__ = [
72
74
  FloatVector,
73
75
  Geopoint,
74
76
  Geoshape,
77
+ IP,
75
78
  ObjectArray,
76
79
  ObjectType,
80
+ UnresolvedType,
77
81
  match,
78
82
  knn_match,
79
83
  insert_bulk,
@@ -26,7 +26,15 @@ from collections import defaultdict
26
26
  import sqlalchemy as sa
27
27
  from sqlalchemy.dialects.postgresql.base import RESERVED_WORDS as POSTGRESQL_RESERVED_WORDS
28
28
  from sqlalchemy.dialects.postgresql.base import PGCompiler
29
- from sqlalchemy.sql import compiler
29
+ from sqlalchemy.sql import compiler, operators
30
+ from sqlalchemy.sql.elements import (
31
+ BinaryExpression,
32
+ BindParameter,
33
+ Grouping,
34
+ Null,
35
+ Slice,
36
+ TypeCoerce,
37
+ )
30
38
  from sqlalchemy.types import String
31
39
 
32
40
  from .sa_version import SA_1_4, SA_VERSION
@@ -97,6 +105,21 @@ def crate_before_execute(conn, clauseelement, multiparams, params, *args, **kwar
97
105
  return clauseelement, multiparams, params
98
106
 
99
107
 
108
+ def _require_numeric_precision(type_):
109
+ if isinstance(type_, sa.types.ARRAY):
110
+ _require_numeric_precision(type_.item_type)
111
+ return
112
+ if isinstance(type_, sa.types.TypeDecorator):
113
+ _require_numeric_precision(type_.impl)
114
+ return
115
+ if isinstance(type_, sa.types.Numeric) and not isinstance(type_, sa.types.Float):
116
+ if type_.precision is None:
117
+ raise sa.exc.CompileError(
118
+ "CrateDB stores a NUMERIC column only with a precision, "
119
+ "as in Numeric(precision=10, scale=2)"
120
+ )
121
+
122
+
100
123
  class CrateDDLCompiler(compiler.DDLCompiler):
101
124
  __special_opts_tmpl = {"partitioned_by": " PARTITIONED BY ({0})"}
102
125
  __clustered_opts_tmpl = {
@@ -106,6 +129,7 @@ class CrateDDLCompiler(compiler.DDLCompiler):
106
129
  __clustered_opt_tmpl = " CLUSTERED{clustered_by}{number_of_shards}"
107
130
 
108
131
  def get_column_specification(self, column, **kwargs):
132
+ _require_numeric_precision(column.type)
109
133
  colspec = (
110
134
  self.preparer.format_column(column)
111
135
  + " "
@@ -213,9 +237,6 @@ class CrateDDLCompiler(compiler.DDLCompiler):
213
237
 
214
238
 
215
239
  class CrateTypeCompiler(compiler.GenericTypeCompiler):
216
- visit_on_conflict_do_update = PGCompiler.visit_on_conflict_do_update
217
- _on_conflict_target = PGCompiler._on_conflict_target
218
-
219
240
  def visit_string(self, type_, **kw):
220
241
  return "STRING"
221
242
 
@@ -225,8 +246,17 @@ class CrateTypeCompiler(compiler.GenericTypeCompiler):
225
246
  def visit_TEXT(self, type_, **kw):
226
247
  return "STRING"
227
248
 
249
+ def visit_CLOB(self, type_, **kw):
250
+ return "STRING"
251
+
252
+ def visit_NCHAR(self, type_, **kw):
253
+ return self.visit_CHAR(type_, **kw)
254
+
255
+ def visit_NVARCHAR(self, type_, **kw):
256
+ return self.visit_VARCHAR(type_, **kw)
257
+
228
258
  def visit_DECIMAL(self, type_, **kw):
229
- return "DOUBLE"
259
+ return self.visit_NUMERIC(type_, **kw)
230
260
 
231
261
  def visit_double(self, type_, **kw):
232
262
  return "DOUBLE"
@@ -235,7 +265,15 @@ class CrateTypeCompiler(compiler.GenericTypeCompiler):
235
265
  return "LONG"
236
266
 
237
267
  def visit_NUMERIC(self, type_, **kw):
238
- return "LONG"
268
+ """
269
+ A bare `NUMERIC` is a valid cast target; only columns require the
270
+ precision, which `CrateDDLCompiler` enforces.
271
+ """
272
+ if type_.precision is None:
273
+ return "NUMERIC"
274
+ if type_.scale is None:
275
+ return "NUMERIC({0})".format(type_.precision)
276
+ return "NUMERIC({0}, {1})".format(type_.precision, type_.scale)
239
277
 
240
278
  def visit_INTEGER(self, type_, **kw):
241
279
  return "INT"
@@ -243,16 +281,30 @@ class CrateTypeCompiler(compiler.GenericTypeCompiler):
243
281
  def visit_SMALLINT(self, type_, **kw):
244
282
  return "SHORT"
245
283
 
246
- def visit_datetime(self, type_, **kw):
284
+ def visit_DATETIME(self, type_, **kw):
247
285
  return self.visit_TIMESTAMP(type_, **kw)
248
286
 
249
- def visit_date(self, type_, **kw):
250
- return "TIMESTAMP"
287
+ def visit_DATE(self, type_, **kw):
288
+ return "DATE" if kw.get("cast_target") else "TIMESTAMP"
289
+
290
+ def visit_TIME(self, type_, **kw):
291
+ """
292
+ CrateDB has no storable `TIME` column type. Plain `TIME` does not exist,
293
+ and `TIME WITH TIME ZONE` (TIMETZ) is literal/cast-only ("does not support
294
+ storage"). So store the time-of-day as a `STRING`, holding the value in
295
+ ISO 8601 format (e.g. ``19:00:30.123456``).
296
+ """
297
+ return "STRING"
251
298
 
252
299
  def visit_ARRAY(self, type_, **kw):
253
300
  if type_.dimensions is not None and type_.dimensions > 1:
254
301
  raise NotImplementedError("CrateDB doesn't support multidimensional arrays")
255
- return "ARRAY({0})".format(self.process(type_.item_type))
302
+ return "ARRAY({0})".format(self.process(type_.item_type, **kw))
303
+
304
+ def visit_unresolved(self, type_, **kw):
305
+ raise sa.exc.CompileError(
306
+ "Unable to represent CrateDB type '{0}' in SQLAlchemy".format(type_.type_name)
307
+ )
256
308
 
257
309
  def visit_OBJECT(self, type_, **kw):
258
310
  return "OBJECT"
@@ -296,12 +348,121 @@ class CrateTypeCompiler(compiler.GenericTypeCompiler):
296
348
  return "OBJECT"
297
349
 
298
350
 
351
+ def _slice_bound(value):
352
+ if value is None:
353
+ return ""
354
+ if isinstance(value, bool) or not isinstance(value, int):
355
+ raise sa.exc.CompileError(f"CrateDB array slices take integer bounds, not {value!r}")
356
+ return str(value)
357
+
358
+
359
+ class _SubscriptType(sa.types.TypeEngine):
360
+ """
361
+ Renders an array index, an array slice, or an object key as a literal.
362
+
363
+ With `int_as_key`, an integer renders as an object key.
364
+ """
365
+
366
+ cache_ok = True
367
+ # Reject `None`, instead of rendering it as `NULL`.
368
+ should_evaluate_none = True
369
+
370
+ def __init__(self, int_as_key=False):
371
+ self.int_as_key = int_as_key
372
+
373
+ def literal_processor(self, dialect):
374
+ def process(value):
375
+ if isinstance(value, slice):
376
+ if value.step is not None:
377
+ raise sa.exc.CompileError("CrateDB array slices do not support a step")
378
+ return "%s:%s" % (_slice_bound(value.start), _slice_bound(value.stop))
379
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
380
+ raise sa.exc.CompileError(
381
+ f"CrateDB subscripts take an integer index or a string key, not {value!r}"
382
+ )
383
+ if isinstance(value, int) and not self.int_as_key:
384
+ return str(value)
385
+ return "'%s'" % str(value).replace("'", "''")
386
+
387
+ return process
388
+
389
+
390
+ def _is_top_level_object(element):
391
+ """
392
+ Whether `element` is an object, and not a value taken out of one, which
393
+ may be an array. CrateDB does not accept an array index on an object.
394
+ """
395
+ while isinstance(element, Grouping):
396
+ element = element.element
397
+ if isinstance(element, BinaryExpression) and element.operator in (
398
+ operators.getitem,
399
+ operators.json_getitem_op,
400
+ ):
401
+ return False
402
+ return isinstance(element.type, sa.types.JSON)
403
+
404
+
405
+ def _unwrap_bindparam(element):
406
+ """
407
+ Return the bind parameter inside `element`, if it renders as a bare one.
408
+ """
409
+ inner = element
410
+ while isinstance(inner, Grouping):
411
+ inner = inner.element
412
+ if isinstance(inner, TypeCoerce):
413
+ inner = inner.typed_expression
414
+ return inner if isinstance(inner, BindParameter) else element
415
+
416
+
299
417
  class CrateCompiler(compiler.SQLCompiler):
418
+ def visit_typeclause(self, typeclause, **kw):
419
+ """
420
+ Mark that a type is being rendered as a cast target.
421
+ """
422
+ return super().visit_typeclause(typeclause, cast_target=True, **kw)
423
+
424
+ visit_on_conflict_do_update = PGCompiler.visit_on_conflict_do_update
425
+ _on_conflict_target = PGCompiler._on_conflict_target
426
+
427
+ def _render_subscript(self, binary, **kw):
428
+ left = self.process(binary.left, **kw)
429
+ index = _unwrap_bindparam(binary.right)
430
+ if isinstance(index, Slice):
431
+ return "%s[%s]" % (left, self._render_slice(index, **kw))
432
+ if not isinstance(index, BindParameter):
433
+ # CrateDB accepts bind parameters inside an expression.
434
+ return "%s[%s]" % (left, self.process(index, **kw))
435
+
436
+ # CrateDB does not accept a bind parameter as an array index or object
437
+ # key, so render it as a literal.
438
+ type_ = _SubscriptType(int_as_key=_is_top_level_object(binary.left))
439
+ if not index.required:
440
+ type_.literal_processor(self.dialect)(index.effective_value)
441
+ elif SA_VERSION < SA_1_4:
442
+ raise sa.exc.CompileError(
443
+ "A subscript taking its value on execution needs SQLAlchemy 1.4 or later"
444
+ )
445
+ if index.required or getattr(self, "cache_key", None) is not None:
446
+ kw["literal_execute"] = True
447
+ else:
448
+ kw["literal_binds"] = True
449
+ index = sa.type_coerce(index, type_).typed_expression
450
+ return "%s[%s]" % (left, self.process(index, **kw))
451
+
452
+ def _render_slice(self, slice_, **kw):
453
+ # CrateDB accepts bind parameters as slice bounds.
454
+ if not isinstance(slice_.step, Null):
455
+ raise sa.exc.CompileError("CrateDB array slices do not support a step")
456
+ return ":".join(
457
+ "" if isinstance(bound, Null) else self.process(bound, **kw)
458
+ for bound in (slice_.start, slice_.stop)
459
+ )
460
+
300
461
  def visit_getitem_binary(self, binary, operator, **kw):
301
- return "{0}['{1}']".format(self.process(binary.left, **kw), binary.right.value)
462
+ return self._render_subscript(binary, **kw)
302
463
 
303
464
  def visit_json_getitem_op_binary(self, binary, operator, _cast_applied=False, **kw):
304
- return "{0}['{1}']".format(self.process(binary.left, **kw), binary.right.value)
465
+ return self._render_subscript(binary, **kw)
305
466
 
306
467
  def visit_any(self, element, **kw):
307
468
  return "%s%sANY (%s)" % (
@@ -20,14 +20,15 @@
20
20
  # software solely pursuant to the terms of the relevant commercial agreement.
21
21
 
22
22
  import logging
23
+ import uuid
23
24
  import warnings
24
- from datetime import date, datetime
25
+ from datetime import date, datetime, time
25
26
 
26
27
  from sqlalchemy import types as sqltypes
27
28
  from sqlalchemy.engine import default, reflection
28
29
  from sqlalchemy.exc import SQLAlchemyError
29
30
  from sqlalchemy.sql import functions
30
- from sqlalchemy.util import asbool, to_list
31
+ from sqlalchemy.util import asbool, to_list, warn
31
32
 
32
33
  from .compiler import (
33
34
  CrateDDLCompiler,
@@ -35,9 +36,21 @@ from .compiler import (
35
36
  CrateTypeCompiler,
36
37
  )
37
38
  from .sa_version import SA_1_4, SA_2_0, SA_VERSION
38
- from .type import FloatVector, ObjectArray, ObjectType
39
+ from .type import IP, FloatVector, Geopoint, Geoshape, ObjectArray, ObjectType, UnresolvedType
39
40
  from .util import SSLMode
40
41
 
42
+ ARRAY_SUFFIX = "_array"
43
+
44
+
45
+ class Double(sqltypes.Float):
46
+ """
47
+ CrateDB's 64-bit approximate number; SQLAlchemy carries no core type for it
48
+ before 2.0's `DOUBLE`.
49
+ """
50
+
51
+ __visit_name__ = "double"
52
+
53
+
41
54
  # For SQLAlchemy >= 1.1.
42
55
  TYPES_MAP = {
43
56
  "boolean": sqltypes.BOOLEAN,
@@ -47,47 +60,33 @@ TYPES_MAP = {
47
60
  "timestamp with time zone": sqltypes.TIMESTAMP(timezone=True),
48
61
  "timestamp without time zone": sqltypes.TIMESTAMP(timezone=False),
49
62
  "object": ObjectType,
50
- "object_array": ObjectArray, # TODO: Can this also be improved to use `sqltypes.ARRAY`?
63
+ # `ObjectArray` tracks mutation of its objects, which a derived `ARRAY` would lose.
64
+ "object_array": ObjectArray,
51
65
  "integer": sqltypes.INTEGER,
52
66
  "long": sqltypes.BIGINT,
53
67
  "bigint": sqltypes.BIGINT,
54
68
  "float": sqltypes.FLOAT,
55
- "double": sqltypes.DECIMAL,
56
- "double precision": sqltypes.DECIMAL,
69
+ "double": Double,
70
+ "double precision": Double,
57
71
  "real": sqltypes.REAL,
58
72
  "string": sqltypes.VARCHAR,
59
73
  "text": sqltypes.VARCHAR,
74
+ "numeric": sqltypes.NUMERIC,
60
75
  "float_vector": FloatVector,
76
+ "geo_point": Geopoint,
77
+ "geo_shape": Geoshape,
78
+ "ip": IP,
79
+ "character": sqltypes.CHAR,
61
80
  }
62
81
 
63
- # For SQLAlchemy >= 1.4.
64
- try:
65
- from sqlalchemy.types import ARRAY
66
-
67
- TYPES_MAP["integer_array"] = ARRAY(sqltypes.INTEGER)
68
- TYPES_MAP["boolean_array"] = ARRAY(sqltypes.BOOLEAN)
69
- TYPES_MAP["short_array"] = ARRAY(sqltypes.SMALLINT)
70
- TYPES_MAP["smallint_array"] = ARRAY(sqltypes.SMALLINT)
71
- TYPES_MAP["timestamp_array"] = ARRAY(sqltypes.TIMESTAMP(timezone=False))
72
- TYPES_MAP["timestamp with time zone_array"] = ARRAY(sqltypes.TIMESTAMP(timezone=True))
73
- TYPES_MAP["long_array"] = ARRAY(sqltypes.BIGINT)
74
- TYPES_MAP["bigint_array"] = ARRAY(sqltypes.BIGINT)
75
- TYPES_MAP["float_array"] = ARRAY(sqltypes.FLOAT)
76
- TYPES_MAP["real_array"] = ARRAY(sqltypes.REAL)
77
- TYPES_MAP["string_array"] = ARRAY(sqltypes.VARCHAR)
78
- TYPES_MAP["text_array"] = ARRAY(sqltypes.VARCHAR)
79
- except Exception: # noqa: S110
80
- pass
81
-
82
82
  # For SQLAlchemy >= 2.0.
83
83
  try:
84
84
  from sqlalchemy.types import DOUBLE, DOUBLE_PRECISION
85
85
 
86
86
  TYPES_MAP["double"] = DOUBLE
87
- TYPES_MAP["double_array"] = ARRAY(DOUBLE)
88
87
  TYPES_MAP["double precision"] = DOUBLE_PRECISION
89
- TYPES_MAP["double precision_array"] = ARRAY(DOUBLE_PRECISION)
90
- except Exception: # noqa: S110
88
+ TYPES_MAP["uuid"] = sqltypes.UUID
89
+ except ImportError:
91
90
  pass
92
91
 
93
92
 
@@ -144,6 +143,11 @@ class DateTime(sqltypes.DateTime):
144
143
  def process(value):
145
144
  if not value:
146
145
  return None
146
+ # When the driver's `time_zone` is configured, the timestamp column
147
+ # has already been converted to `datetime` by the driver's data type converter.
148
+ # Pass it through unchanged so this processor stays idempotent.
149
+ if isinstance(value, datetime):
150
+ return value
147
151
  try:
148
152
  return datetime.utcfromtimestamp(value / 1e3)
149
153
  except TypeError:
@@ -167,12 +171,69 @@ class DateTime(sqltypes.DateTime):
167
171
  return process
168
172
 
169
173
 
174
+ class Time(sqltypes.Time):
175
+ def bind_processor(self, dialect):
176
+ def process(value):
177
+ if value is not None:
178
+ assert isinstance(value, time) # noqa: S101
179
+ return value.isoformat()
180
+ return None
181
+
182
+ return process
183
+
184
+ def result_processor(self, dialect, coltype):
185
+ def process(value):
186
+ if value is None:
187
+ return None
188
+ return time.fromisoformat(value)
189
+
190
+ return process
191
+
192
+
193
+ class Numeric(sqltypes.Numeric):
194
+ """
195
+ Hands `Decimal` values to the driver unconverted; it serializes them as
196
+ strings, which CrateDB stores without rounding.
197
+ """
198
+
199
+ def bind_processor(self, dialect):
200
+ return None
201
+
202
+
170
203
  colspecs = {
171
204
  sqltypes.Date: Date,
172
205
  sqltypes.DateTime: DateTime,
173
206
  sqltypes.TIMESTAMP: DateTime,
207
+ sqltypes.Time: Time,
208
+ sqltypes.Numeric: Numeric,
209
+ # `Float` derives from `Numeric`; this entry keeps it on the generic handling.
210
+ sqltypes.Float: sqltypes.Float,
174
211
  }
175
212
 
213
+ if SA_VERSION >= SA_2_0:
214
+
215
+ class UUID(sqltypes.UUID):
216
+ """
217
+ CrateDB's `UUID` column accepts the dashed form only, while SQLAlchemy binds
218
+ the 32-digit form for any dialect without native UUID support.
219
+ """
220
+
221
+ def bind_processor(self, dialect):
222
+ def process(value):
223
+ if value is None:
224
+ return None
225
+ return str(value if isinstance(value, uuid.UUID) else uuid.UUID(value))
226
+
227
+ return process
228
+
229
+ def literal_processor(self, dialect):
230
+ def process(value):
231
+ return "'{0}'".format(value if isinstance(value, uuid.UUID) else uuid.UUID(value))
232
+
233
+ return process
234
+
235
+ colspecs[sqltypes.UUID] = UUID
236
+
176
237
  if SA_VERSION >= SA_2_0:
177
238
  from .compat.core20 import CrateCompilerSA20
178
239
 
@@ -370,7 +431,7 @@ class CrateDialect(default.DefaultDialect):
370
431
  @reflection.cache
371
432
  def get_columns(self, connection, table_name, schema=None, **kw):
372
433
  query = (
373
- "SELECT column_name, data_type "
434
+ "SELECT column_name, data_type, character_maximum_length "
374
435
  "FROM information_schema.columns "
375
436
  "WHERE table_name = ? AND {0} = ? "
376
437
  "AND column_name !~ ?".format(self.schema_column)
@@ -436,9 +497,15 @@ class CrateDialect(default.DefaultDialect):
436
497
  return "table_schema"
437
498
 
438
499
  def _create_column_info(self, row):
500
+ name, data_type, length = row
501
+ type_ = self._resolve_type(data_type)
502
+ if isinstance(type_, UnresolvedType):
503
+ warn("Did not recognize type '{0}' of column '{1}'".format(data_type, name))
504
+ if length is not None and isinstance(type_, type) and issubclass(type_, sqltypes.String):
505
+ type_ = type_(length)
439
506
  return {
440
- "name": row[0],
441
- "type": self._resolve_type(row[1]),
507
+ "name": name,
508
+ "type": type_,
442
509
  # In Crate every column is nullable except PK
443
510
  # Primary Key Constraints are not nullable anyway, no matter what
444
511
  # we return here, so it's fine to return always `True`
@@ -446,7 +513,26 @@ class CrateDialect(default.DefaultDialect):
446
513
  }
447
514
 
448
515
  def _resolve_type(self, type_):
449
- return TYPES_MAP.get(type_, sqltypes.UserDefinedType)
516
+ resolved = self._lookup_type(type_)
517
+ if resolved is None:
518
+ return UnresolvedType(type_)
519
+ return resolved
520
+
521
+ def _lookup_type(self, type_):
522
+ resolved = TYPES_MAP.get(type_)
523
+ if resolved is not None:
524
+ return resolved
525
+ if not type_.endswith(ARRAY_SUFFIX):
526
+ return None
527
+ element_name = type_[: -len(ARRAY_SUFFIX)]
528
+ # The type compiler refuses `dimensions`, so a nested array could not be created again.
529
+ if not element_name or element_name.endswith(ARRAY_SUFFIX):
530
+ return None
531
+ element_type = self._lookup_type(element_name)
532
+ # CrateDB reports no length for array elements, and a bare `CHAR` holds one character.
533
+ if element_type is None or element_type is sqltypes.CHAR:
534
+ return None
535
+ return sqltypes.ARRAY(element_type)
450
536
 
451
537
  def has_ilike_operator(self):
452
538
  """
@@ -1,13 +1,17 @@
1
1
  from .array import ObjectArray
2
2
  from .geo import Geopoint, Geoshape
3
+ from .ip import IP
3
4
  from .object import ObjectType
5
+ from .unresolved import UnresolvedType
4
6
  from .vector import FloatVector, knn_match
5
7
 
6
8
  __all__ = [
7
9
  Geopoint,
8
10
  Geoshape,
11
+ IP,
9
12
  ObjectArray,
10
13
  ObjectType,
11
14
  FloatVector,
15
+ UnresolvedType,
12
16
  knn_match,
13
17
  ]
@@ -0,0 +1,22 @@
1
+ import ipaddress
2
+
3
+ from sqlalchemy import types as sqltypes
4
+
5
+
6
+ class IP(sqltypes.UserDefinedType):
7
+ cache_ok = True
8
+
9
+ def get_col_spec(self):
10
+ return "IP"
11
+
12
+ def bind_processor(self, dialect):
13
+ def process(value):
14
+ if isinstance(value, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
15
+ return str(value)
16
+ return value
17
+
18
+ return process
19
+
20
+ @property
21
+ def python_type(self):
22
+ return str
@@ -0,0 +1,10 @@
1
+ from sqlalchemy import types as sqltypes
2
+
3
+
4
+ class UnresolvedType(sqltypes.NullType):
5
+ __visit_name__ = "unresolved"
6
+
7
+ cache_ok = True
8
+
9
+ def __init__(self, type_name):
10
+ self.type_name = type_name
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sqlalchemy-cratedb
3
- Version: 0.43.0
3
+ Version: 0.44.0
4
4
  Summary: SQLAlchemy dialect for CrateDB.
5
5
  Author-email: "Crate.io" <office@crate.io>
6
6
  License: Apache License 2.0
@@ -60,17 +60,14 @@ Requires-Python: >=3.10
60
60
  Description-Content-Type: text/markdown
61
61
  License-File: LICENSE
62
62
  License-File: NOTICE
63
- Requires-Dist: backports.zoneinfo<1; python_version < "3.9"
64
63
  Requires-Dist: crate<3,>=2.2.1
65
64
  Requires-Dist: geojson<4,>=2.5
66
- Requires-Dist: importlib-metadata; python_version < "3.8"
67
- Requires-Dist: importlib-resources; python_version < "3.9"
68
65
  Requires-Dist: sqlalchemy<2.2,>=1
69
- Requires-Dist: verlib2<0.4
66
+ Requires-Dist: verlib2<26.3
70
67
  Provides-Extra: all
71
68
  Requires-Dist: sqlalchemy-cratedb[vector]; extra == "all"
72
69
  Provides-Extra: develop
73
- Requires-Dist: mypy<1.20; extra == "develop"
70
+ Requires-Dist: mypy<2.4; extra == "develop"
74
71
  Requires-Dist: poethepoet<1; extra == "develop"
75
72
  Requires-Dist: pyproject-fmt<3; extra == "develop"
76
73
  Requires-Dist: ruff<0.16; extra == "develop"
@@ -80,15 +77,16 @@ Requires-Dist: crate-docs-theme>=0.26.5; extra == "doc"
80
77
  Requires-Dist: sphinx<10,>=3.5; extra == "doc"
81
78
  Provides-Extra: release
82
79
  Requires-Dist: build<2; extra == "release"
83
- Requires-Dist: twine<7; extra == "release"
80
+ Requires-Dist: twine<8; extra == "release"
84
81
  Provides-Extra: test
85
- Requires-Dist: cratedb-toolkit[testing]; extra == "test"
86
82
  Requires-Dist: dask[dataframe]; extra == "test"
83
+ Requires-Dist: httpx; extra == "test"
87
84
  Requires-Dist: pandas<2.4; extra == "test"
88
85
  Requires-Dist: pueblo>=0.0.7; extra == "test"
89
86
  Requires-Dist: pytest<10; extra == "test"
90
87
  Requires-Dist: pytest-cov<8; extra == "test"
91
88
  Requires-Dist: pytest-mock<4; extra == "test"
89
+ Requires-Dist: testcontainers<5,>=4.15; extra == "test"
92
90
  Provides-Extra: vector
93
91
  Requires-Dist: numpy; extra == "vector"
94
92
  Dynamic: license-file
@@ -36,10 +36,13 @@ src/sqlalchemy_cratedb/support/util.py
36
36
  src/sqlalchemy_cratedb/type/__init__.py
37
37
  src/sqlalchemy_cratedb/type/array.py
38
38
  src/sqlalchemy_cratedb/type/geo.py
39
+ src/sqlalchemy_cratedb/type/ip.py
39
40
  src/sqlalchemy_cratedb/type/object.py
41
+ src/sqlalchemy_cratedb/type/unresolved.py
40
42
  src/sqlalchemy_cratedb/type/vector.py
41
43
  tests/test_error_handling.py
42
44
  tests/test_schema.py
43
45
  tests/test_support_pandas.py
44
46
  tests/test_support_polyfill.py
45
- tests/test_support_util.py
47
+ tests/test_support_util.py
48
+ tests/test_type_compilation.py
@@ -1,20 +1,13 @@
1
1
  crate<3,>=2.2.1
2
2
  geojson<4,>=2.5
3
3
  sqlalchemy<2.2,>=1
4
- verlib2<0.4
5
-
6
- [:python_version < "3.8"]
7
- importlib-metadata
8
-
9
- [:python_version < "3.9"]
10
- backports.zoneinfo<1
11
- importlib-resources
4
+ verlib2<26.3
12
5
 
13
6
  [all]
14
7
  sqlalchemy-cratedb[vector]
15
8
 
16
9
  [develop]
17
- mypy<1.20
10
+ mypy<2.4
18
11
  poethepoet<1
19
12
  pyproject-fmt<3
20
13
  ruff<0.16
@@ -26,16 +19,17 @@ sphinx<10,>=3.5
26
19
 
27
20
  [release]
28
21
  build<2
29
- twine<7
22
+ twine<8
30
23
 
31
24
  [test]
32
- cratedb-toolkit[testing]
33
25
  dask[dataframe]
26
+ httpx
34
27
  pandas<2.4
35
28
  pueblo>=0.0.7
36
29
  pytest<10
37
30
  pytest-cov<8
38
31
  pytest-mock<4
32
+ testcontainers<5,>=4.15
39
33
 
40
34
  [vector]
41
35
  numpy
@@ -8,7 +8,7 @@ def test_statement_with_error_trace(cratedb_service):
8
8
  """
9
9
  Verify that the `error_trace` option works correctly.
10
10
  """
11
- engine = sa.create_engine(cratedb_service.database.dburi, connect_args={"error_trace": True})
11
+ engine = sa.create_engine(cratedb_service.dburi, connect_args={"error_trace": True})
12
12
  with engine.connect() as connection:
13
13
  with pytest.raises(sa.exc.ProgrammingError) as ex:
14
14
  connection.execute(sa.text("CREATE TABLE foo AS SELECT 1 AS _id"))
@@ -7,13 +7,11 @@ def test_correct_schema(cratedb_service):
7
7
  """
8
8
  Tests that the correct schema is being picked up.
9
9
  """
10
- database = cratedb_service.database
11
-
12
10
  tablename = f'"{TESTDRIVE_DATA_SCHEMA}"."foobar"'
13
- database.run_sql(f"DROP TABLE IF EXISTS {tablename}")
14
- database.run_sql(f"CREATE TABLE {tablename} AS SELECT 1")
11
+ cratedb_service.run_sql(f"DROP TABLE IF EXISTS {tablename}")
12
+ cratedb_service.run_sql(f"CREATE TABLE {tablename} AS SELECT 1")
15
13
 
16
- inspector: sa.Inspector = sa.inspect(database.engine)
14
+ inspector: sa.Inspector = sa.inspect(cratedb_service.engine)
17
15
  assert TESTDRIVE_DATA_SCHEMA in inspector.get_schema_names()
18
16
 
19
17
  table_names = inspector.get_table_names(schema=TESTDRIVE_DATA_SCHEMA)
@@ -1,5 +1,4 @@
1
1
  import re
2
- import sys
3
2
 
4
3
  import pandas as pd
5
4
  import pytest
@@ -36,9 +35,6 @@ float_nan_df = pd.DataFrame.from_dict(
36
35
  )
37
36
 
38
37
 
39
- @pytest.mark.skipif(
40
- sys.version_info < (3, 8), reason="Feature not supported on Python 3.7 and earlier"
41
- )
42
38
  @pytest.mark.skipif(
43
39
  SA_VERSION < SA_2_0, reason="Feature not supported on SQLAlchemy 1.4 and earlier"
44
40
  )
@@ -47,7 +43,7 @@ def test_table_kwargs_partitioned_by(cratedb_service):
47
43
  Validate adding CrateDB dialect table option `PARTITIONED BY` at runtime.
48
44
  """
49
45
 
50
- engine = cratedb_service.database.engine
46
+ engine = cratedb_service.engine
51
47
 
52
48
  # Insert records from pandas dataframe.
53
49
  with table_kwargs(crate_partitioned_by="time"):
@@ -59,22 +55,19 @@ def test_table_kwargs_partitioned_by(cratedb_service):
59
55
  )
60
56
 
61
57
  # Synchronize writes.
62
- cratedb_service.database.refresh_table(TABLE_NAME)
58
+ cratedb_service.refresh_table(TABLE_NAME)
63
59
 
64
60
  # Inquire table cardinality.
65
- count = cratedb_service.database.count_records(TABLE_NAME)
61
+ count = cratedb_service.count_records(TABLE_NAME)
66
62
 
67
63
  # Compare outcome.
68
64
  assert count == INSERT_RECORDS
69
65
 
70
66
  # Validate SQL DDL.
71
- ddl = cratedb_service.database.run_sql(f"SHOW CREATE TABLE {TABLE_NAME}")
67
+ ddl = cratedb_service.run_sql(f"SHOW CREATE TABLE {TABLE_NAME}")
72
68
  assert 'PARTITIONED BY ("time")' in ddl[0][0]
73
69
 
74
70
 
75
- @pytest.mark.skipif(
76
- sys.version_info < (3, 8), reason="Feature not supported on Python 3.7 and earlier"
77
- )
78
71
  @pytest.mark.skipif(
79
72
  SA_VERSION < SA_2_0, reason="Feature not supported on SQLAlchemy 1.4 and earlier"
80
73
  )
@@ -83,7 +76,7 @@ def test_table_kwargs_translog_durability(cratedb_service):
83
76
  Validate adding CrateDB dialect table option `translog.durability` at runtime.
84
77
  """
85
78
 
86
- engine = cratedb_service.database.engine
79
+ engine = cratedb_service.engine
87
80
 
88
81
  # Insert records from pandas dataframe.
89
82
  with table_kwargs(**{'crate_"translog.durability"': "'async'"}):
@@ -95,22 +88,19 @@ def test_table_kwargs_translog_durability(cratedb_service):
95
88
  )
96
89
 
97
90
  # Synchronize writes.
98
- cratedb_service.database.refresh_table(TABLE_NAME)
91
+ cratedb_service.refresh_table(TABLE_NAME)
99
92
 
100
93
  # Inquire table cardinality.
101
- count = cratedb_service.database.count_records(TABLE_NAME)
94
+ count = cratedb_service.count_records(TABLE_NAME)
102
95
 
103
96
  # Compare outcome.
104
97
  assert count == INSERT_RECORDS
105
98
 
106
99
  # Validate SQL DDL.
107
- ddl = cratedb_service.database.run_sql(f"SHOW CREATE TABLE {TABLE_NAME}")
100
+ ddl = cratedb_service.run_sql(f"SHOW CREATE TABLE {TABLE_NAME}")
108
101
  assert """"translog.durability" = 'ASYNC'""" in ddl[0][0]
109
102
 
110
103
 
111
- @pytest.mark.skipif(
112
- sys.version_info < (3, 8), reason="Feature not supported on Python 3.7 and earlier"
113
- )
114
104
  @pytest.mark.skipif(
115
105
  SA_VERSION < SA_2_0, reason="Feature not supported on SQLAlchemy 1.4 and earlier"
116
106
  )
@@ -118,7 +108,7 @@ def test_table_kwargs_unknown(cratedb_service):
118
108
  """
119
109
  Validate behaviour when adding an unknown CrateDB dialect table option.
120
110
  """
121
- engine = cratedb_service.database.engine
111
+ engine = cratedb_service.engine
122
112
  with table_kwargs(crate_unknown_option="'bazqux'"):
123
113
  with pytest.raises(ProgrammingError) as ex:
124
114
  df.to_sql(
@@ -135,9 +125,6 @@ def test_table_kwargs_unknown(cratedb_service):
135
125
  )
136
126
 
137
127
 
138
- @pytest.mark.skipif(
139
- sys.version_info < (3, 8), reason="Feature not supported on Python 3.7 and earlier"
140
- )
141
128
  @pytest.mark.skipif(
142
129
  SA_VERSION < SA_2_0, reason="Feature not supported on SQLAlchemy 1.4 and earlier"
143
130
  )
@@ -148,21 +135,18 @@ def test_float_special_values(cratedb_service):
148
135
  CrateDB stores all of them as NULL, so they all read back as NaN in pandas.
149
136
  """
150
137
  tablename = "pandas_float_special"
151
- engine = cratedb_service.database.engine
138
+ engine = cratedb_service.engine
152
139
  float_nan_df.to_sql(
153
140
  tablename,
154
141
  engine,
155
142
  if_exists="replace",
156
143
  index=False,
157
144
  )
158
- cratedb_service.database.run_sql(f"REFRESH TABLE {tablename}")
145
+ cratedb_service.run_sql(f"REFRESH TABLE {tablename}")
159
146
  df_load = pd.read_sql_table(tablename, engine)
160
147
  assert df_load["col_1"].isna().all()
161
148
 
162
149
 
163
- @pytest.mark.skipif(
164
- sys.version_info < (3, 8), reason="Feature not supported on Python 3.7 and earlier"
165
- )
166
150
  @pytest.mark.skipif(
167
151
  SA_VERSION < SA_2_0, reason="Feature not supported on SQLAlchemy 1.4 and earlier"
168
152
  )
@@ -173,14 +157,14 @@ def test_float_double(cratedb_service):
173
157
  Motto: Do not lose precision when DOUBLE is required.
174
158
  """
175
159
  tablename = "pandas_double"
176
- engine = cratedb_service.database.engine
160
+ engine = cratedb_service.engine
177
161
  float_double_df.to_sql(
178
162
  tablename,
179
163
  engine,
180
164
  if_exists="replace",
181
165
  index=False,
182
166
  )
183
- cratedb_service.database.run_sql(f"REFRESH TABLE {tablename}")
167
+ cratedb_service.run_sql(f"REFRESH TABLE {tablename}")
184
168
  df_load = pd.read_sql_table(tablename, engine)
185
169
 
186
170
  before = float_double_df.sort_values(by="col_1", ignore_index=True)
@@ -31,7 +31,7 @@ def test_autoincrement_timestamp(cratedb_service):
31
31
  """
32
32
  patch_autoincrement_timestamp()
33
33
 
34
- engine = cratedb_service.database.engine
34
+ engine = cratedb_service.engine
35
35
  session = sessionmaker(bind=engine)()
36
36
  Base = declarative_base()
37
37
 
@@ -73,7 +73,7 @@ def test_check_uniqueness_factory(cratedb_service):
73
73
  https://github.com/crate/sqlalchemy-cratedb/issues/76
74
74
  """
75
75
 
76
- engine = cratedb_service.database.engine
76
+ engine = cratedb_service.engine
77
77
  session = sessionmaker(bind=engine)()
78
78
  Base = declarative_base()
79
79
 
@@ -113,7 +113,7 @@ def test_refresh_after_dml(cratedb_service, mode):
113
113
 
114
114
  https://github.com/crate/sqlalchemy-cratedb/issues/83
115
115
  """
116
- engine = cratedb_service.database.engine
116
+ engine = cratedb_service.engine
117
117
  session = sessionmaker(bind=engine)()
118
118
  Base = declarative_base()
119
119
 
@@ -0,0 +1,105 @@
1
+ # -*- coding: utf-8; -*-
2
+ #
3
+ # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
4
+ # license agreements. See the NOTICE file distributed with this work for
5
+ # additional information regarding copyright ownership. Crate licenses
6
+ # this file to you under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License. You may
8
+ # obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
+ # License for the specific language governing permissions and limitations
16
+ # under the License.
17
+ #
18
+ # However, if you have executed another commercial license agreement
19
+ # with Crate these terms will supersede the license and you may use the
20
+ # software solely pursuant to the terms of the relevant commercial agreement.
21
+
22
+ import pytest
23
+ import sqlalchemy as sa
24
+
25
+ CORE_TYPE_FACTORIES = {
26
+ "BigInteger": lambda: sa.BigInteger,
27
+ "Boolean": lambda: sa.Boolean,
28
+ "Date": lambda: sa.Date,
29
+ "DateTime": lambda: sa.DateTime,
30
+ "Double": lambda: sa.Double,
31
+ "Enum": lambda: sa.Enum("a", "b", name="enum_a_b"),
32
+ "Float": lambda: sa.Float,
33
+ "Integer": lambda: sa.Integer,
34
+ "Interval": lambda: sa.Interval,
35
+ "JSON": lambda: sa.JSON,
36
+ "LargeBinary": lambda: sa.LargeBinary,
37
+ "Numeric": lambda: sa.Numeric(10, 2),
38
+ "PickleType": lambda: sa.PickleType,
39
+ "SmallInteger": lambda: sa.SmallInteger,
40
+ "String": lambda: sa.String(50),
41
+ "Text": lambda: sa.Text,
42
+ "Time": lambda: sa.Time,
43
+ "Unicode": lambda: sa.Unicode(50),
44
+ "UnicodeText": lambda: sa.UnicodeText,
45
+ "Uuid": lambda: sa.Uuid,
46
+ "ARRAY": lambda: sa.ARRAY(sa.Integer),
47
+ "BIGINT": lambda: sa.BIGINT,
48
+ "BINARY": lambda: sa.BINARY,
49
+ "BLOB": lambda: sa.BLOB,
50
+ "BOOLEAN": lambda: sa.BOOLEAN,
51
+ "CHAR": lambda: sa.CHAR(5),
52
+ "CLOB": lambda: sa.CLOB,
53
+ "DATE": lambda: sa.DATE,
54
+ "DATETIME": lambda: sa.DATETIME,
55
+ "DECIMAL": lambda: sa.DECIMAL(10, 2),
56
+ "DOUBLE": lambda: sa.DOUBLE,
57
+ "DOUBLE_PRECISION": lambda: sa.DOUBLE_PRECISION,
58
+ "FLOAT": lambda: sa.FLOAT,
59
+ "INTEGER": lambda: sa.INTEGER,
60
+ "NCHAR": lambda: sa.NCHAR(5),
61
+ "NUMERIC": lambda: sa.NUMERIC(10, 2),
62
+ "NVARCHAR": lambda: sa.NVARCHAR(50),
63
+ "REAL": lambda: sa.REAL,
64
+ "SMALLINT": lambda: sa.SMALLINT,
65
+ "TEXT": lambda: sa.TEXT,
66
+ "TIME": lambda: sa.TIME,
67
+ "TIMESTAMP": lambda: sa.TIMESTAMP,
68
+ "UUID": lambda: sa.UUID,
69
+ "VARBINARY": lambda: sa.VARBINARY(50),
70
+ "VARCHAR": lambda: sa.VARCHAR(50),
71
+ }
72
+
73
+ CORE_TYPES = {name: factory() for name, factory in CORE_TYPE_FACTORIES.items() if hasattr(sa, name)}
74
+
75
+
76
+ KNOWN_UNSUPPORTED = {
77
+ "BINARY": "CrateDB has no binary data type",
78
+ "BLOB": "CrateDB has no binary data type",
79
+ "LargeBinary": "CrateDB has no binary data type",
80
+ "PickleType": "Builds on `sa.LargeBinary`",
81
+ "VARBINARY": "CrateDB has no binary data type",
82
+ }
83
+
84
+
85
+ def _cases():
86
+ for name in sorted(CORE_TYPES):
87
+ marks = []
88
+ if name in KNOWN_UNSUPPORTED:
89
+ marks.append(pytest.mark.xfail(strict=True, reason=KNOWN_UNSUPPORTED[name]))
90
+ yield pytest.param(name, marks=marks)
91
+
92
+
93
+ @pytest.mark.parametrize("name", list(_cases()))
94
+ def test_core_type_is_creatable(cratedb_service, name):
95
+ """CrateDB accepts the DDL the dialect generates for this type."""
96
+ engine = cratedb_service.engine
97
+ table = sa.Table(
98
+ "type_compilation",
99
+ sa.MetaData(),
100
+ sa.Column("id", sa.Integer, primary_key=True),
101
+ sa.Column("d", CORE_TYPES[name]),
102
+ )
103
+ table.drop(engine, checkfirst=True)
104
+ table.create(engine)
105
+ table.drop(engine)