How to use the sqlalchemy.ForeignKey function in SQLAlchemy

To help you get started, we’ve selected a few SQLAlchemy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github abilian / abilian-core / abilian / services / audit / tests.py View on Github external
account = relationship(
        DummyAccount,
        backref=backref(
            "data", order_by="AccountRelated.id", cascade="all, delete-orphan"
        ),
    )

    text = Column(UnicodeText, default="")


class CommentRelated(db.Model):
    __tablename__ = "account_related_comment"
    __auditable_entity__ = ("related.account", "data.comments", ("related.id", "id"))
    id = Column(Integer, primary_key=True)

    related_id = Column(Integer, ForeignKey(AccountRelated.id), nullable=False)
    related = relationship(
        AccountRelated,
        backref=backref(
            "comments", order_by="CommentRelated.id", cascade="all, delete-orphan"
        ),
    )
    text = Column(UnicodeText, default="")


def test_audit(app, session):
    create_root_user()
    audit_service.start()
    assert len(AuditEntry.query.all()) == 0

    # Creation of system user(0) should have created one entry.
    # We clear it for this test.
github openstack / tacker / tacker / db / vnfm / vnfm_db.py View on Github external
__table_args__ = (
        schema.UniqueConstraint(
            "tenant_id",
            "name",
            "deleted_at",
            name="uniq_vnfd0tenant_id0name0deleted_at"),
    )


class ServiceType(model_base.BASE, models_v1.HasId, models_v1.HasTenant):
    """Represents service type which hosting vnf provides.

    Since a vnf may provide many services, This is one-to-many
    relationship.
    """
    vnfd_id = sa.Column(types.Uuid, sa.ForeignKey('vnfd.id'),
                        nullable=False)
    service_type = sa.Column(sa.String(64), nullable=False)


class VNFDAttribute(model_base.BASE, models_v1.HasId):
    """Represents attributes necessary for spinning up VM in (key, value) pair

    key value pair is adopted for being agnostic to actuall manager of VMs.
    The interpretation is up to actual driver of hosting vnf.
    """

    __tablename__ = 'vnfd_attribute'
    vnfd_id = sa.Column(types.Uuid, sa.ForeignKey('vnfd.id'),
                        nullable=False)
    key = sa.Column(sa.String(255), nullable=False)
    value = sa.Column(sa.TEXT(65535), nullable=True)
github galaxyproject / galaxy / lib / tool_shed / webapp / model / migrate / versions / 0005_drop_tool_related_tables.py View on Github external
Column("event_id", Integer, ForeignKey("event.id"), index=True))

    ToolRatingAssociation_table = Table("tool_rating_association", metadata,
                                        Column("id", Integer, primary_key=True),
                                        Column("create_time", DateTime, default=now),
                                        Column("update_time", DateTime, default=now, onupdate=now),
                                        Column("tool_id", Integer, ForeignKey("tool.id"), index=True),
                                        Column("user_id", Integer, ForeignKey("galaxy_user.id"), index=True),
                                        Column("rating", Integer, index=True),
                                        Column("comment", TEXT))

    ToolTagAssociation_table = Table("tool_tag_association", metadata,
                                     Column("id", Integer, primary_key=True),
                                     Column("tool_id", Integer, ForeignKey("tool.id"), index=True),
                                     Column("tag_id", Integer, ForeignKey("tag.id"), index=True),
                                     Column("user_id", Integer, ForeignKey("galaxy_user.id"), index=True),
                                     Column("user_tname", TrimmedString(255), index=True),
                                     Column("value", TrimmedString(255), index=True),
                                     Column("user_value", TrimmedString(255), index=True))

    ToolAnnotationAssociation_table = Table("tool_annotation_association", metadata,
                                            Column("id", Integer, primary_key=True),
                                            Column("tool_id", Integer, ForeignKey("tool.id"), index=True),
                                            Column("user_id", Integer, ForeignKey("galaxy_user.id"), index=True),
                                            Column("annotation", TEXT, index=True))

    # Create the event table
    try:
        Event_table.create()
    except Exception:
        log.exception("Creating event table failed.")
    # Create the tool table
github gunthercox / ChatterBot / chatterbot / ext / sqlalchemy_app / models.py View on Github external
id = Column(
        Integer,
        primary_key=True,
        autoincrement=True
    )


Base = declarative_base(cls=ModelBase)


tag_association_table = Table(
    'tag_association',
    Base.metadata,
    Column('tag_id', Integer, ForeignKey('tag.id')),
    Column('statement_id', Integer, ForeignKey('statement.id'))
)


class Tag(Base):
    """
    A tag that describes a statement.
    """

    name = Column(
        String(constants.TAG_NAME_MAX_LENGTH),
        unique=True
    )


