CREATE TABLE IF NOT EXISTS federated_query_jobs_v017 (
 id VARCHAR(36) PRIMARY KEY, user_id VARCHAR(36) NOT NULL REFERENCES users(id), request_json JSON NOT NULL,
 execution_plan JSON NOT NULL, status VARCHAR(30) NOT NULL DEFAULT 'queued', progress_percent INTEGER NOT NULL DEFAULT 0,
 row_count INTEGER NOT NULL DEFAULT 0, result_key VARCHAR(1000) NOT NULL DEFAULT '', cursor_token VARCHAR(128) NOT NULL DEFAULT '',
 cancel_requested BOOLEAN NOT NULL DEFAULT FALSE, error TEXT NOT NULL DEFAULT '', started_at TIMESTAMPTZ, finished_at TIMESTAMPTZ,
 created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS ix_fq_jobs_user_status ON federated_query_jobs_v017(user_id,status);
CREATE TABLE IF NOT EXISTS federated_join_definitions_v017 (
 id VARCHAR(36) PRIMARY KEY, name VARCHAR(180) UNIQUE NOT NULL, left_model_id VARCHAR(36) NOT NULL REFERENCES semantic_models_v015(id),
 right_model_id VARCHAR(36) NOT NULL REFERENCES semantic_models_v015(id), join_type VARCHAR(20) NOT NULL DEFAULT 'inner',
 left_key VARCHAR(180) NOT NULL, right_key VARCHAR(180) NOT NULL, cardinality VARCHAR(30) NOT NULL DEFAULT 'many_to_one',
 max_rows_per_side INTEGER NOT NULL DEFAULT 100000, enabled BOOLEAN NOT NULL DEFAULT TRUE, owner_id VARCHAR(36) NOT NULL REFERENCES users(id),
 created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS query_quotas_v017 (
 id VARCHAR(36) PRIMARY KEY, subject_type VARCHAR(30) NOT NULL DEFAULT 'role', subject_value VARCHAR(160) NOT NULL,
 max_concurrent INTEGER NOT NULL DEFAULT 3, daily_row_limit INTEGER NOT NULL DEFAULT 1000000, daily_cost_limit INTEGER NOT NULL DEFAULT 1000000,
 max_export_rows INTEGER NOT NULL DEFAULT 100000, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_by VARCHAR(36) NOT NULL REFERENCES users(id),
 created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS ix_query_quotas_subject ON query_quotas_v017(subject_type,subject_value);
CREATE TABLE IF NOT EXISTS query_usage_ledger_v017 (
 id VARCHAR(36) PRIMARY KEY, user_id VARCHAR(36) NOT NULL REFERENCES users(id), job_id VARCHAR(36) REFERENCES federated_query_jobs_v017(id) ON DELETE SET NULL,
 rows_processed INTEGER NOT NULL DEFAULT 0, cost_units INTEGER NOT NULL DEFAULT 0, cache_hit BOOLEAN NOT NULL DEFAULT FALSE,
 operation VARCHAR(40) NOT NULL DEFAULT 'query', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS ix_query_usage_user_date ON query_usage_ledger_v017(user_id,created_at);
