Skip to content

Commit

Permalink
odbc: Support connection with attribute key-value pairs
Browse files Browse the repository at this point in the history
`connect()` now accepts an attribute table to construct a connection string
for `SQLDriverConnect()`. It supports three forms now:

1. The original form
```lua
connect(source, user, pass)
```

2. Connect with the DSN keyword
```lua
connect {
  DSN = source,
  UID = user,
  PWD = pass,
}
```
or
```lua
connect({ DSN = source }, user, pass)
```

3. Connect with the DRIVER keyword
```lua
connect {
  DRIVER = "SQL Server",
  SERVER = ".\\SQLEXPRESS",
  UID = user,
  PWD = pass,
}
```
or
```lua
connect({
  DRIVER = "SQL Server",
  SERVER = ".\\SQLEXPRESS",
}, user, pass)
```
  • Loading branch information
huangqinjin committed Oct 29, 2024
1 parent d60f8b2 commit 91dcfca
Showing 1 changed file with 56 additions and 4 deletions.
60 changes: 56 additions & 4 deletions src/ls_odbc.c
Original file line number Diff line number Diff line change
Expand Up @@ -1075,9 +1075,12 @@ static int create_connection (lua_State *L, int o, env_data *env, SQLHDBC hdbc)
*/
static int env_connect (lua_State *L) {
env_data *env = (env_data *) getenvironment (L, 1);
SQLCHAR *sourcename = (SQLCHAR*)luaL_checkstring (L, 2);
SQLCHAR *sourcename = lua_istable(L, 2) ? NULL : (SQLCHAR*)luaL_checkstring (L, 2);
SQLCHAR *username = (SQLCHAR*)luaL_optstring (L, 3, NULL);
SQLCHAR *password = (SQLCHAR*)luaL_optstring (L, 4, NULL);
luaL_Buffer b;
int k;
int v;
SQLHDBC hdbc;
SQLRETURN ret;

Expand All @@ -1086,9 +1089,58 @@ static int env_connect (lua_State *L) {
if (error(ret))
return luasql_faildirect (L, "connection allocation error.");

/* tries to connect handle */
ret = SQLConnect (hdbc, sourcename, SQL_NTS,
username, SQL_NTS, password, SQL_NTS);
if (sourcename != NULL)
{
/* tries to connect handle */
ret = SQLConnect (hdbc, sourcename, SQL_NTS,
username, SQL_NTS, password, SQL_NTS);
}
else
{
lua_pushnil(L);
k = lua_gettop(L);
lua_pushnil(L);
v = lua_gettop(L);

luaL_buffinit(L, &b);

lua_pushnil(L);
while (lua_next(L, 2))
{
lua_replace(L, v);
lua_replace(L, k);
lua_pushvalue(L, k);
luaL_addvalue(&b);
luaL_addchar(&b, '=');
lua_pushvalue(L, v);
luaL_addvalue(&b);
luaL_addchar(&b, ';');
lua_pushvalue(L, k);
}

if (username != NULL)
{
luaL_addlstring(&b, "UID", 3);
luaL_addchar(&b, '=');
lua_pushvalue(L, 3);
luaL_addvalue(&b);
luaL_addchar(&b, ';');
}
if (password != NULL)
{
luaL_addlstring(&b, "PWD", 3);
luaL_addchar(&b, '=');
lua_pushvalue(L, 4);
luaL_addvalue(&b);
luaL_addchar(&b, ';');
}

/* tries to connect handle */
ret = SQLDriverConnect(hdbc, NULL,
luaL_buffaddr(&b), (SQLSMALLINT)luaL_bufflen(&b),
NULL, 0, NULL, SQL_DRIVER_NOPROMPT);
}

if (error(ret)) {
ret = fail(L, hDBC, hdbc);
SQLFreeHandle(hDBC, hdbc);
Expand Down

0 comments on commit 91dcfca

Please sign in to comment.