本文整理匯總了Python中sqlalchemy.CheckConstraint方法的典型用法代碼示例。如果您正苦於以下問題:Python sqlalchemy.CheckConstraint方法的具體用法?Python sqlalchemy.CheckConstraint怎麽用?Python sqlalchemy.CheckConstraint使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sqlalchemy
的用法示例。
在下文中一共展示了sqlalchemy.CheckConstraint方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: update_table_args
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def update_table_args(self, registry, Model):
"""Return check constraints to limit the value
:param registry:
:param Model:
:return: list of checkConstraint
"""
if self.encrypt_key:
# dont add constraint because the state is crypted and nobody
# can add new entry
return []
if sgdb_in(registry.engine, ['MariaDB', 'MsSQL']):
# No Check constraint in MariaDB
return []
enum = [country.alpha_3 for country in pycountry.countries]
constraint = """"%s" in ('%s')""" % (self.fieldname, "', '".join(enum))
enum.sort()
key = md5()
key.update(str(enum).encode('utf-8'))
name = self.fieldname + '_' + key.hexdigest() + '_types'
return [CheckConstraint(constraint, name=name)]
示例2: test_enum_detection
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_enum_detection(metadata):
Table("simple_items", metadata, Column("enum", VARCHAR(255)), CheckConstraint(r"simple_items.enum IN ('A', '\'B', 'C')"))
assert (
generate_code(metadata)
== """\
# coding: utf-8
from sqlalchemy import Column, Enum, MetaData, Table
metadata = MetaData()
t_simple_items = Table(
'simple_items', metadata,
Column('enum', Enum('A', "\\\\'B", 'C'))
)
"""
)
示例3: test_noindexes_table
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_noindexes_table(metadata):
simple_items = Table("simple_items", metadata, Column("number", INTEGER), CheckConstraint("number > 2"))
simple_items.indexes.add(Index("idx_number", simple_items.c.number))
assert (
generate_code(metadata, noindexes=True)
== """\
# coding: utf-8
from sqlalchemy import CheckConstraint, Column, Integer, MetaData, Table
metadata = MetaData()
t_simple_items = Table(
'simple_items', metadata,
Column('number', Integer),
CheckConstraint('number > 2')
)
"""
)
示例4: test_schema_boolean
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_schema_boolean(metadata):
Table(
"simple_items", metadata, Column("bool1", INTEGER), CheckConstraint("testschema.simple_items.bool1 IN (0, 1)"), schema="testschema"
)
assert (
generate_code(metadata)
== """\
# coding: utf-8
from sqlalchemy import Boolean, Column, MetaData, Table
metadata = MetaData()
t_simple_items = Table(
'simple_items', metadata,
Column('bool1', Boolean),
schema='testschema'
)
"""
)
示例5: render_constraint
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def render_constraint(self, constraint):
def render_fk_options(*opts):
opts = [repr(opt) for opt in opts]
for attr in "ondelete", "onupdate", "deferrable", "initially", "match":
value = getattr(constraint, attr, None)
if value:
opts.append("{0}={1!r}".format(attr, value))
return ", ".join(opts)
if isinstance(constraint, ForeignKey):
remote_column = "{0}.{1}".format(constraint.column.table.fullname, constraint.column.name)
return "ForeignKey({0})".format(render_fk_options(remote_column))
elif isinstance(constraint, ForeignKeyConstraint):
local_columns = _get_column_names(constraint)
remote_columns = ["{0}.{1}".format(fk.column.table.fullname, fk.column.name) for fk in constraint.elements]
return "ForeignKeyConstraint({0})".format(render_fk_options(local_columns, remote_columns))
elif isinstance(constraint, CheckConstraint):
return "CheckConstraint({0!r})".format(self._get_compiled_expression(constraint.sqltext))
elif isinstance(constraint, UniqueConstraint):
columns = [repr(col.name) for col in constraint.columns]
return "UniqueConstraint({0})".format(", ".join(columns))
示例6: test_add_check_constraint_already_named_from_schema
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_add_check_constraint_already_named_from_schema(self):
m1 = MetaData(
naming_convention={"ck": "ck_%(table_name)s_%(constraint_name)s"}
)
ck = CheckConstraint("im a constraint", name="cc1")
Table("t", m1, Column("x"), ck)
context = op_fixture(
naming_convention={"ck": "ck_%(table_name)s_%(constraint_name)s"}
)
op.create_table("some_table", Column("x", Integer, ck))
context.assert_(
"CREATE TABLE some_table "
"(x INTEGER CONSTRAINT ck_t_cc1 CHECK (im a constraint))"
)
示例7: test_rename_col_boolean
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_rename_col_boolean(self):
impl = self._boolean_fixture()
impl.alter_column("tname", "flag", name="bflag")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (bflag IN (0, 1)",
colnames=["id", "flag"],
)
eq_(new_table.c.flag.name, "bflag")
eq_(
len(
[
const
for const in new_table.constraints
if isinstance(const, CheckConstraint)
]
),
1,
)
示例8: test_rename_col_boolean_no_ck
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_rename_col_boolean_no_ck(self):
impl = self._boolean_no_ck_fixture()
impl.alter_column("tname", "flag", name="bflag")
new_table = self._assert_impl(
impl, ddl_not_contains="CHECK", colnames=["id", "flag"]
)
eq_(new_table.c.flag.name, "bflag")
eq_(
len(
[
const
for const in new_table.constraints
if isinstance(const, CheckConstraint)
]
),
0,
)
示例9: test_rename_col_enum
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_rename_col_enum(self):
impl = self._enum_fixture()
impl.alter_column("tname", "thing", name="thang")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (thang IN ('a', 'b', 'c')",
colnames=["id", "thing"],
)
eq_(new_table.c.thing.name, "thang")
eq_(
len(
[
const
for const in new_table.constraints
if isinstance(const, CheckConstraint)
]
),
1,
)
示例10: test_rename_col_sql_ck
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_rename_col_sql_ck(self):
impl = self._sql_ck_fixture()
impl.alter_column("tname", "email", name="emol")
new_table = self._assert_impl(
impl,
ddl_contains="CHECK (emol LIKE '%@%')",
colnames=["id", "email"],
)
eq_(
len(
[
c
for c in new_table.constraints
if isinstance(c, CheckConstraint)
]
),
1,
)
eq_(new_table.c.email.name, "emol")
示例11: test_render_check_constraint_renamed
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def test_render_check_constraint_renamed(self):
"""test that constraints from autogenerate render with
the naming convention name explicitly. These names should
be frozen into the migration scripts so that they remain
the same if the application's naming convention changes.
However, op.create_table() and others need to be careful that
these don't double up when the "%(constraint_name)s" token is
used.
"""
m1 = MetaData(
naming_convention={"ck": "ck_%(table_name)s_%(constraint_name)s"}
)
ck = CheckConstraint("im a constraint", name="cc1")
Table("t", m1, Column("x"), ck)
eq_ignore_whitespace(
autogenerate.render._render_check_constraint(
ck, self.autogen_context
),
"sa.CheckConstraint(!U'im a constraint', name=op.f('ck_t_cc1'))",
)
示例12: json_column
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def json_column(column_name: str, *, default=None) -> sa.Column:
"""A JSONB column.
Return a column of type JSONB for use in models. Use this for entries like
<language>: <text>
:param column_name: the name of the column
:param default: the column default (default value None, meaning no column
default)
:return: a SQLAlchemy Column for a non-null JSONB type.
"""
return sa.Column(
pg.json.JSONB,
sa.CheckConstraint(
"{} @> '{{}}'".format(column_name),
name='{}_valid_json_check'.format(column_name),
),
nullable=False,
server_default=default,
)
示例13: languages_column
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def languages_column(column_name) -> sa.Column:
"""A TEXT[] column of length > 0.
Return an ARRAY(TEXT, as_tuple=True) column.
:param column_name: the name of the column
:returns: a SQLAlchemy Column for a non-null ARRAY(TEXT, as_tuple=True)
type.
"""
return sa.Column(
pg.ARRAY(pg.TEXT, as_tuple=True),
sa.CheckConstraint(
'COALESCE(ARRAY_LENGTH({}, 1), 0) > 0'.format(column_name)
),
nullable=False,
default=['English'],
)
示例14: languages_constraint
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def languages_constraint(column_name, languages_column_name) -> sa.Constraint:
"""CHECK CONSTRAINT for a translatable column.
Checks that all of the languages in the languages column exist as keys in
the translatable column.
:param column_name: the name of the translatable column
:param languages_column_name: the name of the TEXT[] column containing the
languages.
:return: a SQLAlchemy Constraint to ensure that all the required
translations are available.
"""
return sa.CheckConstraint(
"{} ?& {}".format(column_name, languages_column_name),
name='all_{}_languages_present_in_{}'.format(
column_name, languages_column_name
),
)
示例15: _version_table_schema
# 需要導入模塊: import sqlalchemy [as 別名]
# 或者: from sqlalchemy import CheckConstraint [as 別名]
def _version_table_schema(metadata):
# NOTE: When modifying this schema, update the ASSET_DB_VERSION value
return sa.Table(
'version_info',
metadata,
sa.Column(
'id',
sa.Integer,
unique=True,
nullable=False,
primary_key=True,
),
sa.Column(
'version',
sa.Integer,
unique=True,
nullable=False,
),
# This constraint ensures a single entry in this table
sa.CheckConstraint('id <= 1'),
)