SELECT functions.to_global_col_names('"COND"');

SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.STATECD"          TO ".STATECD"      $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.UNITCD"           TO ".UNITCD"       $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.COUNTYCD"         TO ".COUNTYCD"     $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.PLOT"             TO ".PLOT"         $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.INVYR"            TO ".INVYR"        $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.CONDID"           TO ".CONDID"       $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.HABTYPCD1"        TO ".HABTYPCD"     $$);
SELECT functions.rename_if_exists($$ALTER TABLE "COND" RENAME "COND.HABTYPCD1_PUB_CD" TO ".HABTYP_PUB_CD"$$);

SELECT functions.set_col_types('"COND"', ARRAY[
  ('.STATECD' , 'integer')
, ('.UNITCD'  , 'integer')
, ('.COUNTYCD', 'integer')
, ('.PLOT'    , 'integer')
, ('.INVYR'   , 'integer')
, ('.CONDID'  , 'integer')
]::functions.col_cast[]);

SELECT functions.create_if_not_exists($$
ALTER TABLE "COND" ADD   COLUMN "COND.oldgrowth"      boolean;
ALTER TABLE "COND" ALTER COLUMN "COND.oldgrowth" TYPE boolean USING
(
    "COND.STDAGE"::integer>80 
    AND ("COND.TRTCD1"='0' OR "COND.TRTCD1" IS NULL)
    AND (("COND.DSTRBCD1"<>'30' AND "COND.DSTRBCD1"<>'31' AND "COND.DSTRBCD1"<>'32' AND "COND.DSTRBCD1"<>'80') OR "COND.DSTRBCD1" IS NULL)
    AND ("COND.STUMP_CD_PNWRS"='N' OR "COND.STUMP_CD_PNWRS" IS NULL)
    AND "COND.HARVEST_TYPE1_SRS" IS NULL
    AND "COND.PRESNFCD" IS NULL
    AND ("COND.STDORGCD"='0' OR "COND.STDORGCD" IS NULL)
)
OR "COND.STND_COND_CD_PNWRS"='7'
;
$$);

SELECT functions.create_if_not_exists($$ALTER TABLE "COND" ADD CONSTRAINT "COND.ID"     UNIQUE ("COND.CN")                                                       $$);
SELECT functions.create_if_not_exists($$ALTER TABLE "COND" ADD CONSTRAINT "COND.unique" UNIQUE (".STATECD", ".UNITCD", ".COUNTYCD", ".PLOT", ".INVYR", ".CONDID")$$);
SELECT functions.cluster_once('"COND"', '"COND.unique"');
