Previous 199869 Revisions Next

r34322 Saturday 10th January, 2015 at 13:50:15 UTC by Miodrag Milanović
added lsqlite3 full source
[3rdparty/lsqlite3].travis.yml* CMakeLists.txt* HISTORY* Makefile* README* dist.info* lsqlite3.c* lsqlite3.def* lunit.lua* test.lua* tests-sqlite3.lua*
[3rdparty/lsqlite3/cmake]FindLua.cmake* FindSQLite3.cmake* dist.cmake* lua.cmake*
[3rdparty/lsqlite3/doc]lsqlite3.html* lsqlite3.pod* pod2html.pl*
[3rdparty/lsqlite3/examples]aggregate.lua* function.lua* order.lua* simple.lua* smart.lua* statement.lua* tracing.lua*
[src/lib]lib.mak
[src/lib/lua/lib]lsqlite3.c lualibs.h

trunk/3rdparty/lsqlite3/.travis.yml
r0r242834
1#
2# LuaDist Travis-CI Hook
3#
4
5# We assume C build environments
6language: C
7
8# Try using multiple Lua Implementations
9env:
10  - TOOL="gcc"                  # Use native compiler (GCC usually)
11  - TOOL="clang"                # Use clang
12  - TOOL="i686-w64-mingw32"     # 32bit MinGW
13  - TOOL="x86_64-w64-mingw32"   # 64bit MinGW
14  - TOOL="arm-linux-gnueabihf"  # ARM hard-float (hf), linux
15
16# Crosscompile builds may fail
17matrix:
18  allow_failures:
19    - env: TOOL="i686-w64-mingw32"
20    - env: TOOL="x86_64-w64-mingw32"
21    - env: TOOL="arm-linux-gnueabihf"
22
23# Install dependencies
24install:
25  - git clone git://github.com/LuaDist/Tools.git ~/_tools
26  - ~/_tools/travis/travis install
27
28# Bootstap
29before_script:
30  - ~/_tools/travis/travis bootstrap
31
32# Build the module
33script:
34  - ~/_tools/travis/travis build
35
36# Execute additional tests or commands
37after_script:
38  - ~/_tools/travis/travis test
39
40# Only watch the master branch
41branches:
42  only:
43    - master
44
45# Notify the LuaDist Dev group if needed
46notifications:
47  recipients:
48    - luadist-dev@googlegroups.com
49  email:
50    on_success: change
51    on_failure: always
trunk/3rdparty/lsqlite3/CMakeLists.txt
r0r242834
1# Copyright (C) 2007-2012 LuaDist.
2# Created by Peter Kapec
3# Redistribution and use of this file is allowed according to the terms of the MIT license.
4# For details see the COPYRIGHT file distributed with LuaDist.
5# Please note that the package source code is licensed under its own license.
6
7project ( lsqlite3 C )
8cmake_minimum_required ( VERSION 2.8 )
9include ( cmake/dist.cmake )
10include ( lua )
11
12# Find SQLite3
13find_package ( SQLite3 REQUIRED )
14include_directories ( ${SQLITE3_INCLUDE_DIRS} )
15
16# Create lsqlite module
17install_lua_module ( lsqlite3 lsqlite3.c lsqlite3.def LINK ${SQLITE3_LIBRARIES} )
18install_data ( HISTORY README )
19install_doc( doc/ )
20install_test ( lunit.lua test.lua tests-sqlite3.lua )
21install_example ( examples/ )
trunk/3rdparty/lsqlite3/HISTORY
r0r242834
12007-August-15 e
2
3Version "0.6-devel"
4
5Since the "0.5-devel" release of this Lua library...
6
7Tested with SQLite 3.4.2
8
9Added some documentation.
10
11Thanks to Thomas Lauer...
12
13Moved line 525 ("luaL_checktype(L, 2, LUA_TTABLE);")
14below the declarations to eliminate non-gcc compiler errors.
15
16Added create-collation, and associated test case.
17
18-=-
19
202006-October-02 e
21
22Since the "0.1-devel" release of this Lua library...
23- updated for Lua 5.1
24- provide automatic re-preparation of queries after schema changes
25- made prepared statements with bindings work with for-loops
26- added some compatibility names
27- added many test cases, and ported Mike Roth's tests and examples
28
29-=-
30
31Below is a header comment from the 2004 "0.1" version of the library...
32
33/************************************************************************
34$Id: lsqlite3.c,v 1.3 2004/09/05 17:50:32 tngd Exp $
35
36To consider:
37------------
38
39EXPERIMENTAL APIs
40
41* sqlite3_progress_handler (implemented)
42* sqlite3_commit_hook
43
44TODO?
45
46* sqlite3_create_collation
47
48Changes:
4904-09-2004
50----------
51    * changed second return value of db:compile to be the rest of the
52    sql statement that was not processed instead of the number of
53    characters of sql not processed (situation in case of success).
54    * progress callback register function parameter order changed.
55    number of opcodes is given before the callback now.
56
5729-08-2004 e
58------------
59    * added version() (now supported in sqlite 3.0.5)
60    * added db:errmsg db:errcode db:total_changes
61    * rename vm:get_column to vm:get_value
62    * merge in Tiago's v1.11 change in dbvm_tostring
63
6423-06-2004 e
65------------
66    * heavily revised for SQLite3 C API
67    * row values now returned as native type (not always text)
68    * added db:nrows (named rows)
69    * added vm:bind_blob
70    * added vm:get_column
71    * removed encode_binary decode_binary (no longer needed or supported)
72    * removed version encoding error_string (unsupported in v 3.0.1 -- soon?)
73
7409-04-2004
75----------
76    * renamed db:rows to db:urows
77    * renamed db:prows to db:rows
78
79    * added vm:get_unames()
80    * added vm:get_utypes()
81    * added vm:get_uvalues()
82
8308-04-2004
84----------
85    * changed db:encoding() and db:version() to use sqlite_libencoding() and
86    sqlite_libversion()
87
88    * added vm:columns()
89    * added vm:get_named_types()
90    * added vm:get_named_values()
91
92    * added db:prows - like db:rows but returns a table with the column values
93    instead of returning multiple columns seperatly on each iteration
94
95    * added compatibility functions idata,iname,itype,data,type
96
97    * added luaopen_sqlite_module. allow the library to be loaded without
98    setting a global variable. does the same as luaopen_sqlite, but does not
99    set the global name "sqlite".
100
101    * vm:bind now also returns an error string in case of error
102
10331-03-2004 - 01-04-2004
104-----------------------
105    * changed most of the internals. now using references (luaL_ref) in
106    most of the places
107
108    * make the virtual machine interface seperate from the database
109    handle. db:compile now returns a vm handle
110
111    * added db:rows [for ... in db:rows(...) do ... end]
112
113    * added db:close_vm
114
115    * added sqlite.encode_binary and sqlite.decode_binary
116
117    * attempt to do a strict checking on the return type of the user
118    defined functions returned values
119
12018-01-2004
121----------
122    * add check on sql function callback to ensure there is enough stack
123    space to pass column values as parameters
124
12503-12-2003
126----------
127    * callback functions now have to return boolean values to abort or
128    continue operation instead of a zero or non-zero value
129
13006-12-2003
131----------
132    * make version member of sqlite table a function instead of a string
133************************************************************************/
trunk/3rdparty/lsqlite3/Makefile
r0r242834
1# makefile for lsqlite3 library for Lua
2
3ifneq "$(shell pkg-config --version)" ""
4  # automagic setup (OS X fink, Linux apt-get, ..)
5  #
6  LUAINC= $(shell pkg-config --cflags lua)
7  LUALIB= $(shell pkg-config --libs lua)
8  LUAEXE= lua
9  # Now, we actually want to _not_ push in stuff to the distro Lua CMOD directory,
10  # way better to play within /usr/local/lib/lua/5.1/
11  #LUACMOD= $(shell pkg-config --variable=INSTALL_CMOD lua)
12  LUACMOD= /usr/local/lib/lua/5.1/
13  #
14  SQLITE3INC= $(shell pkg-config --cflags sqlite3)
15  SQLITE3LIB= $(shell pkg-config --libs sqlite3)
16else
17  # manual setup (change these to reflect your Lua installation)
18  #
19  BASE= /usr/local
20  LUAINC= -I$(BASE)/include
21  LUAEXE= $(BASE)/bin/lua.exe
22#  LUALIB= -L$(BASE)/lib -llua51
23#  LUACMOD= $(BASE)/lib/lua/5.1/
24#  Windows' LUA_CDIR and LUALIB are both the same as the Lua executable's directory...
25  LUALIB= -L$(BASE)/bin -llua51
26  LUACMOD= $(BASE)/bin
27  #
28  SQLITE3INC= -I$(BASE)/include
29  SQLITE3LIB= -L$(BASE)/bin -lsqlite3
30  #
31  POD2HTML= perl -x -S doc/pod2html.pl
32endif
33
34TMP=./tmp
35DISTDIR=./archive
36
37# OS detection
38#
39SHFLAGS=-shared
40UNAME= $(shell uname)
41ifeq "$(UNAME)" "Linux"
42  _SO=so
43  SHFLAGS= -fPIC
44endif
45ifneq "" "$(findstring BSD,$(UNAME))"
46  _SO=so
47endif
48ifeq "$(UNAME)" "Darwin"
49  _SO=bundle
50  SHFLAGS= -bundle
51endif
52ifneq "" "$(findstring msys,$(OSTYPE))"      # 'msys'
53  _SO=dll
54endif
55
56ifndef _SO
57  $(error $(UNAME))
58  $(error Unknown OS)
59endif
60
61# no need to change anything below here - HAH!
62CFLAGS= $(INCS) $(DEFS) $(WARN) -O2 $(SHFLAGS)
63WARN= -Wall #-ansi -pedantic -Wall
64INCS= $(LUAINC) $(SQLITE3INC)
65LIBS= $(LUALIB) $(SQLITE3LIB)
66
67MYNAME= sqlite3
68MYLIB= l$(MYNAME)
69
70VER=$(shell svnversion -c . | sed 's/.*://')
71TARFILE = $(DISTDIR)/$(MYLIB)-$(VER).tar.gz
72
73OBJS= $(MYLIB).o
74T= $(MYLIB).$(_SO)
75
76all: $T
77
78test: $T
79   $(LUAEXE) test.lua
80   $(LUAEXE) tests-sqlite3.lua
81
82$T:   $(OBJS)
83   $(CC) $(SHFLAGS) -o $@ $(OBJS) $(LIBS)
84
85install:
86   cp $T $(LUACMOD)
87
88clean:
89   rm -f $(OBJS) $T core core.* a.out test.db
90
91html:
92   $(POD2HTML) --title="LuaSQLite 3" --infile=doc/lsqlite3.pod --outfile=doc/lsqlite3.html
93
94dist:   html
95   echo 'Exporting...'
96   mkdir -p $(TMP)
97   mkdir -p $(DISTDIR)
98   svn export -r HEAD . $(TMP)/$(MYLIB)-$(VER)
99   mkdir -p $(TMP)/$(MYLIB)-$(VER)/doc
100   cp -p doc/lsqlite3.html $(TMP)/$(MYLIB)-$(VER)/doc
101   echo 'Compressing...'
102   tar -zcf $(TARFILE) -C $(TMP) $(MYLIB)-$(VER)
103   rm -fr $(TMP)/$(MYLIB)-$(VER)
104   echo 'Done.'
105
106.PHONY: all test clean dist install
trunk/3rdparty/lsqlite3/README
r0r242834
1
2LuaSQLite 3 provides a means to manipulate SQLite3
3databases directly from lua using Lua 5.
4
5To use this library you need SQLite3 library.
6You can get it from http://www.sqlite.org/
7
8Lua 5 is available from http://www.lua.org/
trunk/3rdparty/lsqlite3/cmake/FindLua.cmake
r0r242834
1# Locate Lua library
2# This module defines
3#  LUA_EXECUTABLE, if found
4#  LUA_FOUND, if false, do not try to link to Lua
5#  LUA_LIBRARIES
6#  LUA_INCLUDE_DIR, where to find lua.h
7#  LUA_VERSION_STRING, the version of Lua found (since CMake 2.8.8)
8#
9# Note that the expected include convention is
10#  #include "lua.h"
11# and not
12#  #include <lua/lua.h>
13# This is because, the lua location is not standardized and may exist
14# in locations other than lua/
15
16#=============================================================================
17# Copyright 2007-2009 Kitware, Inc.
18# Modified to support Lua 5.2 by LuaDist 2012
19#
20# Distributed under the OSI-approved BSD License (the "License");
21# see accompanying file Copyright.txt for details.
22#
23# This software is distributed WITHOUT ANY WARRANTY; without even the
24# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
25# See the License for more information.
26#=============================================================================
27# (To distribute this file outside of CMake, substitute the full
28#  License text for the above reference.)
29#
30# The required version of Lua can be specified using the
31# standard syntax, e.g. FIND_PACKAGE(Lua 5.1)
32# Otherwise the module will search for any available Lua implementation
33
34# Always search for non-versioned lua first (recommended)
35SET(_POSSIBLE_LUA_INCLUDE include include/lua)
36SET(_POSSIBLE_LUA_EXECUTABLE lua)
37SET(_POSSIBLE_LUA_LIBRARY lua)
38
39# Determine possible naming suffixes (there is no standard for this)
40IF(Lua_FIND_VERSION_MAJOR AND Lua_FIND_VERSION_MINOR)
41  SET(_POSSIBLE_SUFFIXES "${Lua_FIND_VERSION_MAJOR}${Lua_FIND_VERSION_MINOR}" "${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR}" "-${Lua_FIND_VERSION_MAJOR}.${Lua_FIND_VERSION_MINOR}")
42ELSE(Lua_FIND_VERSION_MAJOR AND Lua_FIND_VERSION_MINOR)
43  SET(_POSSIBLE_SUFFIXES "52" "5.2" "-5.2" "51" "5.1" "-5.1")
44ENDIF(Lua_FIND_VERSION_MAJOR AND Lua_FIND_VERSION_MINOR)
45
46# Set up possible search names and locations
47FOREACH(_SUFFIX ${_POSSIBLE_SUFFIXES})
48  LIST(APPEND _POSSIBLE_LUA_INCLUDE "include/lua${_SUFFIX}")
49  LIST(APPEND _POSSIBLE_LUA_EXECUTABLE "lua${_SUFFIX}")
50  LIST(APPEND _POSSIBLE_LUA_LIBRARY "lua${_SUFFIX}")
51ENDFOREACH(_SUFFIX)
52
53# Find the lua executable
54FIND_PROGRAM(LUA_EXECUTABLE
55  NAMES ${_POSSIBLE_LUA_EXECUTABLE}
56)
57
58# Find the lua header
59FIND_PATH(LUA_INCLUDE_DIR lua.h
60  HINTS
61  $ENV{LUA_DIR}
62  PATH_SUFFIXES ${_POSSIBLE_LUA_INCLUDE}
63  PATHS
64  ~/Library/Frameworks
65  /Library/Frameworks
66  /usr/local
67  /usr
68  /sw # Fink
69  /opt/local # DarwinPorts
70  /opt/csw # Blastwave
71  /opt
72)
73
74# Find the lua library
75FIND_LIBRARY(LUA_LIBRARY
76  NAMES ${_POSSIBLE_LUA_LIBRARY}
77  HINTS
78  $ENV{LUA_DIR}
79  PATH_SUFFIXES lib64 lib
80  PATHS
81  ~/Library/Frameworks
82  /Library/Frameworks
83  /usr/local
84  /usr
85  /sw
86  /opt/local
87  /opt/csw
88  /opt
89)
90
91IF(LUA_LIBRARY)
92  # include the math library for Unix
93  IF(UNIX AND NOT APPLE)
94    FIND_LIBRARY(LUA_MATH_LIBRARY m)
95    SET( LUA_LIBRARIES "${LUA_LIBRARY};${LUA_MATH_LIBRARY}" CACHE STRING "Lua Libraries")
96  # For Windows and Mac, don't need to explicitly include the math library
97  ELSE(UNIX AND NOT APPLE)
98    SET( LUA_LIBRARIES "${LUA_LIBRARY}" CACHE STRING "Lua Libraries")
99  ENDIF(UNIX AND NOT APPLE)
100ENDIF(LUA_LIBRARY)
101
102# Determine Lua version
103IF(LUA_INCLUDE_DIR AND EXISTS "${LUA_INCLUDE_DIR}/lua.h")
104  FILE(STRINGS "${LUA_INCLUDE_DIR}/lua.h" lua_version_str REGEX "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua .+\"")
105
106  STRING(REGEX REPLACE "^#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([^\"]+)\".*" "\\1" LUA_VERSION_STRING "${lua_version_str}")
107  UNSET(lua_version_str)
108ENDIF()
109
110INCLUDE(FindPackageHandleStandardArgs)
111# handle the QUIETLY and REQUIRED arguments and set LUA_FOUND to TRUE if
112# all listed variables are TRUE
113FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua
114                                  REQUIRED_VARS LUA_LIBRARIES LUA_INCLUDE_DIR
115                                  VERSION_VAR LUA_VERSION_STRING)
116
117MARK_AS_ADVANCED(LUA_INCLUDE_DIR LUA_LIBRARIES LUA_LIBRARY LUA_MATH_LIBRARY LUA_EXECUTABLE)
118
trunk/3rdparty/lsqlite3/cmake/FindSQLite3.cmake
r0r242834
1# Copyright (C) 2007-2009 LuaDist.
2# Created by Peter Kapec <kapecp@gmail.com>
3# Redistribution and use of this file is allowed according to the terms of the MIT license.
4# For details see the COPYRIGHT file distributed with LuaDist.
5#   Note:
6#      Searching headers and libraries is very simple and is NOT as powerful as scripts
7#      distributed with CMake, because LuaDist defines directories to search for.
8#      Everyone is encouraged to contact the author with improvements. Maybe this file
9#      becomes part of CMake distribution sometimes.
10
11# - Find sqlite3
12# Find the native SQLITE3 headers and libraries.
13#
14# SQLITE3_INCLUDE_DIRS   - where to find sqlite3.h, etc.
15# SQLITE3_LIBRARIES   - List of libraries when using sqlite.
16# SQLITE3_FOUND   - True if sqlite found.
17
18# Look for the header file.
19FIND_PATH(SQLITE3_INCLUDE_DIR NAMES sqlite3.h)
20
21# Look for the library.
22FIND_LIBRARY(SQLITE3_LIBRARY NAMES sqlite3 libsqlite3 sqlite libsqlite)
23
24# Handle the QUIETLY and REQUIRED arguments and set SQLITE3_FOUND to TRUE if all listed variables are TRUE.
25INCLUDE(FindPackageHandleStandardArgs)
26FIND_PACKAGE_HANDLE_STANDARD_ARGS(SQLITE3 DEFAULT_MSG SQLITE3_LIBRARY SQLITE3_INCLUDE_DIR)
27
28# Copy the results to the output variables.
29IF(SQLITE3_FOUND)
30   SET(SQLITE3_LIBRARIES ${SQLITE3_LIBRARY})
31   SET(SQLITE3_INCLUDE_DIRS ${SQLITE3_INCLUDE_DIR})
32ELSE(SQLITE3_FOUND)
33   SET(SQLITE3_LIBRARIES)
34   SET(SQLITE3_INCLUDE_DIRS)
35ENDIF(SQLITE3_FOUND)
36
37MARK_AS_ADVANCED(SQLITE3_INCLUDE_DIRS SQLITE3_LIBRARIES)
trunk/3rdparty/lsqlite3/cmake/dist.cmake
r0r242834
1# LuaDist CMake utility library.
2# Provides sane project defaults and macros common to LuaDist CMake builds.
3#
4# Copyright (C) 2007-2012 LuaDist.
5# by David Manura, Peter Drahoš
6# Redistribution and use of this file is allowed according to the terms of the MIT license.
7# For details see the COPYRIGHT file distributed with LuaDist.
8# Please note that the package source code is licensed under its own license.
9
10## Extract information from dist.info
11if ( NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/dist.info )
12  message ( FATAL_ERROR
13    "Missing dist.info file (${CMAKE_CURRENT_SOURCE_DIR}/dist.info)." )
14endif ()
15file ( READ ${CMAKE_CURRENT_SOURCE_DIR}/dist.info DIST_INFO )
16if ( "${DIST_INFO}" STREQUAL "" )
17  message ( FATAL_ERROR "Failed to load dist.info." )
18endif ()
19# Reads field `name` from dist.info string `DIST_INFO` into variable `var`.
20macro ( _parse_dist_field name var )
21  string ( REGEX REPLACE ".*${name}[ \t]?=[ \t]?[\"']([^\"']+)[\"'].*" "\\1"
22           ${var} "${DIST_INFO}" )
23  if ( ${var} STREQUAL DIST_INFO )
24    message ( FATAL_ERROR "Failed to extract \"${var}\" from dist.info" )
25  endif ()
26endmacro ()
27#
28_parse_dist_field ( name DIST_NAME )
29_parse_dist_field ( version DIST_VERSION )
30_parse_dist_field ( license DIST_LICENSE )
31_parse_dist_field ( author DIST_AUTHOR )
32_parse_dist_field ( maintainer DIST_MAINTAINER )
33_parse_dist_field ( url DIST_URL )
34_parse_dist_field ( desc DIST_DESC )
35message ( "DIST_NAME: ${DIST_NAME}")
36message ( "DIST_VERSION: ${DIST_VERSION}")
37message ( "DIST_LICENSE: ${DIST_LICENSE}")
38message ( "DIST_AUTHOR: ${DIST_AUTHOR}")
39message ( "DIST_MAINTAINER: ${DIST_MAINTAINER}")
40message ( "DIST_URL: ${DIST_URL}")
41message ( "DIST_DESC: ${DIST_DESC}")
42string ( REGEX REPLACE ".*depends[ \t]?=[ \t]?[\"']([^\"']+)[\"'].*" "\\1"
43         DIST_DEPENDS ${DIST_INFO} )
44if ( DIST_DEPENDS STREQUAL DIST_INFO )
45  set ( DIST_DEPENDS "" )
46endif ()
47message ( "DIST_DEPENDS: ${DIST_DEPENDS}")
48## 2DO: Parse DIST_DEPENDS and try to install Dependencies with automatically using externalproject_add
49
50
51## INSTALL DEFAULTS (Relative to CMAKE_INSTALL_PREFIX)
52# Primary paths
53set ( INSTALL_BIN bin CACHE PATH "Where to install binaries to." )
54set ( INSTALL_LIB lib CACHE PATH "Where to install libraries to." )
55set ( INSTALL_INC include CACHE PATH "Where to install headers to." )
56set ( INSTALL_ETC etc CACHE PATH "Where to store configuration files" )
57set ( INSTALL_SHARE share CACHE PATH "Directory for shared data." )
58
59# Secondary paths
60option ( INSTALL_VERSION
61      "Install runtime libraries and executables with version information." OFF)
62set ( INSTALL_DATA ${INSTALL_SHARE}/${DIST_NAME} CACHE PATH
63      "Directory the package can store documentation, tests or other data in.") 
64set ( INSTALL_DOC  ${INSTALL_DATA}/doc CACHE PATH
65      "Recommended directory to install documentation into.")
66set ( INSTALL_EXAMPLE ${INSTALL_DATA}/example CACHE PATH
67      "Recommended directory to install examples into.")
68set ( INSTALL_TEST ${INSTALL_DATA}/test CACHE PATH
69      "Recommended directory to install tests into.")
70set ( INSTALL_FOO  ${INSTALL_DATA}/etc CACHE PATH
71      "Where to install additional files")
72
73# Tweaks and other defaults
74# Setting CMAKE to use loose block and search for find modules in source directory
75set ( CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true )
76set ( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH} )
77option ( BUILD_SHARED_LIBS "Build shared libraries" ON )
78
79# In MSVC, prevent warnings that can occur when using standard libraries.
80if ( MSVC )
81  add_definitions ( -D_CRT_SECURE_NO_WARNINGS )
82endif ()
83
84# RPath and relative linking
85option ( USE_RPATH "Use relative linking." ON)
86if ( USE_RPATH )
87  string ( REGEX REPLACE "[^!/]+" ".." UP_DIR ${INSTALL_BIN} )
88  set ( CMAKE_SKIP_BUILD_RPATH FALSE CACHE STRING "" FORCE )
89  set ( CMAKE_BUILD_WITH_INSTALL_RPATH FALSE CACHE STRING "" FORCE )
90  set ( CMAKE_INSTALL_RPATH $ORIGIN/${UP_DIR}/${INSTALL_LIB}
91        CACHE STRING "" FORCE )
92  set ( CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE CACHE STRING "" FORCE )
93  set ( CMAKE_INSTALL_NAME_DIR @executable_path/${UP_DIR}/${INSTALL_LIB}
94        CACHE STRING "" FORCE )
95endif ()
96
97## MACROS
98# Parser macro
99macro ( parse_arguments prefix arg_names option_names)
100  set ( DEFAULT_ARGS )
101  foreach ( arg_name ${arg_names} )
102    set ( ${prefix}_${arg_name} )
103  endforeach ()
104  foreach ( option ${option_names} )
105    set ( ${prefix}_${option} FALSE )
106  endforeach ()
107
108  set ( current_arg_name DEFAULT_ARGS )
109  set ( current_arg_list )
110  foreach ( arg ${ARGN} )           
111    set ( larg_names ${arg_names} )   
112    list ( FIND larg_names "${arg}" is_arg_name )                   
113    if ( is_arg_name GREATER -1 )
114      set ( ${prefix}_${current_arg_name} ${current_arg_list} )
115      set ( current_arg_name ${arg} )
116      set ( current_arg_list )
117    else ()
118      set ( loption_names ${option_names} )   
119      list ( FIND loption_names "${arg}" is_option )           
120      if ( is_option GREATER -1 )
121        set ( ${prefix}_${arg} TRUE )
122      else ()
123        set ( current_arg_list ${current_arg_list} ${arg} )
124      endif ()
125    endif ()
126  endforeach ()
127  set ( ${prefix}_${current_arg_name} ${current_arg_list} )
128endmacro ()
129
130
131# install_executable ( executable_targets )
132# Installs any executables generated using "add_executable".
133# USE: install_executable ( lua )
134# NOTE: subdirectories are NOT supported
135set ( CPACK_COMPONENT_RUNTIME_DISPLAY_NAME "${DIST_NAME} Runtime" )
136set ( CPACK_COMPONENT_RUNTIME_DESCRIPTION
137      "Executables and runtime libraries. Installed into ${INSTALL_BIN}." )
138macro ( install_executable )
139  foreach ( _file ${ARGN} )
140    if ( INSTALL_VERSION )
141      set_target_properties ( ${_file} PROPERTIES VERSION ${DIST_VERSION}
142                              SOVERSION ${DIST_VERSION} )
143    endif ()
144    install ( TARGETS ${_file} RUNTIME DESTINATION ${INSTALL_BIN}
145              COMPONENT Runtime )
146  endforeach()
147endmacro ()
148
149# install_library ( library_targets )
150# Installs any libraries generated using "add_library" into apropriate places.
151# USE: install_library ( libexpat )
152# NOTE: subdirectories are NOT supported
153set ( CPACK_COMPONENT_LIBRARY_DISPLAY_NAME "${DIST_NAME} Development Libraries" )
154set ( CPACK_COMPONENT_LIBRARY_DESCRIPTION
155  "Static and import libraries needed for development. Installed into ${INSTALL_LIB} or ${INSTALL_BIN}." )
156macro ( install_library )
157  foreach ( _file ${ARGN} )
158    if ( INSTALL_VERSION )
159      set_target_properties ( ${_file} PROPERTIES VERSION ${DIST_VERSION}
160                              SOVERSION ${DIST_VERSION} )
161    endif ()
162    install ( TARGETS ${_file}
163              RUNTIME DESTINATION ${INSTALL_BIN} COMPONENT Runtime
164              LIBRARY DESTINATION ${INSTALL_LIB} COMPONENT Runtime
165              ARCHIVE DESTINATION ${INSTALL_LIB} COMPONENT Library )
166  endforeach()
167endmacro ()
168
169# helper function for various install_* functions, for PATTERN/REGEX args.
170macro ( _complete_install_args )
171  if ( NOT("${_ARG_PATTERN}" STREQUAL "") )
172    set ( _ARG_PATTERN PATTERN ${_ARG_PATTERN} )
173  endif ()
174  if ( NOT("${_ARG_REGEX}" STREQUAL "") )
175    set ( _ARG_REGEX REGEX ${_ARG_REGEX} )
176  endif ()
177endmacro ()
178
179# install_header ( files/directories [INTO destination] )
180# Install a directories or files into header destination.
181# USE: install_header ( lua.h luaconf.h ) or install_header ( GL )
182# USE: install_header ( mylib.h INTO mylib )
183# For directories, supports optional PATTERN/REGEX arguments like install().
184set ( CPACK_COMPONENT_HEADER_DISPLAY_NAME "${DIST_NAME} Development Headers" )
185set ( CPACK_COMPONENT_HEADER_DESCRIPTION
186      "Headers needed for development. Installed into ${INSTALL_INC}." )
187macro ( install_header )
188  parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
189  _complete_install_args()
190  foreach ( _file ${_ARG_DEFAULT_ARGS} )
191    if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
192      install ( DIRECTORY ${_file} DESTINATION ${INSTALL_INC}/${_ARG_INTO}
193                COMPONENT Header ${_ARG_PATTERN} ${_ARG_REGEX} )
194    else ()
195      install ( FILES ${_file} DESTINATION ${INSTALL_INC}/${_ARG_INTO}
196                COMPONENT Header )
197    endif ()
198  endforeach()
199endmacro ()
200
201# install_data ( files/directories [INTO destination] )
202# This installs additional data files or directories.
203# USE: install_data ( extra data.dat )
204# USE: install_data ( image1.png image2.png INTO images )
205# For directories, supports optional PATTERN/REGEX arguments like install().
206set ( CPACK_COMPONENT_DATA_DISPLAY_NAME "${DIST_NAME} Data" )
207set ( CPACK_COMPONENT_DATA_DESCRIPTION
208      "Application data. Installed into ${INSTALL_DATA}." )
209macro ( install_data )
210  parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
211  _complete_install_args()
212  foreach ( _file ${_ARG_DEFAULT_ARGS} )
213    if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
214      install ( DIRECTORY ${_file}
215                DESTINATION ${INSTALL_DATA}/${_ARG_INTO}
216                COMPONENT Data ${_ARG_PATTERN} ${_ARG_REGEX} )
217    else ()
218      install ( FILES ${_file} DESTINATION ${INSTALL_DATA}/${_ARG_INTO}
219                COMPONENT Data )
220    endif ()
221  endforeach()
222endmacro ()
223
224# INSTALL_DOC ( files/directories [INTO destination] )
225# This installs documentation content
226# USE: install_doc ( doc/ doc.pdf )
227# USE: install_doc ( index.html INTO html )
228# For directories, supports optional PATTERN/REGEX arguments like install().
229set ( CPACK_COMPONENT_DOCUMENTATION_DISPLAY_NAME "${DIST_NAME} Documentation" )
230set ( CPACK_COMPONENT_DOCUMENTATION_DESCRIPTION
231      "Application documentation. Installed into ${INSTALL_DOC}." )
232macro ( install_doc )
233  parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
234  _complete_install_args()
235  foreach ( _file ${_ARG_DEFAULT_ARGS} )
236    if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
237      install ( DIRECTORY ${_file} DESTINATION ${INSTALL_DOC}/${_ARG_INTO}
238                COMPONENT Documentation ${_ARG_PATTERN} ${_ARG_REGEX} )
239    else ()
240      install ( FILES ${_file} DESTINATION ${INSTALL_DOC}/${_ARG_INTO}
241                COMPONENT Documentation )
242    endif ()
243  endforeach()
244endmacro ()
245
246# install_example ( files/directories [INTO destination]  )
247# This installs additional examples
248# USE: install_example ( examples/ exampleA )
249# USE: install_example ( super_example super_data INTO super)
250# For directories, supports optional PATTERN/REGEX argument like install().
251set ( CPACK_COMPONENT_EXAMPLE_DISPLAY_NAME "${DIST_NAME} Examples" )
252set ( CPACK_COMPONENT_EXAMPLE_DESCRIPTION
253    "Examples and their associated data. Installed into ${INSTALL_EXAMPLE}." )
254macro ( install_example )
255  parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
256  _complete_install_args()
257  foreach ( _file ${_ARG_DEFAULT_ARGS} )
258    if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
259      install ( DIRECTORY ${_file} DESTINATION ${INSTALL_EXAMPLE}/${_ARG_INTO}
260                COMPONENT Example ${_ARG_PATTERN} ${_ARG_REGEX} )
261    else ()
262      install ( FILES ${_file} DESTINATION ${INSTALL_EXAMPLE}/${_ARG_INTO}
263                COMPONENT Example )
264    endif ()
265  endforeach()
266endmacro ()
267
268# install_test ( files/directories [INTO destination] )
269# This installs tests and test files, DOES NOT EXECUTE TESTS
270# USE: install_test ( my_test data.sql )
271# USE: install_test ( feature_x_test INTO x )
272# For directories, supports optional PATTERN/REGEX argument like install().
273set ( CPACK_COMPONENT_TEST_DISPLAY_NAME "${DIST_NAME} Tests" )
274set ( CPACK_COMPONENT_TEST_DESCRIPTION
275      "Tests and associated data. Installed into ${INSTALL_TEST}." )
276macro ( install_test )
277  parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
278  _complete_install_args()
279  foreach ( _file ${_ARG_DEFAULT_ARGS} )
280    if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
281      install ( DIRECTORY ${_file} DESTINATION ${INSTALL_TEST}/${_ARG_INTO}
282                COMPONENT Test ${_ARG_PATTERN} ${_ARG_REGEX} )
283    else ()
284      install ( FILES ${_file} DESTINATION ${INSTALL_TEST}/${_ARG_INTO}
285                COMPONENT Test )
286    endif ()
287  endforeach()
288endmacro ()
289
290# install_foo ( files/directories [INTO destination] )
291# This installs optional or otherwise unneeded content
292# USE: install_foo ( etc/ example.doc )
293# USE: install_foo ( icon.png logo.png INTO icons)
294# For directories, supports optional PATTERN/REGEX argument like install().
295set ( CPACK_COMPONENT_OTHER_DISPLAY_NAME "${DIST_NAME} Unspecified Content" )
296set ( CPACK_COMPONENT_OTHER_DESCRIPTION
297      "Other unspecified content. Installed into ${INSTALL_FOO}." )
298macro ( install_foo )
299  parse_arguments ( _ARG "INTO;PATTERN;REGEX" "" ${ARGN} )
300  _complete_install_args()
301  foreach ( _file ${_ARG_DEFAULT_ARGS} )
302    if ( IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/${_file}" )
303      install ( DIRECTORY ${_file} DESTINATION ${INSTALL_FOO}/${_ARG_INTO}
304                COMPONENT Other ${_ARG_PATTERN} ${_ARG_REGEX} )
305    else ()
306      install ( FILES ${_file} DESTINATION ${INSTALL_FOO}/${_ARG_INTO}
307                COMPONENT Other )
308    endif ()
309  endforeach()
310endmacro ()
311
312## CTest defaults
313
314## CPack defaults
315set ( CPACK_GENERATOR "ZIP" )
316set ( CPACK_STRIP_FILES TRUE )
317set ( CPACK_PACKAGE_NAME "${DIST_NAME}" )
318set ( CPACK_PACKAGE_VERSION "${DIST_VERSION}")
319set ( CPACK_PACKAGE_VENDOR "LuaDist" )
320set ( CPACK_COMPONENTS_ALL Runtime Library Header Data Documentation Example Other )
321include ( CPack )
trunk/3rdparty/lsqlite3/cmake/lua.cmake
r0r242834
1# LuaDist CMake utility library for Lua.
2#
3# Copyright (C) 2007-2012 LuaDist.
4# by David Manura, Peter Drahos
5# Redistribution and use of this file is allowed according to the terms of the MIT license.
6# For details see the COPYRIGHT file distributed with LuaDist.
7# Please note that the package source code is licensed under its own license.
8
9set ( INSTALL_LMOD ${INSTALL_LIB}/lua
10      CACHE PATH "Directory to install Lua modules." )
11set ( INSTALL_CMOD ${INSTALL_LIB}/lua
12      CACHE PATH "Directory to install Lua binary modules." )
13
14option ( SKIP_LUA_WRAPPER
15         "Do not build and install Lua executable wrappers." OFF)
16
17# List of (Lua module name, file path) pairs.
18# Used internally by add_lua_test.  Built by add_lua_module.
19set ( _lua_modules )
20
21# utility function: appends path `path` to path `basepath`, properly
22# handling cases when `path` may be relative or absolute.
23macro ( _append_path basepath path result )
24  if ( IS_ABSOLUTE "${path}" )
25    set ( ${result} "${path}" )
26  else ()
27    set ( ${result} "${basepath}/${path}" )
28  endif ()
29endmacro ()
30
31# install_lua_executable ( target source )
32# Automatically generate a binary if srlua package is available
33# The application or its source will be placed into /bin
34# If the application source did not have .lua suffix then it will be added
35# USE: lua_executable ( sputnik src/sputnik.lua )
36macro ( install_lua_executable _name _source )
37  get_filename_component ( _source_name ${_source} NAME_WE )
38  # Find srlua and glue
39  find_program( SRLUA_EXECUTABLE NAMES srlua )
40  find_program( GLUE_EXECUTABLE NAMES glue )
41  # Executable output
42  set ( _exe ${CMAKE_CURRENT_BINARY_DIR}/${_name}${CMAKE_EXECUTABLE_SUFFIX} )
43  if ( NOT SKIP_LUA_WRAPPER AND SRLUA_EXECUTABLE AND GLUE_EXECUTABLE )
44    # Generate binary gluing the lua code to srlua, this is a robuust approach for most systems
45    add_custom_command(
46      OUTPUT ${_exe}
47      COMMAND ${GLUE_EXECUTABLE}
48      ARGS ${SRLUA_EXECUTABLE} ${_source} ${_exe}
49      DEPENDS ${_source}
50      WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
51      VERBATIM
52    )
53    # Make sure we have a target associated with the binary
54    add_custom_target(${_name} ALL
55        DEPENDS ${_exe}
56    )
57    # Install with run permissions
58    install ( PROGRAMS ${_exe} DESTINATION ${INSTALL_BIN} COMPONENT Runtime)
59   # Also install source as optional resurce
60   install ( FILES ${_source} DESTINATION ${INSTALL_FOO} COMPONENT Other )
61  else()
62    # Install into bin as is but without the lua suffix, we assume the executable uses UNIX shebang/hash-bang magic
63    install ( PROGRAMS ${_source} DESTINATION ${INSTALL_BIN}
64            RENAME ${_source_name}
65            COMPONENT Runtime
66    )
67  endif()
68endmacro ()
69
70macro ( _lua_module_helper is_install _name )
71  parse_arguments ( _MODULE "LINK;ALL_IN_ONE" "" ${ARGN} )
72  # _target is CMake-compatible target name for module (e.g. socket_core).
73  # _module is relative path of target (e.g. socket/core),
74  #   without extension (e.g. .lua/.so/.dll).
75  # _MODULE_SRC is list of module source files (e.g. .lua and .c files).
76  # _MODULE_NAMES is list of module names (e.g. socket.core).
77  if ( _MODULE_ALL_IN_ONE )
78    string ( REGEX REPLACE "\\..*" "" _target "${_name}" )
79    string ( REGEX REPLACE "\\..*" "" _module "${_name}" )
80    set ( _target "${_target}_all_in_one")
81    set ( _MODULE_SRC ${_MODULE_ALL_IN_ONE} )
82    set ( _MODULE_NAMES ${_name} ${_MODULE_DEFAULT_ARGS} )
83  else ()
84    string ( REPLACE "." "_" _target "${_name}" )
85    string ( REPLACE "." "/" _module "${_name}" )
86    set ( _MODULE_SRC ${_MODULE_DEFAULT_ARGS} )
87    set ( _MODULE_NAMES ${_name} )
88  endif ()
89  if ( NOT _MODULE_SRC )
90    message ( FATAL_ERROR "no module sources specified" )
91  endif ()
92  list ( GET _MODULE_SRC 0 _first_source )
93 
94  get_filename_component ( _ext ${_first_source} EXT )
95  if ( _ext STREQUAL ".lua" )  # Lua source module
96    list ( LENGTH _MODULE_SRC _len )
97    if ( _len GREATER 1 )
98      message ( FATAL_ERROR "more than one source file specified" )
99    endif ()
100 
101    set ( _module "${_module}.lua" )
102
103    get_filename_component ( _module_dir ${_module} PATH )
104    get_filename_component ( _module_filename ${_module} NAME )
105    _append_path ( "${CMAKE_CURRENT_SOURCE_DIR}" "${_first_source}" _module_path )
106    list ( APPEND _lua_modules "${_name}" "${_module_path}" )
107
108    if ( ${is_install} )
109      install ( FILES ${_first_source} DESTINATION ${INSTALL_LMOD}/${_module_dir}
110                RENAME ${_module_filename}
111                COMPONENT Runtime
112      )
113    endif ()
114  else ()  # Lua C binary module
115    enable_language ( C )
116    find_package ( Lua REQUIRED )
117    include_directories ( ${LUA_INCLUDE_DIR} )
118
119    set ( _module "${_module}${CMAKE_SHARED_MODULE_SUFFIX}" )
120
121    get_filename_component ( _module_dir ${_module} PATH )
122    get_filename_component ( _module_filenamebase ${_module} NAME_WE )
123    foreach ( _thisname ${_MODULE_NAMES} )
124      list ( APPEND _lua_modules "${_thisname}"
125             "${CMAKE_CURRENT_BINARY_DIR}/\${CMAKE_CFG_INTDIR}/${_module}" )
126    endforeach ()
127   
128    add_library( ${_target} MODULE ${_MODULE_SRC})
129    target_link_libraries ( ${_target} ${LUA_LIBRARY} ${_MODULE_LINK} )
130    set_target_properties ( ${_target} PROPERTIES LIBRARY_OUTPUT_DIRECTORY
131                "${_module_dir}" PREFIX "" OUTPUT_NAME "${_module_filenamebase}" )
132    if ( ${is_install} )
133      install ( TARGETS ${_target} DESTINATION ${INSTALL_CMOD}/${_module_dir} COMPONENT Runtime)
134    endif ()
135  endif ()
136endmacro ()
137
138# add_lua_module
139# Builds a Lua source module into a destination locatable by Lua
140# require syntax.
141# Binary modules are also supported where this function takes sources and
142# libraries to compile separated by LINK keyword.
143# USE: add_lua_module ( socket.http src/http.lua )
144# USE2: add_lua_module ( mime.core src/mime.c )
145# USE3: add_lua_module ( socket.core ${SRC_SOCKET} LINK ${LIB_SOCKET} )
146# USE4: add_lua_module ( ssl.context ssl.core ALL_IN_ONE src/context.c src/ssl.c )
147#   This form builds an "all-in-one" module (e.g. ssl.so or ssl.dll containing
148#   both modules ssl.context and ssl.core).  The CMake target name will be
149#   ssl_all_in_one.
150# Also sets variable _module_path (relative path where module typically
151# would be installed).
152macro ( add_lua_module )
153  _lua_module_helper ( 0 ${ARGN} )
154endmacro ()
155
156
157# install_lua_module
158# This is the same as `add_lua_module` but also installs the module.
159# USE: install_lua_module ( socket.http src/http.lua )
160# USE2: install_lua_module ( mime.core src/mime.c )
161# USE3: install_lua_module ( socket.core ${SRC_SOCKET} LINK ${LIB_SOCKET} )
162macro ( install_lua_module )
163  _lua_module_helper ( 1 ${ARGN} )
164endmacro ()
165
166# Builds string representing Lua table mapping Lua modules names to file
167# paths.  Used internally.
168macro ( _make_module_table _outvar )
169  set ( ${_outvar} )
170  list ( LENGTH _lua_modules _n )
171  if ( ${_n} GREATER 0 ) # avoids cmake complaint
172  foreach ( _i RANGE 1 ${_n} 2 )
173    list ( GET _lua_modules ${_i} _path )
174    math ( EXPR _ii ${_i}-1 )
175    list ( GET _lua_modules ${_ii} _name )
176    set ( ${_outvar} "${_table}  ['${_name}'] = '${_path}'\;\n")
177  endforeach ()
178  endif ()
179  set ( ${_outvar}
180"local modules = {
181${_table}}" )
182endmacro ()
183
184# add_lua_test ( _testfile [ WORKING_DIRECTORY _working_dir ] )
185# Runs Lua script `_testfile` under CTest tester.
186# Optional named argument `WORKING_DIRECTORY` is current working directory to
187# run test under (defaults to ${CMAKE_CURRENT_BINARY_DIR}).
188# Both paths, if relative, are relative to ${CMAKE_CURRENT_SOURCE_DIR}.
189# Any modules previously defined with install_lua_module are automatically
190# preloaded (via package.preload) prior to running the test script.
191# Under LuaDist, set test=true in config.lua to enable testing.
192# USE: add_lua_test ( test/test1.lua [args...] [WORKING_DIRECTORY dir])
193macro ( add_lua_test _testfile )
194  if ( NOT SKIP_TESTING )
195    parse_arguments ( _ARG "WORKING_DIRECTORY" "" ${ARGN} )
196    include ( CTest )
197    find_program ( LUA NAMES lua lua.bat )
198    get_filename_component ( TESTFILEABS ${_testfile} ABSOLUTE )
199    get_filename_component ( TESTFILENAME ${_testfile} NAME )
200    get_filename_component ( TESTFILEBASE ${_testfile} NAME_WE )
201
202    # Write wrapper script.
203    # Note: One simple way to allow the script to find modules is
204    # to just put them in package.preload.
205    set ( TESTWRAPPER ${CMAKE_CURRENT_BINARY_DIR}/${TESTFILENAME} )
206    _make_module_table ( _table )
207    set ( TESTWRAPPERSOURCE
208"local CMAKE_CFG_INTDIR = ... or '.'
209${_table}
210local function preload_modules(modules)
211  for name, path in pairs(modules) do
212    if path:match'%.lua' then
213      package.preload[name] = assert(loadfile(path))
214    else
215      local name = name:gsub('.*%-', '') -- remove any hyphen prefix
216      local symbol = 'luaopen_' .. name:gsub('%.', '_')
217          --improve: generalize to support all-in-one loader?
218      local path = path:gsub('%$%{CMAKE_CFG_INTDIR%}', CMAKE_CFG_INTDIR)
219      package.preload[name] = assert(package.loadlib(path, symbol))
220    end
221  end
222end
223preload_modules(modules)
224arg[0] = '${TESTFILEABS}'
225table.remove(arg, 1)
226return assert(loadfile '${TESTFILEABS}')(unpack(arg))
227"    )
228    if ( _ARG_WORKING_DIRECTORY )
229      get_filename_component (
230         TESTCURRENTDIRABS ${_ARG_WORKING_DIRECTORY} ABSOLUTE )
231      # note: CMake 2.6 (unlike 2.8) lacks WORKING_DIRECTORY parameter.
232      set ( _pre ${CMAKE_COMMAND} -E chdir "${TESTCURRENTDIRABS}" )
233    endif ()
234    file ( WRITE ${TESTWRAPPER} ${TESTWRAPPERSOURCE})
235    add_test ( NAME ${TESTFILEBASE} COMMAND ${_pre} ${LUA}
236               ${TESTWRAPPER} "${CMAKE_CFG_INTDIR}"
237               ${_ARG_DEFAULT_ARGS} )
238  endif ()
239  # see also http://gdcm.svn.sourceforge.net/viewvc/gdcm/Sandbox/CMakeModules/UsePythonTest.cmake
240  # Note: ${CMAKE_CFG_INTDIR} is a command-line argument to allow proper
241  # expansion by the native build tool.
242endmacro ()
243
244
245# Converts Lua source file `_source` to binary string embedded in C source
246# file `_target`.  Optionally compiles Lua source to byte code (not available
247# under LuaJIT2, which doesn't have a bytecode loader).  Additionally, Lua
248# versions of bin2c [1] and luac [2] may be passed respectively as additional
249# arguments.
250#
251# [1] http://lua-users.org/wiki/BinToCee
252# [2] http://lua-users.org/wiki/LuaCompilerInLua
253function ( add_lua_bin2c _target _source )
254  find_program ( LUA NAMES lua lua.bat )
255  execute_process ( COMMAND ${LUA} -e "string.dump(function()end)"
256                    RESULT_VARIABLE _LUA_DUMP_RESULT ERROR_QUIET )
257  if ( NOT ${_LUA_DUMP_RESULT} )
258    SET ( HAVE_LUA_DUMP true )
259  endif ()
260  message ( "-- string.dump=${HAVE_LUA_DUMP}" )
261
262  if ( ARGV2 )
263    get_filename_component ( BIN2C ${ARGV2} ABSOLUTE )
264    set ( BIN2C ${LUA} ${BIN2C} )
265  else ()
266    find_program ( BIN2C NAMES bin2c bin2c.bat )
267  endif ()
268  if ( HAVE_LUA_DUMP )
269    if ( ARGV3 )
270      get_filename_component ( LUAC ${ARGV3} ABSOLUTE )
271      set ( LUAC ${LUA} ${LUAC} )
272    else ()
273      find_program ( LUAC NAMES luac luac.bat )
274    endif ()
275  endif ( HAVE_LUA_DUMP )
276  message ( "-- bin2c=${BIN2C}" )
277  message ( "-- luac=${LUAC}" )
278
279  get_filename_component ( SOURCEABS ${_source} ABSOLUTE )
280  if ( HAVE_LUA_DUMP )
281    get_filename_component ( SOURCEBASE ${_source} NAME_WE )
282    add_custom_command (
283      OUTPUT  ${_target} DEPENDS ${_source}
284      COMMAND ${LUAC} -o ${CMAKE_CURRENT_BINARY_DIR}/${SOURCEBASE}.lo
285              ${SOURCEABS}
286      COMMAND ${BIN2C} ${CMAKE_CURRENT_BINARY_DIR}/${SOURCEBASE}.lo
287              ">${_target}" )
288  else ()
289    add_custom_command (
290      OUTPUT  ${_target} DEPENDS ${SOURCEABS}
291      COMMAND ${BIN2C} ${_source} ">${_target}" )
292  endif ()
293endfunction()
trunk/3rdparty/lsqlite3/dist.info
r0r242834
1--- This dist file is part of LuaDist project
2
3name = "lsqlite3"
4version = "0.6devel"
5
6desc = "LuaSQLite 3 is a thin wrapper around the public domain SQLite3 database engine."
7author = "Tiago Dionizio, Doug Currie"
8license = "MIT"
9url = "http://luaforge.net/projects/luasqlite/"
10maintainer = "Peter Kapec"
11
12depends = {
13   "lua ~> 5.1",
14   "libsqlite3 >=3.5"
15}
trunk/3rdparty/lsqlite3/doc/lsqlite3.html
r0r242834
1<HTML>
2<HEAD>
3<TITLE>LuaSQLite 3</TITLE>
4<LINK REV="made" HREF="mailto:unknown@du216771.users">
5</HEAD>
6
7<BODY>
8
9<A NAME="__index__"></A>
10<!-- INDEX BEGIN -->
11
12<UL>
13
14   <LI><A HREF="#name">NAME</A></LI>
15   <LI><A HREF="#overview">OVERVIEW</A></LI>
16   <LI><A HREF="#download">DOWNLOAD</A></LI>
17   <LI><A HREF="#installation">INSTALLATION</A></LI>
18   <LI><A HREF="#examples">EXAMPLES</A></LI>
19   <LI><A HREF="#verification tests">VERIFICATION TESTS</A></LI>
20   <LI><A HREF="#reference">REFERENCE</A></LI>
21   <LI><A HREF="#sqlite3 functions">SQLite3 functions</A></LI>
22   <UL>
23
24      <LI><A HREF="#sqlite3.complete">sqlite3.complete</A></LI>
25      <LI><A HREF="#sqlite3.open">sqlite3.open</A></LI>
26      <LI><A HREF="#sqlite3.open_memory">sqlite3.open_memory</A></LI>
27      <LI><A HREF="#sqlite3.temp_directory">sqlite3.temp_directory</A></LI>
28      <LI><A HREF="#sqlite3.version">sqlite3.version</A></LI>
29   </UL>
30
31   <LI><A HREF="#database methods">Database methods</A></LI>
32   <UL>
33
34      <LI><A HREF="#db:busy_handler">db:busy_handler</A></LI>
35      <LI><A HREF="#db:busy_timeout">db:busy_timeout</A></LI>
36      <LI><A HREF="#db:changes">db:changes</A></LI>
37      <LI><A HREF="#db:close">db:close</A></LI>
38      <LI><A HREF="#db:close_vm">db:close_vm</A></LI>
39      <LI><A HREF="#db:create_aggregate">db:create_aggregate</A></LI>
40      <LI><A HREF="#db:create_collation">db:create_collation</A></LI>
41      <LI><A HREF="#db:create_function">db:create_function</A></LI>
42      <LI><A HREF="#db:errcode">db:errcode</A></LI>
43      <LI><A HREF="#db:errmsg">db:errmsg</A></LI>
44      <LI><A HREF="#db:exec">db:exec</A></LI>
45      <LI><A HREF="#db:interrupt">db:interrupt</A></LI>
46      <LI><A HREF="#db:isopen">db:isopen</A></LI>
47      <LI><A HREF="#db:last_insert_rowid">db:last_insert_rowid</A></LI>
48      <LI><A HREF="#db:nrows">db:nrows</A></LI>
49      <LI><A HREF="#db:prepare">db:prepare</A></LI>
50      <LI><A HREF="#db:progress_handler">db:progress_handler</A></LI>
51      <LI><A HREF="#db:rows">db:rows</A></LI>
52      <LI><A HREF="#db:total_changes">db:total_changes</A></LI>
53      <LI><A HREF="#db:trace">db:trace</A></LI>
54      <LI><A HREF="#db:urows">db:urows</A></LI>
55   </UL>
56
57   <LI><A HREF="#methods for prepared statements">Methods for prepared statements</A></LI>
58   <UL>
59
60      <LI><A HREF="#stmt:bind">stmt:bind</A></LI>
61      <LI><A HREF="#stmt:bind_blob">stmt:bind_blob</A></LI>
62      <LI><A HREF="#stmt:bind_names">stmt:bind_names</A></LI>
63      <LI><A HREF="#stmt:bind_parameter_count">stmt:bind_parameter_count</A></LI>
64      <LI><A HREF="#stmt:bind_parameter_name">stmt:bind_parameter_name</A></LI>
65      <LI><A HREF="#stmt:bind_values">stmt:bind_values</A></LI>
66      <LI><A HREF="#stmt:columns">stmt:columns</A></LI>
67      <LI><A HREF="#stmt:finalize">stmt:finalize</A></LI>
68      <LI><A HREF="#stmt:get_name">stmt:get_name</A></LI>
69      <LI><A HREF="#stmt:get_named_types">stmt:get_named_types</A></LI>
70      <LI><A HREF="#stmt:get_named_values">stmt:get_named_values</A></LI>
71      <LI><A HREF="#stmt:get_names">stmt:get_names</A></LI>
72      <LI><A HREF="#stmt:get_type">stmt:get_type</A></LI>
73      <LI><A HREF="#stmt:get_types">stmt:get_types</A></LI>
74      <LI><A HREF="#stmt:get_unames">stmt:get_unames</A></LI>
75      <LI><A HREF="#stmt:get_utypes">stmt:get_utypes</A></LI>
76      <LI><A HREF="#stmt:get_uvalues">stmt:get_uvalues</A></LI>
77      <LI><A HREF="#stmt:get_value">stmt:get_value</A></LI>
78      <LI><A HREF="#stmt:get_values">stmt:get_values</A></LI>
79      <LI><A HREF="#stmt:isopen">stmt:isopen</A></LI>
80      <LI><A HREF="#stmt:nrows">stmt:nrows</A></LI>
81      <LI><A HREF="#stmt:reset">stmt:reset</A></LI>
82      <LI><A HREF="#stmt:rows">stmt:rows</A></LI>
83      <LI><A HREF="#stmt:step">stmt:step</A></LI>
84      <LI><A HREF="#stmt:urows">stmt:urows</A></LI>
85   </UL>
86
87   <LI><A HREF="#methods for callback contexts">Methods for callback contexts</A></LI>
88   <UL>
89
90      <LI><A HREF="#context:aggregate_count">context:aggregate_count</A></LI>
91      <LI><A HREF="#context:get_aggregate_data">context:get_aggregate_data</A></LI>
92      <LI><A HREF="#context:set_aggregate_data">context:set_aggregate_data</A></LI>
93      <LI><A HREF="#context:result">context:result</A></LI>
94      <LI><A HREF="#context:result_null">context:result_null</A></LI>
95      <LI><A HREF="#context:result_number">context:result_number</A></LI>
96      <LI><A HREF="#context:result_int">context:result_int</A></LI>
97      <LI><A HREF="#context:result_text">context:result_text</A></LI>
98      <LI><A HREF="#context:result_blob">context:result_blob</A></LI>
99      <LI><A HREF="#context:result_error">context:result_error</A></LI>
100      <LI><A HREF="#context:user_data">context:user_data</A></LI>
101   </UL>
102
103   <LI><A HREF="#numerical error and result codes">Numerical error and result codes</A></LI>
104   <LI><A HREF="#version">VERSION</A></LI>
105   <LI><A HREF="#credits">CREDITS</A></LI>
106   <LI><A HREF="#license">LICENSE</A></LI>
107</UL>
108<!-- INDEX END -->
109
110<HR>
111<P>
112<HR>
113<H1><A NAME="name">NAME</A></H1>
114<P><STRONG>LuaSQLite 3</STRONG> - a Lua 5.1 wrapper for the SQLite3 library</P>
115<P>
116<HR>
117<H1><A NAME="overview">OVERVIEW</A></H1>
118<P><STRONG>LuaSQLite 3</STRONG> is a thin wrapper around the public domain SQLite3
119database engine.</P>
120<P>The <CODE>lsqlite3</CODE> module supports the creation and manipulation of
121SQLite3 databases. After a <CODE>require('lsqlite3')</CODE> the exported
122functions are called with prefix <CODE>sqlite3</CODE>. However, most sqlite3
123functions are called via an object-oriented interface to either
124database or SQL statement objects; see below for details.</P>
125<P>This documentation does not attempt to describe how SQLite3 itself
126works, it just describes the Lua binding and the available functions.
127For more information about the SQL features supported by SQLite3 and
128details about the syntax of SQL statements and queries, please see the
129<STRONG>SQLite3 documentation</STRONG> <A HREF="http://www.sqlite.org/">http://www.sqlite.org/</A>. Using some of the
130advanced features (how to use callbacks, for instance) will require
131some familiarity with the SQLite3 API.</P>
132<P>
133<HR>
134<H1><A NAME="download">DOWNLOAD</A></H1>
135<P><STRONG>LuaSQLite 3</STRONG> source code can be downloaded from its
136LuaForge (<A HREF="http://luaforge.net/projects/luasqlite/">http://luaforge.net/projects/luasqlite/</A>) page.</P>
137<P>You will also need to build or obtain an SQLite3 loadable library
138(DLL or .so). See <A HREF="http://www.sqlite.org/">http://www.sqlite.org/</A> for obtaining SQLite3
139source code or downloading a binary SQLite3 library.</P>
140<P>
141<HR>
142<H1><A NAME="installation">INSTALLATION</A></H1>
143<P>A <EM>Makefile</EM> is provided; it assumes an SQLite3 library is already
144installed.</P>
145<P>
146<HR>
147<H1><A NAME="examples">EXAMPLES</A></H1>
148<P>The distribution contains an <EM>examples</EM> directory. The unit tests
149also show some example use.</P>
150<P>
151<HR>
152<H1><A NAME="verification tests">VERIFICATION TESTS</A></H1>
153<P>The distribution contains some units tests using Michael Roth's
154<CODE>lunit</CODE> (which is also included). Some of the tests were also derived
155from Michael's <STRONG>lua-sqlite3</STRONG> module, and more unit tests added by
156Doug Currie.</P>
157<P>The distribution also contains some functional tests by Tiago.</P>
158<P>This version of <CODE>lsqlite3</CODE> was tested with SQLite 3.4.2.</P>
159<P>
160<HR>
161<H1><A NAME="reference">REFERENCE</A></H1>
162<P>
163<HR>
164<H1><A NAME="sqlite3 functions">SQLite3 functions</A></H1>
165<P>
166<H2><A NAME="sqlite3.complete">sqlite3.complete</A></H2>
167<PRE>
168        sqlite3.complete(sql)</PRE>
169<P>Returns true if the string <CODE>sql</CODE> comprises one or more complete SQL
170statements and false otherwise.</P>
171<P>
172<H2><A NAME="sqlite3.open">sqlite3.open</A></H2>
173<PRE>
174        sqlite3.open(filename)</PRE>
175<P>Opens (or creates if it does not exist) an SQLite database with name
176<CODE>filename</CODE> and returns its handle as userdata (the returned object
177should be used for all further method calls in connection with this
178specific database, see <A HREF="#database methods">Database methods</A>). Example:</P>
179<PRE>
180        myDB=sqlite3.open('MyDatabase.sqlite3')  -- open
181        -- do some database calls...
182        myDB:close()  -- close</PRE>
183<P>In case of an error, the function returns nil, an error code and an
184error message.</P>
185<P>
186<H2><A NAME="sqlite3.open_memory">sqlite3.open_memory</A></H2>
187<PRE>
188        sqlite3.open_memory()</PRE>
189<P>Opens an SQLite database <STRONG>in memory</STRONG> and returns its handle as
190userdata. In case of an error, the function returns nil, an error code
191and an error message. (In-memory databases are volatile as they are
192never stored on disk.)</P>
193<P>
194<H2><A NAME="sqlite3.temp_directory">sqlite3.temp_directory</A></H2>
195<PRE>
196        sqlite3.temp_directory([temp])</PRE>
197<P>Sets or queries the directory used by SQLite for temporary files. If
198string <CODE>temp</CODE> is a directory name or nil, the temporary directory is
199set accordingly and the old value is returned. If <CODE>temp</CODE> is missing,
200the function simply returns the current temporary directory.</P>
201<P>
202<H2><A NAME="sqlite3.version">sqlite3.version</A></H2>
203<PRE>
204        sqlite3.version()</PRE>
205<P>Returns a string with SQLite version information, in the form 'x.y[.z]'.</P>
206<P>
207<HR>
208<H1><A NAME="database methods">Database methods</A></H1>
209<P>After opening a database with <A HREF="#sqlite3.open"><CODE>sqlite3.open()</CODE></A> or
210<A HREF="#sqlite3.open_memory"><CODE>sqlite3.open_memory()</CODE></A>
211the returned database object should be used for all further method calls
212in connection with that database. An open database object supports the
213following methods.</P>
214<P>
215<H2><A NAME="db:busy_handler">db:busy_handler</A></H2>
216<PRE>
217        db:busy_handler([func[,udata]])</PRE>
218<P>Sets or removes a busy handler for a database. <CODE>func</CODE> is either a Lua
219function that implements the busy handler or nil to remove a previously
220set handler. This function returns nothing.</P>
221<P>The handler function is called with two parameters: <CODE>udata</CODE> and the
222number of (re-)tries for a pending transaction. It should return nil,
223false or 0 if the transaction is to be aborted. All other values will
224result in another attempt to perform the transaction. (See the SQLite
225documentation for important hints about writing busy handlers.)</P>
226<P>
227<H2><A NAME="db:busy_timeout">db:busy_timeout</A></H2>
228<PRE>
229        db:busy_timeout(t)</PRE>
230<P>Sets a busy handler that waits for <CODE>t</CODE> milliseconds if a transaction
231cannot proceed. Calling this function will remove any busy handler set
232by <A HREF="#db:busy_handler"><CODE>db:busy_handler()</CODE></A>; calling it with an argument
233less than or equal to 0 will turn off all busy handlers.</P>
234<P>
235<H2><A NAME="db:changes">db:changes</A></H2>
236<PRE>
237        db:changes()</PRE>
238<P>This function returns the number of database rows that were changed (or
239inserted or deleted) by the most recent SQL statement. Only changes that
240are directly specified by INSERT, UPDATE, or DELETE statements are
241counted. Auxiliary changes caused by triggers are not counted. Use
242<A HREF="#db:total_changes"><CODE>db:total_changes()</CODE></A> to find the total number of
243changes.</P>
244<P>
245<H2><A NAME="db:close">db:close</A></H2>
246<PRE>
247        db:close()</PRE>
248<P>Closes a database. All SQL statements prepared using
249<A HREF="#db:prepare"><CODE>db:prepare()</CODE></A> should
250have been finalized before this function is called. The function returns
251<CODE>sqlite3.OK</CODE> on success or else a numerical error code (see the list of
252<A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P>
253<P>
254<H2><A NAME="db:close_vm">db:close_vm</A></H2>
255<PRE>
256        db:close_vm(temponly)</PRE>
257<P>Finalizes all statements that have not been explicitly finalized. If
258<CODE>temponly</CODE> is true, only internal, temporary statements are finalized.
259This function returns nothing.</P>
260<P>
261<H2><A NAME="db:create_aggregate">db:create_aggregate</A></H2>
262<PRE>
263        db:create_aggregate(name,nargs,step,final)</PRE>
264<P>This function creates an aggregate callback function. Aggregates perform
265an operation over all rows in a query. <CODE>name</CODE> is a string with the name
266of the aggregate function as given in an SQL statement; <CODE>nargs</CODE> is the
267number of arguments this call will provide. <CODE>step</CODE> is the actual Lua
268function that gets called once for every row; it should accept a function
269context (see <A HREF="#methods for callback contexts">Methods for callback contexts</A>) plus the same number of
270parameters as given in <CODE>nargs</CODE>. <CODE>final</CODE> is a function that is called
271once after all rows have been processed; it receives one argument, the
272function context.</P>
273<P>The function context can be used inside the two callback functions to
274communicate with SQLite3. Here is a simple example:</P>
275<PRE>
276        db:exec[=[
277          CREATE TABLE numbers(num1,num2);
278          INSERT INTO numbers VALUES(1,11);
279          INSERT INTO numbers VALUES(2,22);
280          INSERT INTO numbers VALUES(3,33);
281        ]=]
282        local num_sum=0
283        local function oneRow(context,num)  -- add one column in all rows
284          num_sum=num_sum+num
285        end
286        local function afterLast(context)   -- return sum after last row has been processed
287          context:result_number(num_sum)
288          num_sum=0
289        end
290        db:create_aggregate(&quot;do_the_sums&quot;,1,oneRow,afterLast)
291        for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print(&quot;Sum of col 1:&quot;,sum) end
292        for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print(&quot;Sum of col 2:&quot;,sum) end</PRE>
293<P>This prints:</P>
294<PRE>
295        Sum of col 1:   6
296        Sum of col 2:   66</PRE>
297<P>
298<H2><A NAME="db:create_collation">db:create_collation</A></H2>
299<PRE>
300        db:create_collation(name,func)</PRE>
301<P>This creates a collation callback. A collation callback is used to
302establish a collation order, mostly for string comparisons and sorting
303purposes. <CODE>name</CODE> is a string with the name of the collation to be created;
304<CODE>func</CODE> is a function that accepts two string arguments, compares them
305and returns 0 if both strings are identical, -1 if the first argument is
306lower in the collation order than the second and 1 if the first argument
307is higher in the collation order than the second. A simple example:</P>
308<PRE>
309        local function collate(s1,s2)
310          s1=s1:lower()
311          s2=s2:lower()
312          if s1==s2 then return 0
313          elseif s1&lt;s2 then return -1
314          else return 1 end
315        end
316        db:exec[=[
317          CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS);
318          INSERT INTO test VALUES(NULL,'hello world');
319          INSERT INTO test VALUES(NULL,'Buenos dias');
320          INSERT INTO test VALUES(NULL,'HELLO WORLD');
321        ]=]
322        db:create_collation('CINSENS',collate)
323        for row in db:nrows('SELECT * FROM test') do print(row.id,row.content) end</PRE>
324<P>
325<H2><A NAME="db:create_function">db:create_function</A></H2>
326<PRE>
327        db:create_function(name,nargs,func)</PRE>
328<P>This function creates a callback function. Callback function are called
329by SQLite3 once for every row in a query. <CODE>name</CODE> is a string with the
330name of the callback function as given in an SQL statement; <CODE>nargs</CODE> is
331the number of arguments this call will provide. <CODE>func</CODE> is the actual Lua
332function that gets called once for every row; it should accept a
333function context (see <A HREF="#methods for callback contexts">Methods for callback contexts</A>) plus the same
334number of parameters as given in nargs. Here is an example:</P>
335<PRE>
336        db:exec'CREATE TABLE test(col1,col2,col3)'
337        db:exec'INSERT INTO test VALUES(1,2,4)'
338        db:exec'INSERT INTO test VALUES(2,4,9)'
339        db:exec'INSERT INTO test VALUES(3,6,16)'
340        db:create_function('sum_cols',3,function(ctx,a,b,c)
341          ctx:result_number(a+b+c)
342        end))
343        for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do
344          util.printf('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum)
345        end</PRE>
346<P>
347<H2><A NAME="db:errcode">db:errcode</A></H2>
348<PRE>
349        db:errcode()
350        db:error_code()</PRE>
351<P>Returns the numerical result code (or extended result code) for the most
352recent failed call associated with database db. See
353<A HREF="#numerical error and result codes">Numerical error and result codes</A> for details.</P>
354<P>
355<H2><A NAME="db:errmsg">db:errmsg</A></H2>
356<PRE>
357        db:errmsg()
358        db:error_message()</PRE>
359<P>Returns a string that contains an error message for the most recent
360failed call associated with database db.</P>
361<P>
362<H2><A NAME="db:exec">db:exec</A></H2>
363<PRE>
364        db:exec(sql[,func[,udata]])
365        db:execute(sql[,func[,udata]])</PRE>
366<P>Compiles and executes the SQL <CODE>statement(s)</CODE> given in string <CODE>sql</CODE>. The
367statements are simply executed one after the other and not stored. The
368function returns <CODE>sqlite3.OK</CODE> on success or else a numerical error code
369(see <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P>
370<P>If one or more of the SQL statements are queries, then the callback
371function specified in <CODE>func</CODE> is invoked once for each row of the query
372result (if <CODE>func</CODE> is nil, no callback is invoked). The callback receives
373four arguments: <CODE>udata</CODE> (the third parameter of the <CODE>db:exec()</CODE> call),
374the number of columns in the row, a table with the column values and
375another table with the column names. The callback function should return
3760. If the callback returns a non-zero value then the query is aborted,
377all subsequent SQL statements are skipped and <CODE>db:exec()</CODE> returns
378<CODE>sqlite3.ABORT</CODE>. Here is a simple example:</P>
379<PRE>
380        sql=[=[
381          CREATE TABLE numbers(num1,num2,str);
382          INSERT INTO numbers VALUES(1,11,&quot;ABC&quot;);
383          INSERT INTO numbers VALUES(2,22,&quot;DEF&quot;);
384          INSERT INTO numbers VALUES(3,33,&quot;UVW&quot;);
385          INSERT INTO numbers VALUES(4,44,&quot;XYZ&quot;);
386          SELECT * FROM numbers;
387        ]=]
388        function showrow(udata,cols,values,names)
389          assert(udata=='test_udata')
390          print('exec:')
391          for i=1,cols do print('',names[i],values[i]) end
392          return 0
393        end
394        db:exec(sql,showrow,'test_udata')</PRE>
395<P>
396<H2><A NAME="db:interrupt">db:interrupt</A></H2>
397<PRE>
398        db:interrupt()</PRE>
399<P>This function causes any pending database operation to abort and return
400at the next opportunity. This function returns nothing.</P>
401<P>
402<H2><A NAME="db:isopen">db:isopen</A></H2>
403<PRE>
404        db:isopen()</PRE>
405<P>Returns true if database db is open, false otherwise.</P>
406<P>
407<H2><A NAME="db:last_insert_rowid">db:last_insert_rowid</A></H2>
408<PRE>
409        db:last_insert_rowid()</PRE>
410<P>This function returns the rowid of the most recent INSERT into the
411database. If no inserts have ever occurred, 0 is returned. (Each row in
412an SQLite table has a unique 64-bit signed integer key called the
413'rowid'. This id is always available as an undeclared column named
414ROWID, OID, or _ROWID_. If the table has a column of type INTEGER
415PRIMARY KEY then that column is another alias for the rowid.)</P>
416<P>If an INSERT occurs within a trigger, then the rowid of the inserted row
417is returned as long as the trigger is running. Once the trigger
418terminates, the value returned reverts to the last value inserted before
419the trigger fired.</P>
420<P>
421<H2><A NAME="db:nrows">db:nrows</A></H2>
422<PRE>
423        db:nrows(sql)</PRE>
424<P>Creates an iterator that returns the successive rows selected by the SQL
425statement given in string <CODE>sql</CODE>. Each call to the iterator returns a
426table in which the named fields correspond to the columns in the database.
427Here is an example:</P>
428<PRE>
429        db:exec[=[
430          CREATE TABLE numbers(num1,num2);
431          INSERT INTO numbers VALUES(1,11);
432          INSERT INTO numbers VALUES(2,22);
433          INSERT INTO numbers VALUES(3,33);
434        ]=]
435        for a in db:nrows('SELECT * FROM numbers') do table.print(a) end</PRE>
436<P>This script prints:</P>
437<PRE>
438        num2: 11
439        num1: 1
440        num2: 22
441        num1: 2
442        num2: 33
443        num1: 3</PRE>
444<P>
445<H2><A NAME="db:prepare">db:prepare</A></H2>
446<PRE>
447        db:prepare(sql)</PRE>
448<P>This function compiles the SQL statement in string <CODE>sql</CODE> into an internal
449representation and returns this as userdata. The returned object should
450be used for all further method calls in connection with this specific
451SQL statement (see <A HREF="#methods for prepared statements">Methods for prepared statements</A>).</P>
452<P>
453<H2><A NAME="db:progress_handler">db:progress_handler</A></H2>
454<PRE>
455        db:progress_handler(n,func,udata)</PRE>
456<P>This function installs a callback function <CODE>func</CODE> that is invoked
457periodically during long-running calls to <A HREF="#db:exec"><CODE>db:exec()</CODE></A>
458or <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A>. The
459progress callback is invoked once for every <CODE>n</CODE> internal operations,
460where <CODE>n</CODE> is the first argument to this function. <CODE>udata</CODE> is passed to
461the progress callback function each time it is invoked. If a call to
462<CODE>db:exec()</CODE> or <CODE>stmt:step()</CODE> results in fewer than <CODE>n</CODE> operations
463being executed, then the progress callback is never invoked. Only a
464single progress callback function may be registered for each opened
465database and a call to this function will overwrite any previously set
466callback function. To remove the progress callback altogether, pass nil
467as the second argument.</P>
468<P>If the progress callback returns a result other than 0, then the current
469query is immediately terminated, any database changes are rolled back
470and the containing <CODE>db:exec()</CODE> or <CODE>stmt:step()</CODE> call returns
471<CODE>sqlite3.INTERRUPT</CODE>. This feature can be used to cancel long-running
472queries.</P>
473<P>
474<H2><A NAME="db:rows">db:rows</A></H2>
475<PRE>
476        db:rows(sql)</PRE>
477<P>Creates an iterator that returns the successive rows selected by the SQL
478statement given in string <CODE>sql</CODE>. Each call to the iterator returns a table
479in which the numerical indices 1 to n correspond to the selected columns
4801 to n in the database. Here is an example:</P>
481<PRE>
482        db:exec[=[
483          CREATE TABLE numbers(num1,num2);
484          INSERT INTO numbers VALUES(1,11);
485          INSERT INTO numbers VALUES(2,22);
486          INSERT INTO numbers VALUES(3,33);
487        ]=]
488        for a in db:rows('SELECT * FROM numbers') do table.print(a) end</PRE>
489<P>This script prints:</P>
490<PRE>
491        1: 1
492        2: 11
493        1: 2
494        2: 22
495        1: 3
496        2: 33</PRE>
497<P>
498<H2><A NAME="db:total_changes">db:total_changes</A></H2>
499<PRE>
500        db:total_changes()</PRE>
501<P>This function returns the number of database rows that have been
502modified by INSERT, UPDATE or DELETE statements since the database was
503opened. This includes UPDATE, INSERT and DELETE statements executed as
504part of trigger programs. All changes are counted as soon as the
505statement that produces them is completed by calling either
506<A HREF="#stmt:reset"><CODE>stmt:reset()</CODE></A> or <A HREF="#stmt:finalize"><CODE>stmt:finalize()</CODE></A>.</P>
507<P>
508<H2><A NAME="db:trace">db:trace</A></H2>
509<PRE>
510        db:trace(func,udata)</PRE>
511<P>This function installs a trace callback handler. <CODE>func</CODE> is a Lua
512function that is called by SQLite3 just before the evaluation of an SQL
513statement. This callback receives two arguments: the first is the
514<CODE>udata</CODE> argument used when the callback was installed; the second is a
515string with the SQL statement about to be executed.</P>
516<P>
517<H2><A NAME="db:urows">db:urows</A></H2>
518<PRE>
519        db:urows(sql)</PRE>
520<P>Creates an iterator that returns the successive rows selected by the SQL
521statement given in string <CODE>sql</CODE>. Each call to the iterator returns the
522values that correspond to the columns in the currently selected row.
523Here is an example:</P>
524<PRE>
525        db:exec[=[
526          CREATE TABLE numbers(num1,num2);
527          INSERT INTO numbers VALUES(1,11);
528          INSERT INTO numbers VALUES(2,22);
529          INSERT INTO numbers VALUES(3,33);
530        ]=]
531        for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end</PRE>
532<P>This script prints:</P>
533<PRE>
534        1       11
535        2       22
536        3       33</PRE>
537<P>
538<HR>
539<H1><A NAME="methods for prepared statements">Methods for prepared statements</A></H1>
540<P>After creating a prepared statement with <A HREF="#db:prepare"><CODE>db:prepare()</CODE></A>
541the returned statement object should be used for all further calls in
542connection with that statement. Statement objects support the following
543methods.</P>
544<P>
545<H2><A NAME="stmt:bind">stmt:bind</A></H2>
546<PRE>
547        stmt:bind(n[,value])</PRE>
548<P>Binds value to statement parameter <CODE>n</CODE>. If the type of value is string
549or number, it is bound as text or double, respectively. If <CODE>value</CODE> is a
550boolean or nil or missing, any previous binding is removed. The function
551returns <CODE>sqlite3.OK</CODE> on success or else a numerical error code (see
552<A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P>
553<P>
554<H2><A NAME="stmt:bind_blob">stmt:bind_blob</A></H2>
555<PRE>
556        stmt:bind_blob(n,blob)</PRE>
557<P>Binds string <CODE>blob</CODE> (which can be a binary string) as a blob to
558statement parameter <CODE>n</CODE>. The function returns <CODE>sqlite3.OK</CODE> on success
559or else a numerical error code (see <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P>
560<P>
561<H2><A NAME="stmt:bind_names">stmt:bind_names</A></H2>
562<PRE>
563        stmt:bind_names(nametable)</PRE>
564<P>Binds the values in <CODE>nametable</CODE> to statement parameters. If the
565statement parameters are named (i.e., of the form ``:AAA'' or ``$AAA'')
566then this function looks for appropriately named fields in <CODE>nametable</CODE>;
567if the statement parameters are
568not named, it looks for numerical fields 1 to the number of statement
569parameters. The function returns <CODE>sqlite3.OK</CODE> on success or else a
570numerical error code (see <A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P>
571<P>
572<H2><A NAME="stmt:bind_parameter_count">stmt:bind_parameter_count</A></H2>
573<PRE>
574        stmt:bind_parameter_count()</PRE>
575<P>Returns the largest statement parameter index in prepared statement
576<CODE>stmt</CODE>. When the statement parameters are of the forms ``:AAA'' or ``?'',
577then they are assigned sequentially increasing numbers beginning with
578one, so the value returned is the number of parameters. However if the
579same statement parameter name is used multiple times, each occurrence
580is given the same number, so the value returned is the number of unique
581statement parameter names.</P>
582<P>If statement parameters of the form ``?NNN'' are used (where NNN is an
583integer) then there might be gaps in the numbering and the value
584returned by this interface is the index of the statement parameter with
585the largest index value.</P>
586<P>
587<H2><A NAME="stmt:bind_parameter_name">stmt:bind_parameter_name</A></H2>
588<PRE>
589        stmt:bind_parameter_name(n)</PRE>
590<P>Returns the name of the <CODE>n</CODE>-th parameter in prepared statement <CODE>stmt</CODE>.
591Statement parameters of the form ``:AAA'' or ``@AAA'' or ``$VVV'' have a name
592which  is the string ``:AAA'' or ``@AAA'' or ``$VVV''. In other words, the
593initial ``:'' or ``$'' or ``@'' is included as part of the name. Parameters
594of the form ``?'' or ``?NNN'' have no name. The first bound parameter has
595an index of 1.
596If the value <CODE>n</CODE> is out of range or if the <CODE>n</CODE>-th parameter is
597nameless, then nil is returned. The function returns <CODE>sqlite3.OK</CODE> on
598success or else a numerical error code (see
599<A HREF="#numerical error and result codes">Numerical error and result codes</A>)</P>
600<P>
601<H2><A NAME="stmt:bind_values">stmt:bind_values</A></H2>
602<PRE>
603        stmt:bind_values(value1,value2,...,valueN)</PRE>
604<P>Binds the given values to statement parameters. The function returns
605<CODE>sqlite3.OK</CODE> on success or else a numerical error code (see
606<A HREF="#numerical error and result codes">Numerical error and result codes</A>).</P>
607<P>
608<H2><A NAME="stmt:columns">stmt:columns</A></H2>
609<PRE>
610        stmt:columns()</PRE>
611<P>Returns the number of columns in the result set returned by statement
612stmt or 0 if the statement does not return data (for example an UPDATE).</P>
613<P>
614<H2><A NAME="stmt:finalize">stmt:finalize</A></H2>
615<PRE>
616        stmt:finalize()</PRE>
617<P>This function frees prepared statement stmt. If the statement was
618executed successfully, or not executed at all, then <CODE>sqlite3.OK</CODE> is
619returned. If execution of the statement failed then an error code is
620returned.</P>
621<P>
622<H2><A NAME="stmt:get_name">stmt:get_name</A></H2>
623<PRE>
624        stmt:get_name(n)</PRE>
625<P>Returns the name of column <CODE>n</CODE> in the result set of statement stmt. (The
626left-most column is number 0.)</P>
627<P>
628<H2><A NAME="stmt:get_named_types">stmt:get_named_types</A></H2>
629<PRE>
630        stmt:get_named_types()</PRE>
631<P>Returns a table with the names and types of all columns in the result
632set of statement stmt.</P>
633<P>
634<H2><A NAME="stmt:get_named_values">stmt:get_named_values</A></H2>
635<PRE>
636        stmt:get_named_values()</PRE>
637<P>This function returns a table with names and values of all columns in
638the current result row of a query.</P>
639<P>
640<H2><A NAME="stmt:get_names">stmt:get_names</A></H2>
641<PRE>
642        stmt:get_names()</PRE>
643<P>This function returns an array with the names of all columns in the
644result set returned by statement stmt.</P>
645<P>
646<H2><A NAME="stmt:get_type">stmt:get_type</A></H2>
647<PRE>
648        stmt:get_type(n)</PRE>
649<P>Returns the type of column <CODE>n</CODE> in the result set of statement stmt. (The
650left-most column is number 0.)</P>
651<P>
652<H2><A NAME="stmt:get_types">stmt:get_types</A></H2>
653<PRE>
654        stmt:get_types()</PRE>
655<P>This function returns an array with the types of all columns in the
656result set returned by statement stmt.</P>
657<P>
658<H2><A NAME="stmt:get_unames">stmt:get_unames</A></H2>
659<PRE>
660        stmt:get_unames()</PRE>
661<P>This function returns a list with the names of all columns in the result
662set returned by statement stmt.</P>
663<P>
664<H2><A NAME="stmt:get_utypes">stmt:get_utypes</A></H2>
665<PRE>
666        stmt:get_utypes()</PRE>
667<P>This function returns a list with the types of all columns in the result
668set returned by statement stmt.</P>
669<P>
670<H2><A NAME="stmt:get_uvalues">stmt:get_uvalues</A></H2>
671<PRE>
672        stmt:get_uvalues()</PRE>
673<P>This function returns a list with the values of all columns in the
674current result row of a query.</P>
675<P>
676<H2><A NAME="stmt:get_value">stmt:get_value</A></H2>
677<PRE>
678        stmt:get_value(n)</PRE>
679<P>Returns the value of column <CODE>n</CODE> in the result set of statement stmt. (The
680left-most column is number 0.)</P>
681<P>
682<H2><A NAME="stmt:get_values">stmt:get_values</A></H2>
683<PRE>
684        stmt:get_values()</PRE>
685<P>This function returns an array with the values of all columns in the
686result set returned by statement stmt.</P>
687<P>
688<H2><A NAME="stmt:isopen">stmt:isopen</A></H2>
689<PRE>
690        stmt:isopen()</PRE>
691<P>Returns true if stmt has not yet been finalized, false otherwise.</P>
692<P>
693<H2><A NAME="stmt:nrows">stmt:nrows</A></H2>
694<PRE>
695        stmt:nrows()</PRE>
696<P>Returns an function that iterates over the names and values of the
697result set of statement <CODE>stmt</CODE>. Each iteration returns a table with the
698names and values for the current row.
699This is the prepared statement equivalent of <A HREF="#db:nrows"><CODE>db:nrows()</CODE></A>.</P>
700<P>
701<H2><A NAME="stmt:reset">stmt:reset</A></H2>
702<PRE>
703        stmt:reset()</PRE>
704<P>This function resets SQL statement <CODE>stmt</CODE>, so that it is ready to be
705re-executed. Any statement variables that had values bound to them using
706the <CODE>stmt:bind*()</CODE> functions retain their values.</P>
707<P>
708<H2><A NAME="stmt:rows">stmt:rows</A></H2>
709<PRE>
710        stmt:rows()</PRE>
711<P>Returns an function that iterates over the values of the result set of
712statement stmt. Each iteration returns an array with the values for the
713current row.
714This is the prepared statement equivalent of <A HREF="#db:rows"><CODE>db:rows()</CODE></A>.</P>
715<P>
716<H2><A NAME="stmt:step">stmt:step</A></H2>
717<PRE>
718        stmt:step()</PRE>
719<P>This function must be called to evaluate the (next iteration of the)
720prepared statement stmt. It will return one of the following values:</P>
721<UL>
722<LI>
723<CODE>sqlite3.BUSY</CODE>: the engine was unable to acquire the locks needed. If the
724statement is a COMMIT or occurs outside of an explicit transaction, then
725you can retry the statement. If the statement is not a COMMIT and occurs
726within a explicit transaction then you should rollback the transaction
727before continuing.
728<P></P>
729<LI>
730<CODE>sqlite3.DONE</CODE>: the statement has finished executing successfully.
731<A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> should not be called again on this statement
732without first calling <A HREF="#stmt:reset"><CODE>stmt:reset()</CODE></A> to reset the virtual
733machine back to the initial state.
734<P></P>
735<LI>
736<CODE>sqlite3.ROW</CODE>: this is returned each time a new row of data is ready for
737processing by the caller. The values may be accessed using the column
738access functions. <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> can be called again to
739retrieve the next row of data.
740<P></P>
741<LI>
742<CODE>sqlite3.ERROR</CODE>: a run-time error (such as a constraint violation) has
743occurred. <A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> should not be called again. More
744information may be found by calling <A HREF="#db:errmsg"><CODE>db:errmsg()</CODE></A>. A more
745specific error
746code (can be obtained by calling <A HREF="#stmt:reset"><CODE>stmt:reset()</CODE></A>.
747<P></P>
748<LI>
749<CODE>sqlite3.MISUSE</CODE>: the function was called inappropriately, perhaps
750because the statement has already been finalized or a previous call to
751<A HREF="#stmt:step"><CODE>stmt:step()</CODE></A> has returned <CODE>sqlite3.ERROR</CODE> or
752<CODE>sqlite3.DONE</CODE>.
753<P></P></UL>
754<P>
755<H2><A NAME="stmt:urows">stmt:urows</A></H2>
756<PRE>
757        stmt:urows()</PRE>
758<P>Returns an function that iterates over the values of the result set of
759statement stmt. Each iteration returns the values for the current row.
760This is the prepared statement equivalent of <A HREF="#db:urows"><CODE>db:urows()</CODE></A>.</P>
761<P>
762<HR>
763<H1><A NAME="methods for callback contexts">Methods for callback contexts</A></H1>
764<P>A callback context is available as a parameter inside the callback
765functions <A HREF="#db:create_aggregate"><CODE>db:create_aggregate()</CODE></A> and
766<A HREF="#db:create_function"><CODE>db:create_function()</CODE></A>. It can be used
767to get further information about the state of a query.</P>
768<P>
769<H2><A NAME="context:aggregate_count">context:aggregate_count</A></H2>
770<PRE>
771        context:aggregate_count()</PRE>
772<P>Returns the number of calls to the aggregate step function.</P>
773<P>
774<H2><A NAME="context:get_aggregate_data">context:get_aggregate_data</A></H2>
775<PRE>
776        context:get_aggregate_data()</PRE>
777<P>Returns the user-definable data field for callback funtions.</P>
778<P>
779<H2><A NAME="context:set_aggregate_data">context:set_aggregate_data</A></H2>
780<PRE>
781        context:set_aggregate_data(udata)</PRE>
782<P>Set the user-definable data field for callback funtions to <CODE>udata</CODE>.</P>
783<P>
784<H2><A NAME="context:result">context:result</A></H2>
785<PRE>
786        context:result(res)</PRE>
787<P>This function sets the result of a callback function to res. The type of
788the result depends on the type of res and is either a number or a string
789or nil. All other values will raise an error message.</P>
790<P>
791<H2><A NAME="context:result_null">context:result_null</A></H2>
792<PRE>
793        context:result_null()</PRE>
794<P>This function sets the result of a callback function to nil. It returns
795nothing.</P>
796<P>
797<H2><A NAME="context:result_number">context:result_number</A></H2>
798<PRE>
799        context:result_number(number)
800        context:result_double(number)</PRE>
801<P>This function sets the result of a callback function to the value
802<CODE>number</CODE>. It returns nothing.</P>
803<P>
804<H2><A NAME="context:result_int">context:result_int</A></H2>
805<PRE>
806        context:result_int(number)</PRE>
807<P>This function sets the result of a callback function to the integer
808value in <CODE>number</CODE>. It returns nothing.</P>
809<P>
810<H2><A NAME="context:result_text">context:result_text</A></H2>
811<PRE>
812        context:result_text(str)</PRE>
813<P>This function sets the result of a callback function to the string in
814<CODE>str</CODE>. It returns nothing.</P>
815<P>
816<H2><A NAME="context:result_blob">context:result_blob</A></H2>
817<PRE>
818        context:result_blob(blob)</PRE>
819<P>This function sets the result of a callback function to the binary
820string in <CODE>blob</CODE>. It returns nothing.</P>
821<P>
822<H2><A NAME="context:result_error">context:result_error</A></H2>
823<PRE>
824        context:result_error(err)</PRE>
825<P>This function sets the result of a callback function to the error value
826in <CODE>err</CODE>. It returns nothing.</P>
827<P>
828<H2><A NAME="context:user_data">context:user_data</A></H2>
829<PRE>
830        context:user_data()</PRE>
831<P>Returns the userdata parameter given in the call to install the callback
832function (see <A HREF="#db:create_aggregate"><CODE>db:create_aggregate()</CODE></A> and
833<A HREF="#db:create_function"><CODE>db:create_function()</CODE></A> for details).</P>
834<P>
835<HR>
836<H1><A NAME="numerical error and result codes">Numerical error and result codes</A></H1>
837<P>The following constants are defined by module sqlite3:</P>
838<PRE>
839        OK: 0          ERROR: 1       INTERNAL: 2    PERM: 3        ABORT: 4
840        BUSY: 5        LOCKED: 6      NOMEM: 7       READONLY: 8    INTERRUPT: 9
841        IOERR: 10      CORRUPT: 11    NOTFOUND: 12   FULL: 13       CANTOPEN: 14
842        PROTOCOL: 15   EMPTY: 16      SCHEMA: 17     TOOBIG: 18     CONSTRAINT: 19
843        MISMATCH: 20   MISUSE: 21     NOLFS: 22      FORMAT: 24     RANGE: 25
844        NOTADB: 26     ROW: 100       DONE: 101</PRE>
845<P>For details about their exact meaning please see the <STRONG>SQLite3
846documentation</STRONG> <A HREF="http://www.sqlite.org/">http://www.sqlite.org/</A>.</P>
847<P>
848<HR>
849<H1><A NAME="version">VERSION</A></H1>
850<P>This is <CODE>lsqlite3</CODE> subversion 6, also known as ``devel-0.6''.</P>
851<P>
852<HR>
853<H1><A NAME="credits">CREDITS</A></H1>
854<P><CODE>lsqlite3</CODE> was developed by Tiago Dionizio and Doug Currie with
855contributions from Thomas Lauer and Michael Roth.</P>
856<P>This documentation is based on the ``(very) preliminary'' documents
857for the Idle-SQLite3 database module. Thanks to Thomas Lauer for
858making it available.</P>
859<P>
860<HR>
861<H1><A NAME="license">LICENSE</A></H1>
862<PRE>
863    /************************************************************************
864    * lsqlite3                                                              *
865    * Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie                   *
866    * All rights reserved.                                                  *
867    * Author    : Tiago Dionizio &lt;tiago.dionizio@ist.utl.pt&gt;                *
868    * Author    : Doug Currie &lt;doug.currie@alum.mit.edu&gt;                    *
869    * Library   : lsqlite3 - a SQLite 3 database binding for Lua 5          *
870    *                                                                       *
871    * Permission is hereby granted, free of charge, to any person obtaining *
872    * a copy of this software and associated documentation files (the       *
873    * &quot;Software&quot;), to deal in the Software without restriction, including   *
874    * without limitation the rights to use, copy, modify, merge, publish,   *
875    * distribute, sublicense, and/or sell copies of the Software, and to    *
876    * permit persons to whom the Software is furnished to do so, subject to *
877    * the following conditions:                                             *
878    *                                                                       *
879    * The above copyright notice and this permission notice shall be        *
880    * included in all copies or substantial portions of the Software.       *
881    *                                                                       *
882    * THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND,       *
883    * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
884    * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
885    * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *
886    * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *
887    * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *
888    * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *
889    ************************************************************************/</PRE>
890
891</BODY>
892
893</HTML>
trunk/3rdparty/lsqlite3/doc/lsqlite3.pod
r0r242834
1=pod
2
3=head1 NAME
4
5B<LuaSQLite 3> - a Lua 5.1 wrapper for the SQLite3 library
6
7=head1 OVERVIEW
8
9B<LuaSQLite 3> is a thin wrapper around the public domain SQLite3
10database engine.
11
12The C<lsqlite3> module supports the creation and manipulation of
13SQLite3 databases. After a C<require('lsqlite3')> the exported
14functions are called with prefix C<sqlite3>. However, most sqlite3
15functions are called via an object-oriented interface to either
16database or SQL statement objects; see below for details.
17
18This documentation does not attempt to describe how SQLite3 itself
19works, it just describes the Lua binding and the available functions.
20For more information about the SQL features supported by SQLite3 and
21details about the syntax of SQL statements and queries, please see the
22B<SQLite3 documentation> L<http://www.sqlite.org/>. Using some of the
23advanced features (how to use callbacks, for instance) will require
24some familiarity with the SQLite3 API.
25
26=head1 DOWNLOAD
27
28B<LuaSQLite 3> source code can be downloaded from its
29LuaForge (L<http://luaforge.net/projects/luasqlite/>) page.
30
31You will also need to build or obtain an SQLite3 loadable library
32(DLL or .so). See L<http://www.sqlite.org/> for obtaining SQLite3
33source code or downloading a binary SQLite3 library.
34
35=head1 INSTALLATION
36
37A I<Makefile> is provided; it assumes an SQLite3 library is already
38installed.
39
40=head1 EXAMPLES
41
42The distribution contains an I<examples> directory. The unit tests
43also show some example use.
44
45=head1 VERIFICATION TESTS
46
47The distribution contains some units tests using Michael Roth's
48C<lunit> (which is also included). Some of the tests were also derived
49from Michael's B<lua-sqlite3> module, and more unit tests added by
50Doug Currie.
51
52The distribution also contains some functional tests by Tiago.
53
54This version of C<lsqlite3> was tested with SQLite 3.4.2.
55
56=head1 REFERENCE
57
58=head1 SQLite3 functions
59
60=head2 sqlite3.complete
61
62   sqlite3.complete(sql)
63
64Returns true if the string C<sql> comprises one or more complete SQL
65statements and false otherwise.
66
67=head2 sqlite3.open
68
69   sqlite3.open(filename)
70
71Opens (or creates if it does not exist) an SQLite database with name
72C<filename> and returns its handle as userdata (the returned object
73should be used for all further method calls in connection with this
74specific database, see L</Database methods>). Example:
75
76   myDB=sqlite3.open('MyDatabase.sqlite3')  -- open
77   -- do some database calls...
78   myDB:close()  -- close
79
80In case of an error, the function returns nil, an error code and an
81error message.
82
83=head2 sqlite3.open_memory
84
85   sqlite3.open_memory()
86
87Opens an SQLite database B<in memory> and returns its handle as
88userdata. In case of an error, the function returns nil, an error code
89and an error message. (In-memory databases are volatile as they are
90never stored on disk.)
91
92=head2 sqlite3.temp_directory
93
94   sqlite3.temp_directory([temp])
95
96Sets or queries the directory used by SQLite for temporary files. If
97string C<temp> is a directory name or nil, the temporary directory is
98set accordingly and the old value is returned. If C<temp> is missing,
99the function simply returns the current temporary directory.
100
101=head2 sqlite3.version
102
103   sqlite3.version()
104
105Returns a string with SQLite version information, in the form 'x.y[.z]'.
106
107=head1 Database methods
108
109After opening a database with L<C<sqlite3.open()>|/sqlite3.open> or
110L<C<sqlite3.open_memory()>|/sqlite3.open_memory>
111the returned database object should be used for all further method calls
112in connection with that database. An open database object supports the
113following methods.
114
115=head2 db:busy_handler
116
117   db:busy_handler([func[,udata]])
118
119Sets or removes a busy handler for a database. C<func> is either a Lua
120function that implements the busy handler or nil to remove a previously
121set handler. This function returns nothing.
122
123The handler function is called with two parameters: C<udata> and the
124number of (re-)tries for a pending transaction. It should return nil,
125false or 0 if the transaction is to be aborted. All other values will
126result in another attempt to perform the transaction. (See the SQLite
127documentation for important hints about writing busy handlers.)
128
129=head2 db:busy_timeout
130
131   db:busy_timeout(t)
132
133Sets a busy handler that waits for C<t> milliseconds if a transaction
134cannot proceed. Calling this function will remove any busy handler set
135by L<C<db:busy_handler()>|/db:busy_handler>; calling it with an argument
136less than or equal to 0 will turn off all busy handlers.
137
138=head2 db:changes
139
140   db:changes()
141
142This function returns the number of database rows that were changed (or
143inserted or deleted) by the most recent SQL statement. Only changes that
144are directly specified by INSERT, UPDATE, or DELETE statements are
145counted. Auxiliary changes caused by triggers are not counted. Use
146L<C<db:total_changes()>|/db:total_changes> to find the total number of
147changes.
148
149=head2 db:close
150
151   db:close()
152
153Closes a database. All SQL statements prepared using
154L<C<db:prepare()>|/db:prepare> should
155have been finalized before this function is called. The function returns
156C<sqlite3.OK> on success or else a numerical error code (see the list of
157L</Numerical error and result codes>).
158
159=head2 db:close_vm
160
161   db:close_vm(temponly)
162
163Finalizes all statements that have not been explicitly finalized. If
164C<temponly> is true, only internal, temporary statements are finalized.
165This function returns nothing.
166
167=head2 db:create_aggregate
168
169   db:create_aggregate(name,nargs,step,final)
170
171This function creates an aggregate callback function. Aggregates perform
172an operation over all rows in a query. C<name> is a string with the name
173of the aggregate function as given in an SQL statement; C<nargs> is the
174number of arguments this call will provide. C<step> is the actual Lua
175function that gets called once for every row; it should accept a function
176context (see L</Methods for callback contexts>) plus the same number of
177parameters as given in C<nargs>. C<final> is a function that is called
178once after all rows have been processed; it receives one argument, the
179function context.
180
181The function context can be used inside the two callback functions to
182communicate with SQLite3. Here is a simple example:
183
184   db:exec[=[
185     CREATE TABLE numbers(num1,num2);
186     INSERT INTO numbers VALUES(1,11);
187     INSERT INTO numbers VALUES(2,22);
188     INSERT INTO numbers VALUES(3,33);
189   ]=]
190   local num_sum=0
191   local function oneRow(context,num)  -- add one column in all rows
192     num_sum=num_sum+num
193   end
194   local function afterLast(context)   -- return sum after last row has been processed
195     context:result_number(num_sum)
196     num_sum=0
197   end
198   db:create_aggregate("do_the_sums",1,oneRow,afterLast)
199   for sum in db:urows('SELECT do_the_sums(num1) FROM numbers') do print("Sum of col 1:",sum) end
200   for sum in db:urows('SELECT do_the_sums(num2) FROM numbers') do print("Sum of col 2:",sum) end
201
202This prints:
203
204   Sum of col 1:   6
205   Sum of col 2:   66
206
207=head2 db:create_collation
208
209   db:create_collation(name,func)
210
211This creates a collation callback. A collation callback is used to
212establish a collation order, mostly for string comparisons and sorting
213purposes. C<name> is a string with the name of the collation to be created;
214C<func> is a function that accepts two string arguments, compares them
215and returns 0 if both strings are identical, -1 if the first argument is
216lower in the collation order than the second and 1 if the first argument
217is higher in the collation order than the second. A simple example:
218
219   local function collate(s1,s2)
220     s1=s1:lower()
221     s2=s2:lower()
222     if s1==s2 then return 0
223     elseif s1<s2 then return -1
224     else return 1 end
225   end
226   db:exec[=[
227     CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS);
228     INSERT INTO test VALUES(NULL,'hello world');
229     INSERT INTO test VALUES(NULL,'Buenos dias');
230     INSERT INTO test VALUES(NULL,'HELLO WORLD');
231   ]=]
232   db:create_collation('CINSENS',collate)
233   for row in db:nrows('SELECT * FROM test') do print(row.id,row.content) end
234
235=head2 db:create_function
236
237   db:create_function(name,nargs,func)
238
239This function creates a callback function. Callback function are called
240by SQLite3 once for every row in a query. C<name> is a string with the
241name of the callback function as given in an SQL statement; C<nargs> is
242the number of arguments this call will provide. C<func> is the actual Lua
243function that gets called once for every row; it should accept a
244function context (see L</Methods for callback contexts>) plus the same
245number of parameters as given in nargs. Here is an example:
246
247   db:exec'CREATE TABLE test(col1,col2,col3)'
248   db:exec'INSERT INTO test VALUES(1,2,4)'
249   db:exec'INSERT INTO test VALUES(2,4,9)'
250   db:exec'INSERT INTO test VALUES(3,6,16)'
251   db:create_function('sum_cols',3,function(ctx,a,b,c)
252     ctx:result_number(a+b+c)
253   end))
254   for col1,col2,col3,sum in db:urows('SELECT *,sum_cols(col1,col2,col3) FROM test') do
255     util.printf('%2i+%2i+%2i=%2i\n',col1,col2,col3,sum)
256   end
257
258=head2 db:errcode
259
260   db:errcode()
261   db:error_code()
262
263Returns the numerical result code (or extended result code) for the most
264recent failed call associated with database db. See
265L</Numerical error and result codes> for details.
266
267=head2 db:errmsg
268
269   db:errmsg()
270   db:error_message()
271
272Returns a string that contains an error message for the most recent
273failed call associated with database db.
274
275=head2 db:exec
276
277   db:exec(sql[,func[,udata]])
278   db:execute(sql[,func[,udata]])
279
280Compiles and executes the SQL statement(s) given in string C<sql>. The
281statements are simply executed one after the other and not stored. The
282function returns C<sqlite3.OK> on success or else a numerical error code
283(see L</Numerical error and result codes>).
284
285If one or more of the SQL statements are queries, then the callback
286function specified in C<func> is invoked once for each row of the query
287result (if C<func> is nil, no callback is invoked). The callback receives
288four arguments: C<udata> (the third parameter of the C<db:exec()> call),
289the number of columns in the row, a table with the column values and
290another table with the column names. The callback function should return
2910. If the callback returns a non-zero value then the query is aborted,
292all subsequent SQL statements are skipped and C<db:exec()> returns
293C<sqlite3.ABORT>. Here is a simple example:
294
295   sql=[=[
296     CREATE TABLE numbers(num1,num2,str);
297     INSERT INTO numbers VALUES(1,11,"ABC");
298     INSERT INTO numbers VALUES(2,22,"DEF");
299     INSERT INTO numbers VALUES(3,33,"UVW");
300     INSERT INTO numbers VALUES(4,44,"XYZ");
301     SELECT * FROM numbers;
302   ]=]
303   function showrow(udata,cols,values,names)
304     assert(udata=='test_udata')
305     print('exec:')
306     for i=1,cols do print('',names[i],values[i]) end
307     return 0
308   end
309   db:exec(sql,showrow,'test_udata')
310
311=head2 db:interrupt
312
313   db:interrupt()
314
315This function causes any pending database operation to abort and return
316at the next opportunity. This function returns nothing.
317
318=head2 db:isopen
319
320   db:isopen()
321
322Returns true if database db is open, false otherwise.
323
324=head2 db:last_insert_rowid
325
326   db:last_insert_rowid()
327
328This function returns the rowid of the most recent INSERT into the
329database. If no inserts have ever occurred, 0 is returned. (Each row in
330an SQLite table has a unique 64-bit signed integer key called the
331'rowid'. This id is always available as an undeclared column named
332ROWID, OID, or _ROWID_. If the table has a column of type INTEGER
333PRIMARY KEY then that column is another alias for the rowid.)
334
335If an INSERT occurs within a trigger, then the rowid of the inserted row
336is returned as long as the trigger is running. Once the trigger
337terminates, the value returned reverts to the last value inserted before
338the trigger fired.
339
340=head2 db:nrows
341
342   db:nrows(sql)
343
344Creates an iterator that returns the successive rows selected by the SQL
345statement given in string C<sql>. Each call to the iterator returns a
346table in which the named fields correspond to the columns in the database.
347Here is an example:
348
349   db:exec[=[
350     CREATE TABLE numbers(num1,num2);
351     INSERT INTO numbers VALUES(1,11);
352     INSERT INTO numbers VALUES(2,22);
353     INSERT INTO numbers VALUES(3,33);
354   ]=]
355   for a in db:nrows('SELECT * FROM numbers') do table.print(a) end
356
357This script prints:
358
359   num2: 11
360   num1: 1
361   num2: 22
362   num1: 2
363   num2: 33
364   num1: 3
365
366=head2 db:prepare
367
368   db:prepare(sql)
369
370This function compiles the SQL statement in string C<sql> into an internal
371representation and returns this as userdata. The returned object should
372be used for all further method calls in connection with this specific
373SQL statement (see L</Methods for prepared statements>).
374
375=head2 db:progress_handler
376
377   db:progress_handler(n,func,udata)
378
379This function installs a callback function C<func> that is invoked
380periodically during long-running calls to L<C<db:exec()>|/db:exec>
381or L<C<stmt:step()>|/stmt:step>. The
382progress callback is invoked once for every C<n> internal operations,
383where C<n> is the first argument to this function. C<udata> is passed to
384the progress callback function each time it is invoked. If a call to
385C<db:exec()> or C<stmt:step()> results in fewer than C<n> operations
386being executed, then the progress callback is never invoked. Only a
387single progress callback function may be registered for each opened
388database and a call to this function will overwrite any previously set
389callback function. To remove the progress callback altogether, pass nil
390as the second argument.
391
392If the progress callback returns a result other than 0, then the current
393query is immediately terminated, any database changes are rolled back
394and the containing C<db:exec()> or C<stmt:step()> call returns
395C<sqlite3.INTERRUPT>. This feature can be used to cancel long-running
396queries.
397
398=head2 db:rows
399
400   db:rows(sql)
401
402Creates an iterator that returns the successive rows selected by the SQL
403statement given in string C<sql>. Each call to the iterator returns a table
404in which the numerical indices 1 to n correspond to the selected columns
4051 to n in the database. Here is an example:
406
407   db:exec[=[
408     CREATE TABLE numbers(num1,num2);
409     INSERT INTO numbers VALUES(1,11);
410     INSERT INTO numbers VALUES(2,22);
411     INSERT INTO numbers VALUES(3,33);
412   ]=]
413   for a in db:rows('SELECT * FROM numbers') do table.print(a) end
414
415This script prints:
416
417   1: 1
418   2: 11
419   1: 2
420   2: 22
421   1: 3
422   2: 33
423
424=head2 db:total_changes
425
426   db:total_changes()
427
428This function returns the number of database rows that have been
429modified by INSERT, UPDATE or DELETE statements since the database was
430opened. This includes UPDATE, INSERT and DELETE statements executed as
431part of trigger programs. All changes are counted as soon as the
432statement that produces them is completed by calling either
433L<C<stmt:reset()>|/stmt:reset> or L<C<stmt:finalize()>|/stmt:finalize>.
434
435=head2 db:trace
436
437   db:trace(func,udata)
438
439This function installs a trace callback handler. C<func> is a Lua
440function that is called by SQLite3 just before the evaluation of an SQL
441statement. This callback receives two arguments: the first is the
442C<udata> argument used when the callback was installed; the second is a
443string with the SQL statement about to be executed.
444
445=head2 db:urows
446
447   db:urows(sql)
448
449Creates an iterator that returns the successive rows selected by the SQL
450statement given in string C<sql>. Each call to the iterator returns the
451values that correspond to the columns in the currently selected row.
452Here is an example:
453
454   db:exec[=[
455     CREATE TABLE numbers(num1,num2);
456     INSERT INTO numbers VALUES(1,11);
457     INSERT INTO numbers VALUES(2,22);
458     INSERT INTO numbers VALUES(3,33);
459   ]=]
460   for num1,num2 in db:urows('SELECT * FROM numbers') do print(num1,num2) end
461
462This script prints:
463
464   1       11
465   2       22
466   3       33
467
468=head1 Methods for prepared statements
469
470After creating a prepared statement with L<C<db:prepare()>|/db:prepare>
471the returned statement object should be used for all further calls in
472connection with that statement. Statement objects support the following
473methods.
474
475=head2 stmt:bind
476
477   stmt:bind(n[,value])
478
479Binds value to statement parameter C<n>. If the type of value is string
480or number, it is bound as text or double, respectively. If C<value> is a
481boolean or nil or missing, any previous binding is removed. The function
482returns C<sqlite3.OK> on success or else a numerical error code (see
483L</Numerical error and result codes>).
484
485=head2 stmt:bind_blob
486
487   stmt:bind_blob(n,blob)
488
489Binds string C<blob> (which can be a binary string) as a blob to
490statement parameter C<n>. The function returns C<sqlite3.OK> on success
491or else a numerical error code (see L</Numerical error and result codes>).
492
493=head2 stmt:bind_names
494
495   stmt:bind_names(nametable)
496
497Binds the values in C<nametable> to statement parameters. If the
498statement parameters are named (i.e., of the form ":AAA" or "$AAA")
499then this function looks for appropriately named fields in C<nametable>;
500if the statement parameters are
501not named, it looks for numerical fields 1 to the number of statement
502parameters. The function returns C<sqlite3.OK> on success or else a
503numerical error code (see L</Numerical error and result codes>).
504
505=head2 stmt:bind_parameter_count
506
507   stmt:bind_parameter_count()
508
509Returns the largest statement parameter index in prepared statement
510C<stmt>. When the statement parameters are of the forms ":AAA" or "?",
511then they are assigned sequentially increasing numbers beginning with
512one, so the value returned is the number of parameters. However if the
513same statement parameter name is used multiple times, each occurrence
514is given the same number, so the value returned is the number of unique
515statement parameter names.
516
517If statement parameters of the form "?NNN" are used (where NNN is an
518integer) then there might be gaps in the numbering and the value
519returned by this interface is the index of the statement parameter with
520the largest index value.
521
522=head2 stmt:bind_parameter_name
523
524   stmt:bind_parameter_name(n)
525
526Returns the name of the C<n>-th parameter in prepared statement C<stmt>.
527Statement parameters of the form ":AAA" or "@AAA" or "$VVV" have a name
528which  is the string ":AAA" or "@AAA" or "$VVV". In other words, the
529initial ":" or "$" or "@" is included as part of the name. Parameters
530of the form "?" or "?NNN" have no name. The first bound parameter has
531an index of 1.
532If the value C<n> is out of range or if the C<n>-th parameter is
533nameless, then nil is returned. The function returns C<sqlite3.OK> on
534success or else a numerical error code (see
535L</Numerical error and result codes>)
536
537=head2 stmt:bind_values
538
539   stmt:bind_values(value1,value2,...,valueN)
540
541Binds the given values to statement parameters. The function returns
542C<sqlite3.OK> on success or else a numerical error code (see
543L</Numerical error and result codes>).
544
545=head2 stmt:columns
546
547   stmt:columns()
548
549Returns the number of columns in the result set returned by statement
550stmt or 0 if the statement does not return data (for example an UPDATE).
551
552=head2 stmt:finalize
553
554   stmt:finalize()
555
556This function frees prepared statement stmt. If the statement was
557executed successfully, or not executed at all, then C<sqlite3.OK> is
558returned. If execution of the statement failed then an error code is
559returned.
560
561=head2 stmt:get_name
562
563   stmt:get_name(n)
564
565Returns the name of column C<n> in the result set of statement stmt. (The
566left-most column is number 0.)
567
568=head2 stmt:get_named_types
569
570   stmt:get_named_types()
571
572Returns a table with the names and types of all columns in the result
573set of statement stmt.
574
575=head2 stmt:get_named_values
576
577   stmt:get_named_values()
578
579This function returns a table with names and values of all columns in
580the current result row of a query.
581
582=head2 stmt:get_names
583
584   stmt:get_names()
585
586This function returns an array with the names of all columns in the
587result set returned by statement stmt.
588
589=head2 stmt:get_type
590
591   stmt:get_type(n)
592
593Returns the type of column C<n> in the result set of statement stmt. (The
594left-most column is number 0.)
595
596=head2 stmt:get_types
597
598   stmt:get_types()
599
600This function returns an array with the types of all columns in the
601result set returned by statement stmt.
602
603=head2 stmt:get_unames
604
605   stmt:get_unames()
606
607This function returns a list with the names of all columns in the result
608set returned by statement stmt.
609
610=head2 stmt:get_utypes
611
612   stmt:get_utypes()
613
614This function returns a list with the types of all columns in the result
615set returned by statement stmt.
616
617=head2 stmt:get_uvalues
618
619   stmt:get_uvalues()
620
621This function returns a list with the values of all columns in the
622current result row of a query.
623
624=head2 stmt:get_value
625
626   stmt:get_value(n)
627
628Returns the value of column C<n> in the result set of statement stmt. (The
629left-most column is number 0.)
630
631=head2 stmt:get_values
632
633   stmt:get_values()
634
635This function returns an array with the values of all columns in the
636result set returned by statement stmt.
637
638=head2 stmt:isopen
639
640   stmt:isopen()
641
642Returns true if stmt has not yet been finalized, false otherwise.
643
644=head2 stmt:nrows
645
646   stmt:nrows()
647
648Returns an function that iterates over the names and values of the
649result set of statement C<stmt>. Each iteration returns a table with the
650names and values for the current row.
651This is the prepared statement equivalent of L<C<db:nrows()>|/db:nrows>.
652
653=head2 stmt:reset
654
655   stmt:reset()
656
657This function resets SQL statement C<stmt>, so that it is ready to be
658re-executed. Any statement variables that had values bound to them using
659the C<stmt:bind*()> functions retain their values.
660
661=head2 stmt:rows
662
663   stmt:rows()
664
665Returns an function that iterates over the values of the result set of
666statement stmt. Each iteration returns an array with the values for the
667current row.
668This is the prepared statement equivalent of L<C<db:rows()>|/db:rows>.
669
670=head2 stmt:step
671
672   stmt:step()
673
674This function must be called to evaluate the (next iteration of the)
675prepared statement stmt. It will return one of the following values:
676
677=over 4
678
679=item *
680
681C<sqlite3.BUSY>: the engine was unable to acquire the locks needed. If the
682statement is a COMMIT or occurs outside of an explicit transaction, then
683you can retry the statement. If the statement is not a COMMIT and occurs
684within a explicit transaction then you should rollback the transaction
685before continuing.
686
687=item *
688
689C<sqlite3.DONE>: the statement has finished executing successfully.
690L<C<stmt:step()>|/stmt:step> should not be called again on this statement
691without first calling L<C<stmt:reset()>|/stmt:reset> to reset the virtual
692machine back to the initial state.
693
694=item *
695
696C<sqlite3.ROW>: this is returned each time a new row of data is ready for
697processing by the caller. The values may be accessed using the column
698access functions. L<C<stmt:step()>|/stmt:step> can be called again to
699retrieve the next row of data.
700
701=item *
702
703C<sqlite3.ERROR>: a run-time error (such as a constraint violation) has
704occurred. L<C<stmt:step()>|/stmt:step> should not be called again. More
705information may be found by calling L<C<db:errmsg()>|/db:errmsg>. A more
706specific error
707code (can be obtained by calling L<C<stmt:reset()>|/stmt:reset>.
708
709=item *
710
711C<sqlite3.MISUSE>: the function was called inappropriately, perhaps
712because the statement has already been finalized or a previous call to
713L<C<stmt:step()>|/stmt:step> has returned C<sqlite3.ERROR> or
714C<sqlite3.DONE>.
715
716=back
717
718=head2 stmt:urows
719
720   stmt:urows()
721
722Returns an function that iterates over the values of the result set of
723statement stmt. Each iteration returns the values for the current row.
724This is the prepared statement equivalent of L<C<db:urows()>|/db:urows>.
725
726=head1 Methods for callback contexts
727
728A callback context is available as a parameter inside the callback
729functions L<C<db:create_aggregate()>|/db:create_aggregate> and
730L<C<db:create_function()>|/db:create_function>. It can be used
731to get further information about the state of a query.
732
733=head2 context:aggregate_count
734
735   context:aggregate_count()
736
737Returns the number of calls to the aggregate step function.
738
739=head2 context:get_aggregate_data
740
741   context:get_aggregate_data()
742
743Returns the user-definable data field for callback funtions.
744
745=head2 context:set_aggregate_data
746
747   context:set_aggregate_data(udata)
748
749Set the user-definable data field for callback funtions to C<udata>.
750
751=head2 context:result
752
753   context:result(res)
754
755This function sets the result of a callback function to res. The type of
756the result depends on the type of res and is either a number or a string
757or nil. All other values will raise an error message.
758
759=head2 context:result_null
760
761   context:result_null()
762
763This function sets the result of a callback function to nil. It returns
764nothing.
765
766=head2 context:result_number
767
768   context:result_number(number)
769   context:result_double(number)
770
771This function sets the result of a callback function to the value
772C<number>. It returns nothing.
773
774=head2 context:result_int
775
776   context:result_int(number)
777
778This function sets the result of a callback function to the integer
779value in C<number>. It returns nothing.
780
781=head2 context:result_text
782
783   context:result_text(str)
784
785This function sets the result of a callback function to the string in
786C<str>. It returns nothing.
787
788=head2 context:result_blob
789
790   context:result_blob(blob)
791
792This function sets the result of a callback function to the binary
793string in C<blob>. It returns nothing.
794
795=head2 context:result_error
796
797   context:result_error(err)
798
799This function sets the result of a callback function to the error value
800in C<err>. It returns nothing.
801
802=head2 context:user_data
803
804   context:user_data()
805
806Returns the userdata parameter given in the call to install the callback
807function (see L<C<db:create_aggregate()>|/db:create_aggregate> and
808L<C<db:create_function()>|/db:create_function> for details).
809
810=head1 Numerical error and result codes
811
812The following constants are defined by module sqlite3:
813
814   OK: 0          ERROR: 1       INTERNAL: 2    PERM: 3        ABORT: 4
815   BUSY: 5        LOCKED: 6      NOMEM: 7       READONLY: 8    INTERRUPT: 9
816   IOERR: 10      CORRUPT: 11    NOTFOUND: 12   FULL: 13       CANTOPEN: 14
817   PROTOCOL: 15   EMPTY: 16      SCHEMA: 17     TOOBIG: 18     CONSTRAINT: 19
818   MISMATCH: 20   MISUSE: 21     NOLFS: 22      FORMAT: 24     RANGE: 25
819   NOTADB: 26     ROW: 100       DONE: 101
820
821For details about their exact meaning please see the B<SQLite3
822documentation> L<http://www.sqlite.org/>.
823
824=head1 VERSION
825
826This is C<lsqlite3> subversion 6, also known as "devel-0.6".
827
828=head1 CREDITS
829
830C<lsqlite3> was developed by Tiago Dionizio and Doug Currie with
831contributions from Thomas Lauer and Michael Roth.
832
833This documentation is based on the "(very) preliminary" documents
834for the Idle-SQLite3 database module. Thanks to Thomas Lauer for
835making it available.
836
837=head1 LICENSE
838
839    /************************************************************************
840    * lsqlite3                                                              *
841    * Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie                   *
842    * All rights reserved.                                                  *
843    * Author    : Tiago Dionizio <tiago.dionizio@ist.utl.pt>                *
844    * Author    : Doug Currie <doug.currie@alum.mit.edu>                    *
845    * Library   : lsqlite3 - a SQLite 3 database binding for Lua 5          *
846    *                                                                       *
847    * Permission is hereby granted, free of charge, to any person obtaining *
848    * a copy of this software and associated documentation files (the       *
849    * "Software"), to deal in the Software without restriction, including   *
850    * without limitation the rights to use, copy, modify, merge, publish,   *
851    * distribute, sublicense, and/or sell copies of the Software, and to    *
852    * permit persons to whom the Software is furnished to do so, subject to *
853    * the following conditions:                                             *
854    *                                                                       *
855    * The above copyright notice and this permission notice shall be        *
856    * included in all copies or substantial portions of the Software.       *
857    *                                                                       *
858    * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       *
859    * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
860    * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
861    * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *
862    * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *
863    * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *
864    * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *
865    ************************************************************************/
866
trunk/3rdparty/lsqlite3/doc/pod2html.pl
r0r242834
1#!perl
2
3use Pod::Html;
4
5pod2html @ARGV;
6
7__END__
trunk/3rdparty/lsqlite3/examples/aggregate.lua
r0r242834
1
2require("lsqlite3")
3
4local db = sqlite3.open_memory()
5
6assert( db:exec "CREATE TABLE test (col1, col2)" )
7assert( db:exec "INSERT INTO test VALUES (1, 2)" )
8assert( db:exec "INSERT INTO test VALUES (2, 4)" )
9assert( db:exec "INSERT INTO test VALUES (3, 6)" )
10assert( db:exec "INSERT INTO test VALUES (4, 8)" )
11assert( db:exec "INSERT INTO test VALUES (5, 10)" )
12
13do
14
15  local square_error_sum = 0
16
17  local function step(ctx, a, b)
18    local error        = a - b
19    local square_error = error * error
20    square_error_sum   = square_error_sum + square_error
21  end
22
23  local function final(ctx)
24    ctx:result_number( square_error_sum / ctx:aggregate_count() )
25  end
26
27  assert( db:create_aggregate("my_stats", 2, step, final) )
28
29end
30
31--for a,b in db:urows("SELECT col1, col2 FROM test")
32--do print("a b: ", a, b) end
33
34for my_stats in db:urows("SELECT my_stats(col1, col2) FROM test")
35do print("my_stats:", my_stats) end
trunk/3rdparty/lsqlite3/examples/function.lua
r0r242834
1
2require("lsqlite3")
3
4
5local db = sqlite3.open_memory()
6
7assert( db:exec "CREATE TABLE test (col1, col2)" )
8assert( db:exec "INSERT INTO test VALUES (1, 2)" )
9assert( db:exec "INSERT INTO test VALUES (2, 4)" )
10assert( db:exec "INSERT INTO test VALUES (3, 6)" )
11assert( db:exec "INSERT INTO test VALUES (4, 8)" )
12assert( db:exec "INSERT INTO test VALUES (5, 10)" )
13
14assert( db:create_function("my_sum", 2, function(ctx, a, b)
15  ctx:result_number( a + b )
16end))
17
18
19for col1, col2, sum in db:urows("SELECT *, my_sum(col1, col2) FROM test") do
20  print(col1, col2, sum)
21end
trunk/3rdparty/lsqlite3/examples/order.lua
r0r242834
1
2require("lsqlite3")
3
4local db = assert( sqlite3:open_memory() )
5
6assert( db:exec[[
7
8  CREATE TABLE customer (
9    id      INTEGER PRIMARY KEY,
10    name   VARCHAR(40)
11  );
12
13  CREATE TABLE invoice (
14    id      INTEGER PRIMARY KEY,
15    customer   INTEGER NOT NULL,
16    title   VARCHAR(80) NOT NULL,
17    article1   VARCHAR(40) NOT NULL,
18    price1   REAL NOT NULL,
19    article2   VARCHAR(40),
20    price2   REAL
21  );
22
23  CREATE TABLE invoice_overflow (
24    id      INTEGER PRIMARY KEY,
25    invoice   INTEGER NOT NULL,
26    article   VARCHAR(40) NOT NULL,
27    price   REAL NOT NULL
28  );
29
30  INSERT INTO customer VALUES(
31    1, "Michael" );
32
33  INSERT INTO invoice VALUES(
34    1, 1, "Computer parts", "harddisc", 89.90, "floppy", 9.99 );
35
36  INSERT INTO customer VALUES(
37    2, "John" );
38
39  INSERT INTO invoice VALUES(
40    2, 2, "Somme food", "apples", 2.79, "pears", 5.99 );
41
42  INSERT INTO invoice_overflow VALUES(
43    NULL, 2, "grapes", 6.34 );
44
45  INSERT INTO invoice_overflow VALUES(
46    NULL, 2, "strawberries", 4.12 );
47
48  INSERT INTO invoice_overflow VALUES(
49    NULL, 2, "tomatoes", 6.17 );
50
51  INSERT INTO invoice VALUES(
52    3, 2, "A new car", "Cybercar XL-1000", 65000.00, NULL, NULL );
53
54]] )
55
56
57local function customer_name(id)
58  local stmt = db:prepare("SELECT name FROM customer WHERE id = ?")
59  stmt:bind_values(id)
60  stmt:step()
61  local r = stmt:get_uvalues()
62  stmt:finalize()
63  return r
64end
65
66
67local function all_invoices()
68  return db:nrows("SELECT id, customer, title FROM invoice")
69end
70
71
72local function all_articles(invoice)
73
74  local function iterator()
75    local stmt, row
76
77    -- Get the articles that are contained in the invoice table itself.
78    stmt = db:prepare("SELECT article1, price1, article2, price2 FROM invoice WHERE id = ?")
79    stmt:bind_values(invoice)
80    stmt:step()
81    row = stmt:get_named_values()
82
83    -- Every Invoice has at least one article.
84    coroutine.yield(row.article1, row.price1)
85
86    -- Maybe the Invoice has a second article?
87    if row.article2 then
88
89      -- Yes, there is a second article, so return it.
90      coroutine.yield(row.article2, row.price2)
91
92      -- When there was an second article, maybe there are even
93      -- more articles in the overflow table? We will see...
94
95      stmt = db:prepare("SELECT article, price FROM invoice_overflow WHERE invoice = ? ORDER BY id")
96      stmt:bind_values(invoice)
97     
98      for row in stmt:nrows() do
99        coroutine.yield(row.article, row.price)
100      end
101    end
102  end
103
104  return coroutine.wrap(iterator)
105end
106
107
108for invoice in all_invoices() do
109  local id    = invoice.id
110  local name  = customer_name(invoice.customer)
111  local title = invoice.title
112
113  print()
114  print("Invoice #"..id..", "..name..": '"..title.."'")
115  print("----------------------------------------")
116
117  for article, price in all_articles(id) do
118    print( string.format("%20s  %8.2f", article, price) )
119  end
120
121  print()
122end
trunk/3rdparty/lsqlite3/examples/simple.lua
r0r242834
1
2require("lsqlite3")
3
4local db = sqlite3.open_memory()
5
6db:exec[[
7  CREATE TABLE test (id INTEGER PRIMARY KEY, content);
8
9  INSERT INTO test VALUES (NULL, 'Hello World');
10  INSERT INTO test VALUES (NULL, 'Hello Lua');
11  INSERT INTO test VALUES (NULL, 'Hello Sqlite3')
12]]
13
14for row in db:nrows("SELECT * FROM test") do
15  print(row.id, row.content)
16end
trunk/3rdparty/lsqlite3/examples/smart.lua
r0r242834
1
2require("lsqlite3")
3
4local db = sqlite3.open_memory()
5
6db:exec[[ CREATE TABLE test (id INTEGER PRIMARY KEY, content) ]]
7
8local stmt = db:prepare[[ INSERT INTO test VALUES (:key, :value) ]]
9
10stmt:bind_names{  key = 1,  value = "Hello World"    }
11stmt:step()
12stmt:reset()
13stmt:bind_names{  key = 2,  value = "Hello Lua"      }
14stmt:step()
15stmt:reset()
16stmt:bind_names{  key = 3,  value = "Hello Sqlite3"  }
17stmt:step()
18stmt:finalize()
19
20for row in db:nrows("SELECT * FROM test") do
21  print(row.id, row.content)
22end
trunk/3rdparty/lsqlite3/examples/statement.lua
r0r242834
1
2require("lsqlite3")
3
4local db = sqlite3.open_memory()
5
6db:exec[[
7  CREATE TABLE test (
8    id        INTEGER PRIMARY KEY,
9    content   VARCHAR
10  );
11]]
12
13local insert_stmt = assert( db:prepare("INSERT INTO test VALUES (NULL, ?)") )
14
15local function insert(data)
16  insert_stmt:bind_values(data)
17  insert_stmt:step()
18  insert_stmt:reset()
19end
20
21local select_stmt = assert( db:prepare("SELECT * FROM test") )
22
23local function select()
24  for row in select_stmt:nrows() do
25    print(row.id, row.content)
26  end
27end
28
29insert("Hello World")
30print("First:")
31select()
32
33insert("Hello Lua")
34print("Second:")
35select()
36
37insert("Hello Sqlite3")
38print("Third:")
39select()
trunk/3rdparty/lsqlite3/examples/tracing.lua
r0r242834
1
2require("lsqlite3")
3
4local db = sqlite3.open_memory()
5
6db:trace( function(ud, sql)
7  print("Sqlite Trace:", sql)
8end )
9
10db:exec[[
11  CREATE TABLE test ( id INTEGER PRIMARY KEY, content VARCHAR );
12
13  INSERT INTO test VALUES (NULL, 'Hello World');
14  INSERT INTO test VALUES (NULL, 'Hello Lua');
15  INSERT INTO test VALUES (NULL, 'Hello Sqlite3');
16]]
17
18for row in db:rows("SELECT * FROM test") do
19  -- NOP
20end
trunk/3rdparty/lsqlite3/lsqlite3.c
r0r242834
1/************************************************************************
2* lsqlite3                                                              *
3* Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie                   *
4* All rights reserved.                                                  *
5* Author    : Tiago Dionizio <tiago.dionizio@ist.utl.pt>                *
6* Author    : Doug Currie <doug.currie@alum.mit.edu>                    *
7* Library   : lsqlite3 - a SQLite 3 database binding for Lua 5          *
8*                                                                       *
9* Permission is hereby granted, free of charge, to any person obtaining *
10* a copy of this software and associated documentation files (the       *
11* "Software"), to deal in the Software without restriction, including   *
12* without limitation the rights to use, copy, modify, merge, publish,   *
13* distribute, sublicense, and/or sell copies of the Software, and to    *
14* permit persons to whom the Software is furnished to do so, subject to *
15* the following conditions:                                             *
16*                                                                       *
17* The above copyright notice and this permission notice shall be        *
18* included in all copies or substantial portions of the Software.       *
19*                                                                       *
20* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       *
21* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
22* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
23* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *
24* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *
25* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *
26* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *
27************************************************************************/
28
29#include <stdlib.h>
30#include <string.h>
31#include <assert.h>
32
33#include "lua.h"
34#include "lauxlib.h"
35
36#include "sqlite3.h"
37
38/* compile time features */
39#if !defined(SQLITE_OMIT_PROGRESS_CALLBACK)
40    #define SQLITE_OMIT_PROGRESS_CALLBACK 0
41#endif
42
43typedef struct sdb sdb;
44typedef struct sdb_vm sdb_vm;
45typedef struct sdb_func sdb_func;
46
47/* to use as C user data so i know what function sqlite is calling */
48struct sdb_func {
49    /* references to associated lua values */
50    int fn_step;
51    int fn_finalize;
52    int udata;
53
54    sdb *db;
55    char aggregate;
56
57    sdb_func *next;
58};
59
60/* information about database */
61struct sdb {
62    /* associated lua state */
63    lua_State *L;
64    /* sqlite database handle */
65    sqlite3 *db;
66
67    /* sql functions stack usage */
68    sdb_func *func;         /* top SQL function being called */
69
70    /* references */
71    int busy_cb;        /* busy callback */
72    int busy_udata;
73
74    int progress_cb;    /* progress handler */
75    int progress_udata;
76
77    int trace_cb;       /* trace callback */
78    int trace_udata;
79};
80
81static const char *sqlite_meta      = ":sqlite3";
82static const char *sqlite_vm_meta   = ":sqlite3:vm";
83static const char *sqlite_ctx_meta  = ":sqlite3:ctx";
84static int sqlite_ctx_meta_ref;
85
86/*
87** =======================================================
88** Database Virtual Machine Operations
89** =======================================================
90*/
91
92static void vm_push_column(lua_State *L, sqlite3_stmt *vm, int idx) {
93    switch (sqlite3_column_type(vm, idx)) {
94        case SQLITE_INTEGER:
95            {
96                sqlite_int64 i64 = sqlite3_column_int64(vm, idx);
97                lua_Number n = (lua_Number)i64;
98                if (n == i64)
99                    lua_pushnumber(L, n);
100                else
101                    lua_pushlstring(L, sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
102            }
103            break;
104        case SQLITE_FLOAT:
105            lua_pushnumber(L, sqlite3_column_double(vm, idx));
106            break;
107        case SQLITE_TEXT:
108            lua_pushlstring(L, sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
109            break;
110        case SQLITE_BLOB:
111            lua_pushlstring(L, sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx));
112            break;
113        case SQLITE_NULL:
114            lua_pushnil(L);
115            break;
116        default:
117            lua_pushnil(L);
118            break;
119    }
120}
121
122/* virtual machine information */
123struct sdb_vm {
124    sdb *db;                /* associated database handle */
125    sqlite3_stmt *vm;       /* virtual machine */
126
127    /* sqlite3_step info */
128    int columns;            /* number of columns in result */
129    char has_values;        /* true when step succeeds */
130
131    char temp;              /* temporary vm used in db:rows */
132};
133
134/* called with sql text on the lua stack */
135static sdb_vm *newvm(lua_State *L, sdb *db) {
136    sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm));
137
138    luaL_getmetatable(L, sqlite_vm_meta);
139    lua_setmetatable(L, -2);        /* set metatable */
140
141    svm->db = db;
142    svm->columns = 0;
143    svm->has_values = 0;
144    svm->vm = NULL;
145    svm->temp = 0;
146
147    /* add an entry on the database table: svm -> sql text */
148    lua_pushlightuserdata(L, db);
149    lua_rawget(L, LUA_REGISTRYINDEX);
150    lua_pushlightuserdata(L, svm);
151    lua_pushvalue(L, -4); /* the sql text */
152    lua_rawset(L, -3);
153    lua_pop(L, 1);
154
155    return svm;
156}
157
158static int cleanupvm(lua_State *L, sdb_vm *svm) {
159    /* remove entry in database table - no harm if not present in the table */
160    lua_pushlightuserdata(L, svm->db);
161    lua_rawget(L, LUA_REGISTRYINDEX);
162    lua_pushlightuserdata(L, svm);
163    lua_pushnil(L);
164    lua_rawset(L, -3);
165    lua_pop(L, 1);
166
167    svm->columns = 0;
168    svm->has_values = 0;
169
170    if (!svm->vm) return 0;
171
172    lua_pushnumber(L, sqlite3_finalize(svm->vm));
173    svm->vm = NULL;
174    return 1;
175}
176
177static int stepvm(lua_State *L, sdb_vm *svm) {
178    int result;
179    int loop_limit = 3;
180    while ( loop_limit-- ) {
181        result = sqlite3_step(svm->vm);
182        if ( result==SQLITE_ERROR ) {
183          result = sqlite3_reset (svm->vm);
184        }
185        if ( result==SQLITE_SCHEMA ) {
186            sqlite3_stmt *vn;
187            const char *sql;
188            /* recover sql text */
189            lua_pushlightuserdata(L, svm->db);
190            lua_rawget(L, LUA_REGISTRYINDEX);
191            lua_pushlightuserdata(L, svm);
192            lua_rawget(L, -2); /* sql text */
193            sql = luaL_checkstring(L, -1);
194            /* re-prepare */
195            result = sqlite3_prepare(svm->db->db, sql, -1, &vn, NULL);
196            if (result != SQLITE_OK) break;
197            sqlite3_transfer_bindings(svm->vm, vn);
198            sqlite3_finalize(svm->vm);
199            svm->vm = vn;
200            lua_pop(L,2);
201        } else {
202          break;
203        }
204    }
205    return result;
206}
207
208static sdb_vm *lsqlite_getvm(lua_State *L, int index) {
209    sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta);
210    if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine");
211    return svm;
212}
213
214static sdb_vm *lsqlite_checkvm(lua_State *L, int index) {
215    sdb_vm *svm = lsqlite_getvm(L, index);
216    if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine");
217    return svm;
218}
219
220static int dbvm_isopen(lua_State *L) {
221    sdb_vm *svm = lsqlite_getvm(L, 1);
222    lua_pushboolean(L, svm->vm != NULL ? 1 : 0);
223    return 1;
224}
225
226static int dbvm_tostring(lua_State *L) {
227    char buff[39];
228    sdb_vm *svm = lsqlite_getvm(L, 1);
229    if (svm->vm == NULL)
230        strcpy(buff, "closed");
231    else
232        sprintf(buff, "%p", svm);
233    lua_pushfstring(L, "sqlite virtual machine (%s)", buff);
234    return 1;
235}
236
237static int dbvm_gc(lua_State *L) {
238    sdb_vm *svm = lsqlite_getvm(L, 1);
239    if (svm->vm != NULL)  /* ignore closed vms */
240        cleanupvm(L, svm);
241    return 0;
242}
243
244static int dbvm_step(lua_State *L) {
245    int result;
246    sdb_vm *svm = lsqlite_checkvm(L, 1);
247
248    result = stepvm(L, svm);
249    svm->has_values = result == SQLITE_ROW ? 1 : 0;
250    svm->columns = sqlite3_data_count(svm->vm);
251
252    lua_pushnumber(L, result);
253    return 1;
254}
255
256static int dbvm_finalize(lua_State *L) {
257    sdb_vm *svm = lsqlite_checkvm(L, 1);
258    return cleanupvm(L, svm);
259}
260
261static int dbvm_reset(lua_State *L) {
262    sdb_vm *svm = lsqlite_checkvm(L, 1);
263    sqlite3_reset(svm->vm);
264    lua_pushnumber(L, sqlite3_errcode(svm->db->db));
265    return 1;
266}
267
268static void dbvm_check_contents(lua_State *L, sdb_vm *svm) {
269    if (!svm->has_values) {
270        luaL_error(L, "misuse of function");
271    }
272}
273
274static void dbvm_check_index(lua_State *L, sdb_vm *svm, int index) {
275    if (index < 0 || index >= svm->columns) {
276        luaL_error(L, "index out of range [0..%d]", svm->columns - 1);
277    }
278}
279
280static void dbvm_check_bind_index(lua_State *L, sdb_vm *svm, int index) {
281    if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) {
282        luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm));
283    }
284}
285
286/*
287** =======================================================
288** Virtual Machine - generic info
289** =======================================================
290*/
291static int dbvm_columns(lua_State *L) {
292    sdb_vm *svm = lsqlite_checkvm(L, 1);
293    lua_pushnumber(L, sqlite3_column_count(svm->vm));
294    return 1;
295}
296
297/*
298** =======================================================
299** Virtual Machine - getters
300** =======================================================
301*/
302
303static int dbvm_get_value(lua_State *L) {
304    sdb_vm *svm = lsqlite_checkvm(L, 1);
305    int index = luaL_checkint(L, 2);
306    dbvm_check_contents(L, svm);
307    dbvm_check_index(L, svm, index);
308    vm_push_column(L, svm->vm, index);
309    return 1;
310}
311
312static int dbvm_get_name(lua_State *L) {
313    sdb_vm *svm = lsqlite_checkvm(L, 1);
314    int index = luaL_checknumber(L, 2);
315    dbvm_check_index(L, svm, index);
316    lua_pushstring(L, sqlite3_column_name(svm->vm, index));
317    return 1;
318}
319
320static int dbvm_get_type(lua_State *L) {
321    sdb_vm *svm = lsqlite_checkvm(L, 1);
322    int index = luaL_checknumber(L, 2);
323    dbvm_check_index(L, svm, index);
324    lua_pushstring(L, sqlite3_column_decltype(svm->vm, index));
325    return 1;
326}
327
328static int dbvm_get_values(lua_State *L) {
329    sdb_vm *svm = lsqlite_checkvm(L, 1);
330    sqlite3_stmt *vm = svm->vm;
331    int columns = svm->columns;
332    int n;
333    dbvm_check_contents(L, svm);
334
335    lua_newtable(L);
336    for (n = 0; n < columns;) {
337        vm_push_column(L, vm, n++);
338        lua_rawseti(L, -2, n);
339    }
340    return 1;
341}
342
343static int dbvm_get_names(lua_State *L) {
344    sdb_vm *svm = lsqlite_checkvm(L, 1);
345    sqlite3_stmt *vm = svm->vm;
346    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
347    int n;
348
349    lua_newtable(L);
350    for (n = 0; n < columns;) {
351        lua_pushstring(L, sqlite3_column_name(vm, n++));
352        lua_rawseti(L, -2, n);
353    }
354    return 1;
355}
356
357static int dbvm_get_types(lua_State *L) {
358    sdb_vm *svm = lsqlite_checkvm(L, 1);
359    sqlite3_stmt *vm = svm->vm;
360    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
361    int n;
362
363    lua_newtable(L);
364    for (n = 0; n < columns;) {
365        lua_pushstring(L, sqlite3_column_decltype(vm, n++));
366        lua_rawseti(L, -2, n);
367    }
368    return 1;
369}
370
371static int dbvm_get_uvalues(lua_State *L) {
372    sdb_vm *svm = lsqlite_checkvm(L, 1);
373    sqlite3_stmt *vm = svm->vm;
374    int columns = svm->columns;
375    int n;
376    dbvm_check_contents(L, svm);
377
378    lua_checkstack(L, columns);
379    for (n = 0; n < columns; ++n)
380        vm_push_column(L, vm, n);
381    return columns;
382}
383
384static int dbvm_get_unames(lua_State *L) {
385    sdb_vm *svm = lsqlite_checkvm(L, 1);
386    sqlite3_stmt *vm = svm->vm;
387    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
388    int n;
389
390    lua_checkstack(L, columns);
391    for (n = 0; n < columns; ++n)
392        lua_pushstring(L, sqlite3_column_name(vm, n));
393    return columns;
394}
395
396static int dbvm_get_utypes(lua_State *L) {
397    sdb_vm *svm = lsqlite_checkvm(L, 1);
398    sqlite3_stmt *vm = svm->vm;
399    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
400    int n;
401
402    lua_checkstack(L, columns);
403    for (n = 0; n < columns; ++n)
404        lua_pushstring(L, sqlite3_column_decltype(vm, n));
405    return columns;
406}
407
408static int dbvm_get_named_values(lua_State *L) {
409    sdb_vm *svm = lsqlite_checkvm(L, 1);
410    sqlite3_stmt *vm = svm->vm;
411    int columns = svm->columns;
412    int n;
413    dbvm_check_contents(L, svm);
414
415    lua_newtable(L);
416    for (n = 0; n < columns; ++n) {
417        lua_pushstring(L, sqlite3_column_name(vm, n));
418        vm_push_column(L, vm, n);
419        lua_rawset(L, -3);
420    }
421    return 1;
422}
423
424static int dbvm_get_named_types(lua_State *L) {
425    sdb_vm *svm = lsqlite_checkvm(L, 1);
426    sqlite3_stmt *vm = svm->vm;
427    int columns = sqlite3_column_count(vm);
428    int n;
429
430    lua_newtable(L);
431    for (n = 0; n < columns; ++n) {
432        lua_pushstring(L, sqlite3_column_name(vm, n));
433        lua_pushstring(L, sqlite3_column_decltype(vm, n));
434        lua_rawset(L, -3);
435    }
436    return 1;
437}
438
439/*
440** =======================================================
441** Virtual Machine - Bind
442** =======================================================
443*/
444
445static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) {
446    switch (lua_type(L, lindex)) {
447        case LUA_TSTRING:
448            return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT);
449        case LUA_TNUMBER:
450            return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex));
451        case LUA_TNONE:
452        case LUA_TNIL:
453        /* allow boolean values so i have a way to know which
454        ** values were actually not set */
455        case LUA_TBOOLEAN:
456            return sqlite3_bind_null(vm, index);
457        default:
458            luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lindex));
459            return SQLITE_MISUSE; /*!*/
460    }
461}
462
463
464static int dbvm_bind_parameter_count(lua_State *L) {
465    sdb_vm *svm = lsqlite_checkvm(L, 1);
466    lua_pushnumber(L, sqlite3_bind_parameter_count(svm->vm));
467    return 1;
468}
469
470static int dbvm_bind_parameter_name(lua_State *L) {
471    sdb_vm *svm = lsqlite_checkvm(L, 1);
472    int index = luaL_checknumber(L, 2);
473    dbvm_check_bind_index(L, svm, index);
474    lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index));
475    return 1;
476}
477
478static int dbvm_bind(lua_State *L) {
479    sdb_vm *svm = lsqlite_checkvm(L, 1);
480    sqlite3_stmt *vm = svm->vm;
481    int index = luaL_checkint(L, 2);
482    int result;
483
484    dbvm_check_bind_index(L, svm, index);
485    result = dbvm_bind_index(L, vm, index, 3);
486
487    lua_pushnumber(L, result);
488    return 1;
489}
490
491static int dbvm_bind_blob(lua_State *L) {
492    sdb_vm *svm = lsqlite_checkvm(L, 1);
493    int index = luaL_checkint(L, 2);
494    const char *value = luaL_checkstring(L, 3);
495    int len = lua_strlen(L, 3);
496
497    lua_pushnumber(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT));
498    return 1;
499}
500
501static int dbvm_bind_values(lua_State *L) {
502    sdb_vm *svm = lsqlite_checkvm(L, 1);
503    sqlite3_stmt *vm = svm->vm;
504    int top = lua_gettop(L);
505    int result, n;
506
507    if (top - 1 != sqlite3_bind_parameter_count(vm))
508        luaL_error(L,
509            "incorrect number of parameters to bind (%d given, %d to bind)",
510            top - 1,
511            sqlite3_bind_parameter_count(vm)
512        );
513
514    for (n = 2; n <= top; ++n) {
515        if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) {
516            lua_pushnumber(L, result);
517            return 1;
518        }
519    }
520
521    lua_pushnumber(L, SQLITE_OK);
522    return 1;
523}
524
525static int dbvm_bind_names(lua_State *L) {
526    sdb_vm *svm = lsqlite_checkvm(L, 1);
527    sqlite3_stmt *vm = svm->vm;
528    int count = sqlite3_bind_parameter_count(vm);
529    const char *name;
530    int result, n;
531    luaL_checktype(L, 2, LUA_TTABLE);
532
533    for (n = 1; n <= count; ++n) {
534        name = sqlite3_bind_parameter_name(vm, n);
535        if (name && (name[0] == ':' || name[0] == '$')) {
536            lua_pushstring(L, ++name);
537            lua_gettable(L, 2);
538            result = dbvm_bind_index(L, vm, n, -1);
539        }
540        else {
541            lua_pushnumber(L, n);
542            lua_gettable(L, 2);
543            result = dbvm_bind_index(L, vm, n, -1);
544            lua_pop(L, 1);
545        }
546
547        if (result != SQLITE_OK) {
548            lua_pushnumber(L, result);
549            return 1;
550        }
551    }
552
553    lua_pushnumber(L, SQLITE_OK);
554    return 1;
555}
556
557/*
558** =======================================================
559** Database (internal management)
560** =======================================================
561*/
562
563/*
564** When creating database handles, always creates a `closed' database handle
565** before opening the actual database; so, if there is a memory error, the
566** database is not left opened.
567**
568** Creates a new 'table' and leaves it in the stack
569*/
570static sdb *newdb (lua_State *L) {
571    sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb));
572    db->L = L;
573    db->db = NULL;  /* database handle is currently `closed' */
574    db->func = NULL;
575
576    db->busy_cb =
577    db->busy_udata =
578    db->progress_cb =
579    db->progress_udata =
580    db->trace_cb =
581    db->trace_udata = LUA_NOREF;
582
583    luaL_getmetatable(L, sqlite_meta);
584    lua_setmetatable(L, -2);        /* set metatable */
585
586    /* to keep track of 'open' virtual machines */
587    lua_pushlightuserdata(L, db);
588    lua_newtable(L);
589    lua_rawset(L, LUA_REGISTRYINDEX);
590
591    return db;
592}
593
594static int cleanupdb(lua_State *L, sdb *db) {
595    sdb_func *func;
596    sdb_func *func_next;
597    int top;
598    int result;
599
600    /* free associated virtual machines */
601    lua_pushlightuserdata(L, db);
602    lua_rawget(L, LUA_REGISTRYINDEX);
603
604    /* close all used handles */
605    top = lua_gettop(L);
606    lua_pushnil(L);
607    while (lua_next(L, -2)) {
608        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
609        cleanupvm(L, svm);
610
611        lua_settop(L, top);
612        lua_pushnil(L);
613    }
614
615    lua_pop(L, 1); /* pop vm table */
616
617    /* remove entry in lua registry table */
618    lua_pushlightuserdata(L, db);
619    lua_pushnil(L);
620    lua_rawset(L, LUA_REGISTRYINDEX);
621
622    /* 'free' all references */
623    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
624    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
625    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
626    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
627    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
628    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
629
630    /* close database */
631    result = sqlite3_close(db->db);
632    db->db = NULL;
633
634    /* free associated memory with created functions */
635    func = db->func;
636    while (func) {
637        func_next = func->next;
638        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step);
639        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize);
640        luaL_unref(L, LUA_REGISTRYINDEX, func->udata);
641        free(func);
642        func = func_next;
643    }
644    db->func = NULL;
645    return result;
646}
647
648static sdb *lsqlite_getdb(lua_State *L, int index) {
649    sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta);
650    if (db == NULL) luaL_typerror(L, index, "sqlite database");
651    return db;
652}
653
654static sdb *lsqlite_checkdb(lua_State *L, int index) {
655    sdb *db = lsqlite_getdb(L, index);
656    if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database");
657    return db;
658}
659
660
661/*
662** =======================================================
663** User Defined Functions - Context Methods
664** =======================================================
665*/
666typedef struct {
667    sqlite3_context *ctx;
668    int ud;
669} lcontext;
670
671static lcontext *lsqlite_make_context(lua_State *L) {
672    lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext));
673    lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref);
674    lua_setmetatable(L, -2);
675    ctx->ctx = NULL;
676    ctx->ud = LUA_NOREF;
677    return ctx;
678}
679
680static lcontext *lsqlite_getcontext(lua_State *L, int index) {
681    lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta);
682    if (ctx == NULL) luaL_typerror(L, index, "sqlite context");
683    return ctx;
684}
685
686static lcontext *lsqlite_checkcontext(lua_State *L, int index) {
687    lcontext *ctx = lsqlite_getcontext(L, index);
688    if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context");
689    return ctx;
690}
691
692static int lcontext_tostring(lua_State *L) {
693    char buff[39];
694    lcontext *ctx = lsqlite_getcontext(L, 1);
695    if (ctx->ctx == NULL)
696        strcpy(buff, "closed");
697    else
698        sprintf(buff, "%p", ctx->ctx);
699    lua_pushfstring(L, "sqlite function context (%s)", buff);
700    return 1;
701}
702
703static void lcontext_check_aggregate(lua_State *L, lcontext *ctx) {
704    sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
705    if (!func->aggregate) {
706        luaL_error(L, "attempt to call aggregate method from scalar function");
707    }
708}
709
710static int lcontext_user_data(lua_State *L) {
711    lcontext *ctx = lsqlite_checkcontext(L, 1);
712    sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
713    lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata);
714    return 1;
715}
716
717static int lcontext_get_aggregate_context(lua_State *L) {
718    lcontext *ctx = lsqlite_checkcontext(L, 1);
719    lcontext_check_aggregate(L, ctx);
720    lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud);
721    return 1;
722}
723
724static int lcontext_set_aggregate_context(lua_State *L) {
725    lcontext *ctx = lsqlite_checkcontext(L, 1);
726    lcontext_check_aggregate(L, ctx);
727    lua_settop(L, 2);
728    luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
729    ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX);
730    return 0;
731}
732
733static int lcontext_aggregate_count(lua_State *L) {
734    lcontext *ctx = lsqlite_checkcontext(L, 1);
735    lcontext_check_aggregate(L, ctx);
736    lua_pushnumber(L, sqlite3_aggregate_count(ctx->ctx));
737    return 1;
738}
739
740#if 0
741void *sqlite3_get_auxdata(sqlite3_context*, int);
742void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*));
743#endif
744
745static int lcontext_result(lua_State *L) {
746    lcontext *ctx = lsqlite_checkcontext(L, 1);
747    switch (lua_type(L, 2)) {
748        case LUA_TNUMBER:
749            sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2));
750            break;
751        case LUA_TSTRING:
752            sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT);
753            break;
754        case LUA_TNIL:
755        case LUA_TNONE:
756            sqlite3_result_null(ctx->ctx);
757            break;
758        default:
759            luaL_error(L, "invalid result type %s", lua_typename(L, 2));
760            break;
761    }
762
763    return 0;
764}
765
766static int lcontext_result_blob(lua_State *L) {
767    lcontext *ctx = lsqlite_checkcontext(L, 1);
768    const char *blob = luaL_checkstring(L, 2);
769    int size = lua_strlen(L, 2);
770    sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT);
771    return 0;
772}
773
774static int lcontext_result_double(lua_State *L) {
775    lcontext *ctx = lsqlite_checkcontext(L, 1);
776    double d = luaL_checknumber(L, 2);
777    sqlite3_result_double(ctx->ctx, d);
778    return 0;
779}
780
781static int lcontext_result_error(lua_State *L) {
782    lcontext *ctx = lsqlite_checkcontext(L, 1);
783    const char *err = luaL_checkstring(L, 2);
784    int size = lua_strlen(L, 2);
785    sqlite3_result_error(ctx->ctx, err, size);
786    return 0;
787}
788
789static int lcontext_result_int(lua_State *L) {
790    lcontext *ctx = lsqlite_checkcontext(L, 1);
791    int i = luaL_checkint(L, 2);
792    sqlite3_result_int(ctx->ctx, i);
793    return 0;
794}
795
796static int lcontext_result_null(lua_State *L) {
797    lcontext *ctx = lsqlite_checkcontext(L, 1);
798    sqlite3_result_null(ctx->ctx);
799    return 0;
800}
801
802static int lcontext_result_text(lua_State *L) {
803    lcontext *ctx = lsqlite_checkcontext(L, 1);
804    const char *text = luaL_checkstring(L, 2);
805    int size = lua_strlen(L, 2);
806    sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT);
807    return 0;
808}
809
810/*
811** =======================================================
812** Database Methods
813** =======================================================
814*/
815
816static int db_isopen(lua_State *L) {
817    sdb *db = lsqlite_getdb(L, 1);
818    lua_pushboolean(L, db->db != NULL ? 1 : 0);
819    return 1;
820}
821
822static int db_last_insert_rowid(lua_State *L) {
823    sdb *db = lsqlite_checkdb(L, 1);
824    /* conversion warning: int64 -> luaNumber */
825    sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db);
826    lua_Number n = (lua_Number)rowid;
827    if (n == rowid)
828        lua_pushnumber(L, n);
829    else
830        lua_pushfstring(L, "%ll", rowid);
831    return 1;
832}
833
834static int db_changes(lua_State *L) {
835    sdb *db = lsqlite_checkdb(L, 1);
836    lua_pushnumber(L, sqlite3_changes(db->db));
837    return 1;
838}
839
840static int db_total_changes(lua_State *L) {
841    sdb *db = lsqlite_checkdb(L, 1);
842    lua_pushnumber(L, sqlite3_total_changes(db->db));
843    return 1;
844}
845
846static int db_errcode(lua_State *L) {
847    sdb *db = lsqlite_checkdb(L, 1);
848    lua_pushnumber(L, sqlite3_errcode(db->db));
849    return 1;
850}
851
852static int db_errmsg(lua_State *L) {
853    sdb *db = lsqlite_checkdb(L, 1);
854    lua_pushstring(L, sqlite3_errmsg(db->db));
855    return 1;
856}
857
858static int db_interrupt(lua_State *L) {
859    sdb *db = lsqlite_checkdb(L, 1);
860    sqlite3_interrupt(db->db);
861    return 0;
862}
863
864/*
865** Registering SQL functions:
866*/
867
868static void db_push_value(lua_State *L, sqlite3_value *value) {
869    switch (sqlite3_value_type(value)) {
870        case SQLITE_TEXT:
871            lua_pushlstring(L, sqlite3_value_text(value), sqlite3_value_bytes(value));
872            break;
873
874        case SQLITE_INTEGER:
875            {
876                sqlite_int64 i64 = sqlite3_value_int64(value);
877                lua_Number n = (lua_Number)i64;
878                if (n == i64)
879                    lua_pushnumber(L, n);
880                else
881                    lua_pushlstring(L, sqlite3_value_text(value), sqlite3_value_bytes(value));
882            }
883            break;
884
885        case SQLITE_FLOAT:
886            lua_pushnumber(L, sqlite3_value_double(value));
887            break;
888
889        case SQLITE_BLOB:
890            lua_pushlstring(L, sqlite3_value_blob(value), sqlite3_value_bytes(value));
891            break;
892
893        case SQLITE_NULL:
894            lua_pushnil(L);
895            break;
896
897        default:
898            /* things done properly (SQLite + Lua SQLite)
899            ** this should never happen */
900            lua_pushnil(L);
901            break;
902    }
903}
904
905/*
906** callback functions used when calling registered sql functions
907*/
908
909/* scalar function to be called
910** callback params: context, values... */
911static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv) {
912    sdb_func *func = (sdb_func*)sqlite3_user_data(context);
913    lua_State *L = func->db->L;
914    int n;
915    lcontext *ctx;
916
917    int top = lua_gettop(L);
918
919    /* ensure there is enough space in the stack */
920    lua_checkstack(L, argc + 3);
921
922    lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step);   /* function to call */
923
924    if (!func->aggregate) {
925        ctx = lsqlite_make_context(L); /* push context - used to set results */
926    }
927    else {
928        // reuse context userdata value
929
930        void *p = sqlite3_aggregate_context(context, 1);
931        /* i think it is OK to use assume that using a light user data
932        ** as an entry on LUA REGISTRY table will be unique */
933        lua_pushlightuserdata(L, p);
934        lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
935
936        if (lua_isnil(L, -1)) { /* not yet created? */
937            lua_pop(L, 1);
938            ctx = lsqlite_make_context(L);
939            lua_pushlightuserdata(L, p);
940            lua_pushvalue(L, -2);
941            lua_rawset(L, LUA_REGISTRYINDEX);
942        }
943        else
944            ctx = lsqlite_getcontext(L, -1);
945    }
946
947    /* push params */
948    for (n = 0; n < argc; ++n) {
949        db_push_value(L, argv[n]);
950    }
951
952    // set context
953    ctx->ctx = context;
954
955    if (lua_pcall(L, argc + 1, 0, 0)) {
956        const char *errmsg = lua_tostring(L, -1);
957        int size = lua_strlen(L, -1);
958        sqlite3_result_error(context, errmsg, size);
959    }
960
961    // invalidate context
962    ctx->ctx = NULL;
963
964    if (!func->aggregate) {
965        luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
966    }
967
968    lua_settop(L, top);
969}
970
971static void db_sql_finalize_function(sqlite3_context *context) {
972    sdb_func *func = (sdb_func*)sqlite3_user_data(context);
973    lua_State *L = func->db->L;
974    void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */
975    lcontext *ctx;
976    int top = lua_gettop(L);
977
978    lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize);   /* function to call */
979
980    /* i think it is OK to use assume that using a light user data
981    ** as an entry on LUA REGISTRY table will be unique */
982    lua_pushlightuserdata(L, p);
983    lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
984
985    if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */
986        lua_pop(L, 1);
987        ctx = lsqlite_make_context(L);
988        lua_pushlightuserdata(L, p);
989        lua_pushvalue(L, -2);
990        lua_rawset(L, LUA_REGISTRYINDEX);
991    }
992    else
993        ctx = lsqlite_getcontext(L, -1);
994
995    // set context
996    ctx->ctx = context;
997
998    if (lua_pcall(L, 1, 0, 0)) {
999        sqlite3_result_error(context, lua_tostring(L, -1), -1);
1000    }
1001
1002    // invalidate context
1003    ctx->ctx = NULL;
1004
1005    /* cleanup context */
1006    luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
1007    /* remove it from registry */
1008    lua_pushlightuserdata(L, p);
1009    lua_pushnil(L);
1010    lua_rawset(L, LUA_REGISTRYINDEX);
1011
1012    lua_settop(L, top);
1013}
1014
1015/*
1016** Register a normal function
1017** Params: db, function name, number arguments, [ callback | step, finalize], user data
1018** Returns: true on sucess
1019**
1020** Normal function:
1021** Params: context, params
1022**
1023** Aggregate function:
1024** Params of step: context, params
1025** Params of finalize: context
1026*/
1027static int db_register_function(lua_State *L, int aggregate) {
1028    sdb *db = lsqlite_checkdb(L, 1);
1029    const char *name;
1030    int args;
1031    int result;
1032    sdb_func *func;
1033
1034    /* safety measure */
1035    if (aggregate) aggregate = 1;
1036
1037    name = luaL_checkstring(L, 2);
1038    args = luaL_checkint(L, 3);
1039    luaL_checktype(L, 4, LUA_TFUNCTION);
1040    if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION);
1041
1042    /* maybe an alternative way to allocate memory should be used/avoided */
1043    func = (sdb_func*)malloc(sizeof(sdb_func));
1044    if (func == NULL) {
1045        luaL_error(L, "out of memory");
1046    }
1047
1048    result = sqlite3_create_function(
1049        db->db, name, args, SQLITE_UTF8, func,
1050        aggregate ? NULL : db_sql_normal_function,
1051        aggregate ? db_sql_normal_function : NULL,
1052        aggregate ? db_sql_finalize_function : NULL
1053    );
1054
1055    if (result == SQLITE_OK) {
1056        /* safety measures for userdata field to be present in the stack */
1057        lua_settop(L, 5 + aggregate);
1058
1059        /* save registered function in db function list */
1060        func->db = db;
1061        func->aggregate = aggregate;
1062        func->next = db->func;
1063        db->func = func;
1064
1065        /* save the setp/normal function callback */
1066        lua_pushvalue(L, 4);
1067        func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX);
1068        /* save user data */
1069        lua_pushvalue(L, 5+aggregate);
1070        func->udata = luaL_ref(L, LUA_REGISTRYINDEX);
1071
1072        if (aggregate) {
1073            lua_pushvalue(L, 5);
1074            func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX);
1075        }
1076        else
1077            func->fn_finalize = LUA_NOREF;
1078    }
1079    else {
1080        /* free allocated memory */
1081        free(func);
1082    }
1083
1084    lua_pushboolean(L, result == SQLITE_OK ? 1 : 0);
1085    return 1;
1086}
1087
1088static int db_create_function(lua_State *L) {
1089    return db_register_function(L, 0);
1090}
1091
1092static int db_create_aggregate(lua_State *L) {
1093    return db_register_function(L, 1);
1094}
1095
1096/* create_collation; contributed by Thomas Lauer
1097*/
1098
1099typedef struct {
1100    lua_State *L;
1101    int ref;
1102} scc;
1103
1104static int collwrapper(scc *co,int l1,const void *p1,
1105                        int l2,const void *p2) {
1106    int res=0;
1107    lua_State *L=co->L;
1108    lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref);
1109    lua_pushlstring(L,p1,l1);
1110    lua_pushlstring(L,p2,l2);
1111    if (lua_pcall(L,2,1,0)==0) res=(int)lua_tonumber(L,-1);
1112    lua_pop(L,1);
1113    return res;
1114}
1115
1116static void collfree(scc *co) {
1117    if (co) {
1118        luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref);
1119        free(co);
1120    }
1121}
1122
1123static int db_create_collation(lua_State *L) {
1124    sdb *db=lsqlite_checkdb(L,1);
1125    const char *collname=luaL_checkstring(L,2);
1126    scc *co=NULL;
1127    int (*collfunc)(scc *,int,const void *,int,const void *)=NULL;
1128    lua_settop(L,3); /* default args to nil, and exclude extras */
1129    if (lua_isfunction(L,3)) collfunc=collwrapper;
1130    else if (!lua_isnil(L,3))
1131        luaL_error(L,"create_collation: function or nil expected");
1132    if (collfunc != NULL) {
1133        co=(scc *)malloc(sizeof(scc)); // userdata is a no-no as it
1134                                         // will be garbage-collected
1135        if (co) {
1136            co->L=L;
1137            /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */
1138            co->ref=luaL_ref(L,LUA_REGISTRYINDEX);
1139        }
1140        else luaL_error(L,"create_collation: could not allocate callback");
1141    }
1142    sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8,
1143        (void *)co,
1144        (int(*)(void*,int,const void*,int,const void*))collfunc,
1145        (void(*)(void*))collfree);
1146    return 0;
1147}
1148
1149/*
1150** trace callback:
1151** Params: database, callback function, userdata
1152**
1153** callback function:
1154** Params: userdata, sql
1155*/
1156static void db_trace_callback(void *user, const char *sql) {
1157    sdb *db = (sdb*)user;
1158    lua_State *L = db->L;
1159    int top = lua_gettop(L);
1160
1161    /* setup lua callback call */
1162    lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_cb);    /* get callback */
1163    lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_udata); /* get callback user data */
1164    lua_pushstring(L, sql); /* traced sql statement */
1165
1166    /* call lua function */
1167    lua_pcall(L, 2, 0, 0);
1168    /* ignore any error generated by this function */
1169
1170    lua_settop(L, top);
1171}
1172
1173static int db_trace(lua_State *L) {
1174    sdb *db = lsqlite_checkdb(L, 1);
1175
1176    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1177        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1178        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
1179
1180        db->trace_cb =
1181        db->trace_udata = LUA_NOREF;
1182
1183        /* clear busy handler */
1184        sqlite3_trace(db->db, NULL, NULL);
1185    }
1186    else {
1187        luaL_checktype(L, 2, LUA_TFUNCTION);
1188
1189        /* make sure we have an userdata field (even if nil) */
1190        lua_settop(L, 3);
1191
1192        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1193        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
1194
1195        db->trace_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1196        db->trace_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1197
1198        /* set busy handler */
1199        sqlite3_trace(db->db, db_trace_callback, db);
1200    }
1201
1202    return 0;
1203}
1204
1205
1206#if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK
1207
1208/*
1209** progress handler:
1210** Params: database, number of opcodes, callback function, userdata
1211**
1212** callback function:
1213** Params: userdata
1214** returns: 0 to return immediatly and return SQLITE_ABORT, non-zero to continue
1215*/
1216static int db_progress_callback(void *user) {
1217    int result = 1; /* abort by default */
1218    sdb *db = (sdb*)user;
1219    lua_State *L = db->L;
1220    int top = lua_gettop(L);
1221
1222    lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_cb);
1223    lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_udata);
1224
1225    /* call lua function */
1226    if (!lua_pcall(L, 1, 1, 0))
1227        result = lua_toboolean(L, -1);
1228
1229    lua_settop(L, top);
1230    return result;
1231}
1232
1233static int db_progress_handler(lua_State *L) {
1234    sdb *db = lsqlite_checkdb(L, 1);
1235
1236    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1237        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1238        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
1239
1240        db->progress_cb =
1241        db->progress_udata = LUA_NOREF;
1242
1243        /* clear busy handler */
1244        sqlite3_progress_handler(db->db, 0, NULL, NULL);
1245    }
1246    else {
1247        int nop = luaL_checkint(L, 2);  /* number of opcodes */
1248        luaL_checktype(L, 3, LUA_TFUNCTION);
1249
1250        /* make sure we have an userdata field (even if nil) */
1251        lua_settop(L, 4);
1252
1253        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1254        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
1255
1256        db->progress_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1257        db->progress_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1258
1259        /* set progress callback */
1260        sqlite3_progress_handler(db->db, nop, db_progress_callback, db);
1261    }
1262
1263    return 0;
1264}
1265
1266#else /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
1267
1268static int db_progress_handler(lua_State *L) {
1269    lua_pushliteral(L, "progress callback support disabled at compile time");
1270    lua_error(L);
1271    return 0;
1272}
1273
1274#endif /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
1275
1276/*
1277** busy handler:
1278** Params: database, callback function, userdata
1279**
1280** callback function:
1281** Params: userdata, number of tries
1282** returns: 0 to return immediatly and return SQLITE_BUSY, non-zero to try again
1283*/
1284static int db_busy_callback(void *user, int tries) {
1285    int retry = 0; /* abort by default */
1286    sdb *db = (sdb*)user;
1287    lua_State *L = db->L;
1288    int top = lua_gettop(L);
1289
1290    lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb);
1291    lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata);
1292    lua_pushnumber(L, tries);
1293
1294    /* call lua function */
1295    if (!lua_pcall(L, 2, 1, 0))
1296        retry = lua_toboolean(L, -1);
1297
1298    lua_settop(L, top);
1299    return retry;
1300}
1301
1302static int db_busy_handler(lua_State *L) {
1303    sdb *db = lsqlite_checkdb(L, 1);
1304
1305    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1306        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1307        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1308
1309        db->busy_cb =
1310        db->busy_udata = LUA_NOREF;
1311
1312        /* clear busy handler */
1313        sqlite3_busy_handler(db->db, NULL, NULL);
1314    }
1315    else {
1316        luaL_checktype(L, 2, LUA_TFUNCTION);
1317        /* make sure we have an userdata field (even if nil) */
1318        lua_settop(L, 3);
1319
1320        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1321        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1322
1323        db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1324        db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1325
1326        /* set busy handler */
1327        sqlite3_busy_handler(db->db, db_busy_callback, db);
1328    }
1329
1330    return 0;
1331}
1332
1333static int db_busy_timeout(lua_State *L) {
1334    sdb *db = lsqlite_checkdb(L, 1);
1335    int timeout = luaL_checkint(L, 2);
1336    sqlite3_busy_timeout(db->db, timeout);
1337
1338    /* if there was a timeout callback registered, it is now
1339    ** invalid/useless. free any references we may have */
1340    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1341    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1342    db->busy_cb =
1343    db->busy_udata = LUA_NOREF;
1344
1345    return 0;
1346}
1347
1348/*
1349** Params: db, sql, callback, user
1350** returns: code [, errmsg]
1351**
1352** Callback:
1353** Params: user, number of columns, values, names
1354** Returns: 0 to continue, other value will cause abort
1355*/
1356static int db_exec_callback(void* user, int columns, char **data, char **names) {
1357    int result = SQLITE_ABORT; /* abort by default */
1358    sdb *db = (sdb*)user;
1359    lua_State *L = db->L;
1360    int n;
1361
1362    int top = lua_gettop(L);
1363
1364    lua_pushvalue(L, 3); /* function to call */
1365    lua_pushvalue(L, 4); /* user data */
1366    lua_pushnumber(L, columns); /* total number of rows in result */
1367
1368    /* column values */
1369    lua_pushvalue(L, 6);
1370    for (n = 0; n < columns;) {
1371        lua_pushstring(L, data[n++]);
1372        lua_rawseti(L, -2, n);
1373    }
1374
1375    /* columns names */
1376    lua_pushvalue(L, 5);
1377    if (lua_isnil(L, -1)) {
1378        lua_pop(L, 1);
1379        lua_newtable(L);
1380        lua_pushvalue(L, -1);
1381        lua_replace(L, 5);
1382        for (n = 0; n < columns;) {
1383            lua_pushstring(L, names[n++]);
1384            lua_rawseti(L, -2, n);
1385        }
1386    }
1387
1388    /* call lua function */
1389    if (!lua_pcall(L, 4, 1, 0)) {
1390        if (lua_isnumber(L, -1))
1391            result = lua_tonumber(L, -1);
1392    }
1393
1394    lua_settop(L, top);
1395    return result;
1396}
1397
1398static int db_exec(lua_State *L) {
1399    sdb *db = lsqlite_checkdb(L, 1);
1400    const char *sql = luaL_checkstring(L, 2);
1401    int result;
1402
1403    if (!lua_isnoneornil(L, 3)) {
1404        /* stack:
1405        **  3: callback function
1406        **  4: userdata
1407        **  5: column names
1408        **  6: reusable column values
1409        */
1410        luaL_checktype(L, 3, LUA_TFUNCTION);
1411        lua_settop(L, 4);   /* 'trap' userdata - nil extra parameters */
1412        lua_pushnil(L);     /* column names not known at this point */
1413        lua_newtable(L);    /* column values table */
1414
1415        result = sqlite3_exec(db->db, sql, db_exec_callback, db, NULL);
1416    }
1417    else {
1418        /* no callbacks */
1419        result = sqlite3_exec(db->db, sql, NULL, NULL, NULL);
1420    }
1421
1422    lua_pushnumber(L, result);
1423    return 1;
1424}
1425
1426/*
1427** Params: db, sql
1428** returns: code, compiled length or error message
1429*/
1430static int db_prepare(lua_State *L) {
1431    sdb *db = lsqlite_checkdb(L, 1);
1432    const char *sql = luaL_checkstring(L, 2);
1433    int sql_len = lua_strlen(L, 2);
1434    const char *sqltail;
1435    sdb_vm *svm;
1436    lua_settop(L,2); /* sql is on top of stack for call to newvm */
1437    svm = newvm(L, db);
1438
1439    if (sqlite3_prepare(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) {
1440        cleanupvm(L, svm);
1441
1442        lua_pushnil(L);
1443        lua_pushnumber(L, sqlite3_errcode(db->db));
1444        return 2;
1445    }
1446
1447    /* vm already in the stack */
1448    lua_pushstring(L, sqltail);
1449    return 2;
1450}
1451
1452static int db_do_next_row(lua_State *L, int packed) {
1453    int result;
1454    sdb_vm *svm = lsqlite_checkvm(L, 1);
1455    sqlite3_stmt *vm;
1456    int columns;
1457    int i;
1458
1459    result = stepvm(L, svm);
1460    vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */
1461    svm->has_values = result == SQLITE_ROW ? 1 : 0;
1462    svm->columns = columns = sqlite3_data_count(vm);
1463
1464    if (result == SQLITE_ROW) {
1465        if (packed) {
1466            lua_newtable(L);
1467            if (packed == 1) {
1468                for (i = 0; i < columns;) {
1469                    vm_push_column(L, vm, i);
1470                    lua_rawseti(L, -2, ++i);
1471                }
1472            }
1473            else {
1474                for (i = 0; i < columns; ++i) {
1475                    lua_pushstring(L, sqlite3_column_name(vm, i));
1476                    vm_push_column(L, vm, i);
1477                    lua_rawset(L, -3);
1478                }
1479            }
1480            return 1;
1481        }
1482        else {
1483            lua_checkstack(L, columns);
1484            for (i = 0; i < columns; ++i)
1485                vm_push_column(L, vm, i);
1486            return svm->columns;
1487        }
1488    }
1489
1490    if (svm->temp) {
1491        /* finalize and check for errors */
1492        result = sqlite3_finalize(vm);
1493        svm->vm = NULL;
1494        cleanupvm(L, svm);
1495    }
1496    else if (result == SQLITE_DONE) {
1497        result = sqlite3_reset(vm);
1498    }
1499
1500    if (result != SQLITE_OK) {
1501        lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1502        lua_error(L);
1503    }
1504    return 0;
1505}
1506
1507static int db_next_row(lua_State *L) {
1508    return db_do_next_row(L, 0);
1509}
1510
1511static int db_next_packed_row(lua_State *L) {
1512    return db_do_next_row(L, 1);
1513}
1514
1515static int db_next_named_row(lua_State *L) {
1516    return db_do_next_row(L, 2);
1517}
1518
1519static int dbvm_do_rows(lua_State *L, int(*f)(lua_State *)) {
1520    //sdb_vm *svm =
1521    lsqlite_checkvm(L, 1);
1522    lua_pushvalue(L,1);
1523    lua_pushcfunction(L, f);
1524    lua_insert(L, -2);
1525    return 2;
1526}
1527
1528static int dbvm_rows(lua_State *L) {
1529    return dbvm_do_rows(L, db_next_packed_row);
1530}
1531
1532static int dbvm_nrows(lua_State *L) {
1533    return dbvm_do_rows(L, db_next_named_row);
1534}
1535
1536static int dbvm_urows(lua_State *L) {
1537    return dbvm_do_rows(L, db_next_row);
1538}
1539
1540static int db_do_rows(lua_State *L, int(*f)(lua_State *)) {
1541    sdb *db = lsqlite_checkdb(L, 1);
1542    const char *sql = luaL_checkstring(L, 2);
1543    sdb_vm *svm;
1544    lua_settop(L,2); /* sql is on top of stack for call to newvm */
1545    svm = newvm(L, db);
1546    svm->temp = 1;
1547
1548    if (sqlite3_prepare(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) {
1549        cleanupvm(L, svm);
1550
1551        lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1552        lua_error(L);
1553    }
1554
1555    lua_pushcfunction(L, f);
1556    lua_insert(L, -2);
1557    return 2;
1558}
1559
1560static int db_rows(lua_State *L) {
1561    return db_do_rows(L, db_next_packed_row);
1562}
1563
1564static int db_nrows(lua_State *L) {
1565    return db_do_rows(L, db_next_named_row);
1566}
1567
1568/* unpacked version of db:rows */
1569static int db_urows(lua_State *L) {
1570    return db_do_rows(L, db_next_row);
1571}
1572
1573static int db_tostring(lua_State *L) {
1574    char buff[32];
1575    sdb *db = lsqlite_getdb(L, 1);
1576    if (db->db == NULL)
1577        strcpy(buff, "closed");
1578    else
1579        sprintf(buff, "%p", lua_touserdata(L, 1));
1580    lua_pushfstring(L, "sqlite database (%s)", buff);
1581    return 1;
1582}
1583
1584static int db_close(lua_State *L) {
1585    sdb *db = lsqlite_checkdb(L, 1);
1586    lua_pushnumber(L, cleanupdb(L, db));
1587    return 1;
1588}
1589
1590static int db_close_vm(lua_State *L) {
1591    sdb *db = lsqlite_checkdb(L, 1);
1592    /* cleanup temporary only tables? */
1593    int temp = lua_toboolean(L, 2);
1594
1595    /* free associated virtual machines */
1596    lua_pushlightuserdata(L, db);
1597    lua_rawget(L, LUA_REGISTRYINDEX);
1598
1599    /* close all used handles */
1600    lua_pushnil(L);
1601    while (lua_next(L, -2)) {
1602        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
1603
1604        if ((!temp || svm->temp) && svm->vm)
1605        {
1606            sqlite3_finalize(svm->vm);
1607            svm->vm = NULL;
1608        }
1609
1610        /* leave key in the stack */
1611        lua_pop(L, 1);
1612    }
1613    return 0;
1614}
1615
1616static int db_gc(lua_State *L) {
1617    sdb *db = lsqlite_getdb(L, 1);
1618    if (db->db != NULL)  /* ignore closed databases */
1619        cleanupdb(L, db);
1620    return 0;
1621}
1622
1623/*
1624** =======================================================
1625** General library functions
1626** =======================================================
1627*/
1628
1629static int lsqlite_version(lua_State *L) {
1630    lua_pushstring(L, sqlite3_libversion());
1631    return 1;
1632}
1633
1634static int lsqlite_complete(lua_State *L) {
1635    const char *sql = luaL_checkstring(L, 1);
1636    lua_pushboolean(L, sqlite3_complete(sql));
1637    return 1;
1638}
1639
1640#ifndef WIN32
1641static int lsqlite_temp_directory(lua_State *L) {
1642    const char *oldtemp = sqlite3_temp_directory;
1643
1644    if (!lua_isnone(L, 1)) {
1645        const char *temp = luaL_optstring(L, 1, NULL);
1646        if (sqlite3_temp_directory) {
1647            sqlite3_free((char*)sqlite3_temp_directory);
1648        }
1649        if (temp) {
1650            sqlite3_temp_directory = sqlite3_mprintf("%s", temp);
1651        }
1652        else {
1653            sqlite3_temp_directory = NULL;
1654        }
1655    }
1656    lua_pushstring(L, oldtemp);
1657    return 1;
1658}
1659#endif
1660
1661static int lsqlite_do_open(lua_State *L, const char *filename) {
1662    sdb *db = newdb(L); /* create and leave in stack */
1663
1664    if (sqlite3_open(filename, &db->db) == SQLITE_OK) {
1665        /* database handle already in the stack - return it */
1666        return 1;
1667    }
1668
1669    /* failed to open database */
1670    lua_pushnil(L);                             /* push nil */
1671    lua_pushnumber(L, sqlite3_errcode(db->db));
1672    lua_pushstring(L, sqlite3_errmsg(db->db));  /* push error message */
1673
1674    /* clean things up */
1675    cleanupdb(L, db);
1676
1677    /* return */
1678    return 3;
1679}
1680
1681static int lsqlite_open(lua_State *L) {
1682    const char *filename = luaL_checkstring(L, 1);
1683    return lsqlite_do_open(L, filename);
1684}
1685
1686static int lsqlite_open_memory(lua_State *L) {
1687    return lsqlite_do_open(L, ":memory:");
1688}
1689
1690static int lsqlite_newindex(lua_State *L) {
1691    lua_pushliteral(L, "attempt to change readonly table");
1692    lua_error(L);
1693    return 0;
1694}
1695
1696/*
1697** =======================================================
1698** Register functions
1699** =======================================================
1700*/
1701
1702#define SC(s)   { #s, SQLITE_ ## s },
1703#define LSC(s)  { #s, LSQLITE_ ## s },
1704
1705static const struct {
1706    const char* name;
1707    int value;
1708} sqlite_constants[] = {
1709    /* error codes */
1710    SC(OK)          SC(ERROR)       SC(INTERNAL)    SC(PERM)
1711    SC(ABORT)       SC(BUSY)        SC(LOCKED)      SC(NOMEM)
1712    SC(READONLY)    SC(INTERRUPT)   SC(IOERR)       SC(CORRUPT)
1713    SC(NOTFOUND)    SC(FULL)        SC(CANTOPEN)    SC(PROTOCOL)
1714    SC(EMPTY)       SC(SCHEMA)      SC(TOOBIG)      SC(CONSTRAINT)
1715    SC(MISMATCH)    SC(MISUSE)      SC(NOLFS)
1716    SC(FORMAT)      SC(NOTADB)
1717
1718    /* sqlite_step specific return values */
1719    SC(RANGE)       SC(ROW)         SC(DONE)
1720
1721    /* column types */
1722    SC(INTEGER)     SC(FLOAT)       SC(TEXT)        SC(BLOB)
1723    SC(NULL)
1724
1725    /* terminator */
1726    { NULL, 0 }
1727};
1728
1729/* ======================================================= */
1730
1731static const luaL_reg dblib[] = {
1732    {"isopen",              db_isopen               },
1733    {"last_insert_rowid",   db_last_insert_rowid    },
1734    {"changes",             db_changes              },
1735    {"total_changes",       db_total_changes        },
1736    {"errcode",             db_errcode              },
1737    {"error_code",          db_errcode              },
1738    {"errmsg",              db_errmsg               },
1739    {"error_message",       db_errmsg               },
1740    {"interrupt",           db_interrupt            },
1741
1742    {"create_function",     db_create_function      },
1743    {"create_aggregate",    db_create_aggregate     },
1744    {"create_collation",    db_create_collation     },
1745
1746    {"trace",               db_trace                },
1747    {"progress_handler",    db_progress_handler     },
1748    {"busy_timeout",        db_busy_timeout         },
1749    {"busy_handler",        db_busy_handler         },
1750
1751    {"prepare",             db_prepare              },
1752    {"rows",                db_rows                 },
1753    {"urows",               db_urows                },
1754    {"nrows",               db_nrows                },
1755
1756    {"exec",                db_exec                 },
1757    {"execute",             db_exec                 },
1758    {"close",               db_close                },
1759    {"close_vm",            db_close_vm             },
1760
1761    {"__tostring",          db_tostring             },
1762    {"__gc",                db_gc                   },
1763
1764    {NULL, NULL}
1765};
1766
1767static const luaL_reg vmlib[] = {
1768    {"isopen",              dbvm_isopen             },
1769
1770    {"step",                dbvm_step               },
1771    {"reset",               dbvm_reset              },
1772    {"finalize",            dbvm_finalize           },
1773
1774    {"columns",             dbvm_columns            },
1775
1776    {"bind",                dbvm_bind               },
1777    {"bind_values",         dbvm_bind_values        },
1778    {"bind_names",          dbvm_bind_names         },
1779    {"bind_blob",           dbvm_bind_blob          },
1780    {"bind_parameter_count",dbvm_bind_parameter_count},
1781    {"bind_parameter_name", dbvm_bind_parameter_name},
1782
1783    {"get_value",           dbvm_get_value          },
1784    {"get_values",          dbvm_get_values         },
1785    {"get_name",            dbvm_get_name           },
1786    {"get_names",           dbvm_get_names          },
1787    {"get_type",            dbvm_get_type           },
1788    {"get_types",           dbvm_get_types          },
1789    {"get_uvalues",         dbvm_get_uvalues        },
1790    {"get_unames",          dbvm_get_unames         },
1791    {"get_utypes",          dbvm_get_utypes         },
1792
1793    {"get_named_values",    dbvm_get_named_values   },
1794    {"get_named_types",     dbvm_get_named_types    },
1795
1796    {"rows",                dbvm_rows               },
1797    {"urows",               dbvm_urows              },
1798    {"nrows",               dbvm_nrows              },
1799
1800    /* compatibility names (added by request) */
1801    {"idata",               dbvm_get_values         },
1802    {"inames",              dbvm_get_names          },
1803    {"itypes",              dbvm_get_types          },
1804    {"data",                dbvm_get_named_values   },
1805    {"type",                dbvm_get_named_types    },
1806
1807    {"__tostring",          dbvm_tostring           },
1808    {"__gc",                dbvm_gc                 },
1809
1810    { NULL, NULL }
1811};
1812
1813static const luaL_reg ctxlib[] = {
1814    {"user_data",               lcontext_user_data              },
1815
1816    {"get_aggregate_data",      lcontext_get_aggregate_context  },
1817    {"set_aggregate_data",      lcontext_set_aggregate_context  },
1818    {"aggregate_count",         lcontext_aggregate_count        },
1819
1820    {"result",                  lcontext_result                 },
1821    {"result_null",             lcontext_result_null            },
1822    {"result_number",           lcontext_result_double          },
1823    {"result_double",           lcontext_result_double          },
1824    {"result_int",              lcontext_result_int             },
1825    {"result_text",             lcontext_result_text            },
1826    {"result_blob",             lcontext_result_blob            },
1827    {"result_error",            lcontext_result_error           },
1828
1829    {"__tostring",              lcontext_tostring               },
1830    {NULL, NULL}
1831};
1832
1833static const luaL_reg sqlitelib[] = {
1834    {"version",         lsqlite_version         },
1835    {"complete",        lsqlite_complete        },
1836#ifndef WIN32
1837    {"temp_directory",  lsqlite_temp_directory  },
1838#endif
1839    {"open",            lsqlite_open            },
1840    {"open_memory",     lsqlite_open_memory     },
1841
1842    {"__newindex",      lsqlite_newindex        },
1843    {NULL, NULL}
1844};
1845
1846static void create_meta(lua_State *L, const char *name, const luaL_reg *lib) {
1847    luaL_newmetatable(L, name);
1848    lua_pushstring(L, "__index");
1849    lua_pushvalue(L, -2);               /* push metatable */
1850    lua_rawset(L, -3);                  /* metatable.__index = metatable */
1851
1852    /* register metatable functions */
1853    luaL_openlib(L, NULL, lib, 0);
1854
1855    /* remove metatable from stack */
1856    lua_pop(L, 1);
1857}
1858
1859LUALIB_API int luaopen_lsqlite3(lua_State *L) {
1860    create_meta(L, sqlite_meta, dblib);
1861    create_meta(L, sqlite_vm_meta, vmlib);
1862    create_meta(L, sqlite_ctx_meta, ctxlib);
1863
1864    luaL_getmetatable(L, sqlite_ctx_meta);
1865    sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1866
1867    /* register (local) sqlite metatable */
1868    luaL_register(L, "sqlite3", sqlitelib);
1869
1870    {
1871        int i = 0;
1872        /* add constants to global table */
1873        while (sqlite_constants[i].name) {
1874            lua_pushstring(L, sqlite_constants[i].name);
1875            lua_pushnumber(L, sqlite_constants[i].value);
1876            lua_rawset(L, -3);
1877            ++i;
1878        }
1879    }
1880
1881    /* set sqlite's metatable to itself - set as readonly (__newindex) */
1882    lua_pushvalue(L, -1);
1883    lua_setmetatable(L, -2);
1884
1885    return 1;
1886}
trunk/3rdparty/lsqlite3/lsqlite3.def
r0r242834
1EXPORTS
2luaopen_lsqlite3
trunk/3rdparty/lsqlite3/lunit.lua
r0r242834
1
2--[[--------------------------------------------------------------------------
3
4    This file is part of lunit 0.4pre (alpha).
5
6    For Details about lunit look at: http://www.nessie.de/mroth/lunit/
7
8    Author: Michael Roth <mroth@nessie.de>
9
10    Copyright (c) 2004 Michael Roth <mroth@nessie.de>
11
12    Permission is hereby granted, free of charge, to any person
13    obtaining a copy of this software and associated documentation
14    files (the "Software"), to deal in the Software without restriction,
15    including without limitation the rights to use, copy, modify, merge,
16    publish, distribute, sublicense, and/or sell copies of the Software,
17    and to permit persons to whom the Software is furnished to do so,
18    subject to the following conditions:
19
20    The above copyright notice and this permission notice shall be
21    included in all copies or substantial portions of the Software.
22
23    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
26    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
27    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
28    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
29    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
31--]]--------------------------------------------------------------------------
32
33
34
35
36-----------------------
37-- Intialize package --
38-----------------------
39
40local P = { }
41lunit = P
42
43-- Import
44local type = type
45local print = print
46local ipairs = ipairs
47local pairs = pairs
48local string = string
49local table = table
50local pcall = pcall
51local xpcall = xpcall
52local traceback = debug.traceback
53local error = error
54local setmetatable = setmetatable
55local rawset = rawset
56local orig_assert = assert
57local getfenv = getfenv
58local setfenv = setfenv
59local tostring = tostring
60
61
62-- Start package scope
63setfenv(1, P)
64
65
66
67
68--------------------------------
69-- Private data and functions --
70--------------------------------
71
72local run_testcase
73local do_assert, check_msg
74local stats = { }
75local testcases = { }
76local stats_inc, tc_mt
77
78
79
80
81--------------------------
82-- Type check functions --
83--------------------------
84
85function is_nil(x)
86  return type(x) == "nil"
87end
88
89function is_boolean(x)
90  return type(x) == "boolean"
91end
92
93function is_number(x)
94  return type(x) == "number"
95end
96
97function is_string(x)
98  return type(x) == "string"
99end
100
101function is_table(x)
102  return type(x) == "table"
103end
104
105function is_function(x)
106  return type(x) == "function"
107end
108
109function is_thread(x)
110  return type(x) == "thread"
111end
112
113function is_userdata(x)
114  return type(x) == "userdata"
115end
116
117
118
119
120----------------------
121-- Assert functions --
122----------------------
123
124function assert(assertion, msg)
125  stats_inc("assertions")
126  check_msg("assert", msg)
127  do_assert(not not assertion, "assertion failed (was: "..tostring(assertion)..")", msg)      -- (convert assertion to bool)
128  return assertion
129end
130
131
132function assert_fail(msg)
133  stats_inc("assertions")
134  check_msg("assert_fail", msg)
135  do_assert(false, "failure", msg)
136end
137
138
139function assert_true(actual, msg)
140  stats_inc("assertions")
141  check_msg("assert_true", msg)
142  do_assert(is_boolean(actual), "true expected but was a "..type(actual), msg)
143  do_assert(actual == true, "true expected but was false", msg)
144  return actual
145end
146
147
148function assert_false(actual, msg)
149  stats_inc("assertions")
150  check_msg("assert_false", msg)
151  do_assert(is_boolean(actual), "false expected but was a "..type(actual), msg)
152  do_assert(actual == false, "false expected but was true", msg)
153  return actual
154end
155
156
157function assert_equal(expected, actual, msg)
158  stats_inc("assertions")
159  check_msg("assert_equal", msg)
160  do_assert(expected == actual, "expected '"..tostring(expected).."' but was '"..tostring(actual).."'", msg)
161  return actual
162end
163
164
165function assert_not_equal(unexpected, actual, msg)
166  stats_inc("assertions")
167  check_msg("assert_not_equal", msg)
168  do_assert(unexpected ~= actual, "'"..tostring(expected).."' not expected but was one", msg)
169  return actual
170end
171
172
173function assert_match(pattern, actual, msg)
174  stats_inc("assertions")
175  check_msg("assert_match", msg)
176  do_assert(is_string(pattern), "assert_match expects the pattern as a string")
177  do_assert(is_string(actual), "expected a string to match pattern '"..pattern.."' but was a '"..type(actual).."'", msg)
178  do_assert(not not string.find(actual, pattern), "expected '"..actual.."' to match pattern '"..pattern.."' but doesn't", msg)
179  return actual
180end
181
182
183function assert_not_match(pattern, actual, msg)
184  stats_inc("assertions")
185  check_msg("assert_not_match", msg)
186  do_assert(is_string(actual), "expected a string to not match pattern '"..pattern.."' but was a '"..type(actual).."'", msg)
187  do_assert(string.find(actual, pattern) == nil, "expected '"..actual.."' to not match pattern '"..pattern.."' but it does", msg)
188  return actual
189end
190
191
192function assert_nil(actual, msg)
193  stats_inc("assertions")
194  check_msg("assert_nil", msg)
195  do_assert(is_nil(actual), "nil expected but was a "..type(actual), msg)
196  return actual
197end
198
199
200function assert_not_nil(actual, msg)
201  stats_inc("assertions")
202  check_msg("assert_not_nil", msg)
203  do_assert(not is_nil(actual), "nil not expected but was one", msg)
204  return actual
205end
206
207
208function assert_boolean(actual, msg)
209  stats_inc("assertions")
210  check_msg("assert_boolean", msg)
211  do_assert(is_boolean(actual), "boolean expected but was a "..type(actual), msg)
212  return actual
213end
214
215
216function assert_not_boolean(actual, msg)
217  stats_inc("assertions")
218  check_msg("assert_not_boolean", msg)
219  do_assert(not is_boolean(actual), "boolean not expected but was one", msg)
220  return actual
221end
222
223
224function assert_number(actual, msg)
225  stats_inc("assertions")
226  check_msg("assert_number", msg)
227  do_assert(is_number(actual), "number expected but was a "..type(actual), msg)
228  return actual
229end
230
231
232function assert_not_number(actual, msg)
233  stats_inc("assertions")
234  check_msg("assert_not_number", msg)
235  do_assert(not is_number(actual), "number not expected but was one", msg)
236  return actual
237end
238
239
240function assert_string(actual, msg)
241  stats_inc("assertions")
242  check_msg("assert_string", msg)
243  do_assert(is_string(actual), "string expected but was a "..type(actual), msg)
244  return actual
245end
246
247
248function assert_not_string(actual, msg)
249  stats_inc("assertions")
250  check_msg("assert_not_string", msg)
251  do_assert(not is_string(actual), "string not expected but was one", msg)
252  return actual
253end
254
255
256function assert_table(actual, msg)
257  stats_inc("assertions")
258  check_msg("assert_table", msg)
259  do_assert(is_table(actual), "table expected but was a "..type(actual), msg)
260  return actual
261end
262
263
264function assert_not_table(actual, msg)
265  stats_inc("assertions")
266  check_msg("assert_not_table", msg)
267  do_assert(not is_table(actual), "table not expected but was one", msg)
268  return actual
269end
270
271
272function assert_function(actual, msg)
273  stats_inc("assertions")
274  check_msg("assert_function", msg)
275  do_assert(is_function(actual), "function expected but was a "..type(actual), msg)
276  return actual
277end
278
279
280function assert_not_function(actual, msg)
281  stats_inc("assertions")
282  check_msg("assert_not_function", msg)
283  do_assert(not is_function(actual), "function not expected but was one", msg)
284  return actual
285end
286
287
288function assert_thread(actual, msg)
289  stats_inc("assertions")
290  check_msg("assert_thread", msg)
291  do_assert(is_thread(actual), "thread expected but was a "..type(actual), msg)
292  return actual
293end
294
295
296function assert_not_thread(actual, msg)
297  stats_inc("assertions")
298  check_msg("assert_not_thread", msg)
299  do_assert(not is_thread(actual), "thread not expected but was one", msg)
300  return actual
301end
302
303
304function assert_userdata(actual, msg)
305  stats_inc("assertions")
306  check_msg("assert_userdata", msg)
307  do_assert(is_userdata(actual), "userdata expected but was a "..type(actual), msg)
308  return actual
309end
310
311
312function assert_not_userdata(actual, msg)
313  stats_inc("assertions")
314  check_msg("assert_not_userdata", msg)
315  do_assert(not is_userdata(actual), "userdata not expected but was one", msg)
316  return actual
317end
318
319
320function assert_error(msg, func)
321  stats_inc("assertions")
322  if is_nil(func) then func, msg = msg, nil end
323  check_msg("assert_error", msg)
324  do_assert(is_function(func), "assert_error expects a function as the last argument but it was a "..type(func))
325  local ok, errmsg = pcall(func)
326  do_assert(ok == false, "error expected but no error occurred", msg)
327end
328
329
330function assert_pass(msg, func)
331  stats_inc("assertions")
332  if is_nil(func) then func, msg = msg, nil end
333  check_msg("assert_pass", msg)
334  do_assert(is_function(func), "assert_pass expects a function as the last argument but it was a "..type(func))
335  local ok, errmsg = pcall(func)
336  if not ok then do_assert(ok == true, "no error expected but error was: "..errmsg, msg) end
337end
338
339
340
341
342-----------------------------------------------------------
343-- Assert implementation that assumes it was called from --
344-- lunit code which was called directly from user code.  --
345-----------------------------------------------------------
346
347function do_assert(assertion, base_msg, user_msg)
348  orig_assert(is_boolean(assertion))
349  orig_assert(is_string(base_msg))
350  orig_assert(is_string(user_msg) or is_nil(user_msg))
351  if not assertion then
352    if user_msg then
353      error(base_msg..": "..user_msg, 3)
354    else
355      error(base_msg.."!", 3)
356    end
357  end
358end
359
360-------------------------------------------
361-- Checks the msg argument in assert_xxx --
362-------------------------------------------
363
364function check_msg(name, msg)
365  orig_assert(is_string(name))
366  if not (is_nil(msg) or is_string(msg)) then
367    error("lunit."..name.."() expects the optional message as a string but it was a "..type(msg).."!" ,3)
368  end
369end
370
371
372
373
374-------------------------------------
375-- Creates a new TestCase 'Object' --
376-------------------------------------
377
378function TestCase(name)
379  do_assert(is_string(name), "lunit.TestCase() needs a string as an argument")
380  local tc = {
381    __lunit_name = name;
382    __lunit_setup = nil;
383    __lunit_tests = { };
384    __lunit_teardown = nil;
385  }
386  setmetatable(tc, tc_mt)
387  table.insert(testcases, tc)
388  return tc
389end
390
391tc_mt = {
392  __newindex = function(tc, key, value)
393    rawset(tc, key, value)
394    if is_string(key) and is_function(value) then
395      local name = string.lower(key)
396      if string.find(name, "^test") or string.find(name, "test$") then
397        table.insert(tc.__lunit_tests, key)
398      elseif name == "setup" then
399        tc.__lunit_setup = value
400      elseif name == "teardown" then
401        tc.__lunit_teardown = value
402      end
403    end
404  end
405}
406
407
408
409-----------------------------------------
410-- Wrap Functions in a TestCase object --
411-----------------------------------------
412
413function wrap(name, ...)
414  if is_function(name) then
415    table.insert({...}, 1, name)
416    name = "Anonymous Testcase"
417  end
418 
419  local tc = TestCase(name)
420  for index, test in ipairs({...}) do
421    tc["Test #"..index] = test
422  end
423  return tc
424end
425
426
427
428
429
430
431----------------------------------
432-- Runs the complete Test Suite --
433----------------------------------
434
435function run()
436 
437  ---------------------------
438  -- Initialize statistics --
439  ---------------------------
440 
441  stats.testcases = 0   -- Total number of Test Cases
442  stats.tests = 0   -- Total number of all Tests in all Test Cases
443  stats.run = 0      -- Number of Tests run
444  stats.notrun = 0   -- Number of Tests not run
445  stats.failed = 0   -- Number of Tests failed
446  stats.warnings = 0   -- Number of Warnings (teardown)
447  stats.errors = 0   -- Number of Errors (setup)
448  stats.passed = 0   -- Number of Test passed
449  stats.assertions = 0   -- Number of all assertions made in all Test in all Test Cases
450 
451  --------------------------------
452  -- Count Test Cases and Tests --
453  --------------------------------
454 
455  stats.testcases = table.getn(testcases)
456 
457  for _, tc in ipairs(testcases) do
458    stats_inc("tests" , table.getn(tc.__lunit_tests))
459  end
460 
461  ------------------
462  -- Print Header --
463  ------------------
464 
465  print()
466  print("#### Test Suite with "..stats.tests.." Tests in "..stats.testcases.." Test Cases loaded.")
467 
468  ------------------------
469  -- Run all Test Cases --
470  ------------------------
471 
472  for _, tc in ipairs(testcases) do
473    run_testcase(tc)
474  end
475 
476  ------------------
477  -- Print Footer --
478  ------------------
479 
480  print()
481  print("#### Test Suite finished.")
482 
483  local msg_assertions = stats.assertions.." Assertions checked. "
484  local msg_passed     = stats.passed == stats.tests and "All Tests passed" or  stats.passed.." Tests passed"
485  local msg_failed     = stats.failed > 0 and ", "..stats.failed.." failed" or ""
486  local msg_run          = stats.notrun > 0 and ", "..stats.notrun.." not run" or ""
487  local msg_warn       = stats.warnings > 0 and ", "..stats.warnings.." warnings" or ""
488 
489  print()
490  print(msg_assertions..msg_passed..msg_failed..msg_run..msg_warn.."!")
491 
492  -----------------
493  -- Return code --
494  -----------------
495 
496  if stats.passed == stats.tests then
497    return 0
498  else
499    return 1
500  end
501end
502
503
504
505
506-----------------------------
507-- Runs a single Test Case --
508-----------------------------
509
510function run_testcase(tc)
511 
512  orig_assert(is_table(tc))
513  orig_assert(is_table(tc.__lunit_tests))
514  orig_assert(is_string(tc.__lunit_name))
515  orig_assert(is_nil(tc.__lunit_setup) or is_function(tc.__lunit_setup))
516  orig_assert(is_nil(tc.__lunit_teardown) or is_function(tc.__lunit_teardown))
517 
518  ----------------------------------
519  -- Protected call to a function --
520  ----------------------------------
521 
522  local function call(errprefix, func)
523    orig_assert(is_string(errprefix))
524    orig_assert(is_function(func))
525    local ok, errmsg = xpcall(function() func(tc) end, traceback)
526    if not ok then
527      print()
528      print(errprefix..": "..errmsg)
529    end
530    return ok
531  end
532 
533  ------------------------------------
534  -- Calls setup() on the Test Case --
535  ------------------------------------
536 
537  local function setup(testname)
538    if tc.__lunit_setup then
539      return call("ERROR: "..testname..": setup() failed", tc.__lunit_setup)
540    else
541      return true
542    end
543  end
544 
545  ------------------------------------------
546  -- Calls a single Test on the Test Case --
547  ------------------------------------------
548 
549  local function run(testname)
550    orig_assert(is_string(testname))
551    orig_assert(is_function(tc[testname]))
552    local ok = call("FAIL: "..testname, tc[testname])
553    if not ok then
554      stats_inc("failed")
555    else
556      stats_inc("passed")
557    end
558    return ok
559  end
560 
561  ---------------------------------------
562  -- Calls teardown() on the Test Case --
563  ---------------------------------------
564 
565  local function teardown(testname)
566     if tc.__lunit_teardown then
567       if not call("WARNING: "..testname..": teardown() failed", tc.__lunit_teardown) then
568         stats_inc("warnings")
569       end
570     end
571  end
572 
573  ---------------------------------
574  -- Run all Tests on a TestCase --
575  ---------------------------------
576 
577  print()
578  print("#### Running '"..tc.__lunit_name.."' ("..table.getn(tc.__lunit_tests).." Tests)...")
579 
580  for _, testname in ipairs(tc.__lunit_tests) do
581    if setup(testname) then
582      run(testname)
583      stats_inc("run")
584      teardown(testname)
585    else
586      print("WARN: Skipping '"..testname.."'...")
587      stats_inc("notrun")
588    end
589  end
590 
591end
592
593
594
595
596---------------------
597-- Import function --
598---------------------
599
600function import(name)
601 
602  do_assert(is_string(name), "lunit.import() expects a single string as argument")
603 
604  local user_env = getfenv(2)
605 
606  --------------------------------------------------
607  -- Installs a specific function in the user env --
608  --------------------------------------------------
609 
610  local function install(funcname)
611    user_env[funcname] = P[funcname]
612  end
613 
614 
615  ----------------------------------------------------------
616  -- Install functions matching a pattern in the user env --
617  ----------------------------------------------------------
618 
619  local function install_pattern(pattern)
620    for funcname, _ in pairs(P) do
621      if string.find(funcname, pattern) then
622        install(funcname)
623      end
624    end
625  end
626 
627  ------------------------------------------------------------
628  -- Installs assert() and all assert_xxx() in the user env --
629  ------------------------------------------------------------
630 
631  local function install_asserts()
632    install_pattern("^assert.*")
633  end
634 
635  -------------------------------------------
636  -- Installs all is_xxx() in the user env --
637  -------------------------------------------
638 
639  local function install_tests()
640    install_pattern("^is_.+")
641  end
642 
643  if name == "asserts" or name == "assertions" then
644    install_asserts()
645  elseif name == "tests" or name == "checks" then
646    install_tests()
647  elseif name == "all" then
648    install_asserts()
649    install_tests()
650    install("TestCase")
651  elseif string.find(name, "^assert.*") and P[name] then
652    install(name)
653  elseif string.find(name, "^is_.+") and P[name] then
654    install(name)
655  elseif name == "TestCase" then
656    install("TestCase")
657  else
658    error("luniit.import(): invalid function '"..name.."' to import", 2)
659  end
660end
661
662
663
664
665--------------------------------------------------
666-- Installs a private environment on the caller --
667--------------------------------------------------
668
669function setprivfenv()
670  local new_env = { }
671  local new_env_mt = { __index = getfenv(2) }
672  setmetatable(new_env, new_env_mt)
673  setfenv(2, new_env)
674end
675
676
677
678
679--------------------------------------------------
680-- Increments a counter in the statistics table -- 
681--------------------------------------------------
682
683function stats_inc(varname, value)
684  orig_assert(is_table(stats))
685  orig_assert(is_string(varname))
686  orig_assert(is_nil(value) or is_number(value))
687  if not stats[varname] then return end
688  stats[varname] = stats[varname] + (value or 1)
689end
690
691
692
693
trunk/3rdparty/lsqlite3/test.lua
r0r242834
1require("lsqlite3")
2
3local width = 78
4local function line(pref, suff)
5    pref = pref or ''
6    suff = suff or ''
7    local len = width - 2 - string.len(pref) - string.len(suff)
8    print(pref .. string.rep('-', len) .. suff)
9end
10
11local db, vm
12local assert_, assert = assert, function (test)
13    if (not test) then
14        error(db:errmsg(), 2)
15    end
16end
17
18line(sqlite3.version())
19
20os.remove('test.db')
21db = sqlite3.open('test.db')
22
23line(nil, 'db:exec')
24db:exec('CREATE TABLE t(a, b)')
25
26line(nil, 'prepare')
27vm = db:prepare('insert into t values(?, :bork)')
28assert(vm, db:errmsg())
29assert(vm:bind_parameter_count() == 2)
30assert(vm:bind_values(2, 4) == sqlite3.OK)
31assert(vm:step() == sqlite3.DONE)
32assert(vm:reset() == sqlite3.OK)
33assert(vm:bind_names{ 'pork', bork = 'nono' } == sqlite3.OK)
34assert(vm:step() == sqlite3.DONE)
35assert(vm:reset() == sqlite3.OK)
36assert(vm:bind_names{ bork = 'sisi' } == sqlite3.OK)
37assert(vm:step() == sqlite3.DONE)
38assert(vm:reset() == sqlite3.OK)
39assert(vm:bind_names{ 1 } == sqlite3.OK)
40assert(vm:step() == sqlite3.DONE)
41assert(vm:finalize() == sqlite3.OK)
42
43line("select * from t", 'db:exec')
44
45assert(db:exec('select * from t', function (ud, ncols, values, names)
46    --table.setn(values, 2)
47    print(unpack(values))
48    return sqlite3.OK
49end) == sqlite3.OK)
50
51line("select * from t", 'db:prepare')
52
53vm = db:prepare('select * from t')
54assert(vm, db:errmsg())
55print(vm:get_unames())
56while (vm:step() == sqlite3.ROW) do
57    print(vm:get_uvalues())
58end
59assert(vm:finalize() == sqlite3.OK)
60
61
62
63line('udf', 'scalar')
64
65local function do_query(sql)
66    local r
67    local vm = db:prepare(sql)
68    assert(vm, db:errmsg())
69    print('====================================')
70    print(vm:get_unames())
71    print('------------------------------------')
72    r = vm:step()
73    while (r == sqlite3.ROW) do
74        print(vm:get_uvalues())
75        r = vm:step()
76    end
77    assert(r == sqlite3.DONE)
78    assert(vm:finalize() == sqlite3.OK)
79    print('====================================')
80end
81
82local function udf1_scalar(ctx, v)
83    local ud = ctx:user_data()
84    ud.r = (ud.r or '') .. tostring(v)
85    ctx:result_text(ud.r)
86end
87
88db:create_function('udf1', 1, udf1_scalar, { })
89do_query('select udf1(a) from t')
90
91
92line('udf', 'aggregate')
93
94local function udf2_aggregate(ctx, ...)
95    local ud = ctx:get_aggregate_data()
96    if (not ud) then
97        ud = {}
98        ctx:set_aggregate_data(ud)
99    end
100    ud.r = (ud.r or 0) + 2
101end
102
103local function udf2_aggregate_finalize(ctx, v)
104    local ud = ctx:get_aggregate_data()
105    ctx:result_number(ud and ud.r or 0)
106end
107
108db:create_aggregate('udf2', 1, udf2_aggregate, udf2_aggregate_finalize, { })
109do_query('select udf2(a) from t')
110
111if (true) then
112    line(nil, '100 insert exec')
113    db:exec('delete from t')
114    local t = os.time()
115    for i = 1, 100 do
116        db:exec('insert into t values('..i..', '..(i * 2 * -1^i)..')')
117    end
118    print('elapsed: '..(os.time() - t))
119    do_query('select count(*) from t')
120
121    line(nil, '100000 insert exec T')
122    db:exec('delete from t')
123    local t = os.time()
124    db:exec('begin')
125    for i = 1, 100000 do
126        db:exec('insert into t values('..i..', '..(i * 2 * -1^i)..')')
127    end
128    db:exec('commit')
129    print('elapsed: '..(os.time() - t))
130    do_query('select count(*) from t')
131
132    line(nil, '100000 insert prepare/bind T')
133    db:exec('delete from t')
134    local t = os.time()
135    local vm = db:prepare('insert into t values(?, ?)')
136    db:exec('begin')
137    for i = 1, 100000 do
138        vm:bind_values(i, i * 2 * -1^i)
139        vm:step()
140        vm:reset()
141    end
142    vm:finalize()
143    db:exec('commit')
144    print('elapsed: '..(os.time() - t))
145    do_query('select count(*) from t')
146
147end
148
149line(nil, "db:close")
150
151assert(db:close() == sqlite3.OK)
152
153line(sqlite3.version())
trunk/3rdparty/lsqlite3/tests-sqlite3.lua
r0r242834
1
2--[[--------------------------------------------------------------------------
3
4    Author: Michael Roth <mroth@nessie.de>
5
6    Copyright (c) 2004, 2005 Michael Roth <mroth@nessie.de>
7
8    Permission is hereby granted, free of charge, to any person
9    obtaining a copy of this software and associated documentation
10    files (the "Software"), to deal in the Software without restriction,
11    including without limitation the rights to use, copy, modify, merge,
12    publish, distribute, sublicense, and/or sell copies of the Software,
13    and to permit persons to whom the Software is furnished to do so,
14    subject to the following conditions:
15
16    The above copyright notice and this permission notice shall be
17    included in all copies or substantial portions of the Software.
18
19    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
27--]]--------------------------------------------------------------------------
28
29
30require "lsqlite3"
31
32require "lunit"
33
34lunit.setprivfenv()
35lunit.import "assertions"
36lunit.import "checks"
37
38
39
40
41
42
43-------------------------------
44-- Basic open and close test --
45-------------------------------
46
47lunit.wrap("open_memory", function()
48  local db = assert_userdata( sqlite3.open_memory() )
49  assert( db:close() )
50end)
51
52lunit.wrap("open", function()
53  local filename = "/tmp/__lua-sqlite3-20040906135849." .. os.time()
54  local db = assert_userdata( sqlite3.open(filename) )
55  assert( db:close() )
56  os.remove(filename)
57end)
58
59
60
61-------------------------------------
62-- Presence of db member functions --
63-------------------------------------
64
65local db_funcs = lunit.TestCase("Database Member Functions")
66
67function db_funcs:setup()
68  self.db = assert( sqlite3.open_memory() )
69end
70
71function db_funcs:teardown()
72  assert( self.db:close() )
73end
74
75function db_funcs:test()
76  local db = self.db
77  assert_function( db.close )
78  assert_function( db.exec )
79--e  assert_function( db.irows )
80  assert_function( db.rows )
81--e  assert_function( db.cols )
82--e  assert_function( db.first_irow )
83--e  assert_function( db.first_row )
84--e  assert_function( db.first_cols )
85  assert_function( db.prepare )
86  assert_function( db.interrupt )
87  assert_function( db.last_insert_rowid )
88  assert_function( db.changes )
89  assert_function( db.total_changes )
90end
91
92
93
94---------------------------------------
95-- Presence of stmt member functions --
96---------------------------------------
97
98local stmt_funcs = lunit.TestCase("Statement Member Functions")
99
100function stmt_funcs:setup()
101  self.db = assert( sqlite3.open_memory() )
102  self.stmt = assert( self.db:prepare("CREATE TABLE test (id, content)") )
103end
104
105function stmt_funcs:teardown()
106--e-  assert( self.stmt:close() )
107  assert( self.stmt:finalize() ) --e+
108  assert( self.db:close() )
109end
110
111function stmt_funcs:test()
112  local stmt = self.stmt
113--e  assert_function( stmt.close )
114  assert_function( stmt.reset )
115--e  assert_function( stmt.exec )
116  assert_function( stmt.bind )
117--e  assert_function( stmt.irows )
118--e  assert_function( stmt.rows )
119--e  assert_function( stmt.cols )
120--e  assert_function( stmt.first_irow )
121--e  assert_function( stmt.first_row )
122--e  assert_function( stmt.first_cols )
123--e  assert_function( stmt.column_names )
124--e  assert_function( stmt.column_decltypes )
125--e  assert_function( stmt.column_count )
126--e +
127  assert_function( stmt.isopen )
128  assert_function( stmt.step )
129  assert_function( stmt.reset )
130  assert_function( stmt.finalize )
131  assert_function( stmt.columns )
132  assert_function( stmt.bind )
133  assert_function( stmt.bind_values )
134  assert_function( stmt.bind_names )
135  assert_function( stmt.bind_blob )
136  assert_function( stmt.bind_parameter_count )
137  assert_function( stmt.bind_parameter_name )
138  assert_function( stmt.get_value )
139  assert_function( stmt.get_values )
140  assert_function( stmt.get_name )
141  assert_function( stmt.get_names )
142  assert_function( stmt.get_type )
143  assert_function( stmt.get_types )
144  assert_function( stmt.get_uvalues )
145  assert_function( stmt.get_unames )
146  assert_function( stmt.get_utypes )
147  assert_function( stmt.get_named_values )
148  assert_function( stmt.get_named_types )
149  assert_function( stmt.idata )
150  assert_function( stmt.inames )
151  assert_function( stmt.itypes )
152  assert_function( stmt.data )
153  assert_function( stmt.type )
154--e +
155end
156
157
158
159------------------
160-- Tests basics --
161------------------
162
163local basics = lunit.TestCase("Basics")
164
165function basics:setup()
166  self.db = assert_userdata( sqlite3.open_memory() )
167end
168
169function basics:teardown()
170  assert_number( self.db:close() )
171end
172
173function basics:create_table()
174  assert_number( self.db:exec("CREATE TABLE test (id, name)") )
175end
176
177function basics:drop_table()
178  assert_number( self.db:exec("DROP TABLE test") )
179end
180
181function basics:insert(id, name)
182  assert_number( self.db:exec("INSERT INTO test VALUES ("..id..", '"..name.."')") )
183end
184
185function basics:update(id, name)
186  assert_number( self.db:exec("UPDATE test SET name = '"..name.."' WHERE id = "..id) )
187end
188
189function basics:test_create_drop()
190  self:create_table()
191  self:drop_table()
192end
193
194function basics:test_multi_create_drop()
195  self:create_table()
196  self:drop_table()
197  self:create_table()
198  self:drop_table()
199end
200
201function basics:test_insert()
202  self:create_table()
203  self:insert(1, "Hello World")
204  self:insert(2, "Hello Lua")
205  self:insert(3, "Hello sqlite3")
206end
207
208function basics:test_update()
209  self:create_table()
210  self:insert(1, "Hello Home")
211  self:insert(2, "Hello Lua")
212  self:update(1, "Hello World")
213end
214
215
216---------------------------------
217-- Statement Column Info Tests --
218---------------------------------
219
220lunit.wrap("Column Info Test", function()
221  local db = assert_userdata( sqlite3.open_memory() )
222  assert_number( db:exec("CREATE TABLE test (id INTEGER, name TEXT)") )
223  local stmt = assert_userdata( db:prepare("SELECT * FROM test") )
224 
225  assert_equal(2, stmt:columns(), "Wrong number of columns." )
226 
227  local names = assert_table( stmt:get_names() )
228  assert_equal(2, #(names), "Wrong number of names.")
229  assert_equal("id", names[1] )
230  assert_equal("name", names[2] )
231 
232  local types = assert_table( stmt:get_types() )
233  assert_equal(2, #(types), "Wrong number of declaration types.")
234  assert_equal("INTEGER", types[1] )
235  assert_equal("TEXT", types[2] )
236 
237  assert_equal( sqlite3.OK, stmt:finalize() )
238  assert_equal( sqlite3.OK, db:close() )
239end)
240
241
242
243---------------------
244-- Statement Tests --
245---------------------
246
247st = lunit.TestCase("Statement Tests")
248
249function st:setup()
250  self.db = assert( sqlite3.open_memory() )
251  assert_equal( sqlite3.OK, self.db:exec("CREATE TABLE test (id, name)") )
252  assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (1, 'Hello World')") )
253  assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (2, 'Hello Lua')") )
254  assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (3, 'Hello sqlite3')") )
255end
256
257function st:teardown()
258  assert_equal( sqlite3.OK, self.db:close() )
259end
260
261function st:check_content(expected)
262  local stmt = assert( self.db:prepare("SELECT * FROM test ORDER BY id") )
263  local i = 0
264  for row in stmt:rows() do
265    i = i + 1
266    assert( i <= #(expected), "Too many rows." )
267    assert_equal(2, #(row), "Two result column expected.")
268    assert_equal(i, row[1], "Wrong 'id'.")
269    assert_equal(expected[i], row[2], "Wrong 'name'.")
270  end
271  assert_equal( #(expected), i, "Too few rows." )
272  assert_number( stmt:finalize() )
273end
274
275function st:test_setup()
276  assert_pass(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3" } end)
277  assert_error(function() self:check_content{ "Hello World", "Hello Lua" } end)
278  assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "To much" } end)
279  assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Wrong" } end)
280  assert_error(function() self:check_content{ "Hello World", "Wrong", "Hello sqlite3" } end)
281  assert_error(function() self:check_content{ "Wrong", "Hello Lua", "Hello sqlite3" } end)
282end
283
284function st:test_questionmark_args()
285  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (?, ?)")  )
286  assert_number( stmt:bind_values(0, "Test") )
287  assert_error(function() stmt:bind_values("To few") end)
288  assert_error(function() stmt:bind_values(0, "Test", "To many") end)
289end
290
291function st:test_questionmark()
292  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (?, ?)")  )
293  assert_number( stmt:bind_values(4, "Good morning") )
294  assert_number( stmt:step() )
295  assert_number( stmt:reset() )
296  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" }
297  assert_number( stmt:bind_values(5, "Foo Bar") )
298  assert_number( stmt:step() )
299  assert_number( stmt:reset() )
300  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
301  assert_number( stmt:finalize() )
302end
303
304--[===[
305function st:test_questionmark_multi()
306  local stmt = assert_userdata( self.db:prepare([[
307    INSERT INTO test VALUES (?, ?); INSERT INTO test VALUES (?, ?) ]]))
308  assert( stmt:bind_values(5, "Foo Bar", 4, "Good morning") )
309  assert_number( stmt:step() )
310  assert_number( stmt:reset() )
311  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
312  assert_number( stmt:finalize() )
313end
314]===]
315
316function st:test_identifiers()
317  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)")  )
318  assert_number( stmt:bind_values(4, "Good morning") )
319  assert_number( stmt:step() )
320  assert_number( stmt:reset() )
321  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" }
322  assert_number( stmt:bind_values(5, "Foo Bar") )
323  assert_number( stmt:step() )
324  assert_number( stmt:reset() )
325  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
326  assert_number( stmt:finalize() )
327end
328
329--[===[
330function st:test_identifiers_multi()
331  local stmt = assert_table( self.db:prepare([[
332    INSERT INTO test VALUES (:id1, :name1); INSERT INTO test VALUES (:id2, :name2) ]]))
333  assert( stmt:bind_values(5, "Foo Bar", 4, "Good morning") )
334  assert( stmt:exec() )
335  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
336end
337]===]
338
339function st:test_identifiers_names()
340  --local stmt = assert_userdata( self.db:prepare({"name", "id"}, "INSERT INTO test VALUES (:id, $name)")  )
341  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, $name)")  )
342  assert_number( stmt:bind_names({name="Good morning", id=4}) )
343  assert_number( stmt:step() )
344  assert_number( stmt:reset() )
345  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" }
346  assert_number( stmt:bind_names({name="Foo Bar", id=5}) )
347  assert_number( stmt:step() )
348  assert_number( stmt:reset() )
349  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
350  assert_number( stmt:finalize() )
351end
352
353--[===[
354function st:test_identifiers_multi_names()
355  local stmt = assert_table( self.db:prepare( {"name", "id1", "id2"},[[
356    INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]]))
357  assert( stmt:bind_values("Hoho", 4, 5) )
358  assert( stmt:exec() )
359  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" }
360end
361]===]
362
363function st:test_colon_identifiers_names()
364  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)")  )
365  assert_number( stmt:bind_names({name="Good morning", id=4}) )
366  assert_number( stmt:step() )
367  assert_number( stmt:reset() )
368  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" }
369  assert_number( stmt:bind_names({name="Foo Bar", id=5}) )
370  assert_number( stmt:step() )
371  assert_number( stmt:reset() )
372  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
373  assert_number( stmt:finalize() )
374end
375
376--[===[
377function st:test_colon_identifiers_multi_names()
378  local stmt = assert_table( self.db:prepare( {":name", ":id1", ":id2"},[[
379    INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]]))
380  assert( stmt:bind_values("Hoho", 4, 5) )
381  assert( stmt:exec() )
382  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" }
383end
384
385
386function st:test_dollar_identifiers_names()
387  local stmt = assert_table( self.db:prepare({"$name", "$id"}, "INSERT INTO test VALUES (:id, $name)")  )
388  assert_table( stmt:bind_values("Good morning", 4) )
389  assert_table( stmt:exec() )
390  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" }
391  assert_table( stmt:bind_values("Foo Bar", 5) )
392  assert_table( stmt:exec() )
393  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" }
394end
395
396function st:test_dollar_identifiers_multi_names()
397  local stmt = assert_table( self.db:prepare( {"$name", "$id1", "$id2"},[[
398    INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]]))
399  assert( stmt:bind_values("Hoho", 4, 5) )
400  assert( stmt:exec() )
401  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" }
402end
403]===]
404
405function st:test_bind_by_names()
406  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)")  )
407  local args = { }
408  args.id = 5
409  args.name = "Hello girls"
410  assert( stmt:bind_names(args) )
411  assert_number( stmt:step() )
412  assert_number( stmt:reset() )
413  args.id = 4
414  args.name = "Hello boys"
415  assert( stmt:bind_names(args) )
416  assert_number( stmt:step() )
417  assert_number( stmt:reset() )
418  self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3",  "Hello boys", "Hello girls" }
419  assert_number( stmt:finalize() )
420end
421
422
423
424--------------------------------
425-- Tests binding of arguments --
426--------------------------------
427
428b = lunit.TestCase("Binding Tests")
429
430function b:setup()
431  self.db = assert( sqlite3.open_memory() )
432  assert_number( self.db:exec("CREATE TABLE test (id, name, u, v, w, x, y, z)") )
433end
434
435function b:teardown()
436  assert_number( self.db:close() )
437end
438
439function b:test_auto_parameter_names()
440  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES(:a, $b, :a2, :b2, $a, :b, $a3, $b3)") )
441  local parameters = assert_number( stmt:bind_parameter_count() )
442  assert_equal( 8, parameters )
443  assert_equal( ":a", stmt:bind_parameter_name(1) )
444  assert_equal( "$b", stmt:bind_parameter_name(2) )
445  assert_equal( ":a2", stmt:bind_parameter_name(3) )
446  assert_equal( ":b2", stmt:bind_parameter_name(4) )
447  assert_equal( "$a", stmt:bind_parameter_name(5) )
448  assert_equal( ":b", stmt:bind_parameter_name(6) )
449  assert_equal( "$a3", stmt:bind_parameter_name(7) )
450  assert_equal( "$b3", stmt:bind_parameter_name(8) )
451end
452
453function b:test_auto_parameter_names()
454  local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES($a, $b, $a2, $b2, $a, $b, $a3, $b3)") )
455  local parameters = assert_number( stmt:bind_parameter_count() )
456  assert_equal( 6, parameters )
457  assert_equal( "$a", stmt:bind_parameter_name(1) )
458  assert_equal( "$b", stmt:bind_parameter_name(2) )
459  assert_equal( "$a2", stmt:bind_parameter_name(3) )
460  assert_equal( "$b2", stmt:bind_parameter_name(4) )
461  assert_equal( "$a3", stmt:bind_parameter_name(5) )
462  assert_equal( "$b3", stmt:bind_parameter_name(6) )
463end
464
465function b:test_no_parameter_names_1()
466  local stmt = assert_userdata( self.db:prepare([[ SELECT * FROM test ]]))
467  local parameters = assert_number( stmt:bind_parameter_count() )
468  assert_equal( 0, (parameters) )
469end
470
471function b:test_no_parameter_names_2()
472  local stmt = assert_userdata( self.db:prepare([[ INSERT INTO test VALUES(?, ?, ?, ?, ?, ?, ?, ?) ]]))
473  local parameters = assert_number( stmt:bind_parameter_count() )
474  assert_equal( 8, (parameters) )
475  assert_nil( stmt:bind_parameter_name(1) )
476end
477
478
479
480
481
482
483
484--------------------------------------------
485-- Tests loop break and statement reusage --
486--------------------------------------------
487
488
489
490----------------------------
491-- Test for bugs reported --
492----------------------------
493
494bug = lunit.TestCase("Bug-Report Tests")
495
496function bug:setup()
497  self.db = assert( sqlite3.open_memory() )
498end
499
500function bug:teardown()
501  assert_number( self.db:close() )
502end
503
504--[===[
505function bug:test_1()
506  self.db:exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
507 
508  local query = assert_userdata( self.db:prepare("SELECT id FROM test WHERE value=?") )
509 
510  assert_table ( query:bind_values("1") )
511  assert_nil   ( query:first_cols() )
512  assert_table ( query:bind_values("2") )
513  assert_nil   ( query:first_cols() )
514end
515]===]
516
517function bug:test_nils()   -- appeared in lua-5.1 (holes in arrays)
518  local function check(arg1, arg2, arg3, arg4, arg5)
519    assert_equal(1, arg1)
520    assert_equal(2, arg2)
521    assert_nil(arg3)
522    assert_equal(4, arg4)
523    assert_nil(arg5)
524  end
525 
526  self.db:create_function("test_nils", 5, function(arg1, arg2, arg3, arg4, arg5)
527    check(arg1, arg2, arg3, arg4, arg5)
528  end, {})
529 
530  assert_number( self.db:exec([[ SELECT test_nils(1, 2, NULL, 4, NULL) ]]) )
531 
532  for arg1, arg2, arg3, arg4, arg5 in self.db:urows([[ SELECT 1, 2, NULL, 4, NULL ]])
533  do check(arg1, arg2, arg3, arg4, arg5)
534  end
535 
536  for row in self.db:rows([[ SELECT 1, 2, NULL, 4, NULL ]])
537  do assert_table( row )
538     check(row[1], row[2], row[3], row[4], row[5])
539  end
540end
541
542----------------------------
543-- Test for collation fun --
544----------------------------
545
546colla = lunit.TestCase("Collation Tests")
547
548function colla:setup()
549    local function collate(s1,s2)
550        -- if p then print("collation callback: ",s1,s2) end
551        s1=s1:lower()
552        s2=s2:lower()
553        if s1==s2 then return 0
554        elseif s1<s2 then return -1
555        else return 1 end
556    end
557    self.db = assert( sqlite3.open_memory() )
558    assert_nil(self.db:create_collation('CINSENS',collate))
559    self.db:exec[[
560      CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS);
561      INSERT INTO test VALUES(NULL,'hello world');
562      INSERT INTO test VALUES(NULL,'Buenos dias');
563      INSERT INTO test VALUES(NULL,'HELLO WORLD');
564      INSERT INTO test VALUES(NULL,'Guten Tag');
565      INSERT INTO test VALUES(NULL,'HeLlO WoRlD');
566      INSERT INTO test VALUES(NULL,'Bye for now');
567    ]]
568end
569
570function colla:teardown()
571  assert_number( self.db:close() )
572end
573
574function colla:test()
575    --for row in db:nrows('SELECT * FROM test') do
576    --  print(row.id,row.content)
577    --end
578    local n = 0
579    for row in self.db:nrows('SELECT * FROM test WHERE content="hElLo wOrLd"') do
580      -- print(row.id,row.content)
581      assert_equal (row.content:lower(), "hello world")
582      n = n + 1
583    end
584    assert_equal (n, 3)
585end
586
587lunit.run()
trunk/src/lib/lib.mak
r242833r242834
513513   $(LIBOBJ)/lua/ltablib.o \
514514   $(LIBOBJ)/lua/loadlib.o \
515515   $(LIBOBJ)/lua/linit.o \
516   $(LIBOBJ)/lua/lib/lsqlite3.o \
516   $(LIBOBJ)/lua/lsqlite3/lsqlite3.o \
517517
518518$(OBJ)/liblua.a: $(LUAOBJS)
519519
r242833r242834
530530   @echo Compiling $<...
531531   $(CC) $(CDEFS) $(CCOMFLAGS) $(CONLYFLAGS) -DLUA_COMPAT_ALL $(LUA_FLAGS) -c $< -o $@
532532
533$(LIBOBJ)/lua/lsqlite3/%.o: $(3RDPARTY)/lsqlite3/%.c | $(OSPREBUILD)
534   @echo Compiling $<...
535   $(CC) $(CDEFS) $(CCOMFLAGS) $(CONLYFLAGS) -DLUA_COMPAT_ALL $(LUA_FLAGS) -c $< -o $@
536
533537#-------------------------------------------------
534538# web library objects
535539#-------------------------------------------------


Previous 199869 Revisions Next


© 1997-2024 The MAME Team