vsql-python 1.0.0__cp311-cp311-win_amd64.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 +181 -0
- vsql/_connection.py +358 -0
- vsql/_convert.py +184 -0
- vsql/_errors.py +102 -0
- vsql/_libvsql.c +610 -0
- vsql/_libvsql.cp311-win_amd64.pyd +0 -0
- vsql_python-1.0.0.dist-info/METADATA +156 -0
- vsql_python-1.0.0.dist-info/RECORD +13 -0
- vsql_python-1.0.0.dist-info/WHEEL +5 -0
- vsql_python-1.0.0.dist-info/licenses/LICENSE +21 -0
- vsql_python-1.0.0.dist-info/licenses/internal/amalgamation/LICENSE +21 -0
- vsql_python-1.0.0.dist-info/licenses/internal/amalgamation/LICENSE-V +21 -0
- vsql_python-1.0.0.dist-info/top_level.txt +1 -0
vsql/_convert.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
# Converting parameters to the values that _libvsql.execute binds, and the
|
|
2
|
+
# values of columns to Python.
|
|
3
|
+
|
|
4
|
+
import datetime
|
|
5
|
+
import decimal
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from . import _libvsql as lib
|
|
9
|
+
from ._errors import DataError, Error, NotSupportedError, ProgrammingError
|
|
10
|
+
|
|
11
|
+
_BIGINT_MIN, _BIGINT_MAX = -(2**63), 2**63 - 1
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def to_params(parameters):
|
|
15
|
+
"""The parameters for _libvsql.execute, from a sequence of values."""
|
|
16
|
+
|
|
17
|
+
if parameters is None:
|
|
18
|
+
return ()
|
|
19
|
+
if isinstance(parameters, dict) or hasattr(parameters, "keys"):
|
|
20
|
+
raise NotSupportedError("named parameters are not supported, use ? with a sequence")
|
|
21
|
+
if isinstance(parameters, (str, bytes)):
|
|
22
|
+
raise ProgrammingError("parameters must be a sequence, not a string")
|
|
23
|
+
|
|
24
|
+
params = []
|
|
25
|
+
for i, value in enumerate(parameters, 1):
|
|
26
|
+
try:
|
|
27
|
+
params.append(to_param(value))
|
|
28
|
+
except Error as e:
|
|
29
|
+
e.message = f"parameter {i}: {e.message}"
|
|
30
|
+
e.args = (e.message,)
|
|
31
|
+
raise
|
|
32
|
+
|
|
33
|
+
return tuple(params)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def to_param(value):
|
|
37
|
+
"""A tuple of (value_type, parameter_type, column_size, decimal_digits,
|
|
38
|
+
value) for _libvsql.execute. The value is sent as an SQL type, which is cast
|
|
39
|
+
to the type it's used as."""
|
|
40
|
+
|
|
41
|
+
# The type doesn't matter for a NULL, since it's cast to the type it's
|
|
42
|
+
# used as.
|
|
43
|
+
if value is None:
|
|
44
|
+
return (lib.SQL_CHAR, lib.SQL_VARCHAR, 1, 0, None)
|
|
45
|
+
|
|
46
|
+
# bool is an int, so it's first.
|
|
47
|
+
if isinstance(value, bool):
|
|
48
|
+
return (lib.SQL_CHAR, lib.SQL_BOOLEAN, 0, 0, b"TRUE" if value else b"FALSE")
|
|
49
|
+
|
|
50
|
+
if isinstance(value, int):
|
|
51
|
+
if _BIGINT_MIN <= value <= _BIGINT_MAX:
|
|
52
|
+
return (lib.SQL_BIGINT, lib.SQL_BIGINT, 0, 0, value)
|
|
53
|
+
return _numeric(str(value), 0)
|
|
54
|
+
|
|
55
|
+
if isinstance(value, float):
|
|
56
|
+
return (lib.SQL_DOUBLE, lib.SQL_DOUBLE, 0, 0, value)
|
|
57
|
+
|
|
58
|
+
if isinstance(value, str):
|
|
59
|
+
# A CHARACTER VARYING as long as the string (which can't be 0).
|
|
60
|
+
return (lib.SQL_CHAR, lib.SQL_VARCHAR, max(len(value), 1), 0, value.encode())
|
|
61
|
+
|
|
62
|
+
if isinstance(value, decimal.Decimal):
|
|
63
|
+
if not value.is_finite():
|
|
64
|
+
raise DataError(f"{value} isn't a finite decimal")
|
|
65
|
+
exponent = value.as_tuple().exponent
|
|
66
|
+
return _numeric(format(value, "f"), max(-exponent, 0))
|
|
67
|
+
|
|
68
|
+
# datetime is a date, so it's first.
|
|
69
|
+
if isinstance(value, datetime.datetime):
|
|
70
|
+
s = value.isoformat(sep=" ", timespec="microseconds")
|
|
71
|
+
if value.utcoffset() is None:
|
|
72
|
+
return _datetime(lib.SQL_TYPE_TIMESTAMP, s)
|
|
73
|
+
return _datetime(lib.SQL_TYPE_TIMESTAMP_WITH_TIMEZONE, s)
|
|
74
|
+
|
|
75
|
+
if isinstance(value, datetime.date):
|
|
76
|
+
return _datetime(lib.SQL_TYPE_DATE, value.isoformat())
|
|
77
|
+
|
|
78
|
+
if isinstance(value, datetime.time):
|
|
79
|
+
s = value.isoformat(timespec="microseconds")
|
|
80
|
+
if value.utcoffset() is None:
|
|
81
|
+
return _datetime(lib.SQL_TYPE_TIME, s)
|
|
82
|
+
return _datetime(lib.SQL_TYPE_TIME_WITH_TIMEZONE, s)
|
|
83
|
+
|
|
84
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
85
|
+
raise NotSupportedError("vsql doesn't have a binary type")
|
|
86
|
+
|
|
87
|
+
raise ProgrammingError(f"unsupported type {type(value).__name__}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _numeric(s, scale):
|
|
91
|
+
"""A NUMERIC with the precision of the digits in s. vsql counts at least one
|
|
92
|
+
digit before the decimal point (so 0.25 is NUMERIC(3, 2))."""
|
|
93
|
+
|
|
94
|
+
integer = s.lstrip("-").split(".")[0].lstrip("0")
|
|
95
|
+
|
|
96
|
+
return (lib.SQL_CHAR, lib.SQL_NUMERIC, max(len(integer), 1) + scale, scale, s.encode())
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _datetime(parameter_type, s):
|
|
100
|
+
"""A DATE, TIME or TIMESTAMP, with microseconds (except a DATE)."""
|
|
101
|
+
|
|
102
|
+
digits = 0 if parameter_type == lib.SQL_TYPE_DATE else 6
|
|
103
|
+
|
|
104
|
+
return (lib.SQL_CHAR, parameter_type, len(s), digits, s.encode())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# The datetimes from SQLGetData, such as "2022-01-02T15:04:05.123456+0530".
|
|
108
|
+
# There are at most 6 fractional digits.
|
|
109
|
+
_time = r"(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:([+-])(\d{2})(\d{2}))?"
|
|
110
|
+
_date_re = re.compile(r"(\d{4})-(\d{2})-(\d{2})")
|
|
111
|
+
_time_re = re.compile(_time)
|
|
112
|
+
_timestamp_re = re.compile(r"(\d{4})-(\d{2})-(\d{2})T" + _time)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _match(regex, s, type_name):
|
|
116
|
+
m = regex.fullmatch(s)
|
|
117
|
+
if m is None:
|
|
118
|
+
raise DataError(f"invalid {type_name}: {s!r}")
|
|
119
|
+
|
|
120
|
+
return m.groups()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _time_parts(hour, minute, second, fraction, sign, tz_hour, tz_minute):
|
|
124
|
+
microsecond = int(fraction.ljust(6, "0")) if fraction else 0
|
|
125
|
+
tzinfo = None
|
|
126
|
+
if sign:
|
|
127
|
+
offset = datetime.timedelta(hours=int(tz_hour), minutes=int(tz_minute))
|
|
128
|
+
tzinfo = datetime.timezone(-offset if sign == "-" else offset)
|
|
129
|
+
|
|
130
|
+
return int(hour), int(minute), int(second), microsecond, tzinfo
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def parse_date(s):
|
|
134
|
+
year, month, day = _match(_date_re, s, "DATE")
|
|
135
|
+
|
|
136
|
+
return datetime.date(int(year), int(month), int(day))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def parse_time(s):
|
|
140
|
+
hour, minute, second, microsecond, tzinfo = _time_parts(*_match(_time_re, s, "TIME"))
|
|
141
|
+
|
|
142
|
+
return datetime.time(hour, minute, second, microsecond, tzinfo)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parse_timestamp(s):
|
|
146
|
+
year, month, day, *time = _match(_timestamp_re, s, "TIMESTAMP")
|
|
147
|
+
hour, minute, second, microsecond, tzinfo = _time_parts(*time)
|
|
148
|
+
|
|
149
|
+
return datetime.datetime(int(year), int(month), int(day), hour, minute, second, microsecond,
|
|
150
|
+
tzinfo)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_booleans = {"TRUE": True, "FALSE": False}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def parse_boolean(s):
|
|
157
|
+
try:
|
|
158
|
+
return _booleans[s]
|
|
159
|
+
except KeyError:
|
|
160
|
+
raise DataError(f"invalid BOOLEAN: {s!r}") from None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# For each data type (from SQLDescribeCol): its name, how _libvsql.fetch_row
|
|
164
|
+
# reads it ('i' as an int, 'd' or 'r' as a float, 's' as a str) and the
|
|
165
|
+
# function that converts that to its Python value (None if it doesn't need to
|
|
166
|
+
# be converted).
|
|
167
|
+
types = {
|
|
168
|
+
lib.SQL_SMALLINT: ("SMALLINT", "i", None),
|
|
169
|
+
lib.SQL_INTEGER: ("INTEGER", "i", None),
|
|
170
|
+
lib.SQL_BIGINT: ("BIGINT", "i", None),
|
|
171
|
+
lib.SQL_REAL: ("REAL", "r", None),
|
|
172
|
+
lib.SQL_FLOAT: ("DOUBLE PRECISION", "d", None),
|
|
173
|
+
lib.SQL_DOUBLE: ("DOUBLE PRECISION", "d", None),
|
|
174
|
+
lib.SQL_DECIMAL: ("DECIMAL", "s", decimal.Decimal),
|
|
175
|
+
lib.SQL_NUMERIC: ("NUMERIC", "s", decimal.Decimal),
|
|
176
|
+
lib.SQL_CHAR: ("CHARACTER", "s", None),
|
|
177
|
+
lib.SQL_VARCHAR: ("CHARACTER VARYING", "s", None),
|
|
178
|
+
lib.SQL_BOOLEAN: ("BOOLEAN", "s", parse_boolean),
|
|
179
|
+
lib.SQL_TYPE_DATE: ("DATE", "s", parse_date),
|
|
180
|
+
lib.SQL_TYPE_TIME: ("TIME", "s", parse_time),
|
|
181
|
+
lib.SQL_TYPE_TIME_WITH_TIMEZONE: ("TIME WITH TIME ZONE", "s", parse_time),
|
|
182
|
+
lib.SQL_TYPE_TIMESTAMP: ("TIMESTAMP", "s", parse_timestamp),
|
|
183
|
+
lib.SQL_TYPE_TIMESTAMP_WITH_TIMEZONE: ("TIMESTAMP WITH TIME ZONE", "s", parse_timestamp),
|
|
184
|
+
}
|
vsql/_errors.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# The exceptions of PEP 249. An error from vsql is the exception for the class
|
|
2
|
+
# of its SQLSTATE (the first two characters), and has the SQLSTATE as its
|
|
3
|
+
# sqlstate attribute.
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Warning(Exception): # noqa: A001 (PEP 249 requires this name)
|
|
7
|
+
"""An important warning, such as data truncation."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Error(Exception):
|
|
11
|
+
"""The base class of every other error.
|
|
12
|
+
|
|
13
|
+
sqlstate is the SQLSTATE of an error from vsql (such as "42P01" for an
|
|
14
|
+
undefined table), or None for an error from the module itself.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, message, sqlstate=None):
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.message = message
|
|
20
|
+
self.sqlstate = sqlstate
|
|
21
|
+
|
|
22
|
+
def __str__(self):
|
|
23
|
+
if self.sqlstate is None:
|
|
24
|
+
return self.message
|
|
25
|
+
|
|
26
|
+
return f"{self.message} (SQLSTATE {self.sqlstate})"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InterfaceError(Error):
|
|
30
|
+
"""An error with the interface to vsql, rather than the database."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class DatabaseError(Error):
|
|
34
|
+
"""An error from the database."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DataError(DatabaseError):
|
|
38
|
+
"""A problem with a value, such as one that's out of range."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class OperationalError(DatabaseError):
|
|
42
|
+
"""An error with the database's operation, such as a transaction that
|
|
43
|
+
couldn't be committed."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class IntegrityError(DatabaseError):
|
|
47
|
+
"""A constraint, such as NOT NULL or a unique key, was violated."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class InternalError(DatabaseError):
|
|
51
|
+
"""The database had an internal error."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ProgrammingError(DatabaseError):
|
|
55
|
+
"""A problem with the SQL, such as a syntax error or a table that doesn't
|
|
56
|
+
exist."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class NotSupportedError(DatabaseError):
|
|
60
|
+
"""A feature that vsql doesn't support."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# The exception for each SQLSTATE class. A class that isn't here is a
|
|
64
|
+
# DatabaseError.
|
|
65
|
+
_classes = {
|
|
66
|
+
"07": ProgrammingError, # dynamic SQL error
|
|
67
|
+
"08": OperationalError, # connection exception
|
|
68
|
+
"0A": NotSupportedError, # feature not supported
|
|
69
|
+
"0B": OperationalError, # invalid transaction initiation
|
|
70
|
+
"21": ProgrammingError, # cardinality violation
|
|
71
|
+
"22": DataError, # data exception
|
|
72
|
+
"23": IntegrityError, # integrity constraint violation
|
|
73
|
+
"24": ProgrammingError, # invalid cursor state
|
|
74
|
+
"25": OperationalError, # invalid transaction state
|
|
75
|
+
"26": ProgrammingError, # invalid SQL statement name
|
|
76
|
+
"2B": ProgrammingError, # dependent privilege descriptors still exist
|
|
77
|
+
"2D": OperationalError, # invalid transaction termination
|
|
78
|
+
"34": ProgrammingError, # invalid cursor name
|
|
79
|
+
"3D": ProgrammingError, # invalid catalog name
|
|
80
|
+
"3F": ProgrammingError, # invalid schema name
|
|
81
|
+
"40": OperationalError, # transaction rollback
|
|
82
|
+
"42": ProgrammingError, # syntax error or access rule violation
|
|
83
|
+
"54": OperationalError, # program limit exceeded
|
|
84
|
+
"58": OperationalError, # system error
|
|
85
|
+
"HY": InterfaceError, # CLI-specific condition
|
|
86
|
+
"XX": InternalError, # internal error
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
# SQLSTATEs that aren't the exception for their class.
|
|
90
|
+
_states = {
|
|
91
|
+
"HY000": DatabaseError, # general error
|
|
92
|
+
"HY001": OperationalError, # memory allocation error
|
|
93
|
+
"HYC00": NotSupportedError, # optional feature not implemented
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def error(sqlstate, message):
|
|
98
|
+
"""The exception for an error from vsql."""
|
|
99
|
+
|
|
100
|
+
cls = _states.get(sqlstate) or _classes.get(sqlstate[:2], DatabaseError)
|
|
101
|
+
|
|
102
|
+
return cls(message, sqlstate)
|