class Statement(Base, StatementMixin):
    """
github xraypy / xraylarch / lib / sql / scandb.py View on Github external
def PointerCol(name, other=None, keyid='id', **kws):
    if other is None:
        other = name
    return Column("%s_%s" % (name, keyid), None,
                  ForeignKey('%s.%s' % (other, keyid), **kws))
github healthnmon / healthnmon / healthnmon / db / sqlalchemy / migrate_repo / versions / 001_healthnmon_initial.py View on Github external
Column('isMaintenanceMode', Boolean),
    Column('powerState', String(255)),
    *(__common_columns())
)

IpProfile = Table(
    'healthnmon_ip_profile',
    meta,
    Column('ipAddress', String(255), primary_key=True),
    Column('ipType', Enum('IPV4', 'IPV6', 'UNSPECIFIED',
           name='IpTypeEnum')),
    Column('hostname', String(255), primary_key=True),
    Column('domain', String(255)),
    Column('vmHostId', String(255), ForeignKey('healthnmon_vm_host.id'
                                               )),
    Column('vmId', String(255), ForeignKey('healthnmon_vm.id')),
)

VirtualSwitch = Table(
    'healthnmon_virtual_switch',
    meta,
    Column('id', String(255), primary_key=True),
    Column('name', String(255)),
    Column('note', String(255)),
    Column('costId', Integer(), ForeignKey('healthnmon_cost.id')),
    Column('resourceManagerId', String(255)),
    Column('switchType', String(255)),
    Column('subnetIds', String(255)),
    Column('networkInterfaces', String(255)),
    Column('connectionState', String(255)),
    Column('vmHostId', String(255), ForeignKey('healthnmon_vm_host.id')),
    *(__common_columns())
github SBRG / cobradb / cobradb / components.py View on Github external
super(RNA, self).__init__(bigg_id, name)
        session = Session()
        self.genome_region_id = session.get_or_create(GenomeRegion, name=name, leftpos=leftpos,\
                                                      rightpos=rightpos, strand=strand,
                                                      chromosome_id=chromosome_id).id
        session.close()

    def __repr__(self):
        return "RNA (#%d, %s)" % \
            (self.id, self.bigg_id)


class TUGenes(Base):
    __tablename__ = 'tu_genes'

    tu_id = Column(Integer, ForeignKey('tu.id'), primary_key=True)
    gene_id = Column(Integer, ForeignKey('gene.id'), primary_key=True)

    __table_args__ = (UniqueConstraint('tu_id','gene_id'),{})

    def __init__(self, tu_id, gene_id):
        self.tu_id = tu_id
        self.gene_id = gene_id


class TU(RNA):
    __tablename__ = 'tu'

    id = Column(Integer, ForeignKey('rna.id'), primary_key=True)
    genome_region = relationship("GenomeRegion")
    genes = relationship("Gene", secondary="tu_genes", backref="tu",
                         primaryjoin=(id == TUGenes.tu_id))
github Pagure / pagure / pagure / hooks / mirror_hook.py View on Github external
_config = pagure.config.reload_config()


class MirrorTable(BASE):
    """ Stores information about the mirroring hook deployed on a project.

    Table -- mirror_pagure
    """

    __tablename__ = "hook_mirror"

    id = sa.Column(sa.Integer, primary_key=True)
    project_id = sa.Column(
        sa.Integer,
        sa.ForeignKey("projects.id", onupdate="CASCADE", ondelete="CASCADE"),
        nullable=False,
        unique=True,
        index=True,
    )

    active = sa.Column(sa.Boolean, nullable=False, default=False)

    public_key = sa.Column(sa.Text, nullable=True)
    target = sa.Column(sa.Text, nullable=True)
    last_log = sa.Column(sa.Text, nullable=True)

    project = relation(
        "Project",
        remote_side=[Project.id],
        backref=backref(
            "mirror_hook",
github ringo-framework / ringo / ringo / model / user.py View on Github external
import json
import sqlalchemy as sa
from datetime import datetime
from ringo.lib.alchemy import get_prop_from_instance
from ringo.model import Base
from ringo.model.base import BaseItem, BaseFactory
from ringo.model.mixins import Owned


log = logging.getLogger(__name__)


password_reset_requests = sa.Table(
    'password_reset_requests', Base.metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('uid', sa.Integer, sa.ForeignKey('users.id')),
    sa.Column('created', sa.DateTime),
    sa.Column('token', sa.String)
)

# NM-Table definitions
nm_user_roles = sa.Table(
    'nm_user_roles', Base.metadata,
    sa.Column('uid', sa.Integer, sa.ForeignKey('users.id')),
    sa.Column('rid', sa.Integer, sa.ForeignKey('roles.id'))
)

nm_user_usergroups = sa.Table(
    'nm_user_usergroups', Base.metadata,
    sa.Column('uid', sa.Integer, sa.ForeignKey('users.id')),
    sa.Column('gid', sa.Integer, sa.ForeignKey('usergroups.id'))
)
github grnet / synnefo / snf-pithos-backend / pithos / backends / lib / sqlalchemy / node.py View on Github external
autoincrement=False))
    columns.append(Column('latest_version', Integer))
    columns.append(Column('path', String(2048), default='', nullable=False))
    nodes = Table('nodes', metadata, *columns, mysql_engine='InnoDB')
    Index('idx_nodes_path', nodes.c.path, unique=True)
    Index('idx_nodes_parent', nodes.c.parent)
    Index('idx_latest_version', nodes.c.latest_version)
    Index('idx_nodes_parent0', nodes.c.parent,
          postgresql_where=nodes.c.parent == 0)
    Index('idx_nodes_parent0_path', nodes.c.parent, nodes.c.path,
          postgresql_where=nodes.c.parent == 0)

    #create policy table
    columns = []
    columns.append(Column('node', Integer,
                          ForeignKey('nodes.node',
                                     ondelete='CASCADE',
                                     onupdate='CASCADE'),
                          primary_key=True))
    columns.append(Column('key', String(128), primary_key=True))
    columns.append(Column('value', String(256)))
    Table('policy', metadata, *columns, mysql_engine='InnoDB')

    #create statistics table
    columns = []
    columns.append(Column('node', Integer,
                          ForeignKey('nodes.node',
                                     ondelete='CASCADE',
                                     onupdate='CASCADE'),
                          primary_key=True))
    columns.append(Column('population', Integer, nullable=False, default=0))
    columns.append(Column('size', BigInteger, nullable=False, default=0))