提交 8d5a6ce7 authored 作者: Leon de Rooij's avatar Leon de Rooij

cleanup day

上级 ebd646b5
ENVIRONMENT_NAME= luamod
DRIVER_NAME= template
FS_ROOT = ../../../..
PREFIX= /usr/local
LUA_LIBDIR= $(PREFIX)/lib/lua/5.1
LUA_DIR= $(PREFIX)/share/lua/5.1
LIB_OPTION= -shared #for Linux
#LIB_OPTION= -bundle -undefined dynamic_lookup #for MacOS X
LIBNAME= $(DRIVER_NAME).so
#DRIVER_LIBS= -L/usr/lib64 -L/opt/freeswitch/lib
DRIVER_LIBS= -L/usr/lib64
INCS= -I/usr/include -I$(FS_ROOT)/src/mod/languages/mod_lua/lua -I $(FS_ROOT)/src/include -I$(FS_ROOT)/libs/libteletone/src
CFLAGS= -O2 -fPIC -Wall -ansi -pedantic $(INCS)
CPPFLAGS= -O2 -x c++ -fPIC -Wall -ansi -pedantic $(INCS)
CC= gcc
OBJS= luamod.o $(DRIVER_NAME).o
SRCS= luamod.h luamod.c $(DRIVER_NAME).c
AR= ar rcu
RANLIB= ranlib
#--
#lib: $(LIBNAME)
$(LIBNAME): $(OBJS)
$(CC) $(CPPFLAGS) -o $@ $(LIB_OPTION) $(OBJS) $(DRIVER_LIBS)
$(LIBNAME):
$(CC) $(CFLAGS) -o $@ $(LIB_OPTION) $(OBJS) $(DRIVER_LIBS)
install:
mkdir -p $(LUA_LIBDIR)/$(ENVIRONMENT_NAME)
cp $(LIBNAME) $(LUA_LIBDIR)/$(ENVIRONMENT_NAME)
clean:
rm -f $(LIBNAME) *.o $(COMPAT_O)
LuaMod is a simplification of the module / driver loading mechanism as written for LuaSQL.
I will try to see if I can make this template as generic as possible,
and ready for making use of the facilities provided by FreeSWITCH.
/*
** LuaMod: A simplification of the LuaSQL Module / Driver loading mechanism
** LuaSQL Credits: http://www.keplerproject.org/luasql/index.html#credits
*/
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "luamod.h"
/*
** Typical error situation
*/
LUAMOD_API int luamod_faildirect (lua_State *L, const char *err) {
lua_pushnil(L);
lua_pushstring(L, err);
return 2;
}
/*
** Return the name of the object's metatable.
** This function is used by `tostring'.
*/
static int luamod_tostring (lua_State *L) {
char buff[100];
pseudo_data *obj = (pseudo_data *)lua_touserdata (L, 1);
if (obj->closed)
strcpy (buff, "closed");
else
sprintf (buff, "%p", (void *)obj);
lua_pushfstring (L, "%s (%s)", lua_tostring(L,lua_upvalueindex(1)), buff);
return 1;
}
/*
** Create a metatable and leave it on top of the stack.
*/
LUAMOD_API int luamod_createmeta (lua_State *L, const char *name, const luaL_reg *methods) {
if (!luaL_newmetatable (L, name))
return 0;
/* define methods */
luaL_openlib (L, NULL, methods, 0);
/* define metamethods */
lua_pushliteral (L, "__gc");
lua_pushcfunction (L, methods->func);
lua_settable (L, -3);
lua_pushliteral (L, "__index");
lua_pushvalue (L, -2);
lua_settable (L, -3);
lua_pushliteral (L, "__tostring");
lua_pushstring (L, name);
lua_pushcclosure (L, luamod_tostring, 1);
lua_settable (L, -3);
lua_pushliteral (L, "__metatable");
lua_pushliteral (L, LUAMOD_PREFIX"you're not allowed to get this metatable");
lua_settable (L, -3);
return 1;
}
/*
** Define the metatable for the object on top of the stack
*/
LUAMOD_API void luamod_setmeta (lua_State *L, const char *name) {
luaL_getmetatable (L, name);
lua_setmetatable (L, -2);
}
/*
** Assumes the table is on top of the stack.
*/
LUAMOD_API void luamod_set_info (lua_State *L) {
lua_pushliteral (L, "_COPYRIGHT");
lua_pushliteral (L, "Copyright (C) 2003-2007 Kepler Project");
lua_settable (L, -3);
lua_pushliteral (L, "_DESCRIPTION");
lua_pushliteral (L, "LuaMod is an simplification of the LuaSQL module / driver implementation");
lua_settable (L, -3);
lua_pushliteral (L, "_VERSION");
lua_pushliteral (L, "LuaMod 1.0.0");
lua_settable (L, -3);
}
/*
** LuaMod: A simplification of the LuaSQL Module / Driver loading mechanism
** LuaSQL Credits: http://www.keplerproject.org/luasql/index.html#credits
*/
#ifndef _LUAMOD_
#define _LUAMOD_
#ifndef LUAMOD_API
#define LUAMOD_API
#endif
#define LUAMOD_PREFIX "LuaMod: "
#define LUAMOD_TABLENAME "luamod"
typedef struct {
short closed;
} pseudo_data;
LUAMOD_API int luamod_faildirect (lua_State *L, const char *err);
LUAMOD_API int luamod_createmeta (lua_State *L, const char *name, const luaL_reg *methods);
LUAMOD_API void luamod_setmeta (lua_State *L, const char *name);
LUAMOD_API void luamod_set_info (lua_State *L);
#endif
/*
** LuaMod: A simplification of the LuaSQL Module / Driver loading mechanism
** LuaSQL Credits: http://www.keplerproject.org/luasql/index.html#credits
*/
#include <switch.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined(_WIN32)
#include <windows.h>
#endif
#include "lua.h"
#include "lauxlib.h"
#include "luamod.h"
#define DRIVER_PREFIX "Test: "
#define DRIVER_ENV "Driver Environment"
#define DRIVER_OBJ "Driver Object"
typedef struct {
short closed;
int obj_counter;
} env_t;
typedef struct {
short closed;
int env; /* reference to environment */
char *mandatory_property;
char *optional_property;
} obj_t;
LUAMOD_API int luaopen_luamod_test (lua_State *L);
/*
** Check for valid env.
*/
static env_t *get_env (lua_State *L)
{
env_t *env = (env_t *) luaL_checkudata (L, 1, DRIVER_ENV);
luaL_argcheck (L, env != NULL, 1, LUAMOD_PREFIX"env expected");
luaL_argcheck (L, !env->closed, 1, LUAMOD_PREFIX"env is closed");
return env;
}
/*
** Check for valid obj.
*/
static obj_t *get_obj (lua_State *L)
{
obj_t *obj = (obj_t *) luaL_checkudata (L, 1, DRIVER_ENV);
luaL_argcheck (L, obj != NULL, 1, LUAMOD_PREFIX"obj expected");
luaL_argcheck (L, !obj->closed, 1, LUAMOD_PREFIX"obj is closed");
return obj;
}
/*
** Pushes true and returns 1
*/
static int pass(lua_State *L)
{
lua_pushboolean (L, 1);
return 1;
}
/*
** Closes an object
*/
static int obj_close (lua_State *L)
{
env_t *env;
obj_t *obj = (obj_t *) luaL_checkudata (L,1,DRIVER_OBJ);
luaL_argcheck (L, obj != NULL, 1, LUAMOD_PREFIX"object expected");
if (obj->closed) {
lua_pushboolean (L, 0);
return 1;
}
/* Decrement objection counter on environment object */
lua_rawgeti (L, LUA_REGISTRYINDEX, obj->env);
env = (env_t *) lua_touserdata (L, -1);
env->obj_counter--;
/* Nullify structure fields. */
obj->closed = 1;
obj->mandatory_property = NULL; /* perhaps do some free'ing here if necessary */
obj->optional_property = NULL;
luaL_unref (L, LUA_REGISTRYINDEX, obj->env);
return pass(L);
}
static int obj_method (lua_State *L)
{
obj_t *obj = (obj_t *) get_obj (L);
if (strcmp(obj->mandatory_property, "the right value")) /* or do something more interesting */
return luamod_faildirect (L, LUAMOD_PREFIX"your mandatory_property doesn't have the right value");
return 1; /* ok */
}
/*
** Instantiates a new object
** Lua Input: mandatory [, optional]
** mandatory: you must supply this argument
** optional: you may leave this argument out
** Lua Returns:
** object if successfull
** nil and error message otherwise.
*/
static int env_inst_obj (lua_State *L)
{
env_t *env = (env_t *) get_env (L);
const char *mandatory = luaL_checkstring (L, 2);
const char *optional = luaL_optstring (L, 3, NULL);
obj_t *obj = (obj_t *) lua_newuserdata (L, sizeof (obj_t));
luamod_setmeta (L, DRIVER_OBJ);
obj->closed = 0;
obj->env = LUA_NOREF;
obj->mandatory_property = (char *) mandatory;
obj->optional_property = (char *) optional;
lua_pushvalue (L, 1);
obj->env = luaL_ref (L, LUA_REGISTRYINDEX);
env->obj_counter++;
return 1;
}
/*
** Closes an env object - this function is automatically called on 1st gc try
*/
static int env_close (lua_State *L)
{
env_t *env = (env_t *) luaL_checkudata (L, 1, DRIVER_ENV);
luaL_argcheck (L, env != NULL, 1, LUAMOD_PREFIX"env expected");
if (env->closed) {
lua_pushboolean (L, 0);
return 1;
}
if (env->obj_counter > 0)
return luaL_error (L, LUAMOD_PREFIX"there are open objects");
env->closed = 1;
return pass(L);
}
/*
** Create metatables for each class of object.
*/
static void create_metatables (lua_State *L)
{
struct luaL_reg env_methods[] = {
{"close", env_close},
{"obj", env_inst_obj},
{NULL, NULL},
};
struct luaL_reg obj_methods[] = {
{"close", obj_close},
{"method", obj_method},
{NULL, NULL},
};
luamod_createmeta (L, DRIVER_ENV, env_methods);
luamod_createmeta (L, DRIVER_OBJ, obj_methods);
lua_pop (L, 2); /* 2 for the amount of metatables created */
}
/*
** Creates an Environment and returns it.
*/
static int create_env (lua_State *L)
{
env_t *env;
create_metatables (L);
env = (env_t *) lua_newuserdata (L, sizeof (env_t));
luamod_setmeta (L, DRIVER_ENV);
/* fill in structure */
env->closed = 0;
env->obj_counter = 0;
return 1;
}
/*
** Creates the metatables for the objects and registers the
** driver open method.
*/
LUAMOD_API int luaopen_luamod_template (lua_State *L)
{
struct luaL_reg driver[] = {
{"my_env", create_env},
{NULL, NULL},
};
luaL_openlib (L, LUAMOD_TABLENAME, driver, 0);
luamod_set_info (L);
return 1;
}
mod_lua_dbh - a different implementation from mod_lua_luasql for accessing switch_cache_sqldb from inside Lua.
This time it's done through SWIG. Syntax is different and it has the added benefit of using callback function, so the result doesn't necessarilty have to balloon in memory. Another nicety is that the function is available from the freeswitch table, to keep it more in line with existing functions (also implementation wise).
Syntax:
local dbh = freeswitch.Dbh("dsn","user","pass")
dbh:query("select 1 as foo", function(row) stream:write("Foo = " .. row.foo) end)
-- so the anonymous function is called for each row returned
-- to get previous (mod_odbc_query or mod_lua_luasql) functionality, you can do this:
local res = {}
dbh:query("select 1 as foo", function(row) table.insert(res, row) end)
--
Just use the diff from the root of your FreeSWITCH tree. Enjoy :)
diff --git a/src/mod/languages/mod_lua/freeswitch.i b/src/mod/languages/mod_lua/freeswitch.i
index 3631aca..49db372 100644
--- a/src/mod/languages/mod_lua/freeswitch.i
+++ b/src/mod/languages/mod_lua/freeswitch.i
@@ -18,6 +18,10 @@
%}
+/* Lua function typemap */
+%typemap(in,checkfn="lua_isfunction") SWIGLUA_FN
+%{ $1.L=L; $1.idx=$input; %}
+
%ignore SwitchToMempool;
%newobject EventConsumer::pop;
@@ -25,6 +29,7 @@
%newobject CoreSession;
%newobject Event;
%newobject Stream;
+%newobject Dbh;
/**
* tell swig to grok everything defined in these header files and
@@ -66,9 +71,18 @@ class Session : public CoreSession {
void setLUA(lua_State *state);
};
-}
-
-
+class Dbh {
+ private:
+ switch_cache_db_handle_t *dbh;
+ bool connected;
+ static int query_callback(void *pArg, int argc, char **argv, char **cargv);
+ public:
+ Dbh(char *dsn, char *user = NULL, char *pass = NULL);
+ ~Dbh();
+ bool release();
+ bool query(char *sql, SWIGLUA_FN lua_fun);
+};
+}
diff --git a/src/mod/languages/mod_lua/freeswitch_lua.cpp b/src/mod/languages/mod_lua/freeswitch_lua.cpp
index c73c88c..17d12bc 100644
--- a/src/mod/languages/mod_lua/freeswitch_lua.cpp
+++ b/src/mod/languages/mod_lua/freeswitch_lua.cpp
@@ -308,3 +308,69 @@ switch_status_t Session::run_dtmf_callback(void *input, switch_input_type_t ityp
return SWITCH_STATUS_SUCCESS;
}
+
+Dbh::Dbh(char *dsn, char *user, char *pass)
+{
+ switch_cache_db_connection_options_t options = { {0} };
+
+ options.odbc_options.dsn = dsn;
+ options.odbc_options.user = user;
+ options.odbc_options.pass = pass;
+
+ if (switch_cache_db_get_db_handle(&dbh, SCDB_TYPE_ODBC, &options) == SWITCH_STATUS_SUCCESS) {
+ connected = true;
+ } else {
+ connected = false;
+ }
+}
+
+Dbh::~Dbh()
+{
+ release();
+}
+
+bool Dbh::release()
+{
+ if (connected) {
+ switch_cache_db_release_db_handle(&dbh);
+ connected = false;
+ return true;
+ }
+ return false;
+}
+
+int Dbh::query_callback(void *pArg, int argc, char **argv, char **cargv)
+{
+ SWIGLUA_FN *lua_fun = (SWIGLUA_FN *)pArg;
+
+ lua_pushvalue(lua_fun->L, lua_fun->idx); /* get the lua callback function onto the stack */
+
+ lua_newtable(lua_fun->L); /* push a row (table) */
+
+ for (int i = 0; i < argc; i++) {
+ lua_pushstring(lua_fun->L, switch_str_nil(cargv[i]));
+ lua_pushstring(lua_fun->L, switch_str_nil(argv[i]));
+ lua_settable(lua_fun->L, -3);
+ }
+
+ lua_call(lua_fun->L, 1, 1); /* 1 in, 1 out */
+
+ if (lua_isnumber(lua_fun->L, -1)) {
+ if (lua_tonumber(lua_fun->L, -1) != 0) {
+ return 1;
+ }
+ }
+
+ return 0; /* 0 to continue with next row */
+}
+
+bool Dbh::query(char *sql, SWIGLUA_FN lua_fun)
+{
+ if (connected) {
+ if (switch_cache_db_execute_sql_callback(dbh, sql, query_callback, &lua_fun, NULL) == SWITCH_STATUS_SUCCESS) {
+ return true;
+ }
+ }
+ switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "no workie workie :(\n");
+ return false;
+}
diff --git a/src/mod/languages/mod_lua/freeswitch_lua.h b/src/mod/languages/mod_lua/freeswitch_lua.h
index a1f4a85..a0780b1 100644
--- a/src/mod/languages/mod_lua/freeswitch_lua.h
+++ b/src/mod/languages/mod_lua/freeswitch_lua.h
@@ -8,6 +8,16 @@ extern "C" {
#include "mod_lua_extra.h"
}
#include <switch_cpp.h>
+
+
+typedef struct{
+ lua_State* L;
+ int idx;
+}SWIGLUA_FN;
+
+#define SWIGLUA_FN_GET(fn) {lua_pushvalue(fn.L,fn.idx);}
+
+
namespace LUA {
class Session:public CoreSession {
private:
@@ -41,5 +51,17 @@ namespace LUA {
void setLUA(lua_State * state);
};
+
+ class Dbh {
+ protected:
+ switch_cache_db_handle_t *dbh;
+ bool connected;
+ static int query_callback(void *pArg, int argc, char **argv, char **cargv);
+ public:
+ Dbh(char *dsn, char *user = NULL, char *pass = NULL);
+ ~Dbh();
+ bool release();
+ bool query(char *sql, SWIGLUA_FN lua_fun);
+ };
}
#endif
diff --git a/src/mod/languages/mod_lua/hack.diff b/src/mod/languages/mod_lua/hack.diff
index afd37b0..fc33ddb 100644
--- a/src/mod/languages/mod_lua/hack.diff
+++ b/src/mod/languages/mod_lua/hack.diff
@@ -1,38 +1,38 @@
---- mod_lua_wrap.cpp 2008-07-16 16:58:58.000000000 -0400
-+++ old.cpp 2008-07-16 16:58:42.000000000 -0400
-@@ -6731,7 +6731,7 @@
- SWIG_check_num_args("LUA::Session",0,0)
+--- mod_lua_wrap.cpp.orig 2010-09-05 16:39:26.000000000 +0200
++++ mod_lua_wrap.cpp 2010-09-05 16:39:44.000000000 +0200
+@@ -4913,7 +4913,7 @@
+
result = (LUA::Session *)new LUA::Session();
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
-@@ -6759,7 +6759,7 @@
-
+ fail:
+@@ -4934,7 +4934,7 @@
+ arg2=(CoreSession *)SWIG_MustGetPtr(L,2,SWIGTYPE_p_CoreSession,0,2,"new_Session");
result = (LUA::Session *)new LUA::Session(arg1,arg2);
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
-@@ -6780,7 +6780,7 @@
- arg1 = (char *)lua_tostring(L, 1);
+ fail:
+@@ -4952,7 +4952,7 @@
+ arg1 = (char*)lua_tostring(L, 1);
result = (LUA::Session *)new LUA::Session(arg1);
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
-@@ -6805,7 +6805,7 @@
-
+ fail:
+@@ -4970,7 +4970,7 @@
+ arg1=(switch_core_session_t *)SWIG_MustGetPtr(L,1,SWIGTYPE_p_switch_core_session_t,0,1,"new_Session");
result = (LUA::Session *)new LUA::Session(arg1);
SWIG_arg=0;
- SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++;
+ SWIG_NewPointerObj(L,result,SWIGTYPE_p_LUA__Session,1); SWIG_arg++; result->setLUA(L);
return SWIG_arg;
- if(0) SWIG_fail;
+ fail:
diff --git a/src/mod/languages/mod_lua/my_swigable_cpp.h b/src/mod/languages/mod_lua/my_swigable_cpp.h
index d4d3168..ebe5972 100644
--- a/src/mod/languages/mod_lua/my_swigable_cpp.h
+++ b/src/mod/languages/mod_lua/my_swigable_cpp.h
@@ -49,6 +49,19 @@ class Event {
};
+class Dbh {
+ protected:
+ switch_cache_db_handle_t *dbh;
+ bool connected;
+ static int query_callback(void *pArg, int argc, char **argv, char **cargv);
+ public:
+ Dbh(char *dsn, char *user = NULL, char *pass = NULL);
+ ~Dbh();
+ bool release();
+ bool query(char *sql, SWIGLUA_FN lua_fun);
+};
+
+
class CoreSession {
protected:
switch_input_args_t args;
This patch includes LuaSQL with an 'scdb' driver into the mod_lua FreeSWITCH module.
Result is that it can make use of the connection pooling facilities provided by switch_core_sqldb.
Note that this version of the scdb driver does not have the following functions implemented: execute, commit, rollback, setautocommit.
This is because there is currently no support in switch_core_sqldb to get a single row from a cursor (hstmt).
I hope I can still implement this functionality soon(ish).
However, there is a new function available called exec2table, that takes an SQL statement
as argument and returns a table containing the entire result set.
To try it out, patch FreeSWITCH from the root of the source tree like this:
cd /usr/src/freeswitch
patch -p1 < contrib/ledr/c/mod_lua_luasql/mod_lua_luasql_20100828_1912.patch
The patch applies cleanly to git rev 540ee0123de4119b1df10ce752a5891248215a8b - Fri Aug 27 14:04:45 2010 -0500
Then re-build and install your mod_lua module:
make mod_lua-install
You can use it almost as how you'd use LuaSQL with ODBC driver, but you don't have to 'require' it as it's compiled into mod_lua:
-- DataDumper from here: http://lua-users.org/wiki/DataDumper --
require "DataDumper"
local env = assert(luasql.scdb())
local con = assert(env:connect("dsn", "user", "pass"))
local res = assert(con:exec2table("select * from routes"))
con:close() -- optional, connection (dbh) is automatically released
env:close() -- optional, environment is automatically closed
stream:write(DataDumper(res))
-- end of script --
And execute the script from your cli:
freeswitch@fs-dev> lua test.lua
return {
{
account_id="1",
date_end="2030-12-31 00:00:00",
date_start="1970-01-01 00:00:00",
digits="31320",
enabled="1",
id="4",
lead_strip="0",
prefix="",
quality="0.000000",
rate="0.000000",
reliability="0.000000",
suffix="",
trail_strip="0"
},
{
account_id="999",
date_end="2030-12-31 00:00:00",
date_start="1970-01-01 00:00:00",
digits="31321",
enabled="1",
id="6",
lead_strip="0",
prefix="",
quality="0.000000",
rate="0.000000",
reliability="0.000000",
suffix="",
trail_strip="0"
}
}
-- example.lua - just put this script in scripts/ and run it from you fs_cli
local env = assert(luasql.scdb()) -- same as regular luasql
local con = assert(env:connect("dsn","user","pass")) -- same as regular luasql
local res = assert(con:exec2table("select 1 as foo, 2 as bar")) -- all your rows in a single table
--[[ now res will contain this :
{
[1] = {
["foo"] = "1";
["bar"] = "2";
};
};
]]
for i = 1, table.getn(res) do -- loop through rows
for key, val in pairs(res[i]) do -- loop through columns
stream:write(string.format("%25s : %s\n", key, val))
end
stream:write("\n")
end
con:close(); -- optional, it is also closed at first gc run,
-- although it does release the dbh for re-use by another thread so can be efficient to do it early
env:close(); -- optional, (same reason) just don't close your env before closing the con !
--[[ output on your fs_cli should be :
freeswitch@internal> lua example.lua
bar : 2
foo : 1
]]
diff --git a/src/mod/languages/mod_lua/Makefile.am b/src/mod/languages/mod_lua/Makefile.am
index 805b52c..e030446 100644
--- a/src/mod/languages/mod_lua/Makefile.am
+++ b/src/mod/languages/mod_lua/Makefile.am
@@ -31,5 +31,6 @@ swigclean: clean
lua_wrap: mod_lua_extra.c
swig -lua -c++ -I../../../../src/include -oh mod_lua_wrap.h -o mod_lua_wrap.cpp freeswitch.i
echo "#include \"mod_lua_extra.c\"" >> mod_lua_wrap.cpp
+ echo "#include \"mod_lua_luasql.c\"" >> mod_lua_wrap.cpp
patch -s -p0 -i hack.diff
diff --git a/src/mod/languages/mod_lua/mod_lua.cpp b/src/mod/languages/mod_lua/mod_lua.cpp
index 3ccbef5..924ad55 100644
--- a/src/mod/languages/mod_lua/mod_lua.cpp
+++ b/src/mod/languages/mod_lua/mod_lua.cpp
@@ -37,6 +37,7 @@ SWITCH_BEGIN_EXTERN_C
#include <lauxlib.h>
#include <lualib.h>
#include "mod_lua_extra.h"
+#include "mod_lua_luasql.h"
SWITCH_MODULE_LOAD_FUNCTION(mod_lua_load);
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_lua_shutdown);
@@ -126,6 +127,9 @@ static int lua_parse_and_execute(lua_State * L, char *input_code)
return 1;
}
+ /* Create the metatables for LuaSQL (SCSDB Driver) objects and register the driver open method */
+ luaopen_luasql_scdb(L);
+
if (*input_code == '~') {
char *buff = input_code + 1;
error = luaL_loadbuffer(L, buff, strlen(buff), "line") || docall(L, 0, 1); //lua_pcall(L, 0, 0, 0);
diff --git a/src/mod/languages/mod_lua/mod_lua_luasql.c b/src/mod/languages/mod_lua/mod_lua_luasql.c
index e69de29..f0dee75 100644
--- a/src/mod/languages/mod_lua/mod_lua_luasql.c
+++ b/src/mod/languages/mod_lua/mod_lua_luasql.c
@@ -0,0 +1,490 @@
+/*
+ * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
+ * Copyright (C) 2005-2010, Anthony Minessale II <anthm@freeswitch.org>
+ *
+ * Version: MPL 1.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
+ *
+ * The Initial Developer of the Original Code is
+ * Anthony Minessale II <anthm@freeswitch.org>
+ *
+ * LuaSQL 2.1.1 - Database connectivity for the Lua programming language
+ * Redesigned by Roberto Ierusalimschy, Andre Carregal and Tomas Guisasola as part of the Kepler Project
+ * Implementation by Tomas Guisasola, Eduardo Quintao, Thiago Ponte, Fabio Mascarenhas and Danilo Tuler
+ * With many contributions from Michael Broughton, Tiago Dionizio, Leonardo Godinho, Pedro Maia, Klaus Ripke, Michael Roth and others
+ * LuaSQL 1.0 was originally designed by Pedro Miller Rabinovitch and Roberto Ierusalimschy
+ *
+ * The Initial Developer of this driver is
+ * Leon de Rooij <leon@toyos.nl>
+ *
+ * Portions created by the Initial Developer are Copyright (C)
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * Leon de Rooij <leon@toyos.nl>
+ *
+ * mod_lua_luasql.c -- LuaSQL driver for FreeSWITCH Core SQL DB
+ * Make use of the FreeSWITCH Core ODBC Cache features from inside a Lua script
+ *
+ */
+
+
+SWITCH_BEGIN_EXTERN_C
+
+
+#include <string.h>
+
+#include "lua.h"
+#include "lauxlib.h"
+
+#include "mod_lua_luasql.h"
+
+
+/*
+** Typical database error situation
+*/
+LUASQL_API int luasql_faildirect(lua_State *L, const char *err)
+{
+ lua_pushnil(L);
+ lua_pushstring(L, err);
+ return 2;
+}
+
+
+/*
+** Return the name of the object's metatable.
+** This function is used by `tostring'.
+*/
+static int luasql_tostring (lua_State *L)
+{
+ char buff[100];
+ pseudo_data *obj = (pseudo_data *)lua_touserdata (L, 1);
+ if (obj->closed)
+ strcpy (buff, "closed");
+ else
+ sprintf (buff, "%p", (void *)obj);
+ lua_pushfstring (L, "%s (%s)", lua_tostring(L,lua_upvalueindex(1)), buff);
+ return 1;
+}
+
+
+/*
+** Create a metatable and leave it on top of the stack.
+*/
+LUASQL_API int luasql_createmeta (lua_State *L, const char *name, const luaL_reg *methods)
+{
+ if (!luaL_newmetatable (L, name))
+ return 0;
+
+ /* define methods */
+ luaL_openlib (L, NULL, methods, 0);
+
+ /* define metamethods */
+ lua_pushliteral (L, "__gc");
+ lua_pushcfunction (L, methods->func);
+ lua_settable (L, -3);
+
+ lua_pushliteral (L, "__index");
+ lua_pushvalue (L, -2);
+ lua_settable (L, -3);
+
+ lua_pushliteral (L, "__tostring");
+ lua_pushstring (L, name);
+ lua_pushcclosure (L, luasql_tostring, 1);
+ lua_settable (L, -3);
+
+ lua_pushliteral (L, "__metatable");
+ lua_pushliteral (L, LUASQL_PREFIX"you're not allowed to get this metatable");
+ lua_settable (L, -3);
+
+ return 1;
+}
+
+
+/*
+** Define the metatable for the object on top of the stack
+*/
+LUASQL_API void luasql_setmeta (lua_State *L, const char *name)
+{
+ luaL_getmetatable (L, name);
+ lua_setmetatable (L, -2);
+}
+
+
+/*
+** Assumes the table is on top of the stack.
+*/
+LUASQL_API void luasql_set_info (lua_State *L)
+{
+ lua_pushliteral (L, "_COPYRIGHT");
+ lua_pushliteral (L, "Copyright (C) 2003-2007 Kepler Project");
+ lua_settable (L, -3);
+ lua_pushliteral (L, "_DESCRIPTION");
+ lua_pushliteral (L, "LuaSQL is a simple interface from Lua to a DBMS");
+ lua_settable (L, -3);
+ lua_pushliteral (L, "_VERSION");
+ lua_pushliteral (L, "LuaSQL 2.1.1");
+ lua_settable (L, -3);
+}
+
+
+
+
+
+
+/* End of copy luasql.c */
+
+
+
+
+
+
+#define LUASQL_ENVIRONMENT_SCDB "SCDB environment"
+#define LUASQL_CONNECTION_SCDB "SCDB connection"
+#define LUASQL_CURSOR_SCDB "SCDB cursor"
+
+
+typedef struct {
+ short closed;
+ int conn_counter;
+} env_data;
+
+
+typedef struct {
+ short closed;
+ int cur_counter;
+ int env; /* reference to environment */
+ switch_cache_db_handle_t *dbh;
+} conn_data;
+
+
+/*
+** Check for valid environment.
+*/
+static env_data *getenvironment (lua_State *L)
+{
+ env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_SCDB);
+ luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected");
+ luaL_argcheck (L, !env->closed, 1, LUASQL_PREFIX"environment is closed");
+ return env;
+}
+
+
+/*
+** Check for valid connection.
+*/
+static conn_data *getconnection (lua_State *L)
+{
+ conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_SCDB);
+ luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected");
+ luaL_argcheck (L, !conn->closed, 1, LUASQL_PREFIX"connection is closed");
+ return conn;
+}
+
+
+/*
+** Pushes true and returns 1
+*/
+static int pass(lua_State *L)
+{
+ lua_pushboolean (L, 1);
+ return 1;
+}
+
+
+/*
+** Closes a connection.
+*/
+static int conn_close (lua_State *L)
+{
+ env_data *env;
+ conn_data *conn = (conn_data *) luaL_checkudata(L,1,LUASQL_CONNECTION_SCDB);
+ luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected");
+ if (conn->closed) {
+ lua_pushboolean (L, 0);
+ return 1;
+ }
+ if (conn->cur_counter > 0)
+ return luaL_error (L, LUASQL_PREFIX"there are open cursors");
+
+ /* Decrement connection counter on environment object */
+ lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env);
+ env = (env_data *) lua_touserdata (L, -1);
+ env->conn_counter--;
+
+ /* Nullify structure fields. */
+ conn->closed = 1;
+ luaL_unref (L, LUA_REGISTRYINDEX, conn->env);
+ switch_cache_db_release_db_handle(&(conn->dbh));
+ return pass(L);
+}
+
+
+/*
+** Executes an SQL statement. - NOT IMPLEMENTED YET
+** Returns
+** cursor object: if there are results or
+** row count: number of rows affected by statement if no results
+*/
+static int conn_execute (lua_State *L)
+{
+ return luasql_faildirect (L, LUASQL_PREFIX"execute function is not implemented yet.");
+}
+
+
+/*
+** Rolls back a transaction. - NOT IMPLEMENTED YET
+*/
+static int conn_commit (lua_State *L)
+{
+ return luasql_faildirect (L, LUASQL_PREFIX"commit function is not implemented yet.");
+}
+
+
+/*
+** Rollback the current transaction. - NOT IMPLEMENTED YET
+*/
+static int conn_rollback (lua_State *L)
+{
+ return luasql_faildirect (L, LUASQL_PREFIX"rollback function is not implemented yet.");
+}
+
+
+/*
+** Sets the auto commit mode. - NOT IMPLEMENTED YET
+*/
+static int conn_setautocommit (lua_State *L)
+{
+ return luasql_faildirect (L, LUASQL_PREFIX"setautocommit function is not implemented yet.");
+}
+
+
+/*
+** Callback Struct for conn_exec2table
+*/
+typedef struct exec2table_callback_obj {
+ int rowcount;
+ lua_State *L;
+} exec2table_callback_t;
+
+
+/*
+** Callback function for conn_exec2table
+*/
+static int exec2table_callback(void *pArg, int argc, char **argv, char **columnName)
+{
+ exec2table_callback_t *cbt = (exec2table_callback_t *) pArg;
+ cbt->rowcount++;
+
+ lua_pushnumber(cbt->L, cbt->rowcount);
+
+ lua_newtable(cbt->L);
+
+ for (int i = 0; i < argc; i++) {
+ lua_pushstring(cbt->L, switch_str_nil(columnName[i]));
+ lua_pushstring(cbt->L, switch_str_nil(argv[i]));
+ lua_settable(cbt->L, -3);
+ }
+ lua_settable(cbt->L, -3);
+
+ return 0;
+}
+
+
+/*
+** Executes an SQL statement and returns the entire result set as a table
+** NOTE: Implemented because of lack of cursor support
+** NOTE: No native column type support - everything is a string
+** Returns
+** table containing the entire result set
+*/
+static int conn_exec2table (lua_State *L)
+{
+ conn_data *conn = (conn_data *) getconnection (L);
+ exec2table_callback_t cbt = { 0 };
+
+ const char *statement = luaL_checkstring(L, 2);
+
+ lua_newtable(L);
+
+ cbt.rowcount = 0;
+ cbt.L = L;
+
+ if (switch_cache_db_execute_sql_callback(conn->dbh, (char *) statement,
+ exec2table_callback, (void *) &cbt, NULL) == SWITCH_ODBC_FAIL) {
+ return luasql_faildirect (L, LUASQL_PREFIX"error while performing query.");
+ }
+
+ return 1;
+}
+
+
+/*
+** Create a new Connection object and push it on top of the stack.
+*/
+static int create_connection (lua_State *L, int o, env_data *env, switch_cache_db_handle_t *dbh)
+{
+ conn_data *conn = (conn_data *) lua_newuserdata(L, sizeof(conn_data));
+ /* set auto commit mode */
+ /* NOT IMPLEMENTED YET - But why not just BEGIN your transaction in SQL ? */
+ /*
+ SQLRETURN ret = SQLSetConnectAttr(dbh, SQL_ATTR_AUTOCOMMIT,
+ (SQLPOINTER) SQL_AUTOCOMMIT_ON, 0);
+ if (error(ret))
+ return fail(L, hDBC, dbh);
+ */
+
+ luasql_setmeta (L, LUASQL_CONNECTION_SCDB);
+
+ /* fill in structure */
+ conn->closed = 0;
+ conn->cur_counter = 0;
+ conn->env = LUA_NOREF;
+ conn->dbh = dbh;
+ lua_pushvalue (L, o);
+ conn->env = luaL_ref (L, LUA_REGISTRYINDEX);
+ env->conn_counter++;
+ return 1;
+}
+
+
+/*
+** Creates and returns a connection object
+** Lua Input: dsn [, user [, pass]]
+** dsn: data source name
+** user, pass: data source authentication information
+** Lua Returns:
+** connection object if successfull
+** nil and error message otherwise.
+*/
+static int env_connect (lua_State *L)
+{
+ switch_cache_db_connection_options_t options = { {0} };
+ switch_cache_db_handle_t *dbh = NULL;
+
+ env_data *env = (env_data *) getenvironment (L);
+ const char *dsn = luaL_checkstring (L, 2);
+ const char *user = luaL_optstring (L, 3, NULL);
+ const char *pass = luaL_optstring (L, 4, NULL);
+
+ if (zstr(dsn))
+ return luasql_faildirect (L, LUASQL_PREFIX"no dsn parameter supplied.");
+
+ options.odbc_options.dsn = (char *) dsn;
+ options.odbc_options.user = (char *) user;
+ options.odbc_options.pass = (char *) pass;
+
+ /* try to allocate connection handle */
+ if (switch_cache_db_get_db_handle(&dbh, SCDB_TYPE_ODBC, &options) != SWITCH_STATUS_SUCCESS)
+ return luasql_faildirect (L, LUASQL_PREFIX"unable to get db handle.");
+
+ /* success, return connection object */
+ return create_connection (L, 1, env, dbh);
+}
+
+
+/*
+** Closes an environment object
+*/
+static int env_close (lua_State *L)
+{
+ env_data *env = (env_data *) luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SCDB);
+ luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected");
+ if (env->closed) {
+ lua_pushboolean (L, 0);
+ return 1;
+ }
+ if (env->conn_counter > 0)
+ return luaL_error (L, LUASQL_PREFIX"there are open connections");
+
+ env->closed = 1;
+
+ return pass(L);
+}
+
+
+/*
+** Create metatables for each class of object.
+*/
+static void create_metatables (lua_State *L)
+{
+ struct luaL_reg environment_methods[] = {
+ {"close", env_close},
+ {"connect", env_connect},
+ {NULL, NULL},
+ };
+ struct luaL_reg connection_methods[] = {
+ {"close", conn_close},
+ {"execute", conn_execute}, /* NOT IMPLEMENTED YET */
+ {"commit", conn_commit}, /* NOT IMPLEMENTED YET */
+ {"rollback", conn_rollback}, /* NOT IMPLEMENTED YET */
+ {"setautocommit", conn_setautocommit}, /* NOT IMPLEMENTED YET */
+ {"exec2table", conn_exec2table},
+ {NULL, NULL},
+ };
+ struct luaL_reg cursor_methods[] = {
+/* {"close", cur_close}, */ /* NOT IMPLEMENTED YET */
+/* {"fetch", cur_fetch}, */ /* NOT IMPLEMENTED YET */
+/* {"getcoltypes", cur_coltypes}, */ /* NOT IMPLEMENTED YET */
+/* {"getcolnames", cur_colnames}, */ /* NOT IMPLEMENTED YET */
+ {NULL, NULL},
+ };
+ luasql_createmeta (L, LUASQL_ENVIRONMENT_SCDB, environment_methods);
+ luasql_createmeta (L, LUASQL_CONNECTION_SCDB, connection_methods);
+ luasql_createmeta (L, LUASQL_CURSOR_SCDB, cursor_methods);
+ lua_pop (L, 3);
+}
+
+
+/*
+** Creates an Environment and returns it.
+*/
+static int create_environment (lua_State *L)
+{
+ if (!switch_odbc_available()) {
+ switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "No core ODBC available.\n");
+ return luasql_faildirect (L, LUASQL_PREFIX"No core ODBC available.");
+ }
+
+ create_metatables (L); /* was in luaopen_luasql_scdb below, is it alright here ? */
+
+ env_data *env = (env_data *) lua_newuserdata(L, sizeof(env_data));
+ luasql_setmeta(L, LUASQL_ENVIRONMENT_SCDB);
+
+ /* fill in structure */
+ env->closed = 0;
+ env->conn_counter = 0;
+ return 1;
+}
+
+
+/*
+** Creates the metatables for the objects and registers the
+** driver open method.
+*/
+LUASQL_API int luaopen_luasql_scdb (lua_State *L)
+{
+ struct luaL_reg driver[] = {
+ {"scdb", create_environment},
+ {NULL, NULL},
+ };
+ /* create_metatables (L); // this was done here, moved to create_environment, but will it affect gc ? */
+ luaL_openlib (L, LUASQL_TABLENAME, driver, 0);
+ luasql_set_info (L);
+
+ return 1;
+}
+
+
+SWITCH_END_EXTERN_C
diff --git a/src/mod/languages/mod_lua/mod_lua_luasql.h b/src/mod/languages/mod_lua/mod_lua_luasql.h
index e69de29..6f12aef 100644
--- a/src/mod/languages/mod_lua/mod_lua_luasql.h
+++ b/src/mod/languages/mod_lua/mod_lua_luasql.h
@@ -0,0 +1,27 @@
+#ifndef MOD_LUA_LUASQL
+#define MOD_LUA_LUASQL
+SWITCH_BEGIN_EXTERN_C
+
+#ifndef LUASQL_API
+#define LUASQL_API
+#endif
+
+#define LUASQL_PREFIX "LuaSQL: "
+#define LUASQL_TABLENAME "luasql"
+#define LUASQL_ENVIRONMENT "Each driver must have an environment metatable"
+#define LUASQL_CONNECTION "Each driver must have a connection metatable"
+#define LUASQL_CURSOR "Each driver must have a cursor metatable"
+
+typedef struct {
+ short closed;
+} pseudo_data;
+
+LUASQL_API int luasql_faildirect (lua_State *L, const char *err);
+LUASQL_API int luasql_createmeta (lua_State *L, const char *name, const luaL_reg *methods);
+LUASQL_API void luasql_setmeta (lua_State *L, const char *name);
+LUASQL_API void luasql_set_info (lua_State *L);
+
+LUASQL_API int luaopen_luasql_scdb (lua_State *L);
+
+SWITCH_END_EXTERN_C
+#endif
diff --git a/src/mod/languages/mod_lua/mod_lua_wrap.cpp b/src/mod/languages/mod_lua/mod_lua_wrap.cpp
index bdb5097..e19cf0f 100644
--- a/src/mod/languages/mod_lua/mod_lua_wrap.cpp
+++ b/src/mod/languages/mod_lua/mod_lua_wrap.cpp
@@ -7463,3 +7463,4 @@ void SWIG_init_user(lua_State* L)
}
#include "mod_lua_extra.c"
+#include "mod_lua_luasql.c"
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论