-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathconnection.py
More file actions
2036 lines (1780 loc) · 71.8 KB
/
connection.py
File metadata and controls
2036 lines (1780 loc) · 71.8 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
# type: ignore
# Python implementation of the MySQL client-server protocol
# http://dev.mysql.com/doc/internals/en/client-server-protocol.html
# Error codes:
# https://dev.mysql.com/doc/refman/5.5/en/error-handling.html
import errno
import functools
import io
import os
import queue
import socket
import struct
import sys
import traceback
import warnings
from collections.abc import Iterable
from typing import Any
from typing import Dict
try:
import _singlestoredb_accel
except (ImportError, ModuleNotFoundError):
_singlestoredb_accel = None
from . import _auth
from ..utils import events
from .charset import charset_by_name, charset_by_id
from .constants import CLIENT, COMMAND, CR, ER, FIELD_TYPE, SERVER_STATUS
from . import converters
from .cursors import (
Cursor,
CursorSV,
DictCursor,
DictCursorSV,
NamedtupleCursor,
NamedtupleCursorSV,
ArrowCursor,
ArrowCursorSV,
NumpyCursor,
NumpyCursorSV,
PandasCursor,
PandasCursorSV,
PolarsCursor,
PolarsCursorSV,
SSCursor,
SSCursorSV,
SSDictCursor,
SSDictCursorSV,
SSNamedtupleCursor,
SSNamedtupleCursorSV,
SSArrowCursor,
SSArrowCursorSV,
SSNumpyCursor,
SSNumpyCursorSV,
SSPandasCursor,
SSPandasCursorSV,
SSPolarsCursor,
SSPolarsCursorSV,
)
from .optionfile import Parser
from .protocol import (
dump_packet,
MysqlPacket,
FieldDescriptorPacket,
OKPacketWrapper,
EOFPacketWrapper,
LoadLocalPacketWrapper,
)
from . import err
from ..config import get_option
from .. import fusion
from .. import connection
from ..connection import Connection as BaseConnection
from ..utils.debug import log_query
try:
import ssl
SSL_ENABLED = True
except ImportError:
ssl = None
SSL_ENABLED = False
try:
import getpass
DEFAULT_USER = getpass.getuser()
del getpass
except (ImportError, KeyError):
# KeyError occurs when there's no entry in OS database for a current user.
DEFAULT_USER = None
DEBUG = get_option('debug.connection')
TEXT_TYPES = {
FIELD_TYPE.BIT,
FIELD_TYPE.BLOB,
FIELD_TYPE.LONG_BLOB,
FIELD_TYPE.MEDIUM_BLOB,
FIELD_TYPE.STRING,
FIELD_TYPE.TINY_BLOB,
FIELD_TYPE.VAR_STRING,
FIELD_TYPE.VARCHAR,
FIELD_TYPE.GEOMETRY,
FIELD_TYPE.BSON,
FIELD_TYPE.FLOAT32_VECTOR_JSON,
FIELD_TYPE.FLOAT64_VECTOR_JSON,
FIELD_TYPE.INT8_VECTOR_JSON,
FIELD_TYPE.INT16_VECTOR_JSON,
FIELD_TYPE.INT32_VECTOR_JSON,
FIELD_TYPE.INT64_VECTOR_JSON,
FIELD_TYPE.FLOAT16_VECTOR_JSON,
FIELD_TYPE.FLOAT32_VECTOR,
FIELD_TYPE.FLOAT64_VECTOR,
FIELD_TYPE.INT8_VECTOR,
FIELD_TYPE.INT16_VECTOR,
FIELD_TYPE.INT32_VECTOR,
FIELD_TYPE.INT64_VECTOR,
FIELD_TYPE.FLOAT16_VECTOR,
}
UNSET = 'unset'
DEFAULT_CHARSET = 'utf8mb4'
MAX_PACKET_LEN = 2**24 - 1
def _pack_int24(n):
return struct.pack('<I', n)[:3]
# https://dev.mysql.com/doc/internals/en/integer.html#packet-Protocol::LengthEncodedInteger
def _lenenc_int(i):
if i < 0:
raise ValueError(
'Encoding %d is less than 0 - no representation in LengthEncodedInteger' % i,
)
elif i < 0xFB:
return bytes([i])
elif i < (1 << 16):
return b'\xfc' + struct.pack('<H', i)
elif i < (1 << 24):
return b'\xfd' + struct.pack('<I', i)[:3]
elif i < (1 << 64):
return b'\xfe' + struct.pack('<Q', i)
else:
raise ValueError(
'Encoding %x is larger than %x - no representation in LengthEncodedInteger'
% (i, (1 << 64)),
)
class Connection(BaseConnection):
"""
Representation of a socket with a mysql server.
The proper way to get an instance of this class is to call
``connect()``.
Establish a connection to the SingleStoreDB database.
Parameters
----------
host : str, optional
Host where the database server is located.
user : str, optional
Username to log in as.
password : str, optional
Password to use.
database : str, optional
Database to use, None to not use a particular one.
port : int, optional
Server port to use, default is usually OK. (default: 3306)
bind_address : str, optional
When the client has multiple network interfaces, specify
the interface from which to connect to the host. Argument can be
a hostname or an IP address.
unix_socket : str, optional
Use a unix socket rather than TCP/IP.
read_timeout : int, optional
The timeout for reading from the connection in seconds
(default: None - no timeout)
write_timeout : int, optional
The timeout for writing to the connection in seconds
(default: None - no timeout)
charset : str, optional
Charset to use.
collation : str, optional
The charset collation
sql_mode : str, optional
Default SQL_MODE to use.
read_default_file : str, optional
Specifies my.cnf file to read these parameters from under the
[client] section.
conv : Dict[str, Callable[Any]], optional
Conversion dictionary to use instead of the default one.
This is used to provide custom marshalling and unmarshalling of types.
See converters.
use_unicode : bool, optional
Whether or not to default to unicode strings.
This option defaults to true.
client_flag : int, optional
Custom flags to send to MySQL. Find potential values in constants.CLIENT.
cursorclass : type, optional
Custom cursor class to use.
init_command : str, optional
Initial SQL statement to run when connection is established.
connect_timeout : int, optional
The timeout for connecting to the database in seconds.
(default: 10, min: 1, max: 31536000)
ssl : Dict[str, str], optional
A dict of arguments similar to mysql_ssl_set()'s parameters or
an ssl.SSLContext.
ssl_ca : str, optional
Path to the file that contains a PEM-formatted CA certificate.
ssl_cert : str, optional
Path to the file that contains a PEM-formatted client certificate.
ssl_cipher : str, optional
SSL ciphers to allow.
ssl_disabled : bool, optional
A boolean value that disables usage of TLS.
ssl_key : str, optional
Path to the file that contains a PEM-formatted private key for the
client certificate.
ssl_verify_cert : str, optional
Set to true to check the server certificate's validity.
ssl_verify_identity : bool, optional
Set to true to check the server's identity.
tls_sni_servername: str, optional
Set server host name for TLS connection
read_default_group : str, optional
Group to read from in the configuration file.
autocommit : bool, optional
Autocommit mode. None means use server default. (default: False)
local_infile : bool, optional
Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
max_allowed_packet : int, optional
Max size of packet sent to server in bytes. (default: 16MB)
Only used to limit size of "LOAD LOCAL INFILE" data packet smaller
than default (16KB).
defer_connect : bool, optional
Don't explicitly connect on construction - wait for connect call.
(default: False)
auth_plugin_map : Dict[str, type], optional
A dict of plugin names to a class that processes that plugin.
The class will take the Connection object as the argument to the
constructor. The class needs an authenticate method taking an
authentication packet as an argument. For the dialog plugin, a
prompt(echo, prompt) method can be used (if no authenticate method)
for returning a string from the user. (experimental)
server_public_key : str, optional
SHA256 authentication plugin public key value. (default: None)
binary_prefix : bool, optional
Add _binary prefix on bytes and bytearray. (default: False)
compress :
Not supported.
named_pipe :
Not supported.
db : str, optional
**DEPRECATED** Alias for database.
passwd : str, optional
**DEPRECATED** Alias for password.
parse_json : bool, optional
Parse JSON values into Python objects?
invalid_values : Dict[int, Any], optional
Dictionary of values to use in place of invalid values
found during conversion of data. The default is to return the byte content
containing the invalid value. The keys are the integers associtated with
the column type.
pure_python : bool, optional
Should we ignore the C extension even if it's available?
This can be given explicitly using True or False, or if the value is None,
the C extension will be loaded if it is available. If set to False and
the C extension can't be loaded, a NotSupportedError is raised.
nan_as_null : bool, optional
Should NaN values be treated as NULLs in parameter substitution including
uploading data?
inf_as_null : bool, optional
Should Inf values be treated as NULLs in parameter substitution including
uploading data?
track_env : bool, optional
Should the connection track the SINGLESTOREDB_URL environment variable?
enable_extended_data_types : bool, optional
Should extended data types (BSON, vector) be enabled?
vector_data_format : str, optional
Specify the data type of vector values: json or binary
See `Connection <https://www.python.org/dev/peps/pep-0249/#connection-objects>`_
in the specification.
"""
driver = 'mysql'
paramstyle = 'pyformat'
_sock = None
_auth_plugin_name = ''
_closed = False
_secure = False
_tls_sni_servername = None
def __init__( # noqa: C901
self,
*,
user=None, # The first four arguments is based on DB-API 2.0 recommendation.
password='',
host=None,
database=None,
unix_socket=None,
port=0,
charset='',
collation=None,
sql_mode=None,
read_default_file=None,
conv=None,
use_unicode=True,
client_flag=0,
cursorclass=None,
init_command=None,
connect_timeout=10,
read_default_group=None,
autocommit=False,
local_infile=False,
max_allowed_packet=16 * 1024 * 1024,
defer_connect=False,
auth_plugin_map=None,
read_timeout=None,
write_timeout=None,
bind_address=None,
binary_prefix=False,
program_name=None,
server_public_key=None,
ssl=None,
ssl_ca=None,
ssl_cert=None,
ssl_cipher=None,
ssl_disabled=None,
ssl_key=None,
ssl_verify_cert=None,
ssl_verify_identity=None,
tls_sni_servername=None,
parse_json=True,
invalid_values=None,
pure_python=None,
buffered=True,
results_type='tuples',
compress=None, # not supported
named_pipe=None, # not supported
passwd=None, # deprecated
db=None, # deprecated
driver=None, # internal use
conn_attrs=None,
multi_statements=None,
client_found_rows=None,
nan_as_null=None,
inf_as_null=None,
encoding_errors='strict',
track_env=False,
enable_extended_data_types=True,
vector_data_format='binary',
interpolate_query_with_empty_args=None,
):
BaseConnection.__init__(**dict(locals()))
if db is not None and database is None:
# We will raise warning in 2022 or later.
# See https://github.com/PyMySQL/PyMySQL/issues/939
# warnings.warn("'db' is deprecated, use 'database'", DeprecationWarning, 3)
database = db
if passwd is not None and not password:
# We will raise warning in 2022 or later.
# See https://github.com/PyMySQL/PyMySQL/issues/939
# warnings.warn(
# "'passwd' is deprecated, use 'password'", DeprecationWarning, 3
# )
password = passwd
if compress or named_pipe:
raise NotImplementedError(
'compress and named_pipe arguments are not supported',
)
self._local_infile = bool(local_infile)
self._local_infile_stream = None
if self._local_infile:
client_flag |= CLIENT.LOCAL_FILES
if multi_statements:
client_flag |= CLIENT.MULTI_STATEMENTS
if client_found_rows:
client_flag |= CLIENT.FOUND_ROWS
if read_default_group and not read_default_file:
if sys.platform.startswith('win'):
read_default_file = 'c:\\my.ini'
else:
read_default_file = '/etc/my.cnf'
if read_default_file:
if not read_default_group:
read_default_group = 'client'
cfg = Parser()
cfg.read(os.path.expanduser(read_default_file))
def _config(key, arg):
if arg:
return arg
try:
return cfg.get(read_default_group, key)
except Exception:
return arg
user = _config('user', user)
password = _config('password', password)
host = _config('host', host)
database = _config('database', database)
unix_socket = _config('socket', unix_socket)
port = int(_config('port', port))
bind_address = _config('bind-address', bind_address)
charset = _config('default-character-set', charset)
if not ssl:
ssl = {}
if isinstance(ssl, dict):
for key in ['ca', 'capath', 'cert', 'key', 'cipher']:
value = _config('ssl-' + key, ssl.get(key))
if value:
ssl[key] = value
self.ssl = False
if not ssl_disabled:
if ssl_ca or ssl_cert or ssl_key or ssl_cipher or \
ssl_verify_cert or ssl_verify_identity:
ssl = {
'ca': ssl_ca,
'check_hostname': bool(ssl_verify_identity),
'verify_mode': ssl_verify_cert
if ssl_verify_cert is not None
else False,
}
if ssl_cert is not None:
ssl['cert'] = ssl_cert
if ssl_key is not None:
ssl['key'] = ssl_key
if ssl_cipher is not None:
ssl['cipher'] = ssl_cipher
if ssl:
if not SSL_ENABLED:
raise NotImplementedError('ssl module not found')
self.ssl = True
client_flag |= CLIENT.SSL
self.ctx = self._create_ssl_ctx(ssl)
self.host = host or 'localhost'
self.port = port or 3306
if type(self.port) is not int:
raise ValueError('port should be of type int')
self.user = user or DEFAULT_USER
self.password = password or b''
if isinstance(self.password, str):
self.password = self.password.encode('latin1')
self.db = database
self.unix_socket = unix_socket
self.bind_address = bind_address
if not (0 < connect_timeout <= 31536000):
raise ValueError('connect_timeout should be >0 and <=31536000')
self.connect_timeout = connect_timeout or None
if read_timeout is not None and read_timeout <= 0:
raise ValueError('read_timeout should be > 0')
self._read_timeout = read_timeout
if write_timeout is not None and write_timeout <= 0:
raise ValueError('write_timeout should be > 0')
self._write_timeout = write_timeout
self.charset = charset or DEFAULT_CHARSET
self.collation = collation
self.use_unicode = use_unicode
self.encoding_errors = encoding_errors
self.encoding = charset_by_name(self.charset).encoding
client_flag |= CLIENT.CAPABILITIES
client_flag |= CLIENT.CONNECT_WITH_DB
self.client_flag = client_flag
self.pure_python = pure_python
self.results_type = results_type
self.resultclass = MySQLResult
if cursorclass is not None:
self.cursorclass = cursorclass
elif buffered:
if 'dict' in self.results_type:
self.cursorclass = DictCursor
elif 'namedtuple' in self.results_type:
self.cursorclass = NamedtupleCursor
elif 'numpy' in self.results_type:
self.cursorclass = NumpyCursor
elif 'arrow' in self.results_type:
self.cursorclass = ArrowCursor
elif 'pandas' in self.results_type:
self.cursorclass = PandasCursor
elif 'polars' in self.results_type:
self.cursorclass = PolarsCursor
else:
self.cursorclass = Cursor
else:
if 'dict' in self.results_type:
self.cursorclass = SSDictCursor
elif 'namedtuple' in self.results_type:
self.cursorclass = SSNamedtupleCursor
elif 'numpy' in self.results_type:
self.cursorclass = SSNumpyCursor
elif 'arrow' in self.results_type:
self.cursorclass = SSArrowCursor
elif 'pandas' in self.results_type:
self.cursorclass = SSPandasCursor
elif 'polars' in self.results_type:
self.cursorclass = SSPolarsCursor
else:
self.cursorclass = SSCursor
if self.pure_python is False and _singlestoredb_accel is None:
try:
import _singlestortedb_accel # noqa: F401
except Exception:
import traceback
traceback.print_exc(file=sys.stderr)
finally:
raise err.NotSupportedError(
'pure_python=False, but the '
'C extension can not be loaded',
)
if self.pure_python is True:
pass
# The C extension handles these types internally.
elif _singlestoredb_accel is not None:
self.resultclass = MySQLResultSV
if self.cursorclass is Cursor:
self.cursorclass = CursorSV
elif self.cursorclass is SSCursor:
self.cursorclass = SSCursorSV
elif self.cursorclass is DictCursor:
self.cursorclass = DictCursorSV
self.results_type = 'dicts'
elif self.cursorclass is SSDictCursor:
self.cursorclass = SSDictCursorSV
self.results_type = 'dicts'
elif self.cursorclass is NamedtupleCursor:
self.cursorclass = NamedtupleCursorSV
self.results_type = 'namedtuples'
elif self.cursorclass is SSNamedtupleCursor:
self.cursorclass = SSNamedtupleCursorSV
self.results_type = 'namedtuples'
elif self.cursorclass is NumpyCursor:
self.cursorclass = NumpyCursorSV
self.results_type = 'numpy'
elif self.cursorclass is SSNumpyCursor:
self.cursorclass = SSNumpyCursorSV
self.results_type = 'numpy'
elif self.cursorclass is ArrowCursor:
self.cursorclass = ArrowCursorSV
self.results_type = 'arrow'
elif self.cursorclass is SSArrowCursor:
self.cursorclass = SSArrowCursorSV
self.results_type = 'arrow'
elif self.cursorclass is PandasCursor:
self.cursorclass = PandasCursorSV
self.results_type = 'pandas'
elif self.cursorclass is SSPandasCursor:
self.cursorclass = SSPandasCursorSV
self.results_type = 'pandas'
elif self.cursorclass is PolarsCursor:
self.cursorclass = PolarsCursorSV
self.results_type = 'polars'
elif self.cursorclass is SSPolarsCursor:
self.cursorclass = SSPolarsCursorSV
self.results_type = 'polars'
self._result = None
self._affected_rows = 0
self.host_info = 'Not connected'
# specified autocommit mode. None means use server default.
self.autocommit_mode = autocommit
if conv is None:
conv = converters.conversions
conv = conv.copy()
self.parse_json = parse_json
self.invalid_values = (invalid_values or {}).copy()
# Disable JSON parsing for Arrow
if self.results_type in ['arrow']:
conv[245] = None
self.parse_json = False
# Disable date/time parsing for polars; let polars do the parsing
elif self.results_type in ['polars']:
conv[7] = None
conv[10] = None
conv[12] = None
# Need for MySQLdb compatibility.
self.encoders = {k: v for (k, v) in conv.items() if type(k) is not int}
self.decoders = {k: v for (k, v) in conv.items() if type(k) is int}
self.sql_mode = sql_mode
self.init_command = init_command
self.max_allowed_packet = max_allowed_packet
self._auth_plugin_map = auth_plugin_map or {}
self._binary_prefix = binary_prefix
self.server_public_key = server_public_key
self.interpolate_query_with_empty_args = interpolate_query_with_empty_args
if self.connection_params['nan_as_null'] or \
self.connection_params['inf_as_null']:
float_encoder = self.encoders.get(float)
if float_encoder is not None:
self.encoders[float] = functools.partial(
float_encoder,
nan_as_null=self.connection_params['nan_as_null'],
inf_as_null=self.connection_params['inf_as_null'],
)
from .. import __version__ as VERSION_STRING
if 'SINGLESTOREDB_WORKLOAD_TYPE' in os.environ:
VERSION_STRING += '+' + os.environ['SINGLESTOREDB_WORKLOAD_TYPE']
self._connect_attrs = {
'_os': str(sys.platform),
'_pid': str(os.getpid()),
'_client_name': 'SingleStoreDB Python Client',
'_client_version': VERSION_STRING,
}
if program_name:
self._connect_attrs['program_name'] = program_name
if conn_attrs is not None:
# do not overwrite the attributes that we set ourselves
for k, v in conn_attrs.items():
if k not in self._connect_attrs:
self._connect_attrs[k] = v
self._is_committable = True
self._in_sync = False
self._tls_sni_servername = tls_sni_servername
self._track_env = bool(track_env) or self.host == 'singlestore.com'
self._enable_extended_data_types = enable_extended_data_types
if vector_data_format.lower() in ['json', 'binary']:
self._vector_data_format = vector_data_format
else:
raise ValueError(
'unknown value for vector_data_format, '
f'expecting "json" or "binary": {vector_data_format}',
)
self._connection_info = {}
events.subscribe(self._handle_event)
if defer_connect or self._track_env:
self._sock = None
else:
self.connect()
def _handle_event(self, data: Dict[str, Any]) -> None:
if data.get('name', '') == 'singlestore.portal.connection_updated':
self._connection_info = dict(data)
@property
def messages(self):
# TODO
[]
def __enter__(self):
return self
def __exit__(self, *exc_info):
del exc_info
self.close()
def _raise_mysql_exception(self, data):
err.raise_mysql_exception(data)
def _create_ssl_ctx(self, sslp):
if isinstance(sslp, ssl.SSLContext):
return sslp
ca = sslp.get('ca')
capath = sslp.get('capath')
hasnoca = ca is None and capath is None
ctx = ssl.create_default_context(cafile=ca, capath=capath)
ctx.check_hostname = not hasnoca and sslp.get('check_hostname', True)
verify_mode_value = sslp.get('verify_mode')
if verify_mode_value is None:
ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
elif isinstance(verify_mode_value, bool):
ctx.verify_mode = ssl.CERT_REQUIRED if verify_mode_value else ssl.CERT_NONE
else:
if isinstance(verify_mode_value, str):
verify_mode_value = verify_mode_value.lower()
if verify_mode_value in ('none', '0', 'false', 'no'):
ctx.verify_mode = ssl.CERT_NONE
elif verify_mode_value == 'optional':
ctx.verify_mode = ssl.CERT_OPTIONAL
elif verify_mode_value in ('required', '1', 'true', 'yes'):
ctx.verify_mode = ssl.CERT_REQUIRED
else:
ctx.verify_mode = ssl.CERT_NONE if hasnoca else ssl.CERT_REQUIRED
if 'cert' in sslp:
ctx.load_cert_chain(sslp['cert'], keyfile=sslp.get('key'))
if 'cipher' in sslp:
ctx.set_ciphers(sslp['cipher'])
ctx.options |= ssl.OP_NO_SSLv2
ctx.options |= ssl.OP_NO_SSLv3
return ctx
def close(self):
"""
Send the quit message and close the socket.
See `Connection.close()
<https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
in the specification.
Raises
------
Error : If the connection is already closed.
"""
self._result = None
if self.host == 'singlestore.com':
return
if self._closed:
raise err.Error('Already closed')
events.unsubscribe(self._handle_event)
self._closed = True
if self._sock is None:
return
send_data = struct.pack('<iB', 1, COMMAND.COM_QUIT)
try:
self._write_bytes(send_data)
except Exception:
pass
finally:
self._force_close()
@property
def open(self):
"""Return True if the connection is open."""
return self._sock is not None
def is_connected(self):
"""Return True if the connection is open."""
return self.open
def _force_close(self):
"""Close connection without QUIT message."""
if self._sock:
try:
self._sock.close()
except: # noqa
pass
self._sock = None
self._rfile = None
__del__ = _force_close
def autocommit(self, value):
"""Enable autocommit in the server."""
self.autocommit_mode = bool(value)
current = self.get_autocommit()
if value != current:
self._send_autocommit_mode()
def get_autocommit(self):
"""Retrieve autocommit status."""
return bool(self.server_status & SERVER_STATUS.SERVER_STATUS_AUTOCOMMIT)
def _read_ok_packet(self):
pkt = self._read_packet()
if not pkt.is_ok_packet():
raise err.OperationalError(
CR.CR_COMMANDS_OUT_OF_SYNC,
'Command Out of Sync',
)
ok = OKPacketWrapper(pkt)
self.server_status = ok.server_status
return ok
def _send_autocommit_mode(self):
"""Set whether or not to commit after every execute()."""
log_query('SET AUTOCOMMIT = %s' % self.escape(self.autocommit_mode))
self._execute_command(
COMMAND.COM_QUERY, 'SET AUTOCOMMIT = %s' % self.escape(self.autocommit_mode),
)
self._read_ok_packet()
def begin(self):
"""Begin transaction."""
log_query('BEGIN')
if self.host == 'singlestore.com':
return
self._execute_command(COMMAND.COM_QUERY, 'BEGIN')
self._read_ok_packet()
def commit(self):
"""
Commit changes to stable storage.
See `Connection.commit() <https://www.python.org/dev/peps/pep-0249/#commit>`_
in the specification.
"""
log_query('COMMIT')
if not self._is_committable or self.host == 'singlestore.com':
self._is_committable = True
return
self._execute_command(COMMAND.COM_QUERY, 'COMMIT')
self._read_ok_packet()
def rollback(self):
"""
Roll back the current transaction.
See `Connection.rollback() <https://www.python.org/dev/peps/pep-0249/#rollback>`_
in the specification.
"""
log_query('ROLLBACK')
if not self._is_committable or self.host == 'singlestore.com':
self._is_committable = True
return
self._execute_command(COMMAND.COM_QUERY, 'ROLLBACK')
self._read_ok_packet()
def show_warnings(self):
"""Send the "SHOW WARNINGS" SQL command."""
log_query('SHOW WARNINGS')
self._execute_command(COMMAND.COM_QUERY, 'SHOW WARNINGS')
result = self.resultclass(self)
result.read()
return result.rows
def select_db(self, db):
"""
Set current db.
db : str
The name of the db.
"""
self._execute_command(COMMAND.COM_INIT_DB, db)
self._read_ok_packet()
def escape(self, obj, mapping=None):
"""
Escape whatever value is passed.
Non-standard, for internal use; do not use this in your applications.
"""
dtype = type(obj)
if dtype is str or isinstance(obj, str):
return "'{}'".format(self.escape_string(obj))
if dtype is bytes or dtype is bytearray or isinstance(obj, (bytes, bytearray)):
return self._quote_bytes(obj)
if mapping is None:
mapping = self.encoders
return converters.escape_item(obj, self.charset, mapping=mapping)
def literal(self, obj):
"""
Alias for escape().
Non-standard, for internal use; do not use this in your applications.
"""
return self.escape(obj, self.encoders)
def escape_string(self, s):
"""Escape a string value."""
if self.server_status & SERVER_STATUS.SERVER_STATUS_NO_BACKSLASH_ESCAPES:
return s.replace("'", "''")
return converters.escape_string(s)
def _quote_bytes(self, s):
if self.server_status & SERVER_STATUS.SERVER_STATUS_NO_BACKSLASH_ESCAPES:
if self._binary_prefix:
return "_binary X'{}'".format(s.hex())
return "X'{}'".format(s.hex())
return converters.escape_bytes(s)
def cursor(self):
"""Create a new cursor to execute queries with."""
return self.cursorclass(self)
# The following methods are INTERNAL USE ONLY (called from Cursor)
def query(self, sql, unbuffered=False, infile_stream=None):
"""
Run a query on the server.
Internal use only.
"""
# if DEBUG:
# print("DEBUG: sending query:", sql)
handler = fusion.get_handler(sql)
if handler is not None:
self._is_committable = False
self._result = fusion.execute(self, sql, handler=handler)
self._affected_rows = self._result.affected_rows
else:
self._is_committable = True
if isinstance(sql, str):
sql = sql.encode(self.encoding, 'surrogateescape')
self._local_infile_stream = infile_stream
self._execute_command(COMMAND.COM_QUERY, sql)
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
self._local_infile_stream = None
return self._affected_rows
def next_result(self, unbuffered=False):
"""
Retrieve the next result set.
Internal use only.
"""
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
return self._affected_rows
def affected_rows(self):
"""
Return number of affected rows.
Internal use only.
"""
return self._affected_rows
def kill(self, thread_id):
"""
Execute kill command.
Internal use only.
"""
arg = struct.pack('<I', thread_id)
self._execute_command(COMMAND.COM_PROCESS_KILL, arg)
return self._read_ok_packet()
def ping(self, reconnect=True):
"""
Check if the server is alive.
Parameters
----------
reconnect : bool, optional
If the connection is closed, reconnect.
Raises
------
Error : If the connection is closed and reconnect=False.
"""
if self._sock is None:
if reconnect:
self.connect()
reconnect = False
else:
raise err.Error('Already closed')
try:
self._execute_command(COMMAND.COM_PING, '')
self._read_ok_packet()
except Exception:
if reconnect:
self.connect()
self.ping(False)
else:
raise
def set_charset(self, charset):
"""Deprecated. Use set_character_set() instead."""
# This function has been implemented in old PyMySQL.
# But this name is different from MySQLdb.
# So we keep this function for compatibility and add
# new set_character_set() function.
self.set_character_set(charset)
def set_character_set(self, charset, collation=None):
"""
Set charaset (and collation) on the server.
Send "SET NAMES charset [COLLATE collation]" query.
Update Connection.encoding based on charset.