notatest/server/sql/queries/note_versions.sql
ae 62b1a58e56
feat!: trimming & logic/schema improvements
- build: somewhat polished dockerization setup
- build: io/fs migrations with `golang-migrate`
- feat: automatic init. admin account creation (.env creds)
- feat(routers): combined user & token routers into single auth router
- feat(routers): improved route layouts (`Routes`)
- feat(middlewares): removed redundant `userCtx` middleware
- fix(schema): note <-> note_versions relation (versioning)
- feat(queries): removed redundant rollback functionality
- feat(queries): combined duplicate version check & insertion/creation
- tests: decreased redundancy by removing 'unnecessary' unit tests
- refactor: hid internal packages behind `server/internal`
- docs: notes & auth handler comments
2025-04-09 01:58:38 +03:00

59 lines
1.3 KiB
SQL

-- name: CreateNoteVersion :exec
WITH potential_duplicate AS (
SELECT version_number
FROM note_versions
WHERE
note_id = $1
AND content_hash = $2
ORDER BY version_number DESC
LIMIT 1
),
note_update AS (
UPDATE notes
SET
current_version = COALESCE(
(SELECT version_number FROM potential_duplicate),
latest_version + 1 -- increment only if we don't jump into a historical version
),
latest_version = CASE
WHEN (SELECT version_number FROM potential_duplicate) IS NULL
THEN latest_version + 1
ELSE latest_version
END,
updated_at = NOW()
WHERE id = $1
RETURNING current_version, latest_version
)
INSERT INTO note_versions (
note_id, title, content, version_number, content_hash
)
SELECT
$1, -- note_id
$3, -- title
$4, -- content
current_version,
$2 -- content_hash
FROM note_update
WHERE NOT EXISTS (SELECT 1 FROM potential_duplicate);
-- name: GetVersionHistory :many
SELECT
id AS version_id,
title,
version_number,
created_at
FROM note_versions
WHERE note_id = $1
ORDER BY version_number DESC
LIMIT $2 OFFSET $3;
-- name: GetVersion :one
SELECT
id AS version_id,
title,
content,
version_number,
created_at
FROM note_versions
WHERE note_id = $1 AND id = $2;