CREATE TABLE ps_boards (
  id INTEGER NOT NULL PRIMARY KEY,
  daughterboard_id INTEGER
);

CREATE TABLE qaqc_single_run_results (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  runid INTEGER NOT NULL,
  psboard_id INTEGER NOT NULL,
  daughterboard_id INTEGER,
  position INTEGER,
  resistance_test_passed BOOLEAN NOT NULL,
  qspip INTEGER,
  recov INTEGER,
  power INTEGER,
  clock INTEGER,
  asdtp INTEGER,
  reset INTEGER,
  qaqc_result INTEGER,
  FOREIGN KEY("runid") REFERENCES "qaqc_runs"("id"),
  FOREIGN KEY("psboard_id") REFERENCES "ps_boards"("id"),
  FOREIGN KEY("position") REFERENCES "qaqc_positions"("id")
);

CREATE TABLE qaqc_runs (
  id INTEGER NOT NULL PRIMARY KEY,
  campaign_id INTEGER,
  run_datetime DATETIME,
  note TEXT,
  shifter TEXT NOT NULL,
  logfile TEXT,
  shiftscript_ver TEXT,
  FOREIGN KEY("campaign_id") REFERENCES "qaqc_campaigns"("id")
);

CREATE TABLE qaqc_dispatch (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  qaqc_campaign_id INTEGER,
  psb_id INTEGER,
  source_place TEXT NOT NULL,
  destination TEXT NOT NULL,
  time DATETIME,
  FOREIGN KEY("qaqc_campaign_id") REFERENCES "qaqc_campaigns"("id"),
  FOREIGN KEY("psb_id") REFERENCES "ps_boards"("id")
);

CREATE TABLE qaqc_campaigns (
  id INTEGER NOT NULL PRIMARY KEY,
  start_date DATETIME NOT NULL,
  end_date DATETIME NOT NULL,
  note TEXT
);

CREATE TABLE qaqc_resistance_check (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  psb_id INTEGER NOT NULL,
  passed BOOLEAN,
  FOREIGN KEY("psb_id") REFERENCES "ps_boards"("id")
);

CREATE TABLE qaqc_extra_run_results (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  runid INTEGER,
  psboard_id INTEGER NOT NULL,
  position INTEGER,
  FOREIGN KEY("runid") REFERENCES "qaqc_runs"("id"),
  FOREIGN KEY("psboard_id") REFERENCES "ps_boards"("id"),
  FOREIGN KEY("position") REFERENCES "qaqc_positions"("id")
);

CREATE TABLE qaqc_positions (
  id INTEGER NOT NULL PRIMARY KEY,
  name TEXT NOT NULL UNIQUE,
  station INTEGER NOT NULL,
  position INTEGER NOT NULL
);

CREATE VIEW qaqc_single_run_table
AS
  SELECT
    qaqc_single_run_results.psboard_id,
    qaqc_single_run_results.daughterboard_id,
    qaqc_positions.name,
    qaqc_single_run_results.runid,
    qaqc_runs.run_datetime,
    qaqc_runs.shiftscript_ver,
    qaqc_runs.shifter,
    qaqc_single_run_results.qspip,
    qaqc_single_run_results.recov,
    qaqc_single_run_results.power,
    qaqc_single_run_results.clock,
    qaqc_single_run_results.asdtp,
    qaqc_single_run_results.reset,
    qaqc_single_run_results.qaqc_result
  FROM
    qaqc_single_run_results,
    qaqc_positions,
    qaqc_runs
  WHERE
    qaqc_positions.id = qaqc_single_run_results.position AND
    qaqc_runs.id = qaqc_single_run_results.runid
