zmc
2023-10-12 ed135d79df12a2466b52dae1a82326941211dcc9
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
U
¸ý°d±‚ã@sdZddlmZddlZddlZddlZddlmZddlm    Z    ddlm
Z
ddlm Z d    d
l m Z d    d l mZd    d l mZd    d l mZd    dl mZd    dl mZd    dlmZd    dlmZd    dlmZd    dlmZd    dlmZd    dlmZd    dlmZd    dlmZd    dlmZd    d lmZd    dlm Z d    dlm!Z!d    dlm"Z"d    dlm#Z#d    dlm$Z$d    dlm%Z%d    dlm&Z&d    d lm'Z'd    d!lm(Z(d    d"lm)Z)d    d#lm*Z*d    d$lm+Z+Gd%d&„d&e    ƒZ,Gd'd(„d(ƒZ-Gd)d*„d*e-ej.ƒZ/Gd+d,„d,e-ej0ƒZ1Gd-d.„d.e-ej2ƒZ3ej0e1ej.e/ej    e,ej    j
e
ej    j e ej2e3iZ4ej5ej ej!ej!ej"ej1ej1ej/ej/ej6ej#ej$ej%ej%e    ej&ej'ej(ej)ej3ej3ej*ej+ej7ej8d/œZ9Gd0d1„d1ej:ƒZ;Gd2d3„d3ej<ƒZ=Gd4d5„d5ej>ƒZ?Gd6d7„d7ej@ƒZAGd8d9„d9ejBƒZCGd:d;„d;ejDƒZEdS)<a {
.. dialect:: sqlite
    :name: SQLite
    :full_support: 3.21, 3.28+
    :normal_support: 3.12+
    :best_effort: 3.7.16+
 
.. _sqlite_datetime:
 
Date and Time Types
-------------------
 
SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does
not provide out of the box functionality for translating values between Python
`datetime` objects and a SQLite-supported format. SQLAlchemy's own
:class:`~sqlalchemy.types.DateTime` and related types provide date formatting
and parsing functionality when SQLite is used. The implementation classes are
:class:`_sqlite.DATETIME`, :class:`_sqlite.DATE` and :class:`_sqlite.TIME`.
These types represent dates and times as ISO formatted strings, which also
nicely support ordering. There's no reliance on typical "libc" internals for
these functions so historical dates are fully supported.
 
Ensuring Text affinity
^^^^^^^^^^^^^^^^^^^^^^
 
The DDL rendered for these types is the standard ``DATE``, ``TIME``
and ``DATETIME`` indicators.    However, custom storage formats can also be
applied to these types.   When the
storage format is detected as containing no alpha characters, the DDL for
these types is rendered as ``DATE_CHAR``, ``TIME_CHAR``, and ``DATETIME_CHAR``,
so that the column continues to have textual affinity.
 
.. seealso::
 
    `Type Affinity <https://www.sqlite.org/datatype3.html#affinity>`_ -
    in the SQLite documentation
 
.. _sqlite_autoincrement:
 
SQLite Auto Incrementing Behavior
----------------------------------
 
Background on SQLite's autoincrement is at: https://sqlite.org/autoinc.html
 
Key concepts:
 
* SQLite has an implicit "auto increment" feature that takes place for any
  non-composite primary-key column that is specifically created using
  "INTEGER PRIMARY KEY" for the type + primary key.
 
* SQLite also has an explicit "AUTOINCREMENT" keyword, that is **not**
  equivalent to the implicit autoincrement feature; this keyword is not
  recommended for general use.  SQLAlchemy does not render this keyword
  unless a special SQLite-specific directive is used (see below).  However,
  it still requires that the column's type is named "INTEGER".
 
Using the AUTOINCREMENT Keyword
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
To specifically render the AUTOINCREMENT keyword on the primary key column
when rendering DDL, add the flag ``sqlite_autoincrement=True`` to the Table
construct::
 
    Table('sometable', metadata,
            Column('id', Integer, primary_key=True),
            sqlite_autoincrement=True)
 
Allowing autoincrement behavior SQLAlchemy types other than Integer/INTEGER
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
SQLite's typing model is based on naming conventions.  Among other things, this
means that any type name which contains the substring ``"INT"`` will be
determined to be of "integer affinity".  A type named ``"BIGINT"``,
``"SPECIAL_INT"`` or even ``"XYZINTQPR"``, will be considered by SQLite to be
of "integer" affinity.  However, **the SQLite autoincrement feature, whether
implicitly or explicitly enabled, requires that the name of the column's type
is exactly the string "INTEGER"**.  Therefore, if an application uses a type
like :class:`.BigInteger` for a primary key, on SQLite this type will need to
be rendered as the name ``"INTEGER"`` when emitting the initial ``CREATE
TABLE`` statement in order for the autoincrement behavior to be available.
 
One approach to achieve this is to use :class:`.Integer` on SQLite
only using :meth:`.TypeEngine.with_variant`::
 
    table = Table(
        "my_table", metadata,
        Column("id", BigInteger().with_variant(Integer, "sqlite"), primary_key=True)
    )
 
Another is to use a subclass of :class:`.BigInteger` that overrides its DDL
name to be ``INTEGER`` when compiled against SQLite::
 
    from sqlalchemy import BigInteger
    from sqlalchemy.ext.compiler import compiles
 
    class SLBigInteger(BigInteger):
        pass
 
    @compiles(SLBigInteger, 'sqlite')
    def bi_c(element, compiler, **kw):
        return "INTEGER"
 
    @compiles(SLBigInteger)
    def bi_c(element, compiler, **kw):
        return compiler.visit_BIGINT(element, **kw)
 
 
    table = Table(
        "my_table", metadata,
        Column("id", SLBigInteger(), primary_key=True)
    )
 
.. seealso::
 
    :meth:`.TypeEngine.with_variant`
 
    :ref:`sqlalchemy.ext.compiler_toplevel`
 
    `Datatypes In SQLite Version 3 <https://sqlite.org/datatype3.html>`_
 
.. _sqlite_concurrency:
 
Database Locking Behavior / Concurrency
---------------------------------------
 
SQLite is not designed for a high level of write concurrency. The database
itself, being a file, is locked completely during write operations within
transactions, meaning exactly one "connection" (in reality a file handle)
has exclusive access to the database during this period - all other
"connections" will be blocked during this time.
 
The Python DBAPI specification also calls for a connection model that is
always in a transaction; there is no ``connection.begin()`` method,
only ``connection.commit()`` and ``connection.rollback()``, upon which a
new transaction is to be begun immediately.  This may seem to imply
that the SQLite driver would in theory allow only a single filehandle on a
particular database file at any time; however, there are several
factors both within SQLite itself as well as within the pysqlite driver
which loosen this restriction significantly.
 
However, no matter what locking modes are used, SQLite will still always
lock the database file once a transaction is started and DML (e.g. INSERT,
UPDATE, DELETE) has at least been emitted, and this will block
other transactions at least at the point that they also attempt to emit DML.
By default, the length of time on this block is very short before it times out
with an error.
 
This behavior becomes more critical when used in conjunction with the
SQLAlchemy ORM.  SQLAlchemy's :class:`.Session` object by default runs
within a transaction, and with its autoflush model, may emit DML preceding
any SELECT statement.   This may lead to a SQLite database that locks
more quickly than is expected.   The locking mode of SQLite and the pysqlite
driver can be manipulated to some degree, however it should be noted that
achieving a high degree of write-concurrency with SQLite is a losing battle.
 
For more information on SQLite's lack of write concurrency by design, please
see
`Situations Where Another RDBMS May Work Better - High Concurrency
<https://www.sqlite.org/whentouse.html>`_ near the bottom of the page.
 
The following subsections introduce areas that are impacted by SQLite's
file-based architecture and additionally will usually require workarounds to
work when using the pysqlite driver.
 
.. _sqlite_isolation_level:
 
Transaction Isolation Level / Autocommit
----------------------------------------
 
SQLite supports "transaction isolation" in a non-standard way, along two
axes.  One is that of the
`PRAGMA read_uncommitted <https://www.sqlite.org/pragma.html#pragma_read_uncommitted>`_
instruction.   This setting can essentially switch SQLite between its
default mode of ``SERIALIZABLE`` isolation, and a "dirty read" isolation
mode normally referred to as ``READ UNCOMMITTED``.
 
SQLAlchemy ties into this PRAGMA statement using the
:paramref:`_sa.create_engine.isolation_level` parameter of
:func:`_sa.create_engine`.
Valid values for this parameter when used with SQLite are ``"SERIALIZABLE"``
and ``"READ UNCOMMITTED"`` corresponding to a value of 0 and 1, respectively.
SQLite defaults to ``SERIALIZABLE``, however its behavior is impacted by
the pysqlite driver's default behavior.
 
When using the pysqlite driver, the ``"AUTOCOMMIT"`` isolation level is also
available, which will alter the pysqlite connection using the ``.isolation_level``
attribute on the DBAPI connection and set it to None for the duration
of the setting.
 
.. versionadded:: 1.3.16 added support for SQLite AUTOCOMMIT isolation level
   when using the pysqlite / sqlite3 SQLite driver.
 
 
The other axis along which SQLite's transactional locking is impacted is
via the nature of the ``BEGIN`` statement used.   The three varieties
are "deferred", "immediate", and "exclusive", as described at
`BEGIN TRANSACTION <https://sqlite.org/lang_transaction.html>`_.   A straight
``BEGIN`` statement uses the "deferred" mode, where the database file is
not locked until the first read or write operation, and read access remains
open to other transactions until the first write operation.  But again,
it is critical to note that the pysqlite driver interferes with this behavior
by *not even emitting BEGIN* until the first write operation.
 
.. warning::
 
    SQLite's transactional scope is impacted by unresolved
    issues in the pysqlite driver, which defers BEGIN statements to a greater
    degree than is often feasible. See the section :ref:`pysqlite_serializable`
    for techniques to work around this behavior.
 
.. seealso::
 
    :ref:`dbapi_autocommit`
 
INSERT/UPDATE/DELETE...RETURNING
---------------------------------
 
