-- name: CreateNumericEntitlementUsage :one INSERT INTO core.numeric_entitlement_usage (entitlement_id, pool_id, resource_key) VALUES ($1, $2, $3) RETURNING *; -- name: GetUsageByPoolAndResource :one SELECT * FROM core.numeric_entitlement_usage WHERE pool_id = $1 AND resource_key = $2; -- name: AtomicIncrementUsage :execresult UPDATE core.numeric_entitlement_usage neu SET current_usage = neu.current_usage + 1 WHERE neu.pool_id IN ( SELECT pa.pool_id FROM core.pool_assignments pa WHERE pa.workspace_id = $1 AND pa.is_primary = TRUE AND pa.status = 'active' ) AND neu.resource_key = $2 AND neu.current_usage < ( SELECT ne.resource_limit FROM core.numeric_entitlements ne WHERE ne.entitlement_id = neu.entitlement_id ); -- name: AtomicDecrementUsage :execresult UPDATE core.numeric_entitlement_usage neu SET current_usage = GREATEST(neu.current_usage - 1, 0) WHERE neu.pool_id IN ( SELECT pa.pool_id FROM core.pool_assignments pa WHERE pa.workspace_id = $1 AND pa.is_primary = TRUE AND pa.status = 'active' ) AND neu.resource_key = $2; -- name: ListNumericEntitlementUsageByPoolID :many SELECT * FROM core.numeric_entitlement_usage WHERE pool_id = $1 ORDER BY resource_key ASC; -- name: ListPoolUsageWithLimitsByPoolID :many -- Per-resource usage counters for a pool joined to their materialized -- limit (used vs limit per resource key), for the org-detail pools panel -- (ux-honest-surfaces: "pool status and usage are visible on the -- organization view"). A counter row exists only under a materialized -- numeric entitlement (invariant 9, resource-pools card), so the JOIN -- never orphans. SELECT neu.resource_key, neu.current_usage, ne.resource_limit FROM core.numeric_entitlement_usage neu JOIN core.numeric_entitlements ne ON ne.entitlement_id = neu.entitlement_id WHERE neu.pool_id = $1 ORDER BY neu.resource_key ASC; -- name: RaiseNumericUsageTo :execresult -- Raise-only reconcile against the count of rows the owning integration holds. -- Never lowers: a create workflow holds a reservation between its gated -- increment and its row insert, and lowering here would erase it. Lowering on -- a real deletion stays with the decrement and drift paths. -- Creates no usage row; a missing counter remains the materializer's to create. UPDATE core.numeric_entitlement_usage SET current_usage = GREATEST(current_usage, sqlc.arg(observed)) WHERE pool_id = sqlc.arg(pool_id) AND resource_key = sqlc.arg(resource_key); -- name: SetNumericUsage :execresult -- Exact set, for boot reconciliation only: at boot no create workflow holds an -- unmaterialized reservation, so the owned rows are the whole truth and an -- overstated counter (which refuses creates) can be brought down. -- Creates no usage row. UPDATE core.numeric_entitlement_usage SET current_usage = sqlc.arg(observed) WHERE pool_id = sqlc.arg(pool_id) AND resource_key = sqlc.arg(resource_key);