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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
U
¸ý°dQã´@sðdZddlmZddlZddlZddlZddlZddlmZddlm    Z    ddl
m Z ddl mZdd    lmZdd
lmZdd lmZd d l mZd dl mZd dl mZd dl mZd dl mZd dl mZd dl mZd dlmZd dlmZd dlm Z d dl!m"Z"d dlm#Z#d dlm$Z$d dlm%Z%d dlm&Z&d dlm'Z'd dlm(Z(d dlm)Z)d dlm*Z*d dlmZ+d d l,m-Z-d d!l.m/Z/d d"l0m1Z1d d#l0m2Z2d d$l0m3Z3d d%l0m4Z4d d&l0m5Z5d d'l0m6Z6d d(l0m7Z7d d)l0m8Z8d d*l0m9Z9d d+l0m:Z:d d,l0m;Z;d d-l0m<Z<d d.l0m=Z=d d/l0m>Z>d d0lm?Z?d d1l@mAZAe    rjd d2lBmCZCd d3lDmEZEd4ZFd5ZGd6ZHd7ZId8ZJd9ZKd:ZLd;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dd€dd‚dƒd„d…d†d‡dˆd‰dŠd‹dŒddŽddd‘d’d“d”d•d–d—d˜d™dšd›dœddždŸd d¡d¢d£d¤d¥d¦d§d¨d©dªd«d¬d­d®d¯d°d±d²d³d´dµd¶d·d¸d¹dºd»d¼d½d¾d¿dÀdÁdÂdÃdÄdÅdÆdÇdÈdÉdÊdËdÌdÍdÎdÏdÐdÑdÒdÓdÔdÕdÖd×dØdÙdÚdÛdÜdÝdÞdßdàdádâdãdädådædçdèdédêdëdìdídîh´ZMGdïdð„dðe*jNƒZNGdñdò„dòe*jOƒZOGdódô„dôe*jPƒZQGdõdö„döe*jRƒZSGd÷dø„døe*jTƒZTeTZUGdùdú„dúeTƒZVGdûdü„düƒZWGdýdþ„dþeWe*jXƒZYGdÿd„deWe*jXƒZZGdd„deWe*jXƒZ[Gdd„deWe*jXƒZ\Gdd„dƒZ]Gdd„de]e*j^ƒZ_Gd    d
„d
e]e*j`ƒZaGd d „d e*jbƒZcGd d„decƒZdGdd„de*j`ƒZeGdd„de*jfe*jgƒZfGdd„de*jgƒZhGdd„de*jiƒZjGdd„de*jkƒZlGdd„de*jmƒZnGdd„de*jmƒZoGdd„de*jpƒZqGdd „d e*jpe*jrƒZsGd!d"„d"e*jmƒZtd#d$„ZuGd%d&„d&ej%jvƒZweYZxeSZyeNZzeQZ{eTZ|eZZ}e[Z~e\Ze=Z€eeZe>Z‚e;Zƒe3Z„e9Z…e2Z†efZ‡ehZˆelZ‰enZŠeoZ‹esZŒetZe8e1e<eQe>e;e3e9e=eee6e:e7e5e[e\e4eTeZe2efeleNeOehejeceneoesetd'œZŽGd(d)„d)e$jƒZGd*d+„d+ej‘ƒZ’Gd,d-„d-e$j“ƒZ”Gd.d/„d/e”ƒZ•Gd0d1„d1e$j–ƒZ—Gd2d3„d3e$j˜ƒZ™d4d5„Zšd6d7„Z›d8d9„Zœd:d;„Ze ž¡ZŸd<d=„Z Gd>d?„d?ej¡ƒZ¢dS(@a
.. dialect:: mssql
    :name: Microsoft SQL Server
    :full_support: 2017
    :normal_support: 2012+
    :best_effort: 2005+
 
.. _mssql_external_dialects:
 
External Dialects
-----------------
 
In addition to the above DBAPI layers with native SQLAlchemy support, there
are third-party dialects for other DBAPI layers that are compatible
with SQL Server. See the "External Dialects" list on the
:ref:`dialect_toplevel` page.
 
.. _mssql_identity:
 
Auto Increment Behavior / IDENTITY Columns
------------------------------------------
 
SQL Server provides so-called "auto incrementing" behavior using the
``IDENTITY`` construct, which can be placed on any single integer column in a
table. SQLAlchemy considers ``IDENTITY`` within its default "autoincrement"
behavior for an integer primary key column, described at
:paramref:`_schema.Column.autoincrement`.  This means that by default,
the first integer primary key column in a :class:`_schema.Table` will be
considered to be the identity column - unless it is associated with a
:class:`.Sequence` - and will generate DDL as such::
 
    from sqlalchemy import Table, MetaData, Column, Integer
 
    m = MetaData()
    t = Table('t', m,
            Column('id', Integer, primary_key=True),
            Column('x', Integer))
    m.create_all(engine)
 
The above example will generate DDL as:
 
.. sourcecode:: sql
 
    CREATE TABLE t (
        id INTEGER NOT NULL IDENTITY,
        x INTEGER NULL,
        PRIMARY KEY (id)
    )
 
For the case where this default generation of ``IDENTITY`` is not desired,
specify ``False`` for the :paramref:`_schema.Column.autoincrement` flag,
on the first integer primary key column::
 
    m = MetaData()
    t = Table('t', m,
            Column('id', Integer, primary_key=True, autoincrement=False),
            Column('x', Integer))
    m.create_all(engine)
 
To add the ``IDENTITY`` keyword to a non-primary key column, specify
``True`` for the :paramref:`_schema.Column.autoincrement` flag on the desired
:class:`_schema.Column` object, and ensure that
:paramref:`_schema.Column.autoincrement`
is set to ``False`` on any integer primary key column::
 
    m = MetaData()
    t = Table('t', m,
            Column('id', Integer, primary_key=True, autoincrement=False),
            Column('x', Integer, autoincrement=True))
    m.create_all(engine)
 
.. versionchanged::  1.4   Added :class:`_schema.Identity` construct
   in a :class:`_schema.Column` to specify the start and increment
   parameters of an IDENTITY. These replace
   the use of the :class:`.Sequence` object in order to specify these values.
 
.. deprecated:: 1.4
 
   The ``mssql_identity_start`` and ``mssql_identity_increment`` parameters
   to :class:`_schema.Column` are deprecated and should we replaced by
   an :class:`_schema.Identity` object. Specifying both ways of configuring
   an IDENTITY will result in a compile error.
   These options are also no longer returned as part of the
   ``dialect_options`` key in :meth:`_reflection.Inspector.get_columns`.
   Use the information in the ``identity`` key instead.
 
.. deprecated:: 1.3
 
   The use of :class:`.Sequence` to specify IDENTITY characteristics is
   deprecated and will be removed in a future release.   Please use
   the :class:`_schema.Identity` object parameters
   :paramref:`_schema.Identity.start` and
   :paramref:`_schema.Identity.increment`.
 
.. versionchanged::  1.4   Removed the ability to use a :class:`.Sequence`
   object to modify IDENTITY characteristics. :class:`.Sequence` objects
   now only manipulate true T-SQL SEQUENCE types.
 
.. note::
 
    There can only be one IDENTITY column on the table.  When using
    ``autoincrement=True`` to enable the IDENTITY keyword, SQLAlchemy does not
    guard against multiple columns specifying the option simultaneously.  The
    SQL Server database will instead reject the ``CREATE TABLE`` statement.
 
.. note::
 
    An INSERT statement which attempts to provide a value for a column that is
    marked with IDENTITY will be rejected by SQL Server.   In order for the
    value to be accepted, a session-level option "SET IDENTITY_INSERT" must be
    enabled.   The SQLAlchemy SQL Server dialect will perform this operation
    automatically when using a core :class:`_expression.Insert`
    construct; if the
    execution specifies a value for the IDENTITY column, the "IDENTITY_INSERT"
    option will be enabled for the span of that statement's invocation.However,
    this scenario is not high performing and should not be relied upon for
    normal use.   If a table doesn't actually require IDENTITY behavior in its
    integer primary key column, the keyword should be disabled when creating
    the table by ensuring that ``autoincrement=False`` is set.
 
Controlling "Start" and "Increment"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
Specific control over the "start" and "increment" values for
the ``IDENTITY`` generator are provided using the
:paramref:`_schema.Identity.start` and :paramref:`_schema.Identity.increment`
parameters passed to the :class:`_schema.Identity` object::
 
    from sqlalchemy import Table, Integer, Column, Identity
 
    test = Table(
        'test', metadata,
        Column(
            'id',
            Integer,
            primary_key=True,
            Identity(start=100, increment=10)
        ),
        Column('name', String(20))
    )
 
The CREATE TABLE for the above :class:`_schema.Table` object would be:
 
.. sourcecode:: sql
 
   CREATE TABLE test (
     id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY,
     name VARCHAR(20) NULL,
     )
 
.. note::
 
   The :class:`_schema.Identity` object supports many other parameter in
   addition to ``start`` and ``increment``. These are not supported by
   SQL Server and will be ignored when generating the CREATE TABLE ddl.
 
.. versionchanged:: 1.3.19  The :class:`_schema.Identity` object is
   now used to affect the
   ``IDENTITY`` generator for a :class:`_schema.Column` under  SQL Server.
   Previously, the :class:`.Sequence` object was used.  As SQL Server now
   supports real sequences as a separate construct, :class:`.Sequence` will be
   functional in the normal way starting from SQLAlchemy version 1.4.
 
 
Using IDENTITY with Non-Integer numeric types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
SQL Server also allows ``IDENTITY`` to be used with ``NUMERIC`` columns.  To
implement this pattern smoothly in SQLAlchemy, the primary datatype of the
column should remain as ``Integer``, however the underlying implementation
type deployed to the SQL Server database can be specified as ``Numeric`` using
:meth:`.TypeEngine.with_variant`::
 
    from sqlalchemy import Column
    from sqlalchemy import Integer
    from sqlalchemy import Numeric
    from sqlalchemy import String
    from sqlalchemy.ext.declarative import declarative_base
 
    Base = declarative_base()
 
    class TestTable(Base):
        __tablename__ = "test"
        id = Column(
            Integer().with_variant(Numeric(10, 0), "mssql"),
            primary_key=True,
            autoincrement=True,
        )
        name = Column(String)
 
In the above example, ``Integer().with_variant()`` provides clear usage
information that accurately describes the intent of the code. The general
restriction that ``autoincrement`` only applies to ``Integer`` is established
at the metadata level and not at the per-dialect level.
 
When using the above pattern, the primary key identifier that comes back from
the insertion of a row, which is also the value that would be assigned to an
ORM object such as ``TestTable`` above, will be an instance of ``Decimal()``
and not ``int`` when using SQL Server. The numeric return type of the
:class:`_types.Numeric` type can be changed to return floats by passing False
to :paramref:`_types.Numeric.asdecimal`. To normalize the return type of the
above ``Numeric(10, 0)`` to return Python ints (which also support "long"
integer values in Python 3), use :class:`_types.TypeDecorator` as follows::
 
    from sqlalchemy import TypeDecorator
 
    class NumericAsInteger(TypeDecorator):
        '''normalize floating point return values into ints'''
 
        impl = Numeric(10, 0, asdecimal=False)
        cache_ok = True
 
        def process_result_value(self, value, dialect):
            if value is not None:
                value = int(value)
            return value
 
    class TestTable(Base):
        __tablename__ = "test"
        id = Column(
            Integer().with_variant(NumericAsInteger, "mssql"),
            primary_key=True,
            autoincrement=True,
        )
        name = Column(String)
 
.. _mssql_insert_behavior:
 
INSERT behavior
^^^^^^^^^^^^^^^^
 
Handling of the ``IDENTITY`` column at INSERT time involves two key
techniques. The most common is being able to fetch the "last inserted value"
for a given ``IDENTITY`` column, a process which SQLAlchemy performs
implicitly in many cases, most importantly within the ORM.
 
The process for fetching this value has several variants:
 
* In the vast majority of cases, RETURNING is used in conjunction with INSERT
  statements on SQL Server in order to get newly generated primary key values:
 
  .. sourcecode:: sql
 
    INSERT INTO t (x) OUTPUT inserted.id VALUES (?)
 
  As of SQLAlchemy 2.0, the :ref:`engine_insertmanyvalues` feature is also
  used by default to optimize many-row INSERT statements; for SQL Server
  the feature takes place for both RETURNING and-non RETURNING
  INSERT statements.
 
  .. versionchanged:: 2.0.10 The :ref:`engine_insertmanyvalues` feature for
     SQL Server was temporarily disabled for SQLAlchemy version 2.0.9 due to
     issues with row ordering. As of 2.0.10 the feature is re-enabled, with
     special case handling for the unit of work's requirement for RETURNING to
     be ordered.
 
* When RETURNING is not available or has been disabled via
  ``implicit_returning=False``, either the ``scope_identity()`` function or
  the ``@@identity`` variable is used; behavior varies by backend:
 
  * when using PyODBC, the phrase ``; select scope_identity()`` will be
    appended to the end of the INSERT statement; a second result set will be
    fetched in order to receive the value.  Given a table as::
 
        t = Table(
            't',
            metadata,
            Column('id', Integer, primary_key=True),
            Column('x', Integer),
            implicit_returning=False
        )
 
    an INSERT will look like:
 
    .. sourcecode:: sql
 
        INSERT INTO t (x) VALUES (?); select scope_identity()
 
  * Other dialects such as pymssql will call upon
    ``SELECT scope_identity() AS lastrowid`` subsequent to an INSERT
    statement. If the flag ``use_scope_identity=False`` is passed to
    :func:`_sa.create_engine`,
    the statement ``SELECT @@identity AS lastrowid``
    is used instead.
 
A table that contains an ``IDENTITY`` column will prohibit an INSERT statement
that refers to the identity column explicitly.  The SQLAlchemy dialect will
detect when an INSERT construct, created using a core
:func:`_expression.insert`
construct (not a plain string SQL), refers to the identity column, and
in this case will emit ``SET IDENTITY_INSERT ON`` prior to the insert
statement proceeding, and ``SET IDENTITY_INSERT OFF`` subsequent to the
execution.  Given this example::
 
    m = MetaData()
    t = Table('t', m, Column('id', Integer, primary_key=True),
                    Column('x', Integer))
    m.create_all(engine)
 
    with engine.begin() as conn:
        conn.execute(t.insert(), {'id': 1, 'x':1}, {'id':2, 'x':2})
 
The above column will be created with IDENTITY, however the INSERT statement
we emit is specifying explicit values.  In the echo output we can see
how SQLAlchemy handles this:
 
.. sourcecode:: sql
 
    CREATE TABLE t (
        id INTEGER NOT NULL IDENTITY(1,1),
        x INTEGER NULL,
        PRIMARY KEY (id)
    )
 
    COMMIT
    SET IDENTITY_INSERT t ON
    INSERT INTO t (id, x) VALUES (?, ?)
    ((1, 1), (2, 2))
    SET IDENTITY_INSERT t OFF
    COMMIT
 
 
 
