From 98f42001cc86bd79d2b5877d04cfc3b10080ca05 Mon Sep 17 00:00:00 2001 From: Dan Stillman Date: Sat, 3 Jun 2006 20:23:19 +0000 Subject: [PATCH] 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 --- .../content/scholar/xpcom/scholar.js | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/chrome/chromeFiles/content/scholar/xpcom/scholar.js b/chrome/chromeFiles/content/scholar/xpcom/scholar.js index 25009ccb9..cb11a5899 100644 --- 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 *