vsql-python 1.0.0__cp313-cp313-macosx_11_0_arm64.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.
vsql/__init__.py ADDED
@@ -0,0 +1,181 @@
1
+ """A DB-API 2.0 (PEP 249) driver for vsql (https://github.com/elliotchance/vsql),
2
+ a single file or in-memory SQL database. libvsql (the vsql library) is compiled
3
+ into the package, so nothing else needs to be installed.
4
+
5
+ import vsql
6
+
7
+ with vsql.connect("test.vsql") as conn:
8
+ cur = conn.cursor()
9
+ cur.execute("CREATE TABLE foo (x INTEGER)")
10
+ cur.execute("INSERT INTO foo (x) VALUES (?)", [123])
11
+ conn.commit()
12
+
13
+ The database is the path of the file, which is created if it doesn't exist, or
14
+ ":memory:" for a database that only exists for the life of the connection.
15
+
16
+ Transactions
17
+
18
+ Like PEP 249 requires, autocommit is off: the first statement starts a
19
+ transaction, which is ended by commit or rollback (or closing the connection,
20
+ which rolls it back). With autocommit on, each statement is committed when it
21
+ finishes, or when the rows of a query have all been fetched. START TRANSACTION,
22
+ COMMIT and ROLLBACK can't be executed as statements.
23
+
24
+ Parameters
25
+
26
+ Parameters are "?" (paramstyle is "qmark"). Each Python type is sent as an SQL
27
+ type, which is cast to the type it's used as:
28
+
29
+ None NULL
30
+ bool BOOLEAN
31
+ int BIGINT (NUMERIC if it's out of range)
32
+ float DOUBLE PRECISION
33
+ str CHARACTER VARYING
34
+ decimal.Decimal NUMERIC (it must be finite)
35
+ datetime.datetime TIMESTAMP(6) (WITH TIME ZONE if it's aware)
36
+ datetime.date DATE
37
+ datetime.time TIME(6) (WITH TIME ZONE if it's aware)
38
+
39
+ Columns
40
+
41
+ The Python type of each column type:
42
+
43
+ SMALLINT, INTEGER, BIGINT int
44
+ REAL, DOUBLE PRECISION float
45
+ DECIMAL, NUMERIC decimal.Decimal
46
+ CHARACTER, VARCHAR str
47
+ BOOLEAN bool
48
+ DATE datetime.date
49
+ TIME (WITH TIME ZONE) datetime.time
50
+ TIMESTAMP (WITH TIME ZONE) datetime.datetime
51
+
52
+ A NULL is None. A value WITH TIME ZONE is aware (with a fixed offset), and
53
+ otherwise it's naive. The type_code in a cursor's description is the name of
54
+ the type (such as "INTEGER" or "CHARACTER VARYING"), which compares equal to
55
+ STRING, NUMBER or DATETIME.
56
+
57
+ Errors
58
+
59
+ An error from vsql is the PEP 249 exception for its SQLSTATE (such as
60
+ ProgrammingError for 42P01, an undefined table), with the SQLSTATE as its
61
+ sqlstate attribute.
62
+ """
63
+
64
+ import datetime
65
+ import time
66
+
67
+ from . import _libvsql
68
+ from ._connection import Connection, Cursor
69
+ from ._errors import (
70
+ DatabaseError,
71
+ DataError,
72
+ Error,
73
+ IntegrityError,
74
+ InterfaceError,
75
+ InternalError,
76
+ NotSupportedError,
77
+ OperationalError,
78
+ ProgrammingError,
79
+ Warning,
80
+ error,
81
+ )
82
+
83
+ apilevel = "2.0"
84
+
85
+ # Threads may share the module, but not connections.
86
+ threadsafety = 1
87
+
88
+ paramstyle = "qmark"
89
+
90
+ _libvsql.set_error_factory(error)
91
+
92
+
93
+ def connect(database, autocommit=False, isolation_level="READ COMMITTED", read_only=False):
94
+ """Opens a connection to a database file (which is created if it doesn't
95
+ exist) or ":memory:".
96
+
97
+ isolation_level and read_only are for the transactions that are started
98
+ when autocommit is off. vsql's transactions are READ COMMITTED, so
99
+ "READ UNCOMMITTED" and "READ COMMITTED" are the only isolation levels that
100
+ can be used, and read_only can't be used (the first statement is a
101
+ NotSupportedError).
102
+ """
103
+
104
+ return Connection(database, autocommit, isolation_level, read_only)
105
+
106
+
107
+ Date = datetime.date
108
+ Time = datetime.time
109
+ Timestamp = datetime.datetime
110
+
111
+
112
+ def DateFromTicks(ticks):
113
+ return Date(*time.localtime(ticks)[:3])
114
+
115
+
116
+ def TimeFromTicks(ticks):
117
+ return Time(*time.localtime(ticks)[3:6])
118
+
119
+
120
+ def TimestampFromTicks(ticks):
121
+ return Timestamp(*time.localtime(ticks)[:6])
122
+
123
+
124
+ # vsql doesn't have a binary type, so a Binary can't be a parameter.
125
+ Binary = bytes
126
+
127
+
128
+ class _TypeObject:
129
+ """Compares equal to the type_code of each of its types."""
130
+
131
+ def __init__(self, *type_names):
132
+ self.type_names = frozenset(type_names)
133
+
134
+ def __eq__(self, other):
135
+ return other in self.type_names
136
+
137
+ def __ne__(self, other):
138
+ return not self == other
139
+
140
+ def __hash__(self):
141
+ return hash(self.type_names)
142
+
143
+
144
+ STRING = _TypeObject("CHARACTER", "CHARACTER VARYING")
145
+ BINARY = _TypeObject()
146
+ NUMBER = _TypeObject("SMALLINT", "INTEGER", "BIGINT", "REAL", "DOUBLE PRECISION", "DECIMAL",
147
+ "NUMERIC")
148
+ DATETIME = _TypeObject("DATE", "TIME", "TIME WITH TIME ZONE", "TIMESTAMP",
149
+ "TIMESTAMP WITH TIME ZONE")
150
+ ROWID = _TypeObject()
151
+
152
+ __all__ = [
153
+ "BINARY",
154
+ "DATETIME",
155
+ "NUMBER",
156
+ "ROWID",
157
+ "STRING",
158
+ "Binary",
159
+ "Connection",
160
+ "Cursor",
161
+ "DataError",
162
+ "DatabaseError",
163
+ "Date",
164
+ "DateFromTicks",
165
+ "Error",
166
+ "IntegrityError",
167
+ "InterfaceError",
168
+ "InternalError",
169
+ "NotSupportedError",
170
+ "OperationalError",
171
+ "ProgrammingError",
172
+ "Time",
173
+ "TimeFromTicks",
174
+ "Timestamp",
175
+ "TimestampFromTicks",
176
+ "Warning",
177
+ "apilevel",
178
+ "connect",
179
+ "paramstyle",
180
+ "threadsafety",
181
+ ]
vsql/_connection.py ADDED
@@ -0,0 +1,358 @@
1
+ import os
2
+ import weakref
3
+
4
+ from . import _convert
5
+ from . import _libvsql as lib
6
+ from ._errors import InterfaceError, ProgrammingError
7
+
8
+ _isolation_levels = {
9
+ "READ UNCOMMITTED": lib.SQL_TRANSACTION_READ_UNCOMMITTED,
10
+ "READ COMMITTED": lib.SQL_TRANSACTION_READ_COMMITTED,
11
+ "REPEATABLE READ": lib.SQL_TRANSACTION_REPEATABLE_READ,
12
+ "SERIALIZABLE": lib.SQL_TRANSACTION_SERIALIZABLE,
13
+ }
14
+
15
+
16
+ class Connection:
17
+ """A connection to a database, see vsql.connect.
18
+
19
+ Each connection has its own environment, so connections can be used at the
20
+ same time from different threads (see "Threads" in libvsql.h), but a
21
+ connection (and its cursors) can only be used by one thread at a time.
22
+ """
23
+
24
+ def __init__(self, database, autocommit=False, isolation_level="READ COMMITTED",
25
+ read_only=False):
26
+ try:
27
+ self._isolation_level = _isolation_levels[isolation_level]
28
+ except KeyError:
29
+ raise ProgrammingError(f"unknown isolation level: {isolation_level!r}") from None
30
+ self._access_mode = (lib.SQL_TRANSACTION_READ_ONLY if read_only
31
+ else lib.SQL_TRANSACTION_READ_WRITE)
32
+ self._autocommit = bool(autocommit)
33
+ self._in_transaction = False
34
+ self._cursors = weakref.WeakSet()
35
+ self._dbc = None
36
+
37
+ self._env = lib.alloc_handle(lib.SQL_HANDLE_ENV, lib.SQL_NULL_HANDLE)
38
+ try:
39
+ dbc = lib.alloc_handle(lib.SQL_HANDLE_DBC, self._env)
40
+ try:
41
+ lib.connect(dbc, os.fspath(database))
42
+ except BaseException:
43
+ lib.free_handle(lib.SQL_HANDLE_DBC, dbc)
44
+ raise
45
+ except BaseException:
46
+ lib.free_handle(lib.SQL_HANDLE_ENV, self._env)
47
+ raise
48
+ self._dbc = dbc
49
+
50
+ # Each statement is committed when it finishes, unless it's in a
51
+ # transaction started by _begin.
52
+ try:
53
+ lib.set_autocommit(self._dbc, True)
54
+ except BaseException:
55
+ self.close()
56
+ raise
57
+
58
+ @property
59
+ def closed(self):
60
+ return self._dbc is None
61
+
62
+ def _check(self):
63
+ if self._dbc is None:
64
+ raise InterfaceError("the connection is closed")
65
+
66
+ @property
67
+ def autocommit(self):
68
+ """Whether each statement is committed when it finishes. Otherwise, a
69
+ transaction is started by the first statement, and ended by commit or
70
+ rollback. Turning it on commits the transaction."""
71
+
72
+ return self._autocommit
73
+
74
+ @autocommit.setter
75
+ def autocommit(self, value):
76
+ self._check()
77
+ if value and self._in_transaction:
78
+ self.commit()
79
+ self._autocommit = bool(value)
80
+
81
+ @property
82
+ def in_transaction(self):
83
+ return self._in_transaction
84
+
85
+ def _begin(self):
86
+ """Starts a transaction, unless autocommit is on or there already is
87
+ one."""
88
+
89
+ if self._autocommit or self._in_transaction:
90
+ return
91
+ lib.start_tran(self._dbc, self._access_mode, self._isolation_level)
92
+ self._in_transaction = True
93
+
94
+ def _end(self, commit):
95
+ self._check()
96
+ if not self._in_transaction:
97
+ return
98
+
99
+ # The cursors of the transaction are closed by it.
100
+ for cursor in list(self._cursors):
101
+ cursor._close_results()
102
+ self._in_transaction = False
103
+ lib.end_tran(self._dbc, commit)
104
+
105
+ def commit(self):
106
+ """Commits the transaction, if there is one."""
107
+
108
+ self._end(True)
109
+
110
+ def rollback(self):
111
+ """Rolls back the transaction, if there is one."""
112
+
113
+ self._end(False)
114
+
115
+ def cursor(self):
116
+ self._check()
117
+ cursor = Cursor(self)
118
+ self._cursors.add(cursor)
119
+
120
+ return cursor
121
+
122
+ def execute(self, operation, parameters=None):
123
+ """Executes a statement with a new cursor, which is returned."""
124
+
125
+ return self.cursor().execute(operation, parameters)
126
+
127
+ def close(self):
128
+ """Closes the connection and its cursors. A transaction that hasn't been
129
+ committed is rolled back. It does nothing if it's already closed."""
130
+
131
+ if self._dbc is None:
132
+ return
133
+
134
+ try:
135
+ for cursor in list(self._cursors):
136
+ cursor.close()
137
+ if self._in_transaction:
138
+ self._in_transaction = False
139
+ lib.end_tran(self._dbc, False)
140
+ lib.disconnect(self._dbc)
141
+ finally:
142
+ dbc, self._dbc = self._dbc, None
143
+ try:
144
+ lib.free_handle(lib.SQL_HANDLE_DBC, dbc)
145
+ finally:
146
+ lib.free_handle(lib.SQL_HANDLE_ENV, self._env)
147
+
148
+ def __enter__(self):
149
+ return self
150
+
151
+ def __exit__(self, exc_type, exc_value, traceback):
152
+ """Commits the transaction (or rolls it back if there was an exception),
153
+ and closes the connection."""
154
+
155
+ try:
156
+ if not self.closed:
157
+ self._end(exc_type is None)
158
+ finally:
159
+ self.close()
160
+
161
+ def __del__(self):
162
+ try:
163
+ self.close()
164
+ except Exception:
165
+ pass
166
+
167
+
168
+ class Cursor:
169
+ """A cursor executes statements and reads the rows of a query, see
170
+ Connection.cursor.
171
+
172
+ Each cursor has its own statement handle. The statement of the last
173
+ execute with parameters stays prepared, so executing it again (such as with
174
+ executemany) doesn't prepare it again.
175
+ """
176
+
177
+ arraysize = 1
178
+ lastrowid = None
179
+
180
+ def __init__(self, connection):
181
+ self.connection = connection
182
+ self.description = None
183
+ self.rowcount = -1
184
+ self._stmt = None
185
+ self._prepared = None
186
+ self._open = False
187
+ self._kinds = b""
188
+ self._converters = None
189
+ self._closed = False
190
+
191
+ def _check(self):
192
+ if self._closed:
193
+ raise InterfaceError("the cursor is closed")
194
+ self.connection._check()
195
+
196
+ def _close_results(self):
197
+ """Closes the rows of the last query, if they're still open."""
198
+
199
+ if self._open:
200
+ self._open = False
201
+ lib.close_cursor(self._stmt)
202
+
203
+ def execute(self, operation, parameters=None):
204
+ """Executes a statement, with a "?" for each of the parameters. It
205
+ returns the cursor, so a query can be fetched from it."""
206
+
207
+ self._check()
208
+ self._close_results()
209
+ self.description = None
210
+ self.rowcount = -1
211
+ params = _convert.to_params(parameters)
212
+
213
+ self.connection._begin()
214
+ if self._stmt is None:
215
+ self._stmt = lib.alloc_handle(lib.SQL_HANDLE_STMT, self.connection._dbc)
216
+
217
+ if params or operation == self._prepared:
218
+ if operation != self._prepared:
219
+ self._prepared = None
220
+ lib.prepare(self._stmt, operation)
221
+ self._prepared = operation
222
+ lib.execute(self._stmt, params)
223
+ else:
224
+ self._prepared = None
225
+ lib.exec_direct(self._stmt, operation)
226
+
227
+ n = lib.num_result_cols(self._stmt)
228
+ if n == 0:
229
+ self.rowcount = lib.row_count(self._stmt)
230
+ return self
231
+
232
+ self._open = True
233
+ description = []
234
+ kinds = []
235
+ converters = []
236
+ for i in range(1, n + 1):
237
+ name, data_type, size, digits, nullable = lib.describe_col(self._stmt, i)
238
+ type_name, kind, converter = _convert.types.get(data_type, ("", "s", None))
239
+ description.append(_column(name, type_name, size, digits, nullable))
240
+ kinds.append(kind)
241
+ converters.append(converter)
242
+ self.description = tuple(description)
243
+ self._kinds = "".join(kinds).encode()
244
+ self._converters = converters if any(converters) else None
245
+
246
+ return self
247
+
248
+ def executemany(self, operation, seq_of_parameters):
249
+ """Executes a statement for each sequence of parameters. rowcount is
250
+ the total of the rows affected."""
251
+
252
+ total = 0
253
+ for parameters in seq_of_parameters:
254
+ self.execute(operation, parameters)
255
+ if self._open:
256
+ raise ProgrammingError("executemany can't be used for a query")
257
+ total += max(self.rowcount, 0)
258
+ self.rowcount = total
259
+
260
+ def fetchone(self):
261
+ """The next row as a tuple, or None if there are no more."""
262
+
263
+ self._check()
264
+ if not self._open:
265
+ if self.description is None:
266
+ raise ProgrammingError("the last statement wasn't a query")
267
+ return None
268
+
269
+ row = lib.fetch_row(self._stmt, self._kinds)
270
+ if row is None:
271
+ self._close_results()
272
+ return None
273
+ if self._converters is None:
274
+ return row
275
+
276
+ return tuple(v if f is None or v is None else f(v) for f, v in zip(self._converters, row))
277
+
278
+ def fetchmany(self, size=None):
279
+ """The next rows (arraysize by default)."""
280
+
281
+ if size is None:
282
+ size = self.arraysize
283
+ rows = []
284
+ while len(rows) < size:
285
+ row = self.fetchone()
286
+ if row is None:
287
+ break
288
+ rows.append(row)
289
+
290
+ return rows
291
+
292
+ def fetchall(self):
293
+ """The rest of the rows."""
294
+
295
+ rows = []
296
+ while True:
297
+ row = self.fetchone()
298
+ if row is None:
299
+ return rows
300
+ rows.append(row)
301
+
302
+ def __iter__(self):
303
+ return self
304
+
305
+ def __next__(self):
306
+ row = self.fetchone()
307
+ if row is None:
308
+ raise StopIteration
309
+
310
+ return row
311
+
312
+ def setinputsizes(self, sizes):
313
+ pass
314
+
315
+ def setoutputsize(self, size, column=None):
316
+ pass
317
+
318
+ def close(self):
319
+ """Closes the cursor. It does nothing if it's already closed."""
320
+
321
+ if self._closed:
322
+ return
323
+ self._closed = True
324
+ if self._stmt is None or self.connection.closed:
325
+ return
326
+
327
+ try:
328
+ self._close_results()
329
+ finally:
330
+ stmt, self._stmt = self._stmt, None
331
+ lib.free_handle(lib.SQL_HANDLE_STMT, stmt)
332
+
333
+ def __enter__(self):
334
+ return self
335
+
336
+ def __exit__(self, exc_type, exc_value, traceback):
337
+ self.close()
338
+
339
+ def __del__(self):
340
+ try:
341
+ self.close()
342
+ except Exception:
343
+ pass
344
+
345
+
346
+ # The PEP 249 description of a column: (name, type_code, display_size,
347
+ # internal_size, precision, scale, null_ok).
348
+ def _column(name, type_name, size, digits, nullable):
349
+ display_size = precision = scale = None
350
+ if type_name in ("CHARACTER", "CHARACTER VARYING"):
351
+ # The size is in octets, with 4 for each character.
352
+ display_size = size // 4 if size > 0 else None
353
+ elif type_name in ("DECIMAL", "NUMERIC"):
354
+ precision, scale = size, digits
355
+
356
+ return (name, type_name, display_size, size, precision, scale,
357
+ nullable != lib.SQL_NO_NULLS)
358
+