This is an auxiliary use case suitable for testing and bulk insert scenarios.
 
SEQUENCE support
----------------
 
The :class:`.Sequence` object creates "real" sequences, i.e.,
``CREATE SEQUENCE``:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import Sequence
    >>> from sqlalchemy.schema import CreateSequence
    >>> from sqlalchemy.dialects import mssql
    >>> print(CreateSequence(Sequence("my_seq", start=1)).compile(dialect=mssql.dialect()))
    {printsql}CREATE SEQUENCE my_seq START WITH 1
 
For integer primary key generation, SQL Server's ``IDENTITY`` construct should
generally be preferred vs. sequence.
 
.. tip::
 
    The default start value for T-SQL is ``-2**63`` instead of 1 as
    in most other SQL databases. Users should explicitly set the
    :paramref:`.Sequence.start` to 1 if that's the expected default::
 
        seq = Sequence("my_sequence", start=1)
 
.. versionadded:: 1.4 added SQL Server support for :class:`.Sequence`
 
.. versionchanged:: 2.0 The SQL Server dialect will no longer implicitly
   render "START WITH 1" for ``CREATE SEQUENCE``, which was the behavior
   first implemented in version 1.4.
 
MAX on VARCHAR / NVARCHAR
-------------------------
 
SQL Server supports the special string "MAX" within the
:class:`_types.VARCHAR` and :class:`_types.NVARCHAR` datatypes,
to indicate "maximum length possible".   The dialect currently handles this as
a length of "None" in the base type, rather than supplying a
dialect-specific version of these types, so that a base type
specified such as ``VARCHAR(None)`` can assume "unlengthed" behavior on
more than one backend without using dialect-specific types.
 
To build a SQL Server VARCHAR or NVARCHAR with MAX length, use None::
 
    my_table = Table(
        'my_table', metadata,
        Column('my_data', VARCHAR(None)),
        Column('my_n_data', NVARCHAR(None))
    )
 
 
Collation Support
-----------------
 
Character collations are supported by the base string types,
specified by the string argument "collation"::
 
    from sqlalchemy import VARCHAR
    Column('login', VARCHAR(32, collation='Latin1_General_CI_AS'))
 
When such a column is associated with a :class:`_schema.Table`, the
CREATE TABLE statement for this column will yield::
 
    login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL
 
LIMIT/OFFSET Support
--------------------
 
MSSQL has added support for LIMIT / OFFSET as of SQL Server 2012, via the
"OFFSET n ROWS" and "FETCH NEXT n ROWS" clauses.  SQLAlchemy supports these
syntaxes automatically if SQL Server 2012 or greater is detected.
 
.. versionchanged:: 1.4 support added for SQL Server "OFFSET n ROWS" and
   "FETCH NEXT n ROWS" syntax.
 
For statements that specify only LIMIT and no OFFSET, all versions of SQL
Server support the TOP keyword.   This syntax is used for all SQL Server
versions when no OFFSET clause is present.  A statement such as::
 
    select(some_table).limit(5)
 
will render similarly to::
 
    SELECT TOP 5 col1, col2.. FROM table
 
For versions of SQL Server prior to SQL Server 2012, a statement that uses
LIMIT and OFFSET, or just OFFSET alone, will be rendered using the
``ROW_NUMBER()`` window function.   A statement such as::
 
    select(some_table).order_by(some_table.c.col3).limit(5).offset(10)
 
will render similarly to::
 
    SELECT anon_1.col1, anon_1.col2 FROM (SELECT col1, col2,
    ROW_NUMBER() OVER (ORDER BY col3) AS
    mssql_rn FROM table WHERE t.x = :x_1) AS
    anon_1 WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2 + :param_1
 
Note that when using LIMIT and/or OFFSET, whether using the older
or newer SQL Server syntaxes, the statement must have an ORDER BY as well,
else a :class:`.CompileError` is raised.
 
.. _mssql_comment_support:
 
DDL Comment Support
--------------------
 
Comment support, which includes DDL rendering for attributes such as
:paramref:`_schema.Table.comment` and :paramref:`_schema.Column.comment`, as
well as the ability to reflect these comments, is supported assuming a
supported version of SQL Server is in use. If a non-supported version such as
Azure Synapse is detected at first-connect time (based on the presence
of the ``fn_listextendedproperty`` SQL function), comment support including
rendering and table-comment reflection is disabled, as both features rely upon
SQL Server stored procedures and functions that are not available on all
backend types.
 
To force comment support to be on or off, bypassing autodetection, set the
parameter ``supports_comments`` within :func:`_sa.create_engine`::
 
    e = create_engine("mssql+pyodbc://u:p@dsn", supports_comments=False)
 
.. versionadded:: 2.0 Added support for table and column comments for
   the SQL Server dialect, including DDL generation and reflection.
 
.. _mssql_isolation_level:
 
Transaction Isolation Level
---------------------------
 
All SQL Server dialects support setting of transaction isolation level
both via a dialect-specific parameter
:paramref:`_sa.create_engine.isolation_level`
accepted by :func:`_sa.create_engine`,
as well as the :paramref:`.Connection.execution_options.isolation_level`
argument as passed to
:meth:`_engine.Connection.execution_options`.
This feature works by issuing the
command ``SET TRANSACTION ISOLATION LEVEL <level>`` for
each new connection.
 
To set isolation level using :func:`_sa.create_engine`::
 
    engine = create_engine(
        "mssql+pyodbc://scott:tiger@ms_2008",
        isolation_level="REPEATABLE READ"
    )
 
To set using per-connection execution options::
 
    connection = engine.connect()
    connection = connection.execution_options(
        isolation_level="READ COMMITTED"
    )
 
Valid values for ``isolation_level`` include:
 
* ``AUTOCOMMIT`` - pyodbc / pymssql-specific
* ``READ COMMITTED``
* ``READ UNCOMMITTED``
* ``REPEATABLE READ``
* ``SERIALIZABLE``
* ``SNAPSHOT`` - specific to SQL Server
 
There are also more options for isolation level configurations, such as
"sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
different isolation level settings.  See the discussion at
:ref:`dbapi_autocommit` for background.
 
.. seealso::
 
    :ref:`dbapi_autocommit`
 
.. _mssql_reset_on_return:
 
Temporary Table / Resource Reset for Connection Pooling
-------------------------------------------------------
 
The :class:`.QueuePool` connection pool implementation used
by the SQLAlchemy :class:`.Engine` object includes
:ref:`reset on return <pool_reset_on_return>` behavior that will invoke
the DBAPI ``.rollback()`` method when connections are returned to the pool.
While this rollback will clear out the immediate state used by the previous
transaction, it does not cover a wider range of session-level state, including
temporary tables as well as other server state such as prepared statement
handles and statement caches.   An undocumented SQL Server procedure known
as ``sp_reset_connection`` is known to be a workaround for this issue which
will reset most of the session state that builds up on a connection, including
temporary tables.
 
To install ``sp_reset_connection`` as the means of performing reset-on-return,
the :meth:`.PoolEvents.reset` event hook may be used, as demonstrated in the
example below. The :paramref:`_sa.create_engine.pool_reset_on_return` parameter
is set to ``None`` so that the custom scheme can replace the default behavior
completely.   The custom hook implementation calls ``.rollback()`` in any case,
as it's usually important that the DBAPI's own tracking of commit/rollback
will remain consistent with the state of the transaction::
 
    from sqlalchemy import create_engine
    from sqlalchemy import event
 
    mssql_engine = create_engine(
        "mssql+pyodbc://scott:tiger^5HHH@mssql2017:1433/test?driver=ODBC+Driver+17+for+SQL+Server",
 
        # disable default reset-on-return scheme
        pool_reset_on_return=None,
    )
 
 
    @event.listens_for(mssql_engine, "reset")
    def _reset_mssql(dbapi_connection, connection_record, reset_state):
        if not reset_state.terminate_only:
            dbapi_connection.execute("{call sys.sp_reset_connection}")
 
        # so that the DBAPI itself knows that the connection has been
        # reset
        dbapi_connection.rollback()
 
.. versionchanged:: 2.0.0b3  Added additional state arguments to
   the :meth:`.PoolEvents.reset` event and additionally ensured the event
   is invoked for all "reset" occurrences, so that it's appropriate
   as a place for custom "reset" handlers.   Previous schemes which
   use the :meth:`.PoolEvents.checkin` handler remain usable as well.
 
.. seealso::
 
    :ref:`pool_reset_on_return` - in the :ref:`pooling_toplevel` documentation
 
Nullability
-----------
MSSQL has support for three levels of column nullability. The default
nullability allows nulls and is explicit in the CREATE TABLE
construct::
 
    name VARCHAR(20) NULL
 
If ``nullable=None`` is specified then no specification is made. In
other words the database's configured default is used. This will
render::
 
    name VARCHAR(20)
 
If ``nullable`` is ``True`` or ``False`` then the column will be
``NULL`` or ``NOT NULL`` respectively.
 
Date / Time Handling
--------------------
DATE and TIME are supported.   Bind parameters are converted
to datetime.datetime() objects as required by most MSSQL drivers,
and results are processed from strings if needed.
The DATE and TIME types are not available for MSSQL 2005 and
previous - if a server version below 2008 is detected, DDL
for these types will be issued as DATETIME.
 
.. _mssql_large_type_deprecation:
 
Large Text/Binary Type Deprecation
----------------------------------
 
Per
`SQL Server 2012/2014 Documentation <https://technet.microsoft.com/en-us/library/ms187993.aspx>`_,
the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL
Server in a future release.   SQLAlchemy normally relates these types to the
:class:`.UnicodeText`, :class:`_expression.TextClause` and
:class:`.LargeBinary` datatypes.
 
In order to accommodate this change, a new flag ``deprecate_large_types``
is added to the dialect, which will be automatically set based on detection
of the server version in use, if not otherwise set by the user.  The
behavior of this flag is as follows:
 
* When this flag is ``True``, the :class:`.UnicodeText`,
  :class:`_expression.TextClause` and
  :class:`.LargeBinary` datatypes, when used to render DDL, will render the
  types ``NVARCHAR(max)``, ``VARCHAR(max)``, and ``VARBINARY(max)``,
  respectively.  This is a new behavior as of the addition of this flag.
 
* When this flag is ``False``, the :class:`.UnicodeText`,
  :class:`_expression.TextClause` and
  :class:`.LargeBinary` datatypes, when used to render DDL, will render the
  types ``NTEXT``, ``TEXT``, and ``IMAGE``,
  respectively.  This is the long-standing behavior of these types.
 
* The flag begins with the value ``None``, before a database connection is
  established.   If the dialect is used to render DDL without the flag being
  set, it is interpreted the same as ``False``.
 
* On first connection, the dialect detects if SQL Server version 2012 or
  greater is in use; if the flag is still at ``None``, it sets it to ``True``
  or ``False`` based on whether 2012 or greater is detected.
 
* The flag can be set to either ``True`` or ``False`` when the dialect
  is created, typically via :func:`_sa.create_engine`::
 
        eng = create_engine("mssql+pymssql://user:pass@host/db",
                        deprecate_large_types=True)
 
* Complete control over whether the "old" or "new" types are rendered is
  available in all SQLAlchemy versions by using the UPPERCASE type objects
  instead: :class:`_types.NVARCHAR`, :class:`_types.VARCHAR`,
  :class:`_types.VARBINARY`, :class:`_types.TEXT`, :class:`_mssql.NTEXT`,
  :class:`_mssql.IMAGE`
  will always remain fixed and always output exactly that
  type.
 
.. _multipart_schema_names:
 
Multipart Schema Names
----------------------
 
SQL Server schemas sometimes require multiple parts to their "schema"
qualifier, that is, including the database name and owner name as separate
tokens, such as ``mydatabase.dbo.some_table``. These multipart names can be set
at once using the :paramref:`_schema.Table.schema` argument of
:class:`_schema.Table`::
 
    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="mydatabase.dbo"
    )
 
When performing operations such as table or component reflection, a schema
argument that contains a dot will be split into separate
"database" and "owner"  components in order to correctly query the SQL
Server information schema tables, as these two values are stored separately.
Additionally, when rendering the schema name for DDL or SQL, the two
components will be quoted separately for case sensitive names and other
special characters.   Given an argument as below::
 
    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="MyDataBase.dbo"
    )
 
The above schema would be rendered as ``[MyDataBase].dbo``, and also in
reflection, would be reflected using "dbo" as the owner and "MyDataBase"
as the database name.
 
To control how the schema name is broken into database / owner,
specify brackets (which in SQL Server are quoting characters) in the name.
Below, the "owner" will be considered as ``MyDataBase.dbo`` and the
"database" will be None::
 
    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="[MyDataBase.dbo]"
    )
 
To individually specify both database and owner name with special characters
or embedded dots, use two sets of brackets::
 
    Table(
        "some_table", metadata,
        Column("q", String(50)),
        schema="[MyDataBase.Period].[MyOwner.Dot]"
    )
 
 
.. versionchanged:: 1.2 the SQL Server dialect now treats brackets as
   identifier delimiters splitting the schema into separate database
   and owner tokens, to allow dots within either name itself.
 
.. _legacy_schema_rendering:
 
Legacy Schema Mode
------------------
 
Very old versions of the MSSQL dialect introduced the behavior such that a
schema-qualified table would be auto-aliased when used in a
SELECT statement; given a table::
 
    account_table = Table(
        'account', metadata,
        Column('id', Integer, primary_key=True),
        Column('info', String(100)),
        schema="customer_schema"
    )
 
this legacy mode of rendering would assume that "customer_schema.account"
would not be accepted by all parts of the SQL statement, as illustrated
below:
 
.. sourcecode:: pycon+sql
 
    >>> eng = create_engine("mssql+pymssql://mydsn", legacy_schema_aliasing=True)
    >>> print(account_table.select().compile(eng))
    {printsql}SELECT account_1.id, account_1.info
    FROM customer_schema.account AS account_1
 
This mode of behavior is now off by default, as it appears to have served
no purpose; however in the case that legacy applications rely upon it,
it is available using the ``legacy_schema_aliasing`` argument to
:func:`_sa.create_engine` as illustrated above.
 
.. deprecated:: 1.4
 
   The ``legacy_schema_aliasing`` flag is now
   deprecated and will be removed in a future release.
 
.. _mssql_indexes:
 
Clustered Index Support
-----------------------
 
The MSSQL dialect supports clustered indexes (and primary keys) via the
``mssql_clustered`` option.  This option is available to :class:`.Index`,
:class:`.UniqueConstraint`. and :class:`.PrimaryKeyConstraint`.
 
To generate a clustered index::
 
    Index("my_index", table.c.x, mssql_clustered=True)
 
which renders the index as ``CREATE CLUSTERED INDEX my_index ON table (x)``.
 
