zmc
2023-12-22 9fdbf60165db0400c2e8e6be2dc6e88138ac719a
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
U
¸ý°då·ã@sÌdZddlmZddlZddlZddlmZddlmZddlmZddlmZddlm    Z    dd    lm
Z dd
lm Z d d l mZd d lmZd dlmZd dlmZd dlmZddl mZddl mZddlmZddlmZddlmZejrœd dlmZd dlmZd dlmZd dl m!Z!d dl m"Z"d dl m#Z#d d    l m
Z
d dl m$Z$d dl%m&Z&ddl'm(Z(dd l)m*Z*dd!l)m+Z+dd"l)m,Z,dd#l)m-Z-Gd$d%„d%eƒZ.Gd&d'„d'eƒZ/Gd(d)„d)ej0ƒZ1Gd*d+„d+ej2ee.ƒZ3e3Z4Gd,d-„d-e3ƒZ5Gd.d/„d/e3ƒZ6Gd0d1„d1e6ƒZ7Gd2d3„d3e6ƒZ8Gd4d5„d5e7ƒZ9Gd6d7„d7e8ƒZ:Gd8d9„d9e7ƒZ;Gd:d;„d;e8ƒZ<Gd<d=„d=e.ƒZ=Gd>d?„d?e.ƒZ>Gd@dA„dAe8ƒZ?GdBdC„dCe7ƒZ@GdDdE„dEe8ƒZAGdFdG„dGe7ƒZBGdHdI„dIe8ƒZCGdJdK„dKe7ƒZDGdLdM„dMe8ƒZEGdNdO„dOe6ƒZFGdPdQ„dQe6ƒZGGdRdS„dSe6ƒZHGdTdU„dUe6ƒZIGdVdW„dWe6ƒZJGdXdY„dYe6ƒZKGdZd[„d[eƒZLGd\d]„d]eLƒZMGd^d_„d_eLƒZNGd`da„daeMƒZOGdbdc„dceNƒZPdndddedfdgdhœdidj„ZQdodldm„ZRdS)pzq
Provides the hierarchy of DDL-defining schema items as well as routines
to invoke them for a create/drop call.
 
é)Ú annotationsN)ÚAny)ÚCallable)ÚIterable)ÚList)ÚOptional)ÚSequence)ÚTupleé)Úroles)Ú _generative)Ú
Executable)Ú SchemaVisitor)Ú ClauseElementé)Úexc)Úutil)Ú topological)ÚProtocol)ÚSelf)ÚCompiled)Ú DDLCompiler)Ú BindParameter)Ú
Constraint)ÚForeignKeyConstraint)Ú
SchemaItem)ÚTable)Ú TableClause)Ú
Connection)Ú
CacheStats)ÚCompiledCacheType)ÚDialect)ÚSchemaTranslateMapTypec    @s>eZdZdZdZdd„Zdddœddd    d
d d d dœdd„ZdS)ÚBaseDDLElementz•The root of DDL constructs, including those that are sub-elements
    within the "create table" and other processes.
 
    .. versionadded:: 2.0
 
    FcKs|j||f|ŽS)zNReturn a compiler appropriate for this ClauseElement, given a
        Dialect.)Z ddl_compiler)ÚselfÚdialectÚkw©r'úId:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\sqlalchemy/sql/ddl.pyÚ    _compilerAszBaseDDLElement._compilerN)Úfor_executemanyÚschema_translate_mapr!zOptional[CompiledCacheType]z    List[str]Úboolz Optional[SchemaTranslateMapType]rzJTuple[Compiled, Optional[typing_Sequence[BindParameter[Any]]], CacheStats])r%Úcompiled_cacheÚ column_keysr*r+r&ÚreturncKs
tƒ‚dS©N©ÚNotImplementedError)r$r%r-r.r*r+r&r'r'r(Ú_compile_w_cacheGs zBaseDDLElement._compile_w_cache)Ú__name__Ú
__module__Ú __qualname__Ú__doc__Z_hierarchy_supports_cachingr)r3r'r'r'r(r#6s  ùr#c @s2eZdZdddœdddddd    d
d d d œ    d d„ZdS)Ú DDLIfCallableN.)Úcompilerr#rúOptional[Connection]zOptional[List[Table]]ú Optional[Any]r!úOptional[DDLCompiler]r,)    ÚddlÚtargetÚbindÚtablesÚstater%r9Ú
checkfirstr/c    CsdSr0r')    r$r=r>r?r@rAr%r9rBr'r'r(Ú__call__Ws zDDLIfCallable.__call__)NN)r4r5r6rCr'r'r'r(r8Vs
ú    ÷r8c@s@eZdZUded<ded<ded<ddd    d
d d d dœdd„ZdS)ÚDDLIfú Optional[str]r%úOptional[DDLIfCallable]Ú    callable_r;rANr#rr:r<rr,)r=r>r?r9r&r/cKsž|dk    r|j}n|dk    r |j}n ds,tdƒ‚t|jtƒrJ|j|jkrldSn"t|jtttfƒrl|j|jkrldS|jdk    rš|j|||f|j    ||dœ|—ŽsšdSdS)NFzcompiler or dialect is required)rAr%r9T)
r%ÚAssertionErrorÚ
isinstanceÚstrÚnameÚtupleÚlistÚsetrGrA)r$r=r>r?r9r&r%r'r'r(Ú_should_executeks0    ýúù    zDDLIf._should_execute)N)r4r5r6Ú__annotations__rOr'r'r'r(rDfs
 
