lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi All

Yesterday I added support for Lua 5.4 to the Lua PostgreSQL interface which can be found at https://github.com/arcapos/luapgsql.

The main change is that result sets and notifies are now closable, i.e. they do have a __close meta method.  The __close meta methods free the memory that was allocated by the underlying C library.

When your software does a lot of queries, you end up with a lot of PostgreSQL result sets in memory, before the move to Lua 5.4 these would eventually be garbage collected, but you have no real idea when and how often.  And depending on the data size of your SQL queries, this could use up a quite substantial bit of memory.

In pre-5.4 times, you would probably have a function like this

function getAddress(db, id)
  local res = db:execParams('select * from address where id = $1::integer', id)
  return res:copy() --- convert result to a Lua table
end

Calling this function many times leads to many result sets occupying memory until the garbage collector chimes in.

With Lua 5.4, you can make the result closable:

function getAddress(db, id)
  local res <close> = db:execParams('select * from address where id = $1::integer', id)
  return res:copy() --- convert result to a Lua table
end

With this in place, the memory occupied by the result set in the C part of the code will be free'd immediately when the function returns by calling PQclear() from the underlying PostgreSQL C library.

I hope this is useful.

- mb