-- -- PostgreSQL database dump -- SET client_encoding = 'UTF8'; SET standard_conforming_strings = off; SET check_function_bodies = false; SET client_min_messages = warning; SET escape_string_warning = off; -- -- Name: plpgsql; Type: PROCEDURAL LANGUAGE; Schema: -; Owner: josh -- CREATE PROCEDURAL LANGUAGE plpgsql; ALTER PROCEDURAL LANGUAGE plpgsql OWNER TO josh; SET search_path = public, pg_catalog; -- -- Name: check_balance(); Type: FUNCTION; Schema: public; Owner: josh -- CREATE FUNCTION check_balance() RETURNS trigger AS $$ declare balance integer; amount integer; owner text; begin if (tg_op = 'DELETE') then owner := old.account_owner; amount := -1 * old.amount; elsif (tg_op = 'UPDATE') then owner := new.account_owner; amount := -1 * old.amount + amount; else owner := new.account_owner; amount := new.amount; end if; balance := get_balance(owner); if (balance + amount < 0) then raise exception E'Rejecting operation; account owner %\'s balance would drop below 0', owner; else if (tg_op = 'DELETE') then return old; else return new; end if; end if; end; $$ LANGUAGE plpgsql STABLE; ALTER FUNCTION public.check_balance() OWNER TO josh; -- -- Name: get_balance(text); Type: FUNCTION; Schema: public; Owner: josh -- CREATE FUNCTION get_balance(text) RETURNS bigint AS $_$ select coalesce(sum(amount), 0) from ledger where account_owner = $1;$_$ LANGUAGE sql STABLE; ALTER FUNCTION public.get_balance(text) OWNER TO josh; SET default_tablespace = ''; SET default_with_oids = false; -- -- Name: accounts; Type: TABLE; Schema: public; Owner: josh; Tablespace: -- CREATE TABLE accounts ( owner_name text NOT NULL ); ALTER TABLE public.accounts OWNER TO josh; -- -- Name: ledger; Type: TABLE; Schema: public; Owner: josh; Tablespace: -- CREATE TABLE ledger ( account_owner text NOT NULL, amount integer NOT NULL ); ALTER TABLE public.ledger OWNER TO josh; -- -- Name: accounts_pkey; Type: CONSTRAINT; Schema: public; Owner: josh; Tablespace: -- ALTER TABLE ONLY accounts ADD CONSTRAINT accounts_pkey PRIMARY KEY (owner_name); -- -- Name: ledger_owner_ix; Type: INDEX; Schema: public; Owner: josh; Tablespace: -- CREATE INDEX ledger_owner_ix ON ledger USING btree (account_owner); -- -- Name: check_balance; Type: TRIGGER; Schema: public; Owner: josh -- CREATE TRIGGER check_balance BEFORE INSERT OR DELETE OR UPDATE ON ledger FOR EACH ROW EXECUTE PROCEDURE check_balance(); -- -- Name: ledger_account_owner_fkey; Type: FK CONSTRAINT; Schema: public; Owner: josh -- ALTER TABLE ONLY ledger ADD CONSTRAINT ledger_account_owner_fkey FOREIGN KEY (account_owner) REFERENCES accounts(owner_name); -- -- Name: public; Type: ACL; Schema: -; Owner: josh -- REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON SCHEMA public FROM josh; GRANT ALL ON SCHEMA public TO josh; GRANT ALL ON SCHEMA public TO PUBLIC; -- -- PostgreSQL database dump complete --