The SQLite dialect supports SQLite 3.35's  ``INSERT|UPDATE|DELETE..RETURNING``
syntax.   ``INSERT..RETURNING`` may be used
automatically in some cases in order to fetch newly generated identifiers in
place of the traditional approach of using ``cursor.lastrowid``, however
``cursor.lastrowid`` is currently still preferred for simple single-statement
cases for its better performance.
 
To specify an explicit ``RETURNING`` clause, use the
:meth:`._UpdateBase.returning` method on a per-statement basis::
 
    # INSERT..RETURNING
    result = connection.execute(
        table.insert().
        values(name='foo').
        returning(table.c.col1, table.c.col2)
    )
    print(result.all())
 
    # UPDATE..RETURNING
    result = connection.execute(
        table.update().
        where(table.c.name=='foo').
        values(name='bar').
        returning(table.c.col1, table.c.col2)
    )
    print(result.all())
 
    # DELETE..RETURNING
    result = connection.execute(
        table.delete().
        where(table.c.name=='foo').
        returning(table.c.col1, table.c.col2)
    )
    print(result.all())
 
.. versionadded:: 2.0  Added support for SQLite RETURNING
 
SAVEPOINT Support
----------------------------
 
SQLite supports SAVEPOINTs, which only function once a transaction is
begun.   SQLAlchemy's SAVEPOINT support is available using the
:meth:`_engine.Connection.begin_nested` method at the Core level, and
:meth:`.Session.begin_nested` at the ORM level.   However, SAVEPOINTs
won't work at all with pysqlite unless workarounds are taken.
 
.. warning::
 
    SQLite's SAVEPOINT feature is impacted by unresolved
    issues in the pysqlite driver, which defers BEGIN statements to a greater
    degree than is often feasible. See the section :ref:`pysqlite_serializable`
    for techniques to work around this behavior.
 
Transactional DDL
----------------------------
 
The SQLite database supports transactional :term:`DDL` as well.
In this case, the pysqlite driver is not only failing to start transactions,
it also is ending any existing transaction when DDL is detected, so again,
workarounds are required.
 
.. warning::
 
    SQLite's transactional DDL is impacted by unresolved issues
    in the pysqlite driver, which fails to emit BEGIN and additionally
    forces a COMMIT to cancel any transaction when DDL is encountered.
    See the section :ref:`pysqlite_serializable`
    for techniques to work around this behavior.
 
.. _sqlite_foreign_keys:
 
Foreign Key Support
-------------------
 
SQLite supports FOREIGN KEY syntax when emitting CREATE statements for tables,
however by default these constraints have no effect on the operation of the
table.
 
Constraint checking on SQLite has three prerequisites:
 
* At least version 3.6.19 of SQLite must be in use
* The SQLite library must be compiled *without* the SQLITE_OMIT_FOREIGN_KEY
  or SQLITE_OMIT_TRIGGER symbols enabled.
* The ``PRAGMA foreign_keys = ON`` statement must be emitted on all
  connections before use -- including the initial call to
  :meth:`sqlalchemy.schema.MetaData.create_all`.
 
SQLAlchemy allows for the ``PRAGMA`` statement to be emitted automatically for
new connections through the usage of events::
 
    from sqlalchemy.engine import Engine
    from sqlalchemy import event
 
    @event.listens_for(Engine, "connect")
    def set_sqlite_pragma(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()
 
.. warning::
 
    When SQLite foreign keys are enabled, it is **not possible**
    to emit CREATE or DROP statements for tables that contain
    mutually-dependent foreign key constraints;
    to emit the DDL for these tables requires that ALTER TABLE be used to
    create or drop these constraints separately, for which SQLite has
    no support.
 
.. seealso::
 
    `SQLite Foreign Key Support <https://www.sqlite.org/foreignkeys.html>`_
    - on the SQLite web site.
 
    :ref:`event_toplevel` - SQLAlchemy event API.
 
    :ref:`use_alter` - more information on SQLAlchemy's facilities for handling
     mutually-dependent foreign key constraints.
 
.. _sqlite_on_conflict_ddl:
 
ON CONFLICT support for constraints
-----------------------------------
 
.. seealso:: This section describes the :term:`DDL` version of "ON CONFLICT" for
   SQLite, which occurs within a CREATE TABLE statement.  For "ON CONFLICT" as
   applied to an INSERT statement, see :ref:`sqlite_on_conflict_insert`.
 
SQLite supports a non-standard DDL clause known as ON CONFLICT which can be applied
to primary key, unique, check, and not null constraints.   In DDL, it is
rendered either within the "CONSTRAINT" clause or within the column definition
itself depending on the location of the target constraint.    To render this
clause within DDL, the extension parameter ``sqlite_on_conflict`` can be
specified with a string conflict resolution algorithm within the
:class:`.PrimaryKeyConstraint`, :class:`.UniqueConstraint`,
:class:`.CheckConstraint` objects.  Within the :class:`_schema.Column` object,
there
are individual parameters ``sqlite_on_conflict_not_null``,
``sqlite_on_conflict_primary_key``, ``sqlite_on_conflict_unique`` which each
correspond to the three types of relevant constraint types that can be
indicated from a :class:`_schema.Column` object.
 
.. seealso::
 
    `ON CONFLICT <https://www.sqlite.org/lang_conflict.html>`_ - in the SQLite
    documentation
 
.. versionadded:: 1.3
 
 
The ``sqlite_on_conflict`` parameters accept a  string argument which is just
the resolution name to be chosen, which on SQLite can be one of ROLLBACK,
ABORT, FAIL, IGNORE, and REPLACE.   For example, to add a UNIQUE constraint
that specifies the IGNORE algorithm::
 
    some_table = Table(
        'some_table', metadata,
        Column('id', Integer, primary_key=True),
        Column('data', Integer),
        UniqueConstraint('id', 'data', sqlite_on_conflict='IGNORE')
    )
 
The above renders CREATE TABLE DDL as::
 
    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        data INTEGER,
        PRIMARY KEY (id),
        UNIQUE (id, data) ON CONFLICT IGNORE
    )
 
 
When using the :paramref:`_schema.Column.unique`
flag to add a UNIQUE constraint
to a single column, the ``sqlite_on_conflict_unique`` parameter can
be added to the :class:`_schema.Column` as well, which will be added to the
UNIQUE constraint in the DDL::
 
    some_table = Table(
        'some_table', metadata,
        Column('id', Integer, primary_key=True),
        Column('data', Integer, unique=True,
               sqlite_on_conflict_unique='IGNORE')
    )
 
rendering::
 
    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        data INTEGER,
        PRIMARY KEY (id),
        UNIQUE (data) ON CONFLICT IGNORE
    )
 
To apply the FAIL algorithm for a NOT NULL constraint,
``sqlite_on_conflict_not_null`` is used::
 
    some_table = Table(
        'some_table', metadata,
        Column('id', Integer, primary_key=True),
        Column('data', Integer, nullable=False,
               sqlite_on_conflict_not_null='FAIL')
    )
 
this renders the column inline ON CONFLICT phrase::
 
    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        data INTEGER NOT NULL ON CONFLICT FAIL,
        PRIMARY KEY (id)
    )
 
 
Similarly, for an inline primary key, use ``sqlite_on_conflict_primary_key``::
 
    some_table = Table(
        'some_table', metadata,
        Column('id', Integer, primary_key=True,
               sqlite_on_conflict_primary_key='FAIL')
    )
 
SQLAlchemy renders the PRIMARY KEY constraint separately, so the conflict
resolution algorithm is applied to the constraint itself::
 
    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        PRIMARY KEY (id) ON CONFLICT FAIL
    )
 
.. _sqlite_on_conflict_insert:
 
INSERT...ON CONFLICT (Upsert)
-----------------------------------
 
.. seealso:: This section describes the :term:`DML` version of "ON CONFLICT" for
   SQLite, which occurs within an INSERT statement.  For "ON CONFLICT" as
   applied to a CREATE TABLE statement, see :ref:`sqlite_on_conflict_ddl`.
 
From version 3.24.0 onwards, SQLite supports "upserts" (update or insert)
of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT``
statement. A candidate row will only be inserted if that row does not violate
any unique or primary key constraints. In the case of a unique constraint violation, a
secondary action can occur which can be either "DO UPDATE", indicating that
the data in the target row should be updated, or "DO NOTHING", which indicates
to silently skip this row.
 
Conflicts are determined using columns that are part of existing unique
constraints and indexes.  These constraints are identified by stating the
columns and conditions that comprise the indexes.
 
SQLAlchemy provides ``ON CONFLICT`` support via the SQLite-specific
:func:`_sqlite.insert()` function, which provides
the generative methods :meth:`_sqlite.Insert.on_conflict_do_update`
and :meth:`_sqlite.Insert.on_conflict_do_nothing`:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy.dialects.sqlite import insert
 
    >>> insert_stmt = insert(my_table).values(
    ...     id='some_existing_id',
    ...     data='inserted value')
 
    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     index_elements=['id'],
    ...     set_=dict(data='updated value')
    ... )
 
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?{stop}
 
    >>> do_nothing_stmt = insert_stmt.on_conflict_do_nothing(
    ...     index_elements=['id']
    ... )
 
    >>> print(do_nothing_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
    ON CONFLICT (id) DO NOTHING
 
.. versionadded:: 1.4
 
.. seealso::
 
    `Upsert
    <https://sqlite.org/lang_UPSERT.html>`_
    - in the SQLite documentation.
 
 
Specifying the Target
^^^^^^^^^^^^^^^^^^^^^
 
Both methods supply the "target" of the conflict using column inference:
 
* The :paramref:`_sqlite.Insert.on_conflict_do_update.index_elements` argument
  specifies a sequence containing string column names, :class:`_schema.Column`
  objects, and/or SQL expression elements, which would identify a unique index
  or unique constraint.
 
* When using :paramref:`_sqlite.Insert.on_conflict_do_update.index_elements`
  to infer an index, a partial index can be inferred by also specifying the
  :paramref:`_sqlite.Insert.on_conflict_do_update.index_where` parameter:
 
  .. sourcecode:: pycon+sql
 
        >>> stmt = insert(my_table).values(user_email='a@b.com', data='inserted data')
 
        >>> do_update_stmt = stmt.on_conflict_do_update(
        ...     index_elements=[my_table.c.user_email],
        ...     index_where=my_table.c.user_email.like('%@gmail.com'),
        ...     set_=dict(data=stmt.excluded.data)
        ...     )
 
        >>> print(do_update_stmt)
        {printsql}INSERT INTO my_table (data, user_email) VALUES (?, ?)
        ON CONFLICT (user_email)
        WHERE user_email LIKE '%@gmail.com'
        DO UPDATE SET data = excluded.data
 
The SET Clause
^^^^^^^^^^^^^^^
 
``ON CONFLICT...DO UPDATE`` is used to perform an update of the already
existing row, using any combination of new values as well as values
from the proposed insertion. These values are specified using the
:paramref:`_sqlite.Insert.on_conflict_do_update.set_` parameter.  This
parameter accepts a dictionary which consists of direct values
for UPDATE:
 
.. sourcecode:: pycon+sql
 
    >>> stmt = insert(my_table).values(id='some_id', data='inserted value')
 
    >>> do_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=['id'],
    ...     set_=dict(data='updated value')
    ... )
 
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?
 
