trunk/3rdparty/lsqlite3/doc/lsqlite3.html
| r0 | r242834 | |
| 1 | <HTML> |
| 2 | <HEAD> |
| 3 | <TITLE>LuaSQLite 3</TITLE> |
| 4 | <LINK REV="made" HREF="mailto:unknown@du216771.users"> |
| 5 | </HEAD> |
| 6 | |
| 7 | <BODY> |
| 8 | |
| 9 | <A NAME="__index__"></A> |
| 10 | <!-- INDEX BEGIN --> |
| 11 | |
| 12 | <UL> |
| 13 | |
| 14 | <LI><A HREF="#name">NAME</A></LI> |
| 15 | <LI><A HREF="#overview">OVERVIEW</A></LI> |
| 16 | <LI><A HREF="#download">DOWNLOAD</A></LI> |
| 17 | <LI><A HREF="#installation">INSTALLATION</A></LI> |
| 18 | <LI><A HREF="#examples">EXAMPLES</A></LI> |
| 19 | <LI><A HREF="#verification tests">VERIFICATION TESTS</A></LI> |
| 20 | <LI><A HREF="#reference">REFERENCE</A></LI> |
| 21 | <LI><A HREF="#sqlite3 functions">SQLite3 functions</A></LI> |
| 22 | <UL> |
| 23 | |
| 24 | <LI><A HREF="#sqlite3.complete">sqlite3.complete</A></LI> |
| 25 | <LI><A HREF="#sqlite3.open">sqlite3.open</A></LI> |
| 26 | <LI><A HREF="#sqlite3.open_memory">sqlite3.open_memory</A></LI> |
| 27 | <LI><A HREF="#sqlite3.temp_directory">sqlite3.temp_directory</A></LI> |
| 28 | <LI><A HREF="#sqlite3.version">sqlite3.version</A></LI> |
| 29 | </UL> |
| 30 | |
| 31 | <LI><A HREF="#database methods">Database methods</A></LI> |
| 32 | <UL> |
| 33 | |
| 34 | <LI><A HREF="#db:busy_handler">db:busy_handler</A></LI> |
| 35 | <LI><A HREF="#db:busy_timeout">db:busy_timeout</A></LI> |
| 36 | <LI><A HREF="#db:changes">db:changes</A></LI> |
| 37 | <LI><A HREF="#db:close">db:close</A></LI> |
| 38 | <LI><A HREF="#db:close_vm">db:close_vm</A></LI> |
| 39 | <LI><A HREF="#db:create_aggregate">db:create_aggregate</A></LI> |
| 40 | <LI><A HREF="#db:create_collation">db:create_collation</A></LI> |
| 41 | <LI><A HREF="#db:create_function">db:create_function</A></LI> |
| 42 | <LI><A HREF="#db:errcode">db:errcode</A></LI> |
| 43 | <LI><A HREF="#db:errmsg">db:errmsg</A></LI> |
| 44 | <LI><A HREF="#db:exec">db:exec</A></LI> |
| 45 | <LI><A HREF="#db:interrupt">db:interrupt</A></LI> |
| 46 | <LI><A HREF="#db:isopen">db:isopen</A></LI> |
| 47 | <LI><A HREF="#db:last_insert_rowid">db:last_insert_rowid</A></LI> |
| 48 | <LI><A HREF="#db:nrows">db:nrows</A></LI> |
| 49 | <LI><A HREF="#db:prepare">db:prepare</A></LI> |
| 50 | <LI><A HREF="#db:progress_handler">db:progress_handler</A></LI> |
| 51 | <LI><A HREF="#db:rows">db:rows</A></LI> |
| 52 | <LI><A HREF="#db:total_changes">db:total_changes</A></LI> |
| 53 | <LI><A HREF="#db:trace">db:trace</A></LI> |
| 54 | <LI><A HREF="#db:urows">db:urows</A></LI> |
| 55 | </UL> |
| 56 | |
| 57 | <LI><A HREF="#methods for prepared statements">Methods for prepared statements</A></LI> |
| 58 | <UL> |
| 59 | |
| 60 | <LI><A HREF="#stmt:bind">stmt:bind</A></LI> |
| 61 | <LI><A HREF="#stmt:bind_blob">stmt:bind_blob</A></LI> |
| 62 | <LI><A HREF="#stmt:bind_names">stmt:bind_names</A></LI> |
| 63 | <LI><A HREF="#stmt:bind_parameter_count">stmt:bind_parameter_count</A></LI> |
| 64 | <LI><A HREF="#stmt:bind_parameter_name">stmt:bind_parameter_name</A></LI> |
| 65 | <LI><A HREF="#stmt:bind_values">stmt:bind_values</A></LI> |
| 66 | <LI><A HREF="#stmt:columns">stmt:columns</A></LI> |
| 67 | <LI><A HREF="#stmt:finalize">stmt:finalize</A></LI> |
| 68 | <LI><A HREF="#stmt:get_name">stmt:get_name</A></LI> |
| 69 | <LI><A HREF="#stmt:get_named_types">stmt:get_named_types</A></LI> |
| 70 | <LI><A HREF="#stmt:get_named_values">stmt:get_named_values</A></LI> |
| 71 | <LI><A HREF="#stmt:get_names">stmt:get_names</A></LI> |
| 72 | <LI><A HREF="#stmt:get_type">stmt:get_type</A></LI> |
| 73 | <LI><A HREF="#stmt:get_types">stmt:get_types</A></LI> |
| 74 | <LI><A HREF="#stmt:get_unames">stmt:get_unames</A></LI> |
| 75 | <LI><A HREF="#stmt:get_utypes">stmt:get_utypes</A></LI> |
| 76 | <LI><A HREF="#stmt:get_uvalues">stmt:get_uvalues</A></LI> |
| 77 | <LI><A HREF="#stmt:get_value">stmt:get_value</A></LI> |
| 78 | <LI><A HREF="#stmt:get_values">stmt:get_values</A></LI> |
| 79 | <LI><A HREF="#stmt:isopen">stmt:isopen</A></LI> |
| 80 | <LI><A HREF="#stmt:nrows">stmt:nrows</A></LI> |
| 81 | <LI><A HREF="#stmt:reset">stmt:reset</A></LI> |
| 82 | <LI><A HREF="#stmt:rows">stmt:rows</A></LI> |
| 83 | <LI><A HREF="#stmt:step">stmt:step</A></LI> |
| 84 | <LI><A HREF="#stmt:urows">stmt:urows</A></LI> |
| 85 | </UL> |
| 86 | |
| 87 | <LI><A HREF="#methods for callback contexts">Methods for callback contexts</A></LI> |
| 88 | <UL> |
| 89 | |
| 90 | <LI><A HREF="#context:aggregate_count">context:aggregate_count</A></LI> |
| 91 | <LI><A HREF="#context:get_aggregate_data">context:get_aggregate_data</A></LI> |
| 92 | <LI><A HREF="#context:set_aggregate_data">context:set_aggregate_data</A></LI> |
| 93 | <LI><A HREF="#context:result">context:result</A></LI> |
| 94 | <LI><A HREF="#context:result_null">context:result_null</A></LI> |
| 95 | <LI><A HREF="#context:result_number">context:result_number</A></LI> |
| 96 | <LI><A HREF="#context:result_int">context:result_int</A></LI> |
| 97 | <LI><A HREF="#context:result_text">context:result_text</A></LI> |
| 98 | <LI><A HREF="#context:result_blob">context:result_blob</A></LI> |
| 99 | <LI><A HREF="#context:result_error">context:result_error</A></LI> |
| 100 | <LI><A HREF="#context:user_data">context:user_data</A></LI> |
| 101 | </UL> |
| 102 | |
| 103 | <LI><A HREF="#numerical error and result codes">Numerical error and result codes</A></LI> |
| 104 | <LI><A HREF="#version">VERSION</A></LI> |
| 105 | <LI><A HREF="#credits">CREDITS</A></LI> |
| 106 | <LI><A HREF="#license">LICENSE</A></LI> |
| 107 | </UL> |
| 108 | <!-- INDEX END --> |
| 109 | |
| 110 | <HR> |
| 111 | <P> |
| 112 | <HR> |
| 113 | <H1><A NAME="name">NAME</A></H1> |
| 114 | <P><STRONG>LuaSQLite 3</STRONG> - a Lua 5.1 wrapper for the SQLite3 library</P> |
| 115 | <P> |
| 116 | <HR> |
| 117 | <H1><A NAME="overview">OVERVIEW</A></H1> |
| 118 | <P><STRONG>LuaSQLite 3</STRONG> is a thin wrapper around the public domain SQLite3 |
| 119 | database engine.</P> |
| 120 | <P>The <CODE>lsqlite3</CODE> module supports the creation and manipulation of |
| 121 | SQLite3 databases. After a <CODE>require('lsqlite3')</CODE> the exported |
| 122 | functions are called with prefix <CODE>sqlite3</CODE>. However, most sqlite3 |
| 123 | functions are called via an object-oriented interface to either |
| 124 | database or SQL statement objects; see below for details.</P> |
| 125 | <P>This documentation does not attempt to describe how SQLite3 itself |
| 126 | works, it just describes the Lua binding and the available functions. |
| 127 | For more information about the SQL features supported by SQLite3 and |
| 128 | details about the syntax of SQL statements and queries, please see the |
| 129 | <STRONG>SQLite3 documentation</STRONG> <A HREF="http://www.sqlite.org/">http://www.sqlite.org/</A>. Using some of the |
| 130 | advanced features (how to use callbacks, for instance) will require |
| 131 | some familiarity with the SQLite3 API.</P> |
| 132 | <P> |
| 133 | <HR> |
| 134 | <H1><A NAME="download">DOWNLOAD</A></H1> |
| 135 | <P><STRONG>LuaSQLite 3</STRONG> source code can be downloaded from its |
| 136 | LuaForge (<A HREF="http://luaforge.net/projects/luasqlite/">http://luaforge.net/projects/luasqlite/</A>) page.</P> |
| 137 | <P>You will also need to build or obtain an SQLite3 loadable library |
| 138 | (DLL or .so). See <A HREF="http://www.sqlite.org/">http://www.sqlite.org/</A> for obtaining SQLite3 |
| 139 | source code or downloading a binary SQLite3 library.</P> |
| 140 | <P> |
| 141 | <HR> |
| 142 | <H1><A NAME="installation">INSTALLATION</A></H1> |
| 143 | <P>A <EM>Makefile</EM> is provided; it assumes an SQLite3 library is already |
| 144 | installed.</P> |
| 145 | <P> |
| 146 | <HR> |
| 147 | <H1><A NAME="examples">EXAMPLES</A></H1> |
| 148 | <P>The distribution contains an <EM>examples</EM> directory. The unit tests |
| 149 | also show some example use.</P> |
| 150 | <P> |
| 151 | <HR> |
| 152 | <H1><A NAME="verification tests">VERIFICATION TESTS</A></H1> |
| 153 | <P>The distribution contains some units tests using Michael Roth's |
| 154 | <CODE>lunit</CODE> (which is also included). Some of the tests were also derived |
| 155 | from Michael's <STRONG>lua-sqlite3</STRONG> module, and more unit tests added by |
| 156 | Doug Currie.</P> |
| 157 | <P>The distribution also contains some functional tests by Tiago.</P> |
| 158 | <P>This version of <CODE>lsqlite3</CODE> was tested with SQLite 3.4.2.</P> |
| 159 | <P> |
| 160 | <HR> |
| 161 | <H1><A NAME="reference">REFERENCE</A></H1> |
| 162 | <P> |
| 163 | <HR> |
| 164 | <H1><A NAME="sqlite3 functions">SQLite3 functions</A></H1> |
| 165 | <P> |
| 166 | <H2><A NAME="sqlite3.complete">sqlite3.complete</A></H2> |
| 167 | <PRE> |
| 168 | sqlite3.complete(sql)</PRE> |
| 169 | <P>Returns true if the string <CODE>sql</CODE> comprises one or more complete SQL |
| 170 | statements and false otherwise.</P> |
| 171 | <P> |
| 172 | <H2><A NAME="sqlite3.open">sqlite3.open</A></H2> |
| 173 | <PRE> |
| 174 | sqlite3.open(filename)</PRE> |
| 175 | <P>Opens (or creates if it does not exist) an SQLite database with name |
| 176 | <CODE>filename</CODE> and returns its handle as userdata (the returned object |
| 177 | should be used for all further method calls in connection with this |
| 178 | specific database, see <A HREF="#database methods">Database methods</A>). Example:</P> |
| 179 | <PRE> |
| 180 | myDB=sqlite3.open('MyDatabase.sqlite3') -- open |
| 181 | -- do some database calls... |
| 182 | myDB:close() -- close</PRE> |
| 183 | <P>In case of an error, the function returns nil, an error code and an |
| 184 | error message.</P> |
| 185 | <P> |
| 186 | <H2><A NAME="sqlite3.open_memory">sqlite3.open_memory</A></H2> |
| 187 | <PRE> |
| 188 | sqlite3.open_memory()</PRE> |
| 189 | <P>Opens an SQLite database <STRONG>in memory</STRONG> and returns its handle as |
| 190 | userdata. In case of an error, the function returns nil, an error code |
| 191 | and an error message. (In-memory databases are volatile as they are |
| 192 | never stored on disk.)</P> |
| 193 | <P> |
| 194 | <H2><A NAME="sqlite3.temp_directory">sqlite3.temp_directory</A></H2> |
| 195 | <PRE> |
| 196 | sqlite3.temp_directory([temp])</PRE> |
| 197 | <P>Sets or queries the directory used by SQLite for temporary files. If |
| 198 | string <CODE>temp</CODE> is a directory name or nil, the temporary directory is |
| 199 | set accordingly and the old value is returned. If <CODE>temp</CODE> is missing, |
| 200 | the function simply returns the current temporary directory.</P> |
| 201 | <P> |
| 202 | <H2><A NAME="sqlite3.version">sqlite3.version</A></H2> |
| 203 | <PRE> |
| 204 | sqlite3.version()</PRE> |
| 205 | <P>Returns a string with SQLite version information, in the form 'x.y[.z]'.</P> |
| 206 | <P> |
| 207 | <HR> |
| 208 | <H1><A NAME="database methods">Database methods</A></H1> |
| 209 | <P>After opening a database with <A HREF="#sqlite3.open"><CODE>sqlite3.open()</CODE></A> or |
| 210 | <A HREF="#sqlite3.open_memory"><CODE>sqlite3.open_memory()</CODE></A> |
| 211 | the returned database object should be used for all further method calls |
| 212 | in connection with that database. An open database object supports the |
| 213 | following methods.</P> |
| 214 | <P> |
| 215 | <H2><A NAME="db:busy_handler">db:busy_handler</A></H2> |
| 216 | <PRE> |
| 217 | db:busy_handler([func[,udata]])</PRE> |
| 218 | <P>Sets or removes a busy handler for a database. <CODE>func</CODE> is either a Lua |
| 219 | function that implements the busy handler or nil to remove a previously |
| 220 | set handler. This function returns nothing.</P> |
| 221 | <P>The handler function is called with two parameters: <CODE>udata</CODE> and the |
| 222 | number of (re-)tries for a pending transaction. It should return nil, |
| 223 | false or 0 if the transaction is to be aborted. All other values will |
| 224 | result in another attempt to perform the transaction. (See the SQLite |
| 225 | documentation for important hints about writing busy handlers.)</P> |
| 226 | <P> |
| 227 | <H2><A NAME="db:busy_timeout">db:busy_timeout</A></H2> |
| 228 | <PRE> |
| 229 | db:busy_timeout(t)</PRE> |
| 230 | <P>Sets a busy handler that waits for <CODE>t</CODE> milliseconds if a transaction |
| 231 | cannot proceed. Calling this function will remove any busy handler set |
| 232 | by <A HREF="#db:busy_handler"><CODE>db:busy_handler()</CODE></A>; calling it with an argument |
| 233 | less than or equal to 0 will turn off all busy handlers.</P> |
| 234 | <P> |
| 235 | <H2><A NAME="db:changes">db:changes</A></H2> |
| 236 | <PRE> |
| 237 | db:changes()</PRE> |
| 238 | <P>This function returns the number of database rows that were changed (or |
| 239 | inserted or deleted) by the most recent SQL statement. Only changes that |
| 240 | are directly specified by INSERT, UPDATE, or DELETE statements are |
| 241 | counted. Auxiliary changes caused by triggers are not counted. Use |
| 242 | <A HREF="#db:total_changes"><CODE>db:total_changes()</CODE></A> to find the total number of |
| 243 | changes.</P> |
| 244 | <P> |
| 245 | <H2><A NAME="db:close">db:close</A></H2> |
| 246 | <PRE> |
| 247 | db:close()</PRE> |
| 248 | <P>Closes a database. All SQL statements prepared using |
| 249 | <A HREF="#db:prepare"><CODE>db:prepare()</CODE></A> should |
| 250 | have been finalized before this function is called. The function returns |
| 251 | <CODE>sqlite3.OK</CODE> on success or else a numerical error code (see the list of |
| 252 | <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P> |
| 253 | <P> |
| 254 | <H2><A NAME="db:close_vm">db:close_vm</A></H2> |
| 255 | <PRE> |
| 256 | db:close_vm(temponly)</PRE> |
| 257 | <P>Finalizes all statements that have not been explicitly finalized. If |
| 258 | <CODE>temponly</CODE> is true, only internal, temporary statements are finalized. |
| 259 | This function returns nothing.</P> |
| 260 | <P> |
| 261 | <H2><A NAME="db:create_aggregate">db:create_aggregate</A></H2> |
| 262 | <PRE> |
| 263 | db:create_aggregate(name,nargs,step,final)</PRE> |
| 264 | <P>This function creates an aggregate callback function. Aggregates perform |
| 265 | an operation over all rows in a query. <CODE>name</CODE> is a string with the name |
| 266 | of the aggregate function as given in an SQL statement; <CODE>nargs</CODE> is the |
| 267 | number of arguments this call will provide. <CODE>step</CODE> is the actual Lua |
| 268 | function that gets called once for every row; it should accept a function |
| 269 | context (see <A HREF="#methods for callback contexts">Methods for callback contexts</A>) plus the same number of |
| 270 | parameters as given in <CODE>nargs</CODE>. <CODE>final</CODE> is a function that is called |
| 271 | once after all rows have been processed; it receives one argument, the |
| 272 | function context.</P> |
| 273 | <P>The function context can be used inside the two callback functions to |
| 274 | communicate with SQLite3. Here is a simple example:</P> |
| 275 | <PRE> |
| 276 | db:exec[=[ |
| 277 | CREATE TABLE numbers(num1,num2); |
| 278 | INSERT INTO numbers VALUES(1,11); |
| 279 | INSERT INTO numbers VALUES(2,22); |
| 280 | INSERT INTO numbers VALUES(3,33); |
| 281 | ]=] |
| 282 | local num_sum=0 |
| 283 | local function oneRow(context,num) -- add one column in all rows |
| 284 | num_sum=num_sum+num |
| 285 | end |
| 286 | local function afterLast(context) -- return sum after last row has been processed |
| 287 | context:result_number(num_sum) |
| 288 | num_sum=0 |
| 289 | end |
| 290 | db:create_aggregate("do_the_sums",1,oneRow,afterLast) |
| 291 | for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end |
| 292 | for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end</PRE> |
| 293 | <P>This prints:</P> |
| 294 | <PRE> |
| 295 | Sum of col 1: 6 |
| 296 | Sum of col 2: 66</PRE> |
| 297 | <P> |
| 298 | <H2><A NAME="db:create_collation">db:create_collation</A></H2> |
| 299 | <PRE> |
| 300 | db:create_collation(name,func)</PRE> |
| 301 | <P>This creates a collation callback. A collation callback is used to |
| 302 | establish a collation order, mostly for string comparisons and sorting |
| 303 | purposes. <CODE>name</CODE> is a string with the name of the collation to be created; |
| 304 | <CODE>func</CODE> is a function that accepts two string arguments, compares them |
| 305 | and returns 0 if both strings are identical, -1 if the first argument is |
| 306 | lower in the collation order than the second and 1 if the first argument |
| 307 | is higher in the collation order than the second. A simple example:</P> |
| 308 | <PRE> |
| 309 | local function collate(s1,s2) |
| 310 | s1=s1:lower() |
| 311 | s2=s2:lower() |
| 312 | if s1==s2 then return 0 |
| 313 | elseif s1<s2 then return -1 |
| 314 | else return 1 end |
| 315 | end |
| 316 | db:exec[=[ |
| 317 | CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS); |
| 318 | INSERT INTO test VALUES(NULL,'hello world'); |
| 319 | INSERT INTO test VALUES(NULL,'Buenos dias'); |
| 320 | INSERT INTO test VALUES(NULL,'HELLO WORLD'); |
| 321 | ]=] |
| 322 | db:create_collation('CINSENS',collate) |
| 323 | for row in db:nrows('SELECT * FROM test') do print(row.id,row.content) end</PRE> |
| 324 | <P> |
| 325 | <H2><A NAME="db:create_function">db:create_function</A></H2> |
| 326 | <PRE> |
| 327 | db:create_function(name,nargs,func)</PRE> |
| 328 | <P>This function creates a callback function. Callback function are called |
| 329 | by SQLite3 once for every row in a query. <CODE>name</CODE> is a string with the |
| 330 | name of the callback function as given in an SQL statement; <CODE>nargs</CODE> is |
| 331 | the number of arguments this call will provide. <CODE>func</CODE> is the actual Lua |
| 332 | function that gets called once for every row; it should accept a |
| 333 | function context (see <A HREF="#methods for callback contexts">Methods for callback contexts</A>) plus the same |
| 334 | number of parameters as given in nargs. Here is an example:</P> |
| 335 | <PRE> |
| 336 | db:exec'CREATE TABLE test(col1,col2,col3)' |
| 337 | db:exec'INSERT INTO test VALUES(1,2,4)' |
| 338 | db:exec'INSERT INTO test VALUES(2,4,9)' |
| 339 | db:exec'INSERT INTO test VALUES(3,6,16)' |
| 340 | db:create_function('sum_cols',3,function(ctx,a,b,c) |
| 341 | ctx:result_number(a+b+c) |
| 342 | end)) |
| 343 | for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do |
| 344 | util.printf('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum) |
| 345 | end</PRE> |
| 346 | <P> |
| 347 | <H2><A NAME="db:errcode">db:errcode</A></H2> |
| 348 | <PRE> |
| 349 | db:errcode() |
| 350 | db:error_code()</PRE> |
| 351 | <P>Returns the numerical result code (or extended result code) for the most |
| 352 | recent failed call associated with database db. See |
| 353 | <A HREF="#numerical error and result codes">Numerical error and result codes</A> for details.</P> |
| 354 | <P> |
| 355 | <H2><A NAME="db:errmsg">db:errmsg</A></H2> |
| 356 | <PRE> |
| 357 | db:errmsg() |
| 358 | db:error_message()</PRE> |
| 359 | <P>Returns a string that contains an error message for the most recent |
| 360 | failed call associated with database db.</P> |
| 361 | <P> |
| 362 | <H2><A NAME="db:exec">db:exec</A></H2> |
| 363 | <PRE> |
| 364 | db:exec(sql[,func[,udata]]) |
| 365 | db:execute(sql[,func[,udata]])</PRE> |
| 366 | <P>Compiles and executes the SQL <CODE>statement(s)</CODE> given in string <CODE>sql</CODE>. The |
| 367 | statements are simply executed one after the other and not stored. The |
| 368 | function returns <CODE>sqlite3.OK</CODE> on success or else a numerical error code |
| 369 | (see <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P> |
| 370 | <P>If one or more of the SQL statements are queries, then the callback |
| 371 | function specified in <CODE>func</CODE> is invoked once for each row of the query |
| 372 | result (if <CODE>func</CODE> is nil, no callback is invoked). The callback receives |
| 373 | four arguments: <CODE>udata</CODE> (the third parameter of the <CODE>db:exec()</CODE> call), |
| 374 | the number of columns in the row, a table with the column values and |
| 375 | another table with the column names. The callback function should return |
| 376 | 0. If the callback returns a non-zero value then the query is aborted, |
| 377 | all subsequent SQL statements are skipped and <CODE>db:exec()</CODE> returns |
| 378 | <CODE>sqlite3.ABORT</CODE>. Here is a simple example:</P> |
| 379 | <PRE> |
| 380 | sql=[=[ |
| 381 | CREATE TABLE numbers(num1,num2,str); |
| 382 | INSERT INTO numbers VALUES(1,11,"ABC"); |
| 383 | INSERT INTO numbers VALUES(2,22,"DEF"); |
| 384 | INSERT INTO numbers VALUES(3,33,"UVW"); |
| 385 | INSERT INTO numbers VALUES(4,44,"XYZ"); |
| 386 | SELECT * FROM numbers; |
| 387 | ]=] |
| 388 | function showrow(udata,cols,values,names) |
| 389 | assert(udata=='test_udata') |
| 390 | print('exec:') |
| 391 | for i=1,cols do print('',names[i],values[i]) end |
| 392 | return 0 |
| 393 | end |
| 394 | db:exec(sql,showrow,'test_udata')</PRE> |
| 395 | <P> |
| 396 | <H2><A NAME="db:interrupt">db:interrupt</A></H2> |
| 397 | <PRE> |
| 398 | db:interrupt()</PRE> |
| 399 | <P>This function causes any pending database operation to abort and return |
| 400 | at the next opportunity. This function returns nothing.</P> |
| 401 | <P> |
| 402 | <H2><A NAME="db:isopen">db:isopen</A></H2> |
| 403 | <PRE> |
| 404 | db:isopen()</PRE> |
| 405 | <P>Returns true if database db is open, false otherwise.</P> |
| 406 | <P> |
| 407 | <H2><A NAME="db:last_insert_rowid">db:last_insert_rowid</A></H2> |
| 408 | <PRE> |
| 409 | db:last_insert_rowid()</PRE> |
| 410 | <P>This function returns the rowid of the most recent INSERT into the |
| 411 | database. If no inserts have ever occurred, 0 is returned. (Each row in |
| 412 | an SQLite table has a unique 64-bit signed integer key called the |
| 413 | 'rowid'. This id is always available as an undeclared column named |
| 414 | ROWID, OID, or _ROWID_. If the table has a column of type INTEGER |
| 415 | PRIMARY KEY then that column is another alias for the rowid.)</P> |
| 416 | <P>If an INSERT occurs within a trigger, then the rowid of the inserted row |
| 417 | is returned as long as the trigger is running. Once the trigger |
| 418 | terminates, the value returned reverts to the last value inserted before |
| 419 | the trigger fired.</P> |
| 420 | <P> |
| 421 | <H2><A NAME="db:nrows">db:nrows</A></H2> |
| 422 | <PRE> |
| 423 | db:nrows(sql)</PRE> |
| 424 | <P>Creates an iterator that returns the successive rows selected by the SQL |
| 425 | statement given in string <CODE>sql</CODE>. Each call to the iterator returns a |
| 426 | table in which the named fields correspond to the columns in the database. |
| 427 | Here is an example:</P> |
| 428 | <PRE> |
| 429 | db:exec[=[ |
| 430 | CREATE TABLE numbers(num1,num2); |
| 431 | INSERT INTO numbers VALUES(1,11); |
| 432 | INSERT INTO numbers VALUES(2,22); |
| 433 | INSERT INTO numbers VALUES(3,33); |
| 434 | ]=] |
| 435 | for a in db:nrows('SELECT * FROM numbers') do table.print(a) end</PRE> |
| 436 | <P>This script prints:</P> |
| 437 | <PRE> |
| 438 | num2: 11 |
| 439 | num1: 1 |
| 440 | num2: 22 |
| 441 | num1: 2 |
| 442 | num2: 33 |
| 443 | num1: 3</PRE> |
| 444 | <P> |
| 445 | <H2><A NAME="db:prepare">db:prepare</A></H2> |
| 446 | <PRE> |
| 447 | db:prepare(sql)</PRE> |
| 448 | <P>This function compiles the SQL statement in string <CODE>sql</CODE> into an internal |
| 449 | representation and returns this as userdata. The returned object should |
| 450 | be used for all further method calls in connection with this specific |
| 451 | SQL statement (see <A HREF="#methods for prepared statements">Methods for prepared statements</A>).</P> |
| 452 | <P> |
| 453 | <H2><A NAME="db:progress_handler">db:progress_handler</A></H2> |
| 454 | <PRE> |
| 455 | db:progress_handler(n,func,udata)</PRE> |
| 456 | <P>This function installs a callback function <CODE>func</CODE> that is invoked |
| 457 | periodically during long-running calls to <A HREF="#db:exec"><CODE>db:exec()</CODE></A> |
| 458 | or <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A>. The |
| 459 | progress callback is invoked once for every <CODE>n</CODE> internal operations, |
| 460 | where <CODE>n</CODE> is the first argument to this function. <CODE>udata</CODE> is passed to |
| 461 | the progress callback function each time it is invoked. If a call to |
| 462 | <CODE>db:exec()</CODE> or <CODE>stmt:step()</CODE> results in fewer than <CODE>n</CODE> operations |
| 463 | being executed, then the progress callback is never invoked. Only a |
| 464 | single progress callback function may be registered for each opened |
| 465 | database and a call to this function will overwrite any previously set |
| 466 | callback function. To remove the progress callback altogether, pass nil |
| 467 | as the second argument.</P> |
| 468 | <P>If the progress callback returns a result other than 0, then the current |
| 469 | query is immediately terminated, any database changes are rolled back |
| 470 | and the containing <CODE>db:exec()</CODE> or <CODE>stmt:step()</CODE> call returns |
| 471 | <CODE>sqlite3.INTERRUPT</CODE>. This feature can be used to cancel long-running |
| 472 | queries.</P> |
| 473 | <P> |
| 474 | <H2><A NAME="db:rows">db:rows</A></H2> |
| 475 | <PRE> |
| 476 | db:rows(sql)</PRE> |
| 477 | <P>Creates an iterator that returns the successive rows selected by the SQL |
| 478 | statement given in string <CODE>sql</CODE>. Each call to the iterator returns a table |
| 479 | in which the numerical indices 1 to n correspond to the selected columns |
| 480 | 1 to n in the database. Here is an example:</P> |
| 481 | <PRE> |
| 482 | db:exec[=[ |
| 483 | CREATE TABLE numbers(num1,num2); |
| 484 | INSERT INTO numbers VALUES(1,11); |
| 485 | INSERT INTO numbers VALUES(2,22); |
| 486 | INSERT INTO numbers VALUES(3,33); |
| 487 | ]=] |
| 488 | for a in db:rows('SELECT * FROM numbers') do table.print(a) end</PRE> |
| 489 | <P>This script prints:</P> |
| 490 | <PRE> |
| 491 | 1: 1 |
| 492 | 2: 11 |
| 493 | 1: 2 |
| 494 | 2: 22 |
| 495 | 1: 3 |
| 496 | 2: 33</PRE> |
| 497 | <P> |
| 498 | <H2><A NAME="db:total_changes">db:total_changes</A></H2> |
| 499 | <PRE> |
| 500 | db:total_changes()</PRE> |
| 501 | <P>This function returns the number of database rows that have been |
| 502 | modified by INSERT, UPDATE or DELETE statements since the database was |
| 503 | opened. This includes UPDATE, INSERT and DELETE statements executed as |
| 504 | part of trigger programs. All changes are counted as soon as the |
| 505 | statement that produces them is completed by calling either |
| 506 | <A HREF="#stmt:reset"><CODE>stmt:reset()</CODE></A> or <A HREF="#stmt:finalize"><CODE>stmt:finalize()</CODE></A>.</P> |
| 507 | <P> |
| 508 | <H2><A NAME="db:trace">db:trace</A></H2> |
| 509 | <PRE> |
| 510 | db:trace(func,udata)</PRE> |
| 511 | <P>This function installs a trace callback handler. <CODE>func</CODE> is a Lua |
| 512 | function that is called by SQLite3 just before the evaluation of an SQL |
| 513 | statement. This callback receives two arguments: the first is the |
| 514 | <CODE>udata</CODE> argument used when the callback was installed; the second is a |
| 515 | string with the SQL statement about to be executed.</P> |
| 516 | <P> |
| 517 | <H2><A NAME="db:urows">db:urows</A></H2> |
| 518 | <PRE> |
| 519 | db:urows(sql)</PRE> |
| 520 | <P>Creates an iterator that returns the successive rows selected by the SQL |
| 521 | statement given in string <CODE>sql</CODE>. Each call to the iterator returns the |
| 522 | values that correspond to the columns in the currently selected row. |
| 523 | Here is an example:</P> |
| 524 | <PRE> |
| 525 | db:exec[=[ |
| 526 | CREATE TABLE numbers(num1,num2); |
| 527 | INSERT INTO numbers VALUES(1,11); |
| 528 | INSERT INTO numbers VALUES(2,22); |
| 529 | INSERT INTO numbers VALUES(3,33); |
| 530 | ]=] |
| 531 | for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end</PRE> |
| 532 | <P>This script prints:</P> |
| 533 | <PRE> |
| 534 | 1 11 |
| 535 | 2 22 |
| 536 | 3 33</PRE> |
| 537 | <P> |
| 538 | <HR> |
| 539 | <H1><A NAME="methods for prepared statements">Methods for prepared statements</A></H1> |
| 540 | <P>After creating a prepared statement with <A HREF="#db:prepare"><CODE>db:prepare()</CODE></A> |
| 541 | the returned statement object should be used for all further calls in |
| 542 | connection with that statement. Statement objects support the following |
| 543 | methods.</P> |
| 544 | <P> |
| 545 | <H2><A NAME="stmt:bind">stmt:bind</A></H2> |
| 546 | <PRE> |
| 547 | stmt:bind(n[,value])</PRE> |
| 548 | <P>Binds value to statement parameter <CODE>n</CODE>. If the type of value is string |
| 549 | or number, it is bound as text or double, respectively. If <CODE>value</CODE> is a |
| 550 | boolean or nil or missing, any previous binding is removed. The function |
| 551 | returns <CODE>sqlite3.OK</CODE> on success or else a numerical error code (see |
| 552 | <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P> |
| 553 | <P> |
| 554 | <H2><A NAME="stmt:bind_blob">stmt:bind_blob</A></H2> |
| 555 | <PRE> |
| 556 | stmt:bind_blob(n,blob)</PRE> |
| 557 | <P>Binds string <CODE>blob</CODE> (which can be a binary string) as a blob to |
| 558 | statement parameter <CODE>n</CODE>. The function returns <CODE>sqlite3.OK</CODE> on success |
| 559 | or else a numerical error code (see <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P> |
| 560 | <P> |
| 561 | <H2><A NAME="stmt:bind_names">stmt:bind_names</A></H2> |
| 562 | <PRE> |
| 563 | stmt:bind_names(nametable)</PRE> |
| 564 | <P>Binds the values in <CODE>nametable</CODE> to statement parameters. If the |
| 565 | statement parameters are named (i.e., of the form ``:AAA'' or ``$AAA'') |
| 566 | then this function looks for appropriately named fields in <CODE>nametable</CODE>; |
| 567 | if the statement parameters are |
| 568 | not named, it looks for numerical fields 1 to the number of statement |
| 569 | parameters. The function returns <CODE>sqlite3.OK</CODE> on success or else a |
| 570 | numerical error code (see <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P> |
| 571 | <P> |
| 572 | <H2><A NAME="stmt:bind_parameter_count">stmt:bind_parameter_count</A></H2> |
| 573 | <PRE> |
| 574 | stmt:bind_parameter_count()</PRE> |
| 575 | <P>Returns the largest statement parameter index in prepared statement |
| 576 | <CODE>stmt</CODE>. When the statement parameters are of the forms ``:AAA'' or ``?'', |
| 577 | then they are assigned sequentially increasing numbers beginning with |
| 578 | one, so the value returned is the number of parameters. However if the |
| 579 | same statement parameter name is used multiple times, each occurrence |
| 580 | is given the same number, so the value returned is the number of unique |
| 581 | statement parameter names.</P> |
| 582 | <P>If statement parameters of the form ``?NNN'' are used (where NNN is an |
| 583 | integer) then there might be gaps in the numbering and the value |
| 584 | returned by this interface is the index of the statement parameter with |
| 585 | the largest index value.</P> |
| 586 | <P> |
| 587 | <H2><A NAME="stmt:bind_parameter_name">stmt:bind_parameter_name</A></H2> |
| 588 | <PRE> |
| 589 | stmt:bind_parameter_name(n)</PRE> |
| 590 | <P>Returns the name of the <CODE>n</CODE>-th parameter in prepared statement <CODE>stmt</CODE>. |
| 591 | Statement parameters of the form ``:AAA'' or ``@AAA'' or ``$VVV'' have a name |
| 592 | which is the string ``:AAA'' or ``@AAA'' or ``$VVV''. In other words, the |
| 593 | initial ``:'' or ``$'' or ``@'' is included as part of the name. Parameters |
| 594 | of the form ``?'' or ``?NNN'' have no name. The first bound parameter has |
| 595 | an index of 1. |
| 596 | If the value <CODE>n</CODE> is out of range or if the <CODE>n</CODE>-th parameter is |
| 597 | nameless, then nil is returned. The function returns <CODE>sqlite3.OK</CODE> on |
| 598 | success or else a numerical error code (see |
| 599 | <A HREF="#numerical error and result codes">Numerical error and result codes</A>)</P> |
| 600 | <P> |
| 601 | <H2><A NAME="stmt:bind_values">stmt:bind_values</A></H2> |
| 602 | <PRE> |
| 603 | stmt:bind_values(value1,value2,...,valueN)</PRE> |
| 604 | <P>Binds the given values to statement parameters. The function returns |
| 605 | <CODE>sqlite3.OK</CODE> on success or else a numerical error code (see |
| 606 | <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P> |
| 607 | <P> |
| 608 | <H2><A NAME="stmt:columns">stmt:columns</A></H2> |
| 609 | <PRE> |
| 610 | stmt:columns()</PRE> |
| 611 | <P>Returns the number of columns in the result set returned by statement |
| 612 | stmt or 0 if the statement does not return data (for example an UPDATE).</P> |
| 613 | <P> |
| 614 | <H2><A NAME="stmt:finalize">stmt:finalize</A></H2> |
| 615 | <PRE> |
| 616 | stmt:finalize()</PRE> |
| 617 | <P>This function frees prepared statement stmt. If the statement was |
| 618 | executed successfully, or not executed at all, then <CODE>sqlite3.OK</CODE> is |
| 619 | returned. If execution of the statement failed then an error code is |
| 620 | returned.</P> |
| 621 | <P> |
| 622 | <H2><A NAME="stmt:get_name">stmt:get_name</A></H2> |
| 623 | <PRE> |
| 624 | stmt:get_name(n)</PRE> |
| 625 | <P>Returns the name of column <CODE>n</CODE> in the result set of statement stmt. (The |
| 626 | left-most column is number 0.)</P> |
| 627 | <P> |
| 628 | <H2><A NAME="stmt:get_named_types">stmt:get_named_types</A></H2> |
| 629 | <PRE> |
| 630 | stmt:get_named_types()</PRE> |
| 631 | <P>Returns a table with the names and types of all columns in the result |
| 632 | set of statement stmt.</P> |
| 633 | <P> |
| 634 | <H2><A NAME="stmt:get_named_values">stmt:get_named_values</A></H2> |
| 635 | <PRE> |
| 636 | stmt:get_named_values()</PRE> |
| 637 | <P>This function returns a table with names and values of all columns in |
| 638 | the current result row of a query.</P> |
| 639 | <P> |
| 640 | <H2><A NAME="stmt:get_names">stmt:get_names</A></H2> |
| 641 | <PRE> |
| 642 | stmt:get_names()</PRE> |
| 643 | <P>This function returns an array with the names of all columns in the |
| 644 | result set returned by statement stmt.</P> |
| 645 | <P> |
| 646 | <H2><A NAME="stmt:get_type">stmt:get_type</A></H2> |
| 647 | <PRE> |
| 648 | stmt:get_type(n)</PRE> |
| 649 | <P>Returns the type of column <CODE>n</CODE> in the result set of statement stmt. (The |
| 650 | left-most column is number 0.)</P> |
| 651 | <P> |
| 652 | <H2><A NAME="stmt:get_types">stmt:get_types</A></H2> |
| 653 | <PRE> |
| 654 | stmt:get_types()</PRE> |
| 655 | <P>This function returns an array with the types of all columns in the |
| 656 | result set returned by statement stmt.</P> |
| 657 | <P> |
| 658 | <H2><A NAME="stmt:get_unames">stmt:get_unames</A></H2> |
| 659 | <PRE> |
| 660 | stmt:get_unames()</PRE> |
| 661 | <P>This function returns a list with the names of all columns in the result |
| 662 | set returned by statement stmt.</P> |
| 663 | <P> |
| 664 | <H2><A NAME="stmt:get_utypes">stmt:get_utypes</A></H2> |
| 665 | <PRE> |
| 666 | stmt:get_utypes()</PRE> |
| 667 | <P>This function returns a list with the types of all columns in the result |
| 668 | set returned by statement stmt.</P> |
| 669 | <P> |
| 670 | <H2><A NAME="stmt:get_uvalues">stmt:get_uvalues</A></H2> |
| 671 | <PRE> |
| 672 | stmt:get_uvalues()</PRE> |
| 673 | <P>This function returns a list with the values of all columns in the |
| 674 | current result row of a query.</P> |
| 675 | <P> |
| 676 | <H2><A NAME="stmt:get_value">stmt:get_value</A></H2> |
| 677 | <PRE> |
| 678 | stmt:get_value(n)</PRE> |
| 679 | <P>Returns the value of column <CODE>n</CODE> in the result set of statement stmt. (The |
| 680 | left-most column is number 0.)</P> |
| 681 | <P> |
| 682 | <H2><A NAME="stmt:get_values">stmt:get_values</A></H2> |
| 683 | <PRE> |
| 684 | stmt:get_values()</PRE> |
| 685 | <P>This function returns an array with the values of all columns in the |
| 686 | result set returned by statement stmt.</P> |
| 687 | <P> |
| 688 | <H2><A NAME="stmt:isopen">stmt:isopen</A></H2> |
| 689 | <PRE> |
| 690 | stmt:isopen()</PRE> |
| 691 | <P>Returns true if stmt has not yet been finalized, false otherwise.</P> |
| 692 | <P> |
| 693 | <H2><A NAME="stmt:nrows">stmt:nrows</A></H2> |
| 694 | <PRE> |
| 695 | stmt:nrows()</PRE> |
| 696 | <P>Returns an function that iterates over the names and values of the |
| 697 | result set of statement <CODE>stmt</CODE>. Each iteration returns a table with the |
| 698 | names and values for the current row. |
| 699 | This is the prepared statement equivalent of <A HREF="#db:nrows"><CODE>db:nrows()</CODE></A>.</P> |
| 700 | <P> |
| 701 | <H2><A NAME="stmt:reset">stmt:reset</A></H2> |
| 702 | <PRE> |
| 703 | stmt:reset()</PRE> |
| 704 | <P>This function resets SQL statement <CODE>stmt</CODE>, so that it is ready to be |
| 705 | re-executed. Any statement variables that had values bound to them using |
| 706 | the <CODE>stmt:bind*()</CODE> functions retain their values.</P> |
| 707 | <P> |
| 708 | <H2><A NAME="stmt:rows">stmt:rows</A></H2> |
| 709 | <PRE> |
| 710 | stmt:rows()</PRE> |
| 711 | <P>Returns an function that iterates over the values of the result set of |
| 712 | statement stmt. Each iteration returns an array with the values for the |
| 713 | current row. |
| 714 | This is the prepared statement equivalent of <A HREF="#db:rows"><CODE>db:rows()</CODE></A>.</P> |
| 715 | <P> |
| 716 | <H2><A NAME="stmt:step">stmt:step</A></H2> |
| 717 | <PRE> |
| 718 | stmt:step()</PRE> |
| 719 | <P>This function must be called to evaluate the (next iteration of the) |
| 720 | prepared statement stmt. It will return one of the following values:</P> |
| 721 | <UL> |
| 722 | <LI> |
| 723 | <CODE>sqlite3.BUSY</CODE>: the engine was unable to acquire the locks needed. If the |
| 724 | statement is a COMMIT or occurs outside of an explicit transaction, then |
| 725 | you can retry the statement. If the statement is not a COMMIT and occurs |
| 726 | within a explicit transaction then you should rollback the transaction |
| 727 | before continuing. |
| 728 | <P></P> |
| 729 | <LI> |
| 730 | <CODE>sqlite3.DONE</CODE>: the statement has finished executing successfully. |
| 731 | <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> should not be called again on this statement |
| 732 | without first calling <A HREF="#stmt:reset"><CODE>stmt:reset()</CODE></A> to reset the virtual |
| 733 | machine back to the initial state. |
| 734 | <P></P> |
| 735 | <LI> |
| 736 | <CODE>sqlite3.ROW</CODE>: this is returned each time a new row of data is ready for |
| 737 | processing by the caller. The values may be accessed using the column |
| 738 | access functions. <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> can be called again to |
| 739 | retrieve the next row of data. |
| 740 | <P></P> |
| 741 | <LI> |
| 742 | <CODE>sqlite3.ERROR</CODE>: a run-time error (such as a constraint violation) has |
| 743 | occurred. <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> should not be called again. More |
| 744 | information may be found by calling <A HREF="#db:errmsg"><CODE>db:errmsg()</CODE></A>. A more |
| 745 | specific error |
| 746 | code (can be obtained by calling <A HREF="#stmt:reset"><CODE>stmt:reset()</CODE></A>. |
| 747 | <P></P> |
| 748 | <LI> |
| 749 | <CODE>sqlite3.MISUSE</CODE>: the function was called inappropriately, perhaps |
| 750 | because the statement has already been finalized or a previous call to |
| 751 | <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> has returned <CODE>sqlite3.ERROR</CODE> or |
| 752 | <CODE>sqlite3.DONE</CODE>. |
| 753 | <P></P></UL> |
| 754 | <P> |
| 755 | <H2><A NAME="stmt:urows">stmt:urows</A></H2> |
| 756 | <PRE> |
| 757 | stmt:urows()</PRE> |
| 758 | <P>Returns an function that iterates over the values of the result set of |
| 759 | statement stmt. Each iteration returns the values for the current row. |
| 760 | This is the prepared statement equivalent of <A HREF="#db:urows"><CODE>db:urows()</CODE></A>.</P> |
| 761 | <P> |
| 762 | <HR> |
| 763 | <H1><A NAME="methods for callback contexts">Methods for callback contexts</A></H1> |
| 764 | <P>A callback context is available as a parameter inside the callback |
| 765 | functions <A HREF="#db:create_aggregate"><CODE>db:create_aggregate()</CODE></A> and |
| 766 | <A HREF="#db:create_function"><CODE>db:create_function()</CODE></A>. It can be used |
| 767 | to get further information about the state of a query.</P> |
| 768 | <P> |
| 769 | <H2><A NAME="context:aggregate_count">context:aggregate_count</A></H2> |
| 770 | <PRE> |
| 771 | context:aggregate_count()</PRE> |
| 772 | <P>Returns the number of calls to the aggregate step function.</P> |
| 773 | <P> |
| 774 | <H2><A NAME="context:get_aggregate_data">context:get_aggregate_data</A></H2> |
| 775 | <PRE> |
| 776 | context:get_aggregate_data()</PRE> |
| 777 | <P>Returns the user-definable data field for callback funtions.</P> |
| 778 | <P> |
| 779 | <H2><A NAME="context:set_aggregate_data">context:set_aggregate_data</A></H2> |
| 780 | <PRE> |
| 781 | context:set_aggregate_data(udata)</PRE> |
| 782 | <P>Set the user-definable data field for callback funtions to <CODE>udata</CODE>.</P> |
| 783 | <P> |
| 784 | <H2><A NAME="context:result">context:result</A></H2> |
| 785 | <PRE> |
| 786 | context:result(res)</PRE> |
| 787 | <P>This function sets the result of a callback function to res. The type of |
| 788 | the result depends on the type of res and is either a number or a string |
| 789 | or nil. All other values will raise an error message.</P> |
| 790 | <P> |
| 791 | <H2><A NAME="context:result_null">context:result_null</A></H2> |
| 792 | <PRE> |
| 793 | context:result_null()</PRE> |
| 794 | <P>This function sets the result of a callback function to nil. It returns |
| 795 | nothing.</P> |
| 796 | <P> |
| 797 | <H2><A NAME="context:result_number">context:result_number</A></H2> |
| 798 | <PRE> |
| 799 | context:result_number(number) |
| 800 | context:result_double(number)</PRE> |
| 801 | <P>This function sets the result of a callback function to the value |
| 802 | <CODE>number</CODE>. It returns nothing.</P> |
| 803 | <P> |
| 804 | <H2><A NAME="context:result_int">context:result_int</A></H2> |
| 805 | <PRE> |
| 806 | context:result_int(number)</PRE> |
| 807 | <P>This function sets the result of a callback function to the integer |
| 808 | value in <CODE>number</CODE>. It returns nothing.</P> |
| 809 | <P> |
| 810 | <H2><A NAME="context:result_text">context:result_text</A></H2> |
| 811 | <PRE> |
| 812 | context:result_text(str)</PRE> |
| 813 | <P>This function sets the result of a callback function to the string in |
| 814 | <CODE>str</CODE>. It returns nothing.</P> |
| 815 | <P> |
| 816 | <H2><A NAME="context:result_blob">context:result_blob</A></H2> |
| 817 | <PRE> |
| 818 | context:result_blob(blob)</PRE> |
| 819 | <P>This function sets the result of a callback function to the binary |
| 820 | string in <CODE>blob</CODE>. It returns nothing.</P> |
| 821 | <P> |
| 822 | <H2><A NAME="context:result_error">context:result_error</A></H2> |
| 823 | <PRE> |
| 824 | context:result_error(err)</PRE> |
| 825 | <P>This function sets the result of a callback function to the error value |
| 826 | in <CODE>err</CODE>. It returns nothing.</P> |
| 827 | <P> |
| 828 | <H2><A NAME="context:user_data">context:user_data</A></H2> |
| 829 | <PRE> |
| 830 | context:user_data()</PRE> |
| 831 | <P>Returns the userdata parameter given in the call to install the callback |
| 832 | function (see <A HREF="#db:create_aggregate"><CODE>db:create_aggregate()</CODE></A> and |
| 833 | <A HREF="#db:create_function"><CODE>db:create_function()</CODE></A> for details).</P> |
| 834 | <P> |
| 835 | <HR> |
| 836 | <H1><A NAME="numerical error and result codes">Numerical error and result codes</A></H1> |
| 837 | <P>The following constants are defined by module sqlite3:</P> |
| 838 | <PRE> |
| 839 | OK: 0 ERROR: 1 INTERNAL: 2 PERM: 3 ABORT: 4 |
| 840 | BUSY: 5 LOCKED: 6 NOMEM: 7 READONLY: 8 INTERRUPT: 9 |
| 841 | IOERR: 10 CORRUPT: 11 NOTFOUND: 12 FULL: 13 CANTOPEN: 14 |
| 842 | PROTOCOL: 15 EMPTY: 16 SCHEMA: 17 TOOBIG: 18 CONSTRAINT: 19 |
| 843 | MISMATCH: 20 MISUSE: 21 NOLFS: 22 FORMAT: 24 RANGE: 25 |
| 844 | NOTADB: 26 ROW: 100 DONE: 101</PRE> |
| 845 | <P>For details about their exact meaning please see the <STRONG>SQLite3 |
| 846 | documentation</STRONG> <A HREF="http://www.sqlite.org/">http://www.sqlite.org/</A>.</P> |
| 847 | <P> |
| 848 | <HR> |
| 849 | <H1><A NAME="version">VERSION</A></H1> |
| 850 | <P>This is <CODE>lsqlite3</CODE> subversion 6, also known as ``devel-0.6''.</P> |
| 851 | <P> |
| 852 | <HR> |
| 853 | <H1><A NAME="credits">CREDITS</A></H1> |
| 854 | <P><CODE>lsqlite3</CODE> was developed by Tiago Dionizio and Doug Currie with |
| 855 | contributions from Thomas Lauer and Michael Roth.</P> |
| 856 | <P>This documentation is based on the ``(very) preliminary'' documents |
| 857 | for the Idle-SQLite3 database module. Thanks to Thomas Lauer for |
| 858 | making it available.</P> |
| 859 | <P> |
| 860 | <HR> |
| 861 | <H1><A NAME="license">LICENSE</A></H1> |
| 862 | <PRE> |
| 863 | /************************************************************************ |
| 864 | * lsqlite3 * |
| 865 | * Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie * |
| 866 | * All rights reserved. * |
| 867 | * Author : Tiago Dionizio <tiago.dionizio@ist.utl.pt> * |
| 868 | * Author : Doug Currie <doug.currie@alum.mit.edu> * |
| 869 | * Library : lsqlite3 - a SQLite 3 database binding for Lua 5 * |
| 870 | * * |
| 871 | * Permission is hereby granted, free of charge, to any person obtaining * |
| 872 | * a copy of this software and associated documentation files (the * |
| 873 | * "Software"), to deal in the Software without restriction, including * |
| 874 | * without limitation the rights to use, copy, modify, merge, publish, * |
| 875 | * distribute, sublicense, and/or sell copies of the Software, and to * |
| 876 | * permit persons to whom the Software is furnished to do so, subject to * |
| 877 | * the following conditions: * |
| 878 | * * |
| 879 | * The above copyright notice and this permission notice shall be * |
| 880 | * included in all copies or substantial portions of the Software. * |
| 881 | * * |
| 882 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * |
| 883 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * |
| 884 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.* |
| 885 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * |
| 886 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * |
| 887 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * |
| 888 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * |
| 889 | ************************************************************************/</PRE> |
| 890 | |
| 891 | </BODY> |
| 892 | |
| 893 | </HTML> |
trunk/3rdparty/lsqlite3/doc/lsqlite3.pod
| r0 | r242834 | |
| 1 | =pod |
| 2 | |
| 3 | =head1 NAME |
| 4 | |
| 5 | B<LuaSQLite 3> - a Lua 5.1 wrapper for the SQLite3 library |
| 6 | |
| 7 | =head1 OVERVIEW |
| 8 | |
| 9 | B<LuaSQLite 3> is a thin wrapper around the public domain SQLite3 |
| 10 | database engine. |
| 11 | |
| 12 | The C<lsqlite3> module supports the creation and manipulation of |
| 13 | SQLite3 databases. After a C<require('lsqlite3')> the exported |
| 14 | functions are called with prefix C<sqlite3>. However, most sqlite3 |
| 15 | functions are called via an object-oriented interface to either |
| 16 | database or SQL statement objects; see below for details. |
| 17 | |
| 18 | This documentation does not attempt to describe how SQLite3 itself |
| 19 | works, it just describes the Lua binding and the available functions. |
| 20 | For more information about the SQL features supported by SQLite3 and |
| 21 | details about the syntax of SQL statements and queries, please see the |
| 22 | B<SQLite3 documentation> L<http://www.sqlite.org/>. Using some of the |
| 23 | advanced features (how to use callbacks, for instance) will require |
| 24 | some familiarity with the SQLite3 API. |
| 25 | |
| 26 | =head1 DOWNLOAD |
| 27 | |
| 28 | B<LuaSQLite 3> source code can be downloaded from its |
| 29 | LuaForge (L<http://luaforge.net/projects/luasqlite/>) page. |
| 30 | |
| 31 | You will also need to build or obtain an SQLite3 loadable library |
| 32 | (DLL or .so). See L<http://www.sqlite.org/> for obtaining SQLite3 |
| 33 | source code or downloading a binary SQLite3 library. |
| 34 | |
| 35 | =head1 INSTALLATION |
| 36 | |
| 37 | A I<Makefile> is provided; it assumes an SQLite3 library is already |
| 38 | installed. |
| 39 | |
| 40 | =head1 EXAMPLES |
| 41 | |
| 42 | The distribution contains an I<examples> directory. The unit tests |
| 43 | also show some example use. |
| 44 | |
| 45 | =head1 VERIFICATION TESTS |
| 46 | |
| 47 | The distribution contains some units tests using Michael Roth's |
| 48 | C<lunit> (which is also included). Some of the tests were also derived |
| 49 | from Michael's B<lua-sqlite3> module, and more unit tests added by |
| 50 | Doug Currie. |
| 51 | |
| 52 | The distribution also contains some functional tests by Tiago. |
| 53 | |
| 54 | This version of C<lsqlite3> was tested with SQLite 3.4.2. |
| 55 | |
| 56 | =head1 REFERENCE |
| 57 | |
| 58 | =head1 SQLite3 functions |
| 59 | |
| 60 | =head2 sqlite3.complete |
| 61 | |
| 62 | sqlite3.complete(sql) |
| 63 | |
| 64 | Returns true if the string C<sql> comprises one or more complete SQL |
| 65 | statements and false otherwise. |
| 66 | |
| 67 | =head2 sqlite3.open |
| 68 | |
| 69 | sqlite3.open(filename) |
| 70 | |
| 71 | Opens (or creates if it does not exist) an SQLite database with name |
| 72 | C<filename> and returns its handle as userdata (the returned object |
| 73 | should be used for all further method calls in connection with this |
| 74 | specific database, see L</Database methods>). Example: |
| 75 | |
| 76 | myDB=sqlite3.open('MyDatabase.sqlite3') -- open |
| 77 | -- do some database calls... |
| 78 | myDB:close() -- close |
| 79 | |
| 80 | In case of an error, the function returns nil, an error code and an |
| 81 | error message. |
| 82 | |
| 83 | =head2 sqlite3.open_memory |
| 84 | |
| 85 | sqlite3.open_memory() |
| 86 | |
| 87 | Opens an SQLite database B<in memory> and returns its handle as |
| 88 | userdata. In case of an error, the function returns nil, an error code |
| 89 | and an error message. (In-memory databases are volatile as they are |
| 90 | never stored on disk.) |
| 91 | |
| 92 | =head2 sqlite3.temp_directory |
| 93 | |
| 94 | sqlite3.temp_directory([temp]) |
| 95 | |
| 96 | Sets or queries the directory used by SQLite for temporary files. If |
| 97 | string C<temp> is a directory name or nil, the temporary directory is |
| 98 | set accordingly and the old value is returned. If C<temp> is missing, |
| 99 | the function simply returns the current temporary directory. |
| 100 | |
| 101 | =head2 sqlite3.version |
| 102 | |
| 103 | sqlite3.version() |
| 104 | |
| 105 | Returns a string with SQLite version information, in the form 'x.y[.z]'. |
| 106 | |
| 107 | =head1 Database methods |
| 108 | |
| 109 | After opening a database with L<C<sqlite3.open()>|/sqlite3.open> or |
| 110 | L<C<sqlite3.open_memory()>|/sqlite3.open_memory> |
| 111 | the returned database object should be used for all further method calls |
| 112 | in connection with that database. An open database object supports the |
| 113 | following methods. |
| 114 | |
| 115 | =head2 db:busy_handler |
| 116 | |
| 117 | db:busy_handler([func[,udata]]) |
| 118 | |
| 119 | Sets or removes a busy handler for a database. C<func> is either a Lua |
| 120 | function that implements the busy handler or nil to remove a previously |
| 121 | set handler. This function returns nothing. |
| 122 | |
| 123 | The handler function is called with two parameters: C<udata> and the |
| 124 | number of (re-)tries for a pending transaction. It should return nil, |
| 125 | false or 0 if the transaction is to be aborted. All other values will |
| 126 | result in another attempt to perform the transaction. (See the SQLite |
| 127 | documentation for important hints about writing busy handlers.) |
| 128 | |
| 129 | =head2 db:busy_timeout |
| 130 | |
| 131 | db:busy_timeout(t) |
| 132 | |
| 133 | Sets a busy handler that waits for C<t> milliseconds if a transaction |
| 134 | cannot proceed. Calling this function will remove any busy handler set |
| 135 | by L<C<db:busy_handler()>|/db:busy_handler>; calling it with an argument |
| 136 | less than or equal to 0 will turn off all busy handlers. |
| 137 | |
| 138 | =head2 db:changes |
| 139 | |
| 140 | db:changes() |
| 141 | |
| 142 | This function returns the number of database rows that were changed (or |
| 143 | inserted or deleted) by the most recent SQL statement. Only changes that |
| 144 | are directly specified by INSERT, UPDATE, or DELETE statements are |
| 145 | counted. Auxiliary changes caused by triggers are not counted. Use |
| 146 | L<C<db:total_changes()>|/db:total_changes> to find the total number of |
| 147 | changes. |
| 148 | |
| 149 | =head2 db:close |
| 150 | |
| 151 | db:close() |
| 152 | |
| 153 | Closes a database. All SQL statements prepared using |
| 154 | L<C<db:prepare()>|/db:prepare> should |
| 155 | have been finalized before this function is called. The function returns |
| 156 | C<sqlite3.OK> on success or else a numerical error code (see the list of |
| 157 | L</Numerical error and result codes>). |
| 158 | |
| 159 | =head2 db:close_vm |
| 160 | |
| 161 | db:close_vm(temponly) |
| 162 | |
| 163 | Finalizes all statements that have not been explicitly finalized. If |
| 164 | C<temponly> is true, only internal, temporary statements are finalized. |
| 165 | This function returns nothing. |
| 166 | |
| 167 | =head2 db:create_aggregate |
| 168 | |
| 169 | db:create_aggregate(name,nargs,step,final) |
| 170 | |
| 171 | This function creates an aggregate callback function. Aggregates perform |
| 172 | an operation over all rows in a query. C<name> is a string with the name |
| 173 | of the aggregate function as given in an SQL statement; C<nargs> is the |
| 174 | number of arguments this call will provide. C<step> is the actual Lua |
| 175 | function that gets called once for every row; it should accept a function |
| 176 | context (see L</Methods for callback contexts>) plus the same number of |
| 177 | parameters as given in C<nargs>. C<final> is a function that is called |
| 178 | once after all rows have been processed; it receives one argument, the |
| 179 | function context. |
| 180 | |
| 181 | The function context can be used inside the two callback functions to |
| 182 | communicate with SQLite3. Here is a simple example: |
| 183 | |
| 184 | db:exec[=[ |
| 185 | CREATE TABLE numbers(num1,num2); |
| 186 | INSERT INTO numbers VALUES(1,11); |
| 187 | INSERT INTO numbers VALUES(2,22); |
| 188 | INSERT INTO numbers VALUES(3,33); |
| 189 | ]=] |
| 190 | local num_sum=0 |
| 191 | local function oneRow(context,num) -- add one column in all rows |
| 192 | num_sum=num_sum+num |
| 193 | end |
| 194 | local function afterLast(context) -- return sum after last row has been processed |
| 195 | context:result_number(num_sum) |
| 196 | num_sum=0 |
| 197 | end |
| 198 | db:create_aggregate("do_the_sums",1,oneRow,afterLast) |
| 199 | for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end |
| 200 | for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end |
| 201 | |
| 202 | This prints: |
| 203 | |
| 204 | Sum of col 1: 6 |
| 205 | Sum of col 2: 66 |
| 206 | |
| 207 | =head2 db:create_collation |
| 208 | |
| 209 | db:create_collation(name,func) |
| 210 | |
| 211 | This creates a collation callback. A collation callback is used to |
| 212 | establish a collation order, mostly for string comparisons and sorting |
| 213 | purposes. C<name> is a string with the name of the collation to be created; |
| 214 | C<func> is a function that accepts two string arguments, compares them |
| 215 | and returns 0 if both strings are identical, -1 if the first argument is |
| 216 | lower in the collation order than the second and 1 if the first argument |
| 217 | is higher in the collation order than the second. A simple example: |
| 218 | |
| 219 | local function collate(s1,s2) |
| 220 | s1=s1:lower() |
| 221 | s2=s2:lower() |
| 222 | if s1==s2 then return 0 |
| 223 | elseif s1<s2 then return -1 |
| 224 | else return 1 end |
| 225 | end |
| 226 | db:exec[=[ |
| 227 | CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS); |
| 228 | INSERT INTO test VALUES(NULL,'hello world'); |
| 229 | INSERT INTO test VALUES(NULL,'Buenos dias'); |
| 230 | INSERT INTO test VALUES(NULL,'HELLO WORLD'); |
| 231 | ]=] |
| 232 | db:create_collation('CINSENS',collate) |
| 233 | for row in db:nrows('SELECT * FROM test') do print(row.id,row.content) end |
| 234 | |
| 235 | =head2 db:create_function |
| 236 | |
| 237 | db:create_function(name,nargs,func) |
| 238 | |
| 239 | This function creates a callback function. Callback function are called |
| 240 | by SQLite3 once for every row in a query. C<name> is a string with the |
| 241 | name of the callback function as given in an SQL statement; C<nargs> is |
| 242 | the number of arguments this call will provide. C<func> is the actual Lua |
| 243 | function that gets called once for every row; it should accept a |
| 244 | function context (see L</Methods for callback contexts>) plus the same |
| 245 | number of parameters as given in nargs. Here is an example: |
| 246 | |
| 247 | db:exec'CREATE TABLE test(col1,col2,col3)' |
| 248 | db:exec'INSERT INTO test VALUES(1,2,4)' |
| 249 | db:exec'INSERT INTO test VALUES(2,4,9)' |
| 250 | db:exec'INSERT INTO test VALUES(3,6,16)' |
| 251 | db:create_function('sum_cols',3,function(ctx,a,b,c) |
| 252 | ctx:result_number(a+b+c) |
| 253 | end)) |
| 254 | for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do |
| 255 | util.printf('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum) |
| 256 | end |
| 257 | |
| 258 | =head2 db:errcode |
| 259 | |
| 260 | db:errcode() |
| 261 | db:error_code() |
| 262 | |
| 263 | Returns the numerical result code (or extended result code) for the most |
| 264 | recent failed call associated with database db. See |
| 265 | L</Numerical error and result codes> for details. |
| 266 | |
| 267 | =head2 db:errmsg |
| 268 | |
| 269 | db:errmsg() |
| 270 | db:error_message() |
| 271 | |
| 272 | Returns a string that contains an error message for the most recent |
| 273 | failed call associated with database db. |
| 274 | |
| 275 | =head2 db:exec |
| 276 | |
| 277 | db:exec(sql[,func[,udata]]) |
| 278 | db:execute(sql[,func[,udata]]) |
| 279 | |
| 280 | Compiles and executes the SQL statement(s) given in string C<sql>. The |
| 281 | statements are simply executed one after the other and not stored. The |
| 282 | function returns C<sqlite3.OK> on success or else a numerical error code |
| 283 | (see L</Numerical error and result codes>). |
| 284 | |
| 285 | If one or more of the SQL statements are queries, then the callback |
| 286 | function specified in C<func> is invoked once for each row of the query |
| 287 | result (if C<func> is nil, no callback is invoked). The callback receives |
| 288 | four arguments: C<udata> (the third parameter of the C<db:exec()> call), |
| 289 | the number of columns in the row, a table with the column values and |
| 290 | another table with the column names. The callback function should return |
| 291 | 0. If the callback returns a non-zero value then the query is aborted, |
| 292 | all subsequent SQL statements are skipped and C<db:exec()> returns |
| 293 | C<sqlite3.ABORT>. Here is a simple example: |
| 294 | |
| 295 | sql=[=[ |
| 296 | CREATE TABLE numbers(num1,num2,str); |
| 297 | INSERT INTO numbers VALUES(1,11,"ABC"); |
| 298 | INSERT INTO numbers VALUES(2,22,"DEF"); |
| 299 | INSERT INTO numbers VALUES(3,33,"UVW"); |
| 300 | INSERT INTO numbers VALUES(4,44,"XYZ"); |
| 301 | SELECT * FROM numbers; |
| 302 | ]=] |
| 303 | function showrow(udata,cols,values,names) |
| 304 | assert(udata=='test_udata') |
| 305 | print('exec:') |
| 306 | for i=1,cols do print('',names[i],values[i]) end |
| 307 | return 0 |
| 308 | end |
| 309 | db:exec(sql,showrow,'test_udata') |
| 310 | |
| 311 | =head2 db:interrupt |
| 312 | |
| 313 | db:interrupt() |
| 314 | |
| 315 | This function causes any pending database operation to abort and return |
| 316 | at the next opportunity. This function returns nothing. |
| 317 | |
| 318 | =head2 db:isopen |
| 319 | |
| 320 | db:isopen() |
| 321 | |
| 322 | Returns true if database db is open, false otherwise. |
| 323 | |
| 324 | =head2 db:last_insert_rowid |
| 325 | |
| 326 | db:last_insert_rowid() |
| 327 | |
| 328 | This function returns the rowid of the most recent INSERT into the |
| 329 | database. If no inserts have ever occurred, 0 is returned. (Each row in |
| 330 | an SQLite table has a unique 64-bit signed integer key called the |
| 331 | 'rowid'. This id is always available as an undeclared column named |
| 332 | ROWID, OID, or _ROWID_. If the table has a column of type INTEGER |
| 333 | PRIMARY KEY then that column is another alias for the rowid.) |
| 334 | |
| 335 | If an INSERT occurs within a trigger, then the rowid of the inserted row |
| 336 | is returned as long as the trigger is running. Once the trigger |
| 337 | terminates, the value returned reverts to the last value inserted before |
| 338 | the trigger fired. |
| 339 | |
| 340 | =head2 db:nrows |
| 341 | |
| 342 | db:nrows(sql) |
| 343 | |
| 344 | Creates an iterator that returns the successive rows selected by the SQL |
| 345 | statement given in string C<sql>. Each call to the iterator returns a |
| 346 | table in which the named fields correspond to the columns in the database. |
| 347 | Here is an example: |
| 348 | |
| 349 | db:exec[=[ |
| 350 | CREATE TABLE numbers(num1,num2); |
| 351 | INSERT INTO numbers VALUES(1,11); |
| 352 | INSERT INTO numbers VALUES(2,22); |
| 353 | INSERT INTO numbers VALUES(3,33); |
| 354 | ]=] |
| 355 | for a in db:nrows('SELECT * FROM numbers') do table.print(a) end |
| 356 | |
| 357 | This script prints: |
| 358 | |
| 359 | num2: 11 |
| 360 | num1: 1 |
| 361 | num2: 22 |
| 362 | num1: 2 |
| 363 | num2: 33 |
| 364 | num1: 3 |
| 365 | |
| 366 | =head2 db:prepare |
| 367 | |
| 368 | db:prepare(sql) |
| 369 | |
| 370 | This function compiles the SQL statement in string C<sql> into an internal |
| 371 | representation and returns this as userdata. The returned object should |
| 372 | be used for all further method calls in connection with this specific |
| 373 | SQL statement (see L</Methods for prepared statements>). |
| 374 | |
| 375 | =head2 db:progress_handler |
| 376 | |
| 377 | db:progress_handler(n,func,udata) |
| 378 | |
| 379 | This function installs a callback function C<func> that is invoked |
| 380 | periodically during long-running calls to L<C<db:exec()>|/db:exec> |
| 381 | or L<C<stmt:step()>|/stmt:step>. The |
| 382 | progress callback is invoked once for every C<n> internal operations, |
| 383 | where C<n> is the first argument to this function. C<udata> is passed to |
| 384 | the progress callback function each time it is invoked. If a call to |
| 385 | C<db:exec()> or C<stmt:step()> results in fewer than C<n> operations |
| 386 | being executed, then the progress callback is never invoked. Only a |
| 387 | single progress callback function may be registered for each opened |
| 388 | database and a call to this function will overwrite any previously set |
| 389 | callback function. To remove the progress callback altogether, pass nil |
| 390 | as the second argument. |
| 391 | |
| 392 | If the progress callback returns a result other than 0, then the current |
| 393 | query is immediately terminated, any database changes are rolled back |
| 394 | and the containing C<db:exec()> or C<stmt:step()> call returns |
| 395 | C<sqlite3.INTERRUPT>. This feature can be used to cancel long-running |
| 396 | queries. |
| 397 | |
| 398 | =head2 db:rows |
| 399 | |
| 400 | db:rows(sql) |
| 401 | |
| 402 | Creates an iterator that returns the successive rows selected by the SQL |
| 403 | statement given in string C<sql>. Each call to the iterator returns a table |
| 404 | in which the numerical indices 1 to n correspond to the selected columns |
| 405 | 1 to n in the database. Here is an example: |
| 406 | |
| 407 | db:exec[=[ |
| 408 | CREATE TABLE numbers(num1,num2); |
| 409 | INSERT INTO numbers VALUES(1,11); |
| 410 | INSERT INTO numbers VALUES(2,22); |
| 411 | INSERT INTO numbers VALUES(3,33); |
| 412 | ]=] |
| 413 | for a in db:rows('SELECT * FROM numbers') do table.print(a) end |
| 414 | |
| 415 | This script prints: |
| 416 | |
| 417 | 1: 1 |
| 418 | 2: 11 |
| 419 | 1: 2 |
| 420 | 2: 22 |
| 421 | 1: 3 |
| 422 | 2: 33 |
| 423 | |
| 424 | =head2 db:total_changes |
| 425 | |
| 426 | db:total_changes() |
| 427 | |
| 428 | This function returns the number of database rows that have been |
| 429 | modified by INSERT, UPDATE or DELETE statements since the database was |
| 430 | opened. This includes UPDATE, INSERT and DELETE statements executed as |
| 431 | part of trigger programs. All changes are counted as soon as the |
| 432 | statement that produces them is completed by calling either |
| 433 | L<C<stmt:reset()>|/stmt:reset> or L<C<stmt:finalize()>|/stmt:finalize>. |
| 434 | |
| 435 | =head2 db:trace |
| 436 | |
| 437 | db:trace(func,udata) |
| 438 | |
| 439 | This function installs a trace callback handler. C<func> is a Lua |
| 440 | function that is called by SQLite3 just before the evaluation of an SQL |
| 441 | statement. This callback receives two arguments: the first is the |
| 442 | C<udata> argument used when the callback was installed; the second is a |
| 443 | string with the SQL statement about to be executed. |
| 444 | |
| 445 | =head2 db:urows |
| 446 | |
| 447 | db:urows(sql) |
| 448 | |
| 449 | Creates an iterator that returns the successive rows selected by the SQL |
| 450 | statement given in string C<sql>. Each call to the iterator returns the |
| 451 | values that correspond to the columns in the currently selected row. |
| 452 | Here is an example: |
| 453 | |
| 454 | db:exec[=[ |
| 455 | CREATE TABLE numbers(num1,num2); |
| 456 | INSERT INTO numbers VALUES(1,11); |
| 457 | INSERT INTO numbers VALUES(2,22); |
| 458 | INSERT INTO numbers VALUES(3,33); |
| 459 | ]=] |
| 460 | for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end |
| 461 | |
| 462 | This script prints: |
| 463 | |
| 464 | 1 11 |
| 465 | 2 22 |
| 466 | 3 33 |
| 467 | |
| 468 | =head1 Methods for prepared statements |
| 469 | |
| 470 | After creating a prepared statement with L<C<db:prepare()>|/db:prepare> |
| 471 | the returned statement object should be used for all further calls in |
| 472 | connection with that statement. Statement objects support the following |
| 473 | methods. |
| 474 | |
| 475 | =head2 stmt:bind |
| 476 | |
| 477 | stmt:bind(n[,value]) |
| 478 | |
| 479 | Binds value to statement parameter C<n>. If the type of value is string |
| 480 | or number, it is bound as text or double, respectively. If C<value> is a |
| 481 | boolean or nil or missing, any previous binding is removed. The function |
| 482 | returns C<sqlite3.OK> on success or else a numerical error code (see |
| 483 | L</Numerical error and result codes>). |
| 484 | |
| 485 | =head2 stmt:bind_blob |
| 486 | |
| 487 | stmt:bind_blob(n,blob) |
| 488 | |
| 489 | Binds string C<blob> (which can be a binary string) as a blob to |
| 490 | statement parameter C<n>. The function returns C<sqlite3.OK> on success |
| 491 | or else a numerical error code (see L</Numerical error and result codes>). |
| 492 | |
| 493 | =head2 stmt:bind_names |
| 494 | |
| 495 | stmt:bind_names(nametable) |
| 496 | |
| 497 | Binds the values in C<nametable> to statement parameters. If the |
| 498 | statement parameters are named (i.e., of the form ":AAA" or "$AAA") |
| 499 | then this function looks for appropriately named fields in C<nametable>; |
| 500 | if the statement parameters are |
| 501 | not named, it looks for numerical fields 1 to the number of statement |
| 502 | parameters. The function returns C<sqlite3.OK> on success or else a |
| 503 | numerical error code (see L</Numerical error and result codes>). |
| 504 | |
| 505 | =head2 stmt:bind_parameter_count |
| 506 | |
| 507 | stmt:bind_parameter_count() |
| 508 | |
| 509 | Returns the largest statement parameter index in prepared statement |
| 510 | C<stmt>. When the statement parameters are of the forms ":AAA" or "?", |
| 511 | then they are assigned sequentially increasing numbers beginning with |
| 512 | one, so the value returned is the number of parameters. However if the |
| 513 | same statement parameter name is used multiple times, each occurrence |
| 514 | is given the same number, so the value returned is the number of unique |
| 515 | statement parameter names. |
| 516 | |
| 517 | If statement parameters of the form "?NNN" are used (where NNN is an |
| 518 | integer) then there might be gaps in the numbering and the value |
| 519 | returned by this interface is the index of the statement parameter with |
| 520 | the largest index value. |
| 521 | |
| 522 | =head2 stmt:bind_parameter_name |
| 523 | |
| 524 | stmt:bind_parameter_name(n) |
| 525 | |
| 526 | Returns the name of the C<n>-th parameter in prepared statement C<stmt>. |
| 527 | Statement parameters of the form ":AAA" or "@AAA" or "$VVV" have a name |
| 528 | which is the string ":AAA" or "@AAA" or "$VVV". In other words, the |
| 529 | initial ":" or "$" or "@" is included as part of the name. Parameters |
| 530 | of the form "?" or "?NNN" have no name. The first bound parameter has |
| 531 | an index of 1. |
| 532 | If the value C<n> is out of range or if the C<n>-th parameter is |
| 533 | nameless, then nil is returned. The function returns C<sqlite3.OK> on |
| 534 | success or else a numerical error code (see |
| 535 | L</Numerical error and result codes>) |
| 536 | |
| 537 | =head2 stmt:bind_values |
| 538 | |
| 539 | stmt:bind_values(value1,value2,...,valueN) |
| 540 | |
| 541 | Binds the given values to statement parameters. The function returns |
| 542 | C<sqlite3.OK> on success or else a numerical error code (see |
| 543 | L</Numerical error and result codes>). |
| 544 | |
| 545 | =head2 stmt:columns |
| 546 | |
| 547 | stmt:columns() |
| 548 | |
| 549 | Returns the number of columns in the result set returned by statement |
| 550 | stmt or 0 if the statement does not return data (for example an UPDATE). |
| 551 | |
| 552 | =head2 stmt:finalize |
| 553 | |
| 554 | stmt:finalize() |
| 555 | |
| 556 | This function frees prepared statement stmt. If the statement was |
| 557 | executed successfully, or not executed at all, then C<sqlite3.OK> is |
| 558 | returned. If execution of the statement failed then an error code is |
| 559 | returned. |
| 560 | |
| 561 | =head2 stmt:get_name |
| 562 | |
| 563 | stmt:get_name(n) |
| 564 | |
| 565 | Returns the name of column C<n> in the result set of statement stmt. (The |
| 566 | left-most column is number 0.) |
| 567 | |
| 568 | =head2 stmt:get_named_types |
| 569 | |
| 570 | stmt:get_named_types() |
| 571 | |
| 572 | Returns a table with the names and types of all columns in the result |
| 573 | set of statement stmt. |
| 574 | |
| 575 | =head2 stmt:get_named_values |
| 576 | |
| 577 | stmt:get_named_values() |
| 578 | |
| 579 | This function returns a table with names and values of all columns in |
| 580 | the current result row of a query. |
| 581 | |
| 582 | =head2 stmt:get_names |
| 583 | |
| 584 | stmt:get_names() |
| 585 | |
| 586 | This function returns an array with the names of all columns in the |
| 587 | result set returned by statement stmt. |
| 588 | |
| 589 | =head2 stmt:get_type |
| 590 | |
| 591 | stmt:get_type(n) |
| 592 | |
| 593 | Returns the type of column C<n> in the result set of statement stmt. (The |
| 594 | left-most column is number 0.) |
| 595 | |
| 596 | =head2 stmt:get_types |
| 597 | |
| 598 | stmt:get_types() |
| 599 | |
| 600 | This function returns an array with the types of all columns in the |
| 601 | result set returned by statement stmt. |
| 602 | |
| 603 | =head2 stmt:get_unames |
| 604 | |
| 605 | stmt:get_unames() |
| 606 | |
| 607 | This function returns a list with the names of all columns in the result |
| 608 | set returned by statement stmt. |
| 609 | |
| 610 | =head2 stmt:get_utypes |
| 611 | |
| 612 | stmt:get_utypes() |
| 613 | |
| 614 | This function returns a list with the types of all columns in the result |
| 615 | set returned by statement stmt. |
| 616 | |
| 617 | =head2 stmt:get_uvalues |
| 618 | |
| 619 | stmt:get_uvalues() |
| 620 | |
| 621 | This function returns a list with the values of all columns in the |
| 622 | current result row of a query. |
| 623 | |
| 624 | =head2 stmt:get_value |
| 625 | |
| 626 | stmt:get_value(n) |
| 627 | |
| 628 | Returns the value of column C<n> in the result set of statement stmt. (The |
| 629 | left-most column is number 0.) |
| 630 | |
| 631 | =head2 stmt:get_values |
| 632 | |
| 633 | stmt:get_values() |
| 634 | |
| 635 | This function returns an array with the values of all columns in the |
| 636 | result set returned by statement stmt. |
| 637 | |
| 638 | =head2 stmt:isopen |
| 639 | |
| 640 | stmt:isopen() |
| 641 | |
| 642 | Returns true if stmt has not yet been finalized, false otherwise. |
| 643 | |
| 644 | =head2 stmt:nrows |
| 645 | |
| 646 | stmt:nrows() |
| 647 | |
| 648 | Returns an function that iterates over the names and values of the |
| 649 | result set of statement C<stmt>. Each iteration returns a table with the |
| 650 | names and values for the current row. |
| 651 | This is the prepared statement equivalent of L<C<db:nrows()>|/db:nrows>. |
| 652 | |
| 653 | =head2 stmt:reset |
| 654 | |
| 655 | stmt:reset() |
| 656 | |
| 657 | This function resets SQL statement C<stmt>, so that it is ready to be |
| 658 | re-executed. Any statement variables that had values bound to them using |
| 659 | the C<stmt:bind*()> functions retain their values. |
| 660 | |
| 661 | =head2 stmt:rows |
| 662 | |
| 663 | stmt:rows() |
| 664 | |
| 665 | Returns an function that iterates over the values of the result set of |
| 666 | statement stmt. Each iteration returns an array with the values for the |
| 667 | current row. |
| 668 | This is the prepared statement equivalent of L<C<db:rows()>|/db:rows>. |
| 669 | |
| 670 | =head2 stmt:step |
| 671 | |
| 672 | stmt:step() |
| 673 | |
| 674 | This function must be called to evaluate the (next iteration of the) |
| 675 | prepared statement stmt. It will return one of the following values: |
| 676 | |
| 677 | =over 4 |
| 678 | |
| 679 | =item * |
| 680 | |
| 681 | C<sqlite3.BUSY>: the engine was unable to acquire the locks needed. If the |
| 682 | statement is a COMMIT or occurs outside of an explicit transaction, then |
| 683 | you can retry the statement. If the statement is not a COMMIT and occurs |
| 684 | within a explicit transaction then you should rollback the transaction |
| 685 | before continuing. |
| 686 | |
| 687 | =item * |
| 688 | |
| 689 | C<sqlite3.DONE>: the statement has finished executing successfully. |
| 690 | L<C<stmt:step()>|/stmt:step> should not be called again on this statement |
| 691 | without first calling L<C<stmt:reset()>|/stmt:reset> to reset the virtual |
| 692 | machine back to the initial state. |
| 693 | |
| 694 | =item * |
| 695 | |
| 696 | C<sqlite3.ROW>: this is returned each time a new row of data is ready for |
| 697 | processing by the caller. The values may be accessed using the column |
| 698 | access functions. L<C<stmt:step()>|/stmt:step> can be called again to |
| 699 | retrieve the next row of data. |
| 700 | |
| 701 | =item * |
| 702 | |
| 703 | C<sqlite3.ERROR>: a run-time error (such as a constraint violation) has |
| 704 | occurred. L<C<stmt:step()>|/stmt:step> should not be called again. More |
| 705 | information may be found by calling L<C<db:errmsg()>|/db:errmsg>. A more |
| 706 | specific error |
| 707 | code (can be obtained by calling L<C<stmt:reset()>|/stmt:reset>. |
| 708 | |
| 709 | =item * |
| 710 | |
| 711 | C<sqlite3.MISUSE>: the function was called inappropriately, perhaps |
| 712 | because the statement has already been finalized or a previous call to |
| 713 | L<C<stmt:step()>|/stmt:step> has returned C<sqlite3.ERROR> or |
| 714 | C<sqlite3.DONE>. |
| 715 | |
| 716 | =back |
| 717 | |
| 718 | =head2 stmt:urows |
| 719 | |
| 720 | stmt:urows() |
| 721 | |
| 722 | Returns an function that iterates over the values of the result set of |
| 723 | statement stmt. Each iteration returns the values for the current row. |
| 724 | This is the prepared statement equivalent of L<C<db:urows()>|/db:urows>. |
| 725 | |
| 726 | =head1 Methods for callback contexts |
| 727 | |
| 728 | A callback context is available as a parameter inside the callback |
| 729 | functions L<C<db:create_aggregate()>|/db:create_aggregate> and |
| 730 | L<C<db:create_function()>|/db:create_function>. It can be used |
| 731 | to get further information about the state of a query. |
| 732 | |
| 733 | =head2 context:aggregate_count |
| 734 | |
| 735 | context:aggregate_count() |
| 736 | |
| 737 | Returns the number of calls to the aggregate step function. |
| 738 | |
| 739 | =head2 context:get_aggregate_data |
| 740 | |
| 741 | context:get_aggregate_data() |
| 742 | |
| 743 | Returns the user-definable data field for callback funtions. |
| 744 | |
| 745 | =head2 context:set_aggregate_data |
| 746 | |
| 747 | context:set_aggregate_data(udata) |
| 748 | |
| 749 | Set the user-definable data field for callback funtions to C<udata>. |
| 750 | |
| 751 | =head2 context:result |
| 752 | |
| 753 | context:result(res) |
| 754 | |
| 755 | This function sets the result of a callback function to res. The type of |
| 756 | the result depends on the type of res and is either a number or a string |
| 757 | or nil. All other values will raise an error message. |
| 758 | |
| 759 | =head2 context:result_null |
| 760 | |
| 761 | context:result_null() |
| 762 | |
| 763 | This function sets the result of a callback function to nil. It returns |
| 764 | nothing. |
| 765 | |
| 766 | =head2 context:result_number |
| 767 | |
| 768 | context:result_number(number) |
| 769 | context:result_double(number) |
| 770 | |
| 771 | This function sets the result of a callback function to the value |
| 772 | C<number>. It returns nothing. |
| 773 | |
| 774 | =head2 context:result_int |
| 775 | |
| 776 | context:result_int(number) |
| 777 | |
| 778 | This function sets the result of a callback function to the integer |
| 779 | value in C<number>. It returns nothing. |
| 780 | |
| 781 | =head2 context:result_text |
| 782 | |
| 783 | context:result_text(str) |
| 784 | |
| 785 | This function sets the result of a callback function to the string in |
| 786 | C<str>. It returns nothing. |
| 787 | |
| 788 | =head2 context:result_blob |
| 789 | |
| 790 | context:result_blob(blob) |
| 791 | |
| 792 | This function sets the result of a callback function to the binary |
| 793 | string in C<blob>. It returns nothing. |
| 794 | |
| 795 | =head2 context:result_error |
| 796 | |
| 797 | context:result_error(err) |
| 798 | |
| 799 | This function sets the result of a callback function to the error value |
| 800 | in C<err>. It returns nothing. |
| 801 | |
| 802 | =head2 context:user_data |
| 803 | |
| 804 | context:user_data() |
| 805 | |
| 806 | Returns the userdata parameter given in the call to install the callback |
| 807 | function (see L<C<db:create_aggregate()>|/db:create_aggregate> and |
| 808 | L<C<db:create_function()>|/db:create_function> for details). |
| 809 | |
| 810 | =head1 Numerical error and result codes |
| 811 | |
| 812 | The following constants are defined by module sqlite3: |
| 813 | |
| 814 | OK: 0 ERROR: 1 INTERNAL: 2 PERM: 3 ABORT: 4 |
| 815 | BUSY: 5 LOCKED: 6 NOMEM: 7 READONLY: 8 INTERRUPT: 9 |
| 816 | IOERR: 10 CORRUPT: 11 NOTFOUND: 12 FULL: 13 CANTOPEN: 14 |
| 817 | PROTOCOL: 15 EMPTY: 16 SCHEMA: 17 TOOBIG: 18 CONSTRAINT: 19 |
| 818 | MISMATCH: 20 MISUSE: 21 NOLFS: 22 FORMAT: 24 RANGE: 25 |
| 819 | NOTADB: 26 ROW: 100 DONE: 101 |
| 820 | |
| 821 | For details about their exact meaning please see the B<SQLite3 |
| 822 | documentation> L<http://www.sqlite.org/>. |
| 823 | |
| 824 | =head1 VERSION |
| 825 | |
| 826 | This is C<lsqlite3> subversion 6, also known as "devel-0.6". |
| 827 | |
| 828 | =head1 CREDITS |
| 829 | |
| 830 | C<lsqlite3> was developed by Tiago Dionizio and Doug Currie with |
| 831 | contributions from Thomas Lauer and Michael Roth. |
| 832 | |
| 833 | This documentation is based on the "(very) preliminary" documents |
| 834 | for the Idle-SQLite3 database module. Thanks to Thomas Lauer for |
| 835 | making it available. |
| 836 | |
| 837 | =head1 LICENSE |
| 838 | |
| 839 | /************************************************************************ |
| 840 | * lsqlite3 * |
| 841 | * Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie * |
| 842 | * All rights reserved. * |
| 843 | * Author : Tiago Dionizio <tiago.dionizio@ist.utl.pt> * |
| 844 | * Author : Doug Currie <doug.currie@alum.mit.edu> * |
| 845 | * Library : lsqlite3 - a SQLite 3 database binding for Lua 5 * |
| 846 | * * |
| 847 | * Permission is hereby granted, free of charge, to any person obtaining * |
| 848 | * a copy of this software and associated documentation files (the * |
| 849 | * "Software"), to deal in the Software without restriction, including * |
| 850 | * without limitation the rights to use, copy, modify, merge, publish, * |
| 851 | * distribute, sublicense, and/or sell copies of the Software, and to * |
| 852 | * permit persons to whom the Software is furnished to do so, subject to * |
| 853 | * the following conditions: * |
| 854 | * * |
| 855 | * The above copyright notice and this permission notice shall be * |
| 856 | * included in all copies or substantial portions of the Software. * |
| 857 | * * |
| 858 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * |
| 859 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * |
| 860 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.* |
| 861 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * |
| 862 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * |
| 863 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * |
| 864 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * |
| 865 | ************************************************************************/ |
| 866 | |
trunk/3rdparty/lsqlite3/lsqlite3.c
| r0 | r242834 | |
| 1 | /************************************************************************ |
| 2 | * lsqlite3 * |
| 3 | * Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie * |
| 4 | * All rights reserved. * |
| 5 | * Author : Tiago Dionizio <tiago.dionizio@ist.utl.pt> * |
| 6 | * Author : Doug Currie <doug.currie@alum.mit.edu> * |
| 7 | * Library : lsqlite3 - a SQLite 3 database binding for Lua 5 * |
| 8 | * * |
| 9 | * Permission is hereby granted, free of charge, to any person obtaining * |
| 10 | * a copy of this software and associated documentation files (the * |
| 11 | * "Software"), to deal in the Software without restriction, including * |
| 12 | * without limitation the rights to use, copy, modify, merge, publish, * |
| 13 | * distribute, sublicense, and/or sell copies of the Software, and to * |
| 14 | * permit persons to whom the Software is furnished to do so, subject to * |
| 15 | * the following conditions: * |
| 16 | * * |
| 17 | * The above copyright notice and this permission notice shall be * |
| 18 | * included in all copies or substantial portions of the Software. * |
| 19 | * * |
| 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * |
| 21 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * |
| 22 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.* |
| 23 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * |
| 24 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * |
| 25 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * |
| 26 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * |
| 27 | ************************************************************************/ |
| 28 | |
| 29 | #include <stdlib.h> |
| 30 | #include <string.h> |
| 31 | #include <assert.h> |
| 32 | |
| 33 | #include "lua.h" |
| 34 | #include "lauxlib.h" |
| 35 | |
| 36 | #include "sqlite3.h" |
| 37 | |
| 38 | /* compile time features */ |
| 39 | #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) |
| 40 | #define SQLITE_OMIT_PROGRESS_CALLBACK 0 |
| 41 | #endif |
| 42 | |
| 43 | typedef struct sdb sdb; |
| 44 | typedef struct sdb_vm sdb_vm; |
| 45 | typedef struct sdb_func sdb_func; |
| 46 | |
| 47 | /* to use as C user data so i know what function sqlite is calling */ |
| 48 | struct sdb_func { |
| 49 | /* references to associated lua values */ |
| 50 | int fn_step; |
| 51 | int fn_finalize; |
| 52 | int udata; |
| 53 | |
| 54 | sdb *db; |
| 55 | char aggregate; |
| 56 | |
| 57 | sdb_func *next; |
| 58 | }; |
| 59 | |
| 60 | /* information about database */ |
| 61 | struct sdb { |
| 62 | /* associated lua state */ |
| 63 | lua_State *L; |
| 64 | /* sqlite database handle */ |
| 65 | sqlite3 *db; |
| 66 | |
| 67 | /* sql functions stack usage */ |
| 68 | sdb_func *func; /* top SQL function being called */ |
| 69 | |
| 70 | /* references */ |
| 71 | int busy_cb; /* busy callback */ |
| 72 | int busy_udata; |
| 73 | |
| 74 | int progress_cb; /* progress handler */ |
| 75 | int progress_udata; |
| 76 | |
| 77 | int trace_cb; /* trace callback */ |
| 78 | int trace_udata; |
| 79 | }; |
| 80 | |
| 81 | static const char *sqlite_meta = ":sqlite3"; |
| 82 | static const char *sqlite_vm_meta = ":sqlite3:vm"; |
| 83 | static const char *sqlite_ctx_meta = ":sqlite3:ctx"; |
| 84 | static int sqlite_ctx_meta_ref; |
| 85 | |
| 86 | /* |
| 87 | ** ======================================================= |
| 88 | ** Database Virtual Machine Operations |
| 89 | ** ======================================================= |
| 90 | */ |
| 91 | |
| 92 | static void vm_push_column(lua_State *L, sqlite3_stmt *vm, int idx) { |
| 93 | switch (sqlite3_column_type(vm, idx)) { |
| 94 | case SQLITE_INTEGER: |
| 95 | { |
| 96 | sqlite_int64 i64 = sqlite3_column_int64(vm, idx); |
| 97 | lua_Number n = (lua_Number)i64; |
| 98 | if (n == i64) |
| 99 | lua_pushnumber(L, n); |
| 100 | else |
| 101 | lua_pushlstring(L, sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx)); |
| 102 | } |
| 103 | break; |
| 104 | case SQLITE_FLOAT: |
| 105 | lua_pushnumber(L, sqlite3_column_double(vm, idx)); |
| 106 | break; |
| 107 | case SQLITE_TEXT: |
| 108 | lua_pushlstring(L, sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx)); |
| 109 | break; |
| 110 | case SQLITE_BLOB: |
| 111 | lua_pushlstring(L, sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx)); |
| 112 | break; |
| 113 | case SQLITE_NULL: |
| 114 | lua_pushnil(L); |
| 115 | break; |
| 116 | default: |
| 117 | lua_pushnil(L); |
| 118 | break; |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /* virtual machine information */ |
| 123 | struct sdb_vm { |
| 124 | sdb *db; /* associated database handle */ |
| 125 | sqlite3_stmt *vm; /* virtual machine */ |
| 126 | |
| 127 | /* sqlite3_step info */ |
| 128 | int columns; /* number of columns in result */ |
| 129 | char has_values; /* true when step succeeds */ |
| 130 | |
| 131 | char temp; /* temporary vm used in db:rows */ |
| 132 | }; |
| 133 | |
| 134 | /* called with sql text on the lua stack */ |
| 135 | static sdb_vm *newvm(lua_State *L, sdb *db) { |
| 136 | sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm)); |
| 137 | |
| 138 | luaL_getmetatable(L, sqlite_vm_meta); |
| 139 | lua_setmetatable(L, -2); /* set metatable */ |
| 140 | |
| 141 | svm->db = db; |
| 142 | svm->columns = 0; |
| 143 | svm->has_values = 0; |
| 144 | svm->vm = NULL; |
| 145 | svm->temp = 0; |
| 146 | |
| 147 | /* add an entry on the database table: svm -> sql text */ |
| 148 | lua_pushlightuserdata(L, db); |
| 149 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 150 | lua_pushlightuserdata(L, svm); |
| 151 | lua_pushvalue(L, -4); /* the sql text */ |
| 152 | lua_rawset(L, -3); |
| 153 | lua_pop(L, 1); |
| 154 | |
| 155 | return svm; |
| 156 | } |
| 157 | |
| 158 | static int cleanupvm(lua_State *L, sdb_vm *svm) { |
| 159 | /* remove entry in database table - no harm if not present in the table */ |
| 160 | lua_pushlightuserdata(L, svm->db); |
| 161 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 162 | lua_pushlightuserdata(L, svm); |
| 163 | lua_pushnil(L); |
| 164 | lua_rawset(L, -3); |
| 165 | lua_pop(L, 1); |
| 166 | |
| 167 | svm->columns = 0; |
| 168 | svm->has_values = 0; |
| 169 | |
| 170 | if (!svm->vm) return 0; |
| 171 | |
| 172 | lua_pushnumber(L, sqlite3_finalize(svm->vm)); |
| 173 | svm->vm = NULL; |
| 174 | return 1; |
| 175 | } |
| 176 | |
| 177 | static int stepvm(lua_State *L, sdb_vm *svm) { |
| 178 | int result; |
| 179 | int loop_limit = 3; |
| 180 | while ( loop_limit-- ) { |
| 181 | result = sqlite3_step(svm->vm); |
| 182 | if ( result==SQLITE_ERROR ) { |
| 183 | result = sqlite3_reset (svm->vm); |
| 184 | } |
| 185 | if ( result==SQLITE_SCHEMA ) { |
| 186 | sqlite3_stmt *vn; |
| 187 | const char *sql; |
| 188 | /* recover sql text */ |
| 189 | lua_pushlightuserdata(L, svm->db); |
| 190 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 191 | lua_pushlightuserdata(L, svm); |
| 192 | lua_rawget(L, -2); /* sql text */ |
| 193 | sql = luaL_checkstring(L, -1); |
| 194 | /* re-prepare */ |
| 195 | result = sqlite3_prepare(svm->db->db, sql, -1, &vn, NULL); |
| 196 | if (result != SQLITE_OK) break; |
| 197 | sqlite3_transfer_bindings(svm->vm, vn); |
| 198 | sqlite3_finalize(svm->vm); |
| 199 | svm->vm = vn; |
| 200 | lua_pop(L,2); |
| 201 | } else { |
| 202 | break; |
| 203 | } |
| 204 | } |
| 205 | return result; |
| 206 | } |
| 207 | |
| 208 | static sdb_vm *lsqlite_getvm(lua_State *L, int index) { |
| 209 | sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta); |
| 210 | if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine"); |
| 211 | return svm; |
| 212 | } |
| 213 | |
| 214 | static sdb_vm *lsqlite_checkvm(lua_State *L, int index) { |
| 215 | sdb_vm *svm = lsqlite_getvm(L, index); |
| 216 | if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine"); |
| 217 | return svm; |
| 218 | } |
| 219 | |
| 220 | static int dbvm_isopen(lua_State *L) { |
| 221 | sdb_vm *svm = lsqlite_getvm(L, 1); |
| 222 | lua_pushboolean(L, svm->vm != NULL ? 1 : 0); |
| 223 | return 1; |
| 224 | } |
| 225 | |
| 226 | static int dbvm_tostring(lua_State *L) { |
| 227 | char buff[39]; |
| 228 | sdb_vm *svm = lsqlite_getvm(L, 1); |
| 229 | if (svm->vm == NULL) |
| 230 | strcpy(buff, "closed"); |
| 231 | else |
| 232 | sprintf(buff, "%p", svm); |
| 233 | lua_pushfstring(L, "sqlite virtual machine (%s)", buff); |
| 234 | return 1; |
| 235 | } |
| 236 | |
| 237 | static int dbvm_gc(lua_State *L) { |
| 238 | sdb_vm *svm = lsqlite_getvm(L, 1); |
| 239 | if (svm->vm != NULL) /* ignore closed vms */ |
| 240 | cleanupvm(L, svm); |
| 241 | return 0; |
| 242 | } |
| 243 | |
| 244 | static int dbvm_step(lua_State *L) { |
| 245 | int result; |
| 246 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 247 | |
| 248 | result = stepvm(L, svm); |
| 249 | svm->has_values = result == SQLITE_ROW ? 1 : 0; |
| 250 | svm->columns = sqlite3_data_count(svm->vm); |
| 251 | |
| 252 | lua_pushnumber(L, result); |
| 253 | return 1; |
| 254 | } |
| 255 | |
| 256 | static int dbvm_finalize(lua_State *L) { |
| 257 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 258 | return cleanupvm(L, svm); |
| 259 | } |
| 260 | |
| 261 | static int dbvm_reset(lua_State *L) { |
| 262 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 263 | sqlite3_reset(svm->vm); |
| 264 | lua_pushnumber(L, sqlite3_errcode(svm->db->db)); |
| 265 | return 1; |
| 266 | } |
| 267 | |
| 268 | static void dbvm_check_contents(lua_State *L, sdb_vm *svm) { |
| 269 | if (!svm->has_values) { |
| 270 | luaL_error(L, "misuse of function"); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | static void dbvm_check_index(lua_State *L, sdb_vm *svm, int index) { |
| 275 | if (index < 0 || index >= svm->columns) { |
| 276 | luaL_error(L, "index out of range [0..%d]", svm->columns - 1); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | static void dbvm_check_bind_index(lua_State *L, sdb_vm *svm, int index) { |
| 281 | if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) { |
| 282 | luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm)); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /* |
| 287 | ** ======================================================= |
| 288 | ** Virtual Machine - generic info |
| 289 | ** ======================================================= |
| 290 | */ |
| 291 | static int dbvm_columns(lua_State *L) { |
| 292 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 293 | lua_pushnumber(L, sqlite3_column_count(svm->vm)); |
| 294 | return 1; |
| 295 | } |
| 296 | |
| 297 | /* |
| 298 | ** ======================================================= |
| 299 | ** Virtual Machine - getters |
| 300 | ** ======================================================= |
| 301 | */ |
| 302 | |
| 303 | static int dbvm_get_value(lua_State *L) { |
| 304 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 305 | int index = luaL_checkint(L, 2); |
| 306 | dbvm_check_contents(L, svm); |
| 307 | dbvm_check_index(L, svm, index); |
| 308 | vm_push_column(L, svm->vm, index); |
| 309 | return 1; |
| 310 | } |
| 311 | |
| 312 | static int dbvm_get_name(lua_State *L) { |
| 313 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 314 | int index = luaL_checknumber(L, 2); |
| 315 | dbvm_check_index(L, svm, index); |
| 316 | lua_pushstring(L, sqlite3_column_name(svm->vm, index)); |
| 317 | return 1; |
| 318 | } |
| 319 | |
| 320 | static int dbvm_get_type(lua_State *L) { |
| 321 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 322 | int index = luaL_checknumber(L, 2); |
| 323 | dbvm_check_index(L, svm, index); |
| 324 | lua_pushstring(L, sqlite3_column_decltype(svm->vm, index)); |
| 325 | return 1; |
| 326 | } |
| 327 | |
| 328 | static int dbvm_get_values(lua_State *L) { |
| 329 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 330 | sqlite3_stmt *vm = svm->vm; |
| 331 | int columns = svm->columns; |
| 332 | int n; |
| 333 | dbvm_check_contents(L, svm); |
| 334 | |
| 335 | lua_newtable(L); |
| 336 | for (n = 0; n < columns;) { |
| 337 | vm_push_column(L, vm, n++); |
| 338 | lua_rawseti(L, -2, n); |
| 339 | } |
| 340 | return 1; |
| 341 | } |
| 342 | |
| 343 | static int dbvm_get_names(lua_State *L) { |
| 344 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 345 | sqlite3_stmt *vm = svm->vm; |
| 346 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 347 | int n; |
| 348 | |
| 349 | lua_newtable(L); |
| 350 | for (n = 0; n < columns;) { |
| 351 | lua_pushstring(L, sqlite3_column_name(vm, n++)); |
| 352 | lua_rawseti(L, -2, n); |
| 353 | } |
| 354 | return 1; |
| 355 | } |
| 356 | |
| 357 | static int dbvm_get_types(lua_State *L) { |
| 358 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 359 | sqlite3_stmt *vm = svm->vm; |
| 360 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 361 | int n; |
| 362 | |
| 363 | lua_newtable(L); |
| 364 | for (n = 0; n < columns;) { |
| 365 | lua_pushstring(L, sqlite3_column_decltype(vm, n++)); |
| 366 | lua_rawseti(L, -2, n); |
| 367 | } |
| 368 | return 1; |
| 369 | } |
| 370 | |
| 371 | static int dbvm_get_uvalues(lua_State *L) { |
| 372 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 373 | sqlite3_stmt *vm = svm->vm; |
| 374 | int columns = svm->columns; |
| 375 | int n; |
| 376 | dbvm_check_contents(L, svm); |
| 377 | |
| 378 | lua_checkstack(L, columns); |
| 379 | for (n = 0; n < columns; ++n) |
| 380 | vm_push_column(L, vm, n); |
| 381 | return columns; |
| 382 | } |
| 383 | |
| 384 | static int dbvm_get_unames(lua_State *L) { |
| 385 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 386 | sqlite3_stmt *vm = svm->vm; |
| 387 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 388 | int n; |
| 389 | |
| 390 | lua_checkstack(L, columns); |
| 391 | for (n = 0; n < columns; ++n) |
| 392 | lua_pushstring(L, sqlite3_column_name(vm, n)); |
| 393 | return columns; |
| 394 | } |
| 395 | |
| 396 | static int dbvm_get_utypes(lua_State *L) { |
| 397 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 398 | sqlite3_stmt *vm = svm->vm; |
| 399 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 400 | int n; |
| 401 | |
| 402 | lua_checkstack(L, columns); |
| 403 | for (n = 0; n < columns; ++n) |
| 404 | lua_pushstring(L, sqlite3_column_decltype(vm, n)); |
| 405 | return columns; |
| 406 | } |
| 407 | |
| 408 | static int dbvm_get_named_values(lua_State *L) { |
| 409 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 410 | sqlite3_stmt *vm = svm->vm; |
| 411 | int columns = svm->columns; |
| 412 | int n; |
| 413 | dbvm_check_contents(L, svm); |
| 414 | |
| 415 | lua_newtable(L); |
| 416 | for (n = 0; n < columns; ++n) { |
| 417 | lua_pushstring(L, sqlite3_column_name(vm, n)); |
| 418 | vm_push_column(L, vm, n); |
| 419 | lua_rawset(L, -3); |
| 420 | } |
| 421 | return 1; |
| 422 | } |
| 423 | |
| 424 | static int dbvm_get_named_types(lua_State *L) { |
| 425 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 426 | sqlite3_stmt *vm = svm->vm; |
| 427 | int columns = sqlite3_column_count(vm); |
| 428 | int n; |
| 429 | |
| 430 | lua_newtable(L); |
| 431 | for (n = 0; n < columns; ++n) { |
| 432 | lua_pushstring(L, sqlite3_column_name(vm, n)); |
| 433 | lua_pushstring(L, sqlite3_column_decltype(vm, n)); |
| 434 | lua_rawset(L, -3); |
| 435 | } |
| 436 | return 1; |
| 437 | } |
| 438 | |
| 439 | /* |
| 440 | ** ======================================================= |
| 441 | ** Virtual Machine - Bind |
| 442 | ** ======================================================= |
| 443 | */ |
| 444 | |
| 445 | static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) { |
| 446 | switch (lua_type(L, lindex)) { |
| 447 | case LUA_TSTRING: |
| 448 | return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT); |
| 449 | case LUA_TNUMBER: |
| 450 | return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex)); |
| 451 | case LUA_TNONE: |
| 452 | case LUA_TNIL: |
| 453 | /* allow boolean values so i have a way to know which |
| 454 | ** values were actually not set */ |
| 455 | case LUA_TBOOLEAN: |
| 456 | return sqlite3_bind_null(vm, index); |
| 457 | default: |
| 458 | luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lindex)); |
| 459 | return SQLITE_MISUSE; /*!*/ |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | |
| 464 | static int dbvm_bind_parameter_count(lua_State *L) { |
| 465 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 466 | lua_pushnumber(L, sqlite3_bind_parameter_count(svm->vm)); |
| 467 | return 1; |
| 468 | } |
| 469 | |
| 470 | static int dbvm_bind_parameter_name(lua_State *L) { |
| 471 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 472 | int index = luaL_checknumber(L, 2); |
| 473 | dbvm_check_bind_index(L, svm, index); |
| 474 | lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index)); |
| 475 | return 1; |
| 476 | } |
| 477 | |
| 478 | static int dbvm_bind(lua_State *L) { |
| 479 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 480 | sqlite3_stmt *vm = svm->vm; |
| 481 | int index = luaL_checkint(L, 2); |
| 482 | int result; |
| 483 | |
| 484 | dbvm_check_bind_index(L, svm, index); |
| 485 | result = dbvm_bind_index(L, vm, index, 3); |
| 486 | |
| 487 | lua_pushnumber(L, result); |
| 488 | return 1; |
| 489 | } |
| 490 | |
| 491 | static int dbvm_bind_blob(lua_State *L) { |
| 492 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 493 | int index = luaL_checkint(L, 2); |
| 494 | const char *value = luaL_checkstring(L, 3); |
| 495 | int len = lua_strlen(L, 3); |
| 496 | |
| 497 | lua_pushnumber(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT)); |
| 498 | return 1; |
| 499 | } |
| 500 | |
| 501 | static int dbvm_bind_values(lua_State *L) { |
| 502 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 503 | sqlite3_stmt *vm = svm->vm; |
| 504 | int top = lua_gettop(L); |
| 505 | int result, n; |
| 506 | |
| 507 | if (top - 1 != sqlite3_bind_parameter_count(vm)) |
| 508 | luaL_error(L, |
| 509 | "incorrect number of parameters to bind (%d given, %d to bind)", |
| 510 | top - 1, |
| 511 | sqlite3_bind_parameter_count(vm) |
| 512 | ); |
| 513 | |
| 514 | for (n = 2; n <= top; ++n) { |
| 515 | if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) { |
| 516 | lua_pushnumber(L, result); |
| 517 | return 1; |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | lua_pushnumber(L, SQLITE_OK); |
| 522 | return 1; |
| 523 | } |
| 524 | |
| 525 | static int dbvm_bind_names(lua_State *L) { |
| 526 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 527 | sqlite3_stmt *vm = svm->vm; |
| 528 | int count = sqlite3_bind_parameter_count(vm); |
| 529 | const char *name; |
| 530 | int result, n; |
| 531 | luaL_checktype(L, 2, LUA_TTABLE); |
| 532 | |
| 533 | for (n = 1; n <= count; ++n) { |
| 534 | name = sqlite3_bind_parameter_name(vm, n); |
| 535 | if (name && (name[0] == ':' || name[0] == '$')) { |
| 536 | lua_pushstring(L, ++name); |
| 537 | lua_gettable(L, 2); |
| 538 | result = dbvm_bind_index(L, vm, n, -1); |
| 539 | } |
| 540 | else { |
| 541 | lua_pushnumber(L, n); |
| 542 | lua_gettable(L, 2); |
| 543 | result = dbvm_bind_index(L, vm, n, -1); |
| 544 | lua_pop(L, 1); |
| 545 | } |
| 546 | |
| 547 | if (result != SQLITE_OK) { |
| 548 | lua_pushnumber(L, result); |
| 549 | return 1; |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | lua_pushnumber(L, SQLITE_OK); |
| 554 | return 1; |
| 555 | } |
| 556 | |
| 557 | /* |
| 558 | ** ======================================================= |
| 559 | ** Database (internal management) |
| 560 | ** ======================================================= |
| 561 | */ |
| 562 | |
| 563 | /* |
| 564 | ** When creating database handles, always creates a `closed' database handle |
| 565 | ** before opening the actual database; so, if there is a memory error, the |
| 566 | ** database is not left opened. |
| 567 | ** |
| 568 | ** Creates a new 'table' and leaves it in the stack |
| 569 | */ |
| 570 | static sdb *newdb (lua_State *L) { |
| 571 | sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb)); |
| 572 | db->L = L; |
| 573 | db->db = NULL; /* database handle is currently `closed' */ |
| 574 | db->func = NULL; |
| 575 | |
| 576 | db->busy_cb = |
| 577 | db->busy_udata = |
| 578 | db->progress_cb = |
| 579 | db->progress_udata = |
| 580 | db->trace_cb = |
| 581 | db->trace_udata = LUA_NOREF; |
| 582 | |
| 583 | luaL_getmetatable(L, sqlite_meta); |
| 584 | lua_setmetatable(L, -2); /* set metatable */ |
| 585 | |
| 586 | /* to keep track of 'open' virtual machines */ |
| 587 | lua_pushlightuserdata(L, db); |
| 588 | lua_newtable(L); |
| 589 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 590 | |
| 591 | return db; |
| 592 | } |
| 593 | |
| 594 | static int cleanupdb(lua_State *L, sdb *db) { |
| 595 | sdb_func *func; |
| 596 | sdb_func *func_next; |
| 597 | int top; |
| 598 | int result; |
| 599 | |
| 600 | /* free associated virtual machines */ |
| 601 | lua_pushlightuserdata(L, db); |
| 602 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 603 | |
| 604 | /* close all used handles */ |
| 605 | top = lua_gettop(L); |
| 606 | lua_pushnil(L); |
| 607 | while (lua_next(L, -2)) { |
| 608 | sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */ |
| 609 | cleanupvm(L, svm); |
| 610 | |
| 611 | lua_settop(L, top); |
| 612 | lua_pushnil(L); |
| 613 | } |
| 614 | |
| 615 | lua_pop(L, 1); /* pop vm table */ |
| 616 | |
| 617 | /* remove entry in lua registry table */ |
| 618 | lua_pushlightuserdata(L, db); |
| 619 | lua_pushnil(L); |
| 620 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 621 | |
| 622 | /* 'free' all references */ |
| 623 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 624 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 625 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 626 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 627 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb); |
| 628 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata); |
| 629 | |
| 630 | /* close database */ |
| 631 | result = sqlite3_close(db->db); |
| 632 | db->db = NULL; |
| 633 | |
| 634 | /* free associated memory with created functions */ |
| 635 | func = db->func; |
| 636 | while (func) { |
| 637 | func_next = func->next; |
| 638 | luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step); |
| 639 | luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize); |
| 640 | luaL_unref(L, LUA_REGISTRYINDEX, func->udata); |
| 641 | free(func); |
| 642 | func = func_next; |
| 643 | } |
| 644 | db->func = NULL; |
| 645 | return result; |
| 646 | } |
| 647 | |
| 648 | static sdb *lsqlite_getdb(lua_State *L, int index) { |
| 649 | sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta); |
| 650 | if (db == NULL) luaL_typerror(L, index, "sqlite database"); |
| 651 | return db; |
| 652 | } |
| 653 | |
| 654 | static sdb *lsqlite_checkdb(lua_State *L, int index) { |
| 655 | sdb *db = lsqlite_getdb(L, index); |
| 656 | if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database"); |
| 657 | return db; |
| 658 | } |
| 659 | |
| 660 | |
| 661 | /* |
| 662 | ** ======================================================= |
| 663 | ** User Defined Functions - Context Methods |
| 664 | ** ======================================================= |
| 665 | */ |
| 666 | typedef struct { |
| 667 | sqlite3_context *ctx; |
| 668 | int ud; |
| 669 | } lcontext; |
| 670 | |
| 671 | static lcontext *lsqlite_make_context(lua_State *L) { |
| 672 | lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext)); |
| 673 | lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref); |
| 674 | lua_setmetatable(L, -2); |
| 675 | ctx->ctx = NULL; |
| 676 | ctx->ud = LUA_NOREF; |
| 677 | return ctx; |
| 678 | } |
| 679 | |
| 680 | static lcontext *lsqlite_getcontext(lua_State *L, int index) { |
| 681 | lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta); |
| 682 | if (ctx == NULL) luaL_typerror(L, index, "sqlite context"); |
| 683 | return ctx; |
| 684 | } |
| 685 | |
| 686 | static lcontext *lsqlite_checkcontext(lua_State *L, int index) { |
| 687 | lcontext *ctx = lsqlite_getcontext(L, index); |
| 688 | if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context"); |
| 689 | return ctx; |
| 690 | } |
| 691 | |
| 692 | static int lcontext_tostring(lua_State *L) { |
| 693 | char buff[39]; |
| 694 | lcontext *ctx = lsqlite_getcontext(L, 1); |
| 695 | if (ctx->ctx == NULL) |
| 696 | strcpy(buff, "closed"); |
| 697 | else |
| 698 | sprintf(buff, "%p", ctx->ctx); |
| 699 | lua_pushfstring(L, "sqlite function context (%s)", buff); |
| 700 | return 1; |
| 701 | } |
| 702 | |
| 703 | static void lcontext_check_aggregate(lua_State *L, lcontext *ctx) { |
| 704 | sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx); |
| 705 | if (!func->aggregate) { |
| 706 | luaL_error(L, "attempt to call aggregate method from scalar function"); |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | static int lcontext_user_data(lua_State *L) { |
| 711 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 712 | sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx); |
| 713 | lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata); |
| 714 | return 1; |
| 715 | } |
| 716 | |
| 717 | static int lcontext_get_aggregate_context(lua_State *L) { |
| 718 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 719 | lcontext_check_aggregate(L, ctx); |
| 720 | lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud); |
| 721 | return 1; |
| 722 | } |
| 723 | |
| 724 | static int lcontext_set_aggregate_context(lua_State *L) { |
| 725 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 726 | lcontext_check_aggregate(L, ctx); |
| 727 | lua_settop(L, 2); |
| 728 | luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); |
| 729 | ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX); |
| 730 | return 0; |
| 731 | } |
| 732 | |
| 733 | static int lcontext_aggregate_count(lua_State *L) { |
| 734 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 735 | lcontext_check_aggregate(L, ctx); |
| 736 | lua_pushnumber(L, sqlite3_aggregate_count(ctx->ctx)); |
| 737 | return 1; |
| 738 | } |
| 739 | |
| 740 | #if 0 |
| 741 | void *sqlite3_get_auxdata(sqlite3_context*, int); |
| 742 | void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); |
| 743 | #endif |
| 744 | |
| 745 | static int lcontext_result(lua_State *L) { |
| 746 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 747 | switch (lua_type(L, 2)) { |
| 748 | case LUA_TNUMBER: |
| 749 | sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2)); |
| 750 | break; |
| 751 | case LUA_TSTRING: |
| 752 | sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT); |
| 753 | break; |
| 754 | case LUA_TNIL: |
| 755 | case LUA_TNONE: |
| 756 | sqlite3_result_null(ctx->ctx); |
| 757 | break; |
| 758 | default: |
| 759 | luaL_error(L, "invalid result type %s", lua_typename(L, 2)); |
| 760 | break; |
| 761 | } |
| 762 | |
| 763 | return 0; |
| 764 | } |
| 765 | |
| 766 | static int lcontext_result_blob(lua_State *L) { |
| 767 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 768 | const char *blob = luaL_checkstring(L, 2); |
| 769 | int size = lua_strlen(L, 2); |
| 770 | sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT); |
| 771 | return 0; |
| 772 | } |
| 773 | |
| 774 | static int lcontext_result_double(lua_State *L) { |
| 775 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 776 | double d = luaL_checknumber(L, 2); |
| 777 | sqlite3_result_double(ctx->ctx, d); |
| 778 | return 0; |
| 779 | } |
| 780 | |
| 781 | static int lcontext_result_error(lua_State *L) { |
| 782 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 783 | const char *err = luaL_checkstring(L, 2); |
| 784 | int size = lua_strlen(L, 2); |
| 785 | sqlite3_result_error(ctx->ctx, err, size); |
| 786 | return 0; |
| 787 | } |
| 788 | |
| 789 | static int lcontext_result_int(lua_State *L) { |
| 790 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 791 | int i = luaL_checkint(L, 2); |
| 792 | sqlite3_result_int(ctx->ctx, i); |
| 793 | return 0; |
| 794 | } |
| 795 | |
| 796 | static int lcontext_result_null(lua_State *L) { |
| 797 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 798 | sqlite3_result_null(ctx->ctx); |
| 799 | return 0; |
| 800 | } |
| 801 | |
| 802 | static int lcontext_result_text(lua_State *L) { |
| 803 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 804 | const char *text = luaL_checkstring(L, 2); |
| 805 | int size = lua_strlen(L, 2); |
| 806 | sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT); |
| 807 | return 0; |
| 808 | } |
| 809 | |
| 810 | /* |
| 811 | ** ======================================================= |
| 812 | ** Database Methods |
| 813 | ** ======================================================= |
| 814 | */ |
| 815 | |
| 816 | static int db_isopen(lua_State *L) { |
| 817 | sdb *db = lsqlite_getdb(L, 1); |
| 818 | lua_pushboolean(L, db->db != NULL ? 1 : 0); |
| 819 | return 1; |
| 820 | } |
| 821 | |
| 822 | static int db_last_insert_rowid(lua_State *L) { |
| 823 | sdb *db = lsqlite_checkdb(L, 1); |
| 824 | /* conversion warning: int64 -> luaNumber */ |
| 825 | sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db); |
| 826 | lua_Number n = (lua_Number)rowid; |
| 827 | if (n == rowid) |
| 828 | lua_pushnumber(L, n); |
| 829 | else |
| 830 | lua_pushfstring(L, "%ll", rowid); |
| 831 | return 1; |
| 832 | } |
| 833 | |
| 834 | static int db_changes(lua_State *L) { |
| 835 | sdb *db = lsqlite_checkdb(L, 1); |
| 836 | lua_pushnumber(L, sqlite3_changes(db->db)); |
| 837 | return 1; |
| 838 | } |
| 839 | |
| 840 | static int db_total_changes(lua_State *L) { |
| 841 | sdb *db = lsqlite_checkdb(L, 1); |
| 842 | lua_pushnumber(L, sqlite3_total_changes(db->db)); |
| 843 | return 1; |
| 844 | } |
| 845 | |
| 846 | static int db_errcode(lua_State *L) { |
| 847 | sdb *db = lsqlite_checkdb(L, 1); |
| 848 | lua_pushnumber(L, sqlite3_errcode(db->db)); |
| 849 | return 1; |
| 850 | } |
| 851 | |
| 852 | static int db_errmsg(lua_State *L) { |
| 853 | sdb *db = lsqlite_checkdb(L, 1); |
| 854 | lua_pushstring(L, sqlite3_errmsg(db->db)); |
| 855 | return 1; |
| 856 | } |
| 857 | |
| 858 | static int db_interrupt(lua_State *L) { |
| 859 | sdb *db = lsqlite_checkdb(L, 1); |
| 860 | sqlite3_interrupt(db->db); |
| 861 | return 0; |
| 862 | } |
| 863 | |
| 864 | /* |
| 865 | ** Registering SQL functions: |
| 866 | */ |
| 867 | |
| 868 | static void db_push_value(lua_State *L, sqlite3_value *value) { |
| 869 | switch (sqlite3_value_type(value)) { |
| 870 | case SQLITE_TEXT: |
| 871 | lua_pushlstring(L, sqlite3_value_text(value), sqlite3_value_bytes(value)); |
| 872 | break; |
| 873 | |
| 874 | case SQLITE_INTEGER: |
| 875 | { |
| 876 | sqlite_int64 i64 = sqlite3_value_int64(value); |
| 877 | lua_Number n = (lua_Number)i64; |
| 878 | if (n == i64) |
| 879 | lua_pushnumber(L, n); |
| 880 | else |
| 881 | lua_pushlstring(L, sqlite3_value_text(value), sqlite3_value_bytes(value)); |
| 882 | } |
| 883 | break; |
| 884 | |
| 885 | case SQLITE_FLOAT: |
| 886 | lua_pushnumber(L, sqlite3_value_double(value)); |
| 887 | break; |
| 888 | |
| 889 | case SQLITE_BLOB: |
| 890 | lua_pushlstring(L, sqlite3_value_blob(value), sqlite3_value_bytes(value)); |
| 891 | break; |
| 892 | |
| 893 | case SQLITE_NULL: |
| 894 | lua_pushnil(L); |
| 895 | break; |
| 896 | |
| 897 | default: |
| 898 | /* things done properly (SQLite + Lua SQLite) |
| 899 | ** this should never happen */ |
| 900 | lua_pushnil(L); |
| 901 | break; |
| 902 | } |
| 903 | } |
| 904 | |
| 905 | /* |
| 906 | ** callback functions used when calling registered sql functions |
| 907 | */ |
| 908 | |
| 909 | /* scalar function to be called |
| 910 | ** callback params: context, values... */ |
| 911 | static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv) { |
| 912 | sdb_func *func = (sdb_func*)sqlite3_user_data(context); |
| 913 | lua_State *L = func->db->L; |
| 914 | int n; |
| 915 | lcontext *ctx; |
| 916 | |
| 917 | int top = lua_gettop(L); |
| 918 | |
| 919 | /* ensure there is enough space in the stack */ |
| 920 | lua_checkstack(L, argc + 3); |
| 921 | |
| 922 | lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step); /* function to call */ |
| 923 | |
| 924 | if (!func->aggregate) { |
| 925 | ctx = lsqlite_make_context(L); /* push context - used to set results */ |
| 926 | } |
| 927 | else { |
| 928 | // reuse context userdata value |
| 929 | |
| 930 | void *p = sqlite3_aggregate_context(context, 1); |
| 931 | /* i think it is OK to use assume that using a light user data |
| 932 | ** as an entry on LUA REGISTRY table will be unique */ |
| 933 | lua_pushlightuserdata(L, p); |
| 934 | lua_rawget(L, LUA_REGISTRYINDEX); /* context table */ |
| 935 | |
| 936 | if (lua_isnil(L, -1)) { /* not yet created? */ |
| 937 | lua_pop(L, 1); |
| 938 | ctx = lsqlite_make_context(L); |
| 939 | lua_pushlightuserdata(L, p); |
| 940 | lua_pushvalue(L, -2); |
| 941 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 942 | } |
| 943 | else |
| 944 | ctx = lsqlite_getcontext(L, -1); |
| 945 | } |
| 946 | |
| 947 | /* push params */ |
| 948 | for (n = 0; n < argc; ++n) { |
| 949 | db_push_value(L, argv[n]); |
| 950 | } |
| 951 | |
| 952 | // set context |
| 953 | ctx->ctx = context; |
| 954 | |
| 955 | if (lua_pcall(L, argc + 1, 0, 0)) { |
| 956 | const char *errmsg = lua_tostring(L, -1); |
| 957 | int size = lua_strlen(L, -1); |
| 958 | sqlite3_result_error(context, errmsg, size); |
| 959 | } |
| 960 | |
| 961 | // invalidate context |
| 962 | ctx->ctx = NULL; |
| 963 | |
| 964 | if (!func->aggregate) { |
| 965 | luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); |
| 966 | } |
| 967 | |
| 968 | lua_settop(L, top); |
| 969 | } |
| 970 | |
| 971 | static void db_sql_finalize_function(sqlite3_context *context) { |
| 972 | sdb_func *func = (sdb_func*)sqlite3_user_data(context); |
| 973 | lua_State *L = func->db->L; |
| 974 | void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */ |
| 975 | lcontext *ctx; |
| 976 | int top = lua_gettop(L); |
| 977 | |
| 978 | lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize); /* function to call */ |
| 979 | |
| 980 | /* i think it is OK to use assume that using a light user data |
| 981 | ** as an entry on LUA REGISTRY table will be unique */ |
| 982 | lua_pushlightuserdata(L, p); |
| 983 | lua_rawget(L, LUA_REGISTRYINDEX); /* context table */ |
| 984 | |
| 985 | if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */ |
| 986 | lua_pop(L, 1); |
| 987 | ctx = lsqlite_make_context(L); |
| 988 | lua_pushlightuserdata(L, p); |
| 989 | lua_pushvalue(L, -2); |
| 990 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 991 | } |
| 992 | else |
| 993 | ctx = lsqlite_getcontext(L, -1); |
| 994 | |
| 995 | // set context |
| 996 | ctx->ctx = context; |
| 997 | |
| 998 | if (lua_pcall(L, 1, 0, 0)) { |
| 999 | sqlite3_result_error(context, lua_tostring(L, -1), -1); |
| 1000 | } |
| 1001 | |
| 1002 | // invalidate context |
| 1003 | ctx->ctx = NULL; |
| 1004 | |
| 1005 | /* cleanup context */ |
| 1006 | luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); |
| 1007 | /* remove it from registry */ |
| 1008 | lua_pushlightuserdata(L, p); |
| 1009 | lua_pushnil(L); |
| 1010 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 1011 | |
| 1012 | lua_settop(L, top); |
| 1013 | } |
| 1014 | |
| 1015 | /* |
| 1016 | ** Register a normal function |
| 1017 | ** Params: db, function name, number arguments, [ callback | step, finalize], user data |
| 1018 | ** Returns: true on sucess |
| 1019 | ** |
| 1020 | ** Normal function: |
| 1021 | ** Params: context, params |
| 1022 | ** |
| 1023 | ** Aggregate function: |
| 1024 | ** Params of step: context, params |
| 1025 | ** Params of finalize: context |
| 1026 | */ |
| 1027 | static int db_register_function(lua_State *L, int aggregate) { |
| 1028 | sdb *db = lsqlite_checkdb(L, 1); |
| 1029 | const char *name; |
| 1030 | int args; |
| 1031 | int result; |
| 1032 | sdb_func *func; |
| 1033 | |
| 1034 | /* safety measure */ |
| 1035 | if (aggregate) aggregate = 1; |
| 1036 | |
| 1037 | name = luaL_checkstring(L, 2); |
| 1038 | args = luaL_checkint(L, 3); |
| 1039 | luaL_checktype(L, 4, LUA_TFUNCTION); |
| 1040 | if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION); |
| 1041 | |
| 1042 | /* maybe an alternative way to allocate memory should be used/avoided */ |
| 1043 | func = (sdb_func*)malloc(sizeof(sdb_func)); |
| 1044 | if (func == NULL) { |
| 1045 | luaL_error(L, "out of memory"); |
| 1046 | } |
| 1047 | |
| 1048 | result = sqlite3_create_function( |
| 1049 | db->db, name, args, SQLITE_UTF8, func, |
| 1050 | aggregate ? NULL : db_sql_normal_function, |
| 1051 | aggregate ? db_sql_normal_function : NULL, |
| 1052 | aggregate ? db_sql_finalize_function : NULL |
| 1053 | ); |
| 1054 | |
| 1055 | if (result == SQLITE_OK) { |
| 1056 | /* safety measures for userdata field to be present in the stack */ |
| 1057 | lua_settop(L, 5 + aggregate); |
| 1058 | |
| 1059 | /* save registered function in db function list */ |
| 1060 | func->db = db; |
| 1061 | func->aggregate = aggregate; |
| 1062 | func->next = db->func; |
| 1063 | db->func = func; |
| 1064 | |
| 1065 | /* save the setp/normal function callback */ |
| 1066 | lua_pushvalue(L, 4); |
| 1067 | func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1068 | /* save user data */ |
| 1069 | lua_pushvalue(L, 5+aggregate); |
| 1070 | func->udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1071 | |
| 1072 | if (aggregate) { |
| 1073 | lua_pushvalue(L, 5); |
| 1074 | func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1075 | } |
| 1076 | else |
| 1077 | func->fn_finalize = LUA_NOREF; |
| 1078 | } |
| 1079 | else { |
| 1080 | /* free allocated memory */ |
| 1081 | free(func); |
| 1082 | } |
| 1083 | |
| 1084 | lua_pushboolean(L, result == SQLITE_OK ? 1 : 0); |
| 1085 | return 1; |
| 1086 | } |
| 1087 | |
| 1088 | static int db_create_function(lua_State *L) { |
| 1089 | return db_register_function(L, 0); |
| 1090 | } |
| 1091 | |
| 1092 | static int db_create_aggregate(lua_State *L) { |
| 1093 | return db_register_function(L, 1); |
| 1094 | } |
| 1095 | |
| 1096 | /* create_collation; contributed by Thomas Lauer |
| 1097 | */ |
| 1098 | |
| 1099 | typedef struct { |
| 1100 | lua_State *L; |
| 1101 | int ref; |
| 1102 | } scc; |
| 1103 | |
| 1104 | static int collwrapper(scc *co,int l1,const void *p1, |
| 1105 | int l2,const void *p2) { |
| 1106 | int res=0; |
| 1107 | lua_State *L=co->L; |
| 1108 | lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref); |
| 1109 | lua_pushlstring(L,p1,l1); |
| 1110 | lua_pushlstring(L,p2,l2); |
| 1111 | if (lua_pcall(L,2,1,0)==0) res=(int)lua_tonumber(L,-1); |
| 1112 | lua_pop(L,1); |
| 1113 | return res; |
| 1114 | } |
| 1115 | |
| 1116 | static void collfree(scc *co) { |
| 1117 | if (co) { |
| 1118 | luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref); |
| 1119 | free(co); |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | static int db_create_collation(lua_State *L) { |
| 1124 | sdb *db=lsqlite_checkdb(L,1); |
| 1125 | const char *collname=luaL_checkstring(L,2); |
| 1126 | scc *co=NULL; |
| 1127 | int (*collfunc)(scc *,int,const void *,int,const void *)=NULL; |
| 1128 | lua_settop(L,3); /* default args to nil, and exclude extras */ |
| 1129 | if (lua_isfunction(L,3)) collfunc=collwrapper; |
| 1130 | else if (!lua_isnil(L,3)) |
| 1131 | luaL_error(L,"create_collation: function or nil expected"); |
| 1132 | if (collfunc != NULL) { |
| 1133 | co=(scc *)malloc(sizeof(scc)); // userdata is a no-no as it |
| 1134 | // will be garbage-collected |
| 1135 | if (co) { |
| 1136 | co->L=L; |
| 1137 | /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */ |
| 1138 | co->ref=luaL_ref(L,LUA_REGISTRYINDEX); |
| 1139 | } |
| 1140 | else luaL_error(L,"create_collation: could not allocate callback"); |
| 1141 | } |
| 1142 | sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8, |
| 1143 | (void *)co, |
| 1144 | (int(*)(void*,int,const void*,int,const void*))collfunc, |
| 1145 | (void(*)(void*))collfree); |
| 1146 | return 0; |
| 1147 | } |
| 1148 | |
| 1149 | /* |
| 1150 | ** trace callback: |
| 1151 | ** Params: database, callback function, userdata |
| 1152 | ** |
| 1153 | ** callback function: |
| 1154 | ** Params: userdata, sql |
| 1155 | */ |
| 1156 | static void db_trace_callback(void *user, const char *sql) { |
| 1157 | sdb *db = (sdb*)user; |
| 1158 | lua_State *L = db->L; |
| 1159 | int top = lua_gettop(L); |
| 1160 | |
| 1161 | /* setup lua callback call */ |
| 1162 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_cb); /* get callback */ |
| 1163 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_udata); /* get callback user data */ |
| 1164 | lua_pushstring(L, sql); /* traced sql statement */ |
| 1165 | |
| 1166 | /* call lua function */ |
| 1167 | lua_pcall(L, 2, 0, 0); |
| 1168 | /* ignore any error generated by this function */ |
| 1169 | |
| 1170 | lua_settop(L, top); |
| 1171 | } |
| 1172 | |
| 1173 | static int db_trace(lua_State *L) { |
| 1174 | sdb *db = lsqlite_checkdb(L, 1); |
| 1175 | |
| 1176 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1177 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb); |
| 1178 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata); |
| 1179 | |
| 1180 | db->trace_cb = |
| 1181 | db->trace_udata = LUA_NOREF; |
| 1182 | |
| 1183 | /* clear busy handler */ |
| 1184 | sqlite3_trace(db->db, NULL, NULL); |
| 1185 | } |
| 1186 | else { |
| 1187 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1188 | |
| 1189 | /* make sure we have an userdata field (even if nil) */ |
| 1190 | lua_settop(L, 3); |
| 1191 | |
| 1192 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb); |
| 1193 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata); |
| 1194 | |
| 1195 | db->trace_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1196 | db->trace_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1197 | |
| 1198 | /* set busy handler */ |
| 1199 | sqlite3_trace(db->db, db_trace_callback, db); |
| 1200 | } |
| 1201 | |
| 1202 | return 0; |
| 1203 | } |
| 1204 | |
| 1205 | |
| 1206 | #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK |
| 1207 | |
| 1208 | /* |
| 1209 | ** progress handler: |
| 1210 | ** Params: database, number of opcodes, callback function, userdata |
| 1211 | ** |
| 1212 | ** callback function: |
| 1213 | ** Params: userdata |
| 1214 | ** returns: 0 to return immediatly and return SQLITE_ABORT, non-zero to continue |
| 1215 | */ |
| 1216 | static int db_progress_callback(void *user) { |
| 1217 | int result = 1; /* abort by default */ |
| 1218 | sdb *db = (sdb*)user; |
| 1219 | lua_State *L = db->L; |
| 1220 | int top = lua_gettop(L); |
| 1221 | |
| 1222 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 1223 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 1224 | |
| 1225 | /* call lua function */ |
| 1226 | if (!lua_pcall(L, 1, 1, 0)) |
| 1227 | result = lua_toboolean(L, -1); |
| 1228 | |
| 1229 | lua_settop(L, top); |
| 1230 | return result; |
| 1231 | } |
| 1232 | |
| 1233 | static int db_progress_handler(lua_State *L) { |
| 1234 | sdb *db = lsqlite_checkdb(L, 1); |
| 1235 | |
| 1236 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1237 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 1238 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 1239 | |
| 1240 | db->progress_cb = |
| 1241 | db->progress_udata = LUA_NOREF; |
| 1242 | |
| 1243 | /* clear busy handler */ |
| 1244 | sqlite3_progress_handler(db->db, 0, NULL, NULL); |
| 1245 | } |
| 1246 | else { |
| 1247 | int nop = luaL_checkint(L, 2); /* number of opcodes */ |
| 1248 | luaL_checktype(L, 3, LUA_TFUNCTION); |
| 1249 | |
| 1250 | /* make sure we have an userdata field (even if nil) */ |
| 1251 | lua_settop(L, 4); |
| 1252 | |
| 1253 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 1254 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 1255 | |
| 1256 | db->progress_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1257 | db->progress_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1258 | |
| 1259 | /* set progress callback */ |
| 1260 | sqlite3_progress_handler(db->db, nop, db_progress_callback, db); |
| 1261 | } |
| 1262 | |
| 1263 | return 0; |
| 1264 | } |
| 1265 | |
| 1266 | #else /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 1267 | |
| 1268 | static int db_progress_handler(lua_State *L) { |
| 1269 | lua_pushliteral(L, "progress callback support disabled at compile time"); |
| 1270 | lua_error(L); |
| 1271 | return 0; |
| 1272 | } |
| 1273 | |
| 1274 | #endif /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 1275 | |
| 1276 | /* |
| 1277 | ** busy handler: |
| 1278 | ** Params: database, callback function, userdata |
| 1279 | ** |
| 1280 | ** callback function: |
| 1281 | ** Params: userdata, number of tries |
| 1282 | ** returns: 0 to return immediatly and return SQLITE_BUSY, non-zero to try again |
| 1283 | */ |
| 1284 | static int db_busy_callback(void *user, int tries) { |
| 1285 | int retry = 0; /* abort by default */ |
| 1286 | sdb *db = (sdb*)user; |
| 1287 | lua_State *L = db->L; |
| 1288 | int top = lua_gettop(L); |
| 1289 | |
| 1290 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1291 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1292 | lua_pushnumber(L, tries); |
| 1293 | |
| 1294 | /* call lua function */ |
| 1295 | if (!lua_pcall(L, 2, 1, 0)) |
| 1296 | retry = lua_toboolean(L, -1); |
| 1297 | |
| 1298 | lua_settop(L, top); |
| 1299 | return retry; |
| 1300 | } |
| 1301 | |
| 1302 | static int db_busy_handler(lua_State *L) { |
| 1303 | sdb *db = lsqlite_checkdb(L, 1); |
| 1304 | |
| 1305 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1306 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1307 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1308 | |
| 1309 | db->busy_cb = |
| 1310 | db->busy_udata = LUA_NOREF; |
| 1311 | |
| 1312 | /* clear busy handler */ |
| 1313 | sqlite3_busy_handler(db->db, NULL, NULL); |
| 1314 | } |
| 1315 | else { |
| 1316 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1317 | /* make sure we have an userdata field (even if nil) */ |
| 1318 | lua_settop(L, 3); |
| 1319 | |
| 1320 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1321 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1322 | |
| 1323 | db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1324 | db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1325 | |
| 1326 | /* set busy handler */ |
| 1327 | sqlite3_busy_handler(db->db, db_busy_callback, db); |
| 1328 | } |
| 1329 | |
| 1330 | return 0; |
| 1331 | } |
| 1332 | |
| 1333 | static int db_busy_timeout(lua_State *L) { |
| 1334 | sdb *db = lsqlite_checkdb(L, 1); |
| 1335 | int timeout = luaL_checkint(L, 2); |
| 1336 | sqlite3_busy_timeout(db->db, timeout); |
| 1337 | |
| 1338 | /* if there was a timeout callback registered, it is now |
| 1339 | ** invalid/useless. free any references we may have */ |
| 1340 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1341 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1342 | db->busy_cb = |
| 1343 | db->busy_udata = LUA_NOREF; |
| 1344 | |
| 1345 | return 0; |
| 1346 | } |
| 1347 | |
| 1348 | /* |
| 1349 | ** Params: db, sql, callback, user |
| 1350 | ** returns: code [, errmsg] |
| 1351 | ** |
| 1352 | ** Callback: |
| 1353 | ** Params: user, number of columns, values, names |
| 1354 | ** Returns: 0 to continue, other value will cause abort |
| 1355 | */ |
| 1356 | static int db_exec_callback(void* user, int columns, char **data, char **names) { |
| 1357 | int result = SQLITE_ABORT; /* abort by default */ |
| 1358 | sdb *db = (sdb*)user; |
| 1359 | lua_State *L = db->L; |
| 1360 | int n; |
| 1361 | |
| 1362 | int top = lua_gettop(L); |
| 1363 | |
| 1364 | lua_pushvalue(L, 3); /* function to call */ |
| 1365 | lua_pushvalue(L, 4); /* user data */ |
| 1366 | lua_pushnumber(L, columns); /* total number of rows in result */ |
| 1367 | |
| 1368 | /* column values */ |
| 1369 | lua_pushvalue(L, 6); |
| 1370 | for (n = 0; n < columns;) { |
| 1371 | lua_pushstring(L, data[n++]); |
| 1372 | lua_rawseti(L, -2, n); |
| 1373 | } |
| 1374 | |
| 1375 | /* columns names */ |
| 1376 | lua_pushvalue(L, 5); |
| 1377 | if (lua_isnil(L, -1)) { |
| 1378 | lua_pop(L, 1); |
| 1379 | lua_newtable(L); |
| 1380 | lua_pushvalue(L, -1); |
| 1381 | lua_replace(L, 5); |
| 1382 | for (n = 0; n < columns;) { |
| 1383 | lua_pushstring(L, names[n++]); |
| 1384 | lua_rawseti(L, -2, n); |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | /* call lua function */ |
| 1389 | if (!lua_pcall(L, 4, 1, 0)) { |
| 1390 | if (lua_isnumber(L, -1)) |
| 1391 | result = lua_tonumber(L, -1); |
| 1392 | } |
| 1393 | |
| 1394 | lua_settop(L, top); |
| 1395 | return result; |
| 1396 | } |
| 1397 | |
| 1398 | static int db_exec(lua_State *L) { |
| 1399 | sdb *db = lsqlite_checkdb(L, 1); |
| 1400 | const char *sql = luaL_checkstring(L, 2); |
| 1401 | int result; |
| 1402 | |
| 1403 | if (!lua_isnoneornil(L, 3)) { |
| 1404 | /* stack: |
| 1405 | ** 3: callback function |
| 1406 | ** 4: userdata |
| 1407 | ** 5: column names |
| 1408 | ** 6: reusable column values |
| 1409 | */ |
| 1410 | luaL_checktype(L, 3, LUA_TFUNCTION); |
| 1411 | lua_settop(L, 4); /* 'trap' userdata - nil extra parameters */ |
| 1412 | lua_pushnil(L); /* column names not known at this point */ |
| 1413 | lua_newtable(L); /* column values table */ |
| 1414 | |
| 1415 | result = sqlite3_exec(db->db, sql, db_exec_callback, db, NULL); |
| 1416 | } |
| 1417 | else { |
| 1418 | /* no callbacks */ |
| 1419 | result = sqlite3_exec(db->db, sql, NULL, NULL, NULL); |
| 1420 | } |
| 1421 | |
| 1422 | lua_pushnumber(L, result); |
| 1423 | return 1; |
| 1424 | } |
| 1425 | |
| 1426 | /* |
| 1427 | ** Params: db, sql |
| 1428 | ** returns: code, compiled length or error message |
| 1429 | */ |
| 1430 | static int db_prepare(lua_State *L) { |
| 1431 | sdb *db = lsqlite_checkdb(L, 1); |
| 1432 | const char *sql = luaL_checkstring(L, 2); |
| 1433 | int sql_len = lua_strlen(L, 2); |
| 1434 | const char *sqltail; |
| 1435 | sdb_vm *svm; |
| 1436 | lua_settop(L,2); /* sql is on top of stack for call to newvm */ |
| 1437 | svm = newvm(L, db); |
| 1438 | |
| 1439 | if (sqlite3_prepare(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) { |
| 1440 | cleanupvm(L, svm); |
| 1441 | |
| 1442 | lua_pushnil(L); |
| 1443 | lua_pushnumber(L, sqlite3_errcode(db->db)); |
| 1444 | return 2; |
| 1445 | } |
| 1446 | |
| 1447 | /* vm already in the stack */ |
| 1448 | lua_pushstring(L, sqltail); |
| 1449 | return 2; |
| 1450 | } |
| 1451 | |
| 1452 | static int db_do_next_row(lua_State *L, int packed) { |
| 1453 | int result; |
| 1454 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 1455 | sqlite3_stmt *vm; |
| 1456 | int columns; |
| 1457 | int i; |
| 1458 | |
| 1459 | result = stepvm(L, svm); |
| 1460 | vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */ |
| 1461 | svm->has_values = result == SQLITE_ROW ? 1 : 0; |
| 1462 | svm->columns = columns = sqlite3_data_count(vm); |
| 1463 | |
| 1464 | if (result == SQLITE_ROW) { |
| 1465 | if (packed) { |
| 1466 | lua_newtable(L); |
| 1467 | if (packed == 1) { |
| 1468 | for (i = 0; i < columns;) { |
| 1469 | vm_push_column(L, vm, i); |
| 1470 | lua_rawseti(L, -2, ++i); |
| 1471 | } |
| 1472 | } |
| 1473 | else { |
| 1474 | for (i = 0; i < columns; ++i) { |
| 1475 | lua_pushstring(L, sqlite3_column_name(vm, i)); |
| 1476 | vm_push_column(L, vm, i); |
| 1477 | lua_rawset(L, -3); |
| 1478 | } |
| 1479 | } |
| 1480 | return 1; |
| 1481 | } |
| 1482 | else { |
| 1483 | lua_checkstack(L, columns); |
| 1484 | for (i = 0; i < columns; ++i) |
| 1485 | vm_push_column(L, vm, i); |
| 1486 | return svm->columns; |
| 1487 | } |
| 1488 | } |
| 1489 | |
| 1490 | if (svm->temp) { |
| 1491 | /* finalize and check for errors */ |
| 1492 | result = sqlite3_finalize(vm); |
| 1493 | svm->vm = NULL; |
| 1494 | cleanupvm(L, svm); |
| 1495 | } |
| 1496 | else if (result == SQLITE_DONE) { |
| 1497 | result = sqlite3_reset(vm); |
| 1498 | } |
| 1499 | |
| 1500 | if (result != SQLITE_OK) { |
| 1501 | lua_pushstring(L, sqlite3_errmsg(svm->db->db)); |
| 1502 | lua_error(L); |
| 1503 | } |
| 1504 | return 0; |
| 1505 | } |
| 1506 | |
| 1507 | static int db_next_row(lua_State *L) { |
| 1508 | return db_do_next_row(L, 0); |
| 1509 | } |
| 1510 | |
| 1511 | static int db_next_packed_row(lua_State *L) { |
| 1512 | return db_do_next_row(L, 1); |
| 1513 | } |
| 1514 | |
| 1515 | static int db_next_named_row(lua_State *L) { |
| 1516 | return db_do_next_row(L, 2); |
| 1517 | } |
| 1518 | |
| 1519 | static int dbvm_do_rows(lua_State *L, int(*f)(lua_State *)) { |
| 1520 | //sdb_vm *svm = |
| 1521 | lsqlite_checkvm(L, 1); |
| 1522 | lua_pushvalue(L,1); |
| 1523 | lua_pushcfunction(L, f); |
| 1524 | lua_insert(L, -2); |
| 1525 | return 2; |
| 1526 | } |
| 1527 | |
| 1528 | static int dbvm_rows(lua_State *L) { |
| 1529 | return dbvm_do_rows(L, db_next_packed_row); |
| 1530 | } |
| 1531 | |
| 1532 | static int dbvm_nrows(lua_State *L) { |
| 1533 | return dbvm_do_rows(L, db_next_named_row); |
| 1534 | } |
| 1535 | |
| 1536 | static int dbvm_urows(lua_State *L) { |
| 1537 | return dbvm_do_rows(L, db_next_row); |
| 1538 | } |
| 1539 | |
| 1540 | static int db_do_rows(lua_State *L, int(*f)(lua_State *)) { |
| 1541 | sdb *db = lsqlite_checkdb(L, 1); |
| 1542 | const char *sql = luaL_checkstring(L, 2); |
| 1543 | sdb_vm *svm; |
| 1544 | lua_settop(L,2); /* sql is on top of stack for call to newvm */ |
| 1545 | svm = newvm(L, db); |
| 1546 | svm->temp = 1; |
| 1547 | |
| 1548 | if (sqlite3_prepare(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) { |
| 1549 | cleanupvm(L, svm); |
| 1550 | |
| 1551 | lua_pushstring(L, sqlite3_errmsg(svm->db->db)); |
| 1552 | lua_error(L); |
| 1553 | } |
| 1554 | |
| 1555 | lua_pushcfunction(L, f); |
| 1556 | lua_insert(L, -2); |
| 1557 | return 2; |
| 1558 | } |
| 1559 | |
| 1560 | static int db_rows(lua_State *L) { |
| 1561 | return db_do_rows(L, db_next_packed_row); |
| 1562 | } |
| 1563 | |
| 1564 | static int db_nrows(lua_State *L) { |
| 1565 | return db_do_rows(L, db_next_named_row); |
| 1566 | } |
| 1567 | |
| 1568 | /* unpacked version of db:rows */ |
| 1569 | static int db_urows(lua_State *L) { |
| 1570 | return db_do_rows(L, db_next_row); |
| 1571 | } |
| 1572 | |
| 1573 | static int db_tostring(lua_State *L) { |
| 1574 | char buff[32]; |
| 1575 | sdb *db = lsqlite_getdb(L, 1); |
| 1576 | if (db->db == NULL) |
| 1577 | strcpy(buff, "closed"); |
| 1578 | else |
| 1579 | sprintf(buff, "%p", lua_touserdata(L, 1)); |
| 1580 | lua_pushfstring(L, "sqlite database (%s)", buff); |
| 1581 | return 1; |
| 1582 | } |
| 1583 | |
| 1584 | static int db_close(lua_State *L) { |
| 1585 | sdb *db = lsqlite_checkdb(L, 1); |
| 1586 | lua_pushnumber(L, cleanupdb(L, db)); |
| 1587 | return 1; |
| 1588 | } |
| 1589 | |
| 1590 | static int db_close_vm(lua_State *L) { |
| 1591 | sdb *db = lsqlite_checkdb(L, 1); |
| 1592 | /* cleanup temporary only tables? */ |
| 1593 | int temp = lua_toboolean(L, 2); |
| 1594 | |
| 1595 | /* free associated virtual machines */ |
| 1596 | lua_pushlightuserdata(L, db); |
| 1597 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 1598 | |
| 1599 | /* close all used handles */ |
| 1600 | lua_pushnil(L); |
| 1601 | while (lua_next(L, -2)) { |
| 1602 | sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */ |
| 1603 | |
| 1604 | if ((!temp || svm->temp) && svm->vm) |
| 1605 | { |
| 1606 | sqlite3_finalize(svm->vm); |
| 1607 | svm->vm = NULL; |
| 1608 | } |
| 1609 | |
| 1610 | /* leave key in the stack */ |
| 1611 | lua_pop(L, 1); |
| 1612 | } |
| 1613 | return 0; |
| 1614 | } |
| 1615 | |
| 1616 | static int db_gc(lua_State *L) { |
| 1617 | sdb *db = lsqlite_getdb(L, 1); |
| 1618 | if (db->db != NULL) /* ignore closed databases */ |
| 1619 | cleanupdb(L, db); |
| 1620 | return 0; |
| 1621 | } |
| 1622 | |
| 1623 | /* |
| 1624 | ** ======================================================= |
| 1625 | ** General library functions |
| 1626 | ** ======================================================= |
| 1627 | */ |
| 1628 | |
| 1629 | static int lsqlite_version(lua_State *L) { |
| 1630 | lua_pushstring(L, sqlite3_libversion()); |
| 1631 | return 1; |
| 1632 | } |
| 1633 | |
| 1634 | static int lsqlite_complete(lua_State *L) { |
| 1635 | const char *sql = luaL_checkstring(L, 1); |
| 1636 | lua_pushboolean(L, sqlite3_complete(sql)); |
| 1637 | return 1; |
| 1638 | } |
| 1639 | |
| 1640 | #ifndef WIN32 |
| 1641 | static int lsqlite_temp_directory(lua_State *L) { |
| 1642 | const char *oldtemp = sqlite3_temp_directory; |
| 1643 | |
| 1644 | if (!lua_isnone(L, 1)) { |
| 1645 | const char *temp = luaL_optstring(L, 1, NULL); |
| 1646 | if (sqlite3_temp_directory) { |
| 1647 | sqlite3_free((char*)sqlite3_temp_directory); |
| 1648 | } |
| 1649 | if (temp) { |
| 1650 | sqlite3_temp_directory = sqlite3_mprintf("%s", temp); |
| 1651 | } |
| 1652 | else { |
| 1653 | sqlite3_temp_directory = NULL; |
| 1654 | } |
| 1655 | } |
| 1656 | lua_pushstring(L, oldtemp); |
| 1657 | return 1; |
| 1658 | } |
| 1659 | #endif |
| 1660 | |
| 1661 | static int lsqlite_do_open(lua_State *L, const char *filename) { |
| 1662 | sdb *db = newdb(L); /* create and leave in stack */ |
| 1663 | |
| 1664 | if (sqlite3_open(filename, &db->db) == SQLITE_OK) { |
| 1665 | /* database handle already in the stack - return it */ |
| 1666 | return 1; |
| 1667 | } |
| 1668 | |
| 1669 | /* failed to open database */ |
| 1670 | lua_pushnil(L); /* push nil */ |
| 1671 | lua_pushnumber(L, sqlite3_errcode(db->db)); |
| 1672 | lua_pushstring(L, sqlite3_errmsg(db->db)); /* push error message */ |
| 1673 | |
| 1674 | /* clean things up */ |
| 1675 | cleanupdb(L, db); |
| 1676 | |
| 1677 | /* return */ |
| 1678 | return 3; |
| 1679 | } |
| 1680 | |
| 1681 | static int lsqlite_open(lua_State *L) { |
| 1682 | const char *filename = luaL_checkstring(L, 1); |
| 1683 | return lsqlite_do_open(L, filename); |
| 1684 | } |
| 1685 | |
| 1686 | static int lsqlite_open_memory(lua_State *L) { |
| 1687 | return lsqlite_do_open(L, ":memory:"); |
| 1688 | } |
| 1689 | |
| 1690 | static int lsqlite_newindex(lua_State *L) { |
| 1691 | lua_pushliteral(L, "attempt to change readonly table"); |
| 1692 | lua_error(L); |
| 1693 | return 0; |
| 1694 | } |
| 1695 | |
| 1696 | /* |
| 1697 | ** ======================================================= |
| 1698 | ** Register functions |
| 1699 | ** ======================================================= |
| 1700 | */ |
| 1701 | |
| 1702 | #define SC(s) { #s, SQLITE_ ## s }, |
| 1703 | #define LSC(s) { #s, LSQLITE_ ## s }, |
| 1704 | |
| 1705 | static const struct { |
| 1706 | const char* name; |
| 1707 | int value; |
| 1708 | } sqlite_constants[] = { |
| 1709 | /* error codes */ |
| 1710 | SC(OK) SC(ERROR) SC(INTERNAL) SC(PERM) |
| 1711 | SC(ABORT) SC(BUSY) SC(LOCKED) SC(NOMEM) |
| 1712 | SC(READONLY) SC(INTERRUPT) SC(IOERR) SC(CORRUPT) |
| 1713 | SC(NOTFOUND) SC(FULL) SC(CANTOPEN) SC(PROTOCOL) |
| 1714 | SC(EMPTY) SC(SCHEMA) SC(TOOBIG) SC(CONSTRAINT) |
| 1715 | SC(MISMATCH) SC(MISUSE) SC(NOLFS) |
| 1716 | SC(FORMAT) SC(NOTADB) |
| 1717 | |
| 1718 | /* sqlite_step specific return values */ |
| 1719 | SC(RANGE) SC(ROW) SC(DONE) |
| 1720 | |
| 1721 | /* column types */ |
| 1722 | SC(INTEGER) SC(FLOAT) SC(TEXT) SC(BLOB) |
| 1723 | SC(NULL) |
| 1724 | |
| 1725 | /* terminator */ |
| 1726 | { NULL, 0 } |
| 1727 | }; |
| 1728 | |
| 1729 | /* ======================================================= */ |
| 1730 | |
| 1731 | static const luaL_reg dblib[] = { |
| 1732 | {"isopen", db_isopen }, |
| 1733 | {"last_insert_rowid", db_last_insert_rowid }, |
| 1734 | {"changes", db_changes }, |
| 1735 | {"total_changes", db_total_changes }, |
| 1736 | {"errcode", db_errcode }, |
| 1737 | {"error_code", db_errcode }, |
| 1738 | {"errmsg", db_errmsg }, |
| 1739 | {"error_message", db_errmsg }, |
| 1740 | {"interrupt", db_interrupt }, |
| 1741 | |
| 1742 | {"create_function", db_create_function }, |
| 1743 | {"create_aggregate", db_create_aggregate }, |
| 1744 | {"create_collation", db_create_collation }, |
| 1745 | |
| 1746 | {"trace", db_trace }, |
| 1747 | {"progress_handler", db_progress_handler }, |
| 1748 | {"busy_timeout", db_busy_timeout }, |
| 1749 | {"busy_handler", db_busy_handler }, |
| 1750 | |
| 1751 | {"prepare", db_prepare }, |
| 1752 | {"rows", db_rows }, |
| 1753 | {"urows", db_urows }, |
| 1754 | {"nrows", db_nrows }, |
| 1755 | |
| 1756 | {"exec", db_exec }, |
| 1757 | {"execute", db_exec }, |
| 1758 | {"close", db_close }, |
| 1759 | {"close_vm", db_close_vm }, |
| 1760 | |
| 1761 | {"__tostring", db_tostring }, |
| 1762 | {"__gc", db_gc }, |
| 1763 | |
| 1764 | {NULL, NULL} |
| 1765 | }; |
| 1766 | |
| 1767 | static const luaL_reg vmlib[] = { |
| 1768 | {"isopen", dbvm_isopen }, |
| 1769 | |
| 1770 | {"step", dbvm_step }, |
| 1771 | {"reset", dbvm_reset }, |
| 1772 | {"finalize", dbvm_finalize }, |
| 1773 | |
| 1774 | {"columns", dbvm_columns }, |
| 1775 | |
| 1776 | {"bind", dbvm_bind }, |
| 1777 | {"bind_values", dbvm_bind_values }, |
| 1778 | {"bind_names", dbvm_bind_names }, |
| 1779 | {"bind_blob", dbvm_bind_blob }, |
| 1780 | {"bind_parameter_count",dbvm_bind_parameter_count}, |
| 1781 | {"bind_parameter_name", dbvm_bind_parameter_name}, |
| 1782 | |
| 1783 | {"get_value", dbvm_get_value }, |
| 1784 | {"get_values", dbvm_get_values }, |
| 1785 | {"get_name", dbvm_get_name }, |
| 1786 | {"get_names", dbvm_get_names }, |
| 1787 | {"get_type", dbvm_get_type }, |
| 1788 | {"get_types", dbvm_get_types }, |
| 1789 | {"get_uvalues", dbvm_get_uvalues }, |
| 1790 | {"get_unames", dbvm_get_unames }, |
| 1791 | {"get_utypes", dbvm_get_utypes }, |
| 1792 | |
| 1793 | {"get_named_values", dbvm_get_named_values }, |
| 1794 | {"get_named_types", dbvm_get_named_types }, |
| 1795 | |
| 1796 | {"rows", dbvm_rows }, |
| 1797 | {"urows", dbvm_urows }, |
| 1798 | {"nrows", dbvm_nrows }, |
| 1799 | |
| 1800 | /* compatibility names (added by request) */ |
| 1801 | {"idata", dbvm_get_values }, |
| 1802 | {"inames", dbvm_get_names }, |
| 1803 | {"itypes", dbvm_get_types }, |
| 1804 | {"data", dbvm_get_named_values }, |
| 1805 | {"type", dbvm_get_named_types }, |
| 1806 | |
| 1807 | {"__tostring", dbvm_tostring }, |
| 1808 | {"__gc", dbvm_gc }, |
| 1809 | |
| 1810 | { NULL, NULL } |
| 1811 | }; |
| 1812 | |
| 1813 | static const luaL_reg ctxlib[] = { |
| 1814 | {"user_data", lcontext_user_data }, |
| 1815 | |
| 1816 | {"get_aggregate_data", lcontext_get_aggregate_context }, |
| 1817 | {"set_aggregate_data", lcontext_set_aggregate_context }, |
| 1818 | {"aggregate_count", lcontext_aggregate_count }, |
| 1819 | |
| 1820 | {"result", lcontext_result }, |
| 1821 | {"result_null", lcontext_result_null }, |
| 1822 | {"result_number", lcontext_result_double }, |
| 1823 | {"result_double", lcontext_result_double }, |
| 1824 | {"result_int", lcontext_result_int }, |
| 1825 | {"result_text", lcontext_result_text }, |
| 1826 | {"result_blob", lcontext_result_blob }, |
| 1827 | {"result_error", lcontext_result_error }, |
| 1828 | |
| 1829 | {"__tostring", lcontext_tostring }, |
| 1830 | {NULL, NULL} |
| 1831 | }; |
| 1832 | |
| 1833 | static const luaL_reg sqlitelib[] = { |
| 1834 | {"version", lsqlite_version }, |
| 1835 | {"complete", lsqlite_complete }, |
| 1836 | #ifndef WIN32 |
| 1837 | {"temp_directory", lsqlite_temp_directory }, |
| 1838 | #endif |
| 1839 | {"open", lsqlite_open }, |
| 1840 | {"open_memory", lsqlite_open_memory }, |
| 1841 | |
| 1842 | {"__newindex", lsqlite_newindex }, |
| 1843 | {NULL, NULL} |
| 1844 | }; |
| 1845 | |
| 1846 | static void create_meta(lua_State *L, const char *name, const luaL_reg *lib) { |
| 1847 | luaL_newmetatable(L, name); |
| 1848 | lua_pushstring(L, "__index"); |
| 1849 | lua_pushvalue(L, -2); /* push metatable */ |
| 1850 | lua_rawset(L, -3); /* metatable.__index = metatable */ |
| 1851 | |
| 1852 | /* register metatable functions */ |
| 1853 | luaL_openlib(L, NULL, lib, 0); |
| 1854 | |
| 1855 | /* remove metatable from stack */ |
| 1856 | lua_pop(L, 1); |
| 1857 | } |
| 1858 | |
| 1859 | LUALIB_API int luaopen_lsqlite3(lua_State *L) { |
| 1860 | create_meta(L, sqlite_meta, dblib); |
| 1861 | create_meta(L, sqlite_vm_meta, vmlib); |
| 1862 | create_meta(L, sqlite_ctx_meta, ctxlib); |
| 1863 | |
| 1864 | luaL_getmetatable(L, sqlite_ctx_meta); |
| 1865 | sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1866 | |
| 1867 | /* register (local) sqlite metatable */ |
| 1868 | luaL_register(L, "sqlite3", sqlitelib); |
| 1869 | |
| 1870 | { |
| 1871 | int i = 0; |
| 1872 | /* add constants to global table */ |
| 1873 | while (sqlite_constants[i].name) { |
| 1874 | lua_pushstring(L, sqlite_constants[i].name); |
| 1875 | lua_pushnumber(L, sqlite_constants[i].value); |
| 1876 | lua_rawset(L, -3); |
| 1877 | ++i; |
| 1878 | } |
| 1879 | } |
| 1880 | |
| 1881 | /* set sqlite's metatable to itself - set as readonly (__newindex) */ |
| 1882 | lua_pushvalue(L, -1); |
| 1883 | lua_setmetatable(L, -2); |
| 1884 | |
| 1885 | return 1; |
| 1886 | } |
trunk/3rdparty/lsqlite3/lunit.lua
| r0 | r242834 | |
| 1 | |
| 2 | --[[-------------------------------------------------------------------------- |
| 3 | |
| 4 | This file is part of lunit 0.4pre (alpha). |
| 5 | |
| 6 | For Details about lunit look at: http://www.nessie.de/mroth/lunit/ |
| 7 | |
| 8 | Author: Michael Roth <mroth@nessie.de> |
| 9 | |
| 10 | Copyright (c) 2004 Michael Roth <mroth@nessie.de> |
| 11 | |
| 12 | Permission is hereby granted, free of charge, to any person |
| 13 | obtaining a copy of this software and associated documentation |
| 14 | files (the "Software"), to deal in the Software without restriction, |
| 15 | including without limitation the rights to use, copy, modify, merge, |
| 16 | publish, distribute, sublicense, and/or sell copies of the Software, |
| 17 | and to permit persons to whom the Software is furnished to do so, |
| 18 | subject to the following conditions: |
| 19 | |
| 20 | The above copyright notice and this permission notice shall be |
| 21 | included in all copies or substantial portions of the Software. |
| 22 | |
| 23 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 24 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 25 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 26 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 27 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 28 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 29 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 30 | |
| 31 | --]]-------------------------------------------------------------------------- |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | ----------------------- |
| 37 | -- Intialize package -- |
| 38 | ----------------------- |
| 39 | |
| 40 | local P = { } |
| 41 | lunit = P |
| 42 | |
| 43 | -- Import |
| 44 | local type = type |
| 45 | local print = print |
| 46 | local ipairs = ipairs |
| 47 | local pairs = pairs |
| 48 | local string = string |
| 49 | local table = table |
| 50 | local pcall = pcall |
| 51 | local xpcall = xpcall |
| 52 | local traceback = debug.traceback |
| 53 | local error = error |
| 54 | local setmetatable = setmetatable |
| 55 | local rawset = rawset |
| 56 | local orig_assert = assert |
| 57 | local getfenv = getfenv |
| 58 | local setfenv = setfenv |
| 59 | local tostring = tostring |
| 60 | |
| 61 | |
| 62 | -- Start package scope |
| 63 | setfenv(1, P) |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | -------------------------------- |
| 69 | -- Private data and functions -- |
| 70 | -------------------------------- |
| 71 | |
| 72 | local run_testcase |
| 73 | local do_assert, check_msg |
| 74 | local stats = { } |
| 75 | local testcases = { } |
| 76 | local stats_inc, tc_mt |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | -------------------------- |
| 82 | -- Type check functions -- |
| 83 | -------------------------- |
| 84 | |
| 85 | function is_nil(x) |
| 86 | return type(x) == "nil" |
| 87 | end |
| 88 | |
| 89 | function is_boolean(x) |
| 90 | return type(x) == "boolean" |
| 91 | end |
| 92 | |
| 93 | function is_number(x) |
| 94 | return type(x) == "number" |
| 95 | end |
| 96 | |
| 97 | function is_string(x) |
| 98 | return type(x) == "string" |
| 99 | end |
| 100 | |
| 101 | function is_table(x) |
| 102 | return type(x) == "table" |
| 103 | end |
| 104 | |
| 105 | function is_function(x) |
| 106 | return type(x) == "function" |
| 107 | end |
| 108 | |
| 109 | function is_thread(x) |
| 110 | return type(x) == "thread" |
| 111 | end |
| 112 | |
| 113 | function is_userdata(x) |
| 114 | return type(x) == "userdata" |
| 115 | end |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | ---------------------- |
| 121 | -- Assert functions -- |
| 122 | ---------------------- |
| 123 | |
| 124 | function assert(assertion, msg) |
| 125 | stats_inc("assertions") |
| 126 | check_msg("assert", msg) |
| 127 | do_assert(not not assertion, "assertion failed (was: "..tostring(assertion)..")", msg) -- (convert assertion to bool) |
| 128 | return assertion |
| 129 | end |
| 130 | |
| 131 | |
| 132 | function assert_fail(msg) |
| 133 | stats_inc("assertions") |
| 134 | check_msg("assert_fail", msg) |
| 135 | do_assert(false, "failure", msg) |
| 136 | end |
| 137 | |
| 138 | |
| 139 | function assert_true(actual, msg) |
| 140 | stats_inc("assertions") |
| 141 | check_msg("assert_true", msg) |
| 142 | do_assert(is_boolean(actual), "true expected but was a "..type(actual), msg) |
| 143 | do_assert(actual == true, "true expected but was false", msg) |
| 144 | return actual |
| 145 | end |
| 146 | |
| 147 | |
| 148 | function assert_false(actual, msg) |
| 149 | stats_inc("assertions") |
| 150 | check_msg("assert_false", msg) |
| 151 | do_assert(is_boolean(actual), "false expected but was a "..type(actual), msg) |
| 152 | do_assert(actual == false, "false expected but was true", msg) |
| 153 | return actual |
| 154 | end |
| 155 | |
| 156 | |
| 157 | function assert_equal(expected, actual, msg) |
| 158 | stats_inc("assertions") |
| 159 | check_msg("assert_equal", msg) |
| 160 | do_assert(expected == actual, "expected '"..tostring(expected).."' but was '"..tostring(actual).."'", msg) |
| 161 | return actual |
| 162 | end |
| 163 | |
| 164 | |
| 165 | function assert_not_equal(unexpected, actual, msg) |
| 166 | stats_inc("assertions") |
| 167 | check_msg("assert_not_equal", msg) |
| 168 | do_assert(unexpected ~= actual, "'"..tostring(expected).."' not expected but was one", msg) |
| 169 | return actual |
| 170 | end |
| 171 | |
| 172 | |
| 173 | function assert_match(pattern, actual, msg) |
| 174 | stats_inc("assertions") |
| 175 | check_msg("assert_match", msg) |
| 176 | do_assert(is_string(pattern), "assert_match expects the pattern as a string") |
| 177 | do_assert(is_string(actual), "expected a string to match pattern '"..pattern.."' but was a '"..type(actual).."'", msg) |
| 178 | do_assert(not not string.find(actual, pattern), "expected '"..actual.."' to match pattern '"..pattern.."' but doesn't", msg) |
| 179 | return actual |
| 180 | end |
| 181 | |
| 182 | |
| 183 | function assert_not_match(pattern, actual, msg) |
| 184 | stats_inc("assertions") |
| 185 | check_msg("assert_not_match", msg) |
| 186 | do_assert(is_string(actual), "expected a string to not match pattern '"..pattern.."' but was a '"..type(actual).."'", msg) |
| 187 | do_assert(string.find(actual, pattern) == nil, "expected '"..actual.."' to not match pattern '"..pattern.."' but it does", msg) |
| 188 | return actual |
| 189 | end |
| 190 | |
| 191 | |
| 192 | function assert_nil(actual, msg) |
| 193 | stats_inc("assertions") |
| 194 | check_msg("assert_nil", msg) |
| 195 | do_assert(is_nil(actual), "nil expected but was a "..type(actual), msg) |
| 196 | return actual |
| 197 | end |
| 198 | |
| 199 | |
| 200 | function assert_not_nil(actual, msg) |
| 201 | stats_inc("assertions") |
| 202 | check_msg("assert_not_nil", msg) |
| 203 | do_assert(not is_nil(actual), "nil not expected but was one", msg) |
| 204 | return actual |
| 205 | end |
| 206 | |
| 207 | |
| 208 | function assert_boolean(actual, msg) |
| 209 | stats_inc("assertions") |
| 210 | check_msg("assert_boolean", msg) |
| 211 | do_assert(is_boolean(actual), "boolean expected but was a "..type(actual), msg) |
| 212 | return actual |
| 213 | end |
| 214 | |
| 215 | |
| 216 | function assert_not_boolean(actual, msg) |
| 217 | stats_inc("assertions") |
| 218 | check_msg("assert_not_boolean", msg) |
| 219 | do_assert(not is_boolean(actual), "boolean not expected but was one", msg) |
| 220 | return actual |
| 221 | end |
| 222 | |
| 223 | |
| 224 | function assert_number(actual, msg) |
| 225 | stats_inc("assertions") |
| 226 | check_msg("assert_number", msg) |
| 227 | do_assert(is_number(actual), "number expected but was a "..type(actual), msg) |
| 228 | return actual |
| 229 | end |
| 230 | |
| 231 | |
| 232 | function assert_not_number(actual, msg) |
| 233 | stats_inc("assertions") |
| 234 | check_msg("assert_not_number", msg) |
| 235 | do_assert(not is_number(actual), "number not expected but was one", msg) |
| 236 | return actual |
| 237 | end |
| 238 | |
| 239 | |
| 240 | function assert_string(actual, msg) |
| 241 | stats_inc("assertions") |
| 242 | check_msg("assert_string", msg) |
| 243 | do_assert(is_string(actual), "string expected but was a "..type(actual), msg) |
| 244 | return actual |
| 245 | end |
| 246 | |
| 247 | |
| 248 | function assert_not_string(actual, msg) |
| 249 | stats_inc("assertions") |
| 250 | check_msg("assert_not_string", msg) |
| 251 | do_assert(not is_string(actual), "string not expected but was one", msg) |
| 252 | return actual |
| 253 | end |
| 254 | |
| 255 | |
| 256 | function assert_table(actual, msg) |
| 257 | stats_inc("assertions") |
| 258 | check_msg("assert_table", msg) |
| 259 | do_assert(is_table(actual), "table expected but was a "..type(actual), msg) |
| 260 | return actual |
| 261 | end |
| 262 | |
| 263 | |
| 264 | function assert_not_table(actual, msg) |
| 265 | stats_inc("assertions") |
| 266 | check_msg("assert_not_table", msg) |
| 267 | do_assert(not is_table(actual), "table not expected but was one", msg) |
| 268 | return actual |
| 269 | end |
| 270 | |
| 271 | |
| 272 | function assert_function(actual, msg) |
| 273 | stats_inc("assertions") |
| 274 | check_msg("assert_function", msg) |
| 275 | do_assert(is_function(actual), "function expected but was a "..type(actual), msg) |
| 276 | return actual |
| 277 | end |
| 278 | |
| 279 | |
| 280 | function assert_not_function(actual, msg) |
| 281 | stats_inc("assertions") |
| 282 | check_msg("assert_not_function", msg) |
| 283 | do_assert(not is_function(actual), "function not expected but was one", msg) |
| 284 | return actual |
| 285 | end |
| 286 | |
| 287 | |
| 288 | function assert_thread(actual, msg) |
| 289 | stats_inc("assertions") |
| 290 | check_msg("assert_thread", msg) |
| 291 | do_assert(is_thread(actual), "thread expected but was a "..type(actual), msg) |
| 292 | return actual |
| 293 | end |
| 294 | |
| 295 | |
| 296 | function assert_not_thread(actual, msg) |
| 297 | stats_inc("assertions") |
| 298 | check_msg("assert_not_thread", msg) |
| 299 | do_assert(not is_thread(actual), "thread not expected but was one", msg) |
| 300 | return actual |
| 301 | end |
| 302 | |
| 303 | |
| 304 | function assert_userdata(actual, msg) |
| 305 | stats_inc("assertions") |
| 306 | check_msg("assert_userdata", msg) |
| 307 | do_assert(is_userdata(actual), "userdata expected but was a "..type(actual), msg) |
| 308 | return actual |
| 309 | end |
| 310 | |
| 311 | |
| 312 | function assert_not_userdata(actual, msg) |
| 313 | stats_inc("assertions") |
| 314 | check_msg("assert_not_userdata", msg) |
| 315 | do_assert(not is_userdata(actual), "userdata not expected but was one", msg) |
| 316 | return actual |
| 317 | end |
| 318 | |
| 319 | |
| 320 | function assert_error(msg, func) |
| 321 | stats_inc("assertions") |
| 322 | if is_nil(func) then func, msg = msg, nil end |
| 323 | check_msg("assert_error", msg) |
| 324 | do_assert(is_function(func), "assert_error expects a function as the last argument but it was a "..type(func)) |
| 325 | local ok, errmsg = pcall(func) |
| 326 | do_assert(ok == false, "error expected but no error occurred", msg) |
| 327 | end |
| 328 | |
| 329 | |
| 330 | function assert_pass(msg, func) |
| 331 | stats_inc("assertions") |
| 332 | if is_nil(func) then func, msg = msg, nil end |
| 333 | check_msg("assert_pass", msg) |
| 334 | do_assert(is_function(func), "assert_pass expects a function as the last argument but it was a "..type(func)) |
| 335 | local ok, errmsg = pcall(func) |
| 336 | if not ok then do_assert(ok == true, "no error expected but error was: "..errmsg, msg) end |
| 337 | end |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | ----------------------------------------------------------- |
| 343 | -- Assert implementation that assumes it was called from -- |
| 344 | -- lunit code which was called directly from user code. -- |
| 345 | ----------------------------------------------------------- |
| 346 | |
| 347 | function do_assert(assertion, base_msg, user_msg) |
| 348 | orig_assert(is_boolean(assertion)) |
| 349 | orig_assert(is_string(base_msg)) |
| 350 | orig_assert(is_string(user_msg) or is_nil(user_msg)) |
| 351 | if not assertion then |
| 352 | if user_msg then |
| 353 | error(base_msg..": "..user_msg, 3) |
| 354 | else |
| 355 | error(base_msg.."!", 3) |
| 356 | end |
| 357 | end |
| 358 | end |
| 359 | |
| 360 | ------------------------------------------- |
| 361 | -- Checks the msg argument in assert_xxx -- |
| 362 | ------------------------------------------- |
| 363 | |
| 364 | function check_msg(name, msg) |
| 365 | orig_assert(is_string(name)) |
| 366 | if not (is_nil(msg) or is_string(msg)) then |
| 367 | error("lunit."..name.."() expects the optional message as a string but it was a "..type(msg).."!" ,3) |
| 368 | end |
| 369 | end |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | ------------------------------------- |
| 375 | -- Creates a new TestCase 'Object' -- |
| 376 | ------------------------------------- |
| 377 | |
| 378 | function TestCase(name) |
| 379 | do_assert(is_string(name), "lunit.TestCase() needs a string as an argument") |
| 380 | local tc = { |
| 381 | __lunit_name = name; |
| 382 | __lunit_setup = nil; |
| 383 | __lunit_tests = { }; |
| 384 | __lunit_teardown = nil; |
| 385 | } |
| 386 | setmetatable(tc, tc_mt) |
| 387 | table.insert(testcases, tc) |
| 388 | return tc |
| 389 | end |
| 390 | |
| 391 | tc_mt = { |
| 392 | __newindex = function(tc, key, value) |
| 393 | rawset(tc, key, value) |
| 394 | if is_string(key) and is_function(value) then |
| 395 | local name = string.lower(key) |
| 396 | if string.find(name, "^test") or string.find(name, "test$") then |
| 397 | table.insert(tc.__lunit_tests, key) |
| 398 | elseif name == "setup" then |
| 399 | tc.__lunit_setup = value |
| 400 | elseif name == "teardown" then |
| 401 | tc.__lunit_teardown = value |
| 402 | end |
| 403 | end |
| 404 | end |
| 405 | } |
| 406 | |
| 407 | |
| 408 | |
| 409 | ----------------------------------------- |
| 410 | -- Wrap Functions in a TestCase object -- |
| 411 | ----------------------------------------- |
| 412 | |
| 413 | function wrap(name, ...) |
| 414 | if is_function(name) then |
| 415 | table.insert({...}, 1, name) |
| 416 | name = "Anonymous Testcase" |
| 417 | end |
| 418 | |
| 419 | local tc = TestCase(name) |
| 420 | for index, test in ipairs({...}) do |
| 421 | tc["Test #"..index] = test |
| 422 | end |
| 423 | return tc |
| 424 | end |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | ---------------------------------- |
| 432 | -- Runs the complete Test Suite -- |
| 433 | ---------------------------------- |
| 434 | |
| 435 | function run() |
| 436 | |
| 437 | --------------------------- |
| 438 | -- Initialize statistics -- |
| 439 | --------------------------- |
| 440 | |
| 441 | stats.testcases = 0 -- Total number of Test Cases |
| 442 | stats.tests = 0 -- Total number of all Tests in all Test Cases |
| 443 | stats.run = 0 -- Number of Tests run |
| 444 | stats.notrun = 0 -- Number of Tests not run |
| 445 | stats.failed = 0 -- Number of Tests failed |
| 446 | stats.warnings = 0 -- Number of Warnings (teardown) |
| 447 | stats.errors = 0 -- Number of Errors (setup) |
| 448 | stats.passed = 0 -- Number of Test passed |
| 449 | stats.assertions = 0 -- Number of all assertions made in all Test in all Test Cases |
| 450 | |
| 451 | -------------------------------- |
| 452 | -- Count Test Cases and Tests -- |
| 453 | -------------------------------- |
| 454 | |
| 455 | stats.testcases = table.getn(testcases) |
| 456 | |
| 457 | for _, tc in ipairs(testcases) do |
| 458 | stats_inc("tests" , table.getn(tc.__lunit_tests)) |
| 459 | end |
| 460 | |
| 461 | ------------------ |
| 462 | -- Print Header -- |
| 463 | ------------------ |
| 464 | |
| 465 | print() |
| 466 | print("#### Test Suite with "..stats.tests.." Tests in "..stats.testcases.." Test Cases loaded.") |
| 467 | |
| 468 | ------------------------ |
| 469 | -- Run all Test Cases -- |
| 470 | ------------------------ |
| 471 | |
| 472 | for _, tc in ipairs(testcases) do |
| 473 | run_testcase(tc) |
| 474 | end |
| 475 | |
| 476 | ------------------ |
| 477 | -- Print Footer -- |
| 478 | ------------------ |
| 479 | |
| 480 | print() |
| 481 | print("#### Test Suite finished.") |
| 482 | |
| 483 | local msg_assertions = stats.assertions.." Assertions checked. " |
| 484 | local msg_passed = stats.passed == stats.tests and "All Tests passed" or stats.passed.." Tests passed" |
| 485 | local msg_failed = stats.failed > 0 and ", "..stats.failed.." failed" or "" |
| 486 | local msg_run = stats.notrun > 0 and ", "..stats.notrun.." not run" or "" |
| 487 | local msg_warn = stats.warnings > 0 and ", "..stats.warnings.." warnings" or "" |
| 488 | |
| 489 | print() |
| 490 | print(msg_assertions..msg_passed..msg_failed..msg_run..msg_warn.."!") |
| 491 | |
| 492 | ----------------- |
| 493 | -- Return code -- |
| 494 | ----------------- |
| 495 | |
| 496 | if stats.passed == stats.tests then |
| 497 | return 0 |
| 498 | else |
| 499 | return 1 |
| 500 | end |
| 501 | end |
| 502 | |
| 503 | |
| 504 | |
| 505 | |
| 506 | ----------------------------- |
| 507 | -- Runs a single Test Case -- |
| 508 | ----------------------------- |
| 509 | |
| 510 | function run_testcase(tc) |
| 511 | |
| 512 | orig_assert(is_table(tc)) |
| 513 | orig_assert(is_table(tc.__lunit_tests)) |
| 514 | orig_assert(is_string(tc.__lunit_name)) |
| 515 | orig_assert(is_nil(tc.__lunit_setup) or is_function(tc.__lunit_setup)) |
| 516 | orig_assert(is_nil(tc.__lunit_teardown) or is_function(tc.__lunit_teardown)) |
| 517 | |
| 518 | ---------------------------------- |
| 519 | -- Protected call to a function -- |
| 520 | ---------------------------------- |
| 521 | |
| 522 | local function call(errprefix, func) |
| 523 | orig_assert(is_string(errprefix)) |
| 524 | orig_assert(is_function(func)) |
| 525 | local ok, errmsg = xpcall(function() func(tc) end, traceback) |
| 526 | if not ok then |
| 527 | print() |
| 528 | print(errprefix..": "..errmsg) |
| 529 | end |
| 530 | return ok |
| 531 | end |
| 532 | |
| 533 | ------------------------------------ |
| 534 | -- Calls setup() on the Test Case -- |
| 535 | ------------------------------------ |
| 536 | |
| 537 | local function setup(testname) |
| 538 | if tc.__lunit_setup then |
| 539 | return call("ERROR: "..testname..": setup() failed", tc.__lunit_setup) |
| 540 | else |
| 541 | return true |
| 542 | end |
| 543 | end |
| 544 | |
| 545 | ------------------------------------------ |
| 546 | -- Calls a single Test on the Test Case -- |
| 547 | ------------------------------------------ |
| 548 | |
| 549 | local function run(testname) |
| 550 | orig_assert(is_string(testname)) |
| 551 | orig_assert(is_function(tc[testname])) |
| 552 | local ok = call("FAIL: "..testname, tc[testname]) |
| 553 | if not ok then |
| 554 | stats_inc("failed") |
| 555 | else |
| 556 | stats_inc("passed") |
| 557 | end |
| 558 | return ok |
| 559 | end |
| 560 | |
| 561 | --------------------------------------- |
| 562 | -- Calls teardown() on the Test Case -- |
| 563 | --------------------------------------- |
| 564 | |
| 565 | local function teardown(testname) |
| 566 | if tc.__lunit_teardown then |
| 567 | if not call("WARNING: "..testname..": teardown() failed", tc.__lunit_teardown) then |
| 568 | stats_inc("warnings") |
| 569 | end |
| 570 | end |
| 571 | end |
| 572 | |
| 573 | --------------------------------- |
| 574 | -- Run all Tests on a TestCase -- |
| 575 | --------------------------------- |
| 576 | |
| 577 | print() |
| 578 | print("#### Running '"..tc.__lunit_name.."' ("..table.getn(tc.__lunit_tests).." Tests)...") |
| 579 | |
| 580 | for _, testname in ipairs(tc.__lunit_tests) do |
| 581 | if setup(testname) then |
| 582 | run(testname) |
| 583 | stats_inc("run") |
| 584 | teardown(testname) |
| 585 | else |
| 586 | print("WARN: Skipping '"..testname.."'...") |
| 587 | stats_inc("notrun") |
| 588 | end |
| 589 | end |
| 590 | |
| 591 | end |
| 592 | |
| 593 | |
| 594 | |
| 595 | |
| 596 | --------------------- |
| 597 | -- Import function -- |
| 598 | --------------------- |
| 599 | |
| 600 | function import(name) |
| 601 | |
| 602 | do_assert(is_string(name), "lunit.import() expects a single string as argument") |
| 603 | |
| 604 | local user_env = getfenv(2) |
| 605 | |
| 606 | -------------------------------------------------- |
| 607 | -- Installs a specific function in the user env -- |
| 608 | -------------------------------------------------- |
| 609 | |
| 610 | local function install(funcname) |
| 611 | user_env[funcname] = P[funcname] |
| 612 | end |
| 613 | |
| 614 | |
| 615 | ---------------------------------------------------------- |
| 616 | -- Install functions matching a pattern in the user env -- |
| 617 | ---------------------------------------------------------- |
| 618 | |
| 619 | local function install_pattern(pattern) |
| 620 | for funcname, _ in pairs(P) do |
| 621 | if string.find(funcname, pattern) then |
| 622 | install(funcname) |
| 623 | end |
| 624 | end |
| 625 | end |
| 626 | |
| 627 | ------------------------------------------------------------ |
| 628 | -- Installs assert() and all assert_xxx() in the user env -- |
| 629 | ------------------------------------------------------------ |
| 630 | |
| 631 | local function install_asserts() |
| 632 | install_pattern("^assert.*") |
| 633 | end |
| 634 | |
| 635 | ------------------------------------------- |
| 636 | -- Installs all is_xxx() in the user env -- |
| 637 | ------------------------------------------- |
| 638 | |
| 639 | local function install_tests() |
| 640 | install_pattern("^is_.+") |
| 641 | end |
| 642 | |
| 643 | if name == "asserts" or name == "assertions" then |
| 644 | install_asserts() |
| 645 | elseif name == "tests" or name == "checks" then |
| 646 | install_tests() |
| 647 | elseif name == "all" then |
| 648 | install_asserts() |
| 649 | install_tests() |
| 650 | install("TestCase") |
| 651 | elseif string.find(name, "^assert.*") and P[name] then |
| 652 | install(name) |
| 653 | elseif string.find(name, "^is_.+") and P[name] then |
| 654 | install(name) |
| 655 | elseif name == "TestCase" then |
| 656 | install("TestCase") |
| 657 | else |
| 658 | error("luniit.import(): invalid function '"..name.."' to import", 2) |
| 659 | end |
| 660 | end |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | -------------------------------------------------- |
| 666 | -- Installs a private environment on the caller -- |
| 667 | -------------------------------------------------- |
| 668 | |
| 669 | function setprivfenv() |
| 670 | local new_env = { } |
| 671 | local new_env_mt = { __index = getfenv(2) } |
| 672 | setmetatable(new_env, new_env_mt) |
| 673 | setfenv(2, new_env) |
| 674 | end |
| 675 | |
| 676 | |
| 677 | |
| 678 | |
| 679 | -------------------------------------------------- |
| 680 | -- Increments a counter in the statistics table -- |
| 681 | -------------------------------------------------- |
| 682 | |
| 683 | function stats_inc(varname, value) |
| 684 | orig_assert(is_table(stats)) |
| 685 | orig_assert(is_string(varname)) |
| 686 | orig_assert(is_nil(value) or is_number(value)) |
| 687 | if not stats[varname] then return end |
| 688 | stats[varname] = stats[varname] + (value or 1) |
| 689 | end |
| 690 | |
| 691 | |
| 692 | |
| 693 | |
trunk/3rdparty/lsqlite3/tests-sqlite3.lua
| r0 | r242834 | |
| 1 | |
| 2 | --[[-------------------------------------------------------------------------- |
| 3 | |
| 4 | Author: Michael Roth <mroth@nessie.de> |
| 5 | |
| 6 | Copyright (c) 2004, 2005 Michael Roth <mroth@nessie.de> |
| 7 | |
| 8 | Permission is hereby granted, free of charge, to any person |
| 9 | obtaining a copy of this software and associated documentation |
| 10 | files (the "Software"), to deal in the Software without restriction, |
| 11 | including without limitation the rights to use, copy, modify, merge, |
| 12 | publish, distribute, sublicense, and/or sell copies of the Software, |
| 13 | and to permit persons to whom the Software is furnished to do so, |
| 14 | subject to the following conditions: |
| 15 | |
| 16 | The above copyright notice and this permission notice shall be |
| 17 | included in all copies or substantial portions of the Software. |
| 18 | |
| 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 20 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 21 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 22 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 23 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 24 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 25 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 26 | |
| 27 | --]]-------------------------------------------------------------------------- |
| 28 | |
| 29 | |
| 30 | require "lsqlite3" |
| 31 | |
| 32 | require "lunit" |
| 33 | |
| 34 | lunit.setprivfenv() |
| 35 | lunit.import "assertions" |
| 36 | lunit.import "checks" |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | ------------------------------- |
| 44 | -- Basic open and close test -- |
| 45 | ------------------------------- |
| 46 | |
| 47 | lunit.wrap("open_memory", function() |
| 48 | local db = assert_userdata( sqlite3.open_memory() ) |
| 49 | assert( db:close() ) |
| 50 | end) |
| 51 | |
| 52 | lunit.wrap("open", function() |
| 53 | local filename = "/tmp/__lua-sqlite3-20040906135849." .. os.time() |
| 54 | local db = assert_userdata( sqlite3.open(filename) ) |
| 55 | assert( db:close() ) |
| 56 | os.remove(filename) |
| 57 | end) |
| 58 | |
| 59 | |
| 60 | |
| 61 | ------------------------------------- |
| 62 | -- Presence of db member functions -- |
| 63 | ------------------------------------- |
| 64 | |
| 65 | local db_funcs = lunit.TestCase("Database Member Functions") |
| 66 | |
| 67 | function db_funcs:setup() |
| 68 | self.db = assert( sqlite3.open_memory() ) |
| 69 | end |
| 70 | |
| 71 | function db_funcs:teardown() |
| 72 | assert( self.db:close() ) |
| 73 | end |
| 74 | |
| 75 | function db_funcs:test() |
| 76 | local db = self.db |
| 77 | assert_function( db.close ) |
| 78 | assert_function( db.exec ) |
| 79 | --e assert_function( db.irows ) |
| 80 | assert_function( db.rows ) |
| 81 | --e assert_function( db.cols ) |
| 82 | --e assert_function( db.first_irow ) |
| 83 | --e assert_function( db.first_row ) |
| 84 | --e assert_function( db.first_cols ) |
| 85 | assert_function( db.prepare ) |
| 86 | assert_function( db.interrupt ) |
| 87 | assert_function( db.last_insert_rowid ) |
| 88 | assert_function( db.changes ) |
| 89 | assert_function( db.total_changes ) |
| 90 | end |
| 91 | |
| 92 | |
| 93 | |
| 94 | --------------------------------------- |
| 95 | -- Presence of stmt member functions -- |
| 96 | --------------------------------------- |
| 97 | |
| 98 | local stmt_funcs = lunit.TestCase("Statement Member Functions") |
| 99 | |
| 100 | function stmt_funcs:setup() |
| 101 | self.db = assert( sqlite3.open_memory() ) |
| 102 | self.stmt = assert( self.db:prepare("CREATE TABLE test (id, content)") ) |
| 103 | end |
| 104 | |
| 105 | function stmt_funcs:teardown() |
| 106 | --e- assert( self.stmt:close() ) |
| 107 | assert( self.stmt:finalize() ) --e+ |
| 108 | assert( self.db:close() ) |
| 109 | end |
| 110 | |
| 111 | function stmt_funcs:test() |
| 112 | local stmt = self.stmt |
| 113 | --e assert_function( stmt.close ) |
| 114 | assert_function( stmt.reset ) |
| 115 | --e assert_function( stmt.exec ) |
| 116 | assert_function( stmt.bind ) |
| 117 | --e assert_function( stmt.irows ) |
| 118 | --e assert_function( stmt.rows ) |
| 119 | --e assert_function( stmt.cols ) |
| 120 | --e assert_function( stmt.first_irow ) |
| 121 | --e assert_function( stmt.first_row ) |
| 122 | --e assert_function( stmt.first_cols ) |
| 123 | --e assert_function( stmt.column_names ) |
| 124 | --e assert_function( stmt.column_decltypes ) |
| 125 | --e assert_function( stmt.column_count ) |
| 126 | --e + |
| 127 | assert_function( stmt.isopen ) |
| 128 | assert_function( stmt.step ) |
| 129 | assert_function( stmt.reset ) |
| 130 | assert_function( stmt.finalize ) |
| 131 | assert_function( stmt.columns ) |
| 132 | assert_function( stmt.bind ) |
| 133 | assert_function( stmt.bind_values ) |
| 134 | assert_function( stmt.bind_names ) |
| 135 | assert_function( stmt.bind_blob ) |
| 136 | assert_function( stmt.bind_parameter_count ) |
| 137 | assert_function( stmt.bind_parameter_name ) |
| 138 | assert_function( stmt.get_value ) |
| 139 | assert_function( stmt.get_values ) |
| 140 | assert_function( stmt.get_name ) |
| 141 | assert_function( stmt.get_names ) |
| 142 | assert_function( stmt.get_type ) |
| 143 | assert_function( stmt.get_types ) |
| 144 | assert_function( stmt.get_uvalues ) |
| 145 | assert_function( stmt.get_unames ) |
| 146 | assert_function( stmt.get_utypes ) |
| 147 | assert_function( stmt.get_named_values ) |
| 148 | assert_function( stmt.get_named_types ) |
| 149 | assert_function( stmt.idata ) |
| 150 | assert_function( stmt.inames ) |
| 151 | assert_function( stmt.itypes ) |
| 152 | assert_function( stmt.data ) |
| 153 | assert_function( stmt.type ) |
| 154 | --e + |
| 155 | end |
| 156 | |
| 157 | |
| 158 | |
| 159 | ------------------ |
| 160 | -- Tests basics -- |
| 161 | ------------------ |
| 162 | |
| 163 | local basics = lunit.TestCase("Basics") |
| 164 | |
| 165 | function basics:setup() |
| 166 | self.db = assert_userdata( sqlite3.open_memory() ) |
| 167 | end |
| 168 | |
| 169 | function basics:teardown() |
| 170 | assert_number( self.db:close() ) |
| 171 | end |
| 172 | |
| 173 | function basics:create_table() |
| 174 | assert_number( self.db:exec("CREATE TABLE test (id, name)") ) |
| 175 | end |
| 176 | |
| 177 | function basics:drop_table() |
| 178 | assert_number( self.db:exec("DROP TABLE test") ) |
| 179 | end |
| 180 | |
| 181 | function basics:insert(id, name) |
| 182 | assert_number( self.db:exec("INSERT INTO test VALUES ("..id..", '"..name.."')") ) |
| 183 | end |
| 184 | |
| 185 | function basics:update(id, name) |
| 186 | assert_number( self.db:exec("UPDATE test SET name = '"..name.."' WHERE id = "..id) ) |
| 187 | end |
| 188 | |
| 189 | function basics:test_create_drop() |
| 190 | self:create_table() |
| 191 | self:drop_table() |
| 192 | end |
| 193 | |
| 194 | function basics:test_multi_create_drop() |
| 195 | self:create_table() |
| 196 | self:drop_table() |
| 197 | self:create_table() |
| 198 | self:drop_table() |
| 199 | end |
| 200 | |
| 201 | function basics:test_insert() |
| 202 | self:create_table() |
| 203 | self:insert(1, "Hello World") |
| 204 | self:insert(2, "Hello Lua") |
| 205 | self:insert(3, "Hello sqlite3") |
| 206 | end |
| 207 | |
| 208 | function basics:test_update() |
| 209 | self:create_table() |
| 210 | self:insert(1, "Hello Home") |
| 211 | self:insert(2, "Hello Lua") |
| 212 | self:update(1, "Hello World") |
| 213 | end |
| 214 | |
| 215 | |
| 216 | --------------------------------- |
| 217 | -- Statement Column Info Tests -- |
| 218 | --------------------------------- |
| 219 | |
| 220 | lunit.wrap("Column Info Test", function() |
| 221 | local db = assert_userdata( sqlite3.open_memory() ) |
| 222 | assert_number( db:exec("CREATE TABLE test (id INTEGER, name TEXT)") ) |
| 223 | local stmt = assert_userdata( db:prepare("SELECT * FROM test") ) |
| 224 | |
| 225 | assert_equal(2, stmt:columns(), "Wrong number of columns." ) |
| 226 | |
| 227 | local names = assert_table( stmt:get_names() ) |
| 228 | assert_equal(2, #(names), "Wrong number of names.") |
| 229 | assert_equal("id", names[1] ) |
| 230 | assert_equal("name", names[2] ) |
| 231 | |
| 232 | local types = assert_table( stmt:get_types() ) |
| 233 | assert_equal(2, #(types), "Wrong number of declaration types.") |
| 234 | assert_equal("INTEGER", types[1] ) |
| 235 | assert_equal("TEXT", types[2] ) |
| 236 | |
| 237 | assert_equal( sqlite3.OK, stmt:finalize() ) |
| 238 | assert_equal( sqlite3.OK, db:close() ) |
| 239 | end) |
| 240 | |
| 241 | |
| 242 | |
| 243 | --------------------- |
| 244 | -- Statement Tests -- |
| 245 | --------------------- |
| 246 | |
| 247 | st = lunit.TestCase("Statement Tests") |
| 248 | |
| 249 | function st:setup() |
| 250 | self.db = assert( sqlite3.open_memory() ) |
| 251 | assert_equal( sqlite3.OK, self.db:exec("CREATE TABLE test (id, name)") ) |
| 252 | assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (1, 'Hello World')") ) |
| 253 | assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (2, 'Hello Lua')") ) |
| 254 | assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (3, 'Hello sqlite3')") ) |
| 255 | end |
| 256 | |
| 257 | function st:teardown() |
| 258 | assert_equal( sqlite3.OK, self.db:close() ) |
| 259 | end |
| 260 | |
| 261 | function st:check_content(expected) |
| 262 | local stmt = assert( self.db:prepare("SELECT * FROM test ORDER BY id") ) |
| 263 | local i = 0 |
| 264 | for row in stmt:rows() do |
| 265 | i = i + 1 |
| 266 | assert( i <= #(expected), "Too many rows." ) |
| 267 | assert_equal(2, #(row), "Two result column expected.") |
| 268 | assert_equal(i, row[1], "Wrong 'id'.") |
| 269 | assert_equal(expected[i], row[2], "Wrong 'name'.") |
| 270 | end |
| 271 | assert_equal( #(expected), i, "Too few rows." ) |
| 272 | assert_number( stmt:finalize() ) |
| 273 | end |
| 274 | |
| 275 | function st:test_setup() |
| 276 | assert_pass(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3" } end) |
| 277 | assert_error(function() self:check_content{ "Hello World", "Hello Lua" } end) |
| 278 | assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "To much" } end) |
| 279 | assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Wrong" } end) |
| 280 | assert_error(function() self:check_content{ "Hello World", "Wrong", "Hello sqlite3" } end) |
| 281 | assert_error(function() self:check_content{ "Wrong", "Hello Lua", "Hello sqlite3" } end) |
| 282 | end |
| 283 | |
| 284 | function st:test_questionmark_args() |
| 285 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (?, ?)") ) |
| 286 | assert_number( stmt:bind_values(0, "Test") ) |
| 287 | assert_error(function() stmt:bind_values("To few") end) |
| 288 | assert_error(function() stmt:bind_values(0, "Test", "To many") end) |
| 289 | end |
| 290 | |
| 291 | function st:test_questionmark() |
| 292 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (?, ?)") ) |
| 293 | assert_number( stmt:bind_values(4, "Good morning") ) |
| 294 | assert_number( stmt:step() ) |
| 295 | assert_number( stmt:reset() ) |
| 296 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } |
| 297 | assert_number( stmt:bind_values(5, "Foo Bar") ) |
| 298 | assert_number( stmt:step() ) |
| 299 | assert_number( stmt:reset() ) |
| 300 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 301 | assert_number( stmt:finalize() ) |
| 302 | end |
| 303 | |
| 304 | --[===[ |
| 305 | function st:test_questionmark_multi() |
| 306 | local stmt = assert_userdata( self.db:prepare([[ |
| 307 | INSERT INTO test VALUES (?, ?); INSERT INTO test VALUES (?, ?) ]])) |
| 308 | assert( stmt:bind_values(5, "Foo Bar", 4, "Good morning") ) |
| 309 | assert_number( stmt:step() ) |
| 310 | assert_number( stmt:reset() ) |
| 311 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 312 | assert_number( stmt:finalize() ) |
| 313 | end |
| 314 | ]===] |
| 315 | |
| 316 | function st:test_identifiers() |
| 317 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) |
| 318 | assert_number( stmt:bind_values(4, "Good morning") ) |
| 319 | assert_number( stmt:step() ) |
| 320 | assert_number( stmt:reset() ) |
| 321 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } |
| 322 | assert_number( stmt:bind_values(5, "Foo Bar") ) |
| 323 | assert_number( stmt:step() ) |
| 324 | assert_number( stmt:reset() ) |
| 325 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 326 | assert_number( stmt:finalize() ) |
| 327 | end |
| 328 | |
| 329 | --[===[ |
| 330 | function st:test_identifiers_multi() |
| 331 | local stmt = assert_table( self.db:prepare([[ |
| 332 | INSERT INTO test VALUES (:id1, :name1); INSERT INTO test VALUES (:id2, :name2) ]])) |
| 333 | assert( stmt:bind_values(5, "Foo Bar", 4, "Good morning") ) |
| 334 | assert( stmt:exec() ) |
| 335 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 336 | end |
| 337 | ]===] |
| 338 | |
| 339 | function st:test_identifiers_names() |
| 340 | --local stmt = assert_userdata( self.db:prepare({"name", "id"}, "INSERT INTO test VALUES (:id, $name)") ) |
| 341 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, $name)") ) |
| 342 | assert_number( stmt:bind_names({name="Good morning", id=4}) ) |
| 343 | assert_number( stmt:step() ) |
| 344 | assert_number( stmt:reset() ) |
| 345 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } |
| 346 | assert_number( stmt:bind_names({name="Foo Bar", id=5}) ) |
| 347 | assert_number( stmt:step() ) |
| 348 | assert_number( stmt:reset() ) |
| 349 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 350 | assert_number( stmt:finalize() ) |
| 351 | end |
| 352 | |
| 353 | --[===[ |
| 354 | function st:test_identifiers_multi_names() |
| 355 | local stmt = assert_table( self.db:prepare( {"name", "id1", "id2"},[[ |
| 356 | INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) |
| 357 | assert( stmt:bind_values("Hoho", 4, 5) ) |
| 358 | assert( stmt:exec() ) |
| 359 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } |
| 360 | end |
| 361 | ]===] |
| 362 | |
| 363 | function st:test_colon_identifiers_names() |
| 364 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) |
| 365 | assert_number( stmt:bind_names({name="Good morning", id=4}) ) |
| 366 | assert_number( stmt:step() ) |
| 367 | assert_number( stmt:reset() ) |
| 368 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } |
| 369 | assert_number( stmt:bind_names({name="Foo Bar", id=5}) ) |
| 370 | assert_number( stmt:step() ) |
| 371 | assert_number( stmt:reset() ) |
| 372 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 373 | assert_number( stmt:finalize() ) |
| 374 | end |
| 375 | |
| 376 | --[===[ |
| 377 | function st:test_colon_identifiers_multi_names() |
| 378 | local stmt = assert_table( self.db:prepare( {":name", ":id1", ":id2"},[[ |
| 379 | INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) |
| 380 | assert( stmt:bind_values("Hoho", 4, 5) ) |
| 381 | assert( stmt:exec() ) |
| 382 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } |
| 383 | end |
| 384 | |
| 385 | |
| 386 | function st:test_dollar_identifiers_names() |
| 387 | local stmt = assert_table( self.db:prepare({"$name", "$id"}, "INSERT INTO test VALUES (:id, $name)") ) |
| 388 | assert_table( stmt:bind_values("Good morning", 4) ) |
| 389 | assert_table( stmt:exec() ) |
| 390 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } |
| 391 | assert_table( stmt:bind_values("Foo Bar", 5) ) |
| 392 | assert_table( stmt:exec() ) |
| 393 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } |
| 394 | end |
| 395 | |
| 396 | function st:test_dollar_identifiers_multi_names() |
| 397 | local stmt = assert_table( self.db:prepare( {"$name", "$id1", "$id2"},[[ |
| 398 | INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) |
| 399 | assert( stmt:bind_values("Hoho", 4, 5) ) |
| 400 | assert( stmt:exec() ) |
| 401 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } |
| 402 | end |
| 403 | ]===] |
| 404 | |
| 405 | function st:test_bind_by_names() |
| 406 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) |
| 407 | local args = { } |
| 408 | args.id = 5 |
| 409 | args.name = "Hello girls" |
| 410 | assert( stmt:bind_names(args) ) |
| 411 | assert_number( stmt:step() ) |
| 412 | assert_number( stmt:reset() ) |
| 413 | args.id = 4 |
| 414 | args.name = "Hello boys" |
| 415 | assert( stmt:bind_names(args) ) |
| 416 | assert_number( stmt:step() ) |
| 417 | assert_number( stmt:reset() ) |
| 418 | self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hello boys", "Hello girls" } |
| 419 | assert_number( stmt:finalize() ) |
| 420 | end |
| 421 | |
| 422 | |
| 423 | |
| 424 | -------------------------------- |
| 425 | -- Tests binding of arguments -- |
| 426 | -------------------------------- |
| 427 | |
| 428 | b = lunit.TestCase("Binding Tests") |
| 429 | |
| 430 | function b:setup() |
| 431 | self.db = assert( sqlite3.open_memory() ) |
| 432 | assert_number( self.db:exec("CREATE TABLE test (id, name, u, v, w, x, y, z)") ) |
| 433 | end |
| 434 | |
| 435 | function b:teardown() |
| 436 | assert_number( self.db:close() ) |
| 437 | end |
| 438 | |
| 439 | function b:test_auto_parameter_names() |
| 440 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES(:a, $b, :a2, :b2, $a, :b, $a3, $b3)") ) |
| 441 | local parameters = assert_number( stmt:bind_parameter_count() ) |
| 442 | assert_equal( 8, parameters ) |
| 443 | assert_equal( ":a", stmt:bind_parameter_name(1) ) |
| 444 | assert_equal( "$b", stmt:bind_parameter_name(2) ) |
| 445 | assert_equal( ":a2", stmt:bind_parameter_name(3) ) |
| 446 | assert_equal( ":b2", stmt:bind_parameter_name(4) ) |
| 447 | assert_equal( "$a", stmt:bind_parameter_name(5) ) |
| 448 | assert_equal( ":b", stmt:bind_parameter_name(6) ) |
| 449 | assert_equal( "$a3", stmt:bind_parameter_name(7) ) |
| 450 | assert_equal( "$b3", stmt:bind_parameter_name(8) ) |
| 451 | end |
| 452 | |
| 453 | function b:test_auto_parameter_names() |
| 454 | local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES($a, $b, $a2, $b2, $a, $b, $a3, $b3)") ) |
| 455 | local parameters = assert_number( stmt:bind_parameter_count() ) |
| 456 | assert_equal( 6, parameters ) |
| 457 | assert_equal( "$a", stmt:bind_parameter_name(1) ) |
| 458 | assert_equal( "$b", stmt:bind_parameter_name(2) ) |
| 459 | assert_equal( "$a2", stmt:bind_parameter_name(3) ) |
| 460 | assert_equal( "$b2", stmt:bind_parameter_name(4) ) |
| 461 | assert_equal( "$a3", stmt:bind_parameter_name(5) ) |
| 462 | assert_equal( "$b3", stmt:bind_parameter_name(6) ) |
| 463 | end |
| 464 | |
| 465 | function b:test_no_parameter_names_1() |
| 466 | local stmt = assert_userdata( self.db:prepare([[ SELECT * FROM test ]])) |
| 467 | local parameters = assert_number( stmt:bind_parameter_count() ) |
| 468 | assert_equal( 0, (parameters) ) |
| 469 | end |
| 470 | |
| 471 | function b:test_no_parameter_names_2() |
| 472 | local stmt = assert_userdata( self.db:prepare([[ INSERT INTO test VALUES(?, ?, ?, ?, ?, ?, ?, ?) ]])) |
| 473 | local parameters = assert_number( stmt:bind_parameter_count() ) |
| 474 | assert_equal( 8, (parameters) ) |
| 475 | assert_nil( stmt:bind_parameter_name(1) ) |
| 476 | end |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | -------------------------------------------- |
| 485 | -- Tests loop break and statement reusage -- |
| 486 | -------------------------------------------- |
| 487 | |
| 488 | |
| 489 | |
| 490 | ---------------------------- |
| 491 | -- Test for bugs reported -- |
| 492 | ---------------------------- |
| 493 | |
| 494 | bug = lunit.TestCase("Bug-Report Tests") |
| 495 | |
| 496 | function bug:setup() |
| 497 | self.db = assert( sqlite3.open_memory() ) |
| 498 | end |
| 499 | |
| 500 | function bug:teardown() |
| 501 | assert_number( self.db:close() ) |
| 502 | end |
| 503 | |
| 504 | --[===[ |
| 505 | function bug:test_1() |
| 506 | self.db:exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)") |
| 507 | |
| 508 | local query = assert_userdata( self.db:prepare("SELECT id FROM test WHERE value=?") ) |
| 509 | |
| 510 | assert_table ( query:bind_values("1") ) |
| 511 | assert_nil ( query:first_cols() ) |
| 512 | assert_table ( query:bind_values("2") ) |
| 513 | assert_nil ( query:first_cols() ) |
| 514 | end |
| 515 | ]===] |
| 516 | |
| 517 | function bug:test_nils() -- appeared in lua-5.1 (holes in arrays) |
| 518 | local function check(arg1, arg2, arg3, arg4, arg5) |
| 519 | assert_equal(1, arg1) |
| 520 | assert_equal(2, arg2) |
| 521 | assert_nil(arg3) |
| 522 | assert_equal(4, arg4) |
| 523 | assert_nil(arg5) |
| 524 | end |
| 525 | |
| 526 | self.db:create_function("test_nils", 5, function(arg1, arg2, arg3, arg4, arg5) |
| 527 | check(arg1, arg2, arg3, arg4, arg5) |
| 528 | end, {}) |
| 529 | |
| 530 | assert_number( self.db:exec([[ SELECT test_nils(1, 2, NULL, 4, NULL) ]]) ) |
| 531 | |
| 532 | for arg1, arg2, arg3, arg4, arg5 in self.db:urows([[ SELECT 1, 2, NULL, 4, NULL ]]) |
| 533 | do check(arg1, arg2, arg3, arg4, arg5) |
| 534 | end |
| 535 | |
| 536 | for row in self.db:rows([[ SELECT 1, 2, NULL, 4, NULL ]]) |
| 537 | do assert_table( row ) |
| 538 | check(row[1], row[2], row[3], row[4], row[5]) |
| 539 | end |
| 540 | end |
| 541 | |
| 542 | ---------------------------- |
| 543 | -- Test for collation fun -- |
| 544 | ---------------------------- |
| 545 | |
| 546 | colla = lunit.TestCase("Collation Tests") |
| 547 | |
| 548 | function colla:setup() |
| 549 | local function collate(s1,s2) |
| 550 | -- if p then print("collation callback: ",s1,s2) end |
| 551 | s1=s1:lower() |
| 552 | s2=s2:lower() |
| 553 | if s1==s2 then return 0 |
| 554 | elseif s1<s2 then return -1 |
| 555 | else return 1 end |
| 556 | end |
| 557 | self.db = assert( sqlite3.open_memory() ) |
| 558 | assert_nil(self.db:create_collation('CINSENS',collate)) |
| 559 | self.db:exec[[ |
| 560 | CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS); |
| 561 | INSERT INTO test VALUES(NULL,'hello world'); |
| 562 | INSERT INTO test VALUES(NULL,'Buenos dias'); |
| 563 | INSERT INTO test VALUES(NULL,'HELLO WORLD'); |
| 564 | INSERT INTO test VALUES(NULL,'Guten Tag'); |
| 565 | INSERT INTO test VALUES(NULL,'HeLlO WoRlD'); |
| 566 | INSERT INTO test VALUES(NULL,'Bye for now'); |
| 567 | ]] |
| 568 | end |
| 569 | |
| 570 | function colla:teardown() |
| 571 | assert_number( self.db:close() ) |
| 572 | end |
| 573 | |
| 574 | function colla:test() |
| 575 | --for row in db:nrows('SELECT * FROM test') do |
| 576 | -- print(row.id,row.content) |
| 577 | --end |
| 578 | local n = 0 |
| 579 | for row in self.db:nrows('SELECT * FROM test WHERE content="hElLo wOrLd"') do |
| 580 | -- print(row.id,row.content) |
| 581 | assert_equal (row.content:lower(), "hello world") |
| 582 | n = n + 1 |
| 583 | end |
| 584 | assert_equal (n, 3) |
| 585 | end |
| 586 | |
| 587 | lunit.run() |