Example #1
0
/*
** Escapes a string for use within an SQL statement.
** Returns a string with the escaped string.
*/
static int conn_escape (lua_State *L) {
	conn_data *conn = getconnection (L);
	size_t len;
	const char *from = luaL_checklstring (L, 2, &len);
	int error;
	int ret = 1;
	luaL_Buffer b;
#if defined(luaL_buffinitsize)
	char *to = luaL_buffinitsize (L, &b, 2*len+1);
#else
	char *to;
	luaL_buffinit (L, &b);
	to = luaL_prepbuffer (&b);
#endif
	len = PQescapeStringConn (conn->pg_conn, to, from, len, &error);
	if (error == 0) { /* success ! */
#if defined(luaL_pushresultsize)
		luaL_pushresultsize (&b, len);
#else
		luaL_addsize (&b, len);
		luaL_pushresult (&b);
#endif
	} else {
		ret = luasql_failmsg (L, "cannot escape string. PostgreSQL: ", PQerrorMessage (conn->pg_conn));
	}
	return ret;
}
Example #2
0
/*
** Escapes a string for use within an SQL statement.
** Returns a string with the escaped string.
*/
static int conn_escape (lua_State *L) {
	conn_data *conn = getconnection (L);
	size_t len;
	const char *from = luaL_checklstring (L, 2, &len);
	char to[len*sizeof(char)*2+1];
	int error;
	len = PQescapeStringConn (conn->pg_conn, to, from, len, &error);
	if (error == 0) { /* success ! */
		lua_pushlstring (L, to, len);
		return 1;
	} else
		return luasql_failmsg (L, "cannot escape string. PostgreSQL: ", PQerrorMessage (conn->pg_conn));
}
Example #3
0
/*
** Connects to a data source.
*/
static int env_connect (lua_State *L) {
	const char *sourcename = luaL_checkstring(L, 2);
	const char *username = luaL_optstring(L, 3, NULL);
	const char *password = luaL_optstring(L, 4, NULL);
	const char *pghost = luaL_optstring(L, 5, NULL);
	const char *pgport = luaL_optstring(L, 6, NULL);
	PGconn *conn;
	getenvironment (L);	/* validate environment */
	conn = PQsetdbLogin(pghost, pgport, NULL, NULL, sourcename, username, password);

	if (PQstatus(conn) == CONNECTION_BAD) {
		int rc = luasql_failmsg(L, "error connecting to database. PostgreSQL: ", PQerrorMessage(conn));
		PQfinish(conn);
		return rc;
	}
	PQsetNoticeProcessor(conn, notice_processor, NULL);
	return create_connection(L, 1, conn);
}
Example #4
0
/*
** Execute an SQL statement.
** Return a Cursor object if the statement is a query, otherwise
** return the number of tuples affected by the statement.
*/
static int conn_execute (lua_State *L) {
	conn_data *conn = getconnection (L);
	const char *statement = luaL_checkstring (L, 2);
	PGresult *res = PQexec(conn->pg_conn, statement);
	if (res && PQresultStatus(res)==PGRES_COMMAND_OK) {
		/* no tuples returned */
		lua_pushnumber(L, atof(PQcmdTuples(res)));
		PQclear (res);
		return 1;
	}
	else if (res && PQresultStatus(res)==PGRES_TUPLES_OK)
		/* tuples returned */
		return create_cursor (L, 1, res);
	else {
		/* error */
		PQclear (res);
		return luasql_failmsg(L, "error executing statement. PostgreSQL: ", PQerrorMessage(conn->pg_conn));
	}
}