chdb 3.7.1__cp38-abi3-musllinux_1_2_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of chdb might be problematic. Click here for more details.

@@ -0,0 +1,257 @@
1
+ from . import err
2
+ from .cursors import Cursor
3
+ from . import converters
4
+ from ..state import sqlitelike as chdb_stateful
5
+
6
+ DEBUG = False
7
+ VERBOSE = False
8
+
9
+
10
+ class Connection(object):
11
+ """DB-API 2.0 compliant connection to chDB database.
12
+
13
+ This class provides a standard DB-API interface for connecting to and interacting
14
+ with chDB databases. It supports both in-memory and file-based databases.
15
+
16
+ The connection manages the underlying chDB engine and provides methods for
17
+ executing queries, managing transactions (no-op for ClickHouse), and creating cursors.
18
+
19
+ Args:
20
+ path (str, optional): Database file path. If None, uses in-memory database.
21
+ Can be a file path like 'database.db' or None for ':memory:'
22
+
23
+ Attributes:
24
+ encoding (str): Character encoding for queries, defaults to 'utf8'
25
+ open (bool): True if connection is open, False if closed
26
+
27
+ Examples:
28
+ >>> # In-memory database
29
+ >>> conn = Connection()
30
+ >>> cursor = conn.cursor()
31
+ >>> cursor.execute("SELECT 1")
32
+ >>> result = cursor.fetchall()
33
+ >>> conn.close()
34
+
35
+ >>> # File-based database
36
+ >>> conn = Connection('mydata.db')
37
+ >>> with conn.cursor() as cur:
38
+ ... cur.execute("CREATE TABLE users (id INT, name STRING)")
39
+ ... cur.execute("INSERT INTO users VALUES (1, 'Alice')")
40
+ >>> conn.close()
41
+
42
+ >>> # Context manager usage
43
+ >>> with Connection() as cur:
44
+ ... cur.execute("SELECT version()")
45
+ ... version = cur.fetchone()
46
+
47
+ Note:
48
+ ClickHouse does not support traditional transactions, so commit() and rollback()
49
+ operations are no-ops but provided for DB-API compliance.
50
+ """
51
+
52
+ def __init__(self, path=None):
53
+ """Initialize a new database connection.
54
+
55
+ Args:
56
+ path (str, optional): Database file path. None for in-memory database.
57
+
58
+ Raises:
59
+ err.Error: If connection cannot be established
60
+ """
61
+ self._closed = False
62
+ self.encoding = "utf8"
63
+ self._affected_rows = 0
64
+ self._resp = None
65
+
66
+ # Initialize sqlitelike connection
67
+ connection_string = ":memory:" if path is None else f"file:{path}"
68
+ self._conn = chdb_stateful.Connection(connection_string)
69
+
70
+ # Test connection with a simple query
71
+ cursor = self._conn.cursor()
72
+ cursor.execute("SELECT 1")
73
+ cursor.close()
74
+
75
+ def close(self):
76
+ """Close the database connection.
77
+
78
+ Closes the underlying chDB connection and marks this connection as closed.
79
+ Subsequent operations on this connection will raise an Error.
80
+
81
+ Raises:
82
+ err.Error: If connection is already closed
83
+ """
84
+ if self._closed:
85
+ raise err.Error("Already closed")
86
+ self._closed = True
87
+ self._conn.close()
88
+
89
+ @property
90
+ def open(self):
91
+ """Check if the connection is open.
92
+
93
+ Returns:
94
+ bool: True if connection is open, False if closed
95
+ """
96
+ return not self._closed
97
+
98
+ def commit(self):
99
+ """Commit the current transaction.
100
+
101
+ Note:
102
+ This is a no-op for chDB/ClickHouse as it doesn't support traditional
103
+ transactions. Provided for DB-API 2.0 compliance.
104
+ """
105
+ # No-op for ClickHouse
106
+ pass
107
+
108
+ def rollback(self):
109
+ """Roll back the current transaction.
110
+
111
+ Note:
112
+ This is a no-op for chDB/ClickHouse as it doesn't support traditional
113
+ transactions. Provided for DB-API 2.0 compliance.
114
+ """
115
+ # No-op for ClickHouse
116
+ pass
117
+
118
+ def cursor(self, cursor=None):
119
+ """Create a new cursor for executing queries.
120
+
121
+ Args:
122
+ cursor: Ignored, provided for compatibility
123
+
124
+ Returns:
125
+ Cursor: New cursor object for this connection
126
+
127
+ Raises:
128
+ err.Error: If connection is closed
129
+
130
+ Example:
131
+ >>> conn = Connection()
132
+ >>> cur = conn.cursor()
133
+ >>> cur.execute("SELECT 1")
134
+ >>> result = cur.fetchone()
135
+ """
136
+ if self._closed:
137
+ raise err.Error("Connection closed")
138
+ if cursor:
139
+ return Cursor(self)
140
+ return Cursor(self)
141
+
142
+ def query(self, sql, fmt="CSV"):
143
+ """Execute a SQL query directly and return raw results.
144
+
145
+ This method bypasses the cursor interface and executes queries directly.
146
+ For standard DB-API usage, prefer using cursor() method.
147
+
148
+ Args:
149
+ sql (str or bytes): SQL query to execute
150
+ fmt (str, optional): Output format. Defaults to "CSV".
151
+ Supported formats include "CSV", "JSON", "Arrow", "Parquet", etc.
152
+
153
+ Returns:
154
+ Query result in the specified format
155
+
156
+ Raises:
157
+ err.InterfaceError: If connection is closed or query fails
158
+
159
+ Example:
160
+ >>> conn = Connection()
161
+ >>> result = conn.query("SELECT 1, 'hello'", "CSV")
162
+ >>> print(result)
163
+ "1,hello\\n"
164
+ """
165
+ if self._closed:
166
+ raise err.InterfaceError("Connection closed")
167
+
168
+ if isinstance(sql, str):
169
+ sql = sql.encode(self.encoding, "surrogateescape")
170
+
171
+ try:
172
+ result = self._conn.query(sql.decode(), fmt)
173
+ self._resp = result
174
+ return result
175
+ except Exception as error:
176
+ raise err.InterfaceError(f"Query error: {error}")
177
+
178
+ def escape(self, obj, mapping=None):
179
+ """Escape a value for safe inclusion in SQL queries.
180
+
181
+ Args:
182
+ obj: Value to escape (string, bytes, number, etc.)
183
+ mapping: Optional character mapping for escaping
184
+
185
+ Returns:
186
+ Escaped version of the input suitable for SQL queries
187
+
188
+ Example:
189
+ >>> conn = Connection()
190
+ >>> safe_value = conn.escape("O'Reilly")
191
+ >>> query = f"SELECT * FROM users WHERE name = {safe_value}"
192
+ """
193
+ return converters.escape_item(obj, mapping)
194
+
195
+ def escape_string(self, s):
196
+ """Escape a string value for SQL queries.
197
+
198
+ Args:
199
+ s (str): String to escape
200
+
201
+ Returns:
202
+ str: Escaped string safe for SQL inclusion
203
+ """
204
+ return converters.escape_string(s)
205
+
206
+ def _quote_bytes(self, s):
207
+ """Quote and escape bytes data for SQL queries.
208
+
209
+ Args:
210
+ s (bytes): Bytes data to quote
211
+
212
+ Returns:
213
+ str: Quoted and escaped bytes representation
214
+ """
215
+ return converters.escape_bytes(s)
216
+
217
+ def __enter__(self):
218
+ """Enter context manager and return a cursor.
219
+
220
+ Returns:
221
+ Cursor: New cursor for this connection
222
+
223
+ Example:
224
+ >>> with Connection() as cur:
225
+ ... cur.execute("SELECT 1")
226
+ ... result = cur.fetchone()
227
+ """
228
+ return self.cursor()
229
+
230
+ def __exit__(self, exc, value, traceback):
231
+ """Exit context manager with proper cleanup.
232
+
233
+ Commits on successful exit, rolls back on exception, and always closes connection.
234
+
235
+ Args:
236
+ exc: Exception type (if any)
237
+ value: Exception value (if any)
238
+ traceback: Exception traceback (if any)
239
+ """
240
+ if exc:
241
+ self.rollback()
242
+ else:
243
+ self.commit()
244
+ self.close()
245
+
246
+ @property
247
+ def resp(self):
248
+ """Get the last query response.
249
+
250
+ Returns:
251
+ The raw response from the last query() call
252
+
253
+ Note:
254
+ This property is updated each time query() is called directly.
255
+ It does not reflect queries executed through cursors.
256
+ """
257
+ return self._resp
@@ -0,0 +1,31 @@
1
+ DECIMAL = 0
2
+ TINY = 1
3
+ SHORT = 2
4
+ LONG = 3
5
+ FLOAT = 4
6
+ DOUBLE = 5
7
+ NULL = 6
8
+ TIMESTAMP = 7
9
+ LONGLONG = 8
10
+ INT24 = 9
11
+ DATE = 10
12
+ TIME = 11
13
+ DATETIME = 12
14
+ YEAR = 13
15
+ NEWDATE = 14
16
+ VARCHAR = 15
17
+ BIT = 16
18
+ JSON = 245
19
+ NEWDECIMAL = 246
20
+ ENUM = 247
21
+ SET = 248
22
+ TINY_BLOB = 249
23
+ MEDIUM_BLOB = 250
24
+ LONG_BLOB = 251
25
+ BLOB = 252
26
+ VAR_STRING = 253
27
+ STRING = 254
28
+ GEOMETRY = 255
29
+
30
+ CHAR = TINY
31
+ INTERVAL = ENUM
File without changes