L i  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 d lm+Z+d dlmZ,d d!l-m.Z.d d"l/m0Z0d d#l1m2Z2d d$l3m4Z4d d%l3m5Z5d d&l3m6Z6d d'l3m7Z7d d(l3m8Z8d d)l3m9Z9d d*l3m:Z:d d+l3m;Z;d d,l3mZ>d d/l3m?Z?d d0l3m@Z@d d1l3mAZAd d2lmBZBd d3lCmDZDe r d d4lEmFZFd d5lGmHZHd6ZId7ZJd8ZKd9ZLd:ZMd;ZNdd?e*jZQGd@dAe*jZRGdBdCe*jZTGdDdEe*jZVGdFdGe*jZWeWZXGdHdIeWZYGdJdKZZGdLdMeZe*jZ\GdNdOeZe*jZ]GdPdQeZe*jZ^GdRdSeZe*jZ_GdTdUZ`GdVdWe`e*jZbGdXdYe`e*jZdGdZd[e*jZfGd\d]efZgGd^d_e*jZhGd`dae*je*jZiGdbdce*jZkGdddee*jZmGdfdge*jZoGdhdie*jZqGdjdke*jZrGdldme*jZtGdndoe*je*jZvGdpdqe*jZwe\ZxeVZyeQZzeTZ{eWZ|e]Z}e^Z~e_Ze@ZehZeAZe>Ze6Zedxe6dye<dze@d{ehd|e9d}e=d~e:de8de^de_de7eWe]e5eieoeQeRekemefeqerevewdZGdde$jZGddej"ZGdde$j&ZGddeZGdde$j,ZGdde$j0ZdZdZdZdZej<ZdZGddejBZy)a .. dialect:: mssql :name: Microsoft SQL Server :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: .. sourcecode:: sql 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: .. sourcecode:: sql 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: .. sourcecode:: sql 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 `` 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 ` 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: .. sourcecode:: sql 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: .. sourcecode:: sql 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. .. _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`. For indexes this option can be combined with the ``mssql_columnstore`` one to create a clustered columnstore index. 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: .. sourcecode:: sql 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: .. sourcecode:: sql CREATE TABLE my_table ( x INTEGER NOT NULL, y INTEGER NOT NULL, PRIMARY KEY NONCLUSTERED (x, y) ) Columnstore Index Support ------------------------- The MSSQL dialect supports columnstore indexes via the ``mssql_columnstore`` option. This option is available to :class:`.Index`. It be combined with the ``mssql_clustered`` option to create a clustered columnstore index. To generate a columnstore index:: Index("my_index", table.c.x, mssql_columnstore=True) which renders the index as ``CREATE COLUMNSTORE INDEX my_index ON table (x)``. To generate a clustered columnstore index provide no columns:: idx = Index("my_index", mssql_clustered=True, mssql_columnstore=True) # required to associate the index with the table table.append_constraint(idx) the above renders the index as ``CREATE CLUSTERED COLUMNSTORE INDEX my_index ON table``. .. versionadded:: 2.0.18 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: .. sourcecode:: sql 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)try_cast)is_sql_compiler)InsertmanyvaluesSentinelOpts)TryCast)BIGINT)BINARY)CHAR)DATE)DATETIME)DECIMAL)FLOAT)INTEGER)NCHAR)NUMERIC)NVARCHAR)SMALLINT)TEXT)VARCHARupdate_wrapper)Literal)DMLState) TableClause)) ) ) ) ) )>asbyifinisofonortoaddallandanyascendforkeynotoffsettopusebulkcasedbccdenydescdiskdropdumpelseexecexitfilefromfullgotointojoinkillleftlikeloadnullopenoverplanprocreadrulesavesomethentranuserviewwhenwithalterbeginbreakcheckclosecrossfetchgrantgroupindexinnermergeorderouterpivotprintrighttableunionwherewhilebackupbrowsecolumncommitcreaterdeletedoubleerrlvlescapeexceptexistshavinginsertlinenonullifoptionpublicreturnrevertrevokerselectuniqueupdatevaluesbetweencascadecollatecomputeconvertcurrentdeclarerexecuteforeignnocheckoffsetsopenxmlpercentprimaryrestoresetusertriggertsequalunpivotvaryingwaitforcoalescecontainscontinuedatabasedistinctexternalfreetextfunctionholdlockidentitynationalreadtextrestrictrollbackrowcountshutdowntextsizetruncate clustered intersect openquery precision procedure raiserror writetext checkpoint constraint deallocate fillfactor openrowset references rowguidcol statistics updatetext distributed identitycol reconfigure replication system_user tablesample transaction current_date current_time current_user nonclustered session_user authorization containstable freetexttable securityauditopendatasourceidentity_insertcurrent_timestampc"eZdZdZfdZxZS)REALzthe SQL Server REAL datatype.c H|jddt|di|y)Nr setdefaultsuper__init__selfkw __class__s d/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sqlalchemy/dialects/mssql/base.pyrz REAL.__init__# k2& 2__name__ __module__ __qualname____doc__r __classcell__rs@rrrs'rrc"eZdZdZfdZxZS)DOUBLE_PRECISIONzMthe SQL Server DOUBLE PRECISION datatype. .. versionadded:: 2.0.11 c H|jddt|di|y)Nr5rrrs rrzDOUBLE_PRECISION.__init__rrrrs@rrrs rrceZdZdZy)TINYINTNrrr__visit_name__rrrr r sNrr c<eZdZdZej dZdZy)_MSDatec d}|S)Nct|tjk(r5tj|j|j|j S|SNtypedatetimedateyearmonthdayvalues rprocessz'_MSDate.bind_processor..process8E{hmm+((U[[%))LL rrrdialectrs rbind_processorz_MSDate.bind_processor  rz(\d+)-(\d+)-(\d+)cfd}|S)Nc Tt|tjr|jSt|trgjj |}|st d|dtj|jDcgc]}t|xsdc}S|Scc}w)Ncould not parse z as a date valuer) isinstancerrstr_regmatch ValueErrorgroupsintrmxrs rrz)_MSDate.result_processor..process%!2!23zz|#E3'IIOOE*$@EG }}AHHJ&Gqs16{&GHH 'H B%rrrcoltypers` rresult_processorz_MSDate.result_processor rN)rrrr recompiler'r3rrrrrs 2::* +DrrcxeZdZdfd Zej dddZdZejdZ dZ xZ S)TIMEc 0||_t| yr)rrr)rrkwargsrs rrz TIME.__init__s" rilrcfd}|S)Nct|tjr:tjjj|j }|St|tjr t |}|Sr)r%rcombine_TIME__zero_datetimer&)rrs rrz$TIME.bind_processor..processsf%!2!23 ))11$$ejjlL E8==1E Lrrrs` rr zTIME.bind_processors rz!(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?cfd}|S)Nc Tt|tjr|jSt|trgjj |}|st d|dtj|jDcgc]}t|xsdc}S|Scc}w)Nr$z as a time valuer) r%rr?r&r'r(r)r*r+r,s rrz&TIME.result_processor..process,r/r0rr1s` rr3zTIME.result_processor+r4rr) rrrrrrr>r r5r6r'r3rrs@rr8r8s; (--a+K 2::: ;Drr8ceZdZdZy) _BASETIMEIMPLNr rrrrCrC?$NrrCceZdZdZy) _DateTimeBasec d}|S)Nct|tjk(r5tj|j|j|j S|Srrrs rrz-_DateTimeBase.bind_processor..processErrrrs rr z_DateTimeBase.bind_processorDr!rN)rrrr rrrrFrFCsrrFc eZdZy) _MSDateTimeNrrrrrrrJrJNrrJceZdZdZy) SMALLDATETIMENr rrrrNrNRrDrrNc$eZdZdZdfd ZxZS) DATETIME2c 2t|di|||_yNrrrrrrrrs rrzDATETIME2.__init__Y 2"rrrrrr rrrs@rrPrPVs N##rrPc$eZdZdZdfd ZxZS)DATETIMEOFFSETc 2t|di|||_yrRrSrTs rrzDATETIMEOFFSET.__init__arUrrrVrs@rrXrX^s%N##rrXceZdZdZy)_UnicodeLiteralcfd}|S)Nc|jdd}jjr|jdd}d|zS)N'''%z%%zN'%s')replaceidentifier_preparer_double_percents)rrs rrz2_UnicodeLiteral.literal_processor..processhs<MM#t,E**;; c40U? "rrrs ` rliteral_processorz!_UnicodeLiteral.literal_processorgs #rN)rrrrdrrrr[r[fs rr[c eZdZy) _MSUnicodeNrKrrrrfrfsrLrrfc eZdZy)_MSUnicodeTextNrKrrrrhrhwrLrrhc2eZdZdZdZdZddZfdZxZS) 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` Nc||_y)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)rrls rrzTIMESTAMP.__init__s 'rcPt||||jrfd}|SS)Nc`r|}| ttj|dd}|S)Nhex)r+codecsencode)rsuper_s rrz+TIMESTAMP.result_processor..processs1"5ME$ eU ;R@E r)rr3rl)rrr2rrsrs @rr3zTIMESTAMP.result_processors.)'7;    NMrF) rrrrr lengthrr3rrs@rrjrj{s% !NF 'rrjceZdZdZdZy) 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` Nrrrrr rrrrwrws("NrrwceZdZdZdZy)NTEXTzMMSSQL NTEXT type, for variable-length unicode text up to 2^30 characters.NrxrrrrzrzsNrrzc(eZdZdZdZdfd ZxZS) 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` cj||_|jr|dvr tdt| |y)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 )Nmaxz4length must be None or 'max' when setting filestreamruN) filestreamr)rr)rrurrs rrzVARBINARY.__init__s< % ??v]:F  'r)NF)rrrrr rrrs@rr|r|s !N((rr|ceZdZdZy)IMAGENr rrrrrNrrceZdZdZdZy)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". NrxrrrrrsNrrceZdZdZdZy)BITzMSSQL BIT type. Both pyodbc and pymssql return values from BIT columns as Python so just subclass Boolean. NrxrrrrrsNrrceZdZdZy)MONEYNr rrrrrrrrceZdZdZy) SMALLMONEYNr rrrrrs!NrrceZdZdZdZy)MSUUidcH|jry|jrd}|Sd}|S)Nc"| |j}|Srrors rrz&MSUUid.bind_processor..processs( %  LrcN|"|jddjdd}|S)N-r_r^rars rrz&MSUUid.bind_processor..process's*( % c2 6 > >tS I Lr native_uuidas_uuidrs rr zMSUUid.bind_processors/   ||! ! rcP|jrd}|S|jrd}|Sd}|S)Nc@dt|jdddS)Nr^r_)r&rars rrz)MSUUid.literal_processor..process1s#SZ//c:;1??rc"d|jdS)Nr^rrs rrz)MSUUid.literal_processor..process8s  1//rcNd|jddjdddS)Nr^rrr_rrs rrz)MSUUid.literal_processor..process>s2  c2.66sDA!rrrs rrdzMSUUid.literal_processor.s7    @N||0 rN)rrrr rdrrrrrs .rrcReZdZdZe d ddZe d ddZdd dZy) UNIQUEIDENTIFIERcyrrrrs rrzUNIQUEIDENTIFIER.__init__I rcyrrrs rrzUNIQUEIDENTIFIER.__init__Nrrc ||_d|_y)aConstruct 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)rrrs rrzUNIQUEIDENTIFIER.__init__Ss rN).)rzUNIQUEIDENTIFIER[_python_UUID]rz Literal[True])rzUNIQUEIDENTIFIER[str]rzLiteral[False])T)rbool)rrrr rrrrrrrFsX'N GJ , 7D  ?B # .<   rrceZdZdZy) SQL_VARIANTNr rrrrrds"Nrrr+bigintsmallinttinyintvarcharnvarcharcharncharrntextdecimalnumericfloatr datetime2datetimeoffsetr)r? smalldatetimebinary varbinarybitrealzdouble precisionimagexml timestampmoney smallmoneyuniqueidentifier sql_variantceZdZd$dZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"fd!Z#d"Z$d#Z%xZ&S)%MSTypeCompilerct|ddrd|jz}nd}|s |j}|r|d|zz}dj||fDcgc]}|| c}Scc}w)zYExtend a string-type declaration with standard SQL COLLATE annotations. collationNz COLLATE %s(%s) )getattrrrurd)rspectype_rurcs r_extendzMSTypeCompiler._extendsf 5+t ,$u6II\\F &6/)DxxT9$5GqGHHGs AAc (|j|fi|Sr)visit_DOUBLE_PRECISIONrrrs r visit_doublezMSTypeCompiler.visit_doubles*t**57B77rc 0t|dd}|ydd|izS)Nrr*zFLOAT(%(precision)s)rrrrrs r visit_FLOATzMSTypeCompiler.visit_FLOATs)E;5  )[),DD Drc y)Nr rrs r visit_TINYINTzMSTypeCompiler.visit_TINYINTsrc ,t|dd}|d|zSy)NrzTIME(%s)r8rrs r visit_TIMEzMSTypeCompiler.visit_TIMEs$E;5   ) )rc y)Nrjrrs rvisit_TIMESTAMPzMSTypeCompiler.visit_TIMESTAMPrc y)Nrwrrs rvisit_ROWVERSIONzMSTypeCompiler.visit_ROWVERSIONrc f|jr|j|fi|S|j|fi|Sr)timezonevisit_DATETIMEOFFSETvisit_DATETIMErs rvisit_datetimezMSTypeCompiler.visit_datetimes9 >>,4,,U9b9 9&4&&u33 3rc @t|dd}|d|jzSy)NrzDATETIMEOFFSET(%s)rX)rrrs rrz#MSTypeCompiler.visit_DATETIMEOFFSETs(E;5  '%//9 9#rc ,t|dd}|d|zSy)Nrz DATETIME2(%s)rPrrs rvisit_DATETIME2zMSTypeCompiler.visit_DATETIME2s$E;5  "Y. .rc y)NrNrrs rvisit_SMALLDATETIMEz"MSTypeCompiler.visit_SMALLDATETIMEsrc (|j|fi|Sr)visit_NVARCHARrs r visit_unicodezMSTypeCompiler.visit_unicodes"t""5/B//rc z|jjr|j|fi|S|j|fi|Sr)rdeprecate_large_types visit_VARCHAR visit_TEXTrs r visit_textzMSTypeCompiler.visit_texts= << - -%4%%e2r2 2"4??5/B/ /rc z|jjr|j|fi|S|j|fi|Sr)rrr visit_NTEXTrs rvisit_unicode_textz!MSTypeCompiler.visit_unicode_texts? << - -&4&&u33 3#4##E0R0 0rc &|jd|S)Nrzrrs rrzMSTypeCompiler.visit_NTEXT||GU++rc &|jd|S)Nr0rrs rrzMSTypeCompiler.visit_TEXT||FE**rc F|jd||jxsdS)Nr1r~rrrurs rrzMSTypeCompiler.visit_VARCHARs ||IuU\\5JU|KKrc &|jd|S)Nr&rrs r visit_CHARzMSTypeCompiler.visit_CHARrrc &|jd|S)Nr,rrs r visit_NCHARzMSTypeCompiler.visit_NCHARrrc F|jd||jxsdSNr.r~rrrs rrzMSTypeCompiler.visit_NVARCHARs ||Jell6Ke|LLrc |jjtkr|j|fi|S|j|fi|Sr)rserver_version_infoMS_2008_VERSIONr visit_DATErs r visit_datezMSTypeCompiler.visit_date B << + +o =&4&&u33 3"4??5/B/ /rc (|j|fi|Sr) visit_timers rvisit__BASETIMEIMPLz"MSTypeCompiler.visit__BASETIMEIMPLstu+++rc |jjtkr|j|fi|S|j|fi|Sr)rrrrrrs rrzMSTypeCompiler.visit_timerrc z|jjr|j|fi|S|j|fi|Sr)rrvisit_VARBINARY visit_IMAGErs rvisit_large_binaryz!MSTypeCompiler.visit_large_binarys? << - -'4''44 4#4##E0R0 0rc y)Nrrrs rr zMSTypeCompiler.visit_IMAGErc y)Nrrrs r visit_XMLzMSTypeCompiler.visit_XML!rc n|jd||jxsd}t|ddr|dz }|S)Nr|r~rrFz FILESTREAM)rrur)rrrrs rr zMSTypeCompiler.visit_VARBINARY$s:||Ku||7Lu|M 5, . M !D rc $|j|Sr) visit_BITrs r visit_booleanzMSTypeCompiler.visit_boolean*s~~e$$rc y)Nrrrs rrzMSTypeCompiler.visit_BIT-rrc *|jd|dSrrrs r visit_JSONzMSTypeCompiler.visit_JSON0s||Je|<.decoratesL||22$++++ }d!;R[[Is)b))rr)ryrzrs` r_with_legacy_schema_aliasingz*MSSQLCompiler._with_legacy_schema_aliasings *rc y)NCURRENT_TIMESTAMPrrryrs rvisit_now_funczMSSQLCompiler.visit_now_funcs"rc y)Nz GETDATE()rr~s rvisit_current_date_funcz%MSSQLCompiler.visit_current_date_funcrrc .d|j|fi|zSNzLEN%sfunction_argspecr~s rvisit_length_funczMSSQLCompiler.visit_length_func  ...r8R888rc .d|j|fi|zSrrr~s rvisit_char_length_funcz$MSSQLCompiler.visit_char_length_func rrc |jjdj|fi|}d|d<|jjdj|fi|}d|d|dS)NrTrrrz string_agg(, ))clauses_compiler_dispatch)rryrexpr delimeters rvisit_aggregate_strings_funcz*MSSQLCompiler.visit_aggregate_strings_funcsn7rzz!!!$77CC $ zFMSSQLCompiler.visit_concat_op_expression_clauselist..s!Jt,$,,t2r2Js rd)r clauselistoperatorrs` `r%visit_concat_op_expression_clauselistz3MSSQLCompiler.visit_concat_op_expression_clauselistszzJzJJJrc ||j|jfi|d|j|jfi|S)Nrrrfrrrrrs rvisit_concat_op_binaryz$MSSQLCompiler.visit_concat_op_binarys: DLL + + DLL , ,  rc y)N1rrrrs r visit_truezMSSQLCompiler.visit_true!rc y)N0rrs r visit_falsezMSSQLCompiler.visit_false$rrc d|j|jfi|d|j|jfi|dS)Nz CONTAINS (rrrrs rvisit_match_op_binaryz#MSSQLCompiler.visit_match_op_binary's: DLL + + DLL , ,  rc $t||fi|}|jrr|j|rad|d<|d|j|j |fi|zz }|j (|jdr|dz }|jdr|dz }|S)z+MS-SQL puts TOP, it's version of LIMIT hereTrrzTOP %s rzPERCENT with_tiesz WITH TIES )rget_select_precolumns_has_row_limiting_clause_use_topr_get_limit_or_fetch _fetch_clause_fetch_clause_options)rrrsrs rrz#MSSQLCompiler.get_select_precolumns-s G )& 7B 7  * *t}}V/D%)B ! \T\\((046 A##/// :OA// <%Arc|Srrrrrs rget_from_hint_textz MSSQLCompiler.get_from_hint_textB rc|Srrrs rget_crud_hint_textz MSSQLCompiler.get_crud_hint_textErrcJ|j |jS|jSr)r _limit_clauserrs rrz!MSSQLCompiler._get_limit_or_fetchHs&    ''' ''' 'rc|jduxrZ|j|jxs=|j|jxr |jdxs|jdS)Nrr)_offset_clause_simple_int_clauserrrrs rrzMSSQLCompiler._use_topNsp%%-   % %f&:&: ;  ))&*>*>?00;A33K@ rc yNrr)rcsr:s r limit_clausezMSSQLCompiler.limit_clause]src|jjstjd|j4|jds|jdrtjdyy)NzLMSSQL requires an order_by when using an OFFSET or a non-simple LIMIT clauserrz^MSSQL needs TOP to use PERCENT and/or WITH TIES. Only simple fetch without offset can be used.)_order_by_clauserr CompileErrorrrs r_check_can_use_fetch_limitz(MSSQLCompiler._check_can_use_fetch_limit`sx&&..""   ' ' 3  ( ( 3++K8""@ 9 4rc |jjrG|j|s6|j||j|f|j |dd|Sy)zdMSSQL 2012 supports OFFSET/FETCH operators Use it instead subquery with row_number T) fetch_clauserequire_offsetr)r_supports_offset_fetchrrrrrrrs r_row_limit_clausezMSSQLCompiler._row_limit_clausessg << . .t}}V7L  + +F 3$4$$!55f=#  rc d|j|jfi|d|j|jfi|dS)Nz TRY_CAST (z AS r)rclause typeclause)relementrs rvisit_try_castzMSSQLCompiler.visit_try_casts< DLL .2 . DLL++ 2r 2  rc |}|jr|jjs|j|st |ddsz|j ||j jDcgc]}tj|}}|j|}|j}|j}d|_ |jtj j#j%|j'dj)dj+}tj,d}tj.|j0D cgc]} | j2dk7s| c} } |/| j5||kD} || j5|||zk} | S| j5||k} | S|Scc}wcc} w)zLook 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_visitNT)order_bymssql_rn)rrrrrrrrsql_utilunwrap_label_referencerr _generater add_columnsrr ROW_NUMBERrklabelraliasrrrrNr) r select_stmtr:rr_order_by_clausesr offset_clauserr limitselects rtranslate_select_structurez(MSSQLCompiler.translate_select_structures   + +LL77MM&)FND9  + +F 3#33;;!//5! !  33F;L"11M%%'F"&F ""HH'')T#4T5U:& $ zz*-H**#XX=*)s0GG2Gc ||us|rt||fi|S|j|}||j|fd|i|St||fi|SN mssql_aliased)r visit_table_schema_aliased_tabler)rrriscrudr:rrs rrzMSSQLCompiler.visit_tablesj E !V7&u77 7**51  4<<EUEfE E7&u77 7rc B|j|d<t||fi|Sr)rr visit_alias)rrrrs rrzMSSQLCompiler.visit_aliass($mm?w"5/B//rc |j|js |jr|jr|j |j}|ht j ||}|@||j|j||j|jf|jt|,|fi|St|,|fd|i|S)Nadd_to_result_map) rrDrE is_subqueryrr_corresponding_column_or_errornamerNrr visit_column)rrrrt convertedrs rrzMSSQLCompiler.visit_columns LL $]]4==!**6<<8A}$CCAvN $0%  fjj9 w+I<<<w#  &7 ;=  rct|dd:||jvr|j|j|<|j|Sy)Nr)rror)rrs rrz#MSSQLCompiler._schema_aliased_tablesI 5(D ) 5D---+0;;=!!%($$U+ +rc |jj|j|j}d|d|j|jfi|dS)Nz DATEPART(rr) extract_mapgetfieldrr)rextractrrs r visit_extractzMSSQLCompiler.visit_extractsA  $$W]]GMMB%*LDLL,L,LMMrc >d|jj|zS)NzSAVE TRANSACTION %sr(format_savepointrsavepoint_stmtrs rvisit_savepointzMSSQLCompiler.visit_savepoints#$t}}'E'E (   rc >d|jj|zS)NzROLLBACK TRANSACTION %srrs rvisit_rollback_to_savepointz)MSSQLCompiler.visit_rollback_to_savepoints#(4==+I+I ,   rc zt|jtjr|jtj k(rjt|j tjsF|jtj|j |j|jfi|St|(|fi|S)z]Move bind parameters to the right-hand side of an operator, where possible. ) r%rfr BindParameterreqrrBinaryExpressionr visit_binary)rrr:rs rrzMSSQLCompiler.visit_binary s v{{J$<$< =8;;.v||Z-E-EF4<<++LL&++v   w#F5f55rc |js |jr|jjd}n/|jr|jjd}nJdt j |}|jdtj|D cgc]5\}}} } } |j||j| |d| fif| | ||d|7} } } }}} dd j| zScc} } } }}w) Ninserteddeletedz+expected Insert, Update or Delete statementT)colsresult_map_targets)fallback_label_namecolumn_is_repeatedr proxy_namezOUTPUT r) is_insert is_updaterr is_deleter ClauseAdapter_generate_columns_plus_namesr_select_iterables_label_returning_columntraverserd) rstmtreturning_colspopulate_result_maprtargetadapterrr r rrepeatedcolumnss rreturning_clausezMSSQLCompiler.returning_clause s >>T^^ZZ%%j1F ^^ZZ%%i0F GG G5((0822:77G3%  #! )D ( (  (#%y1  %8#+%    .499W---/ s%:C9 cy)NWITHr)r recursives rget_cte_preamblezMSSQLCompiler.get_cte_preambleF s rc|t|tjr|jdSt||||Sr)r%rFunctionrrlabel_select_column)rrrasfromrs rr$z!MSSQLCompiler.label_select_columnM s6 fj11 2<<% %7.vvvF Frc yrrrs rfor_update_clausezMSSQLCompiler.for_update_clauseS src |jr4|j|s#|j|jjsy|j |j fi|}|rd|zSy)Nrz ORDER BY )rr_offsetrrrr)rrrrs rorder_by_clausezMSSQLCompiler.order_by_clauseX sd    MM&)&||:: 4<< 7 7>2> (* *rc Nddjfd|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 rc3JK|]}|jfddywT)r% fromhintsNrrr from_hintsrrs rrz3MSSQLCompiler.update_from_clause..{ 2#  !A  Odj OB O#  #r)r update_stmt from_table extra_fromsr2rs` ``rupdate_from_clausez MSSQLCompiler.update_from_clauseq s1#  \K/#    rc <d}|rd}|j|fdd|d|S)z=If we have extra froms make sure we render any alias as hint.FT)r%rashintr0)r delete_stmtr6r7rr:s rdelete_table_clausez!MSSQLCompiler.delete_table_clause s; F,z,,  d6 =?  rc Nddjfd|g|zDzS)zjRender the DELETE .. FROM clause specific to MSSQL. Yes, it has the FROM keyword twice. r,rc3JK|]}|jfddywr.r0r1s rrz9MSSQLCompiler.delete_extra_from_clause.. r3r4r)rr;r6r7r2rs` ``rdelete_extra_from_clausez&MSSQLCompiler.delete_extra_from_clause s1#  \K/#    rc y)NzSELECT 1 WHERE 1!=1rrs rvisit_empty_set_exprz"MSSQLCompiler.visit_empty_set_expr s$rc xd|j|jd|j|jdS)NzNOT EXISTS (SELECT  INTERSECT SELECT rrrs rvisit_is_distinct_from_binaryz+MSSQLCompiler.visit_is_distinct_from_binary , LL % LL &  rc xd|j|jd|j|jdS)NzEXISTS (SELECT rCrrrs r!visit_is_not_distinct_from_binaryz/MSSQLCompiler.visit_is_not_distinct_from_binary rErc F|jjtjur?d|j|j fi|d|j|j fi|dSd|j|j fi|d|j|j fi|d}|jjtjurAd|j|j fi|d|j|j fi|d}n|jjtjurd|j|j fi|d|j|j fi|dt|jtjrd n0d |jjd|jjdd}n|jjtjurd }n|jjtjur@d |j|j fi|d|j|j fi|d}n?d |j|j fi|d|j|j fi|d}|dz|zdzS)Nz JSON_QUERY(rrzCASE JSON_VALUE(z) WHEN NULL THEN NULLzELSE CAST(JSON_VALUE(z ) AS INTEGER)z) AS r*zNUMERIC(z0WHEN 'true' THEN 1 WHEN 'false' THEN 0 ELSE NULLzELSE JSON_VALUE(zELSE JSON_QUERY(rz END)r_type_affinityrr rrfrIntegerNumericr%FloatrscaleBooleanString)rrrrcase_expressiontype_expressions r _render_json_extract_from_binaryz.MSSQLCompiler._render_json_extract_from_binary s4 ;; % % 6 V[[/B/ V\\0R0  7 DLL + + DLL , ,  ;; % %)9)9 9 V[[/B/ V\\0R0O[[ ' '8+;+; ; V[[/B/ V\\0R0"&++x~~>>{{,,fkk.?.?AA O[[ ' '8+;+; ;C [[ ' '8?? :  V[[/B/ V\\0R0O ; V[[/B/ V\\0R0O $6??rc *|j||fi|SrrRrs rvisit_json_getitem_op_binaryz*MSSQLCompiler.visit_json_getitem_op_binary 4t44VXLLLrc *|j||fi|SrrTrs r!visit_json_path_getitem_op_binaryz/MSSQLCompiler.visit_json_path_getitem_op_binary rVrc >d|jj|zS)NzNEXT VALUE FOR %s)r(r[)rr\rs rvisit_sequencezMSSQLCompiler.visit_sequence s"T]]%B%B3%GGGr)FFr)8rrrreturning_precedes_valuesr update_copyr SQLCompilerrrrsr{rrrrrrrrrrrrrrrrrrrrrrrrrrrrrr!r$r'r*r8r<r?rArDrGrRrUrXrZrrs@rreresX $"$""(())  K*:#992 K   *(  && 2h" 8" 8"0"0 " " 0N  6$1.fG  2     %  6@pMMHrrec2eZdZdZdZdZdZfdZxZS)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)NTrrz IN rrs rvisit_in_op_binaryz&MSSQLStrictCompiler.visit_in_op_binary E $  DLL + + DLL , ,  rc d|d<|j|jfi|d|j|jfi|S)NTrrz NOT IN rrs rvisit_not_in_op_binaryz*MSSQLStrictCompiler.visit_not_in_op_binary rbrctt|tjrdt |zdzSt |||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. r^) issubclassrrrr&rrender_literal_value)rrrrs rrgz(MSSQLStrictCompiler.render_literal_value s= d5k8== 1U#c) )7/u= =r) rrrransi_bind_rulesrardrgrrs@rr_r_ s#O  >>rr_cbeZdZdZd dZdZdZdZdZdZ dZ d Z d Z fd Z d ZxZS) MSDDLCompilerc b|jj|}|j"|d|j|jzz }n7|d|jj j|j |zz }|jm|jrJ|js>t|jtjs|jdus |jr|dz }n|j|dz }|jt!j"d|j$d}|d}|d }||7|jrt!j"d t'j(d d |jr"||j|jfi|z }|S||jj*us|jdurQt|jtr|jj,r!||jt/|| z }|S|j1|}||d|zz }|S)Nr)rQTz NOT NULLz NULLz;mssql requires Table-bound columns in order to generate DDLmssqlidentity_startidentity_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.4start incrementz DEFAULT )r( format_columncomputedrrtype_compiler_instancernullable primary_keyr%rr_r autoincrementrrr rdialect_optionsrwarn_deprecatedr1rarget_column_default_string)rrr:colspecd_optrqrrrs rget_column_specificationz&MSDDLCompiler.get_column_specification s----f5 ?? & sT\\&//:: :G sT\\@@HH VI G ?? &OO%%fnni.@.@A''4/??;&(7" << ""+  &&w/&'./   5&&,  5   ?? |t||FOO>v> >G fll88 8##t+6>>848O8O t||H5I$NO OG  44V.o s8(!!))T*(s(+includez INCLUDE (%s)rFTrz WHERE )r_verify_index_tabler(rry_prepared_index_namer=rlen expressionsrdr%r&rquoterrexpectrDDLExpressionRolerr)rrrrrr(rrrcol inclusionsr whereclausewhere_compileds` rvisit_create_indexz MSDDLCompiler.visit_create_indexS s   '== << I D))'2;?   $'++G4]C  N "D  % %eN % K  ! !%++ .   u  !A % Gdii("-- ( D   )) 4!009)D'1c&: c"CJ Odii1;. )# ,-DMM   '# /2)rrr(format_constraintryrddefine_constraint_deferrability)rrrrrs` rvisit_primary_key_constraintz*MSDDLCompiler.visit_primary_key_constraint s z?a  ?? & $t}}'F'F( D ..w7 D   $' # 1;#     44Z@@ rc ht|dk(ryd}|j%jj|}||d|zz }|dj|fi|zz }|j dd}| |r|dz }n|dz }|d d j fd |Dzz }|j|z }|S) Nrrrz UNIQUE %srlrrrrrc3hK|])}jj|j+ywrrrs rrz8MSDDLCompiler.visit_unique_constraint.. rr)rrr(r!define_unique_constraint_distinctryrdr)rrrrformatted_namers` rvisit_unique_constraintz%MSDDLCompiler.visit_unique_constraint s z?a  ?? &!]]<99 DdDD     ..w7 D   $' # 1;#     44Z@@ rc d|jj|jddz}|jdur|dz }|S)NzAS (%s)FTrz PERSISTED)rrsqltext persisted)r generatedrrs rvisit_computed_columnz#MSDDLCompiler.visit_computed_column sP4,,44   U$5     $ & L D rc |jj|j}|r|n|jj}dj |j j|jjtj|jj||jj|jdS)NzNexecute sp_addextendedproperty 'MS_Description', {}, 'schema', {}, 'table', {}F use_schema) r(schema_for_objectrrdefault_schema_nameformatrrgcommentrr. quote_schemar=rrrr schema_names rvisit_set_table_commentz%MSDDLCompiler.visit_set_table_comment s00@ &fDLL,L,L  ,,2F!!66NN**H,=,=,? **;7 **6>>e*L - rc  |jj|j}|r|n|jj}dj |jj ||jj|jdS)NzKexecute sp_dropextendedproperty 'MS_Description', 'schema', {}, 'table', {}Fr)r(rrrrrrr=rrZrrrs rvisit_drop_table_commentz&MSDDLCompiler.visit_drop_table_comment sn00> &fDLL,L,L  $f **;7 **4<> # # /00I 2 2 : :9 EEFw,VIFIbIIrc d}|j |j@|jdn |j}|jdn |j}|d|d|dz }|S)Nz IDENTITYr(,rrp)rrrrrqrrs rvisit_identity_columnz#MSDDLCompiler.visit_identity_column s\ >> %););)G!/AX^^E%//7X=O=OI  2 2D rrt)rrrr~rrrrrrrrrrrrrs@rrjrj sB=~:x .0     "  Jrrjc6eZdZeZfdZdZdZddZxZ S)MSIdentifierPreparerc,t||dddy)N[]F) initial_quote final_quotequote_case_sensitive_collations)rr)rrrs rrzMSIdentifierPreparer.__init__ s!  ,1  rc&|jddS)Nr]]rrrs r_escape_identifierz'MSIdentifierPreparer._escape_identifier s}}S$''rc&|jddS)Nrrrrs r_unescape_identifierz)MSIdentifierPreparer._unescape_identifier# s}}T3''rc|tjddt|\}}|r'|j|d|j|}|S|r|j|}|Sd}|S)z'Prepare a quoted table and schema name.zThe 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)version.r)rrz_schema_elementsr)rrforcedbnameownerresults rrz!MSIdentifierPreparer.quote_schema& s    !   )0   $ 6 2DJJu4EFF  ZZ&F F rr) rrrRESERVED_WORDSreserved_wordsrrrrrrs@rrr s#N ((rrc(dfd }t|S)Nc Ht||\}}t|||||||fi|Sr_owner_plus_db _switch_db)r connectionrrrrrys rwrapz$_db_plus_owner_listing..wrapB sB&w7             rrr2ryrs` r_db_plus_owner_listingrA s   $ ##rc(dfd }t|S)Nc Jt||\}}t||||||||f i|Srr)rr tablenamerrrrrys rrz_db_plus_owner..wrapT sE&w7              rrr2rs` r_db_plus_ownerrS s   $ ##rc|r[|jdj}||k7r7|jd|jjj |z ||i||r>|k7r8|jd|jjj |zSSS#|r>|k7r8|jd|jjj |zwwwxYw)Nzselect db_name()zuse %s)exec_driver_sqlscalarrrbr)rrryrxr current_dbs rrrf s //0BCJJL    & &:--AAGGOO 3~"~ jF*  & &$$88>>zJK +66jF*  & &$$88>>zJK +6s B''AC)c8|sd|jfSt|Sr)rr)rrs rrrw s! W0000''rct|tr|jrd|fS|tvr t|S|j drd|fSg}d}d}d}t j d|D]P}|s|dk(rd}d}|dk(rd}|s2|dk(r-|r|jd |zn|j|d}d}L||z }R|r|j|t|d kDradj|d d |d }}t jd |d d rt|d}n9|jdjd}nt|rd|d }}nd\}}||ft|<||fS)Nz __[SCHEMA_rFz (\[|\]|\.)rTrrz[%s]rrz .*\].*\[.*r)NN) r%rr_memoized_schema startswithr5splitappendrrdr(lstriprstrip)rpushsymbolbracket has_bracketstokenrrs rrr s&+&6<<V| !!''&V| D FGL-0  C<GL c\GUc\ FVO, F#F L eOF!" F 4y1}a,d2h 88M6!B< 0 u5F]]3'..s3F Td1g" %u}V 5=rceZdZdZdZdZdZdZdZdZ dZ e Z dZ dZdZdZdZdZdZdZej,eej0eej4eej4j6eej4j8eej:eej>e ejBe"e#e#e$e$e%e%e&e&ejNe(i Z)e*jVjXj[de.j^iZ,e0Z0dZ1dZ2dZ3dZ4dZ5dZ6dZ7dZ8dZ9dZ:e;jxe;jzze;j|zZ?dZ@dZAdZBdZCd ZDeEZFeGZHeIZJeKZLeMjd d ifeMjd d ifeMjd d d d d feMjd d d fgZR d+fd ZSfdZTdZUfdZVhdZWdZXdZYdZZfdZ[dZ\dZ]dZ^dZ_e`dZaebje`dZdebjeedZfebjdZgebjeedZhebjeed Ziebjd!Zjd"Zkebje`d#Zlebje`d$Zmebjd,d%Znd&Zod'Zpebje`d(Zqebje`d)Zrebje`d*ZsxZtS)-r$rlTFdborwri3rrN)rrrr)rmrnc  t|xsd|_||_||_||_| |_|x|_} | | |_|tjdd||_ t |0di| ||_ ||_y)Nrz[The legacy_schema_aliasing parameter is deprecated and will be removed in a future release.ror)r+ query_timeoutrrGr!ignore_no_transaction_on_rollback_user_defined_supports_commentssupports_commentsrrzrwrr_json_serializer_json_deserializer) rrrGrrrjson_serializerjson_deserializerrwroptsudsrs rrzMSDialect.__init__/ s!!3!4&"4%:" - .6GF,s ?%(D " ! -  F  +AD '  4 /"3rcH|jdt| ||y)Nz$IF @@TRANCOUNT = 0 BEGIN TRANSACTION)rr do_savepoint)rrrrs rrzMSDialect.do_savepointU s!""#IJ Z.rcyrr)rrrs rdo_release_savepointzMSDialect.do_release_savepointZ s rc t||y#|jj$rL}|jr5t j dt|rtjdnYd}~yd}~wwxYw)Nz .*\b111214\bz|ProgrammingError 111214 'No corresponding transaction found.' has been suppressed via ignore_no_transaction_on_rollback=True) r do_rollbackdbapiProgrammingErrorrr5r(r&rwarn)rdbapi_connectionrWrs rrzMSDialect.do_rollback^ sj  G  0 1zz** 55"((Q; = sA8AA33A8>READ COMMITTEDREPEATABLE READREAD UNCOMMITTEDSNAPSHOT SERIALIZABLEc,t|jSr)list_isolation_lookup)rrs rget_isolation_level_valuesz$MSDialect.get_isolation_level_valuesv sD**++rc|j}|jd||j|dk(r|jyy)Nz SET TRANSACTION ISOLATION LEVEL r)rrr|r)rrlevelrs rset_isolation_levelzMSDialect.set_isolation_levely sF!((*9%AB  J   # # % rc|j}d} |jdj||j}|s t dd|d}|jdj||j}|dj |j S#|jj$r!}t dj|||d}~wwxYw#|j wxYw)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.) rrrfetchoneNotImplementedErrorupperr|rError)rrr view_namerPerrs rget_isolation_levelzMSDialect.get_isolation_level s!((*& )  NNI&#   //#C)* s1vhI NN F ,//#Cq6<<> LLNzz %55;VC5K   LLNs*A%B,9"C),C&C!!C&&C))C;ct|||j|j||j |yr)r initialize_setup_version_attributes_setup_supports_nvarchar_max_setup_supports_comments)rrrs rr.zMSDialect.initialize s8 :& &&( ))*5 %%j1rc|jdttddvr8tjddj d|jDz|jt k\rd|_nd|_|j|jtk\|_|jxr|jdd k\|_ y) Nrr=z[Unrecognized server version info '%s'. Some SQL Server features may not function properly.rc32K|]}t|ywr)r&)rr.s rrz6MSDialect._setup_version_attributes.. sDa3q6DsTFr:) rrrangerrrdrsupports_multivalues_insertrMS_2012_VERSIONrrSs rr/z#MSDialect._setup_version_attributes s  # #A &d5B<.@ @ II6((D4+C+CDDE   # # 6/3D ,/4D ,  % % -((O;  &  $ $ J)A)A!)D)J #rc |jtjdd|_y#tj $r d|_YywxYw)Nz0SELECT CAST('test max support' AS NVARCHAR(max))TF)rrr_supports_nvarchar_maxr DBAPIErrorrrs rr0z&MSDialect._setup_supports_nvarchar_max sI /   KL  +/D '~~ 0*/D ' 0s$.A  A c|jy |jtjdd|_y#t j $r d|_YywxYw)NzdSELECT 1 FROM fn_listextendedproperty(default, default, default, default, default, default, default)TF)rrrrrr r:r;s rr1z"MSDialect._setup_supports_comments s\  / / ;  *   1 &*D "~~ +%*D " +s$;AActjd}|j|}| t|dS|jS)NzSELECT schema_name()Tr)rrrrr)rrqueryrs r_get_default_schema_namez"MSDialect._get_default_schema_name sD/0(//6  *2$? ?## #rc N|j||j|||fi|Sr)_ensure_has_table_connection_internal_has_table)rrrrrrrs r has_tablezMSDialect.has_table s, ))*5't'' IuKKKrc Ztj}tj|jj j |jj |k(}|r(|j |jj|k(}|j|} | jduSr) ischema sequencesrrr sequence_namersequence_schemarfirst) rr sequencenamerrrrrFrrs r has_sequencezMSDialect.has_sequence s %% JJy{{00 1 7 7 KK % % 5   33u<=A   q !wwy$$rc tj}tj|jj }|r(|j |jj|k(}|j|}|D cgc]} | d c} Scc} wNr) rErFrrrrGrrHr) rrrrrrrFrrrPs rget_sequence_nameszMSDialect.get_sequence_names so%% JJy{{00 1  33u<=A   q !"#$3A$$$s9 Bc "tjtjjj j tjjj }|j|Dcgc]}|d }}|Scc}wrM)rrrEschematarrrr)rrrrr schema_namess rget_schema_nameszMSDialect.get_schema_names sq JJw''))55 6 ? ?      * * '1&8&8&;<!< <=s< B c tj}tj|jj j tj|jj|k(|jjdk(j|jj }|j|Dcgc]}|d } }| Scc}w)N BASE TABLEr rEtablesrrr table_namerand_ table_schema table_typerr) rrrrrrrWrrQ table_namess rget_table_nameszMSDialect.get_table_names s JJvxx** + UHH))U2HH''<7 Xfhh)) * &0%7%7%:;qt; ;< Cc tj}tj|jj j tj|jj|k(|jjdk(j|jj }|j|Dcgc]}|d } }| Scc}w)NVIEWrrV) rrrrrrrWrrQ view_namess rget_view_nameszMSDialect.get_view_names- s JJvxx** + UHH))U2HH''61 Xfhh)) * %/$6$6q$9:qad: :;r^c ||jdr*t|jtddd|diStj }t j|jjjt jt j|jjdk(|jjdk(|jj|k(}|r(|j|jj|k(}|j|}|j!duS)N#z"SELECT object_id(:table_name, 'U')rXz tempdb.dbo.[rrUr`)rrrrrErWrrrrXrrYor_r[rZrrI)rrrrrrWrrs rrBzMSDialect._internal_has_table> s    $!!=>!\)A#>? ^^F 688../55GG++|;++v5HH''94 AGGFHH11U:;""1%A779D( (rc n|j|||fi|r|Stj|d|)Nr)rBr NoSuchTableError)rrrrmethodrs r_default_or_errorzMSDialect._default_or_error^ s> #4 # #J 5 GB G8O&&%)'=> >rc |jtk\rdnd}|jdjt j d|dj t jd|tjt jd|tjjtj }i} |jD]P} | d | d d k(ggid x| | d<} | d} | d} | dvr| d k(| d<| dvr | dk(| d<d| d<| dI| d| d<R|jdjt j dj t jd|tjt jd|tjjtj }|jD]u} | d| vr | | d}|djd}|djd}|r|r@| dr|s|dj| d _|dj| d w| j!D] }|d|dd<| rt#| j!S|j$|||t&j(fi|S)Nzind.filter_definitionzNULL as filter_definitionT future_resultzM select ind.index_id, ind.is_unique, ind.name, ind.type, a+ 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 tabnameschname)rr is_uniquer)rr column_namesinclude_columnsryindex_idryr>rmssql_clustered>rumssql_columnstorefilter_definition mssql_wherea select ind_col.index_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 = :schname order by ind_col.index_id, ind_col.key_ordinal is_included_columnrqrp mssql_include)rrexecution_optionsrrr bindparams bindparamrE CoerceUnicoderrUnicodemappingsrrrrririndexes)rrrrrrrrxrprrPrdo index_type index_def is_colstore is_clustered index_infos r get_indexeszMSDialect.get_indexese s ''?: $,   ) ) ) = E E HH   .Z iG4I4I4KL i0E0E0GHW(**,W -9 <;;= =CF k*a/ "#%#% 2 GC O $w*+BVJV#(2a$%V#(2a$%*.&'&'3$'(;$<=!# =& ) ) ) = E E HH .Z iG4I4I4KL i0E0E0GHW(**,W -9 <;;= BC:g-J0I#$56::;NOK$%67;;H!>J( )/ :  () ))4))Iu.@.H.HLN rc ^|jtjdjtjd|t j tjd|t j j}|r|Stj|d|)Nzselect 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=:schnameviewnamernr) rrrr}r~rErrr rg)rrrrrrrview_defs rget_view_definitionzMSDialect.get_view_definition s %% HHC  j j(G4I4I4KL i0E0E0GH   &(  O&&%('<= =rc |js td|r|n |j}d}|jt j |j t jd|tjt jd|tjj}|rd|iS|j||dtjfi|S)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; rrr)rr'rrrrr}r~rErrrir table_comment)rrrXrrr COMMENT_SQLrs rget_table_commentzMSDialect.get_table_comment s%%%O !'fD,D,D  $$ HH[ ! , , h W5J5J5LM gz73H3H3JK  &(  G$ $)4))"00    rc6||jdsdzSdzS)Nz##z [_][_][_]%r)r)rrs r_temp_table_name_like_patternz'MSDialect._temp_table_name_like_patterns."+"6"6t"<\  BD  rcR |jtjdd|j|ij S#t j $r}t jd|z|d}~wt j$r}t jd|z|d}~wwxYw)Nz_select table_schema, table_name from tempdb.information_schema.tables where table_name like :p1p1zFound 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.) rrrroner MultipleResultsFoundUnreflectableTableError NoResultFoundrg)rrrmenes r_get_internal_temp_table_namez'MSDialect._get_internal_temp_table_names  %%0 t99)DE ce '' --')23      &&H  s$AAB&A22B&B!!B&c Ttj}tj}tj} tj} tj } tj } |jd} | r|j||\}}|jj|g}|r+|jd|jj|| r|jddtjdj|}|jj|k(}|j r| jj"}n3t%j&| jj"t)d}t%j*|jj,|jj,|jj.|jj0|jj2|jj4| jj"|jj6|| jj8| jj:| jj<| jj>| jj@jCdjE|j||jjF|jjFk(jI| t%jJ| jj|jjLk(| jjN|jjPk(jI| t%jJ| jj|jjk(| jjP|jjPk(jI| t%jJ| jj|jjk(| jjP|jjPk(jI| t%jJ| jdd k(| jj,d k(|jj| jjRk(|jjP| jjTk(jW|jY|jjP}| rd d d ii}nd ii}|jZdi|j]|}g}|j_D]}||jj,}||jj,}||jj.d k(}||jj0}||jj2}||jj4}|| jj"}||jj6}||}|| jj8} || jj:}!|| jj<}"|| jj>}#|| jj@}$|j`jc|d}%i}&|%tdtfthjjfvr |dk7r|nd|&d<nP|%tltntpfvr|dk7r|nd|&d<|r/||&d<n)|%trtttvfvr|dk7r|dznd|&d<|r||&d<|%-tyjzd|d|dthj|}%nFt|%thjr$||&d<t|%thjs||&d<|%di|&}%||%|||!du|$d}'| | || d|'d<|!x|"|#i|'d<nnt|%thjrt|"}(t|#})n5t|%thjrt|"}(t|#})n|"}(|#})|(|)d|'d<|j|'|r|S|j|||tjfi|S)Nrdrtempdbrir)onclauseclassrMS_Descriptionr'sysz tempdb.sysrrurrszDid not recognize type 'z ' of column 'r^rrM)rrrvrrxr)rrrtrrpr)JrE sys_columns sys_typessys_default_constraintscomputed_columnsidentity_columnsextended_propertiesrrrbrrr object_idrdrr9 definitionrcastr.rr is_nullable max_lengthrrMcollation_name is_persisted is_identity seed_valueincrement_valuerr select_from user_type_id outerjoinrYdefault_object_idparent_column_id column_idmajor_idminor_idrrr|rr ischema_namesrMSBinary MSVarBinaryr LargeBinaryMSStringMSCharMSText MSNVarcharMSNCharMSNTextrrNULLTYPErfrKrLr% BigIntegerr+rJrrirr)*rrrrrrrrrr computed_cols identity_colsr is_temp_tableobject_id_tokensrrcomputed_definitionr exec_optsrr rPrrrvmaxlen numericprec numericscalerrrrrrmrnrr2r:cdictrqrrs* r get_columnszMSDialect.get_columns3s)) %% ")"A"A00 00 %99",,S1 #AAI  E9!44::9EF   # #At'?'?'E'Ee'L M   # #Ax 0NN388,<#=> !mm--:  & &"///"<"< #&((**HTN#  JJ ""    )) (( '' ##'))44 ,,#,,++**//#%%++11)<  [ % T$33;;++, Y'+--77"}}667+-->>"}}../Y!OO--1H1HH!OO--1H1HHY!OO--1H1HH!OO--1H1HHY#'))'2a7'))..2BBMM++/B/D/D/M/MMMM++/B/D/D/M/MM U;  Xkmm-- .q v /%1FGI/4I (J ( ( 59 5 = =a @::<\ C{}}))*D (()E;==445:H112Fkmm556K{}}223L133>>?GKMM889I01J};;*6w!+F+$"!,D!8" E%,*B)!-%j! &!)-?-G(*E*%!'8+>+>? #N 3$'(:$; #GX-=-=> #N 3$'(:$; .$6 "'%.)E*% KK y\ | K)4))Iu.@.H.HLN rc 4g}tj}tjjd} t j | j j|j j| j jtjtj| j jdz| j jzdjdjt j |j j| j jk(|j j| j jk(| j j"|k(| j j|k(j%|j j| j j&} |j)dj+| } d} d} | j-D]i}d||j jj.vs)|j1|d| #|| j jj.} | e|d} k|r|| d | id S|j2|||t4j6fi|S) NCrCnstIsClustKeyrTrkPRIMARY COLUMN_NAMErt)constrained_columnsrry)rE constraintskey_constraintsrrrr column_nameconstraint_typeconstraint_namerobjectpropertyrrZrrrYrXrordinal_positionr|rrrrrir pk_constraint)rrrrrrrpkeysTCrrrrrrPs rget_pk_constraintzMSDialect.get_pk_constraints/     # # ) )# . JJ$$####NN((3.1D1DD%  %' UDD((ACC,?,??DD%%)9)99CCNNi/CC$$- Xbdd**ACC,@,@ A) ,  ( (t ( < D DQ G ::< 7CC 4 4 9 9:: S/0"*&)!##*=*=*B*B&CO'#&~#6L  7 ','$5|#D  *4))"00    rc tdjtjd|t j tjd|t j j tjtjtjtjtjtjtjtj}tjd}|j|jD]} | \ } } } } } }}} }}|| }| |d<|dk7r||dd <|dk7r||dd <|d s||d <||| k7r|r|d z| z} | |d <|d|d}}|j| |j||rt|jS|j |||t"j$fi|S)NaWITH 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 AND NOT (index_info.table_schema = fk_info.table_schema AND index_info.table_name = fk_info.table_name) ORDER BY fk_info.constraint_schema, fk_info.constraint_name, fk_info.ordinal_position rr)constraint_schemarrZrXconstrained_columnreferred_table_schemareferred_table_namereferred_columncdgddgidS)N)rrreferred_schemareferred_tablereferred_columnsoptionsrrrrz,MSDialect.get_foreign_keys..s')#'"&$& rrz NO ACTIONronupdateondeleterrrrr)rr}rr~rErrrrr defaultdictrrHrrrrir foreign_keys)rrrrrrrrfkeysrQ_rfknmscolrschemartblrcolfkuprule fkdelrulerec local_cols remote_colss rget_foreign_keyszMSDialect.get_foreign_keys=s/ df NZ k9g6K6K6MN gug.C.C.EFW"*"2"2"4 ( 0 0 2%--/#++-#+#3#3#5&.&6&6&8$,$4$4$6 ( 0 0 2 Y r     ##A&**,' %A ,CCK;&-5Iz*K'-6Iz*'((,$%%')9"(3,"8-4C)*)*&'$J   d #   t $O' %R  ' ')4))"//    r) NTrNNNNNFr)urrrrsupports_statement_cachesupports_default_valuessupports_empty_insertfavor_returning_over_lastrowidreturns_native_bytesrsupports_default_metavaluer#execution_ctx_clsrGmax_identifier_lengthrinsert_returningupdate_returningdelete_returningupdate_returning_multifromdelete_returning_multifromrDateTimerJDaterr r r TimerCrrf UnicodeTextrhrXrPrNr(UuidrcolspecsrDefaultDialectengine_config_typesrrasboolrsupports_sequencessequences_optionaldefault_sequence_basesupports_native_boolean#non_native_boolean_check_constraintsupports_unicode_bindspostfetch_lastrowidr6use_insertmanyvalues!use_insertmanyvalues_wo_returningr" AUTOINCREMENTIDENTITYUSE_INSERT_FROM_SELECT"insertmanyvalues_implicit_sentinelinsertmanyvalues_max_parametersrr9rwrrestatement_compilerrj ddl_compilerrtype_compiler_clsrr(r_PrimaryKeyConstraintUniqueConstraintIndexr`construct_argumentsrrrrr r!r$r,r.r/r0r1r?rrCrcacherKrrNrSr]rbrBrirrrrrrrrrrs@rr$r$ s: D#"!%)"!&+K!%!% ; w t ##] ""L }*n9}( vH "00DDJJ !4;;/"M#*/'!#')-% %22 & / / 0 & = = >''+#"""& L&#H  ' '+t)<=  # #k4%89 OO!#      #4 @ ("#*/$4L/   ,&,\2  ,/*"$LL %%  % %    ))>?qqf>>(> 6MM^55nzzrr$)r __future__rrqrrr5typingrruuidr _python_UUIDrrrEjsonr r r r rrr_rrrrenginerrJrrengine.reflectionrrrrrrrrrr r sql._typingr! sql.compilerr" sql.elementsr#typesr$r%r&r'r(r)r*r+r,r-r.r/r0r1r3 util.typingr4sql.dmlr5sql.selectabler6MS_2017_VERSIONMS_2016_VERSIONMS_2014_VERSIONr7rMS_2005_VERSIONMS_2000_VERSIONrrrrJr rrr8_MSTimerCrFrrJrNrPrXr[rrfrrh_Binaryrjrwrzr|rrTextrrNr TypeEnginerrrr _UUID_RETURNrr MSDateTimeMSDateMSReal MSTinyIntegerMSTimeMSSmallDateTime MSDateTime2MSDateTimeOffsetrrrrrrrrMSImageMSBitMSMoney MSSmallMoneyMSUniqueIdentifier MSVariantrGenericTypeCompilerrDefaultExecutionContextr#r]rer_ DDLCompilerrjIdentifierPreparerrrrrrLRUCacherrrr$rrrrXsJX#   %+#' 3'#*8.""#-up8== x00 hhmm:'8=='T %D% -!2!2 %M8#4#4%# x00##]H$5$5#   ("2"2  _h&:&: -  -`""0H %(""H$8$8%(PH  (-- (  H  "$$"-X]]-` x}}X%:%:; <#(%%#     !           %    7  f  w  w    D  U  D  U w w  U    n! " D# $ "  (   (?  FbX11bJZ288Z2zHH((HD)>-)>XH((D)866)X$$$&"(!4==?7t~&&~r