PRAGMA journal_mode=WAL;
PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS AssetHeader (
    UUID              	BLOB        NOT NULL UNIQUE,
    Name            	TEXT        NOT NULL UNIQUE,
    TypeID              INTEGER     NOT NULL,
    TypeName            TEXT        NOT NULL,

    CreateTime      	INTEGER     NOT NULL DEFAULT(CAST(unixepoch('subsec') AS INTEGER) * 1000000),
    ModificationTime    INTEGER     NOT NULL DEFAULT(CAST(unixepoch('subsec') AS INTEGER) * 1000000),

    PRIMARY KEY(UUID)
);

CREATE TRIGGER IF NOT EXISTS AssetHeader_UpdateTime
AFTER UPDATE OF Name, TypeID, TypeName ON AssetHeader FOR EACH ROW
BEGIN
    UPDATE AssetHeader
    SET ModificationTime = CAST(unixepoch('subsec') AS INTEGER) * 1000000
    WHERE UUID = NEW.UUID;
END;

CREATE TABLE IF NOT EXISTS Asset (
    UUID              	BLOB        NOT NULL UNIQUE,

    Asset               BLOB        NOT NULL,

    PRIMARY KEY(UUID),
    FOREIGN KEY(UUID) REFERENCES AssetHeader(UUID) ON DELETE CASCADE
);

CREATE TRIGGER IF NOT EXISTS Asset_UpdateTime
AFTER UPDATE OF Asset ON Asset FOR EACH ROW
BEGIN
    UPDATE AssetHeader
    SET ModificationTime = CAST(unixepoch('subsec') AS INTEGER) * 1000000
    WHERE UUID = NEW.UUID;
END;