rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
mapper.extension.before_insert(mapper, connection, state.obj()) | mapper.extension.before_insert(mapper, conn, state.obj()) | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
mapper.extension.before_update(mapper, connection, state.obj()) row_switches = {} if not postupdate: for state, mapper, connection, has_identity, instance_key in tups: | mapper.extension.before_update(mapper, conn, state.obj()) | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
"detected row switch for identity %s. will update %s, remove %s from " "transaction", instance_key, state_str(state), state_str(existing)) | "detected row switch for identity %s. " "will update %s, remove %s from " "transaction", instance_key, state_str(state), state_str(existing)) | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
row_switches[state] = existing | row_switch = existing tups.append( (state, mapper, conn, has_identity, instance_key, row_switch) ) | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
for table in table_to_mapper.iterkeys(): | for table in table_to_mapper: | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
for state, mapper, connection, has_identity, instance_key in tups: | for state, mapper, connection, has_identity, \ instance_key, row_switch in tups: | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
isinsert = not has_identity and not postupdate and state not in row_switches | isinsert = not has_identity and \ not postupdate and \ not row_switch | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
params[col._label] = mapper._get_state_attr_by_column(row_switches.get(state, state), col) params[col.key] = mapper.version_id_generator(params[col._label]) | params[col._label] = \ mapper._get_state_attr_by_column( row_switch or state, col) params[col.key] = \ mapper.version_id_generator(params[col._label]) | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
mapper.polymorphic_on.shares_lineage(col) and col not in pks: | mapper.polymorphic_on.shares_lineage(col) and \ col not in pks: | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
if post_update_cols is not None and col not in post_update_cols: | if post_update_cols is not None and \ col not in post_update_cols: | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
params[col._label] = mapper._get_state_attr_by_column(state, col) | params[col._label] = \ mapper._get_state_attr_by_column(state, col) | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
clause.clauses.append(col == sql.bindparam(col._label, type_=col.type)) if mapper.version_id_col is not None and \ table.c.contains_column(mapper.version_id_col): | clause.clauses.append( col == sql.bindparam(col._label, type_=col.type) ) needs_version_id = mapper.version_id_col is not None and \ table.c.contains_column(mapper.version_id_col) if needs_version_id: | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
mapper._postfetch(uowtransaction, connection, table, | mapper._postfetch(uowtransaction, table, | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
"Updated rowcount %d does not match number of objects updated %d" % | "Updated rowcount %d does not match number " "of objects updated %d" % | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
elif mapper.version_id_col is not None: | elif needs_version_id: | def _save_obj(self, states, uowtransaction, postupdate=False, post_update_cols=None, single=False): """Issue ``INSERT`` and/or ``UPDATE`` statements for a list of objects. |
def _postfetch(self, uowtransaction, connection, table, | def _postfetch(self, uowtransaction, table, | def _postfetch(self, uowtransaction, connection, table, state, resultproxy, params, value_params): """Expire attributes in need of newly persisted database state.""" |
deferred_props = [prop.key for prop in [self._columntoproperty[c] for c in postfetch_cols]] if deferred_props: _expire_state(state, state.dict, deferred_props) | if postfetch_cols: _expire_state(state, state.dict, [self._columntoproperty[c].key for c in postfetch_cols] ) | def _postfetch(self, uowtransaction, connection, table, state, resultproxy, params, value_params): """Expire attributes in need of newly persisted database state.""" |
cols = set(table.c) for m in self.iterate_to_root(): if m._inherits_equated_pairs and \ cols.intersection([l for l, r in m._inherits_equated_pairs]): sync.populate(state, m, state, m, m._inherits_equated_pairs, uowtransaction, self.passive_updates) | for m, equated_pairs in self._table_to_equated[table]: sync.populate(state, m, state, m, equated_pairs, uowtransaction, self.passive_updates) @util.memoized_property def _table_to_equated(self): """memoized map of tables to collections of columns to be synchronized upwards to the base mapper.""" result = util.defaultdict(list) for table in self._sorted_tables: cols = set(table.c) for m in self.iterate_to_root(): if m._inherits_equated_pairs and \ cols.intersection([l for l, r in m._inherits_equated_pairs]): result[table].append((m, m._inherits_equated_pairs)) return result | def _postfetch(self, uowtransaction, connection, table, state, resultproxy, params, value_params): """Expire attributes in need of newly persisted database state.""" |
connection_callable = uowtransaction.mapper_flush_opts['connection_callable'] tups = [(state, _state_mapper(state), connection_callable(self, state.obj())) for state in _sort_states(states)] | connection_callable = \ uowtransaction.mapper_flush_opts['connection_callable'] | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
tups = [(state, _state_mapper(state), connection) for state in _sort_states(states)] for state, mapper, connection in tups: | connection_callable = None tups = [] for state in _sort_states(states): mapper = _state_mapper(state) conn = connection_callable and \ connection_callable(self, state.obj()) or \ connection | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
mapper.extension.before_delete(mapper, connection, state.obj()) | mapper.extension.before_delete(mapper, conn, state.obj()) tups.append((state, _state_mapper(state), _state_has_identity(state), conn)) | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
delete = {} for state, mapper, connection in tups: if table not in mapper._pks_by_table: | delete = util.defaultdict(list) for state, mapper, has_identity, connection in tups: if not has_identity or table not in mapper._pks_by_table: | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
if not _state_has_identity(state): continue else: delete.setdefault(connection, []).append(params) | delete[connection].append(params) | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
if mapper.version_id_col is not None and table.c.contains_column(mapper.version_id_col): params[mapper.version_id_col.key] = mapper._get_state_attr_by_column(state, mapper.version_id_col) | if mapper.version_id_col is not None and \ table.c.contains_column(mapper.version_id_col): params[mapper.version_id_col.key] = \ mapper._get_state_attr_by_column(state, mapper.version_id_col) | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
if mapper.version_id_col is not None and table.c.contains_column(mapper.version_id_col): | need_version_id = mapper.version_id_col is not None and \ table.c.contains_column(mapper.version_id_col) if need_version_id: | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
c = connection.execute(statement, del_objects) if c.supports_sane_multi_rowcount() and c.rowcount != len(del_objects): raise orm_exc.ConcurrentModificationError("Deleted rowcount %d does not match " "number of objects deleted %d" % (c.rowcount, len(del_objects))) for state, mapper, connection in tups: | rows = -1 if need_version_id and \ not connection.dialect.supports_sane_multi_rowcount: if connection.dialect.supports_sane_rowcount: rows = 0 for params in del_objects: c = connection.execute(statement, params) rows += c.rowcount else: util.warn("Dialect %s does not support deleted rowcount " "- versioning cannot be verified." % c.dialect.dialect_description, stacklevel=12) connection.execute(statement, del_objects) else: c = connection.execute(statement, del_objects) if connection.dialect.supports_sane_multi_rowcount: rows = c.rowcount if rows != -1 and rows != len(del_objects): raise orm_exc.ConcurrentModificationError( "Deleted rowcount %d does not match " "number of objects deleted %d" % (c.rowcount, len(del_objects)) ) for state, mapper, has_identity, connection in tups: | def _delete_obj(self, states, uowtransaction): """Issue ``DELETE`` statements for a list of objects. |
kwargs = util.frozendict() | def values(self, *args, **kwargs): """specify the VALUES clause for an INSERT statement, or the SET clause for an UPDATE. |
|
self.kwargs = self._process_deprecated_kw(kwargs) | if kwargs: self.kwargs = self._process_deprecated_kw(kwargs) | def __init__(self, table, whereclause, values=None, inline=False, bind=None, returning=None, **kwargs): _ValuesBase.__init__(self, table, values) self._bind = bind self._returning = returning if whereclause is not None: self._whereclause = _literal_as_text(whereclause) else: self._whereclause = None self.inline = inline |
self.kwargs = self._process_deprecated_kw(kwargs) | if kwargs: self.kwargs = self._process_deprecated_kw(kwargs) | def __init__(self, table, whereclause, bind=None, returning =None, **kwargs): self._bind = bind self.table = table self._returning = returning if whereclause is not None: self._whereclause = _literal_as_text(whereclause) else: self._whereclause = None |
if previous is not value and previous not in (None, PASSIVE_NO_RESULT): | if (previous is not value and previous is not None and previous is not PASSIVE_NO_RESULT): | def fire_replace_event(self, state, dict_, value, previous, initiator): if self.trackparent: if previous is not value and previous not in (None, PASSIVE_NO_RESULT): self.sethasparent(instance_state(previous), False) |
if oldchild not in (None, PASSIVE_NO_RESULT): | if oldchild is not None and oldchild is not PASSIVE_NO_RESULT: | def set(self, state, child, oldchild, initiator): if oldchild is child: return child if oldchild not in (None, PASSIVE_NO_RESULT): # With lazy=None, there's no guarantee that the full collection is # present when updating via a backref. old_state, old_dict = instance_state(oldchild), instance_dict(oldchild) impl = old_state.get_impl(self.key) try: impl.remove(old_state, old_dict, state.obj(), initiator, passive=PASSIVE_NO_FETCH) except (ValueError, KeyError, IndexError): pass if child is not None: new_state, new_dict = instance_state(child), instance_dict(child) new_state.get_impl(self.key).append(new_state, new_dict, state.obj(), initiator, passive=PASSIVE_NO_FETCH) return child |
[c not in (None, PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.added], [c not in (None, PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.unchanged], [c not in (None, PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.deleted], ) | [(c is not None and c is not PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.added], [(c is not None and c is not PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.unchanged], [(c is not None and c is not PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.deleted], ) | def as_state(self): return History( [c not in (None, PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.added], [c not in (None, PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.unchanged], [c not in (None, PASSIVE_NO_RESULT) and instance_state(c) or None for c in self.deleted], ) |
if original not in [None, NEVER_SET, NO_VALUE]: | if (original is not None and original is not NEVER_SET and original is not NO_VALUE): | def from_attribute(cls, attribute, state, current): original = state.committed_state.get(attribute.key, NEVER_SET) |
lc_alias = schema._get_table_key(table.name, table.schema) | lc_alias = sa_schema._get_table_key(table.name, table.schema) | def _adjust_casing(self, table, charset=None): """Adjust Table name to the server case sensitivity, if needed.""" |
from sqlalchemy.cresultproxy import rowproxy_reconstructor | from sqlalchemy.cresultproxy import safe_rowproxy_reconstructor def rowproxy_reconstructor(cls, state): return safe_rowproxy_reconstructor(cls, state) | def _commit_twophase_impl(self, xid, is_prepared): return proxy.commit_twophase(self, super(ProxyConnection, self)._commit_twophase_impl, xid, is_prepared) |
(table1.c.myid.like('somstr'), "mytable.myid LIKE :myid_1", None), (~table1.c.myid.like('somstr'), "mytable.myid NOT LIKE :myid_1", None), (table1.c.myid.like('somstr', escape='\\'), "mytable.myid LIKE :myid_1 ESCAPE '\\'", None), (~table1.c.myid.like('somstr', escape='\\'), "mytable.myid NOT LIKE :myid_1 ESCAPE '\\'", None), (table1.c.myid.ilike('somstr', escape='\\'), "lower(mytable.myid) LIKE lower(:myid_1) ESCAPE '\\'", None), (~table1.c.myid.ilike('somstr', escape='\\'), "lower(mytable.myid) NOT LIKE lower(:myid_1) ESCAPE '\\'", None), (table1.c.myid.ilike('somstr', escape='\\'), "mytable.myid ILIKE %(myid_1)s ESCAPE '\\'", postgresql.PGDialect()), (~table1.c.myid.ilike('somstr', escape='\\'), "mytable.myid NOT ILIKE %(myid_1)s ESCAPE '\\'", postgresql.PGDialect()), (table1.c.name.ilike('%something%'), "lower(mytable.name) LIKE lower(:name_1)", None), (table1.c.name.ilike('%something%'), "mytable.name ILIKE %(name_1)s", postgresql.PGDialect()), (~table1.c.name.ilike('%something%'), "lower(mytable.name) NOT LIKE lower(:name_1)", None), (~table1.c.name.ilike('%something%'), "mytable.name NOT ILIKE %(name_1)s", postgresql.PGDialect()), | ( table1.c.myid.like('somstr'), "mytable.myid LIKE :myid_1", None), ( ~table1.c.myid.like('somstr'), "mytable.myid NOT LIKE :myid_1", None), ( table1.c.myid.like('somstr', escape='\\'), "mytable.myid LIKE :myid_1 ESCAPE '\\'", None), ( ~table1.c.myid.like('somstr', escape='\\'), "mytable.myid NOT LIKE :myid_1 ESCAPE '\\'", None), ( table1.c.myid.ilike('somstr', escape='\\'), "lower(mytable.myid) LIKE lower(:myid_1) ESCAPE '\\'", None), ( ~table1.c.myid.ilike('somstr', escape='\\'), "lower(mytable.myid) NOT LIKE lower(:myid_1) ESCAPE '\\'", None), ( table1.c.myid.ilike('somstr', escape='\\'), "mytable.myid ILIKE %(myid_1)s ESCAPE '\\\\'", postgresql.PGDialect()), ( ~table1.c.myid.ilike('somstr', escape='\\'), "mytable.myid NOT ILIKE %(myid_1)s ESCAPE '\\\\'", postgresql.PGDialect()), ( table1.c.name.ilike('%something%'), "lower(mytable.name) LIKE lower(:name_1)", None), ( table1.c.name.ilike('%something%'), "mytable.name ILIKE %(name_1)s", postgresql.PGDialect()), ( ~table1.c.name.ilike('%something%'), "lower(mytable.name) NOT LIKE lower(:name_1)", None), ( ~table1.c.name.ilike('%something%'), "mytable.name NOT ILIKE %(name_1)s", postgresql.PGDialect()), | def test_like(self): for expr, check, dialect in [ (table1.c.myid.like('somstr'), "mytable.myid LIKE :myid_1", None), (~table1.c.myid.like('somstr'), "mytable.myid NOT LIKE :myid_1", None), (table1.c.myid.like('somstr', escape='\\'), "mytable.myid LIKE :myid_1 ESCAPE '\\'", None), (~table1.c.myid.like('somstr', escape='\\'), "mytable.myid NOT LIKE :myid_1 ESCAPE '\\'", None), (table1.c.myid.ilike('somstr', escape='\\'), "lower(mytable.myid) LIKE lower(:myid_1) ESCAPE '\\'", None), (~table1.c.myid.ilike('somstr', escape='\\'), "lower(mytable.myid) NOT LIKE lower(:myid_1) ESCAPE '\\'", None), (table1.c.myid.ilike('somstr', escape='\\'), "mytable.myid ILIKE %(myid_1)s ESCAPE '\\'", postgresql.PGDialect()), (~table1.c.myid.ilike('somstr', escape='\\'), "mytable.myid NOT ILIKE %(myid_1)s ESCAPE '\\'", postgresql.PGDialect()), (table1.c.name.ilike('%something%'), "lower(mytable.name) LIKE lower(:name_1)", None), (table1.c.name.ilike('%something%'), "mytable.name ILIKE %(name_1)s", postgresql.PGDialect()), (~table1.c.name.ilike('%something%'), "lower(mytable.name) NOT LIKE lower(:name_1)", None), (~table1.c.name.ilike('%something%'), "mytable.name NOT ILIKE %(name_1)s", postgresql.PGDialect()), ]: self.assert_compile(expr, check, dialect=dialect) |
for attr in '_columns', '_primary_key_foreign_keys', \ | for attr in '_columns', '_primary_key', '_foreign_keys', \ | def _reset_exported(self): """delete memoized collections when a FromClause is cloned.""" |
(VARCHAR(10), "VARCHAR(10)"), | (VARCHAR(10), ("VARCHAR(10)","VARCHAR(10 CHAR)")), | def test_uppercase_rendering(self): """Test that uppercase types from types.py always render as their type. As of SQLA 0.6, using an uppercase type means you want specifically that type. If the database in use doesn't support that DDL, it (the DB backend) should raise an error - it means you should be using a lowercased (genericized) type. """ for dialect in [ oracle.dialect(), mysql.dialect(), postgresql.dialect(), sqlite.dialect(), mssql.dialect()]: # TODO when dialects are complete: engines.all_dialects(): for type_, expected in ( (FLOAT, "FLOAT"), (NUMERIC, "NUMERIC"), (DECIMAL, "DECIMAL"), (INTEGER, "INTEGER"), (SMALLINT, "SMALLINT"), (TIMESTAMP, "TIMESTAMP"), (DATETIME, "DATETIME"), (DATE, "DATE"), (TIME, "TIME"), (CLOB, "CLOB"), (VARCHAR(10), "VARCHAR(10)"), (NVARCHAR(10), ("NVARCHAR(10)", "NATIONAL VARCHAR(10)", "NVARCHAR2(10)")), (CHAR, "CHAR"), (NCHAR, ("NCHAR", "NATIONAL CHAR")), (BLOB, "BLOB"), (BOOLEAN, ("BOOLEAN", "BOOL")) ): if isinstance(expected, str): expected = (expected, ) for exp in expected: compiled = types.to_instance(type_).compile(dialect=dialect) if exp in compiled: break else: assert False, "%r matches none of %r for dialect %s" % \ (compiled, expected, dialect.name) |
def with_hint(self, selectable, text, dialect_name=None): | def with_hint(self, selectable, text, dialect_name='*'): | def with_hint(self, selectable, text, dialect_name=None): """Add an indexing hint for the given entity or selectable to this :class:`Query`. Functionality is passed straight through to :meth:`~sqlalchemy.sql.expression.Select.with_hint`, with the addition that ``selectable`` can be a :class:`Table`, :class:`Alias`, or ORM entity / mapped class /etc. """ mapper, selectable, is_aliased_class = _entity_info(selectable) self._with_hints += ((selectable, text, dialect_name),) |
cx_oracle_ver = None | cx_oracle_ver = (0, 0, 0) | def __init__(self, auto_setinputsizes=True, auto_convert_lobs=True, threaded=True, allow_twophase=True, arraysize=50, **kwargs): OracleDialect.__init__(self, **kwargs) self.threaded = threaded self.arraysize = arraysize self.allow_twophase = allow_twophase self.supports_timestamp = self.dbapi is None or hasattr(self.dbapi, 'TIMESTAMP' ) self.auto_setinputsizes = auto_setinputsizes self.auto_convert_lobs = auto_convert_lobs if hasattr(self.dbapi, 'version'): cx_oracle_ver = tuple([int(x) for x in self.dbapi.version.split('.')]) else: cx_oracle_ver = None def types(*names): return set([ getattr(self.dbapi, name, None) for name in names ]).difference([None]) |
MSSQLCompiler.render_literal_value(self, value, type_) | return super(MSSQLStrictCompiler, self).render_literal_value(value, type_) | def render_literal_value(self, value, type_): """ 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. """ # datetime and date are both subclasses of datetime.date if issubclass(type(value), datetime.date): # SQL Server wants single quotes around the date string. return "'" + str(value) + "'" else: MSSQLCompiler.render_literal_value(self, value, type_) |
active_history = self.parent_property.direction is not interfaces.MANYTOONE, | active_history = not self.use_get, | def init_class_attribute(self, mapper): self.is_class_level = True # MANYTOONE currently only needs the "old" value for delete-orphan # cascades. the required _SingleParentValidator will enable active_history # in that case. otherwise we don't need the "old" value during backref operations. _register_attribute(self, mapper, useobject=True, callable_=self._class_level_loader, uselist = self.parent_property.uselist, typecallable = self.parent_property.collection_class, active_history = self.parent_property.direction is not interfaces.MANYTOONE, ) |
% (name, name)) | % (name, name), globals()) | def test_import_base_dialects(self): for name in ('mysql', 'firebird', 'postgresql', 'sqlite', 'oracle', 'mssql'): exec("from sqlalchemy.dialects import %s\n" "dialect = %s.dialect()" % (name, name)) eq_(dialect.name, name) |
@profiling.function_call_count(64, {'2.4': 42, '2.7':67, | @profiling.function_call_count(72, {'2.4': 42, '2.7':67, | def setup(self): global pool pool = QueuePool(creator=self.Connection, pool_size=3, max_overflow=-1, use_threadlocal=True) |
__tablename__ = None | primary_language = Column(String(50)) | def __tablename__(cls): if has_inherited_table(cls): return None return cls.__name__.lower() |
primary_language = Column(String(50)) | def __tablename__(cls): if has_inherited_table(cls): return None return cls.__name__.lower() |
|
if (decl.has_inherited_table(cls) and TableNameMixin not in cls.__bases__): | if (has_inherited_table(cls) and Tablename not in cls.__bases__): | def __tablename__(cls): if (decl.has_inherited_table(cls) and TableNameMixin not in cls.__bases__): return None return cls.__name__.lower() |
__tablename__ = None | primary_language = Column(String(50)) | def __tablename__(cls): if (decl.has_inherited_table(cls) and TableNameMixin not in cls.__bases__): return None return cls.__name__.lower() |
primary_language = Column(String(50)) | def __tablename__(cls): if (decl.has_inherited_table(cls) and TableNameMixin not in cls.__bases__): return None return cls.__name__.lower() |
|
__tablename__ = None | id = Column(Integer, ForeignKey('person.id'), primary_key=True) preferred_recreation = Column(String(50)) | def __tablename__(cls): if (decl.has_inherited_table(cls) and TableNameMixin not in cls.__bases__): return None return cls.__name__.lower() |
preferred_recreation = Column(String(50)) | def __tablename__(cls): if (decl.has_inherited_table(cls) and TableNameMixin not in cls.__bases__): return None return cls.__name__.lower() |
|
from sqlalchemy.orm import synonym as _orm_synonym, mapper, comparable_property, class_mapper | from sqlalchemy.orm import synonym as _orm_synonym, mapper,\ comparable_property, class_mapper | def __table_args__(self): args = dict() args.update(MySQLSettings.__table_args__) args.update(MyOtherMixin.__table_args__) return args |
__all__ = 'declarative_base', 'synonym_for', 'comparable_using', 'instrument_declarative' | __all__ = 'declarative_base', 'synonym_for', \ 'comparable_using', 'instrument_declarative' | def __table_args__(self): args = dict() args.update(MySQLSettings.__table_args__) args.update(MyOtherMixin.__table_args__) return args |
"Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) | "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, " "'kw2':val2, ...})" ) | def _as_declarative(cls, classname, dict_): # dict_ will be a dictproxy, which we can't write to, and we need to! dict_ = dict(dict_) column_copies = {} potential_columns = {} mapper_args = {} table_args = inherited_table_args = None tablename = None parent_columns = () for base in cls.__mro__: if _is_mapped_class(base): parent_columns = base.__table__.c.keys() else: for name,obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args: mapper_args = cls.__mapper_args__ elif name == '__tablename__': if not tablename: tablename = cls.__tablename__ elif name == '__table_args__': if not table_args: table_args = cls.__table_args__ if base is not cls: inherited_table_args = True elif base is not cls: # we're a mixin. if isinstance(obj, Column): if obj.foreign_keys: raise exceptions.InvalidRequestError( "Columns with foreign keys to other columns " "must be declared as @classproperty callables " "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and name in dict_['__table__'].c ): potential_columns[name] = \ column_copies[obj] = \ obj.copy() column_copies[obj]._creation_order = \ obj._creation_order elif isinstance(obj, MapperProperty): raise exceptions.InvalidRequestError( "Mapper properties (i.e. deferred," "column_property(), relationship(), etc.) must " "be declared as @classproperty callables " "on declarative mixin classes.") elif isinstance(obj, util.classproperty): dict_[name] = ret = \ column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should for k, v in potential_columns.items(): if tablename or k not in parent_columns: dict_[k] = v if inherited_table_args and not tablename: table_args = None # make sure that column copies are used rather # than the original columns from any mixins for k, v in mapper_args.iteritems(): mapper_args[k] = column_copies.get(v,v) cls._decl_class_registry[classname] = cls our_stuff = util.OrderedDict() for k in dict_: value = dict_[k] if (isinstance(value, tuple) and len(value) == 1 and isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) continue if not isinstance(value, (Column, MapperProperty)): continue prop = _deferred_relationship(cls, value) our_stuff[k] = prop # set up attributes in the order they were created our_stuff.sort(key=lambda key: our_stuff[key]._creation_order) # extract columns from the class dict cols = [] for key, c in our_stuff.iteritems(): if isinstance(c, ColumnProperty): for col in c.columns: if isinstance(col, Column) and col.table is None: _undefer_column_name(key, col) cols.append(col) elif isinstance(c, Column): _undefer_column_name(key, c) cols.append(c) # if the column is the same name as the key, # remove it from the explicit properties dict. # the normal rules for assigning column-based properties # will take over, including precedence of columns # in multi-column ColumnProperties. if key == c.key: del our_stuff[key] table = None if '__table__' not in dict_: if tablename is not None: if isinstance(table_args, dict): args, table_kw = (), table_args elif isinstance(table_args, tuple): args = table_args[0:-1] table_kw = table_args[-1] if len(table_args) < 2 or not isinstance(table_kw, dict): raise exceptions.ArgumentError( "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) else: args, table_kw = (), {} autoload = dict_.get('__autoload__') if autoload: table_kw['autoload'] = True cls.__table__ = table = Table(tablename, cls.metadata, *(tuple(cols) + tuple(args)), **table_kw) else: table = cls.__table__ if cols: for c in cols: if not table.c.contains_column(c): raise exceptions.ArgumentError( "Can't add additional column %r when specifying __table__" % key ) if 'inherits' not in mapper_args: for c in cls.__bases__: if _is_mapped_class(c): mapper_args['inherits'] = cls._decl_class_registry.get(c.__name__, None) break if hasattr(cls, '__mapper_cls__'): mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__) else: mapper_cls = mapper if table is None and 'inherits' not in mapper_args: raise exceptions.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing table-mapped class." % cls ) elif 'inherits' in mapper_args and not mapper_args.get('concrete', False): inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'inherit_condition' not in mapper_args and table is not None: # figure out the inherit condition with relaxed rules # about nonexistent tables, to allow for ForeignKeys to # not-yet-defined tables (since we know for sure that our # parent table is defined within the same MetaData) mapper_args['inherit_condition'] = sql_util.join_condition( mapper_args['inherits'].__table__, table, ignore_nonexistent_tables=True) if table is None: # single table inheritance. # ensure no table args if table_args: raise exceptions.ArgumentError( "Can't place __table_args__ on an inherited class with no table." ) # add any columns declared here to the inherited table. for c in cols: if c.primary_key: raise exceptions.ArgumentError( "Can't place primary key columns on an inherited class with no table." ) if c.name in inherited_table.c: raise exceptions.ArgumentError( "Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) inherited_table.append_column(c) # single or joined inheritance # exclude any cols on the inherited table which are not mapped on the # parent class, to avoid # mapping columns specific to sibling/nephew classes inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'exclude_properties' not in mapper_args: mapper_args['exclude_properties'] = exclude_properties = \ set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update([c.key for c in cols]) cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args) |
"Can't add additional column %r when specifying __table__" % key ) | "Can't add additional column %r when " "specifying __table__" % key ) | def _as_declarative(cls, classname, dict_): # dict_ will be a dictproxy, which we can't write to, and we need to! dict_ = dict(dict_) column_copies = {} potential_columns = {} mapper_args = {} table_args = inherited_table_args = None tablename = None parent_columns = () for base in cls.__mro__: if _is_mapped_class(base): parent_columns = base.__table__.c.keys() else: for name,obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args: mapper_args = cls.__mapper_args__ elif name == '__tablename__': if not tablename: tablename = cls.__tablename__ elif name == '__table_args__': if not table_args: table_args = cls.__table_args__ if base is not cls: inherited_table_args = True elif base is not cls: # we're a mixin. if isinstance(obj, Column): if obj.foreign_keys: raise exceptions.InvalidRequestError( "Columns with foreign keys to other columns " "must be declared as @classproperty callables " "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and name in dict_['__table__'].c ): potential_columns[name] = \ column_copies[obj] = \ obj.copy() column_copies[obj]._creation_order = \ obj._creation_order elif isinstance(obj, MapperProperty): raise exceptions.InvalidRequestError( "Mapper properties (i.e. deferred," "column_property(), relationship(), etc.) must " "be declared as @classproperty callables " "on declarative mixin classes.") elif isinstance(obj, util.classproperty): dict_[name] = ret = \ column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should for k, v in potential_columns.items(): if tablename or k not in parent_columns: dict_[k] = v if inherited_table_args and not tablename: table_args = None # make sure that column copies are used rather # than the original columns from any mixins for k, v in mapper_args.iteritems(): mapper_args[k] = column_copies.get(v,v) cls._decl_class_registry[classname] = cls our_stuff = util.OrderedDict() for k in dict_: value = dict_[k] if (isinstance(value, tuple) and len(value) == 1 and isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) continue if not isinstance(value, (Column, MapperProperty)): continue prop = _deferred_relationship(cls, value) our_stuff[k] = prop # set up attributes in the order they were created our_stuff.sort(key=lambda key: our_stuff[key]._creation_order) # extract columns from the class dict cols = [] for key, c in our_stuff.iteritems(): if isinstance(c, ColumnProperty): for col in c.columns: if isinstance(col, Column) and col.table is None: _undefer_column_name(key, col) cols.append(col) elif isinstance(c, Column): _undefer_column_name(key, c) cols.append(c) # if the column is the same name as the key, # remove it from the explicit properties dict. # the normal rules for assigning column-based properties # will take over, including precedence of columns # in multi-column ColumnProperties. if key == c.key: del our_stuff[key] table = None if '__table__' not in dict_: if tablename is not None: if isinstance(table_args, dict): args, table_kw = (), table_args elif isinstance(table_args, tuple): args = table_args[0:-1] table_kw = table_args[-1] if len(table_args) < 2 or not isinstance(table_kw, dict): raise exceptions.ArgumentError( "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) else: args, table_kw = (), {} autoload = dict_.get('__autoload__') if autoload: table_kw['autoload'] = True cls.__table__ = table = Table(tablename, cls.metadata, *(tuple(cols) + tuple(args)), **table_kw) else: table = cls.__table__ if cols: for c in cols: if not table.c.contains_column(c): raise exceptions.ArgumentError( "Can't add additional column %r when specifying __table__" % key ) if 'inherits' not in mapper_args: for c in cls.__bases__: if _is_mapped_class(c): mapper_args['inherits'] = cls._decl_class_registry.get(c.__name__, None) break if hasattr(cls, '__mapper_cls__'): mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__) else: mapper_cls = mapper if table is None and 'inherits' not in mapper_args: raise exceptions.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing table-mapped class." % cls ) elif 'inherits' in mapper_args and not mapper_args.get('concrete', False): inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'inherit_condition' not in mapper_args and table is not None: # figure out the inherit condition with relaxed rules # about nonexistent tables, to allow for ForeignKeys to # not-yet-defined tables (since we know for sure that our # parent table is defined within the same MetaData) mapper_args['inherit_condition'] = sql_util.join_condition( mapper_args['inherits'].__table__, table, ignore_nonexistent_tables=True) if table is None: # single table inheritance. # ensure no table args if table_args: raise exceptions.ArgumentError( "Can't place __table_args__ on an inherited class with no table." ) # add any columns declared here to the inherited table. for c in cols: if c.primary_key: raise exceptions.ArgumentError( "Can't place primary key columns on an inherited class with no table." ) if c.name in inherited_table.c: raise exceptions.ArgumentError( "Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) inherited_table.append_column(c) # single or joined inheritance # exclude any cols on the inherited table which are not mapped on the # parent class, to avoid # mapping columns specific to sibling/nephew classes inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'exclude_properties' not in mapper_args: mapper_args['exclude_properties'] = exclude_properties = \ set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update([c.key for c in cols]) cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args) |
"specified and does not inherit from an existing table-mapped class." % cls | "specified and does not inherit from an existing " "table-mapped class." % cls | def _as_declarative(cls, classname, dict_): # dict_ will be a dictproxy, which we can't write to, and we need to! dict_ = dict(dict_) column_copies = {} potential_columns = {} mapper_args = {} table_args = inherited_table_args = None tablename = None parent_columns = () for base in cls.__mro__: if _is_mapped_class(base): parent_columns = base.__table__.c.keys() else: for name,obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args: mapper_args = cls.__mapper_args__ elif name == '__tablename__': if not tablename: tablename = cls.__tablename__ elif name == '__table_args__': if not table_args: table_args = cls.__table_args__ if base is not cls: inherited_table_args = True elif base is not cls: # we're a mixin. if isinstance(obj, Column): if obj.foreign_keys: raise exceptions.InvalidRequestError( "Columns with foreign keys to other columns " "must be declared as @classproperty callables " "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and name in dict_['__table__'].c ): potential_columns[name] = \ column_copies[obj] = \ obj.copy() column_copies[obj]._creation_order = \ obj._creation_order elif isinstance(obj, MapperProperty): raise exceptions.InvalidRequestError( "Mapper properties (i.e. deferred," "column_property(), relationship(), etc.) must " "be declared as @classproperty callables " "on declarative mixin classes.") elif isinstance(obj, util.classproperty): dict_[name] = ret = \ column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should for k, v in potential_columns.items(): if tablename or k not in parent_columns: dict_[k] = v if inherited_table_args and not tablename: table_args = None # make sure that column copies are used rather # than the original columns from any mixins for k, v in mapper_args.iteritems(): mapper_args[k] = column_copies.get(v,v) cls._decl_class_registry[classname] = cls our_stuff = util.OrderedDict() for k in dict_: value = dict_[k] if (isinstance(value, tuple) and len(value) == 1 and isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) continue if not isinstance(value, (Column, MapperProperty)): continue prop = _deferred_relationship(cls, value) our_stuff[k] = prop # set up attributes in the order they were created our_stuff.sort(key=lambda key: our_stuff[key]._creation_order) # extract columns from the class dict cols = [] for key, c in our_stuff.iteritems(): if isinstance(c, ColumnProperty): for col in c.columns: if isinstance(col, Column) and col.table is None: _undefer_column_name(key, col) cols.append(col) elif isinstance(c, Column): _undefer_column_name(key, c) cols.append(c) # if the column is the same name as the key, # remove it from the explicit properties dict. # the normal rules for assigning column-based properties # will take over, including precedence of columns # in multi-column ColumnProperties. if key == c.key: del our_stuff[key] table = None if '__table__' not in dict_: if tablename is not None: if isinstance(table_args, dict): args, table_kw = (), table_args elif isinstance(table_args, tuple): args = table_args[0:-1] table_kw = table_args[-1] if len(table_args) < 2 or not isinstance(table_kw, dict): raise exceptions.ArgumentError( "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) else: args, table_kw = (), {} autoload = dict_.get('__autoload__') if autoload: table_kw['autoload'] = True cls.__table__ = table = Table(tablename, cls.metadata, *(tuple(cols) + tuple(args)), **table_kw) else: table = cls.__table__ if cols: for c in cols: if not table.c.contains_column(c): raise exceptions.ArgumentError( "Can't add additional column %r when specifying __table__" % key ) if 'inherits' not in mapper_args: for c in cls.__bases__: if _is_mapped_class(c): mapper_args['inherits'] = cls._decl_class_registry.get(c.__name__, None) break if hasattr(cls, '__mapper_cls__'): mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__) else: mapper_cls = mapper if table is None and 'inherits' not in mapper_args: raise exceptions.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing table-mapped class." % cls ) elif 'inherits' in mapper_args and not mapper_args.get('concrete', False): inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'inherit_condition' not in mapper_args and table is not None: # figure out the inherit condition with relaxed rules # about nonexistent tables, to allow for ForeignKeys to # not-yet-defined tables (since we know for sure that our # parent table is defined within the same MetaData) mapper_args['inherit_condition'] = sql_util.join_condition( mapper_args['inherits'].__table__, table, ignore_nonexistent_tables=True) if table is None: # single table inheritance. # ensure no table args if table_args: raise exceptions.ArgumentError( "Can't place __table_args__ on an inherited class with no table." ) # add any columns declared here to the inherited table. for c in cols: if c.primary_key: raise exceptions.ArgumentError( "Can't place primary key columns on an inherited class with no table." ) if c.name in inherited_table.c: raise exceptions.ArgumentError( "Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) inherited_table.append_column(c) # single or joined inheritance # exclude any cols on the inherited table which are not mapped on the # parent class, to avoid # mapping columns specific to sibling/nephew classes inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'exclude_properties' not in mapper_args: mapper_args['exclude_properties'] = exclude_properties = \ set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update([c.key for c in cols]) cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args) |
"Can't place __table_args__ on an inherited class with no table." | "Can't place __table_args__ on an inherited class " "with no table." | def _as_declarative(cls, classname, dict_): # dict_ will be a dictproxy, which we can't write to, and we need to! dict_ = dict(dict_) column_copies = {} potential_columns = {} mapper_args = {} table_args = inherited_table_args = None tablename = None parent_columns = () for base in cls.__mro__: if _is_mapped_class(base): parent_columns = base.__table__.c.keys() else: for name,obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args: mapper_args = cls.__mapper_args__ elif name == '__tablename__': if not tablename: tablename = cls.__tablename__ elif name == '__table_args__': if not table_args: table_args = cls.__table_args__ if base is not cls: inherited_table_args = True elif base is not cls: # we're a mixin. if isinstance(obj, Column): if obj.foreign_keys: raise exceptions.InvalidRequestError( "Columns with foreign keys to other columns " "must be declared as @classproperty callables " "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and name in dict_['__table__'].c ): potential_columns[name] = \ column_copies[obj] = \ obj.copy() column_copies[obj]._creation_order = \ obj._creation_order elif isinstance(obj, MapperProperty): raise exceptions.InvalidRequestError( "Mapper properties (i.e. deferred," "column_property(), relationship(), etc.) must " "be declared as @classproperty callables " "on declarative mixin classes.") elif isinstance(obj, util.classproperty): dict_[name] = ret = \ column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should for k, v in potential_columns.items(): if tablename or k not in parent_columns: dict_[k] = v if inherited_table_args and not tablename: table_args = None # make sure that column copies are used rather # than the original columns from any mixins for k, v in mapper_args.iteritems(): mapper_args[k] = column_copies.get(v,v) cls._decl_class_registry[classname] = cls our_stuff = util.OrderedDict() for k in dict_: value = dict_[k] if (isinstance(value, tuple) and len(value) == 1 and isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) continue if not isinstance(value, (Column, MapperProperty)): continue prop = _deferred_relationship(cls, value) our_stuff[k] = prop # set up attributes in the order they were created our_stuff.sort(key=lambda key: our_stuff[key]._creation_order) # extract columns from the class dict cols = [] for key, c in our_stuff.iteritems(): if isinstance(c, ColumnProperty): for col in c.columns: if isinstance(col, Column) and col.table is None: _undefer_column_name(key, col) cols.append(col) elif isinstance(c, Column): _undefer_column_name(key, c) cols.append(c) # if the column is the same name as the key, # remove it from the explicit properties dict. # the normal rules for assigning column-based properties # will take over, including precedence of columns # in multi-column ColumnProperties. if key == c.key: del our_stuff[key] table = None if '__table__' not in dict_: if tablename is not None: if isinstance(table_args, dict): args, table_kw = (), table_args elif isinstance(table_args, tuple): args = table_args[0:-1] table_kw = table_args[-1] if len(table_args) < 2 or not isinstance(table_kw, dict): raise exceptions.ArgumentError( "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) else: args, table_kw = (), {} autoload = dict_.get('__autoload__') if autoload: table_kw['autoload'] = True cls.__table__ = table = Table(tablename, cls.metadata, *(tuple(cols) + tuple(args)), **table_kw) else: table = cls.__table__ if cols: for c in cols: if not table.c.contains_column(c): raise exceptions.ArgumentError( "Can't add additional column %r when specifying __table__" % key ) if 'inherits' not in mapper_args: for c in cls.__bases__: if _is_mapped_class(c): mapper_args['inherits'] = cls._decl_class_registry.get(c.__name__, None) break if hasattr(cls, '__mapper_cls__'): mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__) else: mapper_cls = mapper if table is None and 'inherits' not in mapper_args: raise exceptions.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing table-mapped class." % cls ) elif 'inherits' in mapper_args and not mapper_args.get('concrete', False): inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'inherit_condition' not in mapper_args and table is not None: # figure out the inherit condition with relaxed rules # about nonexistent tables, to allow for ForeignKeys to # not-yet-defined tables (since we know for sure that our # parent table is defined within the same MetaData) mapper_args['inherit_condition'] = sql_util.join_condition( mapper_args['inherits'].__table__, table, ignore_nonexistent_tables=True) if table is None: # single table inheritance. # ensure no table args if table_args: raise exceptions.ArgumentError( "Can't place __table_args__ on an inherited class with no table." ) # add any columns declared here to the inherited table. for c in cols: if c.primary_key: raise exceptions.ArgumentError( "Can't place primary key columns on an inherited class with no table." ) if c.name in inherited_table.c: raise exceptions.ArgumentError( "Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) inherited_table.append_column(c) # single or joined inheritance # exclude any cols on the inherited table which are not mapped on the # parent class, to avoid # mapping columns specific to sibling/nephew classes inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'exclude_properties' not in mapper_args: mapper_args['exclude_properties'] = exclude_properties = \ set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update([c.key for c in cols]) cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args) |
"Can't place primary key columns on an inherited class with no table." | "Can't place primary key columns on an inherited " "class with no table." | def _as_declarative(cls, classname, dict_): # dict_ will be a dictproxy, which we can't write to, and we need to! dict_ = dict(dict_) column_copies = {} potential_columns = {} mapper_args = {} table_args = inherited_table_args = None tablename = None parent_columns = () for base in cls.__mro__: if _is_mapped_class(base): parent_columns = base.__table__.c.keys() else: for name,obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args: mapper_args = cls.__mapper_args__ elif name == '__tablename__': if not tablename: tablename = cls.__tablename__ elif name == '__table_args__': if not table_args: table_args = cls.__table_args__ if base is not cls: inherited_table_args = True elif base is not cls: # we're a mixin. if isinstance(obj, Column): if obj.foreign_keys: raise exceptions.InvalidRequestError( "Columns with foreign keys to other columns " "must be declared as @classproperty callables " "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and name in dict_['__table__'].c ): potential_columns[name] = \ column_copies[obj] = \ obj.copy() column_copies[obj]._creation_order = \ obj._creation_order elif isinstance(obj, MapperProperty): raise exceptions.InvalidRequestError( "Mapper properties (i.e. deferred," "column_property(), relationship(), etc.) must " "be declared as @classproperty callables " "on declarative mixin classes.") elif isinstance(obj, util.classproperty): dict_[name] = ret = \ column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should for k, v in potential_columns.items(): if tablename or k not in parent_columns: dict_[k] = v if inherited_table_args and not tablename: table_args = None # make sure that column copies are used rather # than the original columns from any mixins for k, v in mapper_args.iteritems(): mapper_args[k] = column_copies.get(v,v) cls._decl_class_registry[classname] = cls our_stuff = util.OrderedDict() for k in dict_: value = dict_[k] if (isinstance(value, tuple) and len(value) == 1 and isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) continue if not isinstance(value, (Column, MapperProperty)): continue prop = _deferred_relationship(cls, value) our_stuff[k] = prop # set up attributes in the order they were created our_stuff.sort(key=lambda key: our_stuff[key]._creation_order) # extract columns from the class dict cols = [] for key, c in our_stuff.iteritems(): if isinstance(c, ColumnProperty): for col in c.columns: if isinstance(col, Column) and col.table is None: _undefer_column_name(key, col) cols.append(col) elif isinstance(c, Column): _undefer_column_name(key, c) cols.append(c) # if the column is the same name as the key, # remove it from the explicit properties dict. # the normal rules for assigning column-based properties # will take over, including precedence of columns # in multi-column ColumnProperties. if key == c.key: del our_stuff[key] table = None if '__table__' not in dict_: if tablename is not None: if isinstance(table_args, dict): args, table_kw = (), table_args elif isinstance(table_args, tuple): args = table_args[0:-1] table_kw = table_args[-1] if len(table_args) < 2 or not isinstance(table_kw, dict): raise exceptions.ArgumentError( "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) else: args, table_kw = (), {} autoload = dict_.get('__autoload__') if autoload: table_kw['autoload'] = True cls.__table__ = table = Table(tablename, cls.metadata, *(tuple(cols) + tuple(args)), **table_kw) else: table = cls.__table__ if cols: for c in cols: if not table.c.contains_column(c): raise exceptions.ArgumentError( "Can't add additional column %r when specifying __table__" % key ) if 'inherits' not in mapper_args: for c in cls.__bases__: if _is_mapped_class(c): mapper_args['inherits'] = cls._decl_class_registry.get(c.__name__, None) break if hasattr(cls, '__mapper_cls__'): mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__) else: mapper_cls = mapper if table is None and 'inherits' not in mapper_args: raise exceptions.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing table-mapped class." % cls ) elif 'inherits' in mapper_args and not mapper_args.get('concrete', False): inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'inherit_condition' not in mapper_args and table is not None: # figure out the inherit condition with relaxed rules # about nonexistent tables, to allow for ForeignKeys to # not-yet-defined tables (since we know for sure that our # parent table is defined within the same MetaData) mapper_args['inherit_condition'] = sql_util.join_condition( mapper_args['inherits'].__table__, table, ignore_nonexistent_tables=True) if table is None: # single table inheritance. # ensure no table args if table_args: raise exceptions.ArgumentError( "Can't place __table_args__ on an inherited class with no table." ) # add any columns declared here to the inherited table. for c in cols: if c.primary_key: raise exceptions.ArgumentError( "Can't place primary key columns on an inherited class with no table." ) if c.name in inherited_table.c: raise exceptions.ArgumentError( "Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) inherited_table.append_column(c) # single or joined inheritance # exclude any cols on the inherited table which are not mapped on the # parent class, to avoid # mapping columns specific to sibling/nephew classes inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'exclude_properties' not in mapper_args: mapper_args['exclude_properties'] = exclude_properties = \ set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update([c.key for c in cols]) cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args) |
"Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) | "Column '%s' on class %s conflicts with " "existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) | def _as_declarative(cls, classname, dict_): # dict_ will be a dictproxy, which we can't write to, and we need to! dict_ = dict(dict_) column_copies = {} potential_columns = {} mapper_args = {} table_args = inherited_table_args = None tablename = None parent_columns = () for base in cls.__mro__: if _is_mapped_class(base): parent_columns = base.__table__.c.keys() else: for name,obj in vars(base).items(): if name == '__mapper_args__': if not mapper_args: mapper_args = cls.__mapper_args__ elif name == '__tablename__': if not tablename: tablename = cls.__tablename__ elif name == '__table_args__': if not table_args: table_args = cls.__table_args__ if base is not cls: inherited_table_args = True elif base is not cls: # we're a mixin. if isinstance(obj, Column): if obj.foreign_keys: raise exceptions.InvalidRequestError( "Columns with foreign keys to other columns " "must be declared as @classproperty callables " "on declarative mixin classes. ") if name not in dict_ and not ( '__table__' in dict_ and name in dict_['__table__'].c ): potential_columns[name] = \ column_copies[obj] = \ obj.copy() column_copies[obj]._creation_order = \ obj._creation_order elif isinstance(obj, MapperProperty): raise exceptions.InvalidRequestError( "Mapper properties (i.e. deferred," "column_property(), relationship(), etc.) must " "be declared as @classproperty callables " "on declarative mixin classes.") elif isinstance(obj, util.classproperty): dict_[name] = ret = \ column_copies[obj] = getattr(cls, name) if isinstance(ret, (Column, MapperProperty)) and \ ret.doc is None: ret.doc = obj.__doc__ # apply inherited columns as we should for k, v in potential_columns.items(): if tablename or k not in parent_columns: dict_[k] = v if inherited_table_args and not tablename: table_args = None # make sure that column copies are used rather # than the original columns from any mixins for k, v in mapper_args.iteritems(): mapper_args[k] = column_copies.get(v,v) cls._decl_class_registry[classname] = cls our_stuff = util.OrderedDict() for k in dict_: value = dict_[k] if (isinstance(value, tuple) and len(value) == 1 and isinstance(value[0], (Column, MapperProperty))): util.warn("Ignoring declarative-like tuple value of attribute " "%s: possibly a copy-and-paste error with a comma " "left at the end of the line?" % k) continue if not isinstance(value, (Column, MapperProperty)): continue prop = _deferred_relationship(cls, value) our_stuff[k] = prop # set up attributes in the order they were created our_stuff.sort(key=lambda key: our_stuff[key]._creation_order) # extract columns from the class dict cols = [] for key, c in our_stuff.iteritems(): if isinstance(c, ColumnProperty): for col in c.columns: if isinstance(col, Column) and col.table is None: _undefer_column_name(key, col) cols.append(col) elif isinstance(c, Column): _undefer_column_name(key, c) cols.append(c) # if the column is the same name as the key, # remove it from the explicit properties dict. # the normal rules for assigning column-based properties # will take over, including precedence of columns # in multi-column ColumnProperties. if key == c.key: del our_stuff[key] table = None if '__table__' not in dict_: if tablename is not None: if isinstance(table_args, dict): args, table_kw = (), table_args elif isinstance(table_args, tuple): args = table_args[0:-1] table_kw = table_args[-1] if len(table_args) < 2 or not isinstance(table_kw, dict): raise exceptions.ArgumentError( "Tuple form of __table_args__ is " "(arg1, arg2, arg3, ..., {'kw1':val1, 'kw2':val2, ...})" ) else: args, table_kw = (), {} autoload = dict_.get('__autoload__') if autoload: table_kw['autoload'] = True cls.__table__ = table = Table(tablename, cls.metadata, *(tuple(cols) + tuple(args)), **table_kw) else: table = cls.__table__ if cols: for c in cols: if not table.c.contains_column(c): raise exceptions.ArgumentError( "Can't add additional column %r when specifying __table__" % key ) if 'inherits' not in mapper_args: for c in cls.__bases__: if _is_mapped_class(c): mapper_args['inherits'] = cls._decl_class_registry.get(c.__name__, None) break if hasattr(cls, '__mapper_cls__'): mapper_cls = util.unbound_method_to_callable(cls.__mapper_cls__) else: mapper_cls = mapper if table is None and 'inherits' not in mapper_args: raise exceptions.InvalidRequestError( "Class %r does not have a __table__ or __tablename__ " "specified and does not inherit from an existing table-mapped class." % cls ) elif 'inherits' in mapper_args and not mapper_args.get('concrete', False): inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'inherit_condition' not in mapper_args and table is not None: # figure out the inherit condition with relaxed rules # about nonexistent tables, to allow for ForeignKeys to # not-yet-defined tables (since we know for sure that our # parent table is defined within the same MetaData) mapper_args['inherit_condition'] = sql_util.join_condition( mapper_args['inherits'].__table__, table, ignore_nonexistent_tables=True) if table is None: # single table inheritance. # ensure no table args if table_args: raise exceptions.ArgumentError( "Can't place __table_args__ on an inherited class with no table." ) # add any columns declared here to the inherited table. for c in cols: if c.primary_key: raise exceptions.ArgumentError( "Can't place primary key columns on an inherited class with no table." ) if c.name in inherited_table.c: raise exceptions.ArgumentError( "Column '%s' on class %s conflicts with existing column '%s'" % (c, cls, inherited_table.c[c.name]) ) inherited_table.append_column(c) # single or joined inheritance # exclude any cols on the inherited table which are not mapped on the # parent class, to avoid # mapping columns specific to sibling/nephew classes inherited_mapper = class_mapper(mapper_args['inherits'], compile=False) inherited_table = inherited_mapper.local_table if 'exclude_properties' not in mapper_args: mapper_args['exclude_properties'] = exclude_properties = \ set([c.key for c in inherited_table.c if c not in inherited_mapper._columntoproperty]) exclude_properties.difference_update([c.key for c in cols]) cls.__mapper__ = mapper_cls(cls, table, properties=our_stuff, **mapper_args) |
"When compiling mapper %s, expression %r failed to locate a name (%r). " "If this is a class name, consider adding this relationship() to the %r " "class after both dependent classes have been defined." % ( prop.parent, arg, n.args[0], cls)) | "When compiling mapper %s, expression %r failed to " "locate a name (%r). If this is a class name, consider " "adding this relationship() to the %r class after " "both dependent classes have been defined." % (prop.parent, arg, n.args[0], cls) ) | def return_cls(): try: x = eval(arg, globals(), d) if isinstance(x, _GetColumns): return x.cls else: return x except NameError, n: raise exceptions.InvalidRequestError( "When compiling mapper %s, expression %r failed to locate a name (%r). " "If this is a class name, consider adding this relationship() to the %r " "class after both dependent classes have been defined." % ( prop.parent, arg, n.args[0], cls)) |
query = """ | query = sql.text(""" | def _get_default_schema_name(self, connection): user_name = connection.scalar("SELECT user_name() as user_name;") if user_name is not None: # now, get the default schema query = """ SELECT default_schema_name FROM sys.database_principals WHERE name = ? AND type = 'S' """ try: default_schema_name = connection.scalar(query, [user_name]) if default_schema_name is not None: return unicode(default_schema_name) except: pass return self.schema_name |
WHERE name = ? | WHERE name = :name | def _get_default_schema_name(self, connection): user_name = connection.scalar("SELECT user_name() as user_name;") if user_name is not None: # now, get the default schema query = """ SELECT default_schema_name FROM sys.database_principals WHERE name = ? AND type = 'S' """ try: default_schema_name = connection.scalar(query, [user_name]) if default_schema_name is not None: return unicode(default_schema_name) except: pass return self.schema_name |
""" | """) | def _get_default_schema_name(self, connection): user_name = connection.scalar("SELECT user_name() as user_name;") if user_name is not None: # now, get the default schema query = """ SELECT default_schema_name FROM sys.database_principals WHERE name = ? AND type = 'S' """ try: default_schema_name = connection.scalar(query, [user_name]) if default_schema_name is not None: return unicode(default_schema_name) except: pass return self.schema_name |
default_schema_name = connection.scalar(query, [user_name]) | default_schema_name = connection.scalar(query, name=user_name) | def _get_default_schema_name(self, connection): user_name = connection.scalar("SELECT user_name() as user_name;") if user_name is not None: # now, get the default schema query = """ SELECT default_schema_name FROM sys.database_principals WHERE name = ? AND type = 'S' """ try: default_schema_name = connection.scalar(query, [user_name]) if default_schema_name is not None: return unicode(default_schema_name) except: pass return self.schema_name |
@collection.adds('entity'): | @collection.adds('entity') | def append(self, append): ... |
self.listeners.append(obj) | if obj not in self.listeners: self.listeners.append(obj) | def append(self, obj, target): # this will be needed, but not # sure why we don't seem to need it yet |
return None | return processors.to_str | def bind_processor(self, dialect): return None |
colfuncs[name.lower()] = (self._ambiguous_processor(origname), i, "ambiguous") | colfuncs[origname.lower()] = (self._ambiguous_processor(origname), i, "ambiguous") | def getcol(row): return processor(row[index]) |
Column('col2', PickleType(comparator=operator.eq)) | Column('col2', PickleType(comparator=operator.eq, mutable=True)) | def test_mutable_identity(self): metadata = MetaData(testing.db) |
def _get_attr(self): return self._some_attr def _set_attr(self, attr): self._some_attr = attr attr = synonym('_attr', descriptor=property(_get_attr, _set_attr)) | @property def attr(self): return self._attr @attr.setter def attr(self, attr): self._attr = attr attr = synonym('_attr', descriptor=attr) | def _get_attr(self): return self._some_attr |
id = Column(Integer, primary_key=True) | def _set_attr(self, attr): self._some_attr = attr |
|
return self._some_attr | return self._attr | def attr(self): return self._some_attr |
:func:`~sqlalchemy.orm.comparable_property` ORM function:: | :func:`~.comparable_property` ORM function:: | def attr(self): return self._some_attr |
global employees_table, metadata | def setup_class(cls): metadata = MetaData(testing.db) |
|
oracle8dialect._supports_char_length = False | oracle8dialect.server_version_info = (8, 0) | def test_char_length(self): self.assert_compile(VARCHAR(50),"VARCHAR(50 CHAR)") |
return instance._should_log_debug and 'debug' or \ (instance._should_log_info and True or False) | return instance._should_log_debug() and 'debug' or \ (instance._should_log_info() and True or False) | def __get__(self, instance, owner): if instance is None: return self else: return instance._should_log_debug and 'debug' or \ (instance._should_log_info and True or False) |
assert dialect.table_names(cx, 'test_schema') == [] | assert dialect.get_table_names(cx, 'test_schema') == [] | def test_attached_as_schema(self): cx = testing.db.connect() try: cx.execute('ATTACH DATABASE ":memory:" AS test_schema') dialect = cx.dialect assert dialect.table_names(cx, 'test_schema') == [] |
eq_(dialect.table_names(cx, 'test_schema'), | eq_(dialect.get_table_names(cx, 'test_schema'), | def test_attached_as_schema(self): cx = testing.db.connect() try: cx.execute('ATTACH DATABASE ":memory:" AS test_schema') dialect = cx.dialect assert dialect.table_names(cx, 'test_schema') == [] |
assert 'tempy' in cx.dialect.table_names(cx, None) | assert 'tempy' in cx.dialect.get_table_names(cx, None) | def test_temp_table_reflection(self): cx = testing.db.connect() try: cx.execute('CREATE TEMPORARY TABLE tempy (id INT)') |
t1.create() | metadata.create_all() | def test_default_exec(self): metadata = MetaData(testing.db) t1 = Table('t1', metadata, Column(u'special_col', Integer, Sequence('special_col'), primary_key=True), Column('data', String(50)) # to appease SQLite without DEFAULT VALUES ) t1.create() |
t1.drop() | metadata.drop_all() | def test_default_exec(self): metadata = MetaData(testing.db) t1 = Table('t1', metadata, Column(u'special_col', Integer, Sequence('special_col'), primary_key=True), Column('data', String(50)) # to appease SQLite without DEFAULT VALUES ) t1.create() |
print "\nSQL String:\n" + str(c) + repr(getattr(c, 'params', {})) | print "\nSQL String:\n" + str(c) + param_str | def assert_compile(self, clause, result, params=None, checkparams=None, dialect=None, use_default_dialect=False): if use_default_dialect: dialect = default.DefaultDialect() if dialect is None: dialect = getattr(self, '__dialect__', None) |
assert cache_key is not None, "Cache key was None !" | def _get_cache_parameters(query): """For a query with cache_region and cache_namespace configured, return the correspoinding Cache instance and cache key, based on this query's current criterion and parameter values. """ if not hasattr(query, '_cache_parameters'): raise ValueError("This Query does not have caching parameters configured.") region, namespace, cache_key = query._cache_parameters namespace = _namespace_from_query(namespace, query) if cache_key is None: # cache key - the value arguments from this query's parameters. args = _params_from_query(query) cache_key = " ".join([str(x) for x in args]) # get cache cache = query.cache_manager.get_cache_region(namespace, region) # optional - hash the cache_key too for consistent length # import uuid # cache_key= str(uuid.uuid5(uuid.NAMESPACE_DNS, cache_key)) return cache, cache_key |
|
value = query._params.get(bind.key, bind.value) if callable(value): value = value() | if bind.key in query._params: value = query._params[bind.key] elif bind.callable: value = bind.callable() else: value = bind.value | def visit_bindparam(bind): value = query._params.get(bind.key, bind.value) # lazyloader may dig a callable in here, intended # to late-evaluate params after autoflush is called. # convert to a scalar value. if callable(value): value = value() v.append(value) |
type = DATE() | type = Date() | def test_conn_execute(self): from sqlalchemy.sql.expression import FunctionElement from sqlalchemy.ext.compiler import compiles class myfunc(FunctionElement): type = DATE() @compiles(myfunc) def compile(elem, compiler, **kw): return compiler.process(func.current_date()) |
filter(User.name.like.('%ed%')).\\ | filter(User.name.like('%ed%')).\\ | def with_entities(self, *entities): """Return a new :class:`.Query` replacing the SELECT list with the given entities. e.g.:: |
controls a Python logger; see `dbengine_logging` at the end of this chapter for information on how to configure logging directly. | controls a Python logger; see :ref:`dbengine_logging` for information on how to configure logging directly. | def create_engine(*args, **kwargs): """Create a new Engine instance. The standard method of specifying the engine is via URL as the first positional argument, to indicate the appropriate database dialect and connection arguments, with additional keyword arguments sent as options to the dialect and resulting Engine. The URL is a string in the form ``dialect://user:password@host/dbname[?key=value..]``, where ``dialect`` is a name such as ``mysql``, ``oracle``, ``postgresql``, etc. Alternatively, the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`. `**kwargs` takes a wide variety of options which are routed towards their appropriate components. Arguments may be specific to the Engine, the underlying Dialect, as well as the Pool. Specific dialects also accept keyword arguments that are unique to that dialect. Here, we describe the parameters that are common to most ``create_engine()`` usage. :param assert_unicode: Deprecated. A warning is raised in all cases when a non-Unicode object is passed when SQLAlchemy would coerce into an encoding (note: but **not** when the DBAPI handles unicode objects natively). To suppress or raise this warning to an error, use the Python warnings filter documented at: http://docs.python.org/library/warnings.html :param connect_args: a dictionary of options which will be passed directly to the DBAPI's ``connect()`` method as additional keyword arguments. :param convert_unicode=False: if set to True, all String/character based types will convert Unicode values to raw byte values going into the database, and all raw byte values to Python Unicode coming out in result sets. This is an engine-wide method to provide unicode conversion across the board. For unicode conversion on a column-by-column level, use the ``Unicode`` column type instead, described in `types`. :param creator: a callable which returns a DBAPI connection. This creation function will be passed to the underlying connection pool and will be used to create all new database connections. Usage of this function causes connection parameters specified in the URL argument to be bypassed. :param echo=False: if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout. The ``echo`` attribute of ``Engine`` can be modified at any time to turn logging on and off. If set to the string ``"debug"``, result rows will be printed to the standard output as well. This flag ultimately controls a Python logger; see `dbengine_logging` at the end of this chapter for information on how to configure logging directly. :param echo_pool=False: if True, the connection pool will log all checkouts/checkins to the logging stream, which defaults to sys.stdout. This flag ultimately controls a Python logger; see `dbengine_logging` for information on how to configure logging directly. :param encoding='utf-8': the encoding to use for all Unicode translations, both by engine-wide unicode conversion as well as the ``Unicode`` type object. :param label_length=None: optional integer value which limits the size of dynamically generated column labels to that many characters. If less than 6, labels are generated as "_(counter)". If ``None``, the value of ``dialect.max_identifier_length`` is used instead. :param module=None: used by database implementations which support multiple DBAPI modules, this is a reference to a DBAPI2 module to be used instead of the engine's default module. For PostgreSQL, the default is psycopg2. For Oracle, it's cx_Oracle. :param pool=None: an already-constructed instance of :class:`~sqlalchemy.pool.Pool`, such as a :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this pool will be used directly as the underlying connection pool for the engine, bypassing whatever connection parameters are present in the URL argument. For information on constructing connection pools manually, see `pooling`. :param poolclass=None: a :class:`~sqlalchemy.pool.Pool` subclass, which will be used to create a connection pool instance using the connection parameters given in the URL. Note this differs from ``pool`` in that you don't actually instantiate the pool in this case, you just indicate what type of pool to be used. :param max_overflow=10: the number of connections to allow in connection pool "overflow", that is connections that can be opened above and beyond the pool_size setting, which defaults to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`. :param pool_size=5: the number of connections to keep open inside the connection pool. This used with :class:`~sqlalchemy.pool.QueuePool` as well as :class:`~sqlalchemy.pool.SingletonThreadPool`. :param pool_recycle=-1: this setting causes the pool to recycle connections after the given number of seconds has passed. It defaults to -1, or no timeout. For example, setting to 3600 means connections will be recycled after one hour. Note that MySQL in particular will ``disconnect automatically`` if no activity is detected on a connection for eight hours (although this is configurable with the MySQLDB connection itself and the server configuration as well). :param pool_timeout=30: number of seconds to wait before giving up on getting a connection from the pool. This is only used with :class:`~sqlalchemy.pool.QueuePool`. :param strategy='plain': used to invoke alternate :class:`~sqlalchemy.engine.base.Engine.` implementations. Currently available is the ``threadlocal`` strategy, which is described in :ref:`threadlocal_strategy`. """ strategy = kwargs.pop('strategy', default_strategy) strategy = strategies.strategies[strategy] return strategy.create(*args, **kwargs) |
`dbengine_logging` for information on how to configure logging | :ref:`dbengine_logging` for information on how to configure logging | def create_engine(*args, **kwargs): """Create a new Engine instance. The standard method of specifying the engine is via URL as the first positional argument, to indicate the appropriate database dialect and connection arguments, with additional keyword arguments sent as options to the dialect and resulting Engine. The URL is a string in the form ``dialect://user:password@host/dbname[?key=value..]``, where ``dialect`` is a name such as ``mysql``, ``oracle``, ``postgresql``, etc. Alternatively, the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`. `**kwargs` takes a wide variety of options which are routed towards their appropriate components. Arguments may be specific to the Engine, the underlying Dialect, as well as the Pool. Specific dialects also accept keyword arguments that are unique to that dialect. Here, we describe the parameters that are common to most ``create_engine()`` usage. :param assert_unicode: Deprecated. A warning is raised in all cases when a non-Unicode object is passed when SQLAlchemy would coerce into an encoding (note: but **not** when the DBAPI handles unicode objects natively). To suppress or raise this warning to an error, use the Python warnings filter documented at: http://docs.python.org/library/warnings.html :param connect_args: a dictionary of options which will be passed directly to the DBAPI's ``connect()`` method as additional keyword arguments. :param convert_unicode=False: if set to True, all String/character based types will convert Unicode values to raw byte values going into the database, and all raw byte values to Python Unicode coming out in result sets. This is an engine-wide method to provide unicode conversion across the board. For unicode conversion on a column-by-column level, use the ``Unicode`` column type instead, described in `types`. :param creator: a callable which returns a DBAPI connection. This creation function will be passed to the underlying connection pool and will be used to create all new database connections. Usage of this function causes connection parameters specified in the URL argument to be bypassed. :param echo=False: if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout. The ``echo`` attribute of ``Engine`` can be modified at any time to turn logging on and off. If set to the string ``"debug"``, result rows will be printed to the standard output as well. This flag ultimately controls a Python logger; see `dbengine_logging` at the end of this chapter for information on how to configure logging directly. :param echo_pool=False: if True, the connection pool will log all checkouts/checkins to the logging stream, which defaults to sys.stdout. This flag ultimately controls a Python logger; see `dbengine_logging` for information on how to configure logging directly. :param encoding='utf-8': the encoding to use for all Unicode translations, both by engine-wide unicode conversion as well as the ``Unicode`` type object. :param label_length=None: optional integer value which limits the size of dynamically generated column labels to that many characters. If less than 6, labels are generated as "_(counter)". If ``None``, the value of ``dialect.max_identifier_length`` is used instead. :param module=None: used by database implementations which support multiple DBAPI modules, this is a reference to a DBAPI2 module to be used instead of the engine's default module. For PostgreSQL, the default is psycopg2. For Oracle, it's cx_Oracle. :param pool=None: an already-constructed instance of :class:`~sqlalchemy.pool.Pool`, such as a :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this pool will be used directly as the underlying connection pool for the engine, bypassing whatever connection parameters are present in the URL argument. For information on constructing connection pools manually, see `pooling`. :param poolclass=None: a :class:`~sqlalchemy.pool.Pool` subclass, which will be used to create a connection pool instance using the connection parameters given in the URL. Note this differs from ``pool`` in that you don't actually instantiate the pool in this case, you just indicate what type of pool to be used. :param max_overflow=10: the number of connections to allow in connection pool "overflow", that is connections that can be opened above and beyond the pool_size setting, which defaults to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`. :param pool_size=5: the number of connections to keep open inside the connection pool. This used with :class:`~sqlalchemy.pool.QueuePool` as well as :class:`~sqlalchemy.pool.SingletonThreadPool`. :param pool_recycle=-1: this setting causes the pool to recycle connections after the given number of seconds has passed. It defaults to -1, or no timeout. For example, setting to 3600 means connections will be recycled after one hour. Note that MySQL in particular will ``disconnect automatically`` if no activity is detected on a connection for eight hours (although this is configurable with the MySQLDB connection itself and the server configuration as well). :param pool_timeout=30: number of seconds to wait before giving up on getting a connection from the pool. This is only used with :class:`~sqlalchemy.pool.QueuePool`. :param strategy='plain': used to invoke alternate :class:`~sqlalchemy.engine.base.Engine.` implementations. Currently available is the ``threadlocal`` strategy, which is described in :ref:`threadlocal_strategy`. """ strategy = kwargs.pop('strategy', default_strategy) strategy = strategies.strategies[strategy] return strategy.create(*args, **kwargs) |
a = Address(email_address='foobar') | a = Address(id=12, email_address='foobar') | def _test_cascade_to_pending(self, cascade, expire_or_refresh): mapper(User, users, properties={ 'addresses':relationship(Address, cascade=cascade) }) mapper(Address, addresses) s = create_session() |
m = re.compile(r"\[SQLCode\: (\d+)\]").search(str(exception.orig.args)) | m = re.compile(r"\[SQLCode\: (\d+)\]").search(str(exception.args)) | def _extract_error_code(self, exception): # e.g.: DBAPIError: (Error) Table 'test.u2' doesn't exist # [SQLCode: 1146], [SQLState: 42S02] 'DESCRIBE `u2`' () m = re.compile(r"\[SQLCode\: (\d+)\]").search(str(exception.orig.args)) c = m.group(1) if c: return int(c) |
if getattr(self, 'scale', None) is not None and dialect.supports_native_decimal: | if getattr(self, 'scale', None) is None: return processors.to_decimal_processor_factory(decimal.Decimal) elif dialect.supports_native_decimal: | def result_processor(self, dialect, coltype): if self.asdecimal: if getattr(self, 'scale', None) is not None and dialect.supports_native_decimal: return None else: return processors.to_decimal_processor_factory(decimal.Decimal) else: #XXX: if the DBAPI returns a float (this is likely, given the # processor when asdecimal is True), this should be a None # processor instead. return processors.to_float return None |
return processors.to_decimal_processor_factory(decimal.Decimal) | return processors.to_decimal_processor_factory(decimal.Decimal, self.scale) | def result_processor(self, dialect, coltype): if self.asdecimal: if getattr(self, 'scale', None) is not None and dialect.supports_native_decimal: return None else: return processors.to_decimal_processor_factory(decimal.Decimal) else: #XXX: if the DBAPI returns a float (this is likely, given the # processor when asdecimal is True), this should be a None # processor instead. return processors.to_float return None |
return None | def result_processor(self, dialect, coltype): if self.asdecimal: if getattr(self, 'scale', None) is not None and dialect.supports_native_decimal: return None else: return processors.to_decimal_processor_factory(decimal.Decimal) else: #XXX: if the DBAPI returns a float (this is likely, given the # processor when asdecimal is True), this should be a None # processor instead. return processors.to_float return None |
|
settings = {} | settings = { "static_path": os.path.join(os.path.dirname(__file__), "static"), } | def get(self): self.render( "templates/contact.html", sets=emptysquare_collection()['set'], current_slug='contact', current_set_index=-1, next_set_slug=emptysquare_collection()['set'][0]['slug'] ) |
photo_index=int(photo_index) | photo_index=int(photo_index)-1 | def get(self, slug, photo_index): if 'facebookexternalhit' in self.request.headers['User-Agent']: # A visitor to my site has clicked "Like", so FB is scraping the # hashless URL sets = emptysquare_collection()['set'] current_set_index = index_for_set_slug(slug) return self.render( "templates/photo_for_facebook.html", sets=sets, current_slug=slug, current_set_index=current_set_index, photos=emptysquare_set_photos(slug), photo_index=int(photo_index) ) else: # A visitor has clicked someone's "like" activity on Facebook.com, # and is inbound to a hashless URL -- redirect them to the # human-readable page self.redirect( '%s#%s/' % ( self.reverse_url('set', slug), photo_index ) ) |
sqlQuery = "select count(1) from address where time_created::date=now()::date" | sqlQuery = "select count(1) count from address where time_created::date=now()::date" | def countCreatedToday(self,request): |
rows = result.fetchall() return rows[0][0] | for row in result: for column in row: return str(column) | def countCreatedToday(self,request): |
rows = result.fetchall() return rows[0][0] | for row in result: for column in row: return str(column) | def countUpdatedToday(self,request): |
displayText = displayText + column + ' ' | if column is not None: displayText = displayText + column + ' ' | def fullTextSearch(self,request): # addresses/fullTextSearch?fields=street,city,housenumber&query=ch%20du%2028&tolerance=0.005&easting=6.62379551&northing=46.51687241&limit=20&distinct=true # Read request parameters fields = request.params['fields'] |
self.mail("[email protected]","OpenAddresses.org new file uploaded !","The file " + permanent_file.name + " has been uploaded by " + email) | self.mail("[email protected]","OpenAddresses.org new file uploaded !","The file " + permanent_file.name + " has been uploaded by " + email) | def create(self): """POST /uploads: Create a new item""" archive = request.POST['uploaded_file'] email = request.POST['email'] permanent_file = open(os.path.join(self.main_root + '/trunk/openaddresses/uploads',archive.filename.lstrip(os.sep)), 'w') shutil.copyfileobj(archive.file, permanent_file) archive.file.close() permanent_file.close() self.mail(email,"OpenAddresses.org upload confirmation","The file " + permanent_file.name + " has been uploaded. Thanks ! The OpenAddresses.org team.") self.mail("[email protected]","OpenAddresses.org new file uploaded !","The file " + permanent_file.name + " has been uploaded by " + email) return dumps({"success": True, "filename": permanent_file.name}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.