Skip to content

Commit

Permalink
Add 'name' and 'group' to DatasetModel (apache#42407)
Browse files Browse the repository at this point in the history
The unique index is also modified to include 'name', so now an asset is
considered unique if *either* the name or URI is different. This makes
no difference for the moment---the name is simply populated from URI.
We'll add a public interface to set the name in a later PR.

This PR strictly only touches the model so it does not conflict with
too many things, and can be merged quickly.

The unique index on DatasetAliasModel is also renamed since we were
using a wrong naming convention on both models. Since the index
namespace is shared in the entire database, the index name should
include additional components. The idx_name_unique is still usable, but
we should a better citizen and name this the right way(tm).
  • Loading branch information
uranusjr authored Sep 30, 2024
1 parent ede7cb2 commit b07b425
Show file tree
Hide file tree
Showing 7 changed files with 1,272 additions and 1,141 deletions.
2 changes: 1 addition & 1 deletion airflow/assets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ class Asset(os.PathLike, BaseAsset):

uri: str = attr.field(
converter=_sanitize_uri,
validator=[attr.validators.min_len(1), attr.validators.max_len(3000)],
validator=[attr.validators.min_len(1), attr.validators.max_len(1500)],
)
extra: dict[str, Any] = attr.field(factory=dict, converter=_set_extra_default)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""
Add name and group fields to DatasetModel.
The unique index on DatasetModel is also modified to include name. Existing rows
have their name copied from URI.
While not strictly related to other changes, the index name on DatasetAliasModel
is also renamed. Index names are scoped to the entire database. Airflow generally
includes the table's name to manually scope the index, but ``idx_uri_unique``
(on DatasetModel) and ``idx_name_unique`` (on DatasetAliasModel) do not do this.
The one on DatasetModel is already renamed in this PR (to include name), so we
also rename the one on DatasetAliasModel here for consistency.
Revision ID: 0d9e73a75ee4
Revises: 16cbcb1c8c36
Create Date: 2024-08-13 09:45:32.213222
"""

from __future__ import annotations

import sqlalchemy as sa
from alembic import op
from sqlalchemy.orm import Session

# revision identifiers, used by Alembic.
revision = "0d9e73a75ee4"
down_revision = "16cbcb1c8c36"
branch_labels = None
depends_on = None
airflow_version = "3.0.0"

_STRING_COLUMN_TYPE = sa.String(length=1500).with_variant(
sa.String(length=1500, collation="latin1_general_cs"),
dialect_name="mysql",
)


def upgrade():
# Fix index name on DatasetAlias.
with op.batch_alter_table("dataset_alias", schema=None) as batch_op:
batch_op.drop_index("idx_name_unique")
batch_op.create_index("idx_dataset_alias_name_unique", ["name"], unique=True)
# Add 'name' column. Set it to nullable for now.
with op.batch_alter_table("dataset", schema=None) as batch_op:
batch_op.add_column(sa.Column("name", _STRING_COLUMN_TYPE))
batch_op.add_column(sa.Column("group", _STRING_COLUMN_TYPE, default=str, nullable=False))
# Fill name from uri column.
Session(bind=op.get_bind()).execute(sa.text("update dataset set name=uri"))
# Set the name column non-nullable.
# Now with values in there, we can create the new unique constraint and index.
# Due to MySQL restrictions, we are also reducing the length on uri.
with op.batch_alter_table("dataset", schema=None) as batch_op:
batch_op.alter_column("name", existing_type=_STRING_COLUMN_TYPE, nullable=False)
batch_op.alter_column("uri", type_=_STRING_COLUMN_TYPE, nullable=False)
batch_op.drop_index("idx_uri_unique")
batch_op.create_index("idx_dataset_name_uri_unique", ["name", "uri"], unique=True)


def downgrade():
with op.batch_alter_table("dataset", schema=None) as batch_op:
batch_op.drop_index("idx_dataset_name_uri_unique")
batch_op.create_index("idx_uri_unique", ["uri"], unique=True)
with op.batch_alter_table("dataset", schema=None) as batch_op:
batch_op.drop_column("group")
batch_op.drop_column("name")
batch_op.alter_column(
"uri",
type_=sa.String(length=3000).with_variant(
sa.String(length=3000, collation="latin1_general_cs"),
dialect_name="mysql",
),
nullable=False,
)
with op.batch_alter_table("dataset_alias", schema=None) as batch_op:
batch_op.drop_index("idx_dataset_alias_name_unique")
batch_op.create_index("idx_name_unique", ["name"], unique=True)
43 changes: 34 additions & 9 deletions airflow/models/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ class AssetAliasModel(Base):

__tablename__ = "dataset_alias"
__table_args__ = (
Index("idx_name_unique", name, unique=True),
Index("idx_dataset_alias_name_unique", name, unique=True),
{"sqlite_autoincrement": True}, # ensures PK values not reused
)

Expand Down Expand Up @@ -151,10 +151,22 @@ class AssetModel(Base):
"""

id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(
String(length=1500).with_variant(
String(
length=1500,
# latin1 allows for more indexed length in mysql
# and this field should only be ascii chars
collation="latin1_general_cs",
),
"mysql",
),
nullable=False,
)
uri = Column(
String(length=3000).with_variant(
String(length=1500).with_variant(
String(
length=3000,
length=1500,
# latin1 allows for more indexed length in mysql
# and this field should only be ascii chars
collation="latin1_general_cs",
Expand All @@ -163,7 +175,21 @@ class AssetModel(Base):
),
nullable=False,
)
group = Column(
String(length=1500).with_variant(
String(
length=1500,
# latin1 allows for more indexed length in mysql
# and this field should only be ascii chars
collation="latin1_general_cs",
),
"mysql",
),
default=str,
nullable=False,
)
extra = Column(sqlalchemy_jsonfield.JSONField(json=json), nullable=False, default={})

created_at = Column(UtcDateTime, default=timezone.utcnow, nullable=False)
updated_at = Column(UtcDateTime, default=timezone.utcnow, onupdate=timezone.utcnow, nullable=False)
is_orphaned = Column(Boolean, default=False, nullable=False, server_default="0")
Expand All @@ -173,7 +199,7 @@ class AssetModel(Base):

__tablename__ = "dataset"
__table_args__ = (
Index("idx_uri_unique", uri, unique=True),
Index("idx_dataset_name_uri_unique", name, uri, unique=True),
{"sqlite_autoincrement": True}, # ensures PK values not reused
)

Expand All @@ -189,16 +215,15 @@ def __init__(self, uri: str, **kwargs):
parsed = urlsplit(uri)
if parsed.scheme and parsed.scheme.lower() == "airflow":
raise ValueError("Scheme `airflow` is reserved.")
super().__init__(uri=uri, **kwargs)
super().__init__(name=uri, uri=uri, **kwargs)

def __eq__(self, other):
if isinstance(other, (self.__class__, Asset)):
return self.uri == other.uri
else:
return NotImplemented
return self.name == other.name and self.uri == other.uri
return NotImplemented

def __hash__(self):
return hash(self.uri)
return hash((self.name, self.uri))

def __repr__(self):
return f"{self.__class__.__name__}(uri={self.uri!r}, extra={self.extra!r})"
Expand Down
2 changes: 1 addition & 1 deletion airflow/utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class MappedClassProtocol(Protocol):
"2.9.0": "1949afb29106",
"2.9.2": "686269002441",
"2.10.0": "22ed7efa9da2",
"3.0.0": "16cbcb1c8c36",
"3.0.0": "0d9e73a75ee4",
}


Expand Down
2 changes: 1 addition & 1 deletion docs/apache-airflow/img/airflow_erd.sha256
Original file line number Diff line number Diff line change
@@ -1 +1 @@
f4379048d3f13f35aaba824c00450c17ad4deea9af82b5498d755a12f8a85a37
c33e9a583a5b29eb748ebd50e117643e11bcb2a9b61ec017efd690621e22769b
Loading

0 comments on commit b07b425

Please sign in to comment.