vsql-python 1.1.0__tar.gz → 1.2.1__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 (29) hide show
  1. {vsql_python-1.1.0 → vsql_python-1.2.1}/PKG-INFO +85 -8
  2. {vsql_python-1.1.0 → vsql_python-1.2.1}/README.md +84 -7
  3. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql/__init__.py +64 -18
  4. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql/_connection.py +110 -16
  5. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql/_convert.py +166 -2
  6. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql/_errors.py +34 -5
  7. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql/_libvsql.c +244 -10
  8. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql_python.egg-info/PKG-INFO +85 -8
  9. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql_python.egg-info/scm_version.json +2 -2
  10. {vsql_python-1.1.0 → vsql_python-1.2.1}/tests/test_vsql.py +253 -3
  11. {vsql_python-1.1.0 → vsql_python-1.2.1}/.github/workflows/release.yml +0 -0
  12. {vsql_python-1.1.0 → vsql_python-1.2.1}/.github/workflows/test.yml +0 -0
  13. {vsql_python-1.1.0 → vsql_python-1.2.1}/.gitignore +0 -0
  14. {vsql_python-1.1.0 → vsql_python-1.2.1}/LICENSE +0 -0
  15. {vsql_python-1.1.0 → vsql_python-1.2.1}/MANIFEST.in +0 -0
  16. {vsql_python-1.1.0 → vsql_python-1.2.1}/example/main.py +0 -0
  17. {vsql_python-1.1.0 → vsql_python-1.2.1}/internal/amalgamation/LICENSE +0 -0
  18. {vsql_python-1.1.0 → vsql_python-1.2.1}/internal/amalgamation/LICENSE-V +0 -0
  19. {vsql_python-1.1.0 → vsql_python-1.2.1}/internal/amalgamation/libvsql.c +0 -0
  20. {vsql_python-1.1.0 → vsql_python-1.2.1}/internal/amalgamation/libvsql.h +0 -0
  21. {vsql_python-1.1.0 → vsql_python-1.2.1}/libvsql_flags.json +0 -0
  22. {vsql_python-1.1.0 → vsql_python-1.2.1}/pyproject.toml +0 -0
  23. {vsql_python-1.1.0 → vsql_python-1.2.1}/scripts/update-amalgamation.sh +0 -0
  24. {vsql_python-1.1.0 → vsql_python-1.2.1}/setup.cfg +0 -0
  25. {vsql_python-1.1.0 → vsql_python-1.2.1}/setup.py +0 -0
  26. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql_python.egg-info/SOURCES.txt +0 -0
  27. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql_python.egg-info/dependency_links.txt +0 -0
  28. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql_python.egg-info/scm_file_list.json +0 -0
  29. {vsql_python-1.1.0 → vsql_python-1.2.1}/src/vsql_python.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vsql-python
3
- Version: 1.1.0
3
+ Version: 1.2.1
4
4
  Summary: A DB-API 2.0 (PEP 249) driver for vsql, a single file or in-memory SQL database.
5
5
  Author-email: Elliot Chance <elliotchance@gmail.com>
6
6
  License-Expression: MIT
@@ -63,6 +63,24 @@ and `ROLLBACK` can't be executed as statements.
63
63
 
64
64
  vsql's transactions are `READ COMMITTED`.
65
65
 
66
+ ### Savepoints
67
+
68
+ A savepoint is made by executing `SAVEPOINT`, and released by executing
69
+ `RELEASE SAVEPOINT`. Like `ROLLBACK`, `ROLLBACK TO SAVEPOINT` can't be executed
70
+ as a statement, so it's `conn.rollback_to_savepoint(name)` instead (which
71
+ closes the cursors of the connection):
72
+
73
+ ```python
74
+ cur.execute("INSERT INTO foo (x) VALUES (1)")
75
+ cur.execute("SAVEPOINT before_two")
76
+ cur.execute("INSERT INTO foo (x) VALUES (2)")
77
+ conn.rollback_to_savepoint("before_two")
78
+ conn.commit() # only 1 is inserted
79
+ ```
80
+
81
+ The name is an identifier, so `"before_two"` is `BEFORE_TWO`, and a name that
82
+ must stay lower case is quoted, such as `'"b"'`.
83
+
66
84
  ## Parameters
67
85
 
68
86
  Parameters are `?` (`paramstyle` is `"qmark"`), given as a sequence. Each
