+xdZddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Zdd lmZdd lmZdd lmZddl mZddl mZddl mZddl mZdd l mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl m Z ddl m!Z!ddl m"Z"ddl m#Z#ddl m$Z$dd lm%Z%dd!l&m'Z'd"Z(d#Z)d$Z*d%Z+d&Z,d'Z-e.gd(Z/Gd)d*ej0Z0Gd+d,ej1Z2Gd-d.ej3Z4Gd/d0ej5Z5e5Z6Gd1d2e7Z8Gd3d4e8ej9Z:Gd5d6e8ej9Z;Gd7d8e8ej9Z<Gd9d:ej=Z>Gd;de?ej@ZAGd?d@e?ejBZCGdAdBejDZEGdCdDeEZFGdEdFejBZGGdGdHejHejIZHGdIdJejIZJGdKdLejKZLGdMdNej=ZMGdOdPej=ZNGdQdRej=ZOGdSdTej=ZPGdUdVej=ZQGdWdXe jRjSZTe'eTdYZUe:ZVe4ZWe0ZXe2ZYe5ZZe;Z[eZ]e#Z^eGZ_e$Z`e!ZaeZbeZceZdeHZeeJZfeMZgeNZheOZiePZjeQZkidZed[ed\e"d]e2d^e$d_e!d`edaedbe#dceGddedee dfedgedhe<die>djee5e;eeHeMe0eJeLeEeNeOePeQdk ZlGdldmejmZnGdndoejoZpGdpdqejqZrGdrdserZsGdtduejtZuGdvdwejvZwdxZxdyZydzZzd{Z{ej|Z}d|Z~Gd}d~ejZdS)a![ .. dialect:: mssql :name: Microsoft SQL Server .. _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 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(1,1), 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.3 Added ``mssql_identity_start`` and ``mssql_identity_increment`` parameters to :class:`_schema.Column`. These replace the use of the :class:`.Sequence` object in order to specify these values. .. 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 ``mssql_identity_start`` and ``mssql_identity_increment`` parameters documented at :ref:`mssql_identity`. .. 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 ``mssql_identity_start`` and ``mssql_identity_increment`` parameters passed to the :class:`_schema.Column` object:: from sqlalchemy import Table, Integer, Column test = Table( 'test', metadata, Column( 'id', Integer, primary_key=True, mssql_identity_start=100, mssql_identity_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, ) .. versionchanged:: 1.3 The ``mssql_identity_start`` and ``mssql_identity_increment`` parameters are 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 in a future SQLAlchemy version. 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 (?) * 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', m, 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. 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 no support for the LIMIT or OFFSET keywords. LIMIT is supported directly through the ``TOP`` Transact SQL keyword:: select.limit will yield:: SELECT TOP n If using SQL Server 2005 or above, LIMIT with OFFSET support is available through the ``ROW_NUMBER OVER`` construct. For versions below 2005, LIMIT with OFFSET usage will fail. .. _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 `` 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 .. versionadded:: 1.2 added AUTOCOMMIT isolation level setting .. seealso:: :ref:`dbapi_autocommit` 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 `_, 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. .. versionadded:: 1.0.0 .. _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 delimeters 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:: >>> eng = create_engine("mssql+pymssql://mydsn", legacy_schema_aliasing=True) >>> print(account_table.select().compile(eng)) 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. .. versionchanged:: 1.1 the ``legacy_schema_aliasing`` flag introduced in version 1.0.5 to allow disabling of legacy mode for schemas now defaults to False. .. _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)) .. versionchanged:: 1.1 the ``mssql_clustered`` option now defaults to None, rather than False. ``mssql_clustered=False`` now explicitly renders the NONCLUSTERED clause, whereas None omits the CLUSTERED clause entirely, allowing SQL Server defaults to take effect. 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. 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} This option can also be specified engine-wide using the ``implicit_returning=False`` argument on :func:`_sa.create_engine`. .. _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. This impacts the SQLAlchemy ORM's versioning feature in many cases where server-side value generators are in use in that while the versioning operations can succeed, the ORM cannot always check that an UPDATE or DELETE statement matched the number of rows expected, which is how it verifies that the version identifier matched. When this condition occurs, a warning will be emitted but the operation will proceed. The use of OUTPUT INSERTED can be disabled by setting the :paramref:`_schema.Table.implicit_returning` flag to ``False`` on a particular :class:`_schema.Table`, which in declarative looks like:: class MyTable(Base): __tablename__ = 'mytable' id = Column(Integer, primary_key=True) stuff = Column(String(10)) timestamp = Column(TIMESTAMP(), default=text('DEFAULT')) __mapper_args__ = { 'version_id_col': timestamp, 'version_id_generator': False, } __table_args__ = { 'implicit_returning': False } 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 http://msdn.microsoft.com/en-us/library/ms175095.aspx. N)information_schema)engine)exc)schema)sql)types)util)default) reflection)compiler) expression)func) quoted_name)BIGINT)BINARY)CHAR)DATE)DATETIME)DECIMAL)FLOAT)INTEGER)NCHAR)NUMERIC)NVARCHAR)SMALLINT)TEXT)VARCHARupdate_wrapper)public_factory) ) ) ) ) ))addallalterandanyasasc authorizationbackupbeginbetweenbreakbrowsebulkbycascadecasecheck checkpointclose clusteredcoalescecollatecolumncommitcompute constraintcontains containstablecontinueconvertcreatecrosscurrent current_date current_timecurrent_timestamp current_usercursordatabasedbcc deallocatedeclarer deletedenydescdiskdistinct distributeddoubledropdumpelseenderrlvlescapeexceptexecexecuteexistsexitexternalfetchfile fillfactorforforeignfreetext freetexttablefromfullfunctiongotograntgrouphavingholdlockidentityidentity_insert identitycolifinindexinnerinsert intersectintoisjoinkeykillleftlikelinenoloadmergenationalnocheck nonclusterednotnullnullifofoffoffsetsonopenopendatasource openquery openrowsetopenxmloptionororderouteroverpercentpivotplan precisionprimaryprintproc procedurepublic raiserrorreadreadtext reconfigure references replicationrestorerestrictreturnrevertrevokerightrollbackrowcount rowguidcolrulesaver securityauditselect session_usersetsetusershutdownsome statistics system_usertable tablesampletextsizethentotoptran transactiontriggertruncatetsequalunionuniqueunpivotupdate updatetextuseuservaluesvaryingviewwaitforwhenwherewhilewith writetextc"eZdZdZfdZxZS)REALc t|ddtt|jdi|dS)Nr) setdefaultsuperr__init__)selfkw __class__s r/builddir/build/BUILD/cloudlinux-venv-1.0.10/venv/lib64/python3.11/site-packages/sqlalchemy/dialects/mssql/base.pyrz REAL.__init__sB k2&&&"dD"((R(((((__name__ __module__ __qualname____visit_name__r __classcell__rs@rrrs=N)))))))))rrceZdZdZdS)TINYINTNrrrrrrrrrsNNNrrc:eZdZdZejdZdZdS)_MSDatec d}|S)Nct|tjkr%tj|j|j|jS|SNtypedatetimedateyearmonthdayvalues rprocessz'_MSDate.bind_processor..process5E{{hm++(U[%)LLL rrrdialectrs rbind_processorz_MSDate.bind_processor    rz(\d+)-(\d+)-(\d+)cfd}|S)NcJt|tjr|St|tjrYj|}|std|dtjd|DS|S)Ncould not parse z as a date valuec0g|]}t|pdSrint.0xs r z=_MSDate.result_processor..process.."&G&G&Gqs16{{&G&G&Gr) isinstancerrr string_types_regmatch ValueErrorgroupsrmrs rrz)_MSDate.result_processor..process%!233 zz||#E4#455 IOOE**$*@EG }&G&GAHHJJ&G&G&GHH rrrrcoltypers` rresult_processorz_MSDate.result_processor#     rN)rrrrrecompilerrrrrrrsF 2:* + +DrrcpeZdZdfd ZejdddZdZej dZ dZ xZ S) TIMENc d||_tt|dSr)rrr"r)rrkwargsrs rrz TIME.__init__s," dD""$$$$$rilrcfd}|S)Nct|tjr8tjj|}n*t|tjr t |}|Sr)rrcombine_TIME__zero_datetimestr)rrs rrz$TIME.bind_processor..processso%!233 # )11$ejjllE8=11 #E Lrrrs` rrzTIME.bind_processors#     rz!(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?cfd}|S)NcJt|tjr|St|tjrYj|}|std|dtjd|DS|S)Nrz as a time valuec0g|]}t|pdSr r r s rrz:TIME.result_processor..process..rr) rrr)r rrrrrrs rrz&TIME.result_processor..processrrrrs` rrzTIME.result_processorrrr) rrrrrrr(rrr rrrrs@rr"r"s%%%%%% (-a++K 2:: ; ;Drr"ceZdZdZdS) _DateTimeBasec d}|S)Nct|tjkr%tj|j|j|jS|Srrrs rrz-_DateTimeBase.bind_processor..processrrrrs rrz_DateTimeBase.bind_processorrrN)rrrrrrrr/r/s#rr/ceZdZdS) _MSDateTimeNrrrrrrr3r3Drr3ceZdZdZdS) SMALLDATETIMENrrrrr7r7s$NNNrr7c$eZdZdZdfd ZxZS) DATETIME2Nc Vtt|jdi|||_dS)Nr)rr9rr)rrrrs rrzDATETIME2.__init__ s1'i'--"---"rrrrs@rr9r9sB N##########rr9ceZdZdZddZdS)DATETIMEOFFSETNc ||_dSrr)rrr$s rrzDATETIMEOFFSET.__init__s "rr)rrrrrrrrr<r<s-%N######rr<ceZdZdZdS)_UnicodeLiteralcfd}|S)Nc~|dd}jjr|dd}d|zS)N'z''%z%%zN'%s')replaceidentifier_preparer_double_percents)rrs rrz2_UnicodeLiteral.literal_processor..processsAMM#t,,E*; 1 c400U? "rrrs ` rliteral_processorz!_UnicodeLiteral.literal_processors# # # # # #rN)rrrrHrrrr@r@s#     rr@ceZdZdS) _MSUnicodeNr4rrrrJrJ%r5rrJceZdZdS)_MSUnicodeTextNr4rrrrLrL)r5rrLc2eZdZdZdZdZddZfdZxZS) 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` NFc||_dS)zConstruct 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)rrPs rrzTIMESTAMP.__init__As'rcxtt||||jrfd}|SS)Nch|}|#ttj|dd}|S)Nhex)r codecsencode)rsuper_s rrz+TIMESTAMP.result_processor..processPs6u $ eU ; ;R@@E r)rrNrrP)rrrrrWrs @rrzTIMESTAMP.result_processorLsSy$''88'JJ        NMrF) rrr__doc__rlengthrrrrs@rrNrN-sd  !NF ' ' ' '         rrNceZdZdZdZdS) 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` NrrrrYrrrrr\r\\s("NNNrr\ceZdZdZdZdS)NTEXTzMMSSQL NTEXT type, for variable-length unicode text up to 2^30 characters.Nr]rrrr_r_tsNNNrr_ceZdZdZdZdS) VARBINARYaGThe MSSQL VARBINARY type. This type is present to support "deprecate_large_types" mode where either ``VARBINARY(max)`` or IMAGE is rendered. Otherwise, this type object is redundant vs. :class:`_types.VARBINARY`. .. versionadded:: 1.0.0 .. seealso:: :ref:`mssql_large_type_deprecation` Nr]rrrrara|s !NNNrraceZdZdZdS)IMAGENrrrrrcrcNNNrrcceZdZdZdZdS)XMLa"MSSQL 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". .. versionadded:: 1.1.11 Nr]rrrrfrfs  NNNrrfceZdZdZdS)BITNrrrrrhrhsNNNrrhceZdZdZdS)MONEYNrrrrrjrjrdrrjceZdZdZdS) SMALLMONEYNrrrrrlrls!NNNrrlceZdZdZdS)UNIQUEIDENTIFIERNrrrrrnrns'NNNrrnceZdZdZdS) SQL_VARIANTNrrrrrprps"NNNrrpc&eZdZdZdZfdZxZS)TryCastz+Represent a SQL Server TRY_CAST expression.try_castcHtt|j|i|dS)aCreate 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 N)rrrr)rargrrs rrzTryCast.__init__s-. &gt%s1b11111r)rrrrYrrrrs@rrrrrsC55N222222222rrrz.dialects.mssql.try_castr bigintsmallinttinyintvarcharnvarcharcharnchartextntextdecimalnumericfloatr datetime2datetimeoffsetr) r) smalldatetimebinary varbinarybitrealimagexml timestampmoney smallmoneyuniqueidentifier sql_variantceZdZd dZdZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dS)!MSTypeCompilerNct|ddr d|jz}nd}|s|j}|r|d|zz}dd||fDS)zYExtend a string-type declaration with standard SQL COLLATE annotations. collationNz COLLATE %s(%s) cg|]}||Srrrcs rrz*MSTypeCompiler._extend..$sGGGqr)getattrrrZr)rspectype_rZrs r_extendzMSTypeCompiler._extendsv 5+t , , $u6III "\F  *&6/)DxxGGT9$5GGGHHHrc :t|dd}|dSdd|izS)NrrzFLOAT(%(precision)s)rrrrrs r visit_FLOATzMSTypeCompiler.visit_FLOAT&s.E;55  7)[),DD Drc dS)Nrrrrrs r visit_TINYINTzMSTypeCompiler.visit_TINYINT-syrc (|j d|jzSdS)NzDATETIMEOFFSET(%s)r<r>rs rvisit_DATETIMEOFFSETz#MSTypeCompiler.visit_DATETIMEOFFSET0s ? &'%/9 9##rc 6t|dd}|d|zSdS)NrzTIME(%s)r"rrs r visit_TIMEzMSTypeCompiler.visit_TIME6s)E;55   ) )6rc dS)NrNrrs rvisit_TIMESTAMPzMSTypeCompiler.visit_TIMESTAMP={rc dS)Nr\rrs rvisit_ROWVERSIONzMSTypeCompiler.visit_ROWVERSION@|rc 6t|dd}|d|zSdS)Nrz DATETIME2(%s)r9rrs rvisit_DATETIME2zMSTypeCompiler.visit_DATETIME2Cs)E;55  "Y. .;rc dS)Nr7rrs rvisit_SMALLDATETIMEz"MSTypeCompiler.visit_SMALLDATETIMEJsrc |j|fi|Sr)visit_NVARCHARrs r visit_unicodezMSTypeCompiler.visit_unicodeMs"t"5//B///rc R|jjr|j|fi|S|j|fi|Sr)rdeprecate_large_types visit_VARCHAR visit_TEXTrs r visit_textzMSTypeCompiler.visit_textPsD < - 0%4%e22r22 2"4?5//B// /rc R|jjr|j|fi|S|j|fi|Sr)rrr visit_NTEXTrs rvisit_unicode_textz!MSTypeCompiler.visit_unicode_textVsE < - 1&4&u3333 3#4#E00R00 0rc .|d|S)Nr_rrs rrzMSTypeCompiler.visit_NTEXT\||GU+++rc .|d|S)Nrrrs rrzMSTypeCompiler.visit_TEXT_||FE***rc @|d||jpdS)NrmaxrZrrZrs rrzMSTypeCompiler.visit_VARCHARbs!||IuU\5JU|KKKrc .|d|S)Nrrrs r visit_CHARzMSTypeCompiler.visit_CHARerrc .|d|S)Nrrrs r visit_NCHARzMSTypeCompiler.visit_NCHARhrrc @|d||jpdS)Nrrrrrs rrzMSTypeCompiler.visit_NVARCHARks!||Jel6Ke|LLLrc d|jjtkr|j|fi|S|j|fi|Sr)rserver_version_infoMS_2008_VERSIONvisit_DATETIME visit_DATErs r visit_datezMSTypeCompiler.visit_datenG < +o = =&4&u3333 3"4?5//B// /rc d|jjtkr|j|fi|S|j|fi|Sr)rrrrrrs r visit_timezMSTypeCompiler.visit_timetrrc R|jjr|j|fi|S|j|fi|Sr)rrvisit_VARBINARY visit_IMAGErs rvisit_large_binaryz!MSTypeCompiler.visit_large_binaryzsE < - 1'4'4444 4#4#E00R00 0rc dS)Nrcrrs rrzMSTypeCompiler.visit_IMAGEwrc dS)Nrfrrs r visit_XMLzMSTypeCompiler.visit_XMLurc @|d||jpdS)Nrarrrrs rrzMSTypeCompiler.visit_VARBINARYs!||Ku|7Lu|MMMrc ,||Sr) visit_BITrs r visit_booleanzMSTypeCompiler.visit_booleans~~e$$$rc dS)Nrhrrs rrzMSTypeCompiler.visit_BITrrc dS)Nrjrrs r visit_MONEYzMSTypeCompiler.visit_MONEYrrc dS)Nrlrrs rvisit_SMALLMONEYzMSTypeCompiler.visit_SMALLMONEYrrc dS)Nrnrrs rvisit_UNIQUEIDENTIFIERz%MSTypeCompiler.visit_UNIQUEIDENTIFIERs!!rc dS)Nrprrs rvisit_SQL_VARIANTz MSTypeCompiler.visit_SQL_VARIANTs}rr)!rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsIIII&EEE$$$ 000000 111 ,,,+++LLL+++,,,MMM000 000 111 NNN%%%"""rrcBeZdZdZdZdZdZdZdZdZ dZ dZ dZ dS) MSExecutionContextFNc^|jjs |j|dS|S)Nr)rsupports_unicode_statements_encoder)r statements r _opt_encodezMSExecutionContext._opt_encodes0|7 <((33A6 6 rc |jr_|jjj}|j}|du}|r|j|jdvp|jjjo|jjjo6|j|jjjdvp||jjjdvp<|jjj o*|j|jjjvp||jjjv|_ nd|_ |jj o|o|jj o|j o|j |_ |j rT|j|j|d|j|zd|dSdSdS)z#Activate IDENTITY_INSERT if needed.NrFzSET IDENTITY_INSERT %s ONr)isinsertcompiledrr_autoincrement_columnrcompiled_parameters parameters_has_multi_parameters_enable_identity_insertinline returning executemany_select_lastrowidroot_connection_cursor_executerOrrF format_table)rtbl seq_columninsert_has_sequences rpre_execzMSExecutionContext.pre_execs =3 -)/C2J",D"8 " 5Nd&>q&AA0M+6!M3I *#'=#:#Ea#H!I!I#-#'=#:#Ea#H$I !% 7 MM *#'=#:#E!F!F#-#'=#:#E$F',,405,M(()') //)44)((  "+ $44K$$32??DDEW3 3 T  rc \|j}|jr|jjr||jdd|n||jdd||jd}t|d|_|j s|j s|j r%|j j rtj||_|jr\||j|d|j|j jjzd|dSdS)z#Disable IDENTITY_INSERT if enabled.z$SELECT scope_identity() AS lastrowidrzSELECT @@identity AS lastrowidrSET IDENTITY_INSERT %s OFFN)rrruse_scope_identityrrOfetchallr  _lastrowidrisupdateisdeleterrrFullyBufferedResultProxy _result_proxyrrrFrrr)rconnrows r post_execzMSExecutionContext.post_execsf#  ! *|. $$K: $$K!A2t+&&((+C!#a&kkDO M G!] G.2m Gm% G"(!@!F!FD   '      0.;; /5        rc|jSr)rrs r get_lastrowidz MSExecutionContext.get_lastrowids rc|jrk |j|d|j|jjjzdS#t$rYdSwxYwdS)Nr) rrOrcrrFrrrr Exception)res rhandle_dbapi_exceptionz)MSExecutionContext.handle_dbapi_exception s  '   ##$$42?? M39      sAA"" A0/A0cF|jr|jStj|Sr)r r ResultProxyrs rget_result_proxyz#MSExecutionContext.get_result_proxys'   ,% %%d++ +r) rrrrrr rrrrrrrrrrrrs#MJ 666p$$$L   ,,,,,rrczeZdZdZejejjdddddZfdZ fdZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZe d,fd Ze fdZe d-fd ZdZdZdZdZfd Z d!Z!d"Z"fd#Z#d$Z$d%Z%d&Z&d'Z'd(Z(d)Z)d*Z*d+Z+xZ,S). MSSQLCompilerT dayofyearweekday millisecond microsecond)doydow milliseconds microsecondscVi|_tt|j|i|dSr) tablealiasesrrr)rargsr$rs rrzMSSQLCompiler.__init__+s3+mT""+T.decorate0s`|2 *r$+++++++ }d!;!;R[IIvs)b)))rr)r*r+rs` r_with_legacy_schema_aliasingz*MSSQLCompiler._with_legacy_schema_aliasing/s) * * * * * *rc dS)NCURRENT_TIMESTAMPrrr*rs rvisit_now_funczMSSQLCompiler.visit_now_func9s""rc dS)Nz GETDATE()rr/s rvisit_current_date_funcz%MSSQLCompiler.visit_current_date_func<rrc $d|j|fi|zSNzLEN%sfunction_argspecr/s rvisit_length_funczMSSQLCompiler.visit_length_func?#..r88R8888rc $d|j|fi|zSr4r5r/s rvisit_char_length_funcz$MSSQLCompiler.visit_char_length_funcBr8rc T|j|jfi|d|j|jfi|S)Nz + rrrrroperatorrs rvisit_concat_op_binaryz$MSSQLCompiler.visit_concat_op_binaryEsG DL + + + + + + DL , , , , ,  rc dS)N1rrexprrs r visit_truezMSSQLCompiler.visit_trueKsrc dS)N0rrBs r visit_falsezMSSQLCompiler.visit_falseNrErc Xd|j|jfi|d|j|jfi|dS)Nz CONTAINS (, )r<r=s rvisit_match_op_binaryz#MSSQLCompiler.visit_match_op_binaryQsL DL + + + + + + DL , , , , , ,  rc d}|jr|dz }|jr&|j|jr|jdkr |d|jzz }|r|St jj||fi|S)z- MS-SQL puts TOP, it's version of LIMIT here z DISTINCT NrzTOP %d ) _distinct_simple_int_limit_offset_clause_simple_int_offset_offset_limitr SQLCompilerget_select_precolumns)rrrss rrVz#MSSQLCompiler.get_select_precolumnsWs      A  # +  ! )) *.4n.A.A V]* *A  H'=f " rc|Srrrrr}s rget_from_hint_textz MSSQLCompiler.get_from_hint_textn rc|SrrrYs rget_crud_hint_textz MSSQLCompiler.get_crud_hint_textqr[rc dSNrNr)rrrs r limit_clausezMSSQLCompiler.limit_clausetsrrc Xd|j|jfi|d|j|jfi|dS)Nz TRY_CAST (z AS rK)rclause typeclause)relementrs rvisit_try_castzMSSQLCompiler.visit_try_castxsM DL . .2 . . . . DL+ 2 2r 2 2 2 2  rc |js|j|j|jr|jrt |ddsy|jjstj dd|jjD}|j}|j}||d<| }d|_ | tj|dd}tj d}tjd |jD}|8|||k|||||zkn|||k|j|fi|St1jj||fi|S) zLook for ``LIMIT`` and OFFSET in a select statement, and if so tries to wrap it in a subquery with ``row_number()`` criterion. N _mssql_visitzLMSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clausec6g|]}tj|Sr)sql_utilunwrap_label_reference)relems rrz.MSSQLCompiler.visit_select..s3!!!/55!!!rselect_wraps_forTorder_bymssql_rnc(g|]}|jdk |S)ro)rrs rrz.MSSQLCompiler.visit_select..s$<<2&.$77 2*2 &# !!"3;!!!  "/L"1M)/F% &%%''F"&F  H''))T#4T55U:&& $ z*--H*<yOOBOOO6u]D))6   &7 ;=   rct|dd2||jvr||j|<|j|SdS)Nr)rr%rx)rrs rrz#MSSQLCompiler._schema_aliased_tablesJ 5(D ) ) 5D---+0;;==!%($U+ +4rc |j|j|j}d|d|j|jfi|dS)Nz DATEPART(rJrK) extract_mapgetfieldrrC)rextractrrs r visit_extractzMSSQLCompiler.visit_extractsK $$W]GMBB%*UULDL,L,L,L,L,L,LMMrc<d|j|zS)NzSAVE TRANSACTION %spreparerformat_savepointrsavepoint_stmts rvisit_savepointzMSSQLCompiler.visit_savepoints&$t}'E'E ( (   rc<d|j|zS)NzROLLBACK TRANSACTION %srrs rvisit_rollback_to_savepointz)MSSQLCompiler.visit_rollback_to_savepoints&(4=+I+I , ,   rc Nt|jtjre|jtjkrPt|jtjs1|jtj|j|j|jfi|Stt|j |fi|S)z]Move bind parameters to the right-hand side of an operator, where possible. ) rrr BindParameterr>eqrrBinaryExpressionrr visit_binary)rrr$rs rrzMSSQLCompiler.visit_binarys v{J$< = = 8;..v|Z-EFF/ 4<+L&+v   7u]D))6vHHHHHrc&jsjr|jd}n|jd}t j|fdt j|D}dd|zS)Ninserteddeletedc hg|].}d|ddi/S)NTF)_label_select_columntraverse)rradapterrs rrz2MSSQLCompiler.returning_clause..sT     % %g&&q))4     rzOUTPUT rJ) rr rrxri ClauseAdapterr_select_iterablesr)rstmtreturning_colstargetcolumnsrs` @rreturning_clausezMSSQLCompiler.returning_clause s = 1DM 1Z%%j11FFZ%%i00F(00      1.AA    499W----rcdS)NWITHr)r recursives rget_cte_preamblezMSSQLCompiler.get_cte_preambles vrct|tjr|dSt t ||||Sr)rrFunctionrwrrlabel_select_column)rrr@asfromrs rrz!MSSQLCompiler.label_select_column&sS fj1 2 2 <<%% %--AA rcdSr_r)rrs rfor_update_clausezMSSQLCompiler.for_update_clause.s rrc t|r |jsdS|j|jfi|}|rd|zSdS)NrNz ORDER BY )rrTrrr)rrrrns rorder_by_clausezMSSQLCompiler.order_by_clause3sZ      fm 24< 7>>2>>  (* *2rc \ddfd|g|zDzS)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 rJc3:K|]}|jfddVdST)r fromhintsN_compiler_dispatchrr from_hintsrrs r z3MSSQLCompiler.update_from_clause..LS# #  !A  Odj O OB O O# # # # # # rr)r update_stmt from_table extra_fromsrrs` ``rupdate_from_clausez MSSQLCompiler.update_from_clauseBs[# # # # # #  \K/# # #     rc@d}|rd}||dd|S)z=If we have extra froms make sure we render any alias as hint.FT)rrashintr)r delete_stmtrrrs rdelete_table_clausez!MSSQLCompiler.delete_table_clauseQs:  F,, d6-   rc \ddfd|g|zDzS)zjRender the DELETE .. FROM clause specific to MSSQL. Yes, it has the FROM keyword twice. rrJc3:K|]}|jfddVdSrrrs rrz9MSSQLCompiler.delete_extra_from_clause..brrr)rrrrrrs` ``rdelete_extra_from_clausez&MSSQLCompiler.delete_extra_from_clauseZs[# # # # # #  \K/# # #     rcdS)NzSELECT 1 WHERE 1!=1r)rrs rvisit_empty_set_exprz"MSSQLCompiler.visit_empty_set_exprgs$$rc td||jd||jdS)NzNOT EXISTS (SELECT  INTERSECT SELECT rKr<r=s rvisit_is_distinct_from_binaryz+MSSQLCompiler.visit_is_distinct_from_binaryj< LL % % % % LL & & & &  rc td||jd||jdS)NzEXISTS (SELECT rrKr<r=s r visit_isnot_distinct_from_binaryz.MSSQLCompiler.visit_isnot_distinct_from_binaryprr)FFr)-rrrreturning_precedes_valuesr update_copyrrUrrr,r0r2r7r:r?rDrHrLrVrZr]r`rerzrrrrrrrrrrrrrrrrrrrrrs@rrrs $"$"())   K=====###999999      .   8M8M8Mt" K K K K K"! K"CCCC"!C "     "! 4NNN      IIIII$...$              %%%          rrc2eZdZdZdZdZdZfdZxZS)MSSQLStrictCompilerzA 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. Tc ^d|d<|j|jfi|d|j|jfi|S)NT literal_bindsz IN r<r=s rvisit_in_op_binaryz&MSSQLStrictCompiler.visit_in_op_binaryQ"? DL + + + + + + DL , , , , ,  rc ^d|d<|j|jfi|d|j|jfi|S)NTrz NOT IN r<r=s rvisit_notin_op_binaryz)MSSQLStrictCompiler.visit_notin_op_binaryrrctt|tjrdt |zdzSt t |||S)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. rC) issubclassrrrr*rrrender_literal_value)rrrrs rrz(MSSQLStrictCompiler.render_literal_values] d5kk8= 1 1 U#c) ),d33HHu r) rrrrYansi_bind_rulesrrrrrs@rrrwsgO      rrc4eZdZdZd dZdZdZdZdZdS) MSDDLCompilerc |j|}|j!|d||jzz }n,|d|jj|j|zz }|jH|jr/|js(t|j tj s |j dur|dz }n |j|dz }|jtjdt|j tj rt|j j|j j||jjurt)jd|j jdkrd}n|j jpd }|d |d |j jpd d z }ni||jjus |j dur3|jd d}|jd d}|d |d |d z }n||}||d|zz }|S)Nr)type_expressionTz NOT NULLz NULLz;mssql requires Table-bound columns in order to generate DDLa Use of Sequence with SQL Server in order to affect the parameters of the IDENTITY value is deprecated, as Sequence will correspond to an actual SQL Server CREATE SEQUENCE in a future release. Please use the mssql_identity_start and mssql_identity_increment parameters.rrz IDENTITY(,rKmssqlidentity_startidentity_incrementz DEFAULT )r format_columncomputedrr type_compilerrnullable primary_keyrr sa_schemaSequence autoincrementrrrtstart incrementrr warn_deprecateddialect_optionsget_column_default_string)rr@r$colspecrrr s rget_column_specificationz&MSDDLCompiler.get_column_specifications;---f55 ? & sT\\&/::: :GG sT\7?? V@ G ? &O #% #fni.@AA #'4//;&(7" < "+  fni&8 9 9# 1$0>+7!CCC$?~#q((,1 G(-A-- GG fl8 8 8#t++*734DEE.w78LMI GUUUIII> >GG44V<.sX!))T*rrKincludeclg|]0}t|tjrjj|n|1Sr)rr rrr)rcolr{s rrz4MSDDLCompiler.visit_create_index.. sNc4#455 c""rz INCLUDE (%s)cDg|]}|jSr)quoter)rrrs rrz4MSDDLCompiler.visit_create_index..s'<<.6F# # ,-DM   ' '# # # # # # rlenrrformat_constraintrrdefine_constraint_deferrability)rrCr}r=s` rvisit_primary_key_constraintz*MSDDLCompiler.visit_primary_key_constraint%s z??a  2 ? & $t}'F'F(( D .w7 D   ( $' # # # # 1;# # #      44Z@@@ rcXt|dkrdSd}|j$j|}||d|zz }|dz }|jdd}| |r|dz }n|dz }|d d fd |Dzz }||z }|S) NrrNrrrr=rrrrJc3VK|]#}j|jV$dSrrrs rrz8MSDDLCompiler.visit_unique_constraint..Mr rr!)rrCr}formatted_namer=s` rvisit_unique_constraintz%MSDDLCompiler.visit_unique_constraint<s z??a  2 ? &!]<99 .w7 D   ( $' # # # # 1;# # #      44Z@@@ rcld|j|jddz}|jdur|dz }|S)NzAS (%s)FTr z PERSISTED)r rsqltext persisted)r generatedr}s rvisit_computed_columnz#MSDDLCompiler.visit_computed_columnSsO4,44  U$5     $ & & L D rNrX) rrrrrrr%r)r.rrrrrsxDDDL0000d   ..rrc6eZdZeZfdZdZdZddZxZ S)MSIdentifierPreparerc`tt||ddddS)N[]F) initial_quote final_quotequote_case_sensitive_collations)rr0r)rrrs rrzMSIdentifierPreparer.__init__`sA "D))22 ,1 3     rc.|ddS)Nr3]]rErrs r_escape_identifierz'MSIdentifierPreparer._escape_identifierhs}}S$'''rc.|ddS)Nr8r3r9r:s r_unescape_identifierz)MSIdentifierPreparer._unescape_identifierks}}T3'''rNc|tjdt|\}}|r.||d||}n|r||}nd}|S)z'Prepare a quoted table and schema name.NzThe 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()..rN)r r_schema_elementsr)rrforcedbnameownerresults r quote_schemaz!MSIdentifierPreparer.quote_schemans    !   )00    $ 6 2 2 2 2DJJu4E4E4EFFF  ZZ&&FFF rr) rrrRESERVED_WORDSreserved_wordsrr;r=rErrs@rr0r0]so#N     ((((((rr0c0dfd }t|S)Nc Rt||\}}t|||||||fi|Sr_owner_plus_db _switch_db)r connectionrrrBrCr*s rwrapz$_db_plus_owner_listing..wrapsO&w77               rrr r*rNs` r_db_plus_owner_listingrPs3        $ # ##rc0dfd }t|S)Nc Tt||\}}t||||||||f i|SrrJ)rrM tablenamerrrBrCr*s rrNz_db_plus_owner..wrapsR&w77                rrr rOs` r_db_plus_ownerrTs3        $ # ##rc|rP|d}||kr5|d|jj|z ||i||r<||kr7|d|jj|zSSS#|r<||kr7|d|jj|zwwwxYw)Nzselect db_name()zuse %s)scalarrcrrFr)rBrMr*rur current_dbs rrLrLs" &&'9::      :-AGGOOO   r3~"~~  jF**   $8>>zJJK     *6 jF**   $8>>zJJK     *s BACcF|s d|jfSd|vrt|Sd|fS)Nr?)default_schema_namer@)rrs rrKrKs9 W000 '''V|rc t|tr |jrd|fS|tvr t|Sg}d}d}d}t jd|D][}|s|dkrd}d}|dkrd}|s;|dkr5|r|d|zn||d}d}V||z }\|r||t|d kr}d|d d |d }}t j d |d d rt|d }nH| d d}nt|r d|d }}nd\}}||ft|<||fS)NrNFz (\[|\]|\.)r2Tr3r?z[%s]rrz .*\].*\[.*r)NN) rrr_memoized_schemarsplitappendr"rrlstriprstrip)rpushsymbolbracket has_bracketstokenrBrCs rr@r@s&+&&6<V| !!!'' D FGL-00   C<<GLL c\\GG Uc\\ $ FVO,,,, F###F LL eOFF  F 4yy1}}ad,,d2h 8M6!B$< 0 0 4 u555FF]]3''..s33FF T#d1g" %u}V 5=rc DeZdZdZdZdZeZdZdZ dZ e j e e jee jee jee jeiZejjdejfgZeZdZdZdZ dZ!dZ"dZ#e$Z%e&Z'e(Z)e*Z+e,j-dd ife,j.dd ife,j/d d d d fe,j0d d d fgZ1 d!fd Z2fdZ3dZ4e5gdZ6dZ7dZ8fdZ9dZ:dZ;dZdZ?e@jAdZBe@jAeCdZDe@jAeCdZEe@jAe>dZFe@jAe>dZGe@jAe>dZHe@jAe>dZIe@jAe>d ZJxZKS)" MSDialectrTFdbor)rr=N)r=r rr)rrc t|pd|_||_||_||_||_t t|jdi|||_ dS)Nrr) r  query_timeout schema_namerrr)rrhrisolation_level) rrlrrmrnrr)optsrs rrzMSDialect.__init__, sk!!3!44&"4%:"&<#'i'//$///.rc|dtt|||dS)Nz$IF @@TRANCOUNT = 0 BEGIN TRANSACTION)rcrrh do_savepoint)rrMrrs rrqzMSDialect.do_savepointA s>ABBB i++J=====rcdSrr)rrMrs rdo_release_savepointzMSDialect.do_release_savepointF s r) SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READSNAPSHOTc p|dd}||jvr:tjd|d|jdd|j|}|d|z||dkr| dSdS) N_rzInvalid value 'z2' for isolation_level. Valid isolation levels for z are rJz"SET TRANSACTION ISOLATION LEVEL %sru) rE_isolation_lookupr ArgumentErrorrrrOrcr<rA)rrMlevelrOs rset_isolation_levelzMSDialect.set_isolation_levelT s c3'' . . .##55$)))TYYt/E%F%F%FH  ""$$;eCDDD  J            rc&|jtkrtdd}d}|D]}|} |d|z|d}||cS#|jj $r }|}Yd}~|d}~wwxYw#|wxYwtj d|d|td|d|)Nz4Can't fetch isolation level prior to SQL Server 2005)zsys.dm_exec_sessionszsys.dm_pdw_nodes_exec_sessionsa 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 %s where session_id = @@SPID rz:Could not fetch transaction isolation level, tried views: z; final error was: zPCan't fetch isolation level on this particular SQL Server version. tried views: ) rMS_2005_VERSIONNotImplementedErrorrOrcfetchoneupperr<dbapiErrorr warn)rrM last_errorviewsrrOvalerrs rget_isolation_levelzMSDialect.get_isolation_levelb s]  #o 5 5%F  J% % D&&((F      oo''* yy{{ :#        II:?%%M   &%55**& s/2B/C C(C*C CC  C!ctt|||||dSr)rrh initialize_setup_version_attributes_setup_supports_nvarchar_max)rrMrs rrzMSDialect.initialize sM i))*555 &&((( ))*55555rc$jfd}|SdS)Nc>|jdSr)r{rn)r rs rconnectz%MSDialect.on_connect..connect s"((t/CDDDDDr)rn)rrs` r on_connectzMSDialect.on_connect s6   + E E E E EN4rcv|jdttddvr9tjddd|jDz|jt krd|jvrd|_|jtkrd|_ |j |jtk|_ dSdS) Nrr(z[Unrecognized server version info '%s'. Some SQL Server features may not function properly.r?c34K|]}t|VdSr)r*r s rrz6MSDialect._setup_version_attributes.. s(DDa3q66DDDDDDrimplicit_returningT) rlistranger rrr}__dict__rrsupports_multivalues_insertrMS_2012_VERSIONrs rrz#MSDialect._setup_version_attributes s  #A &d5B<<.@.@ @ @ I6((DD4+CDDDDDE     $ 7 7$DM99&*D #  # 6 6/3D ,  % -(O;  & & & . -rc |tjdd|_dS#tj$r d|_YdSwxYw)Nz0SELECT CAST('test max support' AS NVARCHAR(max))TF)rVr r}_supports_nvarchar_maxr DBAPIError)rrMs rrz&MSDialect._setup_supports_nvarchar_max sm /   KLL    +/D ' ' '~ 0 0 0*/D ' ' ' ' 0s'2A  A c|jtkr|jStjd}||}|t |dS|jS)NzSELECT schema_name()Tr\)rr}rmr r}rVr)rrMqueryrYs r_get_default_schema_namez"MSDialect._get_default_schema_name sb  #o 5 5# #H344E","3"3E":": ".##6dCCCC''rctj}|jj|k}|r#t j||jj|k}t j|g|}||} | duSr) ischemarr table_namer and_ table_schemarrcfirst) rrMrSrBrCrrrrWrs r has_tablezMSDialect.has_table s{/i*i7  (WY3u<K Jy+ . .   q ! !wwyy$$rc tjtjjjgtjjjg}d||D}|S)Nrmcg|] }|d Sr rrrs rrz.MSDialect.get_schema_names.. s<<<!<<. s;;;qt;;;r rtablesr rrrrr table_typerc) rrMrBrCrrrrW table_namess rget_table_nameszMSDialect.get_table_names s J X ! H%.#|3  h)*    <;Z%7%7%:%:;;; rc tj}tj|jjgtj|jj|k|jjdk|jjg}d| |D}|S)NVIEWrmcg|] }|d Sr rrs rrz,MSDialect.get_view_names.. s:::qad:::rr) rrMrBrCrrrrW view_namess rget_view_nameszMSDialect.get_view_names s J X ! H%.0Cv0M  h)*    ;:J$6$6q$9$9::: rc |jtkrgS|tjdtjd|tjtjd|tj tj }i}|D]!} | d| ddkgd|| d <"|tjd tjd|tjtjd|tj tj }|D]9} | d |vr-|| d d  | d:t|S) Na select ind.index_id, ind.is_unique, ind.name 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 != 0tabnameschname)rr is_uniquer)rr column_namesindex_idaRselect ind_col.index_id, ind_col.object_id, col.name 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=:schnamer)rr}rcr r} bindparams bindparamr CoerceUnicodersqltypesUnicoder_rr) rrMrSrBrCrrrpindexesrs r get_indexeszMSDialect.get_indexes s  #o 5 5I    H=  Z iG4I4K4KLL i0E0G0GHHW(*,,W - -     CF k*a/ "((GC O $ $    H(  Z iG4I4K4KLL i0E0G0GHHW(*,,W - -!  $ M MC:'))J(8??F LLLGNN$$%%%rc @|tjdtjd|t jtjd|t j}|r|}|SdS)Nzselect definition from sys.sql_modules as mod, sys.views as views, sys.schemas as sch where mod.object_id=views.object_id and views.schema_id=sch.schema_id and views.name=:viewname and sch.name=:schnameviewnamer)rcr r}rrrrrV) rrMrrBrCrrrview_defs rget_view_definitionzMSDialect.get_view_definition6 s    H=  j j(G4I4K4KLL i0E0G0GHH     yy{{HO  rc | tj}tj}|rwtj|jj|k|jj|k} |d|} |jjdz|jjz} |jjtj| k} n>|jj|k} |} |jjtj|jjk} tj| |jj |jj k} | || d} |j r |jj}n,tj|jjt!d}tj|||jjg| | |jjg}||}g} |}|n||jj }||jj}||jjdk}||jj}||jj}||jj}||jj}||jj}||}||jj}|j|d}i}|t>t@tBtDtFtHtJtLtNj(f vr|dkrd}||d<|r||d <|(tSj*d |d |d tNj+}nFtY|tNj-r$||d <tY|tNj.s||d<|d!i|}||||dd}| |||d|d<|/|i} |D] }!|!| |!d<|tj0d||d}"d}# |"}|nF|d|d}%}$|%1dr |$| vr|$}#d| |$d<ddd| |$d<n]|"2|#|j3thkr|d|} |d| d| d}"|"5}|R|d J| |#d6to|d to|dd|S)"Nr?T)onclauseisouteri)from_objrnYESr[rZrzDid not recognize type 'z ' of column 'rCrscaleF)rrrr r)r+r,rrzFEXEC sp_columns @table_name = :table_name, @table_owner = :table_owner)r table_ownerrrvrr)mssql_identity_startmssql_identity_incrementrzselect ident_seed('z'), ident_incr('z')rr)8rrcomputed_columnsr rrrr object_idr column_namerrr definitioncastrr is_persistedordinal_positionrcr data_type is_nullablecharacter_maximum_lengthnumeric_precision numeric_scalecolumn_defaultcollation_name ischema_namesrMSStringMSChar MSNVarcharMSNCharMSTextMSNTextMSBinary MSVarBinaryr LargeBinaryr rNULLTYPErNumericFloatr_r}endswithr<rr}rrr )&rrMrSrBrCrrr computed_colsrtable_fullname full_namejoin_onrcomputed_definitionrWrcolsrrrrcharlen numericprec numericscaler rrrrr$cdictcolmaprrOiccol_name type_names& r get_columnszMSDialect.get_columnsN sT/0  ( $ 1 &%/K).yy9N .4wy7KKI#o/4>)3L3LLGG!).);K&N#o/4> $44G( WY*mo.BB  ||MGT|JJ  & "//"<  #&(*HTNN##  J )=?+G H i01       q ! !? **,,C{wy,-D +,E7901U:H')<=Ggi9:Kwy67L')23GGI45I01J};>7*6w!'++F++$"!& E%,*B)!-%%j! KK   ? B & &C"%F3v;  ## H.  %U ; ;    //##C{$'FCFyX!!*-- (f2D2D48x 1,-0177x !23    >d6/II(-yy9N'''!>>>>>3F ,,..C3q6#5r ,-4403CF 47AKK  rc g}tj}tjd} t j| jj|jj| jj gt j |jj | jj k|jj | jj k| jj |k| jj |k |jj | jj} || } d} | D]O} d| |jjjvr4|| d| | | jj j} P|| dS)NCPRIMARYr)constrained_columnsr)r constraintskey_constraintsrxr rrrconstraint_typeconstraint_namerrrrnrrcrr_)rrMrSrBrCrrpkeysTCrrWrrrs rget_pk_constraintzMSDialect.get_pk_constraint s<     # ) )# . . J S_bd2AC4G H H$(;;!QS%55)+ E)      (24')= > >    q ! ! D DCC 4 9::: SV$$$"*&)!#*=*B&CO',oFFFrc tj}tjd}tjd} t j|jj| jj| jj | jj|jj |jj |jj |jj gt j|jj |k|jj|k|jj|jjk|jj |jj k| jj |jjk| jj|jjk|jj| jjk|jj | jjg} g} d} t'j| } || D]x} | \}}}}}}}}| |}||d<|ds||d<|||kr|r|dz|z}||d<|d |d }}||||yt1| S) NrRrmcdgddgdS)N)rrreferred_schemareferred_tablereferred_columnsrrrrfkey_recz,MSDialect.get_foreign_keys..fkey_rec' s ')#'"&$&  rrrr?rrr)rref_constraintsrrxr rrrrrr match_option update_rule delete_rulerconstraint_schemaunique_constraint_nameunique_constraint_schemarr defaultdictrcrr_rr)rrMrSrBrCrrRRrr rWfkeysrrscolrschemartblrcolrfknmfkmatchfkuprule fkdelrulerec local_cols remote_colss rget_foreign_keyszMSDialect.get_foreign_keys sK  $  # ) )# . .  # ) )# . . J $!    H)+ E)&!#*::#rt';;#rt'BB%)FF$(<<  d*AC,@A)   0    **##A&&//11 % %AMN JD'4ugx,CCK'( 5(,$%%')9)99"(3,"8-4C)*)*&'$J   d # # #   t $ $ $ $ELLNN###r)NTrjNNF)Lrrrrsupports_default_valuessupports_empty_insertrexecution_ctx_clsrmax_identifier_lengthrmrDateTimer3DaterTimer"rrJ UnicodeTextrLcolspecsr DefaultDialectengine_config_typesrr asboolrsupports_native_boolean#non_native_boolean_check_constraintsupports_unicode_bindspostfetch_lastrowidrrrstatement_compilerr ddl_compilerrrr0rrPrimaryKeyConstraintUniqueConstraintIndexColumnconstruct_argumentsrrqrsrrxr{rrrrrrrTrr cacherrPrrrrrr r(rrs@rrhrh s D"!*K ; w t*n H"0DJJ "DK 01"M#*/'!"& L"M#H  '+t)<=  #k4%89 MMN  aqIIJ "$//////*>>>>>           ...`66666 &/// ( ( ( % %^ %      3&3&^3&j^,UU^UnGG^G4A$A$^A$A$A$A$A$rrh)rYrUrr>rrNrrrrrrr r rr r r rrrrrirrrrrrrrrrrrrrr!util.langhelpersr"MS_2016_VERSIONMS_2014_VERSIONrrr}MS_2000_VERSIONrrFrIntegerrr.rr"_MSTimeobjectr/r-r3r7r9 TypeEnginer<r@rrJr0rL_BinaryrNr\r_rarrcTextrfrhrjrlrnrpelementsCastrrrs MSDateTimeMSDateMSReal MSTinyIntegerMSTimeMSSmallDateTime MSDateTime2MSDateTimeOffsetrrrrrrrrMSImageMSBitMSMoney MSSmallMoneyMSUniqueIdentifier MSVariantrGenericTypeCompilerrDefaultExecutionContextrrUrr DDLCompilerrIdentifierPreparerr0rPrTrLrKLRUCacher]r@r2rhrrrr`s; e e N  ++++++######!!!!!! ######""""""......uuuwwt)))))8=)))hhm:'''''8='''T F     -!2   %%%%%M8#4%%%##### x0########X(###     f        ("2        _h&:   ,,,,, ,,,^""""""""0H !!!!!"H$8!!!(H      (-   ( H """""$"""(((((x*(((#####(%###22222cl222> >'#= > >    !           %   7 fw  w    D U D Uww U n!" D#$ "     (= DGGGGGX1GGGT,,,,,8,,,DV V V V V H(V V V r ,,,,,-,,,^tttttH(tttn(((((86(((V$$$$$$$&"!4=??444nE $E $E $E $E $&E $E $E $E $E $r