ûrDc@s€eZdZUdZdZded<dZded<dd„Zed    d
d œd d „ƒZ    eddddd
dœdd„ƒZ
dd„Z dd„Z dd„Z dd„ZdS)ÚExecutableDDLElementa”Base class for standalone executable DDL expression constructs.
 
    This class is the base for the general purpose :class:`.DDL` class,
    as well as the various create/drop clause constructs such as
    :class:`.CreateTable`, :class:`.DropTable`, :class:`.AddConstraint`,
    etc.
 
    .. versionchanged:: 2.0  :class:`.ExecutableDDLElement` is renamed from
       :class:`.DDLElement`, which still exists for backwards compatibility.
 
    :class:`.ExecutableDDLElement` integrates closely with SQLAlchemy events,
    introduced in :ref:`event_toplevel`.  An instance of one is
    itself an event receiving callable::
 
        event.listen(
            users,
            'after_create',
            AddConstraint(constraint).execute_if(dialect='postgresql')
        )
 
    .. seealso::
 
        :class:`.DDL`
 
        :class:`.DDLEvents`
 
        :ref:`event_toplevel`
 
        :ref:`schema_ddl_sequences`
 
    NzOptional[DDLIf]Ú_ddl_ifzOptional[SchemaItem]r>cCs| |||¡Sr0)Z _execute_ddl)r$Ú
connectionZdistilled_paramsZexecution_optionsr'r'r(Ú_execute_on_connection²s
ÿz+ExecutableDDLElement._execute_on_connectionrr)r>r/cCs
||_|S)aÏReturn a copy of this :class:`_schema.ExecutableDDLElement` which
        will include the given target.
 
        This essentially applies the given item to the ``.target`` attribute of
        the returned :class:`_schema.ExecutableDDLElement` object. This target
        is then usable by event handlers and compilation routines in order to
        provide services such as tokenization of a DDL string in terms of a
        particular :class:`_schema.Table`.
 
        When a :class:`_schema.ExecutableDDLElement` object is established as
        an event handler for the :meth:`_events.DDLEvents.before_create` or
        :meth:`_events.DDLEvents.after_create` events, and the event then
        occurs for a given target such as a :class:`_schema.Constraint` or
        :class:`_schema.Table`, that target is established with a copy of the
        :class:`_schema.ExecutableDDLElement` object using this method, which
        then proceeds to the :meth:`_schema.ExecutableDDLElement.execute`
        method in order to invoke the actual DDL instruction.
 
        :param target: a :class:`_schema.SchemaItem` that will be the subject
         of a DDL operation.
 
        :return: a copy of this :class:`_schema.ExecutableDDLElement` with the
         ``.target`` attribute assigned to the given
         :class:`_schema.SchemaItem`.
 
        .. seealso::
 
            :class:`_schema.DDL` - uses tokenization against the "target" when
            processing the DDL string.
 
        )r>)r$r>r'r'r(Úagainst¹s!zExecutableDDLElement.againstrErFr;)r%rGrAr/cCst|||ƒ|_|S)a`
Return a callable that will execute this
        :class:`_ddl.ExecutableDDLElement` conditionally within an event
        handler.
 
        Used to provide a wrapper for event listening::
 
            event.listen(
                        metadata,
                        'before_create',
                        DDL("my_ddl").execute_if(dialect='postgresql')
                    )
 
        :param dialect: May be a string or tuple of strings.
          If a string, it will be compared to the name of the
          executing database dialect::
 
            DDL('something').execute_if(dialect='postgresql')
 
          If a tuple, specifies multiple dialect names::
 
            DDL('something').execute_if(dialect=('postgresql', 'mysql'))
 
        :param callable\_: A callable, which will be invoked with
          three positional arguments as well as optional keyword
          arguments:
 
            :ddl:
              This DDL element.
 
            :target:
              The :class:`_schema.Table` or :class:`_schema.MetaData`
              object which is the
              target of this event. May be None if the DDL is executed
              explicitly.
 
            :bind:
              The :class:`_engine.Connection` being used for DDL execution.
              May be None if this construct is being created inline within
              a table, in which case ``compiler`` will be present.
 
            :tables:
              Optional keyword argument - a list of Table objects which are to
              be created/ dropped within a MetaData.create_all() or drop_all()
              method call.
 
            :dialect: keyword argument, but always present - the
              :class:`.Dialect` involved in the operation.
 
            :compiler: keyword argument.  Will be ``None`` for an engine
              level DDL invocation, but will refer to a :class:`.DDLCompiler`
              if this DDL element is being created inline within a table.
 
            :state:
              Optional keyword argument - will be the ``state`` argument
              passed to this function.
 
            :checkfirst:
             Keyword argument, will be True if the 'checkfirst' flag was
             set during the call to ``create()``, ``create_all()``,
             ``drop()``, ``drop_all()``.
 
          If the callable returns a True value, the DDL statement will be
          executed.
 
        :param state: any value which will be passed to the callable\_
          as the ``state`` keyword argument.
 
        .. seealso::
 
            :meth:`.SchemaItem.ddl_if`
 
            :class:`.DDLEvents`
 
            :ref:`event_toplevel`
 
        )rDrR)r$r%rGrAr'r'r(Ú
execute_ifÝsSzExecutableDDLElement.execute_ifcKs&|jdkrdS|jj|||f|ŽSdS©NT)rRrO©r$r>r?r&r'r'r(rO3s
z$ExecutableDDLElement._should_executecCs| |j|¡r| |¡SdSr0)rOr>Úexecute)r$r?r'r'r(Ú _invoke_with9sz!ExecutableDDLElement._invoke_withcKs| |¡ |¡dS)z"Execute the DDL as a ddl_listener.N)rUrZrXr'r'r(rC=szExecutableDDLElement.__call__cCs|j |j¡}|j ¡|_|Sr0)Ú    __class__Ú__new__Ú__dict__Úcopy)r$Úsr'r'r(Ú    _generateBs zExecutableDDLElement._generate)NNN)r4r5r6r7rRrPr>rTr rUrVrOrZrCr`r'r'r'r(rQŽs
   #üUrQc@s&eZdZdZdZddd„Zdd„ZdS)    ÚDDLaAA literal DDL statement.
 
    Specifies literal SQL DDL to be executed by the database.  DDL objects
    function as DDL event listeners, and can be subscribed to those events
    listed in :class:`.DDLEvents`, using either :class:`_schema.Table` or
    :class:`_schema.MetaData` objects as targets.
    Basic templating support allows
    a single DDL instance to handle repetitive tasks for multiple tables.
 
    Examples::
 
      from sqlalchemy import event, DDL
 
      tbl = Table('users', metadata, Column('uid', Integer))
      event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger'))
 
      spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE')
      event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb'))
 
      drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
      connection.execute(drop_spow)
 
    When operating on Table events, the following ``statement``
    string substitutions are available::
 
      %(table)s  - the Table name, with any required quoting applied
      %(schema)s - the schema name, with any required quoting applied
      %(fullname)s - the Table name including schema, quoted if needed
 
    The DDL's "context", if any, will be combined with the standard
    substitutions noted above.  Keys present in the context will override
    the standard substitutions.
 
    r=NcCs,t|tƒst d|¡‚||_|p$i|_dS)aõCreate a DDL statement.
 
        :param statement:
          A string or unicode string to be executed.  Statements will be
          processed with Python's string formatting operator using
          a fixed set of string substitutions, as well as additional
          substitutions provided by the optional :paramref:`.DDL.context`
          parameter.
 
          A literal '%' in a statement must be escaped as '%%'.
 
          SQL bind parameters are not available in DDL statements.
 
        :param context:
          Optional dictionary, defaults to None.  These values will be
          available for use in string substitutions on the DDL statement.
 
        .. seealso::
 
            :class:`.DDLEvents`
 
            :ref:`event_toplevel`
 
        z4Expected a string or unicode SQL statement, got '%r'N)rIrJrÚ ArgumentErrorÚ    statementÚcontext)r$rcrdr'r'r(Ú__init__rs
ÿÿz DDL.__init__c    s8dtˆƒjtˆƒd tˆjƒg‡fdd„dDƒ¡fS)Nz <%s@%s; %s>ú, cs(g|] }tˆ|ƒrd|tˆ|ƒf‘qS)z%s=%r)Úgetattr)Ú.0Úkey©r$r'r(Ú
<listcomp>›s
þz DDL.__repr__.<locals>.<listcomp>)Úonrd)Útyper4ÚidÚjoinÚreprrcrjr'rjr(Ú__repr__•s
 