@@ -79,8 +97,13 @@ Python type is sent as an SQL type, which is cast to the type it's used as:
79
97
  | `datetime.datetime` | `TIMESTAMP(6)` (`WITH TIME ZONE` if aware) |
80
98
  | `datetime.date` | `DATE` |
81
99
  | `datetime.time` | `TIME(6)` (`WITH TIME ZONE` if aware) |
100
+ | `bytes`, `bytearray`, `memoryview` | `BINARY VARYING` |
101
+ | `datetime.timedelta` | `INTERVAL DAY TO SECOND(6)` |
102
+ | `vsql.YearMonthInterval` | `INTERVAL YEAR TO MONTH` |
82
103
 
83
- vsql doesn't have a binary type, so `bytes` can't be a parameter.
104
+ A string can't be a binary string (or the other way around), and a
105
+ year-month interval can't be a day-time interval (`07006`). A
106
+ `datetime.timedelta` can have up to 99,999,999 days (`DAY(8)`).
84
107
 
85
108
  ## Columns
86
109
 
@@ -88,17 +111,38 @@ vsql doesn't have a binary type, so `bytes` can't be a parameter.
88
111
  |----------------------------------|---------------------|
89
112
  | `SMALLINT`, `INTEGER`, `BIGINT` | `int` |
90
113
  | `REAL`, `DOUBLE PRECISION` | `float` |
91
- | `DECIMAL`, `NUMERIC` | `decimal.Decimal` |
92
- | `CHARACTER`, `VARCHAR` | `str` |
114
+ | `DECIMAL`, `NUMERIC`, `DECFLOAT` | `decimal.Decimal` |
115
+ | `CHARACTER`, `VARCHAR`, `CLOB` | `str` |
116
+ | `BINARY`, `VARBINARY`, `BLOB` | `bytes` |
93
117
  | `BOOLEAN` | `bool` |
94
118
  | `DATE` | `datetime.date` |
95
119
  | `TIME (WITH TIME ZONE)` | `datetime.time` |
96
120
  | `TIMESTAMP (WITH TIME ZONE)` | `datetime.datetime` |
121
+ | `INTERVAL YEAR`, `INTERVAL MONTH`, `INTERVAL YEAR TO MONTH` | `vsql.YearMonthInterval` |
122
+ | any other `INTERVAL` (`DAY` to `SECOND`) | `datetime.timedelta` |
97
123
 
98
124
  A `NULL` is `None`. A value `WITH TIME ZONE` is aware (with a fixed offset),
99
- otherwise it's naive. The `type_code` in `cursor.description` is the name of
100
- the type (such as `"INTEGER"`), which compares equal to `vsql.NUMBER`,
101
- `vsql.STRING` or `vsql.DATETIME`.
125
+ otherwise it's naive.
126
+
127
+ A year-month interval isn't a `datetime.timedelta`, since a month doesn't have
128
+ a fixed length. `vsql.YearMonthInterval(years=1, months=2)` is a number of
129
+ months (`total_months`), which is also `years` and `months` (with the same
130
+ sign):
131
+
132
+ ```python
133
+ cur.execute("VALUES INTERVAL -'1-02' YEAR TO MONTH")
134
+ i = cur.fetchone()[0] # YearMonthInterval(years=-1, months=-2)
135
+ print(i.total_months) # -14
136
+ ```
137
+
138
+ The `type_code` in `cursor.description` is the name of the type (such as
139
+ `"INTEGER"` or `"INTERVAL DAY TO SECOND"`), which compares equal to
140
+ `vsql.NUMBER`, `vsql.STRING`, `vsql.BINARY` or `vsql.DATETIME` (which includes
141
+ the intervals). The `internal_size` is the length of a string (in octets, 4 for
142
+ each character) or a binary string, the precision of a number, or the length of
143
+ a datetime or interval. The `precision` and `scale` are those of a `DECIMAL`
144
+ or `NUMERIC`, the precision of a `DECFLOAT` (16 or 34), or the leading field
145
+ precision and the fractional seconds precision of an interval.
102
146
 
103
147
  ## Errors
104
148
 
@@ -110,19 +154,52 @@ try:
110
154
  cur.execute("SELECT * FROM nope")
111
155
  except vsql.ProgrammingError as e:
112
156
  print(e.sqlstate) # 42P01
