Skip to content

Commit

Permalink
Continue work to replace Variable with ClimaticIndicator (wip)
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardogsilva committed Nov 14, 2024
1 parent 396de37 commit 7e7a25a
Show file tree
Hide file tree
Showing 9 changed files with 105 additions and 411 deletions.
182 changes: 60 additions & 122 deletions arpav_ppcv/schemas/observations.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,31 +261,20 @@ class MonthlyMeasurement(MonthlyMeasurementBase, table=True):
onupdate="CASCADE",
ondelete="CASCADE", # i.e. delete a monthly measurement if its related station is deleted
),
# sqlalchemy.ForeignKeyConstraint(
# [
# "variable_id",
# ],
# [
# "variable.id",
# ],
# onupdate="CASCADE",
# ondelete="CASCADE", # i.e. delete a monthly measurement if its related station is deleted
# ),
# sqlalchemy.ForeignKeyConstraint(
# [
# "climatic_indicator_id",
# ],
# [
# "climaticindicator.id",
# ],
# onupdate="CASCADE",
# ondelete="CASCADE", # i.e. delete a monthly measurement if its related station is deleted
# ),
sqlalchemy.ForeignKeyConstraint(
[
"climatic_indicator_id",
],
[
"climaticindicator.id",
],
onupdate="CASCADE",
ondelete="CASCADE", # i.e. delete a monthly measurement if its related climatic_indicator is deleted
),
)
id: pydantic.UUID4 = sqlmodel.Field(default_factory=uuid.uuid4, primary_key=True)
station_id: pydantic.UUID4
# variable_id: pydantic.UUID4
# climatic_indicator_id: int
climatic_indicator_id: int

station: Station = sqlmodel.Relationship(
back_populates="monthly_measurements",
Expand All @@ -296,24 +285,15 @@ class MonthlyMeasurement(MonthlyMeasurementBase, table=True):
"lazy": "joined",
},
)
# variable: Variable = sqlmodel.Relationship(
# back_populates="monthly_measurements",
# sa_relationship_kwargs={
# # retrieve the related resource immediately, by means of a SQL JOIN - this
# # is instead of the default lazy behavior of only retrieving related
# # records when they are accessed by the ORM
# "lazy": "joined",
# },
# )
# climatic_indicator: ClimaticIndicator = sqlmodel.Relationship(
# back_populates="monthly_measurements",
# sa_relationship_kwargs={
# # retrieve the related resource immediately, by means of a SQL JOIN - this
# # is instead of the default lazy behavior of only retrieving related
# # records when they are accessed by the ORM
# "lazy": "joined",
# },
# )
climatic_indicator: ClimaticIndicator = sqlmodel.Relationship(
back_populates="monthly_measurements",
sa_relationship_kwargs={
# retrieve the related resource immediately, by means of a SQL JOIN - this
# is instead of the default lazy behavior of only retrieving related
# records when they are accessed by the ORM
"lazy": "joined",
},
)


class MonthlyMeasurementCreate(sqlmodel.SQLModel):
Expand Down Expand Up @@ -341,31 +321,20 @@ class SeasonalMeasurement(sqlmodel.SQLModel, table=True):
onupdate="CASCADE",
ondelete="CASCADE", # i.e. delete a measurement if its related station is deleted
),
# sqlalchemy.ForeignKeyConstraint(
# [
# "variable_id",
# ],
# [
# "variable.id",
# ],
# onupdate="CASCADE",
# ondelete="CASCADE", # i.e. delete a measurement if its related station is deleted
# ),
# sqlalchemy.ForeignKeyConstraint(
# [
# "climatic_indicator_id",
# ],
# [
# "climaticindicator.id",
# ],
# onupdate="CASCADE",
# ondelete="CASCADE", # i.e. delete a measurement if its related station is deleted
# ),
sqlalchemy.ForeignKeyConstraint(
[
"climatic_indicator_id",
],
[
"climaticindicator.id",
],
onupdate="CASCADE",
ondelete="CASCADE", # i.e. delete a measurement if its related climatic_indicator is deleted
),
)
id: pydantic.UUID4 = sqlmodel.Field(default_factory=uuid.uuid4, primary_key=True)
station_id: pydantic.UUID4
# variable_id: pydantic.UUID4
# climatic_indicator_id: int
climatic_indicator_id: int
value: float
year: int
season: base.Season
Expand All @@ -379,29 +348,19 @@ class SeasonalMeasurement(sqlmodel.SQLModel, table=True):
"lazy": "joined",
},
)
# variable: Variable = sqlmodel.Relationship(
# back_populates="seasonal_measurements",
# sa_relationship_kwargs={
# # retrieve the related resource immediately, by means of a SQL JOIN - this
# # is instead of the default lazy behavior of only retrieving related
# # records when they are accessed by the ORM
# "lazy": "joined",
# },
# )
# climatic_indicator: ClimaticIndicator = sqlmodel.Relationship(
# back_populates="seasonal_measurements",
# sa_relationship_kwargs={
# # retrieve the related resource immediately, by means of a SQL JOIN - this
# # is instead of the default lazy behavior of only retrieving related
# # records when they are accessed by the ORM
# "lazy": "joined",
# },
# )
climatic_indicator: ClimaticIndicator = sqlmodel.Relationship(
back_populates="seasonal_measurements",
sa_relationship_kwargs={
# retrieve the related resource immediately, by means of a SQL JOIN - this
# is instead of the default lazy behavior of only retrieving related
# records when they are accessed by the ORM
"lazy": "joined",
},
)