þÿÿýz DDL.__repr__)N)r4r5r6r7Ú__visit_name__rerqr'r'r'r(raLs#
#rac@s,eZdZdZdd„Zedd„ƒZdd„ZdS)    Ú_CreateDropBasezßBase class for DDL constructs that represent CREATE and DROP or
    equivalents.
 
    The common theme of _CreateDropBase is a single
    ``element`` attribute which refers to the element
    to be created or dropped.
 
    cCs||_|_t|ddƒ|_dS)NrR)Úelementr>rgrR©r$rtr'r'r(re®s z_CreateDropBase.__init__cCs|jjSr0)rtZcreate_drop_stringify_dialectrjr'r'r(Ústringify_dialectµsz!_CreateDropBase.stringify_dialectcCsdS)zÀAllow disable of _create_rule using a callable.
 
        Pass to _create_rule using
        util.portable_instancemethod(self._create_rule_disable)
        to retain serializability.
 
        Fr')r$r9r'r'r(Ú_create_rule_disable¹sz$_CreateDropBase._create_rule_disableN)r4r5r6r7reÚpropertyrvrwr'r'r'r(rs¤s
    
rscseZdZd‡fdd„    Z‡ZS)Ú _CreateBaseFcstƒ |¡||_dSr0)ÚsuperreÚ if_not_exists©r$rtr{©r[r'r(reÅs z_CreateBase.__init__)F©r4r5r6reÚ __classcell__r'r'r}r(ryÄsrycseZdZd‡fdd„    Z‡ZS)Ú    _DropBaseFcstƒ |¡||_dSr0)rzreÚ    if_exists©r$rtrr}r'r(reËs z_DropBase.__init__)Fr~r'r'r}r(r€Êsr€cs*eZdZdZdZdZd‡fdd„    Z‡ZS)Ú CreateSchemazcRepresent a CREATE SCHEMA statement.
 
    The argument here is the string name of the schema.
 
    Z create_schemaÚdefaultFcstƒj||ddS)z.Create a new :class:`.CreateSchema` construct.©rtr{N©rzre)r$rKr{r}r'r(reÛszCreateSchema.__init__)F©r4r5r6r7rrrvrerr'r'r}r(rƒÐs
ýrƒcs*eZdZdZdZdZd‡fdd„    Z‡ZS)Ú
DropSchemazaRepresent a DROP SCHEMA statement.
 
    The argument here is the string name of the schema.
 
    Z drop_schemar„Fcstƒj||d||_dS)z,Create a new :class:`.DropSchema` construct.©rtrN)rzreÚcascade)r$rKrŠrr}r'r(reðszDropSchema.__init__)FFr‡r'r'r}r(rˆås ürˆcs0eZdZdZdZd ddddœ‡fd    d
