Introduction
LuaSQL is a simple interface from Lua to a number of database management systems.It includes a set of drivers to some popular databases(currently PostgreSQL, ODBC, MySQL, SQLite, Oracle, and ADO; Interbase and Sybase are in our plans).LuaSQL defines a simple object-oriented API.All drivers should implement this common API,but each one is free to offer extensions.
LuaSQL defines one single global variable,a table called luasql.This table is used to store the initialization methods of theloaded drivers.These methods are used to create anenvironment objectwhich is used to create aconnection object.A connection object can execute SQL statements and eventuallycreate acursor objectwhich is used to retrieve data.
LuaSQL is free software and uses the samelicenseas Lua 5.1.
Compiling
LuaSQL is distributed as a set of C source files:a pair of common source and header files (luasql.h and luasql.c);and one source file for each driver.Each driver should be compiled with the luasql.c file to generate a library.This library can be linked to the application or dynamically loaded. The initialization function is luaopen_luasqldrivername and it is a Luaopen-library compatible function.
Installation
All LuaSQL drivers follow thepackage modelfor Lua 5.1 and therefore should be "installed" in yourpackage.path.
Windows users can use the compiled versions of LuaSQL available atLuaForge
In order to use LuaSQL with ADO, make sure that you have LuaCOM 1.3 for Lua 5.1 installed.
Error handling
LuaSQL is just an abstraction layer that communicates between Luaand a database system.Therefore errors can occur on both levels, that is,inside the database client or inside LuaSQL driver.
Errors such as malformed SQL statements, unknown table names etc.are called database errors andwill be reported by the function/method returning nilfollowedby the error message provided by the database system.Errors such as wrong parameters, absent connection, invalid objects etc.,called API errors,are usually program errors and so will raise a Lua error.
This behavior will be followed by all functions/methodsdescribed in this document unless otherwise stated.
Drivers
A LuaSQL driver allows the use of the LuaSQL API with a database management systemthat corresponds to the driver. To use a driver you have to load it in theluasql table. The example below
require "luasql.odbc"
loads the ODBC driver in the luasql table. Note that you can have more than onedriver loaded at the same time doing something like:
require "luasql.odbc"
require "luasql.oci8"
This example also shows that the driver name not always correspond to theDatabase name, but to the driver name in the file system. Since it refers tothe OCI8 API, the oracle driver has the name oci8 instead oforacle.
Some drivers, such as the mysql, have libraries for a number of database versions thatuse the same file name (mysql). In this case it is not possible toload more than one version of the MySQL driver in the luasql table.
Environment Objects
An environment object is created by calling the driver's initializationfunction that is stored in the luasql table, indexed with the samename as the driver (odbc, postgres etc). For example,
env = luasql.odbc()
will try to create an environment object using the ODBC driver.
Methods
env:close()Closes the environment env.Only successful if all connections pertaining to it were closed first.
Returns: true in case of success; false whenthe object is already closed.env:connect(sourcename[,username[,password]])Connects to a data source specified in sourcename using username and password if they are supplied.
The sourcename may vary according to each driver.Some use a simple database name, like PostgreSQL, MySQL and SQLite;the ODBC driver expects the name of the DSN;the Oracle driver expects the service name;See also: PostgreSQL,and MySQL extensions.
Returns: a connection object.
Connection Objects
A connection object contains specific attributes and parameters of asingle data source connection.A connection object is created by calling theenvironment:connectmethod.
Methods
conn:close()Closes the connection conn.Only successful if all cursors pertaining to it have been closed and the connection is still open.
Returns: true in case of success and false in case of failure.conn:commit()Commits the current transaction.This feature might not work on database systems that do not implementtransactions.
Returns: true in case of success and false whenthe operation could not be performed or when it is not implemented.conn:execute(statement)Executes the given SQL statement.
Returns: a cursor objectif there are results, or the number of rows affected by the command otherwise.conn:rollback()Rolls back the current transaction.This feature might not work on database systems that do not implementtransactions.
Returns: true in case of success and false whenthe operation could not be performed or when it is not implemented.conn:setautocommit(boolean)Turns on or off the "auto commit" mode.This feature might not work on database systems that do not implementtransactions.On database systems that do not have the concept of "auto commit mode",but do implement transactions, this mechanism is implemented by the driver.
Returns: true in case of success and false whenthe operation could not be performed or when it is not implemented.
Cursor Objects
A cursor object contains methods to retrieve data resulting from anexecuted statement. A cursor object is created by using theconnection:executefunction.See also PostgreSQLand Oracle extensions.
Methods
cur:close()Closes this cursor.
Returns: true in case of success and false whenthe object is already closed.cur:fetch([table[,modestring]])Retrieves the next row of results.
If fetch is called without parameters,the results will be returned directly to the caller.If fetch is called with a table, the results will be copiedinto the table and the changed table will be returned.In this case, an optional modestring parameter can be used.It is just a string indicating how the resulting table should be constructed.The mode string can contain:"n"the resulting table will have numerical indices (default)"a"the resulting table will have alphanumerical indices
The numerical indices are the positions of the fields in the SELECTstatement;the alphanumerical indices are the names of the fields.
The optional table parameter is a table that should beused to store the next row.This allows the use of a unique table for many fetches, whichcan improve the overall performance.
There is no guarantee about the types of the results: they may or may not be converted to adequate Lua types by the driver.In the current implementation,the PostgreSQL and MySQL drivers return all values as stringswhile the ODBC and Oracle drivers convert them to Lua types.
Returns: data, as above, or nil if there are no more rows.Note that this method could return nil as a valid result.cur:getcolnames()Returns: a list (table) of column names.cur:getcoltypes()Returns: a list (table) of column types.
PostgreSQL Extensions
Besides the basic functionality provided by all drivers,the Postgres driver also offers these extra features:
env:connect(sourcename[,username[,password[,hostname[,port]]]])In the PostgreSQL driver, this method adds two optional parameters that indicate the hostname and port to connect. Also, the first parameter can contain all connection information, as stated in the documentation for PQconnectdb function in the PostgreSQL manual (e.g.environment:connect("dbname= user="))
See also: environment objects
Returns: a connection objectcur:numrows()See also: cursor objects
Returns: the number of rows in the query result.
MySQL Extensions
Besides the basic functionality provided by all drivers,the MySQL driver also offers these extra features:
env:connect(sourcename[,username[,password[,hostname[,port]]]])In the MySQL driver, this method adds two optional parameters that indicate the hostname and port to connect. See also: environment objects
Returns: a connection objectcur:numrows()See also: cursor objects
Returns: the number of rows in the query result.
Notes:
This driver is compatible with versions 4.0, 4.1 and 5.0 of theMySQL API. Only from version 4.1 MySQL provides support for transactions by usingBDB or INNODB tables.Therefore, with version 4.0 or without one of these types of tables, themethods commit, rollback andsetautocommit will not work.
If you are using LuaSQL 2.0, cur:numrows()is available only in version 2.0.2 or later.
Oracle Extensions
Besides the basic functionality provided by all drivers,the Oracle driver also offers this extra feature:
cur:numrows()See also: cursor objects
Returns: the number of rows in the query result.