.. warning::
 
    The :meth:`_sqlite.Insert.on_conflict_do_update` method does **not** take
    into account Python-side default UPDATE values or generation functions,
    e.g. those specified using :paramref:`_schema.Column.onupdate`. These
    values will not be exercised for an ON CONFLICT style of UPDATE, unless
    they are manually specified in the
    :paramref:`_sqlite.Insert.on_conflict_do_update.set_` dictionary.
 
Updating using the Excluded INSERT Values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
In order to refer to the proposed insertion row, the special alias
:attr:`~.sqlite.Insert.excluded` is available as an attribute on
the :class:`_sqlite.Insert` object; this object creates an "excluded." prefix
on a column, that informs the DO UPDATE to update the row with the value that
would have been inserted had the constraint not failed:
 
.. sourcecode:: pycon+sql
 
    >>> stmt = insert(my_table).values(
    ...     id='some_id',
    ...     data='inserted value',
    ...     author='jlh'
    ... )
 
    >>> do_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=['id'],
    ...     set_=dict(data='updated value', author=stmt.excluded.author)
    ... )
 
    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author) VALUES (?, ?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?, author = excluded.author
 
Additional WHERE Criteria
^^^^^^^^^^^^^^^^^^^^^^^^^
 
The :meth:`_sqlite.Insert.on_conflict_do_update` method also accepts
a WHERE clause using the :paramref:`_sqlite.Insert.on_conflict_do_update.where`
parameter, which will limit those rows which receive an UPDATE:
 
.. sourcecode:: pycon+sql
 
    >>> stmt = insert(my_table).values(
    ...     id='some_id',
    ...     data='inserted value',
    ...     author='jlh'
    ... )
 
    >>> on_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=['id'],
    ...     set_=dict(data='updated value', author=stmt.excluded.author),
    ...     where=(my_table.c.status == 2)
    ... )
    >>> print(on_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author) VALUES (?, ?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?, author = excluded.author
    WHERE my_table.status = ?
 
 
Skipping Rows with DO NOTHING
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
``ON CONFLICT`` may be used to skip inserting a row entirely
if any conflict with a unique constraint occurs; below this is illustrated
using the :meth:`_sqlite.Insert.on_conflict_do_nothing` method:
 
.. sourcecode:: pycon+sql
 
    >>> stmt = insert(my_table).values(id='some_id', data='inserted value')
    >>> stmt = stmt.on_conflict_do_nothing(index_elements=['id'])
    >>> print(stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?) ON CONFLICT (id) DO NOTHING
 
 
If ``DO NOTHING`` is used without specifying any columns or constraint,
it has the effect of skipping the INSERT for any unique violation which
occurs:
 
.. sourcecode:: pycon+sql
 
    >>> stmt = insert(my_table).values(id='some_id', data='inserted value')
    >>> stmt = stmt.on_conflict_do_nothing()
    >>> print(stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?) ON CONFLICT DO NOTHING
 
.. _sqlite_type_reflection:
 
Type Reflection
---------------
 
SQLite types are unlike those of most other database backends, in that
the string name of the type usually does not correspond to a "type" in a
one-to-one fashion.  Instead, SQLite links per-column typing behavior
to one of five so-called "type affinities" based on a string matching
pattern for the type.
 
SQLAlchemy's reflection process, when inspecting types, uses a simple
lookup table to link the keywords returned to provided SQLAlchemy types.
This lookup table is present within the SQLite dialect as it is for all
other dialects.  However, the SQLite dialect has a different "fallback"
routine for when a particular type name is not located in the lookup map;
it instead implements the SQLite "type affinity" scheme located at
https://www.sqlite.org/datatype3.html section 2.1.
 
The provided typemap will make direct associations from an exact string
name match for the following types:
 
:class:`_types.BIGINT`, :class:`_types.BLOB`,
:class:`_types.BOOLEAN`, :class:`_types.BOOLEAN`,
:class:`_types.CHAR`, :class:`_types.DATE`,
:class:`_types.DATETIME`, :class:`_types.FLOAT`,
:class:`_types.DECIMAL`, :class:`_types.FLOAT`,
:class:`_types.INTEGER`, :class:`_types.INTEGER`,
:class:`_types.NUMERIC`, :class:`_types.REAL`,
:class:`_types.SMALLINT`, :class:`_types.TEXT`,
:class:`_types.TIME`, :class:`_types.TIMESTAMP`,
:class:`_types.VARCHAR`, :class:`_types.NVARCHAR`,
:class:`_types.NCHAR`
 
When a type name does not match one of the above types, the "type affinity"
lookup is used instead:
 
* :class:`_types.INTEGER` is returned if the type name includes the
  string ``INT``
* :class:`_types.TEXT` is returned if the type name includes the
  string ``CHAR``, ``CLOB`` or ``TEXT``
* :class:`_types.NullType` is returned if the type name includes the
  string ``BLOB``
* :class:`_types.REAL` is returned if the type name includes the string
  ``REAL``, ``FLOA`` or ``DOUB``.
* Otherwise, the :class:`_types.NUMERIC` type is used.
 
.. _sqlite_partial_index:
 
Partial Indexes
---------------
 
A partial index, e.g. one which uses a WHERE clause, can be specified
with the DDL system using the argument ``sqlite_where``::
 
    tbl = Table('testtbl', m, Column('data', Integer))
    idx = Index('test_idx1', tbl.c.data,
                sqlite_where=and_(tbl.c.data > 5, tbl.c.data < 10))
 
The index will be rendered at create time as::
 
    CREATE INDEX test_idx1 ON testtbl (data)
    WHERE data > 5 AND data < 10
 
.. _sqlite_dotted_column_names:
 
Dotted Column Names
-------------------
 
Using table or column names that explicitly have periods in them is
**not recommended**.   While this is generally a bad idea for relational
databases in general, as the dot is a syntactically significant character,
the SQLite driver up until version **3.10.0** of SQLite has a bug which
requires that SQLAlchemy filter out these dots in result sets.
 
The bug, entirely outside of SQLAlchemy, can be illustrated thusly::
 
    import sqlite3
 
    assert sqlite3.sqlite_version_info < (3, 10, 0), "bug is fixed in this version"
 
    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()
 
    cursor.execute("create table x (a integer, b integer)")
    cursor.execute("insert into x (a, b) values (1, 1)")
    cursor.execute("insert into x (a, b) values (2, 2)")
 
    cursor.execute("select x.a, x.b from x")
    assert [c[0] for c in cursor.description] == ['a', 'b']
 
    cursor.execute('''
        select x.a, x.b from x where a=1
        union
        select x.a, x.b from x where a=2
    ''')
    assert [c[0] for c in cursor.description] == ['a', 'b'], \
        [c[0] for c in cursor.description]
 
The second assertion fails::
 
    Traceback (most recent call last):
      File "test.py", line 19, in <module>
        [c[0] for c in cursor.description]
    AssertionError: ['x.a', 'x.b']
 
Where above, the driver incorrectly reports the names of the columns
including the name of the table, which is entirely inconsistent vs.
when the UNION is not present.
 
SQLAlchemy relies upon column names being predictable in how they match
to the original statement, so the SQLAlchemy dialect has no choice but
to filter these out::
 
 
    from sqlalchemy import create_engine
 
    eng = create_engine("sqlite://")
    conn = eng.connect()
 
    conn.exec_driver_sql("create table x (a integer, b integer)")
    conn.exec_driver_sql("insert into x (a, b) values (1, 1)")
    conn.exec_driver_sql("insert into x (a, b) values (2, 2)")
 
    result = conn.exec_driver_sql("select x.a, x.b from x")
    assert result.keys() == ["a", "b"]
 
    result = conn.exec_driver_sql('''
        select x.a, x.b from x where a=1
        union
        select x.a, x.b from x where a=2
    ''')
    assert result.keys() == ["a", "b"]
 
Note that above, even though SQLAlchemy filters out the dots, *both
names are still addressable*::
 
    >>> row = result.first()
    >>> row["a"]
    1
    >>> row["x.a"]
    1
    >>> row["b"]
    1
    >>> row["x.b"]
    1
 
Therefore, the workaround applied by SQLAlchemy only impacts
:meth:`_engine.CursorResult.keys` and :meth:`.Row.keys()` in the public API. In
the very specific case where an application is forced to use column names that
contain dots, and the functionality of :meth:`_engine.CursorResult.keys` and
:meth:`.Row.keys()` is required to return these dotted names unmodified,
the ``sqlite_raw_colnames`` execution option may be provided, either on a
per-:class:`_engine.Connection` basis::
 
    result = conn.execution_options(sqlite_raw_colnames=True).exec_driver_sql('''
        select x.a, x.b from x where a=1
        union
        select x.a, x.b from x where a=2
    ''')
    assert result.keys() == ["x.a", "x.b"]
 
or on a per-:class:`_engine.Engine` basis::
 
    engine = create_engine("sqlite://", execution_options={"sqlite_raw_colnames": True})
 
When using the per-:class:`_engine.Engine` execution option, note that
**Core and ORM queries that use UNION may not function properly**.
 
SQLite-specific table options
-----------------------------
 
One option for CREATE TABLE is supported directly by the SQLite
dialect in conjunction with the :class:`_schema.Table` construct:
 
* ``WITHOUT ROWID``::
 
    Table("some_table", metadata, ..., sqlite_with_rowid=False)
 
.. seealso::
 
    `SQLite CREATE TABLE options
    <https://www.sqlite.org/lang_createtable.html>`_
 
 
.. _sqlite_include_internal:
 
Reflecting internal schema tables
----------------------------------
 
Reflection methods that return lists of tables will omit so-called
"SQLite internal schema object" names, which are referred towards by SQLite
as any object name that is prefixed with ``sqlite_``.  An example of
such an object is the ``sqlite_sequence`` table that's generated when
the ``AUTOINCREMENT`` column parameter is used.   In order to return
these objects, the parameter ``sqlite_include_internal=True`` may be
passed to methods such as :meth:`_schema.MetaData.reflect` or
:meth:`.Inspector.get_table_names`.
 
.. versionadded:: 2.0  Added the ``sqlite_include_internal=True`` parameter.
   Previously, these tables were not ignored by SQLAlchemy reflection
   methods.
 
.. note::
 
    The ``sqlite_include_internal`` parameter does not refer to the
    "system" tables that are present in schemas such as ``sqlite_master``.
 
.. seealso::
 
    `SQLite Internal Schema Objects <https://www.sqlite.org/fileformat2.html#intschema>`_ - in the SQLite
    documentation.
 
é)Ú annotationsN)ÚOptionalé)ÚJSON)Ú JSONIndexType)Ú JSONPathTypeé)Úexc©Úschema)Úsql)Útext)Útypes)Úutil)Údefault)Ú
processors)Ú
reflection)ÚReflectionDefaults)Ú    coercions)Ú ColumnElement)Úcompiler)Úelements)Úroles)ÚBLOB)ÚBOOLEAN)ÚCHAR)ÚDECIMAL)ÚFLOAT)ÚINTEGER)ÚNUMERIC)ÚREAL)ÚSMALLINT)ÚTEXT)Ú    TIMESTAMP)ÚVARCHARcseZdZ‡fdd„Z‡ZS)Ú _SQliteJsoncstƒ ||¡‰‡fdd„}|S)Ncs:z
ˆ|ƒWStk
r4t|tjƒr.|YS‚YnXdS©N)Ú    TypeErrorÚ
isinstanceÚnumbersÚNumber©Úvalue©Zdefault_processor©úVd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\sqlalchemy/dialects/sqlite/base.pyÚprocess‘s 
 z-_SQliteJson.result_processor.<locals>.process)ÚsuperÚresult_processor)ÚselfÚdialectÚcoltyper0©Ú    __class__r-r/r2Žs     z_SQliteJson.result_processor)Ú__name__Ú
