<< Click to Display Table of Contents >> Navigation: Multi-Protocol MasterOPC Server > Lua 5.1 Reference Manual > LuaSQLite3 Reference Manual > Database Methods |
After opening a database with sqlite3.open or sqlite3.open_memory the returned database object should be used for all further method calls in connection with that database. An open database object supports the following methods.
db:busy_handler([func[,udata]])
Sets or removes a busy handler for a database. func is either a Lua function that implements the busy handler or nil to remove a previously set handler. This function returns nothing.
The handler function is called with two parameters: udata and the number of (re-)tries for a pending transaction. It should return nil, FALSE or 0 if the transaction is to be aborted. All other values will result in another attempt to perform the transaction. (See the SQLite documentation for important hints about writing busy handlers.)
db:busy_timeout(t)
Sets a busy handler that waits for t milliseconds if a transaction cannot proceed. Calling this function will remove any busy handler set by db:busy_handler ; calling it with an argument less than or equal to 0 will turn off all busy handlers.
db:changes()
This function returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. Only changes that are directly specified by INSERT, UPDATE, or DELETE statements are counted. Auxiliary changes caused by triggers are not counted. Use db:total_changes to find the total number of changes.
db:close()
Closes a database. All SQL statements prepared using db:prepare should have been finalized before this function is called. The function returns sqlite3.OK on success or else a numerical error code (see the list of Numerical Error and Result Codes ).
db:close_vm(temponly)
Finalizes all statements that have not been explicitly finalized. If temponly is true, only internal, temporary statements are finalized. This function returns nothing.
db:create_aggregate(name,nargs,step,final)
This function creates an aggregate callback function. Aggregates perform an operation over all rows in a query. name is a string with the name of the aggregate function as given in an SQL statement; nargs is the number of arguments this call will provide. step is the actual Lua function that gets called once for every row; it should accept a function context (see Methods for Callback Contexts ) plus the same number of parameters as given in nargs. final is a function that is called once after all rows have been processed; it receives one argument, the function context.
The function context can be used inside the two callback functions to communicate with SQLite3. Here is a simple example:
db:exec[=[
CREATE TABLE numbers(num1,num2);
INSERT INTO numbers VALUES(1,11);
INSERT INTO numbers VALUES(2,22);
INSERT INTO numbers VALUES(3,33);
]=]
local num_sum=0
local function oneRow(context,num) -- add one column in all rows
num_sum=num_sum+num
end
local function afterLast(context) -- return sum after last row has been processed
context:result_number(num_sum)
num_sum=0
end
db:create_aggregate("do_the_sums",1,oneRow,afterLast)
for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end
for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end
This code prints the follows:
Sum of col 1: 6
Sum of col 2: 66
db:create_collation(name,func)
This creates a collation callback. A collation callback is used to establish a collation order, mostly for string comparisons and sorting purposes. name is a string with the name of the collation to be created; func is a function that accepts two string arguments, compares them and returns 0 if both strings are identical, -1 if the first argument is lower in the collation order than the second and 1 if the first argument is higher in the collation order than the second. A simple example:
local function collate(s1,s2)
s1=s1:lower()
s2=s2:lower()
if s1==s2 then return 0
elseif s1<s2 then return -1
else return 1 end
end
db:exec[=[
CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS);
INSERT INTO test VALUES(NULL,'hello world');
INSERT INTO test VALUES(NULL,'Buenos dias');
INSERT INTO test VALUES(NULL,'HELLO WORLD');
]=]
db:create_collation('CINSENS',collate)
for row in db:nrows('SELECT * FROM test') do print(row.id,row.content) end
db:create_function(name,nargs,func)
This function creates a callback function. Callback function is called by SQLite3 once for every row in a query. name is a string with the name of the callback function as given in an SQL statement; nargs is the number of arguments this call will provide. func is the actual Lua function that gets called once for every row; it should accept a function context (see Methods for Callback Contexts ) plus the same number of parameters as given in nargs. Here is an example:
db:exec'CREATE TABLE test(col1,col2,col3)'
db:exec'INSERT INTO test VALUES(1,2,4)'
db:exec'INSERT INTO test VALUES(2,4,9)'
db:exec'INSERT INTO test VALUES(3,6,16)'
db:create_function('sum_cols',3,function(ctx,a,b,c)
ctx:result_number(a+b+c)
end))
for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do
util.printf('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum)
end
db:errcode()
db:error_code()
Returns the numerical result code (or extended result code) for the most recent failed call associated with database db. See Numerical Error and Result Codes for details.
db:errmsg()
db:error_message()
Returns a string that contains an error message for the most recent failed call associated with database db.
See db:errcode .
See db:errmsg .
db:exec(sql[,func[,udata]])
db:execute(sql[,func[,udata]])
Compiles and executes the SQL statement(s) given in string sql. The statements are simply executed one after the other and not stored. The function returns sqlite3.OK on success or else a numerical error code (see Numerical Error and Result Codes ).
If one or more of the SQL statements are queries, then the callback function specified in func is invoked once for each row of the query result (if func is nil, no callback is invoked). The callback receives four arguments: udata (the third parameter of the db:exec() call), the number of columns in the row, a table with the column values and another table with the column names. The callback function should return 0. If the callback returns a non-zero value then the query is aborted, all subsequent SQL statements are skipped and db:exec() returns sqlite3.ABORT. Here is a simple example:
sql=[=[
CREATE TABLE numbers(num1,num2,str);
INSERT INTO numbers VALUES(1,11,"ABC");
INSERT INTO numbers VALUES(2,22,"DEF");
INSERT INTO numbers VALUES(3,33,"UVW");
INSERT INTO numbers VALUES(4,44,"XYZ");
SELECT * FROM numbers;
]=]
function showrow(udata,cols,values,names)
assert(udata=='test_udata')
print('exec:')
for i=1,cols do print('',names[i],values[i]) end
return 0
end
db:exec(sql,showrow,'test_udata')
See db:exec .
db:interrupt()
This function causes any pending database operation to abort and return at the next opportunity. This function returns nothing.
db:isopen()
Returns TRUE if database db is open, FALSE otherwise.
db:last_insert_rowid()
This function returns the rowid of the most recent INSERT into the database. If no inserts have ever occurred, 0 is returned. (Each row in an SQLite table has a unique 64-bit signed integer key called the ’rowid’. This ID is always available as an undeclared column named ROWID, OID, or _ROWID_. If the table has a column of type INTEGER PRIMARY KEY then that column is another alias for the rowid.)
If an INSERT occurs within a trigger, then the rowid of the inserted row is returned as long as the trigger is running. Once the trigger terminates, the value returned reverts to the last value inserted before the trigger fired.
db:nrows(sql)
Creates an iterator that returns the successive rows selected by the SQL statement given in string sql. Each call to the iterator returns a table in which the named fields correspond to the columns in the database. Here is an example:
db:exec[=[
CREATE TABLE numbers(num1,num2);
INSERT INTO numbers VALUES(1,11);
INSERT INTO numbers VALUES(2,22);
INSERT INTO numbers VALUES(3,33);
]=]
for a in db:nrows('SELECT * FROM numbers') do table.print(a) end
This script prints:
num2: 11
num1: 1
num2: 22
num1: 2
num2: 33
num1: 3
db:prepare(sql)
This function compiles the SQL statement in string sql into an internal representation and returns this as userdata. The returned object should be used for all further method calls in connection with this specific SQL statement (see Methods for Prepared Statements ).
db:progress_handler(n,func,udata)
This function installs a callback function func that is invoked periodically during long-running calls to db:exec or stmt:step . The progress callback is invoked once for every n internal operations, where n is the first argument to this function. udata is passed to the progress callback function each time it is invoked. If a call to db:exec() or stmt:step() results in fewer than n operations being executed, then the progress callback is never invoked. Only a single progress callback function may be registered for each opened database and a call to this function will overwrite any previously set callback function. To remove the progress callback altogether, pass nil as the second argument.
If the progress callback returns a result other than 0, then the current query is immediately terminated, any database changes are rolled back and the containing db:exec() or stmt:step() call returns sqlite3.INTERRUPT. This feature can be used to cancel long-running queries.
db:rows(sql)
Creates an iterator that returns the successive rows selected by the SQL statement given in string sql. Each call to the iterator returns a table in which the numerical indices 1 to n correspond to the selected columns 1 to n in the database. Here is an example:
db:exec[=[
CREATE TABLE numbers(num1,num2);
INSERT INTO numbers VALUES(1,11);
INSERT INTO numbers VALUES(2,22);
INSERT INTO numbers VALUES(3,33);
]=]
for a in db:rows('SELECT * FROM numbers') do table.print(a) end
This script prints:
1: 1
2: 11
1: 2
2: 22
1: 3
2: 33
db:total_changes()
This function returns the number of database rows that have been modified by INSERT, UPDATE or DELETE statements since the database was opened. This includes UPDATE, INSERT and DELETE statements executed as part of trigger programs. All changes are counted as soon as the statement that produces them is completed by calling either stmt:reset or stmt:finalize .
db:trace(func,udata)
This function installs a trace callback handler. func is a Lua function that is called by SQLite3 just before the evaluation of an SQL statement. This callback receives two arguments: the first is the udata argument used when the callback was installed; the second is a string with the SQL statement about to be executed.
db:urows(sql)
Creates an iterator that returns the successive rows selected by the SQL statement given in string sql. Each call to the iterator returns the values that correspond to the columns in the currently selected row. Here is an example:
db:exec[=[
CREATE TABLE numbers(num1,num2);
INSERT INTO numbers VALUES(1,11);
INSERT INTO numbers VALUES(2,22);
INSERT INTO numbers VALUES(3,33);
]=]
for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end
This script prints:
1 11
2 22
3 33