157
+ print(e.table_name) # NOPE
158
+ ```
159
+
160
+ The object that the error is about is in these attributes (or `None`):
161
+
162
+ | Attribute | |
163
+ |---|---|
164
+ | `constraint_catalog`, `constraint_schema`, `constraint_name` | The constraint that was violated (such as a `PRIMARY KEY` or `CHECK`) |
165
+ | `catalog_name`, `schema_name`, `table_name` | The table (of the constraint, or one that doesn't exist) |
166
+ | `column_name` | The column (such as one that doesn't exist) |
167
+ | `cursor_name` | The cursor (for an invalid cursor state) |
168
+
169
+ ```python
170
+ try:
171
+ cur.execute("INSERT INTO foo (id) VALUES (1)")
172
+ except vsql.IntegrityError as e:
173
+ print(e.constraint_name, e.table_name) # FOO_PK FOO
113
174
  ```
114
175
 
115
176
  | SQLSTATE class | Exception |
116
177
  |------------------------------------------------|---------------------|
117
178
  | `22` data exception | `DataError` |
118
179
  | `23` integrity constraint violation | `IntegrityError` |
119
- | `42` syntax error or access rule violation, `07`, `21`, `24`, `26`, `2B`, `34`, `3D`, `3F` | `ProgrammingError` |
180
+ | `42` syntax error or access rule violation, `07`, `21`, `24`, `26`, `2B`, `34`, `3B`, `3D`, `3F` | `ProgrammingError` |
120
181
  | `0A` feature not supported, `HYC00` | `NotSupportedError` |
121
182
  | `08`, `0B`, `25`, `2D`, `40`, `54`, `58`, `HY001` | `OperationalError` |
122
183
  | `HY` CLI-specific condition | `InterfaceError` |
123
184
  | `XX` internal error | `InternalError` |
124
185
  | anything else | `DatabaseError` |
125
186
 
187
+ ## Versions
188
+
189
+ `vsql.vsql_version` is the version of vsql that's compiled into the package
190
+ (such as `"1.7.58"`), and `vsql.vsql_version_info` is the same as a tuple
191
+ (`(1, 7, 58)`). `vsql.build_info` is a dict of how it was built:
192
+
193
+ ```python
194
+ >>> vsql.build_info
195
+ {'version': 'v1.7.58', 'commit': '3cafbc3...', 'date': '2026-11-26',
196
+ 'v_version': '0.5.2', 'v_commit': 'c0bb949', 'c_compiler': 'clang',
197
+ 'operating_system': 'macos', 'machine': 'arm64'}
198
+ ```
199
+
200
+ `conn.file_version` is the `(read, write)` version of the database file's
201
+ format (`(0, 0)` for `:memory:`).
202
+
126
203
  ## Threads
127
204
 
128
205
  Each connection has its own libvsql environment, so different connections can
@@ -44,6 +44,24 @@ and `ROLLBACK` can't be executed as statements.
44
44
 
45
45
  vsql's transactions are `READ COMMITTED`.
46
46
 
47
+ ### Savepoints
48
+
49
+ A savepoint is made by executing `SAVEPOINT`, and released by executing
50
+ `RELEASE SAVEPOINT`. Like `ROLLBACK`, `ROLLBACK TO SAVEPOINT` can't be executed
51
+ as a statement, so it's `conn.rollback_to_savepoint(name)` instead (which
52
+ closes the cursors of the connection):
53
+
54
+ ```python
55
+ cur.execute("INSERT INTO foo (x) VALUES (1)")
56
+ cur.execute("SAVEPOINT before_two")
57
+ cur.execute("INSERT INTO foo (x) VALUES (2)")
58
+ conn.rollback_to_savepoint("before_two")
59
+ conn.commit() # only 1 is inserted
60
+ ```
61
+
62
+ The name is an identifier, so `"before_two"` is `BEFORE_TWO`, and a name that
63
+ must stay lower case is quoted, such as `'"b"'`.
64
+
47
65
  ## Parameters
48
66
 
49
67
  Parameters are `?` (`paramstyle` is `"qmark"`), given as a sequence. Each
@@ -60,8 +78,13 @@ Python type is sent as an SQL type, which is cast to the type it's used as:
60
78
  | `datetime.datetime` | `TIMESTAMP(6)` (`WITH TIME ZONE` if aware) |
61
79
  | `datetime.date` | `DATE` |
62
80
  | `datetime.time` | `TIME(6)` (`WITH TIME ZONE` if aware) |
81
+ | `bytes`, `bytearray`, `memoryview` | `BINARY VARYING` |
82
+ | `datetime.timedelta` | `INTERVAL DAY TO SECOND(6)` |
83
+ | `vsql.YearMonthInterval` | `INTERVAL YEAR TO MONTH` |
63
84
 
64
- vsql doesn't have a binary type, so `bytes` can't be a parameter.
85
+ A string can't be a binary string (or the other way around), and a
86
+ year-month interval can't be a day-time interval (`07006`). A
87
+ `datetime.timedelta` can have up to 99,999,999 days (`DAY(8)`).
65
88
 
66
89
  ## Columns
67
90
 
@@ -69,17 +92,38 @@ vsql doesn't have a binary type, so `bytes` can't be a parameter.
69
92
  |----------------------------------|---------------------|
70
93
  | `SMALLINT`, `INTEGER`, `BIGINT` | `int` |
71
94
  | `REAL`, `DOUBLE PRECISION` | `float` |
72
- | `DECIMAL`, `NUMERIC` | `decimal.Decimal` |
73
- | `CHARACTER`, `VARCHAR` | `str` |
95
+ | `DECIMAL`, `NUMERIC`, `DECFLOAT` | `decimal.Decimal` |
96
+ | `CHARACTER`, `VARCHAR`, `CLOB` | `str` |
97
+ | `BINARY`, `VARBINARY`, `BLOB` | `bytes` |
74
98
  | `BOOLEAN` | `bool` |
75
99
  | `DATE` | `datetime.date` |
76
100
  | `TIME (WITH TIME ZONE)` | `datetime.time` |
77
101
  | `TIMESTAMP (WITH TIME ZONE)` | `datetime.datetime` |
102
+ | `INTERVAL YEAR`, `INTERVAL MONTH`, `INTERVAL YEAR TO MONTH` | `vsql.YearMonthInterval` |
103
+ | any other `INTERVAL` (`DAY` to `SECOND`) | `datetime.timedelta` |
78
104
 
79
105
  A `NULL` is `None`. A value `WITH TIME ZONE` is aware (with a fixed offset),
80
- otherwise it's naive. The `type_code` in `cursor.description` is the name of
81
- the type (such as `"INTEGER"`), which compares equal to `vsql.NUMBER`,
82
- `vsql.STRING` or `vsql.DATETIME`.
106
+ otherwise it's naive.
107
+
108
+ A year-month interval isn't a `datetime.timedelta`, since a month doesn't have
109
+ a fixed length. `vsql.YearMonthInterval(years=1, months=2)` is a number of
110
+ months (`total_months`), which is also `years` and `months` (with the same
111
+ sign):
112
+
113
+ ```python
114
+ cur.execute("VALUES INTERVAL -'1-02' YEAR TO MONTH")
115
+ i = cur.fetchone()[0] # YearMonthInterval(years=-1, months=-2)
116
+ print(i.total_months) # -14
117
+ ```
118
+
119
+ The `type_code` in `cursor.description` is the name of the type (such as
120
+ `"INTEGER"` or `"INTERVAL DAY TO SECOND"`), which compares equal to
121
+ `vsql.NUMBER`, `vsql.STRING`, `vsql.BINARY` or `vsql.DATETIME` (which includes
122
+ the intervals). The `internal_size` is the length of a string (in octets, 4 for
123
+ each character) or a binary string, the precision of a number, or the length of
124
+ a datetime or interval. The `precision` and `scale` are those of a `DECIMAL`
125
+ or `NUMERIC`, the precision of a `DECFLOAT` (16 or 34), or the leading field
126
+ precision and the fractional seconds precision of an interval.
83
127
 
84
128
  ## Errors
85
129
 
@@ -91,19 +135,52 @@ try:
91
135
  cur.execute("SELECT * FROM nope")
92
136
  except vsql.ProgrammingError as e:
93
137
  print(e.sqlstate) # 42P01
138
+ print(e.table_name) # NOPE
139
+ ```
140
+
141
+ The object that the error is about is in these attributes (or `None`):
142
+
143
+ | Attribute | |
144
+ |---|---|
145
+ | `constraint_catalog`, `constraint_schema`, `constraint_name` | The constraint that was violated (such as a `PRIMARY KEY` or `CHECK`) |
146
+ | `catalog_name`, `schema_name`, `table_name` | The table (of the constraint, or one that doesn't exist) |
147
+ | `column_name` | The column (such as one that doesn't exist) |
148
+ | `cursor_name` | The cursor (for an invalid cursor state) |
149
+
150
+ ```python
151
+ try:
152
+ cur.execute("INSERT INTO foo (id) VALUES (1)")
153
+ except vsql.IntegrityError as e:
154
+ print(e.constraint_name, e.table_name) # FOO_PK FOO
94
155
  ```
95
156
 
96
157
  | SQLSTATE class | Exception |
97
158
  |------------------------------------------------|---------------------|
98
159
  | `22` data exception | `DataError` |
99
160
  | `23` integrity constraint violation | `IntegrityError` |
100
- | `42` syntax error or access rule violation, `07`, `21`, `24`, `26`, `2B`, `34`, `3D`, `3F` | `ProgrammingError` |
161
+ | `42` syntax error or access rule violation, `07`, `21`, `24`, `26`, `2B`, `34`, `3B`, `3D`, `3F` | `ProgrammingError` |
101
162
  | `0A` feature not supported, `HYC00` | `NotSupportedError` |
102
163
  | `08`, `0B`, `25`, `2D`, `40`, `54`, `58`, `HY001` | `OperationalError` |
103
164
  | `HY` CLI-specific condition | `InterfaceError` |
104
165
  | `XX` internal error | `InternalError` |
105
166
  | anything else | `DatabaseError` |
106
167
 
168
+ ## Versions
169
+
170
+ `vsql.vsql_version` is the version of vsql that's compiled into the package
171
+ (such as `"1.7.58"`), and `vsql.vsql_version_info` is the same as a tuple
172
+ (`(1, 7, 58)`). `vsql.build_info` is a dict of how it was built:
173
+
174
+ ```python
175
+ >>> vsql.build_info
176
+ {'version': 'v1.7.58', 'commit': '3cafbc3...', 'date': '2026-11-26',
177
+ 'v_version': '0.5.2', 'v_commit': 'c0bb949', 'c_compiler': 'clang',
178
+ 'operating_system': 'macos', 'machine': 'arm64'}
179
+ ```
180
+
181
+ `conn.file_version` is the `(read, write)` version of the database file's
182
+ format (`(0, 0)` for `:memory:`).
183
+
107
184
  ## Threads
108
185
 
109
186
  Each connection has its own libvsql environment, so different connections can
@@ -21,6 +21,10 @@ which rolls it back). With autocommit on, each statement is committed when it
21
21
  finishes, or when the rows of a query have all been fetched. START TRANSACTION,
22
22
  COMMIT and ROLLBACK can't be executed as statements.
23
23
 
24
+ A savepoint is made by executing SAVEPOINT, and released by executing RELEASE
25
+ SAVEPOINT. ROLLBACK TO SAVEPOINT can't be executed as a statement either, so
26
+ it's Connection.rollback_to_savepoint instead.
27
+
24
28
  Parameters
25
29
 
26
30
  Parameters are "?" (paramstyle is "qmark"). Each Python type is sent as an SQL
@@ -35,37 +39,54 @@ type, which is cast to the type it's used as:
35
39
  datetime.datetime TIMESTAMP(6) (WITH TIME ZONE if it's aware)
36
40
  datetime.date DATE
37
41
  datetime.time TIME(6) (WITH TIME ZONE if it's aware)
42
+ bytes, bytearray BINARY VARYING
43
+ or memoryview
44
+ datetime.timedelta INTERVAL DAY TO SECOND(6)
45
+ YearMonthInterval INTERVAL YEAR TO MONTH
38
46
 
39
47
  Columns
40
48
 
41
49
  The Python type of each column type:
42
50
 
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
+ SMALLINT, INTEGER, BIGINT int
52
+ REAL, DOUBLE PRECISION float
53
+ DECIMAL, NUMERIC, DECFLOAT decimal.Decimal
54
+ CHARACTER, VARCHAR, CLOB str
55
+ BINARY, VARBINARY, BLOB bytes
56
+ BOOLEAN bool
57
+ DATE datetime.date
58
+ TIME (WITH TIME ZONE) datetime.time
59
+ TIMESTAMP (WITH TIME ZONE) datetime.datetime
60
+ INTERVAL YEAR TO MONTH (or YEAR, YearMonthInterval
61
+ or MONTH)
62
+ any other INTERVAL datetime.timedelta
51
63
 
52
64
  A NULL is None. A value WITH TIME ZONE is aware (with a fixed offset), and
53
65
  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.
66
+ the type (such as "INTEGER" or "INTERVAL DAY TO SECOND"), which compares equal
67
+ to STRING, BINARY, NUMBER or DATETIME.
56
68
 
57
69
  Errors
58
70
 
59
71
  An error from vsql is the PEP 249 exception for its SQLSTATE (such as
60
72
  ProgrammingError for 42P01, an undefined table), with the SQLSTATE as its
61
- sqlstate attribute.
73
+ sqlstate attribute. The object it's about (such as constraint_name or
74
+ table_name) is in the other attributes, see Error.
75
+
76
+ Version
77
+
78
+ vsql_version is the version of vsql (such as "1.7.58"), vsql_version_info is
79
+ it as a tuple of ints, and build_info is a dict of how it was built (its
80
+ "version" tag, "commit", "date", "v_version", "v_commit", "c_compiler",
81
+ "operating_system" and "machine").
62
82
  """
63
83
 
64
84
  import datetime
65
85
  import time
66
86
 
67
- from . import _libvsql
68
- from ._connection import Connection, Cursor
87
+ from . import _convert, _libvsql
88
+ from ._connection import Connection, Cursor, build_info as _build_info
89
+ from ._convert import YearMonthInterval
69
90
  from ._errors import (
70
91
  DatabaseError,
71
92
  DataError,
@@ -121,7 +142,6 @@ def TimestampFromTicks(ticks):
121
142
  return Timestamp(*time.localtime(ticks)[:6])
122
143
 
123
144
 
124
- # vsql doesn't have a binary type, so a Binary can't be a parameter.
125
145
  Binary = bytes
126
146
 
127
147
 
@@ -141,14 +161,36 @@ class _TypeObject:
141
161
  return hash(self.type_names)
142
162
 
143
163
 
144
- STRING = _TypeObject("CHARACTER", "CHARACTER VARYING")
145
- BINARY = _TypeObject()
164
+ STRING = _TypeObject("CHARACTER", "CHARACTER VARYING", "CHARACTER LARGE OBJECT")
165
+ BINARY = _TypeObject("BINARY", "BINARY VARYING", "BINARY LARGE OBJECT")
146
166
  NUMBER = _TypeObject("SMALLINT", "INTEGER", "BIGINT", "REAL", "DOUBLE PRECISION", "DECIMAL",
147
- "NUMERIC")
167
+ "NUMERIC", "DECFLOAT")
148
168
  DATETIME = _TypeObject("DATE", "TIME", "TIME WITH TIME ZONE", "TIMESTAMP",
149
- "TIMESTAMP WITH TIME ZONE")
169
+ "TIMESTAMP WITH TIME ZONE",
170
+ *("INTERVAL " + fields for fields in _convert.interval_types.values()))
150
171
  ROWID = _TypeObject()
151
172
 
173
+ _version = None
174
+
175
+
176
+ def __getattr__(name):
177
+ """vsql_version, vsql_version_info and build_info are read from libvsql the
178
+ first time they're used."""
179
+
180
+ global _version
181
+ if name in ("vsql_version", "vsql_version_info", "build_info"):
182
+ if _version is None:
183
+ _version = _build_info()
184
+ version_info, info = _version
185
+ if name == "vsql_version":
186
+ return ".".join(map(str, version_info))
187
+ if name == "vsql_version_info":
188
+ return version_info
189
+ return dict(info)
190
+
191
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
192
+
193
+
152
194
  __all__ = [
153
195
  "BINARY",
154
196
  "DATETIME",
@@ -174,8 +216,12 @@ __all__ = [
174
216
  "Timestamp",
175
217
  "TimestampFromTicks",
176
218
  "Warning",
219
+ "YearMonthInterval",
177
220
  "apilevel",
221
+ "build_info",
178
222
  "connect",
179
223
  "paramstyle",
180
224
  "threadsafety",
225
+ "vsql_version",
226
+ "vsql_version_info",
181
227
  ]
@@ -3,7 +3,7 @@ import weakref
3
3
 
4
4
  from . import _convert
5
5
  from . import _libvsql as lib
6
- from ._errors import InterfaceError, ProgrammingError
6
+ from ._errors import DatabaseError, InterfaceError, ProgrammingError
7
7
 
8
8
  _isolation_levels = {
9
9
  "READ UNCOMMITTED": lib.SQL_TRANSACTION_READ_UNCOMMITTED,
@@ -84,6 +84,16 @@ class Connection:
84
84
  def in_transaction(self):
85
85
  return self._in_transaction
86
86
 
87
+ @property
88
+ def file_version(self):
89
+ """The (read, write) versions of the database file's format, which are
90
+ (0, 0) for ":memory:". vsql can open a file when it knows the read
91
+ version, and change it when it knows the write version."""
92
+
93
+ self._check()
94
+ return (lib.get_info(self._dbc, lib.SQL_VSQL_FILE_READ_VERSION, False),
95
+ lib.get_info(self._dbc, lib.SQL_VSQL_FILE_WRITE_VERSION, False))
96
+
87
97
  def _begin(self):
88
98
  """Starts a transaction, unless autocommit is on or there already is
89
99
  one."""
@@ -93,6 +103,17 @@ class Connection:
93
103
  lib.start_tran(self._dbc, self._access_mode, self._isolation_level)
94
104
  self._in_transaction = True
95
105
 
106
+ def _check_transaction(self, handle_type, handle):
107
+ """Checks whether the transaction is still active after an error. vsql
108
+ rolls back the whole transaction for some errors (such as a 40001
109
+ serialization failure), which closes the cursors, and then the next
110
+ statement starts a new transaction."""
111
+
112
+ if self._in_transaction and not lib.transaction_active(handle_type, handle):
113
+ self._in_transaction = False
114
+ for cursor in list(self._cursors):
115
+ cursor._open = False
116
+
96
117
  def _end(self, commit):
97
118
  self._check()
98
119
  if not self._in_transaction:
@@ -101,8 +122,12 @@ class Connection:
101
122
  # The cursors of the transaction are closed by it.
102
123
  for cursor in list(self._cursors):
103
124
  cursor._close_results()
104
- self._in_transaction = False
105
- lib.end_tran(self._dbc, commit)
125
+ try:
126
+ lib.end_tran(self._dbc, commit)
127
+ finally:
128
+ # A commit that fails may leave the transaction active, or roll
129
+ # it back.
130
+ self._in_transaction = lib.transaction_active(lib.SQL_HANDLE_DBC, self._dbc)
106
131
 
107
132
  def commit(self):
108
133
  """Commits the transaction, if there is one."""
@@ -114,6 +139,26 @@ class Connection:
114
139
 
115
140
  self._end(False)
116
141
 
142
+ def rollback_to_savepoint(self, name):
143
+ """Rolls back the transaction to a savepoint, which was made by
144
+ executing SAVEPOINT. vsql doesn't allow ROLLBACK TO SAVEPOINT as a
145
+ statement (like ROLLBACK), so this is how it's done. The cursors of the
146
+ connection are closed. RELEASE SAVEPOINT can be executed as a
147
+ statement.
148
+
149
+ The name is an identifier, so a name that isn't quoted is upper case
150
+ (such as "foo", which is FOO), and a quoted name (such as '"foo"') is
151
+ what's inside the quotes."""
152
+
153
+ self._check()
154
+ for cursor in list(self._cursors):
155
+ cursor._close_results()
156
+ try:
157
+ lib.end_savepoint(self._dbc, name, True)
158
+ except DatabaseError:
159
+ self._check_transaction(lib.SQL_HANDLE_DBC, self._dbc)
160
+ raise
161
+
117
162
  def cursor(self):
118
163
  self._check()
119
164
  cursor = Cursor(self)
@@ -216,15 +261,19 @@ class Cursor:
216
261
  if self._stmt is None:
217
262
  self._stmt = lib.alloc_handle(lib.SQL_HANDLE_STMT, self.connection._dbc)
218
263
 
219
- if params or operation == self._prepared:
220
- if operation != self._prepared:
264
+ try:
265
+ if params or operation == self._prepared:
266
+ if operation != self._prepared:
267
+ self._prepared = None
268
+ lib.prepare(self._stmt, operation)
269
+ self._prepared = operation
270
+ lib.execute(self._stmt, params)
271
+ else:
221
272
  self._prepared = None
222
- lib.prepare(self._stmt, operation)
223
- self._prepared = operation
224
- lib.execute(self._stmt, params)
225
- else:
226
- self._prepared = None
227
- lib.exec_direct(self._stmt, operation)
273
+ lib.exec_direct(self._stmt, operation)
274
+ except DatabaseError:
275
+ self.connection._check_transaction(lib.SQL_HANDLE_STMT, self._stmt)
276
+ raise
228
277
 
229
278
  n = lib.num_result_cols(self._stmt)
230
279
  if n == 0:
@@ -238,7 +287,11 @@ class Cursor:
238
287
  for i in range(1, n + 1):
239
288
  name, data_type, size, digits, nullable = lib.describe_col(self._stmt, i)
240
289
  type_name, kind, converter = _convert.types.get(data_type, ("", "s", None))
241
- description.append(_column(name, type_name, size, digits, nullable))
290
+ leading = None
291
+ if data_type in _convert.interval_types:
292
+ leading = lib.col_attribute(self._stmt, i,
293
+ lib.SQL_DESC_DATETIME_INTERVAL_PRECISION)
294
+ description.append(_column(name, type_name, size, digits, nullable, leading))
242
295
  kinds.append(kind)
243
296
  converters.append(converter)
244
297
  self.description = tuple(description)
@@ -268,7 +321,11 @@ class Cursor:
268
321
  raise ProgrammingError("the last statement wasn't a query")
269
322
  return None
270
323
 
271
- row = lib.fetch_row(self._stmt, self._kinds)
324
+ try:
325
+ row = lib.fetch_row(self._stmt, self._kinds)
326
+ except DatabaseError:
327
+ self.connection._check_transaction(lib.SQL_HANDLE_STMT, self._stmt)
328
+ raise
272
329
  if row is None:
273
330
  self._close_results()
274
331
  return None
@@ -346,15 +403,52 @@ class Cursor:
346
403
 
347
404
 
348
405
  # The PEP 249 description of a column: (name, type_code, display_size,
349
- # internal_size, precision, scale, null_ok).
350
- def _column(name, type_name, size, digits, nullable):
406
+ # internal_size, precision, scale, null_ok). The internal_size is the
407
+ # ColumnSize from SQLDescribeCol.
408
+ def _column(name, type_name, size, digits, nullable, leading=None):
351
409
  display_size = precision = scale = None
352
- if type_name in ("CHARACTER", "CHARACTER VARYING"):
410
+ if type_name in ("CHARACTER", "CHARACTER VARYING", "CHARACTER LARGE OBJECT"):
353
411
  # The size is in octets, with 4 for each character.
354
412
  display_size = size // 4 if size > 0 else None
355
413
  elif type_name in ("DECIMAL", "NUMERIC"):
356
414
  precision, scale = size, digits
415
+ elif type_name == "DECFLOAT":
416
+ precision = size
417
+ elif leading is not None:
418
+ # An interval's precision is the leading field precision, and its scale
419
+ # is the fractional seconds precision (if it ends with SECOND). The
420
+ # size is its length in positions.
421
+ precision = leading
422
+ display_size = size
423
+ if type_name.endswith("SECOND"):
424
+ scale = digits
357
425
 
358
426
  return (name, type_name, display_size, size, precision, scale,
359
427
  nullable != lib.SQL_NO_NULLS)
360
428
 
429
+
430
+ def build_info():
431
+ """The (major, minor, patch) version of vsql, and a dict of how it was
432
+ built, from SQLGetInfo (which needs a connection, so they're read from a
433
+ ":memory:" database)."""
434
+
435
+ fields = {
436
+ "version": lib.SQL_VSQL_BUILD_VERSION,
437
+ "commit": lib.SQL_VSQL_BUILD_COMMIT,
438
+ "date": lib.SQL_VSQL_BUILD_DATE,
439
+ "v_version": lib.SQL_VSQL_BUILD_V_VERSION,
440
+ "v_commit": lib.SQL_VSQL_BUILD_V_COMMIT,
441
+ "c_compiler": lib.SQL_VSQL_BUILD_C_COMPILER,
442
+ "operating_system": lib.SQL_VSQL_OPERATING_SYSTEM,
443
+ "machine": lib.SQL_VSQL_MACHINE,
444
+ }
445
+ conn = Connection(":memory:")
446
+ try:
447
+ info = {name: lib.get_info(conn._dbc, code, True) for name, code in fields.items()}
448
+ # SQL_DBMS_VERSION is "01.07.0058", even if it isn't a release.
449
+ dbms_version = lib.get_info(conn._dbc, lib.SQL_DBMS_VERSION, True)
450
+ finally:
451
+ conn.close()
452
+
453
+ return tuple(int(part) for part in dbms_version.split(".")), info
454
+