Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Create collections if they aren't there with save() #2

Merged
merged 1 commit into from

2 participants

@e1ven

I don't know if there's a better way to do this, but I added a function to automatically create collections if they aren't there.
In regular mongo, it'll save data to a collection without having to explicitly create it first, so having this makes using it easier ;)

I did it as an exception, to avoid having to do a sql lookup before each insert.
I've never written plv8 before, but it seems to work ;)

-CPD

@JerrySievert
Owner

i like it.

@JerrySievert JerrySievert merged commit cfb3ca7 into from
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 4, 2013
  1. @e1ven
This page is out of date. Refresh to see the latest.
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;
Something went wrong with that request. Please try again.