0
1
Fork 0
hedera-web-mindshore/js/db/connection.js

137 lines
2.9 KiB
JavaScript

/**
* Simulates a connection to a database by making asynchronous requests to a
* remote REST service that returns the results in JSON format.
* Using this class can perform any operation that can be done with a database,
* like open/close a connection or selecion/updating queries.
*
* Warning! You should set a well defined dababase level privileges to use this
* class or you could have a serious security hole in you application becasuse
* the user can send any statement to the server. For example: DROP DATABASE
**/
Db.Connection = new Class ().extend
({
Flag:
{
NOT_NULL : 1
,PRI_KEY : 2
,AI : 512 | 2 | 1
}
,Type:
{
BOOLEAN : 1
,INTEGER : 3
,DOUBLE : 4
,STRING : 5
,DATE : 8
,DATE_TIME : 9
}
});
Db.Connection.implement
({
Extends: Vn.JsonConnection
/**
* Runs a SQL query on the database.
*
* @param {String} sql The SQL statement
* @param {Function} callback The function to call when operation is done
**/
,execSql: function (sql, callback)
{
this.send ('core/query', {'sql': sql},
this._onExec.bind (this, callback));
}
/**
* Runs a stmt on the database.
*
* @param {Sql.Stmt} stmt The statement
* @param {Function} callback The function to call when operation is done
* @param {Sql.Batch} batch The batch used to set the parameters
**/
,execStmt: function (stmt, callback, batch)
{
this.execSql (stmt.render (batch), callback);
}
/**
* Runs a query on the database.
*
* @param {String} query The SQL statement
* @param {Function} callback The function to call when operation is done
* @param {Sql.Batch} batch The batch used to set the parameters
**/
,execQuery: function (query, callback, batch)
{
this.execStmt (new Sql.String ({query: query}), callback, batch);
}
/*
* Parses a value to date.
*/
,valueToDate: function (value)
{
return new Date (value * 1000);
}
/*
* Called when a query is executed.
*/
,_onExec: function (callback, json, error)
{
if (json)
try {
if (json && json instanceof Array)
for (var i = 0; i < json.length; i++)
if (json[i] !== true)
{
var data = json[i].data;
var columns = json[i].columns;
for (var j = 0; j < columns.length; j++)
{
var castFunc = null;
switch (columns[j].type)
{
case Db.Connection.Type.DATE:
case Db.Connection.Type.DATE_TIME:
case Db.Connection.Type.TIMESTAMP:
castFunc = this.valueToDate;
break;
}
if (castFunc !== null)
{
if (columns[j].def != null)
columns[j].def = castFunc (columns[j].def);
for (var k = 0; k < data.length; k++)
if (data[k][j] != null)
data[k][j] = castFunc (data[k][j]);
}
}
}
}
catch (e)
{
error = e;
}
if (error)
this.signalEmit ('error', error);
if (callback)
try {
callback (new Db.ResultSet (json, error));
}
catch (e)
{
this.signalEmit ('error', e);
}
}
});