-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcore.py
1822 lines (1469 loc) · 59.1 KB
/
core.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
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
import logging
import os
import re
import sqlite3
from collections import OrderedDict, defaultdict
from collections.abc import Sequence
from sqlite3 import Connection, Cursor
from typing import TYPE_CHECKING, Any, Callable, Final, Optional, Union, cast
import pathvalidate
import typepy
from dataproperty.typing import TypeHint
from mbstrdecoder import MultiByteStrDecoder
from sqliteschema import SQLITE_SYSTEM_TABLES, SQLiteSchemaExtractor
from tabledata import TableData
from typepy import extract_typepy_from_dtype
from ._common import extract_table_metadata
from ._func import copy_table, validate_table_name
from ._logger import logger
from ._sanitizer import SQLiteTableDataSanitizer
from .converter import RecordConvertor
from .error import (
AttributeNotFoundError,
DatabaseError,
NameValidationError,
NullDatabaseConnectionError,
OperationalError,
TableNotFoundError,
)
from .query import (
Attr,
AttrList,
Insert,
InsertMany,
QueryItem,
Select,
Set,
Table,
Value,
WhereQuery,
make_index_name,
)
from .sqlquery import SqlQuery
if TYPE_CHECKING:
import pandas
MEMORY_DB_NAME: Final = ":memory:"
class SimpleSQLite:
"""
Wrapper class for |sqlite3| module.
:param str database_src:
SQLite database source. Acceptable types are:
(1) File path to a database to be connected.
(2) sqlite3.Connection instance.
(3) SimpleSQLite instance
:param str mode: Open mode.
:param bool delayed_connection:
Delaying connection to a database until access to the database the first time,
if the value is |True|.
:param int max_workers:
Maximum number of workers to generate a table.
In default, the same as the total number of CPUs.
:param bool profile:
Recording SQL query execution time profile, if the value is |True|.
:param Any **connect_kwargs:
Keyword arguments passing to
`sqlite3.connect <https://docs.python.org/3/library/sqlite3.html#sqlite3.connect>`__.
.. seealso::
:py:meth:`.connect`
:py:meth:`.get_profile`
"""
dup_col_handler = "error"
global_debug_query = False
@property
def database_path(self) -> Optional[str]:
"""
:return: File path of the connected database.
:rtype: str
:Examples:
>>> from simplesqlite import SimpleSQLite
>>> con = SimpleSQLite("sample.sqlite", "w")
>>> con.database_path
'/tmp/sample.sqlite'
>>> con.close()
>>> print(con.database_path)
None
"""
if self.__delayed_connection_path:
return self.__delayed_connection_path
return self.__database_path
@property
def connection(self) -> Optional[Connection]:
"""
:return: |Connection| instance of the connected database.
:rtype: sqlite3.Connection
"""
self.__delayed_connect()
return self.__connection
@property
def schema_extractor(self) -> SQLiteSchemaExtractor:
return SQLiteSchemaExtractor(self, max_workers=self.__max_workers)
@property
def total_changes(self) -> int:
"""
.. seealso::
:py:attr:`sqlite3.Connection.total_changes`
"""
self.check_connection()
return self.connection.total_changes # type: ignore
@property
def mode(self) -> Optional[str]:
"""
:return: Connection mode: ``"r"``/``"w"``/``"a"``.
:rtype: str
.. seealso:: :py:meth:`.connect`
"""
return self.__mode
def __initialize_connection(self) -> None:
self.__database_path: Optional[str] = None
self.__connection: Optional[Connection] = None
self.__mode: Optional[str] = None
self.__delayed_connection_path: Optional[str] = None
self.__dict_query_count: dict[str, int] = defaultdict(int)
self.__dict_query_totalexectime: dict[str, float] = defaultdict(float)
def __init__(
self,
database_src: Union[Connection, "SimpleSQLite", str],
mode: str = "a",
delayed_connection: bool = True,
max_workers: Optional[int] = None,
profile: bool = False,
**connect_kwargs: Any,
) -> None:
self.debug_query = False
self.__initialize_connection()
self.__mode = mode
self.__max_workers = max_workers
self.__is_profile = profile
self.__connect_kwargs = connect_kwargs
if database_src is None:
raise TypeError("database_src must be not None")
if isinstance(database_src, SimpleSQLite):
self.__connection = database_src.connection
self.__database_path = database_src.database_path
self.debug_query = database_src.debug_query
return
if isinstance(database_src, sqlite3.Connection):
self.__connection = database_src
return
if delayed_connection:
self.__delayed_connection_path = database_src
return
self.connect(database_src, mode)
def __del__(self) -> None:
self.close()
def __enter__(self): # type: ignore
return self
def __exit__(self, exc_type, exc_value, traceback) -> None: # type: ignore
self.close()
def __fspath__(self) -> str:
if not self.database_path:
raise ValueError("database is not connected")
if self.database_path == MEMORY_DB_NAME:
raise ValueError("database is in-memory")
return self.database_path
def is_connected(self) -> bool:
"""
:return: |True| if the connection to a database is valid.
:rtype: bool
:Examples:
>>> from simplesqlite import SimpleSQLite
>>> con = SimpleSQLite("sample.sqlite", "w")
>>> con.is_connected()
True
>>> con.close()
>>> con.is_connected()
False
"""
try:
self.check_connection()
except NullDatabaseConnectionError:
return False
return True
def check_connection(self) -> None:
"""
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:Sample Code:
.. code:: python
import simplesqlite
con = simplesqlite.SimpleSQLite("sample.sqlite", "w")
print("---- connected to a database ----")
con.check_connection()
print("---- disconnected from a database ----")
con.close()
try:
con.check_connection()
except simplesqlite.NullDatabaseConnectionError as e:
print(e)
:Output:
.. code-block:: none
---- connected to a database ----
---- disconnected from a database ----
null database connection
"""
if self.connection is None:
if not self.__delayed_connect():
raise NullDatabaseConnectionError("null database connection")
def connect(self, database_path: str, mode: str = "a") -> None:
"""
Connect to a SQLite database.
Parameters to open a connection to an SQLite database are passed via
``connect_kwargs`` argument of the constructor.
:param str database_path:
Path to the SQLite database file to be connected.
:param str mode:
``"r"``: Open for read only.
``"w"``: Open for read/write.
Delete existing tables when connecting.
``"a"``: Open for read/write. Append to the existing tables.
:raises ValueError:
If ``database_path`` is invalid or |attr_mode| is invalid.
:raises simplesqlite.DatabaseError:
If the file is encrypted or is not a database.
:raises simplesqlite.OperationalError:
If unable to open the database file.
"""
self.close()
logger.debug(f"connect to a SQLite database: path='{database_path}', mode={mode}")
if mode == "r":
self.__verify_db_file_existence(database_path)
elif mode in ["w", "a"]:
self.__validate_db_path(database_path)
else:
raise ValueError("unknown connection mode: " + mode)
if database_path == MEMORY_DB_NAME:
self.__database_path = database_path
else:
self.__database_path = os.path.realpath(database_path)
try:
self.__connection = sqlite3.connect(database_path, **self.__connect_kwargs)
except sqlite3.OperationalError as e:
raise OperationalError(e)
self.__mode = mode
try:
# validate connection after connect
self.fetch_table_names()
except sqlite3.DatabaseError as e:
raise DatabaseError(e)
if mode != "w":
return
for table in self.fetch_table_names():
self.drop_table(table)
def execute_query(
self, query: Union[str, QueryItem], caller: Optional[tuple] = None
) -> Optional[Cursor]:
"""
Send arbitrary SQLite query to the database.
:param query: Query to executed.
:param tuple caller:
Caller information.
Expects the return value of :py:meth:`logging.Logger.findCaller`.
:return: The result of the query execution.
:rtype: sqlite3.Cursor
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
.. warning::
This method can execute an arbitrary query.
i.e. No access permissions check by |attr_mode|.
"""
import time
self.check_connection()
queryStr = str(query)
if typepy.is_null_string(queryStr):
return None
if self.debug_query or self.global_debug_query:
logger.debug(queryStr)
exec_start_time = time.time()
assert self.connection # to avoid type check error
try:
result = self.connection.execute(queryStr)
except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
if caller is None:
caller = logging.getLogger().findCaller()
file_path, line_no, func_name = caller[:3]
raise OperationalError(
message="\n".join(
[
"failed to execute query at {:s}({:d}) {:s}".format(
file_path, line_no, func_name
),
f" - query: {MultiByteStrDecoder(queryStr).unicode_str}",
f" - msg: {e}",
f" - db: {self.database_path}",
]
)
)
if self.__is_profile:
self.__dict_query_count[queryStr] += 1
elapse_time = time.time() - exec_start_time
self.__dict_query_totalexectime[queryStr] += elapse_time
return result
def set_row_factory(self, row_factory: Optional[Callable]) -> None:
"""
Set row_factory to the database connection.
"""
self.check_connection()
self.__connection.row_factory = row_factory # type: ignore
def select(
self,
select: Union[str, AttrList],
table_name: str,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
) -> Optional[Cursor]:
"""
Send a SELECT query to the database.
:param select: Attribute for the ``SELECT`` query.
:param str table_name: |arg_select_table_name|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
:return: Result of the query execution.
:rtype: sqlite3.Cursor
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
"""
self.verify_table_existence(table_name)
return self.execute_query(
str(Select(select, table_name, where, extra)),
logging.getLogger().findCaller(),
)
def select_as_dataframe(
self,
table_name: str,
columns: Optional[Sequence[str]] = None,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
) -> "pandas.DataFrame":
"""
Get data in the database and return fetched data as a
:py:class:`pandas.Dataframe` instance.
:param str table_name: |arg_select_table_name|
:param columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:param extra: |arg_select_extra|
:return: Table data as a :py:class:`pandas.Dataframe` instance.
:rtype: pandas.DataFrame
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-select-as-dataframe`
.. note::
``pandas`` package required to execute this method.
"""
import pandas
if columns is None:
columns = self.fetch_attr_names(table_name)
result = self.select(
select=AttrList(columns), table_name=table_name, where=where, extra=extra
)
if result is None:
return pandas.DataFrame()
return pandas.DataFrame(result.fetchall(), columns=pandas.Index(columns))
def select_as_tabledata(
self,
table_name: str,
columns: Optional[Sequence[str]] = None,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
type_hints: Optional[dict[str, TypeHint]] = None,
) -> TableData:
"""
Get data in the database and return fetched data as a
:py:class:`tabledata.TableData` instance.
:param str table_name: |arg_select_table_name|
:param columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
:return: Table data as a :py:class:`tabledata.TableData` instance.
:rtype: tabledata.TableData
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
.. note::
``pandas`` package required to execute this method.
"""
if columns is None:
columns = self.fetch_attr_names(table_name)
result = self.select(
select=AttrList(columns), table_name=table_name, where=where, extra=extra
)
if result is None:
return TableData(None, [], [])
if type_hints is None:
type_hints = self.fetch_data_types(table_name)
return TableData(
table_name,
columns,
result.fetchall(),
type_hints=[type_hints.get(col) for col in columns],
max_workers=self.__max_workers,
)
def select_as_dict(
self,
table_name: str,
columns: Optional[Sequence[str]] = None,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
) -> Optional[list[OrderedDict[str, Any]]]:
"""
Get data in the database and return fetched data as a
|OrderedDict| list.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
:return: Table data as |OrderedDict| instances.
:rtype: |list| of |OrderedDict|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-select-as-dict`
"""
return self.select_as_tabledata(table_name, columns, where, extra).as_dict().get(table_name)
def select_as_memdb(
self,
table_name: str,
columns: Optional[Sequence[str]] = None,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
) -> "SimpleSQLite":
"""
Get data in the database and return fetched data as a
in-memory |SimpleSQLite| instance.
:param str table_name: |arg_select_table_name|
:param columns: |arg_select_as_xx_columns|
:param where: |arg_select_where|
:type where: |arg_where_type|
:param str extra: |arg_select_extra|
:return:
Table data as a |SimpleSQLite| instance that connected to in
memory database.
:rtype: |SimpleSQLite|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
"""
table_schema = self.schema_extractor.fetch_table_schema(table_name)
memdb = connect_memdb(max_workers=self.__max_workers)
memdb.create_table_from_tabledata(
self.select_as_tabledata(table_name, columns, where, extra),
primary_key=table_schema.primary_key,
index_attrs=table_schema.index_list,
)
return memdb
def insert(
self, table_name: str, record: Any, attr_names: Optional[Sequence[str]] = None
) -> bool:
"""
Send an INSERT query to the database.
:param str table_name: Table name of executing the query.
:param record: Record to be inserted.
:type record: |dict|/|namedtuple|/|list|/|tuple|
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-insert-records`
"""
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name, allow_view=False)
if attr_names is None:
attr_names = self.fetch_attr_names(table_name)
values = RecordConvertor.to_record(attr_names, record)
query = Insert(table_name, AttrList(attr_names), values).to_query()
if self.execute_query(query, logging.getLogger().findCaller()) is None:
return False
return True
def insert_many(
self,
table_name: str,
records: Sequence[Union[dict, Sequence]],
attr_names: Optional[Sequence[str]] = None,
) -> int:
"""
Send an INSERT query with multiple records to the database.
:param str table: Table name of executing the query.
:param records: Records to be inserted.
:type records: list of |dict|/|namedtuple|/|list|/|tuple|
:return: Number of inserted records.
:rtype: int
:raises IOError: |raises_write_permission|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-insert-records`
"""
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name, allow_view=False)
if attr_names:
logger.debug(
"insert {number} records into {table}({attrs})".format(
number=len(records) if records else 0, table=table_name, attrs=attr_names
)
)
else:
logger.debug(
"insert {number} records into {table}".format(
number=len(records) if records else 0, table=table_name
)
)
if typepy.is_empty_sequence(records):
return 0
if attr_names is None:
attr_names = self.fetch_attr_names(table_name)
records = RecordConvertor.to_records(attr_names, records)
query = InsertMany(table_name, AttrList(attr_names)).to_query()
if self.debug_query or self.global_debug_query:
logging_count = 8
num_records = len(records)
logs = [query] + [
f" record {i:4d}: {record}" for i, record in enumerate(records[:logging_count])
]
if num_records - logging_count > 0:
logs.append(f" and other {num_records - logging_count} records will be inserted")
logger.debug("\n".join(logs))
assert self.connection # to avoid type check error
try:
self.connection.executemany(query, records)
except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
caller = logging.getLogger().findCaller()
file_path, line_no, func_name = caller[:3]
raise OperationalError(
f"{file_path:s}({line_no:d}) {func_name:s}: failed to execute query:\n"
+ f" query={query}\n"
+ f" msg='{e}'\n"
+ f" db={self.database_path}\n"
+ f" records={records[:2]}\n"
)
return len(records)
def update(
self,
table_name: str,
set_query: Union[str, Sequence[Set]],
where: Optional[WhereQuery] = None,
) -> Optional[Cursor]:
"""Execute an UPDATE query.
Args:
table_name (|str|):
Table name of executing the query.
set_query (Union[str, Sequence[Set]]):
``SET`` clause for the update query.
where (|arg_where_type| , optional):
``WHERE`` clause for the update query.
Defaults to |None|.
Raises:
IOError:
|raises_write_permission|
simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
simplesqlite.OperationalError:
|raises_operational_error|
"""
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name, allow_view=False)
query = SqlQuery.make_update(table_name, set_query, where)
return self.execute_query(query, logging.getLogger().findCaller())
def delete(self, table_name: str, where: Optional[WhereQuery] = None) -> Optional[Cursor]:
"""
Send a DELETE query to the database.
:param str table_name: Table name of executing the query.
:param where: |arg_select_where|
:type where: |arg_where_type|
"""
self.validate_access_permission(["w", "a"])
self.verify_table_existence(table_name, allow_view=False)
query = f"DELETE FROM {table_name:s}"
if where:
query += f" WHERE {where:s}"
return self.execute_query(query, logging.getLogger().findCaller())
def fetch_value(
self,
select: str,
table_name: str,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
) -> Optional[int]:
"""
Fetch a value from the table. Return |None| if no value matches
the conditions, or the table not found in the database.
:param str select: Attribute for SELECT query
:param str table_name: Table name of executing the query.
:param where: |arg_select_where|
:type where: |arg_where_type|
:return: Result of execution of the query.
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
"""
try:
self.verify_table_existence(table_name)
except DatabaseError as e:
logger.debug(e)
return None
result = self.execute_query(
Select(select, table_name, where, extra), logging.getLogger().findCaller()
)
if result is None:
return None
fetch = result.fetchone()
if fetch is None:
return None
return fetch[0]
def fetch_values(
self,
select: Union[str, AttrList],
table_name: str,
where: Optional[WhereQuery] = None,
extra: Optional[str] = None,
) -> list:
result = self.select(select=select, table_name=table_name, where=where, extra=extra)
if result is None:
return []
return [record[0] for record in result.fetchall()]
def fetch_table_names(
self, include_system_table: bool = False, include_view: bool = True
) -> list[str]:
"""
:return: List of table names in the database.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Sample Code:
.. code:: python
from simplesqlite import SimpleSQLite
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
"hoge",
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.fetch_table_names())
:Output:
.. code-block:: python
['hoge']
"""
self.check_connection()
return self.schema_extractor.fetch_table_names(
include_system_table=include_system_table, include_view=include_view
)
def fetch_view_names(self) -> list[str]:
"""
:return: List of table names in the database.
:rtype: list
"""
self.check_connection()
return self.schema_extractor.fetch_view_names()
def fetch_attr_names(self, table_name: str) -> list[str]:
"""
:return: List of attribute names in the table.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
.. code:: python
import simplesqlite
table_name = "sample_table"
con = simplesqlite.SimpleSQLite("sample.sqlite", "w")
con.create_table_from_data_matrix(
table_name,
["attr_a", "attr_b"],
[[1, "a"], [2, "b"]])
print(con.fetch_attr_names(table_name))
try:
print(con.fetch_attr_names("not_existing"))
except simplesqlite.TableNotFoundError as e:
print(e)
:Output:
.. parsed-literal::
['attr_a', 'attr_b']
'not_existing' table not found in /tmp/sample.sqlite
"""
self.verify_table_existence(table_name)
return self.schema_extractor.fetch_table_schema(table_name).get_attr_names()
def fetch_attr_type(self, table_name: str) -> dict[str, str]:
"""
:return:
Dictionary of attribute names and attribute types in the table.
:rtype: dict
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.TableNotFoundError:
|raises_verify_table_existence|
:raises simplesqlite.OperationalError: |raises_operational_error|
"""
self.verify_table_existence(table_name, allow_view=False)
result = self.execute_query(
"SELECT sql FROM sqlite_master WHERE type='table' and name={:s}".format(
Value(table_name)
)
)
assert result # to avoid type check error
query = result.fetchone()[0]
match = re.search("[(].*[)]", query)
assert match # to avoid type check error
def get_entry(items: list[str]) -> list[str]:
key = " ".join(items[:-1])
value = items[-1]
return [key, value]
return dict([get_entry(item.split(" ")) for item in match.group().strip("()").split(", ")])
def fetch_num_records(
self, table_name: str, where: Optional[WhereQuery] = None
) -> Optional[int]:
"""
Fetch the number of records in a table.
:param str table_name: Table name to get number of records.
:param where: |arg_select_where|
:type where: |arg_where_type|
:return:
Number of records in the table.
|None| if no value matches the conditions,
or the table not found in the database.
:rtype: int
"""
return self.fetch_value(select="COUNT(*)", table_name=table_name, where=where)
def fetch_data_types(self, table_name: str) -> dict[str, TypeHint]:
_, _, type_hints = extract_table_metadata(self, table_name)
return type_hints
def get_profile(self, profile_count: int = 50) -> list[Any]:
"""
Get profile of query execution time.
:param int profile_count:
Number of profiles to retrieve,
counted from the top query in descending order by
the cumulative execution time.
:return: Profile information for each query.
:rtype: list of |namedtuple|
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|
:raises simplesqlite.OperationalError: |raises_operational_error|
:Example:
:ref:`example-get-profile`
"""
from collections import namedtuple
profile_table_name = "sql_profile"
value_matrix = [
[query, execute_time, self.__dict_query_count.get(query, 0)]
for query, execute_time in self.__dict_query_totalexectime.items()
]
attr_names = ("sql_query", "cumulative_time", "count")
con_tmp = connect_memdb(max_workers=self.__max_workers)
try:
con_tmp.create_table_from_data_matrix(
profile_table_name, attr_names, data_matrix=value_matrix
)
except ValueError:
return []
try:
result = con_tmp.select(
select="{:s},SUM({:s}),SUM({:s})".format(*attr_names),
table_name=profile_table_name,
extra="GROUP BY {:s} ORDER BY {:s} DESC LIMIT {:d}".format(
attr_names[0], attr_names[1], profile_count
),
)
except sqlite3.OperationalError:
return []
if result is None:
return []
SqliteProfile = namedtuple("SqliteProfile", " ".join(attr_names)) # type: ignore
return [SqliteProfile(*profile) for profile in result.fetchall()]
def fetch_sqlite_master(self) -> list[dict]:
"""
Get sqlite_master table information as a list of dictionaries.
:return: sqlite_master table information.
:rtype: list
:raises simplesqlite.NullDatabaseConnectionError:
|raises_check_connection|