PrimaryKeyConstraint
is a class within the sqlalchemy.schema
module of the SQLAlchemy project.
CheckConstraint,
Column,
CreateIndex,
CreateTable,
DDLElement,
ForeignKey,
ForeignKeyConstraint,
Index,
and Table
are several other callables with code examples from the same sqlalchemy.schema
package.
sqlalchemy-utils (project documentation and PyPI package information) is a code library with various helper functions and new data types that make it easier to use SQLAlchemy when building projects that involve more specific storage requirements such as currency. The wide array of data types includes ranged values and aggregated attributes.
sqlalchemy-utils / sqlalchemy_utils / view.py
# view.py
import sqlalchemy as sa
from sqlalchemy.ext import compiler
from sqlalchemy.schema import DDLElement, PrimaryKeyConstraint
class CreateView(DDLElement):
def __init__(self, name, selectable, materialized=False):
self.name = name
self.selectable = selectable
self.materialized = materialized
@compiler.compiles(CreateView)
def compile_create_materialized_view(element, compiler, **kw):
return 'CREATE {}VIEW {} AS {}'.format(
'MATERIALIZED ' if element.materialized else '',
element.name,
compiler.sql_compiler.process(element.selectable, literal_binds=True),
)
class DropView(DDLElement):
def __init__(self, name, materialized=False, cascade=True):
self.name = name
self.materialized = materialized
self.cascade = cascade
## ... source file abbreviated to get to PrimaryKeyConstraint examples ...
name,
selectable,
indexes=None,
metadata=None,
aliases=None
):
if indexes is None:
indexes = []
if metadata is None:
metadata = sa.MetaData()
if aliases is None:
aliases = {}
args = [
sa.Column(
c.name,
c.type,
key=aliases.get(c.name, c.name),
primary_key=c.primary_key
)
for c in selectable.c
] + indexes
table = sa.Table(name, metadata, *args)
if not any([c.primary_key for c in selectable.c]):
table.append_constraint(
PrimaryKeyConstraint(*[c.name for c in selectable.c])
)
return table
def create_materialized_view(
name,
selectable,
metadata,
indexes=None,
aliases=None
):
table = create_table_from_selectable(
name=name,
selectable=selectable,
indexes=indexes,
metadata=None,
aliases=aliases
)
sa.event.listen(
metadata,
'after_create',
CreateView(name, selectable, materialized=True)
)
## ... source file continues with no further PrimaryKeyConstraint examples...