__module__Ú __qualname__r2Ú __classcell__r.r.r6r/r%sr%csFeZdZdZdZd
‡fdd„    Zedd„ƒZ‡fdd„Zdd    „Z    ‡Z
S) Ú_DateTimeMixinNc s4tƒjf|Ž|dk    r"t |¡|_|dk    r0||_dSr&)r1Ú__init__ÚreÚcompileÚ_regÚ_storage_format)r3Ústorage_formatÚregexpÚkwr6r.r/r=¡s
 z_DateTimeMixin.__init__c    Cs*|jddddddddœ}tt d|¡ƒS)a?return True if the storage format will automatically imply
        a TEXT affinity.
 
        If the storage format contains no non-numeric characters,
        it will imply a NUMERIC storage format on SQLite; in this case,
        the type will generate its DDL as DATE_CHAR, DATETIME_CHAR,
        TIME_CHAR.
 
        r©ÚyearÚmonthÚdayÚhourÚminuteÚsecondÚ microsecondz[^0-9])rAÚboolr>Úsearch)r3Úspecr.r.r/Úformat_is_text_affinity¨s ù    z&_DateTimeMixin.format_is_text_affinityc s:t|tƒr*|jr|j|d<|jr*|j|d<tƒj|f|ŽS)NrBrC)Ú
issubclassr<rAr@r1Úadapt)r3ÚclsrDr6r.r/rR¾s 
 
 
z_DateTimeMixin.adaptcs| |¡‰‡fdd„}|S)Ncs dˆ|ƒS)Nú'%s'r.r+©Zbpr.r/r0Ész1_DateTimeMixin.literal_processor.<locals>.process)Úbind_processor©r3r4r0r.rUr/Úliteral_processorÆs
 z _DateTimeMixin.literal_processor)NN) r8r9r:r@rAr=ÚpropertyrPrRrXr;r.r.r6r/r<s
 r<cs4eZdZdZdZ‡fdd„Zdd„Zdd„Z‡ZS)    ÚDATETIMEaûRepresent a Python datetime object in SQLite using a string.
 
    The default string storage format is::
 
        "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
 
    e.g.::
 
        2021-03-15 12:05:57.105542
 
    The incoming storage format is by default parsed using the
    Python ``datetime.fromisoformat()`` function.
 
    .. versionchanged:: 2.0  ``datetime.fromisoformat()`` is used for default
       datetime string parsing.
 
    The storage format can be customized to some degree using the
    ``storage_format`` and ``regexp`` parameters, such as::
 
        import re
        from sqlalchemy.dialects.sqlite import DATETIME
 
        dt = DATETIME(storage_format="%(year)04d/%(month)02d/%(day)02d "
                                     "%(hour)02d:%(minute)02d:%(second)02d",
                      regexp=r"(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)"
        )
 
    :param storage_format: format string which will be applied to the dict
     with keys year, month, day, hour, minute, second, and microsecond.
 
    :param regexp: regular expression which will be applied to incoming result
     rows, replacing the use of ``datetime.fromisoformat()`` to parse incoming
     strings. If the regexp contains named groups, the resulting match dict is
     applied to the Python datetime() constructor as keyword arguments.
     Otherwise, if positional groups are used, the datetime() constructor
     is called with positional arguments via
     ``*map(int, match_obj.groups(0))``.
 
    zW%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06dcsH| dd¡}tƒj||Ž|rDd|ks.tdƒ‚d|ks>tdƒ‚d|_dS)NÚtruncate_microsecondsFrBúDYou can specify only one of truncate_microseconds or storage_format.rCú<You can specify only one of truncate_microseconds or regexp.zE%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d©Úpopr1r=ÚAssertionErrorrA©r3ÚargsÚkwargsr[r6r.r/r=ýs 
ÿ
ÿÿzDATETIME.__init__cs&tj‰tj‰|j‰‡‡‡fdd„}|S)Nc    sp|dkr dSt|ˆƒr<ˆ|j|j|j|j|j|j|jdœSt|ˆƒrdˆ|j|j|jdddddœStdƒ‚dS)NrErzLSQLite DateTime type only accepts Python datetime and date objects as input.)    r(rFrGrHrIrJrKrLr'r+©Ú datetime_dateZdatetime_datetimeÚformat_r.r/r0s2
ù    
ù
ÿz(DATETIME.bind_processor.<locals>.process©ÚdatetimeÚdaterArWr.rdr/rVs
zDATETIME.bind_processorcCs |jrt |jtj¡StjSdSr&)r@rÚ!str_to_datetime_processor_factoryrhZstr_to_datetime©r3r4r5r.r.r/r22s ÿzDATETIME.result_processor©    r8r9r:Ú__doc__rAr=rVr2r;r.r.r6r/rZÏs )ÿ $rZc@s$eZdZdZdZdd„Zdd„ZdS)ÚDATEa@Represent a Python date object in SQLite using a string.
 
    The default string storage format is::
 
        "%(year)04d-%(month)02d-%(day)02d"
 
    e.g.::
 
        2011-03-15
 
    The incoming storage format is by default parsed using the
    Python ``date.fromisoformat()`` function.
 
    .. versionchanged:: 2.0  ``date.fromisoformat()`` is used for default
       date string parsing.
 
 
    The storage format can be customized to some degree using the
    ``storage_format`` and ``regexp`` parameters, such as::
 
        import re
        from sqlalchemy.dialects.sqlite import DATE
 
        d = DATE(
                storage_format="%(month)02d/%(day)02d/%(year)04d",
                regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)")
            )
 
    :param storage_format: format string which will be applied to the
     dict with keys year, month, and day.
 
    :param regexp: regular expression which will be applied to
     incoming result rows, replacing the use of ``date.fromisoformat()`` to
     parse incoming strings. If the regexp contains named groups, the resulting
     match dict is applied to the Python date() constructor as keyword
     arguments. Otherwise, if positional groups are used, the date()
     constructor is called with positional arguments via
     ``*map(int, match_obj.groups(0))``.
 
    z %(year)04d-%(month)02d-%(day)02dcstj‰|j‰‡‡fdd„}|S)Ncs8|dkr dSt|ˆƒr,ˆ|j|j|jdœStdƒ‚dS)N)rFrGrHz;SQLite Date type only accepts Python date objects as input.)r(rFrGrHr'r+©rerfr.r/r0ks
ýÿz$DATE.bind_processor.<locals>.processrgrWr.ror/rVgszDATE.bind_processorcCs |jrt |jtj¡StjSdSr&)r@rrjrhriZ str_to_daterkr.r.r/r2|s ÿzDATE.result_processorN)r8r9r:rmrArVr2r.r.r.r/rn;s)rncs4eZdZdZdZ‡fdd„Zdd„Zdd„Z‡ZS)    ÚTIMEa‚Represent a Python time object in SQLite using a string.
 
    The default string storage format is::
 
        "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"
 
    e.g.::
 
        12:05:57.10558
 
    The incoming storage format is by default parsed using the
    Python ``time.fromisoformat()`` function.
 
    .. versionchanged:: 2.0  ``time.fromisoformat()`` is used for default
       time string parsing.
 
    The storage format can be customized to some degree using the
    ``storage_format`` and ``regexp`` parameters, such as::
 
        import re
        from sqlalchemy.dialects.sqlite import TIME
 
        t = TIME(storage_format="%(hour)02d-%(minute)02d-"
                                "%(second)02d-%(microsecond)06d",
                 regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?")
        )
 
    :param storage_format: format string which will be applied to the dict
     with keys hour, minute, second, and microsecond.
 
    :param regexp: regular expression which will be applied to incoming result
     rows, replacing the use of ``datetime.fromisoformat()`` to parse incoming
     strings. If the regexp contains named groups, the resulting match dict is
     applied to the Python time() constructor as keyword arguments. Otherwise,
     if positional groups are used, the time() constructor is called with
     positional arguments via ``*map(int, match_obj.groups(0))``.
 
    z6%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06dcsH| dd¡}tƒj||Ž|rDd|ks.tdƒ‚d|ks>tdƒ‚d|_dS)Nr[FrBr\rCr]z$%(hour)02d:%(minute)02d:%(second)02dr^rar6r.r/r=¯s 
