NOTE: ScriptDB is now deprecated. Please take a look at Database abstraction with google apps script for alternatives.
Sometimes you need to create a unique identification for each object. ScriptDB automatically assigns a unique objectId for each object, so you can just use this. However, if you really do want to create a unique numeric ID that increments with each save, you can try this using this function to save to your scriptdb.
function incremenKeyAndSave(db,ob,key,proto) { // get a lock on shared resource var lock = LockService.getPublicLock(); lock.waitLock(10000); //now get the latest value for the given key var top = db.query(proto || {}).sortBy(key, db.DESCENDING, db.NUMERIC).limit(1); // will add one to the latest ob[key] = top.hasNext() ? (top.next()[key]) + 1: 1; // save and reslease lock var results = db.save(ob); lock.releaseLock(); return results; }
var top = db.query(proto || {}).sortBy(key, db.DESCENDING, db.NUMERIC).limit(1);
// will add one to the latest ob[key] = top.hasNext() ? (top.next()[key]) + 1: 1;
// save and release lock var results = db.save(ob); lock.releaseLock();
function testIncrement() { var x = 5; var db = ScriptDb.getMyDb(); while (x-->0) { incremenKeyAndSave ( db, {someData:'something',siloId:'test'}, 'someKey', {siloId:'test'} ); } var results = db.query ({}).sortBy('someKey',db.NUMERIC); while (results.hasNext()) { Logger.log(results.next()); } }
and the results..
[14-02-16 14:42:47:629 GMT] {siloId=test, someData=something, someKey=1.0}
[14-02-16 14:42:47:629 GMT] {siloId=test, someData=something, someKey=2.0}
[14-02-16 14:42:47:630 GMT] {siloId=test, someData=something, someKey=3.0}
[14-02-16 14:42:47:630 GMT] {siloId=test, someData=something, someKey=4.0}
[14-02-16 14:42:47:631 GMT] {siloId=test, someData=something, someKey=5.0}
[14-02-16 14:42:47:631 GMT] {siloId=test, someData=something, someKey=6.0}
[14-02-16 14:42:47:631 GMT] {siloId=test, someData=something, someKey=7.0}
[14-02-16 14:42:47:632 GMT] {siloId=test, someData=something, someKey=8.0}
[14-02-16 14:42:47:632 GMT] {siloId=test, someData=something, someKey=9.0}
[14-02-16 14:42:47:633 GMT] {siloId=test, someData=something, someKey=10.0}
For more like this, see From VBA to Google Apps Script . Why not join our forum, follow the blog or follow me on Twitter to ensure you get updates when they are available.
bruce mcpherson is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Based on a work at http://www.mcpher.com. Permissions beyond the scope of this license may be available at code use guidelines