-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
CREATE TABLE a (id SERIAL PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE b (id SERIAL PRIMARY KEY, key_a INTEGER REFERENCES a (id) ON DELETE CASCADE,data TEXT);
> I want to insert related records to both table. The problem is that
> in order to insert record to the second table it's necessary to know
> a.id
Common question, and there's several possible answers. I'm going to break
slightly from the norm though. Postgres has some cool features, and since we
can stuff this logic into the database, we might just as well. So let's play
with them!
CREATE VIEW ab AS SELECT a.id, a.name, b.data FROM a,b WHERE a.id = b.key_a;
CREATE FUNCTION ab_insert (text, text) RETURNS INTEGER AS 'DECLARE newid INTEGER; newname ALIAS FOR $1; newdata
ALIASFOR $2;BEGIN newid := nextval(''a_id_seq''); RAISE NOTICE ''newid is %'', newid; INSERT INTO a (id, name)
VALUES(newid, newname); INSERT INTO b (key_a, data) VALUES (newid, newdata); RETURN newid;END;' LANGUAGE
'plpgsql';
CREATE RULE ab_ins_rule AS ON INSERT TO ab DO INSTEAD SELECT ab_insert(new.name, new.data);
I'd really like to figure out how to write a function that doesn't return
anything (a "procedure" for all you pedantic CS types). Oh well.
- --
Andrew G. Hammond mailto:drew@xyzzy.dhs.org http://xyzzy.dhs.org/~drew/
56 2A 54 EF 19 C0 3B 43 72 69 5B E3 69 5B A1 1F 613-389-5481
5CD3 62B0 254B DEB1 86E0 8959 093E F70A B457 84B1
"To blow recursion you must first blow recur" -- me
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAjv0roYACgkQCT73CrRXhLFd4wCeNvUf1sYztKvs0Xqq9cfcDy97
n/wAmwXdCCaxrKQ6oTbtqSyhJ2IhSExG
=78uf
-----END PGP SIGNATURE-----