golang-template/migrations/00001_init.sql
Leo 43219268e9 feat: Add Sliding expiration for user_sessions
The user_session is valid for 24 hours, but the session will be bumped if it has been over an hour since the last update. An hour was set as a deadline, so that we would not update the user_session rows too often.
2026-08-17 23:47:11 +03:00

49 lines
1.5 KiB
PL/PgSQL

-- +goose Up
CREATE TABLE IF NOT EXISTS user_auth (
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- created_at is Unix seconds, not a timestamp: internal/auth/session.go writes
-- now.Unix() and scans the column straight into an int64.
CREATE TABLE IF NOT EXISTS user_session (
id TEXT PRIMARY KEY,
secret_hash BYTEA NOT NULL,
user_id TEXT NOT NULL REFERENCES user_auth (id) ON DELETE CASCADE,
last_verified_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_user_session_user_id ON user_session (user_id);
-- +goose StatementBegin
CREATE FUNCTION set_updated_at() RETURNS trigger AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- +goose StatementEnd
CREATE TRIGGER user_auth_set_updated_at
BEFORE UPDATE ON user_auth
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
CREATE TRIGGER user_session_set_updated_at
BEFORE UPDATE ON user_session
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
-- +goose Down
DROP TRIGGER IF EXISTS user_auth_set_updated_at ON user_auth;
DROP FUNCTION IF EXISTS set_updated_at();
DROP TABLE IF EXISTS user_session;
DROP TABLE IF EXISTS user_auth;