To generate a clustered primary key use::
 
    Table('my_table', metadata,
          Column('x', ...),
          Column('y', ...),
          PrimaryKeyConstraint("x", "y", mssql_clustered=True))
 
which will render the table, for example, as::
 
  CREATE TABLE my_table (x INTEGER NOT NULL, y INTEGER NOT NULL,
                         PRIMARY KEY CLUSTERED (x, y))
 
Similarly, we can generate a clustered unique constraint using::
 
    Table('my_table', metadata,
          Column('x', ...),
          Column('y', ...),
          PrimaryKeyConstraint("x"),
          UniqueConstraint("y", mssql_clustered=True),
          )
 
To explicitly request a non-clustered primary key (for example, when
a separate clustered index is desired), use::
 
    Table('my_table', metadata,
          Column('x', ...),
          Column('y', ...),
          PrimaryKeyConstraint("x", "y", mssql_clustered=False))
 
which will render the table, for example, as::
 
  CREATE TABLE my_table (x INTEGER NOT NULL, y INTEGER NOT NULL,
                         PRIMARY KEY NONCLUSTERED (x, y))
 
MSSQL-Specific Index Options
-----------------------------
 
In addition to clustering, the MSSQL dialect supports other special options
for :class:`.Index`.
 
INCLUDE
^^^^^^^
 
The ``mssql_include`` option renders INCLUDE(colname) for the given string
names::
 
    Index("my_index", table.c.x, mssql_include=['y'])
 
would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)``
 
.. _mssql_index_where:
 
Filtered Indexes
^^^^^^^^^^^^^^^^
 
The ``mssql_where`` option renders WHERE(condition) for the given string
names::
 
    Index("my_index", table.c.x, mssql_where=table.c.x > 10)
 
would render the index as ``CREATE INDEX my_index ON table (x) WHERE x > 10``.
 
.. versionadded:: 1.3.4
 
Index ordering
^^^^^^^^^^^^^^
 
Index ordering is available via functional expressions, such as::
 
    Index("my_index", table.c.x.desc())
 
would render the index as ``CREATE INDEX my_index ON table (x DESC)``
 
.. seealso::
 
    :ref:`schema_indexes_functional`
 
Compatibility Levels
--------------------
MSSQL supports the notion of setting compatibility levels at the
database level. This allows, for instance, to run a database that
is compatible with SQL2000 while running on a SQL2005 database
server. ``server_version_info`` will always return the database
server version information (in this case SQL2005) and not the
compatibility level information. Because of this, if running under
a backwards compatibility mode SQLAlchemy may attempt to use T-SQL
statements that are unable to be parsed by the database server.
 
.. _mssql_triggers:
 
Triggers
--------
 
SQLAlchemy by default uses OUTPUT INSERTED to get at newly
generated primary key values via IDENTITY columns or other
server side defaults.   MS-SQL does not
allow the usage of OUTPUT INSERTED on tables that have triggers.
To disable the usage of OUTPUT INSERTED on a per-table basis,
specify ``implicit_returning=False`` for each :class:`_schema.Table`
which has triggers::
 
    Table('mytable', metadata,
        Column('id', Integer, primary_key=True),
        # ...,
        implicit_returning=False
    )
 
Declarative form::
 
    class MyClass(Base):
        # ...
        __table_args__ = {'implicit_returning':False}
 
 
.. _mssql_rowcount_versioning:
 
Rowcount Support / ORM Versioning
---------------------------------
 
The SQL Server drivers may have limited ability to return the number
of rows updated from an UPDATE or DELETE statement.
 
As of this writing, the PyODBC driver is not able to return a rowcount when
OUTPUT INSERTED is used.    Previous versions of SQLAlchemy therefore had
limitations for features such as the "ORM Versioning" feature that relies upon
accurate rowcounts in order to match version numbers with matched rows.
 
SQLAlchemy 2.0 now retrieves the "rowcount" manually for these particular use
cases based on counting the rows that arrived back within RETURNING; so while
the driver still has this limitation, the ORM Versioning feature is no longer
impacted by it. As of SQLAlchemy 2.0.5, ORM versioning has been fully
re-enabled for the pyodbc driver.
 
.. versionchanged:: 2.0.5  ORM versioning support is restored for the pyodbc
   driver.  Previously, a warning would be emitted during ORM flush that
   versioning was not supported.
 
 
Enabling Snapshot Isolation
---------------------------
 
SQL Server has a default transaction
isolation mode that locks entire tables, and causes even mildly concurrent
applications to have long held locks and frequent deadlocks.
Enabling snapshot isolation for the database as a whole is recommended
for modern levels of concurrency support.  This is accomplished via the
following ALTER DATABASE commands executed at the SQL prompt::
 
    ALTER DATABASE MyDatabase SET ALLOW_SNAPSHOT_ISOLATION ON
 
    ALTER DATABASE MyDatabase SET READ_COMMITTED_SNAPSHOT ON
 
Background on SQL Server snapshot isolation is available at
https://msdn.microsoft.com/en-us/library/ms175095.aspx.
 
é)Ú annotationsN)Úoverload)Ú TYPE_CHECKING)ÚUUIDé)Úinformation_schema)ÚJSON)Ú JSONIndexType)Ú JSONPathTypeé)Úexc)ÚIdentity)Úschema)ÚSequence)Úsql)Útext)Úutil)Úcursor)Údefault)Ú
reflection)ÚReflectionDefaults)Ú    coercions)Úcompiler)Úelements)Ú
expression)Úfunc)Ú quoted_name)Úroles)Úsqltypes)Úis_sql_compiler)ÚInsertmanyvaluesSentinelOpts)ÚBIGINT)ÚBINARY)ÚCHAR)ÚDATE)ÚDATETIME)ÚDECIMAL)ÚFLOAT)ÚINTEGER)ÚNCHAR)ÚNUMERIC)ÚNVARCHAR)ÚSMALLINT)ÚTEXT)ÚVARCHAR©Úupdate_wrapper)ÚLiteral)ÚDMLState)Ú TableClause)é)é )é )é )é
)é    )éÚaddÚallZalterÚandÚanyÚasZascÚ authorizationÚbackupÚbeginZbetweenÚbreakZbrowseZbulkZbyZcascadeZcaseÚcheckÚ
checkpointÚcloseÚ    clusteredZcoalesceÚcollateÚcolumnÚcommitZcomputeÚ
constraintÚcontainsZ containstableÚcontinueÚconvertÚcreateZcrossÚcurrentZ current_dateÚ current_timeZcurrent_timestampZ current_userrZdatabaseZdbccZ
deallocateZdeclarerÚdeleteZdenyÚdescZdiskZdistinctZ distributedÚdoubleÚdropÚdumpÚelseÚendZerrlvlÚescapeÚexceptÚexecÚexecuteÚexistsÚexitZexternalÚfetchÚfileZ
fillfactorÚforZforeignZfreetextZ freetexttableÚfromÚfullÚfunctionÚgotoZgrantÚgroupZhavingZholdlockÚidentityZidentity_insertZ identitycolÚifÚinÚindexÚinnerÚinsertZ    intersectZintoÚisÚjoinÚkeyÚkillÚleftZlikeÚlinenoÚloadÚmergeZnationalZnocheckZ nonclusteredÚnotÚnullZnullifZofÚoffÚoffsetsÚonÚopenZopendatasourceZ    openqueryZ
openrowsetZopenxmlÚoptionÚorÚorderÚouterÚoverÚpercentZpivotZplanÚ    precisionZprimaryÚprintÚprocZ    procedureÚpublicZ    raiserrorÚreadZreadtextÚ reconfigureZ
referencesZ replicationÚrestoreZrestrictÚreturnÚrevertZrevokeÚrightÚrollbackÚrowcountZ
rowguidcolZruleÚsaverZ securityauditÚselectZ session_userÚsetZsetuserÚshutdownZsomeZ
statisticsZ system_userÚtableZ tablesampleZtextsizeZthenÚtoÚtopZtranZ transactionZtriggerÚtruncateZtsequalÚunionÚuniqueZunpivotÚupdateZ
updatetextZuseÚuserÚvaluesZvaryingÚviewZwaitforÚwhenÚwhereÚwhileÚwithZ    writetextcs eZdZdZ‡fdd„Z‡ZS)ÚREALzthe SQL Server REAL datatype.c s| dd¡tƒjf|ŽdS)Nré©Ú
setdefaultÚsuperÚ__init__©ÚselfÚkw©Ú    __class__©úUd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\sqlalchemy/dialects/mssql/base.pyr¤‰s z REAL.__init__©Ú__name__Ú
__module__Ú __qualname__Ú__doc__r¤Ú __classcell__rªrªr¨r«rŸ†srŸcs eZdZdZ‡fdd„Z‡ZS)ÚDOUBLE_PRECISIONzMthe SQL Server DOUBLE PRECISION datatype.
 
    .. versionadded:: 2.0.11
 
    c s| dd¡tƒjf|ŽdS)Nré5r¡r¥r¨rªr«r¤˜s zDOUBLE_PRECISION.__init__r¬rªrªr¨r«r²‘sr²c@seZdZdZdS)ÚTINYINTN©r­r®r¯Ú__visit_name__rªrªrªr«r´ sr´c@s&eZdZdd„Ze d¡Zdd„ZdS)Ú_MSDatecCs dd„}|S)NcSs*t|ƒtjkr"t |j|j|j¡S|SdS©N©ÚtypeÚdatetimeÚdateÚyearÚmonthÚday©Úvaluerªrªr«Úprocess¬sz'_MSDate.bind_processor.<locals>.processrª©r¦ÚdialectrÂrªrªr«Úbind_processor«sz_MSDate.bind_processorz(\d+)-(\d+)-(\d+)cs‡fdd„}|S)Ncs\t|tjƒr| ¡St|tƒrTˆj |¡}|s<td|fƒ‚tjdd„| ¡DƒŽS|SdS)Nz"could not parse %r as a date valuecSsg|]}t|pdƒ‘qS©r©Úint©Ú.0Úxrªrªr«Ú
<listcomp>Àsz=_MSDate.result_processor.<locals>.process.<locals>.<listcomp>)Ú
isinstancer»r¼ÚstrÚ_regÚmatchÚ
ValueErrorÚgroups©rÁÚm©r¦rªr«r·s 
 ÿz)_MSDate.result_processor.<locals>.processrª©r¦rÄÚcoltyperÂrªrÕr«Úresult_processor¶s z_MSDate.result_processorN)r­r®r¯rÅÚreÚcompilerÏrØrªrªrªr«r·ªs    
r·csFeZdZd ‡fdd„    Ze ddd¡Zdd„Ze     d¡Z
d    d
„Z ‡Z S) ÚTIMENc s||_tƒ ¡dSr¸)rr£r¤)r¦rÚkwargsr¨rªr«r¤Èsz TIME.__init__ilrcs‡fdd„}|S)Ncs:t|tjƒr"tj ˆj| ¡¡}nt|tjƒr6t|ƒ}|Sr¸)rÍr»ÚcombineÚ_TIME__zero_dateÚtimerÎrÀrÕrªr«rÂÏs ÿ z$TIME.bind_processor.<locals>.processrªrÃrªrÕr«rÅÎs zTIME.bind_processorz!(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?cs‡fdd„}|S)Ncs\t|tjƒr| ¡St|tƒrTˆj |¡}|s<td|fƒ‚tjdd„| ¡DƒŽS|SdS)Nz"could not parse %r as a time valuecSsg|]}t|pdƒ‘qSrÆrÇrÉrªrªr«rÌêsz:TIME.result_processor.<locals>.process.<locals>.<listcomp>)rÍr»rßrÎrÏrÐrÑrÒrÓrÕrªr«rÂás 
 ÿz&TIME.result_processor.<locals>.processrªrÖrªrÕr«rØàs zTIME.result_processor)N) r­r®r¯r¤r»r¼rÞrÅrÙrÚrÏrØr±rªrªr¨r«rÛÇs
 
rÛc@seZdZdZdS)Ú _BASETIMEIMPLNrµrªrªrªr«ràôsràc@seZdZdd„ZdS)Ú _DateTimeBasecCs dd„}|S)NcSs*t|ƒtjkr"t |j|j|j¡S|SdSr¸r¹rÀrªrªr«rÂúsz-_DateTimeBase.bind_processor.<locals>.processrªrÃrªrªr«rÅùsz_DateTimeBase.bind_processorN)r­r®r¯rÅrªrªrªr«ráøsrác@s eZdZdS)Ú _MSDateTimeN©r­r®r¯rªrªrªr«râsrâc@seZdZdZdS)Ú SMALLDATETIMENrµrªrªrªr«räsräcs"eZdZdZd‡fdd„    Z‡ZS)Ú    DATETIME2Nc stƒjf|Ž||_dSr¸©r£r¤r©r¦rr§r¨rªr«r¤szDATETIME2.__init__)N©r­r®r¯r¶r¤r±rªrªr¨r«rå sråcs"eZdZdZd‡fdd„    Z‡ZS)ÚDATETIMEOFFSETNc stƒjf|Ž||_dSr¸rærçr¨rªr«r¤szDATETIMEOFFSET.__init__)Nrèrªrªr¨r«résréc@seZdZdd„ZdS)Ú_UnicodeLiteralcs‡fdd„}|S)Ncs(| dd¡}ˆjjr | dd¡}d|S)Nú'ú''ú%z%%zN'%s')ÚreplaceÚidentifier_preparerZ_double_percentsrÀ©rÄrªr«rÂs  z2_UnicodeLiteral.literal_processor.<locals>.processrªrÃrªrðr«Úliteral_processors     z!_UnicodeLiteral.literal_processorN)r­r®r¯rñrªrªrªr«rêsrêc@s eZdZdS)Ú
_MSUnicodeNrãrªrªrªr«rò)sròc@s eZdZdS)Ú_MSUnicodeTextNrãrªrªrªr«ró-srócs2eZdZdZdZdZddd„Z‡fdd„Z‡ZS)    Ú    TIMESTAMPaBImplement the SQL Server TIMESTAMP type.
 
    Note this is **completely different** than the SQL Standard
    TIMESTAMP type, which is not supported by SQL Server.  It
    is a read-only datatype that does not support INSERT of values.
 
    .. versionadded:: 1.2
 
    .. seealso::
 
        :class:`_mssql.ROWVERSION`
 
    NFcCs
||_dS)z¾Construct a TIMESTAMP or ROWVERSION type.
 
        :param convert_int: if True, binary integer values will
         be converted to integers on read.
 
        .. versionadded:: 1.2
 
        N)Ú convert_int)r¦rõrªrªr«r¤Es    zTIMESTAMP.__init__cs,tƒ ||¡‰|jr$‡fdd„}|SˆSdS)Ncs*ˆr ˆ|ƒ}|dk    r&tt |d¡dƒ}|S)NÚhexé)rÈÚcodecsÚencoderÀ©Úsuper_rªr«rÂTs
