commit 98f42001cc86bd79d2b5877d04cfc3b10080ca05
parent bbbb24331555e06f464a47579fc6a425c4d41d03
Author: Dan Stillman <dstillman@zotero.org>
Date: Sat, 3 Jun 2006 20:23:19 +0000
New function Scholar.getRandomID( table, column [, max] ) for getting unique random keys in a DB table, because auto_increments make me feel dirty -- max is optional and defaults to 16383 (which should store in 2 bytes in SQLite), but increases automatically if a unique id can't be found after 10 tries
Diffstat:
1 file changed, 35 insertions(+), 0 deletions(-)
diff --git a/chrome/chromeFiles/content/scholar/xpcom/scholar.js b/chrome/chromeFiles/content/scholar/xpcom/scholar.js
@@ -22,6 +22,7 @@ var Scholar = new function(){
this.flattenArguments = flattenArguments;
this.join = join;
this.randomString = randomString;
+ this.getRandomID = getRandomID;
this.Hash = Hash;
@@ -200,6 +201,40 @@ var Scholar = new function(){
}
+ /**
+ * Find a unique random id for use in a DB table
+ **/
+ function getRandomID(table, column, max){
+ if (!table){
+ throw('SQL query not provided');
+ }
+
+ if (!column){
+ throw('SQL query not provided');
+ }
+
+ var sql = 'SELECT COUNT(*) FROM ' + table + ' WHERE ' + column + '=';
+
+ if (!max){
+ max = 16383;
+ }
+
+ var tries = 10; // # of tries to find a unique id
+ do {
+ // If no luck after number of tries, try a larger range
+ if (!tries){
+ max = max * 2;
+ }
+ var rnd = Math.floor(Math.random()*max);
+ var exists = Scholar.DB.valueQuery(sql + rnd);
+ tries--;
+ }
+ while (exists);
+
+ return rnd;
+ }
+
+
/*
* Class for creating hash arrays that behave a bit more sanely
*