summaryrefslogtreecommitdiff
path: root/lib/chessh/schema/player_session.ex
blob: 84f15ee134ad9b1f6b73e264d48e08de9bd3d1a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
defmodule Chessh.PlayerSession do
  alias Chessh.Repo
  use Ecto.Schema
  import Ecto.{Query, Changeset}

  schema "player_sessions" do
    field(:login, :utc_datetime)

    belongs_to(:node, Chessh.Node, type: :string)
    belongs_to(:player, Chessh.Player)
  end

  def changeset(player_session, attrs) do
    player_session
    |> cast(attrs, [:login])
  end

  def concurrent_sessions(player) do
    Repo.aggregate(
      from(p in Chessh.PlayerSession,
        where: p.player_id == ^player.id
      ),
      :count
    )
  end

  def delete_all_on_node(node_id) do
    Repo.delete_all(
      from(p in Chessh.PlayerSession,
        where: p.node_id == ^node_id
      )
    )
  end
end