class SeasonalMeasurementCreate(sqlmodel.SQLModel):
station_id: pydantic.UUID4
# variable_id: pydantic.UUID4
climatic_indicator_id: pydantic.UUID4
value: float
year: int
Expand All @@ -426,31 +385,20 @@ class YearlyMeasurement(sqlmodel.SQLModel, table=True):
onupdate="CASCADE",
ondelete="CASCADE", # i.e. delete a measurement if its related station is deleted
),
# sqlalchemy.ForeignKeyConstraint(
# [
# "variable_id",
# ],
# [
# "variable.id",
# ],
# onupdate="CASCADE",
# ondelete="CASCADE", # i.e. delete a measurement if its related station is deleted
# ),
# sqlalchemy.ForeignKeyConstraint(
# [
# "climatic_indicator_id",
# ],
# [
# "climaticindicator.id",
# ],
# onupdate="CASCADE",
# ondelete="CASCADE", # i.e. delete a measurement if its related station is deleted
# ),
sqlalchemy.ForeignKeyConstraint(
[
"climatic_indicator_id",
],
[
"climaticindicator.id",
],
onupdate="CASCADE",
ondelete="CASCADE", # i.e. delete a measurement if its climatic_indicator station is deleted
),
)
id: pydantic.UUID4 = sqlmodel.Field(default_factory=uuid.uuid4, primary_key=True)
station_id: pydantic.UUID4
# variable_id: pydantic.UUID4
# climatic_indicator_id: int
climatic_indicator_id: int
value: float
year: int

Expand All @@ -463,29 +411,19 @@ class YearlyMeasurement(sqlmodel.SQLModel, table=True):
"lazy": "joined",
},
)
# variable: Variable = sqlmodel.Relationship(
# back_populates="yearly_measurements",
# sa_relationship_kwargs={
# # retrieve the related resource immediately, by means of a SQL JOIN - this
# # is instead of the default lazy behavior of only retrieving related
# # records when they are accessed by the ORM
# "lazy": "joined",
# },
# )
# climatic_indicator: ClimaticIndicator = sqlmodel.Relationship(
# back_populates="yearly_measurements",
# sa_relationship_kwargs={
# # retrieve the related resource immediately, by means of a SQL JOIN - this
# # is instead of the default lazy behavior of only retrieving related
# # records when they are accessed by the ORM
# "lazy": "joined",
# },
# )
climatic_indicator: ClimaticIndicator = sqlmodel.Relationship(
back_populates="yearly_measurements",
sa_relationship_kwargs={
# retrieve the related resource immediately, by means of a SQL JOIN - this
# is instead of the default lazy behavior of only retrieving related
# records when they are accessed by the ORM
"lazy": "joined",
},
)


