sqlalchemy-singlestoredb 1.2.0__tar.gz → 1.2.2__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_singlestoredb-1.2.2/PKG-INFO +192 -0
  2. sqlalchemy_singlestoredb-1.2.2/README.md +169 -0
  3. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/pyproject.toml +4 -3
  4. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/__init__.py +1 -1
  5. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/base.py +1 -1
  6. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/column.py +126 -0
  7. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/ddlelement.py +516 -61
  8. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/dtypes.py +306 -0
  9. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/conftest.py +7 -5
  10. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_basics.py +8 -4
  11. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/tests/test_connect_retry.py +103 -0
  12. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/tests/test_json_type.py +238 -0
  13. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/tests/test_persisted_column.py +282 -0
  14. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_shard_key.py +91 -0
  15. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/tests/test_vector_type.py +393 -0
  16. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb/tests/utils.py +58 -0
  17. sqlalchemy_singlestoredb-1.2.2/sqlalchemy_singlestoredb.egg-info/PKG-INFO +192 -0
  18. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb.egg-info/SOURCES.txt +6 -1
  19. sqlalchemy_singlestoredb-1.2.0/PKG-INFO +0 -44
  20. sqlalchemy_singlestoredb-1.2.0/README.md +0 -21
  21. sqlalchemy_singlestoredb-1.2.0/sqlalchemy_singlestoredb/column.py +0 -26
  22. sqlalchemy_singlestoredb-1.2.0/sqlalchemy_singlestoredb/dtypes.py +0 -110
  23. sqlalchemy_singlestoredb-1.2.0/sqlalchemy_singlestoredb.egg-info/PKG-INFO +0 -44
  24. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/LICENSE +0 -0
  25. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/setup.cfg +0 -0
  26. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/compat.py +0 -0
  27. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/examples/shard_key_examples.py +0 -0
  28. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/examples/table_constructor_examples.py +0 -0
  29. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/examples/universal/main.py +0 -0
  30. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/reflection.py +0 -0
  31. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/__init__.py +0 -0
  32. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/run_all_tests.py +0 -0
  33. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test.sql +0 -0
  34. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_advanced_indexes.py +0 -0
  35. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_column_group.py +0 -0
  36. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_database_fixtures.py +0 -0
  37. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_declarative_reflection.py +0 -0
  38. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_error_handling.py +0 -0
  39. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_error_handling_pytest.py +0 -0
  40. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_integration_features.py +0 -0
  41. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_key_reflection.py +0 -0
  42. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_priority1_features.py +0 -0
  43. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_sort_key.py +0 -0
  44. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_table_options.py +0 -0
  45. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_table_types.py +0 -0
  46. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb/tests/test_vector_key.py +0 -0
  47. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb.egg-info/dependency_links.txt +0 -0
  48. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb.egg-info/entry_points.txt +0 -0
  49. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb.egg-info/requires.txt +0 -0
  50. {sqlalchemy_singlestoredb-1.2.0 → sqlalchemy_singlestoredb-1.2.2}/sqlalchemy_singlestoredb.egg-info/top_level.txt +0 -0
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlalchemy_singlestoredb
3
+ Version: 1.2.2
4
+ Summary: SQLAlchemy dialect for the SingleStoreDB database
5
+ Author-email: SingleStore <support@singlestore.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/singlestore-labs/sqlalchemy-singlestoredb
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: singlestoredb>=1.0.0
15
+ Requires-Dist: sqlalchemy<3.0.0dev,>=1.4.0
16
+ Provides-Extra: dev
17
+ Requires-Dist: coverage; extra == "dev"
18
+ Requires-Dist: docker; extra == "dev"
19
+ Requires-Dist: pytest; extra == "dev"
20
+ Requires-Dist: pytest-cov; extra == "dev"
21
+ Requires-Dist: tomli; python_version < "3.11" and extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # <img src="https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
25
+
26
+ This project contains a [SQLAlchemy](https://sqlalchemy.org) dialect which allows
27
+ you to use the SQLAlchemy APIs with the [SingleStoreDB](https://singlestore.com) database.
28
+
29
+ ## Features
30
+
31
+ - **SingleStore-specific data types**: VECTOR for AI/ML embeddings, JSON for semi-structured data
32
+ - **Computed columns**: PersistedColumn for server-side computed values
33
+ - **Data distribution**: ShardKey for optimal data partitioning across nodes
34
+ - **Query optimization**: SortKey for improved query performance
35
+ - **Vector similarity search**: VectorKey for AI/ML similarity operations
36
+ - **Full-text search**: FullTextIndex for text search capabilities
37
+ - **JSON array indexing**: MultiValueIndex for efficient JSON array queries
38
+ - **Table types**: ColumnStore (analytical) and RowStore (transactional) with reference table support
39
+ - **Wide table optimization**: ColumnGroup for tables with many columns
40
+
41
+ ## Install
42
+
43
+ This package can be installed from PyPI using `pip`:
44
+ ```bash
45
+ pip install sqlalchemy-singlestoredb
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ### Connecting to SingleStoreDB
51
+
52
+ ```python
53
+ from sqlalchemy import create_engine, text
54
+
55
+ # Basic connection
56
+ engine = create_engine('singlestoredb://user:password@host:3306/database')
57
+
58
+ # Test the connection
59
+ with engine.connect() as conn:
60
+ result = conn.execute(text('SELECT 1'))
61
+ print(result.fetchone())
62
+ ```
63
+
64
+ ### Creating Tables (Core API)
65
+
66
+ ```python
67
+ from sqlalchemy import Column, DateTime, Integer, MetaData, String, Table
68
+ from sqlalchemy_singlestoredb import ShardKey, SortKey, VECTOR, JSON
69
+
70
+ metadata = MetaData()
71
+
72
+ users = Table(
73
+ 'users', metadata,
74
+ Column('id', Integer, primary_key=True),
75
+ Column('name', String(100)),
76
+ Column('email', String(255)),
77
+ Column('created_at', DateTime),
78
+ singlestoredb_shard_key=ShardKey('id'),
79
+ singlestoredb_sort_key=SortKey('created_at'),
80
+ )
81
+
82
+ metadata.create_all(engine)
83
+ ```
84
+
85
+ ### Creating Tables (ORM)
86
+
87
+ ```python
88
+ from sqlalchemy import Column, DateTime, Integer, String
89
+ from sqlalchemy.orm import declarative_base
90
+ from sqlalchemy_singlestoredb import ShardKey, SortKey
91
+
92
+ Base = declarative_base()
93
+
94
+ class User(Base):
95
+ __tablename__ = 'users'
96
+
97
+ id = Column(Integer, primary_key=True)
98
+ name = Column(String(100))
99
+ email = Column(String(255))
100
+ created_at = Column(DateTime)
101
+
102
+ __table_args__ = {
103
+ 'singlestoredb_shard_key': ShardKey('id'),
104
+ 'singlestoredb_sort_key': SortKey('created_at'),
105
+ }
106
+
107
+ Base.metadata.create_all(engine)
108
+ ```
109
+
110
+ ## Key SingleStore Features
111
+
112
+ ### Vector Search for AI/ML
113
+
114
+ SingleStoreDB supports vector similarity search for AI/ML applications:
115
+
116
+ ```python
117
+ from sqlalchemy import Column, Integer, String, func, select
118
+ from sqlalchemy.orm import declarative_base, Session
119
+ from sqlalchemy_singlestoredb import VECTOR, VectorKey, ColumnStore
120
+
121
+ Base = declarative_base()
122
+
123
+ class Document(Base):
124
+ __tablename__ = 'documents'
125
+
126
+ id = Column(Integer, primary_key=True)
127
+ title = Column(String(200))
128
+ embedding = Column(VECTOR(1536))
129
+
130
+ __table_args__ = {
131
+ 'singlestoredb_table_type': ColumnStore(),
132
+ 'singlestoredb_vector_key': [
133
+ VectorKey('embedding', index_options={'metric_type': 'COSINE_SIMILARITY'}),
134
+ ],
135
+ }
136
+
137
+ # Find similar documents
138
+ query_embedding = [0.1, 0.2, ...] # Your embedding vector
139
+ with Session(engine) as session:
140
+ stmt = (
141
+ select(Document)
142
+ .order_by(func.dot_product(Document.embedding, query_embedding).desc())
143
+ .limit(10)
144
+ )
145
+ similar_docs = session.execute(stmt).scalars().all()
146
+ ```
147
+
148
+ ### Data Distribution with Shard Keys
149
+
150
+ Shard keys control how data is distributed across nodes:
151
+
152
+ ```python
153
+ from sqlalchemy_singlestoredb import ShardKey
154
+
155
+ __table_args__ = {
156
+ # Single column shard key
157
+ 'singlestoredb_shard_key': ShardKey('user_id'),
158
+
159
+ # Multi-column shard key
160
+ 'singlestoredb_shard_key': ShardKey('user_id', 'region_id'),
161
+
162
+ # Empty shard key for random distribution
163
+ 'singlestoredb_shard_key': ShardKey(),
164
+ }
165
+ ```
166
+
167
+ ### Table Types
168
+
169
+ Choose the right table type for your workload:
170
+
171
+ ```python
172
+ from sqlalchemy_singlestoredb import ColumnStore, RowStore
173
+
174
+ # ColumnStore (default) - Best for analytical workloads
175
+ __table_args__ = {'singlestoredb_table_type': ColumnStore()}
176
+
177
+ # RowStore - Best for transactional workloads
178
+ __table_args__ = {'singlestoredb_table_type': RowStore()}
179
+
180
+ # Reference table - Replicated to all nodes for fast joins
181
+ __table_args__ = {'singlestoredb_table_type': RowStore(reference=True)}
182
+ ```
183
+
184
+ ## License
185
+
186
+ This library is licensed under the [Apache 2.0 License](https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/LICENSE?token=GHSAT0AAAAAABMGV6QPNR6N23BVICDYK5LAYTVK5EA).
187
+
188
+ ## Resources
189
+
190
+ * [Documentation](https://sqlalchemy-singlestoredb.labs.singlestore.com)
191
+ * [SingleStore](https://www.singlestore.com)
192
+ * [SQLAlchemy](https://sqlalchemy.org)
@@ -0,0 +1,169 @@
1
+ # <img src="https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/resources/singlestore-logo.png" height="60" valign="middle"/> SingleStoreDB SQLAlchemy Dialect
2
+
3
+ This project contains a [SQLAlchemy](https://sqlalchemy.org) dialect which allows
4
+ you to use the SQLAlchemy APIs with the [SingleStoreDB](https://singlestore.com) database.
5
+
6
+ ## Features
7
+
8
+ - **SingleStore-specific data types**: VECTOR for AI/ML embeddings, JSON for semi-structured data
9
+ - **Computed columns**: PersistedColumn for server-side computed values
10
+ - **Data distribution**: ShardKey for optimal data partitioning across nodes
11
+ - **Query optimization**: SortKey for improved query performance
12
+ - **Vector similarity search**: VectorKey for AI/ML similarity operations
13
+ - **Full-text search**: FullTextIndex for text search capabilities
14
+ - **JSON array indexing**: MultiValueIndex for efficient JSON array queries
15
+ - **Table types**: ColumnStore (analytical) and RowStore (transactional) with reference table support
16
+ - **Wide table optimization**: ColumnGroup for tables with many columns
17
+
18
+ ## Install
19
+
20
+ This package can be installed from PyPI using `pip`:
21
+ ```bash
22
+ pip install sqlalchemy-singlestoredb
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ### Connecting to SingleStoreDB
28
+
29
+ ```python
30
+ from sqlalchemy import create_engine, text
31
+
32
+ # Basic connection
33
+ engine = create_engine('singlestoredb://user:password@host:3306/database')
34
+
35
+ # Test the connection
36
+ with engine.connect() as conn:
37
+ result = conn.execute(text('SELECT 1'))
38
+ print(result.fetchone())
39
+ ```
40
+
41
+ ### Creating Tables (Core API)
42
+
43
+ ```python
44
+ from sqlalchemy import Column, DateTime, Integer, MetaData, String, Table
45
+ from sqlalchemy_singlestoredb import ShardKey, SortKey, VECTOR, JSON
46
+
47
+ metadata = MetaData()
48
+
49
+ users = Table(
50
+ 'users', metadata,
51
+ Column('id', Integer, primary_key=True),
52
+ Column('name', String(100)),
53
+ Column('email', String(255)),
54
+ Column('created_at', DateTime),
55
+ singlestoredb_shard_key=ShardKey('id'),
56
+ singlestoredb_sort_key=SortKey('created_at'),
57
+ )
58
+
59
+ metadata.create_all(engine)
60
+ ```
61
+
62
+ ### Creating Tables (ORM)
63
+
64
+ ```python
65
+ from sqlalchemy import Column, DateTime, Integer, String
66
+ from sqlalchemy.orm import declarative_base
67
+ from sqlalchemy_singlestoredb import ShardKey, SortKey
68
+
69
+ Base = declarative_base()
70
+
71
+ class User(Base):
72
+ __tablename__ = 'users'
73
+
74
+ id = Column(Integer, primary_key=True)
75
+ name = Column(String(100))
76
+ email = Column(String(255))
77
+ created_at = Column(DateTime)
78
+
79
+ __table_args__ = {
80
+ 'singlestoredb_shard_key': ShardKey('id'),
81
+ 'singlestoredb_sort_key': SortKey('created_at'),
82
+ }
83
+
84
+ Base.metadata.create_all(engine)
85
+ ```
86
+
87
+ ## Key SingleStore Features
88
+
89
+ ### Vector Search for AI/ML
90
+
91
+ SingleStoreDB supports vector similarity search for AI/ML applications:
92
+
93
+ ```python
94
+ from sqlalchemy import Column, Integer, String, func, select
95
+ from sqlalchemy.orm import declarative_base, Session
96
+ from sqlalchemy_singlestoredb import VECTOR, VectorKey, ColumnStore
97
+
98
+ Base = declarative_base()
99
+
100
+ class Document(Base):
101
+ __tablename__ = 'documents'
102
+
103
+ id = Column(Integer, primary_key=True)
104
+ title = Column(String(200))
105
+ embedding = Column(VECTOR(1536))
106
+
107
+ __table_args__ = {
108
+ 'singlestoredb_table_type': ColumnStore(),
109
+ 'singlestoredb_vector_key': [
110
+ VectorKey('embedding', index_options={'metric_type': 'COSINE_SIMILARITY'}),
111
+ ],
112
+ }
113
+
114
+ # Find similar documents
115
+ query_embedding = [0.1, 0.2, ...] # Your embedding vector
116
+ with Session(engine) as session:
117
+ stmt = (
118
+ select(Document)
119
+ .order_by(func.dot_product(Document.embedding, query_embedding).desc())
120
+ .limit(10)
121
+ )
122
+ similar_docs = session.execute(stmt).scalars().all()
123
+ ```
124
+
125
+ ### Data Distribution with Shard Keys
126
+
127
+ Shard keys control how data is distributed across nodes:
128
+
129
+ ```python
130
+ from sqlalchemy_singlestoredb import ShardKey
131
+
132
+ __table_args__ = {
133
+ # Single column shard key
134
+ 'singlestoredb_shard_key': ShardKey('user_id'),
135
+
136
+ # Multi-column shard key
137
+ 'singlestoredb_shard_key': ShardKey('user_id', 'region_id'),
138
+
139
+ # Empty shard key for random distribution
140
+ 'singlestoredb_shard_key': ShardKey(),
141
+ }
142
+ ```
143
+
144
+ ### Table Types
145
+
146
+ Choose the right table type for your workload:
147
+
148
+ ```python
149
+ from sqlalchemy_singlestoredb import ColumnStore, RowStore
150
+
151
+ # ColumnStore (default) - Best for analytical workloads
152
+ __table_args__ = {'singlestoredb_table_type': ColumnStore()}
153
+
154
+ # RowStore - Best for transactional workloads
155
+ __table_args__ = {'singlestoredb_table_type': RowStore()}
156
+
157
+ # Reference table - Replicated to all nodes for fast joins
158
+ __table_args__ = {'singlestoredb_table_type': RowStore(reference=True)}
159
+ ```
160
+
161
+ ## License
162
+
163
+ This library is licensed under the [Apache 2.0 License](https://raw.githubusercontent.com/singlestore-labs/singlestoredb-python/main/LICENSE?token=GHSAT0AAAAAABMGV6QPNR6N23BVICDYK5LAYTVK5EA).
164
+
165
+ ## Resources
166
+
167
+ * [Documentation](https://sqlalchemy-singlestoredb.labs.singlestore.com)
168
+ * [SingleStore](https://www.singlestore.com)
169
+ * [SQLAlchemy](https://sqlalchemy.org)
@@ -1,14 +1,15 @@
1
1
  [build-system]
2
- requires = ['setuptools>=61.0', 'wheel']
2
+ requires = ['setuptools>=77']
3
3
  build-backend = 'setuptools.build_meta'
4
4
 
5
5
  [project]
6
6
  name = 'sqlalchemy_singlestoredb'
7
- version = '1.2.0'
7
+ version = '1.2.2'
8
8
  description = 'SQLAlchemy dialect for the SingleStoreDB database'
9
9
  readme = 'README.md'
10
10
  requires-python = '>=3.9'
11
- license = {text = 'Apache-2.0'}
11
+ license = 'Apache-2.0'
12
+ license-files = ['LICENSE']
12
13
  authors = [
13
14
  {name = 'SingleStore', email = 'support@singlestore.com'},
14
15
  ]
@@ -57,7 +57,7 @@ array = base.array
57
57
  # default dialect
58
58
  dialect = base.dialect
59
59
 
60
- __version__ = '1.2.0'
60
+ __version__ = '1.2.2'
61
61
 
62
62
  __all__ = (
63
63
  'BIGINT',
@@ -457,7 +457,7 @@ class SingleStoreDBDDLCompiler(MySQLDDLCompiler):
457
457
  'AS',
458
458
  column.persisted_expression,
459
459
  'PERSISTED',
460
- self.dialect.type_compiler_instance.process(
460
+ self.dialect.type_compiler.process(
461
461
  column.type, type_expression=column,
462
462
  ),
463
463
  ]
@@ -0,0 +1,126 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from sqlalchemy import Column
6
+ from sqlalchemy.sql.expression import TextClause
7
+
8
+
9
+ class PersistedColumn(Column):
10
+ """SingleStore computed column that is automatically calculated and stored.
11
+
12
+ PersistedColumn defines computed columns based on an expression. The computed
13
+ value is persisted to disk and updated when dependent columns change.
14
+
15
+ Parameters
16
+ ----------
17
+ name : str
18
+ Column name
19
+ type_ : TypeEngine
20
+ SQLAlchemy type for the computed value
21
+ persisted_expression : str or TextClause
22
+ SQL expression to compute the column value
23
+ *args, **kwargs
24
+ Additional arguments passed to Column
25
+
26
+ Examples
27
+ --------
28
+ Basic computed column:
29
+
30
+ >>> PersistedColumn('total', Integer, persisted_expression='price * quantity')
31
+
32
+ Using TextClause for complex expressions:
33
+
34
+ >>> from sqlalchemy import text
35
+ >>> PersistedColumn('full_name', String(101),
36
+ ... persisted_expression=text("CONCAT(first_name, ' ', last_name)"))
37
+
38
+ **Table Usage:**
39
+
40
+ .. code-block:: python
41
+
42
+ from sqlalchemy import Column, Integer, MetaData, String, Table, text
43
+ from sqlalchemy_singlestoredb import PersistedColumn
44
+
45
+ metadata = MetaData()
46
+
47
+ products = Table(
48
+ 'products', metadata,
49
+ Column('id', Integer, primary_key=True),
50
+ Column('price', Integer),
51
+ Column('quantity', Integer),
52
+ PersistedColumn(
53
+ 'total',
54
+ Integer,
55
+ persisted_expression='price * quantity',
56
+ ),
57
+ )
58
+
59
+ users = Table(
60
+ 'users', metadata,
61
+ Column('id', Integer, primary_key=True),
62
+ Column('first_name', String(50)),
63
+ Column('last_name', String(50)),
64
+ PersistedColumn(
65
+ 'full_name',
66
+ String(101),
67
+ persisted_expression=text("CONCAT(first_name, ' ', last_name)"),
68
+ ),
69
+ )
70
+
71
+ **ORM Usage:**
72
+
73
+ In ORM models, PersistedColumn is used directly as a class attribute,
74
+ just like a regular Column:
75
+
76
+ .. code-block:: python
77
+
78
+ from sqlalchemy import Column, Integer, String
79
+ from sqlalchemy.orm import declarative_base
80
+ from sqlalchemy_singlestoredb import PersistedColumn
81
+
82
+ Base = declarative_base()
83
+
84
+ class Product(Base):
85
+ __tablename__ = 'products'
86
+
87
+ id = Column(Integer, primary_key=True)
88
+ price = Column(Integer)
89
+ quantity = Column(Integer)
90
+ total = PersistedColumn(
91
+ 'total',
92
+ Integer,
93
+ persisted_expression='price * quantity',
94
+ )
95
+
96
+ class User(Base):
97
+ __tablename__ = 'users'
98
+
99
+ id = Column(Integer, primary_key=True)
100
+ first_name = Column(String(50))
101
+ last_name = Column(String(50))
102
+ full_name = PersistedColumn(
103
+ 'full_name',
104
+ String(101),
105
+ persisted_expression="CONCAT(first_name, ' ', last_name)",
106
+ )
107
+
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ *args: Any,
113
+ persisted_expression: Any = None,
114
+ **kwargs: Any,
115
+ ) -> None:
116
+ if persisted_expression is not None:
117
+ # Ensure persisted_expression is either a TextClause or a string
118
+ if not isinstance(persisted_expression, (TextClause, str)):
119
+ raise ValueError(
120
+ 'Persisted expression must be a SQL expression '
121
+ 'as a string or TextClause',
122
+ )
123
+ self.is_persisted = True
124
+ self.persisted_expression = persisted_expression
125
+ kwargs['info'] = {'persisted_expression': persisted_expression}
126
+ super().__init__(*args, **kwargs)