SET SESSION sql_mode='ANSI';

CREATE TABLE "domains" (
	"id" INTEGER NOT NULL AUTO_INCREMENT,
	"name" VARCHAR(255) NOT NULL,
	"type" VARCHAR(6) NOT NULL,
	"master" VARCHAR(40) NOT NULL DEFAULT '',
	"account" VARCHAR(40) NOT NULL DEFAULT '',
	"last_check" INTEGER DEFAULT NULL,
	"notified_serial" INTEGER DEFAULT NULL,
	"auto_serial" INTEGER NOT NULL DEFAULT 0,
	"status" CHAR(1) NOT NULL DEFAULT 'A',
CONSTRAINT "pdns_pk_domains_id"
	PRIMARY KEY ("id"),
CONSTRAINT "pdns_unq_domains_name"
	UNIQUE ("name")
) type=InnoDB;

CREATE INDEX "pdns_idx_domains_status_type" ON "domains" ("status","type");



CREATE TABLE "records" (
	"id" INTEGER NOT NULL AUTO_INCREMENT,
	"domain_id" INTEGER NOT NULL,
	"name" VARCHAR(255) NOT NULL,
	"type" VARCHAR(6) NOT NULL,
	"ttl" INTEGER DEFAULT NULL,
	"prio" INTEGER DEFAULT NULL,
	"content" VARCHAR(255) NOT NULL,
CONSTRAINT "pdns_pk_records_id"
	PRIMARY KEY ("id"),
CONSTRAINT "pdns_fk_records_domainid"
	FOREIGN KEY ("domain_id")
	REFERENCES "domains" ("id")
	ON UPDATE CASCADE
	ON DELETE CASCADE
) type=InnoDB;

CREATE INDEX "pdns_idx_records_name_type" ON "records" ("name","type");
CREATE INDEX "pdns_idx_records_type" ON "records" ("type");



CREATE TABLE "supermasters" (
	"ip" VARCHAR(40) NOT NULL,
	"nameserver" VARCHAR(255) NOT NULL,
	"account" VARCHAR(40) NOT NULL DEFAULT ''
);

CREATE INDEX "pdns_idx_smaster_ip_ns" ON "supermasters" ("ip","nameserver");



GRANT SELECT ON "supermasters" TO "powerdns";
GRANT ALL ON "domains" TO "powerdns";
GRANT ALL ON "records" TO "powerdns";



DELIMITER :

CREATE TRIGGER "pdns_trig_records_insert"
AFTER INSERT ON "records"
FOR EACH ROW BEGIN
	UPDATE "domains" d SET d."auto_serial" = d."auto_serial" + 1
	WHERE d."id" = NEW."domain_id";
END;:

CREATE TRIGGER "pdns_trig_records_update"
AFTER UPDATE ON "records"
FOR EACH ROW BEGIN
	UPDATE "domains" d SET d."auto_serial" = d."auto_serial" + 1
	WHERE d."id" = NEW."domain_id";
END;:

CREATE TRIGGER "pdns_trig_records_delete"
AFTER DELETE ON "records"
FOR EACH ROW BEGIN
	UPDATE "domains" d SET d."auto_serial" = d."auto_serial" + 1
	WHERE d."id" = OLD."domain_id";
END;:

DELIMITER ;
