-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsql.py
1321 lines (1027 loc) · 52.5 KB
/
sql.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
"""
Basic data manipulation with SQL.
*(The current release includes* `PostgreSQL <https://www.postgresql.org/>`_ *only.)*
"""
import copy
import csv
import gc
import getpass
import inspect
import io
import tempfile
import pandas as pd
import pandas.io.parsers
import sqlalchemy
import sqlalchemy.engine.reflection
import sqlalchemy.engine.url
import sqlalchemy_utils
from .ops import confirmed
def get_db_address(db_cls):
"""
Get default address of a database instance.
:param db_cls: a class representation of a database
:type db_cls: object
:return: default address of database
:rtype: str
**Test**::
>>> from pyhelpers.sql import get_db_address, PostgreSQL
>>> db_addr = get_db_address(db_cls=PostgreSQL)
>>> print(db_addr)
None:***@None:None/None
"""
args_spec = inspect.getfullargspec(db_cls)
args_dict = dict(zip([x for x in args_spec.args if x != 'self'], args_spec.defaults))
db_address = "{}:***@{}:{}/{}".format(args_dict['username'], args_dict['host'],
args_dict['port'], args_dict['database_name'])
return db_address
class PostgreSQL:
"""
A class for a basic `PostgreSQL <https://www.postgresql.org/>`_ instance.
:param host: host address,
e.g. ``'localhost'`` or ``'127.0.0.1'`` (default by installation), defaults to ``None``
:type host: str or None
:param port: port, e.g. ``5432`` (default by installation), defaults to ``None``
:type port: int or None
:param password: database password, defaults to ``None``
:type password: str or int or None
:param username: database username, e.g. ``'postgres'`` (default by installation),
defaults to ``None``
:type username: str or None
:param database_name: database name, e.g. ``'postgres'`` (default by installation),
defaults to ``None``
:type database_name: str
:param confirm_new_db: whether to impose a confirmation to create a new database,
defaults to ``False``
:type confirm_new_db: bool
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``True``
:type verbose: bool
:ivar dict database_info: basic information about the server/database being connected
:ivar sqlalchemy.engine.url.URL url: PostgreSQL database URL
(see also [`SQL-P-SP-1 <https://docs.sqlalchemy.org/en/13/core/engines.html#postgresql>`_])
:ivar type dialect: system that SQLAlchemy uses to communicate with PostgreSQL
(see also [`SQL-P-SP-2 <https://docs.sqlalchemy.org/en/13/dialects/postgresql.html>`_])
:ivar str backend: name of database backend
:ivar str driver: name of database driver
:ivar str user: username
:ivar str host: host name
:ivar str port: port number
:ivar str database_name: name of a database
:ivar str address: brief description of the database address
:ivar sqlalchemy.engine.Engine engine: `SQLAlchemy`_ Engine class
(see also [`SQL-P-SP-3 <https://docs.sqlalchemy.org/en/13/core/connections.html
#sqlalchemy.engine.Engine>`_])
:ivar sqlalchemy.pool.base._ConnectionFairy connection: `SQLAlchemy`_ Connection class
(see also [`SQL-P-SP-4 <https://docs.sqlalchemy.org/en/13/core/connections.html#
sqlalchemy.engine.Connection>`_])
.. _`SQLAlchemy`: https://www.sqlalchemy.org/
**Examples**::
>>> from pyhelpers.sql import PostgreSQL
>>> # Connect the default database 'postgres'
>>> postgres = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='postgres')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/postgres ... Successfully.
>>> print(postgres.address)
postgres:***@localhost:5432/postgres
>>> # Connect a database 'testdb' (which will be created if it does not exist)
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> print(testdb.address)
postgres:***@localhost:5432/testdb
>>> # Define a proxy object that inherits from pyhelpers.sql.PostgreSQL
>>> class ExampleProxyObj(PostgreSQL):
...
... def __init__(self, host='localhost', port=5432, username='postgres',
... password=None, database_name='testdb', **kwargs):
...
... super().__init__(host=host, port=port, username=username,
... password=password, database_name=database_name,
... **kwargs)
>>> example_proxy_obj = ExampleProxyObj()
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> print(example_proxy_obj.address)
postgres:***@localhost:5432/testdb
"""
def __init__(self, host=None, port=None, username=None, database_name=None, password=None,
confirm_new_db=False, verbose=True):
"""
Constructor method.
"""
host_ = input("PostgreSQL Host: ") if host is None else str(host)
port_ = input("PostgreSQL Port: ") if port is None else int(port)
username_ = input("Username: ") if username is None else str(username)
database_name_ = input("Database: ") if database_name is None else str(database_name)
if password:
password_ = str(password)
else:
pwd_msg = "Password ({}@{}:{}): ".format(username_, host_, port_)
password_ = getpass.getpass(pwd_msg)
self.database_info = {'drivername': 'postgresql+psycopg2',
'host': host_,
'port': port_,
'username': username_,
'password': password_,
'database': database_name_}
# The typical form of a database URL is:
# url = backend+driver://username:password@host:port/database
self.url = sqlalchemy.engine.url.URL(**self.database_info)
self.dialect = self.url.get_dialect()
self.backend = self.url.get_backend_name()
self.driver = self.url.get_driver_name()
self.user, self.host, self.port = self.url.username, self.url.host, self.url.port
self.database_name = self.database_info['database']
self.address = "{}:***@{}:{}/{}".format(self.user,
self.host,
self.port,
self.database_name)
if not sqlalchemy_utils.database_exists(self.url):
if confirmed("The database \"{}\" does not exist. "
"Proceed by creating it?".format(self.database_name),
confirmation_required=confirm_new_db):
print("Connecting {}".format(self.address), end=" ... ") if verbose else ""
sqlalchemy_utils.create_database(self.url)
else:
if verbose:
print("Connecting {}".format(self.address), end=" ... ")
try:
# Create a SQLAlchemy connectable
self.engine = sqlalchemy.create_engine(self.url, isolation_level='AUTOCOMMIT')
self.connection = self.engine.raw_connection()
print("Successfully.") if verbose else ""
except Exception as e:
print("Failed. {}.".format(e))
def database_exists(self, database_name=None):
"""
Check if a database exists in the PostgreSQL server being connected.
:param database_name: name of a database, defaults to ``None``
:type database_name: str or None
:return: ``True`` if the database exists, ``False``, otherwise
:rtype: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> testdb.database_exists('testdb')
True
>>> testdb.drop_database(verbose=True)
To drop the database "testdb" from postgres:***@localhost:5432
? [No]|Yes: yes
Dropping "testdb" ... Done.
>>> testdb.database_exists('testdb')
False
"""
database_name_ = str(database_name) if database_name is not None else self.database_name
result = self.engine.execute("SELECT EXISTS("
"SELECT datname FROM pg_catalog.pg_database "
"WHERE datname='{}');".format(database_name_))
return result.fetchone()[0]
def connect_database(self, database_name=None, verbose=False):
"""
Establish a connection to a database of the PostgreSQL server being connected.
:param database_name: name of a database;
if ``None`` (default), the database name is input manually
:type database_name: str or None
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> testdb.connect_database()
>>> print(testdb.database_name)
testdb
>>> testdb.connect_database('postgres', verbose=True)
Connecting postgres:***@localhost:5432/postgres ... Successfully.
>>> print(testdb.database_name)
postgres
"""
if database_name:
self.database_name = str(database_name)
self.address = "{}:***@{}:{}/{}".format(
self.user, self.host, self.port, self.database_name)
print("Connecting {}".format(self.address), end=" ... ") if verbose else ""
try:
self.database_info['database'] = self.database_name
self.url = sqlalchemy.engine.url.URL(**self.database_info)
if not sqlalchemy_utils.database_exists(self.url):
sqlalchemy_utils.create_database(self.url)
self.engine = sqlalchemy.create_engine(self.url, isolation_level='AUTOCOMMIT')
self.connection = self.engine.raw_connection()
print("Successfully.") if verbose else ""
except Exception as e:
print("Failed. {}.".format(e))
def create_database(self, database_name, verbose=False):
"""
An alternative to `sqlalchemy_utils.create_database
<https://sqlalchemy-utils.readthedocs.io/en/latest/database_helpers.html#create-database>`_.
:param database_name: name of a database
:type database_name: str
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> testdb.create_database('testdb1', verbose=True)
Creating a database: "testdb1" ... Done.
>>> print(testdb.database_name)
testdb1
>>> testdb.drop_database(verbose=True)
To drop the database "testdb1" from postgres:***@localhost:5432
? [No]|Yes: yes
Dropping "testdb1" ... Done.
"""
if not self.database_exists(database_name):
if verbose:
print("Creating a database: \"{}\" ... ".format(database_name), end="")
self.disconnect_database()
self.engine.execute('CREATE DATABASE "{}";'.format(database_name))
print("Done.") if verbose else ""
else:
print("The database already exists.") if verbose else ""
self.connect_database(database_name)
def get_database_size(self, database_name=None):
"""
Get the size of a database in the PostgreSQL server being connected.
When ``database_name`` is ``None`` (default), the connected database is checked.
:param database_name: name of a database, defaults to ``None``
:type database_name: str or None
:return: size of the database
:rtype: int
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> print(testdb.get_database_size())
7901 kB
"""
db_name = '\'{}\''.format(database_name) if database_name else 'current_database()'
sql_query = 'SELECT pg_size_pretty(pg_database_size({})) AS size;'.format(db_name)
db_size = self.engine.execute(sql_query)
return db_size.fetchone()[0]
def disconnect_database(self, database_name=None, verbose=False):
"""
Kill the connection to a database in the PostgreSQL server being connected.
If ``database_name`` is ``None`` (default), disconnect the current database.
:param database_name: name of database to disconnect from, defaults to ``None``
:type database_name: str or None
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> print(testdb.database_name)
testdb
>>> testdb.disconnect_database()
>>> print(testdb.database_name)
postgres
"""
db_name = self.database_name if database_name is None else database_name
if verbose:
print("Disconnecting the database \"{}\" ... ".format(db_name), end="")
try:
self.connect_database(database_name='postgres')
self.engine.execute(
'REVOKE CONNECT ON DATABASE "{}" FROM PUBLIC, postgres;'.format(db_name))
self.engine.execute(
'SELECT pg_terminate_backend(pid) '
'FROM pg_stat_activity '
'WHERE datname = \'{}\' AND pid <> pg_backend_pid();'.format(db_name))
print("Done.") if verbose else ""
except Exception as e:
print("Failed. {}".format(e))
def disconnect_other_databases(self):
"""
Kill connections to all other databases of the PostgreSQL server being connected.
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> print(testdb.database_name)
testdb
>>> testdb.disconnect_other_databases()
>>> print(testdb.database_name)
postgres
"""
self.connect_database(database_name='postgres')
self.engine.execute(
'SELECT pg_terminate_backend(pid) FROM pg_stat_activity '
'WHERE pid <> pg_backend_pid();')
def drop_database(self, database_name=None, confirmation_required=True, verbose=False):
"""
Drop a database from the PostgreSQL server being connected.
If ``database_name`` is ``None`` (default), drop the current database.
:param database_name: database to be disconnected, defaults to ``None``
:type database_name: str or None
:param confirmation_required: whether to prompt a message for confirmation to proceed,
defaults to ``True``
:type confirmation_required: bool
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> testdb.drop_database(verbose=True)
To drop the database "testdb" from postgres:***@localhost:5432
? [No]|Yes: yes
Dropping "testdb" ... Done.
>>> testdb.database_exists(database_name='testdb')
False
>>> testdb.drop_database(database_name='testdb', verbose=True)
The database "testdb" does not exist.
>>> print(testdb.database_name)
postgres
"""
db_name = self.database_name if database_name is None else database_name
if not self.database_exists(database_name=db_name):
if verbose:
print("The database \"{}\" does not exist.".format(db_name))
else:
if confirmed("To drop the database \"{}\" from {}\n?".format(
db_name, self.address.replace(f"/{db_name}", "")),
confirmation_required=confirmation_required):
self.disconnect_database(db_name)
if verbose:
if confirmation_required:
log_msg = "Dropping \"{}\"".format(db_name)
else:
log_msg = "Dropping the database \"{}\"".format(db_name)
print(log_msg, end=" ... ")
try:
self.engine.execute('DROP DATABASE "{}"'.format(db_name))
print("Done.") if verbose else ""
except Exception as e:
print("Failed. {}".format(e))
def schema_exists(self, schema_name):
"""
Check if a schema exists in the PostgreSQL server being connected.
:param schema_name: name of a schema
:type schema_name: str
:return: ``True`` if the schema exists, ``False`` otherwise
:rtype: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> testdb.schema_exists('public')
True
>>> testdb.schema_exists('test_schema')
>>> # (if the schema 'test_schema' does not exist)
False
"""
result = self.engine.execute(
"SELECT EXISTS("
"SELECT schema_name FROM information_schema.schemata "
"WHERE schema_name='{}');".format(schema_name))
return result.fetchone()[0]
def create_schema(self, schema_name, verbose=False):
"""
Create a new schema in the database being connected.
:param schema_name: name of a schema
:type schema_name: str
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> test_schema_name = 'test_schema'
>>> testdb.create_schema(test_schema_name, verbose=True)
Creating a schema: "test_schema" ... Done.
>>> testdb.schema_exists(test_schema_name)
True
>>> testdb.drop_schema(test_schema_name, verbose=True)
To drop the schema "test_schema" from postgres:***@localhost:5432/testdb
? [No]|Yes: yes
Dropping "test_schema" ... Done.
"""
if not self.schema_exists(schema_name=schema_name):
if verbose:
print("Creating a schema: \"{}\" ... ".format(schema_name), end="")
try:
self.engine.execute('CREATE SCHEMA IF NOT EXISTS "{}";'.format(schema_name))
print("Done.") if verbose else ""
except Exception as e:
print("Failed. {}".format(e))
else:
print("The schema \"{}\" already exists.".format(schema_name))
def msg_for_multi_schemas(self, item_names, desc='schema'):
"""
Formulate printing message for multiple schemas.
:param item_names: name of one table/schema, or names of several tables/schemas
:type item_names: str or collections.abc.Iterable
:param desc: for additional description, defaults to ``'schema'``
:type desc: str
:return: printing message
:rtype: tuple
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> schema_name = 'points'
>>> schemas, msg = testdb.msg_for_multi_schemas(schema_name, desc='schema')
>>> print(schemas)
['points']
>>> print(msg)
schema "points"
>>> schema_names = ['points', 'lines', 'polygons']
>>> schemas, msg = testdb.msg_for_multi_schemas(schema_names, desc='schema')
>>> print(schemas)
['points', 'lines', 'polygons']
>>> print(msg)
schemas:
"points",
"lines" and
"polygons"
:meta private:
"""
if item_names is None:
inspector = sqlalchemy.engine.reflection.Inspector.from_engine(self.engine)
items = [x for x in inspector.get_schema_names()
if x != 'public' and x != 'information_schema']
else:
items = [item_names] if isinstance(item_names, str) else copy.copy(item_names)
if len(items) == 1:
print_plural = "{} ".format(desc)
print_schema = "\"{}\"".format(items[0])
else:
print_plural = "{}s: ".format(desc)
print_schema = ("\n\t\"{}\"" * len(items)).format(*items)
return items, print_plural + print_schema
def drop_schema(self, schema_names, confirmation_required=True, verbose=False):
"""
Drop a schema in the database being connected.
:param schema_names: name of one schema, or names of multiple schemas
:type schema_names: str or collections.abc.Iterable
:param confirmation_required: whether to prompt a message for confirmation to proceed,
defaults to ``True``
:type confirmation_required: bool
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> new_schema_names = ['points', 'lines', 'polygons']
>>> new_schema_names_ = ['test_schema']
>>> for new_schema in new_schema_names:
... testdb.create_schema(new_schema, verbose=True)
Creating a schema: "points" ... Done.
Creating a schema: "lines" ... Done.
Creating a schema: "polygons" ... Done.
>>> testdb.drop_schema(new_schema_names + new_schema_names_, verbose=True)
To drop the following schemas:
"points"
"lines"
"polygons"
"test_schema"
from postgres:***@localhost:5432/testdb
? [No]|Yes: >? yes
Dropping ...
"points" ... Done.
"lines" ... Done.
"polygons" ... Done.
"test_schema" does not exist.
"""
schemas, schemas_msg = self.msg_for_multi_schemas(schema_names)
if len(schemas) == 1:
cfm_msg_ = "To drop the {} from {}\n?"
else:
cfm_msg_ = "To drop the following {}\n from {}\n?"
if confirmed(cfm_msg_.format(schemas_msg, self.address), confirmation_required):
if verbose:
if len(schemas) == 1:
if confirmation_required:
print("Dropping {}".format(schemas_msg.split(" ")[1]), end=" ... ")
else:
print("Dropping the {} from {}".format(schemas_msg, self.address),
end=" ... ")
else:
if confirmation_required:
print("Dropping ... ")
else:
print("Dropping the following schemas from {}:".format(self.address))
for schema in schemas:
if not self.schema_exists(schema):
# `schema` does not exist
if len(schemas) == 1:
print("Such a schema does not exist.") if verbose else ""
else:
print("\t\"{}\" does not exist.".format(schema)) if verbose else ""
else:
if len(schemas) > 1:
print("\t\"{}\"".format(schema), end=" ... ") if verbose else ""
try:
# schema_ = ('%s, ' * (len(schemas) - 1) + '%s') % tuple(schemas)
self.engine.execute('DROP SCHEMA "{}" CASCADE;'.format(schema))
print("Done.") if verbose else ""
except Exception as e:
print("Failed. {}".format(e))
def table_exists(self, table_name, schema_name='public'):
"""
Check if a table exists in the database being connected.
:param table_name: name of a table
:type table_name: str
:param schema_name: name of a schema, defaults to ``'public'``
:type schema_name: str
:return: ``True`` if the table exists, ``False`` otherwise
:rtype: bool
**Examples**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> table_name_ = 'England'
>>> schema_name_ = 'points'
>>> testdb.table_exists(table_name_, schema_name_)
>>> # (if 'points.England' does not exist)
False
"""
res = self.engine.execute("SELECT EXISTS("
"SELECT * FROM information_schema.tables "
"WHERE table_schema='{}' "
"AND table_name='{}');".format(schema_name, table_name))
return res.fetchone()[0]
def create_table(self, table_name, column_specs, schema_name='public', verbose=False):
"""
Create a new table for the database being connected.
:param table_name: name of a table
:type table_name: str
:param column_specs: specifications for each column of the table
:type column_specs: str
:param schema_name: name of a schema, defaults to ``'public'``
:type schema_name: str
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
.. _postgresql-create_table-example:
**Example**::
>>> from pyhelpers.sql import PostgreSQL
>>> testdb = PostgreSQL(host='localhost', port=5432, username='postgres',
... database_name='testdb')
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/testdb ... Successfully.
>>> tbl_name = 'test_table'
>>> column_specifications = 'col_name_1 INT, col_name_2 TEXT'
>>> testdb.create_table(tbl_name, column_specifications, verbose=True)
Creating a table "public"."test_table" ... Done.
>>> testdb.table_exists(tbl_name)
True
>>> test_tbl_col_info = testdb.get_column_info(tbl_name, as_dict=False)
>>> print(test_tbl_col_info)
column_0 column_1
table_catalog testdb testdb
table_schema public public
table_name test_table test_table
column_name col_name_1 col_name_2
ordinal_position 1 2
column_default None None
is_nullable YES YES
data_type integer text
character_maximum_length None None
character_octet_length NaN 1073741824.0
numeric_precision 32.0 NaN
numeric_precision_radix 2.0 NaN
numeric_scale 0.0 NaN
datetime_precision None None
interval_type None None
interval_precision None None
character_set_catalog None None
character_set_schema None None
character_set_name None None
collation_catalog None None
collation_schema None None
collation_name None None
domain_catalog None None
domain_schema None None
domain_name None None
udt_catalog testdb testdb
udt_schema pg_catalog pg_catalog
udt_name int4 text
scope_catalog None None
scope_schema None None
scope_name None None
maximum_cardinality None None
dtd_identifier 1 2
is_self_referencing NO NO
is_identity NO NO
identity_generation None None
identity_start None None
identity_increment None None
identity_maximum None None
identity_minimum None None
identity_cycle NO NO
is_generated NEVER NEVER
generation_expression None None
is_updatable YES YES
>>> # Drop the table
>>> testdb.drop_table(tbl_name, verbose=True)
To drop the table "public"."test_table" from postgres:***@localhost:5432/testdb
? [No]|Yes: >? yes
Dropping "public"."test_table" ... Done.
"""
table_name_ = '"{schema}"."{table}"'.format(schema=schema_name, table=table_name)
if self.table_exists(table_name=table_name, schema_name=schema_name):
print("The table {} already exists.".format(table_name_)) if verbose else ""
else:
if not self.schema_exists(schema_name):
self.create_schema(schema_name, verbose=False)
try:
if verbose:
print("Creating a table: {} ... ".format(table_name_), end="")
self.engine.execute('CREATE TABLE {} ({});'.format(table_name_, column_specs))
print("Done.") if verbose else ""
except Exception as e:
print("Failed. {}".format(e))
def get_column_info(self, table_name, schema_name='public', as_dict=True):
"""
Get information about columns of a table.
:param table_name: name of a table
:type table_name: str
:param schema_name: name of a schema, defaults to ``'public'``
:type schema_name: str
:param as_dict: whether to return the column information as a dictionary,
defaults to ``True``
:type as_dict: bool
:return: information about each column of the given table
:rtype: pandas.DataFrame or dict
See the example for the method
:py:meth:`.create_table()<pyhelpers.sql.PostgreSQL.create_table>`.
"""
column_info = self.engine.execute(
"SELECT * FROM information_schema.columns "
"WHERE table_schema='{}' AND table_name='{}';".format(
schema_name, table_name))
keys, values = column_info.keys(), column_info.fetchall()
idx = ['column_{}'.format(x) for x in range(len(values))]
info_tbl = pd.DataFrame(values, index=idx, columns=keys).T
if as_dict:
info_tbl = {k: v.to_list() for k, v in info_tbl.iterrows()}
return info_tbl
def drop_table(self, table_name, schema_name='public', confirmation_required=True,
verbose=False):
"""
Remove a table from the database being connected.
:param table_name: name of a table
:type table_name: str
:param schema_name: name of a schema, defaults to ``'public'``
:type schema_name: str
:param confirmation_required: whether to prompt a message for confirmation to proceed,
defaults to ``True``
:type confirmation_required: bool
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool
See the example for the method
:py:meth:`.create_table()<pyhelpers.sql.PostgreSQL.create_table>`.
"""
table = '\"{}\".\"{}\"'.format(schema_name, table_name)
if not self.table_exists(table_name=table_name, schema_name=schema_name):
if verbose:
print("The table {} does not exist.".format(table))
else:
if confirmed("To drop the table {} from {}\n?".format(table, self.address),
confirmation_required=confirmation_required):
if verbose:
if confirmation_required:
log_msg = "Dropping {}".format(table)
else:
log_msg = "Dropping the table {} from {}".format(table, self.address)
print(log_msg, end=" ... ")
try:
self.engine.execute(
'DROP TABLE "{}"."{}" CASCADE;'.format(schema_name, table_name))
print("Done.") if verbose else ""
except Exception as e:
print("Failed. {}".format(e))
@staticmethod
def psql_insert_copy(sql_table, sql_db_engine, column_name_list, data_iter):
"""
A callable using PostgreSQL COPY clause for executing inserting data.
:param sql_table: pandas.io.sql.SQLTable
:param sql_db_engine: `sqlalchemy.engine.Connection`_ or `sqlalchemy.engine.Engine`_
:param column_name_list: (list of str) column names
:param data_iter: iterable that iterates the values to be inserted
.. _`sqlalchemy.engine.Connection`:
https://docs.sqlalchemy.org/en/13/core/connections.html#sqlalchemy.engine.Connection
.. _`sqlalchemy.engine.Engine`:
https://docs.sqlalchemy.org/en/13/core/connections.html#sqlalchemy.engine.Engine
.. note::
This function is copied and slightly modified from the source code available at
[`SQL-P-PIC-1 <https://pandas.pydata.org/pandas-docs/stable/user_guide/
io.html#io-sql-method>`_].
"""
con_cur = sql_db_engine.connection.cursor()
io_buffer = io.StringIO()
csv_writer = csv.writer(io_buffer)
csv_writer.writerows(data_iter)
io_buffer.seek(0)
sql_column_names = ', '.join('"{}"'.format(k) for k in column_name_list)
sql_table_name = '"{}"."{}"'.format(sql_table.schema, sql_table.name)
sql_query = 'COPY {} ({}) FROM STDIN WITH CSV'.format(sql_table_name, sql_column_names)
con_cur.copy_expert(sql=sql_query, file=io_buffer)
def import_data(self, data, table_name, schema_name='public', if_exists='replace',
force_replace=False, chunk_size=None, col_type=None, method='multi',
index=False, confirmation_required=True, verbose=False, **kwargs):
"""
Import tabular data into the database being connected.
See also [`SQL-P-DD-1
<https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method/>`_]
and [`SQL-P-DD-2
<https://www.postgresql.org/docs/current/sql-copy.html/>`_].