sqlalchemy-singlestoredb 0.4.0__tar.gz → 1.1.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 (21) hide show
  1. {sqlalchemy_singlestoredb-0.4.0/sqlalchemy_singlestoredb.egg-info → sqlalchemy_singlestoredb-1.1.0}/PKG-INFO +4 -7
  2. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/README.md +1 -1
  3. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/setup.cfg +4 -7
  4. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb/__init__.py +11 -3
  5. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb/base.py +81 -36
  6. sqlalchemy_singlestoredb-1.1.0/sqlalchemy_singlestoredb/column.py +29 -0
  7. sqlalchemy_singlestoredb-1.1.0/sqlalchemy_singlestoredb/ddlelement.py +29 -0
  8. sqlalchemy_singlestoredb-1.1.0/sqlalchemy_singlestoredb/dtypes.py +79 -0
  9. sqlalchemy_singlestoredb-1.1.0/sqlalchemy_singlestoredb/reflection.py +295 -0
  10. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0/sqlalchemy_singlestoredb.egg-info}/PKG-INFO +4 -7
  11. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb.egg-info/SOURCES.txt +3 -0
  12. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb.egg-info/requires.txt +1 -1
  13. sqlalchemy_singlestoredb-0.4.0/sqlalchemy_singlestoredb/reflection.py +0 -104
  14. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/LICENSE +0 -0
  15. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/setup.py +0 -0
  16. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb/tests/__init__.py +0 -0
  17. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb/tests/test.sql +0 -0
  18. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb/tests/test_basics.py +0 -0
  19. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb.egg-info/dependency_links.txt +0 -0
  20. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb.egg-info/entry_points.txt +0 -0
  21. {sqlalchemy_singlestoredb-0.4.0 → sqlalchemy_singlestoredb-1.1.0}/sqlalchemy_singlestoredb.egg-info/top_level.txt +0 -0
@@ -1,25 +1,22 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlalchemy_singlestoredb
3
- Version: 0.4.0
3
+ Version: 1.1.0
4
4
  Summary: SQLAlchemy dialect for the SingleStoreDB database
5
5
  Home-page: https://github.com/singlestore-labs/sqlalchemy-singlestoredb
6
6
  Author: SingleStore
7
7
  Author-email: support@singlestore.com
8
8
  License: Apache-2.0
9
- Classifier: Development Status :: 4 - Beta
9
+ Classifier: Development Status :: 5 - Production/Stable
10
10
  Classifier: License :: OSI Approved :: Apache Software License
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3 :: Only
13
- Classifier: Programming Language :: Python :: 3.8
14
- Classifier: Programming Language :: Python :: 3.9
15
- Classifier: Programming Language :: Python :: 3.10
16
13
  Requires-Python: >=3.8
17
14
  Description-Content-Type: text/markdown
18
15
  License-File: LICENSE
19
- Requires-Dist: singlestoredb>=0.10.4
16
+ Requires-Dist: singlestoredb>=1.0.0
20
17
  Requires-Dist: sqlalchemy<3.0.0dev,>=1.4.0
21
18
 
22
- # <img src="resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
19
+ # <img src="https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
23
20
 