„ Z‡ZS) Ú CreateTablez#Represent a CREATE TABLE statement.Z create_tableNFrz/Optional[typing_Sequence[ForeignKeyConstraint]]r,)rtÚinclude_foreign_key_constraintsr{cs,tƒj||ddd„|jDƒ|_||_dS)aƒCreate a :class:`.CreateTable` construct.
 
        :param element: a :class:`_schema.Table` that's the subject
         of the CREATE
        :param on: See the description for 'on' in :class:`.DDL`.
        :param include_foreign_key_constraints: optional sequence of
         :class:`_schema.ForeignKeyConstraint` objects that will be included
         inline within the CREATE construct; if omitted, all foreign key
         constraints that do not specify use_alter=True are included.
 
        :param if_not_exists: if True, an IF NOT EXISTS operator will be
         applied to the construct.
 
         .. versionadded:: 1.4.0b2
 
        ©r{cSsg|] }t|ƒ‘qSr')Ú CreateColumn)rhÚcolumnr'r'r(rksz(CreateTable.__init__.<locals>.<listcomp>N)rzreÚcolumnsrŒ)r$rtrŒr{r}r'r(reszCreateTable.__init__)NF©r4r5r6r7rrrerr'r'r}r(r‹üs
úr‹c@seZdZdZdZdS)Ú    _DropViewz©Semi-public 'DROP VIEW' construct.
 
    Used by the test suite for dialect-agnostic drops of views.
    This object will eventually be part of a public "view" API.
 
    Z    drop_viewN©r4r5r6r7rrr'r'r'r(r’sr’c@seZdZddœdd„ZdS)ÚCreateConstraintr©rtcCs
