XBSDB - Cross-Browser JavaScript Database library
XBSDB is the tool to operate with data arrays in your JavaScript code like with SQL-data.
XBSDB stores, arranges and selects data in your scripts. You can insert, delete, update and select records, you can use indexes to make a selection faster. JSON-based methods allow you to prepare data on one side (browser or web-server) and to load them on other one (web-server or browser).
Using of XBSDB allows to move some database operations from web-server to client machine and to reduce number of web-server requests.
Main feature of XBSDB is the speed of 'select' operation by complex WHERE-condition. XBSDB parses WHERE-expression to simple conditions tree once only, then this tree is used to reduce numbers of records to process per each condition. Indexes helps to reduce numbers of records to process also.
XBSDB consists of 2 parts - for browser and for web-server. Browser part is the core, web-server part just prepares data for exchange. Browser part is JavaScript code, web-server part is presented in 2 equivalent variants in Perl and PHP.
XBSDB is not an SQL-server so it don't take the time to parse SQL-queries at all. To create complex parser of SQL-queries was not the aim of development.
JavaScript - version 1.5 and more.
PHP - version 5.x.x and more, functions 'json_decode', 'json_encode'.
Perl - version 5.x.x and more, 'JSON' module.
There are 3 basic steps.
Prepare data on web-server side, convert them to JSON-string. Do this by web-server side library object of clacc named XBSDB (sure :-). Both Perl and PHP classes are functionally equal, methods names are same in both.
Note: XBSDB doesn't provide any way to send\recieve data, it just prepare them. You may use your favorite methods to send\recieve data strings (or even hashes).
Load recieved data into database on browser side, process them somehow, create the result and prepare it to send back to web-server. Core library functionality is available by a single JavaScript public class named XBSDB (again :-). Each object of this class contains one database. It can create\drop tables, insert\delete\update\select records, create\drop indexes, load and dump tables or even entire database. It cannot modity structure of table. Tables are not binded, and multiply select operation is not allowed (yet).
Load recieved client's data into database of web-server side, export them. Do this by the same class objects. Again, both Perl and PHP classes are equivalent in functionality.
Note: Perl class operates with references, PHP class - with variables.
See API section for details, see demo(s) for real code.
Expressions: Parsing & Processing
Valid WHERE-expressions may contain brackets, 'and' and 'or' keywords, arithmetical and logical operations, field names and numeric and string constants.
Functions are not allowed. Superfluous brackets are not allowed also.
Parser converts the WHERE-expression to condition objects tree in several steps:
Valid fields expression may contain brackets, arithmetical operations, field names of one table and numeric and string constants. No functions are allowed.
During WHERE-expression processing XBSDB creates initial recordset containing all records.
Then XBSDB reduce this recordset on every OR- and AND-expression in tree:
There is an optimization such as zero recordset checking and so on. Finally XBSDB returns reduced initial recordset as result.
Tip: to insrease a speed of complex WHERE-expression processing place most strong conditions first, it will reduce number of records to process in the beginning.
JavaScript
Indexes may be built on any correct fields expression. Indexes may increase the selection speed or may not - it depends on client's JavaScript engine. In some cases they make 'select' operation up to 7 times faster. Sure, every index makes 'insert' and 'update' operations slower.
Once again - use indexes only and only when you are sure that they are useful in your case.
Perl, PHP
There are no methods to create correct JavaScript index for now. But you may create it: index data is just an array or record numbers sorted by index expression.
JavaScript
Correct field types are 'number' and 'string' for now.
Perl, PHP
Web-server side calss doesn't perform any types checking, so be sure that value types correspond with field types declared in structure.
JavaScript
Default locale is English ('en'). Locales must be defined as properties of class variable XBSDB.prototype.Text of type object. See locale files for details. There may be several databases with different locale settings. Locale results in service messages language only. Russian locale ('ru') is included also. Other locale files are welcome.
Perl, PHP
There are no locale-related methods on web-server side, because database locale is feature of XBSDB core only.
JavaScript
Mostly all methods return false when error. The sResultCode public field keeps string of result code: 'OK' means OK, anything else means error. You can use the ResultText method to get the result description in current locale of database.
Perl
All methods return 0 when error. The sResultCode public field keeps string of result code: 'OK' means OK, anything else means error.
PHP
All methods return false when error. The sResultCode public field keeps string of result code: 'OK' means OK, anything else means error.
API is OOP based. There are objects only. No functions and globals at all - just class methods and object fields.
Class name is XBSDB in all platforms - JavaScript, Perl and PHP.
XBSDB object - Public fields
sResultCode - string of result code of last operation, 'OK' by default.
Description:
sResultCode may contain not only one value, but some string with several error codes, after espression parsing, for example.
Look at locale files (xbsdb_en.js, for example) for actual error codes.
XBSDB class - Public methods
Syntax:
XBSDB([sLocale])
Parameters:
[string sLocale] - string of locale or null (means 'en')
Return values:
object - XBSDB object
Description:
Creates XBSDB object. Then checks locale paramater.
sLocale should be equal to one of properties of XBSDB.prototype.Text object. Otherwise constructor sets locale to 'en' and makes sResultCode = 'DB_LOCALE_NOT_DEFINED'.
You can define any string as XBSDB.prototype.Text property, so you can set any locale - XBSDB will understand this.
If sLocale is not a string then constructor sets locale to 'en' and makes sResultCode = 'DB_LOCALE_NOT_STRING'.
LoadDB - loads entire database from database dump
Syntax:
LoadDB(vDatabase)
Parameters:
object or string vDatabase - database dump object or its JSON-string
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Clears table set of database, parses dump, when dump is correct then creates tables, fills them by data if any, defines indexes if any and fills indexes by data.
Dump may be an object or JSON-string of object.
LoadDB doesn't perform any data checking, this method is intended for fast load.
Use CreateTable, CreateIndex, InsertMany and InsertOne for same operation with data checking.
DumpDB - dumps entire database (all tables) to database dump
Syntax:
DumpDB([sType])
Parameters:
[string sType] - type of dump, 'object' or 'string' or null (means 'object')
Return values:
object or string when success
false when failed (sResultCode != 'OK')
Description:
Dumps all tables with structures, data and without indexes to an object (by default) or to a JSON-string.
LoadTable - loads table structure, data and indexes from table dump
Syntax:
LoadTable(sTableName, vTable)
Parameters:
string sTableName - table name
object or string vTable - table dump object or its JSON-string
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Parses dump, when dump is correct then clear structure, data and indexes of table, sets the new structure of table, fills it by data if any, defines indexes if any and fills indexes by data.
Dump may be an object or JSON-string of object.
LoadTable doesn't perform any data checking, this method is intended for fast load.
Use CreateTable, CreateIndex, InsertMany and InsertOne for same operation with data checking.
LoadTableData - loads table data and indexes from table data dump
Syntax:
LoadTableData(sTableName, vTable)
Parameters:
string sTableName - table name
object or string vTable - table dump object or its JSON-string
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Parses dump, when dump is correct then clears table data and indexes, fills table by data if any, defines indexes if any and fills indexes by data.
Dump may be an object or JSON-string of object.
LoadTableData doesn't perform any data checking, this method is intended for fast load.
Use CreateIndex, InsertMany and InsertOne for same operation with data checking.
DumpTable - dumps table without indexes to table dump
Syntax:
DumpTable(sTableName, [sType])
Parameters:
string sTableName - table name
[string sType] - type of dump, 'object' or 'string' or null (means 'object')
Return values:
object or string when success
false when failed (sResultCode != 'OK')
Description:
Dumps table with structures, data and without indexes to an object (by default) or to a JSON-string.
CreateTable - creates a new table in database
Syntax:
CreateTable(sTableName, aTableStructure)
Parameters:
string sTableName - table name
array aTableStructure - table structure
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Creates new table, if not exists, and then sets it's structure.
IsTable - checks is table exists or not
Syntax:
IsTable(sTableName)
Parameters:
string sTableName - table name
Return values:
true when table exists
false when table doesn't exist
false when failed (sResultCode != 'OK')
Description:
Returns true when parameter is not empty string and table with this name exists.
Returns false when parameter is not empty string and table with this name doesn't exist.
Otherwise returns false and set sResultCode to error code.
ShowTables - gets list of all tables in database
Syntax:
ShowTables()
Parameters:
none
Return values:
array when success
false when failed (sResultCode != 'OK')
Description:
Returns unsorted array of strings - names of all existing tables in database.
DropTable - removes table from a database
Syntax:
DropTable(sTableName)
Parameters:
string sTableName - table name
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Checks is table existing, if so remove it and returns true.
ShowFields - gets table structure
Syntax:
ShowFields(sTableName)
Parameters:
string sTableName - table name
Return values:
array when success
false when failed (sResultCode != 'OK')
Description:
Checks is table existing, if so returns table structure - field names and types as array of 2-element arrays [name, type].
InsertOne - inserts one record into table
Syntax:
InsertOne(sTableName, aFieldValues, [aFieldNames])
Parameters:
string sTableName - table name
array aFieldValues - array of fields values
[array aFieldNames] - array of fields names or null
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Inserts one record, then rebuilds all indexes. The slowest way to insert data.
If aFieldNames is omitted, then fields are used in structure order.
InsertMany - inserts many records into table at once
Syntax:
InsertMany(sTableName, aRows, [aFieldNames])
Parameters:
string sTableName - table name
array aRows - array of arrays of fields values
[array aFieldNames] - array of fields names or null
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Inserts many records, then rebuilds all indexes once.
If aFieldNames is omitted, then fields are used in structure order.
Update - updates data in table
Syntax:
Update(sTableName, aFieldValues, [aFieldNames], [sWhereExpr])
Parameters:
string sTableName - table name
array aFieldValues - array of fields values
[array aFieldNames] - array of fields names or null
[string sWhereExpr] - WHERE-expression or null
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Sets new values to record fields, then then rebuilds all indexes binded with every used field. Slow operation when many indexes.
If aFieldNames is omitted, then fields are used in structure order.
If sWhereExpr is omitted, then all records will be updated.
Delete - removes data from table
Syntax:
Delete(sTableName, [sWhereExpr])
Parameters:
string sTableName - table name
[string sWhereExpr] - WHERE-expression or null
Return values:
number of deleted records when success
false when failed (sResultCode != 'OK')
Description:
Deletes records, if sWhereExpr is omitted, then all records will be deleted.
Select - selects data from table
Syntax:
Select(sTableName, [aFieldNames], [sWhereExpr], [sOrderByExpr], [bDescFlag], [sGroupByExpr])
Parameters:
string sTableName - table name
[array aFieldNames] - array of result fields names or null
[string sWhereExpr] - WHERE-expression or null
[string sOrderByExpr] - ORDER BY expression to sort output or null
[boolean bDescFlag] - DESC flag of reverse sorting or null, valid when sOrderByExpr not null only
[string sGroupByExpr] - GROUP BY expression to group output or null
Return values:
array of record field values arrays when success
false when failed (sResultCode != 'OK')
Description:
Selects records and returns values of selected.
If aFieldNames is omitted, then fields are selected in structure order.
If sWhereExpr is omitted, then all records will be selected.
SelectToRecordSet - gets array of record identifiers from table
Syntax:
SelectToRecordSet(sTableName, [sWhereExpr], [sOrderByExpr], [bDescFlag], [sGroupByExpr])
Parameters:
string sTableName - table name
[string sWhereExpr] - WHERE-expression or null
[string sOrderByExpr] - ORDER BY expression to sort output or null
[boolean bDescFlag] - DESC flag of reverse sorting or null, valid when sOrderByExpr not null only
[string sGroupByExpr] - GROUP BY expression to group output or null
Return values:
array of record identifiers when success
false when failed (sResultCode != 'OK')
Description:
SelectToRecordSet selects records and return array of appropriate identifiers, that can be used in SelectFromRecordSet that returns field values.
This method is intended for pagers - SelectToRecordSet process sWhereExpr once, SelectFromRecordSet selects needed range.
SelectFromRecordSet - selects data from array of record identifiers
Syntax:
SelectFromRecordSet(sTableName, aRecords, [aFieldNames], [nOffset], [nLimit])
Parameters:
string sTableName - table name
array aRecords - array of record identifiers
[array aFieldNames] - array of result fields names or null
[number nOffset] - offset of result records or null
[number nLimit] - limit of result records or null
Return values:
array of record field values arrays when success
false when failed (sResultCode != 'OK')
Description:
Returns field values of not more than nLimit records from array of record identifiers beginning with nOffset.
aRecords must be result of SelectToRecordSet.
This method is intended for pagers - SelectToRecordSet selects all needed record once, SelectFromRecordSet selects needed range.
Rows2String - gets string from array of record field values arrays, uses toString
Syntax:
Rows2String(aRows, sRowBefore, sRowAfter, sValueBefore, sValueAfter, sValueEmpty)
Parameters:
array aRows - array of record values arrays
string sRowBefore - string to put before each record
string sRowAfter - string to put after each record
string sValueBefore - string to put before each field
string sValueAfter - string to put after each field
string sEmptyString - string to display empty field value
Return values:
string when success
false when failed (sResultCode != 'OK')
Description:
Method for easy output of array, returned by Select and SelectFromRecordSet methods.
Rows2LocaleString - gets string from array of record field values arrays, uses toLocaleString
Syntax:
Rows2LocaleString(aRows, sRowBefore, sRowAfter, sValueBefore, sValueAfter, sValueEmpty)
Parameters:
array aRows - array of record values arrays
string sRowBefore - string to put before each record
string sRowAfter - string to put after each record
string sValueBefore - string to put before each field
string sValueAfter - string to put after each field
string sEmptyString - string to display empty field value
Return values:
string when success
false when failed (sResultCode != 'OK')
Description:
Method for easy output of array, returned by Select and SelectFromRecordSet methods also.
Uses toLocaleString, so remember about formats.
CreateIndex - creates a new key in table
Syntax:
CreateIndex(sTableName, sKeyExpr)
Parameters:
string sTableName - table name
string sKeyExpr - key expression
Return values:
string - key id (normalized key expression) when success
false when failed (sResultCode != 'OK')
Description:
Normalizes sKeyExpr, creates new key, if not exists, and then builds it.
IsIndex - checks is key exists or not
Syntax:
IsIndex(sTableName, sKeyID)
Parameters:
string sTableName - table name
string sKeyID - key id
Return values:
true when key exists
false when key doesn't exist
false when failed (sResultCode != 'OK')
Description:
Normalizes sKeyExpr, checks existing of key with such id.
ShowIndexes - gets list of all keys of one type in table
Syntax:
ShowIndexes(sTableName)
Parameters:
string sTableName - table name
Return values:
array when success
false when failed (sResultCode != 'OK')
Description:
Returns unsorted array of key identifiers - normalized key expressions.
DropIndex - removes key from table
Syntax:
DropIndex(sTableName, sKeyID)
Parameters:
string sTableName - table name
string sKeyID - key id
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Normalizes sKeyExpr, deletes key with such id, if exists.
ResultText - returns last result status text in current database locale
Syntax:
ResultText()
Parameters:
none
Return values:
string
Description:
It uses sResultCode field. It takes value of sResultCode, then replaces all error codes by messages according to current locale and returns it.
SetLocale - sets database locale
Syntax:
SetLocale(sLocale)
Parameters:
string sLocale - string of locale
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Sets new locale of database if parameter is string and it is defined in XBSDB.prototype.Text by included file.
GetLocale - gets database locale
Syntax:
GetLocale()
Parameters:
none
Return values:
string when success
Description:
Returns current database locale.
XBSDB object - Public fields
sResultCode - string of result code of last operation, 'OK' by default
Description:
Error codes are:
'JSON_ERROR' - error in JSON-converting
'PARAM_EMPTY' - parameter is empty
'PARAM_TYPE_MISMATCH' - parameter's type mismatch
'TABLE_NO_DATA' - table has no data
'TABLE_NO_STRUCTURE' - table has no structure
'TABLE_NOT_EXIST' - table doesn't exist
XBSDB class - Public methods
Syntax:
new()
Parameters:
none
Return values:
reference blessed to the XBSDB class
Description:
Creates instance of XBSDB class.
setTableStructure - sets structure of table with given name
Syntax:
setTableStructure($name, \@structure)
Parameters:
string $name - table name
ref \@structure - table structure as reference to array of [name,type] pairs
Return values:
1 when success
0 when failed (sResultCode ne 'OK')
Description:
Clears table structure, data and indexes when table exists, if not - creates new table with given name. Sets table structure to given.
Methos doesn't perform any structure check.
getTableStructure - gets structure of table with given name
Syntax:
getTableStructure($name)
Parameters:
string $name - table name
Return values:
ref \@ when success
0 when failed (sResultCode ne 'OK')
Description:
Returns table structure as reference to array of [name,type] pairs.
setTableData - sets data of table with given name
Syntax:
setTableData($name, \@data)
Parameters:
string $name - table name
ref \@data - table data as reference to array of arrays of field values
Return values:
1 when success
0 when failed (sResultCode ne 'OK')
Description:
Clears table data and indexes when table exists. Sets table data to given.
Methos doesn't perform any data check.
getTableData - gets data of table with given name
Syntax:
getTableData($name)
Parameters:
string $name - table name
Return values:
ref \@ when success
0 when failed (sResultCode ne 'OK')
Description:
Returns table data as reference to array of arrays of field values.
setTableKey - sets index of table with given name
Syntax:
setTableKey($name, $expression, [\@data])
Parameters:
string $name - table name
string $expression - correct JavaScript index expression
[ref \@data] - index data as reference to sorted array of record numbers or null (menas no data, will be created by XBSDB core on browser side)
Return values:
1 when success
0 when failed (sResultCode ne 'OK')
Description:
Add index when table exists. Existing index with same expression will be overwritten.
Methos doesn't perform any index check and $expression normalization, $expression will be normalized on browser side automatically.
unsetTable - removes table with given name from database
Syntax:
unsetTable($name)
Parameters:
string $name - table name
Return values:
1 when success
0 when failed (sResultCode ne 'OK')
Description:
Deletes table when exists.
toHash - gets correct hash of database or table
Syntax:
toHash([$name])
Parameters:
[string $name] - table name or null (means entire database)
Return values:
ref \% when success
0 when failed (sResultCode ne 'OK')
Description:
Returns correct hash containing one table with structure, data and indexes, or entire database. Such hash may be sent to XBSDB core.
toJSON - gets correct JSON-string of hash of database or table
Syntax:
toJSON([$name])
Parameters:
[string $name] - table name or null (means entire database)
Return values:
string when success
0 when failed (sResultCode ne 'OK')
Description:
Returns correct JSON-string of hash containing one table with structure, data and indexes, or entire database. Such string may be sent to XBSDB core.
fromHash - loads database or table from hash
Syntax:
fromHash(\%hash, [$name])
Parameters:
ref \%hash - hash representing database or table
[string $name] - table name or null (means entire database)
Return values:
1 when success
0 when failed (sResultCode ne 'OK')
Description:
Sets entire database or one table equal to given hash.
Methos doesn't perform any hash check.
fromJSON - loads database or table from correct JSON-string
Syntax:
fromJSON($json_str, [$name])
Parameters:
string $json_str - JSON-string of hash representing database or table
[string $name] - table name or null (means entire database)
Return values:
1 when success
0 when failed (sResultCode ne 'OK')
Description:
Converts JSON-string to a hash, when success sets entire database or one table equal to this hash.
Methos doesn't perform any hash check.
XBSDB object - Public fields
sResultCode - string of result code of last operation, 'OK' by default
Description:
Error codes are:
'JSON_ERROR' - error in JSON-converting
'JSON_ERROR_CTRL_CHAR' - json_last_error() returns JSON_ERROR_CTRL_CHAR
'JSON_ERROR_DEPTH' - json_last_error() returns JSON_ERROR_DEPTH
'JSON_ERROR_SYNTAX' - json_last_error() returns JSON_ERROR_SYNTAX
'PARAM_EMPTY' - parameter is empty
'PARAM_TYPE_MISMATCH' - parameter's type mismatch
'TABLE_NO_DATA' - table has no data
'TABLE_NO_STRUCTURE' - table has no structure
'TABLE_NOT_EXIST' - table doesn't exist
XBSDB class - Public methods
setTableStructure - sets structure of table with given name
Syntax:
setTableStructure($name, $structure)
Parameters:
string $name - table name
array $structure - table structure as array of [name,type] pairs
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Clears table structure, data and indexes when table exists, if not - creates new table with given name. Sets table structure to given.
Methos doesn't perform any structure check.
getTableStructure - gets structure of table with given name
Syntax:
getTableStructure($name)
Parameters:
string $name - table name
Return values:
array when success
false when failed (sResultCode != 'OK')
Description:
Returns table structure as array of [name,type] pairs.
setTableData - sets data of table with given name
Syntax:
setTableData($name, $data)
Parameters:
string $name - table name
array $data - table data as array of arrays of field values
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Clears table data and indexes when table exists. Sets table data to given.
Methos doesn't perform any data check.
getTableData - gets data of table with given name
Syntax:
getTableData($name)
Parameters:
string $name - table name
Return values:
array when success
false when failed (sResultCode != 'OK')
Description:
Returns table data as array of arrays of field values.
setTableKey - sets index of table with given name
Syntax:
setTableKey($name, $expression, [$data])
Parameters:
string $name - table name
string $expression - correct JavaScript index expression
[array $data] - index data as sorted array of record numbers or null (menas no data, will be created by XBSDB core on browser side)
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Add index when table exists. Index with existing expression will be overwritten.
Methos doesn't perform any index check and $expression normalization, $expression will be normalized on browser side automatically.
unsetTable - removes table with given name from database
Syntax:
unsetTable($name)
Parameters:
string $name - table name
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Deletes table when exists.
toHash - gets correct object representing database or table
Syntax:
toHash([$name])
Parameters:
[string $name] - table name or null (means entire database)
Return values:
object when success
false when failed (sResultCode != 'OK')
Description:
Returns correct object containing one table with structure, data and indexes, or entire database. Such object may be sent to XBSDB core.
toJSON - gets correct JSON-string of object of database or table
Syntax:
toJSON([$name])
Parameters:
[string $name] - table name or null (means entire database)
Return values:
string when success
false when failed (sResultCode != 'OK')
Description:
Returns correct JSON-string of object containing one table with structure, data and indexes, or entire database. Such string may be sent to XBSDB core.
fromHash - loads database or table from object
Syntax:
fromHash($hash, [$name])
Parameters:
object $hash - object representing database or table
[string $name] - table name or null (means entire database)
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Sets entire database or one table equal to given object.
Methos doesn't perform any object check.
fromJSON - loads database or table from correct JSON-string
Syntax:
fromJSON($json_str, [$name])
Parameters:
string $json_str - JSON-string of object representing database or table
[string $name] - table name or null (means entire database)
Return values:
true when success
false when failed (sResultCode != 'OK')
Description:
Converts JSON-string to an object, when success sets entire database or one table equal to this object.
Methos doesn't perform any object check.
Alexey Znayev, 2010, znaeff@mail.ru