ÿ
ÿz TIME.__init__cstj‰|j‰‡‡fdd„}|S)Ncs<|dkr dSt|ˆƒr0ˆ|j|j|j|jdœStdƒ‚dS)N)rIrJrKrLz;SQLite Time type only accepts Python time objects as input.)r(rIrJrKrLr'r+©Z datetime_timerfr.r/r0Ás
üÿz$TIME.bind_processor.<locals>.process)rhÚtimerArWr.rqr/rV½szTIME.bind_processorcCs |jrt |jtj¡StjSdSr&)r@rrjrhrrZ str_to_timerkr.r.r/r2Ós ÿzTIME.result_processorrlr.r.r6r/rp…s
' rp)ÚBIGINTrÚBOOLrrrnÚ    DATE_CHARrZÚ DATETIME_CHARÚDOUBLErrÚINTrrrr r!r"rpÚ    TIME_CHARr#r$ÚNVARCHARÚNCHARcsöeZdZe ejjddddddddd    d
d œ
¡Zd d „Zdd„Z    dd„Z
dd„Z dd„Z dd„Z ‡fdd„Zdd„Z‡fdd„Zdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Zd2d3„Zd4d5„Zd6d7„Zd8d9„Z‡ZS):ÚSQLiteCompilerz%mz%dz%Yz%Sz%Hz%jz%Mz%sz%wz%W)
rGrHrFrKrIZdoyrJÚepochZdowÚweekcKs(|j|jf|Ždd|j|jf|ŽS)Nz / z
(%s + 0.0)©r0ÚleftÚright©r3ÚbinaryÚoperatorrDr.r.r/Úvisit_truediv_binarys ÿþÿz#SQLiteCompiler.visit_truediv_binarycKsdS)NZCURRENT_TIMESTAMPr.©r3ÚfnrDr.r.r/Úvisit_now_funcszSQLiteCompiler.visit_now_funccKsdS)Nz(DATETIME(CURRENT_TIMESTAMP, "localtime")r.)r3ÚfuncrDr.r.r/Úvisit_localtimestamp_funcsz(SQLiteCompiler.visit_localtimestamp_funccKsdS)NÚ1r.©r3ÚexprrDr.r.r/Ú
visit_true szSQLiteCompiler.visit_truecKsdS)NÚ0r.rŒr.r.r/Ú visit_false#szSQLiteCompiler.visit_falsecKsd| |¡S)Nzlength%s)Zfunction_argspecr†r.r.r/Úvisit_char_length_func&sz%SQLiteCompiler.visit_char_length_funcc s,|jjrtƒj|f|ŽS|j|jf|ŽSdSr&)r4Ú supports_castr1Ú
visit_castr0Úclause)r3Úcastrcr6r.r/r“)szSQLiteCompiler.visit_castc
Ks\z"d|j|j|j|jf|ŽfWStk
rV}zt d|j¡|‚W5d}~XYnXdS)Nz#CAST(STRFTIME('%s', %s) AS INTEGER)z#%s is not a valid extract argument.)Ú extract_mapÚfieldr0rÚKeyErrorr    Ú CompileError)r3ÚextractrDÚerrr.r.r/Ú visit_extract/s
þÿþzSQLiteCompiler.visit_extractc s"d|d<tƒj||fd|i|—ŽS)NFÚ include_tableÚpopulate_result_map)r1Úreturning_clause)r3ZstmtZreturning_colsržrDr6r.r/rŸ:sÿÿÿzSQLiteCompiler.returning_clausecKsŒd}|jdk    r&|d|j|jf|Ž7}|jdk    rl|jdkrR|d| t d¡¡7}|d|j|jf|Ž7}n|d|jt d¡f|Ž7}|S)NÚz
 LIMIT éÿÿÿÿz OFFSET r)Z _limit_clauser0Z_offset_clauser Úliteral)r3ÚselectrDr r.r.r/Ú limit_clauseGs
 
 
zSQLiteCompiler.limit_clausecKsdS)Nr r.)r3r£rDr.r.r/Úfor_update_clauseSsz SQLiteCompiler.for_update_clausec s(dˆd<dd ‡‡‡fdd„|Dƒ¡S)NTZasfromzFROM ú, c3s$|]}|jˆfdˆiˆ—ŽVqdS)Z    fromhintsN)Z_compiler_dispatch)Ú.0Út©Ú
from_hintsrDr3r.r/Ú    <genexpr>[sÿz4SQLiteCompiler.update_from_clause.<locals>.<genexpr>)Újoin)r3Z update_stmtZ
from_tableZ extra_fromsrªrDr.r©r/Úupdate_from_clauseWsþz!SQLiteCompiler.update_from_clausecKsd| |j¡| |j¡fS)Nz %s IS NOT %srr‚r.r.r/Úvisit_is_distinct_from_binary`s
 
þz,SQLiteCompiler.visit_is_distinct_from_binarycKsd| |j¡| |j¡fS)Nz%s IS %srr‚r.r.r/Ú!visit_is_not_distinct_from_binaryfs
 
þz0SQLiteCompiler.visit_is_not_distinct_from_binarycKs<|jjtjkrd}nd}||j|jf|Ž|j|jf|ŽfS©Nz JSON_QUOTE(JSON_EXTRACT(%s, %s))zJSON_EXTRACT(%s, %s)©ÚtypeÚ_type_affinityÚsqltypesrr0r€r©r3rƒr„rDrr.r.r/Úvisit_json_getitem_op_binarylsþz+SQLiteCompiler.visit_json_getitem_op_binarycKs<|jjtjkrd}nd}||j|jf|Ž|j|jf|ŽfSr°r±rµr.r.r/Ú!visit_json_path_getitem_op_binarywsþz0SQLiteCompiler.visit_json_path_getitem_op_binarycKs
| |¡Sr&)Úvisit_empty_set_expr)r3Útype_Z    expand_oprDr.r.r/Úvisit_empty_set_op_expr‚sz&SQLiteCompiler.visit_empty_set_op_exprcKs<dd dd„|ptƒgDƒ¡d dd„|p0tƒgDƒ¡fS)Nz%SELECT %s FROM (SELECT %s) WHERE 1!=1r¦css|]
}dVqdS©r‹Nr.©r§r¹r.r.r/r«‰sz6SQLiteCompiler.visit_empty_set_expr.<locals>.<genexpr>css|]
}dVqdSr»r.r¼r.r.r/r«Šs)r¬r)r3Z element_typesrDr.r.r/r¸‡sþz#SQLiteCompiler.visit_empty_set_exprcKs|j|df|ŽS)Nz REGEXP ©Z_generate_generic_binaryr‚r.r.r/Úvisit_regexp_match_op_binarysz+SQLiteCompiler.visit_regexp_match_op_binarycKs|j|df|ŽS)Nz  NOT REGEXP r½r‚r.r.r/Ú visit_not_regexp_match_op_binarysz/SQLiteCompiler.visit_not_regexp_match_op_binaryc sn|jdk    rd|j}nT|jdk    rfdd ‡fdd„|jDƒ¡}|jdk    rj|dˆj|jdddd7}nd    }|S)
Nz(%s)r¦c3s4|],}t|tƒrˆj |¡nˆj|dddVqdS)F©rÚ
use_schemaN)r(ÚstrÚpreparerÚquoter0©r§Úc©r3r.r/r«—sýÿz5SQLiteCompiler._on_conflict_target.<locals>.<genexpr>ú     WHERE %sFT)rrÁÚ literal_bindsr )Zconstraint_targetZinferred_target_elementsr¬Zinferred_target_whereclauser0)r3r”rDÚ target_textr.rÇr/Ú_on_conflict_target“s
 
ú
 
ü z"SQLiteCompiler._on_conflict_targetcKs"|j|f|Ž}|rd|SdSdS)NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)rË)r3Ú on_conflictrDrÊr.r.r/Úvisit_on_conflict_do_nothing¬sz+SQLiteCompiler.visit_on_conflict_do_nothingcKs²|}|j|f|Ž}g}t|jƒ}|jdd}|jj}|D]¨}    |    j}
|
|krX| |
¡} n|    |kr:| |    ¡} nq:t     | ¡rŒt
j d| |    j d} n$t | t
j ƒr°| j jr°|  ¡} |    j | _ |j|  ¡dd} |j |    j¡} | d| | f¡q:|rvt d|jjjd d    d
„|Dƒ¡f¡| ¡D]Z\}}t |tƒr:|j |¡n |j|dd} |jt tj|¡dd} | d| | f¡qd |¡}|jdk    r¦|d |j|jd dd 7}d||fS)Nr¡Z
selectable)r¹F©rÁz%s = %szFAdditional column names not matching any column keys in table '%s': %sr¦css|]}d|VqdS)rTNr.rÅr.r.r/r«ász=SQLiteCompiler.visit_on_conflict_do_update.<locals>.<genexpr>rÈTrÀzON CONFLICT %s DO UPDATE SET %s) rËÚdictZupdate_values_to_setÚstackÚtablerÆÚkeyr_rZ _is_literalrZ BindParameterr²r(Z_isnullZ_cloner0Z
self_grouprÃrÄÚnameÚappendrÚwarnZcurrent_executabler¬ÚitemsrÂÚexpectrZExpressionElementRoleZupdate_whereclause)r3rÌrDr”rÊZaction_set_opsZset_parametersZinsert_statementÚcolsrÆZcol_keyr,Z
value_textZkey_textÚkÚvZ action_textr.r.r/Úvisit_on_conflict_do_updateµsd
 
 
ÿþþþÿÿ ý þ
 ÿ
z*SQLiteCompiler.visit_on_conflict_do_update) r8r9r:rZ update_copyrÚ SQLCompilerr–r…rˆrŠrŽrr‘r“rœrŸr¤r¥r­r®r¯r¶r·rºr¸r¾r¿rËrÍrÛr;r.r.r6r/r|sJöþ             r|csneZdZdd„Z‡fdd„Z‡fdd„Z‡fdd„Z‡fd    d
„Z‡fd d „Zd d„Z    ddd„Z
dd„Z ‡Z S)ÚSQLiteDDLCompilercKsV|jjj|j|d}|j |¡d|}| |¡}|dk    r`t|jj    t
ƒrTd|d}|d|7}|j s|d7}|j dd}|dk    r|d    |7}|j r2|jd
kr¾t|jj jƒd kr¾t d ¡‚|jj dd r2t|jj jƒd kr2t|jjtjƒr2|js2|d7}|j dd}|dk    r*|d    |7}|d7}|jdk    rR|d| |j¡7}|S)N)Ztype_expressionú ú(ú)z     DEFAULT z     NOT NULLÚsqliteÚon_conflict_not_nullú  ON CONFLICT Trz@SQLite does not support autoincrement for composite primary keysÚ autoincrementz  PRIMARY KEYÚon_conflict_primary_keyz AUTOINCREMENT)r4Ztype_compiler_instancer0r²rÃZ format_columnZget_column_default_stringr(Zserver_defaultÚargrÚnullableÚdialect_optionsÚ primary_keyräÚlenrÑÚcolumnsr    r™rQr³r´ÚIntegerÚ foreign_keysÚcomputed)r3Úcolumnrcr5ÚcolspecrÚon_conflict_clauser.r.r/Úget_column_specificationúsVÿ
  ÿ ÿþÿÿþýüÿ
  z*SQLiteDDLCompiler.get_column_specificationc s¨t|jƒdkrJt|ƒd}|jrJ|jjddrJt|jjt    j
