Using SQL in Lua Scripts
The SQL support of AspenTech Inmation is based on the LuaSQL library.
| Accessing the system database via the syslib.getsystemdb() function uses an internal connection which already exists. For this, you can skip the next two sections and continue reading at Accessing a Database with a Connection Object. |
Specifying the Driver
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 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.
Accessing a Database with a Connection Object
A connection object contains specific attributes and parameters of a single data source connection.
Generally, a connection object is created by calling the environment:connect method.
For connections to the system database, the connection object is
created by calling the the
syslib.getsystemdb() function.
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 implement transactions.
Returns: true in case of success and false when the operation could not be performed or when it is not implemented. -
conn:query(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 and false 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 and false when the operation could not be performed or when it is not implemented.
Retrieving Data with 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 and false when the 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 copied into 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 SELECT statement; the alphanumerical indices are the names of the fields.
The optional table 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 to fetch 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, 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.
SQLite3 Extensions
Besides the basic functionality provided by all drivers, the SQLite3 driver also offers this extra feature:
env:connect(sourcename[,locktimeout])
In the SQLite3 driver, this method adds an optional parameter that indicate the amount of milliseconds to wait for a write lock if one cannot be obtained immediately.
See also: environment objects
Returns: a connection object
|
Unlike other SQL database systems, connecting to a SQLite database is not done via ODBC or a similar driver, but via the SQLite library as illustrated in the example below. |
-- Example showing how to:
-- * create a custom Sqlite database with a single sample table
-- * Add some rows
-- * Query the table
local luasql = require "luasql.sqlite3"
-- Create environment and connection
local env = luasql.sqlite3()
local DB_FILE = "c:\\test.db"
local conn = env:connect(DB_FILE) -- will create test.db if not exists
-- Drop table if exists (for clean run)
conn:query("DROP TABLE IF EXISTS my_table")
-- Create the table
conn:query([[
CREATE TABLE my_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
field1 TEXT,
field2 REAL
)
]])
-- Insert some dummy rows
conn:query("INSERT INTO my_table (field1, field2) VALUES ('Alice', 10.5)")
conn:query("INSERT INTO my_table (field1, field2) VALUES ('Bob', 20.0)")
conn:query("INSERT INTO my_table (field1, field2) VALUES ('Charlie', 30.25)")
-- Verify by selecting rows
local cur = conn:query("SELECT id, field1, field2 FROM my_table")
local row = cur:fetch({}, "a") -- fetch rows as a table with column names as keys
local rows = {} -- put the queried rows in here
while row do
table.insert( rows, { id = row.id, field1 = row.field1, field2 = row.field2 } )
row = cur:fetch(row, "a")
end
-- Cleanup
cur:close()
conn:close()
env:close()
return syslib.json().encode( rows )
conn:escape(str)
Escape especial characters in the given string according to the connection’s character set.
See also: Official documentation of function sqlite3_mprintf
Returns: the escaped string.
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 function mysql_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.
|