Files
member-console/internal/organization/queries/workspaces.sql
T
cgalo5758 dd3962990b Adopt entity keys and add invoice numbers
Replace the entity slugs on organizations, workspaces, resource pools,
and
plan ladders with nullable `key` columns and add keys to products,
prices,
and entitlement sets. Rename `providers.slug` to `provider` and add
partial
unique indexes for system and org role names.

Assign invoice numbers per billing account from a gapless transactional
counter; Stripe's number moves to the invoice mapping as an external
reference.

Seeds, fixtures, and the operator lookup address rows by key, and the
returning-login resync no longer blanks a display name when the IdP
sends
no `name` claim.
2026-08-29 20:12:04 -05:00

52 lines
2.0 KiB
SQL

-- name: CreateWorkspace :one
-- The name is what people see and the only thing the create form asks for;
-- uq_workspaces_org_id_name_ci keeps it unambiguous within the organization
-- among live workspaces. `key` is the optional declarative address
-- (entity-keys §3), unique within the organization rather than globally
-- because a workspace is a child; UI-created workspaces leave it NULL, and a
-- singleton workspace is addressed through its organization.
INSERT INTO core.workspaces (org_id, name, key)
VALUES ($1, $2, sqlc.narg(key))
RETURNING *;
-- name: GetWorkspaceByOrgAndKey :one
-- Child key resolver (entity-keys §5): the declarative address of a
-- workspace is its organization's key plus its own, never a name.
-- uq_workspaces_org_id_key guarantees at most one row matches.
SELECT * FROM core.workspaces
WHERE org_id = $1 AND key = $2;
-- name: GetWorkspacesByOrgID :many
SELECT * FROM core.workspaces
WHERE org_id = $1
ORDER BY name;
-- name: GetWorkspaceByID :one
SELECT * FROM core.workspaces
WHERE workspace_id = $1;
-- name: CountWorkspacesByOrgID :one
SELECT COUNT(*) FROM core.workspaces
WHERE org_id = $1;
-- name: EnsureSystemWorkspace :exec
-- Idempotently insert the System tenant's workspace, keyed on its name
-- within the organization (entity-keys). The conflict target
-- repeats the predicate of the partial index uq_workspaces_org_id_name_ci
-- so Postgres can infer it. Only called when the system org has no
-- workspace yet.
INSERT INTO core.workspaces (org_id, name)
VALUES ($1, $2)
ON CONFLICT (org_id, lower(name)) WHERE status <> 'deleted' DO NOTHING;
-- name: GetSystemOrgWorkspace :one
-- Natural-key resolver: the workspace of the singleton organization whose
-- org_type is 'system'. Returns the oldest workspace so a pre-existing
-- workspace (e.g. an ad-hoc seed using a different name) is adopted rather
-- than duplicated.
SELECT w.* FROM core.workspaces w
JOIN core.organizations o ON o.org_id = w.org_id
WHERE o.org_type = 'system'
ORDER BY w.created_at
LIMIT 1;