]>
jfr.im git - irc/quakenet/newserv.git/blob - lua/luadb.c
7 #include "../pqsql/pqsql.h"
9 static int lua_dbcreatequery(lua_State
*ps
) {
10 char *s
= (char *)lua_tostring(ps
, 1);
13 LUA_RETURN(ps
, LUA_FAIL
);
16 LUA_RETURN(ps
, LUA_OK
);
21 static int lua_dbloadtable(lua_State *ps) {
22 lua_list *l = lua_listfromstate(ps);
24 LUA_RETURN(ps, LUA_FAIL);
29 typedef struct lua_callback
{
37 static int lua_dbnumfields(lua_State
*ps
) {
38 lua_pushint(ps
, PQnfields(pgres
));
43 static int lua_dbnumrows(lua_State
*ps
) {
44 lua_pushint(ps
, PQntuples(pgres
));
49 static int lua_dbgetvalue(lua_State
*ps
) {
51 int tuple
, field
, len
;
53 if(!lua_isint(ps
, 1) || !lua_isint(ps
, 2))
56 tuple
= lua_toint(ps
, 1);
57 field
= lua_toint(ps
, 2);
59 r
= PQgetvalue(pgres
, lua_toint(ps
, 1), lua_toint(ps
, 2));
60 len
= PQgetlength(pgres
, tuple
, field
);
62 lua_pushlstring(ps
, r
, len
); /* safe?! */
67 void lua_dbcallback(PGconn
*dbconn
, void *arg
) {
68 pgres
= PQgetResult(dbconn
);
69 lua_callback
*c
= (lua_callback
*)arg
;
71 if(!lua_listexists(c
->l
)) {
76 if(PQresultStatus(pgres
) != PGRES_TUPLES_OK
) {
77 _lua_vpcall(c
->l
->l
, (void *)c
->handler
, LUA_POINTERMODE
, "bR", 0, c
->args
);
79 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->handler
);
80 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->args
);
85 _lua_vpcall(c
->l
->l
, (void *)c
->handler
, LUA_POINTERMODE
, "bR", 1, c
->args
);
87 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->handler
);
88 luaL_unref(c
->l
->l
, LUA_REGISTRYINDEX
, c
->args
);
94 static int lua_dbquery(lua_State
*ps
) {
95 lua_list
*l
= lua_listfromstate(ps
);
96 char *q
= (char *)lua_tostring(ps
, 1);
99 /* what happens if 3 isn't there? */
101 LUA_RETURN(ps
, LUA_FAIL
);
103 if(!lua_isfunction(ps
, 2)) {
105 LUA_RETURN(ps
, LUA_OK
);
108 cb
= (lua_callback
*)luamalloc(sizeof(lua_callback
));
110 LUA_RETURN(ps
, LUA_FAIL
);
113 cb
->args
= luaL_ref(ps
, LUA_REGISTRYINDEX
);
114 cb
->handler
= luaL_ref(ps
, LUA_REGISTRYINDEX
);
116 pqasyncquery(lua_dbcallback
, cb
, q
);
118 LUA_RETURN(ps
, LUA_OK
);
121 static int lua_dbescape(lua_State
*ps
) {
123 char *s
= (char *)lua_tostring(ps
, 1);
130 len
= lua_strlen(ps
, 1);
131 if(len
> sizeof(ebuf
) / 2 - 5)
134 elen
= PQescapeString(ebuf
, s
, len
);
135 lua_pushlstring(ps
, ebuf
, elen
);
140 void lua_registerdbcommands(lua_State
*l
) {
141 lua_register(l
, "db_createquery", lua_dbcreatequery
);
143 /* lua_register(l, "db_loadtable", lua_dbloadtable); */
145 lua_register(l
, "db_query", lua_dbquery
);
146 lua_register(l
, "db_escape", lua_dbescape
);
147 lua_register(l
, "db_numfields", lua_dbnumfields
);
148 lua_register(l
, "db_numrows", lua_dbnumrows
);
149 lua_register(l
, "db_getvalue", lua_dbgetvalue
);
154 void lua_registerdbcommands(lua_State
*l
) {