-
Notifications
You must be signed in to change notification settings - Fork 74
/
cursor.py
2277 lines (2101 loc) · 96 KB
/
cursor.py
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
import functools
import logging
import re
import typing
from collections import deque
from itertools import count, islice
from typing import TYPE_CHECKING
from warnings import warn
import redshift_connector
from redshift_connector.config import (
ClientProtocolVersion,
_client_encoding,
table_type_clauses,
)
from redshift_connector.error import (
MISSING_MODULE_ERROR_MSG,
InterfaceError,
ProgrammingError,
)
if TYPE_CHECKING:
from redshift_connector.core import Connection
try:
import numpy # type: ignore
import pandas # type: ignore
except:
pass
_logger: logging.Logger = logging.getLogger(__name__)
class Cursor:
"""A cursor object is returned by the :meth:`~Connection.cursor` method of
a connection. It has the following attributes and methods:
.. attribute:: arraysize
This read/write attribute specifies the number of rows to fetch at a
time with :meth:`fetchmany`. It defaults to 1.
.. attribute:: connection
This read-only attribute contains a reference to the connection object
(an instance of :class:`Connection`) on which the cursor was
created.
This attribute is part of a DBAPI 2.0 extension. Accessing this
attribute will generate the following warning: ``DB-API extension
cursor.connection used``.
.. attribute:: rowcount
This read-only attribute contains the number of rows that the last
``execute()`` or ``executemany()`` method produced (for query
statements like ``SELECT``) or affected (for modification statements
like ``UPDATE``).
The value is -1 if:
- No ``execute()`` or ``executemany()`` method has been performed yet
on the cursor.
- There was no rowcount associated with the last ``execute()``.
- At least one of the statements executed as part of an
``executemany()`` had no row count associated with it.
- Using a ``SELECT`` query statement on Amazon Redshift server older than
version 9.
- Using a ``COPY`` query statement.
This attribute is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
.. attribute:: description
This read-only attribute is a sequence of 7-item sequences. Each value
contains information describing one result column. The 7 items
returned for each column are (name, type_code, display_size,
internal_size, precision, scale, null_ok). Only the first two values
are provided by the current implementation.
This attribute is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
"""
def __init__(self: "Cursor", connection: "Connection", paramstyle=None) -> None:
"""
A cursor object is returned by the :meth:`~Connection.cursor` method of a connection.
Parameters
----------
connection : :class:`Connection`
The :class:`Connection` object to associate with this :class:`Cursor`
paramstyle : Optional[str]
The DB-API paramstyle to use with this :class:`Cursor`
"""
self._c: typing.Optional["Connection"] = connection
self.arraysize: int = 1
self.ps: typing.Optional[typing.Dict[str, typing.Any]] = None
self._row_count: int = -1
self._redshift_row_count: int = -1
self._cached_rows: deque = deque()
if paramstyle is None:
self.paramstyle: str = redshift_connector.paramstyle
else:
self.paramstyle = paramstyle
_logger.debug("Cursor.paramstyle={}".format(self.paramstyle))
def __enter__(self: "Cursor") -> "Cursor":
return self
def __exit__(self: "Cursor", exc_type, exc_value, traceback) -> None:
self.close()
@property
def connection(self: "Cursor") -> typing.Optional["Connection"]:
warn("DB-API extension cursor.connection used", stacklevel=3)
return self._c
@property
def rowcount(self: "Cursor") -> int:
"""
This read-only attribute specifies the number of rows that the last .execute*() produced
(for DQL statements like SELECT) or affected (for DML statements like UPDATE or INSERT).
The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last
operation is cannot be determined by the interface.
"""
return self._row_count
@property
def redshift_rowcount(self: "Cursor") -> int:
"""
Native to ``redshift_connector``, this read-only attribute specifies the number of rows that the last .execute*() produced.
For DQL statements (like SELECT) the number of rows is derived by ``redshift_connector`` rather than
provided by the server. For DML statements (like UPDATE or INSERT) this value is provided by the server.
This property's behavior is subject to change inline with modifications made to query execution.
Use ``rowcount`` as an alternative to this property.
"""
return self._redshift_row_count
@typing.no_type_check
@functools.lru_cache()
def truncated_row_desc(self: "Cursor"):
_data: typing.List[
typing.Optional[typing.Union[typing.Tuple[typing.Callable, int], typing.Tuple[typing.Callable]]]
] = []
for cidx in range(len(self.ps["row_desc"])):
if self._c._client_protocol_version == ClientProtocolVersion.BINARY and self.ps["row_desc"][cidx][
"type_oid"
] in (1700,):
scale: int
if self.ps["row_desc"][cidx]["type_modifier"] != -1:
scale = (self.ps["row_desc"][cidx]["type_modifier"] - 4) & 0xFFFF
else:
scale = -4 & 0xFFFF
_data.append((self.ps["input_funcs"][cidx], scale))
else:
_data.append((self.ps["input_funcs"][cidx],))
return _data
description = property(lambda self: self._getDescription())
def _getDescription(self: "Cursor") -> typing.Optional[typing.List[typing.Optional[typing.Tuple]]]:
if self.ps is None:
return None
row_desc: typing.List[typing.Dict[str, typing.Union[bytes, str, int, typing.Callable]]] = self.ps["row_desc"]
if len(row_desc) == 0:
return None
columns: typing.List[typing.Optional[typing.Tuple]] = []
for col in row_desc:
try:
col_name: typing.Union[str, bytes] = typing.cast(bytes, col["label"]).decode(_client_encoding)
except UnicodeError:
warn("failed to decode column name: {}, reverting to bytes".format(col["label"])) # type: ignore
col_name = typing.cast(bytes, col["label"])
columns.append((col_name, col["type_oid"], None, None, None, None, None))
return columns
##
# Executes a database operation. Parameters may be provided as a sequence
# or mapping and will be bound to variables in the operation.
# <p>
# Stability: Part of the DBAPI 2.0 specification.
def execute(self: "Cursor", operation, args=None, stream=None, merge_socket_read=False) -> "Cursor":
"""Executes a database operation. Parameters may be provided as a
sequence, or as a mapping, depending upon the value of
:data:`paramstyle`.
This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
:param operation: str
The SQL statement to execute.
:param args: typing.Union[typing.Mapping, typing.Dict, list]
If :data:`paramstyle` is ``qmark``, ``numeric``, or ``format``,
this argument should be an array of parameters to bind into the
statement. If :data:`paramstyle` is ``named``, the argument should
be a dict mapping of parameters. If the :data:`paramstyle` is
``pyformat``, the argument value may be either an array or a
mapping.
:param stream: This is a extension for use with the Amazon Redshift
`COPY
<https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html>`_
command. For a COPY FROM the parameter must be a readable file-like
object, and for COPY TO it must be writable.
.. versionadded:: 1.9.11
Returns
-------
The Cursor object used for executing the specified database operation: :class:`Cursor`
"""
if self._c is None:
raise InterfaceError("Cursor closed")
if self._c._sock is None:
raise InterfaceError("connection is closed")
try:
self.stream = stream
# a miniaturized version of the row description is cached to speed up
# processing data from server. It needs to be cleared with each statement
# execution.
self.truncated_row_desc.cache_clear()
# For Redshift, we need to begin transaction and then to process query
# In the end we can use commit or rollback to end the transaction
if not self._c.in_transaction and not self._c.autocommit:
self._c.execute(self, "begin transaction", None)
self._c.merge_socket_read = merge_socket_read
self._c.execute(self, operation, args)
except AttributeError as e:
raise e
return self
def executemany(self: "Cursor", operation, param_sets) -> "Cursor":
"""Prepare a database operation, and then execute it against all
parameter sequences or mappings provided.
This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
:param operation: str
The SQL statement to execute
:param parameter_sets:
A sequence of parameters to execute the statement with. The values
in the sequence should be sequences or mappings of parameters, the
same as the args argument of the :meth:`execute` method.
Returns
-------
The Cursor object used for executing the specified database operation: :class:`Cursor`
"""
rowcounts: typing.List[int] = []
redshift_rowcounts: typing.List[int] = []
for parameters in param_sets:
self.execute(operation, parameters)
rowcounts.append(self._row_count)
redshift_rowcounts.append(self._redshift_row_count)
self._row_count = -1 if -1 in rowcounts else sum(rowcounts)
self._redshift_row_count = -1 if -1 in redshift_rowcounts else sum(rowcounts)
return self
def insert_data_bulk(
self: "Cursor",
filename: str,
table_name: str,
parameter_indices: typing.List[int],
column_names: typing.List[str],
delimiter: str,
batch_size: int = 1,
) -> "Cursor":
"""runs a single bulk insert statement into the database.
This method is native to redshift_connector.
:param filename: str
The name of the file to read from.
:param table_name: str
The name of the table to insert to.
:param column_names:list
The name of the columns in the table to insert to.
:param parameter_indices:list
The indexes of the columns in the file to insert to.
:param delimiter: str
The delimiter to use when reading the file.
:param batch_size: int
The number of rows to insert per insert statement. Minimum allowed value is 1.
Returns
-------
The Cursor object used for executing the specified database operation: :class:`Cursor`
"""
if batch_size < 1:
raise InterfaceError("batch_size must be greater than 1")
if not self.__is_valid_table(table_name):
raise InterfaceError("Invalid table name passed to insert_data_bulk: {}".format(table_name))
if not self.__has_valid_columns(table_name, column_names):
raise InterfaceError("Invalid column names passed to insert_data_bulk: {}".format(table_name))
orig_paramstyle = self.paramstyle
import csv
if len(column_names) != len(parameter_indices):
raise InterfaceError("Column names and parameter indexes must be the same length")
base_stmt = f"INSERT INTO {table_name} ("
base_stmt += ", ".join(column_names)
base_stmt += ") VALUES "
sql_param_list_template = "(" + ", ".join(["%s"] * len(parameter_indices)) + ")"
try:
with open(filename) as csv_file:
reader = csv.reader(csv_file, delimiter=delimiter)
next(reader)
values_list: typing.List[str] = []
row_count = 0
for row in reader:
if row_count == batch_size:
sql_param_lists = [sql_param_list_template] * row_count
insert_stmt = base_stmt + ", ".join(sql_param_lists) + ";"
self.execute(insert_stmt, values_list)
row_count = 0
values_list.clear()
for column_index in parameter_indices:
values_list.append(row[column_index])
row_count += 1
if row_count:
sql_param_lists = [sql_param_list_template] * row_count
insert_stmt = base_stmt + ", ".join(sql_param_lists) + ";"
self.execute(insert_stmt, values_list)
except Exception as e:
raise InterfaceError(e)
finally:
# reset paramstyle to it's original value
self.paramstyle = orig_paramstyle
return self
def __has_valid_columns(self: "Cursor", table: str, columns: typing.List[str]) -> bool:
split_table_name: typing.List[str] = table.split(".")
q: str = "select 1 from information_schema.columns where table_name = ? and column_name = ?"
if len(split_table_name) == 2:
q += " and table_schema = ?"
param_list = [[split_table_name[1], c, split_table_name[0]] for c in columns]
else:
param_list = [[split_table_name[0], c] for c in columns]
temp = self.paramstyle
self.paramstyle = "qmark"
try:
for params in param_list:
self.execute(q, params)
res = self.fetchone()
if typing.cast(typing.List[int], res)[0] != 1:
raise InterfaceError("Invalid column name: {} specified for table: {}".format(params[1], table))
except:
raise
finally:
# reset paramstyle to it's original value
self.paramstyle = temp
return True
def callproc(self, procname, parameters=None):
args = [] if parameters is None else parameters
operation = "CALL " + self.__sanitize_str(procname) + "(" + ", ".join(["%s" for _ in args]) + ")"
from redshift_connector.core import convert_paramstyle
try:
statement, make_args = convert_paramstyle("format", operation)
vals = make_args(args)
self.execute(statement, vals)
except AttributeError as e:
if self._c is None:
raise InterfaceError("Cursor closed")
elif self._c._sock is None:
raise InterfaceError("connection is closed")
else:
raise e
def fetchone(self: "Cursor") -> typing.Optional[typing.List]:
"""Fetch the next row of a query result set.
This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
Returns
-------
A row as a sequence of field values, or ``None`` if no more rows are available:typing.Optional[typing.List]
"""
try:
return next(self)
except StopIteration:
return None
except TypeError:
raise ProgrammingError("attempting to use unexecuted cursor")
except AttributeError:
raise ProgrammingError("attempting to use unexecuted cursor")
def fetchmany(self: "Cursor", num: typing.Optional[int] = None) -> typing.Tuple:
"""Fetches the next set of rows of a query result.
This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
:param num:
The number of rows to fetch when called. If not provided, the
:attr:`arraysize` attribute value is used instead.
:returns:
A sequence, each entry of which is a sequence of field values
making up a row. If no more rows are available, an empty sequence
will be returned.:typing.Tuple
"""
try:
return tuple(islice(self, self.arraysize if num is None else num))
except TypeError:
raise ProgrammingError("attempting to use unexecuted cursor")
def fetchall(self: "Cursor") -> typing.Tuple:
"""Fetches all remaining rows of a query result.
This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
:returns:
A sequence, each entry of which is a sequence of field values
making up a row.:tuple
"""
try:
return tuple(self)
except TypeError:
raise ProgrammingError("attempting to use unexecuted cursor")
def close(self: "Cursor") -> None:
"""Closes the cursor.
This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_.
A row as a sequence of field values, or ``None`` if no more rows
are available.
Returns
-------
None:None
"""
self._c = None
def __iter__(self: "Cursor") -> "Cursor":
"""A cursor object is iterable to retrieve the rows from a query.
This is a DBAPI 2.0 extension.
"""
return self
def setinputsizes(self: "Cursor", *sizes):
"""This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_, however, it is not
implemented.
"""
pass
def setoutputsize(self: "Cursor", size, column=None):
"""This method is part of the `DBAPI 2.0 specification
<http://www.python.org/dev/peps/pep-0249/>`_, however, it is not
implemented.
"""
pass
def __next__(self: "Cursor") -> typing.List:
try:
return self._cached_rows.popleft()
except IndexError:
if self.ps is None:
raise ProgrammingError("A query hasn't been issued.")
elif len(self.ps["row_desc"]) == 0:
raise ProgrammingError("no result set")
else:
raise StopIteration()
def fetch_dataframe(self: "Cursor", num: typing.Optional[int] = None) -> "pandas.DataFrame":
"""
Fetches a user defined number of rows of a query result as a :class:`pandas.DataFrame`.
Parameters
----------
num : Optional[int] The number of rows to retrieve. If unspecified, all rows will be retrieved
Returns
-------
A `pandas.DataFrame` containing field values making up a row. A column label, derived from the row description of the table, is provided. : "pandas.Dataframe"
"""
try:
import pandas
except ModuleNotFoundError:
raise ModuleNotFoundError(MISSING_MODULE_ERROR_MSG.format(module="pandas"))
columns: typing.Optional[typing.List[typing.Union[str, bytes]]] = None
try:
columns = [column[0].lower() for column in self.description]
except:
warn("No row description was found. pandas dataframe will be missing column labels.", stacklevel=2)
if num:
fetcheddata: tuple = self.fetchmany(num)
else:
fetcheddata = self.fetchall()
result: typing.List = [tuple(column for column in rows) for rows in fetcheddata]
return pandas.DataFrame(result, columns=columns)
def __is_valid_table(self: "Cursor", table: str) -> bool:
split_table_name: typing.List[str] = table.split(".")
if len(split_table_name) > 2:
return False
q: str = "select 1 from information_schema.tables where table_name = ?"
temp = self.paramstyle
self.paramstyle = "qmark"
try:
if len(split_table_name) == 2:
q += " and table_schema = ?"
self.execute(q, (split_table_name[1], split_table_name[0]))
else:
self.execute(q, (split_table_name[0],))
except:
raise
finally:
# reset paramstyle to it's original value
self.paramstyle = temp
result = self.fetchone()
return result[0] == 1 if result is not None else False
def write_dataframe(self: "Cursor", df: "pandas.DataFrame", table: str) -> None:
"""
Inserts a :class:`pandas.DataFrame` into an table within the current database.
Parameters
----------
df : :class:`pandas.DataFrame` Contains row values to insert into `table`
table : str Name of an existing table in the current Amazon Redshift database to insert the values in `df`
Returns
-------
None: None
"""
try:
import pandas
except ModuleNotFoundError:
raise ModuleNotFoundError(MISSING_MODULE_ERROR_MSG.format(module="pandas"))
if not self.__is_valid_table(table):
raise InterfaceError("Invalid table name passed to write_dataframe: {}".format(table))
sanitized_table_name: str = self.__sanitize_str(table)
arrays: "numpy.ndarray" = df.values
placeholder: str = ", ".join(["%s"] * len(arrays[0]))
sql: str = "insert into {table} values ({placeholder})".format(
table=sanitized_table_name, placeholder=placeholder
)
if len(arrays) == 1:
self.execute(sql, arrays[0])
elif len(arrays) > 1:
self.executemany(sql, arrays)
def fetch_numpy_array(self: "Cursor", num: typing.Optional[int] = None) -> "numpy.ndarray":
"""
Fetches a user defined number of rows of a query result as a :class:`numpy.ndarray`.
Parameters
----------
num : int The number of rows to retrieve from the result set.
Returns
-------
A `numpy.ndarray` containing the results of a query executed::class:`numpy.ndarray`
"""
try:
import numpy
except ModuleNotFoundError:
raise ModuleNotFoundError(MISSING_MODULE_ERROR_MSG.format(module="numpy"))
if num:
fetched: typing.Tuple = self.fetchmany(num)
else:
fetched = self.fetchall()
return numpy.array(fetched)
def get_procedures(
self: "Cursor",
catalog: typing.Optional[str] = None,
schema_pattern: typing.Optional[str] = None,
procedure_name_pattern: typing.Optional[str] = None,
) -> tuple:
sql: str = (
"SELECT current_database() AS PROCEDURE_CAT, n.nspname AS PROCEDURE_SCHEM, p.proname AS PROCEDURE_NAME, "
"NULL, NULL, NULL, d.description AS REMARKS, "
" CASE p.prokind "
" WHEN 'f' THEN 2 "
" WHEN 'p' THEN 1 "
" ELSE 0 "
" END AS PROCEDURE_TYPE, "
" p.proname || '_' || p.prooid AS SPECIFIC_NAME "
" FROM pg_catalog.pg_namespace n, pg_catalog.pg_proc_info p "
" LEFT JOIN pg_catalog.pg_description d ON (p.prooid=d.objoid) "
" LEFT JOIN pg_catalog.pg_class c ON (d.classoid=c.oid AND c.relname='pg_proc') "
" LEFT JOIN pg_catalog.pg_namespace pn ON (c.relnamespace=pn.oid AND pn.nspname='pg_catalog') "
" WHERE p.pronamespace=n.oid "
)
query_args: typing.List[str] = []
if schema_pattern is not None and schema_pattern != "":
sql += " AND n.nspname LIKE ?"
query_args.append(self.__sanitize_str(schema_pattern))
else:
sql += "and pg_function_is_visible(p.prooid)"
if procedure_name_pattern is not None and procedure_name_pattern != "":
sql += " AND p.proname LIKE ?"
query_args.append(self.__sanitize_str(procedure_name_pattern))
sql += " ORDER BY PROCEDURE_SCHEM, PROCEDURE_NAME, p.prooid::text "
if len(query_args) > 0:
# temporarily use qmark paramstyle
temp = self.paramstyle
self.paramstyle = "qmark"
try:
self.execute(sql, tuple(query_args))
except:
raise
finally:
# reset the original value of paramstyle
self.paramstyle = temp
else:
self.execute(sql)
procedures: tuple = self.fetchall()
return procedures
def _get_catalog_filter_conditions(
self: "Cursor",
catalog: typing.Optional[str],
api_supported_only_for_connected_database: bool,
database_col_name: typing.Optional[str],
) -> str:
if self._c is None:
raise InterfaceError("connection is closed")
catalog_filter: str = ""
if catalog is not None and catalog != "":
if self._c.is_single_database_metadata is True or api_supported_only_for_connected_database is True:
catalog_filter += " AND current_database() = {catalog}".format(catalog=self.__escape_quotes(catalog))
else:
if database_col_name is None or database_col_name == "":
database_col_name = "database_name"
catalog_filter += " AND {col_name} = {catalog}".format(
col_name=self.__sanitize_str(database_col_name), catalog=self.__escape_quotes(catalog)
)
return catalog_filter
def get_schemas(
self: "Cursor", catalog: typing.Optional[str] = None, schema_pattern: typing.Optional[str] = None
) -> tuple:
if self._c is None:
raise InterfaceError("connection is closed")
query_args: typing.List[str] = []
sql: str = ""
if self._c.is_single_database_metadata is True:
sql = (
"SELECT nspname AS TABLE_SCHEM, NULL AS TABLE_CATALOG FROM pg_catalog.pg_namespace "
" WHERE nspname <> 'pg_toast' AND (nspname !~ '^pg_temp_' "
" OR nspname = (pg_catalog.current_schemas(true))[1]) AND (nspname !~ '^pg_toast_temp_' "
" OR nspname = replace((pg_catalog.current_schemas(true))[1], 'pg_temp_', 'pg_toast_temp_')) "
)
sql += self._get_catalog_filter_conditions(catalog, True, None)
if schema_pattern is not None and schema_pattern != "":
sql += " AND nspname LIKE ?"
query_args.append(self.__sanitize_str(schema_pattern))
# if self._c.get_hide_unprivileged_objects(): # TODO: not implemented
# sql += " AND has_schema_privilege(nspname, 'USAGE, CREATE')"
sql += " ORDER BY TABLE_SCHEM"
else:
sql = (
"SELECT CAST(schema_name AS varchar(124)) AS TABLE_SCHEM, "
" CAST(database_name AS varchar(124)) AS TABLE_CATALOG "
" FROM PG_CATALOG.SVV_ALL_SCHEMAS "
" WHERE TRUE "
)
sql += self._get_catalog_filter_conditions(catalog, False, None)
if schema_pattern is not None and schema_pattern != "":
sql += " AND schema_name LIKE ?"
query_args.append(self.__sanitize_str(schema_pattern))
sql += " ORDER BY TABLE_CATALOG, TABLE_SCHEM"
if len(query_args) == 1:
# temporarily use qmark paramstyle
temp = self.paramstyle
self.paramstyle = "qmark"
try:
self.execute(sql, tuple(query_args))
except:
raise
finally:
self.paramstyle = temp
else:
self.execute(sql)
schemas: tuple = self.fetchall()
return schemas
def get_primary_keys(
self: "Cursor",
catalog: typing.Optional[str] = None,
schema: typing.Optional[str] = None,
table: typing.Optional[str] = None,
) -> tuple:
sql: str = (
"SELECT "
"current_database() AS TABLE_CAT, "
"n.nspname AS TABLE_SCHEM, "
"ct.relname AS TABLE_NAME, "
"a.attname AS COLUMN_NAME, "
"a.attnum AS KEY_SEQ, "
"ci.relname AS PK_NAME "
"FROM "
"pg_catalog.pg_namespace n, "
"pg_catalog.pg_class ct, "
"pg_catalog.pg_class ci, "
"pg_catalog.pg_attribute a, "
"pg_catalog.pg_index i "
"WHERE "
"ct.oid=i.indrelid AND "
"ci.oid=i.indexrelid AND "
"a.attrelid=ci.oid AND "
"i.indisprimary AND "
"ct.relnamespace = n.oid "
)
query_args: typing.List[str] = []
if schema is not None and schema != "":
sql += " AND n.nspname = ?"
query_args.append(self.__sanitize_str(schema))
if table is not None and table != "":
sql += " AND ct.relname = ?"
query_args.append(self.__sanitize_str(table))
sql += " ORDER BY table_name, pk_name, key_seq"
if len(query_args) > 0:
# temporarily use qmark paramstyle
temp = self.paramstyle
self.paramstyle = "qmark"
try:
self.execute(sql, tuple(query_args))
except:
raise
finally:
self.paramstyle = temp
else:
self.execute(sql)
keys: tuple = self.fetchall()
return keys
def get_catalogs(self: "Cursor") -> typing.Tuple:
"""
Redshift does not support multiple catalogs from a single connection, so to reduce confusion we only return the
current catalog.
Returns
-------
A tuple containing the name of the current catalog: tuple
"""
if self._c is None:
raise InterfaceError("connection is closed")
sql: str = ""
if self._c.is_single_database_metadata is True:
sql = "select current_database as TABLE_CAT FROM current_database()"
else:
# Datasharing/federation support enable, so get databases using the new view.
sql = "SELECT CAST(database_name AS varchar(124)) AS TABLE_CAT FROM PG_CATALOG.SVV_REDSHIFT_DATABASES "
sql += " ORDER BY TABLE_CAT"
self.execute(sql)
catalogs: typing.Tuple = self.fetchall()
return catalogs
def get_tables(
self: "Cursor",
catalog: typing.Optional[str] = None,
schema_pattern: typing.Optional[str] = None,
table_name_pattern: typing.Optional[str] = None,
types: list = [],
) -> tuple:
"""
Returns the unique public tables which are user-defined within the system.
Parameters
----------
catalog : Optional[str] The name of the catalog
schema_pattern : Optional[str] A valid pattern for desired schemas
table_name_pattern : Optional[str] A valid pattern for desired table names
types : Optional[list[str]] A list of `str` containing table types. By default table types is not used as a filter.
Returns
-------
A tuple containing unique public tables which are user-defined within the system: tuple
"""
if self._c is None:
raise InterfaceError("connection is closed")
sql: str = ""
sql_args: typing.Tuple[str, ...] = tuple()
schema_pattern_type: str = self.__schema_pattern_match(schema_pattern)
if schema_pattern_type == "LOCAL_SCHEMA_QUERY":
sql, sql_args = self.__build_local_schema_tables_query(catalog, schema_pattern, table_name_pattern, types)
elif schema_pattern_type == "NO_SCHEMA_UNIVERSAL_QUERY":
if self._c.is_single_database_metadata is True:
sql, sql_args = self.__build_universal_schema_tables_query(
catalog, schema_pattern, table_name_pattern, types
)
else:
sql, sql_args = self.__build_universal_all_schema_tables_query(
catalog, schema_pattern, table_name_pattern, types
)
elif schema_pattern_type == "EXTERNAL_SCHEMA_QUERY":
sql, sql_args = self.__build_external_schema_tables_query(
catalog, schema_pattern, table_name_pattern, types
)
if len(sql_args) > 0:
temp = self.paramstyle
self.paramstyle = "qmark"
try:
self.execute(sql, sql_args)
except:
raise
finally:
self.paramstyle = temp
else:
self.execute(sql)
tables: tuple = self.fetchall()
return tables
def __build_local_schema_tables_query(
self: "Cursor",
catalog: typing.Optional[str],
schema_pattern: typing.Optional[str],
table_name_pattern: typing.Optional[str],
types: list,
) -> typing.Tuple[str, typing.Tuple[str, ...]]:
sql: str = (
"SELECT CAST(current_database() AS VARCHAR(124)) AS TABLE_CAT, n.nspname AS TABLE_SCHEM, c.relname AS TABLE_NAME, "
" CASE n.nspname ~ '^pg_' OR n.nspname = 'information_schema' "
" WHEN true THEN CASE "
" WHEN n.nspname = 'pg_catalog' OR n.nspname = 'information_schema' THEN CASE c.relkind "
" WHEN 'r' THEN 'SYSTEM TABLE' "
" WHEN 'v' THEN 'SYSTEM VIEW' "
" WHEN 'i' THEN 'SYSTEM INDEX' "
" ELSE NULL "
" END "
" WHEN n.nspname = 'pg_toast' THEN CASE c.relkind "
" WHEN 'r' THEN 'SYSTEM TOAST TABLE' "
" WHEN 'i' THEN 'SYSTEM TOAST INDEX' "
" ELSE NULL "
" END "
" ELSE CASE c.relkind "
" WHEN 'r' THEN 'TEMPORARY TABLE' "
" WHEN 'p' THEN 'TEMPORARY TABLE' "
" WHEN 'i' THEN 'TEMPORARY INDEX' "
" WHEN 'S' THEN 'TEMPORARY SEQUENCE' "
" WHEN 'v' THEN 'TEMPORARY VIEW' "
" ELSE NULL "
" END "
" END "
" WHEN false THEN CASE c.relkind "
" WHEN 'r' THEN 'TABLE' "
" WHEN 'p' THEN 'PARTITIONED TABLE' "
" WHEN 'i' THEN 'INDEX' "
" WHEN 'S' THEN 'SEQUENCE' "
" WHEN 'v' THEN 'VIEW' "
" WHEN 'c' THEN 'TYPE' "
" WHEN 'f' THEN 'FOREIGN TABLE' "
" WHEN 'm' THEN 'MATERIALIZED VIEW' "
" ELSE NULL "
" END "
" ELSE NULL "
" END "
" AS TABLE_TYPE, d.description AS REMARKS, "
" '' as TYPE_CAT, '' as TYPE_SCHEM, '' as TYPE_NAME, "
"'' AS SELF_REFERENCING_COL_NAME, '' AS REF_GENERATION "
" FROM pg_catalog.pg_namespace n, pg_catalog.pg_class c "
" LEFT JOIN pg_catalog.pg_description d ON (c.oid = d.objoid AND d.objsubid = 0) "
" LEFT JOIN pg_catalog.pg_class dc ON (d.classoid=dc.oid AND dc.relname='pg_class') "
" LEFT JOIN pg_catalog.pg_namespace dn ON (dn.oid=dc.relnamespace AND dn.nspname='pg_catalog') "
" WHERE c.relnamespace = n.oid "
)
filter_clause, filter_args = self.__get_table_filter_clause(
catalog, schema_pattern, table_name_pattern, types, "LOCAL_SCHEMA_QUERY", True, None
)
orderby: str = " ORDER BY TABLE_TYPE,TABLE_SCHEM,TABLE_NAME "
return sql + filter_clause + orderby, filter_args
def __get_table_filter_clause(
self: "Cursor",
catalog: typing.Optional[str],
schema_pattern: typing.Optional[str],
table_name_pattern: typing.Optional[str],
types: typing.List[str],
schema_pattern_type: str,
api_supported_only_for_connected_database: bool,
database_col_name: typing.Optional[str],
) -> typing.Tuple[str, typing.Tuple[str, ...]]:
filter_clause: str = ""
use_schemas: str = "SCHEMAS"
filter_clause += self._get_catalog_filter_conditions(
catalog, api_supported_only_for_connected_database, database_col_name
)
query_args: typing.List[str] = []
if schema_pattern is not None and schema_pattern != "":
filter_clause += " AND TABLE_SCHEM LIKE ?"
query_args.append(self.__sanitize_str(schema_pattern))
if table_name_pattern is not None and table_name_pattern != "":
filter_clause += " AND TABLE_NAME LIKE ?"
query_args.append(self.__sanitize_str(table_name_pattern))
if len(types) > 0:
if schema_pattern_type == "LOCAL_SCHEMA_QUERY":
filter_clause += " AND (false "
orclause: str = ""
for type in types:
if type not in table_type_clauses.keys():
raise InterfaceError(
"Invalid type: {} provided. types may only contain: {}".format(
type, table_type_clauses.keys()
)
)
clauses: typing.Optional[typing.Dict[str, str]] = table_type_clauses[type]
if clauses is not None:
cluase: str = clauses[use_schemas]
orclause += " OR ( {cluase} ) ".format(cluase=cluase)
filter_clause += orclause + ") "
elif schema_pattern_type == "NO_SCHEMA_UNIVERSAL_QUERY" or schema_pattern_type == "EXTERNAL_SCHEMA_QUERY":
filter_clause += " AND TABLE_TYPE IN ( "
length = len(types)
for type in types:
if type not in table_type_clauses.keys():
raise InterfaceError(
"Invalid type: {} provided. types may only contain: {}".format(
type, table_type_clauses.keys()
)
)
filter_clause += "?"
query_args.append(type)
length -= 1
if length > 0:
filter_clause += ", "
filter_clause += ") "
return filter_clause, tuple(query_args)
def __build_universal_schema_tables_query(
self: "Cursor",
catalog: typing.Optional[str],
schema_pattern: typing.Optional[str],
table_name_pattern: typing.Optional[str],
types: list,
) -> typing.Tuple[str, typing.Tuple[str, ...]]:
sql: str = (
"SELECT * FROM (SELECT CAST(current_database() AS VARCHAR(124)) AS TABLE_CAT,"
" table_schema AS TABLE_SCHEM,"
" table_name AS TABLE_NAME,"