ƒrJ|j sJdSt ƒ  |¡}|jdd}|dkrt|jƒdkrt|ƒdjdd}|dk    r¤|d|7}|S)NrrrárärÌrårã)rêrëÚlistrérÑrèrQr²r³r´rìrír1Úvisit_primary_key_constraint)r3Ú
constraintrDrÆr rñr6r.r/rô.s, ÿþýü ÿÿ z.SQLiteDDLCompiler.visit_primary_key_constraintc svtƒ |¡}|jdd}|dkr^t|jƒdkr^t|ƒd}t|tjƒr^t|ƒdjdd}|dk    rr|d|7}|S)NrárÌrrÚon_conflict_uniquerã)    r1Úvisit_unique_constraintrèrêrërór(r Z
SchemaItem)r3rõrDr rñZcol1r6r.r/r÷Ks ÿ   ÿþ z)SQLiteDDLCompiler.visit_unique_constraintc s2tƒ |¡}|jdd}|dk    r.|d|7}|S)NrárÌrã)r1Úvisit_check_constraintrè)r3rõrDr rñr6r.r/rø]s ÿ z(SQLiteDDLCompiler.visit_check_constraintc s,tƒ |¡}|jdddk    r(t d¡‚|S)NrárÌzFSQLite does not support on conflict clause for column check constraint)r1Úvisit_column_check_constraintrèr    r™)r3rõrDr r6r.r/rùis  ÿz/SQLiteDDLCompiler.visit_column_check_constraintc s<|jdjj}|jdjj}|j|jkr,dStƒ |¡SdS)Nr)rÚparentrÑrïr r1Úvisit_foreign_key_constraint)r3rõrDZ local_tableZ remote_tabler6r.r/rûts
 z.SQLiteDDLCompiler.visit_foreign_key_constraintcCs|j|ddS)z=Format the remote table clause of a CREATE CONSTRAINT clause.FrÎ)Ú format_table)r3rõrÑrÃr.r.r/Údefine_constraint_remote_table~sz0SQLiteDDLCompiler.define_constraint_remote_tableFTc
     s´|j}ˆ |¡ˆj}d}|jr(|d7}|d7}|jr>|d7}|dˆj|dd|j|jdd    d
 ‡fd d „|j    Dƒ¡f7}|j
d d}|dk    r°ˆj j |ddd}    |d|    7}|S)NzCREATE zUNIQUE zINDEX zIF NOT EXISTS z %s ON %s (%s)T)Úinclude_schemaFrÎr¦c3s |]}ˆjj|dddVqdS)FT©rrÉN)Ú sql_compilerr0)r§rrÇr.r/r«•s ýÿz7SQLiteDDLCompiler.visit_create_index.<locals>.<genexpr>ráÚwhererÿz WHERE ) ÚelementZ_verify_index_tablerÃÚuniqueZ if_not_existsZ_prepared_index_namerürÑr¬Z expressionsrèrr0)
r3ÚcreaterþZinclude_table_schemarDÚindexrÃr Z whereclauseZwhere_compiledr.rÇr/Úvisit_create_indexƒs2
 üý ÿ z$SQLiteDDLCompiler.visit_create_indexcCs|jdddkrdSdS)NráÚ
with_rowidFz
 WITHOUT ROWIDr )rè)r3rÑr.r.r/Úpost_create_table¦sz#SQLiteDDLCompiler.post_create_table)FT) r8r9r:ròrôr÷rørùrûrýrrr;r.r.r6r/rÝùs4  
ÿ
#rÝcsDeZdZdd„Z‡fdd„Z‡fdd„Z‡fdd„Zd    d
„Z‡ZS) ÚSQLiteTypeCompilercKs
| |¡Sr&)Z
visit_BLOB©r3r¹rDr.r.r/Úvisit_large_binary­sz%SQLiteTypeCompiler.visit_large_binaryc s$t|tƒr|jrtƒ |¡SdSdS)Nrv)r(r<rPr1Úvisit_DATETIMEr
r6r.r/r °s ÿþ z!SQLiteTypeCompiler.visit_DATETIMEc s$t|tƒr|jrtƒ |¡SdSdS)Nru)r(r<rPr1Ú
visit_DATEr
r6r.r/r ¹s ÿþ zSQLiteTypeCompiler.visit_DATEc s$t|tƒr|jrtƒ |¡SdSdS)Nry)r(r<rPr1Ú
visit_TIMEr
r6r.r/rÂs ÿþ zSQLiteTypeCompiler.visit_TIMEcKsdS)Nrr.r
r.r.r/Ú
visit_JSONËszSQLiteTypeCompiler.visit_JSON)    r8r9r:r r r rrr;r.r.r6r/r    ¬s
               r    cu@súeZdZddddddddd    d
d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtduhuZdvS)wÚSQLiteIdentifierPreparerÚaddÚafterÚallZalterZanalyzeÚandÚasZascÚattachräZbeforeÚbeginZbetweenZbyZcascadeZcaser•ÚcheckZcollaterïÚcommitÚconflictrõrZcrossZ current_dateÚ current_timeZcurrent_timestampZdatabaserÚ
deferrableÚdeferredÚdeleteÚdescÚdetachZdistinctZdropZeachÚelseÚendÚescapeÚexceptZ    exclusiveÚexistsÚexplainÚfalseZfailÚforZforeignÚfromÚfullÚglobÚgroupZhavingÚifÚignoreZ    immediateÚinrZindexedÚ    initiallyÚinnerÚinsertZinsteadZ    intersectZintoÚisZisnullr¬rÒr€ZlikeÚlimitÚmatchZnaturalÚnotZnotnullÚnullZofÚoffsetÚonÚorÚorderÚouterZplanÚpragmaZprimaryÚqueryÚraiseZ
referencesZreindexÚrenameÚreplaceZrestrictrÚrollbackÚrowr£ÚsetrÑÚtempÚ    temporaryZthenÚtoZ transactionZtriggerÚtrueÚunionrÚupdateZusingZvacuumÚvaluesÚviewZvirtualÚwhenrN)r8r9r:Zreserved_wordsr.r.r.r/rÒsì‹rc@s"eZdZejdd„ƒZdd„ZdS)ÚSQLiteExecutionContextcCs|jj p|j dd¡S)NZsqlite_raw_colnamesF)r4Ú_broken_dotted_colnamesZexecution_optionsÚgetrÇr.r.r/Ú_preserve_raw_colnamesMs
 þz-SQLiteExecutionContext._preserve_raw_colnamescCs,|js d|kr | d¡d|fS|dfSdS)NÚ.r¡)rQÚsplit)r3Zcolnamer.r.r/Ú_translate_colnameTsz)SQLiteExecutionContext._translate_colnameN)r8r9r:rZmemoized_propertyrQrTr.r.r.r/rNLs
rNc@s&eZdZdZdZdZdZdZdZdZ    dZ
dZ dZ dZ dZdZdZdZdZdZdZdZdZeZeZeZeZeZeZe Z e!j"dddœfe!j#ddife!j$dddd    œfe!j%d
difgZ&dZ'dZ(e)j*d d d dIdd„ƒZ+e) ,dddœ¡Z-dd„Z.dd„Z/dd„Z0e1j2dd„ƒZ3dd„Z4ddddd œd!d"„Z5e1j2dJd#d$„ƒZ6e1j2dKd%d&„ƒZ7e1j2dLd'd(„ƒZ8e1j2dMd)d*„ƒZ9d+d,„Z:e1j2dNd-d.„ƒZ;e1j2dOd/d0„ƒZ<e1j2dPd1d2„ƒZ=d3d4„Z>d5d6„Z?e1j2dQd7d8„ƒZ@e1j2dRd9d:„ƒZAd;d<„ZBe1j2dSd=d>„ƒZCe1j2dTd?d@„ƒZDe1j2dUdAdB„ƒZEdCdD„ZFe1j2dVdEdF„ƒZGdWdGdH„ZHdS)XÚ SQLiteDialectráFTÚNULLZqmark)rärrN)rårârörÌ)ú1.3.7z¨The _json_serializer argument to the SQLite dialect has been renamed to the correct name of json_serializer.  The old argument name will be removed in a future release.)rWz¬The _json_deserializer argument to the SQLite dialect has been renamed to the correct name of json_deserializer.  The old argument name will be removed in a future release.)Ú_json_serializerÚ_json_deserializercKsÜtjj|f|Ž|r|}|r |}||_||_||_|jdk    rØ|jjdkr\t     d|jjf¡|jjdk|_
|jjdk|_ |jjdk|_ |jjdk|_ |jjdk|_|jjdks´tjrÆd    |_|_|_|jjd
krØd |_dS) N)réézÇSQLite version %s is older than 3.7.16, and will not support right nested joins, as are sometimes used in more complex ORM scenarios.  SQLAlchemy 1.4 and above no longer tries to rewrite these joins.)ré
r)rré)rér)rrZé )réé)ré#F)ré riç)rÚDefaultDialectr=rXrYÚnative_datetimeZdbapiZsqlite_version_inforrÕrOÚsupports_default_valuesr’Úsupports_multivalues_insertÚ_broken_fk_pragma_quotesÚpypyÚupdate_returningÚdelete_returningÚinsert_returningZinsertmanyvalues_max_parameters)r3reZjson_serializerZjson_deserializerrXrYrcr.r.r/r=¥s<
 üÿ