z+TIMESTAMP.result_processor.<locals>.process)r£rØrõrÖr¨rúr«rØPs
 zTIMESTAMP.result_processor)F)    r­r®r¯r°r¶Úlengthr¤rØr±rªrªr¨r«rô1s
 
rôc@seZdZdZdZdS)Ú
ROWVERSIONa(Implement the SQL Server ROWVERSION type.
 
    The ROWVERSION datatype is a SQL Server synonym for the TIMESTAMP
    datatype, however current SQL Server documentation suggests using
    ROWVERSION for new datatypes going forward.
 
    The ROWVERSION datatype does **not** reflect (e.g. introspect) from the
    database as itself; the returned datatype will be
    :class:`_mssql.TIMESTAMP`.
 
    This is a read-only datatype that does not support INSERT of values.
 
    .. versionadded:: 1.2
 
    .. seealso::
 
        :class:`_mssql.TIMESTAMP`
 
    N©r­r®r¯r°r¶rªrªrªr«rýasrýc@seZdZdZdZdS)ÚNTEXTzMMSSQL NTEXT type, for variable-length unicode text up to 2^30
    characters.Nrþrªrªrªr«rÿysrÿcs&eZdZdZdZd‡fdd„    Z‡ZS)Ú    VARBINARYaLThe MSSQL VARBINARY type.
 
    This type adds additional features to the core :class:`_types.VARBINARY`
    type, including "deprecate_large_types" mode where
    either ``VARBINARY(max)`` or IMAGE is rendered, as well as the SQL
    Server ``FILESTREAM`` option.
 
    .. seealso::
 
        :ref:`mssql_large_type_deprecation`
 
    NFcs.||_|jr|dkrtdƒ‚tƒj|ddS)a·
        Construct a VARBINARY type.
 
        :param length: optional, a length for the column for use in
          DDL statements, for those binary types that accept a length,
          such as the MySQL BLOB type.
 
        :param filestream=False: if True, renders the ``FILESTREAM`` keyword
          in the table definition. In this case ``length`` must be ``None``
          or ``'max'``.
 
          .. versionadded:: 1.4.31
 
        )NÚmaxz4length must be None or 'max' when setting filestream©rüN)Ú
filestreamrÑr£r¤)r¦rürr¨rªr«r¤‘s ÿzVARBINARY.__init__)NF)r­r®r¯r°r¶r¤r±rªrªr¨r«rs rc@seZdZdZdS)ÚIMAGENrµrªrªrªr«r©src@seZdZdZdZdS)ÚXMLaMSSQL XML type.
 
    This is a placeholder type for reflection purposes that does not include
    any Python-side datatype support.   It also does not currently support
    additional arguments, such as "CONTENT", "DOCUMENT",
    "xml_schema_collection".
 
    Nrþrªrªrªr«r­s    rc@seZdZdZdZdS)ÚBITzˆMSSQL BIT type.
 
    Both pyodbc and pymssql return values from BIT columns as
    Python <class 'bool'> so just subclass Boolean.
 
    Nrþrªrªrªr«rºsrc@seZdZdZdS)ÚMONEYNrµrªrªrªr«rÅsrc@seZdZdZdS)Ú
SMALLMONEYNrµrªrªrªr«rÉsrc@s$eZdZdd„Zdd„Zdd„ZdS)ÚMSUUidcCs,|jr
dS|jrdd„}|Sdd„}|SdS)NcSs|dk    r|j}|Sr¸©rörÀrªrªr«rÂÖsz&MSUUid.bind_processor.<locals>.processcSs |dk    r| dd¡ dd¡}|S)Nú-Úrìrë©rîrÀrªrªr«rÂÞs©Ú native_uuidÚas_uuidrÃrªrªr«rÅÎszMSUUid.bind_processorcCs4|jrdd„}|S|jr$dd„}|Sdd„}|SdS)NcSs$|dk    r dt|ƒ dd¡›d}|S)Nrërì)rÎrîrÀrªrªr«rÂèsz)MSUUid.literal_processor.<locals>.processcSs|dk    rd|j›d}|S)Nrër
rÀrªrªr«rÂñscSs(|dk    r$d| dd¡ dd¡›d}|S)Nrër r rìr rÀrªrªr«rÂùs
ÿrrÃrªrªr«rñåszMSUUid.literal_processorcCs8|j p|j }|r0|jr$dd„}ndd„}|SdSdS)aÊReturn a callable that will receive the uuid object or string
        as it is normally passed to the DB in the parameter set, after
        bind_processor() is called.  Convert this value to match
        what it would be as coming back from an INSERT..OUTPUT inserted.
 
        for the UUID type, there are four varieties of settings so here
        we seek to convert to the string or UUID representation that comes
        back from the driver.
 
        cSs t|ƒ ¡Sr¸)rÎÚupperrÀrªrªr«rÂsz0MSUUid._sentinel_value_resolver.<locals>.processcSst|ƒSr¸©rÎrÀrªrªr«rÂsN)Zsupports_native_uuidr)r¦rÄZcharacter_based_uuidrÂrªrªr«Ú_sentinel_value_resolvers ÿ
zMSUUid._sentinel_value_resolverN)r­r®r¯rÅrñrrªrªrªr«r    Ísr    c@sLeZdZdZeddddœdd„ƒZeddddœd    d„ƒZdd d œd d„ZdS)ÚUNIQUEIDENTIFIER.zUNIQUEIDENTIFIER[_python_UUID]z Literal[True]©r¦rcCsdSr¸rªrrªrªr«r¤'szUNIQUEIDENTIFIER.__init__zUNIQUEIDENTIFIER[str]zLiteral[False]cCsdSr¸rªrrªrªr«r¤-sTÚbool)rcCs||_d|_dS)aƒConstruct a :class:`_mssql.UNIQUEIDENTIFIER` type.
 
 
        :param as_uuid=True: if True, values will be interpreted
         as Python uuid objects, converting to/from string via the
         DBAPI.
 
         .. versionchanged: 2.0 Added direct "uuid" support to the
            :class:`_mssql.UNIQUEIDENTIFIER` datatype; uuid interpretation
            defaults to ``True``.
 
        TN)rrrrªrªr«r¤1s N).).)T)r­r®r¯r¶rr¤rªrªrªr«r$sÿrc@seZdZdZdS)Ú SQL_VARIANTNrµrªrªrªr«rBsrcOs
t||ŽS)adCreate a TRY_CAST expression.
 
    :class:`.TryCast` is a subclass of SQLAlchemy's :class:`.Cast`
    construct, and works in the same way, except that the SQL expression
    rendered is "TRY_CAST" rather than "CAST"::
 
        from sqlalchemy import select
        from sqlalchemy import Numeric
        from sqlalchemy.dialects.mssql import try_cast
 
        stmt = select(
            try_cast(product_table.c.unit_price, Numeric(10, 4))
        )
 
    The above would render::
 
        SELECT TRY_CAST (product_table.unit_price AS NUMERIC(10, 4))
        FROM product_table
 
    .. versionadded:: 1.3.7
 
    )ÚTryCast)Úargr§rªrªr«Útry_castFsrc@seZdZdZdZdZdZdS)rz+Represent a SQL Server TRY_CAST expression.rÚmssqlTN)r­r®r¯r°r¶Zstringify_dialectZ inherit_cacherªrªrªr«r`sr)rÈZbigintZsmallintZtinyintZvarcharZnvarcharÚcharZncharrZntextÚdecimalÚnumericÚfloatr»Z    datetime2Zdatetimeoffsetr¼rßZ smalldatetimeÚbinaryZ    varbinaryÚbitÚrealzdouble precisionÚimageÚxmlÚ    timestampZmoneyZ
smallmoneyZuniqueidentifierZ sql_variantcs.eZdZdHdd„Zdd„Zdd„Zdd    „Zd
d „Zd d „Zdd„Z    dd„Z
dd„Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Zd,d-„Zd.d/„Zd0d1„Zd2d3„Zd4d5„Zd6d7„Zd8d9„Zd:d;„Zd<d=„Z d>d?„Z!d@dA„Z"‡fdBdC„Z#dDdE„Z$dFdG„Z%‡Z&S)IÚMSTypeCompilerNcCsNt|ddƒrd|j}nd}|s&|j}|r6|d|}d dd„||fDƒ¡S)zYExtend a string-type declaration with standard SQL
        COLLATE annotations.
 
        Ú    collationNz
COLLATE %sú(%s)ú cSsg|]}|dk    r|‘qSr¸rª©rÊÚcrªrªr«r̶sz*MSTypeCompiler._extend.<locals>.<listcomp>)Úgetattrr'rürn)r¦ÚspecÚtype_rür'rªrªr«Ú_extend¥s   zMSTypeCompiler._extendcKs|j|f|ŽSr¸)Zvisit_DOUBLE_PRECISION©r¦r.r§rªrªr«Ú visit_double¸szMSTypeCompiler.visit_doublecKs(t|ddƒ}|dkrdSdd|iSdS)Nrr'zFLOAT(%(precision)s)©r,©r¦r.r§rrªrªr«Ú visit_FLOAT»s zMSTypeCompiler.visit_FLOATcKsdS)Nr´rªr0rªrªr«Ú visit_TINYINTÂszMSTypeCompiler.visit_TINYINTcKs$t|ddƒ}|dk    rd|SdSdS)NrzTIME(%s)rÛr2r3rªrªr«Ú
visit_TIMEÅs zMSTypeCompiler.visit_TIMEcKsdS)Nrôrªr0rªrªr«Úvisit_TIMESTAMPÌszMSTypeCompiler.visit_TIMESTAMPcKsdS)Nrýrªr0rªrªr«Úvisit_ROWVERSIONÏszMSTypeCompiler.visit_ROWVERSIONcKs&|jr|j|f|ŽS|j|f|ŽSdSr¸)ÚtimezoneÚvisit_DATETIMEOFFSETÚvisit_DATETIMEr0rªrªr«Úvisit_datetimeÒszMSTypeCompiler.visit_datetimecKs&t|ddƒ}|dk    rd|jSdSdS)NrzDATETIMEOFFSET(%s)ré)r,rr3rªrªr«r:Øs 
z#MSTypeCompiler.visit_DATETIMEOFFSETcKs$t|ddƒ}|dk    rd|SdSdS)Nrz DATETIME2(%s)rår2r3rªrªr«Úvisit_DATETIME2ßs zMSTypeCompiler.visit_DATETIME2cKsdS)Nrärªr0rªrªr«Úvisit_SMALLDATETIMEæsz"MSTypeCompiler.visit_SMALLDATETIMEcKs|j|f|ŽSr¸)Úvisit_NVARCHARr0rªrªr«Ú visit_unicodeészMSTypeCompiler.visit_unicodecKs(|jjr|j|f|ŽS|j|f|ŽSdSr¸)rÄÚdeprecate_large_typesÚ visit_VARCHARÚ
visit_TEXTr0rªrªr«Ú
visit_textìszMSTypeCompiler.visit_textcKs(|jjr|j|f|ŽS|j|f|ŽSdSr¸)rÄrAr?Ú visit_NTEXTr0rªrªr«Úvisit_unicode_textòsz!MSTypeCompiler.visit_unicode_textcKs | d|¡S)Nrÿ©r/r0rªrªr«rEøszMSTypeCompiler.visit_NTEXTcKs | d|¡S)Nr-rGr0rªrªr«rCûszMSTypeCompiler.visit_TEXTcKs|jd||jpddS)Nr.rr©r/rür0rªrªr«rBþszMSTypeCompiler.visit_VARCHARcKs | d|¡S)Nr#rGr0rªrªr«Ú
visit_CHARszMSTypeCompiler.visit_CHARcKs | d|¡S)Nr)rGr0rªrªr«Ú visit_NCHARszMSTypeCompiler.visit_NCHARcKs|jd||jpddS©Nr+rrrHr0rªrªr«r?szMSTypeCompiler.visit_NVARCHARcKs,|jjtkr|j|f|ŽS|j|f|ŽSdSr¸)rÄÚserver_version_infoÚMS_2008_VERSIONr;Z
visit_DATEr0rªrªr«Ú
visit_date
s zMSTypeCompiler.visit_datecKs|j|f|ŽSr¸)Ú
visit_timer0rªrªr«Úvisit__BASETIMEIMPLsz"MSTypeCompiler.visit__BASETIMEIMPLcKs,|jjtkr|j|f|ŽS|j|f|ŽSdSr¸)rÄrLrMr;r6r0rªrªr«rOs zMSTypeCompiler.visit_timecKs(|jjr|j|f|ŽS|j|f|ŽSdSr¸)rÄrAÚvisit_VARBINARYÚ visit_IMAGEr0rªrªr«Úvisit_large_binarysz!MSTypeCompiler.visit_large_binarycKsdS)Nrrªr0rªrªr«rRszMSTypeCompiler.visit_IMAGEcKsdS)Nrrªr0rªrªr«Ú    visit_XML"szMSTypeCompiler.visit_XMLcKs.|jd||jpdd}t|ddƒr*|d7}|S)NrrrrFz  FILESTREAM)r/rür,)r¦r.r§rrªrªr«rQ%s zMSTypeCompiler.visit_VARBINARYcKs
| |¡Sr¸)Ú    visit_BITr0rªrªr«Ú visit_boolean+szMSTypeCompiler.visit_booleancKsdS)Nrrªr0rªrªr«rU.szMSTypeCompiler.visit_BITcKs|jd|ddSrKrGr0rªrªr«Ú
visit_JSON1szMSTypeCompiler.visit_JSONcKsdS)Nrrªr0rªrªr«Ú visit_MONEY6szMSTypeCompiler.visit_MONEYcKsdS)Nrrªr0rªrªr«Úvisit_SMALLMONEY9szMSTypeCompiler.visit_SMALLMONEYc s(|jr|j|f|ŽStƒj|f|ŽSdSr¸)rÚvisit_UNIQUEIDENTIFIERr£Ú
visit_uuidr0r¨rªr«r[<szMSTypeCompiler.visit_uuidcKsdS)Nrrªr0rªrªr«rZBsz%MSTypeCompiler.visit_UNIQUEIDENTIFIERcKsdS)Nrrªr0rªrªr«Úvisit_SQL_VARIANTEsz MSTypeCompiler.visit_SQL_VARIANT)N)'r­r®r¯r/r1r4r5r6r7r8r<r:r=r>r@rDrFrErCrBrIrJr?rNrPrOrSrRrTrQrVrUrWrXrYr[rZr\r±rªrªr¨r«r&¤sF
 r&csreZdZUdZdZdZdZded<dd„Zdd„Z    d    d
„Z
d d „Z e d d„ƒZ dd„Zdd„Z‡fdd„Z‡ZS)ÚMSExecutionContextFNÚ    MSDialectrÄcCs*|jr&|jjr&|jjj}|||jjƒ}|Sr¸)ÚcompiledZschema_translate_mapÚpreparerZ_render_schema_translates)r¦Z    statementZrstrªrªr«Ú _opt_encodeQs
zMSExecutionContext._opt_encodec    Csø|jrôtr>t|jƒst‚t|jjtƒs*t‚t|jjjt    ƒs>t‚|jjj}|j
}|dk    r”t|j t ƒs”d}|jj }|j|jdkpŽ|joŽ|j|jk|_n
d}d|_|jj oÄ|oÄ|jj oÄ|j oÄ|j |_|jrô|j |j| d|j |¡¡d|¡dS)z#Activate IDENTITY_INSERT if needed.NTrFzSET IDENTITY_INSERT %s ONrª)Úisinsertrrr_ÚAssertionErrorrÍÚ compile_stater2Ú    dml_tabler3Ú_autoincrement_columnrrZdml_compile_stateroZcompiled_parametersZ_dict_parametersZ_insert_col_keysÚ_enable_identity_insertÚinlineÚeffective_returningZ executemanyÚ_select_lastrowidÚroot_connectionÚ_cursor_executerrarïÚ format_table)r¦ZtblZ    id_columnZinsert_has_identityrdrªrªr«Úpre_execZsTÿ
 
ÿÿ
ü
ÿþýû
ÿÿùzMSExecutionContext.pre_execc    Cs|j}|js|js|jr"|jj|_|jrt|jj    rD| 
|jdd|¡n| 
|jdd|¡|j  ¡d}t |dƒ|_ n8|jdk    r¬t|jƒr¬|jjr¬t |j|jj|j  ¡¡|_|jrtrìt|jƒsÆt‚t|jjtƒsØt‚t|jjjtƒsìt‚| 
|j| d|j |jjj¡¡d|¡dS)z#Disable IDENTITY_INSERT if enabled.z$SELECT scope_identity() AS lastrowidrªzSELECT @@identity AS lastrowidrNúSET IDENTITY_INSERT %s OFF) rkrbÚisupdateÚisdeleterrŒÚ    _rowcountrjrÄÚuse_scope_identityrlZfetchallrÈÚ
_lastrowidr_rriÚ_cursorZ FullyBufferedCursorFetchStrategyÚ descriptionZcursor_fetch_strategyrgrrcrÍrdr2rer3rarïrm)r¦ÚconnÚrowrªrªr«Ú    post_exec‹sf
üÿÿþýýÿÿÿÿÿ÷zMSExecutionContext.post_execcCs|jSr¸)rtrÕrªrªr«Ú get_lastrowidÃsz MSExecutionContext.get_lastrowidcCs|jdk    r|jS|jjSdSr¸)rrrrŒrÕrªrªr«rŒÆs
zMSExecutionContext.rowcountcCsH|jrDz(|j | d|j |jjj¡¡¡Wnt    k
rBYnXdS)Nro)
rgrr\rarïrmr_rdreÚ    Exception)r¦Úerªrªr«Úhandle_dbapi_exceptionÍsÿÿÿÿz)MSExecutionContext.handle_dbapi_exceptioncCs| d|j |¡|¡S)NzSELECT NEXT VALUE FOR %s)Z_execute_scalarrïÚformat_sequence)r¦Úseqr.rªrªr«Ú fire_sequenceÛs 
ÿûz MSExecutionContext.fire_sequencecs>t|tjƒr2||jjkr2t|jtjƒr2|jjr2dStƒ     |¡Sr¸)
rÍÚ    sa_schemaÚColumnr‘rfrrÚoptionalr£Úget_insert_default)r¦rIr¨rªr«r„äs
ÿ
þ ýüz%MSExecutionContext.get_insert_default)r­r®r¯rgrjrtrrÚ__annotations__rarnryrzÚpropertyrŒr}r€r„r±rªrªr¨r«r]Is
    18
    r]cs¾eZdZdZe ejjdddddœ¡Z‡fdd„Z    ‡fd    d
„Z
d d „Z d d„Z dd„Z dd„Zdd„Zdd„Zdd„Zdd„Zdd„Z‡fdd„Zdd „Zd!d"„Zd#d$„Zd%d&„Zd'd(„Zd)d*„Zd+d,„Zd-d.„Zd/d0„Ze
da‡fd2d3„    ƒZe
‡fd4d5„ƒZe
db‡fd7d8„    ƒZ d9d:„Z!d;d<„Z"d=d>„Z#d?d@„Z$‡fdAdB„Z%dCdD„Z&dEdF„Z'‡fdGdH„Z(dIdJ„Z)dKdL„Z*dMdN„Z+dOdP„Z,dQdR„Z-dSdT„Z.dUdV„Z/dWdX„Z0dYdZ„Z1d[d\„Z2d]d^„Z3d_d`„Z4‡Z5S)cÚ MSSQLCompilerTZ    dayofyearÚweekdayZ millisecondÚ microsecond)ZdoyZdowZ millisecondsÚ microsecondscsi|_tƒj||ŽdSr¸)Ú tablealiasesr£r¤)r¦ÚargsrÜr¨rªr«r¤üszMSSQLCompiler.__init__cs‡‡fdd„}|S)Ncs8|jjrˆ|f|ž|ŽSttt|ƒˆjƒ}|||ŽSdSr¸)rÄÚlegacy_schema_aliasingr,r£r‡r­)r¦rr§rû)r©Úfnrªr«Údecoratesz<MSSQLCompiler._with_legacy_schema_aliasing.<locals>.decoraterª)rŽrr¨©rŽr«Ú_with_legacy_schema_aliasingsz*MSSQLCompiler._with_legacy_schema_aliasingcKsdS)NZCURRENT_TIMESTAMPrª©r¦rŽr§rªrªr«Úvisit_now_func
szMSSQLCompiler.visit_now_funccKsdS)Nz    GETDATE()rªr’rªrªr«Úvisit_current_date_func sz%MSSQLCompiler.visit_current_date_funccKsd|j|f|ŽS©NzLEN%s©Zfunction_argspecr’rªrªr«Úvisit_length_funcszMSSQLCompiler.visit_length_funccKsd|j|f|ŽSr•r–r’rªrªr«Úvisit_char_length_funcsz$MSSQLCompiler.visit_char_length_funcc sd ‡‡fdd„|Dƒ¡S)Nz + c3s|]}ˆj|fˆŽVqdSr¸)r©rÊÚelem©r§r¦rªr«Ú    <genexpr>szFMSSQLCompiler.visit_concat_op_expression_clauselist.<locals>.<genexpr>©rn)r¦Z
clauselistÚoperatorr§rªr›r«Ú%visit_concat_op_expression_clauselistsz3MSSQLCompiler.visit_concat_op_expression_clauselistcKs$d|j|jf|Ž|j|jf|ŽfS)Nz%s + %s©rÂrqrŠ©r¦r ržr§rªrªr«Úvisit_concat_op_binarysþz$MSSQLCompiler.visit_concat_op_binarycKsdS)NÚ1rª©r¦Úexprr§rªrªr«Ú
visit_true!szMSSQLCompiler.visit_truecKsdS)NÚ0rªr¤rªrªr«Ú visit_false$szMSSQLCompiler.visit_falsecKs$d|j|jf|Ž|j|jf|ŽfS)NzCONTAINS (%s, %s)r r¡rªrªr«Úvisit_match_op_binary'sþz#MSSQLCompiler.visit_match_op_binaryc svtƒj|f|Ž}|jrr| |¡rrd|d<|d|j| |¡f|Ž7}|jdk    rr|jdr`|d7}|jdrr|d7}|S)    z+MS-SQL puts TOP, it's version of LIMIT hereTÚliteral_executezTOP %s Nr€zPERCENT Ú    with_tiesz
WITH TIES )r£Úget_select_precolumnsÚ_has_row_limiting_clauseÚ_use_toprÂÚ_get_limit_or_fetchÚ _fetch_clauseÚ_fetch_clause_options)r¦rŽr§Úsr¨rªr«r¬-sÿÿ
 
 
z#MSSQLCompiler.get_select_precolumnscCs|Sr¸rª©r¦r‘rrªrªr«Úget_from_hint_textBsz MSSQLCompiler.get_from_hint_textcCs|Sr¸rªr³rªrªr«Úget_crud_hint_textEsz MSSQLCompiler.get_crud_hint_textcCs|jdkr|jS|jSdSr¸)r°Ú _limit_clause©r¦rŽrªrªr«r¯Hs
z!MSSQLCompiler._get_limit_or_fetchcCs6|jdko4| |j¡p4| |j¡o4|jdp4|jdS)Nr€r«)Ú_offset_clauseZ_simple_int_clauser¶r°r±r·rªrªr«r®Ns 
 
