Skip to content

prefect.server.database.orm_models

Agent

Bases: Base

SQLAlchemy model of an agent

Source code in src/prefect/server/database/orm_models.py
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
class Agent(Base):
    """SQLAlchemy model of an agent"""

    name = sa.Column(sa.String, nullable=False)

    work_queue_id = sa.Column(
        UUID,
        sa.ForeignKey("work_queue.id"),
        nullable=False,
        index=True,
    )

    last_activity_time = sa.Column(
        Timestamp(),
        nullable=False,
        server_default=now(),
        default=lambda: pendulum.now("UTC"),
    )

    __table_args__ = (sa.UniqueConstraint("name"),)

AioSqliteORMConfiguration

Bases: BaseORMConfiguration

SQLite specific orm configuration

Source code in src/prefect/server/database/orm_models.py
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
class AioSqliteORMConfiguration(BaseORMConfiguration):
    """SQLite specific orm configuration"""

    @property
    def versions_dir(self) -> Path:
        """Directory containing migrations"""
        return (
            Path(prefect.server.database.__file__).parent
            / "migrations"
            / "versions"
            / "sqlite"
        )

versions_dir: Path property

Directory containing migrations

Artifact

Bases: Base

SQLAlchemy model of artifacts.

Source code in src/prefect/server/database/orm_models.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class Artifact(Base):
    """
    SQLAlchemy model of artifacts.
    """

    key = sa.Column(
        sa.String,
        nullable=True,
        index=True,
    )

    task_run_id = sa.Column(
        UUID(),
        nullable=True,
        index=True,
    )

    flow_run_id = sa.Column(
        UUID(),
        nullable=True,
        index=True,
    )

    type = sa.Column(sa.String)
    data = sa.Column(sa.JSON, nullable=True)
    description = sa.Column(sa.String, nullable=True)

    # Suffixed with underscore as attribute name 'metadata' is reserved for the MetaData instance when using a declarative base class.
    metadata_ = sa.Column(sa.JSON, nullable=True)

    __table_args__ = (
        sa.Index(
            "ix_artifact__key",
            "key",
        ),
    )

AsyncPostgresORMConfiguration

Bases: BaseORMConfiguration

Postgres specific orm configuration

Source code in src/prefect/server/database/orm_models.py
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
class AsyncPostgresORMConfiguration(BaseORMConfiguration):
    """Postgres specific orm configuration"""

    @property
    def versions_dir(self) -> Path:
        """Directory containing migrations"""
        return (
            Path(prefect.server.database.__file__).parent
            / "migrations"
            / "versions"
            / "postgresql"
        )

versions_dir: Path property

Directory containing migrations

Automation

Bases: Base

Source code in src/prefect/server/database/orm_models.py
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
class Automation(Base):
    name = sa.Column(sa.String, nullable=False)
    description = sa.Column(sa.String, nullable=False, default="")

    enabled = sa.Column(sa.Boolean, nullable=False, server_default="1", default=True)

    trigger = sa.Column(Pydantic(ServerTriggerTypes), nullable=False)

    actions = sa.Column(Pydantic(List[ServerActionTypes]), nullable=False)
    actions_on_trigger = sa.Column(
        Pydantic(List[ServerActionTypes]),
        server_default="[]",
        default=list,
        nullable=False,
    )
    actions_on_resolve = sa.Column(
        Pydantic(List[ServerActionTypes]),
        server_default="[]",
        default=list,
        nullable=False,
    )

    related_resources = sa.orm.relationship(
        "AutomationRelatedResource", back_populates="automation", lazy="raise"
    )

    @classmethod
    def sort_expression(cls, value: AutomationSort) -> ColumnElement:
        """Return an expression used to sort Automations"""
        sort_mapping = {
            AutomationSort.CREATED_DESC: cls.created.desc(),
            AutomationSort.UPDATED_DESC: cls.updated.desc(),
            AutomationSort.NAME_ASC: cast(sa.Column, cls.name).asc(),
            AutomationSort.NAME_DESC: cast(sa.Column, cls.name).desc(),
        }
        return sort_mapping[value]

sort_expression(value) classmethod

Return an expression used to sort Automations

Source code in src/prefect/server/database/orm_models.py
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
@classmethod
def sort_expression(cls, value: AutomationSort) -> ColumnElement:
    """Return an expression used to sort Automations"""
    sort_mapping = {
        AutomationSort.CREATED_DESC: cls.created.desc(),
        AutomationSort.UPDATED_DESC: cls.updated.desc(),
        AutomationSort.NAME_ASC: cast(sa.Column, cls.name).asc(),
        AutomationSort.NAME_DESC: cast(sa.Column, cls.name).desc(),
    }
    return sort_mapping[value]

Base

Bases: DeclarativeBase

Base SQLAlchemy model that automatically infers the table name and provides ID, created, and updated columns

