⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 schema.py

📁 SQLAlchemy. 经典的Python ORM框架。学习必看。
💻 PY
📖 第 1 页 / 共 5 页
字号:
    def get_children(self, column_collections=True, schema_visitor=False, **kwargs):        if not schema_visitor:            return expression.TableClause.get_children(self, column_collections=column_collections, **kwargs)        else:            if column_collections:                return [c for c in self.columns]            else:                return []    def exists(self, bind=None):        """Return True if this table exists."""        if bind is None:            bind = _bind_or_error(self)        def do(conn):            return conn.dialect.has_table(conn, self.name, schema=self.schema)        return bind.run_callable(do)    def create(self, bind=None, checkfirst=False):        """Issue a ``CREATE`` statement for this table.        See also ``metadata.create_all()``."""        self.metadata.create_all(bind=bind, checkfirst=checkfirst, tables=[self])    def drop(self, bind=None, checkfirst=False):        """Issue a ``DROP`` statement for this table.        See also ``metadata.drop_all()``."""        self.metadata.drop_all(bind=bind, checkfirst=checkfirst, tables=[self])    def tometadata(self, metadata, schema=None):        """Return a copy of this ``Table`` associated with a different ``MetaData``."""        try:            if schema is None:                schema = self.schema            key = _get_table_key(self.name, schema)            return metadata.tables[key]        except KeyError:            args = []            for c in self.columns:                args.append(c.copy())            for c in self.constraints:                args.append(c.copy())            return Table(self.name, metadata, schema=schema, *args)class Column(SchemaItem, expression._ColumnClause):    """Represent a column in a database table.    This is a subclass of ``expression.ColumnClause`` and represents an    actual existing table in the database, in a similar fashion as    ``TableClause``/``Table``.    """    def __init__(self, name, type_, *args, **kwargs):        """Construct a new ``Column`` object.        Arguments are:        name          The name of this column.  This should be the identical name          as it appears, or will appear, in the database.        type\_          The ``TypeEngine`` for this column.  This can be any          subclass of ``types.AbstractType``, including the          database-agnostic types defined in the types module,          database-specific types defined within specific database          modules, or user-defined types. If the column contains a          ForeignKey, the type can also be None, in which case the          type assigned will be that of the referenced column.        \*args          Constraint, ForeignKey, ColumnDefault and Sequence objects          should be added as list values.        \**kwargs          Keyword arguments include:          key            Defaults to None: an optional *alias name* for this column.            The column will then be identified everywhere in an            application, including the column list on its Table, by            this key, and not the given name.  Generated SQL, however,            will still reference the column by its actual name.          primary_key            Defaults to False: True if this column is a primary key            column.  Multiple columns can have this flag set to            specify composite primary keys.  As an alternative, the            primary key of a Table can be specified via an explicit            ``PrimaryKeyConstraint`` instance appended to the Table's            list of objects.          nullable            Defaults to True : True if this column should allow            nulls. True is the default unless this column is a primary            key column.          default            Defaults to None: a scalar, Python callable, or ``ClauseElement``            representing the *default value* for this column, which will            be invoked upon insert if this column is not present in            the insert list or is given a value of None.  The default            expression will be converted into a ``ColumnDefault`` object            upon initialization.          _is_oid            Defaults to False: used internally to indicate that this            column is used as the quasi-hidden "oid" column          index            Defaults to False: indicates that this column is            indexed. The name of the index is autogenerated.  to            specify indexes with explicit names or indexes that            contain multiple columns, use the ``Index`` construct instead.          info            Defaults to {}: A space to store application specific data;            this must be a dictionary.          unique            Defaults to False: indicates that this column contains a            unique constraint, or if `index` is True as well,            indicates that the Index should be created with the unique            flag.  To specify multiple columns in the constraint/index            or to specify an explicit name, use the            ``UniqueConstraint`` or ``Index`` constructs instead.          autoincrement            Defaults to True: indicates that integer-based primary key            columns should have autoincrementing behavior, if            supported by the underlying database.  This will affect            ``CREATE TABLE`` statements such that they will use the            databases *auto-incrementing* keyword (such as ``SERIAL``            for Postgres, ``AUTO_INCREMENT`` for Mysql) and will also            affect the behavior of some dialects during ``INSERT``            statement execution such that they will assume primary key            values are created in this manner.  If a ``Column`` has an            explicit ``ColumnDefault`` object (such as via the `default`            keyword, or a ``Sequence`` or ``PassiveDefault``), then            the value of `autoincrement` is ignored and is assumed to be            False.  `autoincrement` value is only significant for a            column with a type or subtype of Integer.          quote            Defaults to False: indicates that the Column identifier            must be properly escaped and quoted before being sent to            the database.  This flag should normally not be required            as dialects can auto-detect conditions where quoting is            required.        """        super(Column, self).__init__(name, None, type_)        self.args = args        self.key = kwargs.pop('key', name)        self.primary_key = kwargs.pop('primary_key', False)        self.nullable = kwargs.pop('nullable', not self.primary_key)        self._is_oid = kwargs.pop('_is_oid', False)        self.default = kwargs.pop('default', None)        self.index = kwargs.pop('index', None)        self.unique = kwargs.pop('unique', None)        self.quote = kwargs.pop('quote', False)        self.onupdate = kwargs.pop('onupdate', None)        self.autoincrement = kwargs.pop('autoincrement', True)        self.constraints = util.Set()        self.foreign_keys = util.OrderedSet()        if kwargs.get('info'):            self._info = kwargs.pop('info')        if kwargs:            raise exceptions.ArgumentError("Unknown arguments passed to Column: " + repr(kwargs.keys()))    def __str__(self):        if self.table is not None:            if self.table.named_with_column:                return (self.table.description + "." + self.description)            else:                return self.description        else:            return self.description    def bind(self):        return self.table.bind    bind = property(bind)    def references(self, column):        """return true if this column references the given column via foreign key"""        for fk in self.foreign_keys:            if fk.column is column:                return True        else:            return False    def append_foreign_key(self, fk):        fk._set_parent(self)    def __repr__(self):        kwarg = []        if self.key != self.name:            kwarg.append('key')        if self.primary_key:            kwarg.append('primary_key')        if not self.nullable:            kwarg.append('nullable')        if self.onupdate:            kwarg.append('onupdate')        if self.default:            kwarg.append('default')        return "Column(%s)" % ', '.join(            [repr(self.name)] + [repr(self.type)] +            [repr(x) for x in self.foreign_keys if x is not None] +            [repr(x) for x in self.constraints] +            [(self.table and "table=<%s>" % self.table.description or "")] +            ["%s=%s" % (k, repr(getattr(self, k))) for k in kwarg])    def _set_parent(self, table):        self.metadata = table.metadata        if getattr(self, 'table', None) is not None:            raise exceptions.ArgumentError("this Column already has a table!")        if not self._is_oid:            self._pre_existing_column = table._columns.get(self.key)            table._columns.replace(self)        else:            self._pre_existing_column = None        if self.primary_key:            table.primary_key.replace(self)        elif self.key in table.primary_key:            raise exceptions.ArgumentError("Trying to redefine primary-key column '%s' as a non-primary-key column on table '%s'" % (self.key, table.fullname))            # if we think this should not raise an error, we'd instead do this:            #table.primary_key.remove(self)        self.table = table        if self.index:            if isinstance(self.index, basestring):                raise exceptions.ArgumentError("The 'index' keyword argument on Column is boolean only.  To create indexes with a specific name, create an explicit Index object external to the Table.")            Index('ix_%s' % self._label, self, unique=self.unique)        elif self.unique:            if isinstance(self.unique, basestring):                raise exceptions.ArgumentError("The 'unique' keyword argument on Column is boolean only.  To create unique constraints or indexes with a specific name, append an explicit UniqueConstraint to the Table's list of elements, or create an explicit Index object external to the Table.")            table.append_constraint(UniqueConstraint(self.key))        toinit = list(self.args)        if self.default is not None:            toinit.append(ColumnDefault(self.default))        if self.onupdate is not None:            toinit.append(ColumnDefault(self.onupdate, for_update=True))        self._init_items(*toinit)        self.args = None    def copy(self):        """Create a copy of this ``Column``, unitialized.        This is used in ``Table.tometadata``.        """        return Column(self.name, self.type, self.default, key = self.key, primary_key = self.primary_key, nullable = self.nullable, _is_oid = self._is_oid, quote=self.quote, index=self.index, *[c.copy() for c in self.constraints])    def _make_proxy(self, selectable, name = None):        """Create a *proxy* for this column.        This is a copy of this ``Column`` referenced by a different parent        (such as an alias or select statement).        """        fk = [ForeignKey(f._colspec) for f in self.foreign_keys]        c = Column(name or self.name, self.type, self.default, key = name or self.key, primary_key = self.primary_key, nullable = self.nullable, _is_oid = self._is_oid, quote=self.quote, *fk)        c.table = selectable        c.proxies = [self]        c._pre_existing_column = self._pre_existing_column        if not c._is_oid:            selectable.columns.add(c)            if self.primary_key:                selectable.primary_key.add(c)        [c._init_items(f) for f in fk]        return c    def get_children(self, schema_visitor=False, **kwargs):        if schema_visitor:            return [x for x in (self.default, self.onupdate) if x is not None] + \                list(self.foreign_keys) + list(self.constraints)        else:            return expression._ColumnClause.get_children(self, **kwargs)class ForeignKey(SchemaItem):    """Defines a column-level ``ForeignKey`` constraint between two columns.    ``ForeignKey`` is specified as an argument to a Column object.    One or more ``ForeignKey`` objects are used within a    ``ForeignKeyConstraint`` object which represents the table-level    constraint definition.    """    def __init__(self, column, constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None):        """Construct a new ``ForeignKey`` object.        column          Can be a ``schema.Column`` object representing the relationship,          or just its string name given as ``tablename.columnname``.          schema can be specified as ``schema.tablename.columnname``.        constraint          Is the owning ``ForeignKeyConstraint`` object, if any.  if not          given, then a ``ForeignKeyConstraint`` will be automatically          created and added to the parent table.        """        self._colspec = column        self._column = None        self.constraint = constraint        self.use_alter = use_alter        self.name = name        self.onupdate = onupdate        self.ondelete = ondelete        self.deferrable = deferrable        self.initially = initially    def __repr__(self):        return "ForeignKey(%s)" % repr(self._get_colspec())    def copy(self):        """Produce a copy of this ForeignKey object."""        return ForeignKey(self._get_colspec())    def _get_colspec(self):        if isinstance(self._colspec, basestring):            return self._colspec        elif self._colspec.table.schema is not None:            return "%s.%s.%s" % (self._colspec.table.schema, self._colspec.table.name, self._colspec.key)        else:            return "%s.%s" % (self._colspec.table.name, self._colspec.key)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -