Permalink
Browse files

Merge branch 'master' of https://github.com/JerrySievert/mongolike

  • Loading branch information...
2 parents 8d0e290 + cfb3ca7 commit da4d9d2c47f81b3fdad18aeab932d3c7379e0fa1 @JerrySievert committed Jan 4, 2013
Showing with 22 additions and 6 deletions.
  1. +2 −4 create_collection.sql
  2. +20 −2 save.sql
View
6 create_collection.sql
@@ -7,28 +7,26 @@ CREATE UNIQUE INDEX idx_collection_constraint ON collection (name);
CREATE OR REPLACE FUNCTION create_collection(collection varchar) RETURNS
boolean AS $$
+
+
var plan1 = plv8.prepare('INSERT INTO collection (name) VALUES ($1)', [ 'varchar' ]);
var plan2 = plv8.prepare('CREATE TABLE col_' + collection +
' (col_' + collection + '_id INT NOT NULL PRIMARY KEY, data JSON)');
var plan3 = plv8.prepare('CREATE SEQUENCE seq_col_' + collection);
var ret;
-
try {
plv8.subtransaction(function () {
plan1.execute([ collection ]);
plan2.execute([ ]);
plan3.execute([ ]);
-
ret = true;
});
} catch (err) {
ret = false;
}
-
plan1.free();
plan2.free();
plan3.free();
- return ret;
$$ LANGUAGE plv8 IMMUTABLE STRICT;
View
22 save.sql
@@ -1,12 +1,30 @@
CREATE OR REPLACE FUNCTION save(collection varchar, data json) RETURNS
BOOLEAN AS $$
var obj = JSON.parse(data);
-
var id = obj._id;
// if there is no id, naively assume an insert
if (id === undefined) {
- var seq = plv8.prepare("SELECT nextval('seq_col_" + collection + "') AS id");
+
+
+
+ var seq;
+ try
+ {
+ plv8.subtransaction(function(){
+ seq = plv8.prepare("SELECT nextval('seq_col_" + collection + "') AS id");
+ });
+ }
+ catch(err)
+ {
+ if (err='Error: relation "seq_col_' + collection + '" does not exist')
+ {
+ var create_collection = plv8.find_function("create_collection");
+ res = create_collection(collection);
+ seq = plv8.prepare("SELECT nextval('seq_col_" + collection + "') AS id");
+ }
+ }
+
var rows = seq.execute([ ]);
id = rows[0].id;

0 comments on commit da4d9d2

Please sign in to comment.