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

This commit is contained in:
Dan Stillman 2006-06-03 20:23:19 +00:00
parent bbbb243315
commit 98f42001cc

View File

@ -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
*