Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PgREST - REST implemented inside postgresql

PgREST - REST implemented inside postgresql

plv8, plv8x, pgrest!

Chia-liang Kao

November 29, 2013
Tweet

More Decks by Chia-liang Kao

Other Decks in Technology

Transcript

  1. PgREST is… • … a JSON document store • …

    running inside PostgreSQL • … working with existing relational data • … capable of loading Node.js modules • … compatible with MongoLab's REST API • … compatible with Firebase API (new!)
  2. postgresql 9.2: json type ! test=# CREATE TABLE x (

    foo json ); ! in postgresql 9.3
  3. plv8 CREATE FUNCTION to_jsontext(keys text[], vals text[]) RETURNS text AS

    $$ var o = {}; for (var i = 0; i < keys.length; i++) o[keys[i]] = vals[i]; return JSON.stringify(o); $$ LANGUAGE plv8 IMMUTABLE STRICT; ! SELECT to_jsontext(ARRAY['age', 'sex'], ARRAY['21', 'female']); to_jsontext ----------------------------- {"age":"21","sex":"female"} (1 row) Stored Procedures are hard to develop/test/maintain
  4. plv8x test=# select '{"foo": [1,2,3]}'::json |> 'return this.foo[1]'; ! test=#

    CREATE TABLE x ( foo json ); ! test=# SELECT foo ~> ‘this.bar + this.baz’ from x; ! ~> ‘@foo[1]’ in coffee
  5. plv8x with npm modules ! % npm i qs %

    plv8x —-import qs ! % plv8x -f 'plv8x.json parse_qs(text)=qs:parse' ok plv8x.json parse_qs(text) ! # Now parse_qs is a postgresql function! test=# select parse_qs('foo=bar&baz=1') as qs; qs ------------------------- {"foo":"bar","baz":"1"} !
  6. PgREST createdb yahnc; psql yahnc ! yahnc=# create table links

    ( _id int, link_id, int, body text, create_date timestamp, rating int ); ! % pgrest —-db yahnc Implicit table creation also supported demo: https://github.com/poga/yahnc
  7. PgREST - relational =# CREATE VIEW links_with_comments AS SELECT …

    join … USING () …; ! => /collections/links_with_comments A declarative way to construct views is also available
  8. PgREST - ACL =# CREATE VIEW pgrest.links AS SELECT *

    from links; ! =# CREATE RULE … AS ON UPDATE TO pgrest.links DO INSTEAD ( # ACL check and actual update ); Ditto for INSERT / DELETE
  9. PgREST - realtime api Compatible with firebase api: ! ref

    = new PgBase(‘http://localhost:3000/links'); ! ref.on(“value”, function(snapshot) {…}); ! ref.set(…);
  10. What’s next • More doc! • Simplified authn/authz integration •

    scaling with londiste/PGQ • pgbase bindings for frontend frameworks/toolkits • ngx_postgres <-> postgresql directly • <Your idea> ?