pax_global_header00006660000000000000000000000064117574300050014514gustar00rootroot0000000000000052 comment=c5270246408557791c6784db0ed2ee2cf32adee9 keplerproject-luasql-c527024/000077500000000000000000000000001175743000500161345ustar00rootroot00000000000000keplerproject-luasql-c527024/Makefile000066400000000000000000000011651175743000500175770ustar00rootroot00000000000000V= 2.3.0 CONFIG= ./config include $(CONFIG) OBJS= src/luasql.o src/ls_$T.o SRCS= src/luasql.h src/luasql.c \ src/ls_firebird.c \ src/ls_postgres.c \ src/ls_odbc.c \ src/ls_oci8.c \ src/ls_mysql.c \ src/ls_sqlite.c \ src/ls_sqlite3.c AR= ar rcu RANLIB= ranlib lib: src/$(LIBNAME) src/$(LIBNAME): $(OBJS) export MACOSX_DEPLOYMENT_TARGET="10.3"; $(CC) $(CFLAGS) -o $@ $(LIB_OPTION) $(OBJS) $(DRIVER_LIBS) install: mkdir -p $(LUA_LIBDIR)/luasql cp src/$(LIBNAME) $(LUA_LIBDIR)/luasql jdbc_driver: cd src/jdbc; make $@ clean: rm -f src/$(LIBNAME) src/*.o # $Id: Makefile,v 1.56 2008/05/30 17:21:18 tomas Exp $ keplerproject-luasql-c527024/Makefile.win000066400000000000000000000006111175743000500203660ustar00rootroot00000000000000 OBJS= src\luasql.obj src\ls_$T.obj SRCS= src\luasql.h src\luasql.c src\ls_$T.c LIBNAME= $T.dll all: src\$(LIBNAME) .c.obj: cl /c /Fo$@ /O2 $(CFLAGS) /DWIN32 /D_CRT_SECURE_NO_DEPRECATE $< src\$(LIBNAME): $(OBJS) link /dll /def:src\$T.def /out:$@ $(LIB_OPTION) $(OBJS) install: IF NOT EXIST "$(LUA_LIBDIR)\luasql" mkdir "$(LUA_LIBDIR)\luasql" cp src\$(LIBNAME) "$(LUA_LIBDIR)\luasql" keplerproject-luasql-c527024/Makefile.win.ado000066400000000000000000000002111175743000500211240ustar00rootroot00000000000000LUA_DIR=c:\lua5.1\lua install: IF NOT EXIST $(LUA_DIR)\luasql mkdir $(LUA_DIR)\luasql copy src\ado\ado.lua $(LUA_DIR)\luasql clean: keplerproject-luasql-c527024/Makefile.win.firebird000066400000000000000000000010451175743000500221550ustar00rootroot00000000000000LUA_INC=c:\lua5.1\include LUA_DIR=c:\lua5.1\lua LUA_LIBDIR=c:\lua5.1 LUA_LIB=c:\lua5.1\lua5.1.lib T=firebird DRIVER_INCLUDE= DRIVER_LIBS=fbclient_ms.lib OBJS= src\luasql.obj src\ls_$T.obj .c.obj: cl /c /Fo$@ /O2 /I$(LUA_INC) /D_CRT_SECURE_NO_DEPRECATE $(DRIVER_INCLUDE) $< src\$T.dll: $(OBJS) link /dll /def:src\$T.def /out:$@ $(OBJS) $(DRIVER_LIBS) $(LUA_LIB) install: IF NOT EXIST $(LUA_LIBDIR)\luasql mkdir $(LUA_LIBDIR)\luasql copy src\$T.dll $(LUA_LIBDIR)\luasql clean: del src\$T.dll del src\$T.exp del src\$T.lib del $(OBJS) keplerproject-luasql-c527024/Makefile.win.mysql000066400000000000000000000013211175743000500215310ustar00rootroot00000000000000LUA_INC=c:\lua5.1\include LUA_DIR=c:\lua5.1\lua LUA_LIBDIR=c:\lua5.1 LUA_LIB=c:\lua5.1\lua5.1.lib T=mysql DRIVER_INCLUDE= /I"c:\Program Files\MySQL\MySQL Server 5.0\include" DRIVER_LIBS= "C:\Program Files\MySQL\MySQL Server 5.0\lib\opt\libmySQL.lib" "C:\Program Files\MySQL\MySQL Server 5.0\lib\opt\mysqlclient.lib" OBJS= src\luasql.obj src\ls_$T.obj .c.obj: cl /c /Fo$@ /O2 /I$(LUA_INC) /DWIN32 /D_CRT_SECURE_NO_DEPRECATE $(DRIVER_INCLUDE) $< src\$T.dll: $(OBJS) link /dll /def:src\$T.def /out:$@ $(OBJS) $(DRIVER_LIBS) $(LUA_LIB) install: IF NOT EXIST $(LUA_LIBDIR)\luasql mkdir $(LUA_LIBDIR)\luasql copy src\$T.dll $(LUA_LIBDIR)\luasql clean: del src\$T.dll del src\$T.exp del src\$T.lib del $(OBJS) keplerproject-luasql-c527024/Makefile.win.odbc000066400000000000000000000010341175743000500212740ustar00rootroot00000000000000LUA_INC=c:\lua5.1\include LUA_DIR=c:\lua5.1\lua LUA_LIBDIR=c:\lua5.1 LUA_LIB=c:\lua5.1\lua5.1.lib T=odbc DRIVER_INCLUDE= DRIVER_LIBS=odbc32.lib OBJS= src\luasql.obj src\ls_$T.obj .c.obj: cl /c /Fo$@ /O2 /I$(LUA_INC) /D_CRT_SECURE_NO_DEPRECATE $(DRIVER_INCLUDE) $< src\$T.dll: $(OBJS) link /dll /def:src\$T.def /out:$@ $(OBJS) $(DRIVER_LIBS) $(LUA_LIB) install: IF NOT EXIST $(LUA_LIBDIR)\luasql mkdir $(LUA_LIBDIR)\luasql copy src\$T.dll $(LUA_LIBDIR)\luasql clean: del src\$T.dll del src\$T.exp del src\$T.lib del $(OBJS) keplerproject-luasql-c527024/Makefile.win.sqlite3000066400000000000000000000011161175743000500217520ustar00rootroot00000000000000LUA_INC=c:\lua5.1\include LUA_DIR=c:\lua5.1\lua LUA_LIBDIR=c:\lua5.1 LUA_LIB=c:\lua5.1\lua5.1.lib T=sqlite3 DRIVER_INCLUDE= /I"c:\sqlite3" DRIVER_OBJ="c:\sqlite3\sqlite3.obj" OBJS= src\luasql.obj src\ls_$T.obj $(DRIVER_OBJ) .c.obj: cl /c /Fo$@ /O2 /MD /I$(LUA_INC) /DWIN32 /D_CRT_SECURE_NO_DEPRECATE $(DRIVER_INCLUDE) $< src\$T.dll: $(OBJS) link /dll /def:src\$T.def /out:$@ $(OBJS) $(LUA_LIB) install: IF NOT EXIST "$(LUA_LIBDIR)\luasql" mkdir "$(LUA_LIBDIR)\luasql" copy "src\$T.dll" "$(LUA_LIBDIR)\luasql" clean: del src\$T.dll del src\$T.exp del src\$T.lib del $(OBJS) keplerproject-luasql-c527024/README000066400000000000000000000014251175743000500170160ustar00rootroot00000000000000LuaSQL 2.1 http://www.keplerproject.org/luasql/ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to: * Connect to ODBC, ADO, Oracle, MySQL, SQLite and PostgreSQL databases; * Execute arbitrary SQL statements; * Retrieve results in a row-by-row cursor fashion. LuaSQL is free software and uses the same license as Lua 5.1. Source code for LuaSQL can be downloaded from the LuaForge page. If you are using LuaBinaries a Windows binary version of LuaSQL can be found at the same LuaForge page. LuaSQL 2.1.1 [29/Oct/2007] * Fixed a bug in the SQLite3 error handling (patch by David Burgess) * Fixed bug [#1834] for SQLite 3 (found by Savin Zlobec, patch by Marc Nijdam) * Fixed bug [#1770] for SQLite 3 (found by Enrico Tassi, patch by Marc Nijdam)keplerproject-luasql-c527024/config000066400000000000000000000035051175743000500173270ustar00rootroot00000000000000# $Id: config,v 1.10 2008/05/30 17:21:18 tomas Exp $ # Driver (leave uncommented ONLY the line with the name of the driver) T= mysql #T= oci8 #T= odbc #T= postgres #T= sqlite #T=sqlite3 #T=firebird # Installation directories # Default prefix PREFIX = /usr/local # System's libraries directory (where binary libraries are installed) LUA_LIBDIR= $(PREFIX)/lib/lua/5.1 # System's lua directory (where Lua libraries are installed) LUA_DIR= $(PREFIX)/share/lua/5.1 # Lua includes directory LUA_INC= $(PREFIX)/include # Lua version number (first and second digits of target version) LUA_VERSION_NUM= 501 # OS dependent LIB_OPTION= -shared #for Linux #LIB_OPTION= -bundle -undefined dynamic_lookup #for MacOS X LIBNAME= $T.so # Compilation parameters # Driver specific ######## MySQL #DRIVER_LIBS= -L/usr/local/mysql/lib -lmysqlclient -lz #DRIVER_INCS= -I/usr/local/mysql/include DRIVER_LIBS= -L/usr/lib -lmysqlclient -lz DRIVER_INCS= -I/usr/include/mysql ######## Oracle OCI8 #DRIVER_LIBS= -L/home/oracle/OraHome1/lib -lz -lclntsh #DRIVER_INCS= -I/home/oracle/OraHome1/rdbms/demo -I/home/oracle/OraHome1/rdbms/public ######## PostgreSQL #DRIVER_LIBS= -L/usr/local/pgsql/lib -lpq #DRIVER_INCS= -I/usr/local/pgsql/include/ #DRIVER_LIBS= -L/usr/lib -lpq #DRIVER_INCS= -I/usr/include/postgresql ######## SQLite #DRIVER_LIBS= -lsqlite #DRIVER_INCS= ######## SQLite3 #DRIVER_LIBS= -L/opt/local/lib -lsqlite3 #DRIVER_INCS= -I/opt/local/include ######## ODBC #DRIVER_LIBS= -L/usr/local/lib -lodbc #DRIVER_INCS= -DUNIXODBC -I/usr/local/include ######## Firebird #DRIVER_LIBS= -L/usr/local/firebird -lfbclient #DRIVER_INCS= WARN= -Wall -Wmissing-prototypes -Wmissing-declarations -ansi -pedantic INCS= -I$(LUA_INC) CFLAGS= -O2 $(WARN) -fPIC $(DRIVER_INCS) $(INCS) -DLUASQL_VERSION_NUMBER='"$V"' $(DEFS) CC= gcc # $Id: config,v 1.10 2008/05/30 17:21:18 tomas Exp $ keplerproject-luasql-c527024/doc/000077500000000000000000000000001175743000500167015ustar00rootroot00000000000000keplerproject-luasql-c527024/doc/br/000077500000000000000000000000001175743000500173045ustar00rootroot00000000000000keplerproject-luasql-c527024/doc/br/examples.html000066400000000000000000000127051175743000500220150ustar00rootroot00000000000000 LuaSQL: Conectividade de banco de dados para a linguagem de programação Lua
LuaSQL
Conectividade de banco de dados para a linguagem de programação Lua

Exemplos

Abaixo, você verá um pequeno exemplo do código do uso básico da biblioteca. Em seguida, outro exemplo mostra como criar um iterador sobre o resultado de uma determinada consulta.

Uso básico

-- carregar o driver
require "luasql.postgres"
-- criar o objeto de ambiente
env = assert (luasql.postgres())
-- conectar a base de dados
con = assert (env:connect("luasql-test"))
-- retornar a tabela
res = con:execute"DROP TABLE people"
res = assert (con:execute[[
  CREATE TABLE people (
    name  varchar(50),
    email varchar(50)
  )
]])
-- adiciona alguns elementos
list = {
  { name="José das Couves", email="jose@couves.com", },
  { name="Manoel Joaquim", email="manoel.joaquim@cafundo.com", },
  { name="Maria das Dores", email="maria@dores.com", },
}
for i, p in pairs (list) do
  res = assert (con:execute(string.format([[
    INSERT INTO people
    VALUES ('%s', '%s')]], p.name, p.email)
  ))
end
-- obtem um cursor
cur = assert (con:execute"SELECT name, email from people")
-- imprime todos os registros, indexados pelos nomes de campos
row = cur:fetch ({}, "a")
while row do
  print(string.format("Nome: %s, E-mail: %s", row.name, row.email))
  -- reutiliza a tabela de resultados
  row = cur:fetch (row, "a")
end
-- fecha tudo
cur:close()
con:close()
env:close()

O resultado desse script será:

Nome: José das Couves, E-mail: jose@couves.com
Nome: Manoel Joaquim, E-mail: manoel.joaquim@cafundo.com
Nome: Maria das Dores, E-mail: maria@dores.com

Uso do iterador

Pode ser útil oferecer um iterador para cada registro do resultado:

function rows (connection, sql_statement)
  local cursor = assert (connection:execute (sql_statement))
  return function ()
    return cursor:fetch()
  end
end

Esse iterador é usado da seguinte forma:

require "luasql.mysql"
env = assert (luasql.mysql())
con = assert (env:connect"my_db")
for id, name, address in rows (con, "select * from contacts") do
  print (string.format ("%s: %s", name, address))
end

A implementação acima utiliza a coleta de lixo de Lua para fechar o cursor. Ela pode ser melhorada de modo a apresentar mensagens de erro mais adequadas (incluindo o statement SQL por exemplo) ou para fechar explicitamente o cursor (verificando se ainda existem mais linhas).

Valid XHTML 1.0!

$Id: examples.html,v 1.7 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/br/history.html000066400000000000000000000114361175743000500217000ustar00rootroot00000000000000 LuaSQL: Conectividade de banco de dados para a linguagem de programação Lua
LuaSQL
Conectividade de banco de dados para a linguagem de programação Lua

História

2.0.2 [26/06/2006]
Método numrows acrescentado ao driver MySQL.
Adicionado um arquivo config para o makefile.
Adicionada configuração do driver LinuxODBC.
Corrigiu um bug no driver SQLite (bug encontrado por Mike Petersen).
Corrigiu bugs nos drivers JDBC, OCI8 e ADO.
Testes melhorados.
Documentação melhorada.
2.0.1 [02/06/2005]
Corrigiu alguns erros relativos ao driver ODBC.
2.0.0 [22/03/2005]
Novo driver ADO e corrigiu alguns erros relativos ao driver ODBC.
2.0 beta 3 [23/12/2004]
Corrigiu apenas alguns pequenos erros.
2.0 beta 2 [26/11/2004]
Corrigiu alguns erros e introduziu os novos drivers SQLite and JDBC. Utiliza a proposta de pacotes para Lua 5.1. Veja mais detalhes em Instalação.
2.0 beta [10/12/2003]

A versão 2.0 apresenta algumas modificações no design e aprimoramentos na implementação em relação à versão 1.0:

  • Novo método de fetch: mais eficiente e mais flexível;
  • Novo método de setautocommit;
  • Compatível com Lua 5.0 e 5.1;
  • Carregável dinamicamente ou estaticamente;
  • Novos drivers para bancos de dados Oracle e MySQL.

 

 

 

Valid XHTML 1.0!

$Id: history.html,v 1.11 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/br/index.html000066400000000000000000000142331175743000500213040ustar00rootroot00000000000000 LuaSQL: Conectividade de banco de dados para a linguagem de programação Lua
LuaSQL
Conectividade de banco de dados para a linguagem de programação Lua

Visão Geral

LuaSQL é uma interface simples entre Lua e um sistema gerenciador de banco de dados (DBMS). Ela permite que um programa Lua:

  • Conecte-se aos bancos de dados ODBC, ADO, Oracle, MySQL, SQLite, JDBC e PostgreSQL;
  • Execute comandos arbritários do SQL;
  • Recupere resultados no modo linha-a-linha de um cursor SQL.

LuaSQL é um software livre e utiliza a mesma licença do Lua 5.0.

Status

A versão LuaSQL 2.0.2 (para Lua 5.0) está disponível para download.

O driver PostgreSQL foi testado em Windows, Linux e MacOS X e é compatível com PostgreSQL 7.x e 8.x.

O driver ODBC foi testado em Windows (drivers SQLServer e Microsoft Access).

O driver MySQL foi testado em Windows, Linux e é compatível com as versões 4.0, 4.1 e 5.0.

O driver Oracle foi testado em Windows e é compatível com OCI 8 API.

O driver SQLite foi testado em Windows e Linux e é compatível com as versões 2.x.

O driver JDBC foi testado em Windows com LuaJava 1.0 e JDK 1.4 (driver MySQL).

O driver ADO foi testado em Windows, com LuaCOM 1.3 (driver Microsoft Access).

Download

O download do código fonte do LuaSQL pode ser feito a partir da sua página no LuaForge. Para os usuários do LuaBinaries 5.0.2 Release 2 uma versão compilada dos drivers do LuaSQL pode ser encontrada na mesma página do LuaForge.

Créditos

LuaSQL 2.0

A Versão 2.0 foi redesenhada por Roberto Ierusalimschy, André Carregal e Tomás Guisasola como parte do Projeto Kepler. A implementação é compatível com Lua 5.0 e foi codificada por Tomás Guisasola, Eduardo Quintão, Thiago Ponte, Fabio Mascarenhas, Danilo Tuler, com inestimáveis contribuições de Michael Roth, Tiago Dionizio e Leonardo Godinho.

LuaSQL 1.0

LuaSQL foi projetado por Pedro Miller Rabinovitch e Roberto Ierusalimschy. A primeira implementação era compatível com Lua 4.0a. Muitas modificações foram feitas, mas não distribuídas, por Diego Nehab (ODBC), Carlos Cassino, Tomás Guisasola and Eduardo Quintão (PostgreSQL).

O desenvolvimento de LuaSQL foi patrocinado pela Fábrica Digital, FINEP e CNPq.

Contato

Para mais informações, entre em contato conosco. Comentários são muito bem-vindos!

A lista de discussão do projeto Kepler é outra forma de entrar em contato com desenvolvedores e usuários da plataforma Kepler.

Valid XHTML 1.0!

$Id: index.html,v 1.9 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/br/license.html000066400000000000000000000116151175743000500216200ustar00rootroot00000000000000 Licença LuaSQL
LuaSQL
Conectividade de banco de dados para a linguagem de programação Lua

License

LuaSQL is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like "copyleft" restrictions. LuaSQL qualifies as Open Source software. Its licenses are compatible with GPL. LuaSQL is not in the public domain and the Kepler Project keep its copyright. The legal details are below.

The spirit of the license is that you are free to use LuaSQL for any purpose at no cost without having to ask us. The only requirement is that if you do use LuaSQL, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.

The LuaSQL library is designed and implemented by the Kepler Project team. The implementation is not derived from licensed software.


Copyright © 2003-2006 The Kepler Project.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Valid XHTML 1.0!

$Id: license.html,v 1.6 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/br/luasql.png000066400000000000000000000170531175743000500213210ustar00rootroot00000000000000PNG  IHDRL\IDATxy\SWHB U@Ped*"ni;TߺQGGy:}>OOV۪:n-#([MC ,oGf($7Ʌg͹s~g?0 8K'_W0`a^ ¼y% 3T* :;;-9`<d22ẉlv{{-`ddKT:;;s\Չbf钙#T0 WTTt`[[[MMMLL̊+@=<|T*5//n߾}m0 +a,X}^XX8>>fI$BYg=7ߟqPrzԜdiiA011*8D"4s H L-}h4H$zÇKRq ;v1\47֮eKT4r (̿lmm}||=<>~ժUئs&=s@ `2666S涘msfRwb<;w."""))@ /_jT^^^uuΝ;5mBCIIIQQJ h``f[[[#b0/(( _jf"PS3RM/(*Ҳv_[n9::]V35$ C[<-00P;qwwrt:b9;;Ĺ,}@tppg0rh!sb![[R|b`>x`|||ddIgggmmؘGLLK@pvv555b8##w=2W/R4>30 .44TR544TVV B{{{[[G ̢jTJPu󁢢NKfQ@ς> 0iii XF0Vq83cUuu {˖- %88N_^^ؘf ۢ177777[[[D90719*L T%[Ymlhl6%chP(tD`miiYP jaOJJ661yqҮO{jknV!!He<ll3b O޿J$''GEE XZZŋ;::|>a``7^vV GFd/_:TJ&㣢X6BWW;xy/}Cs---׮]o~もD?~sB&BJzLU^^J*Zx}m^fɧXi]\\V\ @AA 9dkEI z0kk`Rυ.v,s%JrƍovUUեK.\E̼;7?kOߞ>]eY[ygۺ5\gu4WQQQ , ۉF**H5;)-Z̖-9XvqS_gsDea:2Q!50 o߾=--p4>.ߵǸ՘-vLċwb]O͉oW)P*7o|ٳT+++WVVsN}Tُuj7>,_oR_o゙bfݿK}8wvvjF$##c…:CBᇺH=t ֭Yj91س'y޴6^G5kG x(O R(JJvi..vcc=Q'kΩ_pb"M$###nruuEdV\.W*mݚk)u;;ÇBBF`\b|exNlwACC5]7^V=ͷ-E"능Kq-9ZBaCCbHa}]EER9]T.GEE0ynllǦMM~H?6m+HnES FHH h"///P3AFYJkpF^"rsbpuonx[۰/c"n,\ B0<00PZZH$#"".]jkk{رxoEZg//Z[4[weCgg3WȦp& KFFpYYYyyӧOe2ْ%Kuc >+W_$'sH$BM}844?S)$m*?DGGktWk?z)&3^FƆC.1&0P({._\_CJ''Ċ=YJ&S8P+WMid2YzH$9s ̛svзqB ں[_mNx0UgӨ|~x ٹY_,Rnl:h 3AϯY_/,\.vttbss_.W5G^jqBd455=z~$aRXة p2.@ d"+PNNyƄѓ'sB?؂h Xβzs_RleSƍFa%%] 4Zhp^9۷Moj5{w`33 TF,ŶmƩh9pv4!KJ3pkk̿@R}ݩF:TW/H$]2)) çOW Ą1XNNNKSol--"믙GGթmӟ 23D)PcpC܄J%o޼X󻲲 "==cv|Otڪkas߾{<ހ _pϱ@k+TύP|7l9;p JIXP~r]eei!gBhu bDG#G"Qfgfg`oOPHcJPhG!0\ZZJ`_ɱcsCS "}CPq6>Ym5bNc2$R 0bŘ}C Hh扙 `gGӭH&5@+W454`4) "CXJ$/|/XHsɓl6mZʴ#pZ OL~ܹj̧d_*655N{:D >>>K@ 4 P&Xc@23#J- hֱc̶m7n@0290sW`̖|aiWaH?.(t|+|CP 8v_K..Vhbٞ=?1P 9qtC'~e bTJ fhqhk*b5G^ʷߖkW00 44v7?kx&>>>S=kA> t2 Yͭ{ Z dmjlciadNC t D6[PQ\PD9>@t#LX+KqzǼJh9::J$Dww{ k@y{33#Ξ]kԋ=0 Ó:Z@ppppp0+bݼvlq88t_bرc۷o׺gJ B i;L&;2"ӍU1AQP }̏dqq OGLL80633⣏auDjm[S7_{ҥ7wz==oE zкihhy 4Ο~ο8=&nee=.-œ#~W{/t oΜ޾ @c (62ҲGs A˗nx-&kQ[ÇKL,ͼɴ=8 =J%rb?V [PTfia骃8SOn$z][;q 6Ӡe߾#G~qf_=AL&;rHjj?J$kWf%)j&ygϮ9T?رL&E󕙾kKKtt:=}ftTed.Ih!@ 24;$a^2ip^^^4 /HsrP&p))eKDVܹfaIaYΝwͷmܱc|aTgK\]Ŭtz[; h4v|~777J0S˗/駟MNTTlrgx eo[` O?Օy{KK߿?f>!kA#ʶ"[eiid2\NIw̺OZe[Jŋx<~fQvQ+"2vvO>۳g.!vZOOϖ-[LSmyh&.=qb.^wc)@V߼yuӦM M|hhĉ'+&Mx=6;wb^Bzj\\'9t/]qF4>t"rsϟt :4 "޼yoS0 컠,[o;)P({9/sQ0 Tի 2D˗/$''cJni[N877{6hтHGv AVGDl D"LJhtT&JRS4L&064innuܴiz D,h>APaaaii)]r%j.a.**j4ZZZ***֭[yT*{zzbcc-[6{,NӘ.HVWVVۯYbGMa\P2p%K?wUÇw؁` šD⺺:&5 pw񚚚&yIFFF``%-˗=prr rB1\.'sLe^?}3afJGͥg2/{}}},=x<"g-V#LÇCCCQԔ p5AbX,h4.CV{zzΓȼHN|}}}}}ry___4=gϊD""H xݻY$8qkkk6MKFu+1[arJRTڦRD"gVZ9rb&`a^ ?nw LuaSQL: Conectividade de banco de dados para a linguagem de programação Lua
LuaSQL
Conectividade de banco de dados para a linguagem de programação Lua

Introdução

LuaSQL é uma interface simples entre Lua e diversos sistemas gerenciadores de bancos de dados (DBMS) populares (atualmente PostgreSQL, ODBC, JDBC, MySQL, SQLite, Oracle e ADO; Interbase e Sybase estão nos nossos planos). LuaSQL define uma API orientada a objetos. Todos os drivers devem implementar essa API comum, mas cada um é livre para oferecer extensões.

LuaSQL define uma única variável global: uma tabela chamada luasql. Essa tabela é usada para armazenar os métodos de inicialização dos drivers instalados. Esses métodos são usados para criar um ambiente, o qual é usado para criar uma conexão. A conexão pode executar comandos SQL e, eventualmente, criar um cursor, utilizado para recuperar dados.

LuaSQL é um software livre e usa a mesma licença do Lua 5.0.

Compilando

LuaSQL é distribuído como um conjunto de arquivos fonte C – um arquivo fonte e um arquivo cabeçalho comuns a todos os drivers (luasql.h e luasql.c) – e um arquivo fonte para cada driver. Cada driver deve ser compilado juntamente com o arquivo luasql.c para gerar uma biblioteca. Essa biblioteca pode ser linkada à aplicação ou carregada dinamicamente. A função de inicialização é luaopen_luasqlnomedriver e é compatível com o formato open-library de Lua.

Instalação

Todos os drivers LuaSQL seguem a proposta de pacotes para Lua 5.1. Logo, esse pacote deve ser "instalado". Consulte a seção de configuração do Compat-5.1 para saber como instalar os pacotes binários da maneira correta. As bibliotecas compiladas devem ser instaladas em um diretório chamado luasql no seu LUA_CPATH.

Usuários Windows podem utilizar os pacotes compilados do LuaSQL disponíveis na página do LuaForge

Para usar LuaSQL com o JDBC, certifique-se que:

  • Lua está rodando com LuaJava
  • O jar do LuaSQL está na classpath da máquina virtual do Java
  • O driver JDBC do banco de dados desejado também está na classpath da máquina virtual

Para usar LuaSQL com ADO, certifique-se que Lua está rodando com LuaCOM 1.3

Tratamento de erros

LuaSQL é apenas uma camada abstrata de comunicação entre Lua e um sistema de banco de dados. Portanto, erros podem ocorrem em ambos os níveis: no cliente do banco de dados ou no driver LuaSQL.

Erros como comandos SQL mal formados, nomes de tabela desconhecidos etc., chamados erros de banco de dados, serão reportados pelo retorno de nil pela função/método, seguido de uma mensagem de erro enviada pelo sistema de banco de dados. Erros como parâmetros inválidos, ausência de conexão, objetos inválidos etc., chamados erros de API, são usualmente erros de programação e geram erros Lua.

Esse comportamento vale para todas as funções/métodos descritos neste documento, a menos que seja especificado de outra forma.

Drivers

Um driver LuaSQL permite o uso da API LuaSQL com um determinado banco de dados. Para usar um driver, este deve ser carregado na tabela luasql. O exemplo abaixo

require "luasql.odbc"

carrega o driver ODBC na tabela luasql. Note que pode-se ter mais de um driver carregado usando-se algo como:

require "luasql.odbc"
require "luasql.oci8"

Este exemplo também mostra que o nome do driver nem sempre corresponde ao nome do banco de dados, mas sim ao nome do driver no sistema de arquivos. Dado que o driver Oracle se refere à API OCI8, ele recebe o nome de oci8 ao invés de oracle.

Alguns drivers, tais como o MySQL, tem bibliotecas para versões diferentes do banco de dados MySQL mas utilizam o mesmo nome de arquivo (mysql). Neste caso não é possível carregar mais de uma versão do driver MySQL na tabela luasql.

Ambiente

Um ambiente é criado chamando a função de inicialização do driver que está armazenada na tabela luasql com o mesmo nome do driver (odbc, postgres etc). Por exemplo,

env = luasql.odbc()

tentará criar um ambiente usando o driver ODBC. A única exceção é o driver JDBC, que precisa saber que driver interno utilizar. Logo, quando se cria um ambiente, deve-se passar o nome da classe do driver como primeiro parâmetro para a função luasql.jdbc. Por exemplo:

env = luasql.jdbc ("com.mysql.jdbc.Driver")

Métodos

env:close()
Fecha o ambiente env. Só é bem sucedido se todas as suas conexões já tiverem sido fechadas anteriormente.
Retorna: true, em caso de sucesso; false, quando o ambiente já estiver fechado.
env:connect(sourcename[,username[,password]])
Conecta à fonte de dados especificada em sourcename usando username e password se eles são fornecidos.
O sourcename pode variar de acordo com cada driver. Alguns usam simplesmente o nome do banco de dados, como PostgreSQL, MySQL e SQLite; o driver ODBC recebe o nome de DSN; o driver Oracle recebe o nome do serviço; e o driver JDBC recebe um comando como "jdbc:<database system>://<database name>", o qual é específico para cada driver.
Veja também: PostgreSQL e MySQL.
Retorna: uma conexão.

Conexão

Uma conexão contém atributos e parâmetros específicos de uma única conexão de base de dados. Uma conexão é criada chamando o método environment:connect.

Métodos

conn:close()
Fecha a conexão conn. Só é bem sucedido se todos os seus cursores tiverem sido fechados anteriormente e se a conexão ainda estiver aberta.
Retorna: true, em caso de sucesso; false em caso de fracasso.
conn:commit()
Efetua a transação corrente. Esse atributo pode não funcionar em sistemas de banco de dados que não implementam transações.
Retorna: true, em caso de sucesso; false, quando a operação não pode ser realizada ou não está implementada.
conn:execute(statement)
Executa o statement SQL dado.
Retorna: o cursor, se houver resultados, ou o número de registros alterados pelo comando.
conn:rollback()
Desfaz a transação corrente. Esse atributo pode não funcionar em sistemas de banco de dados que não implementam transações.
Retorna: true, em caso de sucesso; false, quando a operação não pode ser realizada ou não está implementada.
conn:setautocommit(boolean)
Ativa ou desativa o modo "auto commit". Esse atributo pode não funcionar em sistemas de banco de dados que não implementam transações. Em sistemas de banco de dados que não trabalham com o conceito de "modo auto commit", mas que implementam transações, esse mecanismo é implementado pelo driver.
Retorna: true, em caso de sucesso; false, quando a operação não pode ser realizada ou não está implementada.

Cursores

Um cursor contém métodos para recuperar dados resultantes de um comando executado. Um cursor é criado por meio de uma função connection:execute. Veja também: PostgreSQL e Oracle.

Métodos

cur:close()
Fecha esse cursor.
Retorna: true, em caso de sucesso; false, quando o cursor já está fechado.
cur:fetch([table[,modestring]])
Recupera o próximo registro do resultado.
Se fetch é chamado sem parâmetros, os resultados consistem em uma lista de valores. Se fetch é chamado com uma tabela, os resultados são copiados para a tabela e a tabela é retornada. Neste caso, pode ser usado um parâmetro opcional de modo (modestring): uma seqüência de caracteres indicando como deve ser construída a tabela de resultados. A seqüência de caracteres do modo pode conter:
"n"
a tabela resultante terá índices numéricos (padrão)
"a"
a tabela resultante terá índices alfanuméricos

Os índices numéricos representam as posições dos campos no comando SELECT; os índices alfanuméricos representam os nomes dos campos.
A tabela opcional (table) será usada para armazenar o próximo registro. Isso permite o uso de uma única tabela para várias chamadas, o que pode melhorar o desempenho geral.
Não existe garantia sobre os tipos dos resultados: eles podem ou não ser convertidos pelo driver para os tipos Lua adequados. Na implementação atual, os drivers PostgreSQL e MySQL retornam todos os valores como strings, enquanto os drivers ODBC e Oracle convertem esses valores em tipos Lua.
Retorna: dados, como descrito acima, ou nil se não existem mais registros. Note que esse método pode retornar nil como um resultado válido.
cur:getcolnames()
Retorna: uma tabela com os nomes das colunas.
cur:getcoltypes()
Retorna: uma tabela com os tipos das colunas.

PostgreSQL

Além das funcionalidades básicas oferecidas por todos os drivers, o driver Postgres oferece as seguintes funcionalidades adicionais:

env:connect(sourcename[,username[,password[,hostname[,port]]]])
No driver PostgreSQL este método tem mais dois parâmetros opcionais que indicam o hostname e a port a serem utilizados na conexão. Além disso, o primeiro parâmetro também pode conter todas as informações de conexão, como é dito na documentação para a função PQconnectdb no manual do PostgreSQL (ex. environment:connect("dbname=<name> user=<username>"))
Veja também: ambiente
Retorna: uma conexão
cur:numrows()
Veja também: cursores
Retorna: o número de registros no resultado da busca.

MySQL

Além das funcionalidades básicas oferecidas por todos os drivers, o driver MySQL ainda oferece as seguintes funcionalidades adicionais:

env:connect(sourcename[,username[,password[,hostname[,port]]]])
No driver MySQL, esse método tem mais dois parâmetros opcionais que indicam o hostname e a port a serem utilizados na conexão. Veja também: ambiente
Retorna: uma conexão
cur:numrows()
Veja também: cursores
Retorna: o número de registros no resultado da busca.

Nota: Este driver é compatível com as versões 4.0, 4.1 e 5.0 da API MySQL. Apenas as versões a partir de 4.1 oferecem suporte para transações, através de tabelas BDB ou INNODB. Com a versão 4.0 ou sem um desses tipos de tabelas, os métodos commit, rollback e setautocommit não funcionam.

Oracle

Além das funcionalidades básicas oferecidas por todos os drivers, o driver Oracle ainda oferece uma funcionalidade adicional:

cur:numrows()
Veja também: cursores
Retorna: o número de registros no resultado da pesquisa.

SQLite3

Além das funcionalidades básicas oferecidas por todos os drivers, o driver para SQLite3 ainda oferece uma funcionalidade adicional:

env:connect(sourcename[,locktimeout])
No driver para SQLite3, este método tem mais um parâmetro opcional que indica a quantidade de milissegundos para esperar por uma trava de escrita no banco de dados, se ela não for obtida de imediato.
Veja também: ambiente
Retorna: uma conexão

Valid XHTML 1.0!

$Id: manual.html,v 1.11 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/us/000077500000000000000000000000001175743000500173305ustar00rootroot00000000000000keplerproject-luasql-c527024/doc/us/examples.html000066400000000000000000000122261175743000500220370ustar00rootroot00000000000000 LuaSQL: Database connectivity for the Lua programming language
LuaSQL
Database connectivity for the Lua programming language

Examples

Here is an example of the basic use of the library. After that, another example shows how to create an iterator over the result of a SELECT query.

Basic use

-- load driver
local driver = require "luasql.postgres"
-- create environment object
env = assert (driver.postgres())
-- connect to data source
con = assert (env:connect("luasql-test"))
-- reset our table
res = con:execute"DROP TABLE people"
res = assert (con:execute[[
  CREATE TABLE people(
    name  varchar(50),
    email varchar(50)
  )
]])
-- add a few elements
list = {
  { name="Jose das Couves", email="jose@couves.com", },
  { name="Manoel Joaquim", email="manoel.joaquim@cafundo.com", },
  { name="Maria das Dores", email="maria@dores.com", },
}
for i, p in pairs (list) do
  res = assert (con:execute(string.format([[
    INSERT INTO people
    VALUES ('%s', '%s')]], p.name, p.email)
  ))
end
-- retrieve a cursor
cur = assert (con:execute"SELECT name, email from people")
-- print all rows, the rows will be indexed by field names
row = cur:fetch ({}, "a")
while row do
  print(string.format("Name: %s, E-mail: %s", row.name, row.email))
  -- reusing the table of results
  row = cur:fetch (row, "a")
end
-- close everything
cur:close() -- already closed because all the result set was consumed
con:close()
env:close()

And the output of this script should be:

Name: Jose das Couves, E-mail: jose@couves.com
Name: Manoel Joaquim, E-mail: manoel.joaquim@cafundo.com
Name: Maria das Dores, E-mail: maria@dores.com

Iterator

It may be useful to offer an iterator for the resulting rows:

function rows (connection, sql_statement)
  local cursor = assert (connection:execute (sql_statement))
  return function ()
    return cursor:fetch()
  end
end

Here is how the iterator is used:

env = assert (require"luasql.mysql".mysql())
con = assert (env:connect"my_db")
for id, name, address in rows (con, "select * from contacts") do
  print (string.format ("%s: %s", name, address))
end

Obviously, the code above only works if there is a table called contacts with the columns id, name and address in this order. At the end of the loop the cursor will be automatically closed by the driver.

Valid XHTML 1.0!

$Id: examples.html,v 1.16 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/us/history.html000066400000000000000000000167141175743000500217300ustar00rootroot00000000000000 LuaSQL: Database connectivity for the Lua programming language
LuaSQL
Database connectivity for the Lua programming language

History

LuaSQL 2.3.0 [23/May/2012]
  • Added support to compile the drivers for all Lua 5.X versions (only Postgres, MySQL and SQLite were tested by the time of the launch)
  • Correction on MySQL implementation to honor the close of the cursor when the last row is returned
  • Drivers:
    • Postgres: tested with versions 8.4 and 9.1
    • MySQL: tested with version 5.1
    • SQLite3: tested with version 3.6
    • Firebird: compiled but not tested
    • SQLite: adapted but not compiled
    • ODBC: adapted but not compiled
    • Oracle/OCI8: adapted but not compiled
    • ADO: nothing changed
    • JDBC: nothing changed
LuaSQL 2.2.0 [??/??/200?]
  • Added Firebird driver
  • Added LuaRocks specifications
  • escape method added to some drivers
  • getlastautoid method added to MySQL driver
  • fetch method now closes the cursor when there is no more rows to retrieve
  • Uniformization of method's return values on all drivers
LuaSQL 2.1.1 [29/Oct/2007]
  • Fixed a bug in the SQLite3 error handling (patch by David Burgess)
  • Fixed bug [#1770] for SQLite 3 (found by Enrico Tassi, patch by Marc Nijdam)
  • Fixed bug [#1834] for SQLite 3 (found by Savin Zlobec, patch by Marc Nijdam)
LuaSQL 2.1.0 [29/Aug/2007]
  • Added support for SQLite 3
  • Bug correction: freeing PGresults in the Postgres driver (thanks to Michael Broughton)
  • Corrected memory leak when no cursor created (thanks to Klaus Ripke)
  • Corrected bug avoiding duplicate access to stack
LuaSQL 2.0.2 [26/Jun/2006]
  • numrows method added to MySQL driver.
  • Added a config for the makefile.
  • Added configuration for the UnixODBC driver.
  • Bug fixes to the SQLite driver (bug found by Mike Petersen).
  • Bug fixes to the JDBC, OCI8 and ADO drivers.
  • Improved tests.
  • Updated documentation.
LuaSQL 2.0.1 [02/Jun/2005]
  • Bug fixes to the ODBC driver.
LuaSQL 2.0.0 [22/Mar/2005]
  • Added ADO driver and some bug fixes to the ODBC driver.
LuaSQL 2.0 Beta 3 [23/Dec/2004]
  • Minor bug fixes.
LuaSQL 2.0 Beta 2 [26/Nov/2004]
  • Bug fixes
  • New SQLite and JDBC drivers
  • LuaSQL now follows the package model for Lua 5.1 (see Installation section for more details).
LuaSQL 2.0 Beta [10/Nov/2003]

Changes from previous versions

Version 2.x has some design changes and implementation improvements compared to version 1.0:

  • New fetch method: more eficient and more flexible
  • New setautocommit method
  • Lua 5.0 and 5.1 compatible
  • Dynamically loadable or statically linked
  • New drivers for Oracle and MySQL databases

 

 

 

Valid XHTML 1.0!

$Id: history.html,v 1.20 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/us/index.html000066400000000000000000000125041175743000500213270ustar00rootroot00000000000000 LuaSQL: Database connectivity for the Lua programming language
LuaSQL
Database connectivity for the Lua programming language

Overview

LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to:

  • Connect to ODBC, ADO, Oracle, MySQL, SQLite, Firebird and PostgreSQL databases;
  • Execute arbitrary SQL statements;
  • Retrieve results in a row-by-row cursor fashion.

LuaSQL is free software and uses the same license as Lua 5.1.

Status

LuaSQL version 2.3.0 (for Lua 5.X) is now available for download. For more details on the features list please check the product history.

Download

Source code for LuaSQL can be downloaded from the LuaForge page. If you are using LuaBinaries a Windows binary version of LuaSQL can be found at the same LuaForge page.

Credits

LuaSQL 2.x

Version 2.2 started a distributed development, with all project discussions happenign through the Kepler's mailing list. New developers: Hisham Muhammad, Ignacio Burgueño, Luis Eduardo Jason Santos, Marc Nijdam, Mauricio Bomfim and Scott Morgan.

Version 2.1 and 2.0 were redesigned by Roberto Ierusalimschy, André Carregal and Tomás Guisasola as part of the Kepler Project. The implementation was coded by Tomás Guisasola, Eduardo Quintão, Thiago Ponte, Fabio Mascarenhas and Danilo Tuler, with many contributions from Michael Broughton, Tiago Dionizio, Leonardo Godinho, Pedro Maia, Klaus Ripke, Michael Roth and others.

LuaSQL 1.0

LuaSQL was originally designed by Pedro Miller Rabinovitch and Roberto Ierusalimschy. The first implementation was compatible with Lua 4.0a. Many modifications were made but not distributed by Diego Nehab (ODBC), Carlos Cassino, Tomás Guisasola and Eduardo Quintão (PostgreSQL).

LuaSQL development was sponsored by Fábrica Digital, FINEP and CNPq.

Contact us

For more information please contact us. Comments are welcome!

You can also reach other Kepler developers and users on the Kepler Project mailing list.

Valid XHTML 1.0!

$Id: index.html,v 1.27 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/us/license.html000066400000000000000000000114171175743000500216440ustar00rootroot00000000000000 LuaSQL License
LuaSQL
Database connectivity for the Lua programming language

License

LuaSQL is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like "copyleft" restrictions. LuaSQL qualifies as Open Source software. Its licenses are compatible with GPL. LuaSQL is not in the public domain and the Kepler Project keep its copyright. The legal details are below.

The spirit of the license is that you are free to use LuaSQL for any purpose at no cost without having to ask us. The only requirement is that if you do use LuaSQL, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.

The LuaSQL library is designed and implemented by the Kepler Project team. The implementation is not derived from licensed software.


Copyright © 2003-2007 The Kepler Project.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Valid XHTML 1.0!

$Id: license.html,v 1.17 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/doc/us/luasql.png000066400000000000000000000170531175743000500213450ustar00rootroot00000000000000PNG  IHDRL\IDATxy\SWHB U@Ped*"ni;TߺQGGy:}>OOV۪:n-#([MC ,oGf($7Ʌg͹s~g?0 8K'_W0`a^ ¼y% 3T* :;;-9`<d22ẉlv{{-`ddKT:;;s\Չbf钙#T0 WTTt`[[[MMMLL̊+@=<|T*5//n߾}m0 +a,X}^XX8>>fI$BYg=7ߟqPrzԜdiiA011*8D"4s H L-}h4H$zÇKRq ;v1\47֮eKT4r (̿lmm}||=<>~ժUئs&=s@ `2666S涘msfRwb<;w."""))@ /_jT^^^uuΝ;5mBCIIIQQJ h``f[[[#b0/(( _jf"PS3RM/(*Ҳv_[n9::]V35$ C[<-00P;qwwrt:b9;;Ĺ,}@tppg0rh!sb![[R|b`>x`|||ddIgggmmؘGLLK@pvv555b8##w=2W/R4>30 .44TR544TVV B{{{[[G ̢jTJPu󁢢NKfQ@ς> 0iii XF0Vq83cUuu {˖- %88N_^^ؘf ۢ177777[[[D90719*L T%[Ymlhl6%chP(tD`miiYP jaOJJ661yqҮO{jknV!!He<ll3b O޿J$''GEE XZZŋ;::|>a``7^vV GFd/_:TJ&㣢X6BWW;xy/}Cs---׮]o~もD?~sB&BJzLU^^J*Zx}m^fɧXi]\\V\ @AA 9dkEI z0kk`Rυ.v,s%JrƍovUUեK.\E̼;7?kOߞ>]eY[ygۺ5\gu4WQQQ , ۉF**H5;)-Z̖-9XvqS_gsDea:2Q!50 o߾=--p4>.ߵǸ՘-vLċwb]O͉oW)P*7o|ٳT+++WVVsN}Tُuj7>,_oR_o゙bfݿK}8wvvjF$##c…:CBᇺH=t ֭Yj91س'y޴6^G5kG x(O R(JJvi..vcc=Q'kΩ_pb"M$###nruuEdV\.W*mݚk)u;;ÇBBF`\b|exNlwACC5]7^V=ͷ-E"능Kq-9ZBaCCbHa}]EER9]T.GEE0ynllǦMM~H?6m+HnES FHH h"///P3AFYJkpF^"rsbpuonx[۰/c"n,\ B0<00PZZH$#"".]jkk{رxoEZg//Z[4[weCgg3WȦp& KFFpYYYyyӧOe2ْ%Kuc >+W_$'sH$BM}844?S)$m*?DGGktWk?z)&3^FƆC.1&0P({._\_CJ''Ċ=YJ&S8P+WMid2YzH$9s ̛svзqB ں[_mNx0UgӨ|~x ٹY_,Rnl:h 3AϯY_/,\.vttbss_.W5G^jqBd455=z~$aRXة p2.@ d"+PNNyƄѓ'sB?؂h Xβzs_RleSƍFa%%] 4Zhp^9۷Moj5{w`33 TF,ŶmƩh9pv4!KJ3pkk̿@R}ݩF:TW/H$]2)) çOW Ą1XNNNKSol--"믙GGթmӟ 23D)PcpC܄J%o޼X󻲲 "==cv|Otڪkas߾{<ހ _pϱ@k+TύP|7l9;p JIXP~r]eei!gBhu bDG#G"Qfgfg`oOPHcJPhG!0\ZZJ`_ɱcsCS "}CPq6>Ym5bNc2$R 0bŘ}C Hh扙 `gGӭH&5@+W454`4) "CXJ$/|/XHsɓl6mZʴ#pZ OL~ܹj̧d_*655N{:D >>>K@ 4 P&Xc@23#J- hֱc̶m7n@0290sW`̖|aiWaH?.(t|+|CP 8v_K..Vhbٞ=?1P 9qtC'~e bTJ fhqhk*b5G^ʷߖkW00 44v7?kx&>>>S=kA> t2 Yͭ{ Z dmjlciadNC t D6[PQ\PD9>@t#LX+KqzǼJh9::J$Dww{ k@y{33#Ξ]kԋ=0 Ó:Z@ppppp0+bݼvlq88t_bرc۷o׺gJ B i;L&;2"ӍU1AQP }̏dqq OGLL80633⣏auDjm[S7_{ҥ7wz==oE zкihhy 4Ο~ο8=&nee=.-œ#~W{/t oΜ޾ @c (62ҲGs A˗nx-&kQ[ÇKL,ͼɴ=8 =J%rb?V [PTfia骃8SOn$z][;q 6Ӡe߾#G~qf_=AL&;rHjj?J$kWf%)j&ygϮ9T?رL&E󕙾kKKtt:=}ftTed.Ih!@ 24;$a^2ip^^^4 /HsrP&p))eKDVܹfaIaYΝwͷmܱc|aTgK\]Ŭtz[; h4v|~777J0S˗/駟MNTTlrgx eo[` O?Օy{KK߿?f>!kA#ʶ"[eiid2\NIw̺OZe[Jŋx<~fQvQ+"2vvO>۳g.!vZOOϖ-[LSmyh&.=qb.^wc)@V߼yuӦM M|hhĉ'+&Mx=6;wb^Bzj\\'9t/]qF4>t"rsϟt :4 "޼yoS0 컠,[o;)P({9/sQ0 Tի 2D˗/$''cJni[N877{6hтHGv AVGDl D"LJhtT&JRS4L&064innuܴiz D,h>APaaaii)]r%j.a.**j4ZZZ***֭[yT*{zzbcc-[6{,NӘ.HVWVVۯYbGMa\P2p%K?wUÇw؁` šD⺺:&5 pw񚚚&yIFFF``%-˗=prr rB1\.'sLe^?}3afJGͥg2/{}}},=x<"g-V#LÇCCCQԔ p5AbX,h4.CV{zzΓȼHN|}}}}}ry___4=gϊD""H xݻY$8qkkk6MKFu+1[arJRTڦRD"gVZ9rb&`a^ ?nw LuaSQL: Database connectivity for the Lua programming language
LuaSQL
Database connectivity for the Lua programming language

Introduction

LuaSQL is a simple interface from Lua to a number of database management systems. It includes a set of drivers to some popular databases (currently PostgreSQL, ODBC, MySQL, SQLite, Oracle, and ADO; Interbase and Sybase are in our plans). LuaSQL defines a simple object-oriented API. All drivers should implement this common API, but each one is free to offer extensions.

LuaSQL defines one single global variable, a table called luasql. This table is used to store the initialization methods of the loaded drivers. These methods are used to create an environment object which is used to create a connection object. A connection object can execute SQL statements and eventually create a cursor object which is used to retrieve data.

LuaSQL is free software and uses the same license as Lua 5.1.

Compiling

LuaSQL is distributed as a set of C source files: a pair of common source and header files (luasql.h and luasql.c); and one source file for each driver. Each driver should be compiled with the luasql.c file to generate a library. This library can be linked to the application or dynamically loaded. The initialization function is luaopen_luasqldrivername and it is a Lua open-library compatible function.

Installation

All LuaSQL drivers follow the package model for Lua 5.1 and therefore should be "installed" in your package.cpath.

Windows users can use the compiled versions of LuaSQL available at LuaForge

In order to use LuaSQL with ADO, make sure that you have LuaCOM 1.3 for Lua 5.1 installed.

Error handling

LuaSQL is just an abstraction layer that communicates between Lua and a database system. Therefore errors can occur on both levels, that is, inside the database client or inside LuaSQL driver.

Errors such as malformed SQL statements, unknown table names etc. are called database errors and will be reported by the function/method returning nil followed by the error message provided by the database system. Errors such as wrong parameters, absent connection, invalid objects etc., called API errors, are usually program errors and so will raise a Lua error.

This behavior will be followed by all functions/methods described in this document unless otherwise stated.

Drivers

A LuaSQL driver allows the use of the LuaSQL API with a database management system that corresponds to the driver. To use a driver you have to load it. The example below

local driver = require "luasql.odbc"

loads the ODBC driver and returns a table with an entry with the name of the driver (odbc in this case). Note that you can have more than one driver loaded at the same time doing something like:

local odbc_driver = require "luasql.odbc"
local oci8_driver = require "luasql.oci8"

This example also shows that the driver name not always correspond to the Database name, but to the driver name in the file system. Since it refers to the OCI8 API, the Oracle driver has the name oci8.

Environment Objects

An environment object is created by calling the driver's initialization function that is stored in the table returned when it was loaded, indexed with the same name as the driver (odbc, postgres etc). The following example, will try to create an environment object using the ODBC driver.

local driver = require"luasql.odbc"
local env = driver.odbc()

Methods

env:close()
Closes the environment env. Only successful if all connections pertaining to it were closed first.
Returns: true in case of success; false when the object is already closed.
env:connect(sourcename[,username[,password]])
Connects to a data source specified in sourcename using username and password if they are supplied.
The sourcename may vary according to each driver. Some use a simple database name, like PostgreSQL, MySQL and SQLite; the ODBC driver expects the name of the DSN; the Oracle driver expects the service name; See also: PostgreSQL, and MySQL extensions.
Returns: a connection object.

Connection Objects

A connection object contains specific attributes and parameters of a single data source connection. A connection object is created by calling the environment:connect method.

Methods

conn:close()
Closes the connection conn. Only successful if all cursors pertaining to it have been closed and the connection is still open.
Returns: true in case of success and false in case of failure.
conn:commit()
Commits the current transaction. This feature might not work on database systems that do not implement transactions.
Returns: true in case of success and false when the operation could not be performed or when it is not implemented.
conn:execute(statement)
Executes the given SQL statement.
Returns: a cursor object if there are results, or the number of rows affected by the command otherwise.
conn:rollback()
Rolls back the current transaction. This feature might not work on database systems that do not implement transactions.
Returns: true in case of success and false when the operation could not be performed or when it is not implemented.
conn:setautocommit(boolean)
Turns on or off the "auto commit" mode. This feature might not work on database systems that do not implement transactions. On database systems that do not have the concept of "auto commit mode", but do implement transactions, this mechanism is implemented by the driver.
Returns: true in case of success and false when the operation could not be performed or when it is not implemented.

Cursor Objects

A cursor object contains methods to retrieve data resulting from an executed statement. A cursor object is created by using the connection:execute function. See also PostgreSQL and Oracle extensions.

Methods

cur:close()
Closes this cursor.
Returns: true in case of success and false when the object is already closed.
cur:fetch([table[,modestring]])
Retrieves the next row of results.
If fetch is called without parameters, the results will be returned directly to the caller. If fetch is called with a table, the results will be copied into the table and the changed table will be returned. In this case, an optional modestring parameter can be used. It is just a string indicating how the resulting table should be constructed. The mode string can contain:
"n"
the resulting table will have numerical indices (default)
"a"
the resulting table will have alphanumerical indices

The numerical indices are the positions of the fields in the SELECT statement; the alphanumerical indices are the names of the fields.
The optional table parameter is a table that should be used to store the next row. This allows the use of a unique table for many fetches, which can improve the overall performance.
A call to fetch after the last row has already being returned will close the corresponding cursor. There is no guarantee about the types of the results: they may or may not be converted to adequate Lua types by the driver. In the current implementation, the PostgreSQL and MySQL drivers return all values as strings while the ODBC and Oracle drivers convert them to Lua types.
Returns: data, as above, or nil if there are no more rows. Note that this method could return nil as a valid result.
cur:getcolnames()
Returns: a list (table) of column names.
cur:getcoltypes()
Returns: a list (table) of column types.

PostgreSQL Extensions

Besides the basic functionality provided by all drivers, the Postgres driver also offers these extra features:

env:connect(sourcename[,username[,password[,hostname[,port]]]])
In the PostgreSQL driver, this method adds two optional parameters that indicate the hostname and port to connect. Also, the first parameter can contain all connection information, as stated in the documentation for PQconnectdb function in the PostgreSQL manual (e.g. environment:connect("dbname=<name> user=<username>"))
See also: environment objects
Returns: a connection object
conn:escape(str)
Escape especial characters in the given string according to the connection's character set.
See also: Official documentation of function PQescapeStringConn
Returns: the escaped string.
cur:numrows()
See also: cursor objects
Returns: the number of rows in the query result.

MySQL Extensions

Besides the basic functionality provided by all drivers, the MySQL driver also offers these extra features:

env:connect(sourcename[,username[,password[,hostname[,port]]]])
In the MySQL driver, this method adds two optional parameters that indicate the hostname and port to connect.
See also: environment objects
Returns: a connection object
conn:escape(str)
Escape especial characters in the given string according to the connection's character set.
See also: Official documentation of function mysql_real_escape_string
Returns: the escaped string.
conn:getlastautoid()
Obtains the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement.
See also: Official documentation of function mysql_insert_id for versions 4.0, 5.1 and 6.0
Returns: the number of the last value generated for an AUTO_INCREMENT column.
cur:numrows()
See also: cursor objects
Returns: the number of rows in the query result.

Notes:

This driver is compatible with versions 4.0, 4.1 and 5.0 of the MySQL API. Only from version 4.1 MySQL provides support for transactions by using BDB or INNODB tables. Therefore, with version 4.0 or without one of these types of tables, the methods commit, rollback and setautocommit will not work.

If you are using LuaSQL 2.0, cur:numrows() is available only in version 2.0.2 or later.

Oracle Extensions

Besides the basic functionality provided by all drivers, the Oracle driver also offers this extra feature:

cur:numrows()
See also: cursor objects
Returns: the number of rows in the query result.

SQLite3 Extensions

Besides the basic functionality provided by all drivers, the SQLite3 driver also offers this extra feature:

env:connect(sourcename[,locktimeout])
In the SQLite3 driver, this method adds an optional parameter that indicate the amount of milisseconds to wait for a write lock if one cannot be obtained immediately.
See also: environment objects
Returns: a connection object
conn:escape(str)
Escape especial characters in the given string according to the connection's character set.
See also: Official documentation of function sqlite3_mprintf
Returns: the escaped string.

Valid XHTML 1.0!

$Id: manual.html,v 1.28 2008/06/11 00:26:13 jasonsantos Exp $

keplerproject-luasql-c527024/rockspec/000077500000000000000000000000001175743000500177455ustar00rootroot00000000000000keplerproject-luasql-c527024/rockspec/luasql-mysql-2.2.0rc1-1.rockspec000066400000000000000000000016731175743000500253540ustar00rootroot00000000000000package = "LuaSQL-MySQL" version = "2.2.0rc1-1" source = { url = "http://luasql.luaforge.net/luasql-2.2.0rc1.tar.gz", } description = { summary = "Database connectivity for Lua (MySQL driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { MYSQL = { header = "mysql/mysql.h" } } build = { type = "make", variables = { T="mysql", LIB_OPTION = "$(LIBFLAG) -L$(MYSQL_LIBDIR) -lmysqlclient -lz -lcrypt -lnsl -lm", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR) -I$(MYSQL_INCDIR)/mysql" }, build_variables = { DRIVER_LIBS="", }, install_variables = { LUA_LIBDIR = "$(LIBDIR)", } } keplerproject-luasql-c527024/rockspec/luasql-mysql-2.2.0rc1-2.rockspec000066400000000000000000000022061175743000500253460ustar00rootroot00000000000000package = "LuaSQL-MySQL" version = "2.2.0rc1-2" source = { url = "http://luasql.luaforge.net/luasql-2.2.0rc1.tar.gz", } description = { summary = "Database connectivity for Lua (MySQL driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { MYSQL = { header = "mysql/mysql.h" }, OPENSSL = { header = "openssl/crypto.h" }, ZLIB = { header = "zlib.h" } } build = { type = "make", variables = { T="mysql", LIB_OPTION = "$(LIBFLAG) -L$(MYSQL_LIBDIR) -L$(MYSQL_LIBDIR)/mysql -lmysqlclient -L$(ZLIB_LIBDIR) -lz -L$(OPENSSL_LIBDIR) -lcrypt -lnsl -lm", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR) -I$(MYSQL_INCDIR)/mysql -I$(OPENSSL_INCDIR)/openssl -I$(ZLIB_INCDIR)" }, build_variables = { DRIVER_LIBS="", }, install_variables = { LUA_LIBDIR = "$(LIBDIR)", } } keplerproject-luasql-c527024/rockspec/luasql-mysql-2.3.0-1.rockspec000066400000000000000000000015571175743000500247500ustar00rootroot00000000000000package = "LuaSQL-MySQL" version = "2.3.0-1" source = { url = "git://github.com/keplerproject/luasql.git", branch = "v2.3.0", } description = { summary = "Database connectivity for Lua (MySQL driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { MYSQL = { header = "mysql.h" } } build = { type = "builtin", modules = { ["luasql.mysql"] = { sources = { "src/luasql.c", "src/ls_mysql.c" }, libraries = { "mysqlclient" }, incdirs = { "$(MYSQL_INCDIR)" }, libdirs = { "$(MYSQL_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-mysql-cvs-1.rockspec000066400000000000000000000015271175743000500251000ustar00rootroot00000000000000package = "LuaSQL-MySQL" version = "cvs-1" source = { url = "git://github.com/keplerproject/luasql.git" } description = { summary = "Database connectivity for Lua (MySQL driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { MYSQL = { header = "mysql.h" } } build = { type = "builtin", modules = { ["luasql.mysql"] = { sources = { "src/luasql.c", "src/ls_mysql.c" }, libraries = { "mysqlclient" }, incdirs = { "$(MYSQL_INCDIR)" }, libdirs = { "$(MYSQL_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-oci8-2.3.0-1.rockspec000066400000000000000000000015511175743000500244370ustar00rootroot00000000000000package = "LuaSQL-OCI8" version = "2.3.0-1" source = { url = "git://github.com/keplerproject/luasql.git", branch = "v2.3.0", } description = { summary = "Database connectivity for Lua (Oracle driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { OCI8 = { header = "oci.h" } } build = { type = "builtin", modules = { ["luasql.oci8"] = { sources = { "src/luasql.c", "src/ls_oci8.c" }, libraries = { "z", "clntsh", }, incdirs = { "$(OCI8_INCDIR)" }, libdirs = { "$(OCI8_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-odbc-2.3.0-1.rockspec000066400000000000000000000015371175743000500245100ustar00rootroot00000000000000package = "LuaSQL-ODBC" version = "2.3.0-1" source = { url = "git://github.com/keplerproject/luasql.git", branch = "v2.3.0", } description = { summary = "Database connectivity for Lua (ODBC driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { ODBC = { header = "sql.h" } } build = { type = "builtin", modules = { ["luasql.odbc"] = { sources = { "src/luasql.c", "src/ls_odbc.c" }, libraries = { "odbc" }, incdirs = { "$(ODBC_INCDIR)" }, libdirs = { "$(ODBC_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-odbc-cvs-1.rockspec000066400000000000000000000016101175743000500246330ustar00rootroot00000000000000package = "LuaSQL-ODBC" version = "cvs-1" source = { url = "git://github.com/keplerproject/luasql.git" } description = { summary = "Database connectivity for Lua (ODBC driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { ODBC = { header = "sql.h" } } build = { type = "make", variables = { T="odbc", LIB_OPTION = "$(LIBFLAG) -L$(ODBC_LIBDIR) -lodbc", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR) -I$(ODBC_INCDIR) -DUNIXODBC" }, build_variables = { DRIVER_LIBS = "", }, install_variables = { LUA_LIBDIR = "$(LIBDIR)", } } keplerproject-luasql-c527024/rockspec/luasql-postgres-2.3.0-1.rockspec000066400000000000000000000015661175743000500254510ustar00rootroot00000000000000package = "LuaSQL-Postgres" version = "2.3.0-1" source = { url = "git://github.com/keplerproject/luasql.git", branch = "v2.3.0", } description = { summary = "Database connectivity for Lua (Postgres driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { PGSQL = { header = "pg_config.h" } } build = { type = "builtin", modules = { ["luasql.postgres"] = { sources = { "src/luasql.c", "src/ls_postgres.c" }, libraries = { "pq" }, incdirs = { "$(PGSQL_INCDIR)" }, libdirs = { "$(PGSQL_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-postgres-cvs-2.rockspec000066400000000000000000000016671175743000500256070ustar00rootroot00000000000000package = "LuaSQL-Postgres" version = "cvs-2" source = { url = "git://github.com/keplerproject/luasql.git" } description = { summary = "Database connectivity for Lua (Postgres driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { POSTGRES = { header = "pg_config.h" } } build = { type = "make", variables = { T="postgres", LIB_OPTION = "$(LIBFLAG) -L$(POSTGRES_LIBDIR) -lpq", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR) -I$(POSTGRES_INCDIR) -I$(POSTGRES_INCDIR)/postgresql" }, build_variables = { DRIVER_LIBS="", }, install_variables = { LUA_LIBDIR = "$(LIBDIR)", } } keplerproject-luasql-c527024/rockspec/luasql-sqlite-2.2.0rc1-1.rockspec000066400000000000000000000016331175743000500255040ustar00rootroot00000000000000package = "LuaSQL-SQLite" version = "2.2.0rc1-1" source = { url = "http://luasql.luaforge.net/luasql-2.2.0rc1.tar.gz", } description = { summary = "Database connectivity for Lua (SQLite driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite.h" } } build = { type = "make", variables = { T="sqlite", LIB_OPTION = "$(LIBFLAG) -L$(SQLITE_LIBDIR) -lsqlite", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR) -I$(SQLITE_INCDIR)" }, build_variables = { DRIVER_LIBS="", }, install_variables = { LUA_LIBDIR = "$(LIBDIR)", } } keplerproject-luasql-c527024/rockspec/luasql-sqlite-2.3.0-1.rockspec000066400000000000000000000015621175743000500251000ustar00rootroot00000000000000package = "LuaSQL-SQLite" version = "2.3.0-1" source = { url = "git://github.com/keplerproject/luasql.git", branch = "v2.3.0", } description = { summary = "Database connectivity for Lua (SQLite driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite.h" } } build = { type = "builtin", modules = { ["luasql.sqlite"] = { sources = { "src/luasql.c", "src/ls_sqlite.c" }, libraries = { "sqlite" }, incdirs = { "$(SQLITE_INCDIR)" }, libdirs = { "$(SQLITE_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-sqlite-cvs-1.rockspec000066400000000000000000000015321175743000500252300ustar00rootroot00000000000000package = "LuaSQL-SQLite" version = "cvs-1" source = { url = "git://github.com/keplerproject/luasql.git" } description = { summary = "Database connectivity for Lua (SQLite driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite.h" } } build = { type = "builtin", modules = { ["luasql.sqlite"] = { sources = { "src/luasql.c", "src/ls_sqlite.c" }, libraries = { "sqlite" }, incdirs = { "$(SQLITE_INCDIR)" }, libdirs = { "$(SQLITE_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-sqlite3-2.2.0-1.rockspec000066400000000000000000000016031175743000500251560ustar00rootroot00000000000000package = "LuaSQL-SQLite3" version = "2.2.0-1" source = { url = "http://cloud.github.com/downloads/keplerproject/luasql/luasql-2.2.0.tar.gz" } description = { summary = "Database connectivity for Lua (SQLite3 driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite3.h" } } build = { type = "builtin", modules = { ["luasql.sqlite3"] = { sources = { "src/luasql.c", "src/ls_sqlite3.c" }, libraries = { "sqlite3" }, incdirs = { "$(SQLITE_INCDIR)" }, libdirs = { "$(SQLITE_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-sqlite3-2.2.0rc1-1.rockspec000066400000000000000000000021551175743000500255670ustar00rootroot00000000000000package = "LuaSQL-SQLite3" version = "2.2.0rc1-1" source = { url = "http://luasql.luaforge.net/luasql-2.2.0rc1.tar.gz", } description = { summary = "Database connectivity for Lua (SQLite3 driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite3.h" } } build = { type = "make", variables = { T="sqlite3", LIB_OPTION = "$(LIBFLAG) -L$(SQLITE_LIBDIR) -lsqlite3", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR) -I$(SQLITE_INCDIR)" }, build_variables = { DRIVER_LIBS="", }, install_variables = { LUA_LIBDIR = "$(LIBDIR)", }, platforms = { win32 = { variables = { LIB_OPTION = "$(SQLITE_LIB) $(LUA_LIBDIR)\\lua5.1.lib", CFLAGS = "$(CFLAGS) /I$(LUA_INCDIR) /I$(SQLITE_INCDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-sqlite3-2.3.0-1.rockspec000066400000000000000000000015701175743000500251620ustar00rootroot00000000000000package = "LuaSQL-SQLite3" version = "2.3.0-1" source = { url = "git://github.com/keplerproject/luasql.git", branch = "v2.3.0", } description = { summary = "Database connectivity for Lua (SQLite3 driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite3.h" } } build = { type = "builtin", modules = { ["luasql.sqlite3"] = { sources = { "src/luasql.c", "src/ls_sqlite3.c" }, libraries = { "sqlite3" }, incdirs = { "$(SQLITE_INCDIR)" }, libdirs = { "$(SQLITE_LIBDIR)" } } } } keplerproject-luasql-c527024/rockspec/luasql-sqlite3-cvs-1.rockspec000066400000000000000000000015401175743000500253120ustar00rootroot00000000000000package = "LuaSQL-SQLite3" version = "cvs-1" source = { url = "git://github.com/keplerproject/luasql.git" } description = { summary = "Database connectivity for Lua (SQLite3 driver)", detailed = [[ LuaSQL is a simple interface from Lua to a DBMS. It enables a Lua program to connect to databases, execute arbitrary SQL statements and retrieve results in a row-by-row cursor fashion. ]], license = "MIT/X11", homepage = "http://www.keplerproject.org/luasql/" } dependencies = { "lua >= 5.1" } external_dependencies = { SQLITE = { header = "sqlite3.h" } } build = { type = "builtin", modules = { ["luasql.sqlite3"] = { sources = { "src/luasql.c", "src/ls_sqlite3.c" }, libraries = { "sqlite3" }, incdirs = { "$(SQLITE_INCDIR)" }, libdirs = { "$(SQLITE_LIBDIR)" } } } } keplerproject-luasql-c527024/src/000077500000000000000000000000001175743000500167235ustar00rootroot00000000000000keplerproject-luasql-c527024/src/ado/000077500000000000000000000000001175743000500174665ustar00rootroot00000000000000keplerproject-luasql-c527024/src/ado/ado.lua000066400000000000000000000221121175743000500207320ustar00rootroot00000000000000--------------------------------------------------------------------- -- ADO driver implemented using LuaCOM --------------------------------------------------------------------- require"luacom" --------------------------------------------------------------------- -- luasql table name --------------------------------------------------------------------- local libName = "luasql" local Private = {} luasql = type(_G[libName]) == "table" and _G[libName] or {} local ADOTypes = {} do local conn = luacom.CreateObject("ADODB.Connection") local typeinfo = luacom.GetTypeInfo(conn) local typelib = typeinfo:GetTypeLib() local enums = typelib:ExportEnumerations() for k, v in pairs(enums.DataTypeEnum) do ADOTypes[k] = v ADOTypes[v] = k end end local metatable = { __metatable = "LuaSQL: you're not allowed to get this metatable" } luasql._COPYRIGHT = "Copyright (C) 2003-2006 Kepler Project" luasql._DESCRIPTION = "LuaSQL is a simple interface from Lua to a DBMS" luasql._VERSION = "LuaSQL 2.1.1" --------------------------------------------------------------------- -- function that returns an ADO environment --------------------------------------------------------------------- function luasql.ado() local isClosed = false local openConns = {} openConns.n = 0 local env = {} setmetatable(env, metatable) env.ADOTypes = ADOTypes local function closeConn(con) if not openConns[con] then return false end openConns[con] = nil openConns.n = openConns.n - 1 return true end function env:close() if not self then error("You must provide a self parameter") end if isClosed or openConns.n ~= 0 then return false end isClosed = true return true end function env:connect(sourcestr, user, pass, opts) if not self then error("You must provide a self parameter") end if isClosed then error("Environment closed") end if type(sourcestr) ~= "string" then error("Sourcename must be a string") end local conn = luacom.CreateObject("ADODB.Connection") local ok, errmsg = pcall(conn.Open, conn, sourcestr, user, pass, opts) if not ok then return nil, errmsg end if conn.State == 0 then return nil, "Invalid sourcename" end openConns[conn] = true openConns.n = openConns.n + 1 local ok, errmsg = pcall(conn.BeginTrans, conn) return Private.createConnection(conn, closeConn) end return env end --------------------------------------------------------------------- -- creates an ADO connection --------------------------------------------------------------------- function Private.createConnection(conObj, closeFunc) local openCursors = {} openCursors.n = 0 local isClosed = false local con = {} setmetatable(con, metatable) local autocommit = true local function closeCursor(cursor) if not openCursors[cursor] then return false end openCursors[cursor] = nil openCursors.n = openCursors.n - 1 end function con:close() if not self then error("You must provide a self parameter") end if isClosed or openCursors.n ~= 0 then return false end isClosed = true local cond, err = pcall(conObj.RollbackTrans, conObj) conObj:Close() closeFunc(conObj) return true end function con:commit() if not self then error("You must provide a self parameter") end if isClosed then error("Connection closed") end local cond, err = pcall(conObj.CommitTrans, conObj) if not cond then return false, err end local cond, err = pcall(conObj.BeginTrans, conObj) if not cond then return false, err end return true end function con:execute(sql) if not self then error("You must provide a self parameter") end if isClosed then error("Connection closed") end local cond, res, upcount = pcall(conObj.Execute, conObj, sql) if not cond then return nil, res end if not upcount then upcount = 0 end if autocommit then local cond, err = con:commit() if not cond then return nil, err end end if res and res.State ~= 0 then res = Private.createCursor(res, con, closeCursor) openCursors[res] = true openCursors.n = openCursors.n + 1 else res = upcount end return res end function con:rollback() if not self then error("You must provide a self parameter") end if isClosed then error("Connection closed") end local cond, err = pcall(conObj.RollbackTrans, conObj) if not cond then return false, err end local cond, err = pcall(conObj.BeginTrans, conObj) if not cond then return false, err end return true end function con:setautocommit(bool) if not self then error("You must provide a self parameter") end if isClosed then error("Connection closed") end local cond, err = pcall(conObj.CommitTrans, conObj) if not cond then return false, err end autocommit = bool local cond, err = pcall(conObj.BeginTrans, conObj) if not cond then return false, err end return true end return con end --------------------------------------------------------------------- -- creates an ADO cursor (recordset) --------------------------------------------------------------------- function Private.createCursor(rs, con, closeFunc) local isClosed = false local cursor = rs local res = {} local col_names = nil local col_types = nil setmetatable(res, metatable) function res:close() if not self then error("You must provide a self parameter") end if isClosed then return false end rs:Close() closeFunc(res, con) isClosed = true return true end function res:fetch(tb, modestring) if not self then error("You must provide a self parameter") end if isClosed then error("Cursor closed") end local arg_tb = tb if cursor.EOF then return nil, "End of cursor reached" end if tb == nil or type(tb) ~= "table" then tb = {} end if modestring == nil or type(modestring) ~= "string" then modestring = "n" end for i = 0, cursor.Fields.Count-1 do local fields = cursor.Fields local cond, field = pcall(fields.Item, fields, i) if not cond then return nil, field end if modestring == "n" or modestring == "an" or modestring == "na" then tb[i+1] = field.Value end if modestring == "a" or modestring == "an" or modestring == "na" then tb[field.Name] = field.Value end end local cond, err = pcall(cursor.MoveNext, cursor) if not cond then return nil, err end if modestring == "n" and not arg_tb then return unpack(tb) else return tb end end function res:getcolnames() if not self then error("You must provide a self parameter") end if isClosed then error("Cursor closed") end if col_names then return col_names end col_names = {} local tb = col_names for i = 0, cursor.Fields.Count-1 do local fields = cursor.Fields local cond, field = pcall(fields.Item, fields, i) if not cond then return nil, field end tb[i+1] = field.Name end return tb end function res:getcoltypes() if not self then error("You must provide a self parameter") end if isClosed then error("Cursor closed") end if col_types then return col_types end col_types = {} local tb = col_types for i = 0, cursor.Fields.Count-1 do local fields = cursor.Fields local cond, field = pcall(fields.Item, fields, i) if not cond then return nil, field end tb[i+1] = ADOTypes[field.Type] end return tb end return res end keplerproject-luasql-c527024/src/firebird.def000066400000000000000000000000411175743000500211640ustar00rootroot00000000000000EXPORTS luaopen_luasql_firebird keplerproject-luasql-c527024/src/jdbc/000077500000000000000000000000001175743000500176255ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/Makefile000066400000000000000000000014431175743000500212670ustar00rootroot00000000000000# JDBC JDK= $(JAVA_HOME) #source dir JDBC_SRC= src/java #lib dir JDBC_LIB= lib #build dir JDBC_BUILD= bin #java compiler JAVAC= $(JAVA_HOME)/bin/javac JAR= $(JAVA_HOME)/bin/jar #luajava jar name LUAJAVA_JAR= luajava-1.0b4.jar #compilation options COMPILEOPT= -d $(JDBC_BUILD) -classpath $(JDBC_LIB)/$(LUAJAVA_JAR) #package name ALLPACKAGES= org/keplerproject/luasql/jdbc SUBDIRS= addprefix $(JDBC_SRC), $(ALLPACKAGES) SOURCEDIRS= $(JDBC_SRC)/$(ALLPACKAGES) SOURCEFILES = $(addsuffix /*.java, $(SOURCEDIRS)) JARSDIR= . PACKAGENAME= luasql jdbc_driver: rm -rf $(JDBC_BUILD) mkdir $(JDBC_BUILD) for i in $(SUBDIRS); \ do ( $(JAVAC) $(COMPILEOPT) $(SOURCEFILES) ) done $(JAR) -cvf $(JARSDIR)/$(PACKAGENAME).jar -C $(JDBC_BUILD) . clean: rm -rf $(JDBC_BUILD) rm -f $(JARSDIR)/$(PACKAGENAME).jar keplerproject-luasql-c527024/src/jdbc/Makefile.win000066400000000000000000000014531175743000500220640ustar00rootroot00000000000000# JDBC JDK= $(JAVA_HOME) #source dir JDBC_SRC= src\java #lib dir JDBC_LIB= lib #build dir JDBC_BUILD= bin #java compiler JAVAC= $(JAVA_HOME)\bin\javac.exe JAR= $(JAVA_HOME)\bin\jar.exe #luajava jar name LUAJAVA_JAR= luajava-1.0b4.jar #compilation options COMPILEOPT= -d $(JDBC_BUILD) -classpath $(JDBC_LIB)\$(LUAJAVA_JAR) #package name ALLPACKAGES= org/keplerproject/luasql/jdbc SUBDIRS= addprefix $(JDBC_SRC), $(ALLPACKAGES) SOURCEDIRS= $(JDBC_SRC)/$(ALLPACKAGES) SOURCEFILES = $(addsuffix /*.java, $(SOURCEDIRS)) JARSDIR= . PACKAGENAME= luasql jdbc_driver: rm -rf $(JDBC_BUILD) mkdir $(JDBC_BUILD) for i in $(SUBDIRS); \ do ( $(JAVAC) $(COMPILEOPT) $(SOURCEFILES) ) done $(JAR) -cvf $(JARSDIR)/$(PACKAGENAME).jar -C $(JDBC_BUILD) . clean: rm -rf $(JDBC_BUILD) rm -f $(JARSDIR)/$(PACKAGENAME).jar keplerproject-luasql-c527024/src/jdbc/build.xml000066400000000000000000000052341175743000500214520ustar00rootroot00000000000000 keplerproject-luasql-c527024/src/jdbc/src/000077500000000000000000000000001175743000500204145ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/java/000077500000000000000000000000001175743000500213355ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/java/org/000077500000000000000000000000001175743000500221245ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/java/org/keplerproject/000077500000000000000000000000001175743000500247755ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/java/org/keplerproject/luasql/000077500000000000000000000000001175743000500262765ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/java/org/keplerproject/luasql/jdbc/000077500000000000000000000000001175743000500272005ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/java/org/keplerproject/luasql/jdbc/LuaSQLCursor.java000066400000000000000000000110141175743000500323370ustar00rootroot00000000000000package org.keplerproject.luasql.jdbc; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import org.keplerproject.luajava.JavaFunction; import org.keplerproject.luajava.LuaException; import org.keplerproject.luajava.LuaObject; import org.keplerproject.luajava.LuaState; /** * LuaSQL JDBC cursor. Is implemented in Java because it's more efficient. * The fetch method was slow in Lua, due to many accesses to Java. * * @author Thiago Ponte */ public class LuaSQLCursor { private LuaState L; private ResultSet rs; /** * Function that open the Lib. */ static public int open(LuaState L) throws LuaException { L.pushJavaFunction(new JavaFunction(L){ /** * Creates a LuaSQLCursor and returns it. */ public int execute() throws LuaException { ResultSet rs = (ResultSet) L.getObjectFromUserdata(2); L.pushJavaObject(new LuaSQLCursor(L, rs)); return 1; } }); return 1; } protected LuaSQLCursor(LuaState L, ResultSet rs) { this.L = L; this.rs = rs; } /** * * @param table the results will be copied into the table and this table will be returned. * @param modeString the results will be copied into the table and this table will be returned
* "n" the resulting table will have numerical indices (default)
* "a" the resulting table will have alphanumerical indices * @return the parameter table */ public LuaObject fetch(LuaObject table, String modeString) { try { if (!rs.next()) return null; table.push(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); for (int i = 1; i <= columnCount; i++) { int type = md.getColumnType(i); /* if ("a".equalsIgnoreCase(modeString)) L.pushString(md.getColumnName(i)); else L.pushNumber(i);*/ switch (type) { case Types.INTEGER: case Types.BIGINT: case Types.SMALLINT: case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.NUMERIC: case Types.REAL: case Types.TINYINT: L.pushNumber(rs.getDouble(i)); break; case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CLOB: L.pushString(rs.getString(i)); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: L.pushString(rs.getBytes(i)); break; case Types.BIT: case Types.BOOLEAN: L.pushBoolean(rs.getBoolean(i)? 1 : 0); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: L.pushString(rs.getDate(i).toString()); break; case Types.NULL: L.pushNil(); break; default: L.pushString(rs.getString(i)); break; } if (modeString.contains("a")) { L.pushString(md.getColumnName(i)); L.pushValue(-2); L.setTable(-4); } if (modeString.contains("n")) { L.pushNumber(i); L.pushValue(-2); L.setTable(-4); } L.pop(1); } L.pop(1); return table; } catch (SQLException e) { return table; } } /** * Gets the name of the columns. * * @return a list of column names. */ public LuaObject getcolnames() throws SQLException { L.newTable(); LuaObject table = L.getLuaObject(-1); ResultSetMetaData md = rs.getMetaData(); for (int i = 1; i <= md.getColumnCount(); i++) { String name = md.getColumnName(i); L.pushNumber(i); L.pushString(name); L.setTable(-3); } L.pop(1); return table; } /** * Gets the types of the columns * * @return a list of column types. */ public LuaObject getcoltypes() throws SQLException { L.newTable(); LuaObject table = L.getLuaObject(-1); ResultSetMetaData md = rs.getMetaData(); for (int i = 1; i <= md.getColumnCount(); i++) { String name = md.getColumnTypeName(i); L.pushNumber(i); L.pushString(name); L.setTable(-3); } L.pop(1); return table; } } keplerproject-luasql-c527024/src/jdbc/src/lua/000077500000000000000000000000001175743000500211755ustar00rootroot00000000000000keplerproject-luasql-c527024/src/jdbc/src/lua/jdbc.lua000066400000000000000000000213031175743000500226010ustar00rootroot00000000000000--------------------------------------------------------------------- -- LuaSQL JDBC driver implementation -- @author Thiago Ponte --------------------------------------------------------------------- --------------------------------------------------------------------- -- luasql table name --------------------------------------------------------------------- local libName = "luasql" local LUASQL_PREFIX = "LuaSQL: " local Private = {} luasql = type(_G[libName]) == "table" and _G[libName] or {} Private.createJavaCursor = luajava.loadLib("org.keplerproject.luasql.jdbc.LuaSQLCursor", "open") luasql._COPYRIGHT = "Copyright (C) 2003-2006 Kepler Project" luasql._DESCRIPTION = "LuaSQL is a simple interface from Lua to a DBMS" luasql._VERSION = "LuaSQL 2.0.2" --------------------------------------------------------------------- -- function that returns a jdbc environment --------------------------------------------------------------------- function luasql.jdbc(driver) if driver == nil then return nil, "Error. Argument #1 must be the jdbc driver class." end local cond, err = pcall(luajava.bindClass, driver) if not cond then return nil, err end return Private.createEnv() end --------------------------------------------------------------------- -- creates a jdbc environment --------------------------------------------------------------------- function Private.createEnv() local isClosed = false local openConns = {} openConns.n = 0 local env = {} local function closeConn(con) if not openConns[con] then return false end openConns[con] = nil openConns.n = openConns.n - 1 return true end function env:close() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."environment expected") end if isClosed or openConns.n ~= 0 then return false end isClosed = true return true end function env:connect(sourcename, username, password) -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."environment expected") end if isClosed then error(LUASQL_PREFIX.."environment is closed") --return nil, "Environment closed." end if sourcename == nil then return nil, "Invalid sourcename." end local driverManager = luajava.bindClass("java.sql.DriverManager") local cond, con if username == nil and password == nil then cond, con = pcall(driverManager.getConnection, driverManager, sourcename) else cond, con = pcall(driverManager.getConnection, driverManager, sourcename, username or '', password or '') end if not cond then return nil, con end openConns[con] = true openConns.n = openConns.n + 1 return Private.createConnection(con, closeConn) end -- For compatibility with other drivers setmetatable(env, {__metatable = LUASQL_PREFIX.."you're not allowed to get this metatable"}) return env end --------------------------------------------------------------------- -- creates a jdbc connection --------------------------------------------------------------------- function Private.createConnection(conObj, closeFunc) local openCursors = {} openCursors.n = 0 local con = {} local function closeCursor(cursor) if not openCursors[cursor] then return false end openCursors[cursor] = nil openCursors.n = openCursors.n - 1 end function con:close() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."connection expected") end if conObj:isClosed() or openCursors.n ~= 0 then return false end conObj:close() closeFunc(conObj) return true end function con:commit() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."connection expected") end local cond, err = pcall(conObj.commit, conObj) if not cond then return nil, err end end function con:execute(sql) if conObj:isClosed() then error(LUASQL_PREFIX.."connection is closed") end -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."connection expected") end local st = conObj:createStatement() local cond, isRS = pcall(st.execute, st, sql) if not cond then return nil, isRS end local res; if isRS then res = Private.createCursor(st:getResultSet(), st, closeCursor, con) openCursors[res] = true openCursors.n = openCursors.n + 1 else res = st:getUpdateCount() st:close(); end return res end function con:rollback() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."connection expected") end local cond, err = pcall(conObj.rollback, conObj) if not cond then return nil, err end end function con:setautocommit(bool) -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."connection expected") end local cond, err = pcall(conObj.setAutoCommit, conObj, bool) if not cond then return nil, err end end -- For compatibility with other drivers setmetatable(con, {__metatable = LUASQL_PREFIX.."you're not allowed to get this metatable"}) return con end --------------------------------------------------------------------- -- creates a jdbc cursor --------------------------------------------------------------------- function Private.createCursor(rs, st, closeFunc, con) local isClosed = false local cursor = Private.createJavaCursor(rs) local res = {} local names local types res._con = con function res:close() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."cursor expected") end if isClosed then return false end rs:close() st:close() closeFunc(res) isClosed = true return true end function res:fetch(tb, modestring) -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."cursor expected") end if tb == nil or type(tb) ~= "table" then tb = {} local cond, tb = pcall(cursor.fetch, cursor, tb, "n") if not cond then error(LUASQ_PREFIX.."error fetching result") end if tb then return unpack(tb) else return nil end end if modestring == nil or type(modestring) ~= "string" then modestring = "n" end local cond, tb = pcall(cursor.fetch, cursor, tb, modestring) if not cond then return nil, tb end return tb end function res:getcolnames() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."cursor expected") end if names then return names end local cond, tb = pcall (cursor.getcolnames, cursor) if not cond then return cond, tb end names = tb return tb end function res:getcoltypes() -- For compatibility with other drivers if type(self) ~= "table" then error(LUASQL_PREFIX.."cursor expected") end if types then return types end local cond, tb = pcall(cursor.getcoltypes, cursor) if not cond then return nil, tb end types = tb return tb end -- For compatibility with other drivers setmetatable(res, {__metatable = LUASQL_PREFIX.."you're not allowed to get this metatable"}) return res end keplerproject-luasql-c527024/src/ls_firebird.c000066400000000000000000000666701175743000500213720ustar00rootroot00000000000000/* ** LuaSQL, Firebird driver ** Authors: Scott Morgan ** ls_firebird.c */ #include /* The Firebird API*/ #include /* For managing time values */ #include #include /* Lua API */ #include #include #include "luasql.h" #define LUASQL_ENVIRONMENT_FIREBIRD "Firebird environment" #define LUASQL_CONNECTION_FIREBIRD "Firebird connection" #define LUASQL_CURSOR_FIREBIRD "Firebird cursor" typedef struct { short closed; ISC_STATUS status_vector[20]; /* for error results */ int lock; /* lock count for open connections */ } env_data; typedef struct { short closed; env_data* env; /* the DB enviroment this is in */ isc_db_handle db; /* the database handle */ char dpb_buffer[256];/* holds the database paramet buffer */ short dpb_length; /* the used amount of the dpb */ isc_tr_handle transaction; /* the transaction handle */ int lock; /* lock count for open cursors */ int autocommit; /* should each statement be commited */ } conn_data; typedef struct { short closed; env_data* env; /* the DB enviroment this is in */ conn_data* conn; /* the DB connection this cursor is from */ isc_stmt_handle stmt; /* the statement handle */ XSQLDA *out_sqlda; /* the cursor data array */ } cur_data; /* How many fields to pre-alloc to the cursor */ #define CURSOR_PREALLOC 10 /* Macro to ease code reading */ #define CHECK_DB_ERROR( X ) ( (X)[0] == 1 && (X)[1] ) /* Use the new interpret API if available */ #undef FB_INTERPRET #if FB_API_VER >= 20 #define FB_INTERPRET(BUF, LEN, VECTOR) fb_interpret(BUF, LEN, VECTOR) #else #define FB_INTERPRET(BUF, LEN, VECTOR) isc_interpret(BUF, VECTOR) #endif LUASQL_API int luaopen_luasql_firebird (lua_State *L); /* ** Returns a standard database error message */ static int return_db_error(lua_State *L, const ISC_STATUS *pvector) { char errmsg[512]; lua_pushnil(L); FB_INTERPRET(errmsg, 512, &pvector); lua_pushstring(L, errmsg); while(FB_INTERPRET(errmsg, 512, &pvector)) { lua_pushstring(L, "\n * "); lua_pushstring(L, errmsg); lua_concat(L, 3); } return 2; } /* ** Registers a given C object in the registry to avoid GC */ static void lua_registerobj(lua_State *L, int index, void *obj) { lua_pushvalue(L, index); lua_pushlightuserdata(L, obj); lua_pushvalue(L, -2); lua_settable(L, LUA_REGISTRYINDEX); lua_pop(L, 1); } /* ** Unregisters a given C object from the registry */ static void lua_unregisterobj(lua_State *L, void *obj) { lua_pushlightuserdata(L, obj); lua_pushnil(L); lua_settable(L, LUA_REGISTRYINDEX); } /* ** Free's up the memory alloc'd to the cursor data */ static void free_cur(cur_data* cur) { int i; XSQLVAR *var; /* free the field memory blocks */ for (i=0, var = cur->out_sqlda->sqlvar; i < cur->out_sqlda->sqld; i++, var++) { free(var->sqldata); if(var->sqlind != NULL) free(var->sqlind); } /* free the data array */ free(cur->out_sqlda); } /* ** Check for valid environment. */ static env_data *getenvironment (lua_State *L, int i) { env_data *env = (env_data *)luaL_checkudata (L, i, LUASQL_ENVIRONMENT_FIREBIRD); luaL_argcheck (L, env != NULL, i, "environment expected"); luaL_argcheck (L, !env->closed, i, "environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection (lua_State *L, int i) { conn_data *conn = (conn_data *)luaL_checkudata (L, i, LUASQL_CONNECTION_FIREBIRD); luaL_argcheck (L, conn != NULL, i, "connection expected"); luaL_argcheck (L, !conn->closed, i, "connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor (lua_State *L, int i) { cur_data *cur = (cur_data *)luaL_checkudata (L, i, LUASQL_CURSOR_FIREBIRD); luaL_argcheck (L, cur != NULL, i, "cursor expected"); luaL_argcheck (L, !cur->closed, i, "cursor is closed"); return cur; } /* ** Returns the statement type */ static int get_statement_type(cur_data* cur) { int length, type; char type_item[] = { isc_info_sql_stmt_type }; char res_buffer[88], *pres; pres = res_buffer; isc_dsql_sql_info( cur->env->status_vector, &cur->stmt, sizeof(type_item), type_item, sizeof(res_buffer), res_buffer ); if (cur->env->status_vector[0] == 1 && cur->env->status_vector[1] > 0) return -1; /* check the type of the statement */ if (*pres == isc_info_sql_stmt_type) { pres++; length = isc_vax_integer(pres, 2); pres += 2; type = isc_vax_integer(pres, length); pres += length; } else return -2; /* should have had the isc_info_sql_stmt_type info */ return type; } /* ** Return the number of rows affected by last operation */ static int count_rows_affected(cur_data* cur) { int length, type, res=0; int del_count = 0, ins_count = 0, upd_count = 0, sel_count = 0; char type_item[] = { isc_info_sql_stmt_type, isc_info_sql_records }; char res_buffer[88], *pres; pres = res_buffer; isc_dsql_sql_info( cur->env->status_vector, &cur->stmt, sizeof(type_item), type_item, sizeof(res_buffer), res_buffer ); if (cur->env->status_vector[0] == 1 && cur->env->status_vector[1] > 0) return -1; /* check the type of the statement */ if (*pres == isc_info_sql_stmt_type) { pres++; length = isc_vax_integer(pres, 2); pres += 2; type = isc_vax_integer(pres, length); pres += length; } else return -2; /* should have had the isc_info_sql_stmt_type info */ if(type > 4) return 0; /* not a SELECT, INSERT, UPDATE or DELETE SQL statement */ if (*pres == isc_info_sql_records) { pres++; length = isc_vax_integer(pres, 2); /* normally 29 bytes */ pres += 2; while(*pres != 1) { switch(*pres) { case isc_info_req_select_count: pres++; length = isc_vax_integer(pres, 2); pres += 2; sel_count = isc_vax_integer(pres, length); pres += length; break; case isc_info_req_insert_count: pres++; length = isc_vax_integer(pres, 2); pres += 2; ins_count = isc_vax_integer(pres, length); pres += length; break; case isc_info_req_update_count: pres++; length = isc_vax_integer(pres, 2); pres += 2; upd_count = isc_vax_integer(pres, length); pres += length; break; case isc_info_req_delete_count: pres++; length = isc_vax_integer(pres, 2); pres += 2; del_count = isc_vax_integer(pres, length); pres += length; break; default: pres++; break; } } } else return -3; switch(type) { case isc_info_sql_stmt_select: res = sel_count; break; case isc_info_sql_stmt_delete: res = del_count; break; case isc_info_sql_stmt_update: res = upd_count; break; case isc_info_sql_stmt_insert: res = ins_count; break; } return res; } /* ** Executes a SQL statement. ** Returns ** cursor object: if there are results or ** row count: number of rows affected by statement if no results */ static int conn_execute (lua_State *L) { conn_data *conn = getconnection(L,1); const char *statement = luaL_checkstring(L, 2); int dialect = (int)luaL_optnumber(L, 3, 3); XSQLVAR *var; long dtype; int i, n, count, stmt_type; cur_data cur; cur.closed = 0; cur.env = conn->env; cur.conn = conn; cur.stmt = 0; cur.out_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(CURSOR_PREALLOC)); cur.out_sqlda->version = SQLDA_VERSION1; cur.out_sqlda->sqln = CURSOR_PREALLOC; /* create a statement to handle the query */ isc_dsql_allocate_statement(conn->env->status_vector, &conn->db, &cur.stmt); if ( CHECK_DB_ERROR(conn->env->status_vector) ) { free(cur.out_sqlda); return return_db_error(L, conn->env->status_vector); } /* process the SQL ready to run the query */ isc_dsql_prepare(conn->env->status_vector, &conn->transaction, &cur.stmt, 0, (char*)statement, dialect, cur.out_sqlda); if ( CHECK_DB_ERROR(conn->env->status_vector) ) { free(cur.out_sqlda); return return_db_error(L, conn->env->status_vector); } /* what type of SQL statement is it? */ stmt_type = get_statement_type(&cur); if(stmt_type < 0) { free(cur.out_sqlda); return return_db_error(L, conn->env->status_vector); } /* an unsupported SQL statement (something like COMMIT) */ if(stmt_type > 5) { free(cur.out_sqlda); return luasql_faildirect(L, "unsupported SQL statement"); } /* resize the result set if needed */ if (cur.out_sqlda->sqld > cur.out_sqlda->sqln) { n = cur.out_sqlda->sqld; free(cur.out_sqlda); cur.out_sqlda = (XSQLDA *)malloc(XSQLDA_LENGTH(n)); cur.out_sqlda->sqln = n; cur.out_sqlda->version = SQLDA_VERSION1; isc_dsql_describe(conn->env->status_vector, &cur.stmt, 1, cur.out_sqlda); if ( CHECK_DB_ERROR(conn->env->status_vector) ) { free(cur.out_sqlda); return return_db_error(L, conn->env->status_vector); } } /* prep the result set ready to handle the data */ for (i=0, var = cur.out_sqlda->sqlvar; i < cur.out_sqlda->sqld; i++, var++) { dtype = (var->sqltype & ~1); /* drop flag bit for now */ switch(dtype) { case SQL_VARYING: var->sqldata = (char *)malloc(sizeof(char)*var->sqllen + 2); break; case SQL_TEXT: var->sqldata = (char *)malloc(sizeof(char)*var->sqllen); break; case SQL_SHORT: var->sqldata = (char *)malloc(sizeof(short)); break; case SQL_LONG: var->sqldata = (char *)malloc(sizeof(long)); break; case SQL_INT64: var->sqldata = (char *)malloc(sizeof(ISC_INT64)); break; case SQL_FLOAT: var->sqldata = (char *)malloc(sizeof(float)); break; case SQL_DOUBLE: var->sqldata = (char *)malloc(sizeof(double)); break; case SQL_TYPE_TIME: var->sqldata = (char *)malloc(sizeof(ISC_TIME)); break; case SQL_TYPE_DATE: var->sqldata = (char *)malloc(sizeof(ISC_DATE)); break; case SQL_TIMESTAMP: var->sqldata = (char *)malloc(sizeof(ISC_TIMESTAMP)); break; case SQL_BLOB: var->sqldata = (char *)malloc(sizeof(ISC_QUAD)); break; /* TODO : add extra data type handles here */ } if (var->sqltype & 1) { /* allocate variable to hold NULL status */ var->sqlind = (short *)malloc(sizeof(short)); } else { var->sqlind = NULL; } } /* run the query */ isc_dsql_execute(conn->env->status_vector, &conn->transaction, &cur.stmt, 1, NULL); if ( CHECK_DB_ERROR(conn->env->status_vector) ) { free_cur(&cur); return return_db_error(L, conn->env->status_vector); } /* if autocommit is set and it's a non SELECT query, commit change */ if(conn->autocommit != 0 && stmt_type > 1) { isc_commit_retaining(conn->env->status_vector, &conn->transaction); if ( CHECK_DB_ERROR(conn->env->status_vector) ) { free_cur(&cur); return return_db_error(L, conn->env->status_vector); } } /* what do we return? a cursor or a count */ if(cur.out_sqlda->sqld > 0) { /* a cursor */ char cur_name[32]; cur_data* user_cur = (cur_data*)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_FIREBIRD); sprintf(cur_name, "dyn_cursor_%p", (void *)user_cur); /* open the cursor ready for fetch cycles */ isc_dsql_set_cursor_name(cur.env->status_vector, &cur.stmt, cur_name, 0); if ( CHECK_DB_ERROR(conn->env->status_vector) ) { lua_pop(L, 1); /* the userdata */ free_cur(&cur); return return_db_error(L, conn->env->status_vector); } /* copy the cursor into a new lua userdata object */ memcpy((void*)user_cur, (void*)&cur, sizeof(cur_data)); /* add cursor to the lock count */ lua_registerobj(L, 1, conn); ++conn->lock; } else { /* a count */ if( (count = count_rows_affected(&cur)) < 0 ) { free(cur.out_sqlda); return return_db_error(L, conn->env->status_vector); } lua_pushnumber(L, count); /* totaly finnished with the cursor */ isc_dsql_free_statement(conn->env->status_vector, &cur.stmt, DSQL_drop); free(cur.out_sqlda); } return 1; } /* ** Commits the current transaction */ static int conn_commit(lua_State *L) { conn_data *conn = getconnection(L,1); isc_commit_retaining(conn->env->status_vector, &conn->transaction); if ( CHECK_DB_ERROR(conn->env->status_vector) ) return return_db_error(L, conn->env->status_vector); lua_pushboolean(L, 1); return 1; } /* ** Rolls back the current transaction ** Lua Returns: ** 1 if rollback is sucsessful ** nil and error message otherwise. */ static int conn_rollback(lua_State *L) { conn_data *conn = getconnection(L,1); isc_rollback_retaining(conn->env->status_vector, &conn->transaction); if ( CHECK_DB_ERROR(conn->env->status_vector) ) return return_db_error(L, conn->env->status_vector); lua_pushboolean(L, 1); return 1; } /* ** Sets the autocommit state of the connection ** Lua Returns: ** autocommit state (0:off, 1:on) ** nil and error message on error. */ static int conn_setautocommit(lua_State *L) { conn_data *conn = getconnection(L,1); if(lua_toboolean(L, 2)) conn->autocommit = 1; else conn->autocommit = 0; lua_pushboolean(L, 1); return 1; } /* ** Closes a connection. ** Lua Returns: ** 1 if close was sucsessful, 0 if already closed ** nil and error message otherwise. */ static int conn_close (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata(L,1,LUASQL_CONNECTION_FIREBIRD); luaL_argcheck (L, conn != NULL, 1, "connection expected"); /* already closed */ if(conn->closed != 0) { lua_pushboolean(L, 0); return 1; } /* are all related cursors closed? */ if(conn->lock > 0) return luasql_faildirect(L, "there are still open cursors"); if(conn->autocommit != 0) isc_commit_transaction(conn->env->status_vector, &conn->transaction); else isc_rollback_transaction(conn->env->status_vector, &conn->transaction); if ( CHECK_DB_ERROR(conn->env->status_vector) ) return return_db_error(L, conn->env->status_vector); isc_detach_database(conn->env->status_vector, &conn->db); if ( CHECK_DB_ERROR(conn->env->status_vector) ) return return_db_error(L, conn->env->status_vector); conn->closed = 1; --conn->env->lock; /* check environment can be GC'd */ if(conn->env->lock == 0) lua_unregisterobj(L, conn->env); lua_pushboolean(L, 1); return 1; } /* ** GCs an connection object */ static int conn_gc (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata(L,1,LUASQL_CONNECTION_FIREBIRD); if(conn->closed == 0) { if(conn->autocommit != 0) isc_commit_transaction(conn->env->status_vector, &conn->transaction); else isc_rollback_transaction(conn->env->status_vector, &conn->transaction); isc_detach_database(conn->env->status_vector, &conn->db); conn->closed = 1; --conn->env->lock; /* check environment can be GC'd */ if(conn->env->lock == 0) lua_unregisterobj(L, conn->env); } return 0; } /* ** Escapes a given string so that it can't break out of it's delimiting quotes */ static int conn_escape(lua_State *L) { size_t len; const char *from = luaL_checklstring (L, 2, &len); char *res = malloc(len*sizeof(char)*2+1); char *to = res; if(res) { while(*from != '\0') { *(to++) = *from; if(*from == '\'') *(to++) = *from; from++; } *to = '\0'; lua_pushstring(L, res); free(res); return 1; } luaL_error(L, "could not allocate escaped string"); return 0; } /* ** Pushes the indexed value onto the lua stack */ static void push_column(lua_State *L, int i, cur_data *cur) { int varcharlen; struct tm timevar; char timestr[256]; ISC_STATUS blob_stat; isc_blob_handle blob_handle = 0; ISC_QUAD blob_id; luaL_Buffer b; char *buffer; unsigned short actual_seg_len; if( (cur->out_sqlda->sqlvar[i].sqlind != NULL) && (*(cur->out_sqlda->sqlvar[i].sqlind) != 0) ) { /* a null field? */ lua_pushnil(L); } else { switch(cur->out_sqlda->sqlvar[i].sqltype & ~1) { case SQL_VARYING: varcharlen = (int)isc_vax_integer(cur->out_sqlda->sqlvar[i].sqldata, 2); lua_pushlstring(L, cur->out_sqlda->sqlvar[i].sqldata+2, varcharlen); break; case SQL_TEXT: lua_pushlstring(L, cur->out_sqlda->sqlvar[i].sqldata, cur->out_sqlda->sqlvar[i].sqllen); break; case SQL_SHORT: lua_pushnumber(L, *(short*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_LONG: lua_pushnumber(L, *(long*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_INT64: lua_pushnumber(L, (lua_Number)*(ISC_INT64*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_FLOAT: lua_pushnumber(L, *(float*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_DOUBLE: lua_pushnumber(L, *(double*)(cur->out_sqlda->sqlvar[i].sqldata)); break; case SQL_TYPE_TIME: isc_decode_sql_time((ISC_TIME*)(cur->out_sqlda->sqlvar[i].sqldata), &timevar); strftime(timestr, 255, "%X", &timevar); lua_pushstring(L, timestr); break; case SQL_TYPE_DATE: isc_decode_sql_date((ISC_DATE*)(cur->out_sqlda->sqlvar[i].sqldata), &timevar); strftime(timestr, 255, "%x", &timevar); lua_pushstring(L, timestr); break; case SQL_TIMESTAMP: isc_decode_timestamp((ISC_TIMESTAMP*)(cur->out_sqlda->sqlvar[i].sqldata), &timevar); strftime(timestr, 255, "%x %X", &timevar); lua_pushstring(L, timestr); break; case SQL_BLOB: /* get the BLOB ID and open it */ memcpy(&blob_id, cur->out_sqlda->sqlvar[i].sqldata, sizeof(ISC_QUAD)); isc_open_blob2( cur->env->status_vector, &cur->conn->db, &cur->conn->transaction, &blob_handle, &blob_id, 0, NULL ); /* fetch the blob data */ luaL_buffinit(L, &b); buffer = luaL_prepbuffer(&b); blob_stat = isc_get_segment( cur->env->status_vector, &blob_handle, &actual_seg_len, LUAL_BUFFERSIZE, buffer ); while(blob_stat == 0 || cur->env->status_vector[1] == isc_segment) { luaL_addsize(&b, actual_seg_len); buffer = luaL_prepbuffer(&b); blob_stat = isc_get_segment( cur->env->status_vector, &blob_handle, &actual_seg_len, LUAL_BUFFERSIZE, buffer ); } /* finnished, close the BLOB */ isc_close_blob(cur->env->status_vector, &blob_handle); blob_handle = 0; luaL_pushresult(&b); break; default: lua_pushstring(L, ""); break; } } } /* ** Returns a row of data from the query ** Lua Returns: ** list of results or table of results depending on call ** nil and error message otherwise. */ static int cur_fetch (lua_State *L) { ISC_STATUS fetch_stat; int i; cur_data *cur = getcursor(L,1); const char *opts = luaL_optstring (L, 3, "n"); int num = strchr(opts, 'n') != NULL; int alpha = strchr(opts, 'a') != NULL; if ((fetch_stat = isc_dsql_fetch(cur->env->status_vector, &cur->stmt, 1, cur->out_sqlda)) == 0) { if (lua_istable (L, 2)) { /* remove the option string */ lua_settop(L, 2); /* loop through the columns */ for (i = 0; i < cur->out_sqlda->sqld; i++) { push_column(L, i, cur); if( num ) { lua_pushnumber(L, i+1); lua_pushvalue(L, -2); lua_settable(L, 2); } if( alpha ) { lua_pushlstring(L, cur->out_sqlda->sqlvar[i].aliasname, cur->out_sqlda->sqlvar[i].aliasname_length); lua_pushvalue(L, -2); lua_settable(L, 2); } lua_pop(L, 1); } /* returning given table */ return 1; } else { for (i = 0; i < cur->out_sqlda->sqld; i++) push_column(L, i, cur); /* returning a list of values */ return cur->out_sqlda->sqld; } } /* isc_dsql_fetch returns 100 if no more rows remain to be retrieved so this can be ignored */ if (fetch_stat != 100L) return return_db_error(L, cur->env->status_vector); /* last row has been fetched, close cursor */ isc_dsql_free_statement(cur->env->status_vector, &cur->stmt, DSQL_drop); if ( CHECK_DB_ERROR(cur->env->status_vector) ) return return_db_error(L, cur->env->status_vector); /* free the cursor data */ free_cur(cur); cur->closed = 1; /* remove cursor from lock count */ --cur->conn->lock; /* return sucsess */ return 0; } /* ** Returns a table of column names from the query ** Lua Returns: ** a table of column names ** nil and error message otherwise. */ static int cur_colnames (lua_State *L) { int i; XSQLVAR *var; cur_data *cur = getcursor(L,1); lua_newtable(L); for (i=1, var = cur->out_sqlda->sqlvar; i <= cur->out_sqlda->sqld; i++, var++) { lua_pushnumber(L, i); lua_pushlstring(L, var->aliasname, var->aliasname_length); lua_settable(L, -3); } return 1; } /* ** Returns a table of column types from the query ** Lua Returns: ** a table of column types ** nil and error message otherwise. */ static int cur_coltypes (lua_State *L) { int i; XSQLVAR *var; cur_data *cur = getcursor(L,1); lua_newtable(L); for (i=1, var = cur->out_sqlda->sqlvar; i <= cur->out_sqlda->sqld; i++, var++) { lua_pushnumber(L, i); switch(var->sqltype & ~1) { case SQL_VARYING: case SQL_TEXT: case SQL_TYPE_TIME: case SQL_TYPE_DATE: case SQL_TIMESTAMP: case SQL_BLOB: lua_pushstring(L, "string"); break; case SQL_SHORT: case SQL_LONG: case SQL_INT64: case SQL_FLOAT: case SQL_DOUBLE: lua_pushstring(L, "number"); break; default: lua_pushstring(L, "unknown"); break; } lua_settable(L, -3); } return 1; } /* ** Closes a cursor object ** Lua Returns: ** 1 if close was sucsessful, 0 if already closed ** nil and error message otherwise. */ static int cur_close (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata(L,1,LUASQL_CURSOR_FIREBIRD); luaL_argcheck (L, cur != NULL, 1, "cursor expected"); if(cur->closed == 0) { isc_dsql_free_statement(cur->env->status_vector, &cur->stmt, DSQL_drop); if ( CHECK_DB_ERROR(cur->env->status_vector) ) return return_db_error(L, cur->env->status_vector); /* free the cursor data */ free_cur(cur); /* remove cursor from lock count */ cur->closed = 1; --cur->conn->lock; /* check if connection can be unregistered */ if(cur->conn->lock == 0) lua_unregisterobj(L, cur->conn); /* return sucsess */ lua_pushboolean(L, 1); return 1; } lua_pushboolean(L, 0); return 1; } /* ** GCs a cursor object */ static int cur_gc (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata(L,1,LUASQL_CURSOR_FIREBIRD); luaL_argcheck (L, cur != NULL, 1, "cursor expected"); if(cur->closed == 0) { isc_dsql_free_statement(cur->env->status_vector, &cur->stmt, DSQL_drop); /* free the cursor data */ free_cur(cur); /* remove cursor from lock count */ cur->closed = 1; --cur->conn->lock; /* check if connection can be unregistered */ if(cur->conn->lock == 0) lua_unregisterobj(L, cur->conn); } return 0; } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { int i; env_data *env; env = (env_data *)lua_newuserdata (L, sizeof (env_data)); luasql_setmeta (L, LUASQL_ENVIRONMENT_FIREBIRD); /* fill in structure */ for(i=0; i<20; i++) env->status_vector[i] = 0; env->closed = 0; env->lock = 0; return 1; } /* ** Creates and returns a connection object ** Lua Input: source, user, pass ** source: data source ** user, pass: data source authentication information ** Lua Returns: ** connection object if successfull ** nil and error message otherwise. */ static int env_connect (lua_State *L) { char *dpb; int i; static char isc_tpb[] = { isc_tpb_version3, isc_tpb_write }; conn_data conn; conn_data* res_conn; env_data *env = (env_data *) getenvironment (L, 1); const char *sourcename = luaL_checkstring (L, 2); const char *username = luaL_optstring (L, 3, ""); const char *password = luaL_optstring (L, 4, ""); conn.env = env; conn.db = 0L; conn.transaction = 0L; conn.lock = 0; conn.autocommit = 0; /* Construct a database parameter buffer. */ dpb = conn.dpb_buffer; *dpb++ = isc_dpb_version1; *dpb++ = isc_dpb_num_buffers; *dpb++ = 1; *dpb++ = 90; /* add the user name and password */ *dpb++ = isc_dpb_user_name; *dpb++ = (char)strlen(username); for(i=0; i<(int)strlen(username); i++) *dpb++ = username[i]; *dpb++ = isc_dpb_password; *dpb++ = (char)strlen(password); for(i=0; i<(int)strlen(password); i++) *dpb++ = password[i]; /* the length of the dpb */ conn.dpb_length = (short)(dpb - conn.dpb_buffer); /* do the job */ isc_attach_database(env->status_vector, (short)strlen(sourcename), (char*)sourcename, &conn.db, conn.dpb_length, conn.dpb_buffer); /* an error? */ if ( CHECK_DB_ERROR(conn.env->status_vector) ) return return_db_error(L, conn.env->status_vector); /* open up the transaction handle */ isc_start_transaction( env->status_vector, &conn.transaction, 1, &conn.db, (unsigned short)sizeof(isc_tpb), isc_tpb ); /* return NULL on error */ if ( CHECK_DB_ERROR(conn.env->status_vector) ) return return_db_error(L, conn.env->status_vector); /* create the lua object and add the connection to the lock */ res_conn = (conn_data*)lua_newuserdata(L, sizeof(conn_data)); luasql_setmeta (L, LUASQL_CONNECTION_FIREBIRD); memcpy(res_conn, &conn, sizeof(conn_data)); res_conn->closed = 0; /* connect now officially open */ /* register the connection */ lua_registerobj(L, 1, env); ++env->lock; return 1; } /* ** Closes an environment object ** Lua Returns: ** 1 if close was sucsessful, 0 if already closed ** nil and error message otherwise. */ static int env_close (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_FIREBIRD); luaL_argcheck (L, env != NULL, 1, "environment expected"); /* already closed? */ if(env->closed == 1) { lua_pushboolean(L, 0); return 1; } /* check the lock */ if(env->lock > 0) return luasql_faildirect(L, "there are still open connections"); /* unregister */ lua_unregisterobj(L, env); /* mark as closed */ env->closed = 1; lua_pushboolean(L, 1); return 1; } /* ** GCs an environment object */ static int env_gc (lua_State *L) { /* nothing to be done for the FB envronment */ return 0; } /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_gc}, {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_gc}, {"close", conn_close}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {"escape", conn_escape}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_gc}, {"close", cur_close}, {"fetch", cur_fetch}, {"getcoltypes", cur_coltypes}, {"getcolnames", cur_colnames}, {NULL, NULL}, }; luasql_createmeta (L, LUASQL_ENVIRONMENT_FIREBIRD, environment_methods); luasql_createmeta (L, LUASQL_CONNECTION_FIREBIRD, connection_methods); luasql_createmeta (L, LUASQL_CURSOR_FIREBIRD, cursor_methods); lua_pop (L, 3); } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_firebird (lua_State *L) { struct luaL_Reg driver[] = { {"firebird", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable (L); luaL_setfuncs (L, driver, 0); luasql_set_info (L); return 1; } keplerproject-luasql-c527024/src/ls_mysql.c000066400000000000000000000371161175743000500207420ustar00rootroot00000000000000/* ** LuaSQL, MySQL driver ** Authors: Eduardo Quintao ** See Copyright Notice in license.html ** $Id: ls_mysql.c,v 1.31 2009/02/07 23:16:23 tomas Exp $ */ #include #include #include #include #include #ifdef WIN32 #include #define NO_CLIENT_LONG_LONG #endif #include "mysql.h" #include "lua.h" #include "lauxlib.h" #include "luasql.h" #define LUASQL_ENVIRONMENT_MYSQL "MySQL environment" #define LUASQL_CONNECTION_MYSQL "MySQL connection" #define LUASQL_CURSOR_MYSQL "MySQL cursor" /* For compat with old version 4.0 */ #if (MYSQL_VERSION_ID < 40100) #define MYSQL_TYPE_VAR_STRING FIELD_TYPE_VAR_STRING #define MYSQL_TYPE_STRING FIELD_TYPE_STRING #define MYSQL_TYPE_DECIMAL FIELD_TYPE_DECIMAL #define MYSQL_TYPE_SHORT FIELD_TYPE_SHORT #define MYSQL_TYPE_LONG FIELD_TYPE_LONG #define MYSQL_TYPE_FLOAT FIELD_TYPE_FLOAT #define MYSQL_TYPE_DOUBLE FIELD_TYPE_DOUBLE #define MYSQL_TYPE_LONGLONG FIELD_TYPE_LONGLONG #define MYSQL_TYPE_INT24 FIELD_TYPE_INT24 #define MYSQL_TYPE_YEAR FIELD_TYPE_YEAR #define MYSQL_TYPE_TINY FIELD_TYPE_TINY #define MYSQL_TYPE_TINY_BLOB FIELD_TYPE_TINY_BLOB #define MYSQL_TYPE_MEDIUM_BLOB FIELD_TYPE_MEDIUM_BLOB #define MYSQL_TYPE_LONG_BLOB FIELD_TYPE_LONG_BLOB #define MYSQL_TYPE_BLOB FIELD_TYPE_BLOB #define MYSQL_TYPE_DATE FIELD_TYPE_DATE #define MYSQL_TYPE_NEWDATE FIELD_TYPE_NEWDATE #define MYSQL_TYPE_DATETIME FIELD_TYPE_DATETIME #define MYSQL_TYPE_TIME FIELD_TYPE_TIME #define MYSQL_TYPE_TIMESTAMP FIELD_TYPE_TIMESTAMP #define MYSQL_TYPE_ENUM FIELD_TYPE_ENUM #define MYSQL_TYPE_SET FIELD_TYPE_SET #define MYSQL_TYPE_NULL FIELD_TYPE_NULL #define mysql_commit(_) ((void)_) #define mysql_rollback(_) ((void)_) #define mysql_autocommit(_,__) ((void)_) #endif typedef struct { short closed; } env_data; typedef struct { short closed; int env; /* reference to environment */ MYSQL *my_conn; } conn_data; typedef struct { short closed; int conn; /* reference to connection */ int numcols; /* number of columns */ int colnames, coltypes; /* reference to column information tables */ MYSQL_RES *my_res; } cur_data; LUASQL_API int luaopen_luasql_mysql (lua_State *L); /* ** Check for valid environment. */ static env_data *getenvironment (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_MYSQL); luaL_argcheck (L, env != NULL, 1, "environment expected"); luaL_argcheck (L, !env->closed, 1, "environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_MYSQL); luaL_argcheck (L, conn != NULL, 1, "connection expected"); luaL_argcheck (L, !conn->closed, 1, "connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_MYSQL); luaL_argcheck (L, cur != NULL, 1, "cursor expected"); luaL_argcheck (L, !cur->closed, 1, "cursor is closed"); return cur; } /* ** Push the value of #i field of #tuple row. */ static void pushvalue (lua_State *L, void *row, long int len) { if (row == NULL) lua_pushnil (L); else lua_pushlstring (L, row, len); } /* ** Get the internal database type of the given column. */ static char *getcolumntype (enum enum_field_types type) { switch (type) { case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: return "string"; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_YEAR: case MYSQL_TYPE_TINY: return "number"; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: return "binary"; case MYSQL_TYPE_DATE: case MYSQL_TYPE_NEWDATE: return "date"; case MYSQL_TYPE_DATETIME: return "datetime"; case MYSQL_TYPE_TIME: return "time"; case MYSQL_TYPE_TIMESTAMP: return "timestamp"; case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: return "set"; case MYSQL_TYPE_NULL: return "null"; default: return "undefined"; } } /* ** Creates the lists of fields names and fields types. */ static void create_colinfo (lua_State *L, cur_data *cur) { MYSQL_FIELD *fields; char typename[50]; int i; fields = mysql_fetch_fields(cur->my_res); lua_newtable (L); /* names */ lua_newtable (L); /* types */ for (i = 1; i <= cur->numcols; i++) { lua_pushstring (L, fields[i-1].name); lua_rawseti (L, -3, i); sprintf (typename, "%.20s(%ld)", getcolumntype (fields[i-1].type), fields[i-1].length); lua_pushstring(L, typename); lua_rawseti (L, -2, i); } /* Stores the references in the cursor structure */ cur->coltypes = luaL_ref (L, LUA_REGISTRYINDEX); cur->colnames = luaL_ref (L, LUA_REGISTRYINDEX); } /* ** Closes the cursos and nullify all structure fields. */ static int cur_nullify (lua_State *L, cur_data *cur) { /* Nullify structure fields. */ cur->closed = 1; mysql_free_result(cur->my_res); luaL_unref (L, LUA_REGISTRYINDEX, cur->conn); luaL_unref (L, LUA_REGISTRYINDEX, cur->colnames); luaL_unref (L, LUA_REGISTRYINDEX, cur->coltypes); } /* ** Get another row of the given cursor. */ static int cur_fetch (lua_State *L) { cur_data *cur = getcursor (L); MYSQL_RES *res = cur->my_res; unsigned long *lengths; MYSQL_ROW row = mysql_fetch_row(res); if (row == NULL) { cur_nullify (L, cur); lua_pushnil(L); /* no more results */ return 1; } lengths = mysql_fetch_lengths(res); if (lua_istable (L, 2)) { const char *opts = luaL_optstring (L, 3, "n"); if (strchr (opts, 'n') != NULL) { /* Copy values to numerical indices */ int i; for (i = 0; i < cur->numcols; i++) { pushvalue (L, row[i], lengths[i]); lua_rawseti (L, 2, i+1); } } if (strchr (opts, 'a') != NULL) { int i; /* Check if colnames exists */ if (cur->colnames == LUA_NOREF) create_colinfo(L, cur); lua_rawgeti (L, LUA_REGISTRYINDEX, cur->colnames);/* Push colnames*/ /* Copy values to alphanumerical indices */ for (i = 0; i < cur->numcols; i++) { lua_rawgeti(L, -1, i+1); /* push the field name */ /* Actually push the value */ pushvalue (L, row[i], lengths[i]); lua_rawset (L, 2); } /* lua_pop(L, 1); Pops colnames table. Not needed */ } lua_pushvalue(L, 2); return 1; /* return table */ } else { int i; luaL_checkstack (L, cur->numcols, LUASQL_PREFIX"too many columns"); for (i = 0; i < cur->numcols; i++) pushvalue (L, row[i], lengths[i]); return cur->numcols; /* return #numcols values */ } } /* ** Cursor object collector function */ static int cur_gc (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_MYSQL); if (cur != NULL && !(cur->closed)) cur_nullify (L, cur); return 0; } /* ** Close the cursor on top of the stack. ** Return 1 */ static int cur_close (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_MYSQL); luaL_argcheck (L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); if (cur->closed) { lua_pushboolean (L, 0); return 1; } cur_nullify (L, cur); lua_pushboolean (L, 1); return 1; } /* ** Pushes a column information table on top of the stack. ** If the table isn't built yet, call the creator function and stores ** a reference to it on the cursor structure. */ static void _pushtable (lua_State *L, cur_data *cur, size_t off) { int *ref = (int *)((char *)cur + off); /* If colnames or coltypes do not exist, create both. */ if (*ref == LUA_NOREF) create_colinfo(L, cur); /* Pushes the right table (colnames or coltypes) */ lua_rawgeti (L, LUA_REGISTRYINDEX, *ref); } #define pushtable(L,c,m) (_pushtable(L,c,offsetof(cur_data,m))) /* ** Return the list of field names. */ static int cur_getcolnames (lua_State *L) { pushtable (L, getcursor(L), colnames); return 1; } /* ** Return the list of field types. */ static int cur_getcoltypes (lua_State *L) { pushtable (L, getcursor(L), coltypes); return 1; } /* ** Push the number of rows. */ static int cur_numrows (lua_State *L) { lua_pushnumber (L, (lua_Number)mysql_num_rows (getcursor(L)->my_res)); return 1; } /* ** Create a new Cursor object and push it on top of the stack. */ static int create_cursor (lua_State *L, int conn, MYSQL_RES *result, int cols) { cur_data *cur = (cur_data *)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_MYSQL); /* fill in structure */ cur->closed = 0; cur->conn = LUA_NOREF; cur->numcols = cols; cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->my_res = result; lua_pushvalue (L, conn); cur->conn = luaL_ref (L, LUA_REGISTRYINDEX); return 1; } static int conn_gc (lua_State *L) { conn_data *conn=(conn_data *)luaL_checkudata(L, 1, LUASQL_CONNECTION_MYSQL); if (conn != NULL && !(conn->closed)) { /* Nullify structure fields. */ conn->closed = 1; luaL_unref (L, LUA_REGISTRYINDEX, conn->env); mysql_close (conn->my_conn); } return 0; } /* ** Close a Connection object. */ static int conn_close (lua_State *L) { conn_data *conn=(conn_data *)luaL_checkudata(L, 1, LUASQL_CONNECTION_MYSQL); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); if (conn->closed) { lua_pushboolean (L, 0); return 1; } conn_gc (L); lua_pushboolean (L, 1); return 1; } static int escape_string (lua_State *L) { size_t size, new_size; conn_data *conn = getconnection (L); const char *from = luaL_checklstring(L, 2, &size); char *to; to = (char*)malloc(sizeof(char) * (2 * size + 1)); if(to) { new_size = mysql_real_escape_string(conn->my_conn, to, from, size); lua_pushlstring(L, to, new_size); free(to); return 1; } luaL_error(L, "could not allocate escaped string"); return 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); size_t st_len; const char *statement = luaL_checklstring (L, 2, &st_len); if (mysql_real_query(conn->my_conn, statement, st_len)) /* error executing query */ return luasql_failmsg(L, "error executing query. MySQL: ", mysql_error(conn->my_conn)); else { MYSQL_RES *res = mysql_store_result(conn->my_conn); unsigned int num_cols = mysql_field_count(conn->my_conn); if (res) { /* tuples returned */ return create_cursor (L, 1, res, num_cols); } else { /* mysql_use_result() returned nothing; should it have? */ if(num_cols == 0) { /* no tuples returned */ /* query does not return data (it was not a SELECT) */ lua_pushnumber(L, mysql_affected_rows(conn->my_conn)); return 1; } else /* mysql_use_result() should have returned data */ return luasql_failmsg(L, "error retrieving result. MySQL: ", mysql_error(conn->my_conn)); } } } /* ** Commit the current transaction. */ static int conn_commit (lua_State *L) { conn_data *conn = getconnection (L); lua_pushboolean(L, !mysql_commit(conn->my_conn)); return 1; } /* ** Rollback the current transaction. */ static int conn_rollback (lua_State *L) { conn_data *conn = getconnection (L); lua_pushboolean(L, !mysql_rollback(conn->my_conn)); return 1; } /* ** Set "auto commit" property of the connection. Modes ON/OFF */ static int conn_setautocommit (lua_State *L) { conn_data *conn = getconnection (L); if (lua_toboolean (L, 2)) { mysql_autocommit(conn->my_conn, 1); /* Set it ON */ } else { mysql_autocommit(conn->my_conn, 0); } lua_pushboolean(L, 1); return 1; } /* ** Get Last auto-increment id generated */ static int conn_getlastautoid (lua_State *L) { conn_data *conn = getconnection(L); lua_pushnumber(L, mysql_insert_id(conn->my_conn)); return 1; } /* ** Create a new Connection object and push it on top of the stack. */ static int create_connection (lua_State *L, int env, MYSQL *const my_conn) { conn_data *conn = (conn_data *)lua_newuserdata(L, sizeof(conn_data)); luasql_setmeta (L, LUASQL_CONNECTION_MYSQL); /* fill in structure */ conn->closed = 0; conn->env = LUA_NOREF; conn->my_conn = my_conn; lua_pushvalue (L, env); conn->env = luaL_ref (L, LUA_REGISTRYINDEX); return 1; } /* ** Connects to a data source. ** param: one string for each connection parameter, said ** datasource, username, password, host and port. */ 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 *host = luaL_optstring(L, 5, NULL); const int port = luaL_optint(L, 6, 0); MYSQL *conn; getenvironment(L); /* validade environment */ /* Try to init the connection object. */ conn = mysql_init(NULL); if (conn == NULL) return luasql_faildirect(L, "error connecting: Out of memory."); if (!mysql_real_connect(conn, host, username, password, sourcename, port, NULL, 0)) { char error_msg[100]; strncpy (error_msg, mysql_error(conn), 99); mysql_close (conn); /* Close conn if connect failed */ return luasql_failmsg (L, "error connecting to database. MySQL: ", error_msg); } return create_connection(L, 1, conn); } /* ** */ static int env_gc (lua_State *L) { env_data *env= (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_MYSQL); if (env != NULL && !(env->closed)) env->closed = 1; return 0; } /* ** Close environment object. */ static int env_close (lua_State *L) { env_data *env= (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_MYSQL); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); if (env->closed) { lua_pushboolean (L, 0); return 1; } env->closed = 1; lua_pushboolean (L, 1); return 1; } /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_gc}, {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_gc}, {"close", conn_close}, {"escape", escape_string}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {"getlastautoid", conn_getlastautoid}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_gc}, {"close", cur_close}, {"getcolnames", cur_getcolnames}, {"getcoltypes", cur_getcoltypes}, {"fetch", cur_fetch}, {"numrows", cur_numrows}, {NULL, NULL}, }; luasql_createmeta (L, LUASQL_ENVIRONMENT_MYSQL, environment_methods); luasql_createmeta (L, LUASQL_CONNECTION_MYSQL, connection_methods); luasql_createmeta (L, LUASQL_CURSOR_MYSQL, cursor_methods); lua_pop (L, 3); } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { env_data *env = (env_data *)lua_newuserdata(L, sizeof(env_data)); luasql_setmeta (L, LUASQL_ENVIRONMENT_MYSQL); /* fill in structure */ env->closed = 0; return 1; } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_mysql (lua_State *L) { struct luaL_Reg driver[] = { {"mysql", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable(L); luaL_setfuncs(L, driver, 0); luasql_set_info (L); lua_pushliteral (L, "_MYSQLVERSION"); lua_pushliteral (L, MYSQL_SERVER_VERSION); lua_settable (L, -3); return 1; } keplerproject-luasql-c527024/src/ls_oci8.c000066400000000000000000000544111175743000500204340ustar00rootroot00000000000000/* ** LuaSQL, Oracle driver ** Authors: Tomas Guisasola, Leonardo Godinho ** See Copyright Notice in license.html ** $Id: ls_oci8.c,v 1.31 2009/02/07 23:16:23 tomas Exp $ */ #include #include #include #include #include #include "oci.h" #include "oratypes.h" #include "ociapr.h" #include "ocidem.h" #include "lua.h" #include "lauxlib.h" #include "luasql.h" #define LUASQL_ENVIRONMENT_OCI8 "Oracle environment" #define LUASQL_CONNECTION_OCI8 "Oracle connection" #define LUASQL_CURSOR_OCI8 "Oracle cursor" typedef struct { short closed; int conn_counter; OCIEnv *envhp; OCIError *errhp; /* !!! */ } env_data; typedef struct { short closed; short loggedon; short auto_commit; /* 0 for manual commit */ int cur_counter; int env; /* reference to environment */ OCISvcCtx *svchp; /* service handle */ OCIError *errhp; /* !!! */ } conn_data; typedef union { int i; char *s; double d; } column_value; typedef struct { ub2 type; /* database type */ text *name; /* column name */ ub4 namelen; /* column name length */ ub2 max; /* maximum size */ sb2 null; /* is null? */ OCIDefine *define; /* define handle */ column_value val; } column_data; typedef struct { short closed; int conn; /* reference to connection */ int numcols; /* number of columns */ int colnames, coltypes; /* reference to column info tables */ int curr_tuple; /* next tuple to be read */ char *text; /* text of SQL statement */ OCIStmt *stmthp; /* statement handle */ OCIError *errhp; /* !!! */ column_data *cols; /* array of columns */ } cur_data; int checkerr (lua_State *L, sword status, OCIError *errhp); #define ASSERT(L,exp,err) {sword s = exp; if (s) return checkerr (L, s, err);} LUASQL_API int luaopen_luasql_oci8 (lua_State *L); /* ** Check for valid environment. */ static env_data *getenvironment (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_OCI8); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); luaL_argcheck (L, !env->closed, 1, LUASQL_PREFIX"environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_OCI8); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); luaL_argcheck (L, !conn->closed, 1, LUASQL_PREFIX"connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_OCI8); luaL_argcheck (L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); luaL_argcheck (L, !cur->closed, 1, LUASQL_PREFIX"cursor is closed"); return cur; } /* ** Push nil plus an error message. */ int checkerr (lua_State *L, sword status, OCIError *errhp) { lua_pushnil (L); switch (status) { case OCI_SUCCESS: lua_pushnil (L); /* !!!!!!!!!!!!! */ break; case OCI_SUCCESS_WITH_INFO: lua_pushstring (L, LUASQL_PREFIX"Success with info!"); break; case OCI_NEED_DATA: lua_pushstring (L, LUASQL_PREFIX"OCI_NEED_DATA"); break; case OCI_NO_DATA: lua_pushstring (L, LUASQL_PREFIX"OCI_NODATA"); break; case OCI_ERROR: { text errbuf[512]; sb4 errcode = 0; OCIErrorGet (errhp, (ub4) 1, (text *) NULL, &errcode, errbuf, (ub4) sizeof (errbuf), OCI_HTYPE_ERROR); lua_pushstring (L, LUASQL_PREFIX); lua_pushstring (L, errbuf); lua_concat (L, 2); break; } case OCI_INVALID_HANDLE: lua_pushstring (L, LUASQL_PREFIX"OCI_INVALID_HANDLE"); break; case OCI_STILL_EXECUTING: lua_pushstring (L, LUASQL_PREFIX"OCI_STILL_EXECUTE"); break; case OCI_CONTINUE: lua_pushstring (L, LUASQL_PREFIX"OCI_CONTINUE"); break; } return 2; } /* ** Copy the column name to the column structure and convert it to lower case. */ static void copy_column_name (column_data *col, text *name) { unsigned int i; col->name = (text *)malloc (col->namelen); memcpy (col->name, name, col->namelen); for (i = 0; i < col->namelen; i++) col->name[i] = tolower (col->name[i]); } /* ** Alloc buffers for column values. */ static int alloc_column_buffer (lua_State *L, cur_data *cur, int i) { /* column index ranges from 1 to numcols */ /* C array index ranges from 0 to numcols-1 */ column_data *col = &(cur->cols[i-1]); OCIParam *param; text *name; ASSERT (L, OCIParamGet (cur->stmthp, OCI_HTYPE_STMT, cur->errhp, (dvoid **)¶m, i), cur->errhp); ASSERT (L, OCIAttrGet (param, OCI_DTYPE_PARAM, (dvoid *)&(name), (ub4 *)&(col->namelen), OCI_ATTR_NAME, cur->errhp), cur->errhp); copy_column_name (col, name); ASSERT (L, OCIAttrGet (param, OCI_DTYPE_PARAM, (dvoid *)&(col->type), (ub4 *)0, OCI_ATTR_DATA_TYPE, cur->errhp), cur->errhp); switch (col->type) { case SQLT_CHR: case SQLT_STR: case SQLT_VCS: case SQLT_AFC: case SQLT_AVC: ASSERT (L, OCIAttrGet (param, OCI_DTYPE_PARAM, (dvoid *)&(col->max), 0, OCI_ATTR_DATA_SIZE, cur->errhp), cur->errhp); col->val.s = calloc (col->max + 1, sizeof(col->val.s)); ASSERT (L, OCIDefineByPos (cur->stmthp, &(col->define), cur->errhp, (ub4)i, col->val.s, col->max+1, SQLT_STR /*col->type*/, (dvoid *)&(col->null), (ub2 *)0, (ub2 *)0, (ub4) OCI_DEFAULT), cur->errhp); break; case SQLT_NUM: case SQLT_FLT: case SQLT_INT: /* case SQLT_UIN: */ ASSERT (L, OCIDefineByPos (cur->stmthp, &(col->define), cur->errhp, (ub4)i, &(col->val.d), sizeof(col->val.d), SQLT_FLT, (dvoid *)&(col->null), (ub2 *)0, (ub2 *)0, (ub4) OCI_DEFAULT), cur->errhp); break; case SQLT_CLOB: { env_data *env; conn_data *conn; lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); conn = (conn_data *)lua_touserdata (L, -1); lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env); env = (env_data *)lua_touserdata (L, -1); lua_pop (L, 2); ASSERT (L, OCIDescriptorAlloc (env->envhp, (dvoid *)&(col->val.s), OCI_DTYPE_LOB, (size_t)0, (dvoid **)0), cur->errhp); ASSERT (L, OCIDefineByPos (cur->stmthp, &(col->define), cur->errhp, (ub4)i, &(col->val.s), (sb4)sizeof(dvoid *), SQLT_CLOB, (dvoid *)&(col->null), (ub2 *)0, (ub2 *)0, OCI_DEFAULT), cur->errhp); break; } default: luaL_error (L, LUASQL_PREFIX"invalid type %d #%d", col->type, i); break; } return 0; } /* ** Deallocate column buffers. */ static int free_column_buffers (lua_State *L, cur_data *cur, int i) { /* column index ranges from 1 to numcols */ /* C array index ranges from 0 to numcols-1 */ column_data *col = &(cur->cols[i-1]); free (col->name); switch (col->type) { case SQLT_INT: case SQLT_FLT: case SQLT_NUM: break; case SQLT_CHR: case SQLT_STR: case SQLT_VCS: case SQLT_AFC: case SQLT_AVC: free(col->val.s); break; case SQLT_CLOB: ASSERT (L, OCIDescriptorFree (col->val.s, OCI_DTYPE_LOB), cur->errhp); break; default: luaL_error (L, LUASQL_PREFIX"unknown type"); /*printf("free_buffers(): Unknow Type: %d count: %d\n",cols.item[count].type, count );*/ break; } return 0; } /* ** Push a value on top of the stack. */ static int pushvalue (lua_State *L, cur_data *cur, int i) { /* column index ranges from 1 to numcols */ /* C array index ranges from 0 to numcols-1 */ column_data *col = &(cur->cols[i-1]); if (col->null) { /* Oracle NULL => Lua nil */ lua_pushnil (L); return 1; } switch (col->type) { case SQLT_NUM: case SQLT_INT: case SQLT_FLT: lua_pushnumber (L, col->val.d); break; case SQLT_CHR: case SQLT_STR: case SQLT_VCS: case SQLT_AFC: case SQLT_AVC: lua_pushstring (L, (char *)(col->val.s)); break; case SQLT_CLOB: { ub4 lob_len; conn_data *conn; env_data *env; lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); conn = lua_touserdata (L, -1); lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env); env = lua_touserdata (L, -1); lua_pop (L, 2); ASSERT (L, OCILobGetLength (conn->svchp, cur->errhp, (OCILobLocator *)col->val.s, &lob_len), cur->errhp); if (lob_len > 0) { char *lob_buffer=malloc(lob_len); ub4 amount = lob_len; ASSERT(L, OCILobRead(conn->svchp, cur->errhp, (OCILobLocator *) col->val.s, &amount, (ub4) 1, (dvoid *) lob_buffer, (ub4) lob_len, (dvoid *)0, (sb4 (*) (dvoid *, CONST dvoid *, ub4, ub1)) 0, (ub2) 0, (ub1) SQLCS_IMPLICIT), cur->errhp); lua_pushlstring (L, lob_buffer, amount); free(lob_buffer); } else { lua_pushstring (L, ""); } break; } default: luaL_error (L, LUASQL_PREFIX"unexpected error"); } return 1; } /* ** Get another row of the given cursor. */ static int cur_fetch (lua_State *L) { cur_data *cur = getcursor (L); sword status = OCIStmtFetch (cur->stmthp, cur->errhp, 1, OCI_FETCH_NEXT, OCI_DEFAULT); if (status == OCI_NO_DATA) { /* No more rows */ lua_pushnil (L); return 1; } else if (status != OCI_SUCCESS) { /* Error */ return checkerr (L, status, cur->errhp); } if (lua_istable (L, 2)) { int i; const char *opts = luaL_optstring (L, 3, "n"); if (strchr (opts, 'n') != NULL) /* Copy values to numerical indices */ for (i = 1; i <= cur->numcols; i++) { int ret = pushvalue (L, cur, i); if (ret != 1) return ret; lua_rawseti (L, 2, i); } if (strchr (opts, 'a') != NULL) /* Copy values to alphanumerical indices */ for (i = 1; i <= cur->numcols; i++) { column_data *col = &(cur->cols[i-1]); int ret; lua_pushlstring (L, col->name, col->namelen); if ((ret = pushvalue (L, cur, i)) != 1) return ret; lua_rawset (L, 2); } lua_pushvalue(L, 2); return 1; /* return table */ } else { int i; luaL_checkstack (L, cur->numcols, LUASQL_PREFIX"too many columns"); for (i = 1; i <= cur->numcols; i++) { int ret = pushvalue (L, cur, i); if (ret != 1) return ret; } return cur->numcols; /* return #numcols values */ } } /* ** Close the cursor on top of the stack. ** Return 1 */ static int cur_close (lua_State *L) { int i; conn_data *conn; cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_OCI8); luaL_argcheck (L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); if (cur->closed) { lua_pushboolean (L, 0); return 1; } /* Deallocate buffers. */ for (i = 1; i <= cur->numcols; i++) { int ret = free_column_buffers (L, cur, i); if (ret) return ret; } free (cur->cols); free (cur->text); /* Nullify structure fields. */ cur->closed = 1; if (cur->stmthp) OCIHandleFree ((dvoid *)cur->stmthp, OCI_HTYPE_STMT); if (cur->errhp) OCIHandleFree ((dvoid *)cur->errhp, OCI_HTYPE_ERROR); /* Decrement cursor counter on connection object */ lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); conn = lua_touserdata (L, -1); conn->cur_counter--; luaL_unref (L, LUA_REGISTRYINDEX, cur->conn); luaL_unref (L, LUA_REGISTRYINDEX, cur->colnames); luaL_unref (L, LUA_REGISTRYINDEX, cur->coltypes); lua_pushboolean (L, 1); return 1; } /* ** Return the list of field names as a table on top of the stack. */ static int cur_getcolnames (lua_State *L) { cur_data *cur = getcursor (L); if (cur->colnames != LUA_NOREF) lua_rawgeti (L, LUA_REGISTRYINDEX, cur->colnames); else { int i; lua_newtable (L); for (i = 1; i <= cur->numcols; i++) { column_data *col = &(cur->cols[i-1]); lua_pushlstring (L, col->name, col->namelen); lua_rawseti (L, -2, i); } lua_pushvalue (L, -1); cur->colnames = luaL_ref (L, LUA_REGISTRYINDEX); } return 1; } /* ** */ static char *getcolumntype (column_data *col) { switch (col->type) { case SQLT_CHR: case SQLT_STR: case SQLT_VCS: case SQLT_AFC: case SQLT_AVC: return "string"; case SQLT_NUM: case SQLT_FLT: case SQLT_INT: /* case SQLT_UIN: */ return "number"; case SQLT_CLOB: return "string"; default: return ""; } } /* ** Return the list of field types as a table on top of the stack. */ static int cur_getcoltypes (lua_State *L) { cur_data *cur = getcursor (L); if (cur->coltypes != LUA_NOREF) lua_rawgeti (L, LUA_REGISTRYINDEX, cur->coltypes); else { int i; lua_newtable (L); for (i = 1; i <= cur->numcols; i++) { column_data *col = &(cur->cols[i-1]); lua_pushnumber (L, i); lua_pushstring (L, getcolumntype (col)); lua_rawset (L, -3); } lua_pushvalue (L, -1); cur->coltypes = luaL_ref (L, LUA_REGISTRYINDEX); } return 1; } /* ** Push the number of rows. */ static int cur_numrows (lua_State *L) { int n; cur_data *cur = getcursor (L); ASSERT (L, OCIAttrGet ((dvoid *) cur->stmthp, OCI_HTYPE_STMT, (dvoid *)&n, (ub4)0, OCI_ATTR_NUM_ROWS, cur->errhp), cur->errhp); lua_pushnumber (L, n); return 1; } /* ** Close a Connection object. */ static int conn_close (lua_State *L) { env_data *env; conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_OCI8); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); if (conn->closed) { lua_pushboolean (L, 0); return 1; } if (conn->cur_counter > 0) return luaL_error (L, LUASQL_PREFIX"there are open cursors"); /* Nullify structure fields. */ conn->closed = 1; if (conn->svchp) { if (conn->loggedon) OCILogoff (conn->svchp, conn->errhp); else OCIHandleFree ((dvoid *)conn->svchp, OCI_HTYPE_SVCCTX); } if (conn->errhp) OCIHandleFree ((dvoid *)conn->errhp, OCI_HTYPE_ERROR); /* Decrement connection counter on environment object */ lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env); env = lua_touserdata (L, -1); env->conn_counter--; luaL_unref (L, LUA_REGISTRYINDEX, conn->env); lua_pushboolean (L, 1); return 1; } /* ** Create a new Cursor object and push it on top of the stack. */ static int create_cursor (lua_State *L, int o, conn_data *conn, OCIStmt *stmt, const char *text) { int i; env_data *env; cur_data *cur = (cur_data *)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_OCI8); conn->cur_counter++; /* fill in structure */ cur->closed = 0; cur->numcols = 0; cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->curr_tuple = 0; cur->stmthp = stmt; cur->errhp = NULL; cur->cols = NULL; cur->text = strdup (text); lua_pushvalue (L, o); cur->conn = luaL_ref (L, LUA_REGISTRYINDEX); /* error handler */ lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env); env = lua_touserdata (L, -1); lua_pop (L, 1); ASSERT (L, OCIHandleAlloc((dvoid *) env->envhp, (dvoid **) &(cur->errhp), (ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0), conn->errhp); /* get number of columns */ ASSERT (L, OCIAttrGet ((dvoid *)stmt, (ub4)OCI_HTYPE_STMT, (dvoid *)&cur->numcols, (ub4 *)0, (ub4)OCI_ATTR_PARAM_COUNT, cur->errhp), cur->errhp); cur->cols = (column_data *)malloc (sizeof(column_data) * cur->numcols); /* define output variables */ /* Oracle and Lua column indices ranges from 1 to numcols */ /* C array indices ranges from 0 to numcols-1 */ for (i = 1; i <= cur->numcols; i++) { int ret = alloc_column_buffer (L, cur, i); if (ret) return ret; } return 1; } /* ** 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) { env_data *env; conn_data *conn = getconnection (L); const char *statement = luaL_checkstring (L, 2); sword status; ub4 prefetch = 0; ub4 iters; ub4 mode; ub2 type; OCIStmt *stmthp; /* get environment */ lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env); if (!lua_isuserdata (L, -1)) luaL_error(L,LUASQL_PREFIX"invalid environment in connection!"); env = (env_data *)lua_touserdata (L, -1); /* statement handle */ ASSERT (L, OCIHandleAlloc ((dvoid *)env->envhp, (dvoid **)&stmthp, OCI_HTYPE_STMT, (size_t)0, (dvoid **)0), conn->errhp); ASSERT (L, OCIAttrSet ((dvoid *)stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&prefetch, (ub4)0, (ub4)OCI_ATTR_PREFETCH_ROWS, conn->errhp), conn->errhp); ASSERT (L, OCIStmtPrepare (stmthp, conn->errhp, (text *)statement, (ub4) strlen(statement), (ub4) OCI_NTV_SYNTAX, (ub4) OCI_DEFAULT), conn->errhp); /* statement type */ ASSERT (L, OCIAttrGet ((dvoid *)stmthp, (ub4) OCI_HTYPE_STMT, (dvoid *)&type, (ub4 *)0, (ub4)OCI_ATTR_STMT_TYPE, conn->errhp), conn->errhp); if (type == OCI_STMT_SELECT) iters = 0; else iters = 1; if (conn->auto_commit) mode = OCI_COMMIT_ON_SUCCESS; else mode = OCI_DEFAULT; /* execute statement */ status = OCIStmtExecute (conn->svchp, stmthp, conn->errhp, iters, (ub4)0, (CONST OCISnapshot *)NULL, (OCISnapshot *)NULL, mode); if (status && (status != OCI_NO_DATA)) { OCIHandleFree ((dvoid *)stmthp, OCI_HTYPE_STMT); return checkerr (L, status, conn->errhp); } if (type == OCI_STMT_SELECT) { /* create cursor */ return create_cursor (L, 1, conn, stmthp, statement); } else { /* return number of rows */ int rows_affected; ASSERT (L, OCIAttrGet ((dvoid *)stmthp, (ub4)OCI_HTYPE_STMT, (dvoid *)&rows_affected, (ub4 *)0, (ub4)OCI_ATTR_ROW_COUNT, conn->errhp), conn->errhp); OCIHandleFree ((dvoid *)stmthp, OCI_HTYPE_STMT); lua_pushnumber (L, rows_affected); return 1; } } /* ** Commit the current transaction. */ static int conn_commit (lua_State *L) { conn_data *conn = getconnection (L); ASSERT (L, OCITransCommit (conn->svchp, conn->errhp, OCI_DEFAULT), conn->errhp); /* if (conn->auto_commit == 0) ASSERT (L, OCITransStart (conn->svchp, conn->errhp... */ return 0; } /* ** Rollback the current transaction. */ static int conn_rollback (lua_State *L) { conn_data *conn = getconnection (L); ASSERT (L, OCITransRollback (conn->svchp, conn->errhp, OCI_DEFAULT), conn->errhp); /* if (conn->auto_commit == 0) sql_begin(conn); */ return 0; } /* ** Set "auto commit" property of the connection. ** If 'true', then rollback current transaction. ** If 'false', then start a new transaction. */ static int conn_setautocommit (lua_State *L) { conn_data *conn = getconnection (L); if (lua_toboolean (L, 2)) { conn->auto_commit = 1; /* Undo active transaction. */ ASSERT (L, OCITransRollback (conn->svchp, conn->errhp, OCI_DEFAULT), conn->errhp); } else { conn->auto_commit = 0; /* sql_begin(conn);*/ } lua_pushboolean(L, 1); return 1; } /* ** Connects to a data source. */ static int env_connect (lua_State *L) { env_data *env = getenvironment (L); const char *sourcename = luaL_checkstring(L, 2); const char *username = luaL_optstring(L, 3, NULL); const char *password = luaL_optstring(L, 4, NULL); /* Sizes of strings */ size_t snlen = strlen(sourcename); size_t userlen = (username) ? strlen(username) : 0; size_t passlen = (password) ? strlen(password) : 0; /* Alloc connection object */ conn_data *conn = (conn_data *)lua_newuserdata(L, sizeof(conn_data)); /* fill in structure */ luasql_setmeta (L, LUASQL_CONNECTION_OCI8); conn->env = LUA_NOREF; conn->closed = 1; conn->auto_commit = 1; conn->cur_counter = 0; conn->loggedon = 0; conn->svchp = NULL; conn->errhp = NULL; lua_pushvalue (L, 1); conn->env = luaL_ref (L, LUA_REGISTRYINDEX); /* error handler */ ASSERT (L, OCIHandleAlloc((dvoid *) env->envhp, (dvoid **) &(conn->errhp), /* !!! */ (ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0), env->errhp); /* service handler */ /*ASSERT (L, OCIHandleAlloc((dvoid *) env->envhp, (dvoid **) &(conn->svchp), (ub4) OCI_HTYPE_SVCCTX, (size_t) 0, (dvoid **) 0), conn->errhp); */ /* login */ ASSERT (L, OCILogon(env->envhp, conn->errhp, &(conn->svchp), (CONST text*)username, userlen, (CONST text*)password, passlen, (CONST text*)sourcename, snlen), conn->errhp); conn->closed = 0; env->conn_counter++; conn->loggedon = 1; return 1; } /* ** Close environment object. */ static int env_close (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_OCI8); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); if (env->closed) { lua_pushboolean (L, 0); return 1; } if (env->conn_counter > 0) return luaL_error (L, LUASQL_PREFIX"there are open connections"); env->closed = 1; /* desalocar: env->errhp e env->envhp */ if (env->envhp) OCIHandleFree ((dvoid *)env->envhp, OCI_HTYPE_ENV); if (env->errhp) OCIHandleFree ((dvoid *)env->errhp, OCI_HTYPE_ERROR); lua_pushboolean (L, 1); return 1; } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { env_data *env = (env_data *)lua_newuserdata(L, sizeof(env_data)); luasql_setmeta (L, LUASQL_ENVIRONMENT_OCI8); /* fill in structure */ env->closed = 0; env->conn_counter = 0; env->envhp = NULL; env->errhp = NULL; /* maybe OCI_SHARED and OCI_THREADED ??? */ if (OCIEnvCreate ( &(env->envhp), (ub4)OCI_DEFAULT, (dvoid *)0, (dvoid * (*)(dvoid *, size_t)) 0, (dvoid * (*)(dvoid *, dvoid *, size_t)) 0, (void (*)(dvoid *, dvoid *)) 0, (size_t) 0, (dvoid **) 0)) luasql_faildirect (L, "couldn't create environment"); /* error handler */ ASSERT (L, OCIHandleAlloc((dvoid *) env->envhp, (dvoid **) &(env->errhp), /* !!! */ (ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0), env->errhp); return 1; } /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_close}, /* Should this method be changed? */ {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_close}, /* Should this method be changed? */ {"close", conn_close}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_close}, /* Should this method be changed? */ {"close", cur_close}, {"getcolnames", cur_getcolnames}, {"getcoltypes", cur_getcoltypes}, {"fetch", cur_fetch}, {"numrows", cur_numrows}, {NULL, NULL}, }; luasql_createmeta (L, LUASQL_ENVIRONMENT_OCI8, environment_methods); luasql_createmeta (L, LUASQL_CONNECTION_OCI8, connection_methods); luasql_createmeta (L, LUASQL_CURSOR_OCI8, cursor_methods); lua_pop (L, 3); } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_oci8 (lua_State *L) { struct luaL_Reg driver[] = { {"oci8", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable (L); luaL_setfuncs (L, driver, 0); luasql_set_info (L); return 1; } keplerproject-luasql-c527024/src/ls_odbc.c000066400000000000000000000441631175743000500205040ustar00rootroot00000000000000/* ** LuaSQL, ODBC driver ** Authors: Pedro Rabinovitch, Roberto Ierusalimschy, Diego Nehab, ** Tomas Guisasola ** See Copyright Notice in license.html ** $Id: ls_odbc.c,v 1.39 2009/02/07 23:16:23 tomas Exp $ */ #include #include #include #include #include #if defined(_WIN32) #include #include #elif defined(INFORMIX) #include "infxcli.h" #elif defined(UNIXODBC) #include "sql.h" #include "sqltypes.h" #include "sqlext.h" #endif #include "lua.h" #include "lauxlib.h" #include "luasql.h" #define LUASQL_ENVIRONMENT_ODBC "ODBC environment" #define LUASQL_CONNECTION_ODBC "ODBC connection" #define LUASQL_CURSOR_ODBC "ODBC cursor" typedef struct { short closed; int conn_counter; SQLHENV henv; /* environment handle */ } env_data; typedef struct { short closed; int cur_counter; int env; /* reference to environment */ SQLHDBC hdbc; /* database connection handle */ } conn_data; typedef struct { short closed; int conn; /* reference to connection */ int numcols; /* number of columns */ int coltypes, colnames; /* reference to column information tables */ SQLHSTMT hstmt; /* statement handle */ } cur_data; /* we are lazy */ #define hENV SQL_HANDLE_ENV #define hSTMT SQL_HANDLE_STMT #define hDBC SQL_HANDLE_DBC #define error(a) ((a) != SQL_SUCCESS && (a) != SQL_SUCCESS_WITH_INFO) LUASQL_API int luaopen_luasql_odbc (lua_State *L); /* ** Check for valid environment. */ static env_data *getenvironment (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_ODBC); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); luaL_argcheck (L, !env->closed, 1, LUASQL_PREFIX"environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_ODBC); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); luaL_argcheck (L, !conn->closed, 1, LUASQL_PREFIX"connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor (lua_State *L) { cur_data *cursor = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_ODBC); luaL_argcheck (L, cursor != NULL, 1, LUASQL_PREFIX"cursor expected"); luaL_argcheck (L, !cursor->closed, 1, LUASQL_PREFIX"cursor is closed"); return cursor; } /* ** Pushes true and returns 1 */ static int pass(lua_State *L) { lua_pushboolean (L, 1); return 1; } /* ** Fails with error message from ODBC ** Inputs: ** type: type of handle used in operation ** handle: handle used in operation */ static int fail(lua_State *L, const SQLSMALLINT type, const SQLHANDLE handle) { SQLCHAR State[6]; SQLINTEGER NativeError; SQLSMALLINT MsgSize, i; SQLRETURN ret; char Msg[SQL_MAX_MESSAGE_LENGTH]; luaL_Buffer b; lua_pushnil(L); luaL_buffinit(L, &b); i = 1; while (1) { ret = SQLGetDiagRec(type, handle, i, State, &NativeError, Msg, sizeof(Msg), &MsgSize); if (ret == SQL_NO_DATA) break; luaL_addlstring(&b, Msg, MsgSize); luaL_putchar(&b, '\n'); i++; } luaL_pushresult(&b); return 2; } /* ** Returns the name of an equivalent lua type for a SQL type. */ static const char *sqltypetolua (const SQLSMALLINT type) { switch (type) { case SQL_UNKNOWN_TYPE: case SQL_CHAR: case SQL_VARCHAR: case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: case SQL_DATE: case SQL_INTERVAL: case SQL_TIMESTAMP: case SQL_LONGVARCHAR: case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: return "string"; case SQL_BIGINT: case SQL_TINYINT: case SQL_NUMERIC: case SQL_DECIMAL: case SQL_INTEGER: case SQL_SMALLINT: case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE: return "number"; case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: return "binary"; /* !!!!!! nao seria string? */ case SQL_BIT: return "boolean"; default: assert(0); return NULL; } } /* ** Retrieves data from the i_th column in the current row ** Input ** types: index in stack of column types table ** hstmt: statement handle ** i: column number ** Returns: ** 0 if successfull, non-zero otherwise; */ static int push_column(lua_State *L, int coltypes, const SQLHSTMT hstmt, SQLUSMALLINT i) { const char *tname; char type; /* get column type from types table */ lua_rawgeti (L, LUA_REGISTRYINDEX, coltypes); lua_rawgeti (L, -1, i); /* typename of the column */ tname = lua_tostring(L, -1); if (!tname) return luasql_faildirect(L, "invalid type in table."); type = tname[1]; lua_pop(L, 2); /* pops type name and coltypes table */ /* deal with data according to type */ switch (type) { /* nUmber */ case 'u': { double num; SQLINTEGER got; SQLRETURN rc = SQLGetData(hstmt, i, SQL_C_DOUBLE, &num, 0, &got); if (error(rc)) return fail(L, hSTMT, hstmt); if (got == SQL_NULL_DATA) lua_pushnil(L); else lua_pushnumber(L, num); return 0; } /* bOol */ case 'o': { char b; SQLINTEGER got; SQLRETURN rc = SQLGetData(hstmt, i, SQL_C_BIT, &b, 0, &got); if (error(rc)) return fail(L, hSTMT, hstmt); if (got == SQL_NULL_DATA) lua_pushnil(L); else lua_pushboolean(L, b); return 0; } /* sTring */ case 't': /* bInary */ case 'i': { SQLSMALLINT stype = (type == 't') ? SQL_C_CHAR : SQL_C_BINARY; SQLINTEGER got; char *buffer; luaL_Buffer b; SQLRETURN rc; luaL_buffinit(L, &b); buffer = luaL_prepbuffer(&b); rc = SQLGetData(hstmt, i, stype, buffer, LUAL_BUFFERSIZE, &got); if (got == SQL_NULL_DATA) { lua_pushnil(L); return 0; } /* concat intermediary chunks */ while (rc == SQL_SUCCESS_WITH_INFO) { if (got >= LUAL_BUFFERSIZE || got == SQL_NO_TOTAL) { got = LUAL_BUFFERSIZE; /* get rid of null termination in string block */ if (stype == SQL_C_CHAR) got--; } luaL_addsize(&b, got); buffer = luaL_prepbuffer(&b); rc = SQLGetData(hstmt, i, stype, buffer, LUAL_BUFFERSIZE, &got); } /* concat last chunk */ if (rc == SQL_SUCCESS) { if (got >= LUAL_BUFFERSIZE || got == SQL_NO_TOTAL) { got = LUAL_BUFFERSIZE; /* get rid of null termination in string block */ if (stype == SQL_C_CHAR) got--; } luaL_addsize(&b, got); } if (rc == SQL_ERROR) return fail(L, hSTMT, hstmt); /* return everything we got */ luaL_pushresult(&b); return 0; } } return 0; } /* ** Get another row of the given cursor. */ static int cur_fetch (lua_State *L) { cur_data *cur = (cur_data *) getcursor (L); SQLHSTMT hstmt = cur->hstmt; int ret; SQLRETURN rc = SQLFetch(cur->hstmt); if (rc == SQL_NO_DATA) { lua_pushnil(L); return 1; } else if (error(rc)) return fail(L, hSTMT, hstmt); if (lua_istable (L, 2)) { SQLUSMALLINT i; const char *opts = luaL_optstring (L, 3, "n"); int num = strchr (opts, 'n') != NULL; int alpha = strchr (opts, 'a') != NULL; for (i = 1; i <= cur->numcols; i++) { ret = push_column (L, cur->coltypes, hstmt, i); if (ret) return ret; if (alpha) { lua_rawgeti (L, LUA_REGISTRYINDEX, cur->colnames); lua_rawgeti (L, -1, i); /* gets column name */ lua_pushvalue (L, -3); /* duplicates column value */ lua_rawset (L, 2); /* table[name] = value */ lua_pop (L, 1); /* pops colnames table */ } if (num) lua_rawseti (L, 2, i); else lua_pop (L, 1); /* pops value */ } lua_pushvalue (L, 2); return 1; /* return table */ } else { SQLUSMALLINT i; luaL_checkstack (L, cur->numcols, LUASQL_PREFIX"too many columns"); for (i = 1; i <= cur->numcols; i++) { ret = push_column (L, cur->coltypes, hstmt, i); if (ret) return ret; } return cur->numcols; } } /* ** Closes a cursor. */ static int cur_close (lua_State *L) { conn_data *conn; cur_data *cur = (cur_data *) luaL_checkudata (L, 1, LUASQL_CURSOR_ODBC); SQLRETURN ret; luaL_argcheck (L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); if (cur->closed) { lua_pushboolean (L, 0); return 1; } /* Nullify structure fields. */ cur->closed = 1; ret = SQLCloseCursor(cur->hstmt); if (error(ret)) return fail(L, hSTMT, cur->hstmt); ret = SQLFreeHandle(hSTMT, cur->hstmt); if (error(ret)) return fail(L, hSTMT, cur->hstmt); /* Decrement cursor counter on connection object */ lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); conn = lua_touserdata (L, -1); conn->cur_counter--; luaL_unref (L, LUA_REGISTRYINDEX, cur->conn); luaL_unref (L, LUA_REGISTRYINDEX, cur->colnames); luaL_unref (L, LUA_REGISTRYINDEX, cur->coltypes); return pass(L); } /* ** Returns the table with column names. */ static int cur_colnames (lua_State *L) { cur_data *cur = (cur_data *) getcursor (L); lua_rawgeti (L, LUA_REGISTRYINDEX, cur->colnames); return 1; } /* ** Returns the table with column types. */ static int cur_coltypes (lua_State *L) { cur_data *cur = (cur_data *) getcursor (L); lua_rawgeti (L, LUA_REGISTRYINDEX, cur->coltypes); return 1; } /* ** Creates two tables with the names and the types of the columns. */ static void create_colinfo (lua_State *L, cur_data *cur) { SQLCHAR buffer[256]; SQLSMALLINT namelen, datatype, i; SQLRETURN ret; int types, names; lua_newtable(L); types = lua_gettop (L); lua_newtable(L); names = lua_gettop (L); for (i = 1; i <= cur->numcols; i++) { ret = SQLDescribeCol(cur->hstmt, i, buffer, sizeof(buffer), &namelen, &datatype, NULL, NULL, NULL); /*if (ret == SQL_ERROR) return fail(L, hSTMT, cur->hstmt);*/ lua_pushstring (L, buffer); lua_rawseti (L, names, i); lua_pushstring(L, sqltypetolua(datatype)); lua_rawseti (L, types, i); } cur->colnames = luaL_ref (L, LUA_REGISTRYINDEX); cur->coltypes = luaL_ref (L, LUA_REGISTRYINDEX); } /* ** Creates a cursor table and leave it on the top of the stack. */ static int create_cursor (lua_State *L, int o, conn_data *conn, const SQLHSTMT hstmt, const SQLSMALLINT numcols) { cur_data *cur = (cur_data *) lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_ODBC); conn->cur_counter++; /* fill in structure */ cur->closed = 0; cur->conn = LUA_NOREF; cur->numcols = numcols; cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->hstmt = hstmt; lua_pushvalue (L, o); cur->conn = luaL_ref (L, LUA_REGISTRYINDEX); /* make and store column information table */ create_colinfo (L, cur); return 1; } /* ** Closes a connection. */ static int conn_close (lua_State *L) { SQLRETURN ret; env_data *env; conn_data *conn = (conn_data *)luaL_checkudata(L,1,LUASQL_CONNECTION_ODBC); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); if (conn->closed) { lua_pushboolean (L, 0); return 1; } if (conn->cur_counter > 0) return luaL_error (L, LUASQL_PREFIX"there are open cursors"); /* Decrement connection counter on environment object */ lua_rawgeti (L, LUA_REGISTRYINDEX, conn->env); env = lua_touserdata (L, -1); env->conn_counter--; /* Nullify structure fields. */ conn->closed = 1; luaL_unref (L, LUA_REGISTRYINDEX, conn->env); ret = SQLDisconnect(conn->hdbc); if (error(ret)) return fail(L, hDBC, conn->hdbc); ret = SQLFreeHandle(hDBC, conn->hdbc); if (error(ret)) return fail(L, hDBC, conn->hdbc); return pass(L); } /* ** Executes a SQL statement. ** Returns ** cursor object: if there are results or ** row count: number of rows affected by statement if no results */ static int conn_execute (lua_State *L) { conn_data *conn = (conn_data *) getconnection (L); const char *statement = luaL_checkstring(L, 2); SQLHDBC hdbc = conn->hdbc; SQLHSTMT hstmt; SQLSMALLINT numcols; SQLRETURN ret; ret = SQLAllocHandle(hSTMT, hdbc, &hstmt); if (error(ret)) return fail(L, hDBC, hdbc); ret = SQLPrepare(hstmt, (char *) statement, SQL_NTS); if (error(ret)) { ret = fail(L, hSTMT, hstmt); SQLFreeHandle(hSTMT, hstmt); return ret; } /* execute the statement */ ret = SQLExecute (hstmt); if (error(ret)) { ret = fail(L, hSTMT, hstmt); SQLFreeHandle(hSTMT, hstmt); return ret; } /* determine the number of results */ ret = SQLNumResultCols (hstmt, &numcols); if (error(ret)) { ret = fail(L, hSTMT, hstmt); SQLFreeHandle(hSTMT, hstmt); return ret; } if (numcols > 0) /* if there is a results table (e.g., SELECT) */ return create_cursor (L, 1, conn, hstmt, numcols); else { /* if action has no results (e.g., UPDATE) */ SQLINTEGER numrows; ret = SQLRowCount(hstmt, &numrows); if (error(ret)) { ret = fail(L, hSTMT, hstmt); SQLFreeHandle(hSTMT, hstmt); return ret; } lua_pushnumber(L, numrows); SQLFreeHandle(hSTMT, hstmt); return 1; } } /* ** Rolls back a transaction. */ static int conn_commit (lua_State *L) { conn_data *conn = (conn_data *) getconnection (L); SQLRETURN ret = SQLEndTran(hDBC, conn->hdbc, SQL_COMMIT); if (error(ret)) return fail(L, hSTMT, conn->hdbc); else return pass(L); } /* ** Rollback the current transaction. */ static int conn_rollback (lua_State *L) { conn_data *conn = (conn_data *) getconnection (L); SQLRETURN ret = SQLEndTran(hDBC, conn->hdbc, SQL_ROLLBACK); if (error(ret)) return fail(L, hSTMT, conn->hdbc); else return pass(L); } /* ** Sets the auto commit mode */ static int conn_setautocommit (lua_State *L) { conn_data *conn = (conn_data *) getconnection (L); SQLRETURN ret; if (lua_toboolean (L, 2)) { ret = SQLSetConnectAttr(conn->hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_ON, 0); } else { ret = SQLSetConnectAttr(conn->hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_OFF, 0); } if (error(ret)) return fail(L, hSTMT, conn->hdbc); else return pass(L); } /* ** Create a new Connection object and push it on top of the stack. */ static int create_connection (lua_State *L, int o, env_data *env, SQLHDBC hdbc) { conn_data *conn = (conn_data *) lua_newuserdata(L, sizeof(conn_data)); /* set auto commit mode */ SQLRETURN ret = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_ON, 0); if (error(ret)) return fail(L, hDBC, hdbc); luasql_setmeta (L, LUASQL_CONNECTION_ODBC); /* fill in structure */ conn->closed = 0; conn->cur_counter = 0; conn->env = LUA_NOREF; conn->hdbc = hdbc; lua_pushvalue (L, o); conn->env = luaL_ref (L, LUA_REGISTRYINDEX); env->conn_counter++; return 1; } /* ** Creates and returns a connection object ** Lua Input: source [, user [, pass]] ** source: data source ** user, pass: data source authentication information ** Lua Returns: ** connection object if successfull ** nil and error message otherwise. */ static int env_connect (lua_State *L) { env_data *env = (env_data *) getenvironment (L); const char *sourcename = luaL_checkstring (L, 2); const char *username = luaL_optstring (L, 3, NULL); const char *password = luaL_optstring (L, 4, NULL); SQLHDBC hdbc; SQLRETURN ret; /* tries to allocate connection handle */ ret = SQLAllocHandle (hDBC, env->henv, &hdbc); if (error(ret)) return luasql_faildirect (L, "connection allocation error."); /* tries to connect handle */ ret = SQLConnect (hdbc, (char *) sourcename, SQL_NTS, (char *) username, SQL_NTS, (char *) password, SQL_NTS); if (error(ret)) { ret = fail(L, hDBC, hdbc); SQLFreeHandle(hDBC, hdbc); return ret; } /* success, return connection object */ return create_connection (L, 1, env, hdbc); } /* ** Closes an environment object */ static int env_close (lua_State *L) { SQLRETURN ret; env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_ODBC); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); if (env->closed) { lua_pushboolean (L, 0); return 1; } if (env->conn_counter > 0) return luaL_error (L, LUASQL_PREFIX"there are open connections"); env->closed = 1; ret = SQLFreeHandle (hENV, env->henv); if (error(ret)) { int ret = fail(L, hENV, env->henv); env->henv = NULL; return ret; } return pass(L); } /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_close}, /* Should this method be changed? */ {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_close}, /* Should this method be changed? */ {"close", conn_close}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_close}, /* Should this method be changed? */ {"close", cur_close}, {"fetch", cur_fetch}, {"getcoltypes", cur_coltypes}, {"getcolnames", cur_colnames}, {NULL, NULL}, }; luasql_createmeta (L, LUASQL_ENVIRONMENT_ODBC, environment_methods); luasql_createmeta (L, LUASQL_CONNECTION_ODBC, connection_methods); luasql_createmeta (L, LUASQL_CURSOR_ODBC, cursor_methods); lua_pop (L, 3); } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { env_data *env; SQLHENV henv; SQLRETURN ret = SQLAllocHandle(hENV, SQL_NULL_HANDLE, &henv); if (error(ret)) return luasql_faildirect(L, "error creating environment."); ret = SQLSetEnvAttr (henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); if (error(ret)) { ret = luasql_faildirect (L, "error setting SQL version."); SQLFreeHandle (hENV, henv); return ret; } env = (env_data *)lua_newuserdata (L, sizeof (env_data)); luasql_setmeta (L, LUASQL_ENVIRONMENT_ODBC); /* fill in structure */ env->closed = 0; env->conn_counter = 0; env->henv = henv; return 1; } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_odbc (lua_State *L) { struct luaL_Reg driver[] = { {"odbc", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable (L); luaL_setfuncs (L, driver, 0); luasql_set_info (L); return 1; } keplerproject-luasql-c527024/src/ls_postgres.c000066400000000000000000000356201175743000500214410ustar00rootroot00000000000000/* ** LuaSQL, PostgreSQL driver ** Authors: Pedro Rabinovitch, Roberto Ierusalimschy, Carlos Cassino ** Tomas Guisasola, Eduardo Quintao ** See Copyright Notice in license.html ** $Id: ls_postgres.c,v 1.11 2009/02/07 23:16:23 tomas Exp $ */ #include #include #include #include #include #include "libpq-fe.h" #include "lua.h" #include "lauxlib.h" #include "luasql.h" #define LUASQL_ENVIRONMENT_PG "PostgreSQL environment" #define LUASQL_CONNECTION_PG "PostgreSQL connection" #define LUASQL_CURSOR_PG "PostgreSQL cursor" typedef struct { short closed; } env_data; typedef struct { short closed; int env; /* reference to environment */ int auto_commit; /* 0 for manual commit */ PGconn *pg_conn; } conn_data; typedef struct { short closed; int conn; /* reference to connection */ int numcols; /* number of columns */ int colnames, coltypes; /* reference to column information tables */ int curr_tuple; /* next tuple to be read */ PGresult *pg_res; } cur_data; typedef void (*creator) (lua_State *L, cur_data *cur); LUASQL_API int luaopen_luasql_postgres(lua_State *L); /* ** Check for valid environment. */ static env_data *getenvironment (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_PG); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); luaL_argcheck (L, !env->closed, 1, LUASQL_PREFIX"environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_PG); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); luaL_argcheck (L, !conn->closed, 1, LUASQL_PREFIX"connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_PG); luaL_argcheck (L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); luaL_argcheck (L, !cur->closed, 1, LUASQL_PREFIX"cursor is closed"); return cur; } /* ** Push the value of #i field of #tuple row. */ static void pushvalue (lua_State *L, PGresult *res, int tuple, int i) { if (PQgetisnull (res, tuple, i-1)) lua_pushnil (L); else lua_pushstring (L, PQgetvalue (res, tuple, i-1)); } /* ** Closes the cursor and nullify all structure fields. */ static void cur_nullify (lua_State *L, cur_data *cur) { /* Nullify structure fields. */ cur->closed = 1; PQclear(cur->pg_res); luaL_unref (L, LUA_REGISTRYINDEX, cur->conn); luaL_unref (L, LUA_REGISTRYINDEX, cur->colnames); luaL_unref (L, LUA_REGISTRYINDEX, cur->coltypes); } /* ** Get another row of the given cursor. */ static int cur_fetch (lua_State *L) { cur_data *cur = getcursor (L); PGresult *res = cur->pg_res; int tuple = cur->curr_tuple; if (tuple >= PQntuples(cur->pg_res)) { cur_nullify (L, cur); lua_pushnil(L); /* no more results */ return 1; } cur->curr_tuple++; if (lua_istable (L, 2)) { int i; const char *opts = luaL_optstring (L, 3, "n"); if (strchr (opts, 'n') != NULL) /* Copy values to numerical indices */ for (i = 1; i <= cur->numcols; i++) { pushvalue (L, res, tuple, i); lua_rawseti (L, 2, i); } if (strchr (opts, 'a') != NULL) /* Copy values to alphanumerical indices */ for (i = 1; i <= cur->numcols; i++) { lua_pushstring (L, PQfname (res, i-1)); pushvalue (L, res, tuple, i); lua_rawset (L, 2); } lua_pushvalue(L, 2); return 1; /* return table */ } else { int i; luaL_checkstack (L, cur->numcols, LUASQL_PREFIX"too many columns"); for (i = 1; i <= cur->numcols; i++) pushvalue (L, res, tuple, i); return cur->numcols; /* return #numcols values */ } } /* ** Cursor object collector function */ static int cur_gc (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_PG); if (cur != NULL && !(cur->closed)) cur_nullify (L, cur); return 0; } /* ** Closes the cursor on top of the stack. ** Returns true in case of success, or false in case the cursor was ** already closed. ** Throws an error if the argument is not a cursor. */ static int cur_close (lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_PG); luaL_argcheck (L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); if (cur->closed) { lua_pushboolean (L, 0); return 1; } cur_nullify (L, cur); /* == cur_gc (L); */ lua_pushboolean (L, 1); return 1; } /* ** Get the internal database type of the given column. */ static char *getcolumntype (PGconn *conn, PGresult *result, int i, char *buff) { Oid codigo = PQftype (result, i); char stmt[100]; PGresult *res; sprintf (stmt, "select typname from pg_type where oid = %d", codigo); res = PQexec(conn, stmt); strcpy (buff, "undefined"); if (PQresultStatus (res) == PGRES_TUPLES_OK) { if (PQntuples(res) > 0) { char *name = PQgetvalue(res, 0, 0); if (strcmp (name, "bpchar")==0 || strcmp (name, "varchar")==0) { int modifier = PQfmod (result, i) - 4; sprintf (buff, "%.20s (%d)", name, modifier); } else strncpy (buff, name, 20); } } PQclear(res); return buff; } /* ** Creates the list of fields names and pushes it on top of the stack. */ static void create_colnames (lua_State *L, cur_data *cur) { PGresult *result = cur->pg_res; int i; lua_newtable (L); for (i = 1; i <= cur->numcols; i++) { lua_pushstring (L, PQfname (result, i-1)); lua_rawseti (L, -2, i); } } /* ** Creates the list of fields types and pushes it on top of the stack. */ static void create_coltypes (lua_State *L, cur_data *cur) { PGresult *result = cur->pg_res; conn_data *conn; char typename[100]; int i; lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); if (!lua_isuserdata (L, -1)) luaL_error (L, LUASQL_PREFIX"invalid connection"); conn = (conn_data *)lua_touserdata (L, -1); lua_newtable (L); for (i = 1; i <= cur->numcols; i++) { lua_pushstring(L, getcolumntype (conn->pg_conn, result, i-1, typename)); lua_rawseti (L, -2, i); } } /* ** Pushes a column information table on top of the stack. ** If the table isn't built yet, call the creator function and stores ** a reference to it on the cursor structure. */ static void _pushtable (lua_State *L, cur_data *cur, size_t off, creator func) { int *ref = (int *)((char *)cur + off); if (*ref != LUA_NOREF) lua_rawgeti (L, LUA_REGISTRYINDEX, *ref); else { func (L, cur); /* Stores a reference to it on the cursor structure */ lua_pushvalue (L, -1); *ref = luaL_ref (L, LUA_REGISTRYINDEX); } } #define pushtable(L,c,m,f) (_pushtable(L,c,offsetof(cur_data,m),f)) /* ** Return the list of field names. */ static int cur_getcolnames (lua_State *L) { pushtable (L, getcursor(L), colnames, create_colnames); return 1; } /* ** Return the list of field types. */ static int cur_getcoltypes (lua_State *L) { pushtable (L, getcursor(L), coltypes, create_coltypes); return 1; } /* ** Push the number of rows. */ static int cur_numrows (lua_State *L) { lua_pushnumber (L, PQntuples (getcursor(L)->pg_res)); return 1; } /* ** Create a new Cursor object and push it on top of the stack. */ static int create_cursor (lua_State *L, int conn, PGresult *result) { cur_data *cur = (cur_data *)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_PG); /* fill in structure */ cur->closed = 0; cur->conn = LUA_NOREF; cur->numcols = PQnfields(result); cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->curr_tuple = 0; cur->pg_res = result; lua_pushvalue (L, conn); cur->conn = luaL_ref (L, LUA_REGISTRYINDEX); return 1; } static void sql_commit(conn_data *conn) { PQclear(PQexec(conn->pg_conn, "COMMIT")); } static void sql_begin(conn_data *conn) { PQclear(PQexec(conn->pg_conn, "BEGIN")); } static void sql_rollback(conn_data *conn) { PQclear(PQexec(conn->pg_conn, "ROLLBACK")); } /* ** Connection object collector function */ static int conn_gc (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_PG); if (conn != NULL && !(conn->closed)) { /* Nullify structure fields. */ conn->closed = 1; luaL_unref (L, LUA_REGISTRYINDEX, conn->env); PQfinish (conn->pg_conn); } return 0; } /* ** Closes the connection on top of the stack. ** Returns true in case of success, or false in case the connection was ** already closed. ** Throws an error if the argument is not a connection. */ static int conn_close (lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_PG); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); if (conn->closed) { lua_pushboolean (L, 0); return 1; } conn_gc (L); lua_pushboolean (L, 1); return 1; } /* ** 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)); } /* ** 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)); } } /* ** Commit the current transaction. */ static int conn_commit (lua_State *L) { conn_data *conn = getconnection (L); sql_commit(conn); if (conn->auto_commit == 0) { sql_begin(conn); lua_pushboolean (L, 1); } else lua_pushboolean (L, 0); return 1; } /* ** Rollback the current transaction. */ static int conn_rollback (lua_State *L) { conn_data *conn = getconnection (L); sql_rollback(conn); if (conn->auto_commit == 0) { sql_begin(conn); lua_pushboolean (L, 1); } else lua_pushboolean (L, 0); return 1; } /* ** Set "auto commit" property of the connection. ** If 'true', then rollback current transaction. ** If 'false', then start a new transaction. */ static int conn_setautocommit (lua_State *L) { conn_data *conn = getconnection (L); if (lua_toboolean (L, 2)) { conn->auto_commit = 1; sql_rollback(conn); /* Undo active transaction. */ } else { conn->auto_commit = 0; sql_begin(conn); } lua_pushboolean(L, 1); return 1; } /* ** Create a new Connection object and push it on top of the stack. */ static int create_connection (lua_State *L, int env, PGconn *const pg_conn) { conn_data *conn = (conn_data *)lua_newuserdata(L, sizeof(conn_data)); luasql_setmeta (L, LUASQL_CONNECTION_PG); /* fill in structure */ conn->closed = 0; conn->env = LUA_NOREF; conn->auto_commit = 1; conn->pg_conn = pg_conn; lua_pushvalue (L, env); conn->env = luaL_ref (L, LUA_REGISTRYINDEX); return 1; } static void notice_processor (void *arg, const char *message) { (void)arg; (void)message; /* arg == NULL */ } /* ** Connects to a data source. ** This driver provides two ways to connect to a data source: ** (1) giving the connection parameters as a set of pairs separated ** by whitespaces in a string (first method parameter) ** (2) giving one string for each connection parameter, said ** datasource, username, password, host and port. */ static int env_connect (lua_State *L) { const char *sourcename = luaL_checkstring(L, 2); PGconn *conn; getenvironment (L); /* validate environment */ if ((lua_gettop (L) == 2) && (strchr (sourcename, '=') != NULL)) conn = PQconnectdb (sourcename); else { 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); conn = PQsetdbLogin(pghost, pgport, NULL, NULL, sourcename, username, password); } if (PQstatus(conn) == CONNECTION_BAD) return luasql_failmsg(L, "error connecting to database. PostgreSQL: ", PQerrorMessage(conn)); PQsetNoticeProcessor(conn, notice_processor, NULL); return create_connection(L, 1, conn); } /* ** Environment object collector function. */ static int env_gc (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_PG); if (env != NULL && !(env->closed)) env->closed = 1; return 0; } /* ** Closes the environment on top of the stack. ** Returns true in case of success, or false in case the environment was ** already closed. ** Throws an error if the argument is not an environment. */ static int env_close (lua_State *L) { env_data *env = (env_data *)luaL_checkudata (L, 1, LUASQL_ENVIRONMENT_PG); luaL_argcheck (L, env != NULL, 1, LUASQL_PREFIX"environment expected"); if (env->closed) { lua_pushboolean (L, 0); return 1; } env_gc (L); lua_pushboolean (L, 1); return 1; } /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_gc}, {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_gc}, {"close", conn_close}, {"escape", conn_escape}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_gc}, {"close", cur_close}, {"getcolnames", cur_getcolnames}, {"getcoltypes", cur_getcoltypes}, {"fetch", cur_fetch}, {"numrows", cur_numrows}, {NULL, NULL}, }; luasql_createmeta (L, LUASQL_ENVIRONMENT_PG, environment_methods); luasql_createmeta (L, LUASQL_CONNECTION_PG, connection_methods); luasql_createmeta (L, LUASQL_CURSOR_PG, cursor_methods); lua_pop (L, 3); } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { env_data *env = (env_data *)lua_newuserdata(L, sizeof(env_data)); luasql_setmeta (L, LUASQL_ENVIRONMENT_PG); /* fill in structure */ env->closed = 0; return 1; } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_postgres (lua_State *L) { struct luaL_Reg driver[] = { {"postgres", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable (L); luaL_setfuncs (L, driver, 0); luasql_set_info (L); return 1; } keplerproject-luasql-c527024/src/ls_sqlite.c000066400000000000000000000341551175743000500210760ustar00rootroot00000000000000/* ** LuaSQL, SQLite driver ** Author: Tiago Dionizio, Eduardo Quintao ** See Copyright Notice in license.html ** $Id: ls_sqlite.c,v 1.13 2008/05/04 02:46:17 tomas Exp $ */ #include #include #include #include #include "sqlite.h" #include "lua.h" #include "lauxlib.h" #include "luasql.h" #define LUASQL_ENVIRONMENT_SQLITE "SQLite environment" #define LUASQL_CONNECTION_SQLITE "SQLite connection" #define LUASQL_CURSOR_SQLITE "SQLite cursor" typedef struct { short closed; } env_data; typedef struct { short closed; int env; /* reference to environment */ short auto_commit; /* 0 for manual commit */ unsigned int cur_counter; sqlite *sql_conn; } conn_data; typedef struct { short closed; int conn; /* reference to connection */ int numcols; /* number of columns */ int colnames, coltypes; /* reference to column information tables */ sqlite_vm *sql_vm; } cur_data; LUASQL_API int luaopen_luasql_sqlite(lua_State *L); /* ** Check for valid environment. */ static env_data *getenvironment(lua_State *L) { env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SQLITE); luaL_argcheck(L, env != NULL, 1, LUASQL_PREFIX"environment expected"); luaL_argcheck(L, !env->closed, 1, LUASQL_PREFIX"environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection(lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_SQLITE); luaL_argcheck(L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); luaL_argcheck(L, !conn->closed, 1, LUASQL_PREFIX"connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor(lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_SQLITE); luaL_argcheck(L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); luaL_argcheck(L, !cur->closed, 1, LUASQL_PREFIX"cursor is closed"); return cur; } /* ** Closes the cursor and nullify all structure fields. */ static void cur_nullify(lua_State *L, cur_data *cur) { conn_data *conn; /* Nullify structure fields. */ cur->closed = 1; cur->sql_vm = NULL; /* Decrement cursor counter on connection object */ lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); conn = lua_touserdata (L, -1); conn->cur_counter--; luaL_unref(L, LUA_REGISTRYINDEX, cur->conn); luaL_unref(L, LUA_REGISTRYINDEX, cur->colnames); luaL_unref(L, LUA_REGISTRYINDEX, cur->coltypes); } /* ** Finalizes the vm ** Return nil + errmsg or nil in case of sucess */ static int finalize(lua_State *L, cur_data *cur) { char *errmsg; if (sqlite_finalize(cur->sql_vm, &errmsg) != SQLITE_OK) { cur_nullify(L, cur); lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); return 2; } cur_nullify(L, cur); lua_pushnil(L); return 1; } /* ** Get another row of the given cursor. */ static int cur_fetch (lua_State *L) { cur_data *cur = getcursor(L); sqlite_vm *vm = cur->sql_vm; const char **row = NULL; int res; if (vm == NULL) return 0; res = sqlite_step(vm, NULL, &row, NULL); /* no more results? */ if (res == SQLITE_DONE) return finalize(L, cur); if (res != SQLITE_ROW) return finalize(L, cur); if (lua_istable (L, 2)) { int i; const char *opts = luaL_optstring(L, 3, "n"); if (strchr(opts, 'n') != NULL) { /* Copy values to numerical indices */ for (i = 0; i < cur->numcols;) { lua_pushstring(L, row[i]); lua_rawseti(L, 2, ++i); } } if (strchr(opts, 'a') != NULL) { /* Copy values to alphanumerical indices */ lua_rawgeti(L, LUA_REGISTRYINDEX, cur->colnames); for (i = 0; i < cur->numcols; i++) { lua_rawgeti(L, -1, i+1); lua_pushstring(L, row[i]); lua_rawset (L, 2); } } lua_pushvalue(L, 2); return 1; /* return table */ } else { int i; luaL_checkstack (L, cur->numcols, LUASQL_PREFIX"too many columns"); for (i = 0; i < cur->numcols; ++i) lua_pushstring(L, row[i]); return cur->numcols; /* return #numcols values */ } } /* ** Cursor object collector function */ static int cur_gc(lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata(L, 1, LUASQL_CURSOR_SQLITE); if (cur != NULL && !(cur->closed)) { sqlite_finalize(cur->sql_vm, NULL); cur_nullify(L, cur); } return 0; } /* ** Close the cursor on top of the stack. ** Return 1 */ static int cur_close(lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata(L, 1, LUASQL_CURSOR_SQLITE); luaL_argcheck(L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); if (cur->closed) { lua_pushboolean(L, 0); return 1; } sqlite_finalize(cur->sql_vm, NULL); cur_nullify(L, cur); lua_pushboolean(L, 1); return 1; } /* ** Return the list of field names. */ static int cur_getcolnames(lua_State *L) { cur_data *cur = getcursor(L); lua_rawgeti(L, LUA_REGISTRYINDEX, cur->colnames); return 1; } /* ** Return the list of field types. */ static int cur_getcoltypes(lua_State *L) { cur_data *cur = getcursor(L); lua_rawgeti(L, LUA_REGISTRYINDEX, cur->coltypes); return 1; } /* ** Create a new Cursor object and push it on top of the stack. */ /* static int create_cursor(lua_State *L, int conn, sqlite_vm *sql_vm, int numcols, const char **row, const char **col_info)*/ static int create_cursor(lua_State *L, int o, conn_data *conn, sqlite_vm *sql_vm, int numcols, const char **col_info) { int i; cur_data *cur = (cur_data*)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_SQLITE); /* increment cursor count for the connection creating this cursor */ conn->cur_counter++; /* fill in structure */ cur->closed = 0; cur->conn = LUA_NOREF; cur->numcols = numcols; cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->sql_vm = sql_vm; lua_pushvalue(L, o); cur->conn = luaL_ref(L, LUA_REGISTRYINDEX); /* create table with column names */ lua_newtable(L); for (i = 0; i < numcols;) { lua_pushstring(L, col_info[i]); lua_rawseti(L, -2, ++i); } cur->colnames = luaL_ref(L, LUA_REGISTRYINDEX); /* create table with column types */ lua_newtable(L); for (i = 0; i < numcols;) { lua_pushstring(L, col_info[numcols+i]); lua_rawseti(L, -2, ++i); } cur->coltypes = luaL_ref(L, LUA_REGISTRYINDEX); return 1; } /* ** Connection object collector function */ static int conn_gc(lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata(L, 1, LUASQL_CONNECTION_SQLITE); if (conn != NULL && !(conn->closed)) { if (conn->cur_counter > 0) return luaL_error (L, LUASQL_PREFIX"there are open cursors"); /* Nullify structure fields. */ conn->closed = 1; luaL_unref(L, LUA_REGISTRYINDEX, conn->env); sqlite_close(conn->sql_conn); } return 0; } /* ** Close a Connection object. */ static int conn_close(lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata(L, 1, LUASQL_CONNECTION_SQLITE); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); if (conn->closed) { lua_pushboolean(L, 0); return 1; } conn_gc(L); lua_pushboolean(L, 1); return 1; } /* ** 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); int res; sqlite_vm *vm; char *errmsg; int numcols; const char **col_info; res = sqlite_compile(conn->sql_conn, statement, NULL, &vm, &errmsg); if (res != SQLITE_OK) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); return 2; } /* process first result to retrive query information and type */ res = sqlite_step(vm, &numcols, NULL, &col_info); /* real query? if empty, must have numcols!=0 */ if ((res == SQLITE_ROW) || ((res == SQLITE_DONE) && numcols)) { sqlite_reset(vm, NULL); return create_cursor(L, 1, conn, vm, numcols, col_info); } if (res == SQLITE_DONE) /* and numcols==0, INSERT,UPDATE,DELETE statement */ { sqlite_finalize(vm, NULL); /* return number of columns changed */ lua_pushnumber(L, sqlite_changes(conn->sql_conn)); return 1; } /* error */ sqlite_finalize(vm, &errmsg); lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); return 2; } /* ** Commit the current transaction. */ static int conn_commit(lua_State *L) { char *errmsg; conn_data *conn = getconnection(L); int res; const char *sql = "COMMIT"; if (conn->auto_commit == 0) sql = "COMMIT;BEGIN"; res = sqlite_exec(conn->sql_conn, sql, NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); return 2; } lua_pushboolean(L, 1); return 1; } /* ** Rollback the current transaction. */ static int conn_rollback(lua_State *L) { char *errmsg; conn_data *conn = getconnection(L); int res; const char *sql = "ROLLBACK"; if (conn->auto_commit == 0) sql = "ROLLBACK;BEGIN"; res = sqlite_exec(conn->sql_conn, sql, NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); return 2; } lua_pushboolean(L, 1); return 1; } /* ** Set "auto commit" property of the connection. ** If 'true', then rollback current transaction. ** If 'false', then start a new transaction. */ static int conn_setautocommit(lua_State *L) { conn_data *conn = getconnection(L); if (lua_toboolean(L, 2)) { conn->auto_commit = 1; /* undo active transaction - ignore errors */ sqlite_exec(conn->sql_conn, "ROLLBACK", NULL, NULL, NULL); } else { char *errmsg; int res; conn->auto_commit = 0; res = sqlite_exec(conn->sql_conn, "BEGIN", NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); lua_error(L); } } lua_pushboolean(L, 1); return 1; } /* ** Create a new Connection object and push it on top of the stack. */ static int create_connection(lua_State *L, int env, sqlite *sql_conn) { conn_data *conn = (conn_data*)lua_newuserdata(L, sizeof(conn_data)); luasql_setmeta(L, LUASQL_CONNECTION_SQLITE); /* fill in structure */ conn->closed = 0; conn->env = LUA_NOREF; conn->auto_commit = 1; conn->sql_conn = sql_conn; conn->cur_counter = 0; lua_pushvalue (L, env); conn->env = luaL_ref (L, LUA_REGISTRYINDEX); return 1; } /* ** Connects to a data source. */ static int env_connect(lua_State *L) { const char *sourcename; sqlite *conn; char *errmsg; getenvironment(L); /* validate environment */ sourcename = luaL_checkstring(L, 2); conn = sqlite_open(sourcename, 0, &errmsg); if (conn == NULL) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite_freemem(errmsg); lua_concat(L, 2); return 2; } return create_connection(L, 1, conn); } /* ** Close environment object. */ static int env_gc (lua_State *L) { env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SQLITE); if (env != NULL && !(env->closed)) env->closed = 1; return 0; } /* ** Close environment object. */ static int env_close (lua_State *L) { env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SQLITE); luaL_argcheck(L, env != NULL, 1, LUASQL_PREFIX"environment expected"); if (env->closed) { lua_pushboolean(L, 0); return 1; } env_gc(L); lua_pushboolean(L, 1); return 1; } static int conn_escape(lua_State *L) { const char *from = luaL_checklstring (L, 2, 0); char *escaped = sqlite_mprintf("%q", from); if (escaped == NULL) { lua_pushnil(L); } else { lua_pushstring(L, escaped); sqlite_freemem(escaped); } return 1; } /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_gc}, {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_gc}, {"close", conn_close}, {"escape", conn_escape}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_gc}, {"close", cur_close}, {"getcolnames", cur_getcolnames}, {"getcoltypes", cur_getcoltypes}, {"fetch", cur_fetch}, {NULL, NULL}, }; luasql_createmeta(L, LUASQL_ENVIRONMENT_SQLITE, environment_methods); luasql_createmeta(L, LUASQL_CONNECTION_SQLITE, connection_methods); luasql_createmeta(L, LUASQL_CURSOR_SQLITE, cursor_methods); lua_pop (L, 3); } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { env_data *env = (env_data *)lua_newuserdata(L, sizeof(env_data)); luasql_setmeta(L, LUASQL_ENVIRONMENT_SQLITE); /* fill in structure */ env->closed = 0; return 1; } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_sqlite(lua_State *L) { struct luaL_Reg driver[] = { {"sqlite", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable (L); luaL_setfuncs (L, driver, 0); luasql_set_info (L); return 1; } keplerproject-luasql-c527024/src/ls_sqlite3.c000066400000000000000000000362371175743000500211640ustar00rootroot00000000000000/* ** LuaSQL, SQLite driver ** Author: Tiago Dionizio, Eduardo Quintao ** See Copyright Notice in license.html ** $Id: ls_sqlite3.c,v 1.15 2009/02/07 23:16:23 tomas Exp $ */ #include #include #include #include #include "sqlite3.h" #include "lua.h" #include "lauxlib.h" #include "luasql.h" #define LUASQL_ENVIRONMENT_SQLITE "SQLite3 environment" #define LUASQL_CONNECTION_SQLITE "SQLite3 connection" #define LUASQL_CURSOR_SQLITE "SQLite3 cursor" typedef struct { short closed; } env_data; typedef struct { short closed; int env; /* reference to environment */ short auto_commit; /* 0 for manual commit */ unsigned int cur_counter; sqlite3 *sql_conn; } conn_data; typedef struct { short closed; int conn; /* reference to connection */ int numcols; /* number of columns */ int colnames, coltypes; /* reference to column information tables */ conn_data *conn_data; /* reference to connection for cursor */ sqlite3_stmt *sql_vm; } cur_data; LUASQL_API int luaopen_luasql_sqlite3(lua_State *L); /* ** Check for valid environment. */ static env_data *getenvironment(lua_State *L) { env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SQLITE); luaL_argcheck(L, env != NULL, 1, LUASQL_PREFIX"environment expected"); luaL_argcheck(L, !env->closed, 1, LUASQL_PREFIX"environment is closed"); return env; } /* ** Check for valid connection. */ static conn_data *getconnection(lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata (L, 1, LUASQL_CONNECTION_SQLITE); luaL_argcheck(L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); luaL_argcheck(L, !conn->closed, 1, LUASQL_PREFIX"connection is closed"); return conn; } /* ** Check for valid cursor. */ static cur_data *getcursor(lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata (L, 1, LUASQL_CURSOR_SQLITE); luaL_argcheck(L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); luaL_argcheck(L, !cur->closed, 1, LUASQL_PREFIX"cursor is closed"); return cur; } /* ** Closes the cursor and nullify all structure fields. */ static void cur_nullify(lua_State *L, cur_data *cur) { conn_data *conn; /* Nullify structure fields. */ cur->closed = 1; cur->sql_vm = NULL; /* Decrement cursor counter on connection object */ lua_rawgeti (L, LUA_REGISTRYINDEX, cur->conn); conn = lua_touserdata (L, -1); conn->cur_counter--; luaL_unref(L, LUA_REGISTRYINDEX, cur->conn); luaL_unref(L, LUA_REGISTRYINDEX, cur->colnames); luaL_unref(L, LUA_REGISTRYINDEX, cur->coltypes); } /* ** Finalizes the vm ** Return nil + errmsg or nil in case of sucess */ static int finalize(lua_State *L, cur_data *cur) { const char *errmsg; if (sqlite3_finalize(cur->sql_vm) != SQLITE_OK) { errmsg = sqlite3_errmsg(cur->conn_data->sql_conn); cur_nullify(L, cur); return luasql_faildirect(L, errmsg); } cur_nullify(L, cur); lua_pushnil(L); return 1; } static void push_column(lua_State *L, sqlite3_stmt *vm, int column) { switch (sqlite3_column_type(vm, column)) { case SQLITE_INTEGER: lua_pushinteger(L, sqlite3_column_int64(vm, column)); break; case SQLITE_FLOAT: lua_pushnumber(L, sqlite3_column_double(vm, column)); break; case SQLITE_TEXT: lua_pushlstring(L, (const char *)sqlite3_column_text(vm, column), (size_t)sqlite3_column_bytes(vm, column)); break; case SQLITE_BLOB: lua_pushlstring(L, sqlite3_column_blob(vm, column), (size_t)sqlite3_column_bytes(vm, column)); break; case SQLITE_NULL: lua_pushnil(L); break; default: luaL_error(L, LUASQL_PREFIX"Unrecognized column type"); break; } } /* ** Get another row of the given cursor. */ static int cur_fetch (lua_State *L) { cur_data *cur = getcursor(L); sqlite3_stmt *vm = cur->sql_vm; int res; if (vm == NULL) return 0; res = sqlite3_step(vm); /* no more results? */ if (res == SQLITE_DONE) return finalize(L, cur); if (res != SQLITE_ROW) return finalize(L, cur); if (lua_istable (L, 2)) { int i; const char *opts = luaL_optstring(L, 3, "n"); if (strchr(opts, 'n') != NULL) { /* Copy values to numerical indices */ for (i = 0; i < cur->numcols;) { push_column(L, vm, i); lua_rawseti(L, 2, ++i); } } if (strchr(opts, 'a') != NULL) { /* Copy values to alphanumerical indices */ lua_rawgeti(L, LUA_REGISTRYINDEX, cur->colnames); for (i = 0; i < cur->numcols; i++) { lua_rawgeti(L, -1, i+1); push_column(L, vm, i); lua_rawset (L, 2); } } lua_pushvalue(L, 2); return 1; /* return table */ } else { int i; luaL_checkstack (L, cur->numcols, LUASQL_PREFIX"too many columns"); for (i = 0; i < cur->numcols; ++i) push_column(L, vm, i); return cur->numcols; /* return #numcols values */ } } /* ** Cursor object collector function */ static int cur_gc(lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata(L, 1, LUASQL_CURSOR_SQLITE); if (cur != NULL && !(cur->closed)) { sqlite3_finalize(cur->sql_vm); cur_nullify(L, cur); } return 0; } /* ** Close the cursor on top of the stack. ** Return 1 */ static int cur_close(lua_State *L) { cur_data *cur = (cur_data *)luaL_checkudata(L, 1, LUASQL_CURSOR_SQLITE); luaL_argcheck(L, cur != NULL, 1, LUASQL_PREFIX"cursor expected"); if (cur->closed) { lua_pushboolean(L, 0); return 1; } sqlite3_finalize(cur->sql_vm); cur_nullify(L, cur); lua_pushboolean(L, 1); return 1; } /* ** Return the list of field names. */ static int cur_getcolnames(lua_State *L) { cur_data *cur = getcursor(L); lua_rawgeti(L, LUA_REGISTRYINDEX, cur->colnames); return 1; } /* ** Return the list of field types. */ static int cur_getcoltypes(lua_State *L) { cur_data *cur = getcursor(L); lua_rawgeti(L, LUA_REGISTRYINDEX, cur->coltypes); return 1; } /* ** Create a new Cursor object and push it on top of the stack. */ /* static int create_cursor(lua_State *L, int conn, sqlite3_stmt *sql_vm, int numcols, const char **row, const char **col_info)*/ static int create_cursor(lua_State *L, int o, conn_data *conn, sqlite3_stmt *sql_vm, int numcols) { int i; cur_data *cur = (cur_data*)lua_newuserdata(L, sizeof(cur_data)); luasql_setmeta (L, LUASQL_CURSOR_SQLITE); /* increment cursor count for the connection creating this cursor */ conn->cur_counter++; /* fill in structure */ cur->closed = 0; cur->conn = LUA_NOREF; cur->numcols = numcols; cur->colnames = LUA_NOREF; cur->coltypes = LUA_NOREF; cur->sql_vm = sql_vm; cur->conn_data = conn; lua_pushvalue(L, o); cur->conn = luaL_ref(L, LUA_REGISTRYINDEX); /* create table with column names */ lua_newtable(L); for (i = 0; i < numcols;) { lua_pushstring(L, sqlite3_column_name(sql_vm, i)); lua_rawseti(L, -2, ++i); } cur->colnames = luaL_ref(L, LUA_REGISTRYINDEX); /* create table with column types */ lua_newtable(L); for (i = 0; i < numcols;) { lua_pushstring(L, sqlite3_column_decltype(sql_vm, i)); lua_rawseti(L, -2, ++i); } cur->coltypes = luaL_ref(L, LUA_REGISTRYINDEX); return 1; } /* ** Connection object collector function */ static int conn_gc(lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata(L, 1, LUASQL_CONNECTION_SQLITE); if (conn != NULL && !(conn->closed)) { if (conn->cur_counter > 0) return luaL_error (L, LUASQL_PREFIX"there are open cursors"); /* Nullify structure fields. */ conn->closed = 1; luaL_unref(L, LUA_REGISTRYINDEX, conn->env); sqlite3_close(conn->sql_conn); } return 0; } /* ** Close a Connection object. */ static int conn_close(lua_State *L) { conn_data *conn = (conn_data *)luaL_checkudata(L, 1, LUASQL_CONNECTION_SQLITE); luaL_argcheck (L, conn != NULL, 1, LUASQL_PREFIX"connection expected"); if (conn->closed) { lua_pushboolean(L, 0); return 1; } conn_gc(L); lua_pushboolean(L, 1); return 1; } static int conn_escape(lua_State *L) { const char *from = luaL_checklstring (L, 2, 0); char *escaped = sqlite3_mprintf("%q", from); if (escaped == NULL) { lua_pushnil(L); } else { lua_pushstring(L, escaped); sqlite3_free(escaped); } return 1; } /* ** 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); int res; sqlite3_stmt *vm; const char *errmsg; int numcols; const char *tail; res = sqlite3_prepare(conn->sql_conn, statement, -1, &vm, &tail); if (res != SQLITE_OK) { errmsg = sqlite3_errmsg(conn->sql_conn); return luasql_faildirect(L, errmsg); } /* process first result to retrive query information and type */ res = sqlite3_step(vm); numcols = sqlite3_column_count(vm); /* real query? if empty, must have numcols!=0 */ if ((res == SQLITE_ROW) || ((res == SQLITE_DONE) && numcols)) { sqlite3_reset(vm); return create_cursor(L, 1, conn, vm, numcols); } if (res == SQLITE_DONE) /* and numcols==0, INSERT,UPDATE,DELETE statement */ { sqlite3_finalize(vm); /* return number of columns changed */ lua_pushnumber(L, sqlite3_changes(conn->sql_conn)); return 1; } /* error */ errmsg = sqlite3_errmsg(conn->sql_conn); sqlite3_finalize(vm); return luasql_faildirect(L, errmsg); } /* ** Commit the current transaction. */ static int conn_commit(lua_State *L) { char *errmsg; conn_data *conn = getconnection(L); int res; const char *sql = "COMMIT"; if (conn->auto_commit == 0) sql = "COMMIT;BEGIN"; res = sqlite3_exec(conn->sql_conn, sql, NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite3_free(errmsg); lua_concat(L, 2); return 2; } lua_pushboolean(L, 1); return 1; } /* ** Rollback the current transaction. */ static int conn_rollback(lua_State *L) { char *errmsg; conn_data *conn = getconnection(L); int res; const char *sql = "ROLLBACK"; if (conn->auto_commit == 0) sql = "ROLLBACK;BEGIN"; res = sqlite3_exec(conn->sql_conn, sql, NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite3_free(errmsg); lua_concat(L, 2); return 2; } lua_pushboolean(L, 1); return 1; } static int conn_getlastautoid(lua_State *L) { conn_data *conn = getconnection(L); lua_pushnumber(L, sqlite3_last_insert_rowid(conn->sql_conn)); return 1; } /* ** Set "auto commit" property of the connection. ** If 'true', then rollback current transaction. ** If 'false', then start a new transaction. */ static int conn_setautocommit(lua_State *L) { conn_data *conn = getconnection(L); if (lua_toboolean(L, 2)) { conn->auto_commit = 1; /* undo active transaction - ignore errors */ sqlite3_exec(conn->sql_conn, "ROLLBACK", NULL, NULL, NULL); } else { char *errmsg; int res; conn->auto_commit = 0; res = sqlite3_exec(conn->sql_conn, "BEGIN", NULL, NULL, &errmsg); if (res != SQLITE_OK) { lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, errmsg); sqlite3_free(errmsg); lua_concat(L, 2); lua_error(L); } } lua_pushboolean(L, 1); return 1; } /* ** Create a new Connection object and push it on top of the stack. */ static int create_connection(lua_State *L, int env, sqlite3 *sql_conn) { conn_data *conn = (conn_data*)lua_newuserdata(L, sizeof(conn_data)); luasql_setmeta(L, LUASQL_CONNECTION_SQLITE); /* fill in structure */ conn->closed = 0; conn->env = LUA_NOREF; conn->auto_commit = 1; conn->sql_conn = sql_conn; conn->cur_counter = 0; lua_pushvalue (L, env); conn->env = luaL_ref (L, LUA_REGISTRYINDEX); return 1; } /* ** Connects to a data source. */ static int env_connect(lua_State *L) { const char *sourcename; sqlite3 *conn; const char *errmsg; int res; getenvironment(L); /* validate environment */ sourcename = luaL_checkstring(L, 2); res = sqlite3_open(sourcename, &conn); if (res != SQLITE_OK) { errmsg = sqlite3_errmsg(conn); luasql_faildirect(L, errmsg); sqlite3_close(conn); return 2; } if (lua_isnumber(L, 3)) { sqlite3_busy_timeout(conn, lua_tonumber(L,3)); /* TODO: remove this */ } return create_connection(L, 1, conn); } /* ** Environment object collector function. */ static int env_gc (lua_State *L) { env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SQLITE); if (env != NULL && !(env->closed)) env->closed = 1; return 0; } /* ** Close environment object. */ static int env_close (lua_State *L) { env_data *env = (env_data *)luaL_checkudata(L, 1, LUASQL_ENVIRONMENT_SQLITE); luaL_argcheck(L, env != NULL, 1, LUASQL_PREFIX"environment expected"); if (env->closed) { lua_pushboolean(L, 0); return 1; } env_gc(L); lua_pushboolean(L, 1); return 1; } /* ** Sets the timeout for a lock in the connection. static int opts_settimeout (lua_State *L) { conn_data *conn = getconnection(L); int milisseconds = luaL_checknumber(L, 2); lua_pushnumber(L, sqlite3_busy_timeout(conn->sql_conn, milisseconds)); return 1; } */ /* ** Create metatables for each class of object. */ static void create_metatables (lua_State *L) { struct luaL_Reg environment_methods[] = { {"__gc", env_gc}, {"close", env_close}, {"connect", env_connect}, {NULL, NULL}, }; struct luaL_Reg connection_methods[] = { {"__gc", conn_gc}, {"close", conn_close}, {"escape", conn_escape}, {"execute", conn_execute}, {"commit", conn_commit}, {"rollback", conn_rollback}, {"setautocommit", conn_setautocommit}, {"getlastautoid", conn_getlastautoid}, {NULL, NULL}, }; struct luaL_Reg cursor_methods[] = { {"__gc", cur_gc}, {"close", cur_close}, {"getcolnames", cur_getcolnames}, {"getcoltypes", cur_getcoltypes}, {"fetch", cur_fetch}, {NULL, NULL}, }; luasql_createmeta(L, LUASQL_ENVIRONMENT_SQLITE, environment_methods); luasql_createmeta(L, LUASQL_CONNECTION_SQLITE, connection_methods); luasql_createmeta(L, LUASQL_CURSOR_SQLITE, cursor_methods); lua_pop (L, 3); } /* ** Creates an Environment and returns it. */ static int create_environment (lua_State *L) { env_data *env = (env_data *)lua_newuserdata(L, sizeof(env_data)); luasql_setmeta(L, LUASQL_ENVIRONMENT_SQLITE); /* fill in structure */ env->closed = 0; return 1; } /* ** Creates the metatables for the objects and registers the ** driver open method. */ LUASQL_API int luaopen_luasql_sqlite3(lua_State *L) { struct luaL_Reg driver[] = { {"sqlite3", create_environment}, {NULL, NULL}, }; create_metatables (L); lua_newtable (L); luaL_setfuncs (L, driver, 0); luasql_set_info (L); return 1; } keplerproject-luasql-c527024/src/luasql.c000066400000000000000000000061041175743000500203710ustar00rootroot00000000000000/* ** $Id: luasql.c,v 1.28 2009/02/11 12:08:50 tomas Exp $ ** See Copyright Notice in license.html */ #include #include "lua.h" #include "lauxlib.h" #include "luasql.h" #if !defined(lua_pushliteral) #define lua_pushliteral(L, s) \ lua_pushstring(L, "" s, (sizeof(s)/sizeof(char))-1) #endif /* ** Typical database error situation */ LUASQL_API int luasql_faildirect(lua_State *L, const char *err) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, err); lua_concat(L, 2); return 2; } /* ** Database error with LuaSQL message ** @param err LuaSQL error message. ** @param m Driver error message. */ LUASQL_API int luasql_failmsg(lua_State *L, const char *err, const char *m) { lua_pushnil(L); lua_pushliteral(L, LUASQL_PREFIX); lua_pushstring(L, err); lua_pushstring(L, m); lua_concat(L, 3); return 2; } typedef struct { short closed; } pseudo_data; /* ** Return the name of the object's metatable. ** This function is used by `tostring'. */ static int luasql_tostring (lua_State *L) { char buff[100]; pseudo_data *obj = (pseudo_data *)lua_touserdata (L, 1); if (obj->closed) strcpy (buff, "closed"); else sprintf (buff, "%p", (void *)obj); lua_pushfstring (L, "%s (%s)", lua_tostring(L,lua_upvalueindex(1)), buff); return 1; } #if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501 /* ** Adapted from Lua 5.2.0 */ void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { luaL_checkstack(L, nup, "too many upvalues"); for (; l->name != NULL; l++) { /* fill the table with given functions */ int i; for (i = 0; i < nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -nup); lua_pushstring(L, l->name); lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ lua_settable(L, -(nup + 3)); } lua_pop(L, nup); /* remove upvalues */ } #endif /* ** Create a metatable and leave it on top of the stack. */ LUASQL_API int luasql_createmeta (lua_State *L, const char *name, const luaL_Reg *methods) { if (!luaL_newmetatable (L, name)) return 0; /* define methods */ luaL_setfuncs (L, methods, 0); /* define metamethods */ lua_pushliteral (L, "__index"); lua_pushvalue (L, -2); lua_settable (L, -3); lua_pushliteral (L, "__tostring"); lua_pushstring (L, name); lua_pushcclosure (L, luasql_tostring, 1); lua_settable (L, -3); lua_pushliteral (L, "__metatable"); lua_pushliteral (L, LUASQL_PREFIX"you're not allowed to get this metatable"); lua_settable (L, -3); return 1; } /* ** Define the metatable for the object on top of the stack */ LUASQL_API void luasql_setmeta (lua_State *L, const char *name) { luaL_getmetatable (L, name); lua_setmetatable (L, -2); } /* ** Assumes the table is on top of the stack. */ LUASQL_API void luasql_set_info (lua_State *L) { lua_pushliteral (L, "_COPYRIGHT"); lua_pushliteral (L, "Copyright (C) 2003-2012 Kepler Project"); lua_settable (L, -3); lua_pushliteral (L, "_DESCRIPTION"); lua_pushliteral (L, "LuaSQL is a simple interface from Lua to a DBMS"); lua_settable (L, -3); lua_pushliteral (L, "_VERSION"); lua_pushliteral (L, "LuaSQL 2.3.0"); lua_settable (L, -3); } keplerproject-luasql-c527024/src/luasql.h000066400000000000000000000021031175743000500203710ustar00rootroot00000000000000/* ** $Id: luasql.h,v 1.12 2009/02/07 23:16:23 tomas Exp $ ** See Copyright Notice in license.html */ #ifndef _LUASQL_ #define _LUASQL_ #ifndef LUASQL_API #define LUASQL_API #endif #if !defined LUA_VERSION_NUM /* Lua 5.0 */ #define luaL_Reg luaL_reg #define lua_pushinteger(L, n) \ lua_pushnumber(L, (lua_Number)n) #endif #define LUASQL_PREFIX "LuaSQL: " #define LUASQL_TABLENAME "luasql" #define LUASQL_ENVIRONMENT "Each driver must have an environment metatable" #define LUASQL_CONNECTION "Each driver must have a connection metatable" #define LUASQL_CURSOR "Each driver must have a cursor metatable" LUASQL_API int luasql_faildirect (lua_State *L, const char *err); LUASQL_API int luasql_failmsg (lua_State *L, const char *err, const char *m); LUASQL_API int luasql_createmeta (lua_State *L, const char *name, const luaL_Reg *methods); LUASQL_API void luasql_setmeta (lua_State *L, const char *name); LUASQL_API void luasql_set_info (lua_State *L); #if !defined LUA_VERSION_NUM || LUA_VERSION_NUM==501 void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup); #endif #endif keplerproject-luasql-c527024/src/mysql.def000066400000000000000000000000361175743000500205470ustar00rootroot00000000000000EXPORTS luaopen_luasql_mysql keplerproject-luasql-c527024/src/oci8.def000066400000000000000000000000351175743000500202430ustar00rootroot00000000000000EXPORTS luaopen_luasql_oci8 keplerproject-luasql-c527024/src/odbc.def000066400000000000000000000000351175743000500203100ustar00rootroot00000000000000EXPORTS luaopen_luasql_odbc keplerproject-luasql-c527024/src/postgres.def000066400000000000000000000000411175743000500212440ustar00rootroot00000000000000EXPORTS luaopen_luasql_postgres keplerproject-luasql-c527024/src/sqlite.def000066400000000000000000000000371175743000500207040ustar00rootroot00000000000000EXPORTS luaopen_luasql_sqlite keplerproject-luasql-c527024/src/sqlite3.def000066400000000000000000000000401175743000500207610ustar00rootroot00000000000000EXPORTS luaopen_luasql_sqlite3 keplerproject-luasql-c527024/tests/000077500000000000000000000000001175743000500172765ustar00rootroot00000000000000keplerproject-luasql-c527024/tests/ado.lua000066400000000000000000000001051175743000500205400ustar00rootroot00000000000000#!/usr/local/bin/lua50 QUERYING_STRING_TYPE_NAME = "adLongVarWChar" keplerproject-luasql-c527024/tests/example.lua000066400000000000000000000021141175743000500214320ustar00rootroot00000000000000-- See Copyright Notice in license.html -- load driver require"luasql.postgres" -- create environment object env = assert (luasql.postgres()) -- connect to data source con = assert (env:connect("luasql-test")) -- reset our table res = con:execute"DROP TABLE people" res = assert (con:execute[[ CREATE TABLE people( name varchar(50), email varchar(50) ) ]]) -- add a few elements list = { { name="Jose das Couves", email="jose@couves.com", }, { name="Manoel Joaquim", email="manoel.joaquim@cafundo.com", }, { name="Maria das Dores", email="maria@dores.com", }, } for i, p in pairs (list) do res = assert (con:execute(string.format([[ INSERT INTO people VALUES ('%s', '%s')]], p.name, p.email) )) end -- retrieve a cursor cur = assert (con:execute"SELECT name, email from people") -- print all rows row = cur:fetch ({}, "a") -- the rows will be indexed by field names while row do print(string.format("Name: %s, E-mail: %s", row.name, row.email)) row = cur:fetch (row, "a") -- reusing the table of results end -- close everything cur:close() con:close() env:close() keplerproject-luasql-c527024/tests/firebird.lua000066400000000000000000000006411175743000500215700ustar00rootroot00000000000000DEFINITION_STRING_TYPE_NAME = "VARCHAR(80)" QUERYING_STRING_TYPE_NAME = "string" CHECK_GETCOL_INFO_TABLES = false local orig_create_table = create_table --------------------------------------------------------------------- -- New metadata needs to be commited before it is used --------------------------------------------------------------------- function create_table () orig_create_table() CONN:commit() end keplerproject-luasql-c527024/tests/mysql.lua000066400000000000000000000020661175743000500211520ustar00rootroot00000000000000--------------------------------------------------------------------- -- MySQL specific tests and configurations. -- $Id: mysql.lua,v 1.4 2006/01/25 20:28:30 tomas Exp $ --------------------------------------------------------------------- QUERYING_STRING_TYPE_NAME = "binary(65535)" table.insert (CUR_METHODS, "numrows") table.insert (EXTENSIONS, numrows) --------------------------------------------------------------------- -- Build SQL command to create the test table. --------------------------------------------------------------------- local _define_table = define_table function define_table (n) return _define_table(n) .. " TYPE = InnoDB;" end --------------------------------------------------------------------- -- MySQL versions 4.0.x do not implement rollback. --------------------------------------------------------------------- local _rollback = rollback function rollback () if luasql._MYSQLVERSION and string.sub(luasql._MYSQLVERSION, 1, 3) == "4.0" then io.write("skipping rollback test (mysql version 4.0.x)") return else _rollback () end end keplerproject-luasql-c527024/tests/oci8.lua000066400000000000000000000006161175743000500206460ustar00rootroot00000000000000--------------------------------------------------------------------- -- Oracle specific tests and configurations. -- $Id: oci8.lua,v 1.3 2006/05/31 21:43:15 carregal Exp $ --------------------------------------------------------------------- table.insert (CUR_METHODS, "numrows") table.insert (EXTENSIONS, numrows) DEFINITION_STRING_TYPE_NAME = "varchar(60)" QUERYING_STRING_TYPE_NAME = "string"keplerproject-luasql-c527024/tests/odbc.lua000066400000000000000000000025341175743000500207140ustar00rootroot00000000000000--------------------------------------------------------------------- -- ODBC specific tests and configurations. -- $Id: odbc.lua,v 1.2 2006/01/25 19:54:21 tomas Exp $ --------------------------------------------------------------------- QUERYING_STRING_TYPE_NAME = "string" -- The CREATE_TABLE_RETURN_VALUE and DROP_TABLE_RETURN_VALUE works -- with -1 on MS Acess Driver, and 0 on SQL Server Driver CREATE_TABLE_RETURN_VALUE = -1 DROP_TABLE_RETURN_VALUE = -1 --------------------------------------------------------------------- -- Test of data types managed by ODBC driver. --------------------------------------------------------------------- table.insert (EXTENSIONS, function () assert2 (CREATE_TABLE_RETURN_VALUE, CONN:execute"create table test_dt (f1 integer, f2 varchar(30), f3 bit )") -- Inserts a number, a string value and a "bit" value. assert2 (1, CONN:execute"insert into test_dt values (10, 'ABCDE', 1)") -- Checks the results with the inserted values. local cur = CUR_OK (CONN:execute"select * from test_dt") local row, err = cur:fetch ({}, "a") assert2 ("table", type(row), err) assert2 (10, row.f1, "Wrong number representation") assert2 ("ABCDE", row.f2, "Wrong string representation") assert2 (true, row.f3, "Wrong bit representation") -- Drops the table assert2 (DROP_TABLE_RETURN_VALUE0, CONN:execute("drop table test_dt") ) end) keplerproject-luasql-c527024/tests/performance.lua000066400000000000000000000115301175743000500223020ustar00rootroot00000000000000#!/usr/local/bin/lua -- See Copyright Notice in license.html TOTAL_ROWS = 200 --------------------------------------------------------------------- -- checks for a value and throw an error if it is invalid. --------------------------------------------------------------------- function assert2 (expected, value, msg) if not msg then msg = '' else msg = msg..'\n' end return assert (value == expected, msg.."wrong value (["..tostring(value).."] instead of ".. tostring(expected)..")") end --------------------------------------------------------------------- -- object test. --------------------------------------------------------------------- function test_object (obj, objmethods) -- checking object type. assert2 ("userdata", type(obj), "incorrect object type") -- trying to get metatable. assert2 ("LuaSQL: you're not allowed to get this metatable", getmetatable(obj), "error permitting access to object's metatable") -- trying to set metatable. assert2 (false, pcall (setmetatable, ENV, {})) -- checking existence of object's methods. for i = 1, table.getn (objmethods) do local method = objmethods[i] assert2 ("function", type(obj[method])) end return obj end ENV_OK = function (obj) return test_object (obj, { "close", "connect", }) end CONN_OK = function (obj) return test_object (obj, { "close", "commit", "execute", "rollback", "setautocommit", }) end CUR_OK = function (obj) return test_object (obj, { "close", "fetch", "getcolnames", "getcoltypes", }) end --------------------------------------------------------------------- -- Main --------------------------------------------------------------------- if type(arg[1]) ~= "string" then print (string.format ("Usage %s [ [, [, ]]]", arg[0])) os.exit() end local driver = arg[1] local datasource = arg[2] or "luasql-test" local username = arg[3] or nil local password = arg[4] or nil require (arg[1]) assert (luasql, "no luasql table") local env, err = luasql[driver] () assert (env, err) conn, err = env:connect (datasource, username, password) assert (conn, err) conn:execute ("drop table fetch_test") -- Create test table local n, err = conn:execute ([[ create table fetch_test ( f1 varchar(30), f2 varchar(30), f3 varchar(30), f4 varchar(30), f5 varchar(30), f6 varchar(30), f7 varchar(30), f8 varchar(30) )]]) assert (n, err) assert (type(n) == "number", "couldn't create fetch_test table") -- Insert rows for i = 1, TOTAL_ROWS do local n, err = conn:execute ( "insert into fetch_test values ('f1','f2','f3','f4','f5','f6','f7','f8')") assert (n, err) assert (type (n) == "number", "couldn't insert rows") end print ("table created; rows inserted") -- default local cur, err = conn:execute ("select * from fetch_test") assert (cur, err) --assert (cur:numrows() == TOTAL_ROWS, "wrong number of rows") local t1 = os.clock() --for i = 1, cur:numrows() do --local f1,f2,f3,f4,f5,f6,f7,f8 = cur:fetch() --end local f1,f2,f3,f4,f5,f6,f7,f8 = cur:fetch() while f1 do f1,f2,f3,f4,f5,f6,f7,f8 = cur:fetch() end print ("default: ", os.clock() - t1) assert (cur:close () == 1, "couldn't close cursor object") -- using the same table local cur, err = conn:execute ("select * from fetch_test") assert (cur, err) --assert (cur:numrows() == TOTAL_ROWS, "wrong number of rows") t1 = os.clock() local t = {} --for i = 1, cur:numrows() do --t = cur:fetch (t) --end t = cur:fetch(t) while t do t = cur:fetch(t) end print ("same table: ", os.clock() - t1) assert (cur:close () == 1, "couldn't close cursor object") -- using the same table with alphanumeric keys local cur, err = conn:execute ("select * from fetch_test") assert (cur, err) --assert (cur:numrows() == TOTAL_ROWS, "wrong number of rows") t1 = os.clock() local t = {} --for i = 1, cur:numrows() do --t = cur:fetch (t,"a") --end t = cur:fetch (t, "a") while t do t = cur:fetch (t, "a") end print ("alpha keys: ", os.clock() - t1) assert (cur:close () == 1, "couldn't close cursor object") -- using the same table with numeric and alphanumeric keys local cur, err = conn:execute ("select * from fetch_test") assert (cur, err) --assert (cur:numrows() == TOTAL_ROWS, "wrong number of rows") t1 = os.clock() local t = {} --for i = 1, cur:numrows() do --t = cur:fetch (t,"an") --end t = cur:fetch (t, "an") while t do t = cur:fetch (t, "an") end print ("all keys: ", os.clock() - t1) assert (cur:close () == 1, "couldn't close cursor object") -- creating a table local cur, err = conn:execute ("select * from fetch_test") assert (cur, err) --assert (cur:numrows() == TOTAL_ROWS, "wrong number of rows") t1 = os.clock() --for i = 1, cur:numrows() do --local t = cur:fetch{} --end while cur:fetch{} do end print ("new table: ", os.clock() - t1) assert (cur:close () == 1, "couldn't close cursor object") assert (conn:close () == 1, "couldn't close connection object") assert (env:close () == 1, "couldn't close environment object") keplerproject-luasql-c527024/tests/postgres.lua000066400000000000000000000005021175743000500216440ustar00rootroot00000000000000--------------------------------------------------------------------- -- PostgreSQL specific tests and configurations. -- $Id: postgres.lua,v 1.2 2006/01/25 19:15:21 tomas Exp $ --------------------------------------------------------------------- table.insert (CUR_METHODS, "numrows") table.insert (EXTENSIONS, numrows) keplerproject-luasql-c527024/tests/sqlite.lua000066400000000000000000000012761175743000500213100ustar00rootroot00000000000000--------------------------------------------------------------------- -- SQLite specific tests and configurations. -- $Id: sqlite.lua,v 1.2 2006/05/31 21:43:33 carregal Exp $ --------------------------------------------------------------------- --------------------------------------------------------------------- -- Produces a SQL statement which completely erases a table. -- @param table_name String with the name of the table. -- @return String with SQL statement. --------------------------------------------------------------------- function sql_erase_table (table_name) return string.format ("delete from %s where 1", table_name) end function checkUnknownDatabase(ENV) -- skip this test endkeplerproject-luasql-c527024/tests/sqlite3.lua000066400000000000000000000013341175743000500213660ustar00rootroot00000000000000--------------------------------------------------------------------- -- SQLite specific tests and configurations. -- $Id: sqlite3.lua,v 1.2 2007/10/16 15:42:50 carregal Exp $ --------------------------------------------------------------------- DROP_TABLE_RETURN_VALUE = 1 --------------------------------------------------------------------- -- Produces a SQL statement which completely erases a table. -- @param table_name String with the name of the table. -- @return String with SQL statement. --------------------------------------------------------------------- function sql_erase_table (table_name) return string.format ("delete from %s where 1", table_name) end function checkUnknownDatabase(ENV) -- skip this test endkeplerproject-luasql-c527024/tests/test.lua000066400000000000000000000567421175743000500207760ustar00rootroot00000000000000#!/usr/local/bin/lua5.1 -- See Copyright Notice in license.html -- $Id: test.lua,v 1.52 2008/06/30 10:43:03 blumf Exp $ TOTAL_FIELDS = 40 TOTAL_ROWS = 40 --unused DEFINITION_STRING_TYPE_NAME = "text" QUERYING_STRING_TYPE_NAME = "text" CREATE_TABLE_RETURN_VALUE = 0 DROP_TABLE_RETURN_VALUE = 0 MSG_CURSOR_NOT_CLOSED = "cursor was not automatically closed by fetch" CHECK_GETCOL_INFO_TABLES = true --------------------------------------------------------------------- if not string.find(_VERSION, " 5.0") then table.getn = assert((loadstring or load)[[return function (t) return #t end]])() end --------------------------------------------------------------------- -- Creates a table that can handle differing capitalization of field -- names -- @return A table with altered metatable --------------------------------------------------------------------- local mt = { __index = function(t, i) if type(i) == "string" then return rawget(t, string.upper(i)) or rawget(t, string.lower(i)) end return rawget(t, i) end } function fetch_table () return setmetatable({}, mt) end --------------------------------------------------------------------- -- Produces a SQL statement which completely erases a table. -- @param table_name String with the name of the table. -- @return String with SQL statement. --------------------------------------------------------------------- function sql_erase_table (table_name) return string.format ("delete from %s", table_name) end --------------------------------------------------------------------- -- checks for a value and throw an error if it is invalid. --------------------------------------------------------------------- function assert2 (expected, value, msg) if not msg then msg = '' else msg = msg..'\n' end return assert (value == expected, msg.."wrong value ("..tostring(value).." instead of ".. tostring(expected)..")") end --------------------------------------------------------------------- -- Shallow compare of two tables --------------------------------------------------------------------- function table_compare(t1, t2) if t1 == t2 then return true; end for i, v in pairs(t1) do if t2[i] ~= v then return false; end end for i, v in pairs(t2) do if t1[i] ~= v then return false; end end return true end --------------------------------------------------------------------- -- object test. --------------------------------------------------------------------- function test_object (obj, objmethods) -- checking object type. assert2 (true, type(obj) == "userdata" or type(obj) == "table", "incorrect object type") -- trying to get metatable. assert2 ("LuaSQL: you're not allowed to get this metatable", getmetatable(obj), "error permitting access to object's metatable") -- trying to set metatable. assert2 (false, pcall (setmetatable, ENV, {})) -- checking existence of object's methods. for i = 1, table.getn (objmethods) do local method = obj[objmethods[i]] assert2 ("function", type(method)) assert2 (false, pcall (method), "no 'self' parameter accepted") end return obj end ENV_METHODS = { "close", "connect", } ENV_OK = function (obj) return test_object (obj, ENV_METHODS) end CONN_METHODS = { "close", "commit", "execute", "rollback", "setautocommit", } CONN_OK = function (obj) return test_object (obj, CONN_METHODS) end CUR_METHODS = { "close", "fetch", "getcolnames", "getcoltypes", } CUR_OK = function (obj) return test_object (obj, CUR_METHODS) end function checkUnknownDatabase(ENV) assert2 (nil, ENV:connect ("/unknown-data-base"), "this should be an error") end --------------------------------------------------------------------- -- basic checking test. --------------------------------------------------------------------- function basic_test () -- Check environment object. ENV = ENV_OK (luasql[driver] ()) assert2 (true, ENV:close(), "couldn't close environment") -- trying to connect with a closed environment. assert2 (false, pcall (ENV.connect, ENV, datasource, username, password), "error connecting with a closed environment") -- it is ok to close a closed object, but false is returned instead of true. assert2 (false, ENV:close()) -- Reopen the environment. ENV = ENV_OK (luasql[driver] ()) -- Check connection object. local conn, err = ENV:connect (datasource, username, password) assert (conn, (err or '').." ("..datasource..")") CONN_OK (conn) assert2 (true, conn:close(), "couldn't close connection") -- trying to execute a statement with a closed connection. assert2 (false, pcall (conn.execute, conn, "create table x (c char)"), "error while executing through a closed connection") -- it is ok to close a closed object, but false is returned instead of true. assert2 (false, conn:close()) -- Check error situation. checkUnknownDatabase(ENV) -- force garbage collection local a = {} setmetatable(a, {__mode="v"}) a.ENV = ENV_OK (luasql[driver] ()) a.CONN = a.ENV:connect (datasource, username, password) collectgarbage () collectgarbage () assert2(nil, a.ENV, "environment not collected") assert2(nil, a.CONN, "connection not collected") end --------------------------------------------------------------------- -- Build SQL command to create the test table. --------------------------------------------------------------------- function define_table (n) local t = {} for i = 1, n do table.insert (t, "f"..i.." "..DEFINITION_STRING_TYPE_NAME) end return "create table t ("..table.concat (t, ',')..")" end --------------------------------------------------------------------- -- Create a table with TOTAL_FIELDS character fields. --------------------------------------------------------------------- function create_table () -- Check SQL statements. CONN = CONN_OK (ENV:connect (datasource, username, password)) -- Create t. local cmd = define_table(TOTAL_FIELDS) assert2 (CREATE_TABLE_RETURN_VALUE, CONN:execute (cmd)) end --------------------------------------------------------------------- -- Fetch 2 values. --------------------------------------------------------------------- function fetch2 () -- insert a record. assert2 (1, CONN:execute ("insert into t (f1, f2) values ('b', 'c')")) -- retrieve data. local cur = CUR_OK (CONN:execute ("select f1, f2, f3 from t")) -- check data. local f1, f2, f3 = cur:fetch() assert2 ('b', f1) assert2 ('c', f2) assert2 (nil, f3) assert2 (nil, cur:fetch()) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- insert a second record. assert2 (1, CONN:execute ("insert into t (f1, f2) values ('d', 'e')")) cur = CUR_OK (CONN:execute ("select f1, f2, f3 from t order by f1")) local f1, f2, f3 = cur:fetch() assert2 ('b', f1, f2) -- f2 can be an error message assert2 ('c', f2) assert2 (nil, f3) f1, f2, f3 = cur:fetch() assert2 ('d', f1, f2) -- f2 can be an error message assert2 ('e', f2) assert2 (nil, f3) assert2 (nil, cur:fetch()) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- remove records. assert2 (2, CONN:execute ("delete from t where f1 in ('b', 'd')")) end --------------------------------------------------------------------- -- Test fetch with a new table, reusing a table and with different -- indexing. --------------------------------------------------------------------- function fetch_new_table () -- insert elements. assert2 (1, CONN:execute ("insert into t (f1, f2, f3, f4) values ('a', 'b', 'c', 'd')")) assert2 (1, CONN:execute ("insert into t (f1, f2, f3, f4) values ('f', 'g', 'h', 'i')")) -- retrieve data using a new table. local cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch(fetch_table()) assert2 (type(row), "table", err) assert2 ('a', row[1]) assert2 ('b', row[2]) assert2 ('c', row[3]) assert2 ('d', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) row, err = cur:fetch(fetch_table()) assert (type(row), "table", err) assert2 ('f', row[1]) assert2 ('g', row[2]) assert2 ('h', row[3]) assert2 ('i', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) assert2 (nil, cur:fetch{}) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- retrieve data reusing the same table. io.write ("reusing a table...") cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch(fetch_table()) assert (type(row), "table", err) assert2 ('a', row[1]) assert2 ('b', row[2]) assert2 ('c', row[3]) assert2 ('d', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) row, err = cur:fetch (row) assert (type(row), "table", err) assert2 ('f', row[1]) assert2 ('g', row[2]) assert2 ('h', row[3]) assert2 ('i', row[4]) assert2 (nil, row.f1) assert2 (nil, row.f2) assert2 (nil, row.f3) assert2 (nil, row.f4) assert2 (nil, cur:fetch(fetch_table())) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- retrieve data reusing the same table with alphabetic indexes. io.write ("with alpha keys...") cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch (fetch_table(), "a") assert (type(row), "table", err) assert2 (nil, row[1]) assert2 (nil, row[2]) assert2 (nil, row[3]) assert2 (nil, row[4]) assert2 ('a', row.f1) assert2 ('b', row.f2) assert2 ('c', row.f3) assert2 ('d', row.f4) row, err = cur:fetch (row, "a") assert2 (type(row), "table", err) assert2 (nil, row[1]) assert2 (nil, row[2]) assert2 (nil, row[3]) assert2 (nil, row[4]) assert2 ('f', row.f1) assert2 ('g', row.f2) assert2 ('h', row.f3) assert2 ('i', row.f4) assert2 (nil, cur:fetch(row, "a")) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- retrieve data reusing the same table with both indexes. io.write ("with both keys...") cur = CUR_OK (CONN:execute ("select f1, f2, f3, f4 from t order by f1")) local row, err = cur:fetch (fetch_table(), "an") assert (type(row), "table", err) assert2 ('a', row[1]) assert2 ('b', row[2]) assert2 ('c', row[3]) assert2 ('d', row[4]) assert2 ('a', row.f1) assert2 ('b', row.f2) assert2 ('c', row.f3) assert2 ('d', row.f4) row, err = cur:fetch (row, "an") assert (type(row), "table", err) assert2 ('f', row[1]) assert2 ('g', row[2]) assert2 ('h', row[3]) assert2 ('i', row[4]) assert2 ('f', row.f1) assert2 ('g', row.f2) assert2 ('h', row.f3) assert2 ('i', row.f4) assert2 (nil, cur:fetch(row, "an")) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) assert2 (false, cur:close()) -- clean the table. assert2 (2, CONN:execute ("delete from t where f1 in ('a', 'f')")) end --------------------------------------------------------------------- -- Fetch many values --------------------------------------------------------------------- function fetch_many () -- insert values. local fields, values = "f1", "'v1'" for i = 2, TOTAL_FIELDS do fields = string.format ("%s,f%d", fields, i) values = string.format ("%s,'v%d'", values, i) end local cmd = string.format ("insert into t (%s) values (%s)", fields, values) assert2 (1, CONN:execute (cmd)) -- fetch values (without a table). local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = { cur:fetch () } assert2 ("string", type(row[1]), "error while trying to fetch many values (without a table)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with a table and default indexing). io.write ("with a table...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch(fetch_table()) assert2 ("string", type(row[1]), "error while trying to fetch many values (default indexing)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with numbered indexes on a table). io.write ("with numbered keys...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch (fetch_table(), "n") assert2 ("string", type(row[1]), "error while trying to fetch many values (numbered indexes)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with alphanumeric indexes on a table). io.write ("with alpha keys...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch (fetch_table(), "a") assert2 ("string", type(row.f1), "error while trying to fetch many values (alphanumeric indexes)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row['f'..i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- fetch values (with both indexes on a table). io.write ("with both keys...") local cur = CUR_OK (CONN:execute ("select * from t where f1 = 'v1'")) local row = cur:fetch (fetch_table(), "na") assert2 ("string", type(row[1]), "error while trying to fetch many values (both indexes)") assert2 ("string", type(row.f1), "error while trying to fetch many values (both indexes)") for i = 1, TOTAL_FIELDS do assert2 ('v'..i, row[i]) assert2 ('v'..i, row['f'..i]) end assert2 (nil, cur:fetch (row)) assert2 (false, cur:close(), MSG_CURSOR_NOT_CLOSED) -- clean the table. assert2 (1, CONN:execute ("delete from t where f1 = 'v1'")) end --------------------------------------------------------------------- --------------------------------------------------------------------- function rollback () -- begin transaction assert2 (true, CONN:setautocommit (false), "couldn't disable autocommit") -- insert a record and commit the operation. assert2 (1, CONN:execute ("insert into t (f1) values ('a')")) local cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber (cur:fetch ()), "Insert failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:commit(), "couldn't commit transaction") -- insert a record and roll back the operation. assert2 (1, CONN:execute ("insert into t (f1) values ('b')")) local cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (2, tonumber (cur:fetch ()), "Insert failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:rollback (), "couldn't roolback transaction") -- check resulting table with one record. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) -- delete a record and roll back the operation. assert2 (1, CONN:execute ("delete from t where f1 = 'a'")) cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (0, tonumber(cur:fetch())) assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:rollback (), "couldn't roolback transaction") -- check resulting table with one record. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) --[[ -- insert a second record and turn on the auto-commit mode. -- this will produce a rollback on PostgreSQL and a commit on ODBC. -- what to do? assert2 (1, CONN:execute ("insert into t (f1) values ('b')")) cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (2, tonumber (cur:fetch ()), "Insert failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) assert2 (true, CONN:setautocommit (true), "couldn't enable autocommit") -- check resulting table with one record. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (1, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) --]] -- clean the table. assert2 (1, CONN:execute (sql_erase_table"t")) assert2 (true, CONN:commit (), "couldn't commit transaction") assert2 (true, CONN:setautocommit (true), "couldn't enable autocommit") -- check resulting table with no records. cur = CUR_OK (CONN:execute ("select count(*) from t")) assert2 (0, tonumber(cur:fetch()), "Rollback failed") assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) end --------------------------------------------------------------------- -- Get column names and types. --------------------------------------------------------------------- function column_info () -- insert elements. assert2 (1, CONN:execute ("insert into t (f1, f2, f3, f4) values ('a', 'b', 'c', 'd')")) local cur = CUR_OK (CONN:execute ("select f1,f2,f3,f4 from t")) -- get column information. local names, types = cur:getcolnames(), cur:getcoltypes() assert2 ("table", type(names), "getcolnames failed") assert2 ("table", type(types), "getcoltypes failed") assert2 (4, table.getn(names), "incorrect column names table") assert2 (4, table.getn(types), "incorrect column types table") for i = 1, table.getn(names) do assert2 ("f"..i, string.lower(names[i]), "incorrect column names table") local type_i = types[i] assert (type_i == QUERYING_STRING_TYPE_NAME, "incorrect column types table") end -- check if the tables are being reused. local n2, t2 = cur:getcolnames(), cur:getcoltypes() if CHECK_GETCOL_INFO_TABLES then assert2 (names, n2, "getcolnames is rebuilding the table") assert2 (types, t2, "getcoltypes is rebuilding the table") else assert2 (true, table_compare(names, n2), "getcolnames is inconsistent") assert2 (true, table_compare(types, t2), "getcoltypes is inconsistent") end assert2 (true, cur:close(), "couldn't close cursor") assert2 (false, cur:close()) -- clean the table. assert2 (1, CONN:execute ("delete from t where f1 = 'a'")) end --------------------------------------------------------------------- -- Escaping strings --------------------------------------------------------------------- function escape () local escaped = CONN:escape"a'b'c'd" assert ("a\\'b\\'c\\'d" == escaped or "a''b''c''d" == escaped) end --------------------------------------------------------------------- --------------------------------------------------------------------- function check_close() -- an object with references to it can't be closed local cmd = "select * from t" local cur = CUR_OK(CONN:execute (cmd)) assert2 (true, cur:close(), "couldn't close cursor") -- force garbage collection local a = {} setmetatable(a, {__mode="v"}) a.CONN = ENV:connect (datasource, username, password) cur = CUR_OK(a.CONN:execute (cmd)) collectgarbage () collectgarbage () CONN_OK (a.CONN) a.cur = cur a.cur:close() a.CONN:close() cur = nil collectgarbage () assert2(nil, a.cur, "cursor not collected") collectgarbage () assert2(nil, a.CONN, "connection not collected") -- check cursor integrity after trying to close a connection local conn = CONN_OK (ENV:connect (datasource, username, password)) assert2 (1, conn:execute"insert into t (f1) values (1)", "could not insert a new record") local cur = CUR_OK (conn:execute (cmd)) local ok, err = pcall (conn.close, conn) CUR_OK (cur) assert (cur:fetch(), "corrupted cursor") cur:close () conn:close () end --------------------------------------------------------------------- --------------------------------------------------------------------- function drop_table () assert2 (true, CONN:setautocommit(true), "couldn't enable autocommit") -- Postgres retorns 0, ODBC retorns -1, sqlite returns 1 assert2 (DROP_TABLE_RETURN_VALUE, CONN:execute ("drop table t")) end --------------------------------------------------------------------- --------------------------------------------------------------------- function close_conn () assert (true, CONN:close()) assert (true, ENV:close()) end --------------------------------------------------------------------- -- Testing Extensions --------------------------------------------------------------------- EXTENSIONS = { } function extensions_test () for i, f in ipairs (EXTENSIONS) do f () end end --------------------------------------------------------------------- -- Testing numrows method. -- This is not a default test, it must be added to the extensions -- table to be executed. --------------------------------------------------------------------- function numrows() local cur = CUR_OK(CONN:execute"select * from t") assert2(0,cur:numrows()) cur:close() -- Inserts one row. assert2 (1, CONN:execute"insert into t (f1) values ('a')", "could not insert a new record") cur = CUR_OK(CONN:execute"select * from t") assert2(1,cur:numrows()) cur:close() -- Inserts three more rows (total = 4). assert2 (1, CONN:execute"insert into t (f1) values ('b')", "could not insert a new record") assert2 (1, CONN:execute"insert into t (f1) values ('c')", "could not insert a new record") assert2 (1, CONN:execute"insert into t (f1) values ('d')", "could not insert a new record") cur = CUR_OK(CONN:execute"select * from t") assert2(4,cur:numrows()) cur:close() -- Deletes one row assert2(1, CONN:execute"delete from t where f1 = 'a'", "could not delete the specified row") cur = CUR_OK(CONN:execute"select * from t") assert2(3,cur:numrows()) cur:close() -- Deletes all rows assert2 (3, CONN:execute (sql_erase_table"t")) cur = CUR_OK(CONN:execute"select * from t") assert2(0,cur:numrows()) cur:close() io.write (" numrows") end --------------------------------------------------------------------- -- Main --------------------------------------------------------------------- if type(arg[1]) ~= "string" then print (string.format ("Usage %s [ [, [, ]]]", arg[0])) os.exit() end driver = arg[1] datasource = arg[2] or "luasql-test" username = arg[3] or nil password = arg[4] or nil -- Loading driver specific functions if arg[0] then local path = string.gsub (arg[0], "^(.*%/)[^/]*$", "%1") if path == "test.lua" then path = "" end local file = path..driver..".lua" local f, err = loadfile (file) if not f then print ("LuaSQL test: couldn't find driver-specific test file (".. file..").\nProceeding with general test") else print ("Loading driver-specific test file ("..file..").") f () end end -- Complete set of tests tests = { { "basic checking", basic_test }, { "create table", create_table }, { "fetch two values", fetch2 }, { "fetch new table", fetch_new_table }, { "fetch many", fetch_many }, { "rollback", rollback }, { "get column information", column_info }, { "escape", escape }, { "extensions", extensions_test }, { "close objects", check_close }, { "drop table", drop_table }, { "close connection", close_conn }, } if string.find(_VERSION, " 5.0") then luasql = assert(loadlib("./"..driver..".so", "luaopen_luasql_"..driver))() else luasql = require ("luasql."..driver) end assert (luasql, "Could not load driver: no luasql table.") io.write (luasql._VERSION.." "..driver.." driver test. "..luasql._COPYRIGHT.."\n") for i = 1, table.getn (tests) do local t = tests[i] io.write (t[1].." ...") local ok, err = xpcall (t[2], debug.traceback) if not ok then io.write ("\n"..err) io.write"\n... trying to drop test table ..." local ok, err = pcall (drop_table) if not ok then io.write (" failed: "..err) else io.write" OK !\n... and to close the connection ..." local ok, err = pcall (close_conn) if not ok then io.write (" failed: "..err) else io.write" OK !" end end io.write"\nThe test failed!\n" return end io.write (" OK !\n") end io.write ("The test passed!\n") keplerproject-luasql-c527024/vc6/000077500000000000000000000000001175743000500166325ustar00rootroot00000000000000keplerproject-luasql-c527024/vc6/def.tmpl000066400000000000000000000001101175743000500202560ustar00rootroot00000000000000LIBRARY DRIVER.dll VERSION VERSION_NUMBER EXPORTS luaopen_luasqlDRIVER keplerproject-luasql-c527024/vc6/luasql.dsw000066400000000000000000000032421175743000500206530ustar00rootroot00000000000000Microsoft Developer Studio Workspace File, Format Version 6.00 # WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! ############################################################################### Project: "luasqlmysql40_dll"=.\luasqlmysql40_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "luasqlmysql41_dll"=.\luasqlmysql41_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "luasqlmysql50_dll"=.\luasqlmysql50_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "luasqloci8_dll"=.\luasqloci8_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "luasqlodbc_dll"=.\luasqlodbc_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "luasqlpostgres_dll"=.\luasqlpostgres_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Project: "luasqlsqlite_dll"=.\luasqlsqlite_dll.dsp - Package Owner=<4> Package=<5> {{{ }}} Package=<4> {{{ }}} ############################################################################### Global: Package=<5> {{{ }}} Package=<3> {{{ }}} ############################################################################### keplerproject-luasql-c527024/vc6/luasqlmysql40_dll.dsp000066400000000000000000000116511175743000500227340ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqlmysql40_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqlmysql40_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqlmysql40_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqlmysql40_dll.mak" CFG="luasqlmysql40_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqlmysql40_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqlmysql40_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqlmysql40_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqlmysql40_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlmysql40_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql40_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MT /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../external-src/mysql-4.0.26-win32/include" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql40_dll_EXPORTS" /FR /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib libmysql.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/mysql40.dll" /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/mysql-4.0.26-win32/lib/opt" !ELSEIF "$(CFG)" == "luasqlmysql40_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlmysql40_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql40_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../external-src/mysql-4.0.26-win32/include" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql40_dll_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib libmysql.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/mysql40d.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/mysql-4.0.26-win32/lib/debug" !ENDIF # Begin Target # Name "luasqlmysql40_dll - Win32 Release" # Name "luasqlmysql40_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_mysql.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\mysql.def # End Source File # Begin Source File SOURCE=.\mysql40.rc # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/luasqlmysql41_dll.dsp000066400000000000000000000117671175743000500227450ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqlmysql41_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqlmysql41_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqlmysql41_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqlmysql41_dll.mak" CFG="luasqlmysql41_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqlmysql41_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqlmysql41_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqlmysql41_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqlmysql41_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlmysql41_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql41_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MT /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../external-src/mysql-4.1.16-win32/include" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql41_dll_EXPORTS" /FR /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib libmysql.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/mysql41.dll" /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/mysql-4.1.16-win32/lib/opt" !ELSEIF "$(CFG)" == "luasqlmysql41_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlmysql41_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql41_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../external-src/mysql-4.1.16-win32/include" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql41_dll_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib libmysql.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/mysql41d.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/mysql-4.1.16-win32/lib/debug" !ENDIF # Begin Target # Name "luasqlmysql41_dll - Win32 Release" # Name "luasqlmysql41_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_mysql.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\mysql.def # End Source File # Begin Source File SOURCE=.\mysql41.rc # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.h" # End Source File # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/luasqlmysql50_dll.dsp000066400000000000000000000117731175743000500227420ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqlmysql50_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqlmysql50_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqlmysql50_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqlmysql50_dll.mak" CFG="luasqlmysql50_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqlmysql50_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqlmysql50_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqlmysql50_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqlmysql50_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlmysql50_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql50_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MT /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../external-src/mysql-5.0.20a-win32/include" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql50_dll_EXPORTS" /FR /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib libmysql.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/mysql50.dll" /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/mysql-5.0.20a-win32/lib/opt" !ELSEIF "$(CFG)" == "luasqlmysql50_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlmysql50_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql50_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../external-src/mysql-5.0.20a-win32/include" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlmysql50_dll_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib libmysql.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/mysql50d.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/mysql-5.0.20a-win32/lib/debug" !ENDIF # Begin Target # Name "luasqlmysql50_dll - Win32 Release" # Name "luasqlmysql50_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_mysql.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\mysql.def # End Source File # Begin Source File SOURCE=.\mysql50.rc # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.h" # End Source File # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/luasqloci8_dll.dsp000066400000000000000000000115141175743000500222630ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqloci8_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqloci8_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqloci8_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqloci8_dll.mak" CFG="luasqloci8_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqloci8_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqloci8_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqloci8_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqloci8_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqloci8_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqloci8_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../external-src/oci8/oci/include" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqloci8_dll_EXPORTS" /FR /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib oci.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/oci8.dll" /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/oci8/oci/lib/msvc" !ELSEIF "$(CFG)" == "luasqloci8_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqloci8_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqloci8_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../external-src/oci8/oci/include" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqloci8_dll_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib oci.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/oci8d.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/oci8/oci/lib/msvc" !ENDIF # Begin Target # Name "luasqloci8_dll - Win32 Release" # Name "luasqloci8_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_oci8.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\oci8.def # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.h" # End Source File # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/luasqlodbc_dll.dsp000066400000000000000000000113221175743000500223250ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqlodbc_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqlodbc_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqlodbc_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqlodbc_dll.mak" CFG="luasqlodbc_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqlodbc_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqlodbc_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqlodbc_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqlodbc_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlodbc_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlodbc_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MT /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlodbc_dll_EXPORTS" /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/odbc.dll" /libpath:"../../external-src/lua50/lib/dll" !ELSEIF "$(CFG)" == "luasqlodbc_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlodbc_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlodbc_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlodbc_dll_EXPORTS" /FR /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/odbcd.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" !ENDIF # Begin Target # Name "luasqlodbc_dll - Win32 Release" # Name "luasqlodbc_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_odbc.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\odbc.def # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.h" # End Source File # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/luasqlpostgres_dll.dsp000066400000000000000000000121661175743000500232730ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqlpostgres_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqlpostgres_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqlpostgres_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqlpostgres_dll.mak" CFG="luasqlpostgres_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqlpostgres_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqlpostgres_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqlpostgres_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqlpostgres_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlpostgres_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlpostgres_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MD /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../external-src/postgresql-7.4.12/src/include" /I "../../external-src/postgresql-7.4.12/src/interfaces/libpq" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlpostgres_dll_EXPORTS" /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib libpq.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/postgres.dll" /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/postgresql-7.4.12/src/interfaces/libpq/Release" !ELSEIF "$(CFG)" == "luasqlpostgres_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlpostgres_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlpostgres_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../external-src/postgresql-7.4.12/src/include" /I "../../external-src/postgresql-7.4.12/src/interfaces/libpq" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlpostgres_dll_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib libpq.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/postgresd.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/postgresql-7.4.12/src/interfaces/libpq/Release" !ENDIF # Begin Target # Name "luasqlpostgres_dll - Win32 Release" # Name "luasqlpostgres_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_postgres.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\postgres.def # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.h" # End Source File # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/luasqlsqlite_dll.dsp000066400000000000000000000212621175743000500227230ustar00rootroot00000000000000# Microsoft Developer Studio Project File - Name="luasqlsqlite_dll" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 CFG=luasqlsqlite_dll - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "luasqlsqlite_dll.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "luasqlsqlite_dll.mak" CFG="luasqlsqlite_dll - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "luasqlsqlite_dll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE "luasqlsqlite_dll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "luasqlsqlite_dll" # PROP Scc_LocalPath ".." CPP=cl.exe MTL=midl.exe RSC=rc.exe !IF "$(CFG)" == "luasqlsqlite_dll - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlsqlite_dll/Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlsqlite_dll_EXPORTS" /YX /FD /c # ADD CPP /nologo /MT /W3 /GX /O2 /I "../../external-src/lua50/include" /I "../../external-src/sqlite-2.8.17" /I "../../compat/src" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlsqlite_dll_EXPORTS" /FR /YX /FD /c # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "NDEBUG" # ADD RSC /l 0x416 /d "NDEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 # ADD LINK32 lua50.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /machine:I386 /out:"../bin/vc6/luasql/sqlite.dll" /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/sqlite-2.8.15/lib/opt" !ELSEIF "$(CFG)" == "luasqlsqlite_dll - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "../lib/vc6/luasql" # PROP Intermediate_Dir "luasqlsqlite_dll/Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlsqlite_dll_EXPORTS" /YX /FD /GZ /c # ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../../external-src/lua50/include" /I "../../external-src/sqlite-2.8.17" /I "../../compat/src" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "luasqlsqlite_dll_EXPORTS" /YX /FD /GZ /c # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 # ADD BASE RSC /l 0x416 /d "_DEBUG" # ADD RSC /l 0x416 /d "_DEBUG" BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /pdbtype:sept # ADD LINK32 lua50.lib wsock32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /dll /debug /machine:I386 /out:"../bin/vc6/luasql/sqlited.dll" /pdbtype:sept /libpath:"../../external-src/lua50/lib/dll" /libpath:"../../external-src/sqlite-2.8.17/lib/debug" !ENDIF # Begin Target # Name "luasqlsqlite_dll - Win32 Release" # Name "luasqlsqlite_dll - Win32 Debug" # Begin Group "Source Files" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.c" # End Source File # Begin Source File SOURCE=..\src\ls_sqlite.c # End Source File # Begin Source File SOURCE=..\src\luasql.c # End Source File # Begin Source File SOURCE=.\sqlite.def # End Source File # End Group # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File SOURCE="..\..\compat\src\compat-5.1.h" # End Source File # Begin Source File SOURCE=..\src\luasql.h # End Source File # End Group # Begin Group "Resource Files" # PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" # End Group # Begin Group "sqllite Files" # PROP Default_Filter "" # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\attach.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\auth.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\btree.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\btree.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\btree_rb.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\build.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\config.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\copy.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\date.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\delete.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\encode.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\expr.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\func.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\hash.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\hash.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\insert.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\main.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\opcodes.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\opcodes.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\os.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\os.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\pager.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\pager.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\parse.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\parse.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\pragma.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\printf.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\random.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\select.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\shell.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\sqlite.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\sqliteInt.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\table.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\tokenize.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\trigger.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\update.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\util.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\vacuum.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\vdbe.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\vdbe.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\vdbeaux.c" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\vdbeInt.h" # End Source File # Begin Source File SOURCE="..\..\external-src\sqlite-2.8.17\where.c" # End Source File # End Group # End Target # End Project keplerproject-luasql-c527024/vc6/mysql.def000066400000000000000000000001251175743000500204550ustar00rootroot00000000000000LIBRARY mysql.dll DESCRIPTION "LuaSQL driver for mysql" EXPORTS luaopen_luasqlmysql keplerproject-luasql-c527024/vc6/mysql40.rc000066400000000000000000000047161175743000500205010ustar00rootroot00000000000000//Microsoft Developer Studio generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // Portuguese (Brazil) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_PTB) #ifdef _WIN32 LANGUAGE LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN #pragma code_page(1252) #endif //_WIN32 #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 2,0,2,0 PRODUCTVERSION 2,0,2,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x21L #else FILEFLAGS 0x20L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "MySQL 4.0.24\0" VALUE "CompanyName", "Kepler\0" VALUE "FileDescription", "mysql40\0" VALUE "FileVersion", "2, 0, 2, 0\0" VALUE "InternalName", "mysql40\0" VALUE "LegalCopyright", "Copyright 2006\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "mysql40.dll\0" VALUE "PrivateBuild", "\0" VALUE "ProductName", "LuaSQL MySQL Driver\0" VALUE "ProductVersion", "2, 0, 2, 0\0" VALUE "SpecialBuild", "Kepler Project\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // !_MAC #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0" END 2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE DISCARDABLE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #endif // Portuguese (Brazil) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED keplerproject-luasql-c527024/vc6/mysql41.rc000066400000000000000000000047161175743000500205020ustar00rootroot00000000000000//Microsoft Developer Studio generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // Portuguese (Brazil) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_PTB) #ifdef _WIN32 LANGUAGE LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN #pragma code_page(1252) #endif //_WIN32 #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 2,0,2,0 PRODUCTVERSION 2,0,2,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x21L #else FILEFLAGS 0x20L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "MySQL 4.1.16\0" VALUE "CompanyName", "Kepler\0" VALUE "FileDescription", "mysql41\0" VALUE "FileVersion", "2, 0, 2, 0\0" VALUE "InternalName", "mysql41\0" VALUE "LegalCopyright", "Copyright 2006\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "mysql41.dll\0" VALUE "PrivateBuild", "\0" VALUE "ProductName", "LuaSQL MySQL Driver\0" VALUE "ProductVersion", "2, 0, 2, 0\0" VALUE "SpecialBuild", "Kepler Project\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // !_MAC #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0" END 2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE DISCARDABLE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #endif // Portuguese (Brazil) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED keplerproject-luasql-c527024/vc6/mysql50.rc000066400000000000000000000047171175743000500205030ustar00rootroot00000000000000//Microsoft Developer Studio generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // Portuguese (Brazil) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_PTB) #ifdef _WIN32 LANGUAGE LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN #pragma code_page(1252) #endif //_WIN32 #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 2,0,2,0 PRODUCTVERSION 2,0,2,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x21L #else FILEFLAGS 0x20L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "MySQL 5.0.20a\0" VALUE "CompanyName", "Kepler\0" VALUE "FileDescription", "mysql50\0" VALUE "FileVersion", "2, 0, 2, 0\0" VALUE "InternalName", "mysql50\0" VALUE "LegalCopyright", "Copyright 2006\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "mysql50.dll\0" VALUE "PrivateBuild", "\0" VALUE "ProductName", "LuaSQL MySQL Driver\0" VALUE "ProductVersion", "2, 0, 2, 0\0" VALUE "SpecialBuild", "Kepler Project\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // !_MAC #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0" END 2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE DISCARDABLE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #endif // Portuguese (Brazil) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED keplerproject-luasql-c527024/vc6/oci8.def000066400000000000000000000001331175743000500201510ustar00rootroot00000000000000LIBRARY oci8.dll DESCRIPTION "LuaSQL driver for oci8 (Oracle)" EXPORTS luaopen_luasqloci8 keplerproject-luasql-c527024/vc6/odbc.def000066400000000000000000000001221175743000500202140ustar00rootroot00000000000000LIBRARY odbc.dll DESCRIPTION "LuaSQL driver for odbc" EXPORTS luaopen_luasqlodbc keplerproject-luasql-c527024/vc6/postgres.def000066400000000000000000000001361175743000500211600ustar00rootroot00000000000000LIBRARY postgres.dll DESCRIPTION "LuaSQL driver for postgres" EXPORTS luaopen_luasqlpostgres keplerproject-luasql-c527024/vc6/postgres.rc000066400000000000000000000047321175743000500210340ustar00rootroot00000000000000//Microsoft Developer Studio generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // Portuguese (Brazil) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_PTB) #ifdef _WIN32 LANGUAGE LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN #pragma code_page(1252) #endif //_WIN32 #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 2,0,2,0 PRODUCTVERSION 2,0,2,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x21L #else FILEFLAGS 0x20L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "Postgresql 7.4.6\0" VALUE "CompanyName", "Ideais\0" VALUE "FileDescription", "postgres\0" VALUE "FileVersion", "2, 0, 2, 0\0" VALUE "InternalName", "postgres\0" VALUE "LegalCopyright", "Copyright 2006\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "postgres.dll\0" VALUE "PrivateBuild", "\0" VALUE "ProductName", "LuaSQL Postgresql Driver\0" VALUE "ProductVersion", "2, 0, 2, 0\0" VALUE "SpecialBuild", "Kepler Project\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // !_MAC #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0" END 2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE DISCARDABLE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #endif // Portuguese (Brazil) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED keplerproject-luasql-c527024/vc6/resource.h000066400000000000000000000006141175743000500206330ustar00rootroot00000000000000//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by mysql40.rc // // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif keplerproject-luasql-c527024/vc6/sqlite.def000066400000000000000000000001301175743000500206050ustar00rootroot00000000000000LIBRARY sqlite.dll DESCRIPTION "LuaSQL driver for sqlite" EXPORTS luaopen_luasqlsqlite