Source code in src/prefect/server/database/orm_models.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class Base(DeclarativeBase):
    """
    Base SQLAlchemy model that automatically infers the table name
    and provides ID, created, and updated columns
    """

    registry = registry(
        metadata=sa.schema.MetaData(
            # define naming conventions for our Base class to use
            # sqlalchemy will use the following templated strings
            # to generate the names of indices, constraints, and keys
            #
            # we offset the table name with two underscores (__) to
            # help differentiate, for example, between "flow_run.state_type"
            # and "flow_run_state.type".
            #
            # more information on this templating and available
            # customization can be found here
            # https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.MetaData
            #
            # this also allows us to avoid having to specify names explicitly
            # when using sa.ForeignKey.use_alter = True
            # https://docs.sqlalchemy.org/en/14/core/constraints.html
            naming_convention={
                "ix": "ix_%(table_name)s__%(column_0_N_name)s",
                "uq": "uq_%(table_name)s__%(column_0_N_name)s",
                "ck": "ck_%(table_name)s__%(constraint_name)s",
                "fk": "fk_%(table_name)s__%(column_0_N_name)s__%(referred_table_name)s",
                "pk": "pk_%(table_name)s",
            }
        ),
        type_annotation_map={
            uuid.UUID: UUID,
        },
    )

    # required in order to access columns with server defaults
    # or SQL expression defaults, subsequent to a flush, without
    # triggering an expired load
    #
    # this allows us to load attributes with a server default after
    # an INSERT, for example
    #
    # https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#preventing-implicit-io-when-using-asyncsession
    __mapper_args__ = {"eager_defaults": True}

    def __repr__(self):
        return f"{self.__class__.__name__}(id={self.id})"

    @declared_attr
    def __tablename__(cls):
        """
        By default, turn the model's camel-case class name
        into a snake-case table name. Override by providing
        an explicit `__tablename__` class property.
        """
        return camel_to_snake.sub("_", cls.__name__).lower()

    id: Mapped[uuid.UUID] = mapped_column(
        primary_key=True,
        server_default=GenerateUUID(),
        default=uuid.uuid4,
    )

    created = sa.Column(
        Timestamp(),
        nullable=False,
        server_default=now(),
        default=lambda: pendulum.now("UTC"),
    )

    # onupdate is only called when statements are actually issued
    # against the database. until COMMIT is issued, this column
    # will not be updated
    updated = sa.Column(
        Timestamp(),
        nullable=False,
        index=True,
        server_default=now(),
        default=lambda: pendulum.now("UTC"),
        onupdate=now(),
        server_onupdate=FetchedValue(),
    )

__tablename__()

By default, turn the model's camel-case class name into a snake-case table name. Override by providing an explicit __tablename__ class property.

Source code in src/prefect/server/database/orm_models.py
101
102
103
104
105
106
107
108
@declared_attr
def __tablename__(cls):
    """
    By default, turn the model's camel-case class name
    into a snake-case table name. Override by providing
    an explicit `__tablename__` class property.
    """
    return camel_to_snake.sub("_", cls.__name__).lower()

BaseORMConfiguration

Bases: ABC

Abstract base class used to inject database-specific ORM configuration into Prefect.

Modifications to core Prefect REST API data structures can have unintended consequences. Use with caution.

Source code in src/prefect/server/database/orm_models.py
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
class BaseORMConfiguration(ABC):
    """
    Abstract base class used to inject database-specific ORM configuration into Prefect.

    Modifications to core Prefect REST API data structures can have unintended consequences.
    Use with caution.
    """

    def _unique_key(self) -> Tuple[Hashable, ...]:
        """
        Returns a key used to determine whether to instantiate a new DB interface.
        """
        return (self.__class__, Base.metadata)

    @property
    @abstractmethod
    def versions_dir(self):
        """Directory containing migrations"""
        ...

    @property
    def deployment_unique_upsert_columns(self):
        """Unique columns for upserting a Deployment"""
        return [Deployment.flow_id, Deployment.name]

    @property
    def concurrency_limit_unique_upsert_columns(self):
        """Unique columns for upserting a ConcurrencyLimit"""
        return [ConcurrencyLimit.tag]

    @property
    def flow_run_unique_upsert_columns(self):
        """Unique columns for upserting a FlowRun"""
        return [FlowRun.flow_id, FlowRun.idempotency_key]

    @property
    def block_type_unique_upsert_columns(self):
        """Unique columns for upserting a BlockType"""
        return [BlockType.slug]

    @property
    def artifact_collection_unique_upsert_columns(self):
        """Unique columns for upserting an ArtifactCollection"""
        return [ArtifactCollection.key]

    @property
    def block_schema_unique_upsert_columns(self):
        """Unique columns for upserting a BlockSchema"""
        return [BlockSchema.checksum, BlockSchema.version]

    @property
    def flow_unique_upsert_columns(self):
        """Unique columns for upserting a Flow"""
        return [Flow.name]

    @property
    def saved_search_unique_upsert_columns(self):
        """Unique columns for upserting a SavedSearch"""
        return [SavedSearch.name]

    @property
    def task_run_unique_upsert_columns(self):
        """Unique columns for upserting a TaskRun"""
        return [
            TaskRun.flow_run_id,
            TaskRun.task_key,
            TaskRun.dynamic_key,
        ]

    @property
    def block_document_unique_upsert_columns(self):
        """Unique columns for upserting a BlockDocument"""
        return [BlockDocument.block_type_id, BlockDocument.name]

artifact_collection_unique_upsert_columns property