øzMSSQLCompiler._use_topcKsdS©Nr rª)r¦ÚcsrÜrªrªr«Ú limit_clause\szMSSQLCompiler.limit_clausecCs>|jjst d¡‚|jdk    r:|jds0|jdr:t d¡‚dS)NzLMSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clauser€r«z^MSSQL needs TOP to use PERCENT and/or WITH TIES. Only simple fetch without offset can be used.)Ú_order_by_clauseÚclausesr Ú CompileErrorr±r·rªrªr«Ú_check_can_use_fetch_limit_sÿ
ÿþÿz(MSSQLCompiler._check_can_use_fetch_limitcKsB|jjr:| |¡s:| |¡|j|f| |¡ddœ|—ŽSdSdS)zdMSSQL 2012 supports OFFSET/FETCH operators
        Use it instead subquery with row_number
 
        T)Ú fetch_clauseZrequire_offsetr N)rÄÚ_supports_offset_fetchr®r¿rÀr¯©r¦rŽr§rªrªr«Ú_row_limit_clausers
ÿýüzMSSQLCompiler._row_limit_clausecKs$d|j|jf|Ž|j|jf|ŽfS)NzTRY_CAST (%s AS %s))rÂZclauseZ
typeclause)r¦Úelementr§rªrªr«Úvisit_try_cast…sþzMSSQLCompiler.visit_try_castc    Ksö|}|jrî|jjsî| |¡sît|ddƒsî| |¡dd„|jjDƒ}| |¡}|j    }| 
¡}d|_ |  t j ¡j|d d¡¡ d¡ ¡}t  d¡}t jdd„|jDƒŽ}|dk    rÜ| ||k¡}|dk    rê| |||k¡}n| ||k¡}|S|SdS)    zºLook for ``LIMIT`` and OFFSET in a select statement, and if
        so tries to wrap it in a subquery with ``row_number()`` criterion.
        MSSQL 2012 and above are excluded
 
        Ú _mssql_visitNcSsg|]}t |¡‘qSrª)Úsql_utilZunwrap_label_referencer™rªrªr«r̛sÿz<MSSQLCompiler.translate_select_structure.<locals>.<listcomp>T)Úorder_byÚmssql_rncSsg|]}|jdkr|‘qS)rÉ)ror*rªrªr«ṟs
)r­rÄrÁr®r,r¿r¼r½r¯r¸Z    _generaterÆZ add_columnsrrZ
ROW_NUMBERrÚlabelrÈÚaliasrIrŽr+rœ)    r¦Z select_stmtrÜrŽZ_order_by_clausesr»Z offset_clauserÉZ limitselectrªrªr«Útranslate_select_structure‹sPÿþý
ü
þ
 
ÿþÿûÿ
 
ÿ
ÿz(MSSQLCompiler.translate_select_structureFc sX||ks |rtƒj|f|ŽS| |¡}|dk    rD|j|fd|i|—ŽStƒj|f|ŽSdS©NÚ mssql_aliased)r£Ú visit_tableÚ_schema_aliased_tablerÂ)r¦r‘rÎÚiscrudrÜrËr¨rªr«rÏ¿s  
zMSSQLCompiler.visit_tablec s|j|d<tƒj|f|ŽSrÍ)rÄr£Ú visit_alias)r¦rËr§r¨rªr«rÒËs
zMSSQLCompiler.visit_aliasNc sŒ|jdk    r|js|jr| ¡rt| |j¡}|dk    rtt ||¡}|dk    rd||j|j||j|jf|j    ƒt
ƒj |f|ŽSt
ƒj |fd|i|—ŽS)NÚadd_to_result_map) r‘rprqÚ is_subqueryrÐrZ_corresponding_column_or_errorÚnamerorºr£Ú visit_column)r¦rIrÓr§ÚtZ    convertedr¨rªr«rÖÑs4ÿþþý   üÿÿÿzMSSQLCompiler.visit_columncCs:t|ddƒdk    r2||jkr(| ¡|j|<|j|SdSdS)Nr)r,r‹rË)r¦r‘rªrªr«rÐês
 
 
z#MSSQLCompiler._schema_aliased_tablecKs*|j |j|j¡}d||j|jf|ŽfS)NzDATEPART(%s, %s))Ú extract_mapÚgetÚfieldrÂr¥)r¦Úextractr§rÚrªrªr«Ú visit_extractòszMSSQLCompiler.visit_extractcKsd|j |¡S)NzSAVE TRANSACTION %s©r`Zformat_savepoint©r¦Zsavepoint_stmtr§rªrªr«Úvisit_savepointösÿzMSSQLCompiler.visit_savepointcKsd|j |¡S)NzROLLBACK TRANSACTION %srÝrÞrªrªr«Úvisit_rollback_to_savepointûsÿz)MSSQLCompiler.visit_rollback_to_savepointc sVt|jtjƒrF|jtjkrFt|jtjƒsF|jt |j|j|j¡f|ŽSt    ƒj
|f|ŽS)z]Move bind parameters to the right-hand side of an operator, where
        possible.
 
        ) rÍrqrZ BindParameterržÚeqrŠrÂZBinaryExpressionr£Ú visit_binary)r¦r rÜr¨rªr«râ    s  ÿ
þ ýÿÿüzMSSQLCompiler.visit_binaryc s|ˆjs ˆjrˆj d¡}n ˆjr.ˆj d¡}n ds:tdƒ‚t |¡‰‡‡‡‡‡fdd„ˆjdt     
|¡dDƒ}d    d
  |¡S) NZinsertedZdeletedFz+expected Insert, Update or Delete statementc    sDg|]<\}}}}}ˆjˆˆ |¡ˆd|fif||||dœˆ—Ž‘qS)Zresult_map_targets)Úfallback_label_nameZcolumn_is_repeatedrÕÚ
proxy_name)Z_label_returning_columnZtraverse)rÊrÕrärãrIZrepeated©Úadapterr§Úpopulate_result_mapr¦Ústmtrªr«rÌ,    s& ðüø    ÷z2MSSQLCompiler.returning_clause.<locals>.<listcomp>T)ÚcolszOUTPUT ú, ) Z    is_insertZ    is_updater‘rËZ    is_deletercrÇZ ClauseAdapterZ_generate_columns_plus_namesrZ_select_iterablesrn)r¦rèZreturning_colsrçr§ÚtargetÚcolumnsrªrår«Úreturning_clause    s      
 
