-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathconnection.py
More file actions
1533 lines (1235 loc) · 46.8 KB
/
connection.py
File metadata and controls
1533 lines (1235 loc) · 46.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
#!/usr/bin/env python
"""SingleStoreDB connections and cursors."""
import abc
import functools
import inspect
import io
import queue
import re
import sys
import warnings
import weakref
from collections.abc import Iterator
from collections.abc import Mapping
from collections.abc import MutableMapping
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 parse_qs
from urllib.parse import unquote_plus
from urllib.parse import urlparse
import sqlparams
from . import auth
from . import exceptions
from .config import get_option
from .utils.results import Description
from .utils.results import Result
if sys.version_info < (3, 10):
InfileQueue = queue.Queue
else:
InfileQueue = queue.Queue[Union[bytes, str]]
# DB-API settings
apilevel = '2.0'
threadsafety = 1
paramstyle = map_paramstyle = 'pyformat'
positional_paramstyle = 'format'
# Type codes for character-based columns
CHAR_COLUMNS = set(list(range(247, 256)) + [245])
def under2camel(s: str) -> str:
"""Format underscore-delimited strings to camel-case."""
def upper_mid(m: Any) -> str:
"""Uppercase middle group of matches."""
return m.group(1) + m.group(2).upper() + m.group(3)
def upper(m: Any) -> str:
"""Uppercase match."""
return m.group(1).upper()
s = re.sub(r'(\b|_)(xml|sql|json)(\b|_)', upper_mid, s, flags=re.I)
s = re.sub(r'(?:^|_+)(\w)', upper, s)
s = re.sub(r'_+$', r'', s)
return s
def nested_converter(
conv: Callable[[Any], Any],
inner: Callable[[Any], Any],
) -> Callable[[Any], Any]:
"""Create a pipeline of two functions."""
def converter(value: Any) -> Any:
return conv(inner(value))
return converter
def cast_bool_param(val: Any) -> bool:
"""Cast value to a bool."""
if val is None or val is False:
return False
if val is True:
return True
# Test ints
try:
ival = int(val)
if ival == 1:
return True
if ival == 0:
return False
except Exception:
pass
# Lowercase strings
if hasattr(val, 'lower'):
if val.lower() in ['on', 't', 'true', 'y', 'yes', 'enabled', 'enable']:
return True
elif val.lower() in ['off', 'f', 'false', 'n', 'no', 'disabled', 'disable']:
return False
raise ValueError('Unrecognized value for bool: {}'.format(val))
def build_params(**kwargs: Any) -> Dict[str, Any]:
"""
Construct connection parameters from given URL and arbitrary parameters.
Parameters
----------
**kwargs : keyword-parameters, optional
Arbitrary keyword parameters corresponding to connection parameters
Returns
-------
dict
"""
out: Dict[str, Any] = {}
kwargs = {k: v for k, v in kwargs.items() if v is not None}
# Set known parameters
for name in inspect.getfullargspec(connect).args:
if name == 'conv':
out[name] = kwargs.get(name, None)
elif name == 'results_format': # deprecated
if kwargs.get(name, None) is not None:
warnings.warn(
'The `results_format=` parameter has been '
'renamed to `results_type=`.',
DeprecationWarning,
)
out['results_type'] = kwargs.get(name, get_option('results.type'))
elif name == 'results_type':
out[name] = kwargs.get(name, get_option('results.type'))
else:
out[name] = kwargs.get(name, get_option(name))
# See if host actually contains a URL; definitely not a perfect test.
host = out['host']
if host and (':' in host or '/' in host or '@' in host or '?' in host):
urlp = _parse_url(host)
if 'driver' not in urlp:
urlp['driver'] = get_option('driver')
out.update(urlp)
out = _cast_params(out)
# Set default port based on driver.
if 'port' not in out or not out['port']:
if out['driver'] == 'http':
out['port'] = int(get_option('http_port') or 80)
elif out['driver'] == 'https':
out['port'] = int(get_option('http_port') or 443)
else:
out['port'] = int(get_option('port') or 3306)
# If there is no user and the password is empty, remove the password key.
if 'user' not in out and not out.get('password', None):
out.pop('password', None)
if out.get('ssl_ca', '') and not out.get('ssl_verify_cert', None):
out['ssl_verify_cert'] = True
return out
def _get_param_types(func: Any) -> Dict[str, Any]:
"""
Retrieve the types for the parameters to the given function.
Note that if a parameter has multiple possible types, only the
first one is returned.
Parameters
----------
func : callable
Callable object to inspect the parameters of
Returns
-------
dict
"""
out = {}
args = inspect.getfullargspec(func)
for name in args.args:
ann = args.annotations[name]
if isinstance(ann, str):
ann = eval(ann)
if hasattr(ann, '__args__'):
out[name] = ann.__args__[0]
else:
out[name] = ann
return out
def _cast_params(params: Dict[str, Any]) -> Dict[str, Any]:
"""
Cast known keys to appropriate values.
Parameters
----------
params : dict
Dictionary of connection parameters
Returns
-------
dict
"""
param_types = _get_param_types(connect)
out = {}
for key, val in params.items():
key = key.lower()
if val is None:
continue
if key not in param_types:
raise ValueError('Unrecognized connection parameter: {}'.format(key))
dtype = param_types[key]
if dtype is bool:
val = cast_bool_param(val)
elif getattr(dtype, '_name', '') in ['Dict', 'Mapping'] or \
str(dtype).startswith('typing.Dict'):
val = dict(val)
elif getattr(dtype, '_name', '') == 'List':
val = list(val)
elif getattr(dtype, '_name', '') == 'Tuple':
val = tuple(val)
else:
val = dtype(val)
out[key] = val
return out
def _parse_url(url: str) -> Dict[str, Any]:
"""
Parse a connection URL and return only the defined parts.
Parameters
----------
url : str
The URL passed in can be a full URL or a partial URL. At a minimum,
a host name must be specified. All other parts are optional.
Returns
-------
dict
"""
out: Dict[str, Any] = {}
if '//' not in url:
url = '//' + url
if url.startswith('singlestoredb+'):
url = re.sub(r'^singlestoredb\+', r'', url)
parts = urlparse(url, scheme='singlestoredb', allow_fragments=True)
url_db = parts.path
if url_db.startswith('/'):
url_db = url_db.split('/')[1].strip()
url_db = url_db.split('/')[0].strip() or ''
# Retrieve basic connection parameters
out['host'] = parts.hostname or None
out['port'] = parts.port or None
out['database'] = url_db or None
out['user'] = parts.username or None
# Allow an empty string for password
if out['user'] and parts.password is not None:
out['password'] = parts.password
if parts.scheme != 'singlestoredb':
out['driver'] = parts.scheme.lower()
if out.get('user'):
out['user'] = unquote_plus(out['user'])
if out.get('password'):
out['password'] = unquote_plus(out['password'])
if out.get('database'):
out['database'] = unquote_plus(out['database'])
# Convert query string to parameters
out.update({k.lower(): v[-1] for k, v in parse_qs(parts.query).items()})
return {k: v for k, v in out.items() if v is not None}
def _name_check(name: str) -> str:
"""
Make sure the given name is a legal variable name.
Parameters
----------
name : str
Name to check
Returns
-------
str
"""
name = name.strip()
if not re.match(r'^[A-Za-z_][\w+_]*$', name):
raise ValueError('Name contains invalid characters')
return name
def quote_identifier(name: str) -> str:
"""Escape identifier value."""
return f'`{name}`'
class Driver(object):
"""Compatibility class for driver name."""
def __init__(self, name: str):
self.name = name
class VariableAccessor(MutableMapping): # type: ignore
"""Variable accessor class."""
def __init__(self, conn: 'Connection', vtype: str):
object.__setattr__(self, 'connection', weakref.proxy(conn))
object.__setattr__(self, 'vtype', vtype.lower())
if self.vtype not in [
'global', 'local', '',
'cluster', 'cluster global', 'cluster local',
]:
raise ValueError(
'Variable type must be global, local, cluster, '
'cluster global, cluster local, or empty',
)
def _cast_value(self, value: Any) -> Any:
if isinstance(value, str):
if value.lower() in ['on', 'true']:
return True
if value.lower() in ['off', 'false']:
return False
return value
def __getitem__(self, name: str) -> Any:
name = _name_check(name)
out = self.connection._iquery(
'show {} variables like %s;'.format(self.vtype),
[name],
)
if not out:
raise KeyError(f"No variable found with the name '{name}'.")
if len(out) > 1:
raise KeyError(f"Multiple variables found with the name '{name}'.")
return self._cast_value(out[0]['Value'])
def __setitem__(self, name: str, value: Any) -> None:
name = _name_check(name)
if value is True:
value = 'ON'
elif value is False:
value = 'OFF'
if 'local' in self.vtype:
self.connection._iquery(
'set {} {}=%s;'.format(
self.vtype.replace('local', 'session'), name,
), [value],
)
else:
self.connection._iquery('set {} {}=%s;'.format(self.vtype, name), [value])
def __delitem__(self, name: str) -> None:
raise TypeError('Variables can not be deleted.')
def __getattr__(self, name: str) -> Any:
return self[name]
def __setattr__(self, name: str, value: Any) -> None:
self[name] = value
def __delattr__(self, name: str) -> None:
del self[name]
def __len__(self) -> int:
out = self.connection._iquery('show {} variables;'.format(self.vtype))
return len(list(out))
def __iter__(self) -> Iterator[str]:
out = self.connection._iquery('show {} variables;'.format(self.vtype))
return iter(list(x.values())[0] for x in out)
class Cursor(metaclass=abc.ABCMeta):
"""
Database cursor for submitting commands and queries.
This object should not be instantiated directly.
The ``Connection.cursor`` method should be used.
"""
def __init__(self, connection: 'Connection'):
"""Call ``Connection.cursor`` instead."""
self.errorhandler = connection.errorhandler
self._connection: Optional[Connection] = weakref.proxy(connection)
self._rownumber: Optional[int] = None
self._description: Optional[List[Description]] = None
#: Default batch size of ``fetchmany`` calls.
self.arraysize = get_option('results.arraysize')
self._converters: List[
Tuple[
int, Optional[str],
Optional[Callable[..., Any]],
]
] = []
#: Number of rows affected by the last query.
self.rowcount: int = -1
self._messages: List[Tuple[int, str]] = []
#: Row ID of the last modified row.
self.lastrowid: Optional[int] = None
@property
def messages(self) -> List[Tuple[int, str]]:
"""Messages created by the server."""
return self._messages
@abc.abstractproperty
def description(self) -> Optional[List[Description]]:
"""The field descriptions of the last query."""
return self._description
@abc.abstractproperty
def rownumber(self) -> Optional[int]:
"""The last modified row number."""
return self._rownumber
@property
def connection(self) -> Optional['Connection']:
"""the connection that the cursor belongs to."""
return self._connection
@abc.abstractmethod
def callproc(
self, name: str,
params: Optional[Sequence[Any]] = None,
) -> None:
"""
Call a stored procedure.
The result sets generated by a store procedure can be retrieved
like the results of any other query using :meth:`fetchone`,
:meth:`fetchmany`, or :meth:`fetchall`. If the procedure generates
multiple result sets, subsequent result sets can be accessed
using :meth:`nextset`.
Examples
--------
>>> cur.callproc('myprocedure', ['arg1', 'arg2'])
>>> print(cur.fetchall())
Parameters
----------
name : str
Name of the stored procedure
params : iterable, optional
Parameters to the stored procedure
"""
# NOTE: The `callproc` interface varies quite a bit between drivers
# so it is implemented using `execute` here.
if not self.is_connected():
raise exceptions.InterfaceError(2048, 'Cursor is closed.')
name = _name_check(name)
if not params:
self.execute(f'CALL {name}();')
else:
keys = ', '.join([f':{i+1}' for i in range(len(params))])
self.execute(f'CALL {name}({keys});', params)
@abc.abstractmethod
def is_connected(self) -> bool:
"""Is the cursor still connected?"""
raise NotImplementedError
@abc.abstractmethod
def close(self) -> None:
"""Close the cursor."""
raise NotImplementedError
@abc.abstractmethod
def execute(
self, query: str,
args: Optional[Union[Sequence[Any], Dict[str, Any], Any]] = None,
infile_stream: Optional[ # type: ignore
Union[
io.RawIOBase,
io.TextIOBase,
Iterator[Union[bytes, str]],
InfileQueue,
]
] = None,
) -> int:
"""
Execute a SQL statement.
Queries can use the ``format``-style parameters (``%s``) when using a
list of paramters or ``pyformat``-style parameters (``%(key)s``)
when using a dictionary of parameters.
Parameters
----------
query : str
The SQL statement to execute
args : Sequence or dict, optional
Parameters to substitute into the SQL code
infile_stream : io.RawIOBase or io.TextIOBase or Iterator[bytes|str], optional
Data stream for ``LOCAL INFILE`` statement
Examples
--------
Query with no parameters
>>> cur.execute('select * from mytable')
Query with positional parameters
>>> cur.execute('select * from mytable where id < %s', [100])
Query with named parameters
>>> cur.execute('select * from mytable where id < %(max)s', dict(max=100))
Returns
-------
Number of rows affected
"""
raise NotImplementedError
def executemany(
self, query: str,
args: Optional[Sequence[Union[Sequence[Any], Dict[str, Any], Any]]] = None,
) -> int:
"""
Execute SQL code against multiple sets of parameters.
Queries can use the ``format``-style parameters (``%s``) when using
lists of paramters or ``pyformat``-style parameters (``%(key)s``)
when using dictionaries 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
Examples
--------
>>> cur.executemany('select * from mytable where id < %s',
... [[100], [200], [300]])
>>> cur.executemany('select * from mytable where id < %(max)s',
... [dict(max=100), dict(max=100), dict(max=300)])
Returns
-------
Number of rows affected
"""
# NOTE: Just implement using `execute` to cover driver inconsistencies
if not args:
self.execute(query)
else:
for params in args:
self.execute(query, params)
return self.rowcount
@abc.abstractmethod
def fetchone(self) -> Optional[Result]:
"""
Fetch a single row from the result set.
Examples
--------
>>> while True:
... row = cur.fetchone()
... if row is None:
... break
... print(row)
Returns
-------
tuple
Values of the returned row if there are rows remaining
"""
raise NotImplementedError
@abc.abstractmethod
def fetchmany(self, size: Optional[int] = None) -> Result:
"""
Fetch `size` rows from the result.
If `size` is not specified, the `arraysize` attribute is used.
Examples
--------
>>> while True:
... out = cur.fetchmany(100)
... if not len(out):
... break
... for row in out:
... print(row)
Returns
-------
list of tuples
Values of the returned rows if there are rows remaining
"""
raise NotImplementedError
@abc.abstractmethod
def fetchall(self) -> Result:
"""
Fetch all rows in the result set.
Examples
--------
>>> for row in cur.fetchall():
... print(row)
Returns
-------
list of tuples
Values of the returned rows if there are rows remaining
None
If there are no rows to return
"""
raise NotImplementedError
@abc.abstractmethod
def nextset(self) -> Optional[bool]:
"""
Skip to the next available result set.
This is used when calling a procedure that returns multiple
results sets.
Note
----
The ``nextset`` method must be called until it returns an empty
set (i.e., once more than the number of expected result sets).
This is to retain compatibility with PyMySQL and MySOLdb.
Returns
-------
``True``
If another result set is available
``False``
If no other result set is available
"""
raise NotImplementedError
@abc.abstractmethod
def setinputsizes(self, sizes: Sequence[int]) -> None:
"""Predefine memory areas for parameters."""
raise NotImplementedError
@abc.abstractmethod
def setoutputsize(self, size: int, column: Optional[str] = None) -> None:
"""Set a column buffer size for fetches of large columns."""
raise NotImplementedError
@abc.abstractmethod
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
Where to move the cursor from: 'relative' or 'absolute'
"""
raise NotImplementedError
def next(self) -> Optional[Result]:
"""
Return the next row from the result set for use in iterators.
Raises
------
StopIteration
If no more results exist
Returns
-------
tuple of values
"""
if not self.is_connected():
raise exceptions.InterfaceError(2048, 'Cursor is closed.')
out = self.fetchone()
if out is None:
raise StopIteration
return out
__next__ = next
def __iter__(self) -> Any:
"""Return result iterator."""
return self
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()
class ShowResult(Sequence[Any]):
"""
Simple result object.
This object is primarily used for displaying results to a
terminal or web browser, but it can also be treated like a
simple data frame where columns are accessible using either
dictionary key-like syntax or attribute syntax.
Examples
--------
>>> conn.show.status().Value[10]
>>> conn.show.status()[10]['Value']
Parameters
----------
*args : Any
Parameters to send to underlying list constructor
**kwargs : Any
Keyword parameters to send to underlying list constructor
See Also
--------
:attr:`Connection.show`
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._data: List[Dict[str, Any]] = []
item: Any = None
for item in list(*args, **kwargs):
self._data.append(item)
def __getitem__(self, item: Union[int, slice]) -> Any:
return self._data[item]
def __getattr__(self, name: str) -> List[Any]:
if name.startswith('_ipython'):
raise AttributeError(name)
out = []
for item in self._data:
out.append(item[name])
return out
def __len__(self) -> int:
return len(self._data)
def __repr__(self) -> str:
if not self._data:
return ''
return '\n{}\n'.format(self._format_table(self._data))
@property
def columns(self) -> List[str]:
"""The columns in the result."""
if not self._data:
return []
return list(self._data[0].keys())
def _format_table(self, rows: Sequence[Dict[str, Any]]) -> str:
if not self._data:
return ''
keys = rows[0].keys()
lens = [len(x) for x in keys]
for row in self._data:
align = ['<'] * len(keys)
for i, k in enumerate(keys):
lens[i] = max(lens[i], len(str(row[k])))
align[i] = '<' if isinstance(row[k], (bytes, bytearray, str)) else '>'
fmt = '| %s |' % '|'.join([' {:%s%d} ' % (x, y) for x, y in zip(align, lens)])
out = []
out.append(fmt.format(*keys))
out.append('-' * len(out[0]))
for row in rows:
out.append(fmt.format(*[str(x) for x in row.values()]))
return '\n'.join(out)
def __str__(self) -> str:
return self.__repr__()
def _repr_html_(self) -> str:
if not self._data:
return ''
cell_style = 'style="text-align: left; vertical-align: top"'
out = []
out.append('<table border="1" class="dataframe">')
out.append('<thead>')
out.append('<tr>')
for name in self._data[0].keys():
out.append(f'<th {cell_style}>{name}</th>')
out.append('</tr>')
out.append('</thead>')
out.append('<tbody>')
for row in self._data:
out.append('<tr>')
for item in row.values():
out.append(f'<td {cell_style}>{item}</td>')
out.append('</tr>')
out.append('</tbody>')
out.append('</table>')
return ''.join(out)
class ShowAccessor(object):
"""
Accessor for ``SHOW`` commands.
See Also
--------
:attr:`Connection.show`
"""
def __init__(self, conn: 'Connection'):
self._conn = conn
def columns(self, table: str, full: bool = False) -> ShowResult:
"""Show the column information for the given table."""
table = quote_identifier(table)
if full:
return self._iquery(f'full columns in {table}')
return self._iquery(f'columns in {table}')
def tables(self, extended: bool = False) -> ShowResult:
"""Show tables in the current database."""
if extended:
return self._iquery('tables extended')
return self._iquery('tables')
def warnings(self) -> ShowResult:
"""Show warnings."""
return self._iquery('warnings')
def errors(self) -> ShowResult:
"""Show errors."""
return self._iquery('errors')
def databases(self, extended: bool = False) -> ShowResult:
"""Show all databases in the server."""
if extended:
return self._iquery('databases extended')
return self._iquery('databases')
def database_status(self) -> ShowResult:
"""Show status of the current database."""
return self._iquery('database status')
def global_status(self) -> ShowResult:
"""Show global status of the current server."""
return self._iquery('global status')
def indexes(self, table: str) -> ShowResult:
"""Show all indexes in the given table."""
table = quote_identifier(table)
return self._iquery(f'indexes in {table}')
def functions(self) -> ShowResult:
"""Show all functions in the current database."""
return self._iquery('functions')
def partitions(self, extended: bool = False) -> ShowResult:
"""Show partitions in the current database."""
if extended:
return self._iquery('partitions extended')
return self._iquery('partitions')
def pipelines(self) -> ShowResult:
"""Show all pipelines in the current database."""
return self._iquery('pipelines')
def plan(self, plan_id: int, json: bool = False) -> ShowResult:
"""Show the plan for the given plan ID."""
plan_id = int(plan_id)
if json:
return self._iquery(f'plan json {plan_id}')
return self._iquery(f'plan {plan_id}')
def plancache(self) -> ShowResult:
"""Show all query statements compiled and executed."""
return self._iquery('plancache')
def processlist(self) -> ShowResult:
"""Show details about currently running threads."""
return self._iquery('processlist')
def reproduction(self, outfile: Optional[str] = None) -> ShowResult:
"""Show troubleshooting data for query optimizer and code generation."""
if outfile:
outfile = outfile.replace('"', r'\"')
return self._iquery('reproduction into outfile "{outfile}"')
return self._iquery('reproduction')
def schemas(self) -> ShowResult:
"""Show schemas in the server."""
return self._iquery('schemas')
def session_status(self) -> ShowResult:
"""Show server status information for a session."""
return self._iquery('session status')
def status(self, extended: bool = False) -> ShowResult:
"""Show server status information."""
if extended:
return self._iquery('status extended')
return self._iquery('status')
def table_status(self) -> ShowResult:
"""Show table status information for the current database."""
return self._iquery('table status')
def procedures(self) -> ShowResult:
"""Show all procedures in the current database."""
return self._iquery('procedures')
def aggregates(self) -> ShowResult:
"""Show all aggregate functions in the current database."""
return self._iquery('aggregates')
def create_aggregate(self, name: str) -> ShowResult:
"""Show the function creation code for the given aggregate function."""
name = quote_identifier(name)
return self._iquery(f'create aggregate {name}')
def create_function(self, name: str) -> ShowResult:
"""Show the function creation code for the given function."""
name = quote_identifier(name)
return self._iquery(f'create function {name}')
def create_pipeline(self, name: str, extended: bool = False) -> ShowResult:
"""Show the pipeline creation code for the given pipeline."""
name = quote_identifier(name)
if extended:
return self._iquery(f'create pipeline {name} extended')
return self._iquery(f'create pipeline {name}')
def create_table(self, name: str) -> ShowResult:
"""Show the table creation code for the given table."""
name = quote_identifier(name)
return self._iquery(f'create table {name}')
def create_view(self, name: str) -> ShowResult:
"""Show the view creation code for the given view."""
name = quote_identifier(name)
return self._iquery(f'create view {name}')
# def grants(