dbd/mysql/connection.c

changeset 3
b61020ca4753
parent 2
c4f02fc67e5a
child 4
c50b0e6f25d6
equal deleted inserted replaced
2:c4f02fc67e5a 3:b61020ca4753
1 #include "dbd_mysql.h" 1 #include "dbd_mysql.h"
2 2
3 int dbd_mysql_statement_create(lua_State *L, connection_t *conn, const char *sql_query); 3 int dbd_mysql_statement_create(lua_State *L, connection_t *conn, const char *sql_query);
4 4
5 /* 5 /*
6 * connection = DBD.MySQl.New(dbname, user, password, host, port) 6 * connection,err = DBD.MySQl.New(dbname, user, password, host, port)
7 */ 7 */
8 static int connection_new(lua_State *L) { 8 static int connection_new(lua_State *L) {
9 int n = lua_gettop(L); 9 int n = lua_gettop(L);
10 10
11 connection_t *conn = NULL; 11 connection_t *conn = NULL;
40 40
41 conn = (connection_t *)lua_newuserdata(L, sizeof(connection_t)); 41 conn = (connection_t *)lua_newuserdata(L, sizeof(connection_t));
42 42
43 conn->mysql = mysql_init(NULL); 43 conn->mysql = mysql_init(NULL);
44 44
45 if (mysql_real_connect(conn->mysql, host, user, password, db, port, unix_socket, client_flag)) { 45 if (!mysql_real_connect(conn->mysql, host, user, password, db, port, unix_socket, client_flag)) {
46 luaL_getmetatable(L, DBD_MYSQL_CONNECTION);
47 lua_setmetatable(L, -2);
48 } else {
49 luaL_error(L, "Failed to connect to database: %s", mysql_error(conn->mysql));
50 lua_pushnil(L); 46 lua_pushnil(L);
47 lua_pushfstring(L, "Failed to connect to database: %s", mysql_error(conn->mysql));
48 return 2;
51 } 49 }
50
51 luaL_getmetatable(L, DBD_MYSQL_CONNECTION);
52 lua_setmetatable(L, -2);
52 53
53 return 1; 54 return 1;
54 } 55 }
55 56
56 /* 57 /*
61 int disconnect = 0; 62 int disconnect = 0;
62 63
63 if (conn->mysql) { 64 if (conn->mysql) {
64 mysql_close(conn->mysql); 65 mysql_close(conn->mysql);
65 disconnect = 1; 66 disconnect = 1;
67 conn->mysql = NULL;
66 } 68 }
67 69
68 lua_pushboolean(L, disconnect); 70 lua_pushboolean(L, disconnect);
69 return 1; 71 return 1;
70 } 72 }
83 lua_pushboolean(L, !err); 85 lua_pushboolean(L, !err);
84 return 1; 86 return 1;
85 } 87 }
86 88
87 /* 89 /*
88 * statement = connection:prepare(sql_string) 90 * statement,err = connection:prepare(sql_string)
89 */ 91 */
90 static int connection_prepare(lua_State *L) { 92 static int connection_prepare(lua_State *L) {
91 connection_t *conn = (connection_t *)luaL_checkudata(L, 1, DBD_MYSQL_CONNECTION); 93 connection_t *conn = (connection_t *)luaL_checkudata(L, 1, DBD_MYSQL_CONNECTION);
92 94
93 if (conn->mysql) { 95 if (conn->mysql) {
94 return dbd_mysql_statement_create(L, conn, luaL_checkstring(L, 2)); 96 return dbd_mysql_statement_create(L, conn, luaL_checkstring(L, 2));
95 } 97 }
96 98
97 lua_pushnil(L); 99 lua_pushnil(L);
98 return 1; 100 lua_pushstring(L, "Database not available");
101
102 return 2;
99 } 103 }
100 104
101 /* 105 /*
102 * __gc 106 * __gc
103 */ 107 */

mercurial