Unique columns for upserting an ArtifactCollection

block_document_unique_upsert_columns property

Unique columns for upserting a BlockDocument

block_schema_unique_upsert_columns property

Unique columns for upserting a BlockSchema

block_type_unique_upsert_columns property

Unique columns for upserting a BlockType

concurrency_limit_unique_upsert_columns property

Unique columns for upserting a ConcurrencyLimit

deployment_unique_upsert_columns property

Unique columns for upserting a Deployment

flow_run_unique_upsert_columns property

Unique columns for upserting a FlowRun

flow_unique_upsert_columns property

Unique columns for upserting a Flow

saved_search_unique_upsert_columns property

Unique columns for upserting a SavedSearch

task_run_unique_upsert_columns property

Unique columns for upserting a TaskRun

versions_dir abstractmethod property

Directory containing migrations

BlockDocument

Bases: Base

Source code in src/prefect/server/database/orm_models.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
class BlockDocument(Base):
    name = sa.Column(sa.String, nullable=False, index=True)
    data = sa.Column(JSON, server_default="{}", default=dict, nullable=False)
    is_anonymous = sa.Column(sa.Boolean, server_default="0", index=True, nullable=False)

    block_type_name = sa.Column(sa.String, nullable=True)

    block_type_id = sa.Column(
        UUID(),
        sa.ForeignKey("block_type.id", ondelete="cascade"),
        nullable=False,
    )

    block_type = sa.orm.relationship("BlockType", lazy="selectin")

    block_schema_id = sa.Column(
        UUID(),
        sa.ForeignKey("block_schema.id", ondelete="cascade"),
        nullable=False,
    )

    block_schema = sa.orm.relationship("BlockSchema", lazy="selectin")

    __table_args__ = (
        sa.Index(
            "uq_block__type_id_name",
            "block_type_id",
            "name",
            unique=True,
        ),
    )

    async def encrypt_data(self, session, data):
        """
        Store encrypted data on the ORM model

        Note: will only succeed if the caller has sufficient permission.
        """
        self.data = await encrypt_fernet(session, data)

    async def decrypt_data(self, session):
        """
        Retrieve decrypted data from the ORM model.

        Note: will only succeed if the caller has sufficient permission.
        """
        return await decrypt_fernet(session, self.data)

decrypt_data(session) async

Retrieve decrypted data from the ORM model.

Note: will only succeed if the caller has sufficient permission.

Source code in src/prefect/server/database/orm_models.py
1089
1090
1091
1092
1093
1094
1095
async def decrypt_data(self, session):
    """
    Retrieve decrypted data from the ORM model.

    Note: will only succeed if the caller has sufficient permission.
    """
    return await decrypt_fernet(session, self.data)

encrypt_data(session, data) async

Store encrypted data on the ORM model

Note: will only succeed if the caller has sufficient permission.

Source code in src/prefect/server/database/orm_models.py
1081
1082
1083
1084
1085
1086
1087
async def encrypt_data(self, session, data):
    """
    Store encrypted data on the ORM model

    Note: will only succeed if the caller has sufficient permission.
    """
    self.data = await encrypt_fernet(session, data)

Deployment

Bases: Base

SQLAlchemy model of a deployment.

