# Copyright (c) 2008-2012 Nuxeo SA (http://nuxeo.com/) and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#     Florent Guillaume
#     Benoit Delbosc

# Variables used:
# ${idType} VARCHAR(36)
# ${h2Functions} org.nuxeo.ecm.core.storage.sql.db.H2Functions
# ${h2Fulltext} org.nuxeo.ecm.core.storage.sql.db.H2Fulltext
# ${readPermissions} ('Browse'), ('Read'), ('ReadProperties'), ('ReadRemove'), ('ReadWrite'), ('Everything')
# ${usersSeparator} default is set to "," but it configurable
# Conditions used:
# fulltextEnabled

############################################################


#CATEGORY: beforeTableCreation


CREATE ALIAS IF NOT EXISTS NX_IN_TREE FOR "${h2Functions}.isInTreeString";

CREATE ALIAS IF NOT EXISTS NX_ACCESS_ALLOWED FOR "${h2Functions}.isAccessAllowedString";

#IF: clusteringEnabled
CREATE ALIAS IF NOT EXISTS NX_CLUSTER_INVAL FOR "${h2Functions}.clusterInvalidateString";

#IF: clusteringEnabled
CREATE ALIAS IF NOT EXISTS NX_CLUSTER_GET_INVALS FOR "${h2Functions}.getClusterInvalidationsString";

CREATE ALIAS IF NOT EXISTS nx_upgrade_versions FOR "${h2Functions}.upgradeVersions";

CREATE ALIAS IF NOT EXISTS nx_upgrade_lastContributor FOR "${h2Functions}.upgradeLastContributor";

CREATE ALIAS IF NOT EXISTS NX_ANCESTORS FOR "${h2Functions}.getAncestorsIds";

#IF: fulltextEnabled
CREATE ALIAS IF NOT EXISTS NXFT_INIT FOR "${h2Fulltext}.init";

#IF: fulltextEnabled
CALL NXFT_INIT();


############################################################


#CATEGORY: afterTableCreation

DROP TRIGGER IF EXISTS nx_trig_acls_modified;

DROP TRIGGER IF EXISTS nx_trig_hierarchy_modified;

DROP TRIGGER IF EXISTS NX_TRIG_DESC;


############################################################


#CATEGORY: upgradeVersions

MERGE INTO hierarchy (id, isversion)
  SELECT h.id, true
    FROM hierarchy h JOIN versions v ON h.id = v.id;

CALL NX_UPGRADE_VERSIONS();


############################################################


#CATEGORY: upgradeLastContributor

CALL NX_UPGRADE_LASTCONTRIBUTOR();


############################################################


#CATEGORY: upgradeLocks

ALTER TABLE locks DROP CONSTRAINT locks_id_hierarchy_fk;

DELETE FROM locks WHERE lock IS NULL;

UPDATE locks SET
  owner = SUBSTRING(lock, 1, POSITION(':', lock) - 1),
  created = PARSEDATETIME(SUBSTRING(lock, POSITION(':', lock) + 1), 'MMM d, yyyy', 'en_US')
  WHERE owner IS NULL;
