Database/xyz/Functions/fn_GetAsset.sqlmodified--liquibase formatted sql
--changeset agentneo:fn_GetAsset runOnChange:true stripComments:false endDelimiter:/
--comment: Create or replace xyz."fn_GetAsset"
------------------------------------------------------------------------------------
-- Created by: AgentNeo
-- Created on: 09/07/2026
-- Description: Get a single asset by project and asset id (excludes soft-deleted).
-- Includes a scalar "SystemId" resolved from the asset's AssetType via
-- xyz."AssetTypeSystemTypeMapping" (NULL when no mapping exists). The
-- AssetType->SystemType relationship may be many, so the lookup picks a
-- single deterministic mapping (earliest created) to avoid fan-out.
------------------------------------------------------------------------------------
DROP FUNCTION IF EXISTS xyz."fn_GetAsset";
CREATE OR REPLACE FUNCTION xyz."fn_GetAsset" (
_projectId UUID,
_assetId UUID
)
RETURNS TABLE (
"AssetId" UUID,
"ProjectId" UUID,
"AssetTypeId" UUID,
"ParentAssetId" UUID,
"Name" TEXT,
"CreatedBy" TEXT,
"InsertedOn" TIMESTAMP WITH TIME ZONE,
"LastModifiedOn" TIMESTAMP WITH TIME ZONE,
"LastModifiedBy" TEXT,
"IsDeleted" BOOLEAN,
"DeletedOn" TIMESTAMP WITH TIME ZONE,
"DeletedBy" TEXT,
"SystemId" UUID
)
AS $$
DECLARE
-- project id map
_projectShardId INT;
BEGIN
-- get shard id from uuid
SELECT xyz."fn_GetProjectShardId"(_projectId) INTO _projectShardId;
RETURN QUERY
SELECT
a."AssetId",
_projectId,
a."AssetTypeId",
a."ParentAssetId",
a."Name",
a."CreatedBy",
a."InsertedOn",
a."LastModifiedOn",
a."LastModifiedBy",
a."IsDeleted",
a."DeletedOn",
a."DeletedBy",
sys."SystemTypeId" AS "SystemId"
FROM xyz."Asset" a
LEFT JOIN LATERAL (
SELECT m."SystemTypeId"
FROM xyz."AssetTypeSystemTypeMapping" m
WHERE m."ProjectShardId" = a."ProjectShardId"
AND m."AssetTypeId" = a."AssetTypeId"
ORDER BY m."Id" ASC
LIMIT 1
) sys ON TRUE
WHERE a."ProjectShardId" = _projectShardId
AND a."AssetId" = _assetId
AND a."IsDeleted" = FALSE;
END;
$$
LANGUAGE plpgsql;
/