||_dSr0r•rur'r'r(re*szCreateConstraint.__init__N)r4r5r6rer'r'r'r(r”)sr”c@seZdZdZdZdd„ZdS)rŽa–Represent a :class:`_schema.Column`
    as rendered in a CREATE TABLE statement,
    via the :class:`.CreateTable` construct.
 
    This is provided to support custom column DDL within the generation
    of CREATE TABLE statements, by using the
    compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel`
    to extend :class:`.CreateColumn`.
 
    Typical integration is to examine the incoming :class:`_schema.Column`
    object, and to redirect compilation if a particular flag or condition
    is found::
 
        from sqlalchemy import schema
        from sqlalchemy.ext.compiler import compiles
 
        @compiles(schema.CreateColumn)
        def compile(element, compiler, **kw):
            column = element.element
 
            if "special" not in column.info:
                return compiler.visit_create_column(element, **kw)
 
            text = "%s SPECIAL DIRECTIVE %s" % (
                    column.name,
                    compiler.type_compiler.process(column.type)
                )
            default = compiler.get_column_default_string(column)
            if default is not None:
                text += " DEFAULT " + default
 
            if not column.nullable:
                text += " NOT NULL"
 
            if column.constraints:
                text += " ".join(
                            compiler.process(const)
                            for const in column.constraints)
            return text
 
    The above construct can be applied to a :class:`_schema.Table`
    as follows::
 
        from sqlalchemy import Table, Metadata, Column, Integer, String
        from sqlalchemy import schema
 
        metadata = MetaData()
 
        table = Table('mytable', MetaData(),
                Column('x', Integer, info={"special":True}, primary_key=True),
                Column('y', String(50)),
                Column('z', String(20), info={"special":True})
            )
 
        metadata.create_all(conn)
 
    Above, the directives we've added to the :attr:`_schema.Column.info`
    collection
    will be detected by our custom compilation scheme::
 
        CREATE TABLE mytable (
                x SPECIAL DIRECTIVE INTEGER NOT NULL,
                y VARCHAR(50),
                z SPECIAL DIRECTIVE VARCHAR(20),
            PRIMARY KEY (x)
        )
 
    The :class:`.CreateColumn` construct can also be used to skip certain
    columns when producing a ``CREATE TABLE``.  This is accomplished by
    creating a compilation rule that conditionally returns ``None``.
    This is essentially how to produce the same effect as using the
    ``system=True`` argument on :class:`_schema.Column`, which marks a column
    as an implicitly-present "system" column.
 
    For example, suppose we wish to produce a :class:`_schema.Table`
    which skips
    rendering of the PostgreSQL ``xmin`` column against the PostgreSQL
    backend, but on other backends does render it, in anticipation of a
    triggered rule.  A conditional compilation rule could skip this name only
    on PostgreSQL::
 
        from sqlalchemy.schema import CreateColumn
 
        @compiles(CreateColumn, "postgresql")
        def skip_xmin(element, compiler, **kw):
            if element.element.name == 'xmin':
                return None
            else:
                return compiler.visit_create_column(element, **kw)
 
 
        my_table = Table('mytable', metadata,
                    Column('id', Integer, primary_key=True),
                    Column('xmin', Integer)
                )
 
    Above, a :class:`.CreateTable` construct will generate a ``CREATE TABLE``
    which only includes the ``id`` column in the string; the ``xmin`` column
    will be omitted, but only against the PostgreSQL backend.
 
    Z create_columncCs
||_dSr0r•rur'r'r(re—szCreateColumn.__init__N)r4r5r6r7rrrer'r'r'r(rŽ.sfrŽcs.eZdZdZdZd    dddœ‡fdd„ Z‡ZS)
Ú    DropTablez!Represent a DROP TABLE statement.Z
drop_tableFrr,r‰cstƒj||ddS)aVCreate a :class:`.DropTable` construct.
 
        :param element: a :class:`_schema.Table` that's the subject
         of the DROP.
        :param on: See the description for 'on' in :class:`.DDL`.
        :param if_exists: if True, an IF EXISTS operator will be applied to the
         construct.
 
         .. versionadded:: 1.4.0b2
 
        ©rNr†r‚r}r'r(re s zDropTable.__init__)Fr‘r'r'r}r(r–›sr–cs.eZdZdZdZd    dddœ‡fdd„ Z‡ZS)
ÚCreateSequencez&Represent a CREATE SEQUENCE statement.Zcreate_sequenceFrr,r…cstƒj||ddS)Nrr†r|r}r'r(re´szCreateSequence.__init__)Fr‘r'r'r}r(r˜¯sr˜cs.eZdZdZdZd    dddœ‡fdd„ Z‡ZS)
Ú DropSequencez$Represent a DROP SEQUENCE statement.Z drop_sequenceFrr,r‰cstƒj||ddS)Nr—r†r‚r}r'r(re½szDropSequence.__init__)Fr‘r'r'r}r(r™¸sr™cs&eZdZdZdZd‡fdd„    Z‡ZS)Ú CreateIndexz#Represent a CREATE INDEX statement.Z create_indexFcstƒj||ddS)a Create a :class:`.Createindex` construct.
 
        :param element: a :class:`_schema.Index` that's the subject
         of the CREATE.
        :param if_not_exists: if True, an IF NOT EXISTS operator will be
         applied to the construct.
 
         .. versionadded:: 1.4.0b2
 
        rNr†r|r}r'r(reÆs zCreateIndex.__init__)Fr‘r'r'r}r(ršÁsršcs&eZdZdZdZd‡fdd„    Z‡ZS)Ú    DropIndexz!Represent a DROP INDEX statement.Z
drop_indexFcstƒj||ddS)aCreate a :class:`.DropIndex` construct.
 
        :param element: a :class:`_schema.Index` that's the subject
         of the DROP.
        :param if_exists: if True, an IF EXISTS operator will be applied to the
         construct.
 
         .. versionadded:: 1.4.0b2
 
        r—Nr†r‚r}r'r(reÙs zDropIndex.__init__)Fr‘r'r'r}r(r›Ôsr›cs$eZdZdZdZ‡fdd„Z‡ZS)Ú AddConstraintz2Represent an ALTER TABLE ADD CONSTRAINT statement.Zadd_constraintcstƒ |¡t |j¡|_dSr0)rzrerÚportable_instancemethodrwÚ _create_rulerur}r'r(reìs ÿzAddConstraint.__init__r‘r'r'r}r(rœçsrœcs&eZdZdZdZd‡fdd„    Z‡ZS)ÚDropConstraintz3Represent an ALTER TABLE DROP CONSTRAINT statement.Zdrop_constraintFc s0||_tƒj|fd|i|—Žt |j¡|_dS)Nr)rŠrzrerrrwrž)r$rtrŠrr&r}r'r(reøs
ÿzDropConstraint.__init__)FFr‘r'r'r}r(rŸósrŸc@seZdZdZdZdS)ÚSetTableCommentz*Represent a COMMENT ON TABLE IS statement.Zset_table_commentNr“r'r'r'r(r sr c@seZdZdZdZdS)ÚDropTableCommentzfRepresent a COMMENT ON TABLE '' statement.
 
    Note this varies a lot across database backends.
 
    Zdrop_table_commentNr“r'r'r'r(r¡sr¡c@seZdZdZdZdS)ÚSetColumnCommentz+Represent a COMMENT ON COLUMN IS statement.Zset_column_commentNr“r'r'r'r(r¢sr¢c@seZdZdZdZdS)ÚDropColumnCommentz0Represent a COMMENT ON COLUMN IS NULL statement.Zdrop_column_commentNr“r'r'r'r(r£sr£c@seZdZdZdZdS)ÚSetConstraintCommentz/Represent a COMMENT ON CONSTRAINT IS statement.Zset_constraint_commentNr“r'r'r'r(r¤sr¤c@seZdZdZdZdS)ÚDropConstraintCommentz4Represent a COMMENT ON CONSTRAINT IS NULL statement.Zdrop_constraint_commentNr“r'r'r'r(r¥"sr¥c@s"eZdZdd„Zejdd„ƒZdS)Ú InvokeDDLBasecCs
||_dSr0)rS)r$rSr'r'r(re)szInvokeDDLBase.__init__cKs
tƒ‚dS)údhelper context manager that will apply appropriate DDL events
        to a CREATE or DROP operation.Nr1©r$r>r&r'r'r(Úwith_ddl_events,szInvokeDDLBase.with_ddl_eventsN)r4r5r6reÚ
contextlibÚcontextmanagerr©r'r'r'r(r¦(sr¦c@seZdZejdd„ƒZdS)ÚInvokeCreateDDLBasecksB|jj||jfd|i|—ŽdV|jj||jfd|i|—ŽdS©r§Z _ddl_runnerN)ÚdispatchZ before_createrSZ after_creater¨r'r'r(r©5s"ÿÿÿÿÿÿz#InvokeCreateDDLBase.with_ddl_eventsN©r4r5r6rªr«r©r'r'r'r(r¬4sr¬c@seZdZejdd„ƒZdS)ÚInvokeDropDDLBasecksB|jj||jfd|i|—ŽdV|jj||jfd|i|—ŽdSr­)r®Z before_droprSZ
after_dropr¨r'r'r(r©Ds"ÿÿÿÿÿÿz!InvokeDropDDLBase.with_ddl_eventsNr¯r'r'r'r(r°Csr°csdeZdZd‡fdd„    Zdd„Zdd„Zd    d
„Zd d „Zdd d„Zdd„Z    ddd„Z
ddd„Z ‡Z S)ÚSchemaGeneratorFNc s4tƒj|f|Ž||_||_|j|_||_i|_dSr0©rzrerBr@Zidentifier_preparerÚpreparerr%Úmemo©r$r%rSrBr@Úkwargsr}r'r(reSs zSchemaGenerator.__init__cCsJ|j |j¡|j |¡}|r*|j |¡|j pH|jj|j|j|d S©N)Úschema©r%Úvalidate_identifierrKrSÚschema_for_objectrBZ    has_table©r$ÚtableÚeffective_schemar'r'r(Ú_can_create_table]s  ÿz!SchemaGenerator._can_create_tablecCsD|j |j¡}|r|j |¡|j pB|jj|j|jj|j|d Sr·©rSr»r½r%rºrBZ    has_indexrK©r$Úindexr¾r'r'r(Ú_can_create_indexfs üz!SchemaGenerator._can_create_indexcCsF|j |¡}|jjoD|jj s&|j oD|j pD|jj|j|j|d Sr·©    rSr»r%Zsupports_sequencesZsequences_optionalÚoptionalrBZ has_sequencerK©r$Úsequencer¾r'r'r(Ú_can_create_sequenceqs ÿüz$SchemaGenerator._can_create_sequencec
    sԈjdk    rˆj}nt|j ¡ƒ}t‡fdd„|Dƒƒ}‡fdd„|j ¡Dƒ}dd„|Dƒ}ˆj||ˆjd\|D]}ˆj|ddqt|D]8\}}|dk    r°ˆj|d|ddqŒ|D]}    ˆ |    ¡q´qŒW5QRXdS)    Ncsg|]}ˆ |¡r|‘qSr')r¿©rhÚtrjr'r(rk…s
z2SchemaGenerator.visit_metadata.<locals>.<listcomp>cs$g|]}|jdkrˆ |¡r|‘qSr0)rrÈ©rhr_rjr'r(rkˆs
 
þcSsg|]\}}|dk    r|‘qSr0r'©rhrÊZfksr'r'r(rkŽs©r@rBT©Ú    create_ok)rÏrŒÚ_is_metadata_operation)r@rMÚvaluesÚsort_tables_and_constraintsÚ
_sequencesr©rBÚtraverse_single)
r$Úmetadatar@Ú
collectionÚseq_collÚevent_collectionÚseqr½ÚfkcsÚfkcr'rjr(Úvisit_metadata~s6
ÿ
þý üzSchemaGenerator.visit_metadatac    Cs|s| |¡sdS|j||j|dð|jD]}|jdk    r,| |j¡q,|jjsTd}t||d     |j
¡t |dƒrŒ|j D]}|j|ddqx|jj r|jjs|jdk    rºt|ƒ     |j
¡|jD]}|jdk    rÀt|ƒ     |j
¡qÀ|jjr|jD]}|jdk    rð|j
 t|ƒ¡qðW5QRXdS)N©rBrÐ)rŒÚindexesTrÎ)r¿r©rBrr„rÔr%Úsupports_alterr‹rZrSÚhasattrrÞZsupports_commentsZinline_commentsÚcommentr r¢Zsupports_constraint_commentsÚ constraintsrYr¤)r$r½rÏrŒrÐrrÂÚ
constraintr'r'r(Ú visit_table¤sHý
 
ýû
 
ÿþ
 
 
 
 
 
ÿzSchemaGenerator.visit_tablec    Cs6|jjs dS| |¡t|ƒ |j¡W5QRXdSr0)r%rßr©rœrZrS©r$rãr'r'r(Úvisit_foreign_key_constraintÙs z,SchemaGenerator.visit_foreign_key_constraintc    Cs<|s| |¡sdS| |¡t|ƒ |j¡W5QRXdSr0)rÈr©r˜rZrS)r$rÇrÏr'r'r(Úvisit_sequenceàs zSchemaGenerator.visit_sequencec    Cs<|s| |¡sdS| |¡t|ƒ |j¡W5QRXdSr0)rÃr©ršrZrS)r$rÂrÏr'r'r(Ú visit_indexæs zSchemaGenerator.visit_index)FN)FNF)F)F) r4r5r6rer¿rÃrÈrÜrärærçrèrr'r'r}r(r±Rsÿ
      )û
5
r±csdeZdZd‡fdd„    Zdd„Zdd„Zd    d
„Zd d „Zdd d„Zddd„Z    dd„Z
ddd„Z ‡Z S)Ú SchemaDropperFNc s4tƒj|f|Ž||_||_|j|_||_i|_dSr0r²rµr}r'r(reîs zSchemaDropper.__init__c s˜ˆjdk    rˆj}nt|j ¡ƒ}z2‡fdd„|Dƒ}ttt|‡fdd„dƒƒ}Wn˜tjk
rê}zxˆjjs¢t     
dd  t dd„|j Dƒƒ¡¡d    d„|Dƒ}n8tj|jd
|j |jd d  t d d„|j Dƒƒ¡d |‚W5d}~XYnX‡fdd„|j ¡Dƒ}dd„|Dƒ}ˆj||ˆjdj|D]>\}}    |dk    rPˆj|dd|dn|    D]}
ˆ |
¡qTq*|D]} ˆj| | jdkdqnW5QRXdS)Ncsg|]}ˆ |¡r|‘qSr')Ú_can_drop_tablerÉrjr'r(rkÿs
z0SchemaDropper.visit_metadata.<locals>.<listcomp>csˆjjr|jdkrdSdS©NF)r%rßrK)rãrjr'r(Ú<lambda>s
ÿþz.SchemaDropper.visit_metadata.<locals>.<lambda>©Ú    filter_fna4Can't sort tables for DROP; an unresolvable foreign key dependency exists between tables: %s; and backend does not support ALTER.  To restore at least a partial sort, apply use_alter=True to ForeignKey and ForeignKeyConstraint objects involved in the cycle to mark these as known cycles that will be ignored.rfcSsg|]
}|j‘qSr'©ÚfullnamerÉr'r'r(rkscSsg|] }|df‘qS)r'r'rÉr'r'r(rksrzõCan't sort tables for DROP; an unresolvable foreign key dependency exists between tables: %s.  Please ensure that the ForeignKey and ForeignKeyConstraint objects involved in the cycle have names so that they can be dropped using DROP CONSTRAINT.cSsg|]
}|j‘qSr'rïrÉr'r'r(rk%s)Úmsgcsg|]}ˆ |¡r|‘qSr')Ú_can_drop_sequencerËrjr'r(rk(s
þcSsg|]\}}|dk    r|‘qSr0r'rÌr'r'r(rk.srÍT)Údrop_okrÐÚ_ignore_sequences)ró)r@rMrÑÚreversedrÒrÚCircularDependencyErrorr%rßrÚwarnroÚsortedÚcyclesÚargsÚedgesrÓr©rBrÔr) r$rÕr@Zunsorted_tablesrÖZerr2r×rØr½rÚrÛrÙr'rjr(rÜøsh
 
þÿÿ øÿ ùü ô
þý 
üzSchemaDropper.visit_metadatacCsH|j |j¡|j |¡}|r*|j |¡|j pF|jj|j|j|dSr·r¹r¼r'r'r(rêEs  ÿzSchemaDropper._can_drop_tablecCsB|j |j¡}|r|j |¡|j p@|jj|j|jj|j|dSr·rÀrÁr'r'r(Ú_can_drop_indexNs üzSchemaDropper._can_drop_indexcCsD|j |¡}|jjoB|jj s&|j oB|j pB|jj|j|j|dSr·rÄrÆr'r'r(ròYs ÿüz SchemaDropper._can_drop_sequencec    Cs<|s| |¡sdS| |¡t|ƒ||jƒW5QRXdSr0)rür©r›rS)r$rÂrór'r'r(rèes zSchemaDropper.visit_indexr'c    Csp|s| |¡sdS|j||j|dBt|ƒ |j¡|jD]$}|jdk    r<|j|kr<| |j¡q<W5QRXdS)NrÝ)    rêr©rBr–rZrSrr„rÔ)r$r½rórÐrôrr'r'r(rälsý    
ÿþzSchemaDropper.visit_tablec    Cs6|jjs dS| |¡t|ƒ |j¡W5QRXdSr0)r%rßr©rŸrZrSrår'r'r(ræŒs z*SchemaDropper.visit_foreign_key_constraintc    Cs<|s| |¡sdS| |¡t|ƒ |j¡W5QRXdSr0)ròr©r™rZrS)r$rÇrór'r'r(rç’s zSchemaDropper.visit_sequence)FN)F)FFr')F) r4r5r6rerÜrêrüròrèrärærçrr'r'r}r(réísÿ
M     
 
û
 rézIterable[TableClause]z0Optional[Callable[[ForeignKeyConstraint], bool]]z:Optional[typing_Sequence[Tuple[TableClause, TableClause]]]z List[Table])r@Úskip_fnÚextra_dependenciesr/cs8|dk    r|‰‡fdd„}nd}dd„t|||ddDƒS)a
Sort a collection of :class:`_schema.Table` objects based on
    dependency.
 
    This is a dependency-ordered sort which will emit :class:`_schema.Table`
    objects such that they will follow their dependent :class:`_schema.Table`
    objects.
    Tables are dependent on another based on the presence of
    :class:`_schema.ForeignKeyConstraint`
    objects as well as explicit dependencies
    added by :meth:`_schema.Table.add_is_dependent_on`.
 
    .. warning::
 
        The :func:`._schema.sort_tables` function cannot by itself
        accommodate automatic resolution of dependency cycles between
        tables, which are usually caused by mutually dependent foreign key
        constraints. When these cycles are detected, the foreign keys
        of these tables are omitted from consideration in the sort.
        A warning is emitted when this condition occurs, which will be an
        exception raise in a future release.   Tables which are not part
        of the cycle will still be returned in dependency order.
 
        To resolve these cycles, the
        :paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be
        applied to those constraints which create a cycle.  Alternatively,
        the :func:`_schema.sort_tables_and_constraints` function will
        automatically return foreign key constraints in a separate
        collection when cycles are detected so that they may be applied
        to a schema separately.
 
        .. versionchanged:: 1.3.17 - a warning is emitted when
           :func:`_schema.sort_tables` cannot perform a proper sort due to
           cyclical dependencies.  This will be an exception in a future
           release.  Additionally, the sort will continue to return
           other tables not involved in the cycle in dependency order
           which was not the case previously.
 
    :param tables: a sequence of :class:`_schema.Table` objects.
 
    :param skip_fn: optional callable which will be passed a
     :class:`_schema.ForeignKeyConstraint` object; if it returns True, this
     constraint will not be considered as a dependency.  Note this is
     **different** from the same parameter in
     :func:`.sort_tables_and_constraints`, which is
     instead passed the owning :class:`_schema.ForeignKeyConstraint` object.
 
    :param extra_dependencies: a sequence of 2-tuples of tables which will
     also be considered as dependent on each other.
 
    .. seealso::
 
        :func:`.sort_tables_and_constraints`
 
        :attr:`_schema.MetaData.sorted_tables` - uses this function to sort
 
 
    Ncs|jD]}ˆ|ƒrdSqdSrW)Úelements)rÛZfk©Z fixed_skip_fnr'r(Ú_skip_fnÞs
zsort_tables.<locals>._skip_fncSsg|]\}}|dk    r|‘qSr0r')rhrÊrÚr'r'r(rkèsùzsort_tables.<locals>.<listcomp>T)rîrþÚ_warn_for_cycles)rÒ)r@rýrþrr'rr(Ú sort_tablesšsAüþrFc sÂtƒ}tƒ}|dk    r| |¡tƒ‰|D]|‰ˆjD]V}|jdkrLˆ |¡q2ˆrlˆ|ƒ}|dkrlˆ |¡q2|j}|ˆk    r2| |ˆf¡q2| ‡fdd„ˆjDƒ¡q(ztt     | 
|¡|¡ƒ}    Wnàt j k
r }
z¾|rt  dd tdd„|
jDƒƒ¡f¡|
jD]p} | |kr| d‰ˆ|
jkr.q‡fd    d
„ˆjDƒ} ˆ | ¡| D]$}|j}|ˆk    rP| |ˆf¡qPqtt     | 
|¡|¡ƒ}    W5d}
~
XYnX‡fd d
„|    DƒdtˆƒfgS) aÐSort a collection of :class:`_schema.Table`  /
    :class:`_schema.ForeignKeyConstraint`
    objects.
 
    This is a dependency-ordered sort which will emit tuples of
    ``(Table, [ForeignKeyConstraint, ...])`` such that each
    :class:`_schema.Table` follows its dependent :class:`_schema.Table`
    objects.
    Remaining :class:`_schema.ForeignKeyConstraint`
    objects that are separate due to
    dependency rules not satisfied by the sort are emitted afterwards
    as ``(None, [ForeignKeyConstraint ...])``.
 
    Tables are dependent on another based on the presence of
    :class:`_schema.ForeignKeyConstraint` objects, explicit dependencies
    added by :meth:`_schema.Table.add_is_dependent_on`,
    as well as dependencies
    stated here using the :paramref:`~.sort_tables_and_constraints.skip_fn`
    and/or :paramref:`~.sort_tables_and_constraints.extra_dependencies`
    parameters.
 
    :param tables: a sequence of :class:`_schema.Table` objects.
 
    :param filter_fn: optional callable which will be passed a
     :class:`_schema.ForeignKeyConstraint` object,
     and returns a value based on
     whether this constraint should definitely be included or excluded as
     an inline constraint, or neither.   If it returns False, the constraint
     will definitely be included as a dependency that cannot be subject
     to ALTER; if True, it will **only** be included as an ALTER result at
     the end.   Returning None means the constraint is included in the
     table-based result unless it is detected as part of a dependency cycle.
 
    :param extra_dependencies: a sequence of 2-tuples of tables which will
     also be considered as dependent on each other.
 
    .. seealso::
 
        :func:`.sort_tables`
 
 
    NTc3s|]}|ˆfVqdSr0r')rhÚparent)r½r'r(Ú    <genexpr>:sz.sort_tables_and_constraints.<locals>.<genexpr>aCannot correctly sort tables; there are unresolvable cycles between tables "%s", which is usually caused by mutually dependent foreign key constraints.  Foreign key constraints involving these tables will not be considered; this warning may raise an error in a future release.rfcss|] }|jVqdSr0rïrÉr'r'r(rMsr
cs$g|]}ˆdksˆ|ƒdk    r|‘qSrër')rhrÛrír'r(rkTs þz/sort_tables_and_constraints.<locals>.<listcomp>csg|]}||j ˆ¡f‘qSr')Úforeign_key_constraintsÚ
difference)rhr½)Úremaining_fkcsr'r(rkesÿ)rNÚupdaterZ    use_alterÚaddZreferred_tableZ_extra_dependenciesrMrÚsortÚunionrrörr÷rorørùrûÚdiscard) r@rîrþrZfixed_dependenciesZmutable_dependenciesrÛÚfilteredZ dependent_onZcandidate_sortÚerrZedgeZ
can_remover')rîrr½r(rÒôsv.
 
 
 
 
ÿ
þÿûÿ
 
 
þ
 
þÿ
þ ýrÒ)NN)NNF)Sr7Ú
__future__rrªÚtypingrrrrrrZtyping_Sequencer    Úr Úbaser r rrÿrrrrZ util.typingrrÚ TYPE_CHECKINGr9rrrr¸rrrrZ
selectablerZ engine.baserZengine.interfacesrr r!r"r#r8Ú
NamedTuplerDZDDLRolerQZ
DDLElementrarsryr€rƒrˆr‹r’r”rŽr–r˜r™ršr›rœrŸr r¡r¢r£r¤r¥r¦r¬r°r±rérrÒr'r'r'r(Ú<module>    sœ                                 (;X " m          
 0û[ÿ