ÿþþ zSQLiteDialect.__init__rr)úREAD UNCOMMITTEDÚ SERIALIZABLEcCs
t|jƒSr&)róÚ_isolation_lookup)r3Údbapi_connectionr.r.r/Úget_isolation_level_valuesüsz(SQLiteDialect.get_isolation_level_valuescCs.|j|}| ¡}| d|›¡| ¡dS)NzPRAGMA read_uncommitted = )roÚcursorÚexecuteÚclose)r3rpÚlevelZisolation_levelrrr.r.r/Úset_isolation_levelÿs
z!SQLiteDialect.set_isolation_levelcCs`| ¡}| d¡| ¡}|r(|d}nd}| ¡|dkr@dS|dkrLdSds\td|ƒ‚dS)NzPRAGMA read_uncommittedrrnrrmFzUnknown isolation level %s)rrrsZfetchonertr`)r3rprrÚresr,r.r.r/Úget_isolation_levels
 
z!SQLiteDialect.get_isolation_levelcKsd}| |¡}dd„|DƒS)NzPRAGMA database_listcSs g|]}|ddkr|d‘qS)rrEr.)r§Údbr.r.r/Ú
<listcomp>!s z2SQLiteDialect.get_schema_names.<locals>.<listcomp>)Úexec_driver_sql)r3Ú
connectionrDÚsÚdlr.r.r/Úget_schema_namess
zSQLiteDialect.get_schema_namescCs,|dk    r$|j |¡}|›d|›}n|}|S)NrR)Úidentifier_preparerÚquote_identifier)r3r Ú
table_nameÚqschemarÓr.r.r/Ú_format_schema#s
 zSQLiteDialect._format_schemarÂz Optional[str]rM)rÑr¹r Úsqlite_include_internalcCs6| ||¡}|sd}nd}d|›d|›d|›d}|S)Nz) AND name NOT LIKE 'sqlite~_%' ESCAPE '~'r zSELECT name FROM z  WHERE type='ú'z ORDER BY name)r„)r3rÑr¹r r…ÚmainZ filter_tabler>r.r.r/Ú_sqlite_main_query+s ÿz SQLiteDialect._sqlite_main_querycKs&| dd||¡}| |¡ ¡ ¡}|S)NÚ sqlite_masterrÑ©rˆr{Zscalarsr©r3r|r r…rDr>Únamesr.r.r/Úget_table_names>sÿzSQLiteDialect.get_table_namescKs&| ddd|¡}| |¡ ¡ ¡}|S)NÚsqlite_temp_masterrÑrŠ©r3r|r…rDr>rŒr.r.r/Úget_temp_table_namesHsÿz"SQLiteDialect.get_temp_table_namescKs&| ddd|¡}| |¡ ¡ ¡}|S)NrŽrLrŠrr.r.r/Úget_temp_view_namesRsÿz!SQLiteDialect.get_temp_view_namescKsB| |¡|dk    r(||j|f|Žkr(dS|j|d||d}t|ƒS)NFÚ
table_infor
)Z_ensure_has_table_connectionrÚ_get_table_pragmarM)r3r|r‚r rDÚinfor.r.r/Ú    has_table\s
ÿÿÿzSQLiteDialect.has_tablecCsdS)Nr‡r.)r3r|r.r.r/Ú_get_default_schema_namejsz&SQLiteDialect._get_default_schema_namecKs&| dd||¡}| |¡ ¡ ¡}|S)Nr‰rLrŠr‹r.r.r/Úget_view_namesmsÿzSQLiteDialect.get_view_namesc
Ks®|dk    r8|j |¡}|›d}d|f}| ||f¡}n@zd}| ||f¡}Wn(tjk
rvd}| ||f¡}YnX| ¡}    |    rŽ|    djSt |r¤|›d|›n|¡‚dS)Nz.sqlite_masterz1SELECT sql FROM %s WHERE name = ? AND type='view'zzSELECT sql FROM  (SELECT * FROM sqlite_master UNION ALL   SELECT * FROM sqlite_temp_master) WHERE name = ? AND type='view'z<SELECT sql FROM sqlite_master WHERE name = ? AND type='view'rrR)r€rr{r    Ú
DBAPIErrorÚfetchallr ÚNoSuchTableError)
r3r|Z    view_namer rDrƒZmasterr}ÚrsÚresultr.r.r/Úget_view_definitionws* 
ÿÿÿ
ÿz!SQLiteDialect.get_view_definitionc Ksd}|jdkrd}|j||||d}g}d}|D]œ}    |    d}
|    d ¡} |    d } |    d} |    d    }|dkrr|    d
nd }|dkr€q0t|ƒ}|dk}|dkr®|r®|j|||f|Ž}| | |
| | | ||||¡¡q0|rÖ|S| |||¡st     |rü|›d |›n|¡‚nt
  ¡SdS) Nr’)réZ table_xinfor
rr^réér`rrR) Zserver_version_infor“ÚupperrMÚ_get_table_sqlrÔÚ_get_column_infor•r    ršrrë)r3r|r‚r rDr=r”rëÚtablesqlrCrÓr¹rçrréÚhiddenÚ    generatedÚ    persistedr.r.r/Ú get_columns™sb
ÿ 
 ÿÿøÿ ÿzSQLiteDialect.get_columnsc    Cs¤|r0tjdd|tjd}tjdd|tjd ¡}| |¡}    |dk    rJt|ƒ}||    |||dœ}
|r d} |r’d} t t |¡| |tj¡} | r’|  d¡} | |dœ|
d    <|
S)
Nr¦r )ÚflagsÚalways)rÓr²rçrréz.[^,]*\s+AS\s+\(([^,]*)\)\s*(?:virtual|stored)?r)Úsqltextr§rî)    r>ÚsubÚ
IGNORECASEÚstripÚ_resolve_type_affinityrÂrNr#r,)r3rÓr¹rçrrér¦r§r¤r5rðr«Úpatternr5r.r.r/r£Ïs2 
û ÿ
zSQLiteDialect._get_column_infocCst d|¡}|r&| d¡}| d¡}nd}d}||jkrD|j|}njd|krTtj}nZd|ksld|ksld|krttj}n:d    |ks€|sˆtj}n&d
|ks d |ks d |kr¨tj}ntj    }|d k    r t 
d|¡}z|dd„|DƒŽ}Wn.t k
rt   d||f¡|ƒ}YnXn|ƒ}|S)aZReturn a data type from a reflected column, using affinity rules.
 
        SQLite's goal for universal compatibility introduces some complexity
        during reflection, as a column's defined type might not actually be a
        type that SQLite understands - or indeed, my not be defined *at all*.
        Internally, SQLite handles this with a 'data type affinity' for each
        column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER',
        'REAL', or 'NONE' (raw bits). The algorithm that determines this is
        listed in https://www.sqlite.org/datatype3.html section 2.1.
 
        This method allows SQLAlchemy to support that algorithm, while still
        providing access to smarter reflection utilities by recognizing
        column definitions that SQLite only supports through affinity (like
        DATE and DOUBLE).
 
        z([\w ]+)(\(.*?\))?rr^r rxrZCLOBr"rr ZFLOAZDOUBNz(\d+)cSsg|] }t|ƒ‘qSr.)Úint)r§Úar.r.r/rz"    sz8SQLiteDialect._resolve_type_affinity.<locals>.<listcomp>zNCould not instantiate type %s with reflected arguments %s; using no arguments.)r>r5r,Ú ischema_namesr´rr"ZNullTyper rÚfindallr'rrÕ)r3r¹r5r5rbr.r.r/r¯ùs< 
 
 
 þÿz$SQLiteDialect._resolve_type_affinityc Ks–d}|j|||d}|r>d}t ||tj¡}|r:| d¡nd}|j|||f|Ž}    dd„|    Dƒ}    |    jdd„dd    d„|    Dƒ}
|
rŠ|
|d
œSt ¡SdS) Nr
zCONSTRAINT (\w+) PRIMARY KEYrcSs g|]}| dd¡dkr|‘qS)rér©rP©r§Úcolr.r.r/rz;    sz3SQLiteDialect.get_pk_constraint.<locals>.<listcomp>cSs
| d¡S)Nrérµ)r·r.r.r/Ú<lambda><    óz1SQLiteDialect.get_pk_constraint.<locals>.<lambda>©rÒcSsg|] }|d‘qS)rÓr.r¶r.r.r/rz=    s)Úconstrained_columnsrÓ)    r¢r>rNÚIr,r¨ÚsortrZ pk_constraint) r3r|r‚r rDÚconstraint_nameÚ
table_dataZ
PK_PATTERNrœrØZpkeysr.r.r/Úget_pk_constraint/    s
zSQLiteDialect.get_pk_constraintc     sˆj|d||d}i}|D]Ú}|d|d|d|df\}}    }
} | sˆz$ˆj||    fd|i|—Ž} | d} WqŒtjk
r„g} YqŒXng} ˆjr t d    d
|    ¡}    ||kr²||}n"dg||    | id œ}||<|||<|d |
¡| r|d  | ¡qd d„‰‡fdd„| ¡Dƒ}ˆj    |||d‰‡‡fdd„}g}|ƒD]`\}}}} }ˆ||| ƒ}||krvt
  d||f¡q<|  |¡}||d<||d<| |¡q<|  | ¡¡|r¶|St ¡SdS)NZforeign_key_listr
