Last active
September 20, 2023 04:41
-
-
Save mazz/5e9e62a1dd6a7d91199189cf77936b35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Multimedia.ProgressTrack do | |
use MyApp.Schema | |
import Ecto.Changeset | |
import Ecto.Query | |
import Ecto.Changeset | |
alias MyApp.Repo | |
schema "progress_track" do | |
# field(:video_id, :integer) | |
field(:media_item_id, :binary_id) | |
field(:seconds_watched, :integer, default: 0) | |
field(:fully_watched, :boolean, default: false) | |
field(:last_track_timestamp, :integer) | |
field(:user_id, :binary_id) | |
timestamps() | |
end | |
def insert_conflict_strategy(%{"fully_watched" => fully_watched}) do | |
dbg(fully_watched) | |
from(v in MyApp.Multimedia.ProgressTrack, | |
update: [ | |
set: [ | |
seconds_watched: | |
fragment( | |
"CASE WHEN last_track_timestamp < v.last_track_timestamp THEN v.seconds_watched ELSE seconds_watched END" | |
), | |
last_track_timestamp: | |
fragment( | |
"CASE WHEN last_track_timestamp < v.last_track_timestamp THEN v.last_track_timestamp ELSE last_track_timestamp" | |
), | |
updated_at: ^ecto_time(), | |
fully_watched: ^fully_watched | |
] | |
] | |
) | |
end | |
def insert_conflict_strategy(progress_track) do | |
dbg(progress_track) | |
from(v in MyApp.Multimedia.ProgressTrack, | |
update: [ | |
set: [ | |
seconds_watched: | |
fragment( | |
"CASE WHEN last_track_timestamp < v.last_track_timestamp THEN v.seconds_watched ELSE seconds_watched END" | |
), | |
last_track_timestamp: | |
fragment( | |
"CASE WHEN last_track_timestamp < v.last_track_timestamp THEN v.last_track_timestamp ELSE last_track_timestamp" | |
), | |
updated_at: ^ecto_time() | |
] | |
] | |
) | |
end | |
defp ecto_time do | |
timestamp = {_, _, usec} = :os.timestamp() | |
NaiveDateTime.from_erl!(:calendar.now_to_datetime(timestamp), usec) | |
end | |
@doc false | |
def changeset(progress_track, attrs) do | |
progress_track | |
|> cast(attrs, [ | |
:media_item_id, | |
:seconds_watched, | |
:fully_watched, | |
:last_track_timestamp, | |
:user_id | |
]) | |
|> unique_constraint(:media_item_id, name: :progress_track_user_id_media_item_id_index) | |
|> validate_required([ | |
:media_item_id, | |
:seconds_watched, | |
:last_track_timestamp, | |
:user_id | |
]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment