本文整理汇总了Python中sqlalchemy.util.warn函数的典型用法代码示例。如果您正苦于以下问题:Python warn函数的具体用法?Python warn怎么用?Python warn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __new__
def __new__(cls, arg):
values = set([
c for c
in re.split('\s*,\s*', arg or "")
if c
])
if values.difference(cls._allowed_cascades):
raise sa_exc.ArgumentError(
"Invalid cascade option(s): %s" %
", ".join([repr(x) for x in
sorted(
values.difference(cls._allowed_cascades)
)])
)
if "all" in values:
values.update(cls._add_w_all_cascades)
if "none" in values:
values.clear()
values.discard('all')
self = frozenset.__new__(CascadeOptions, values)
self.save_update = 'save-update' in values
self.delete = 'delete' in values
self.refresh_expire = 'refresh-expire' in values
self.merge = 'merge' in values
self.expunge = 'expunge' in values
self.delete_orphan = "delete-orphan" in values
if self.delete_orphan and not self.delete:
util.warn("The 'delete-orphan' cascade "
"option requires 'delete'.")
return self
示例2: _emit_update_statements
def _emit_update_statements(base_mapper, uowtransaction,
cached_connections, mapper, table, update):
"""Emit UPDATE statements corresponding to value lists collected
by _collect_update_commands()."""
needs_version_id = mapper.version_id_col is not None and \
table.c.contains_column(mapper.version_id_col)
def update_stmt():
clause = sql.and_()
for col in mapper._pks_by_table[table]:
clause.clauses.append(col == sql.bindparam(col._label,
type_=col.type))
if needs_version_id:
clause.clauses.append(mapper.version_id_col ==\
sql.bindparam(mapper.version_id_col._label,
type_=col.type))
return table.update(clause)
statement = base_mapper._memo(('update', table), update_stmt)
rows = 0
for state, state_dict, params, mapper, \
connection, value_params in update:
if value_params:
c = connection.execute(
statement.values(value_params),
params)
else:
c = cached_connections[connection].\
execute(statement, params)
_postfetch(
mapper,
uowtransaction,
table,
state,
state_dict,
c.context.prefetch_cols,
c.context.postfetch_cols,
c.context.compiled_parameters[0],
value_params)
rows += c.rowcount
if connection.dialect.supports_sane_rowcount:
if rows != len(update):
raise orm_exc.StaleDataError(
"UPDATE statement on table '%s' expected to "
"update %d row(s); %d were matched." %
(table.description, len(update), rows))
elif needs_version_id:
util.warn("Dialect %s does not support updated rowcount "
"- versioning cannot be verified." %
c.dialect.dialect_description,
stacklevel=12)
示例3: __determine_targets
def __determine_targets(self):
if isinstance(self.argument, type):
self.mapper = mapper.class_mapper(self.argument, entity_name=self.entity_name, compile=False)
elif isinstance(self.argument, mapper.Mapper):
self.mapper = self.argument
elif callable(self.argument):
# accept a callable to suit various deferred-configurational schemes
self.mapper = mapper.class_mapper(self.argument(), entity_name=self.entity_name, compile=False)
else:
raise exceptions.ArgumentError("relation '%s' expects a class or a mapper argument (received: %s)" % (self.key, type(self.argument)))
if not self.parent.concrete:
for inheriting in self.parent.iterate_to_root():
if inheriting is not self.parent and inheriting._get_property(self.key, raiseerr=False):
util.warn(
("Warning: relation '%s' on mapper '%s' supercedes "
"the same relation on inherited mapper '%s'; this "
"can cause dependency issues during flush") %
(self.key, self.parent, inheriting))
self.target = self.mapper.mapped_table
self.table = self.mapper.mapped_table
if self.cascade.delete_orphan:
if self.parent.class_ is self.mapper.class_:
raise exceptions.ArgumentError("In relationship '%s', can't establish 'delete-orphan' cascade "
"rule on a self-referential relationship. "
"You probably want cascade='all', which includes delete cascading but not orphan detection." %(str(self)))
self.mapper.primary_mapper().delete_orphans.append((self.key, self.parent.class_))
示例4: limit_clause
def limit_clause(self, select):
text = ""
if select._limit is not None:
text += "\n LIMIT %d" % int(select._limit)
if select._offset is not None:
util.warn("EXASolution does not support OFFSET")
return text
示例5: get_lastrowid
def get_lastrowid(self):
columns = self.compiled.sql_compiler.statement.table.columns
autoinc_pk_columns = \
[c.name for c in columns if c.autoincrement and c.primary_key]
if len(autoinc_pk_columns) == 0:
return None
elif len(autoinc_pk_columns) > 1:
util.warn("Table with more than one autoincrement, primary key"\
" Column!")
raise Exception
else:
id_col = self.dialect.denormalize_name(autoinc_pk_columns[0])
table = self.compiled.sql_compiler.statement.table.name
table = self.dialect.denormalize_name(table)
sql_stmnt = "SELECT column_identity from SYS.EXA_ALL_COLUMNS "\
"WHERE column_object_type = 'TABLE' and column_table "\
"= ? AND column_name = ?"
schema = self.compiled.sql_compiler.statement.table.schema
if schema is not None:
schema = self.dialect.denormalize_name(schema)
sql_stmnt += " AND column_schema = ?"
cursor = self.create_cursor()
if schema:
cursor.execute(sql_stmnt, table, id_col, schema)
else:
cursor.execute(sql_stmnt, table, id_col)
lastrowid = cursor.fetchone()[0] - 1
cursor.close()
return lastrowid
示例6: _get_column_info
def _get_column_info(self, name, type_, nullable, default, primary_key):
match = re.match(r"(\w+)(\(.*?\))?", type_)
if match:
coltype = match.group(1)
args = match.group(2)
else:
coltype = "VARCHAR"
args = ""
try:
coltype = self.ischema_names[coltype]
if args is not None:
args = re.findall(r"(\d+)", args)
coltype = coltype(*[int(a) for a in args])
except KeyError:
util.warn("Did not recognize type '%s' of column '%s'" % (coltype, name))
coltype = sqltypes.NullType()
if default is not None:
default = str(default)
return {
"name": name,
"type": coltype,
"nullable": nullable,
"default": default,
"autoincrement": default is None,
"primary_key": primary_key,
}
示例7: get_columns
def get_columns(self, connection, table_name, schema=None, **kw):
rows = self._get_table_columns(connection, table_name, schema)
# Strip whitespace
rows = [[col.strip() if col else None for col in row] for row in rows]
# Filter out empty rows and comment
rows = [row for row in rows if row[0] and row[0] != '# col_name']
result = []
for (col_name, col_type, _comment) in rows:
if col_name == '# Partition Information':
break
# Take out the more detailed type information
# e.g. 'map<int,int>' -> 'map'
# 'decimal(10,1)' -> decimal
col_type = re.search(r'^\w+', col_type).group(0)
try:
coltype = _type_map[col_type]
except KeyError:
util.warn("Did not recognize type '%s' of column '%s'" % (
col_type, col_name))
coltype = types.NullType
result.append({
'name': col_name,
'type': coltype,
'nullable': True,
'default': None,
})
return result
示例8: register_object
def register_object(self,
state,
isdelete=False,
listonly=False,
cancel_delete=False,
operation=None,
prop=None):
if not self.session._contains_state(state):
if not state.deleted and operation is not None:
util.warn("Object of type %s not in session, %s operation "
"along '%s' will not proceed" %
(mapperutil.state_class_str(state), operation, prop))
return False
if state not in self.states:
mapper = state.manager.mapper
if mapper not in self.mappers:
mapper._per_mapper_flush_actions(self)
self.mappers[mapper].add(state)
self.states[state] = (isdelete, listonly)
else:
if not listonly and (isdelete or cancel_delete):
self.states[state] = (isdelete, False)
return True
示例9: _get_column_info
def _get_column_info(self, name, type_, nullable,
default, primary_key):
match = re.match(r'(\w+)(\(.*?\))?', type_)
if match:
coltype = match.group(1)
args = match.group(2)
else:
coltype = "VARCHAR"
args = ''
try:
coltype = self.ischema_names[coltype]
if args is not None:
args = re.findall(r'(\d+)', args)
coltype = coltype(*[int(a) for a in args])
except KeyError:
util.warn("Did not recognize type '%s' of column '%s'" %
(coltype, name))
coltype = sqltypes.NullType()
if default is not None:
default = unicode(default)
return {
'name': name,
'type': coltype,
'nullable': nullable,
'default': default,
'autoincrement': default is None,
'primary_key': primary_key
}
示例10: define_constraint_cascades
def define_constraint_cascades(self, constraint):
text = ""
if constraint.ondelete is not None:
text += " ON DELETE %s" % constraint.ondelete
if constraint.onupdate is not None:
util.warn("DB2 does not support UPDATE CASCADE for foreign keys.")
return text
示例11: get_columns
def get_columns(self, connection, table_name, schema=None, **kw):
current_schema = self.denormalize_name(schema or self.default_schema_name)
table_name = self.denormalize_name(table_name)
syscols = self.sys_columns
query = sql.select([syscols.c.colname,
syscols.c.typename,
syscols.c.defaultval, syscols.c.nullable,
syscols.c.length, syscols.c.scale,
syscols.c.isid, syscols.c.idgenerate],
sql.and_(syscols.c.tabschema == current_schema,
syscols.c.tabname == table_name),
order_by=[syscols.c.colno])
sa_columns = []
for r in connection.execute(query):
coltype = r[1].upper()
if coltype in ('DECIMAL', 'NUMERIC'):
coltype = self.ischema_names.get(coltype)(int(r[4]), int(r[5]))
elif coltype in ('CHARACTER', 'CHAR', 'VARCHAR', 'GRAPHIC', 'VARGRAPHIC'):
coltype = self.ischema_names.get(coltype)(int(r[4]))
else:
try:
coltype = self.ischema_names[coltype]
except KeyError:
util.warn("Did not recognize type '%s' of column '%s'" % (coltype, r[0]))
coltype = sa_types.NULLTYPE
sa_columns.append({'name': self.normalize_name(r[0]),
'type': coltype,
'nullable': r[3] == 'Y',
'default': r[2],
'autoincrement': (r[6] == 'YES') and (r[7] is not None)})
return sa_columns
示例12: reflecttable
def reflecttable(self, connection, table, include_columns=None, exclude_columns=None):
exclude_columns = exclude_columns or []
try:
rows = connection.execute('SHOW COLUMNS FROM {}'.format(table))
except presto.DatabaseError as e:
# Normally SQLAlchemy should wrap this exception in sqlalchemy.exc.DatabaseError, which
# it successfully does in the Hive version. The difference with Presto is that this
# error is raised when fetching the cursor's description rather than the initial execute
# call. SQLAlchemy doesn't handle this. Thus, we catch the unwrapped
# presto.DatabaseError here.
# Does the table exist?
msg = e.message.get('message') if isinstance(e.message, dict) else None
regex = r"^Table\ \'.*{}\'\ does\ not\ exist$".format(re.escape(table.name))
if msg and re.match(regex, msg):
raise exc.NoSuchTableError(table.name)
else:
raise
else:
for row in rows:
name, coltype, nullable, is_partition_key = row
if include_columns is not None and name not in include_columns:
continue
if name in exclude_columns:
continue
try:
coltype = _type_map[coltype]
except KeyError:
util.warn("Did not recognize type '%s' of column '%s'" % (coltype, name))
coltype = types.NullType
table.append_column(schema.Column(
name=name,
type_=coltype,
nullable=nullable,
index=is_partition_key, # Translate Hive partitions to indexes
))
示例13: execute
def execute(state, dict_, row):
collection = collections.get(tuple([row[col] for col in local_cols]), (None,))
if len(collection) > 1:
util.warn("Multiple rows returned with " "uselist=False for eagerly-loaded attribute '%s' " % self)
scalar = collection[0]
state.get_impl(self.key).set_committed_value(state, dict_, scalar)
示例14: get_indexes
def get_indexes(self, connection, table_name, schema, **kw):
table_oid = self.get_table_oid(connection, table_name, schema, info_cache=kw.get("info_cache"))
IDX_SQL = """
SELECT c.relname, i.indisunique, i.indexprs, i.indpred,
a.attname
FROM pg_index i, pg_class c, pg_attribute a
WHERE i.indrelid = :table_oid AND i.indexrelid = c.oid
AND a.attrelid = i.indexrelid AND i.indisprimary = 'f'
ORDER BY c.relname, a.attnum
"""
t = sql.text(IDX_SQL, typemap={"attname": sqltypes.Unicode})
c = connection.execute(t, table_oid=table_oid)
index_names = {}
indexes = []
sv_idx_name = None
for row in c.fetchall():
idx_name, unique, expr, prd, col = row
if expr:
if idx_name != sv_idx_name:
util.warn("Skipped unsupported reflection of " "expression-based index %s" % idx_name)
sv_idx_name = idx_name
continue
if prd and not idx_name == sv_idx_name:
util.warn("Predicate of partial index %s ignored during reflection" % idx_name)
sv_idx_name = idx_name
if idx_name in index_names:
index_d = index_names[idx_name]
else:
index_d = {"column_names": []}
indexes.append(index_d)
index_names[idx_name] = index_d
index_d["name"] = idx_name
index_d["column_names"].append(col)
index_d["unique"] = unique
return indexes
示例15: _get_column_info
def _get_column_info(self, name, type_, nullable, autoincrement, default,
precision, scale, length):
coltype = self.ischema_names.get(type_, None)
kwargs = {}
if coltype in (NUMERIC, DECIMAL):
args = (precision, scale)
elif coltype == FLOAT:
args = (precision,)
elif coltype in (CHAR, VARCHAR, UNICHAR, UNIVARCHAR, NCHAR, NVARCHAR):
args = (length,)
else:
args = ()
if coltype:
coltype = coltype(*args, **kwargs)
#is this necessary
#if is_array:
# coltype = ARRAY(coltype)
else:
util.warn("Did not recognize type '%s' of column '%s'" %
(type_, name))
coltype = sqltypes.NULLTYPE
if default:
default = re.sub("DEFAULT", "", default).strip()
default = re.sub("^'(.*)'$", lambda m: m.group(1), default)
else:
default = None
column_info = dict(name=name, type=coltype, nullable=nullable,
default=default, autoincrement=autoincrement)
return column_info