CREATE OR REPLACE FUNCTION greater_zero(a int)
RETURNS boolean AS $$
SELECT a > 0
$$ LANGUAGE sql;

CREATE DOMAIN positive_int AS int CHECK(greater_zero(VALUE) OR VALUE = 0);

CREATE TYPE pt AS (x int, y int);

CREATE OR REPLACE FUNCTION randint(int)
RETURNS int AS $$
SELECT (random() * $1)::int;
$$ LANGUAGE sql;

CREATE TABLE dept(
  no serial PRIMARY KEY,
  name text,
  xx int DEFAULT randint(10),
  xy int NOT NULL CHECK (greater_zero(xy)),
  xz positive_int,
  xj pt
);

CREATE UNIQUE INDEX ON dept(name);

CREATE TABLE emp(
  no serial PRIMARY KEY,
  name text,
  dept_no int REFERENCES dept(no)
);

CREATE INDEX ON emp(name);

CREATE OR REPLACE FUNCTION trigger_func()
RETURNS TRIGGER AS $$
BEGIN
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER emp_insert_trigger BEFORE INSERT ON emp
  FOR EACH ROW EXECUTE PROCEDURE trigger_func();

CREATE OR REPLACE FUNCTION mdiv(anyelement, anyelement)
RETURNS double precision AS $$
  SELECT CASE WHEN $2=0 THEN NULL ELSE $1/$2::double precision END
$$ LANGUAGE sql;

CREATE OPERATOR // (
  PROCEDURE = mdiv,
  LEFTARG = anyelement,
  RIGHTARG = anyelement
);

CREATE SCHEMA myschema;
CREATE TABLE myschema.mytable(a int);
CREATE VIEW myschema.myview AS SELECT 1;

CREATE VIEW myview AS SELECT 10;

CREATE MATERIALIZED VIEW mymview AS SELECT * FROM generate_series(1,10);

CREATE OR REPLACE FUNCTION myschema.int_to_date(int)
RETURNS date AS $$
  SELECT '1970-01-01'::date + ($1 - 1);
$$ LANGUAGE sql;

CREATE CAST (int AS date)
   WITH FUNCTION myschema.int_to_date(int)
  AS IMPLICIT;
