
-- for primordial facts:
CREATE TABLE american(person text);
CREATE TABLE missile(thing text);
CREATE TABLE owns(owner text, property text);
CREATE TABLE enemy(person text, target text);

-- for derived facts:
CREATE TABLE weapon(thing text);
CREATE TABLE sells(seller text, thing text, buyer text);
CREATE TABLE hostile(person text);
CREATE TABLE criminal(person text);

-- rules:
CREATE RULE missile_is_a_weapon AS
	   ON INSERT TO missile 
	   DO ALSO 
	   INSERT INTO weapon SELECT NEW.thing;

CREATE RULE enemy_of_america_is_hostile AS
	   ON INSERT TO enemy WHERE NEW.target = 'America'
	   DO ALSO
	   INSERT INTO hostile SELECT NEW.person;

-- nono_can_get_missiles_only_from_west
CREATE RULE nono_can_get_missiles_only_from_west__missile AS
	   ON INSERT TO missile
	   DO ALSO
	   INSERT INTO sells
	   SELECT 'West' AS seller, NEW.thing, 'Nono' AS buyer 
	   FROM owns WHERE owner='Nono' AND property=NEW.thing;

CREATE RULE nono_can_get_missiles_only_from_west__owns AS
	   ON INSERT TO owns WHERE NEW.owner='Nono'
	   DO ALSO
	   INSERT INTO sells
	   SELECT 'West' AS seller, NEW.property, 'Nono' AS buyer 
	   FROM missile WHERE thing=NEW.property;

-- americans_selling_weapons_to_hostiles_are_criminal
CREATE RULE americans_selling_weapons_to_hostiles_are_criminal__hostile AS
	   ON INSERT TO hostile
	   DO ALSO
	   INSERT INTO criminal
	   SELECT seller FROM sells, weapon, american
	   WHERE sells.buyer=NEW.person 
	   		 AND sells.thing=weapon.thing
			 AND sells.seller=american.person;

CREATE RULE americans_selling_weapons_to_hostiles_are_criminal__weapon AS
	   ON INSERT TO weapon
	   DO ALSO
	   INSERT INTO criminal
	   SELECT seller FROM sells, hostile, american
	   WHERE sells.buyer=hostile.person 
	   		 AND sells.thing=NEW.thing
			 AND sells.seller=american.person;


CREATE RULE americans_selling_weapons_to_hostiles_are_criminal__american AS
	   ON INSERT TO american
	   DO ALSO
	   INSERT INTO criminal
	   SELECT seller FROM sells, hostile, weapon
	   WHERE sells.buyer=hostile.person 
	   		 AND sells.thing=weapon.thing
			 AND sells.seller=NEW.person;

CREATE RULE americans_selling_weapons_to_hostiles_are_criminal__sells AS
	   ON INSERT TO sells
	   DO ALSO
	   INSERT INTO criminal
	   SELECT NEW.seller FROM american, hostile, weapon
	   WHERE NEW.buyer=hostile.person 
	   		 AND NEW.thing=weapon.thing
			 AND NEW.seller=american.person;


-- entering some facts now:
INSERT INTO missile VALUES('M1');
INSERT INTO enemy VALUES('Nono','America');
INSERT INTO owns VALUES('Nono','M1');
INSERT INTO american VALUES('West');

-- querying the database:
SELECT * FROM criminal;