Source code in src/prefect/server/database/orm_models.py
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
class Deployment(Base):
    """SQLAlchemy model of a deployment."""

    name = sa.Column(sa.String, nullable=False)
    version = sa.Column(sa.String, nullable=True)
    description = sa.Column(sa.Text(), nullable=True)
    work_queue_name = sa.Column(sa.String, nullable=True, index=True)
    infra_overrides = sa.Column(JSON, server_default="{}", default=dict, nullable=False)
    path = sa.Column(sa.String, nullable=True)
    entrypoint = sa.Column(sa.String, nullable=True)

    last_polled = sa.Column(Timestamp(), nullable=True)
    status = sa.Column(
        sa.Enum(DeploymentStatus, name="deployment_status"),
        nullable=False,
        default=DeploymentStatus.NOT_READY,
        server_default="NOT_READY",
    )

    @declared_attr
    def job_variables(self):
        return synonym("infra_overrides")

    flow_id: Mapped[uuid.UUID] = mapped_column(
        UUID,
        sa.ForeignKey("flow.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    work_queue_id: Mapped[uuid.UUID] = mapped_column(
        UUID,
        sa.ForeignKey("work_queue.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    paused = sa.Column(
        sa.Boolean, nullable=False, server_default="0", default=False, index=True
    )

    schedules = sa.orm.relationship(
        "DeploymentSchedule",
        lazy="selectin",
        order_by=sa.desc(sa.text("updated")),
    )

    concurrency_limit: Mapped[Union[int, None]] = mapped_column(
        sa.Integer, default=None, nullable=True
    )
    tags: Mapped[List[str]] = mapped_column(
        JSON, server_default="[]", default=list, nullable=False
    )
    parameters = sa.Column(JSON, server_default="{}", default=dict, nullable=False)
    pull_steps = sa.Column(JSON, default=list, nullable=True)
    parameter_openapi_schema = sa.Column(JSON, default=dict, nullable=True)
    enforce_parameter_schema = sa.Column(
        sa.Boolean, default=True, server_default="0", nullable=False
    )
    created_by = sa.Column(
        Pydantic(schemas.core.CreatedBy),
        server_default=None,
        default=None,
        nullable=True,
    )
    updated_by = sa.Column(
        Pydantic(schemas.core.UpdatedBy),
        server_default=None,
        default=None,
        nullable=True,
    )

    infrastructure_document_id = sa.Column(
        UUID,
        sa.ForeignKey("block_document.id", ondelete="CASCADE"),
        nullable=True,
        index=False,
    )

    storage_document_id = sa.Column(
        UUID,
        sa.ForeignKey("block_document.id", ondelete="CASCADE"),
        nullable=True,
        index=False,
    )

    flow = sa.orm.relationship("Flow", back_populates="deployments", lazy="raise")

    work_queue = sa.orm.relationship(
        "WorkQueue", lazy="selectin", foreign_keys=[work_queue_id]
    )

    __table_args__ = (
        sa.Index(
            "uq_deployment__flow_id_name",
            "flow_id",
            "name",
            unique=True,
        ),
        sa.Index(
            "ix_deployment__created",
            "created",
        ),
    )

Flow

Bases: Base

SQLAlchemy mixin of a flow.

Source code in src/prefect/server/database/orm_models.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
class Flow(Base):
    """SQLAlchemy mixin of a flow."""

    name = sa.Column(sa.String, nullable=False)
    tags: Mapped[List[str]] = mapped_column(
        JSON, server_default="[]", default=list, nullable=False
    )

    flow_runs = sa.orm.relationship("FlowRun", back_populates="flow", lazy="raise")
    deployments = sa.orm.relationship("Deployment", back_populates="flow", lazy="raise")

    __table_args__ = (
        sa.UniqueConstraint("name"),
        sa.Index("ix_flow__created", "created"),
    )

FlowRun

Bases: Run

SQLAlchemy model of a flow run.

Source code in src/prefect/server/database/orm_models.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
class FlowRun(Run):
    """SQLAlchemy model of a flow run."""

    flow_id: Mapped[uuid.UUID] = mapped_column(
        UUID(),
        sa.ForeignKey("flow.id", ondelete="cascade"),
        nullable=False,
        index=True,
    )

    deployment_id: Mapped[Union[uuid.UUID, None]] = mapped_column(UUID(), nullable=True)
    work_queue_name = sa.Column(sa.String, index=True)
    flow_version = sa.Column(sa.String, index=True)
    deployment_version = sa.Column(sa.String, index=True)
    parameters = sa.Column(JSON, server_default="{}", default=dict, nullable=False)
    idempotency_key = sa.Column(sa.String)
    context = sa.Column(JSON, server_default="{}", default=dict, nullable=False)
    empirical_policy = sa.Column(
        Pydantic(schemas.core.FlowRunPolicy),
        server_default="{}",
        default=schemas.core.FlowRunPolicy,
        nullable=False,
    )
    tags: Mapped[List[str]] = mapped_column(
        JSON, server_default="[]", default=list, nullable=False
    )

    created_by: Mapped[Union[schemas.core.CreatedBy, None]] = mapped_column(
        Pydantic(schemas.core.CreatedBy),
        server_default=None,
        default=None,
        nullable=True,
    )

    infrastructure_pid = sa.Column(sa.String)
    job_variables = sa.Column(JSON, server_default="{}", default=dict, nullable=True)

    infrastructure_document_id = sa.Column(
        UUID,
        sa.ForeignKey("block_document.id", ondelete="CASCADE"),
        nullable=True,
        index=True,
    )

    parent_task_run_id: Mapped[uuid.UUID] = mapped_column(
        UUID(),
        sa.ForeignKey(
            "task_run.id",
            ondelete="SET NULL",
            use_alter=True,
        ),
        index=True,
    )

    auto_scheduled = sa.Column(
        sa.Boolean, server_default="0", default=False, nullable=False
    )

    # TODO remove this foreign key for significant delete performance gains
    state_id = sa.Column(
        UUID(),
        sa.ForeignKey(
            "flow_run_state.id",
            ondelete="SET NULL",
            use_alter=True,
        ),
        index=True,
    )

    work_queue_id: Mapped[Union[uuid.UUID, None]] = mapped_column(
        UUID,
        sa.ForeignKey("work_queue.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )

    # -------------------------- relationships

    # current states are eagerly loaded unless otherwise specified
    _state = sa.orm.relationship(
        "FlowRunState",
        lazy="selectin",
        foreign_keys=[state_id],
        primaryjoin="FlowRunState.id==FlowRun.state_id",
    )

    @hybrid_property
    def state(self):
        return self._state

    @state.setter
    def state(self, value):
        # because this is a slightly non-standard SQLAlchemy relationship, we
        # prefer an explicit setter method to a setter property, because
        # user expectations about SQLAlchemy attribute assignment might not be
        # met, namely that an unrelated (from SQLAlchemy's perspective) field of
        # the provided state is also modified. However, property assignment
        # still works because the ORM model's __init__ depends on it.
        return self.set_state(value)

    def set_state(self, state):
        """
        If a state is assigned to this run, populate its run id.

        This would normally be handled by the back-populated SQLAlchemy
        relationship, but because this is a one-to-one pointer to a
        one-to-many relationship, SQLAlchemy can't figure it out.
        """
        if state is not None:
            state.flow_run_id = self.id
        self._state = state

    flow = sa.orm.relationship("Flow", back_populates="flow_runs", lazy="raise")

    task_runs = sa.orm.relationship(
        "TaskRun",
        back_populates="flow_run",
        lazy="raise",
        # foreign_keys=lambda: [flow_run_id],
        primaryjoin="TaskRun.flow_run_id==FlowRun.id",
    )

    parent_task_run = sa.orm.relationship(
        "TaskRun",
        back_populates="subflow_run",
        lazy="raise",
        foreign_keys=[parent_task_run_id],
    )

    work_queue = sa.orm.relationship(
        "WorkQueue",
        lazy="selectin",
        foreign_keys=[work_queue_id],
    )

    __table_args__ = (
        sa.Index(
            "uq_flow_run__flow_id_idempotency_key",
            "flow_id",
            "idempotency_key",
            unique=True,
        ),
        sa.Index(
            "ix_flow_run__coalesce_start_time_expected_start_time_desc",
            sa.desc(coalesce("start_time", "expected_start_time")),
        ),
        sa.Index(
            "ix_flow_run__coalesce_start_time_expected_start_time_asc",
            sa.asc(coalesce("start_time", "expected_start_time")),
        ),
        sa.Index(
            "ix_flow_run__expected_start_time_desc",
            sa.desc("expected_start_time"),
        ),
        sa.Index(
            "ix_flow_run__next_scheduled_start_time_asc",
            sa.asc("next_scheduled_start_time"),
        ),
        sa.Index(
            "ix_flow_run__end_time_desc",
            sa.desc("end_time"),
        ),
        sa.Index(
            "ix_flow_run__start_time",
            "start_time",
        ),
        sa.Index(
            "ix_flow_run__state_type",
            "state_type",
        ),
        sa.Index(
            "ix_flow_run__state_name",
            "state_name",
        ),
        sa.Index(
            "ix_flow_run__state_timestamp",
            "state_timestamp",
        ),
    )

set_state(state)

If a state is assigned to this run, populate its run id.

This would normally be handled by the back-populated SQLAlchemy relationship, but because this is a one-to-one pointer to a one-to-many relationship, SQLAlchemy can't figure it out.

Source code in src/prefect/server/database/orm_models.py
589
590
591
592
593
594
595
596
597
598
599
def set_state(self, state):
    """
    If a state is assigned to this run, populate its run id.

    This would normally be handled by the back-populated SQLAlchemy
    relationship, but because this is a one-to-one pointer to a
    one-to-many relationship, SQLAlchemy can't figure it out.
    """
    if state is not None:
        state.flow_run_id = self.id
    self._state = state

FlowRunState

Bases: Base

SQLAlchemy mixin of a flow run state.

Source code in src/prefect/server/database/orm_models.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
class FlowRunState(Base):
    """SQLAlchemy mixin of a flow run state."""

    flow_run_id = sa.Column(
        UUID(), sa.ForeignKey("flow_run.id", ondelete="cascade"), nullable=False
    )

    type = sa.Column(
        sa.Enum(schemas.states.StateType, name="state_type"), nullable=False, index=True
    )
    timestamp = sa.Column(
        Timestamp(),
        nullable=False,
        server_default=now(),
        default=lambda: pendulum.now("UTC"),
    )
    name = sa.Column(sa.String, nullable=False, index=True)
    message = sa.Column(sa.String)
    state_details = sa.Column(
        Pydantic(schemas.states.StateDetails),
        server_default="{}",
        default=schemas.states.StateDetails,
        nullable=False,
    )
    _data = sa.Column(sa.JSON, nullable=True, name="data")

    result_artifact_id = sa.Column(
        UUID(),
        sa.ForeignKey(
            "artifact.id",
            ondelete="SET NULL",
            use_alter=True,
        ),
        index=True,
    )

    _result_artifact = sa.orm.relationship(
        "Artifact",
        lazy="selectin",
        foreign_keys=[result_artifact_id],
        primaryjoin="Artifact.id==FlowRunState.result_artifact_id",
    )

    @hybrid_property
    def data(self):
        if self._data:
            # ensures backwards compatibility for results stored on state objects
            return self._data
        if not self.result_artifact_id:
            # do not try to load the relationship if there's no artifact id
            return None
        return self._result_artifact.data

    flow_run = sa.orm.relationship(
        "FlowRun",
        lazy="raise",
        foreign_keys=[flow_run_id],
    )

    def as_state(self) -> schemas.states.State:
        return schemas.states.State.model_validate(self, from_attributes=True)

    __table_args__ = (
        sa.Index(
            "uq_flow_run_state__flow_run_id_timestamp_desc",
            "flow_run_id",
            sa.desc("timestamp"),
            unique=True,
        ),
    )

Log

Bases: Base

SQLAlchemy model of a logging statement.

Source code in src/prefect/server/database/orm_models.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
class Log(Base):
    """
    SQLAlchemy model of a logging statement.
    """

    name = sa.Column(sa.String, nullable=False)
    level = sa.Column(sa.SmallInteger, nullable=False, index=True)
    flow_run_id = sa.Column(UUID(), nullable=True, index=True)
    task_run_id = sa.Column(UUID(), nullable=True, index=True)
    message = sa.Column(sa.Text, nullable=False)

    # The client-side timestamp of this logged statement.
    timestamp = sa.Column(Timestamp(), nullable=False, index=True)

    __table_args__ = (
        sa.Index(
            "ix_log__flow_run_id_timestamp",
            "flow_run_id",
            "timestamp",
        ),
    )

Run

Bases: Base

Common columns and logic for FlowRun and TaskRun models

Source code in src/prefect/server/database/orm_models.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
class Run(Base):
    """
    Common columns and logic for FlowRun and TaskRun models
    """

    __abstract__ = True

    name = sa.Column(
        sa.String,
        default=lambda: generate_slug(2),
        nullable=False,
        index=True,
    )
    state_type = sa.Column(sa.Enum(schemas.states.StateType, name="state_type"))
    state_name = sa.Column(sa.String, nullable=True)
    state_timestamp = sa.Column(Timestamp(), nullable=True)
    run_count = sa.Column(sa.Integer, server_default="0", default=0, nullable=False)
    expected_start_time = sa.Column(Timestamp())
    next_scheduled_start_time = sa.Column(Timestamp())
    start_time = sa.Column(Timestamp())
    end_time = sa.Column(Timestamp())
    total_run_time = sa.Column(
        sa.Interval(),
        server_default="0",
        default=datetime.timedelta(0),
        nullable=False,
    )

    @hybrid_property
    def estimated_run_time(self):
        """Total run time is incremented in the database whenever a RUNNING
        state is exited. To give up-to-date estimates, we estimate incremental
        run time for any runs currently in a RUNNING state."""
        if self.state_type and self.state_type == schemas.states.StateType.RUNNING:
            return self.total_run_time + (pendulum.now("UTC") - self.state_timestamp)
        else:
            return self.total_run_time

    @estimated_run_time.expression
    def estimated_run_time(cls):
        return (
            sa.select(
                sa.case(
                    (
                        cls.state_type == schemas.states.StateType.RUNNING,
                        interval_add(
                            cls.total_run_time,
                            date_diff(now(), cls.state_timestamp),
                        ),
                    ),
                    else_=cls.total_run_time,
                )
            )
            # add a correlate statement so this can reuse the `FROM` clause
            # of any parent query
            .correlate(cls)
            .label("estimated_run_time")
        )

    @hybrid_property
    def estimated_start_time_delta(self) -> datetime.timedelta:
        """The delta to the expected start time (or "lateness") is computed as
        the difference between the actual start time and expected start time. To
        give up-to-date estimates, we estimate lateness for any runs that don't
        have a start time and are not in a final state and were expected to
        start already."""
        if self.start_time and self.start_time > self.expected_start_time:
            return self.start_time - self.expected_start_time
        elif (
            self.start_time is None
            and self.expected_start_time
            and self.expected_start_time < pendulum.now("UTC")
            and self.state_type not in schemas.states.TERMINAL_STATES
        ):
            return pendulum.now("UTC") - self.expected_start_time
        else:
            return datetime.timedelta(0)

    @estimated_start_time_delta.expression
    def estimated_start_time_delta(cls):
        return sa.case(
            (
                cls.start_time > cls.expected_start_time,
                date_diff(cls.start_time, cls.expected_start_time),
            ),
            (
                sa.and_(
                    cls.start_time.is_(None),
                    cls.state_type.not_in(schemas.states.TERMINAL_STATES),
                    cls.expected_start_time < now(),
                ),
                date_diff(now(), cls.expected_start_time),
            ),
            else_=datetime.timedelta(0),
        )

SavedSearch

Bases: Base

SQLAlchemy model of a saved search.

Source code in src/prefect/server/database/orm_models.py
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
class SavedSearch(Base):
    """SQLAlchemy model of a saved search."""

    name = sa.Column(sa.String, nullable=False)
    filters = sa.Column(
        JSON,
        server_default="[]",
        default=list,
        nullable=False,
    )

    __table_args__ = (sa.UniqueConstraint("name"),)

TaskRun

Bases: Run

SQLAlchemy model of a task run.

Source code in src/prefect/server/database/orm_models.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
class TaskRun(Run):
    """SQLAlchemy model of a task run."""

    flow_run_id = sa.Column(
        UUID(),
        sa.ForeignKey("flow_run.id", ondelete="cascade"),
        nullable=True,
        index=True,
    )

    task_key = sa.Column(sa.String, nullable=False)
    dynamic_key = sa.Column(sa.String, nullable=False)
    cache_key = sa.Column(sa.String)
    cache_expiration = sa.Column(Timestamp())
    task_version = sa.Column(sa.String)
    flow_run_run_count = sa.Column(
        sa.Integer, server_default="0", default=0, nullable=False
    )
    empirical_policy = sa.Column(
        Pydantic(schemas.core.TaskRunPolicy),
        server_default="{}",
        default=schemas.core.TaskRunPolicy,
        nullable=False,
    )
    task_inputs = sa.Column(
        Pydantic(
            Dict[
                str,
                List[
                    Union[
                        schemas.core.TaskRunResult,
                        schemas.core.Parameter,
                        schemas.core.Constant,
                    ]
                ],
            ]
        ),
        server_default="{}",
        default=dict,
        nullable=False,
    )
    tags: Mapped[List[str]] = mapped_column(
        JSON, server_default="[]", default=list, nullable=False
    )

    # TODO remove this foreign key for significant delete performance gains
    state_id = sa.Column(
        UUID(),
        sa.ForeignKey(
            "task_run_state.id",
            ondelete="SET NULL",
            use_alter=True,
        ),
        index=True,
    )

    # -------------------------- relationships

    # current states are eagerly loaded unless otherwise specified
    _state = sa.orm.relationship(
        "TaskRunState",
        lazy="selectin",
        foreign_keys=[state_id],
        primaryjoin="TaskRunState.id==TaskRun.state_id",
    )

    @hybrid_property
    def state(self):
        return self._state

    @state.setter
    def state(self, value):
        # because this is a slightly non-standard SQLAlchemy relationship, we
        # prefer an explicit setter method to a setter property, because
        # user expectations about SQLAlchemy attribute assignment might not be
        # met, namely that an unrelated (from SQLAlchemy's perspective) field of
        # the provided state is also modified. However, property assignment
        # still works because the ORM model's __init__ depends on it.
        return self.set_state(value)

    def set_state(self, state):
        """
        If a state is assigned to this run, populate its run id.

        This would normally be handled by the back-populated SQLAlchemy
        relationship, but because this is a one-to-one pointer to a
        one-to-many relationship, SQLAlchemy can't figure it out.
        """
        if state is not None:
            state.task_run_id = self.id
        self._state = state

    flow_run = sa.orm.relationship(
        "FlowRun",
        back_populates="task_runs",
        lazy="raise",
        foreign_keys=[flow_run_id],
    )

    subflow_run = sa.orm.relationship(
        "FlowRun",
        back_populates="parent_task_run",
        lazy="raise",
        # foreign_keys=["FlowRun.parent_task_run_id"],
        primaryjoin="FlowRun.parent_task_run_id==TaskRun.id",
        uselist=False,
    )

    __table_args__ = (
        sa.Index(
            "uq_task_run__flow_run_id_task_key_dynamic_key",
            "flow_run_id",
            "task_key",
            "dynamic_key",
            unique=True,
        ),
        sa.Index(
            "ix_task_run__expected_start_time_desc",
            sa.desc("expected_start_time"),
        ),
        sa.Index(
            "ix_task_run__next_scheduled_start_time_asc",
            sa.asc("next_scheduled_start_time"),
        ),
        sa.Index(
            "ix_task_run__end_time_desc",
            sa.desc("end_time"),
        ),
        sa.Index(
            "ix_task_run__start_time",
            "start_time",
        ),
        sa.Index(
            "ix_task_run__state_type",
            "state_type",
        ),
        sa.Index(
            "ix_task_run__state_name",
            "state_name",
        ),
        sa.Index(
            "ix_task_run__state_timestamp",
            "state_timestamp",
        ),
    )

set_state(state)

If a state is assigned to this run, populate its run id.

This would normally be handled by the back-populated SQLAlchemy relationship, but because this is a one-to-one pointer to a one-to-many relationship, SQLAlchemy can't figure it out.

Source code in src/prefect/server/database/orm_models.py
750
751
752
753
754
755
756
757
758
759
760
def set_state(self, state):
    """
    If a state is assigned to this run, populate its run id.

    This would normally be handled by the back-populated SQLAlchemy
    relationship, but because this is a one-to-one pointer to a
    one-to-many relationship, SQLAlchemy can't figure it out.
    """
    if state is not None:
        state.task_run_id = self.id
    self._state = state

TaskRunState

Bases: Base

SQLAlchemy model of a task run state.

Source code in src/prefect/server/database/orm_models.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
class TaskRunState(Base):
    """SQLAlchemy model of a task run state."""

    # this column isn't explicitly indexed because it is included in
    # the unique compound index on (task_run_id, timestamp)
    task_run_id = sa.Column(
        UUID(), sa.ForeignKey("task_run.id", ondelete="cascade"), nullable=False
    )

    type = sa.Column(
        sa.Enum(schemas.states.StateType, name="state_type"), nullable=False, index=True
    )
    timestamp = sa.Column(
        Timestamp(),
        nullable=False,
        server_default=now(),
        default=lambda: pendulum.now("UTC"),
    )
    name = sa.Column(sa.String, nullable=False, index=True)
    message = sa.Column(sa.String)
    state_details = sa.Column(
        Pydantic(schemas.states.StateDetails),
        server_default="{}",
        default=schemas.states.StateDetails,
        nullable=False,
    )
    _data = sa.Column(sa.JSON, nullable=True, name="data")

    result_artifact_id = sa.Column(
        UUID(),
        sa.ForeignKey(
            "artifact.id",
            ondelete="SET NULL",
            use_alter=True,
        ),
        index=True,
    )

    _result_artifact = sa.orm.relationship(
        "Artifact",
        lazy="selectin",
        foreign_keys=[result_artifact_id],
        primaryjoin="Artifact.id==TaskRunState.result_artifact_id",
    )

    @hybrid_property
    def data(self):
        if self._data:
            # ensures backwards compatibility for results stored on state objects
            return self._data
        if not self.result_artifact_id:
            # do not try to load the relationship if there's no artifact id
            return None
        return self._result_artifact.data

    task_run = sa.orm.relationship(
        "TaskRun",
        lazy="raise",
        foreign_keys=[task_run_id],
    )

    def as_state(self) -> schemas.states.State:
        return schemas.states.State.model_validate(self, from_attributes=True)

    __table_args__ = (
        sa.Index(
            "uq_task_run_state__task_run_id_timestamp_desc",
            "task_run_id",
            sa.desc("timestamp"),
            unique=True,
        ),
    )

TaskRunStateCache

Bases: Base

SQLAlchemy model of a task run state cache.

Source code in src/prefect/server/database/orm_models.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
class TaskRunStateCache(Base):
    """
    SQLAlchemy model of a task run state cache.
    """

    cache_key = sa.Column(sa.String, nullable=False)
    cache_expiration = sa.Column(
        Timestamp(),
        nullable=True,
    )
    task_run_state_id = sa.Column(UUID(), nullable=False)

    __table_args__ = (
        sa.Index(
            "ix_task_run_state_cache__cache_key_created_desc",
            "cache_key",
            sa.desc("created"),
        ),
    )

WorkPool

Bases: Base

SQLAlchemy model of an worker

Source code in src/prefect/server/database/orm_models.py
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
class WorkPool(Base):
    """SQLAlchemy model of an worker"""

    name = sa.Column(sa.String, nullable=False)
    description = sa.Column(sa.String)
    type = sa.Column(sa.String)
    base_job_template = sa.Column(JSON, nullable=False, server_default="{}", default={})
    is_paused = sa.Column(sa.Boolean, nullable=False, server_default="0", default=False)
    default_queue_id = sa.Column(UUID, nullable=True)
    concurrency_limit = sa.Column(
        sa.Integer,
        nullable=True,
    )

    status = sa.Column(
        sa.Enum(WorkPoolStatus, name="work_pool_status"),
        nullable=False,
        default=WorkPoolStatus.NOT_READY,
        server_default=WorkPoolStatus.NOT_READY.value,
    )
    last_transitioned_status_at: Mapped[Union[pendulum.DateTime, None]] = mapped_column(
        Timestamp(), nullable=True
    )
    last_status_event_id: Mapped[uuid.UUID] = mapped_column(UUID, nullable=True)

    __table_args__ = (sa.UniqueConstraint("name"),)

WorkQueue

Bases: Base

SQLAlchemy model of a work queue

Source code in src/prefect/server/database/orm_models.py
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
class WorkQueue(Base):
    """SQLAlchemy model of a work queue"""

    name = sa.Column(sa.String, nullable=False)

    filter = sa.Column(
        Pydantic(schemas.core.QueueFilter),
        server_default=None,
        default=None,
        nullable=True,
    )
    description = sa.Column(sa.String, nullable=False, default="", server_default="")
    is_paused = sa.Column(sa.Boolean, nullable=False, server_default="0", default=False)
    concurrency_limit = sa.Column(
        sa.Integer,
        nullable=True,
    )
    priority = sa.Column(sa.Integer, index=True, nullable=False)

    last_polled = sa.Column(Timestamp(), nullable=True)
    status = sa.Column(
        sa.Enum(WorkQueueStatus, name="work_queue_status"),
        nullable=False,
        default=WorkQueueStatus.NOT_READY,
        server_default=WorkQueueStatus.NOT_READY.value,
    )

    __table_args__ = (sa.UniqueConstraint("work_pool_id", "name"),)

    work_pool_id: Mapped[uuid.UUID] = mapped_column(
        UUID,
        sa.ForeignKey("work_pool.id", ondelete="cascade"),
        nullable=False,
        index=True,
    )

    work_pool = sa.orm.relationship(
        "WorkPool",
        lazy="selectin",
        foreign_keys=[work_pool_id],
    )

Worker

Bases: Base

SQLAlchemy model of an worker

Source code in src/prefect/server/database/orm_models.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
class Worker(Base):
    """SQLAlchemy model of an worker"""

    @declared_attr
    def work_pool_id(cls):
        return sa.Column(
            UUID,
            sa.ForeignKey("work_pool.id", ondelete="cascade"),
            nullable=False,
            index=True,
        )

    name = sa.Column(sa.String, nullable=False)
    last_heartbeat_time = sa.Column(
        Timestamp(),
        nullable=False,
        server_default=now(),
        default=lambda: pendulum.now("UTC"),
        index=True,
    )
    heartbeat_interval_seconds = sa.Column(sa.Integer, nullable=True)

    status = sa.Column(
        sa.Enum(WorkerStatus, name="worker_status"),
        nullable=False,
        default=WorkerStatus.OFFLINE,
        server_default=WorkerStatus.OFFLINE.value,
    )

    __table_args__ = (sa.UniqueConstraint("work_pool_id", "name"),)