]>
jfr.im git - irc/quakenet/newserv.git/blob - lua/luadb.c
3 #include "../pqsql/pqsql.h"
5 static int lua_dbcreatequery(lua_State
*ps
) {
6 char *s
= (char *)lua_tostring(ps
, 1);
9 LUA_RETURN(ps
, LUA_FAIL
);
12 LUA_RETURN(ps
, LUA_OK
);
17 static int lua_dbloadtable(lua_State *ps) {
18 lua_list *l = lua_listfromstate(ps);
20 LUA_RETURN(ps, LUA_FAIL);
25 typedef struct lua_callback
{
33 static int lua_dbnumfields(lua_State
*ps
) {
34 lua_pushint(ps
, PQnfields(pgres
));
39 static int lua_dbnumrows(lua_State
*ps
) {
40 lua_pushint(ps
, PQntuples(pgres
));
45 static int lua_dbgetvalue(lua_State
*ps
) {
47 int tuple
, field
, len
;
49 if(!lua_isint(ps
, 1) || !lua_isint(ps
, 2))
52 tuple
= lua_toint(ps
, 1);
53 field
= lua_toint(ps
, 2);
55 r
= PQgetvalue(pgres
, lua_toint(ps
, 1), lua_toint(ps
, 2));
56 len
= PQgetlength(pgres
, tuple
, field
);
58 lua_pushlstring(ps
, r
, len
); /* safe?! */
63 void lua_dbcallback(PGconn
*dbconn
, void *arg
) {
64 pgres
= PQgetResult(dbconn
);
65 lua_callback
*c
= (lua_callback
*)arg
;
67 if(!lua_listexists(c
->l
)) {
72 if(PQresultStatus(pgres
) != PGRES_TUPLES_OK
) {
73 _lua_vpcall(c
->l
->l
, (void *)c
->handler
, LUA_POINTERMODE
, "bR", 0, c
->args
);
75 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->handler
);
76 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->args
);
81 _lua_vpcall(c
->l
->l
, (void *)c
->handler
, LUA_POINTERMODE
, "bR", 1, c
->args
);
83 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->handler
);
84 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->args
);
90 static int lua_dbquery(lua_State
*ps
) {
91 lua_list
*l
= lua_listfromstate(ps
);
92 char *q
= (char *)lua_tostring(ps
, 1);
95 /* what happens if 3 isn't there? */
97 LUA_RETURN(ps
, LUA_FAIL
);
99 if(!lua_isfunction(ps
, 2)) {
101 LUA_RETURN(ps
, LUA_OK
);
104 cb
= (lua_callback
*)luamalloc(sizeof(lua_callback
));
106 LUA_RETURN(ps
, LUA_FAIL
);
109 cb
->args
= luaL_ref(ps
, LUA_REGISTRYINDEX
);
110 cb
->handler
= luaL_ref(ps
, LUA_REGISTRYINDEX
);
112 pqasyncquery(lua_dbcallback
, cb
, q
);
114 LUA_RETURN(ps
, LUA_OK
);
117 static int lua_dbescape(lua_State
*ps
) {
119 char *s
= (char *)lua_tostring(ps
, 1);
126 len
= lua_strlen(ps
, 1);
127 if(len
> sizeof(ebuf
) / 2 - 5)
130 elen
= PQescapeString(ebuf
, s
, len
);
131 lua_pushlstring(ps
, ebuf
, elen
);
136 void lua_registerdbcommands(lua_State
*l
) {
137 lua_register(l
, "db_createquery", lua_dbcreatequery
);
139 /* lua_register(l, "db_loadtable", lua_dbloadtable); */
141 lua_register(l
, "db_query", lua_dbquery
);
142 lua_register(l
, "db_escape", lua_dbescape
);
143 lua_register(l
, "db_numfields", lua_dbnumfields
);
144 lua_register(l
, "db_numrows", lua_dbnumrows
);
145 lua_register(l
, "db_getvalue", lua_dbgetvalue
);