-- name: CreateNamespace :one
INSERT INTO
  namespace(
    name,
    lastseen,
    allowance_time,
    quota_kb,
    quota_usage_kb,
    usage_id,
    download_id,
    upload_id
  )
  values(?, ?, ?, ?, ?, ?, ?, ?)
  returning id;

-- name: CreateFileStats :one
INSERT INTO file_stats(num, size_b)
  values(?, ?)
  returning id;

-- name: AllNamespaces :many
SELECT
 ns.id,
 ns.name,
 ns.lastseen,
 ns.allowance_time,
 ns.quota_kb,
 ns.quota_usage_kb,
 u.num as u_num,
 u.size_b as u_size_b,
 d.num as d_num,
 d.size_b as d_size_b,
 ul.num as ul_num,
 ul.size_b as ul_size_b
 FROM namespace as ns
 JOIN file_stats as u
  ON ns.usage_id = u.id
 JOIN file_stats as d
  ON ns.download_id = d.id
 JOIN file_stats as ul
  ON ns.upload_id = ul.id;

-- name: GetNamespaceByName :one
SELECT
 ns.id,
 ns.name,
 ns.lastseen,
 ns.allowance_time,
 ns.quota_kb,
 ns.quota_usage_kb,
 u.num as u_num,
 u.size_b as u_size_b,
 d.num as d_num,
 d.size_b as d_size_b,
 ul.num as ul_num,
 ul.size_b as ul_size_b
 FROM namespace as ns
 JOIN file_stats as u
  ON ns.usage_id = u.id
 JOIN file_stats as d
  ON ns.download_id = d.id
 JOIN file_stats as ul
  ON ns.upload_id = ul.id
 WHERE ns.name = ?;


-- name: GetFileStat :one
SELECT * FROM file_stats where id = ?;

-- name: UpdateFileStat :exec
UPDATE file_stats SET num = ?, size_b = ? where id = ?;

-- name: UpdateNamespace :one
UPDATE namespace SET
 name = ?,
 lastseen = ?,
 allowance_time = ?,
 quota_kb = ?,
 quota_usage_kb = ?
 WHERE id = ?
 RETURNING usage_id, download_id, upload_id;

-- name: DeleteNameSpace :exec
DELETE FROM namespace where id = ?;