ÿîzMSSQLCompiler.returning_clausecCsdS)NZWITHrª)r¦Ú    recursiverªrªr«Úget_cte_preambleE    szMSSQLCompiler.get_cte_preamblecs*t|tjƒr| d¡Stƒ |||¡SdSr¸)rÍrZFunctionrÊr£Úlabel_select_column)r¦rŽrIÚasfromr¨rªr«rðL    s 
z!MSSQLCompiler.label_select_columncKsdSr¹rªrÂrªrªr«Úfor_update_clauseR    szMSSQLCompiler.for_update_clausecKsH| ¡r$|js$|jdks |jjs$dS|j|jf|Ž}|r@d|SdSdS)Nr z
 ORDER BY )rÔZ_limitÚ_offsetrÄrÁrÂr¼)r¦rŽr§rÈrªrªr«Úorder_by_clauseW    sÿþüû zMSSQLCompiler.order_by_clausec s&dd ‡‡‡fdd„|g|Dƒ¡S)aRender the UPDATE..FROM clause specific to MSSQL.
 
        In MSSQL, if the UPDATE statement involves an alias of the table to
        be updated, then the table itself must be added to the FROM list as
        well. Otherwise, it is optional. Here, we add it regardless.
 
        úFROM rêc3s&|]}|jˆfdˆdœˆ—ŽVqdS©T)rñZ    fromhintsN©Z_compiler_dispatch©rÊrשÚ
from_hintsr§r¦rªr«rœw    sÿz3MSSQLCompiler.update_from_clause.<locals>.<genexpr>r)r¦Z update_stmtÚ
from_tableÚ extra_fromsrúr§rªrùr«Úupdate_from_clausem    s
þz MSSQLCompiler.update_from_clausecKs&d}|r d}|j|fdd|dœ|—ŽS)z=If we have extra froms make sure we render any alias as hint.FT)rñrÑÚashintr÷)r¦Ú delete_stmtrûrür§rþrªrªr«Údelete_table_clause|    sÿÿÿz!MSSQLCompiler.delete_table_clausec s&dd ‡‡‡fdd„|g|Dƒ¡S)zjRender the DELETE .. FROM clause specific to MSSQL.
 
        Yes, it has the FROM keyword twice.
 
        rõrêc3s&|]}|jˆfdˆdœˆ—ŽVqdSrör÷rørùrªr«rœ    sÿz9MSSQLCompiler.delete_extra_from_clause.<locals>.<genexpr>r)r¦rÿrûrürúr§rªrùr«Údelete_extra_from_clause…    sþz&MSSQLCompiler.delete_extra_from_clausecKsdS)NzSELECT 1 WHERE 1!=1rªr0rªrªr«Úvisit_empty_set_expr’    sz"MSSQLCompiler.visit_empty_set_exprcKsd| |j¡| |j¡fS)Nz*NOT EXISTS (SELECT %s INTERSECT SELECT %s)r r¡rªrªr«Úvisit_is_distinct_from_binary•    s
 
þz+MSSQLCompiler.visit_is_distinct_from_binarycKsd| |j¡| |j¡fS)Nz&EXISTS (SELECT %s INTERSECT SELECT %s)r r¡rªrªr«Ú!visit_is_not_distinct_from_binary›    s
 
þz/MSSQLCompiler.visit_is_not_distinct_from_binarycKs`|jjtjkr2d|j|jf|Ž|j|jf|ŽfSd|j|jf|Ž|j|jf|Žf}|jjtjkrŠd|j|jf|Ž|j|jf|Žf}nÆ|jjtjkrâd|j|jf|Ž|j|jf|Žt    |jtj
ƒrÈdnd|jj |jj ff}nn|jjtj kröd}nZ|jjtjkr,d|j|jf|Ž|j|jf|Žf}n$d    |j|jf|Ž|j|jf|Žf}|d
|d S) NzJSON_QUERY(%s, %s)z+CASE JSON_VALUE(%s, %s) WHEN NULL THEN NULLz(ELSE CAST(JSON_VALUE(%s, %s) AS INTEGER)z#ELSE CAST(JSON_VALUE(%s, %s) AS %s)r'zNUMERIC(%s, %s)z0WHEN 'true' THEN 1 WHEN 'false' THEN 0 ELSE NULLzELSE JSON_VALUE(%s, %s)zELSE JSON_QUERY(%s, %s)r)z END)rºZ_type_affinityrrrÂrqrŠÚIntegerÚNumericrÍÚFloatrÚscaleÚBooleanÚString)r¦r ržr§Zcase_expressionÚtype_expressionrªrªr«Ú _render_json_extract_from_binary¡    sJþþþ ÿÿûÿþþz.MSSQLCompiler._render_json_extract_from_binarycKs|j||f|ŽSr¸©r r¡rªrªr«Úvisit_json_getitem_op_binary×    sz*MSSQLCompiler.visit_json_getitem_op_binarycKs|j||f|ŽSr¸r r¡rªrªr«Ú!visit_json_path_getitem_op_binaryÚ    sz/MSSQLCompiler.visit_json_path_getitem_op_binarycKsd|j |¡S)NzNEXT VALUE FOR %s)r`r~)r¦rr§rªrªr«Úvisit_sequenceÝ    szMSSQLCompiler.visit_sequence)FF)N)6r­r®r¯Zreturning_precedes_valuesrZ 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Ürßràrârírïrðròrôrýrrrrrr rrrr±rªrªr¨r«r‡ïspüþ
 
 4  3      6r‡cs4eZdZdZdZdd„Zdd„Z‡fdd„Z‡ZS)    ÚMSSQLStrictCompilerzËA subclass of MSSQLCompiler which disables the usage of bind
    parameters where not allowed natively by MS-SQL.
 
    A dialect may use this compiler on a platform where native
    binds are used.
 
    TcKs,d|d<d|j|jf|Ž|j|jf|ŽfS)NTrªz%s IN %sr r¡rªrªr«Úvisit_in_op_binaryí    s
þz&MSSQLStrictCompiler.visit_in_op_binarycKs,d|d<d|j|jf|Ž|j|jf|ŽfS)NTrªz %s NOT IN %sr r¡rªrªr«Úvisit_not_in_op_binaryô    s
þz*MSSQLStrictCompiler.visit_not_in_op_binarycs2tt|ƒtjƒr dt|ƒdStƒ ||¡SdS)a5
        For date and datetime values, convert to a string
        format acceptable to MSSQL. That seems to be the
        so-called ODBC canonical date format which looks
        like this:
 
            yyyy-mm-dd hh:mi:ss.mmm(24h)
 
        For other data types, call the base class implementation.
        rëN)Ú
issubclassrºr»r¼rÎr£Úrender_literal_value)r¦rÁr.r¨rªr«rû    s z(MSSQLStrictCompiler.render_literal_value)    r­r®r¯r°Zansi_bind_rulesrrrr±rªrªr¨r«rá    s
rcsveZdZdd„Zddd„Zdd„Zdd    „Zd
d „Zd d „Zdd„Z    dd„Z
dd„Z dd„Z ‡fdd„Z dd„Z‡ZS)Ú MSDDLCompilercKs~|j |¡}|jdk    r,|d| |j¡7}n|d|jjj|j|d7}|jdk    r˜|jr||js|t    |j
t j ƒs||j dks||jr†|d7}n|jdkr˜|d7}|jdkr¬t d¡‚|jd}|d}|d    }|dk    sÖ|dk    rò|jræt d
¡‚t d d ¡|jr||j|jf|Ž7}nj||jjks*|j dkrZt    |j
t ƒrB|j
jrZ|| t||d ¡7}n | |¡}|dk    rz|d|7}|S)Nr))r Tz     NOT NULLz NULLz;mssql requires Table-bound columns in order to generate DDLrÚidentity_startÚidentity_incrementzzCannot specify options 'mssql_identity_start' and/or 'mssql_identity_increment' while also using the 'Identity' construct.z|The dialect options 'mssql_identity_start' and 'mssql_identity_increment' are deprecated. Use the 'Identity' object instead.ú1.4©ÚstartÚ    incrementz     DEFAULT )r`Ú format_columnÚcomputedrÂrÄZtype_compiler_instancerºÚnullableZ primary_keyrÍrrrÚ autoincrementrgr‘r r¾Údialect_optionsrÚwarn_deprecatedrfrƒr Zget_column_default_string)r¦rIrÜZcolspecZd_optrrrrªrªr«Úget_column_specification
sh 
 ÿ
 
ÿþ ýüû
 
 
ÿ
ÿü
ÿþ
üü
 
 z&MSDDLCompiler.get_column_specificationFc         s |j‰ˆ ˆ¡ˆj‰d}ˆjr(|d7}ˆjdd}|dk    rT|rL|d7}n|d7}|dˆjˆ|dˆ ˆj¡d     ‡fd
d „ˆj    Dƒ¡f7}ˆjdd r؇fd d„ˆjdd Dƒ}|dd     ‡fdd„|Dƒ¡7}ˆjdd}|dk    rt
  t j |¡}ˆjj|ddd}|d|7}|S)NzCREATE úUNIQUE rrGú
CLUSTERED ú NONCLUSTERED zINDEX %s ON %s (%s)©Úinclude_schemarêc3s |]}ˆjj|dddVqdS)FT©Z include_tableZ literal_bindsN)Ú sql_compilerrÂ)rÊr¥rÕrªr«rœa
s ýÿz3MSDDLCompiler.visit_create_index.<locals>.<genexpr>Úincludecs&g|]}t|tƒrˆjj|n|‘qSrª)rÍrÎr‘r+)rÊÚcol)rjrªr«rÌk
sÿz4MSDDLCompiler.visit_create_index.<locals>.<listcomp>z  INCLUDE (%s)csg|]}ˆ |j¡‘qSrª)ÚquoterÕr*)r`rªr«rÌq
srœFTr*z WHERE )rÄZ_verify_index_tabler`r–r"Ú_prepared_index_namermr‘rnZ expressionsrÚexpectrZDDLExpressionRoler+rÂ)    r¦rOr)r§rrGZ
inclusionsÚ whereclauseZwhere_compiledrª)rjr`r¦r«Úvisit_create_indexN
sL
 
 
üý 
 þÿ
ÿÿ z MSDDLCompiler.visit_create_indexcKs$d|j|jdd|j |jj¡fS)Nz
DROP INDEX %s ON %sFr()r/rÄr`rmr‘)r¦rUr§rªrªr«Úvisit_drop_index‚
sþzMSDDLCompiler.visit_drop_indexc s˜t|ƒdkrdSd}|jdk    r2|dˆj |¡7}|d7}|jdd}|dk    rf|r^|d7}n|d7}|d    d
 ‡fd d „|Dƒ¡7}|ˆ |¡7}|S) Nrr úCONSTRAINT %s z PRIMARY KEY rrGr&r'r(rêc3s|]}ˆj |j¡VqdSr¸©r`r.rÕr*rÕrªr«rœ™
sz=MSDDLCompiler.visit_primary_key_constraint.<locals>.<genexpr>©ÚlenrÕr`Zformat_constraintr"rnZdefine_constraint_deferrability)r¦rKr§rrGrªrÕr«Úvisit_primary_key_constraintˆ
s$ 
 
ÿ
ÿ z*MSDDLCompiler.visit_primary_key_constraintc s¤t|ƒdkrdSd}|jdk    r>ˆj |¡}|dk    r>|d|7}|d7}|jdd}|dk    rr|rj|d7}n|d7}|d    d
 ‡fd d „|Dƒ¡7}|ˆ |¡7}|S) Nrr r4r%rrGr&r'r(rêc3s|]}ˆj |j¡VqdSr¸r5r*rÕrªr«rœ°
sz8MSDDLCompiler.visit_unique_constraint.<locals>.<genexpr>r6)r¦rKr§rZformatted_namerGrªrÕr«Úvisit_unique_constraintŸ
s$ 
 
ÿ z%MSDDLCompiler.visit_unique_constraintcKs.d|jj|jddd}|jdkr*|d7}|S)NzAS (%s)FTr*z
 PERSISTED)r+rÂÚsqltextÚ    persisted)r¦Ú    generatedr§rrªrªr«Úvisit_computed_column¶
sÿ
z#MSDDLCompiler.visit_computed_columncKsT|j |j¡}|r|n|jj}d |j |jjt     
¡¡|j  |¡|jj |jdd¡S)NzNexecute sp_addextendedproperty 'MS_Description', {}, 'schema', {}, 'table', {}F©Z
use_schema) r`Úschema_for_objectrÄrÄÚdefault_schema_nameÚformatr+rÚcommentrr+Ú quote_schemarm©r¦rOr§rÚ schema_namerªrªr«Úvisit_set_table_comment¿
sÿ
úÿz%MSDDLCompiler.visit_set_table_commentcKs@|j |j¡}|r|n|jj}d |j |¡|jj|jdd¡S)NzKexecute sp_dropextendedproperty 'MS_Description', 'schema', {}, 'table', {}Fr>)r`r?rÄrÄr@rArCrm©r¦rUr§rrErªrªr«Úvisit_drop_table_commentÍ
s
ýÿz&MSDDLCompiler.visit_drop_table_commentcKsd|j |jj¡}|r|n|jj}d |j |jj    t
  ¡¡|j  |¡|jj |jjdd|j |j¡¡S)Nz\execute sp_addextendedproperty 'MS_Description', {}, 'schema', {}, 'table', {}, 'column', {}Fr>)r`r?rÄr‘rÄr@rAr+rrBrr+rCrmrrDrªrªr«Úvisit_set_column_commentØ
