관리-도구
편집 파일: base.cpython-311.pyc
� �܋f�d � � � d Z ddlZddlZddlZddlZddlmZ ddlmZ ddlm Z ddlm Z dd lmZ dd lm Z ddlmZ ddlmZ dd lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl mZ ddl mZ ddl mZ ddl mZ ddl mZ ddl mZ ddl mZ ddl mZ ddl mZ ddl 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.g d(�� � Z/ G d)� d*ej0 � � Z0 G d+� d,ej1 � � Z2 G d-� d.ej3 � � Z4 G d/� d0ej5 � � Z5e5Z6 G d1� d2e7� � Z8 G d3� d4e8ej9 � � Z: G d5� d6e8ej9 � � Z; G d7� d8e8ej9 � � Z< G d9� d:ej= � � Z> G d;� d<e7� � Z? G d=� d>e?ej@ � � ZA G d?� d@e?ejB � � ZC G dA� dBejD � � ZE G dC� dDeE� � ZF G dE� dFejB � � ZG G dG� dHejH ejI � � ZH G dI� dJejI � � ZJ G dK� dLejK � � ZL G dM� dNej= � � ZM G dO� dPej= � � ZN G dQ� dRej= � � ZO G dS� dTej= � � ZP G dU� dVej= � � ZQ G dW� dXejR jS � � ZT e'eTdY� � ZUe:ZVe4ZWe0ZXe2ZYe5ZZe;Z[e<Z\e>Z]e#Z^eGZ_e$Z`e!ZaeZbeZceZdeHZeeJZfeMZgeNZheOZiePZjeQZki dZe�d[e�d\e"�d]e2�d^e$�d_e!�d`e�dae�dbe#�dceG�dde�dee �dfe�dge�dhe<�die>�dje�e5e;eeHeMe0eJeLeEeNeOePeQdk� �Zl G dl� dmejm � � Zn G dn� doejo � � Zp G dp� dqejq � � Zr G dr� dser� � Zs G dt� duejt � � Zu G dv� dwejv � � Zwdx� Zxdy� Zydz� Zzd{� Z{ ej| � � Z}d|� Z~ G d}� d~ej � � Z�dS )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 <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 <http://technet.microsoft.com/en-us/library/ms187993.aspx>`_, the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL Server in a future release. SQLAlchemy normally relates these types to the :class:`.UnicodeText`, :class:`_expression.TextClause` and :class:`.LargeBinary` datatypes. In order to accommodate this change, a new flag ``deprecate_large_types`` is added to the dialect, which will be automatically set based on detection of the server version in use, if not otherwise set by the user. The behavior of this flag is as follows: * When this flag is ``True``, the :class:`.UnicodeText`, :class:`_expression.TextClause` and :class:`.LargeBinary` datatypes, when used to render DDL, will render the types ``NVARCHAR(max)``, ``VARCHAR(max)``, and ``VARBINARY(max)``, respectively. This is a new behavior as of the addition of this flag. * When this flag is ``False``, the :class:`.UnicodeText`, :class:`_expression.TextClause` and :class:`.LargeBinary` datatypes, when used to render DDL, will render the types ``NTEXT``, ``TEXT``, and ``IMAGE``, respectively. This is the long-standing behavior of these types. * The flag begins with the value ``None``, before a database connection is established. If the dialect is used to render DDL without the flag being set, it is interpreted the same as ``False``. * On first connection, the dialect detects if SQL Server version 2012 or greater is in use; if the flag is still at ``None``, it sets it to ``True`` or ``False`` based on whether 2012 or greater is detected. * The flag can be set to either ``True`` or ``False`` when the dialect is created, typically via :func:`_sa.create_engine`:: eng = create_engine("mssql+pymssql://user:pass@host/db", deprecate_large_types=True) * Complete control over whether the "old" or "new" types are rendered is available in all SQLAlchemy versions by using the UPPERCASE type objects instead: :class:`_types.NVARCHAR`, :class:`_types.VARCHAR`, :class:`_types.VARBINARY`, :class:`_types.TEXT`, :class:`_mssql.NTEXT`, :class:`_mssql.IMAGE` will always remain fixed and always output exactly that type. .. 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)�VARCHAR��update_wrapper)�public_factory)� )� )� )� )� )� )��add�all�alter�and�any�as�asc� authorization�backup�begin�between�break�browse�bulk�by�cascade�case�check� checkpoint�close� clustered�coalesce�collate�column�commit�compute� constraint�contains� containstable�continue�convert�create�cross�current�current_date�current_time�current_timestamp�current_user�cursor�database�dbcc� deallocate�declarer �delete�deny�desc�disk�distinct�distributed�double�drop�dump�else�end�errlvl�escape�except�exec�execute�exists�exit�external�fetch�file� fillfactor�for�foreign�freetext� freetexttable�from�full�function�goto�grant�group�having�holdlock�identity�identity_insert�identitycol�if�in�index�inner�insert� intersect�into�is�join�key�kill�left�like�lineno�load�merge�national�nocheck�nonclustered�not�null�nullif�of�off�offsets�on�open�opendatasource� openquery� openrowset�openxml�option�or�order�outer�over�percent�pivot�plan� precision�primary�print�proc� procedure�public� raiserror�read�readtext�reconfigure� references�replication�restore�restrict�return�revert�revoke�right�rollback�rowcount� rowguidcol�rule�saver � securityaudit�select�session_user�set�setuser�shutdown�some� statistics�system_user�table�tablesample�textsize�then�to�top�tran�transaction�trigger�truncate�tsequal�union�unique�unpivot�update� updatetext�use�user�values�varying�view�waitfor�when�where�while�with� writetextc �"