-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathconnection.py
More file actions
1272 lines (1060 loc) · 39 KB
/
connection.py
File metadata and controls
1272 lines (1060 loc) · 39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""SingleStoreDB HTTP API interface."""
import datetime
import decimal
import functools
import io
import json
import math
import os
import re
import time
from base64 import b64decode
from collections.abc import Iterable
from collections.abc import Sequence
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from urllib.parse import urljoin
from urllib.parse import urlparse
import requests
try:
import numpy as np
has_numpy = True
except ImportError:
has_numpy = False
try:
import pygeos
has_pygeos = True
except ImportError:
has_pygeos = False
try:
import shapely.geometry
import shapely.wkt
has_shapely = True
except ImportError:
has_shapely = False
try:
import pydantic
has_pydantic = True
except ImportError:
has_pydantic = False
from .. import connection
from .. import fusion
from .. import types
from ..config import get_option
from ..converters import converters
from ..exceptions import DatabaseError # noqa: F401
from ..exceptions import DataError
from ..exceptions import Error # noqa: F401
from ..exceptions import IntegrityError
from ..exceptions import InterfaceError
from ..exceptions import InternalError
from ..exceptions import NotSupportedError
from ..exceptions import OperationalError
from ..exceptions import ProgrammingError
from ..exceptions import Warning # noqa: F401
from ..utils.convert_rows import convert_rows
from ..utils.debug import log_query
from ..utils.mogrify import mogrify
from ..utils.results import Description
from ..utils.results import format_results
from ..utils.results import get_schema
from ..utils.results import Result
# DB-API settings
apilevel = '2.0'
paramstyle = 'named'
threadsafety = 1
_interface_errors = set([
0,
2013, # CR_SERVER_LOST
2006, # CR_SERVER_GONE_ERROR
2012, # CR_HANDSHAKE_ERR
2004, # CR_IPSOCK_ERROR
2014, # CR_COMMANDS_OUT_OF_SYNC
])
_data_errors = set([
1406, # ER_DATA_TOO_LONG
1441, # ER_DATETIME_FUNCTION_OVERFLOW
1365, # ER_DIVISION_BY_ZERO
1230, # ER_NO_DEFAULT
1171, # ER_PRIMARY_CANT_HAVE_NULL
1264, # ER_WARN_DATA_OUT_OF_RANGE
1265, # ER_WARN_DATA_TRUNCATED
])
_programming_errors = set([
1065, # ER_EMPTY_QUERY
1179, # ER_CANT_DO_THIS_DURING_AN_TRANSACTION
1007, # ER_DB_CREATE_EXISTS
1110, # ER_FIELD_SPECIFIED_TWICE
1111, # ER_INVALID_GROUP_FUNC_USE
1082, # ER_NO_SUCH_INDEX
1741, # ER_NO_SUCH_KEY_VALUE
1146, # ER_NO_SUCH_TABLE
1449, # ER_NO_SUCH_USER
1064, # ER_PARSE_ERROR
1149, # ER_SYNTAX_ERROR
1113, # ER_TABLE_MUST_HAVE_COLUMNS
1112, # ER_UNSUPPORTED_EXTENSION
1102, # ER_WRONG_DB_NAME
1103, # ER_WRONG_TABLE_NAME
1049, # ER_BAD_DB_ERROR
1582, # ER_??? Wrong number of args
])
_integrity_errors = set([
1215, # ER_CANNOT_ADD_FOREIGN
1062, # ER_DUP_ENTRY
1169, # ER_DUP_UNIQUE
1364, # ER_NO_DEFAULT_FOR_FIELD
1216, # ER_NO_REFERENCED_ROW
1452, # ER_NO_REFERENCED_ROW_2
1217, # ER_ROW_IS_REFERENCED
1451, # ER_ROW_IS_REFERENCED_2
1460, # ER_XAER_OUTSIDE
1401, # ER_XAER_RMERR
1048, # ER_BAD_NULL_ERROR
1264, # ER_DATA_OUT_OF_RANGE
4025, # ER_CONSTRAINT_FAILED
1826, # ER_DUP_CONSTRAINT_NAME
])
def get_precision_scale(type_code: str) -> Tuple[Optional[int], Optional[int]]:
"""Parse the precision and scale from a data type."""
if '(' not in type_code:
return (None, None)
m = re.search(r'\(\s*(\d+)\s*,\s*(\d+)\s*\)', type_code)
if m:
return int(m.group(1)), int(m.group(2))
m = re.search(r'\(\s*(\d+)\s*\)', type_code)
if m:
return (int(m.group(1)), None)
raise ValueError(f'Unrecognized type code: {type_code}')
def get_exc_type(code: int) -> type:
"""Map error code to DB-API error type."""
if code in _interface_errors:
return InterfaceError
if code in _data_errors:
return DataError
if code in _programming_errors:
return ProgrammingError
if code in _integrity_errors:
return IntegrityError
if code >= 1000:
return OperationalError
return InternalError
def identity(x: Any) -> Any:
"""Return input value."""
return x
def b64decode_converter(
converter: Callable[..., Any],
x: Optional[str],
encoding: str = 'utf-8',
) -> Optional[bytes]:
"""Decode value before applying converter."""
if x is None:
return None
if converter is None:
return b64decode(x)
return converter(b64decode(x))
def encode_timedelta(obj: datetime.timedelta) -> str:
"""Encode timedelta as str."""
seconds = int(obj.seconds) % 60
minutes = int(obj.seconds // 60) % 60
hours = int(obj.seconds // 3600) % 24 + int(obj.days) * 24
if obj.microseconds:
fmt = '{0:02d}:{1:02d}:{2:02d}.{3:06d}'
else:
fmt = '{0:02d}:{1:02d}:{2:02d}'
return fmt.format(hours, minutes, seconds, obj.microseconds)
def encode_time(obj: datetime.time) -> str:
"""Encode time as str."""
if obj.microsecond:
fmt = '{0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}'
else:
fmt = '{0.hour:02}:{0.minute:02}:{0.second:02}'
return fmt.format(obj)
def encode_datetime(obj: datetime.datetime) -> str:
"""Encode datetime as str."""
if obj.microsecond:
fmt = '{0.year:04}-{0.month:02}-{0.day:02} ' \
'{0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}'
else:
fmt = '{0.year:04}-{0.month:02}-{0.day:02} ' \
'{0.hour:02}:{0.minute:02}:{0.second:02}'
return fmt.format(obj)
def encode_date(obj: datetime.date) -> str:
"""Encode date as str."""
fmt = '{0.year:04}-{0.month:02}-{0.day:02}'
return fmt.format(obj)
def encode_struct_time(obj: time.struct_time) -> str:
"""Encode time struct to str."""
return encode_datetime(datetime.datetime(*obj[:6]))
def encode_decimal(o: decimal.Decimal) -> str:
"""Encode decimal to str."""
return format(o, 'f')
# Most argument encoding is done by the JSON encoder, but these
# are exceptions to the rule.
encoders = {
datetime.datetime: encode_datetime,
datetime.date: encode_date,
datetime.time: encode_time,
datetime.timedelta: encode_timedelta,
time.struct_time: encode_struct_time,
decimal.Decimal: encode_decimal,
}
if has_shapely:
encoders[shapely.geometry.Point] = shapely.wkt.dumps
encoders[shapely.geometry.Polygon] = shapely.wkt.dumps
encoders[shapely.geometry.LineString] = shapely.wkt.dumps
if has_numpy:
def encode_ndarray(obj: np.ndarray) -> bytes: # type: ignore
"""Encode an ndarray as bytes."""
return obj.tobytes()
encoders[np.ndarray] = encode_ndarray
if has_pygeos:
encoders[pygeos.Geometry] = pygeos.io.to_wkt
def convert_special_type(
arg: Any,
nan_as_null: bool = False,
inf_as_null: bool = False,
) -> Any:
"""Convert special data type objects."""
dtype = type(arg)
if dtype is float or \
(
has_numpy and dtype in (
np.float16, np.float32, np.float64,
getattr(np, 'float128', np.float64),
)
):
if nan_as_null and math.isnan(arg):
return None
if inf_as_null and math.isinf(arg):
return None
func = encoders.get(dtype, None)
if func is not None:
return func(arg) # type: ignore
return arg
def convert_special_params(
params: Optional[Union[Sequence[Any], Dict[str, Any]]] = None,
nan_as_null: bool = False,
inf_as_null: bool = False,
) -> Optional[Union[Sequence[Any], Dict[str, Any]]]:
"""Convert parameters of special data types."""
if params is None:
return params
converter = functools.partial(
convert_special_type,
nan_as_null=nan_as_null,
inf_as_null=inf_as_null,
)
if isinstance(params, Dict):
return {k: converter(v) for k, v in params.items()}
return tuple(map(converter, params))
class PyMyField(object):
"""Field for PyMySQL compatibility."""
def __init__(self, name: str, flags: int, charset: int) -> None:
self.name = name
self.flags = flags
self.charsetnr = charset
class PyMyResult(object):
"""Result for PyMySQL compatibility."""
def __init__(self) -> None:
self.fields: List[PyMyField] = []
self.unbuffered_active = False
def append(self, item: PyMyField) -> None:
self.fields.append(item)
class Cursor(connection.Cursor):
"""
SingleStoreDB HTTP database cursor.
Cursor objects should not be created directly. They should come from
the `cursor` method on the `Connection` object.
Parameters
----------
connection : Connection
The HTTP Connection object the cursor belongs to
"""
def __init__(self, conn: 'Connection'):
connection.Cursor.__init__(self, conn)
self._connection: Optional[Connection] = conn
self._results: List[List[Tuple[Any, ...]]] = [[]]
self._results_type: str = self._connection._results_type \
if self._connection is not None else 'tuples'
self._row_idx: int = -1
self._result_idx: int = -1
self._descriptions: List[List[Description]] = []
self._schemas: List[Dict[str, Any]] = []
self.arraysize: int = get_option('results.arraysize')
self.rowcount: int = 0
self.lastrowid: Optional[int] = None
self._pymy_results: List[PyMyResult] = []
self._expect_results: bool = False
@property
def _result(self) -> Optional[PyMyResult]:
"""Return Result object for PyMySQL compatibility."""
if self._result_idx < 0:
return None
return self._pymy_results[self._result_idx]
@property
def description(self) -> Optional[List[Description]]:
"""Return description for current result set."""
if not self._descriptions:
return None
if self._result_idx >= 0 and self._result_idx < len(self._descriptions):
return self._descriptions[self._result_idx]
return None
@property
def _schema(self) -> Optional[Any]:
if not self._schemas:
return None
if self._result_idx >= 0 and self._result_idx < len(self._schemas):
return self._schemas[self._result_idx]
return None
def _post(self, path: str, *args: Any, **kwargs: Any) -> requests.Response:
"""
Invoke a POST request on the HTTP connection.
Parameters
----------
path : str
The path of the resource
*args : positional parameters, optional
Extra parameters to the POST request
**kwargs : keyword parameters, optional
Extra keyword parameters to the POST request
Returns
-------
requests.Response
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed.')
if 'timeout' not in kwargs:
kwargs['timeout'] = self._connection.connection_params['connect_timeout']
return self._connection._post(path, *args, **kwargs)
def callproc(
self, name: str,
params: Optional[Sequence[Any]] = None,
) -> None:
"""
Call a stored procedure.
Parameters
----------
name : str
Name of the stored procedure
params : sequence, optional
Parameters to the stored procedure
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed.')
name = connection._name_check(name)
if not params:
self._execute(f'CALL {name}();', is_callproc=True)
else:
keys = ', '.join(['%s' for i in range(len(params))])
self._execute(f'CALL {name}({keys});', params, is_callproc=True)
def close(self) -> None:
"""Close the cursor."""
self._connection = None
def execute(
self, query: str,
args: Optional[Union[Sequence[Any], Dict[str, Any]]] = None,
infile_stream: Optional[ # type: ignore
Union[
io.RawIOBase,
io.TextIOBase,
Iterable[Union[bytes, str]],
connection.InfileQueue,
]
] = None,
) -> int:
"""
Execute a SQL statement.
Parameters
----------
query : str
The SQL statement to execute
args : iterable or dict, optional
Parameters to substitute into the SQL code
"""
return self._execute(query, args, infile_stream=infile_stream)
def _validate_param_subs(
self, query: str,
args: Optional[Union[Sequence[Any], Dict[str, Any]]] = None,
) -> None:
"""Make sure the parameter substitions are valid."""
if args:
if isinstance(args, Sequence):
query = query % tuple(args)
else:
query = query % args
def _execute_fusion_query(
self,
oper: Union[str, bytes],
params: Optional[Union[Sequence[Any], Dict[str, Any]]] = None,
handler: Any = None,
) -> int:
oper = mogrify(oper, params)
if isinstance(oper, bytes):
oper = oper.decode('utf-8')
log_query(oper, None)
results_type = self._results_type
self._results_type = 'tuples'
try:
mgmt_res = fusion.execute(
self._connection, # type: ignore
oper,
handler=handler,
)
finally:
self._results_type = results_type
self._descriptions.append(list(mgmt_res.description))
self._schemas.append(get_schema(self._results_type, list(mgmt_res.description)))
self._results.append(list(mgmt_res.rows))
self.rowcount = len(self._results[-1])
pymy_res = PyMyResult()
for field in mgmt_res.fields:
pymy_res.append(
PyMyField(
field.name,
field.flags,
field.charsetnr,
),
)
self._pymy_results.append(pymy_res)
if self._results and self._results[0]:
self._row_idx = 0
self._result_idx = 0
return self.rowcount
def _execute(
self, oper: str,
params: Optional[Union[Sequence[Any], Dict[str, Any]]] = None,
is_callproc: bool = False,
infile_stream: Optional[ # type: ignore
Union[
io.RawIOBase,
io.TextIOBase,
Iterable[Union[bytes, str]],
connection.InfileQueue,
]
] = None,
) -> int:
self._descriptions = []
self._schemas = []
self._results = []
self._pymy_results = []
self._row_idx = -1
self._result_idx = -1
self.rowcount = 0
self._expect_results = False
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed.')
sql_type = 'exec'
if re.match(r'^\s*(select|show|call|echo|describe|with)\s+', oper, flags=re.I):
self._expect_results = True
sql_type = 'query'
if has_pydantic and isinstance(params, pydantic.BaseModel):
params = params.model_dump()
self._validate_param_subs(oper, params)
handler = fusion.get_handler(oper)
if handler is not None:
return self._execute_fusion_query(oper, params, handler=handler)
interpolate_query_with_empty_args = self._connection.connection_params.get(
'interpolate_query_with_empty_args', False,
)
oper, params = self._connection._convert_params(
oper, params, interpolate_query_with_empty_args,
)
log_query(oper, params)
data: Dict[str, Any] = dict(sql=oper)
if params is not None:
data['args'] = convert_special_params(
params,
nan_as_null=self._connection.connection_params['nan_as_null'],
inf_as_null=self._connection.connection_params['inf_as_null'],
)
if self._connection._database:
data['database'] = self._connection._database
if sql_type == 'query':
res = self._post('query/tuples', json=data)
else:
res = self._post('exec', json=data)
if res.status_code >= 400:
if res.text:
m = re.match(r'^Error\s+(\d+).*?:', res.text)
if m:
code = m.group(1)
msg = res.text.split(':', 1)[-1]
icode = int(code.split()[-1])
else:
icode = res.status_code
msg = res.text
raise get_exc_type(icode)(icode, msg.strip())
raise InterfaceError(errno=res.status_code, msg='HTTP Error')
out = json.loads(res.text)
if 'error' in out:
raise OperationalError(
errno=out['error'].get('code', 0),
msg=out['error'].get('message', 'HTTP Error'),
)
if sql_type == 'query':
# description: (name, type_code, display_size, internal_size,
# precision, scale, null_ok, column_flags, charset)
# Remove converters for things the JSON parser already converted
http_converters = dict(self._connection.decoders)
http_converters.pop(4, None)
http_converters.pop(5, None)
http_converters.pop(6, None)
http_converters.pop(15, None)
http_converters.pop(245, None)
http_converters.pop(247, None)
http_converters.pop(249, None)
http_converters.pop(250, None)
http_converters.pop(251, None)
http_converters.pop(252, None)
http_converters.pop(253, None)
http_converters.pop(254, None)
# Merge passed in converters
if self._connection._conv:
for k, v in self._connection._conv.items():
if isinstance(k, int):
http_converters[k] = v
# Make JSON a string for Arrow
if 'arrow' in self._results_type:
def json_to_str(x: Any) -> Optional[str]:
if x is None:
return None
return json.dumps(x)
http_converters[245] = json_to_str
# Don't convert date/times in polars
elif 'polars' in self._results_type:
http_converters.pop(7, None)
http_converters.pop(10, None)
http_converters.pop(12, None)
results = out['results']
# Convert data to Python types
if results and results[0]:
self._row_idx = 0
self._result_idx = 0
for result in results:
pymy_res = PyMyResult()
convs = []
description: List[Description] = []
for i, col in enumerate(result.get('columns', [])):
charset = 0
flags = 0
data_type = col['dataType'].split('(')[0]
type_code = types.ColumnType.get_code(data_type)
prec, scale = get_precision_scale(col['dataType'])
converter = http_converters.get(type_code, None)
if 'UNSIGNED' in data_type:
flags = 32
if data_type.endswith('BLOB') or data_type.endswith('BINARY'):
converter = functools.partial(
b64decode_converter, converter, # type: ignore
)
charset = 63 # BINARY
if type_code == 0: # DECIMAL
type_code = types.ColumnType.get_code('NEWDECIMAL')
elif type_code == 15: # VARCHAR / VARBINARY
type_code = types.ColumnType.get_code('VARSTRING')
if converter is not None:
convs.append((i, None, converter))
description.append(
Description(
str(col['name']), type_code,
None, None, prec, scale,
col.get('nullable', False),
flags, charset,
),
)
pymy_res.append(PyMyField(col['name'], flags, charset))
self._descriptions.append(description)
self._schemas.append(get_schema(self._results_type, description))
rows = convert_rows(result.get('rows', []), convs)
self._results.append(rows)
self._pymy_results.append(pymy_res)
# For compatibility with PyMySQL/MySQLdb
if is_callproc:
self._results.append([])
self.rowcount = len(self._results[0])
else:
# For compatibility with PyMySQL/MySQLdb
if is_callproc:
self._results.append([])
self.rowcount = out['rowsAffected']
return self.rowcount
def executemany(
self, query: str,
args: Optional[Sequence[Union[Sequence[Any], Dict[str, Any]]]] = None,
) -> int:
"""
Execute SQL code against multiple sets of parameters.
Parameters
----------
query : str
The SQL statement to execute
args : iterable of iterables or dicts, optional
Sets of parameters to substitute into the SQL code
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed.')
results = []
rowcount = 0
if args is not None and len(args) > 0:
description = []
schema = {}
# Detect dataframes
if hasattr(args, 'itertuples'):
argiter = args.itertuples(index=False) # type: ignore
else:
argiter = iter(args)
for params in argiter:
self.execute(query, params)
if self._descriptions:
description = self._descriptions[-1]
if self._schemas:
schema = self._schemas[-1]
if self._rows is not None:
results.append(self._rows)
rowcount += self.rowcount
self._results = results
self._descriptions = [description for _ in range(len(results))]
self._schemas = [schema for _ in range(len(results))]
else:
self.execute(query)
rowcount += self.rowcount
self.rowcount = rowcount
return self.rowcount
@property
def _has_row(self) -> bool:
"""Determine if a row is available."""
if self._result_idx < 0 or self._result_idx >= len(self._results):
return False
if self._row_idx < 0 or self._row_idx >= len(self._results[self._result_idx]):
return False
return True
@property
def _rows(self) -> List[Tuple[Any, ...]]:
"""Return current set of rows."""
if not self._has_row:
return []
return self._results[self._result_idx]
def fetchone(self) -> Optional[Result]:
"""
Fetch a single row from the result set.
Returns
-------
tuple
Values of the returned row if there are rows remaining
None
If there are no rows left to return
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed')
if not self._expect_results:
raise self._connection.ProgrammingError(msg='No query has been submitted')
if not self._has_row:
return None
out = self._rows[self._row_idx]
self._row_idx += 1
return format_results(
self._results_type,
self.description or [],
out, single=True,
schema=self._schema,
)
def fetchmany(
self,
size: Optional[int] = None,
) -> Result:
"""
Fetch `size` rows from the result.
If `size` is not specified, the `arraysize` attribute is used.
Returns
-------
list of tuples
Values of the returned rows if there are rows remaining
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed')
if not self._expect_results:
raise self._connection.ProgrammingError(msg='No query has been submitted')
if not self._has_row:
if 'dict' in self._results_type:
return {}
return tuple()
if not size:
size = max(int(self.arraysize), 1)
else:
size = max(int(size), 1)
out = self._rows[self._row_idx:self._row_idx+size]
self._row_idx += len(out)
return format_results(
self._results_type, self.description or [],
out, schema=self._schema,
)
def fetchall(self) -> Result:
"""
Fetch all rows in the result set.
Returns
-------
list of tuples
Values of the returned rows if there are rows remaining
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed')
if not self._expect_results:
raise self._connection.ProgrammingError(msg='No query has been submitted')
if not self._has_row:
if 'dict' in self._results_type:
return {}
return tuple()
out = list(self._rows[self._row_idx:])
self._row_idx = len(out)
return format_results(
self._results_type, self.description or [],
out, schema=self._schema,
)
def nextset(self) -> Optional[bool]:
"""Skip to the next available result set."""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed')
if self._result_idx < 0:
self._row_idx = -1
return None
self._result_idx += 1
self._row_idx = 0
if self._result_idx >= len(self._results):
self._result_idx = -1
self._row_idx = -1
return None
self.rowcount = len(self._results[self._result_idx])
return True
def setinputsizes(self, sizes: Sequence[int]) -> None:
"""Predefine memory areas for parameters."""
pass
def setoutputsize(self, size: int, column: Optional[str] = None) -> None:
"""Set a column buffer size for fetches of large columns."""
pass
@property
def rownumber(self) -> Optional[int]:
"""
Return the zero-based index of the cursor in the result set.
Returns
-------
int
"""
if self._row_idx < 0:
return None
return self._row_idx
def scroll(self, value: int, mode: str = 'relative') -> None:
"""
Scroll the cursor to the position in the result set.
Parameters
----------
value : int
Value of the positional move
mode : str
Type of move that should be made: 'relative' or 'absolute'
"""
if self._connection is None:
raise ProgrammingError(errno=2048, msg='Connection is closed')
if mode == 'relative':
self._row_idx += value
elif mode == 'absolute':
self._row_idx = value
else:
raise ValueError(
f'{mode} is not a valid mode, '
'expecting "relative" or "absolute"',
)
def next(self) -> Optional[Result]:
"""
Return the next row from the result set for use in iterators.
Returns
-------
tuple
Values from the next result row
None
If no more rows exist
"""
if self._connection is None:
raise InterfaceError(errno=2048, msg='Connection is closed')
out = self.fetchone()
if out is None:
raise StopIteration
return out
__next__ = next
def __iter__(self) -> Iterable[Tuple[Any, ...]]:
"""Return result iterator."""
return iter(self._rows[self._row_idx:])
def __enter__(self) -> 'Cursor':
"""Enter a context."""
return self
def __exit__(
self, exc_type: Optional[object],
exc_value: Optional[Exception], exc_traceback: Optional[str],
) -> None:
"""Exit a context."""
self.close()
@property
def open(self) -> bool:
"""Check if the cursor is still connected."""
if self._connection is None:
return False
return self._connection.is_connected()
def is_connected(self) -> bool:
"""
Check if the cursor is still connected.
Returns
-------
bool
"""
return self.open
class Connection(connection.Connection):
"""
SingleStoreDB HTTP database connection.
Instances of this object are typically created through the
`connection` function rather than creating them directly.
See Also
--------
`connect`
"""
driver = 'https'
paramstyle = 'qmark'
def __init__(self, **kwargs: Any):
from .. import __version__ as client_version
if 'SINGLESTOREDB_WORKLOAD_TYPE' in os.environ:
client_version += '+' + os.environ['SINGLESTOREDB_WORKLOAD_TYPE']
connection.Connection.__init__(self, **kwargs)