sÿ
ÿ ÷ÿz&MSDDLCompiler.visit_set_column_commentcKsP|j |jj¡}|r|n|jj}d |j |¡|jj|jjdd|j     |j¡¡S)NzYexecute sp_dropextendedproperty 'MS_Description', 'schema', {}, 'table', {}, 'column', {}Fr>)
r`r?rÄr‘rÄr@rArCrmrrGrªrªr«Úvisit_drop_column_commenté
s
ÿ úÿz'MSDDLCompiler.visit_drop_column_commentc s@d}|jjdk    r(|jj}d|j |¡}tƒj|fd|i|—ŽS)Nz AS %sÚprefix)rÄÚ    data_typeZ type_compilerrÂr£Úvisit_create_sequence)r¦rOr§rKrLr¨rªr«rM÷
s
 z#MSDDLCompiler.visit_create_sequencecKsTd}|jdk    s|jdk    rP|jdkr&dn|j}|jdkr:dn|j}|d||f7}|S)Nz     IDENTITYrz(%s,%s)r)r¦rgr§rrrrªrªr«Úvisit_identity_columnþ
s z#MSDDLCompiler.visit_identity_column)F)r­r®r¯r$r2r3r8r9r=rFrHrIrJrMrNr±rªrªr¨r«r
s?
4      rcs:eZdZeZ‡fdd„Zdd„Zdd„Zd
dd    „Z‡Z    S) ÚMSIdentifierPreparercstƒj|dddddS)Nú[ú]F)Z initial_quoteZ final_quoteZquote_case_sensitive_collations)r£r¤)r¦rÄr¨rªr«r¤
s üzMSIdentifierPreparer.__init__cCs | dd¡S)NrQú]]r ©r¦rÁrªrªr«Ú_escape_identifier sz'MSIdentifierPreparer._escape_identifiercCs | dd¡S)NrRrQr rSrªrªr«Ú_unescape_identifier sz)MSIdentifierPreparer._unescape_identifierNcCsX|dk    rtjdddt|ƒ\}}|r@d| |¡| |¡f}n|rP| |¡}nd}|S)z'Prepare a quoted table and schema name.NzÚThe IdentifierPreparer.quote_schema.force parameter is deprecated and will be removed in a future release.  This flag has no effect on the behavior of the IdentifierPreparer.quote method; please refer to quoted_name().z1.3)Úversionz%s.%sr )rr#Ú_schema_elementsr.)r¦rÚforceÚdbnameÚownerÚresultrªrªr«rC sú      z!MSIdentifierPreparer.quote_schema)N)
r­r®r¯ÚRESERVED_WORDSZreserved_wordsr¤rTrUrCr±rªrªr¨r«rO s
 rOcsd‡fdd„    }t|ˆƒS)Nc    s(t||ƒ\}}t||ˆ|||||f|ŽSr¸©Ú_owner_plus_dbÚ
_switch_db)rÄÚ
connectionrr§rYrZrrªr«Úwrap4 sø    ÷z$_db_plus_owner_listing.<locals>.wrap)Nr/©rŽrarªrr«Ú_db_plus_owner_listing3 srccsd‡fdd„    }t|ˆƒS)Nc
s*t||ƒ\}}t||ˆ||||||f    |ŽSr¸r])rÄr`Ú    tablenamerr§rYrZrrªr«raF s÷
öz_db_plus_owner.<locals>.wrap)Nr/rbrªrr«Ú_db_plus_ownerE srec Osl|r2| d¡ ¡}||kr2| d|jj |¡¡z|||ŽW¢S|rf||krf| d|jj |¡¡XdS)Nzselect db_name()zuse %s)Úexec_driver_sqlÚscalarrÄrïr.)rYr`rŽrr§Z
current_dbrªrªr«r_X sÿ  ÿÿr_cCs|sd|jfSt|ƒSdSr¸)r@rW)rÄrrªrªr«r^i s
r^cCsbt|tƒr|jrd|fS|tkr(t|S| d¡r:d|fSg}d}d}d}t d|¡D]f}|s`qV|dkrrd}d}qV|dkr€d}qV|s´|dkr´|r | d    |¡n
| |¡d}d}qV||7}qV|rÌ| |¡t|ƒd
kr,d     |d d …¡|d }}t 
d |d
d …¡rt|dd}n|  d¡  d¡}n"t|ƒrFd|d }}nd\}}||ft|<||fS)Nz
__[SCHEMA_r Fz
(\[|\]|\.)rPTrQÚ.z[%s]rréÿÿÿÿz
.*\].*\[.*©r.)NN) rÍrr.Ú_memoized_schemaÚ
startswithrÙÚsplitÚappendr7rnrÐÚlstripÚrstrip)rÚpushÚsymbolZbracketZ has_bracketsÚtokenrYrZrªrªr«rWs sJ    
 
 
 
 
 rWcsÄeZdZdZdZdZdZdZdZdZ    dZ
e Z dZ dZdZdZdZdZdZdZejeejeejeejjeejjeejeeje ej!e"e#e#e$e$e%e%e&e&ej'e(i Z)e*j+j, -de.j/i¡Z,e0Z0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9dZ:e;j<e;j=Be;j>BZ?dZ@dZAdZBdZCd    ZDeEZFeGZHeIZJeKZLeMjNd
d ifeMjOd
d ifeMjPd d d d œfeMjQd d d œfgZRdK‡fdd„    ZS‡fdd„ZTdd„ZU‡fdd„ZVdddddhZWdd„ZXdd„ZYdd „ZZ‡fd!d"„Z[d#d$„Z\d%d&„Z]d'd(„Z^d)d*„Z_e`d+d,„ƒZaebjce`d-d.„ƒƒZdebjceed/d0„ƒƒZfebjcd1d2„ƒZgebjceed3d4„ƒƒZhebjceed5d6„ƒƒZiebjcd7d8„ƒZjd9d:„Zkebjce`d;d<„ƒƒZlebjce`d=d>„ƒƒZmebjcdLd?d@„ƒZndAdB„ZodCdD„Zpebjce`dEdF„ƒƒZqebjce`dGdH„ƒƒZrebjce`dIdJ„ƒƒZs‡ZtS)Mr^rTFé€Údborri3rªrGN)rGr,rœ)rrc
 svt|pdƒ|_||_||_||_|    |_||_} | dk    r>| |_|dk    rXt     dd¡||_
t ƒj f|
Ž||_ ||_dS)Nrz[The legacy_schema_aliasing parameter is deprecated and will be removed in a future release.r)rÈÚ query_timeoutrErsrAÚ!ignore_no_transaction_on_rollbackÚ_user_defined_supports_commentsÚsupports_commentsrr#rr£r¤Z_json_serializerZ_json_deserializer) r¦rvrsrErAryZjson_serializerZjson_deserializerrrwÚoptsZudsr¨rªr«r¤ s$ ÿ
ýzMSDialect.__init__cs| d¡tƒ ||¡dS)Nz$IF @@TRANCOUNT = 0 BEGIN TRANSACTION)rfr£Ú do_savepoint©r¦r`rÕr¨rªr«r{? s
zMSDialect.do_savepointcCsdSr¸rªr|rªrªr«Údo_release_savepointD szMSDialect.do_release_savepointc
s`ztƒ |¡WnJ|jjk
rZ}z(|jrHt dt|ƒ¡rHt     d¡n‚W5d}~XYnXdS)Nz .*\b111214\bz|ProgrammingError 111214 'No corresponding transaction found.' has been suppressed via ignore_no_transaction_on_rollback=True)
r£Ú do_rollbackÚdbapiZProgrammingErrorrwrÙrÐrÎrÚwarn)r¦Údbapi_connectionr|r¨rªr«r~H s
ÿÿzMSDialect.do_rollbackZ SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READÚSNAPSHOTcCs
t|jƒSr¸)ÚlistÚ_isolation_lookup)r¦rrªrªr«Úget_isolation_level_values` sz$MSDialect.get_isolation_level_valuescCs4| ¡}| d|›¡| ¡|dkr0| ¡dS)Nz SET TRANSACTION ISOLATION LEVEL r‚)rr\rFrJ)r¦rÚlevelrrªrªr«Úset_isolation_levelc s
zMSDialect.set_isolation_levelc
Cs¸| ¡}d}zœzF| d |¡¡| ¡}|s4tdƒ‚d|d›}| d |¡¡Wn8|jjk
rŒ}ztd ||¡ƒ|‚W5d}~XYnX| ¡}|d ¡W¢SW5| ¡XdS)Nzsys.system_viewszTSELECT name FROM {} WHERE name IN ('dm_exec_sessions', 'dm_pdw_nodes_exec_sessions')zBCan't fetch isolation level on this particular SQL Server version.zsys.raã
                    SELECT CASE transaction_isolation_level
                    WHEN 0 THEN NULL
                    WHEN 1 THEN 'READ UNCOMMITTED'
                    WHEN 2 THEN 'READ COMMITTED'
                    WHEN 3 THEN 'REPEATABLE READ'
                    WHEN 4 THEN 'SERIALIZABLE'
                    WHEN 5 THEN 'SNAPSHOT' END
                    AS TRANSACTION_ISOLATION_LEVEL
                    FROM {}
                    where session_id = @@SPID
                zZCan't fetch isolation level;  encountered error {} when attempting to query the "{}" view.)    rrFr\rAZfetchoneÚNotImplementedErrorrÚErrorr)r¦rrZ    view_namerxÚerrrªrªr«Úget_isolation_levelj s@ÿýÿÿ ôÿÿÿýzMSDialect.get_isolation_levelcs,tƒ |¡| ¡| |¡| |¡dSr¸)r£Ú
initializeÚ_setup_version_attributesÚ_setup_supports_nvarchar_maxÚ_setup_supports_comments©r¦r`r¨rªr«rŒ˜ s 
zMSDialect.initializecCs€|jdttddƒƒkr8t dd dd„|jDƒ¡¡|jtkrJd|_nd    |_|jdkrf|jt    k|_|jox|jdd
k|_
dS) Nrr:éz[Unrecognized server version info '%s'.  Some SQL Server features may not function properly.rhcss|]}t|ƒVqdSr¸rrÉrªrªr«rœ£ sz6MSDialect._setup_version_attributes.<locals>.<genexpr>TFr7) rLrƒÚrangerr€rnrMÚsupports_multivalues_insertrAÚMS_2012_VERSIONrÁrÕrªrªr«rž sþÿ
 
ÿÿz#MSDialect._setup_version_attributescCs<z| t d¡¡Wntjk
r0d|_YnXd|_dS)Nz0SELECT CAST('test max support' AS NVARCHAR(max))FT)rgrrr Ú
DBAPIErrorÚ_supports_nvarchar_maxrrªrªr«rŽ´ sÿ z&MSDialect._setup_supports_nvarchar_maxcCsJ|jdk    rdSz| t d¡¡Wntjk
r>d|_YnXd|_dS)NzdSELECT 1 FROM fn_listextendedproperty(default, default, default, default, default, default, default)FT)rxrgrrr r•ryrrªrªr«r¾ s
ÿÿ z"MSDialect._setup_supports_commentscCs2t d¡}| |¡}|dk    r(t|ddS|jSdS)NzSELECT schema_name()Trj)rrrgrrE)r¦r`Úqueryr@rªrªr«Ú_get_default_schema_nameÏ s
 
 
 z"MSDialect._get_default_schema_namecKs| |¡|j|||f|ŽSr¸)Z_ensure_has_table_connectionÚ_internal_has_table)r¦r`rdrYrZrr§rªrªr«Ú    has_tableÙ s
zMSDialect.has_tablec
KsNtj}t |jj¡ |jj|k¡}|r8| |jj|k¡}| |¡}    |         ¡dk    Sr¸)
ÚischemaÚ    sequencesrrŽr+Ú sequence_namerœÚsequence_schemar\Úfirst)
r¦r`Z sequencenamerYrZrr§rœr²r+rªrªr«Ú has_sequenceß s
ÿ
zMSDialect.has_sequencec    KsBtj}t |jj¡}|r*| |jj|k¡}| |¡}dd„|DƒS)NcSsg|] }|d‘qSrÆrª)rÊrxrªrªr«rÌü sz0MSDialect.get_sequence_names.<locals>.<listcomp>)    r›rœrrŽr+rrœržr\)    r¦r`rYrZrr§rœr²r+rªrªr«Úget_sequence_namesñ s 
zMSDialect.get_sequence_namescKs4t tjjj¡ tjjj¡}dd„| |¡Dƒ}|S)NcSsg|] }|d‘qSrÆrª©rÊÚrrªrªr«rÌ sz.MSDialect.get_schema_names.<locals>.<listcomp>)rrŽr›Zschematar+rErÈr\)r¦r`r§r²Z schema_namesrªrªr«Úget_schema_namesþ s
ÿzMSDialect.get_schema_namesc    KsTtj}t |jj¡ t |jj|k|jj    dk¡¡ 
|jj¡}dd„|  |¡Dƒ}|S)Nú
BASE TABLEcSsg|] }|d‘qSrÆrªr¢rªrªr«rÌ sz-MSDialect.get_table_names.<locals>.<listcomp>© r›ÚtablesrrŽr+Ú
table_namerœÚand_Ú table_schemaÚ
table_typerÈr\)    r¦r`rYrZrr§r§r²Z table_namesrªrªr«Úget_table_names s
 
þþùÿ
zMSDialect.get_table_namesc    KsTtj}t |jj¡ t |jj|k|jj    dk¡¡ 
|jj¡}dd„|  |¡Dƒ}|S)NÚVIEWcSsg|] }|d‘qSrÆrªr¢rªrªr«rÌ% sz,MSDialect.get_view_names.<locals>.<listcomp>r¦)    r¦r`rYrZrr§r§r²Z
view_namesrªrªr«Úget_view_names s
 
þþùÿ
zMSDialect.get_view_namesc    Ksœ| d¡r*t| tdƒdd|›di¡ƒStj}t |jj    ¡ 
t  t  |jj dk|jj dk¡|jj    |k¡¡}|r‚| 
|jj|k¡}| |¡}| ¡dk    SdS)Nú#z"SELECT object_id(:table_name, 'U')r¨z tempdb.dbo.[rQr¥r­)rlrrgrr›r§rrŽr+r¨rœr©Úor_r«rªr\rŸ)r¦r`rdrZr§r§r²r+rªrªr«r™( s*
ýÿ
 
þ
ûÿ
 
zMSDialect._internal_has_tablecKs0|j|||f|Žr|ƒSt |›d|›¡‚dS)Nrh)r™r ÚNoSuchTableError)r¦r`rdrZÚmethodr§rªrªr«Ú_default_or_errorH szMSDialect._default_or_errorc Ks¾|jtkrdnd}|jdd t d|›d¡ t d|t     ¡¡t d|t     ¡¡¡j
t   ¡d    ¡}i}    |  ¡D]X}
|
d
|
d d kggd |
didœ|    |
d<|
ddk    rn|
d|    |
d di¡d<qn|jdd t d¡ t d|t     ¡¡t d|t     ¡¡¡j
t   ¡d    ¡}|  ¡D]T}
|
d|    kr|
drP|    |
dd |
d
¡n|    |
dd |
d
¡q|     ¡D]} | d|  di¡d<qv|    r¤t|     ¡ƒS|j|||tjf|ŽSdS)Nzind.filter_definitionzNULL as filter_definitionT©Z future_resultz†select ind.index_id, ind.is_unique, ind.name, case when ind.index_id = 1 then cast(1 as bit) else cast(0 as bit) end as is_clustered, zó from sys.indexes as ind join sys.tables as tab on ind.object_id=tab.object_id join sys.schemas as sch on sch.schema_id=tab.schema_id where tab.name = :tabname and sch.name=:schname and ind.is_primary_key=0 and ind.type != 0 order by ind.name ZtabnameÚschname)rÕrÕZ    is_uniquerÚmssql_clusteredÚ is_clustered)rÕr–Ú column_namesÚinclude_columnsr"Zindex_idÚfilter_definitionr"Z mssql_whereanselect ind_col.index_id, ind_col.object_id, col.name, ind_col.is_included_column from sys.columns as col join sys.tables as tab on tab.object_id=col.object_id join sys.index_columns as ind_col on (ind_col.column_id=col.column_id and ind_col.object_id=tab.object_id) join sys.schemas as sch on sch.schema_id=tab.schema_id where tab.name=:tabname and sch.name=:schnameZis_included_columnr¹r¸Z mssql_include)rLrMÚexecution_optionsr\rrÚ
bindparamsÚ    bindparamr›Ú CoerceUnicoderìrÚUnicodeÚmappingsr¢rnr™rƒr³rÚindexes) r¦r`rdrYrZrr§rºÚrprÁrxÚ
index_inforªrªr«Ú get_indexesO szÿý 
ÿðîÿ 
 
