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.default...
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 ...
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 = inlin...
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_...
[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 '\\'",...
( 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 '\...
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=...
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 lowerca...
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...
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.db...
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 dat...
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,...
% (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(...
"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(...
"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(...
"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(...
"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(...
"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(...
"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 " "cl...
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(que...
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(que...
"""
""")
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(que...
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(que...
@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 par...
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. T...
`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. T...
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 asdecim...
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 asdecim...
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 asdecim...
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", s...
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("info@openaddresses.org","OpenAddresses.org new file uploaded !","The file " + permanent_file.name + " has been uploaded by " + email)
self.mail("cedric.moullet@openaddresses.org","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() p...