rr^rrŸr r»z^[\"\[`\']|[\"\]`\']$r )rÓr»Zreferred_schemaÚreferred_tableÚreferred_columnsÚoptionsrÂcSst|ƒ|ft|ƒSr&)Útuple©r»rÁrÂr.r.r/Úfk_sigy    s ÿþÿz.SQLiteDialect.get_foreign_keys.<locals>.fk_sigcs&i|]}ˆ|d|d|dƒ|“qSrÅr.)r§Úfk)rÆr.r/Ú
<dictcomp>„    sûýz2SQLiteDialect.get_foreign_keys.<locals>.<dictcomp>c 3s2ˆdkr dSd}t |ˆtj¡D]
}| dddddddd    ¡\}}}}}}}}    tˆ |¡ƒ}|sf|}ntˆ |¡ƒ}|pz|}i}
t d
| ¡¡D]b} |  d ¡rÄ| dd…     ¡} | rò| d krò| |
d <q|  d¡r| dd…     ¡} | r| d kr| |
d<q|r
d| ¡k|
d<|    r|     ¡|
d<|||||
fVq dS)Nzö(?:CONSTRAINT (\w+) +)?FOREIGN KEY *\( *(.+?) *\) +REFERENCES +(?:(?:"(.+?)")|([a-z0-9_]+)) *\((.+?)\) *((?:ON (?:DELETE|UPDATE) (?:SET NULL|SET DEFAULT|CASCADE|RESTRICT|NO ACTION) *)*)((?:NOT +)?DEFERRABLE)?(?: +INITIALLY +(DEFERRED|IMMEDIATE))?rr^rrŸr r`rZr]z
 *\bON\b *ÚDELETEz    NO ACTIONÚondeleteZUPDATEÚonupdateZNOTrr0)
r>Úfinditerr¼r,róÚ_find_cols_in_sigrSr¡Ú
startswithr®)Z
FK_PATTERNr5r¾r»Zreferred_quoted_nameÚ referred_namerÂZonupdatedeleterr0rÃÚtokenrÊrË©r3r¿r.r/Ú    parse_fks    sXÿ    
÷ÿÿ
 
 
 
 ûz1SQLiteDialect.get_foreign_keys.<locals>.parse_fkszhWARNING: SQL-parsed foreign key constraint '%s' could not be located in PRAGMA foreign_keys for table %srÓrÃ)r“rÀr    ršrhr>r¬rÔrKr¢rrÕr_Úextendrrí)r3r|r‚r rDZ
pragma_fksZfksrCZ numerical_idZrtblZlcolZrcolZ referred_pkrÂrÇZkeys_by_signaturerÒZfkeysr¾r»rÏrÃÚsigrÒr.)rÆr3r¿r/Úget_foreign_keysD    sˆÿ$ÿÿÿ  
ú
ú    ;ú 
þÿ
zSQLiteDialect.get_foreign_keysccs0t d|tj¡D]}| d¡p&| d¡VqdS)Nz(?:"(.+?)")|([a-z0-9_]+)rr^)r>rÌr¼r,)r3rÔr5r.r.r/rÍè    szSQLiteDialect._find_cols_in_sigc  sÄi}ˆj||f|ddœ|—ŽD](}|d d¡s2qt|dƒ}|||<qˆj||fd|i|—މg}‡‡fdd„}    |    ƒD]6\}
} t| ƒ}||krx| |¡|
| d    œ} | | ¡qx|r¸|St ¡SdS)
NT)r Úinclude_auto_indexesrÓÚsqlite_autoindexÚ column_namesr c3sˆdkr dSd}d}t |ˆtj¡D](}| dd¡\}}|tˆ |¡ƒfVq$t |ˆtj¡D],}tˆ | d¡pz| d¡¡ƒ}d|fVq^dS)Nz,(?:CONSTRAINT "?(.+?)"? +)?UNIQUE *\((.+?)\)zB(?:(".+?")|(?:[\[`])?([a-z0-9_]+)(?:[\]`])?) +[a-z0-9_ ]+? +UNIQUErr^)r>rÌr¼r,rórÍ)ZUNIQUE_PATTERNZINLINE_UNIQUE_PATTERNr5rÓrØrÑr.r/Ú    parse_uqs
sÿÿz7SQLiteDialect.get_unique_constraints.<locals>.parse_uqs)rÓrØ)Ú get_indexesrÎrÄr¢r_rÔrÚunique_constraints) r3r|r‚r rDZauto_index_by_sigÚidxrÔrÛrÙrÓrØZparsed_constraintr.rÑr/Úget_unique_constraintsì    sBþüû
 
ÿÿÿ
 
 z$SQLiteDialect.get_unique_constraintsc
Ks|j||fd|i|—Ž}d}g}t ||p,dtj¡D]6}| d¡}    |    rTt dd|    ¡}    | | d¡|    dœ¡q4|jdd    „d
|r„|St     ¡SdS) Nr z-(?:CONSTRAINT (.+) +)?CHECK *\( *(.+) *\),? *r rz^"|"$r^)r«rÓcSs |dp
dS©NrÓú~r.©Údr.r.r/r¸;
r¹z5SQLiteDialect.get_check_constraints.<locals>.<lambda>rº)
r¢r>rÌr¼r,r¬rÔr½rZcheck_constraints)
r3r|r‚r rDr¿Z CHECK_PATTERNZcksr5rÓr.r.r/Úget_check_constraints&
s&ÿÿÿ
z#SQLiteDialect.get_check_constraintsc    KsÐ|j|d||d}g}t dtj¡}|r:d|j |¡}nd}| dd¡}    |D]´}
|    sf|
d d    ¡rfqN| t    |
dg|
d
id ¡t
|
ƒd krN|
d rNdd|i} |  | |
df¡} |   ¡} |  | ¡}|dkrät d|
d¡qN| d¡}t|ƒ|ddd<qNt|ƒD]l}|j|d|d|d}|D]J}
|
d
dkr`t d|d¡| |¡q n|d |
d
¡q*q |jdd„d|r”|S| |||¡sÄt |r¼|›d|›n|¡‚nt ¡SdS)NZ
index_listr
z\)\s+where\s+(.+)ú%s.r rÖFrr×r^)rÓrØrrèr rŸzISELECT sql FROM %(schema)ssqlite_master WHERE name = ? AND type = 'index'r z6Failed to look up filter predicate of partial index %sr¡rèZ sqlite_whereÚ
index_inforÓz;Skipped unsupported reflection of expression-based index %srØcSs |dp
dSrÞr.ràr.r.r/r¸‘
r¹z+SQLiteDialect.get_indexes.<locals>.<lambda>rºrR)r“r>r?r­r€rr_rÎrÔrÏrêr{ÚscalarrNrrÕr,r róÚremover½r•r    ršrÚindexes)r3r|r‚r rDZpragma_indexesrçZpartial_pred_reÚ schema_exprrÖrCr}r›Z    index_sqlZpredicate_matchÚ    predicaterÜZ pragma_indexr.r.r/rÚA
sŒÿÿ  ÿüÿ
þÿ
ÿÿ
ÿ ÿÿÿ
ÿzSQLiteDialect.get_indexescCs|dkS)N>Úsqlite_temp_schemar‰Ú sqlite_schemarŽr.)r3r‚r.r.r/Ú _is_sys_table›
szSQLiteDialect._is_sys_tablec    Ksš|rd|j |¡}nd}zdd|i}| ||f¡}Wn0tjk
rhdd|i}| ||f¡}YnX| ¡}|dkr–| |¡s–t |›|›¡‚|S)Nrãr zœSELECT sql FROM  (SELECT * FROM %(schema)ssqlite_master UNION ALL   SELECT * FROM %(schema)ssqlite_temp_master) WHERE name = ? AND type in ('table', 'view')r zTSELECT sql FROM %(schema)ssqlite_master WHERE name = ? AND type in ('table', 'view'))r€rr{r    r˜rårìrš)    r3r|r‚r rDrèr}r›r,r.r.r/r¢£
s*
ÿüÿþÿzSQLiteDialect._get_table_sqlc Cs€|jj}|dk    r$d||ƒ›dg}nddg}||ƒ}|D]B}|›|›d|›d}| |¡}    |    jsj|     ¡}
ng}
|
r8|
Sq8gS)NzPRAGMA rRz PRAGMA main.z PRAGMA temp.rßrà)r€rr{Z _soft_closedr™) r3r|r=r‚r rÄZ
statementsZqtableZ    statementrrrœr.r.r/r“À
s
 
 
zSQLiteDialect._get_table_pragma)FNNNN)NF)F)F)N)NF)N)N)N)N)N)N)N)N)N)Ir8r9r:rÓZsupports_alterrfZsupports_default_metavalueZ supports_sane_rowcount_returningZsupports_empty_insertr’rgZuse_insertmanyvaluesZtuple_in_valuesZsupports_statement_cacheZ#insert_null_pk_still_autoincrementsrlrjZupdate_returning_multifromrkZdefault_metavalue_tokenZdefault_paramstylerNZexecution_ctx_clsr|Zstatement_compilerrÝZ ddl_compilerr    Ztype_compiler_clsrrÃr³ÚcolspecsÚ    sa_schemaZTableZIndexZColumnZ
ConstraintZconstruct_argumentsrhrOrZdeprecated_paramsr=Z immutabledictrorqrvrxrÚcacherr„rˆrrr‘r•r–r—rr¨r£r¯rÀrÕrÍrÝrârÚrìr¢r“r.r.r.r/rUbsÎþþ ýþ ïùú Eÿ
ÿ     ÿ     ÿ      ÿ      ! 5*6  $ÿ 9  Y rU)FrmÚ
__future__rrhr)r>ÚtypingrÚjsonrrrr r    r rîr r rr´rZenginerrrZengine.reflectionrrrrrrrrrrrrrr r!r"r#r$r%r<ÚDateTimerZÚDaternZTimerprírsrwrzr{r³rÜr|Z DDLCompilerrÝZGenericTypeCompilerr    ZIdentifierPreparerrZDefaultExecutionContextrNrdrUr.r.r.r/Ú<module>
s¼a                                 2lJXú
çx4&z