û þÿ ÿ òðÿ 
ÿÿ þ
ÿ ÿÿzMSDialect.get_indexesc KsX| t d¡ t d|t ¡¡t d|t ¡¡¡¡ ¡}|r@|St     |›d|›¡‚dS)NzØselect mod.definition from sys.sql_modules as mod join sys.views as views on mod.object_id = views.object_id join sys.schemas as sch on views.schema_id = sch.schema_id where views.name=:viewname and sch.name=:schnameÚviewnamerµrh)
r\rrr¼r½r›r¾rgr r±)r¦r`rÅrYrZrr§Zview_defrªrªr«Úget_view_definition¦ sÿøÿ zMSDialect.get_view_definitionc Ks~|jstdƒ‚|r|n|j}d}| t |¡ t d|t     ¡¡t d|t     ¡¡¡¡ 
¡}|rdd|iS|j ||dt j f|ŽSdS)Nz=Can't get table comments on current SQL Server version in usezÍ
            SELECT cast(com.value as nvarchar(max))
            FROM fn_listextendedproperty('MS_Description',
                'schema', :schema, 'table', :table, NULL, NULL
            ) as com;
        rr‘r)ryrˆr@r\rrr¼r½r›r¾rgr³rZ table_comment)r¦r`r¨rr§rEZ COMMENT_SQLrBrªrªr«Úget_table_comment¼ s,ÿ
þÿüûzMSDialect.get_table_commentcCs|| d¡sdndS)Nz##z
[_][_][_]%r )rl)r¦rdrªrªr«Ú_temp_table_name_like_patternÜ sÿz'MSDialect._temp_table_name_like_patternc
CsŽz"| t d¡d| |¡i¡ ¡WStjk
rV}zt d|¡|‚W5d}~XYn4tjk
rˆ}zt     d|¡|‚W5d}~XYnXdS)Nz_select table_schema, table_name from tempdb.information_schema.tables where table_name like :p1Úp1z„Found more than one temporary table named '%s' in tempdb at this time. Cannot reliably resolve that name to its internal table name.z6Unable to find a temporary table named '%s' in tempdb.)
r\rrrÈZoner ZMultipleResultsFoundZUnreflectableTableErrorZ NoResultFoundr±)r¦r`rdÚmeÚnerªrªr«Ú_get_internal_temp_table_nameä s.ÿ ú
þÿüÿÿýz'MSDialect._get_internal_temp_table_namec&Ks(| d¡}|r&| ||¡\}}tj}ntj}tj}    tj}
|rnt |j    j
|k|j    j |k¡} |j    j d|j    j
} n|j    j
|k} |j    j
} |j r’|    j    j } nt |    j    j tdƒ¡} t | ¡}t |j    j|j    j|j    j|j    j|j    j|j    j|j    j|j    j| |    j    j|
j    j|
j    j|
j    jtjj    j  !d¡¡ "|¡j#|    t |    j    j|k|    j    j$|j    j %d¡k¡dj#|
t |
j    j|k|
j    j$|j    j %d¡k¡dj#tjt tjj    ddktjj    j&|ktjj    j'|j    j(ktjj    j$d    k¡d )| ¡ *|j    j(¡}|j+d
d  ,|¡}g}| -¡D]}||j    j}||j    j}||j    jd k}||j    j}||j    j}||j    j}||j    j}||j    j}|| }||    j    j}||
j    j}||
j    j}||
j    j}|tjj    j } |j. /|d¡}!i}"|!t0t1t2t3t4t5t6t7t8j9f    kræ|d krÐd}||"d<|ræ||"d<|!dkr
t: ;d||f¡t8j<}!n6t=|!t8j>ƒr6||"d<t=|!t8j?ƒs6||"d<|!f|"Ž}!||!|||dk    | dœ}#|dk    rx|dk    rx||dœ|#d<|dk    rö|dks–|dkr i|#d<nVt@|!t8jAƒrÀtB|ƒ}$tB|ƒ}%n(t@|!t8jCƒràtB|ƒ}$tB|ƒ}%n|}$|}%|$|%dœ|#d<| D|#¡qâ|r|S|jE|||tFjf|ŽSdS)Nr¯rhi rBZDATABASE_DEFAULT)ZonclauseÚclassrZMS_DescriptionTr´ZYESrirür'z*Did not recognize type '%s' of column '%s'rr)rÕrºr rr!rB)r:r;rrgr)GrlrÌr›Zmssql_temp_table_columnsrìZcomputed_columnsZidentity_columnsrr©r+r¨rªr–Ú
definitionÚcastr+rÚ    object_idrŽÚ column_namerLZ is_nullableZcharacter_maximum_lengthZnumeric_precisionZ numeric_scaleZcolumn_defaultZcollation_nameÚ is_persistedÚ is_identityZ
seed_valueZincrement_valueZextended_propertiesrÁrÊÚ select_fromZ    outerjoinrÕrHZmajor_idZminor_idÚordinal_positionrœrÈr»r\rÀÚ ischema_namesrÙÚMSStringÚMSCharÚ
MSNVarcharÚMSNCharÚMSTextÚMSNTextÚMSBinaryÚ MSVarBinaryrÚ LargeBinaryrr€ZNULLTYPErrrrÍZ
BigIntegerrÈrrnr³r)&r¦r`rdrYrZrr§Z is_temp_tablerìZ computed_colsZ identity_colsr1Z    full_nameZcomputed_definitionrÐr²r+rérxrÕr.r ZcharlenZ numericprecZ numericscalerr'rÎrÒrÓrrrBr×rÜZcdictrrrªrªr«Ú get_columnsÿ s:
ÿ
 
þ 
ÿ
òð
 ÿþí
 ÿþå" ÿ ûÝ+Õ,Ôÿ0           ÷
 
ÿÿ
ú    þ
 
 
 
 
þ
ÿÿzMSDialect.get_columnsc Ks>g}tj}tj d¡}    t |    jj|jj|    jj    t
  t
  |    jj d|    jj    ¡d¡ d¡¡ t |jj    |    jj    k|jj |    jj k|    jj|k|    jj |k¡¡ |jj    |    jj¡}
|jdd |
¡} d} d} |  ¡D]J}d||jjjkrÂ| |d¡| dkrü||    jj    j} | dkrÂ|d} qÂ|r$|| d    | id
œS|j|||tjf|ŽSdS) NÚCrhZCnstIsClustKeyr·Tr´ZPRIMARYZ COLUMN_NAMEr¶)Úconstrained_columnsrÕr")r›Ú constraintsZkey_constraintsrËrrŽr+rÑZconstraint_typeÚconstraint_namerZobjectpropertyrÐrªrÊrœr©r¨rÈrÕr»r\rÀrÕrnr³rZ pk_constraint)r¦r`rdrYrZrr§ZpkeysZTCrár²r+rär·rxrªrªr«Úget_pk_constraint³sd ÿüûü 
 
üôíÿ 
ýüûzMSDialect.get_pk_constraintc Ksltdƒ t d|t ¡¡t d|t ¡¡¡jt ¡t ¡t ¡t ¡t ¡t ¡t ¡t ¡d}g}dd„}    t     
|    ¡}|  |¡  ¡D]¸}
|
\
} } } } }}}} }}|| }| |d<|dkrÆ||d    d
<|dkrÚ||d    d <|d s||d <|dk    sþ||kr|r|d |}||d<|d|d}}|  | ¡|  |¡q†|rRt| ¡ƒS|j|||tjf|ŽSdS)Na>WITH fk_info AS (
    SELECT
        ischema_ref_con.constraint_schema,
        ischema_ref_con.constraint_name,
        ischema_key_col.ordinal_position,
        ischema_key_col.table_schema,
        ischema_key_col.table_name,
        ischema_ref_con.unique_constraint_schema,
        ischema_ref_con.unique_constraint_name,
        ischema_ref_con.match_option,
        ischema_ref_con.update_rule,
        ischema_ref_con.delete_rule,
        ischema_key_col.column_name AS constrained_column
    FROM
        INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ischema_ref_con
        INNER JOIN
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col ON
            ischema_key_col.table_schema = ischema_ref_con.constraint_schema
            AND ischema_key_col.constraint_name =
            ischema_ref_con.constraint_name
    WHERE ischema_key_col.table_name = :tablename
        AND ischema_key_col.table_schema = :owner
),
constraint_info AS (
    SELECT
        ischema_key_col.constraint_schema,
        ischema_key_col.constraint_name,
        ischema_key_col.ordinal_position,
        ischema_key_col.table_schema,
        ischema_key_col.table_name,
        ischema_key_col.column_name
    FROM
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col
),
index_info AS (
    SELECT
        sys.schemas.name AS index_schema,
        sys.indexes.name AS index_name,
        sys.index_columns.key_ordinal AS ordinal_position,
        sys.schemas.name AS table_schema,
        sys.objects.name AS table_name,
        sys.columns.name AS column_name
    FROM
        sys.indexes
        INNER JOIN
        sys.objects ON
            sys.objects.object_id = sys.indexes.object_id
        INNER JOIN
        sys.schemas ON
            sys.schemas.schema_id = sys.objects.schema_id
        INNER JOIN
        sys.index_columns ON
            sys.index_columns.object_id = sys.objects.object_id
            AND sys.index_columns.index_id = sys.indexes.index_id
        INNER JOIN
        sys.columns ON
            sys.columns.object_id = sys.indexes.object_id
            AND sys.columns.column_id = sys.index_columns.column_id
)
    SELECT
        fk_info.constraint_schema,
        fk_info.constraint_name,
        fk_info.ordinal_position,
        fk_info.constrained_column,
        constraint_info.table_schema AS referred_table_schema,
        constraint_info.table_name AS referred_table_name,
        constraint_info.column_name AS referred_column,
        fk_info.match_option,
        fk_info.update_rule,
        fk_info.delete_rule
    FROM
        fk_info INNER JOIN constraint_info ON
            constraint_info.constraint_schema =
                fk_info.unique_constraint_schema
            AND constraint_info.constraint_name =
                fk_info.unique_constraint_name
            AND constraint_info.ordinal_position = fk_info.ordinal_position
    UNION
    SELECT
        fk_info.constraint_schema,
        fk_info.constraint_name,
        fk_info.ordinal_position,
        fk_info.constrained_column,
        index_info.table_schema AS referred_table_schema,
        index_info.table_name AS referred_table_name,
        index_info.column_name AS referred_column,
        fk_info.match_option,
        fk_info.update_rule,
        fk_info.delete_rule
    FROM
        fk_info INNER JOIN index_info ON
            index_info.index_schema = fk_info.unique_constraint_schema
            AND index_info.index_name = fk_info.unique_constraint_name
            AND index_info.ordinal_position = fk_info.ordinal_position
 
    ORDER BY fk_info.constraint_schema, fk_info.constraint_name,
        fk_info.ordinal_position
rdrZ)Zconstraint_schemarärªr¨Zconstrained_columnZreferred_table_schemaZreferred_table_nameZreferred_columncSsdgddgidœS)N)rÕrâÚreferred_schemaÚreferred_tableÚreferred_columnsÚoptionsrªrªrªrªr«Úfkey_recksúz,MSDialect.get_foreign_keys.<locals>.fkey_recrÕz    NO ACTIONréZonupdateZondeleterçrhrærârè)rr¼rr½r›r¾rìrr¿rÚ defaultdictr\r<rnrƒr™r³rZ foreign_keys)r¦r`rdrYrZrr§r²Zfkeysrêr£Ú_ZrfknmZscolZrschemaZrtblZrcolZfkupruleZ    fkdelruleZrecZ
local_colsZ remote_colsrªrªr«Úget_foreign_keysìsvÿf™jÿw
 
ò  
 þ
  üûzMSDialect.get_foreign_keys)    NTruNNNNNF)N)ur­r®r¯rÕZsupports_statement_cacheZsupports_default_valuesZsupports_empty_insertZfavor_returning_over_lastrowidZreturns_native_bytesryZsupports_default_metavaluer]Zexecution_ctx_clsrsZmax_identifier_lengthrEZinsert_returningZupdate_returningZdelete_returningZupdate_returning_multifromZdelete_returning_multifromrÚDateTimerâÚDater·rr    r
ZTimeràr¿ròÚ UnicodeTextrórérårär%ÚUuidr    ZcolspecsrÚDefaultDialectZengine_config_typesr•rZasboolrÖZsupports_sequencesZsequences_optionalZdefault_sequence_baseZsupports_native_booleanZ#non_native_boolean_check_constraintZsupports_unicode_bindsZpostfetch_lastrowidr“Zuse_insertmanyvaluesZ!use_insertmanyvalues_wo_returningr Z AUTOINCREMENTZIDENTITYZUSE_INSERT_FROM_SELECTZ"insertmanyvalues_implicit_sentinelZinsertmanyvalues_max_parametersrÁr–rrLr‡Zstatement_compilerrZ ddl_compilerr&Ztype_compiler_clsrOr`rZPrimaryKeyConstraintZUniqueConstraintZIndexr‚Zconstruct_argumentsr¤r{r}r~r„r…r‡r‹rŒrrŽrr˜reršrÚcacher rcr¡r¤r¬r®r™r³rÄrÆrÇrÈrÌràrårír±rªrªr¨r«r^­ s$
óÿÿþÿ      þü ö&  û. 
 
 
 
 
 U   3 7r^)£r°Ú
__future__rrør»ržrÙÚtypingrrÚuuidrZ _python_UUIDr rr›Újsonrr    r
r r rrrrrrZenginerrurrZengine.reflectionrrrrrrrrrrÇZ sql._typingrZ sql.compilerr Útypesr!r"r#r$r%r&r'r(r)r*r+r,r-r.r0Z util.typingr1Zsql.dmlr2Zsql.selectabler3ZMS_2017_VERSIONZMS_2016_VERSIONZMS_2014_VERSIONr”rMZMS_2005_VERSIONZMS_2000_VERSIONr\rŸr²rr´rïr·rÛZ_MSTimeràrárîrârärårérêr¿ròrðróZ_BinaryrôrýrÿrrßrÚTextrr    rZ
TypeEnginerrrñr    Z _UUID_RETURNrrrZCastrZ
MSDateTimeZMSDateZMSRealZ MSTinyIntegerZMSTimeZMSSmallDateTimeZ MSDateTime2ZMSDateTimeOffsetrÛrÜr×rÙrØrÚrÝrÞZMSImageZMSBitZMSMoneyZ MSSmallMoneyZMSUniqueIdentifierZ    MSVariantrÖZGenericTypeCompilerr&ZDefaultExecutionContextr]rr‡rZ DDLCompilerrZIdentifierPreparerrOrcrer_r^ZLRUCacherkrWròr^rªrªrªr«Ú<module>    sÀ
                                               €Ì9 
* 0(  W 
á#&'u-z,     :