-- sample data to test Firebird system tables

-- TABLE TEST
CREATE TABLE TEST1 (
  TEST_NAME CHAR(30) CHARACTER SET NONE NOT NULL COLLATE NONE,
  TEST_ID INTEGER DEFAULT '0' NOT NULL,
  TEST_DATE TIMESTAMP NOT NULL
);
ALTER TABLE TEST1 ADD CONSTRAINT PK_TEST PRIMARY KEY (TEST_ID);

-- TABLE TEST2 with some CONSTRAINTs and an INDEX
CREATE TABLE TEST2 (
  ID INTEGER NOT NULL,
  FIELD1 INTEGER,
  FIELD2 CHAR(15) CHARACTER SET NONE COLLATE NONE,
  FIELD3 VARCHAR(50) CHARACTER SET NONE COLLATE NONE,
  FIELD4 INTEGER,
  FIELD5 INTEGER,
  ID2 INTEGER NOT NULL
);
ALTER TABLE TEST2 ADD PRIMARY KEY (ID2);
CREATE UNIQUE INDEX TEST2_FIELD1ID_IDX ON TEST2(ID, FIELD1);
CREATE UNIQUE INDEX TEST2_FIELD4_IDX ON TEST2(FIELD4);
CREATE INDEX TEST2_FIELD5_IDX ON TEST2(FIELD5);

-- TABLE NUMBERS
CREATE TABLE NUMBERS (
  NUMBER INTEGER DEFAULT '0' NOT NULL,
  EN CHAR(100) CHARACTER SET ISO8859_1 NOT NULL COLLATE ISO8859_1,
  FR CHAR(100) CHARACTER SET ISO8859_1 NOT NULL COLLATE ISO8859_1
);

-- TABLE NEWTABLE
CREATE TABLE NEWTABLE (
  ID INT DEFAULT 0 NOT NULL,
  SOMENAME VARCHAR (12),
  SOMEDESCRIPTION VARCHAR (12)
);
ALTER TABLE NEWTABLE ADD CONSTRAINT PKINDEX_IDX PRIMARY KEY (ID);
CREATE GENERATOR NEWTABLE_SEQ;

-- VIEW on TEST
CREATE VIEW "testview"(
  TEST_NAME,
  TEST_ID,
  TEST_DATE
) AS
SELECT *
FROM TEST1
WHERE TEST_NAME LIKE 't%';

-- VIEW on NUMBERS
CREATE VIEW "numbersview"(
  NUM,
  EN,
  FR
) AS
SELECT *
FROM NUMBERS
WHERE NUMBER > 100;

-- TRIGGER on NEWTABLE (emulate autoincrement)
SET TERM ^ ;

CREATE TRIGGER AUTOINCREMENTPK FOR NEWTABLE
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN
  IF (NEW.ID IS NULL OR NEW.ID = 0) THEN
     NEW.ID = GEN_ID(NEWTABLE_SEQ, 1);
END^

SET TERM ; ^

-- SAMPLE STORED PROCEDURE
SET TERM ^ ;

CREATE PROCEDURE getEnglishNumber(N INTEGER)
RETURNS (
  english_number CHAR(100)
)
AS
BEGIN
  FOR
    SELECT EN
    FROM NUMBERS
    WHERE NUMBER = :N
    INTO :english_number
  DO
    BEGIN
      SUSPEND;
    END
END ^

SET TERM ; ^

-- TABLEs for testing CONSTRAINTs
CREATE TABLE "testconstraints" (
  "someid" integer NOT NULL,
  "somename" char(10) NOT NULL,
  CONSTRAINT "testconstraints_id_pk" PRIMARY KEY ("someid")
);
CREATE TABLE "testconstraints2" (
  "ext_id" integer NOT NULL,
  "modified" date,
  "uniquefield" char(10) NOT NULL,
  "usraction" integer NOT NULL,
  CONSTRAINT "testconstraints_id_fk" FOREIGN KEY ("ext_id")
      REFERENCES "testconstraints" ("someid")
      ON UPDATE CASCADE
	  ON DELETE CASCADE,
  CONSTRAINT "unique_2_fields_idx" UNIQUE ("modified", "usraction"),
  CONSTRAINT "uniquefld_idx" UNIQUE ("uniquefield")
);
