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 the
loaded drivers.
These methods are used to create an
environment object
which is used to create a
connection object.
A connection object can execute SQL statements and eventually
create a
cursor object
which is used to retrieve data.
LuaSQL is free software and uses the same license as 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 Lua
open-library
compatible function.
Installation
Since version 2.3, all LuaSQL drivers follow the package model of Lua 5.2.
All drivers should be "installed" in your package.cpath
into a
folder called luasql
.
In order to use LuaSQL with ADO, make sure that you have installed LuaCOM 1.3 for the appropriate version of Lua.
Error handling
LuaSQL is just an abstraction layer that communicates between Lua and 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 and
will be reported by the function/method returning nil
followed
by 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/methods described in this document unless otherwise stated.
Drivers
A LuaSQL driver allows the use of the LuaSQL API with a database management system that corresponds to the driver. To use a driver you have to load it. The example below
local driver = require "luasql.odbc"
loads the ODBC driver and returns a table with an entry with the name of the
driver (odbc
in this case). Note that you can have more than one
driver loaded at the same time doing something like:
local odbc_driver = require "luasql.odbc" local oci8_driver = require "luasql.oci8"
This example also shows that the driver name not always correspond to the
Database name, but to the driver name in the file system. Since it refers to
the OCI8 API, the Oracle driver has the name oci8
.
Environment Objects
An environment object is created by calling the driver's initialization function that is stored in the table returned when it was loaded, indexed with the same name as the driver (odbc, postgres etc). The following example, will try to create an environment object using the ODBC driver.
local driver = require"luasql.odbc" local env = driver.odbc()
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
when the object is already closed. env:connect(sourcename[,username[,password]])
- Connects to a data source specified in
sourcename
usingusername
andpassword
if they are supplied.
Thesourcename
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 a
single data source connection.
A connection object is created by calling the
environment:connect
method.
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 andfalse
in case of failure. conn:commit()
- Commits the current transaction.
This feature might not work on database systems that do not implement
transactions.
Returns:true
in case of success andfalse
when the operation could not be performed or when it is not implemented. conn:execute(statement)
- Executes the given SQL
statement
.
Returns: a cursor object if 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 implement
transactions.
Returns:true
in case of success andfalse
when the 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 implement
transactions.
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 andfalse
when the operation could not be performed or when it is not implemented.
Cursor Objects
A cursor object contains methods to retrieve data resulting from an
executed statement. A cursor object is created by using the
connection:execute
function.
See also PostgreSQL
and Oracle extensions.
Methods
cur:close()
- Closes this cursor.
Returns:true
in case of success andfalse
when the object is already closed. cur:fetch([table[,modestring]])
- Retrieves the next row of results.
Iffetch
is called without parameters, the results will be returned directly to the caller. Iffetch
is called with a table, the results will be copied into the table and the changed table will be returned. In this case, an optionalmodestring
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 SELECT statement; the alphanumerical indices are the names of the fields.
The optionaltable
parameter is a table that should be used to store the next row. This allows the use of a unique table for many fetches, which can improve the overall performance.
A call tofetch
after the last row has already being returned will close the corresponding cursor. 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 strings while the ODBC and Oracle drivers convert them to Lua types.
Returns: data, as above, ornil
if there are no more rows. Note that this method could returnnil
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=<name> user=<username>")
)
See also: environment objects
Returns: a connection object conn:escape(str)
- Escape especial characters in the given string according to the
connection's character set.
See also: Official documentation of function PQescapeStringConn
Returns: the escaped string. cur: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[,socket[,client_flag]]]]]])
- In the MySQL driver, this method adds two optional parameters
that indicate the hostname and port to connect.
It also accepts two optional parameters that indicate a unix socket and the
client flag.
See also: environment objects
Returns: a connection object conn:escape(str)
- Escape especial characters in the given string according to the
connection's character set.
See also: Official documentation of function mysql_real_escape_string
Returns: the escaped string. conn:getlastautoid()
- Obtains the value generated for an AUTO_INCREMENT column by the previous
INSERT or UPDATE statement.
See also: Official documentation of functionmysql_insert_id
for versions 4.0, 5.1 and 6.0
Returns: the number of the last value generated for an AUTO_INCREMENT column. conn:ping()
- Check whether the connection is closed (returns false) or opened (returns true).
It will return nil followed by an error message in case of error.
Returns: true, if the connection is opened, or false, if it is closed. cur: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 the
MySQL API. Only from version 4.1 MySQL provides support for transactions by using
BDB or INNODB tables.
Therefore, with version 4.0 or without one of these types of tables, the
methods commit
, rollback
and
setautocommit
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.
SQLite3 Extensions
Besides the basic functionality provided by all drivers, the SQLite3 driver also offers this extra feature:
env:connect(sourcename[,locktimeout])
See also: environment objects
Returns: a connection object
conn:escape(str)
See also: Official documentation of function sqlite3_mprintf
Returns: the escaped string.