/*
* Created by Andrey Cherkashin (acherkashin)
* http://acherkashin.me
*
* License
* Copyright (c) 2015 Andrey Cherkashin
* The project released under the MIT license: http://opensource.org/licenses/MIT
*/
package ragefist.extension.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.OneArgFunction;
import org.luaj.vm2.lib.TwoArgFunction;
/**
*
* @author acherkashin
*/
public class LuaMySQL extends TwoArgFunction
{
@Override
public LuaValue call(LuaValue modname, LuaValue env) {
LuaTable table = LuaValue.tableOf();
// Getters
table.set("newConnection", lua_newConnection);
env.get("Extensions").set("MySQL", table);
return table;
}
OneArgFunction lua_newConnection = new OneArgFunction() {
@Override
public LuaValue call(LuaValue lv) {
String connectionURL = lv.tojstring();
if (connectionURL.isEmpty()) {
Logger.getLogger(LuaMySQL.class.getName()).log(Level.SEVERE, "ConnectionURL is null");
return LuaValue.FALSE;
}
Connection connection;
try {
connection = DriverManager.getConnection(connectionURL);
} catch (SQLException ex) {
Logger.getLogger(LuaMySQL.class.getName()).log(Level.SEVERE, null, ex);
return LuaValue.FALSE;
}
LuaTable table = LuaValue.tableOf();
table.set("connection", LuaValue.userdataOf(connection));
table.set("execute", lua_connection_execute);
return table;
}
};
TwoArgFunction lua_connection_execute = new TwoArgFunction() {
@Override
public LuaValue call(LuaValue self, LuaValue lv2) {
if (self.istable() == false) {
return LuaValue.listOf(new LuaValue[] { LuaValue.FALSE, LuaValue.valueOf("ERROR_BAD_SELF") });
}
if (self.get("connection") == LuaValue.NIL) {
return LuaValue.listOf(new LuaValue[] { LuaValue.FALSE, LuaValue.valueOf("ERROR_BAD_CONNECTION") });
}
Connection connection = (Connection)self.get("connection").touserdata();
if (connection == null) {
return LuaValue.listOf(new LuaValue[] { LuaValue.FALSE, LuaValue.valueOf("ERROR_BAD_CONNECTION") });
}
Statement stmt = null;
ResultSet rs = null;
try {
stmt = connection.createStatement();
if (stmt.execute(lv2.tojstring())) {
rs = stmt.getResultSet();
}
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
if (rs != null) {
try {
LuaTable table = ResultSetConverter.convertToLuaTable(rs);
try {
rs.close();
if(stmt != null) stmt.close();
} catch (SQLException sqlEx) { } // ignore
return LuaValue.listOf(new LuaValue[] { LuaValue.TRUE, table });
} catch (SQLException ex) {
Logger.getLogger(LuaMySQL.class.getName()).log(Level.SEVERE, null, ex);
return LuaValue.listOf(new LuaValue[] { LuaValue.FALSE, LuaValue.valueOf("ERROR_BAD_RESP") });
}
}
return LuaValue.TRUE;
}
};
}