class YearlyMeasurementCreate(sqlmodel.SQLModel):
station_id: pydantic.UUID4
# variable_id: pydantic.UUID4
climatic_indicator_id: int
value: float
year: int
Expand Down
1 change: 0 additions & 1 deletion arpav_ppcv/webapp/admin/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ def create_admin(settings: config.ArpavPpcvSettings) -> ArpavPpcvAdmin:
admin.add_view(
coverage_views.CoverageConfigurationView(coverages.CoverageConfiguration)
)
admin.add_view(observations_views.VariableView(observations.Variable))
admin.add_view(observations_views.StationView(observations.Station))
admin.add_view(
DropDown(
Expand Down
11 changes: 0 additions & 11 deletions arpav_ppcv/webapp/admin/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,6 @@ class CoverageConfigurationReadListItem(sqlmodel.SQLModel):
name: str


class VariableRead(sqlmodel.SQLModel):
id: uuid.UUID
name: str
display_name_english: Optional[str]
display_name_italian: Optional[str]
description_english: Optional[str]
description_italian: Optional[str]
unit_english: Optional[str]
unit_italian: Optional[str]


class StationRead(sqlmodel.SQLModel):
id: uuid.UUID
name: str
Expand Down
108 changes: 0 additions & 108 deletions arpav_ppcv/webapp/admin/views/observations.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,114 +198,6 @@ async def find_all(
return [self._serialize_instance(item) for item in db_measurements]


class VariableView(ModelView):
identity = "variables"
name = "Variable"
label = "Variables"
icon = "fa fa-blog"
pk_attr = "id"

exclude_fields_from_list = (
"id",
"display_name_english",
"display_name_italian",
"description_english",
"description_italian",
"unit_english",
"unit_italian",
)
exclude_fields_from_detail = ("id",)

fields = (
fields.UuidField("id"),
starlette_admin.StringField("name", required=True),
starlette_admin.StringField("display_name_english", required=True),
starlette_admin.StringField("display_name_italian", required=True),
starlette_admin.StringField("description_english"),
starlette_admin.StringField("description_italian"),
starlette_admin.StringField("unit_english"),
starlette_admin.StringField("unit_italian"),
)

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.icon = "fa-solid fa-cloud-sun-rain"

@staticmethod
def _serialize_instance(
instance: observations.Variable,
) -> read_schemas.VariableRead:
return read_schemas.VariableRead(**instance.model_dump())

async def get_pk_value(self, request: Request, obj: Any) -> str:
# note: we need to cast the value, which is a uuid.UUID, to a string
# because starlette_admin just assumes that the value of a model's
# pk attribute is always JSON serializable so it doesn't bother with
# calling the respective field's `serialize_value()` method
result = await super().get_pk_value(request, obj)
return str(result)

async def create(
self, request: Request, data: dict[str, Any]
) -> Optional[read_schemas.VariableRead]:
try:
data = await self._arrange_data(request, data)
await self.validate(request, data)
var_create = observations.VariableCreate(**data)
db_variable = await anyio.to_thread.run_sync(
db.create_variable,
request.state.session,
var_create,
)
return self._serialize_instance(db_variable)
except Exception as e:
return self.handle_exception(e)

async def edit(
self, request: Request, pk: Any, data: dict[str, Any]
) -> Optional[read_schemas.VariableRead]:
try:
data = await self._arrange_data(request, data, True)
await self.validate(request, data)
var_update = observations.VariableUpdate(**data)
db_var = await anyio.to_thread.run_sync(
db.get_variable, request.state.session, pk
)
db_var = await anyio.to_thread.run_sync(
db.update_variable, request.state.session, db_var, var_update
)
return self._serialize_instance(db_var)
except Exception as e:
logger.exception("something went wrong")
self.handle_exception(e)

async def find_by_pk(self, request: Request, pk: Any) -> read_schemas.VariableRead:
db_var = await anyio.to_thread.run_sync(
db.get_variable, request.state.session, pk
)
return self._serialize_instance(db_var)

async def find_all(
self,
request: Request,
skip: int = 0,
limit: int = 100,
where: Union[dict[str, Any], str, None] = None,
order_by: Optional[list[str]] = None,
) -> Sequence[read_schemas.VariableRead]:
list_variables = functools.partial(
db.list_variables,
limit=limit,
offset=skip,
name_filter=str(where) if where not in (None, "") else None,
include_total=False,
)
db_vars, _ = await anyio.to_thread.run_sync(
list_variables, request.state.session
)
return [self._serialize_instance(db_var) for db_var in db_vars]


class StationView(ModelView):
identity = "stations"
name = "Station"
Expand Down
Loading

0 comments on commit 7e7a25a

Please sign in to comment.