24
21
  This project contains a [SQLAlchemyDB](https://sqlalchemy.org) dialect which allows
25
22
  you to use the SQLAlchemy APIs with the [SingleStoreDB](https://singlestore.com) database.
@@ -1,4 +1,4 @@
1
- # <img src="resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
1
+ # <img src="https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
2
2
 
3
3
  This project contains a [SQLAlchemyDB](https://sqlalchemy.org) dialect which allows
4
4
  you to use the SQLAlchemy APIs with the [SingleStoreDB](https://singlestore.com) database.
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = sqlalchemy_singlestoredb
3
- version = 0.4.0
3
+ version = 1.1.0
4
4
  description = SQLAlchemy dialect for the SingleStoreDB database
5
5
  long_description = file: README.md
6
6
  long_description_content_type = text/markdown
@@ -8,20 +8,17 @@ url = https://github.com/singlestore-labs/sqlalchemy-singlestoredb
8
8
  author = SingleStore
9
9
  author_email = support@singlestore.com
10
10
  license = Apache-2.0
11
- license_file = LICENSE
11
+ license_files = LICENSE
12
12
  classifiers =
13
- Development Status :: 4 - Beta
13
+ Development Status :: 5 - Production/Stable
14
14
  License :: OSI Approved :: Apache Software License
15
15
  Programming Language :: Python :: 3
16
16
  Programming Language :: Python :: 3 :: Only
17
- Programming Language :: Python :: 3.8
18
- Programming Language :: Python :: 3.9
19
- Programming Language :: Python :: 3.10
20
17
 
21
18
  [options]
22
19
  packages = find:
23
20
  install_requires =
24
- singlestoredb>=0.10.4
21
+ singlestoredb>=1.0.0
25
22
  sqlalchemy>=1.4.0,<3.0.0dev
26
23
  python_requires = >=3.8
27
24
  tests_require =
@@ -39,15 +39,19 @@ from sqlalchemy.dialects.mysql.base import YEAR
39
39
  from sqlalchemy.dialects.mysql.dml import Insert
40
40
  from sqlalchemy.dialects.mysql.dml import insert
41
41
 
42
- from . import base # noqa
43
- from .base import JSON
42
+ from . import base
43
+ from .column import PersistedColumn
44
+ from .ddlelement import ShardKey
45
+ from .ddlelement import SortKey
46
+ from .dtypes import JSON
47
+ from .dtypes import VECTOR
44
48
 
45
49
  array = base.array
46
50
 
47
51
  # default dialect
48
52
  dialect = base.dialect
49
53
 
50
- __version__ = '0.4.0'
54
+ __version__ = '1.1.0'
51
55
 
52
56
  __all__ = (
53
57
  'BIGINT',
@@ -73,8 +77,11 @@ __all__ = (
73
77
  'NCHAR',
74
78
  'NVARCHAR',
75
79
  'NUMERIC',
80
+ 'PersistedColumn',
76
81
  'SET',
77
82
  'SMALLINT',
83
+ 'ShardKey',
84
+ 'SortKey',
78
85
  'REAL',
79
86
  'TEXT',
80
87
  'TIME',
@@ -84,6 +91,7 @@ __all__ = (
84
91
  'TINYTEXT',
85
92
  'VARBINARY',
86
93
  'VARCHAR',
94
+ 'VECTOR',
87
95
  'YEAR',
88
96
  'dialect',
89
97
  'insert',
@@ -2,18 +2,14 @@
2
2
  """Base classes for SingleStoreDB SQLAlchemy objects."""
3
3
  from __future__ import annotations
4
4
 
5
- import json
6
5
  from typing import Any
7
6
  from typing import Callable
8
7
  from typing import Dict
9
8
  from typing import List
10
9
  from typing import Optional
11
10
  from typing import Type
12
- from typing import Union
13
11
 
14
- import sqlalchemy.dialects.mysql.base as mybase
15
12
  import sqlalchemy.sql.elements as se
16
- from singlestoredb.connection import build_params
17
13
  from sqlalchemy import util
18
14
  from sqlalchemy.dialects.mysql.base import BIT # noqa: F401
19
15
  from sqlalchemy.dialects.mysql.base import CHAR # noqa: F401
@@ -30,8 +26,16 @@ from sqlalchemy.engine.url import URL
30
26
  from sqlalchemy.sql import sqltypes
31
27
  from sqlalchemy.sql.compiler import BIND_PARAMS
32
28
  from sqlalchemy.sql.compiler import BIND_PARAMS_ESC
29
+ try:
30
+ from sqlalchemy.sql.schema import SchemaConst
31
+ except ImportError:
32
+ from sqlalchemy.sql import schema as SchemaConst
33
33
 
34
34
  from . import reflection
35
+ from .column import PersistedColumn
36
+ from .dtypes import _json_deserializer
37
+ from .dtypes import JSON
38
+ from .dtypes import VECTOR
35
39
 
36
40
 
37
41
  class CaseInsensitiveDict(Dict[str, Any]):
@@ -65,39 +69,8 @@ class CaseInsensitiveDict(Dict[str, Any]):
65
69
 
66
70
 
67
71
  ischema_names = CaseInsensitiveDict(MySQLDialect.ischema_names)
68
-
69
-
70
- def _json_deserializer(value: Union[str, bytes, Dict[str, Any], List[Any]]) -> Any:
71
- if value is None:
72
- return None
73
- if type(value) is dict or type(value) is list:
74
- return value
75
- return json.loads(value) # type: ignore
76
-
77
-
78
- class JSON(mybase.JSON):
79
-
80
- def __init__(self, *args: Any, **kwargs: Any) -> None:
81
- kwargs.pop('collate', None)
82
- mybase.JSON(*args, **kwargs)
83
-
84
- def result_processor(self, dialect: Any, coltype: Any) -> Any:
85
- string_process = self._str_impl.result_processor(dialect, coltype)
86
- json_deserializer = dialect._json_deserializer or json.loads
87
-
88
- def process(value: Union[str, bytes, Dict[str, Any], List[Any]]) -> Any:
89
- if value is None:
90
- return None
91
- if string_process:
92
- value = string_process(value)
93
- if type(value) is dict or type(value) is list:
94
- return value
95
- return json_deserializer(value) # type: ignore
96
-
97
- return process
98
-
99
-
100
72
  ischema_names['json'] = JSON
73
+ ischema_names['vector'] = VECTOR
101
74
 
102
75
 
103
76
  class SingleStoreDBExecutionContext(MySQLExecutionContext):
@@ -146,6 +119,8 @@ class SingleStoreDBCompiler(MySQLCompiler):
146
119
  ):
147
120
  adapted = CHAR._adapt_string_for_cast(type_)
148
121
  return self.dialect.type_compiler.process(adapted)
122
+ elif isinstance(type_, VECTOR):
123
+ return 'VECTOR'
149
124
  elif isinstance(type_, sqltypes._Binary):
150
125
  return 'BINARY'
151
126
  elif isinstance(type_, sqltypes.JSON):
@@ -228,6 +203,72 @@ class SingleStoreDBCompiler(MySQLCompiler):
228
203
  class SingleStoreDBDDLCompiler(MySQLDDLCompiler):
229
204
  """SingleStoreDB SQLAlchemy DDL compiler."""
230
205
 
206
+ def visit_create_table(self, create: Any, **kw: Any) -> str:
207
+ create_table_sql = super().visit_create_table(create, **kw)
208
+ shard_key = create.element.info.get('singlestoredb_shard_key')
209
+ if shard_key is not None:
210
+ shard_columns = ', '.join(shard_key.columns)
211
+ shard_key_sql = f'SHARD KEY ({shard_columns})'
212
+ # Append the SHARD KEY definition to the original SQL
213
+ create_table_sql = f'{create_table_sql.rstrip()[:-2]},\n\t{shard_key_sql}\n)'
214
+
215
+ sort_key = create.element.info.get('singlestoredb_sort_key')
216
+ if sort_key is not None:
217
+ sort_columns = ', '.join(sort_key.columns)
218
+ sort_key_sql = f'SORT KEY ({sort_columns})'
219
+ # Append the SHARD KEY definition to the original SQL
220
+ create_table_sql = f'{create_table_sql.rstrip()[:-2]},\n\t{sort_key_sql}\n)'
221
+
222
+ return create_table_sql
223
+
224
+ def get_column_specification(self, column: Any, **kw: Any) -> str:
225
+ """Builds column DDL."""
226
+ if not isinstance(column, PersistedColumn):
227
+ return super().get_column_specification(column, **kw)
228
+
229
+ if (
230
+ self.dialect.is_mariadb is True
231
+ and column.computed is not None
232
+ and column._user_defined_nullable is SchemaConst.NULL_UNSPECIFIED
233
+ ):
234
+ column.nullable = True
235
+ colspec = [
236
+ self.preparer.format_column(column),
237
+ 'AS',
238
+ column.persisted_expression,
239
+ 'PERSISTED',
240
+ self.dialect.type_compiler_instance.process(
241
+ column.type, type_expression=column,
242
+ ),
243
+ ]
244
+
245
+ if column.computed is not None:
246
+ colspec.append(self.process(column.computed))
247
+
248
+ is_timestamp = isinstance(
249
+ column.type._unwrapped_dialect_impl(self.dialect),
250
+ sqltypes.TIMESTAMP,
251
+ )
252
+
253
+ if not column.nullable:
254
+ colspec.append('NOT NULL')
255
+
256
+ # see: https://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql_timestamp_null # noqa
257
+ elif column.nullable and is_timestamp:
258
+ colspec.append('NULL')
259
+
260
+ comment = column.comment
261
+ if comment is not None:
262
+ literal = self.sql_compiler.render_literal_value(
263
+ comment, sqltypes.String(),
264
+ )
265
+ colspec.append('COMMENT ' + literal)
266
+
267
+ default = self.get_column_default_string(column)
268
+ if default is not None:
269
+ colspec.append('DEFAULT ' + default)
270
+ return ' '.join(colspec)
271
+
231
272
 
232
273
  class SingleStoreDBTypeCompiler(MySQLTypeCompiler):
233
274
  """SingleStoreDB SQLAlchemy type compiler."""
@@ -242,6 +283,9 @@ class SingleStoreDBTypeCompiler(MySQLTypeCompiler):
242
283
  return 'TIMESTAMP(%d)' % type_.fsp
243
284
  return 'TIMESTAMP'
244
285
 
286
+ def visit_VECTOR(self, type_: Any, **kw: Any) -> str:
287
+ return 'VECTOR(%d, %s)' % (type_.n_elems, type_.elem_type)
288
+
245
289
 
246
290
  class SingleStoreDBIdentifierPreparer(MySQLIdentifierPreparer):
247
291
  """SingleStoreDB SQLAlchemy identifier preparer."""
@@ -331,6 +375,7 @@ class SingleStoreDBDialect(MySQLDialect):
331
375
  return MySQLDialect.initialize(self, connection)
332
376
 
333
377
  def create_connect_args(self, url: URL) -> List[Any]:
378
+ from singlestoredb.connection import build_params
334
379
  return [[], build_params(host=url.render_as_string(hide_password=False))]
335
380
 
336
381
  def _extract_error_code(self, exception: Exception) -> int:
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from sqlalchemy import Column
6
+ from sqlalchemy.ext.declarative import declarative_base
7
+ from sqlalchemy.sql.expression import TextClause
8
+
9
+ Base = declarative_base()
10
+
11
+
12
+ class PersistedColumn(Column):
13
+ def __init__(
14
+ self,
15
+ *args: Any,
16
+ persisted_expression: Any = None,
17
+ **kwargs: Any,
18
+ ) -> None:
19
+ if persisted_expression is not None:
20
+ # Ensure persisted_expression is either a TextClause or a string
21
+ if not isinstance(persisted_expression, (TextClause, str)):
22
+ raise ValueError(
23
+ 'Persisted expression must be a SQL expression '
24
+ 'as a string or TextClause',
25
+ )
26
+ self.is_persisted = True
27
+ self.persisted_expression = persisted_expression
28
+ kwargs['info'] = {'persisted_expression': persisted_expression}
29
+ super().__init__(*args, **kwargs)
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from sqlalchemy.ext.compiler import compiles
6
+ from sqlalchemy.ext.declarative import declarative_base
7
+ from sqlalchemy.schema import DDLElement
8
+
9
+ Base = declarative_base()
10
+
11
+
12
+ class ShardKey(DDLElement):
13
+ def __init__(self, *columns: Any) -> None:
14
+ self.columns = columns
15
+
16
+
17
+ @compiles(ShardKey, 'singlestoredb.mysql')
18
+ def compile_shard_key(element: Any, compiler: Any, **kw: Any) -> str:
19
+ return 'SHARD KEY (%s)' % ', '.join(element.columns)
20
+
21
+
22
+ class SortKey(DDLElement):
23
+ def __init__(self, *columns: Any) -> None:
24
+ self.columns = columns
25
+
26
+
27
+ @compiles(SortKey, 'singlestoredb.mysql')
28
+ def compile_sort_key(element: Any, compiler: Any, **kw: Any) -> str:
29
+ return 'SORT KEY (%s)' % ', '.join(element.columns)
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env python
2
+ """Base classes for SingleStoreDB SQLAlchemy objects."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+ from typing import Dict
8
+ from typing import List
9
+ from typing import Optional
10
+ from typing import Union
11
+
12
+ import sqlalchemy.dialects.mysql.base as mybase
13
+
14
+
15
+ def _json_deserializer(value: Union[str, bytes, Dict[str, Any], List[Any]]) -> Any:
16
+ if value is None:
17
+ return None
18
+ if type(value) is dict or type(value) is list:
19
+ return value
20
+ return json.loads(value) # type: ignore
21
+
22
+
23
+ class JSON(mybase.JSON):
24
+
25
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
26
+ kwargs.pop('collate', None)
27
+ mybase.JSON(*args, **kwargs)
28
+
29
+ def result_processor(self, dialect: Any, coltype: Any) -> Any:
30
+ string_process = self._str_impl.result_processor(dialect, coltype)
31
+ json_deserializer = dialect._json_deserializer or json.loads
32
+
33
+ def process(value: Union[str, bytes, Dict[str, Any], List[Any]]) -> Any:
34
+ if value is None:
35
+ return None
36
+ if string_process:
37
+ value = string_process(value)
38
+ if type(value) is dict or type(value) is list:
39
+ return value
40
+ return json_deserializer(value) # type: ignore
41
+
42
+ return process
43
+
44
+
45
+ class VECTOR(mybase.BLOB):
46
+
47
+ __visit_name__ = 'VECTOR'
48
+
49
+ F16 = FLOAT16 = 'F16'
50
+ F32 = FLOAT32 = 'F32'
51
+ F64 = FLOAT64 = 'F64'
52
+ I8 = INT8 = 'I8'
53
+ I16 = INT16 = 'I16'
54
+ I32 = INT32 = 'I32'
55
+ I64 = INT64 = 'I64'
56
+
57
+ def __init__(
58
+ self,
59
+ n_elems: Optional[int] = None,
60
+ elem_type: Optional[str] = None,
61
+ ) -> None:
62
+ self.n_elems = n_elems or 1
63
+ self.elem_type = elem_type or 'F32'
64
+ mybase.BLOB(self.n_elems * int(self.elem_type[1:]) / 8)
65
+
66
+ def result_processor(self, dialect: Any, coltype: Any) -> Any:
67
+ string_process = self._str_impl.result_processor(dialect, coltype)
68
+ json_deserializer = dialect._json_deserializer or json.loads
69
+
70
+ def process(value: Union[str, bytes, Dict[str, Any], List[Any]]) -> Any:
71
+ if value is None:
72
+ return None
73
+ if string_process:
74
+ value = string_process(value)
75
+ if type(value) is dict or type(value) is list:
76
+ return value
77
+ return json_deserializer(value) # type: ignore
78
+
79
+ return process
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env python
2
+ """SingleStoreDB SQLAlchemy reflection utilities."""
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+ from typing import Dict
8
+ from typing import List
9
+ from typing import Tuple
10
+
11
+ from sqlalchemy import log
12
+ from sqlalchemy import util
13
+ from sqlalchemy.dialects.mysql.reflection import MySQLTableDefinitionParser
14
+ from sqlalchemy.dialects.mysql.reflection import ReflectedState
15
+ from sqlalchemy.sql import sqltypes
16
+
17
+ from . import DATETIME
18
+ from . import ENUM
19
+ from . import SET
20
+ from . import TIME
21
+ from . import TIMESTAMP
22
+
23
+
24
+ _control_char_map = {
25
+ '\\\\': '\\',
26
+ '\\0': '\0',
27
+ '\\a': '\a',
28
+ '\\b': '\b',
29
+ '\\t': '\t',
30
+ '\\n': '\n',
31
+ '\\v': '\v',
32
+ '\\f': '\f',
33
+ '\\r': '\r',
34
+ # '\\e':'\e',
35
+ }
36
+ _control_char_regexp = re.compile(
37
+ '|'.join(re.escape(k) for k in _control_char_map),
38
+ )
39
+
40
+
41
+ def _re_compile(regex: str) -> Any:
42
+ """Compile a string to regex, I and UNICODE."""
43
+ return re.compile(regex, re.I | re.UNICODE)
44
+
45
+
46
+ def _strip_values(values: List[str]) -> List[str]:
47
+ """Strip reflected values quotes"""
48
+ strip_values = []
49
+ for a in values:
50
+ if a[0:1] == '"' or a[0:1] == "'":
51
+ # strip enclosing quotes and unquote interior
52
+ a = a[1:-1].replace(a[0] * 2, a[0])
53
+ strip_values.append(a)
54
+ return strip_values
55
+
56
+
57
+ def cleanup_text(raw_text: str) -> str:
58
+ if '\\' in raw_text:
59
+ raw_text = re.sub(
60
+ _control_char_regexp, lambda s: _control_char_map[s[0]], raw_text,
61
+ )
62
+ return raw_text.replace("''", "'")
63
+
64
+
65
+ @log.class_logger
66
+ class SingleStoreDBTableDefinitionParser(MySQLTableDefinitionParser):
67
+ """Parses the results of a SHOW CREATE TABLE statement."""
68
+
69
+ def _parse_constraints(self, line: str) -> Tuple[str, Dict[str, Any]]:
70
+ type_, spec = super(
71
+ SingleStoreDBTableDefinitionParser,
72
+ self,
73
+ )._parse_constraints(line)
74
+ re_shard = _re_compile(r'\s+,\s+SHARD\s+KEY\s+\(\)\s+')
75
+ m = re_shard.match(line)
76
+ if m:
77
+ type_ = 'shard_key'
78
+ spec = {
79
+ 'type': None, 'name': 'SHARD', 'using_pre': None,
80
+ 'columns': [], 'using_post': None, 'keyblock': None,
81
+ 'parser': None, 'comment': None, 'version_sql': None,
82
+ }
83
+ return type_, spec
84
+
85
+ def parse(self, show_create: str, charset: str) -> ReflectedState:
86
+ state = ReflectedState()
87
+ state.charset = charset
88
+ for line in re.split(r'\r?\n', show_create):
89
+ if line.startswith(' ' + self.preparer.initial_quote):
90
+ self._parse_column(line, state)
91
+ # a regular table options line
92
+ elif line.startswith(') '):
93
+ self._parse_table_options(line, state)
94
+ # an ANSI-mode table options line
95
+ elif line == ')':
96
+ pass
97
+ elif line.startswith('CREATE '):
98
+ self._parse_table_name(line, state)
99
+ # Not present in real reflection, but may be if
100
+ # loading from a file.
101
+ elif not line:
102
+ pass
103
+ else:
104
+ type_, spec = self._parse_constraints(line)
105
+ if type_ is None:
106
+ util.warn('Unknown schema content: %r' % line)
107
+ elif type_ == 'key':
108
+ state.keys.append(spec)
109
+ elif type_ == 'fk_constraint':
110
+ state.fk_constraints.append(spec)
111
+ elif type_ == 'ck_constraint':
112
+ state.ck_constraints.append(spec)
113
+ elif type_ == 'shard_key':
114
+ state.keys.append(spec)
115
+ else:
116
+ pass
117
+ return state
118
+
119
+ def _prep_regexes(self) -> None:
120
+ """Pre-compile regular expressions."""
121
+ super(SingleStoreDBTableDefinitionParser, self)._prep_regexes()
122
+
123
+ quotes = dict(
124
+ zip(
125
+ ('iq', 'fq', 'esc_fq'),
126
+ [
127
+ re.escape(s)
128
+ for s in (
129
+ self.preparer.initial_quote,
130
+ self.preparer.final_quote,
131
+ self.preparer._escape_identifier(self.preparer.final_quote),
132
+ )
133
+ ],
134
+ ),
135
+ )
136
+
137
+ # (PRIMARY|UNIQUE|FULLTEXT|SPATIAL) INDEX `name` (USING (BTREE|HASH))?
138
+ # (`col` (ASC|DESC)?, `col` (ASC|DESC)?)
139
+ # KEY_BLOCK_SIZE size | WITH PARSER name /*!50100 WITH PARSER name */
140
+ self._re_key = _re_compile(
141
+ r' '
142
+ r'(?:(?P<type>\S+) )?KEY'
143
+ r'(?: +%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s)?'
144
+ r'(?: +USING +(?P<using_pre>\S+))?'
145
+ r' +\((?P<columns>.*?)\)'
146
+ r'(?: +USING +(?P<using_post>\S+|CLUSTERED +COLUMNSTORE))?'
147
+ r'(?: +KEY_BLOCK_SIZE *[ =]? *(?P<keyblock>\S+))?'
148
+ r'(?: +WITH PARSER +(?P<parser>\S+))?'
149
+ r'(?: +COMMENT +(?P<comment>(\x27\x27|\x27([^\x27])*?\x27)+))?'
150
+ r'(?: +/\*(?P<version_sql>.+)\*/ *)?'
151
+ r',?$' % quotes,
152
+ )
153
+
154
+ # `colname` <type> [type opts]
155
+ # (NOT NULL | NULL)
156
+ # DEFAULT ('value' | CURRENT_TIMESTAMP...)
157
+ # COMMENT 'comment'
158
+ # COLUMN_FORMAT (FIXED|DYNAMIC|DEFAULT)
159
+ # STORAGE (DISK|MEMORY)
160
+ self._re_column = _re_compile(
161
+ r' '
162
+ r'%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s +'
163
+ r'(?P<coltype>\w+)'
164
+ r'(?:\((?P<arg>(?:\d+|\d+,\s*(?:F|I)?\d+|'
165
+ r"(?:'(?:''|[^'])*',?)+))\))?"
166
+ r'(?: +(?P<unsigned>UNSIGNED))?'
167
+ r'(?: +(?P<zerofill>ZEROFILL))?'
168
+ r'(?: +CHARACTER SET +(?P<charset>[\w_]+))?'
169
+ r'(?: +COLLATE +(?P<collate>[\w_]+))?'
170
+ r'(?: +(?P<notnull>(?:NOT )?NULL))?'
171
+ r'(?: +DEFAULT +(?P<default>'
172
+ r"(?:NULL|'(?:''|[^'])*'|[\-\w\.\(\)]+"
173
+ r'(?: +ON UPDATE [\-\w\.\(\)]+)?)'
174
+ r'))?'
175
+ r'(?: +(?:GENERATED ALWAYS)? ?AS +(?P<generated>\('
176
+ r'.*\))? ?(?P<persistence>VIRTUAL|STORED)?)?'
177
+ r'(?: +(?P<autoincr>AUTO_INCREMENT))?'
178
+ r"(?: +COMMENT +'(?P<comment>(?:''|[^'])*)')?"
179
+ r'(?: +COLUMN_FORMAT +(?P<colfmt>\w+))?'
180
+ r'(?: +STORAGE +(?P<storage>\w+))?'
181
+ r'(?: +(?P<extra>.*))?'
182
+ r',?$' % quotes,
183
+ )
184
+
185
+ def _parse_column(self, line: str, state: Any) -> None: # noqa: C901
186
+ """
187
+ Extract column details.
188
+
189
+ Falls back to a 'minimal support' variant if full parse fails.
190
+
191
+ Paraemeters
192
+ -----------
193
+ line :
194
+ Any column-bearing line from SHOW CREATE TABLE
195
+
196
+ """
197
+ spec = None
198
+ m = self._re_column.match(line)
199
+ if m:
200
+ spec = m.groupdict()
201
+ spec['full'] = True
202
+ else:
203
+ m = self._re_column_loose.match(line)
204
+ if m:
205
+ spec = m.groupdict()
206
+ spec['full'] = False
207
+ if not spec:
208
+ util.warn('Unknown column definition %r' % line)
209
+ return
210
+ if not spec['full']:
211
+ util.warn('Incomplete reflection of column definition %r' % line)
212
+
213
+ name, type_, args = spec['name'], spec['coltype'], spec['arg']
214
+
215
+ try:
216
+ col_type = self.dialect.ischema_names[type_]
217
+ except KeyError:
218
+ util.warn(
219
+ "Did not recognize type '%s' of column '%s'" % (type_, name),
220
+ )
221
+ col_type = sqltypes.NullType
222
+
223
+ # Column type positional arguments eg. varchar(32)
224
+ if args is None or args == '':
225
+ type_args = []
226
+ elif args[0] == "'" and args[-1] == "'":
227
+ type_args = self._re_csv_str.findall(args)
228
+ else:
229
+ type_args = []
230
+ for v in re.split(r'\s*,\s*', args):
231
+ try:
232
+ type_args.append(int(v))
233
+ except ValueError:
234
+ type_args.append(v)
235
+
236
+ # Column type keyword options
237
+ type_kw = {}
238
+
239
+ if issubclass(col_type, (DATETIME, TIME, TIMESTAMP)):
240
+ if type_args:
241
+ type_kw['fsp'] = type_args.pop(0)
242
+
243
+ for kw in ('unsigned', 'zerofill'):
244
+ if spec.get(kw, False):
245
+ type_kw[kw] = True
246
+ for kw in ('charset', 'collate'):
247
+ if spec.get(kw, False):
248
+ type_kw[kw] = spec[kw]
249
+ if issubclass(col_type, (ENUM, SET)):
250
+ type_args = _strip_values(type_args)
251
+
252
+ if issubclass(col_type, SET) and '' in type_args:
253
+ type_kw['retrieve_as_bitwise'] = True
254
+
255
+ type_instance = col_type(*type_args, **type_kw)
256
+
257
+ col_kw: Dict[str, Any] = {}
258
+
259
+ # NOT NULL
260
+ col_kw['nullable'] = True
261
+ # this can be "NULL" in the case of TIMESTAMP
262
+ if spec.get('notnull', False) == 'NOT NULL':
263
+ col_kw['nullable'] = False
264
+
265
+ # AUTO_INCREMENT
266
+ if spec.get('autoincr', False):
267
+ col_kw['autoincrement'] = True
268
+ elif issubclass(col_type, sqltypes.Integer):
269
+ col_kw['autoincrement'] = False
270
+
271
+ # DEFAULT
272
+ default = spec.get('default', None)
273
+
274
+ if default == 'NULL':
275
+ # eliminates the need to deal with this later.
276
+ default = None
277
+
278
+ comment = spec.get('comment', None)
279
+
280
+ if comment is not None:
281
+ comment = cleanup_text(comment)
282
+
283
+ sqltext = spec.get('generated')
284
+ if sqltext is not None:
285
+ computed = dict(sqltext=sqltext)
286
+ persisted = spec.get('persistence')
287
+ if persisted is not None:
288
+ computed['persisted'] = persisted == 'STORED'
289
+ col_kw['computed'] = computed
290
+
291
+ col_d = dict(
292
+ name=name, type=type_instance, default=default, comment=comment,
293
+ )
294
+ col_d.update(col_kw)
295
+ state.columns.append(col_d)
@@ -1,25 +1,22 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: sqlalchemy_singlestoredb
3
- Version: 0.4.0
3
+ Version: 1.1.0
4
4
  Summary: SQLAlchemy dialect for the SingleStoreDB database
5
5
  Home-page: https://github.com/singlestore-labs/sqlalchemy-singlestoredb
6
6
  Author: SingleStore
7
7
  Author-email: support@singlestore.com
8
8
  License: Apache-2.0
9
- Classifier: Development Status :: 4 - Beta
9
+ Classifier: Development Status :: 5 - Production/Stable
10
10
  Classifier: License :: OSI Approved :: Apache Software License
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3 :: Only
13
- Classifier: Programming Language :: Python :: 3.8
14
- Classifier: Programming Language :: Python :: 3.9
15
- Classifier: Programming Language :: Python :: 3.10
16
13
  Requires-Python: >=3.8
17
14
  Description-Content-Type: text/markdown
18
15
  License-File: LICENSE
19
- Requires-Dist: singlestoredb>=0.10.4
16
+ Requires-Dist: singlestoredb>=1.0.0
20
17
  Requires-Dist: sqlalchemy<3.0.0dev,>=1.4.0
21
18
 
22
- # <img src="resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
19
+ # <img src="https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
23
20
 
24
21
  This project contains a [SQLAlchemyDB](https://sqlalchemy.org) dialect which allows
25
22
  you to use the SQLAlchemy APIs with the [SingleStoreDB](https://singlestore.com) database.
@@ -4,6 +4,9 @@ setup.cfg
4
4
  setup.py
5
5
  sqlalchemy_singlestoredb/__init__.py
6
6
  sqlalchemy_singlestoredb/base.py
7
+ sqlalchemy_singlestoredb/column.py
8
+ sqlalchemy_singlestoredb/ddlelement.py
9
+ sqlalchemy_singlestoredb/dtypes.py
7
10
  sqlalchemy_singlestoredb/reflection.py
8
11
  sqlalchemy_singlestoredb.egg-info/PKG-INFO
9
12
  sqlalchemy_singlestoredb.egg-info/SOURCES.txt
@@ -1,2 +1,2 @@
1
- singlestoredb>=0.10.4
1
+ singlestoredb>=1.0.0
2
2
  sqlalchemy<3.0.0dev,>=1.4.0
@@ -1,104 +0,0 @@
1
- #!/usr/bin/env python
2
- """SingleStoreDB SQLAlchemy reflection utilities."""
3
- from __future__ import annotations
4
-
5
- import re
6
- from typing import Any
7
- from typing import Dict
8
- from typing import Tuple
9
-
10
- from sqlalchemy import log
11
- from sqlalchemy import util
12
- from sqlalchemy.dialects.mysql.reflection import _re_compile
13
- from sqlalchemy.dialects.mysql.reflection import MySQLTableDefinitionParser
14
- from sqlalchemy.dialects.mysql.reflection import ReflectedState
15
-
16
-
17
- @log.class_logger
18
- class SingleStoreDBTableDefinitionParser(MySQLTableDefinitionParser):
19
- """Parses the results of a SHOW CREATE TABLE statement."""
20
-
21
- def _parse_constraints(self, line: str) -> Tuple[str, Dict[str, Any]]:
22
- type_, spec = super(
23
- SingleStoreDBTableDefinitionParser,
24
- self,
25
- )._parse_constraints(line)
26
- re_shard = _re_compile(r'\s+,\s+SHARD\s+KEY\s+\(\)\s+')
27
- m = re_shard.match(line)
28
- if m:
29
- type_ = 'shard_key'
30
- spec = {
31
- 'type': None, 'name': 'SHARD', 'using_pre': None,
32
- 'columns': [], 'using_post': None, 'keyblock': None,
33
- 'parser': None, 'comment': None, 'version_sql': None,
34
- }
35
- return type_, spec
36
-
37
- def parse(self, show_create: str, charset: str) -> ReflectedState:
38
- state = ReflectedState()
39
- state.charset = charset
40
- for line in re.split(r'\r?\n', show_create):
41
- if line.startswith(' ' + self.preparer.initial_quote):
42
- self._parse_column(line, state)
43
- # a regular table options line
44
- elif line.startswith(') '):
45
- self._parse_table_options(line, state)
46
- # an ANSI-mode table options line
47
- elif line == ')':
48
- pass
49
- elif line.startswith('CREATE '):
50
- self._parse_table_name(line, state)
51
- # Not present in real reflection, but may be if
52
- # loading from a file.
53
- elif not line:
54
- pass
55
- else:
56
- type_, spec = self._parse_constraints(line)
57
- if type_ is None:
58
- util.warn('Unknown schema content: %r' % line)
59
- elif type_ == 'key':
60
- state.keys.append(spec)
61
- elif type_ == 'fk_constraint':
62
- state.fk_constraints.append(spec)
63
- elif type_ == 'ck_constraint':
64
- state.ck_constraints.append(spec)
65
- elif type_ == 'shard_key':
66
- state.keys.append(spec)
67
- else:
68
- pass
69
- return state
70
-
71
- def _prep_regexes(self) -> None:
72
- """Pre-compile regular expressions."""
73
- super(SingleStoreDBTableDefinitionParser, self)._prep_regexes()
74
-
75
- quotes = dict(
76
- zip(
77
- ('iq', 'fq', 'esc_fq'),
78
- [
79
- re.escape(s)
80
- for s in (
81
- self.preparer.initial_quote,
82
- self.preparer.final_quote,
83
- self.preparer._escape_identifier(self.preparer.final_quote),
84
- )
85
- ],
86
- ),
87
- )
88
-
89
- # (PRIMARY|UNIQUE|FULLTEXT|SPATIAL) INDEX `name` (USING (BTREE|HASH))?
90
- # (`col` (ASC|DESC)?, `col` (ASC|DESC)?)
91
- # KEY_BLOCK_SIZE size | WITH PARSER name /*!50100 WITH PARSER name */
92
- self._re_key = _re_compile(
93
- r' '
94
- r'(?:(?P<type>\S+) )?KEY'
95
- r'(?: +%(iq)s(?P<name>(?:%(esc_fq)s|[^%(fq)s])+)%(fq)s)?'
96
- r'(?: +USING +(?P<using_pre>\S+))?'
97
- r' +\((?P<columns>.*?)\)'
98
- r'(?: +USING +(?P<using_post>\S+|CLUSTERED +COLUMNSTORE))?'
99
- r'(?: +KEY_BLOCK_SIZE *[ =]? *(?P<keyblock>\S+))?'
100
- r'(?: +WITH PARSER +(?P<parser>\S+))?'
101
- r'(?: +COMMENT +(?P<comment>(\x27\x27|\x27([^\x27])*?\x27)+))?'
102
- r'(?: +/\*(?P<version_sql>.+)\*/ *)?'
103
- r',?$' % quotes,
104
- )