group TagDefinitionDao;

CHECK_TENANT() ::= "tenant_record_id = :tenantRecordId"
AND_CHECK_TENANT() ::= "AND <CHECK_TENANT()>"

fields(prefix) ::= <<
    <prefix>id,
    <prefix>name,
    <prefix>description,
    <prefix>created_by,
    <prefix>created_date ,
    <prefix>updated_by,
    <prefix>updated_date,
    <prefix>tenant_record_id
>>

get() ::= <<
  SELECT <fields()>
  FROM tag_definitions
  WHERE <CHECK_TENANT()>
  ;
>>

create() ::= <<
  INSERT INTO tag_definitions(<fields()>)
  VALUES(:id, :name, :description, :userName, :createdDate, :userName, :updatedDate, :tenantRecordId);
>>

load() ::= <<
  SELECT <fields()>
  FROM tag_definitions
  WHERE id = :id
  <AND_CHECK_TENANT()>
  ;
>>


deleteTagDefinition() ::= <<
  DELETE FROM tag_definitions
  WHERE id = :id
  <AND_CHECK_TENANT()>
  ;
>>

tagDefinitionUsageCount() ::= <<
  SELECT COUNT(id)
  FROM tags
  WHERE tag_definition_id = :id
  <AND_CHECK_TENANT()>
>>

getByName() ::= <<
  SELECT <fields()>
   FROM tag_definitions
  WHERE name = :name
  <AND_CHECK_TENANT()>
  ;
>>

getRecordId() ::= <<
    SELECT record_id
    FROM tag_definitions
    WHERE id = :id
    <AND_CHECK_TENANT()>
    ;
>>

getByRecordId() ::= <<
    SELECT <fields()>
    FROM tag_definitions
    WHERE record_id = :recordId <AND_CHECK_TENANT()>
    ;
>>

getHistoryRecordId() ::= <<
    SELECT MAX(history_record_id)
    FROM tag_definition_history
    WHERE record_id = :recordId <AND_CHECK_TENANT()>;
>>

getById() ::= <<
  SELECT <fields()>
  FROM tag_definitions
  WHERE id = :id
  <AND_CHECK_TENANT()>
  ;
>>

getByIds(tag_definition_ids) ::= <<
  SELECT <fields()>
  FROM tag_definitions
  WHERE id IN (<tag_definition_ids: {id | :id_<i0>}; separator="," >)
  <AND_CHECK_TENANT()>
>>

auditFields(prefix) ::= <<
    <prefix>table_name,
    <prefix>record_id,
    <prefix>change_type,
    <prefix>change_date,
    <prefix>changed_by,
    <prefix>reason_code,
    <prefix>comments,
    <prefix>user_token,
    <prefix>account_record_id,
    <prefix>tenant_record_id
>>

insertAuditFromTransaction() ::= <<
    INSERT INTO audit_log(<auditFields()>)
    VALUES(:tableName, :recordId, :changeType, :createdDate, :userName, :reasonCode, :comment, :userToken, :accountRecordId, :tenantRecordId);
>>

historyFields() ::= <<
    record_id,
    id,
    name,
    created_by,
    description,
    change_type,
    updated_by,
    date,
    tenant_record_id
>>

addHistoryFromTransaction() ::= <<
    INSERT INTO tag_definition_history(<historyFields()>)
    VALUES (:recordId, :id, :name, :userName, :description, :changeType, :userName, :createdDate, :tenantRecordId);
>>
