[DEPRECATED] This repository is no longer maintained. Please follow https://github.com/pllua/pllua
[DEPRECATED] This repository is no longer maintained. Please follow https://github.com/pllua/pllua
PL/Lua is an implementation of Lua as a loadable procedural language for PostgreSQL: with PL/Lua you can use PostgreSQL functions and triggers written in the Lua programming language.
PL/Lua is an implementation of [Lua][8] as a loadable procedural language for [PostgreSQL][9]: with PL/Lua you can use PostgreSQL functions and triggers written in the Lua programming language.
Procedural languages offer many extra capabilities to PostgreSQL, similar to C language extensions: control structures, more complex computations than allowed by SQL, access to user-defined types and database functions and operators, and restriction to trusted execution.
PL/Lua brings the power and simplicity of Lua to PostgreSQL, including: small memory footprint, simple syntax, lexical scoping, functions as first-class values, and coroutines for non-preemptive threading. As a simple example, consider the following hello function:
# CREATE FUNCTION hello(name text) RETURNS text AS $$
return string.format("Hello, %s!", name)
$$ LANGUAGE pllua;
CREATE FUNCTION
# SELECT hello('PostgreSQL');
hello
--------------------
Hello, PostgreSQL!
(1 row)The next sections present more examples where other features are used. In the Languages section the two flavors of PL/Lua are described; the Functions section details how functions are registered in PL/Lua and how arguments are treated; Database access presents the SPI interface to PL/Lua; and Triggers shows how triggers can be declared.
PL/Lua is licensed under the [same license as Lua][11] -- the [MIT license][12] -- and so can be freely used for academic and commercial purposes. Please refer to the Installation section for more details.
Trusted and Untrusted PL/Lua
PL/Lua is available as either a trusted (pllua) or an untrusted (plluau) language. In plluau the user has access to a full-blown Lua environment, similar to the regular interpreter: all libraries are loaded, the user can access the global table freely, and modules can be loaded. Only database superusers are allowed to create functions using this untrusted version of PL/Lua.
Unprivileged users can only create functions using the trusted version of PL/Lua, pllua. The environment in pllua is more restricted: only table, string, and math libraries are fully loaded, the os library is restricted, the package library is not available, that is, there is no module system (including require), and the global table is restricted for writing. The following table summarizes the differences:
plluau |
pllua |
|
|---|---|---|
table, string, math |
All functions | All functions |
os |
All functions | date, clock, time, difftime |
package (module system) |
All functions | None |
_G (global environment) |
Free access | Writing is restricted |
Even though the module system is absent in pllua, PL/Lua allows for modules to be automatically loaded after creating the environment: all entries in table _pllua.init_ are require'd at startup.
To facilitate the use of PL/Lua and following the tradition of other PLs, the global table is aliased to shared. Moreover, write access to the global table in pllua is restricted to avoid pollution; global variables should then be created with setshared.
Finally, errors in PL/Lua are propagated to the calling query and the transaction is aborted if the error is not caught. Messages can be emitted by log, info, notice, and warning at log levels LOG, INFO, NOTICE, and WARNING respectively. In particular, print emits log messages of level INFO.
log(msg)Emits message msg at log level LOG. Similar functions info, notice, and warning have the same signature but emit msg at their respective log levels.
setshared(varname [, value])Sets global varname to value, which defaults to true. It is semantically equivalent to shared[varname] = value.
Data values in PL/Lua
PL/Lua makes no conversion of function arguments to string/text form between Lua and PostgreSQL. Basic data types are natively supported, that is, converted directly, by value, to a Lua equivalent. The following table shows type equivalences:
| PostgreSQL type | Lua type |
|---|---|
bool |
boolean |
float4, float8, int2, int4 |
number |
text, char, varchar |
string |
| Base, domain | userdata |
| Arrays, composite | table |
Base and domain types other than the ones in the first three rows in the table are converted to a raw datum userdata in Lua with a suitable __tostring metamethod based on the type's output function. Conversely, fromstring takes a type name and a string and returns a raw datum from the provided type's input function. Arrays are converted to Lua tables with integer indices, while composite types become tables with keys corresponding to attribute names.
fromstring(tname, s)Returns a raw datum userdata for s of type tname using tname's input function to convert s.
Functions in PL/Lua
PL/Lua functions are created according to the following prototype:
CREATE FUNCTION func(args) RETURNS rettype AS $$
-- Lua function body
$$ LANGUAGE [pllua | plluau];where args are usually named arguments. The value returned by func is converted to a datum of type rettype unless rettype is void.
The function body is composed as below to become a typical Lua chunk:
local _U, func -- _U is upvalue
func = function(_argnames_)
-- Lua function body
end
return funcNote the upvalue _U that can be later declared in the function body (see examples below.)
If any of the arguments provided to create function is not named then argnames gets substituted to ..., that is, func becomes vararg.
The resulting chunk is then compiled and stored in the registry of the PL/Lua state as a function with the same name. It is important to have the above structure in mind when writing PL/Lua functions. As an example, consider the following function:
CREATE FUNCTION max(a integer, b integer) RETURNS integer AS $$
if a == nil then return b end -- first arg is NULL?
if b == nil then return a end -- second arg is NULL?
return a > b and a or b -- return max(a, b)
$$ LANGUAGE pllua;Note that max is not strict and returns NULL when both a and b are NULL.
Since functions in PL/Lua are stored with their declared names, they can be recursive:
CREATE FUNCTION fib(n int) RETURNS int as $$
if n > 3 then
return n
else
return fib(n - 1) + fib(n - 2)
end
$$ LANGUAGE pllua;Moreover, as can be seen in the composition of func above, PL/Lua functions are actually closures on the upvalue __U_. The user can think of _U as local cache to func that could — and should! — be used instead of the global state to store values. Quick example:
CREATE FUNCTION counter() RETURNS int AS $$
while true do
_U = _U + 1
coroutine.yield(_U)
end
end
do
_U = 0 -- counter
counter = coroutine.wrap(counter)
$$ LANGUAGE pllua;Function counter is similar to an iterator, returning consecutive integers every time it is called, starting at one. Note that we need to add end to finish the function definition body and do to start a new block since the process of function composition always appends an end. It is important to observe that what actually gets defined as counter is a wrapper around a coroutine.
From Types we know that composite types can be accessed as tables with keys corresponding to attribute names:
CREATE TYPE greeting AS (how text, who text);
CREATE FUNCTION makegreeting (g greeting, f text) RETURNS text AS $$
return string.format(f, g.how, g.who)
$$ LANGUAGE pllua;Set-returning functions (SRFs) are implemented in PL/Lua using coroutines. When a SRF func is first called a new Lua thread is created and func is pushed along with its arguments onto the new thread's stack. A new result is then returned whenever func yields and func is done when the coroutine suspends or finishes. Using our composite type from above, we can define
CREATE FUNCTION greetingset (how text, who text[])
RETURNS SETOF greeting AS $$
for _, name in ipairs(who) do
coroutine.yield{how=how, who=name}
end
$$ LANGUAGE pllua;with this usage example:
# SELECT makegreeting(greetingset, '%s, %s!') FROM
(SELECT greetingset('Hello', ARRAY['foo', 'bar', 'psql'])) AS q;
makegreeting
--------------
Hello, foo!
Hello, bar!
Hello, psql!
(3 rows)Now, to further illustrate the use of arrays in PL/Lua, we adapt an [example][15] from [Programming in Lua][16]:
CREATE FUNCTION perm (a text[]) RETURNS SETOF text[] AS $$
_U(a, #a)
end
do
_U = function (a, n) -- permgen in PiL
if n == 0 then
coroutine.yield(a) -- return next SRF row
else
for i = 1, n do
a[n], a[i] = a[i], a[n] -- i-th element as last one
_U(a, n - 1) -- recurse on head
a[n], a[i] = a[i], a[n] -- restore i-th element
end
end
end
$$ LANGUAGE pllua;As stated in Languages, it is possible to access the global table of PL/Lua's state. However, as noted before, since PL/Lua functions are closures, creating global variables should be restricted to cases where data is to be shared between different functions. The following simple example defines a getter-setter pair to access a shared variable counter:
CREATE FUNCTION getcounter() RETURNS integer AS $$
if shared.counter == nil then -- not cached?
setshared("counter", 0)
end
return counter -- _G.counter == shared.counter
$$ LANGUAGE pllua;
CREATE FUNCTION setcounter(c integer) RETURNS void AS $$
if shared.counter == nil then -- not cached?
setshared("counter", c)
else
counter = c -- _G.counter == shared.counter
end
$$ LANGUAGE pllua;Let's revisit our (rather inefficient) recursive Fibonacci function fib. A better version uses tail recursion:
CREATE FUNCTION fibt(n integer) RETURNS integer AS $$
return _U(n, 0, 1)
end
_U = function(n, a, b) -- tail recursive
if n > 1 then
return b
else
return _U(n - 1, b, a + b)
end
$$ LANGUAGE pllua;We can also use the upvalue _U as a cache to store previous elements in the sequence and obtain a memoized version:
CREATE FUNCTION fibm(n integer) RETURNS integer AS $$
if n > 3 then
return n
else
local v = _U[n]
if not v then
v = fibm(n - 1) + fibm(n - 2)
_U[n] = v
end
return v
end
end
do _U = {} -- memoize
$$ LANGUAGE pllua;Finally, we can implement an iterator similar to counter:
CREATE FUNCTION fibi() RETURNS integer AS $$
while true do
_U.curr, _U.next = _U.next, _U.curr + _U.next
coroutine.yield(_U.curr)
end
end
do
_U = {curr = 0, next = 1}
fibi = coroutine.wrap(fibi)
$$ LANGUAGE pllua;Anonymous code blocks are also supported in PL/Lua. The following prototype
DO $$
-- Lua chunk
$$ LANGUAGE [pllua | plluau];compiles and executes the Lua chunk. Here are some examples:
DO $$ print(_VERSION)No open issues yet, or sync has not completed.