Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions apps/transport/lib/db/resource_history_mv.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
defmodule DB.ResourceHistoryMV do
@moduledoc """
Materialized view of resource history with direct belongs_to dataset and latest multi_validation.
"""

use Ecto.Schema

@primary_key {:id, :id, autogenerate: false}
typed_schema "resource_history_mv" do
# All this is copied from DB.ResourceHistory schema
field(:datagouv_id, :string)
field(:payload, :map)
# the last moment we checked and the resource history was corresponding to the real online resource
field(:last_up_to_date_at, :utc_datetime_usec)

timestamps(type: :utc_datetime_usec)
belongs_to(:resource, DB.Resource)
belongs_to(:reuser_improved_data, DB.ReuserImprovedData)
has_many(:geo_data_import, DB.GeoDataImport)
has_many(:validations, DB.MultiValidation)
has_many(:metadata, DB.ResourceMetadata)

# Just adding two belongs_to fields
belongs_to(:dataset, DB.Dataset)
belongs_to(multi_validation: DB.MultiValidation)
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
defmodule :"Elixir.DB.Repo.Migrations.Create-dataset-resource-history-materialized-view" do
use Ecto.Migration

def up do
execute("""
CREATE MATERIALIZED VIEW resource_history_mv AS
SELECT
rh.*,
(rh.payload->>'dataset_id')::bigint AS dataset_id,
mv_latest.id AS latest_multivalidation_id
FROM
resource_history rh
LEFT JOIN LATERAL (
SELECT mv.id
FROM multi_validation mv
WHERE mv.resource_history_id = rh.id
ORDER BY mv.inserted_at DESC
LIMIT 1
) mv_latest ON TRUE;
""")

execute("CREATE INDEX ON resource_history_mv (dataset_id);")
execute("CREATE INDEX ON resource_history_mv (latest_multivalidation_id);")
execute("CREATE INDEX ON resource_history_mv (resource_id);")
end

def down do
execute("DROP INDEX IF EXISTS resource_history_mv_dataset_id_idx;")
execute("DROP INDEX IF EXISTS resource_history_mv_latest_multivalidation_id_idx;")
execute("DROP INDEX IF EXISTS resource_history_mv_resource_id_idx;")

execute("DROP MATERIALIZED VIEW IF EXISTS resource_history_mv;")
end
end