-- NOTE: This file is auto generated by ./sql-generator

-- MemoryRepository.cleanup
delete from "memories"
where
  "createdAt" < $1
  and "isSaved" = $2

-- MemoryRepository.search
select
  "memories".*,
  (
    select
      coalesce(json_agg(agg), '[]')
    from
      (
        select
          "assets".*
        from
          "assets"
          inner join "memories_assets_assets" on "assets"."id" = "memories_assets_assets"."assetsId"
        where
          "memories_assets_assets"."memoriesId" = "memories"."id"
          and "assets"."deletedAt" is null
        order by
          "assets"."fileCreatedAt" asc
      ) as agg
  ) as "assets"
from
  "memories"
where
  "deletedAt" is null
  and "ownerId" = $1
order by
  "memoryAt" desc

-- MemoryRepository.search (date filter)
select
  "memories".*,
  (
    select
      coalesce(json_agg(agg), '[]')
    from
      (
        select
          "assets".*
        from
          "assets"
          inner join "memories_assets_assets" on "assets"."id" = "memories_assets_assets"."assetsId"
        where
          "memories_assets_assets"."memoriesId" = "memories"."id"
          and "assets"."deletedAt" is null
        order by
          "assets"."fileCreatedAt" asc
      ) as agg
  ) as "assets"
from
  "memories"
where
  (
    "showAt" is null
    or "showAt" <= $1
  )
  and (
    "hideAt" is null
    or "hideAt" >= $2
  )
  and "deletedAt" is null
  and "ownerId" = $3
order by
  "memoryAt" desc

-- MemoryRepository.get
select
  "memories".*,
  (
    select
      coalesce(json_agg(agg), '[]')
    from
      (
        select
          "assets".*
        from
          "assets"
          inner join "memories_assets_assets" on "assets"."id" = "memories_assets_assets"."assetsId"
        where
          "memories_assets_assets"."memoriesId" = "memories"."id"
          and "assets"."deletedAt" is null
        order by
          "assets"."fileCreatedAt" asc
      ) as agg
  ) as "assets"
from
  "memories"
where
  "id" = $1
  and "deletedAt" is null

-- MemoryRepository.update
update "memories"
set
  "ownerId" = $1,
  "isSaved" = $2
where
  "id" = $3
select
  "memories".*,
  (
    select
      coalesce(json_agg(agg), '[]')
    from
      (
        select
          "assets".*
        from
          "assets"
          inner join "memories_assets_assets" on "assets"."id" = "memories_assets_assets"."assetsId"
        where
          "memories_assets_assets"."memoriesId" = "memories"."id"
          and "assets"."deletedAt" is null
        order by
          "assets"."fileCreatedAt" asc
      ) as agg
  ) as "assets"
from
  "memories"
where
  "id" = $1
  and "deletedAt" is null

-- MemoryRepository.delete
delete from "memories"
where
  "id" = $1

-- MemoryRepository.getAssetIds
select
  "assetsId"
from
  "memories_assets_assets"
where
  "memoriesId" = $1
  and "assetsId" in ($2)

-- MemoryRepository.addAssetIds
insert into
  "memories_assets_assets" ("memoriesId", "assetsId")
values
  ($1, $2)
