Here are the examples of the python api sqlalchemy.exc.InvalidRequestError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
62 Examples
3
Example 1
Project: CouchPotatoV1 Source File: pg8000.py
def result_processor(self, dialect, coltype):
if self.asdecimal:
if coltype in _FLOAT_TYPES:
return processors.to_decimal_processor_factory(decimal.Decimal)
elif coltype in _DECIMAL_TYPES:
# pg8000 returns Decimal natively for 1700
return None
else:
raise exc.InvalidRequestError("Unknown PG numeric type: %d" % coltype)
else:
if coltype in _FLOAT_TYPES:
# pg8000 returns float natively for 701
return None
elif coltype in _DECIMAL_TYPES:
return processors.to_float
else:
raise exc.InvalidRequestError("Unknown PG numeric type: %d" % coltype)
3
Example 2
def limit_clause(self, select):
# The docs say offsets are supported with LIMIT. But they're not.
# TODO: maybe emulate by adding a ROWNO/ROWNUM predicate?
# TODO: does MaxDB support bind params for LIMIT / TOP ?
if self.is_subquery():
# sub queries need TOP
return ''
elif select._offset:
raise exc.InvalidRequestError(
'MaxDB does not support LIMIT with an offset.')
else:
return ' \n LIMIT %s' % (select._limit,)
3
Example 3
def invalidate(self, e=None):
"""Mark this connection as invalidated.
The connection will be immediately closed. The containing
ConnectionRecord will create a new connection when next used.
"""
if self.connection is None:
raise exc.InvalidRequestError("This connection is closed")
if self._connection_record is not None:
self._connection_record.invalidate(e=e)
self.connection = None
self._close()
3
Example 4
def get_select_precolumns(self, select):
# Convert a subquery's LIMIT to TOP
sql = select._distinct and 'DISTINCT ' or ''
if self.is_subquery() and select._limit:
if select._offset:
raise exc.InvalidRequestError(
'MaxDB does not support LIMIT with an offset.')
sql += 'TOP %s ' % select._limit
return sql
3
Example 5
Project: sqlalchemy Source File: test_events.py
def test_indirect(self):
def listen(x, y):
pass
event.listen("one", "event_one", listen)
eq_(
list(self.Target().dispatch.event_one),
[listen]
)
assert_raises(
exc.InvalidRequestError,
event.listen,
listen, "event_one", self.Target
)
3
Example 6
def limit_clause(self, select):
# The docs say offsets are supported with LIMIT. But they're not.
# TODO: maybe emulate by adding a ROWNO/ROWNUM predicate?
if self.is_subquery():
# sub queries need TOP
return ''
elif select._offset:
raise exc.InvalidRequestError(
'MaxDB does not support LIMIT with an offset.')
else:
return ' \n LIMIT %s' % (select._limit,)
3
Example 7
@property
def info(self):
"""An info collection unique to this DB-API connection."""
try:
return self._connection_record.info
except AttributeError:
if self.connection is None:
raise exc.InvalidRequestError("This connection is closed")
try:
return self._detached_info
except AttributeError:
self._detached_info = value = {}
return value
3
Example 8
Project: sqlalchemy Source File: test_update_delete.py
def test_no_eval_against_multi_table_criteria(self):
User = self.classes.User
Docuement = self.classes.Docuement
s = Session()
q = s.query(User).filter(User.id == Docuement.user_id)
assert_raises_message(
exc.InvalidRequestError,
"Could not evaluate current criteria in Python.",
q.update,
{"name": "ed"}
)
3
Example 9
Project: zaqar Source File: utils.py
def raises_conn_error(func):
"""Handles sqlalchemy DisconnectionError
When sqlalchemy detects a disconnect from the database server, it
retries a number of times. After failing that number of times, it
will convert the internal DisconnectionError into an
InvalidRequestError. This decorator handles that error.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exc.InvalidRequestError as ex:
LOG.exception(ex)
raise errors.ConnectionError()
return wrapper
3
Example 10
Project: OpenClos Source File: test_dao.py
def testDeleteNonExistingPod(self):
dict = {'devicePassword': 'test'}
pod = Pod('unknown', dict)
with self.assertRaises(exc.InvalidRequestError):
with self.__dao.getReadWriteSession() as session:
self.__dao.deleteObject(session, pod)
3
Example 11
Project: sqlalchemy Source File: test_update_delete.py
def test_evaluate_invalid(self):
User = self.classes.User
class Thing(object):
def __clause_element__(self):
return 5
s = Session()
assert_raises_message(
exc.InvalidRequestError,
"Invalid expression type: 5",
s.query(User).update, {Thing(): 'moonbeam'},
synchronize_session='evaluate'
)
3
Example 12
Project: sqlalchemy Source File: test_clsregistry.py
def test_dupe_classes_name_race(self):
"""test the race condition that the class was garbage "
"collected while being resolved from a dupe class."""
base = weakref.WeakValueDictionary()
f1 = MockClass(base, "foo.bar.Foo")
f2 = MockClass(base, "foo.alt.Foo")
clsregistry.add_class("Foo", f1)
clsregistry.add_class("Foo", f2)
dupe_reg = base['Foo']
dupe_reg.contents = [lambda: None]
resolver = clsregistry._resolver(f1, MockProp())
resolver = resolver("Foo")
assert_raises_message(
exc.InvalidRequestError,
"When initializing mapper some_parent, expression "
"'Foo' failed to locate a name \('Foo'\).",
resolver
)
3
Example 13
Project: sqlalchemy Source File: test_insert.py
def test_insert_mix_select_values_exception(self):
table1 = self.tables.mytable
sel = select([table1.c.myid, table1.c.name]).where(
table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
from_select(("otherid", "othername"), sel)
assert_raises_message(
exc.InvalidRequestError,
"This construct already inserts from a SELECT",
ins.values, othername="5"
)
3
Example 14
Project: sqlalchemy Source File: test_dialect.py
@testing.fails_on('+zxjdbc', 'psycopg2/pg8000 specific assertion')
@testing.requires.psycopg2_or_pg8000_compatibility
def test_numeric_raise(self):
stmt = text(
"select cast('hi' as char) as hi", typemap={'hi': Numeric})
assert_raises(exc.InvalidRequestError, testing.db.execute, stmt)
3
Example 15
def bind_processor(self, dialect):
def process(value):
if value is None:
return None
elif isinstance(value, basestring):
return value
elif dialect.datetimeformat == 'internal':
return value.strftime("%H%M%S")
elif dialect.datetimeformat == 'iso':
return value.strftime("%H-%M-%S")
else:
raise exc.InvalidRequestError(
"datetimeformat '%s' is not supported." % (
dialect.datetimeformat,))
return process
3
Example 16
Project: sqlalchemy Source File: test_update_delete.py
def test_illegal_metadata(self):
person = self.classes.Person.__table__
engineer = self.classes.Engineer.__table__
sess = Session()
assert_raises_message(
exc.InvalidRequestError,
"This operation requires only one Table or entity be "
"specified as the target.",
sess.query(person.join(engineer)).update, {}
)
3
Example 17
Project: sqlalchemy Source File: test_ddlevents.py
def test_append_listener(self):
metadata, table, bind = self.metadata, self.table, self.bind
fn = lambda *a: None
table.append_ddl_listener('before-create', fn)
assert_raises(exc.InvalidRequestError, table.append_ddl_listener,
'blah', fn)
metadata.append_ddl_listener('before-create', fn)
assert_raises(exc.InvalidRequestError, metadata.append_ddl_listener,
'blah', fn)
3
Example 18
Project: sqlalchemy Source File: test_clsregistry.py
def test_fragment_ambiguous(self):
base = weakref.WeakValueDictionary()
f1 = MockClass(base, "foo.bar.Foo")
f2 = MockClass(base, "foo.alt.Foo")
f3 = MockClass(base, "bat.alt.Foo")
clsregistry.add_class("Foo", f1)
clsregistry.add_class("Foo", f2)
clsregistry.add_class("Foo", f3)
resolver = clsregistry._resolver(f1, MockProp())
gc_collect()
assert_raises_message(
exc.InvalidRequestError,
'Multiple classes found for path "alt.Foo" in the registry '
'of this declarative base. Please use a fully '
'module-qualified path.',
resolver("alt.Foo")
)
3
Example 19
Project: maraschino Source File: pg8000.py
def result_processor(self, dialect, coltype):
if self.asdecimal:
if coltype in _FLOAT_TYPES:
return processors.to_decimal_processor_factory(decimal.Decimal)
elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
# pg8000 returns Decimal natively for 1700
return None
else:
raise exc.InvalidRequestError(
"Unknown PG numeric type: %d" % coltype)
else:
if coltype in _FLOAT_TYPES:
# pg8000 returns float natively for 701
return None
elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
return processors.to_float
else:
raise exc.InvalidRequestError(
"Unknown PG numeric type: %d" % coltype)
3
Example 20
Project: distil Source File: api.py
def resource_add(project_id, resource_id, resource_type, raw, metadata):
session = get_session()
metadata = _merge_resource_metadata({'type': resource_type}, raw, metadata)
resource_ref = Resource(id=resource_id, project_id=project_id,
resource_type=resource_type, meta_data=metadata)
try:
resource_ref.save(session=session)
except sa.exc.InvalidRequestError as e:
# FIXME(flwang): I assume there should be a DBDuplicateEntry error
if str(e).rfind("Duplicate entry '\s' for key 'PRIMARY'"):
LOG.warning(e)
return
raise e
except Exception as e:
raise e
3
Example 21
Project: sqlalchemy Source File: test_insert.py
def test_insert_mix_values_select_exception(self):
table1 = self.tables.mytable
sel = select([table1.c.myid, table1.c.name]).where(
table1.c.name == 'foo')
ins = self.tables.myothertable.insert().values(othername="5")
assert_raises_message(
exc.InvalidRequestError,
"This construct already inserts value expressions",
ins.from_select, ("otherid", "othername"), sel
)
3
Example 22
def bind_processor(self, dialect):
def process(value):
if value is None:
return None
elif isinstance(value, basestring):
return value
elif dialect.datetimeformat == 'internal':
ms = getattr(value, 'microsecond', 0)
return value.strftime("%Y%m%d%H%M%S" + ("%06u" % ms))
elif dialect.datetimeformat == 'iso':
ms = getattr(value, 'microsecond', 0)
return value.strftime("%Y-%m-%d %H:%M:%S." + ("%06u" % ms))
else:
raise exc.InvalidRequestError(
"datetimeformat '%s' is not supported." % (
dialect.datetimeformat,))
return process
3
Example 23
Project: sqlalchemy Source File: test_clsregistry.py
def test_resolve_dupe_by_name(self):
base = weakref.WeakValueDictionary()
f1 = MockClass(base, "foo.bar.Foo")
f2 = MockClass(base, "foo.alt.Foo")
clsregistry.add_class("Foo", f1)
clsregistry.add_class("Foo", f2)
gc_collect()
resolver = clsregistry._resolver(f1, MockProp())
resolver = resolver("Foo")
assert_raises_message(
exc.InvalidRequestError,
'Multiple classes found for path "Foo" in the '
'registry of this declarative base. Please use a '
'fully module-qualified path.',
resolver
)
3
Example 24
def bind_processor(self, dialect):
def process(value):
if value is None:
return None
elif isinstance(value, basestring):
return value
elif dialect.datetimeformat == 'internal':
return value.strftime("%Y%m%d")
elif dialect.datetimeformat == 'iso':
return value.strftime("%Y-%m-%d")
else:
raise exc.InvalidRequestError(
"datetimeformat '%s' is not supported." % (
dialect.datetimeformat,))
return process
3
Example 25
Project: sqlalchemy Source File: test_insert_exec.py
@testing.requires.empty_inserts
@testing.requires.returning
def test_no_inserted_pk_on_returning(self):
users = self.tables.users
result = testing.db.execute(users.insert().returning(
users.c.user_id, users.c.user_name))
assert_raises_message(
exc.InvalidRequestError,
r"Can't call inserted_primary_key when returning\(\) is used.",
getattr, result, 'inserted_primary_key'
)
3
Example 26
Project: CouchPotatoV1 Source File: base.py
def visit_select_precolumns(self, select):
"""Access puts TOP, it's version of LIMIT here """
s = select.distinct and "DISTINCT " or ""
if select.limit:
s += "TOP %s " % (select.limit)
if select.offset:
raise exc.InvalidRequestError(
'Access does not support LIMIT with an offset')
return s
3
Example 27
Project: sqlalchemy Source File: test_events.py
def test_remove_not_listened(self):
Target = self._fixture()
m1 = Mock()
t1 = Target()
event.listen(t1, "event_one", m1, propagate=True)
event.listen(t1, "event_three", m1)
event.remove(t1, "event_one", m1)
assert_raises_message(
exc.InvalidRequestError,
r"No listeners found for event <.*Target.*> / "
r"'event_two' / <Mock.*> ",
event.remove, t1, "event_two", m1
)
event.remove(t1, "event_three", m1)
0
Example 28
Project: CouchPotatoV1 Source File: base.py
def order_by_clause(self, select, **kw):
order_by = self.process(select._order_by_clause, **kw)
# ORDER BY clauses in DISTINCT queries must reference aliased
# inner columns by alias name, not true column name.
if order_by and getattr(select, '_distinct', False):
labels = self._find_labeled_columns(select.inner_columns,
select.use_labels)
if labels:
for needs_alias in labels.keys():
r = re.compile(r'(^| )(%s)(,| |$)' %
re.escape(needs_alias))
order_by = r.sub((r'\1%s\3' % labels[needs_alias]),
order_by)
# No ORDER BY in subqueries.
if order_by:
if self.is_subquery():
# It's safe to simply drop the ORDER BY if there is no
# LIMIT. Right? Other dialects seem to get away with
# dropping order.
if select._limit:
raise exc.InvalidRequestError(
"MaxDB does not support ORDER BY in subqueries")
else:
return ""
return " ORDER BY " + order_by
else:
return ""
0
Example 29
Project: sqlalchemy Source File: test_update_delete.py
@testing.fails_on('mysql', 'FIXME: unknown')
def test_delete_invalid_evaluation(self):
User = self.classes.User
sess = Session()
john, jack, jill, jane = sess.query(User).order_by(User.id).all()
assert_raises(exc.InvalidRequestError,
sess.query(User).
filter(
User.name == select([func.max(User.name)])).delete,
synchronize_session='evaluate'
)
sess.query(User).filter(User.name == select([func.max(User.name)])).\
delete(synchronize_session='fetch')
assert john not in sess
eq_(sess.query(User).order_by(User.id).all(), [jack, jill, jane])
0
Example 30
def pre_exec(self):
quoted_bind_names = \
getattr(self.compiled, '_quoted_bind_names', None)
if quoted_bind_names:
if not self.dialect.supports_unicode_binds:
quoted_bind_names = \
dict(
(fromname, toname.encode(self.dialect.encoding))
for fromname, toname in
quoted_bind_names.items()
)
for param in self.parameters:
for fromname, toname in quoted_bind_names.items():
param[toname] = param[fromname]
del param[fromname]
if self.dialect.auto_setinputsizes:
# cx_oracle really has issues when you setinputsizes
# on String, including that outparams/RETURNING
# breaks for varchars
self.set_input_sizes(quoted_bind_names,
exclude_types=self.dialect._cx_oracle_string_types
)
# if a single execute, check for outparams
if len(self.compiled_parameters) == 1:
for bindparam in self.compiled.binds.values():
if bindparam.isoutparam:
dbtype = bindparam.type.dialect_impl(self.dialect).\
get_dbapi_type(self.dialect.dbapi)
if not hasattr(self, 'out_parameters'):
self.out_parameters = {}
if dbtype is None:
raise exc.InvalidRequestError("Cannot create out parameter for parameter "
"%r - it's type %r is not supported by"
" cx_oracle" %
(name, bindparam.type)
)
name = self.compiled.bind_names[bindparam]
self.out_parameters[name] = self.cursor.var(dbtype)
self.parameters[0][quoted_bind_names.get(name, name)] = \
self.out_parameters[name]
0
Example 31
def on_connect(self):
if self.isolation_level is not None:
extensions = __import__('psycopg2.extensions').extensions
isol = {
'READ_COMMITTED':extensions.ISOLATION_LEVEL_READ_COMMITTED,
'READ_UNCOMMITTED':extensions.ISOLATION_LEVEL_READ_UNCOMMITTED,
'REPEATABLE_READ':extensions.ISOLATION_LEVEL_REPEATABLE_READ,
'SERIALIZABLE':extensions.ISOLATION_LEVEL_SERIALIZABLE
}
def base_on_connect(conn):
try:
conn.set_isolation_level(isol[self.isolation_level])
except:
raise exc.InvalidRequestError(
"Invalid isolation level: '%s'" %
self.isolation_level)
else:
base_on_connect = None
if self.dbapi and self.use_native_unicode:
extensions = __import__('psycopg2.extensions').extensions
def connect(conn):
extensions.register_type(extensions.UNICODE, conn)
if base_on_connect:
base_on_connect(conn)
return connect
else:
return base_on_connect
0
Example 32
def create_connect_args(self, url):
dialect_opts = dict(url.query)
for opt in ('use_ansi', 'auto_setinputsizes', 'auto_convert_lobs',
'threaded', 'allow_twophase'):
if opt in dialect_opts:
util.coerce_kw_type(dialect_opts, opt, bool)
setattr(self, opt, dialect_opts[opt])
database = url.database
service_name = dialect_opts.get('service_name', None)
if database or service_name:
# if we have a database, then we have a remote host
port = url.port
if port:
port = int(port)
else:
port = 1521
if database and service_name:
raise exc.InvalidRequestError(
'"service_name" option shouldn\'t '
'be used with a "database" part of the url')
if database:
makedsn_kwargs = {'sid': database}
if service_name:
makedsn_kwargs = {'service_name': service_name}
dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs)
else:
# we have a local tnsname
dsn = url.host
opts = dict(
threaded=self.threaded,
twophase=self.allow_twophase,
)
if dsn is not None:
opts['dsn'] = dsn
if url.password is not None:
opts['password'] = url.password
if url.username is not None:
opts['user'] = url.username
if util.py2k:
if self._cx_oracle_with_unicode:
for k, v in opts.items():
if isinstance(v, str):
opts[k] = unicode(v)
else:
for k, v in opts.items():
if isinstance(v, unicode):
opts[k] = str(v)
if 'mode' in url.query:
opts['mode'] = url.query['mode']
if isinstance(opts['mode'], util.string_types):
mode = opts['mode'].upper()
if mode == 'SYSDBA':
opts['mode'] = self.dbapi.SYSDBA
elif mode == 'SYSOPER':
opts['mode'] = self.dbapi.SYSOPER
else:
util.coerce_kw_type(opts, 'mode', int)
return ([], opts)
0
Example 33
def pre_exec(self):
if self.isinsert:
tbl = self.compiled.statement.table
seq_column = tbl._autoincrement_column
insert_has_sequence = seq_column is not None
if insert_has_sequence:
self._enable_identity_insert = \
seq_column.key in self.compiled_parameters[0]
else:
self._enable_identity_insert = False
if self._enable_identity_insert:
self.cursor.execute("SET IDENTITY_INSERT %s ON" %
self.dialect.identifier_preparer.format_table(tbl))
if self.isddl:
# TODO: to enhance this, we can detect "ddl in tran" on the
# database settings. this error message should be improved to
# include a note about that.
if not self.should_autocommit:
raise exc.InvalidRequestError(
"The Sybase dialect only supports "
"DDL in 'autocommit' mode at this time.")
self.root_connection.engine.logger.info(
"AUTOCOMMIT (Assuming no Sybase 'ddl in tran')")
self.set_ddl_autocommit(
self.root_connection.connection.connection,
True)
0
Example 34
def get_column_specification(self, column, **kwargs):
colspec = self.preparer.format_column(column) + " " + \
self.dialect.type_compiler.process(column.type)
if column.table is None:
raise exc.InvalidRequestError(
"The Sybase dialect requires Table-bound "
"columns in order to generate DDL")
seq_col = column.table._autoincrement_column
# install a IDENTITY Sequence if we have an implicit IDENTITY column
if seq_col is column:
sequence = isinstance(column.default, sa_schema.Sequence) \
and column.default
if sequence:
start, increment = sequence.start or 1, \
sequence.increment or 1
else:
start, increment = 1, 1
if (start, increment) == (1, 1):
colspec += " IDENTITY"
else:
# TODO: need correct syntax for this
colspec += " IDENTITY(%s,%s)" % (start, increment)
else:
if column.nullable is not None:
if not column.nullable or column.primary_key:
colspec += " NOT NULL"
else:
colspec += " NULL"
default = self.get_column_default_string(column)
if default is not None:
colspec += " DEFAULT " + default
return colspec
0
Example 35
Project: sqlalchemy Source File: test_validators.py
def test_validator_multi_warning(self):
users = self.tables.users
class Foo(object):
@validates("name")
def validate_one(self, key, value):
pass
@validates("name")
def validate_two(self, key, value):
pass
assert_raises_message(
exc.InvalidRequestError,
"A validation function for mapped attribute "
"'name' on mapper Mapper|Foo|users already exists",
mapper, Foo, users
)
class Bar(object):
@validates("id")
def validate_three(self, key, value):
return value + 10
@validates("id", "name")
def validate_four(self, key, value):
return value + "foo"
assert_raises_message(
exc.InvalidRequestError,
"A validation function for mapped attribute "
"'name' on mapper Mapper|Bar|users already exists",
mapper, Bar, users
)
0
Example 36
def checkout(self):
if self.connection is None:
raise exc.InvalidRequestError("This connection is closed")
self.__counter += 1
if not self._pool._on_checkout or self.__counter != 1:
return self
# Pool listeners can trigger a reconnection on checkout
attempts = 2
while attempts > 0:
try:
for l in self._pool._on_checkout:
l.checkout(self.connection, self._connection_record, self)
return self
except exc.DisconnectionError, e:
self._pool.logger.info(
"Disconnection detected on checkout: %s", e)
self._connection_record.invalidate(e)
self.connection = self._connection_record.get_connection()
attempts -= 1
self._pool.logger.info("Reconnection attempts exhausted on checkout")
self.invalidate()
raise exc.InvalidRequestError("This connection is closed")
0
Example 37
Project: ReadableWebProxy Source File: NuForwarder.py
def insert_new_release(self, input_data):
new = db.NuOutboundWrapperMap(
client_id = input_data['nu_release']['client_id'],
client_key = input_data['nu_release']['client_key'],
seriesname = input_data['nu_release']['seriesname'],
releaseinfo = input_data['nu_release']['releaseinfo'],
groupinfo = input_data['nu_release']['groupinfo'],
referrer = input_data['nu_release']['referrer'],
outbound_wrapper = input_data['nu_release']['outbound_wrapper'],
actual_target = input_data['nu_release']['actual_target'],
)
while 1:
try:
self.db_sess.add(new)
self.db_sess.commit()
return
except sqlalchemy.exc.InvalidRequestError:
print("InvalidRequest error!")
self.db_sess.rollback()
traceback.print_exc()
except sqlalchemy.exc.OperationalError:
print("InvalidRequest error!")
self.db_sess.rollback()
except sqlalchemy.exc.IntegrityError:
with open("nu_db_collisions.txt", "wa") as fp:
fp.write(str(input_data))
fp.write("\n")
print("[upsertRssItems] -> Integrity error!")
traceback.print_exc()
self.db_sess.rollback()
break
0
Example 38
def pre_exec(self):
if self.isinsert:
tbl = self.compiled.statement.table
seq_column = tbl._autoincrement_column
insert_has_sequence = seq_column is not None
if insert_has_sequence:
self._enable_identity_insert = \
seq_column.key in self.compiled_parameters[0]
else:
self._enable_identity_insert = False
if self._enable_identity_insert:
self.cursor.execute("SET IDENTITY_INSERT %s ON" %
self.dialect.identifier_preparer.format_table(tbl))
if self.isddl:
# TODO: to enhance this, we can detect "ddl in tran" on the
# database settings. this error message should be improved to
# include a note about that.
if not self.should_autocommit:
raise exc.InvalidRequestError(
"The Sybase dialect only supports "
"DDL in 'autocommit' mode at this time.")
self.root_connection.engine.logger.info(
"AUTOCOMMIT (Assuming no Sybase 'ddl in tran')")
self.set_ddl_autocommit(
self.root_connection.connection.connection,
True)
0
Example 39
def pre_exec(self):
if self.isinsert:
tbl = self.compiled.statement.table
seq_column = tbl._autoincrement_column
insert_has_sequence = seq_column is not None
if insert_has_sequence:
self._enable_identity_insert = \
seq_column.key in self.compiled_parameters[0]
else:
self._enable_identity_insert = False
if self._enable_identity_insert:
self.cursor.execute(
"SET IDENTITY_INSERT %s ON" %
self.dialect.identifier_preparer.format_table(tbl))
if self.isddl:
# TODO: to enhance this, we can detect "ddl in tran" on the
# database settings. this error message should be improved to
# include a note about that.
if not self.should_autocommit:
raise exc.InvalidRequestError(
"The Sybase dialect only supports "
"DDL in 'autocommit' mode at this time.")
self.root_connection.engine.logger.info(
"AUTOCOMMIT (Assuming no Sybase 'ddl in tran')")
self.set_ddl_autocommit(
self.root_connection.connection.connection,
True)
0
Example 40
Project: ReadableWebProxy Source File: Engine.py
def upsertRssItems(self, job, entrylist, feedurl):
start = urllib.parse.urlsplit(job.starturl).netloc
interval = settings.REWALK_INTERVAL_DAYS
if start in self.netloc_rewalk_times:
interval = self.netloc_rewalk_times[start]
ignoreuntiltime = (datetime.datetime.now() + datetime.timedelta(days=interval))
print("[upsertFileResponse] Ignore until: ", ignoreuntiltime)
while 1:
try:
self.db_sess.flush()
if not (job.state == "fetching" or job.state == 'processing'):
self.log.critical("Someone else modified row first? State: %s, url: %s", job.state, job.url)
job.state = 'complete'
job.fetchtime = datetime.datetime.now()
job.ignoreuntiltime = ignoreuntiltime
self.db_sess.commit()
self.log.info("Marked RSS job with id %s, url %s as complete (%s)!", job.id, job.url, job.state)
break
except sqlalchemy.exc.InvalidRequestError:
print("InvalidRequest error!")
self.db_sess.rollback()
traceback.print_exc()
except sqlalchemy.exc.OperationalError:
print("InvalidRequest error!")
self.db_sess.rollback()
except sqlalchemy.exc.IntegrityError:
print("[upsertRssItems] -> Integrity error!")
traceback.print_exc()
self.db_sess.rollback()
# print("InsertFeed!")
for feedentry in entrylist:
# print(feedentry)
# print(feedentry.keys())
# print(feedentry['contents'])
# print(feedentry['published'])
while 1:
try:
self.insertRssItem(feedentry, feedurl)
break
except sqlalchemy.exc.InvalidRequestError:
print("InvalidRequest error!")
self.db_sess.rollback()
traceback.print_exc()
except sqlalchemy.exc.OperationalError:
print("OperationalError error!")
self.db_sess.rollback()
except sqlalchemy.exc.IntegrityError:
print("[upsertRssItems] -> Integrity error!")
traceback.print_exc()
self.db_sess.rollback()
0
Example 41
def get_row(self, url, distance=None, priority=None):
if distance == None:
distance = self.db.MAX_DISTANCE-2
if priority == None:
priority = self.db.DB_REALTIME_PRIORITY
# Rather then trying to add, and rolling back if it exists,
# just do a simple check for the row first. That'll
# probably be faster in the /great/ majority of cases.
while 1:
# self.db_sess.begin()
try:
row = self.db_sess.query(self.db.WebPages) \
.filter(self.db.WebPages.url == url) \
.scalar()
self.db_sess.commit()
break
except sqlalchemy.exc.InvalidRequestError:
self.db_sess.rollback()
except sqlalchemy.exc.OperationalError:
self.db_sess.rollback()
except sqlalchemy.exc.IntegrityError:
self.db_sess.rollback()
if row:
self.log.info("Item already exists in database.")
else:
self.log.info("Row does not exist in DB")
url_netloc = urllib.parse.urlsplit(url).netloc
# New jobs are inserted in the "fetching" state since we
# don't want them to be picked up by the fetch engine
# while they're still in-progress
row = self.db.WebPages(
state = 'fetching',
url = url,
starturl = url,
netloc = url_netloc,
distance = distance,
is_text = True,
priority = priority,
type = "unknown",
fetchtime = datetime.datetime.now(),
)
# Because we can have parallel operations happening here, we spin on adding&committing the new
# row untill the commit either succeeds, or we get an integrity error, and then successfully
# fetch the row inserted by another thread at the same time.
while 1:
try:
# self.db_sess.begin()
self.db_sess.add(row)
self.db_sess.commit()
print("Row added?")
break
except sqlalchemy.exc.InvalidRequestError:
print("InvalidRequest error!")
self.db_sess.rollback()
traceback.print_exc()
except sqlalchemy.exc.OperationalError:
print("InvalidRequest error!")
self.db_sess.rollback()
except sqlalchemy.exc.IntegrityError:
print("[synchronousJobRequest] -> Integrity error!")
self.db_sess.rollback()
row = self.db_sess.query(self.db.WebPages) \
.filter(self.db.WebPages.url == url) \
.one()
self.db_sess.commit()
break
return row
0
Example 42
@classmethod
def dbapi(cls):
import win32com.client, pythoncom
global const, daoEngine
if const is None:
const = win32com.client.constants
for suffix in (".36", ".35", ".30"):
try:
daoEngine = win32com.client.\
gencache.\
EnsureDispatch("DAO.DBEngine" + suffix)
break
except pythoncom.com_error:
pass
else:
raise exc.InvalidRequestError(
"Can't find a DB engine. Check "
"http://support.microsoft.com/kb/239114 for details.")
import pyodbc as module
return module
0
Example 43
Project: sqlalchemy Source File: test_bind.py
@engines.close_open_connections
def test_bound_connection(self):
users, User = self.tables.users, self.classes.User
mapper(User, users)
c = testing.db.connect()
sess = create_session(bind=c)
sess.begin()
transaction = sess.transaction
u = User(name='u1')
sess.add(u)
sess.flush()
assert transaction._connection_for_bind(testing.db, None) \
is transaction._connection_for_bind(c, None) is c
assert_raises_message(sa.exc.InvalidRequestError,
'Session already has a Connection '
'associated',
transaction._connection_for_bind,
testing.db.connect(), None)
transaction.rollback()
assert len(sess.query(User).all()) == 0
sess.close()
0
Example 44
def result_processor(self, dialect, coltype):
if dialect.datetimeformat == 'internal':
def process(value):
if value is None:
return None
else:
return datetime.datetime(
*[int(v)
for v in (value[0:4], value[4:6], value[6:8],
value[8:10], value[10:12], value[12:14],
value[14:])])
elif dialect.datetimeformat == 'iso':
def process(value):
if value is None:
return None
else:
return datetime.datetime(
*[int(v)
for v in (value[0:4], value[5:7], value[8:10],
value[11:13], value[14:16], value[17:19],
value[20:])])
else:
raise exc.InvalidRequestError(
"datetimeformat '%s' is not supported." %
dialect.datetimeformat)
return process
0
Example 45
Project: sqlalchemy Source File: test_selectable.py
def test_no_selects(self):
Subset, common = self.classes.Subset, self.tables.common
subset_select = select([common.c.id, common.c.data])
assert_raises(sa.exc.InvalidRequestError, mapper, Subset, subset_select)
0
Example 46
def result_processor(self, dialect, coltype):
if dialect.datetimeformat == 'internal':
def process(value):
if value is None:
return None
else:
return datetime.date(int(value[0:4]), int(value[4:6]),
int(value[6:8]))
elif dialect.datetimeformat == 'iso':
def process(value):
if value is None:
return None
else:
return datetime.date(int(value[0:4]), int(value[5:7]),
int(value[8:10]))
else:
raise exc.InvalidRequestError(
"datetimeformat '%s' is not supported." %
dialect.datetimeformat)
return process
0
Example 47
def pre_exec(self):
quoted_bind_names = \
getattr(self.compiled, '_quoted_bind_names', None)
if quoted_bind_names:
if not self.dialect.supports_unicode_statements:
# if DBAPI doesn't accept unicode statements,
# keys in self.parameters would have been encoded
# here. so convert names in quoted_bind_names
# to encoded as well.
quoted_bind_names = \
dict(
(fromname.encode(self.dialect.encoding),
toname.encode(self.dialect.encoding))
for fromname, toname in
quoted_bind_names.items()
)
for param in self.parameters:
for fromname, toname in quoted_bind_names.items():
param[toname] = param[fromname]
del param[fromname]
if self.dialect.auto_setinputsizes:
# cx_oracle really has issues when you setinputsizes
# on String, including that outparams/RETURNING
# breaks for varchars
self.set_input_sizes(quoted_bind_names,
exclude_types=self.dialect.exclude_setinputsizes
)
# if a single execute, check for outparams
if len(self.compiled_parameters) == 1:
for bindparam in self.compiled.binds.values():
if bindparam.isoutparam:
dbtype = bindparam.type.dialect_impl(self.dialect).\
get_dbapi_type(self.dialect.dbapi)
if not hasattr(self, 'out_parameters'):
self.out_parameters = {}
if dbtype is None:
raise exc.InvalidRequestError(
"Cannot create out parameter for parameter "
"%r - it's type %r is not supported by"
" cx_oracle" %
(bindparam.key, bindparam.type)
)
name = self.compiled.bind_names[bindparam]
self.out_parameters[name] = self.cursor.var(dbtype)
self.parameters[0][quoted_bind_names.get(name, name)] = \
self.out_parameters[name]
0
Example 48
def pre_exec(self):
quoted_bind_names = \
getattr(self.compiled, '_quoted_bind_names', None)
if quoted_bind_names:
if not self.dialect.supports_unicode_statements:
# if DBAPI doesn't accept unicode statements,
# keys in self.parameters would have been encoded
# here. so convert names in quoted_bind_names
# to encoded as well.
quoted_bind_names = \
dict(
(fromname.encode(self.dialect.encoding),
toname.encode(self.dialect.encoding))
for fromname, toname in
quoted_bind_names.items()
)
for param in self.parameters:
for fromname, toname in quoted_bind_names.items():
param[toname] = param[fromname]
del param[fromname]
if self.dialect.auto_setinputsizes:
# cx_oracle really has issues when you setinputsizes
# on String, including that outparams/RETURNING
# breaks for varchars
self.set_input_sizes(
quoted_bind_names,
exclude_types=self.dialect.exclude_setinputsizes
)
# if a single execute, check for outparams
if len(self.compiled_parameters) == 1:
for bindparam in self.compiled.binds.values():
if bindparam.isoutparam:
dbtype = bindparam.type.dialect_impl(self.dialect).\
get_dbapi_type(self.dialect.dbapi)
if not hasattr(self, 'out_parameters'):
self.out_parameters = {}
if dbtype is None:
raise exc.InvalidRequestError(
"Cannot create out parameter for parameter "
"%r - its type %r is not supported by"
" cx_oracle" %
(bindparam.key, bindparam.type)
)
name = self.compiled.bind_names[bindparam]
self.out_parameters[name] = self.cursor.var(dbtype)
self.parameters[0][quoted_bind_names.get(name, name)] = \
self.out_parameters[name]
0
Example 49
Project: sqlalchemy Source File: test_update_delete.py
def test_illegal_operations(self):
User = self.classes.User
Address = self.classes.Address
s = Session()
for q, mname in (
(s.query(User).limit(2), r"limit\(\)"),
(s.query(User).offset(2), r"offset\(\)"),
(s.query(User).limit(2).offset(2), r"limit\(\)"),
(s.query(User).order_by(User.id), r"order_by\(\)"),
(s.query(User).group_by(User.id), r"group_by\(\)"),
(s.query(User).distinct(), r"distinct\(\)"),
(s.query(User).join(User.addresses),
r"join\(\), outerjoin\(\), select_from\(\), or from_self\(\)"),
(s.query(User).outerjoin(User.addresses),
r"join\(\), outerjoin\(\), select_from\(\), or from_self\(\)"),
(s.query(User).select_from(Address),
r"join\(\), outerjoin\(\), select_from\(\), or from_self\(\)"),
(s.query(User).from_self(),
r"join\(\), outerjoin\(\), select_from\(\), or from_self\(\)"),
):
assert_raises_message(
exc.InvalidRequestError,
r"Can't call Query.update\(\) or Query.delete\(\) when "
"%s has been called" % mname,
q.update,
{'name': 'ed'})
assert_raises_message(
exc.InvalidRequestError,
r"Can't call Query.update\(\) or Query.delete\(\) when "
"%s has been called" % mname,
q.delete)
0
Example 50
def result_processor(self, dialect, coltype):
if dialect.datetimeformat == 'internal':
def process(value):
if value is None:
return None
else:
return datetime.time(int(value[0:4]), int(value[4:6]),
int(value[6:8]))
elif dialect.datetimeformat == 'iso':
def process(value):
if value is None:
return None
else:
return datetime.time(int(value[0:4]), int(value[5:7]),
int(value[8:10]))
else:
raise exc.InvalidRequestError(
"datetimeformat '%s' is not supported." %
dialect.datetimeformat)
return process