poco-1.3.6p1-all/0000755000076500001200000000000011313735450014250 5ustar guenteradmin00000000000000poco-1.3.6p1-all/build/0000755000076500001200000000000011313735443015351 5ustar guenteradmin00000000000000poco-1.3.6p1-all/build/config/0000755000076500001200000000000011313735443016616 5ustar guenteradmin00000000000000poco-1.3.6p1-all/build/config/AIX0000644000076500001200000000304311313735443017162 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/AIX#1 $ # # AIX # # Make settings for AIX 5.x/xlC 8.0 # # # # General Settings # LINKMODE = SHARED # # Define Tools # CC = xlc_r CXX = xlC_r LINK = $(CXX) LIB = ar -cr -X32_64 RANLIB = ranlib SHLIB = $(CXX) -qmkshrobj -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = strip -X32_64 DEP = $(POCO_BASE)/build/script/makedepend.xlC SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -qobjmodel=compat -qfuncsect CFLAGS32 = -q32 CFLAGS64 = -q64 CXXFLAGS = -qrtti=all -qobjmodel=compat -qnamemangling=v5 -qfuncsect CXXFLAGS32 = -q32 CXXFLAGS64 = -q64 SHLIBFLAGS = -qtwolink -bh:5 -bnoipath -blibpath:/usr/lib:/lib -blibsuff:so -bautoexp -bnoentry -bM:SRE SHLIBFLAGS32 = -q32 SHLIBFLAGS64 = -q64 LINKFLAGS = -qtwolink -bh:5 -bnoipath -blibpath:/usr/lib:/lib -blibsuff:so -brtl LINKFLAGS32 = -q32 LINKFLAGS64 = -q64 STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = SHAREDOPT_CC = -qpic SHAREDOPT_CXX = -qpic SHAREDOPT_LINK = DEBUGOPT_CC = -g -D_DEBUG -qfullpath DEBUGOPT_CXX = -g -D_DEBUG -qfullpath -qnoinline DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG -qmaxmem=16384 RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lC_r -lc_r poco-1.3.6p1-all/build/config/Angstrom0000644000076500001200000000263611313735443020342 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/Angstrom#1 $ # # Angstrom # # Make settings for Open Embedded/Angstrom # # # General Settings # LINKMODE = SHARED POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = armv5te TOOL = arm-angstrom-linux-gnueabi # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) STRIP = $(TOOL)-strip LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O3 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/ARM-Linux0000644000076500001200000000331011313735443020252 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/ARM-Linux#3 $ # # ARM-Linux # # Make settings for ARM Linux/gcc 2.95.3 (cross-compile, using STLport 4.6.2) # # # General Settings # LINKMODE = SHARED POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = ARM STLPORT_INCLUDE = /usr/local/include/stlport STLPORT_LIB = /usr/local/lib OPENSSL_INCLUDE = /usr/local/arm/2.95.3/include OPENSSL_LIB = /usr/local/arm/2.95.3/lib TOOL = arm-linux # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = $(TOOL)-strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -I$(STLPORT_INCLUDE) -I$(OPENSSL_INCLUDE) -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT # # System Specific Libraries # SYSLIBS = -L$(STLPORT_LIB) -L$(OPENSSL_LIB) -lstlport_arm-linux-gcc -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/CEGCCARM0000644000076500001200000000324411313735443017710 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/CEGCCARM#1 $ # # CYGWIN # # Make settings for Cygwin on WinXP/gcc 3.4 # for cross compiling to WinCE ARM with CEGCC # # # # General Settings # LINKMODE = SHARED POCO_TARGET_OSNAME = WinCE POCO_TARGET_OSARCH = ARM TOOLPATH = /opt/cegcc TOOL = /opt/cegcc/bin/arm-wince-cegcc- # # Define Tools # CC = $(TOOL)gcc CXX = $(TOOL)g++ LINK = $(CXX) LIB = $(TOOL)ar -cr RANLIB = $(TOOL)ranlib SHLIB = $(CXX) -shared -o $@ -Wl,--out-implib=$(dir $@)$(subst ce,lib,$(notdir $@)).a -Wl,--export-all-symbols -Wl,--enable-auto-import SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = $(TOOL)strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # LIBPREFIX = ce SHAREDLIBEXT = .$(target_version).dll SHAREDLIBLINKEXT = .dll # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = SHAREDOPT_CXX = SHAREDOPT_LINK = DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -DPOCO_NO_FPENVIRONMENT -DPOCO_OS_FAMILY_WINDOWS -DNOMINMAX -D_WIN32 -D_WIN32_WCE=0x0420 -D_WIN32_IE=0x0420 -DNO_GZCOMPRESS -DPOCO_WIN32_UTF8 -DUNICODE -DPOCO_DLL -DFoundation_EXPORTS # # System Specific Libraries # SYSLIBS = -L$(TOOLPATH)/lib -L$(TOOLPATH)/arm-wince-cegcc/lib poco-1.3.6p1-all/build/config/CygLinux0000644000076500001200000000271311313735443020306 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/CygLinux#1 $ # # Linux # # Make settings for Linux 2.6/gcc 3.3 # # # # General Settings # LINKMODE = SHARED TOOL = /opt/crosstool/gcc-4.0.2-glibc-2.3.2/i686-unknown-linux-gnu/bin/i686-unknown-linux-gnu- POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = i686 # # Define Tools # CC = $(TOOL)gcc CXX = $(TOOL)g++ LINK = $(CXX) LIB = $(TOOL)ar -cr RANLIB = $(TOOL)ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = $(TOOL)strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = -Wall -Wno-sign-compare CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_REENTRANT -D_THREAD_SAFE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # # System Specific Libraries # SYSLIBS = -lpthread -ldl poco-1.3.6p1-all/build/config/CYGWIN0000644000076500001200000000247711313735443017553 0ustar guenteradmin00000000000000# # $Id$ # # CYGWIN # # Make settings for Cygwin on WinXP/gcc 3.4 # # # # General Settings, note that strip doesn't do anything on Cygwin, thus empty # LINKMODE = SHARED # # Define Tools # CC = gcc CXX = g++ LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -o $@ -Wl,--out-implib=$(dir $@)$(subst cyg,lib,$(notdir $@)).a -Wl,--export-all-symbols -Wl,--enable-auto-import SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # LIBPREFIX = cyg SHAREDLIBEXT = .$(target_version).dll SHAREDLIBLINKEXT = .dll # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = -DPOCO_NO_FPENVIRONMENT -DPOCO_NO_WSTRING -DPOCO_NO_SHAREDMEMORY CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = SHAREDOPT_CXX = SHAREDOPT_LINK = DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -DNDEBUG RELEASEOPT_CXX = -DNDEBUG RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 # # System Specific Libraries # SYSLIBS = poco-1.3.6p1-all/build/config/Darwin0000644000076500001200000000270611313735443017772 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/Darwin#8 $ # # Darwin # # Build settings for Mac OS X 10.5/10.6 (GCC 4.0.1) # The build settings defined in this file are compatible # with XCode 3.1 C++ projects. # # # General Settings # LINKMODE = SHARED # # Tools # CC = gcc-4.0 CXX = g++-4.0 LINK = $(CXX) -bind_at_load LIB = libtool -static -o RANLIB = ranlib SHLIB = $(CXX) -dynamiclib -o $@ DYLIB = $(CXX) -dynamic -bundle -read_only_relocs suppress -Wl,-bind_at_load -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .$(target_version).dylib SHAREDLIBLINKEXT = .dylib # # Compiler and Linker Flags # CFLAGS = CXXFLAGS = -Wall -Wno-sign-compare LINKFLAGS = SHLIBFLAGS = DYLIBFLAGS = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = DEBUGOPT_CC = -O0 -g -gdwarf-2 -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -O0 -g -gdwarf-2 -D_DEBUG=$(DEBUGLEVEL) -D_GLIBCXX_DEBUG=1 -D_GLIBCXX_DEBUG_PEDANTIC=1 -mfix-and-continue -fvisibility-inlines-hidden DEBUGOPT_LINK = RELEASEOPT_CC = -DNDEBUG -Os RELEASEOPT_CXX = -DNDEBUG -O2 -fvisibility-inlines-hidden RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -DPOCO_HAVE_IPv6 # # System Specific Libraries # SYSLIBS = -ldl poco-1.3.6p1-all/build/config/Darwin70000644000076500001200000000270111313735443020054 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/Darwin7#1 $ # # Darwin # # Build settings for Mac OS X 10.3 # # # General Settings # LINKMODE = SHARED # # Tools # CC = gcc CXX = c++ LINK = $(CXX) -bind_at_load LIB = libtool -static -o RANLIB = ranlib SHLIB = libtool -dynamic -flat_namespace -undefined suppress -noprebind -install_name $@ -o $@ DYLIB = ld -dynamic -bundle -read_only_relocs suppress -flat_namespace -undefined warning -noprebind -bind_at_load -o $@ /usr/lib/bundle1.o SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .$(target_version).dylib SHAREDLIBLINKEXT = .dylib # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = -Wno-long-double -fmessage-length=0 -fcoalesce-templates CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = SHAREDOPT_CC = SHAREDOPT_CXX = SHAREDOPT_LINK = DEBUGOPT_CC = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_LINK = RELEASEOPT_CC = -DNDEBUG -O2 RELEASEOPT_CXX = -DNDEBUG -O RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE # # System Specific Libraries # SYSLIBS = -lstdc++ -framework System -ldl -lcc_dynamic poco-1.3.6p1-all/build/config/Darwin_x86_640000644000076500001200000000302611313735443021004 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/Darwin_x86_64#2 $ # # Darwin_x86_64 # # Build settings for Mac OS X 10.5/10.6 (GCC 4.0.1) # The build settings defined in this file are compatible # with XCode 3.1 C++ projects. # # # General Settings # LINKMODE = SHARED # # Tools # CC = gcc-4.0 CXX = g++-4.0 LINK = $(CXX) -bind_at_load LIB = libtool -static -o RANLIB = ranlib SHLIB = $(CXX) -dynamiclib -o $@ DYLIB = $(CXX) -dynamic -bundle -read_only_relocs suppress -Wl,-bind_at_load -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .$(target_version).dylib SHAREDLIBLINKEXT = .dylib # # Compiler and Linker Flags # CFLAGS = -arch x86_64 CXXFLAGS = -arch x86_64 -Wall -Wno-sign-compare LINKFLAGS = -arch x86_64 SHLIBFLAGS = -arch x86_64 DYLIBFLAGS = -arch x86_64 STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = DEBUGOPT_CC = -O0 -g -gdwarf-2 -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -O0 -g -gdwarf-2 -D_DEBUG=$(DEBUGLEVEL) -D_GLIBCXX_DEBUG=1 -D_GLIBCXX_DEBUG_PEDANTIC=1 -mfix-and-continue -fvisibility-inlines-hidden DEBUGOPT_LINK = RELEASEOPT_CC = -DNDEBUG -Os RELEASEOPT_CXX = -DNDEBUG -O2 -fvisibility-inlines-hidden RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -DPOCO_HAVE_IPv6 # # System Specific Libraries # SYSLIBS = -ldl poco-1.3.6p1-all/build/config/DigiEL0000644000076500001200000000271011313735443017636 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/DigiEL#4 $ # # DigiEL # # Make settings for Digi Embedded Linux 4 (gcc 4.0.3, uclibc 0.9.28) # # # General Settings # LINKMODE = STATIC TOOL = arm-linux POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = armv5tejl # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = $(TOOL)-strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT -DPOCO_NO_WSTRING -DPOCO_NO_SHAREDMEMORY # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/FreeBSD0000644000076500001200000000227311313735443017757 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/FreeBSD#2 $ # # FreeBSD # # Make settings for FreeBSD 6.0/gcc 3.4 # # # # General Settings # LINKMODE = SHARED # # Define Tools # CC = gcc CXX = g++ LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.gcc STRIP = strip SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE # # System Specific Libraries # SYSLIBS = -lpthread poco-1.3.6p1-all/build/config/GCCEMBEDLINUX0000644000076500001200000000307111313735443020513 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/GCCEMBEDLINUX#2 $ # # ARM-Linux # # Make settings for Cross compiling in to unknown, ARM-based embedded Linux # # # General Settings # LINKMODE = STATIC POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = ARM TOOL = /opt/crosstool/gcc-4.1.0-glibc-2.3.2/arm-unknown-linux-gnu/bin/arm-unknown-linux-gnu # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) STRIP = $(TOOL)-strip STRIPDBG = $(TOOL)-strip LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -I$(STLPORT_INCLUDE) -I$(OPENSSL_INCLUDE) -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT # # System Specific Libraries # SYSLIBS = -lpthread -ldl poco-1.3.6p1-all/build/config/HP-UX0000644000076500001200000000270311313735443017404 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/HP-UX#1 $ # # HP-UX # # Make settings for HP-UX 11.11/aCC 03.30 (and later) # # # General Settings # LINKMODE = SHARED # # Define Tools # CC = cc CXX = aCC LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) $(LINKFLAGS) -b -Wl,+h$(notdir $@) -o $@ -Wl,+s SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.aCC STRIP = SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .$(target_version) SHAREDLIBLINKEXT = .sl # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = +DD32 CFLAGS64 = +DD64 CXXFLAGS = -AA +W361 +W307 +W749 +W849 CXXFLAGS32 = +DD32 CXXFLAGS64 = +DD64 LINKFLAGS = -AA LINKFLAGS32 = +DD32 LINKFLAGS64 = +DD64 STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -Wl,-aarchive_shared SHAREDOPT_CC = +Z SHAREDOPT_CXX = +Z SHAREDOPT_LINK = -Wl,+b$(LIBPATH) -Wl,+s -Wl,-ashared_archive DEBUGOPT_CC = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -g0 +d -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_LINK = -g0 RELEASEOPT_CC = +O2 -DNDEBUG RELEASEOPT_CXX = +O2 +Onolimit -DNDEBUG RELEASEOPT_LINK = +O2 +Onolimit # # System Specific Flags # SYSFLAGS = -Dhpux -D_REENTRANT -D_THREAD_SAFE -D_RWSTD_MULTI_THREAD -D_HPUX_SOURCE -D_XOPEN_SOURCE_EXTENDED -D_POSIX_C_SOURCE=199506L # # System Specific Libraries # SYSLIBS = -lpthread -lxnet poco-1.3.6p1-all/build/config/iPhone0000644000076500001200000000352311313735443017766 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/iPhone#1 $ # # iPhone # # Build settings for iPhone OS, using Apple's iPhone SDK # # # General Settings # LINKMODE = STATIC IPHONE_SDK_VERSION = 2.2.1 IPHONE_SDK = iPhoneOS POCO_TARGET_OSNAME = iPhone POCO_TARGET_OSARCH = armv6 TOOL_PREFIX = /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin9- OSFLAGS = -arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/$(IPHONE_SDK)$(IPHONE_SDK_VERSION).sdk -mthumb -miphoneos-version-min=$(IPHONE_SDK_VERSION) # # Tools # CC = $(TOOL_PREFIX)gcc-4.0.1 CXX = $(TOOL_PREFIX)g++-4.0.1 LINK = $(CXX) -bind_at_load LIB = libtool -static -o RANLIB = ranlib SHLIB = $(CXX) $(OSFLAGS) -dynamiclib -Wl,-install_name,$@ -o $@ DYLIB = $(CXX) $(OSFLAGS) -dynamic -bundle -read_only_relocs suppress -Wl,-bind_at_load -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .$(target_version).dylib SHAREDLIBLINKEXT = .dylib # # Compiler and Linker Flags # CFLAGS = $(OSFLAGS) CFLAGS32 = CFLAGS64 = CXXFLAGS = $(OSFLAGS) -Wall -Wno-sign-compare CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = $(OSFLAGS) LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = DEBUGOPT_CC = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_LINK = RELEASEOPT_CC = -DNDEBUG -O2 RELEASEOPT_CXX = -DNDEBUG -O RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -DPOCO_HAVE_IPv6 -DPOCO_NO_FPENVIRONMENT -DPOCO_NO_STAT64 # # System Specific Libraries # SYSLIBS = -ldl poco-1.3.6p1-all/build/config/Linux0000644000076500001200000000242611313735443017644 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/Linux#3 $ # # Linux # # Make settings for Linux 2.6/gcc 3.3 # # # # General Settings # LINKMODE = SHARED # # Define Tools # CC = gcc CXX = g++ LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = -Wall -Wno-sign-compare CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_REENTRANT -D_THREAD_SAFE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/Linux-stlport0000644000076500001200000000264411313735443021353 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/Linux-stlport#1 $ # # Linux # # Make settings for Linux 2.6/gcc 3.3 # # # # General Settings # LINKMODE = SHARED STLPORT_INCLUDE = /usr/local/include/stlport STLPORT_LIB = /usr/local/lib # # Define Tools # CC = gcc CXX = g++ LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = -Wall -Wno-sign-compare CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -I$(STLPORT_INCLUDE) -D_XOPEN_SOURCE=500 -D_REENTRANT -D_THREAD_SAFE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # # System Specific Libraries # SYSLIBS = -L$(STLPORT_LIB) -lstlport -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/MinGW0000644000076500001200000000300311313735443017516 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/MinGW#2 $ # # MinGW32 # # Make settings for MinGW on WinXP # # # General Settings # LINKMODE = STATIC POCO_TARGET_OSNAME = MinGW POCO_TARGET_OSARCH = ia32 # # Define Tools # CC = gcc CXX = g++ LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -mno-cygwin -o $@ -Wl,--out-implib=$(dir $@)$(subst cyg,lib,$(basename $(notdir $@))).a SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .dll SHAREDLIBLINKEXT = .dll BINEXT = .exe # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = -Wl,--allow-multiple-definition LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = SHAREDOPT_CXX = SHAREDOPT_LINK = -shared DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -mno-cygwin -D_WIN32 -DMINGW32 -DWINVER=0x500 -DPOCO_NO_FPENVIRONMENT -DPCRE_STATIC -DPOCO_THREAD_STACK_SIZE -DFoundation_Config_INCLUDED -I/usr/local/include -I/usr/include # # System Specific Libraries # SYSLIBS = -L/usr/local/lib -L/usr/lib -liphlpapi -lws2_32 -lssl -lcrypto -lws2_32 -lgdi32 poco-1.3.6p1-all/build/config/OSF10000644000076500001200000000266011313735443017255 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/OSF1#2 $ # # OSF1 # # Make settings for HP Tru64 5.1/Compaq C++ 6.5 # # # General Settings # LINKMODE = SHARED # # Define Tools # CC = cc CXX = cxx LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) $(LINKFLAGS) -shared -o $@ -soname $(notdir $@) SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.cxx SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -pthread CFLAGS32 = CFLAGS64 = CXXFLAGS = -model ansi -pthread -ansi_alias -std ansi -D__USE_STD_IOSTREAM -nousing_std -nopure_cname -ieee CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = -pthread -model ansi -std ansi LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = -non_shared STATICOPT_CXX = -non_shared STATICOPT_LINK = -non_shared SHAREDOPT_CC = -shared SHAREDOPT_CXX = -shared SHAREDOPT_LINK = -call_shared DEBUGOPT_CC = -g2 -D_DEBUG DEBUGOPT_CXX = -gall -D_DEBUG DEBUGOPT_LINK = -gall RELEASEOPT_CC = +O2 -DNDEBUG RELEASEOPT_CXX = +O2 -DNDEBUG RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE -D_RWSTD_MULTI_THREAD -D_XOPEN_SOURCE=500 -D_OSF_SOURCE -D_SOCKADDR_LEN # # System Specific Libraries # SYSLIBS = -lm -lrt poco-1.3.6p1-all/build/config/PPC-Linux0000644000076500001200000000265411313735443020267 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/PPC-Linux#1 $ # # PPC-Linux # # Make settings for Cross compiling in to unknown, PPC-based embedded Linux # # # General Settings # LINKMODE = STATIC POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = PPC TOOL = ppc-linux # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) STRIP = $(TOOL)-strip LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/QNX0000644000076500001200000000234711313735443017215 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/QNX#3 $ # # QNX # # Make settings for QNX Neutrino 6.3 with GCC 3.3.5 # # # General Settings # LINKMODE = SHARED # # Define Tools # CCVER = 3.3.5,gcc_ntox86 CC = qcc -V$(CCVER) CXX = QCC -V$(CCVER) LINK = $(CXX) -V$(CCVER) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.qcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fpic SHAREDOPT_CXX = -fpic SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_QNX_SOURCE # # System Specific Libraries # SYSLIBS = -lm -lsocket poco-1.3.6p1-all/build/config/SH-Linux0000644000076500001200000000260311313735443020151 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SH-Linux#1 $ # # SH-Linux # # Make settings for Renesas SH-Linux # # # General Settings # LINKMODE = SHARED POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = sh4 TOOL = sh4-linux # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) STRIP = $(TOOL)-strip LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O3 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/SSV-LINUX0000644000076500001200000000301711313735443020112 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SSV-LINUX#3 $ # # ARM-Linux # # Make settings for ARM Linux/gcc 2.95.3 (cross-compile, using STLport 4.6.2) # # # General Settings # LINKMODE = STATIC POCO_TARGET_OSNAME = Linux POCO_TARGET_OSARCH = ARM TOOL = /usr/local/arm-ssv1-linux/bin/arm-ssv1-linux # # Define Tools # CC = $(TOOL)-gcc CXX = $(TOOL)-g++ LINK = $(CXX) STRIP = $(TOOL)-strip STRIPDBG = $(TOOL)-strip LIB = $(TOOL)-ar -cr RANLIB = $(TOOL)-ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -I$(STLPORT_INCLUDE) -I$(OPENSSL_INCLUDE) -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_REENTRANT -D_THREAD_SAFE -DPOCO_NO_FPENVIRONMENT # # System Specific Libraries # SYSLIBS = -lpthread -ldl poco-1.3.6p1-all/build/config/SunOS0000644000076500001200000000022611313735443017550 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SunOS#4 $ # # SunOS # # Build settings for SunOS/Sun Studio C++ # include $(POCO_BASE)/build/config/SunOS-SunStudio poco-1.3.6p1-all/build/config/SunOS-GCC0000644000076500001200000000242611313735443020146 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SunOS-GCC#1 $ # # SunOS-GCC # # Make settings for SunOS/gcc # # # # General Settings # LINKMODE = SHARED # # Define Tools # CC = gcc CXX = g++ LINK = $(CXX) LIB = ar -cr RANLIB = ranlib SHLIB = $(CXX) -shared -Wl,-soname,$(notdir $@) -o $@ SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = strip DEP = $(POCO_BASE)/build/script/makedepend.gcc SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = CFLAGS32 = CFLAGS64 = CXXFLAGS = -Wall -Wno-sign-compare CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -static SHAREDOPT_CC = -fPIC SHAREDOPT_CXX = -fPIC SHAREDOPT_LINK = -Wl,-rpath,$(LIBPATH) DEBUGOPT_CC = -g -D_DEBUG DEBUGOPT_CXX = -g -D_DEBUG DEBUGOPT_LINK = -g RELEASEOPT_CC = -O2 -DNDEBUG RELEASEOPT_CXX = -O2 -DNDEBUG RELEASEOPT_LINK = -O2 # # System Specific Flags # SYSFLAGS = -D_XOPEN_SOURCE=500 -D_REENTRANT -D_THREAD_SAFE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # # System Specific Libraries # SYSLIBS = -lpthread -ldl -lrt poco-1.3.6p1-all/build/config/SunOS-stdcxx-x86_640000644000076500001200000000344311313735443022023 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SunOS-stdcxx-x86_64#1 $ # # SunOS # # Build settings for SunOS 5.10/Sun Studio 12 C++ 5.9/Apache stdcxx/AMD Opteron 64 bit # # # General Settings # LINKMODE = SHARED # # Tools # CC = cc -xtarget=opteron -m64 CXX = CC -xtarget=opteron -m64 -library=no%Cstd LINK = $(CXX) LIB = $(CXX) -xar -o $@ RANLIB = ranlib SHLIB = $(CXX) $(LINKFLAGS) -G -o $@ -h$(notdir $@) SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.SunCC SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -mt -Isrc CFLAGS32 = CFLAGS64 = CXXFLAGS = -mt -features=tmplife CXXFLAGS32 = CXXFLAGS64 = LINKFLAGS = -mt -L$(STDCXX_BASE)/lib -R$(STDCXX_BASE)/lib LINKFLAGS32 = LINKFLAGS64 = STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -Bstatic SHAREDOPT_CC = -KPIC SHAREDOPT_CXX = -KPIC SHAREDOPT_LINK = -Bdynamic DEBUGOPT_CC = -g -xdebugformat=stabs -xs -D_DEBUG=$(DEBUGLEVEL) -I$(STDCXX_BASE)/include DEBUGOPT_CXX = -g -xdebugformat=stabs -xs -D_DEBUG=$(DEBUGLEVEL) -I$(STDCXX_BASE)/include DEBUGOPT_LINK = -g -xdebugformat=stabs -xs RELEASEOPT_CC = -xO3 -g0 -xregs=no%frameptr -xdebugformat=stabs -xs -DNDEBUG -library=no%Cstd -I$(STDCXX_BASE)/include RELEASEOPT_CXX = -xO3 -g0 -xregs=no%frameptr -xdebugformat=stabs -xs -DNDEBUG -library=no%Cstd -I$(STDCXX_BASE)/include RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE -D_POSIX_PTHREAD_SEMANTICS -D_RWSTDDEBUG -D_RWSTD_NO_DEBUG_ITER # # System Specific Libraries # SYSLIBS = -lstd15D -lpthread -lrt -lxnet -lsocket -lnsl -lresolv -ldl poco-1.3.6p1-all/build/config/SunOS-SunForte0000644000076500001200000000257211313735443021321 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SunOS-SunForte#1 $ # # SunOS # # Build settings for SunOS 5.9/Forte C++ 5.4 # # # General Settings # LINKMODE = SHARED # # Tools # CC = cc CXX = CC LINK = $(CXX) LIB = $(CXX) -xar -o $@ RANLIB = ranlib SHLIB = $(CXX) $(LINKFLAGS) -G -o $@ -h$(notdir $@) SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.SunCC SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -mt -Isrc CFLAGS32 = CFLAGS64 = -xarch=v9 CXXFLAGS = -mt -library=stlport4 -erroff=hidevf CXXFLAGS32 = CXXFLAGS64 = -xarch=v9 LINKFLAGS = -mt -library=stlport4 LINKFLAGS32 = LINKFLAGS64 = -xarch=v9 STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -Bstatic SHAREDOPT_CC = -KPIC SHAREDOPT_CXX = -KPIC SHAREDOPT_LINK = -Bdynamic DEBUGOPT_CC = -g -xs -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -g -xs -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_LINK = -g -xs RELEASEOPT_CC = -O -DNDEBUG RELEASEOPT_CXX = -O -DNDEBUG RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE -D_POSIX_PTHREAD_SEMANTICS # # System Specific Libraries # SYSLIBS = -lpthread -lrt -lxnet -lsocket -lnsl -lresolv -ldl poco-1.3.6p1-all/build/config/SunOS-SunStudio0000644000076500001200000000263011313735443021504 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/config/SunOS-SunStudio#3 $ # # SunStudio # # Build settings for SunOS/Sun Studio C++ # # # General Settings # LINKMODE = SHARED # # Tools # CC = cc CXX = CC LINK = $(CXX) LIB = $(CXX) -xar -o $@ RANLIB = ranlib SHLIB = $(CXX) $(LINKFLAGS) -G -o $@ -h$(notdir $@) SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.SunCC SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -mt -Isrc CFLAGS32 = CFLAGS64 = -m64 CXXFLAGS = -mt -library=stlport4 -erroff=hidevf CXXFLAGS32 = CXXFLAGS64 = -m64 LINKFLAGS = -mt -library=stlport4 LINKFLAGS32 = LINKFLAGS64 = -m64 STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = -Bstatic SHAREDOPT_CC = -KPIC SHAREDOPT_CXX = -KPIC SHAREDOPT_LINK = -Bdynamic DEBUGOPT_CC = -g -xs -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -g -xs -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_LINK = -g -xs RELEASEOPT_CC = -O -DNDEBUG RELEASEOPT_CXX = -O -DNDEBUG RELEASEOPT_LINK = # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE -D_POSIX_PTHREAD_SEMANTICS -D_POSIX_C_SOURCE=199506L -D__EXTENSIONS__ # # System Specific Libraries # SYSLIBS = -lpthread -lrt -lxnet -lsocket -lnsl -lresolv -ldl poco-1.3.6p1-all/build/config/SunOS-SunStudio110000644000076500001200000000261211313735443021646 0ustar guenteradmin00000000000000# # Solaris 8 # SunStudio 11 - Sun C/C++ 5.8 # # Build settings for SunOS/Sun Studio C++ # # # General Settings # LINKMODE = BOTH OSARCH_64BITS=1 # # Tools # CC = cc CXX = CC LINK = libtool --mode=link $(CXX) LIB = ar cru RANLIB = ranlib SHLIB = $(CXX) $(LINKFLAGS) -G -o $@ -h$(notdir $@) SHLIBLN = $(POCO_BASE)/build/script/shlibln STRIP = DEP = $(POCO_BASE)/build/script/makedepend.SunCC SHELL = sh RM = rm -rf CP = cp MKDIR = mkdir -p # # Extension for Shared Libraries # SHAREDLIBEXT = .so.$(target_version) SHAREDLIBLINKEXT = .so # # Compiler and Linker Flags # CFLAGS = -mt CFLAGS32 = -xarch=v8plus CFLAGS64 = -xarch=v9 CXXFLAGS = -mt -library=stlport4 -erroff=hidevf CXXFLAGS32 = -xarch=v8plus CXXFLAGS64 = -xarch=v9 LINKFLAGS = -mt -library=stlport4 LINKFLAGS32 = -xarch=v8plus LINKFLAGS64 = -xarch=v9 STATICOPT_CC = STATICOPT_CXX = STATICOPT_LINK = SHAREDOPT_CC = -KPIC SHAREDOPT_CXX = -KPIC SHAREDOPT_LINK = DEBUGOPT_CC = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_CXX = -g -D_DEBUG=$(DEBUGLEVEL) DEBUGOPT_LINK = -g RELEASEOPT_CC = -xO5 -DNDEBUG RELEASEOPT_CXX = -xO5 -DNDEBUG RELEASEOPT_LINK = -xO5 # # System Specific Flags # SYSFLAGS = -D_REENTRANT -D_THREAD_SAFE -D_POSIX_PTHREAD_SEMANTICS # # System Specific Libraries # SYSLIBS = -lpthread -lrt -lxnet -lsocket -lnsl -lresolv -ldl poco-1.3.6p1-all/build/rules/0000755000076500001200000000000011313735443016503 5ustar guenteradmin00000000000000poco-1.3.6p1-all/build/rules/compile0000644000076500001200000000551411313735443020063 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/rules/compile#3 $ # # compile # # Compile rule definitions for makefiles # # # Targets # .PHONY: all all_static all_shared all_debug all_release \ clean static_debug static_release shared_debug shared_release all: $(DEFAULT_TARGET) all_static: static_debug static_release all_shared: shared_debug shared_release all_debug: static_debug shared_debug all_release: static_release shared_release # # Create directories if necessary # .PHONY: objdirs libdirs bindirs objdirs: $(OBJPATH_RELEASE_STATIC) $(OBJPATH_DEBUG_STATIC) $(OBJPATH_RELEASE_SHARED) $(OBJPATH_DEBUG_SHARED) libdirs: objdirs $(LIBPATH) bindirs: objdirs $(BINPATH) $(OBJPATH_RELEASE_STATIC) $(OBJPATH_DEBUG_STATIC) $(OBJPATH_RELEASE_SHARED) $(OBJPATH_DEBUG_SHARED) $(LIBPATH) $(BINPATH): $(MKDIR) $@ # # Rules for compiling # $(OBJPATH_DEBUG_STATIC)/%.o: $(SRCDIR)/%.cpp $(DEPPATH)/%.d @echo "** Compiling" $< "(debug)" $(CXX) $(INCLUDE) $(CXXFLAGS) $(DEBUGOPT_CXX) $(STATICOPT_CXX) -c $< -o $@ $(OBJPATH_RELEASE_STATIC)/%.o: $(SRCDIR)/%.cpp $(DEPPATH)/%.d @echo "** Compiling" $< "(release)" $(CXX) $(INCLUDE) $(CXXFLAGS) $(RELEASEOPT_CXX) $(STATICOPT_CXX) -c $< -o $@ $(OBJPATH_DEBUG_STATIC)/%.o: $(SRCDIR)/%.c $(DEPPATH)/%.d @echo "** Compiling" $< "(debug)" $(CC) $(INCLUDE) $(CFLAGS) $(DEBUGOPT_CC) $(STATICOPT_CC) -c $< -o $@ $(OBJPATH_RELEASE_STATIC)/%.o: $(SRCDIR)/%.c $(DEPPATH)/%.d @echo "** Compiling" $< "(release)" $(CC) $(INCLUDE) $(CFLAGS) $(RELEASEOPT_CC) $(STATICOPT_CC) -c $< -o $@ $(OBJPATH_DEBUG_SHARED)/%.o: $(SRCDIR)/%.cpp $(DEPPATH)/%.d @echo "** Compiling" $< "(debug, shared)" $(CXX) $(INCLUDE) $(CXXFLAGS) $(DEBUGOPT_CXX) $(SHAREDOPT_CXX) -c $< -o $@ $(OBJPATH_RELEASE_SHARED)/%.o: $(SRCDIR)/%.cpp $(DEPPATH)/%.d @echo "** Compiling" $< "(release, shared)" $(CXX) $(INCLUDE) $(CXXFLAGS) $(RELEASEOPT_CXX) $(SHAREDOPT_CXX) -c $< -o $@ $(OBJPATH_DEBUG_SHARED)/%.o: $(SRCDIR)/%.c $(DEPPATH)/%.d @echo "** Compiling" $< "(debug, shared)" $(CC) $(INCLUDE) $(CFLAGS) $(DEBUGOPT_CC) $(SHAREDOPT_CC) -c $< -o $@ $(OBJPATH_RELEASE_SHARED)/%.o: $(SRCDIR)/%.c $(DEPPATH)/%.d @echo "** Compiling" $< "(release, shared)" $(CC) $(INCLUDE) $(CFLAGS) $(RELEASEOPT_CC) $(SHAREDOPT_CC) -c $< -o $@ # # Rules for creating dependency information # $(DEPPATH)/%.d: $(SRCDIR)/%.cpp @echo "** Creating dependency info for" $^ $(MKDIR) $(DEPPATH) $(DEP) $(SRCDIR)/$(patsubst %.d,%.cpp,$(notdir $@)) $@ $(OBJPATH_DEBUG_STATIC) $(OBJPATH_RELEASE_STATIC) $(OBJPATH_DEBUG_SHARED) $(OBJPATH_RELEASE_SHARED) $(INCLUDE) $(CXXFLAGS) $(DEPPATH)/%.d: $(SRCDIR)/%.c @echo "** Creating dependency info for" $^ $(MKDIR) $(DEPPATH) $(DEP) $(SRCDIR)/$(patsubst %.d,%.c,$(notdir $@)) $@ $(OBJPATH_DEBUG_STATIC) $(OBJPATH_RELEASE_STATIC) $(OBJPATH_DEBUG_SHARED) $(OBJPATH_RELEASE_SHARED) $(INCLUDE) $(CFLAGS) depend: $(addprefix $(DEPPATH)/,$(addsuffix .d,$(objects))) poco-1.3.6p1-all/build/rules/dylib0000644000076500001200000000467411313735443017544 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/rules/dylib#4 $ # # dylib # # Rule definitions for building dynamically loadable shared libraries # # # Target names # SHL_EXT = $(SHAREDLIBLINKEXT) # Some systems (e.g. Mac OS X) make a difference between # shared libraries (as used by the linker/loader) and # dynamic libraries, as used for dynamically loadable modules. # If no specific instructions for making dynamic libraries # are given, use the instructions for making shared libraries. ifndef DYLIB DYLIB = $(SHLIB) DYLIBFLAGS = $(SHLIBFLAGS) endif DYLIB_DEBUG = $(BINPATH)/$(target)d$(OSARCH_POSTFIX)$(SHL_EXT) DYLIB_RELEASE = $(BINPATH)/$(target)$(OSARCH_POSTFIX)$(SHL_EXT) DYLIB_S_DEBUG = $(BINPATH)/$(target)d$(OSARCH_POSTFIX)_s$(SHL_EXT) DYLIB_S_RELEASE = $(BINPATH)/$(target)$(OSARCH_POSTFIX)_s$(SHL_EXT) TARGET_LIBS_DEBUG = $(foreach l,$(target_libs),-l$(l)d$(OSARCH_POSTFIX)) TARGET_LIBS_RELEASE = $(foreach l,$(target_libs),-l$(l)$(OSARCH_POSTFIX)) # # Include the compile rules # include $(POCO_BASE)/build/rules/compile # # Rules for creating a dynamically loadable shared library # clean: $(RM) $(OBJPATH) $(RM) $(DYLIB_DEBUG) $(DYLIB_RELEASE) $(DYLIB_S_DEBUG) $(DYLIB_S_RELEASE) distclean: clean $(RM) obj $(RM) .dep ifeq ($(LINKMODE),BOTH) static_debug: bindirs $(DYLIB_S_DEBUG) static_release: bindirs $(DYLIB_S_RELEASE) else static_debug: bindirs $(DYLIB_DEBUG) static_release: bindirs $(DYLIB_RELEASE) endif shared_debug: bindirs $(DYLIB_DEBUG) shared_release: bindirs $(DYLIB_RELEASE) $(DYLIB_DEBUG): $(foreach o,$(objects),$(OBJPATH_DEBUG_SHARED)/$(o).o) @echo "** Building dynamic library (debug)" $@ $(DYLIB) $(DYLIBFLAGS) $^ $(LIBRARY) $(TARGET_LIBS_DEBUG) $(SYSLIBS) $(postbuild) $(DYLIB_RELEASE): $(foreach o,$(objects),$(OBJPATH_RELEASE_SHARED)/$(o).o) @echo "** Building dynamic library (release)" $@ $(DYLIB) $(DYLIBFLAGS) $^ $(LIBRARY) $(TARGET_LIBS_RELEASE) $(SYSLIBS) $(postbuild) $(DYLIB_S_DEBUG): $(foreach o,$(objects),$(OBJPATH_DEBUG_SHARED)/$(o).o) @echo "** Building dynamic library (debug)" $@ $(DYLIB) $(DYLIBFLAGS) $^ $(LIBRARY) $(TARGET_LIBS_DEBUG) $(SYSLIBS) $(postbuild) $(DYLIB_S_RELEASE): $(foreach o,$(objects),$(OBJPATH_RELEASE_SHARED)/$(o).o) @echo "** Building dynamic library (release)" $@ $(DYLIB) $(DYLIBFLAGS) $^ $(LIBRARY) $(TARGET_LIBS_RELEASE) $(SYSLIBS) $(postbuild) # # Include the automatically generated dependency files # sinclude $(addprefix $(DEPPATH)/,$(addsuffix .d,$(objects))) poco-1.3.6p1-all/build/rules/exec0000644000076500001200000000417211313735443017356 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/rules/exec#4 $ # # exec # # Rule definitions for building executables # # # Target names # EXEC_RELEASE_STATIC = $(BINPATH)/$(target)$(OSARCH_POSTFIX)_s EXEC_DEBUG_STATIC = $(BINPATH)/$(target)d$(OSARCH_POSTFIX)_s EXEC_RELEASE_SHARED = $(BINPATH)/$(target)$(OSARCH_POSTFIX) EXEC_DEBUG_SHARED = $(BINPATH)/$(target)d$(OSARCH_POSTFIX) TARGET_LIBS_DEBUG = $(foreach l,$(target_libs),-l$(l)d$(OSARCH_POSTFIX)) TARGET_LIBS_RELEASE = $(foreach l,$(target_libs),-l$(l)$(OSARCH_POSTFIX)) # # Include the compile rules # include $(POCO_BASE)/build/rules/compile # # Rules for creating an executable # clean: $(RM) $(OBJPATH) $(RM) $(EXEC_RELEASE_STATIC) $(EXEC_DEBUG_STATIC) $(EXEC_RELEASE_SHARED) $(EXEC_DEBUG_SHARED) distclean: clean $(RM) bin $(RM) obj $(RM) .dep static_debug: bindirs $(EXEC_DEBUG_STATIC) static_release: bindirs $(EXEC_RELEASE_STATIC) shared_debug: bindirs $(EXEC_DEBUG_SHARED) shared_release: bindirs $(EXEC_RELEASE_SHARED) $(EXEC_DEBUG_STATIC): $(foreach o,$(objects),$(OBJPATH_DEBUG_STATIC)/$(o).o) @echo "** Building executable (debug)" $@ $(LINK) $(LINKFLAGS) $(DEBUGOPT_LINK) $(STATICOPT_LINK) -o $@ $^ $(LIBRARY) $(TARGET_LIBS_DEBUG) $(SYSLIBS) $(CPYDBG) $(STRIPDBGCMD) $(postbuild) $(EXEC_RELEASE_STATIC): $(foreach o,$(objects),$(OBJPATH_RELEASE_STATIC)/$(o).o) @echo "** Building executable (release)" $@ $(LINK) $(LINKFLAGS) $(RELEASEOPT_LINK) $(STATICOPT_LINK) -o $@ $^ $(LIBRARY) $(TARGET_LIBS_RELEASE) $(SYSLIBS) $(STRIPCMD) $(postbuild) $(EXEC_DEBUG_SHARED): $(foreach o,$(objects),$(OBJPATH_DEBUG_SHARED)/$(o).o) @echo "** Building shared executable (debug)" $@ $(LINK) $(LINKFLAGS) $(DEBUGOPT_LINK) $(SHAREDOPT_LINK) -o $@ $^ $(LIBRARY) $(TARGET_LIBS_DEBUG) $(SYSLIBS) $(postbuild) $(EXEC_RELEASE_SHARED): $(foreach o,$(objects),$(OBJPATH_RELEASE_SHARED)/$(o).o) @echo "** Building shared executable (release)" $@ $(LINK) $(LINKFLAGS) $(RELEASEOPT_LINK) $(SHAREDOPT_LINK) -o $@ $^ $(LIBRARY) $(TARGET_LIBS_RELEASE) $(SYSLIBS) $(STRIPCMD) $(postbuild) # # Include the automatically generated dependency files # sinclude $(addprefix $(DEPPATH)/,$(addsuffix .d,$(objects))) poco-1.3.6p1-all/build/rules/global0000644000076500001200000001300511313735443017665 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/rules/global#10 $ # # global # # Global build configuration # # Environment variables: # POCO_BASE: Path to POCO source tree. Must be defined. # POCO_BUILD: Path to directory where build files are put. # Defaults to $(POCO_BASE) # POCO_CONFIG: Build configuration to use. # Defaults to `uname`. # POCO_TARGET_OSNAME: Target system operating system name (for cross builds) # POCO_TARGET_OSARCH: Target system architecture (forr cross builds) # # # Check for POCO_BASE # ifndef POCO_BASE $(error POCO_BASE is not defined.) endif # # Include some optional make configuration # sinclude $(POCO_BASE)/config.build # # Check for PROJECT_BASE # ifndef PROJECT_BASE PROJECT_BASE = $(POCO_BASE) endif export PROJECT_BASE # # Check for POCO_BUILD # ifndef POCO_BUILD POCO_BUILD = $(PROJECT_BASE) endif export POCO_BUILD # # POCO_BASE/POCO_BUILD/cwd sanity checks # # Ensure that the current working directory is either # under $POCO_BASE or under $PROJECT_BASE # Also, if we're building under $POCO_BASE, disarm # $PROJECT_BASE # cwd = $(shell pwd) inpoco = $(shell echo | awk '{print index("$(cwd)","$(POCO_BASE)")}') inproj = $(shell echo | awk '{print index("$(cwd)","$(PROJECT_BASE)")}') ifeq ($(inpoco),1) PROJECT_BASE = $(POCO_BASE) else ifeq ($(inproj),1) else $(error Current working directory not under $$PROJECT_BASE) endif endif # # Determine OS # POCO_HOST_OSNAME = $(shell uname) ifeq ($(findstring CYGWIN,$(POCO_HOST_OSNAME)),CYGWIN) POCO_HOST_OSNAME = CYGWIN endif ifeq ($(findstring MINGW,$(POCO_HOST_OSNAME)),MINGW) POCO_HOST_OSNAME = MinGW endif POCO_HOST_OSARCH = $(subst /,-,$(shell uname -m | tr ' ' _)) # # Begin Sun platforms # # Pure Solaris or GNU (Nexenta), Sun Forte and Sun Studio compilers supported # (on Nexenta, the default compiler is g++) # ifeq ($(findstring SunOS,$(POCO_HOST_OSNAME)),SunOS) # detect if this is Nexenta platform POCO_HOST_ALL_OSNAME := $(shell uname -a) ifeq ($(findstring Nexenta,$(POCO_HOST_ALL_OSNAME)),Nexenta) POCO_HOST_OSNAME := Nexenta else # Up to version 5.5 SunOS-SunForte config is used, 5.6 and above use SunOS-SunStudio POCO_COMPILER_NAME := $(shell CC -V 2>&1) POCO_COMPILER_VERSION := $(subst .,,$(filter 5.%,$(POCO_COMPILER_NAME))) ifeq (0, $(shell test $(POCO_COMPILER_VERSION) -gt 55; echo $$?)) POCO_CONFIG := SunOS-SunStudio else POCO_CONFIG := SunOS-SunForte endif endif endif # # End Sun Platforms # # # If POCO_CONFIG is not set, use the OS name as configuration name # ifndef POCO_CONFIG POCO_CONFIG = $(POCO_HOST_OSNAME) endif # # Check if a 64bit build is requested # ifndef OSARCH_64BITS OSARCH_64BITS = 0 endif ifeq ($(OSARCH_64BITS),1) OSARCH_POSTFIX = 64 else OSARCH_POSTFIX = endif # # Include System Specific Settings # include $(POCO_BASE)/build/config/$(POCO_CONFIG) # # Determine operating system # ifndef POCO_TARGET_OSNAME OSNAME := $(POCO_HOST_OSNAME) else OSNAME := $(POCO_TARGET_OSNAME) endif ifndef POCO_TARGET_OSARCH OSARCH := $(subst /,-,$(shell uname -m | tr ' ' _)) else OSARCH := $(POCO_TARGET_OSARCH) endif HOSTNAME := $(shell hostname) # # Find out current component # COMPONENT := $(shell $(POCO_BASE)/build/script/projname "$(PROJECT_BASE)") # # Define standard directories # SRCDIR = src INCDIR = include LIBDIR = lib/$(OSNAME)/$(OSARCH) BINDIR = bin/$(OSNAME)/$(OSARCH) OBJDIR = obj/$(OSNAME)/$(OSARCH) DEPDIR = .dep/$(OSNAME)/$(OSARCH) LIBPATH = $(POCO_BUILD)/$(LIBDIR) BINPATH = $(POCO_BUILD)/$(COMPONENT)/$(BINDIR) OBJPATH = $(POCO_BUILD)/$(COMPONENT)/$(OBJDIR) DEPPATH = $(POCO_BUILD)/$(COMPONENT)/$(DEPDIR) ifeq ($(POCO_BASE),$(PROJECT_BASE)) POCO_LIBRARY = else POCO_LIBRARY = -L$(POCO_BASE)/$(LIBDIR) endif ifndef LIBPREFIX LIBPREFIX = lib endif # # Build component list # COMPONENTS := $(shell cat $(POCO_BASE)/components) # # Read global library version number # LIBVERSION := $(shell cat $(POCO_BASE)/libversion) # # Determine link mode # ifndef LINKMODE LINKMODE = BOTH endif ifeq ($(LINKMODE),SHARED) DEFAULT_TARGET = all_shared endif ifeq ($(LINKMODE),STATIC) DEFAULT_TARGET = all_static endif ifeq ($(LINKMODE),BOTH) DEFAULT_TARGET = all_static all_shared endif # # Compose compiler flags # COMMONFLAGS = -DPOCO_BUILD_HOST=$(HOSTNAME) $(POCO_FLAGS) CFLAGS += $(COMMONFLAGS) $(SYSFLAGS) CXXFLAGS += $(COMMONFLAGS) $(SYSFLAGS) LINKFLAGS += $(COMMONFLAGS) $(SYSFLAGS) ifeq ($(OSARCH_64BITS),1) CFLAGS += $(CFLAGS64) CXXFLAGS += $(CXXFLAGS64) SHLIBFLAGS += $(SHLIBFLAGS64) DYLIBFLAGS += $(DYLIBFLAGS64) LINKFLAGS += $(LINKFLAGS64) else CFLAGS += $(CFLAGS32) CXXFLAGS += $(CXXFLAGS32) SHLIBFLAGS += $(SHLIBFLAGS32) DYLIBFLAGS += $(DYLIBFLAGS32) LINKFLAGS += $(LINKFLAGS32) endif # # Compose object file path # OBJPATH_RELEASE_STATIC = $(OBJPATH)/release_static$(OSARCH_POSTFIX) OBJPATH_DEBUG_STATIC = $(OBJPATH)/debug_static$(OSARCH_POSTFIX) OBJPATH_RELEASE_SHARED = $(OBJPATH)/release_shared$(OSARCH_POSTFIX) OBJPATH_DEBUG_SHARED = $(OBJPATH)/debug_shared$(OSARCH_POSTFIX) # # Build Include directory List # INCLUDE = $(foreach p,$(POCO_ADD_INCLUDE),-I$(p)) -Iinclude $(foreach p,$(COMPONENTS),-I$(POCO_BASE)/$(p)/$(INCDIR)) # # Build Library Directory List # LIBRARY = $(foreach p,$(POCO_ADD_LIBRARY),-L$(p)) -L$(LIBPATH) $(POCO_LIBRARY) # # Strip Command definition # ifeq ($(strip $(STRIP)),) STRIPCMD = else STRIPCMD = $(STRIP) $@$(BINEXT) endif # # Remote debugging support # ifeq ($(strip $(STRIPDBG)),) CPYDBG = STRIPDBGCMD = else CPYDBG = cp $@ $@x STRIPDBGCMD = $(STRIP) $@x endif # # Make CC and CXX environment vars # export CC export CXX poco-1.3.6p1-all/build/rules/lib0000644000076500001200000000452411313735443017201 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/rules/lib#4 $ # # lib # # Rule definitions for building libraries # # # Target names # ifeq ($(OSNAME),CYGWIN) SHL_EXT = $(SHAREDLIBLINKEXT) else ifdef target_version SHL_EXT = $(SHAREDLIBEXT) else SHL_EXT = $(SHAREDLIBLINKEXT) endif endif LIB_RELEASE_STATIC = $(LIBPATH)/$(LIBPREFIX)$(target)$(OSARCH_POSTFIX).a LIB_DEBUG_STATIC = $(LIBPATH)/$(LIBPREFIX)$(target)d$(OSARCH_POSTFIX).a LIB_RELEASE_SHARED = $(LIBPATH)/$(LIBPREFIX)$(target)$(OSARCH_POSTFIX)$(SHL_EXT) LIB_DEBUG_SHARED = $(LIBPATH)/$(LIBPREFIX)$(target)d$(OSARCH_POSTFIX)$(SHL_EXT) LIB_RELEASE_SHARED_LINK = $(LIBPATH)/$(LIBPREFIX)$(target)$(OSARCH_POSTFIX)$(SHAREDLIBLINKEXT) LIB_DEBUG_SHARED_LINK = $(LIBPATH)/$(LIBPREFIX)$(target)d$(OSARCH_POSTFIX)$(SHAREDLIBLINKEXT) TARGET_LIBS_DEBUG = $(foreach l,$(target_libs),-l$(l)d$(OSARCH_POSTFIX)) TARGET_LIBS_RELEASE = $(foreach l,$(target_libs),-l$(l)$(OSARCH_POSTFIX)) # # Include the compile rules # include $(POCO_BASE)/build/rules/compile # # Rules for creating a library # clean: $(RM) $(OBJPATH) $(RM) $(LIB_RELEASE_STATIC) $(LIB_DEBUG_STATIC) $(LIB_RELEASE_SHARED) $(LIB_DEBUG_SHARED) distclean: clean $(RM) obj $(RM) .dep static_debug: libdirs $(LIB_DEBUG_STATIC) static_release: libdirs $(LIB_RELEASE_STATIC) shared_debug: libdirs $(LIB_DEBUG_SHARED) shared_release: libdirs $(LIB_RELEASE_SHARED) $(LIB_DEBUG_STATIC): $(foreach o,$(objects),$(OBJPATH_DEBUG_STATIC)/$(o).o) @echo "** Building library (debug)" $@ $(LIB) $@ $^ $(RANLIB) $@ $(postbuild) $(LIB_RELEASE_STATIC): $(foreach o,$(objects),$(OBJPATH_RELEASE_STATIC)/$(o).o) @echo "** Building library (release)" $@ $(LIB) $@ $^ $(RANLIB) $@ $(postbuild) $(LIB_DEBUG_SHARED): $(foreach o,$(objects),$(OBJPATH_DEBUG_SHARED)/$(o).o) @echo "** Building shared library (debug)" $@ $(SHLIB) $(SHLIBFLAGS) $^ $(LIBRARY) $(TARGET_LIBS_DEBUG) $(SYSLIBS) $(SHLIBLN) $(LIB_DEBUG_SHARED) $(LIB_DEBUG_SHARED_LINK) $(postbuild) $(LIB_RELEASE_SHARED): $(foreach o,$(objects),$(OBJPATH_RELEASE_SHARED)/$(o).o) @echo "** Building shared library (release)" $@ $(SHLIB) $(SHLIBFLAGS) $^ $(LIBRARY) $(TARGET_LIBS_RELEASE) $(SYSLIBS) $(SHLIBLN) $(LIB_RELEASE_SHARED) $(LIB_RELEASE_SHARED_LINK) $(STRIPCMD) $(postbuild) # # Include the automatically generated dependency files # sinclude $(addprefix $(DEPPATH)/,$(addsuffix .d,$(objects))) poco-1.3.6p1-all/build/rules/sample0000644000076500001200000000340011313735443017704 0ustar guenteradmin00000000000000# # $Id: //poco/1.3/build/rules/sample#3 $ # # sample # # Global build configuration for samples # # Environment variables: # POCO_BASE: Path to POCO source tree. # POCO_CONFIG: Build configuration to use. # Defaults to `uname`. # # # Check for POCO_BASE # ifndef POCO_BASE $(error POCO_BASE is not defined.) endif # # Determine OS # POCO_HOST_OSNAME = $(shell uname) # # If POCO_CONFIG is not set, use the OS name as configuration name # ifndef POCO_CONFIG POCO_CONFIG = $(POCO_HOST_OSNAME) endif # # Include System Specific Settings # include $(POCO_BASE)/build/config/$(POCO_CONFIG) # # Define standard directories # SRCDIR = src INCDIR = include LIBDIR = lib BINDIR = bin OBJDIR = obj DEPDIR = .dep INCPATH = $(POCO_BASE)/$(INCDIR) LIBPATH = $(POCO_BASE)/$(LIBDIR) BINPATH = $(BINDIR) OBJPATH = $(OBJDIR) DEPPATH = $(DEPDIR) # # Determine link mode # ifndef LINKMODE LINKMODE = BOTH endif ifeq ($(LINKMODE),SHARED) DEFAULT_TARGET = all_shared endif ifeq ($(LINKMODE),STATIC) DEFAULT_TARGET = all_static endif ifeq ($(LINKMODE),BOTH) DEFAULT_TARGET = all_static all_shared endif # # Compose compiler flags # COMMONFLAGS = $(POCO_FLAGS) CFLAGS += $(COMMONFLAGS) $(SYSFLAGS) CXXFLAGS += $(COMMONFLAGS) $(SYSFLAGS) LINKFLAGS += $(COMMONFLAGS) $(SYSFLAGS) # # Compose object file path # OBJPATH_RELEASE_STATIC = $(OBJPATH)/release_static$(OSARCH_POSTFIX) OBJPATH_DEBUG_STATIC = $(OBJPATH)/debug_static$(OSARCH_POSTFIX) OBJPATH_RELEASE_SHARED = $(OBJPATH)/release_shared$(OSARCH_POSTFIX) OBJPATH_DEBUG_SHARED = $(OBJPATH)/debug_shared$(OSARCH_POSTFIX) # # Build Include directory List # INCLUDE = -Iinclude -I$(INCPATH) # # Build Library Directory List # LIBRARY = -L$(LIBPATH) # # Make CC and CXX environment vars # export CC export CXX poco-1.3.6p1-all/build/script/0000755000076500001200000000000011313735443016655 5ustar guenteradmin00000000000000poco-1.3.6p1-all/build/script/makedepend.aCC0000755000076500001200000000066711313735443021336 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/makedepend.aCC#1 $ # # makedepend.aCC # # Create dependency file, HP ANSI C++ version # Usage: makedepend.gcc source target dir1 dir2 dir3 dir4 flags... # source=$1 shift target=$1 shift dir1=$1 shift dir2=$1 shift dir3=$1 shift dir4=$1 shift tmpfile=`basename $target` aCC -E +maked $@ $source >/dev/null sed "s#\(.*\.o\)#$dir1/\1 $dir2/\1 $dir3/\1 $dir4/\1#" <$tmpfile >$target rm $tmpfile poco-1.3.6p1-all/build/script/makedepend.cxx0000755000076500001200000000056411313735443021506 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/makedepend.cxx#1 $ # # makedepend.cxx # # Create dependency file, Compaq C++ version # Usage: makedepend.gcc source target dir1 dir2 dir3 dir4 flags... # source=$1 shift target=$1 shift dir1=$1 shift dir2=$1 shift dir3=$1 shift dir4=$1 shift cxx -M $@ $source | sed "s#\(.*\.o\)#$dir1/\1 $dir2/\1 $dir3/\1 $dir4/\1#" >$target poco-1.3.6p1-all/build/script/makedepend.gcc0000755000076500001200000000055611313735443021441 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/makedepend.gcc#1 $ # # makedepend.gcc # # Create dependency file, GCC version # Usage: makedepend.gcc source target dir1 dir2 dir3 dir4 flags... # source=$1 shift target=$1 shift dir1=$1 shift dir2=$1 shift dir3=$1 shift dir4=$1 shift $CC -MM $@ $source | sed "s#\(.*\.o\)#$dir1/\1 $dir2/\1 $dir3/\1 $dir4/\1#" >$target poco-1.3.6p1-all/build/script/makedepend.qcc0000755000076500001200000000060111313735443021442 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/makedepend.qcc#1 $ # # makedepend.gcc # # Create dependency file, QNX Neutrino QCC version # Usage: makedepend.qcc source target dir1 dir2 dir3 dir4 flags... # source=$1 shift target=$1 shift dir1=$1 shift dir2=$1 shift dir3=$1 shift dir4=$1 shift $CC -E -Wp,-MM $@ $source | sed "s#\(.*\.o\)#$dir1/\1 $dir2/\1 $dir3/\1 $dir4/\1#" >$target poco-1.3.6p1-all/build/script/makedepend.SunCC0000755000076500001200000000057611313735443021662 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/makedepend.SunCC#1 $ # # makedepend.SunCC # # Create dependency file, Sun Forte C++ version # Usage: makedepend.SunCC source target dir1 dir2 dir3 dir4 flags... # source=$1 shift target=$1 shift dir1=$1 shift dir2=$1 shift dir3=$1 shift dir4=$1 shift CC -xM1 $@ $source | sed "s#\(.*\.o\)#$dir1/\1 $dir2/\1 $dir3/\1 $dir4/\1#" >$target poco-1.3.6p1-all/build/script/makedepend.xlC0000755000076500001200000000100611313735443021422 0ustar guenteradmin00000000000000#! /bin/sh # # # makedepend.xlC # # Create dependency file, xlC version # Usage: makedepend.xlC source target dir1 dir2 dir3 dir4 flags... # source=$1 shift target=$1 shift dir1=$1 shift dir2=$1 shift dir3=$1 shift dir4=$1 shift cwd=`pwd` cd `dirname $target` $CXX -qmakedep -E -w $@ $cwd/$source >/dev/null ufile=`basename $source` ufile=`echo $ufile | sed "s#\.cpp#\.u#"` cat $ufile | sort | uniq | grep -v '/usr/include' | grep -v '/usr/vacpp' | sed "s#\(.*\.o\)#$dir1/\1 $dir2/\1 $dir3/\1 $dir4/\1#" >$target poco-1.3.6p1-all/build/script/makeldpath0000755000076500001200000000070211313735443020714 0ustar guenteradmin00000000000000#! /bin/sh # # makeldpath # # $Id: //poco/1.3/build/script/makeldpath#1 $ # # Create a LD_LIBRARY_PATH for all project libraries. # if [ "$POCO_BASE" == "" ] ; then echo $0": POCO_BASE is not set." exit 1 fi projectList=`cat ${POCO_BASE}/components` OSNAME=`uname` OSARCH=`uname -m | tr " /" "_-"` for proj in $projectList ; do path=${POCO_BASE}/${proj}/lib/${OSNAME}/${OSARCH} echo $path if [ -d $path ] ; then echo -n ":"$path fi done poco-1.3.6p1-all/build/script/projname0000755000076500001200000000062111313735443020415 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/projname#2 $ # # projname # # Usage: projname PROJECT_BASE # # Extract the project name from the current path # NOTE: the cd $PROJECT_BASE is necessary to resolve symbolic links, # ditto is the kinda strange sh -c pwd # PROJECT_BASE=$1 cdir=`sh -c pwd` cd $PROJECT_BASE projbase=`sh -c pwd` cd "$cdir" sh -c pwd | sed "s:^$projbase::" | sed "s:^/::" poco-1.3.6p1-all/build/script/shlibln0000755000076500001200000000062211313735443020236 0ustar guenteradmin00000000000000#! /bin/sh # # $Id: //poco/1.3/build/script/shlibln#1 $ # # shlibln # # Create a symbolic link for a shared library # if [ $# -ne 2 ] ; then echo "usage: $0:t file link" exit 1 fi source="$1" target="$2" sourcedir=`dirname "$source"` targetdir=`dirname "$target"` if [ "$sourcedir" = "$targetdir" ] ; then source=`basename $source` fi if [ "$1" != "$2" ] ; then ln -sf "$source" "$target" fi poco-1.3.6p1-all/build/vms/0000755000076500001200000000000011313735443016156 5ustar guenteradmin00000000000000poco-1.3.6p1-all/build/vms/build.com0000755000076500001200000001065511313735443017767 0ustar guenteradmin00000000000000$ ! $ ! BUILD.COM $ ! $ ! $Id: //poco/1.3/build/vms/build.com#1 $ $ ! $ ! OpenVMS build procedure $ ! $ ! Requires the logical POCO_BASE to be set accordingly. $ ! $ ! Usage: build [-32|-64] [-DEBUG|-RELEASE] [-CLEAN] [-VERBOSE] $ ! $ $ clean == 0 $ verbose == 0 $ buildMode == "DEBUG" $ pointerSize == 32 $ buildfile == F$SEARCH("*.VMSBUILD") $ projectDefines == "" $ lib = "" $ exe = "" $ shr = "" $ $ DEFINE/PROC/NOLOG CppUnit POCO_BASE:[CPPUNIT.INCLUDE.CPPUNIT] $ DEFINE/PROC/NOLOG Foundation POCO_BASE:[FOUNDATION.INCLUDE.FOUNDATION] $ DEFINE/PROC/NOLOG XML POCO_BASE:[XML.INCLUDE.XML] $ DEFINE/PROC/NOLOG SAX POCO_BASE:[XML.INCLUDE.SAX] $ DEFINE/PROC/NOLOG DOM POCO_BASE:[XML.INCLUDE.DOM] $ $ CALL handleArgs "''P1'" $ CALL handleArgs "''P2'" $ CALL handleArgs "''P3'" $ CALL handleArgs "''P4'" $ CALL handleArgs "''P5'" $ $ IF buildfile .EQS. "" $ THEN $ WRITE SYS$OUTPUT "Cannot find build file." $ EXIT 1 $ ENDIF $ $ IF pointerSize .EQ. 32 $ THEN $ objdir = "OBJ32" $ ELSE $ objdir = "OBJ64" $ ENDIF $ $ IF buildMode .EQS. "DEBUG" $ THEN $ objdir = objdir + "D" $ ELSE $ objdir = objdir + "R" $ ENDIF $ $ objpath = "[.''objdir']" $ exists = F$SEARCH("''objdir'.DIR") $ IF exists .EQS. "" $ THEN $ CREATE/DIR/NOLOG 'objpath' $ SET FILE/PROT=(O:RWED) 'objdir'.DIR;* $ ENDIF $ $ IF clean .EQ. 1 $ THEN $ DELETE/NOLOG 'objpath'*.*;* $ ENDIF $ $ PCXX :== @POCO_BASE:[BUILD.VMS]POCOCXX.COM $ PCC :== @POCO_BASE:[BUILD.VMS]POCOCC.COM $ PLIB :== @POCO_BASE:[BUILD.VMS]POCOLIB.COM $ PLNK :== @POCO_BASE:[BUILD.VMS]POCOLNK.COM $ $ OPEN fileList 'buildfile' $ ON ERROR THEN GOTO EOF $ ON CONTROL_Y THEN GOTO EOF $ ReadLoop: $ READ/END_OF_FILE=EOF fileList file $ file = F$EDIT(file, "TRIM") $ IF F$EXTRACT(0, 4, file) .EQS. "DEF=" $ THEN $ projectDefines = F$EXTRACT(4, 64, file) $ projectDefines = "," + F$EDIT(projectDefines, "TRIM") $ GOTO ReadLoop $ ENDIF $ IF F$EXTRACT(0, 4, file) .EQS. "LIB=" $ THEN $ lib = F$EXTRACT(4, 64, file) $ lib = F$EDIT(lib, "TRIM") $ GOTO ReadLoop $ ENDIF $ IF F$EXTRACT(0, 4, file) .EQS. "EXE=" $ THEN $ exe = F$EXTRACT(4, 64, file) $ exe = F$EDIT(exe, "TRIM") $ GOTO ReadLoop $ ENDIF $ IF F$EXTRACT(0, 4, file) .EQS. "SHR=" $ THEN $ shr = F$EXTRACT(4, 64, file) $ shr = F$EDIT(shr, "TRIM") $ GOTO ReadLoop $ ENDIF $ IF F$EXTRACT(0, 1, file) .NES. "#" $ THEN $ cfile = F$SEARCH(F$PARSE(file, "[.SRC]", ".C")) $ cppfile = F$SEARCH(F$PARSE(file, "[.SRC]", ".CPP")) $ IF cppfile .NES. "" $ THEN $ srcfile = "[.SRC]''file'.CPP" $ ELSE $ srcfile = "[.SRC]''file'.C" $ ENDIF $ srctime = F$CVTIME(F$FILE_ATTRIBUTES(srcfile, "RDT"), "COMPARISON") $ objfile = F$SEARCH(F$PARSE(file, objpath, ".OBJ")) $ IF objfile .NES. "" $ THEN $ objtime = F$CVTIME(F$FILE_ATTRIBUTES(objfile, "RDT"), "COMPARISON") $ ELSE $ objtime = F$CVTIME("01-JAN-1970 00:00:00.00", "COMPARISON") $ ENDIF $ IF srctime .GTS. objtime $ THEN $ WRITE SYS$OUTPUT "** Compiling ",file $ IF cppfile .NES. "" $ THEN $ PCXX 'srcfile' $ ELSE $ PCC 'srcfile' $ ENDIF $ ELSE $ WRITE SYS$OUTPUT "** Skipping ",file," (up-to-date)" $ ENDIF $ ENDIF $ GOTO ReadLoop $ EOF: $ CLOSE fileList $ $ IF lib .NES. "" $ THEN $ WRITE SYS$OUTPUT "** Creating Library ",lib $ PLIB 'lib' $ ELSE $ IF exe .NES. "" $ THEN $ WRITE SYS$OUTPUT "** Creating Executable ",exe $ PLNK 'exe' $ ELSE $ IF shr .NES. "" $ THEN $ WRITE SYS$OUTPUT "** Creating Shareable ",shr $ PLNK 'shr' "SHAREABLE" $ ENDIF $ ENDIF $ ENDIF $ $ handleArgs: SUBROUTINE $ arg = F$EDIT("''P1'", "UPCASE") $ IF arg .NES. "" $ THEN $ IF arg .EQS. "-CLEAN" THEN clean == 1 $ IF arg .EQS. "-32" THEN pointerSize == 32 $ IF arg .EQS. "-64" THEN pointerSize == 64 $ IF arg .EQS. "-DEBUG" THEN buildMode == "DEBUG" $ IF arg .EQS. "-RELEASE" THEN buildMode == "RELEASE" $ IF arg .EQS. "-VERBOSE" THEN verbose == 1 $ IF F$EXTRACT(0, 1, arg) .NES. "-" THEN buildfile == F$SEARCH("''arg'.VMSBUILD") $ ENDIF $ ENDSUBROUTINE poco-1.3.6p1-all/build/vms/pococc.com0000755000076500001200000000165411313735443020135 0ustar guenteradmin00000000000000$ ! $ ! POCOCC.COM $ ! $ ! $Id: //poco/1.3/build/vms/pococc.com#1 $ $ ! $ ! C compile procedure for Poco libraries $ ! $ ! The logical POCO_BASE must be set and point to the $ ! Poco base directory (e.g. USER1:[PROJECTS.POCO.]) $ ! $ $ IF "''pointerSize'" .EQS. "32" $ THEN $ ptropt = "/POINTER=32" $ objdir = "OBJ32" $ ELSE $ ptropt = "/POINTER=64" $ objdir = "OBJ64" $ ENDIF $ $ IF "''buildMode'" .EQS. "RELEASE" $ THEN $ modeopt = "/NODEBUG" $ modedef = "NDEBUG" $ objdir = objdir + "R" $ ELSE $ modeopt = "/DEBUG=ALL/NOOPTIMIZE" $ modedef = "_DEBUG" $ objdir = objdir + "D" $ ENDIF $ $ baseopt = "/STANDARD=RELAXED/ANSI_ALIAS/FLOAT=IEEE_FLOAT/OBJECT=[.''objdir'].OBJ" $ defines = "/DEFINE=(''modedef' ''projectDefines')" $ $ IF "''verbose'" .EQS. "1" $ THEN $ WRITE SYS$OUTPUT "CC ''baseopt' ''ptropt' ''modeopt' ''defines' ''P1'" $ ENDIF $ $ CC 'baseopt' 'ptropt' 'modeopt' 'defines' 'p1' poco-1.3.6p1-all/build/vms/pococxx.com0000755000076500001200000000210411313735443020341 0ustar guenteradmin00000000000000$ ! $ ! POCOCXX.COM $ ! $ ! $Id: //poco/1.3/build/vms/pococxx.com#1 $ $ ! $ ! C++ compile procedure for Poco libraries $ ! $ ! The logical POCO_BASE must be set and point to the $ ! Poco base directory (e.g. USER1:[PROJECTS.POCO.]) $ ! $ $ IF "''pointerSize'" .EQS. "32" $ THEN $ ptropt = "/POINTER=32" $ objdir = "OBJ32" $ ELSE $ ptropt = "/MODEL=ANSI" $ objdir = "OBJ64" $ ENDIF $ $ IF "''buildMode'" .EQS. "RELEASE" $ THEN $ modeopt = "/NODEBUG" $ modedef = "NDEBUG" $ objdir = objdir + "R" $ ELSE $ modeopt = "/DEBUG=ALL/NOOPT" $ modedef = "_DEBUG" $ objdir = objdir + "D" $ ENDIF $ $ node = F$GETSYI("NODENAME") $ baseopt = "/STANDARD=ANSI/ANSI/NOUSING/FLOAT=IEEE/IEEE=UNDER/REENT=MULTI/OBJ=[.''objdir'].OBJ" $ repopt = "/REP=[.''objdir']" $ defines = "/DEF=(__USE_STD_IOSTREAM,__NEW_STARLET,POCO_BUILD_HOST=''node',''modedef' ''projectDefines')" $ $ IF "''verbose'" .EQS. "1" $ THEN $ WRITE SYS$OUTPUT "CXX ''baseopt' ''ptropt' ''modeopt' ''defines' ''repopt' ''P1'" $ ENDIF $ $ CXX 'baseopt' 'ptropt' 'modeopt' 'defines' 'repopt' 'p1' poco-1.3.6p1-all/build/vms/pocolib.com0000755000076500001200000000134011313735443020306 0ustar guenteradmin00000000000000$ ! $ ! POCOLIB.COM $ ! $ ! $Id: //poco/1.3/build/vms/pocolib.com#1 $ $ ! $ ! C++ library creation procedure for Poco libraries $ ! $ ! The logical POCO_BASE must be set and point to the $ ! Poco base directory (e.g. USER1:[PROJECTS.POCO.]) $ ! $ $ libdir = "POCO_BASE:[LIB]" $ lib = libdir + p1 $ $ IF "''pointerSize'" .EQS. "32" $ THEN $ objdir = "OBJ32" $ ELSE $ objdir = "OBJ64" $ lib = lib + "64" $ ENDIF $ $ IF "''buildMode'" .EQS. "RELEASE" $ THEN $ objdir = objdir + "R" $ ELSE $ objdir = objdir + "D" $ lib = lib + "D" $ ENDIF $ $ $ IF "''verbose'" .EQS. "1" $ THEN $ WRITE SYS$OUTPUT "LIBRARY/OBJECT/CREATE ''lib' [.''objdir']*.OBJ" $ ENDIF $ $ LIBRARY/OBJECT/CREATE 'lib' [.'objdir']*.OBJ poco-1.3.6p1-all/build/vms/pocolnk.com0000755000076500001200000000407611313735443020335 0ustar guenteradmin00000000000000$ ! $ ! POCOLNK.COM $ ! $ ! $Id: //poco/1.3/build/vms/pocolnk.com#1 $ $ ! $ ! C++ link procedure for Poco $ ! $ ! The logical POCO_BASE must be set and point to the $ ! Poco base directory (e.g. USER1:[PROJECTS.POCO.]) $ ! $ $ target = P1 $ libdir = "POCO_BASE:[LIB]" $ bindir = "[.BIN]" $ baseopt = "/THREADS" $ $ IF "''P2'" .EQS. "SHAREABLE" $ THEN $ outopt="/SHAREABLE" $ ELSE $ outopt="/EXECUTABLE" $ ENDIF $ $ IF "''pointerSize'" .EQS. "32" $ THEN $ libsuffix = "" $ binsuffix = "" $ ptropt = "/MODEL=ARM" $ objdir = "OBJ32" $ ELSE $ libsuffix = "64" $ binsuffix = "64" $ ptropt = "/MODEL=ANSI" $ objdir = "OBJ64" $ ENDIF $ $ IF "''buildMode'" .EQS. "RELEASE" $ THEN $ dbgopt = "/NOTRACEBACK" $ objdir = objdir + "R" $ ELSE $ libsuffix = "''libsuffix'D" $ binsuffix = "''binsuffix'D" $ dbgopt = "/TRACEBACK/debug" $ objdir = objdir + "D" $ ENDIF $ $ IF F$SEARCH("''target'.OPT") .NES. "" $ THEN $ COPY 'target'.OPT 'target'.TMPOPT $ OPEN/APPEND optfile 'target'.TMPOPT $ ELSE $ OPEN/WRITE optfile 'target'.TMPOPT $ ENDIF $ ObjWriteLoop: $ obj = F$SEARCH("[.''objdir']*.OBJ", 1) $ IF obj .EQS. "" THEN GOTO LibWriteLoop1 $ WRITE optfile "''obj'" $ GOTO ObjWriteLoop $ LibWriteLoop1: $ lib = F$SEARCH("''libdir'*''libsuffix'.OLB", 2) $ IF lib .EQS. "" THEN GOTO LibWriteLoop2 $ WRITE optfile "''lib'/LIBRARY" $ GOTO LibWriteLoop1 $ LibWriteLoop2: $ lib = F$SEARCH("''libdir'*''libsuffix'.OLB", 3) $ IF lib .EQS. "" THEN GOTO EndWriteLoop $ WRITE optfile "''lib'/LIBRARY" $ GOTO LibWriteLoop2 $ EndWriteLoop: $ CLOSE optfile $ $ bin = bindir + target + binsuffix + ".EXE" $ baseopt = baseopt + "/REPOSITORY=[.''objdir']" $ $ IF "''verbose'" .EQS. "1" $ THEN $ WRITE SYS$OUTPUT "CXXLINK''outopt'=''bin' ''baseopt' ''ptropt' ''dbgopt' ''target'.TMPOPT/OPTIONS" $ ENDIF $ $ IF F$SEARCH("BIN.DIR") .EQS. "" $ THEN $ CREATE/DIR/NOLOG 'bindir' $ ENDIF $ $ CXXLINK 'outopt'='bin' 'baseopt' 'ptropt' 'dbgopt' 'target'.TMPOPT/OPTIONS $ PURGE 'target'.TMPOPT poco-1.3.6p1-all/build_vcexpress.cmd0000644000076500001200000000006611313735450020140 0ustar guenteradmin00000000000000@echo off buildwin 90 build shared both yes vcexpress poco-1.3.6p1-all/build_vs71.cmd0000644000076500001200000000005411313735450016713 0ustar guenteradmin00000000000000@echo off buildwin 71 build shared both yes poco-1.3.6p1-all/build_vs80.cmd0000644000076500001200000000005411313735450016713 0ustar guenteradmin00000000000000@echo off buildwin 80 build shared both yes poco-1.3.6p1-all/build_vs90.cmd0000644000076500001200000000005411313735450016714 0ustar guenteradmin00000000000000@echo off buildwin 90 build shared both yes poco-1.3.6p1-all/buildvms.com0000644000076500001200000000105011313735443016573 0ustar guenteradmin00000000000000$ ! $ ! BUILDVMS.COM $ ! $ ! $Id: //poco/1.3/buildvms.com#1 $ $ ! $ ! OpenVMS build procedure $ ! $ $ options == "''p1' ''p2' ''p3' ''p4' ''p5'" $ $ base = F$ENVIRONMENT("DEFAULT") $ base = base - "]" + ".]" $ define/nolog POCO_BASE 'base' $ build :== @POCO_BASE:[build.vms]build.com $ $ set def [.CppUnit] $ build 'options' $ $ set def [-.Foundation] $ build 'options' $ $ set def [.testsuite] $ build testlibrary 'options' $ build testsuite 'options' $ $ set def [--.XML] $ build 'options' $ $ set def [.testsuite] $ build 'options' $ $ set def [--] poco-1.3.6p1-all/buildwin.cmd0000755000076500001200000001444611313735443016570 0ustar guenteradmin00000000000000@echo off setlocal rem rem buildwin.cmd rem rem command-line build script for MS Visual Studio rem rem Usage: rem ------ rem buildwin VS_VERSION [ACTION] [LINKMODE] [CONFIGURATION] [SAMPLES] [DEVENV] rem VS_VERSION: 71|80|90 rem ACTION: build|rebuild|clean rem LINKMODE: static|shared|both rem CONFIG: release|debug|both rem SAMPLES: yes|no (shared only) rem DEVENV: devenv|vcexpress rem rem VS_VERSION is required argument. Default is build all. rem Change OPENSSL_DIR to match your setup set OPENSSL_DIR=c:\OpenSSL set OPENSSL_INCLUDE=%OPENSSL_DIR%\include set OPENSSL_LIB=%OPENSSL_DIR%\lib\VC set INCLUDE=%INCLUDE%;%OPENSSL_INCLUDE% set LIB=%LIB%;%OPENSSL_LIB% set POCO_BASE=%CD% set PATH=%POCO_BASE%\bin;%PATH% rem VS version {71|80|90} if "%1"=="" goto usage set VS_VERSION=vs%1 if "%6"=="" goto USE_DEVENV set BUILD_TOOL="%6" goto USE_CUSTOM :USE_DEVENV set BUILD_TOOL=devenv :USE_CUSTOM rem Action [build|rebuild|clean] set ACTION=%2 if not "%ACTION%"=="build" ( if not "%ACTION%"=="rebuild" ( if not "%ACTION%"=="" ( if not "%ACTION%"=="clean" goto usage))) if "%ACTION%"=="" (set ACTION="build") rem Link mode [static|shared|both] set LINK_MODE=%3 if not "%LINK_MODE%"=="static" ( if not "%LINK_MODE%"=="shared" ( if not "%LINK_MODE%"=="" ( if not "%LINK_MODE%"=="both" goto usage))) rem Configuration [release|debug|both] set CONFIGURATION=%4 if not "%CONFIGURATION%"=="release" ( if not "%CONFIGURATION%"=="debug" ( if not "%CONFIGURATION%"=="" ( if not "%CONFIGURATION%"=="both" goto usage))) rem Samples [yes|no] set SAMPLES=%5 if "%SAMPLES%"=="" (set SAMPLES=yes) set RELEASE_SHARED=0 set DEBUG_SHARED=0 set DEBUG_STATIC=0 set RELEASE_STATIC=0 if "%LINK_MODE%"=="shared" ( if "%CONFIGURATION%"=="release" (set RELEASE_SHARED=1) else ( if "%CONFIGURATION%"=="both" (set RELEASE_SHARED=1) else ( if "%CONFIGURATION%"=="" (set RELEASE_SHARED=1)))) if "%LINK_MODE%"=="shared" ( if "%CONFIGURATION%"=="debug" (set DEBUG_SHARED=1) else ( if "%CONFIGURATION%"=="both" (set DEBUG_SHARED=1) else ( if "%CONFIGURATION%"=="" (set DEBUG_SHARED=1)))) if "%LINK_MODE%"=="static" ( if "%CONFIGURATION%"=="release" (set RELEASE_STATIC=1) else ( if "%CONFIGURATION%"=="both" (set RELEASE_STATIC=1) else ( if "%CONFIGURATION%"=="" (set RELEASE_STATIC=1)))) if "%LINK_MODE%"=="static" ( if "%CONFIGURATION%"=="debug" (set DEBUG_STATIC=1) else ( if "%CONFIGURATION%"=="both" (set DEBUG_STATIC=1) else ( if "%CONFIGURATION%"=="" (set DEBUG_STATIC=1)))) if "%LINK_MODE%"=="both" ( if "%CONFIGURATION%"=="debug" ( set DEBUG_STATIC=1 set DEBUG_SHARED=1) else ( if "%CONFIGURATION%"=="release" ( set RELEASE_STATIC=1 set RELEASE_SHARED=1) else ( if "%CONFIGURATION%"=="both" ( set DEBUG_STATIC=1 set DEBUG_SHARED=1 set RELEASE_STATIC=1 set RELEASE_SHARED=1) else ( if "%CONFIGURATION%"=="" ( set DEBUG_STATIC=1 set DEBUG_SHARED=1 set RELEASE_STATIC=1 set RELEASE_SHARED=1))))) if "%LINK_MODE%"=="" ( if "%CONFIGURATION%"=="debug" ( set DEBUG_STATIC=1 set DEBUG_SHARED=1) else ( if "%CONFIGURATION%"=="release" ( set RELEASE_STATIC=1 set RELEASE_SHARED=1) else ( if "%CONFIGURATION%"=="both" ( set DEBUG_STATIC=1 set DEBUG_SHARED=1 set RELEASE_STATIC=1 set RELEASE_SHARED=1) else ( if "%CONFIGURATION%"=="" ( set DEBUG_STATIC=1 set DEBUG_SHARED=1 set RELEASE_STATIC=1 set RELEASE_SHARED=1))))) echo Building: if %DEBUG_SHARED%==1 (echo debug_shared) if %RELEASE_SHARED%==1 (echo release_shared) if %DEBUG_STATIC%==1 (echo debug_static) if %RELEASE_STATIC%==1 (echo release_static) rem build for up to 4 levels deep for /f %%G in ('findstr /R "." components') do ( if exist %%G ( cd %%G for /f "tokens=1,2,3,4 delims=/" %%Q in ("%%G") do ( if exist %%Q_%VS_VERSION%.sln ( echo. echo ========== Building %%G ========== if %DEBUG_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_shared %%Q_%VS_VERSION%.sln) if %RELEASE_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% release_shared %%Q_%VS_VERSION%.sln) if %DEBUG_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_static %%Q_%VS_VERSION%.sln) if %RELEASE_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% release_static %%Q_%VS_VERSION%.sln) ) if exist %%R_%VS_VERSION%.sln ( echo. echo ========== Building %%G ========== if %DEBUG_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_shared %%R_%VS_VERSION%.sln) if %RELEASE_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% release_shared %%R_%VS_VERSION%.sln) if %DEBUG_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_static %%R_%VS_VERSION%.sln) if %RELEASE_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% release_static %%R_%VS_VERSION%.sln) ) if exist %%S_%VS_VERSION%.sln ( echo. echo ========== Building %%G ========== if %DEBUG_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_shared %%S_%VS_VERSION%.sln) if %RELEASE_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% release_shared %%S_%VS_VERSION%.sln) if %DEBUG_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_static %%S_%VS_VERSION%.sln) if %RELEASE_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% release_static %%S_%VS_VERSION%.sln) ) if exist %%T_%VS_VERSION%.sln ( echo. echo ========== Building %%G ========== if %DEBUG_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_shared %%T_%VS_VERSION%.sln) if %RELEASE_SHARED%==1 (%BUILD_TOOL% /useenv /%ACTION% release_shared %%T_%VS_VERSION%.sln) if %DEBUG_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% debug_static %%T_%VS_VERSION%.sln) if %RELEASE_STATIC%==1 (%BUILD_TOOL% /useenv /%ACTION% release_static %%T_%VS_VERSION%.sln) ) ) cd %POCO_BASE% ) ) if "%SAMPLES%"=="no" goto :EOF rem root level component samples for /f %%G in ('findstr /R "." components') do ( if exist %%G\samples\samples_%VS_VERSION%.sln ( cd %%G\samples echo. echo ========== Building %%G/samples ========== if %DEBUG_SHARED%==1 %BUILD_TOOL% /useenv /%ACTION% debug_shared samples_%VS_VERSION%.sln if %RELEASE_SHARED%==1 %BUILD_TOOL% /useenv /%ACTION% release_shared samples_%VS_VERSION%.sln cd %POCO_BASE% ) ) goto :EOF :usage echo Usage: echo ------ echo buildwin VS_VERSION [ACTION] [LINKMODE] [CONFIGURATION] [SAMPLES] [DEVENV] echo VS_VERSION: "71|80|90" echo ACTION: "build|rebuild|clean" echo LINKMODE: "static|shared|both" echo CONFIG: "release|debug|both" echo SAMPLES: "yes|no" (shared only) echo DEVENV: "devenv|vcexpress" echo. echo Default is build all. endlocal poco-1.3.6p1-all/CHANGELOG0000644000076500001200000017035111313735443015473 0ustar guenteradmin00000000000000This is the changelog file for the POCO C++ Libraries. Release 1.3.6p1 (2009-12-21) ============================ - added support for using external zlib, pcre, expat and sqlite3 instead of bundled ones (-DPOCO_UNBUNDLED, configure --unbundled) - fixed SF# 2911407: Add sh4 support - fixed SF# 2912746: RSAKey::EXP_LARGE doesn't work - fixed SF# 2904119: abstractstrategy uses std::set but do not includes it - fixed SF# 2909946: localtime NULL pointer - fixed SF# 2914986: potential expat DoS security issues (CVE-2009-3560 and CVE-2009-3720) - fixed SF# 2916305: SSL Manager crashes - fixed SF# 2903676: Tuple TypeHander does not handle composites. Release 1.3.6 (2009-11-24) ========================== - added Environment::processorCount() - added POCO_VERSION macro to Poco/Foundation.h - fixed SF# 2807527: Poco::Timer bug for long startInterval/periodic interval - fixed a bug similar to SF# 2807527 in Poco::Util::Timer. - fixed SF# 2795395: Constructor doesn't treat the params "key" and "iv" - fixed SF# 2804457: DateTime::checkLimit looks wrong - fixed SF# 2804546: DateTimeParser requires explicit RFC1123 format - added ReleaseArrayPolicy to Poco::SharedPtr - upgraded to SQLite 3.6.20 - fixed SF# 2782709: Missing semicolons in "Logger.h" convenience - fixed SF# 2526407: DefaultStrategy.h ++it instead of it++ in a loop - fixed SF# 2502235: Poco STLPort patch - fixed SF# 2186643: Data::Statement::reset() not implemented in 1.3.3 - fixed SF# 2164227: Allow File opened read only by FileInputSteam to be writable - fixed SF# 2791934: use of char_traits::copy in BufferedStreamBuf::underflow - fixed SF# 2807750: Support additional SQL types in SQLite - fixed documentation bugs in Timed/PriorityNotificationQueue - fixed SF# 2828401: Deadlock in SocketReactor/NotificationCenter (also fixes patch# 1956490) NotificationCenter now uses a std::vector internally instead of a std::list, and the mutex is no longer held while notifications are sent to observers. - fixed SF# 2835206: File_WIN32 not checking aganist INVALID_HANDLE_VALUE - fixed SF# 2841812: Posix ThreadImpl::sleepImpl throws exceptions on EINTR - fixed SF# 2839579: simple DoS for SSL TCPServer, HTTPS server No SSL handshake is performed during accept() - the handshake is delayed until sendBytes(), receiveBytes() or completeHandshake() is called for the first time. This also allows for better handshake and certificate validation when using nonblocking connections. - fixed SF# 2836049: Possible handle leak in FileStream If sync() fails, close() now simply set's the stream's bad bit. In any case, close() closes the file handle/descriptor. - fixed SF# 2814451: NetSSL: receiveBytes crashes if socket is closed - added a workaround for Vista service network initialization issue (an Windows service using the Net library running under Vista will crash in the call to WSAStartup() done in NetworkInitializer). Workaround is to call WSAStartup() in the application's main(). Automatic call to WSAStartup() in the Net library can now be disabled by compiling Net with -DPOCO_NET_NO_AUTOMATIC_WSASTARTUP. Also the new Poco::Net::initializeNetwork() and Poco::Net::uninitializeNetwork() functions can be used to call WSAStartup() and WSACleanup(), respectively, in a platform-independent way (on platforms other than Windows, these functions will simply do nothing). - added VCexpress build script support (contributed by Jolyon Wright) - fixed SF# 2851052: Poco::DirectoryIterator copy constructor is broken - fixed SF# 2851197: IPAddress ctor throw keyword missing - added Poco::ProtocolException - PageCompiler improvements: new tags, support for buffered output, etc. - better error reporting in Data MySQL connector (patch #2881270 by Jan "HanzZ" Kaluza) - fixed SF# 1892462: FTPClient:Choose explicitely between EPSV and PASV - fixed SF# 2806365: Option for PageCompiler to write output to different dir - fixed a documentation bug (wrong sample code) in Process::launch() documentation - added --header-output-dir option to PageCompiler - fixed SF# 2849144: Zip::Decompress notifications error - SAXParser has a new feature: "http://www.appinf.com/features/enable-partial-reads". See ParserEngine::setEnablePartialReads() for a description of what this does. - fixed SF# 2876179: MySQL Signed/Unsigned value bug - fixed SF# 2877970: possible bug in timer task - fixed SF# 2874104: wrong parsing empty http headers - fixed SF# 2860694: Incorrect return code from SecureStreamSocketImpl::sendBytes - fixed SF# 2849750: Possible bug with XMLWriter? - added MailMessage::encodeWord() to support RFC 2047 word encoded mail header fields when sending out mail containing non-ASCII characters. - fixed SF# 2890975: SMTPClientSession bug with 7BIT encoding - fixed an issue with retrieving the value of socket options on Windows 7. Before obtaining the value of a socket, we now initialize the variable receiving the socket option value to zero. - fixed SF# 2836141: Documentation errors - fixed SF# 2864232: Socket::select() does not detect closed sockets on windows - fixed SF# 2812143: Socket::select() should check socket descriptors... - fixed SF# 2801750: NetworkInterface forName returns wrong subnetMask - fixed SF# 2816315: Problem with POSIX Thread::sleepImpl - fixed SF# 2795646: IPv6 address parsing bug - fixed #0000092: ServerApplication::waitForTerminationRequest(), SIGINT and GDB. Poco::Util::ServerApplication::waitForTerminationRequest() no longer registers a signal handler for SIGINT if the environment variable POCO_ENABLE_DEBUGGER is defined. - fixed SF# 2896070: Poco::Net::Context with non-ASCII paths - added Unicode Surrogate support to Poco::UTF16Encoding. See Poco::TextEncoding::queryConvert() and Poco::TextEncoding::sequenceLength() for how this is implemented. Contributed by Philippe Cuvillier. - fixed SF# 2897650: [branch 1.3.6] Net.SocketAddress won't compile for CYGWIN - fixed SF# 2896161: Building on Windows fails when basedir has space in it - fixed SF# 2864380: Memory leak when using secure sockets - NetSSL_OpenSSL: the SSL/TLS session cache is now disabled by default and can be enabled per Context using Poco::Net::Context::enableSessionCache(). - fixed SF# 2899039: Wrong DST handling in LocalDateTime - added RWLock::ScopedReadLock and RWLock::ScopedWriteLock (contributed by Marc Chevrier) - added Thread::TID type, as well as Thread::tid() and Thread::currentTid() to obtain the native thread handle/ID - added Zip file comment support - On Windows, Poco::SharedLibrary::load() now uses LoadLibraryEx instead of LoadLibrary and uses the LOAD_WITH_ALTERED_SEARCH_PATH if an absolute path is specified. This will add the directory containing the library to the search path for DLLs that the loaded library depends upon. - Mac OS X build settings now match those used by default Xcode projects, making linking the POCO libs to Xcode projects easier - Replaced use of std::valarray in Poco::Net::ICMPEventArgs with std::vector due to issues with std::valarray together with STDCXX debug mode on OS X Release 1.3.5 (2009-05-11) ========================== - fixed SF# 2779410: Poco::Data::ODBC::HandleException impovement - fixed wrong exception text for Poco::UnhandledException - Fixed a problem with SSL shutdown that causes clients (web browsers) to hang when the server attempts to perform a clean SSL shutdown. We now call SSL_shutdown() once, even if the shutdown is not complete after the first call. - added Poco::Crypto::X509Certificate::save() - fixed a bug in Poco::Zip::Decompress that results in wrong paths for extracted files - fixed a bug in Poco::Zip::ZipManipulator where the Zip file was opened in text format on Windows. - added Poco::Crypto::X509Certificate::issuedBy() to verify certificate chain. - fixed 0000089: Thread::sleep() on Linux is extremely inaccurate - added methods to extract the contents of specific fields from the subject and issuer distinguished names of a certificate. Release 1.3.4 (2009-04-21) ========================== - fixed SF# 2611804: PropertyFileConfiguration continuation lines - fixed SF# 2529788: ServerApplication::beDaemon() broken - fixed SF# 2445467: Bug in Thread_WIN32.cpp - Improved performance of HTTP Server by removing some string copy operations - fixed SF# 2310735: HTTPServer: Keep-Alive only works with send() - fixed appinf.com IP address in Net testsuite - fixed RFC-00188: NumberFormatter and float/double numbers - added --pidfile option to ServerApplication on Unix - fixed SF# 2499504: Bug in Win32_Thread when using from dll (fixed also for POSIX threads) - fixed SF# 2465794: HTTPServerRequestImpl memory leak - fixed SF# 2583934: Zip: No Unix permissions set - the NetSSL_OpenSSL library has been heavily refactored - added NumberFormatter::append*() and DateTimeFormatter::append() functions - use NumberFormatter::append() and DateTimeFormatter::append() instead of format() where it makes sense to gain some performance - added system.dateTime and system.pid to Poco::Util::SystemConfiguration - added %F format specifier (fractional seconds/microseconds) to DateTimeFormatter, DateTimeParser and PatternFormatter. - fixed SF# 2630476: Thread_POSIX::setStackSize() failure with g++ 4.3 - fixed SF# 2679279: Handling of -- option broken - added compile options to reduce memory footprint of statically linked applications by excluding various classes from automatically being linked. See the POCO_NO_* macros in Poco/Config.h. - fixed SF# 2644940: on Windows the COMPUTER-NAME and the HOSTNAME can be different - added DNS::hostName() function - added build configuration for iPhone (using Apple's SDK) - basic support for AIX 5.x/xlC 8 - fixed a bug resulting in a badly formatted exception message with IOException thrown due to a socket-related error - fixed SF# 2644718: NetworkInterface name conflict in MinGW - added a missing #include to CryptoTransform.h - fixed SF# 2635377: HTTPServer::HTTPServer should take AutoPtr - replaced plain pointers with smart pointers in some interfaces - upgraded to sqlite 3.6.13 - improved Data::SQLite error reporting - Poco::Glob now works with UTF-8 encoded strings and supports case-insensitive comparison. This also fixes SF# 1944831: Glob::glob on windows should be case insensitve - added Twitter client sample to Net library - Fixed SF# 2513643: Seg fault in Poco::UTF8::toLower on 64-bit Linux - Poco::Data::SessionPool: the janitor can be disabled by specifying a zero idle time. - added Poco::Data::SessionPool::customizeSession() - added support for different SQLite transaction modes (DEFERRED, IMMEDIATE, EXCLUSIVE) - fixed a few wrong #if POCO_HAVE_IPv6 in the Net library - added support for creating an initialized, but unconnected StreamSocket. - added File::isDevice() - added family() member function to SocketAddress, - Data::SQLite: added support for automatic retries if the database is locked - XMLConfiguration is now writable - fixed an IPv6 implementation for Windows bug in HostEntry - Timer class improvement: interval between callback is no longer influenced by the time needed to execute the callback. - added PriorityNotificationQueue and TimedNotificationQueue classes to Foundation. These are variants of the NotificationQueue class that support priority and timestamp-tagged notifications. - added Poco::Util::Timer class. This implements a timer that can schedule different tasks at different times, using only one thread. - the signatures of Poco::NotificationQueue and Poco::NotificationCenter member functions have been changed to accept a Poco::Notification::Ptr instead of Poco::Notification* to improve exception safety. This change should be transparent and fully backwards compatible. The signature of the methods returning a Poco::Notification* have not been changed for backwards compatibility. It is recommended, that any Notification* obtained should be immediately assigned to a Notification::Ptr. - SQLite::SessionImpl::isTransaction() now uses sqlite3_get_autocommit() to find out about the transaction state. - refactored Crypto library to make it independent from NetSSL_OpenSSL. - added support for RSA-MD5 digital signatures to Crypto library. - removed SSLInitializer from NetSSL library (now moved to Crypto library) - added build configs for static libraries to Crypto library - OpenSSL now depends on Crypto library (which makes more sense than vice versa, as it was before). Poco::Net::X509Certificate is now a subclass of Poco::Crypto::X509Certificate (adding the verify() member function) and the Poco::Net::SSLInitializer class was moved to Poco::Crypto::OpenSSLInitializer. - added build configs for static libraries to Zip - added batch mode to CppUnit::WinTestRunner. WinTestRunnerApp supports a batch mode, which runs the test using the standard text-based TestRunner from CppUnit. To enable batch mode, start the application with the "/b" or "/B" command line argument. Optionally, a path to a file where the test output will be written to may be given: "/b:" or "/B:". When run in batch mode, the exit code of the application will denote test success (0) or failure (1). - testsuites now also work for static builds on Windows - The IPv6 support for Windows now basically works (Net library compiled with POCO_HAVE_IPv6) - fixed a potential error when shutting down openssl in a statically linked application - added static build configs to Data library - added Poco::AtomicCounter class, which uses OS-specific APIs for atomic (thread-safe) manipulation of counter values. - Poco::RefCountedObject and Poco::SharedPtr now use Poco::AtomicCounter for reference counting - fixed SF# 2765569: LoadConfiguration failing from current directory Release 1.3.3p1 (2008-10-09) ============================ - Fixed SF# 2153031: 1.3.3 Crypto won't compile on 64-bit Linux - Fixed a warning in MySQL connector - Updated README - The global Makefile in the Zip archive is no longer broken Release 1.3.3 (2008-10-07) ========================== - Threads now have optional user-settable stack size (if the OS supports that feature) - Events now support simplified delegate syntax based on delegate function template. See Poco::AbstractEvent documentation for new syntax. - Cache supports new access expire strategy. - Upgraded to SQLite 3.6.2 - Upgraded to PCRE 7.8 - added HttpOnly support to Poco::Net::HTTPCookie - NetworkInterface now has displayName() member (useful only on Windows) - Poco::Util::WinRegistryKey now has a read-only mode - Poco::Util::WinRegistryKey::deleteKey() can now recursively delete registry keys - Poco::File::created() now returns 0 if the creation date/time is not known, as it's the case on most Unix platforms (including Linux). On FreeBSD and Mac OS X, it returns the real creation time. - Time interval based log file rotation (Poco::FileChannel) now works correctly. Since there's no reliable and portable way to find out the creation date of a file (Windows has the tunneling "feature", most Unixes don't provide the creation date), the creation/rotation date of the log file is written into the log file as the first line. - added Environment::nodeId() for obtaining the Ethernet address of the system (this is now also used by UUIDGenerator - the corresponding code from UUIDGenerator was moved into Environment) - added a release policy argument to SharedPtr template - Socket::select() will no longer throw an InvalidArgumentException on Windows when called with no sockets at all. If all three socket sets are empty, Socket::select() will return 0 immediately. - SocketReactor::run() now catches exceptions and reports them via the ErrorHandler. - SocketReactor has a new IdleNotification, which will be posted when the SocketReactor has no sockets to handle. - added referenceCount() method to Poco::SharedPtr. - POCO now builds with GCC 4.3 (but there are some stupid warnings: "suggest parentheses around && within ||". - Solution and project files for Visual Studio 2008 are included - The Zip library is now officially part of the standard POCO release. - The Crypto library (based on OpenSSL) has been added. The original code was kindly contributed by Ferdinand Beyer. - A Data Connector to MySQL, contributed by Sergey Kholodilov, is now part of the POCO release. - fixed SF# 1859738: AsyncChannel stall - fixed SF# 1815124: XML Compile failed on VS7.1 with XML_UNICODE_WCHAR_T - fixed SF# 1867340: Net and NetSSL additional dependency not set - ws2_32.lib - fixed SF# 1871946: no exception thrown on error - fixed SF# 1881113: LinearHashTable does not conform to stl iterators - fixed SF# 1899808: HTMLForm.load() should call clear() first - fixed SF# 2030074: Cookie problem with .NET server - fixed SF# 2009707: small bug in Net/ICMPPacketImpl.cpp - fixed SF# 1988579: Intel Warning: invalid multibyte character sequence - fixed SF# 2007486: Please clarify license for Data/samples/* - fixed SF# 1985180: Poco::Net::DNS multithreading issue - fixed SF# 1968106: DigestOutputStream losing data - fixed SF# 1980478: FileChannel loses messages with "archive"="timestamp" - fixed SF# 1906481: mingw build WC_NO_BEST_FIT_CHARS is not defined - fixed SF# 1916763: Bug in Activity? - fixed SF# 1956300: HTTPServerConnection hanging - fixed SF# 1963214: Typo in documentation for NumberParser::parseFloat - fixed SF# 1981865: Cygwin Makefile lacks ThreadTarget.cpp - fixed SF# 1981130: pointless comparison of unsigned integer with zero - fixed SF# 1943728: POCO_APP_MAIN namespace issue - fixed SF# 1981139: initial value of reference to non-const must be an lvalue - fixed SF# 1995073: setupRegistry is broken if POCO_WIN32_UTF8 enabled - fixed SF# 1981125: std::swap_ranges overloading resolution failed - fixed SF# 2019857: Memory leak in Data::ODBC Extractor - fixed SF# 1916761: Bug in Stopwatch? - fixed SF# 1951443: NetworkInterface::list BSD/QNX no netmask and broadcast addr - fixed SF# 1935310: Unhandled characters in Windows1252Encoding - fixed SF# 1948361: a little bug for win32 - fixed SF# 1896482: tryReadLock intermittent error - workaround for SF# 1959059: Poco::SignalHandler deadlock the SignalHandler can now be disabled globally by adding a #define POCO_NO_SIGNAL_HANDLER to Poco/Config.h - fixed SF# 2012050: Configuration key created on read access - fixed SF# 1895483: PCRE - possible buffer overflow - fixed SF# 2062835: Logfile _creationDate is wrong - fixed SF# 2118943: out_of_bound access in Poco::Data::BLOB:rawContent - fixed SF# 2121732: Prevent InvalidArgumentException in SocketReactor - fixed SF# 1891132: Poco::Data::StatementImpl::executeWithLimit is not correct - fixed SF# 1951604: POCO refuses to compile with g++ 4.3.0 - fixed SF# 1954327: CYGWIN's pthread does not define PTHREAD_STACK_MIN - fixed SF# 2124636: Discrepancy between FileWIN32(U)::handleLastError - fixed SF# 1558300: MinGW/MSYS Builds - fixed SF# 2123266: Memory leak under QNX6 with dinkum library - fixed SF# 2140411: ScopedUnlock documentation bug - fixed SF# 2036460: UUID regression tests are failing on Linux with g++ 4.3.1 - fixed SF# 2150438: Tuple TypeHandler position increment size is wrong Release 1.3.2 (2008-02-04) ========================== Foundation, XML, Net, Util: - added POCO_NO_SHAREDMEMORY to Config.h - POCO_NO_WSTRING now really disables all wide string related calls - added template specialization for string hashfunction (performance) - XML parser performance improvements (SAX parser is now up to 40 % faster - added parseMemoryNP() to XMLReader and friends - URIStreamOpener improvement: redirect logic is now in URIStreamOpener. this enables support for redirects from http to https. - added support for temporary redirects and useproxy return code - added getBlocking() to Socket - added File::isHidden() - better WIN64 support (AMD64 and IA64 platforms are recognized) - added support for timed lock operations to [Fast]Mutex - SharedLibrary: dlopen() is called with RTLD_GLOBAL instead of RTLD_LOCAL (see http://gcc.gnu.org/faq.html#dso) - Poco::Timer threads can now run with a specified priority - added testcase for SF# 1774351 - fixed SF# 1784772: Message::swap omits _tid mem - fixed SF# 1790894: IPAddress(addr,family) doesn't fail on invalid address - fixed SF# 1804395: Constructor argument name wrong - fixed SF# 1806807: XMLWriter::characters should ignore empty strings - fixed SF# 1806994: property application.runAsService set too late - fixed SF# 1828908: HTMLForm does not encode '+' - fixed SF# 1831871: Windows configuration file line endings not correct. - fixed SF# 1845545: TCP server hangs on shutdown - fixed SF# 1846734: Option::validator() does not behave according to doc - fixed SF# 1856567: Assertion in DateTimeParser::tryParse() - fixed SF# 1864832: HTTP server sendFile() uses incorrect date - HTTPServerResponseImpl now always sets the Date header automatically in the constructor. - fixed SF# 1787667: DateTimeFormatter and time related classes (also SF# 1800031: The wrong behavior of time related classes) - fixed SF# 1829700: TaskManager::_taskList contains tasks that never started - fixed SF# 1834127: Anonymous enums in Tuple.h result in invalid C++ - fixed SF# 1834130: RunnableAdapter::operator= not returning a value - fixed SF# 1873924: Add exception code to NetException - fixed SF# 1873929: SMTPClientSession support for name in sender field - logging performance improvements (PatternFormatter) - fixed SF# 1883871: TypeList operator < fails for tuples with duplicate values - CYGWIN build works again (most things work but Foundation testsuite still fails) - new build configuration for Digi Embedded Linux (ARM9, uclibc) - new build configuration for PowerPC Linux Data: - fixed SF# 1724388: ODBC Diagnostics - fixed SF# 1804797: ODBC Statement multiple execution fails - fixed SF# 1803435: SessionPool onJanitorTimer called too often? - fixed SF# 1851997: Undefined Behavior in ODBC::Preparation - updated SQlite to 3.5.5 Release 1.3.1 (2007-08-08) ========================== Foundation, XML, Net, Util: - DynamicAny fixes for char conversions - fixed SF# 1733362: Strange timeout handling in SocketImpl::poll and Socket::select - fixed SF patch# 1728912: crash in POCO on Solaris - fixed SF# 1732138: Bug in WinRegistryConfiguration::getString - fixed SF# 1730790: Reference counting breaks NetworkInterface::list() - fixed SF# 1720733: Poco::SignalHandler bug - fixed SF# 1718724: Poco::StreamCopier::copyStream loops forever - fixed SF# 1718437: HashMap bug - changed LinearHashTable iterator implementation. less templates -> good thing. - fixed SF# 1733964: DynamicAny compile error - UUIDGenerator: fixed infinite loop with non ethernet interfaces - updated expat to 2.0.1 - fixed SF# 1730566: HTTP server throws exception - Glob supports symbolic links (additional flag to control behavior) - fixed a problem with non blocking connect in NetSSL_OpenSSL (see http://www.appinf.com/poco/wiki/tiki-view_forum_thread.php?comments_parentId=441&topics_threshold=0&topics_offset=29&topics_sort_mode=commentDate_desc&topics_find=&forumId=6) - fixed a problem with SSL renegotiation in NetSSL_OpenSSL (thanks to Sanjay Chouksey for the fix) - fixed SF# 1714753: NetSSL_OpenSSL: HTTPS connections fail with wildcard certs - HTTPClientSession: set Host header only if it's not already set (proposed by EHL) - NetworkInterface (Windows): Loopback interface now has correct netmask; interfaces that do not have an IP address assigned are no longer reported. - Fixes for VC++ W4 warnings from EHL - SharedMemory: first constructor has an additional "server" parameter Setting to true does not unlink the shared memory region when the SharedMemory object is destroyed. (Alessandro Oliveira Ungaro) - fixed SF# 1768231: MemoryPool constructor Data: - fixed SF# 1739989: Data::RecordSet::operator = () (in 1.3 branch) - fixed SF# 1747525: SQLite, Transactions and Session Pooling (in 1.3 branch) - upgraded to SQLite 3.4.1 Release 1.3.0 (2007-05-07) ========================== - added HashMap, HashSet classes - the HashFunction class template has been changed in an incompatible way. The member function formerly named hash() is now the function call operator. If you have defined your own HashFunction classes, you have to update your code. Sorry for the inconvenience. - added Poco::Tuple - added AbstractCache::getAllKeys(), improved performance of the get operation - fixed AbstractCache::size() to do cache replacement before returning the size - added additional match() method to RegularExpression and documented the fact that the simple match() method internally sets RE_ANCHORED and RE_NOTEMPTY. - added ExpirationDecorator template. Decorates data types so that they can be used with UniqueExpireCaches - added operator ! to AutoPtr and SharedPtr - Buffer uses std::size_t instead of int - Exception::what() now returns exception name instead of message - added poco_ndc_dbg() macro (same as poco_ndc(), but only enabled in debug builds) - added Environment::get(name, defaultValue); - Foundation.h now includes Config.h at the very beginning. - added replace() and replaceInPlace() to Poco/String.h - added AutoPtr::assign() and SharedPtr::assign() - added operator () to AbstractEvent - gcc Makefiles now strip release builds - Void now has a == and != operator - Base64Encoder and HexBinaryEncoder now support an unlimited line length (no newlines written), by specifying a line length of 0 - NumberParser now has stricter syntax requirements: garbage following a number leads to a SyntaxException (Thanks to phireis@gmail.com for the suggestion) - fixed SF# 1676830: Don't use -rpath in libraries - fixed SF# 1670279: AbstractConfiguration::unckeckedExpand crash - fixed a warning in Hashtable - HTTPClientSession now uses a keepAliveTimeout for better persistent connection handling - added DateTime::makeUTC() and DateTime::makeLocal() - added another constructor to LocalDateTime - POCO_WIN32_UTF8 is ignored on non-Windows platforms - fixed a timeout bug (with NetSSL) in HTTPSession - AsyncChannel is automatically opened with first log() - minor fix to NotificationQueue sample (reported by Laszlo Keresztfalvi) - added File::canExecute() and File::setExecutable() - added SharedMemory class to Foundation - added FileStream, FileInputStream, FileOutputStream to Foundation - added NodeAppender class to XML for faster DOM tree creation - HTTPServerRequest and HTTPServerResponse are now abstract base classes, actual functionality has moved into HTTPServerRequestImpl and HTTPServerResponseImpl. This allows us to plug other HTTP servers into POCO. - added DynamicAny class to Foundation - replaced std::fstream with Poco::FileStream across POCO. - added Poco::Checksum class to Foundation. - fixed SF# 1700811: conflict in threadpool - bugfix: File::moveTo() does not work if the target is a directory - File::copyTo() and File::moveTo() now copy/move directories recursively - refactored NetworkInterface (now using pimpl idiom); added broadcast address and netmask support - fixed SF# 1688982: POP3ClientSession fails when retrieving mails with attachment - fixed SF# 1655104: Enhance Poco::TextEncoding functionality - added Poco::Condition class, implementing a POSIX-style condition variable - fixed a bug in File::create() for Windows - added poco_static_assert (imported from boost) - added Thread::join(timeout) and Thread::tryJoin() - ClassLoader support for named manifests (see ClassLibrary.h - POCO_EXPORT_NAMED_MANIFEST) - POCO_WIN32_UTF8: UNICODE #define is no longer required (and no longer automatically defined in POCO_WIN32_UTF8 is defined) - PCRE: upgraded to PCRE version 7.1 - fixed SF# 1682162: Suggestion on thread priority - fixed SF# 1613460: MSVC/STLPort warnings - fixed SF# 1709358: Format double percent std::String bug - added WindowsConsoleChannel class to Foundation - added AutoPtr::unsafeCast<>() and SharedPtr::unsafeCast<>() - fixed SF# 1708552: Failed to build on arm and powerpc - fixed SF$ 1708529: Failed to build using GCC 4.3: missing #includes - fixed SF# 1710053: LogStream proposal - fixed a bug involving empty root directories in Windows DirectoryIterator implementation (see http://www.appinf.com/poco/wiki/tiki-view_forum_thread.php?comments_parentId=343&forumId=6) - robustness improvements to ActiveMethod - removed the opportunity for memory leaks in case something goes while invoking the method - made C library usage more C++-like - use C++ headers (e.g. ) instead of C ones (). Also, use C library functions in std namespace. - added Unicode and UTF8String for improved Unicode support. The Unicode class can be used to obtain the Unicode properties of a character. The UTF8 class provides case insensitive comparison and case conversion for UTF-8 encoded strings. - added UnWindows.h header file, replaced all #include with #include "Poco/UnWindows.h". See the Poco/UnWindows.h header file for a rationale and explanations. - fixed SF# 1713820: StreamSocketImpl::sendBytes sends too many bytes - File::copyTo(): on Windows, the copy now always has the read-only flag reset, to be consistent with other platforms. - With Microsoft Visual C++, the necessary POCO libraries are now implicitly linked when the corresponding header files are included (#pragma comment(lib, "PocoXYZ.lib") is used). To disable this, compile POCO with the preprocessor symbol POCO_NO_AUTOMATIC_LIBS #define'd (see Poco/Foundation.h and Poco/Config.h). - The Visual Studio project files for the POCO libraries now include configurations for building static libraries. Release 1.2.9 (2007-02-26) ========================== - fixed a formatting problem in Util::HelpFormatter - HTTPClientSession::sendRequest() now attempts to send the complete request in one network packet. - improved network performance of ChunkedOutputStream: chunk size and chunk data are sent in one network packet if possible - fixed SF# 1655035: Wrong expires field calculation in HTTPCookie (thanks to Sergey N. Yatskevich for this and other fixes) - fixed SF# 1655049: Fix discrepancy of a code to the description - fixed SF# 1655170: Poco::Timezone::standardName() problem on WIN32 - fixed SF# 1629095: POCO_WIN32_UTF8 problem There is a new function Path::transcode() that can be used to convert a path (or any other string) from UTF-8 to the current Windows code page. This string can the be passed as a filename to an fstream or fopen(). This function only does the conversion on Windows, and only, if POCO_WIN32_UTF8 is defined. Otherwise, it simply returns the unmodified argument. - fixed SF# 1659607: Probably a bug in Poco::Net::DialogSocket - HTTPServer network performance improvement: responses that fit into a single network packet sent with HTTPServerResponse::sendFile() or the new HTTPServerResponse::sendBuffer() are sent in only one packet. - added HTTPServerResponse::sendBuffer() - HTTPServer now sends a Bad Request response if it fails to parse the HTTP request header. - HTTPServer now sends an Internal Server Error response if the request handler throws an exception prior to sending a response.- enabled TCP_NODELAY per default on TCPServer/HTTPServer - fixed a bug in HTTP persistent connection handling (server does not send Connection: close when it reaches connection maximum) - HTMLForm - POST submission of URL encoded form no longer uses chunked transfer encoding (thus improving interoperability with certain web servers) - integrated Environment.cpp from Main (missing get(var, default)) - added missing AutoPtr include to Util/Application (and using Poco::AutoPtr is no longer necessary for POCO_APP_MAIN macro) - fixed SF# 1635420: Per Regents of the University of Calfornia letter, remove advertising from BSD licensed parts - fixed SF# 1633133: MultipartWriter writes superluous CR-LF at beginning Release 1.2.8 (2007-01-04) ========================== - fixed SF# 1613906: Util/Application.h and GCC 3.3 - fixed a byte order issue (failed test) in IPv6 address formatting - fixed SF# 1626640: Poco::Net::SocketReactor bug - fixed client side chunked transfer encoding handling - fixed client side persistent connection handling - fixed SF# 1623536: HTTP Server Chunked Transfer Encoding Bug - improved HTTP server exception text - fixed SF# 1616294: KeepAlive HTTPServerSession patch - fixed SF# 1616296: Trivial Poco::TaskCustomNotification patch - fixed SF# 1619282: PurgeStrategy bug fix - fixed SF# 1620855: Format problem there is a new format specifier %z for std::size_t, as well as a new flag ? for %d, %i, %o, %x meaning any signed or unsigned integer Release 1.2.7 (2006-12-07) ========================== - Poco::File: fixed root directory handling - fixed UUIDGenerator documentation - clarified Application::setUnixOptions() documentation - fixes for issue [SOAPLite Transport 0000023]: SOAP Transport Listener should be able to use existing HTTPServer instance - fixing mantis issues 13, 14, 15, 16, 17, 18, 19, 21 - fixed SF# 1597022: Signed/unsigned warning in StringTokenizer::operator[] - fixed SF# 1598601: Message::op= leaks - fixed SF# 1605960: PatternFormatter crashes on custom property - fixed SF# 1605950: Memory leak in Logger sample code - fixed SF# 1591635: Copy Paste Error in sample code - fixed SF# 1591512: SMTPClientSession response stream - fixed SF #1592776: LayeredConfiguration: getRaw should enumerate in reverse order - SF Patch # 1599848 ] VS 2005 Util build fails - Logger::dump() now uses std::size_t instead of int for buffer size - LayeredConfiguration now supports a priority value for each configuration. Also, it's possible to specify for each configuration added whether it should be writeable. - ServerApplication: cd to root directory only if running as a daemon - added Message::swap() - improvements to build system: global Makefile has correct dependencies for samples on Windows, samples build after libraries are ready configure supports --no-wstring and --no-fpenvironment flags build system supports POCO_FLAGS environment variable for compiler flags - RemoteGen: fixed error handling for write protected files (SystemException) fixing integral constant overflow messages with large cache expiration, m_ support for type serializers, case-insensitive comparison added Release 1.2.6 (2006-11-19) ========================== - added additional match() method to RegularExpression and documented the fact that the simple match() method internally sets RE_ANCHORED and RE_NOTEMPTY. - added ExpirationDecorator template. Decorates data types so that they can be used with UniqueExpireCaches - added operator ! to AutoPtr and SharedPtr - Buffer uses std::size_t instead of int - added poco_ndc_dbg() macro (same as poco_ndc(), but only enabled in debug builds) - Foundation.h now includes Config.h at the very beginning. - added AutoPtr::assign() and SharedPtr::assign() - added operator () to AbstractEvent - gcc Makefiles now strip release builds - documentation improvements Release 1.2.5 (2006-10-23) ========================== - Improved LoggingConfigurator: channel creation and configuration is now a two-step process. This means that the previous problems with PropertyFileConfiguration and IniFileConfiguration when referencing other channels are solved. - improved options handling: better handling of (non) ambiguities. If both an option named "help" and one named "helper" is specified, this no longer causes ambiguity errors. - added check for duplicate option definition - ThreadPool bugfix: fixed a crash that occurs on Linux multiprocessor machines (caused by an thread unsafe string assignment corrupting the heap...) (SF# 1575315) - improved ThreadPool performance - XML now compiles with -DXML_UNICODE_WCHAR_T (SF# 1575174) - fixed SF# 1572757: HTML forms can have more than one key/value pair with the same name - got rid of the dynamic casts in Events, Events/Cache: simpler/faster Delegate < operator, prevents some rare dynamic casts error from occuring when using StrategyCollection with Caches - improvements to Logger and LoggingConfigurator: * added Logger::unsafeGet() * added Logger::setProperty(loggerName, propertyName, value) * LoggingConfigurator now correctly (re)configures existing Loggers (prior to this change, if a Logger named "a.b.c" existed before the LoggingConfigurator started its work, and the LoggingConfigurator configured a Logger named "a.b", then "a.b.c" would not inherit the new configuration). - improvements to SplitterChannel and EventLogChannel configuration - improved LoggingRegistry exception messages - MessageHeader::read() is more liberal with malformed message headers. This fixes problems with certain network cameras sending malformed HTTP headers. Release 1.2.4 (2006-10-02) ========================== - some code beautifying and improvements to comments - DOMParser now automatically sets FEATURE_NAMESPACE_PREFIXES - fixed SF #1567051: DOMBuilder/DOMParser/NamespaceStrategy bug - fixed SF #1567364: POCO_APP_MAIN - added Document::getElementById() (two-argument) and getElementByIdNS() - added another test for DOMParser - added AutoPtr::isNull() (to be consistent with SharedPtr) - this release again compiles on PA-RISC HP-UX systems with aCC - added CMAKE support files contributed by Andrew J. P. Maclean Release 1.2.3 (2006-09-14) ========================== - configure script now checks if (auto)selected configuration is supported - fixed SF #1552904: NamedEvent bug? - fixed SF #1552787: POCO not handling EINTR - fixed SF #1552846: Random::~Random uses scalar delete - fixed SF #1552987: TLSSlot should explicitly default-construct _value - IPAddress no longer accepts an empty address string - split up Observer.h into AbstractObserver.h and Observer.h - added NObserver class template which supports an AutoPtr argument for the notification callback - changed EchoServer sample to use NObserver - some Windows-specific files were missing in the tarballs Release 1.2.2 (2006-09-01) ========================== - fixed SF # 1549973: NotificationCenter::hasObservers() returns wrong result - fixed a memory leak in EchoServer sample - fixed SocketReactor TimeoutNotification bug (SF #1549365, SocketNotifier::addObserver() incorrect behavior) - fixed SF# 1549513: MultipartReader does not work with Unix-style linefeeds - MailMessage and HTMLForm: processing of multipart messages will no longer fail if a PartHandler does not read all data from the part stream. - added additional test case (Unix-style line ends) to MultipartReaderTest Release 1.2.1 (2006-08-29) ========================== - fixed Config.h header (no more #undefs) Release 1.2.0 (2006-08-29) ========================== - DateTime fixes: Julian Day is no longer stored internally. Times (hours, minutes, seconds, ...) are now always taken from an utcValue (if available) and not from the Julian day. The Julian day is only used for calculating year, month and day (except when the Julian day is the only thing we have) This helps us get rid of rounding errors that the Julian Day arithmetic introduced.- on Windows, UUIDGenerator no longer uses Netbios, but GetAdaptersInfo instead - The main Makefile now has correct dependencies - updated poco-doc.pl with latest version by Caleb Epstein - fixed SF #1542722: InflatingInputStream: buffer error - improved Windows UTF-8 support - added Logger::names() - added configure script and make install target - XMLWriter bugfix: pretty-print bug with characters() and rawCharacters() - improvements to build system: support builds outside of source tree - added header doc conversion tool contributed by Caleb Epstein - fixed SF #1542618 (build/config/Linux patch) - bugfix: BinaryReader/BinaryWriter BOM is now 16 bits, as documented - fixed SF #1542247 (Compiler warning from OptionCallback) - fixed SF #1542253 (ServerApplication::handleOption doesn't call Application::handleOption) - added Application::stopOptionsProcessing() - updated samples - Util::Application command line handling now supports: * argument validation (Option::validator(); see Validator, IntValidator, RegExpValidator) * binding of argument values to config properties (Option::binding()) * callbacks for arguments (Option::callback()) * checking of required parameters - changed header file locations: Foundation headers are now in Poco (#include "Poco/Foundation.h") XML headers are now in Poco/XML, Poco/SAX and Poco/DOM (#include "Poco/XML/XML.h") Util headers are now in Poco/Util (#include "Poco/Util/Util.h") etc. Unfortunately, this change will break existing code. However, fixing the code is a matter of a few global search/replace operations and can be done quickly. On the plus side, POCO is now a much better citizen when used with other libraries. - changed namespaces: Foundation is now Poco XML is now Poco::XML Util is now Poco::Util Net is now Poco::Net - removed namespace macros - fixed some warnings reported by gcc -Wall -Wextra - fixed AutoPtr and LayeredConfiguration documentation - improved StreamSocket::receiveBytes() doc - added Pipe and PipeStream classes - added support for I/O redirection (pipes) to Process::launch() - added LogStream class (ostream interface to Logger) - improved Makefiles (no more double-building if clean all is specified) - added CppUnit and DateTime testsuite contributions by Andrew Marlow - improved Cygwin and minimal MinGW support - FileChannel: gzip compression if archived files now runs in a background thread (SF #1537481) - POCO now compiles with large (64-bit) file support on Linux (SF #1536634) - added format() function, which provides typesafe sprintf-like functionality (SF #1327621) - added File::isLink() - bugfix: dangling symbolic links in a directory no longer cause recursive remove to fail with file not found error - added Void class (useful as argument to ActiveMethod) - ActiveResult now supports exceptions - bugfix: Timezone::utcOffset() and Timezone::dst() returned wrong values on Unix platforms (SF #1535428) - added ActiveDispatcher class - added ActiveStarter class, which is a policy used by ActiveMethod for starting methods - ActiveRunnable moved to its own header file - ThreadPool: added startWithPriority(), which allows for running threads with a different priority - added error handling to dir sample - added additional test case to HTTPServer test suite- HTMLForm: should now work with request methods other than POST and GET (all non-POST requests are treated the same as GET) - clarified HTMLForm documentation - HTMLForm bugfix: uploaded files no longer end up in value; PartHandler is called instead - NameValueCollection: added get(name, defaultValue) - added HTTPFormServer sample - added Foundation::HashTable and SimpleHashTable - added Net::HTTPSessionFactory - improvements to AutoPtr and SharedPtr - improvements to namespaces handling in XMLWriter - Foundation Cache: fixed add implementation to match the docu: a 2nd add will now simply overwrite existing entries - added DateTime::isValid() - added Exception::rethrow() (virtual, must be overridden by all subclasses) - Timer can now use a user-supplied ThreadPool - added rethrow() to exception classes - Net: made some constructors explicit - Net: added SocketAddress constructor to HTTPClientSession - Net: added HTTPSession::networkException() to check for exceptions swallowed by stream classes - Net: added single string argument constructor to SocketAddress. - Net: improved HTTPClientSession error handling (no more "Invalid HTTP version string" exceptions when the server prematurely closes the connection due to too much load) - Net: improved HTTPSession error handling. Exceptions while sending and receiving data are stored for later retrieval and no longer get lost since streambufs swallow them. - Net: added HTTPLoadTest sample - fixed a bug when opening logfiles on Unix platforms causing an existing logfile to be truncated - bugfix: log file purge intervals given in months did not work, due to a stupid typo - added RawSocket and ICMP classes - UUID: fixed a doc formatting bug - NetworkInterface::list() now includes loopback interface on Windows (SF #1460309) - made Exception::message() and Exception::nested() inline - added Net::UnsupportedRedirectException - HTTPStreamFactory throws an UnsupportedRedirectException if it encounters a redirect to https - HTTP: fixed bad 100 Continue handling in client and server code - added CONTRIBUTORS file Release 1.1.2 (2006-07-07) ========================== - Changed license to Boost license - DBlite and NetSSL have been removed from the Boost-licensed release. Please contact Applied Informatics (info@appinf.com) if you're interested in them. Release 1.1.1 (2006-04-03) ========================== - NetSSL_OpenSSL now supports separate certificate verification settings for client and server. - fixed SF #1460309 (enumerating network interfaces failed on 64bit Linux) - TCPServer no longer crashes if accept() fails Release 1.1.0 (2006-03-23) ========================== - events no longer require awkward += new syntax - source code and documentation cleanups - basic support for new compilers and platforms Release 1.1b2 (2006-03-04) ========================== - made NetSSL threadsafe (added locking callbacks for OpenSSL) - improved OpenSSL initialization (random generator seeding) - various changes to improve compatibility with various platforms Release 1.1b1 (2006-03-03) ========================== - New Events package in Foundation. The package supports C#-style event handling - New Cache package in Foundation: a templates-based caching framework - added Any class to Foundation - added DBLite library - fixed a memory leak with layered configurations in the application - made POCO_DLL the default (unless POCO_STATIC is #defined) It is no longer necessary to specify POCO_DLL in projects that use Poco (SourceForge Patch #1408231 and Feature Request #1407575). - added Buffer template class to Foundation - added the UnicodeConverter utility class. This is mainly used for Windows Unicode support and probably of little use for anything else. - added Path::resolve() - added Windows Unicode support. This calls the Unicode variant of the Windows API functions. For this to work, all strings must be UTF-8 encoded and POCO_WIN32_UTF8 must be defined in all compilation units. - added StreamCopier::copyToString() - added URIStreamOpener::unregisterStreamFactory() and new variants of URIStreamOpener::open() that also work with filesystem paths. This fixes SourceForge Bug #1409064 and Feature Request #1409062. - added NodeIterator::currentNodeNP() to XML library - added some sanity checks to UTF8Encoding::convert() - added NetSSL - SSL support for Net library, based on OpenSSL - console output of processes launched with Process::launch() is now visible Release 1.0.0 (2006-01-19) ========================== - removed unnecessary console output from ProcessTest - documentation fixes Release 1.0b2 (2006-01-16) ========================== - added ProcessHandle class - Process::launch() now returns a ProcessHandle instead of a process ID. This fixes a potential problem on Windows with Process::wait() when the process terminates before wait() is called. - added SplitterChannel::close() - added Logger::destroy() - added POP3ClientSession::deleteMessage() - added test for Process::launch() - documentation fixes Release 1.0b1 (2006-01-09) ========================== - improved recognition of Windows paths in Path::parseGuess() - added setCurrentLineNumber()/getCurrentLineNumber() to CountingStreamBuf - improvememts to StreamTokenizer and Token; fixed documentation - added a workaround for some strange istream behaviour with VS 2005 and FTPClientSessionTest - improved exception/error reporting in cppunit - added POP3ClientSession - added Process::launch() and Process::wait() - added Mail sample - added MailStream and SMTPClientSession classes - renamed some methods in DialogSocket to make them more general - NullPartHandler has moved out of HTMLForm.cpp into a separate file - Base64Encoder now always writes \r\n line ends - MessageHeader::quote has an optional addition arg controlling the treatment of whitespace - bugfix: MultipartReader had a problem with empty lines (\r\n sequences) in a part - added MailMessage and MailRecipient classes - added text encoding support for Windows-1252 codepage Release 1.0a1 (2006-01-03) [internal] ===================================== - mediaType is used consistently to refer to a MIME media type (some occurences of contentType and mimeType have been replaced) - moved MediaType::quote() to MessageHeader and made it public - added MultipartWriter::stream() - Renamed AttachmentSource to PartSource and AttachmentHandler to PartHandler - SIGPIPE is always blocked in main thread on Unix systems - added EchoServer sample - fixed a bug in SocketImpl::setBlocking() - did exactly the opposite (value to ioctl was wrong) - fixed a memory leak in NotificationQueue sample - added comparison operators to Socket so that Sockets can be used as keys in maps - added Socket::setBlocking() - added StreamSocket::connectNB() (non-blocking connect) - added Observer::accepts() - added SocketReactor, SocketConnector and SocketAcceptor classes to support event-based socket programming - NamespacePrefixesStrategy now uses expat's XML_SetReturnNSTriplet(). The previously used separate namespace handling code has been removed. This improves performance if NamespacePrefixesStrategy is used (both the n amespaces and namespace-prefixes SAX2 features are used) - upgraded expat to 2.0 pre-release (2005-12-27) snapshot - added TeeInputStream and TeeOutputStream classes - added download sample for URIStreamOpener - renamed registerOpener() to registerFactory() in HTTPStreamFactory and FTPStreamFactory - added LineEndingConverter streams - added FTPClientSession - code and documentation clean-up - added DialogSocket class - reorganized HTTP test suites - added FTPClientSession and FTPStreamFactory - added DialogSocket class Release 0.96.1 (2005-12-28) =========================== - fixed a memory leak caused by a bug in Microsoft's stream implementation (see the comment in Foundation/StreamUtil.h for an explanation) - added samples for Net library - added uptime() and startTime() to Util::Application - added DateTimeFormatter::format() for Timespan - added ErrorHandler class and better exception handling for threads - added poco_debugger() and poco_debugger_msg() macros - added project and solution files for Visual Studio 2005 (due to some bugs/leaks in Microsofts standard library - see http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=e08bd793-3fef-40ff-adda-ed313e0eafcc we do not recommend using this for production purposes) - fixed two problems with out-of-range string iterator in Path (the testsuite triggered an assertion in VC++ 8.0) - fixed mac line endings in a few files - added a workaround to the class loader that fixes strange behavior with VC++ 8.0. There seems to be a problem with typeid() not returning a valid typeinfo under certain circumstances. - added buffer allocator argument to buffered stream buffer templates - added buffer pools to HTTP to reduce memory fragmentation and to improve performance - added Net to Windows build.cmd script - added swap() to various classes that already support assignment - added a null pointer check in DOMWriter::writeNode() - fixed documentation in BinaryWriter.h and BinaryReader.h - added explicit support for network byte order to BinaryReader and BinaryWriter - added basic support for FreeBSD (needs more testing) - BinaryReader: renamed readRawData() to readRaw() to be consistent with BinaryWriter::writeRaw() - added support for uppercase output to HexBinaryEncoder. - added MediaType class - added QuotedPrintableEncoder and QuotedPrintableDecoder classes - renamed ObjectFactory to Instantiator. This should prevent the confusion caused by DynamicFactory and ObjectFactory. Sorry for the inconvenience if you are already using this. - AttachmentSource::filename() now returns const string& - added StringAttachmentSource - replaced old-style C casts with C++ casts in NetworkInterface.cpp - MutexImpl (WIN32): replaced InitializeCriticalSection with InitializeCriticalSectionAndSpinCount, which should increase performance on multiprocessor or multicore systems when many locks are used. - fixed a problem with STLport 5.0 when compiling StreamTokenizer - HTTPStreamOpener now also works with no-path URIs (like http://www.appinf.com) - fixed wrong delete usage (plain delete instead of delete [] was used in a few cases) - fixed a handle leak in WinTestRunner Release 0.95.4 (2005-11-07) =========================== - fixed #1348006 and #1348005 Release 0.95.3 (2005-10-28) [internal] ====================================== - updated build scripts (patch #1339015) - added support for AMD64 platforms (patch #1339015) - MultipartWriter creates its own boundary if an empty string is passed in as boundary - made MultipartWriter::createBoundary() public - fixed wrong documentation for DateTimeFormat::HTTP_FORMAT - added support for HTTP Basic authentication - added support for HTTP Cookies - added support for HTML forms Release 0.95.2 (2005-10-22) [internal] ====================================== - fixed a potential problems with streams when close in destructor fails (added try..catch block around close in destructors) - added HTTPServer & friends - added hasIdleThreads() method to NotificationQueue - added TCPServer and friend - added support for HTTP proxies to HTTPClientSession and HTTPStreamOpener - fixed documentation bugs (Mutex.h, ClassLoader.h) Relesae 0.95.1 (2005-10-15) [internal] ====================================== - Tasks can now throw custom notifications (contributed by Alex Fabijanic) - renamed URIFileStreamFactory to FileStreamFactory - added a few methods to URI (setPathEtc(), getPathEtc(), getPathAndQuery()) - added new exception classes - fixed some documentation - added basic checks when reading a MessageHeader from a stream - added HTTP classes (testsuite still incomplete) - added MessageHeader, NameValueCollection, MultipartReader and MultipartWriter classes - added Timespan::useconds() - added ClassLoader::isLibraryLoaded() - Socket classes use Timespan::useconds() to fill struct timeval - added DatagramSocket, MulticastSocket and NetworkInterface classes - added socket classes and related basic stuff - added additonal constructor/assign to Timespan- added BasicBufferedBidirectionalStreamBuf - fixed a potential MT issue in Base64Decoder - code beautifying in [Un]BufferedStreamBuf - more improvements to ClassLoader - code cleanup and naming convention fixes (changed all *Imp classes to *Impl for consistency) Release 0.94.1 (2005-09-30) [internal] ====================================== - added MetaSingleton (based on a contribution by Alex Fabijanic) - added ClassLoader::create() - added ClassLoader::instance() - code clean-ups in FileChannel and related classes - added SimpleFileChannel - RotateAtTimeStrategy: ::getNextRollover() rewritten (buggy) - DateTime microseconds assert corrected asserts in computeGregorian() (except for year - see comment in computeGregorian()) milliseconds calculation modified in computeGregorian() microseconds assigned in computeGregorian() normalize() and checkLimit() private functions to correct cases of overflow for milli/microseconds - LocalDateTime: added timestamp() method - FileChannel: added "times" property (used to determine whether to use UTC or local time with RotateAtTimeStrategy) ::setProperty() modified (whenever "times" property is set, methods setRotation and setArchive are reinvoked to reflect the change) - FileChannel: added support for archived file compression and archived file purging - FileChannel tests modified - FileChannel: put LogFile, RotateStrategy and ArchiveStrategy into their own files - Message: added thread id field - PatternFormatter: added %I specifier for thread id - ThreadPool: PooledThread can be assigned a name - TaskManager: task name is reflected in thread name - fixed LocalDateTime::operator - (const Timespan&) [#0000004] - upon startup all loggers' channels are set to a console channel - improved search for application configuration files (see loadConfiguration()). - added Glob class (fixes #1249700) - upgraded to zlib 1.2.3 (fixes #1261712) - added Logger::dump() - fixed a wrong condition in Logger::log(const Message&) - Path::find() now also works with relative paths in addition to plain file names - added Path(const Path&, const Path&) constructor - added SharedPtr template - added Path::tryParse() - SAXParser::parse()/EntityResolverImpl now works for both URIs and local filesystem paths (fixes #1254812) Release 0.93.1 (2005-08-01) =========================== This release contains various new features, improvements and bugfixes: - bugfix: UUIDGenerator throws an exception if no connected ethernet adapter can be found (and thus no MAC address can be obtained) - added UUIDGenerator::createOne() method - added error handling to UUID sample application - added relational (==, !=, <, <=, >, >=) and arithmetic operators (+, -, +=, -=) to DateTime - added LocalDateTime class - added support for LocalDateTime to DateTimeParser and DateTimeFormatter - added enqueueUrgentNotification() to NotificationQueue - added support for timezone specifiers (%z, %Z) to PatternFormatter - added [] operator and count() to StringTokenizer - added elapsed() and isElapsed() to Timestamp - added tzd() to Timezone - added WinRegistryKey and WinService classes (Windows only) - added index operator and count() to StringTokenizer - added day/time-based log rotation (thanks to Alex Fabijanic), minor improvements to DateTimeParser - support for Mac OS X 10.4/gcc 4.0.0 - added NamedMutex and NamedEvent - added Process::kill() - added NoPermissionException - added Task and TaskManager classes - added ServerApplication class - bugfix: EventLogChannel - _logFile was not properly initialized in one constructor - bugfix: File::createDirectories did not work for hierarchies deeper than three - added Util::FilesystemConfiguration - documented logging policy: log() must open channel if it hasn't been opened yet - FileChannel::log() opens channel if necessary - the application reference passed to initialize() and reinitialize() is no longer const - improved application logging initialization - fixed a problem with configuration view and property placeholders - fixed Util build configuration for Visual Studio - improved application samples - fixed documentation for Semaphore class Release 0.92.1 (2005-05-09) =========================== This release introduces the Util library that provides support for configuration file parsing (different file formats), command line argument processing, logging configuration and a framework for command line/server applications. There have also been various changes to the Foundation library: - a new RefCountedObject class that acts as a base class for various classes that use reference counting - some missing members have been added to the AutoPtr template - various improvements and bugfixes to the Logging framework, as well as new LoggingFactory and LoggingRegistry classses, and a NullChannel class - the SignalHandler class (Unix platforms only) - ObjectFactory and DynamicFactory template classes - the Path::find method for searching a file in a list of directories - various new Exception classes Release 0.91.4 (2005-04-11) =========================== This is mainly a maintenance release that adds support for QNX Neutrino and OpenVMS. There are also minor bugfixes and improvements. The Unix build system has been modified to work on QNX Neutrino. The OpenVMS build system has been fixed and works now. Some missing #include's have been added for QNX Neutrino. Foundation/String.h: icompare now supports comparison with const char*; the classic C version of isspace() has been used in a few places instead of the C++ version, this has been fixed. Foundation/Exception.h: IllegalStateException added. Release 0.91.3 (2005-03-19) =========================== This is a maintenance release that adds support for Solaris/Sun Forte C++. No new features have been added. An implementation of FPEnvironment for Solaris has been included. All stream classes have been modified to work around an initialization problem that surfaced with Sun's C++ compiler when using STLport. Source-code compatibility with the previous release is not affected. Various minor changes, mostly adding missing #include's for Solaris. Release 0.91.2 (2005-02-27) =========================== Minor improvements to the Unix build system. No actual changes in the libraries. Release 0.91.1 (2005-02-21) =========================== This is the first public release of the C++ Portable Components. The release does not contain all features planned for the later 1.0 release (the NET library is missing, for example), but is already quite usable. Please refer to the README file for more information and instructions for building the libraries. -- $Id: //poco/1.3/dist/CHANGELOG#72 $ poco-1.3.6p1-all/components0000644000076500001200000000015511313735450016361 0ustar guenteradmin00000000000000CppUnit Foundation XML Util Net Crypto NetSSL_OpenSSL Data Data/SQLite Data/ODBC Data/MySQL Zip PageCompiler poco-1.3.6p1-all/configure0000755000076500001200000001305711313735443016167 0ustar guenteradmin00000000000000#! /bin/sh # # configure # # $Id: //poco/1.3/dist/configure#11 $ # # Configuration script for POCO. # # Invoke configure --help for help. # showhelp() { cat << ENDHELP usage: configure {options} Configure the POCO C++ Libraries. Options: --help Display this help screen. --config= Use the given build configuration. Available configurations are: `ls -C $base/build/config/` --prefix= Use the given install directory for make install. Default is /usr/local. --stdcxx-base= If (and only if) the $base/build/config selected with --config uses the Apache stdcxx library, then apache_stdcxx_install_prefix specifies the base directory where stdcxx is installed. --no-tests Do not build testsuites. --no-samples Do not build samples. --no-wstring Compile with -DPOCO_NO_WSTRING. Useful if your C++ compiler does not support std::wstring (such as uClibc-based systems). --no-fpenvironment Compile with -DPOCO_NO_FPENVIRONMENT. Useful if your C++ compiler has incomplete floating-point support (such as uClibc-based systems). --omit={,} Do not build the specified component(s). Example: --omit=Data/MySQL,Data/ODBC,Zip --include-path= Add search path for header files. --library-path= Add search path for library files. --poquito Omit a few features for smaller codesize when linking statically for embedded targets. --unbundled Use system-provided zlib, pcre, expat and sqlite instead of bundled ones. ENDHELP } # save cwd build=`pwd` # get directory where we are located cd `dirname $0` base=`pwd` cd $build if [ `uname` = "QNX" ] ; then EXPR=expr NOTFOUND=0 else EXPR="expr --" NOTFOUND="" fi tests="tests" samples="samples" flags="" omit="" includepath="" librarypath="" unbundled="" # parse arguments while [ "$1" != "" ] ; do val=`$EXPR "$1" : '--config=\(.*\)'` if [ "$val" != "$NOTFOUND" ] ; then config=$val; fi val=`$EXPR "$1" : '--prefix=\(.*\)'` if [ "$val" != "$NOTFOUND" ] ; then prefix=$val fi val=`$EXPR $1 : '--stdcxx-base=\(.*\)'` if [ "$val" != "$NOTFOUND" ] ; then stdcxx_base=$val fi val=`$EXPR "$1" : '--omit=\(.*\)'` if [ "$val" != "$NOTFOUND" ] ; then omit="$omit `echo $val | tr ',;' ' '`" fi val=`$EXPR "$1" : '--include-path=\(.*\)'` if [ "$val" != "$NOTFOUND" ] ; then includepath="$includepath `echo $val | tr ',;' ' '`" fi val=`$EXPR "$1" : '--library-path=\(.*\)'` if [ "$val" != "$NOTFOUND" ] ; then librarypath="$librarypath `echo $val | tr ',;' ' '`" fi if [ "$1" = "--no-samples" ] ; then samples="" fi if [ "$1" = "--no-tests" ] ; then tests="" fi if [ "$1" = "--no-wstring" ] ; then flags="$flags -DPOCO_NO_WSTRING" fi if [ "$1" = "--no-fpenvironment" ] ; then flags="$flags -DPOCO_NO_FPENVIRONMENT" fi if [ "$1" = "--poquito" ] ; then flags="$flags -DPOCO_NO_FILECHANNEL -DPOCO_NO_SPLITTERCHANNEL -DPOCO_NO_SYSLOGCHANNEL -DPOCO_UTIL_NO_INIFILECONFIGURATION -DPOCO_UTIL_NO_XMLCONFIGURATION" fi if [ "$1" = "--unbundled" ] ; then flags="$flags -DPOCO_UNBUNDLED" unbundled=1 fi if [ "$1" = "--help" ] ; then showhelp exit 0 fi shift done # autodetect build environment # ...special cases for CYGWIN or MinGW if [ "$config" = "" ] ; then config=`uname` cyg=`$EXPR $config : '\(CYGWIN\).*'` if [ "$cyg" = "CYGWIN" ] ; then config=CYGWIN else ming=`$EXPR $config : '\(MINGW\).*'` if [ "$ming" = "MINGW" ] ; then config=MinGW fi fi fi if [ ! -f "$base/build/config/$config" ] ; then echo "Unknown configuration: $config" echo "Please use the --config option to specify another build configuration" echo "The following configurations are available:" ls $base/build/config exit 1 fi if [ "$prefix" = "" ] ; then prefix=/usr/local fi # check for patches if [ -d $base/patches/$config ] ; then echo "NOTE: There are patches for your configuration available. Please apply them before compiling." fi # copy Makefile to build dir if [ "$base" != "$build" ] ; then cp $base/Makefile $build fi # create config.make echo '# config.make generated by configure script' >$build/config.make echo "POCO_CONFIG = $config" >>$build/config.make echo "POCO_BASE = $base" >>$build/config.make echo "POCO_BUILD = $build" >>$build/config.make echo "POCO_PREFIX = $prefix" >>$build/config.make echo "POCO_FLAGS = $flags" >>$build/config.make echo "OMIT = $omit" >>$build/config.make if [ "$stdcxx_base" != "" ] ; then echo "STDCXX_BASE = $stdcxx_base" >>$build/config.make fi if [ "$includepath" != "" ] ; then echo "POCO_ADD_INCLUDE = $includepath" >>$build/config.make fi if [ "$librarypath" != "" ] ; then echo "POCO_ADD_LIBRARY = $librarypath" >>$build/config.make fi if [ "$unbundled" != "" ] ; then echo "POCO_UNBUNDLED = 1" >>$build/config.make fi echo "export POCO_CONFIG" >>$build/config.make echo "export POCO_BASE" >>$build/config.make echo "export POCO_BUILD" >>$build/config.make echo "export POCO_PREFIX" >>$build/config.make echo "export POCO_FLAGS" >>$build/config.make if [ "$stdcxx_base" != "" ] ; then echo "export STDCXX_BASE" >>$build/config.make fi if [ "$includepath" != "" ] ; then echo "export POCO_ADD_INCLUDE" >>$build/config.make fi if [ "$librarypath" != "" ] ; then echo "export POCO_ADD_LIBRARY" >>$build/config.make fi if [ "$unbundled" != "" ] ; then echo "export POCO_UNBUNDLED " >>$build/config.make fi echo ".PHONY: poco" >>$build/config.make echo "poco: libexecs $tests $samples" >>$build/config.make echo "Configured for $config" poco-1.3.6p1-all/contrib/0000755000076500001200000000000011313735443015712 5ustar guenteradmin00000000000000poco-1.3.6p1-all/contrib/cmake/0000755000076500001200000000000011313735443016772 5ustar guenteradmin00000000000000poco-1.3.6p1-all/contrib/cmake/CMakeLists.txt0000644000076500001200000000754211313735443021542 0ustar guenteradmin00000000000000PROJECT (FTPTest) SET (EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin CACHE PATH "Single output directory for building all executables.") SET( TARGET_BASE_NAME "${PROJECT_NAME}" ) SET( LIB_NAME "${TARGET_BASE_NAME}Lib" ) #----------------------------------------------------------------------------- # Let's use the highest warning level. #----------------------------------------------------------------------------- IF(CMAKE_BUILD_TOOL MATCHES "(msdev|devenv|nmake)") # Use the highest warning level for visual studio. IF(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") STRING(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") ELSE(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") ENDIF(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") IF(CMAKE_C_FLAGS MATCHES "/W[0-4]") STRING(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") ELSE(CMAKE_C_FLAGS MATCHES "/W[0-4]") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4") ENDIF(CMAKE_C_FLAGS MATCHES "/W[0-4]") # Disable deprecation warnings for standard C functions in VS2005 and later IF(CMAKE_COMPILER_2005) ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE) ENDIF(CMAKE_COMPILER_2005) ENDIF(CMAKE_BUILD_TOOL MATCHES "(msdev|devenv|nmake)") IF(CMAKE_BUILD_TOOL MATCHES "make") IF(NOT CMAKE_CXX_FLAGS MATCHES "-Wall") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") ENDIF(NOT CMAKE_CXX_FLAGS MATCHES "-Wall") IF(NOT CMAKE_C_FLAGS MATCHES "-Wall") SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall") ENDIF(NOT CMAKE_C_FLAGS MATCHES "-Wall") ENDIF(CMAKE_BUILD_TOOL MATCHES "make") SET(Poco_DIR ${PROJECT_SOURCE_DIR}) FIND_PACKAGE(Poco REQUIRED) IF(${Poco_FOUND}) INCLUDE_DIRECTORIES(${Poco_INCLUDE_DIRS}) LINK_DIRECTORIES(${Poco_LIBRARY_DIRS}) ENDIF(WIN32) ENDIF(${Poco_FOUND}) #----------------------------------------------------------------------------- SET( EXE_NAME "${TARGET_BASE_NAME}" ) # Add any source files here. SET( EXE_SRCS "My File.cpp" ) # Add any include files here. SET( EXE_INCS "My File.h" ) #----------------------------------------------------------------------------- # The executable. ADD_EXECUTABLE(${EXE_NAME} ${EXE_SRCS} ${EXE_INCS}) TARGET_LINK_LIBRARIES ( ${EXE_NAME} "optimized" CppUnit "debug" CppUnitd "optimized" PocoFoundation "debug" PocoFoundationd "optimized" PocoNet "debug" PocoNetd "optimized" PocoUtil "debug" PocoUtild "optimized" PocoXML "debug" PocoXMLd ) # Copy the DLLS to where the executable is. # Only do this if you haven't set your path to the Poco DLLs. IF(WIN32) SET ( DLL_FILES_DEBUG ${Poco_BINARY_DIRS}/CppUnitd.dll ${Poco_BINARY_DIRS}/PocoFoundationd.dll ${Poco_BINARY_DIRS}/PocoNetd.dll ${Poco_BINARY_DIRS}/PocoUtild.dll ${Poco_BINARY_DIRS}/PocoXMLd.dll ) SET ( DLL_FILES_RELEASE ${Poco_BINARY_DIRS}/CppUnit.dll ${Poco_BINARY_DIRS}/PocoFoundation.dll ${Poco_BINARY_DIRS}/PocoNet.dll ${Poco_BINARY_DIRS}/PocoUtil.dll ${Poco_BINARY_DIRS}/PocoXML.dll ) # Copy these files to the build tree. ADD_CUSTOM_TARGET(CopyDll ALL echo "Copying dlls ...") FOREACH(file ${DLL_FILES_DEBUG}) GET_FILENAME_COMPONENT(fn ${file} NAME) SET(tgt ${EXECUTABLE_OUTPUT_PATH}/Debug/${fn}) SET(src ${file}) ADD_CUSTOM_COMMAND( TARGET CopyDll COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${src} ${tgt} COMMENT "Source copy of dlls" ) ENDFOREACH(file) FOREACH(file ${DLL_FILES_RELEASE}) GET_FILENAME_COMPONENT(fn ${file} NAME) SET(tgt ${EXECUTABLE_OUTPUT_PATH}/Release/${fn}) SET(src ${file}) ADD_CUSTOM_COMMAND( TARGET CopyDll COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${src} ${tgt} COMMENT "Source copy of dlls" ) ENDFOREACH(file) ENDIF(WIN32) poco-1.3.6p1-all/contrib/cmake/PocoConfig.cmake0000644000076500001200000001177211313735443022032 0ustar guenteradmin00000000000000# - Find the Poco includes and libraries. # The following variables are set if Poco is found. If Poco is not # found, Poco_FOUND is set to false. # Poco_FOUND - True when the Poco include directory is found. # Poco_INCLUDE_DIRS - the path to where the poco include files are. # Poco_LIBRARY_DIRS - The path to where the poco library files are. # Poco_BINARY_DIRS - The path to where the poco dlls are. # ---------------------------------------------------------------------------- # If you have installed Poco in a non-standard location. # Then you have three options. # In the following comments, it is assumed that # points to the root directory of the include directory of Poco. e.g # If you have put poco in C:\development\Poco then is # "C:/development/Poco" and in this directory there will be two # directories called "include" and "lib". # 1) After CMake runs, set Poco_INCLUDE_DIR to /poco<-version> # 2) Use CMAKE_INCLUDE_PATH to set a path to /poco<-version>. This will allow FIND_PATH() # to locate Poco_INCLUDE_DIR by utilizing the PATH_SUFFIXES option. e.g. # SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "/include") # 3) Set an environment variable called ${POCO_ROOT} that points to the root of where you have # installed Poco, e.g. . It is assumed that there is at least a subdirectory called # Foundation/include/Poco in this path. # # Note: # 1) If you are just using the poco headers, then you do not need to use # Poco_LIBRARY_DIRS in your CMakeLists.txt file. # 2) If Poco has not been installed, then when setting Poco_LIBRARY_DIRS # the script will look for /lib first and, if this fails, then for /stage/lib. # # Usage: # In your CMakeLists.txt file do something like this: # ... # # Poco # FIND_PACKAGE(Poco) # ... # INCLUDE_DIRECTORIES(${Poco_INCLUDE_DIRS}) # LINK_DIRECTORIES(${Poco_LIBRARY_DIRS}) # # In Windows, we make the assumption that, if the Poco files are installed, the default directory # will be C:\poco or C:\Program Files\Poco. SET(POCO_INCLUDE_PATH_DESCRIPTION "top-level directory containing the poco include directories. E.g /usr/local/include/poco-1.2.1 or c:\\poco\\include\\poco-1.2.1") SET(POCO_INCLUDE_DIR_MESSAGE "Set the Poco_INCLUDE_DIR cmake cache entry to the ${POCO_INCLUDE_PATH_DESCRIPTION}") SET(POCO_LIBRARY_PATH_DESCRIPTION "top-level directory containing the poco libraries.") SET(POCO_LIBRARY_DIR_MESSAGE "Set the Poco_LIBRARY_DIR cmake cache entry to the ${POCO_LIBRARY_PATH_DESCRIPTION}") SET(POCO_DIR_SEARCH $ENV{POCO_ROOT}) IF(POCO_DIR_SEARCH) FILE(TO_CMAKE_PATH ${POCO_DIR_SEARCH} POCO_DIR_SEARCH) ENDIF(POCO_DIR_SEARCH) IF(WIN32) SET(POCO_DIR_SEARCH ${POCO_DIR_SEARCH} C:/poco D:/poco "C:Program Files/poco" "D:Program Files/poco" ) ENDIF(WIN32) # Add in some path suffixes. These will have to be updated whenever a new Poco version comes out. SET(SUFFIX_FOR_INCLUDE_PATH poco-1.2.4 poco-1.2.3 poco-1.2.1 ) SET(SUFFIX_FOR_LIBRARY_PATH poco-1.2.4/lib poco-1.2.4/lib/Linux/i686 poco-1.2.3/lib poco-1.2.3/lib/Linux/i686 poco-1.2.1/lib poco-1.2.1/lib/Linux/i686 lib lib/Linux/i686 ) # # Look for an installation. # FIND_PATH(Poco_INCLUDE_DIR NAMES Foundation/include/Poco/AbstractCache.h PATH_SUFFIXES ${SUFFIX_FOR_INCLUDE_PATH} PATHS # Look in other places. ${POCO_DIR_SEARCH} # Help the user find it if we cannot. DOC "The ${POCO_INCLUDE_DIR_MESSAGE}" ) # Assume we didn't find it. SET(Poco_FOUND 0) # Now try to get the include and library path. IF(Poco_INCLUDE_DIR) IF(EXISTS "${Poco_INCLUDE_DIR}") SET(Poco_INCLUDE_DIRS ${Poco_INCLUDE_DIR}/CppUnit/include ${Poco_INCLUDE_DIR}/Foundation/include ${Poco_INCLUDE_DIR}/Net/include ${Poco_INCLUDE_DIR}/Util/include ${Poco_INCLUDE_DIR}/XML/include ) SET(Poco_FOUND 1) ENDIF(EXISTS "${Poco_INCLUDE_DIR}") FIND_LIBRARY(Poco_LIBRARY_DIR NAMES PocoFoundation PocoFoundationd PATH_SUFFIXES ${SUFFIX_FOR_LIBRARY_PATH} PATHS # Look in other places. ${Poco_INCLUDE_DIR} ${POCO_DIR_SEARCH} # Help the user find it if we cannot. DOC "The ${POCO_LIBRARY_PATH_DESCRIPTION}" ) GET_FILENAME_COMPONENT(Poco_LIBRARY_DIR ${Poco_LIBRARY_DIR} PATH) IF(Poco_INCLUDE_DIR) SET(Poco_LIBRARY_DIRS ${Poco_LIBRARY_DIR}) # Look for the poco binary path. SET(Poco_BINARY_DIR ${Poco_INCLUDE_DIR}) IF(Poco_BINARY_DIR AND EXISTS "${Poco_BINARY_DIR}") SET(Poco_BINARY_DIRS ${Poco_BINARY_DIR}/bin) ENDIF(Poco_BINARY_DIR AND EXISTS "${Poco_BINARY_DIR}") ENDIF(Poco_INCLUDE_DIR) ENDIF(Poco_INCLUDE_DIR) IF(NOT Poco_FOUND) IF(NOT Poco_FIND_QUIETLY) MESSAGE(STATUS "Poco was not found. ${POCO_DIR_MESSAGE}") ELSE(NOT Poco_FIND_QUIETLY) IF(Poco_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Poco was not found. ${POCO_DIR_MESSAGE}") ENDIF(Poco_FIND_REQUIRED) ENDIF(NOT Poco_FIND_QUIETLY) ENDIF(NOT Poco_FOUND) poco-1.3.6p1-all/contrib/cmake/README0000644000076500001200000000234011313735443017651 0ustar guenteradmin00000000000000CMAKE Files contributed by Andrew J. P. Maclean Put the following files in the directory where your source code is: CMakeLists.txt PocoConfig.cmake. Edit CMakeLists.txt to include your source and header files. The sections of interest are: # Add any source files here. SET( EXE_SRCS "My File.cpp" ) # Add any include files here. SET( EXE_INCS "My File.h" ) Then create a subdirectory called build. In Linux: cd build ccmake .. or ccmake -GKDevelop3 .. (This will set up everything so you can use KDevelop3). In Windows: run CMakeSetup.exe and set the source code directory and where to build the libraries. If CMake cannot find Poco, you will see that the variable Poco_INCLUDE_DIR has the value Poco_INCLUDE_DIR-NOTFOUND. Just set this value to the top level direcotry of where the Poco includes are. If there is a different version of Poco, you may have to add edit the variables SUFFIX_FOR_INCLUDE_PATH, and SUFFIX_FOR_LIBRARY_PATH adding in the new Poco version in a similar manner to the existing ones in the file PocoConfig.cmake. Finally: In Linux Either type "make" or if you are using KDevelop, click on the .kdevelop file. In Windows just use your IDE or nmake if you use nmake. poco-1.3.6p1-all/contrib/poco-doc.pl0000644000076500001200000000203011313735443017745 0ustar guenteradmin00000000000000#!/usr/bin/perl -wi # # poco-doc.pl # # This script, when run on a POCO header file, moves the documentation # for classes, methods, etc above their declarations, making the code # suitable for running through Doxygen, etc. # # Author: Caleb Epstein # # $Id$ use strict; use warnings; my @COMMENT; my @DECL; my $comment_re = qr@^\s*//@; while (<>) { if ((/^\s*(template|class|enum)/ and not /\;\s*$/) or (/[\(\)](\s*const)?\;$/ and $_ !~ $comment_re)) { if (scalar @DECL) { print join ("", @COMMENT) if scalar @COMMENT; print join ("", @DECL); } @DECL = ($_); @COMMENT = (); next; } elsif (m@^\s*///@ and scalar @DECL) { push (@COMMENT, $_); } else { if (scalar @DECL) { print join ("", @COMMENT) if scalar @COMMENT; print join ("", @DECL); @COMMENT = @DECL = (); } # Handle in-line documentation of enum values if (m@^\s*[^/]@ and m@/// @) { s@/// @///< @; } print; } } poco-1.3.6p1-all/CONTRIBUTORS0000644000076500001200000000163611313735443016140 0ustar guenteradmin00000000000000Guenter Obiltschnig Alex Fabijanic Peter Schojer Ferdinand Beyer Krzysztof Burghardt Claus Dabringer Caleb Epstein Eran Hammer-Lahav Chris Johnson Sergey Kholodilov Ryan Kraay Larry Lewis Andrew J. P. Maclean Andrew Marlow Paschal Mushubi Jiang Shan David Shawley Sergey Skorokhodov Tom Tan <> Sergey N. Yatskevich Marc Chevrier Philippe Cuvillier -- $Id: //poco/1.3/dist/CONTRIBUTORS#7 $ poco-1.3.6p1-all/CppUnit/0000755000076500001200000000000011313735443015634 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/cppunit.vmsbuild0000644000076500001200000000026111313735443021064 0ustar guenteradmin00000000000000# # buildfiles.vms # # $Id: //poco/CppUnit/cppunit.vmsbuild#1 $ # LIB=CppUnit CppUnitException TestCase TestDecorator TestFailure TestResult TestRunner TestSuite TextTestResult poco-1.3.6p1-all/CppUnit/CppUnit_vs71.sln0000644000076500001200000000462411313735443020622 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUnit", "CppUnit_VS71.vcproj", "{138BB448-808A-4FE5-A66D-78D1F8770F59}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinTestRunner", "WinTestRunner\WinTestRunner_VS71.vcproj", "{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}" ProjectSection(ProjectDependencies) = postProject {138BB448-808A-4FE5-A66D-78D1F8770F59} = {138BB448-808A-4FE5-A66D-78D1F8770F59} EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared debug_static = debug_static release_shared = release_shared release_static = release_static EndGlobalSection GlobalSection(ProjectDependencies) = postSolution EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared.ActiveCfg = debug_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared.Build.0 = debug_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_static.ActiveCfg = debug_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_static.Build.0 = debug_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared.ActiveCfg = release_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared.Build.0 = release_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_static.ActiveCfg = release_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_static.Build.0 = release_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared.ActiveCfg = debug_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared.Build.0 = debug_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_static.ActiveCfg = debug_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_static.Build.0 = debug_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared.ActiveCfg = release_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared.Build.0 = release_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_static.ActiveCfg = release_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_static.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/CppUnit/CppUnit_vs71.vcproj0000644000076500001200000002443311313735443021331 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/CppUnit/CppUnit_vs80.sln0000644000076500001200000000462311313735443020621 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUnit", "CppUnit_vs80.vcproj", "{138BB448-808A-4FE5-A66D-78D1F8770F59}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinTestRunner", "WinTestRunner\WinTestRunner_vs80.vcproj", "{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}" ProjectSection(ProjectDependencies) = postProject {138BB448-808A-4FE5-A66D-78D1F8770F59} = {138BB448-808A-4FE5-A66D-78D1F8770F59} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 debug_static|Win32 = debug_static|Win32 release_shared|Win32 = release_shared|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared|Win32.Build.0 = debug_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_static|Win32.ActiveCfg = debug_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_static|Win32.Build.0 = debug_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared|Win32.ActiveCfg = release_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared|Win32.Build.0 = release_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_static|Win32.ActiveCfg = release_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_static|Win32.Build.0 = release_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared|Win32.Build.0 = debug_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_static|Win32.ActiveCfg = debug_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_static|Win32.Build.0 = debug_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared|Win32.ActiveCfg = release_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared|Win32.Build.0 = release_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_static|Win32.ActiveCfg = release_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/CppUnit/CppUnit_vs80.vcproj0000644000076500001200000002717411313735443021336 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/CppUnit/CppUnit_vs90.sln0000644000076500001200000000462411313735443020623 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CppUnit", "CppUnit_vs90.vcproj", "{138BB448-808A-4FE5-A66D-78D1F8770F59}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinTestRunner", "WinTestRunner\WinTestRunner_vs90.vcproj", "{BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}" ProjectSection(ProjectDependencies) = postProject {138BB448-808A-4FE5-A66D-78D1F8770F59} = {138BB448-808A-4FE5-A66D-78D1F8770F59} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 debug_static|Win32 = debug_static|Win32 release_shared|Win32 = release_shared|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_shared|Win32.Build.0 = debug_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_static|Win32.ActiveCfg = debug_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.debug_static|Win32.Build.0 = debug_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared|Win32.ActiveCfg = release_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_shared|Win32.Build.0 = release_shared|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_static|Win32.ActiveCfg = release_static|Win32 {138BB448-808A-4FE5-A66D-78D1F8770F59}.release_static|Win32.Build.0 = release_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_shared|Win32.Build.0 = debug_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_static|Win32.ActiveCfg = debug_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.debug_static|Win32.Build.0 = debug_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared|Win32.ActiveCfg = release_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_shared|Win32.Build.0 = release_shared|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_static|Win32.ActiveCfg = release_static|Win32 {BA620CC4-0E7D-4B9D-88E2-6DBE5C51FCBD}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/CppUnit/CppUnit_vs90.vcproj0000644000076500001200000002720011313735443021325 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/CppUnit/doc/0000755000076500001200000000000011313735443016401 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/doc/cookbook.htm0000644000076500001200000002412311313735443020723 0ustar guenteradmin00000000000000 CppUnit Cookbook

CppUnit Cookbook

Here is a short cookbook to help you get started.

Simple Test Case

You want to know whether your code is working. How do you do it? There are many ways. Stepping through a debugger or littering your code with stream output calls are two of the simpler ways, but they both have drawbacks. Stepping through your code is a good idea, but it is not automatic. You have to do it every time you make changes. Streaming out text is also fine, but it makes code ugly and it generates far more information than you need most of the time.

Tests in CppUnit can be run automatically. They are easy to set up and once you have written them, they are always there to help you keep confidence in the quality of your code.

To make a simple test, here is what you do:

Subclass the TestCase class. Override the method "runTest ()". When you want to check a value, call "assert (bool)" and pass in an expression that is true if the test succeeds.

For example, to test the equality comparison for a Complex number class, write:

	class ComplexNumberTest : public TestCase { 
	public: 
                    ComplexNumberTest (string name) : TestCase (name) {}
        void        runTest () {
                        assert (Complex (10, 1) == Complex (10, 1));
                        assert (!(Complex (1, 1) == Complex (2, 2)));
                    }
        };

That was a very simple test. Ordinarily, you'll have many little test cases that you'll want to run on the same set of objects. To do this, use a fixture.

 

Fixture

A fixture is a known set of objects that serves as a base for a set of test cases. Fixtures come in very handy when you are testing as you develop. Let's try out this style of development and learn about fixtures along the away. Suppose that we are really developing a complex number class. Let's start by defining a empty class named Complex.

	class Complex {}; 

Now create an instance of ComplexNumberTest above, compile the code and see what happens. The first thing we notice is a few compiler errors. The test uses operator==, but it is not defined. Let's fix that.

	bool operator== (const Complex& a, const Complex& b) { return true; }

Now compile the test, and run it. This time it compiles but the test fails. We need a bit more to get an operator== working correctly, so we revisit the code.

	class Complex { 
        friend bool operator== (const Complex& a, const Complex& b);
        double      real, imaginary;
        public:
                    Complex ()  {
                    real = imaginary = 0.0;
                    }
        };

        bool operator== (const Complex& a, const Complex& b)
        { return eq(a.real,b.real) && eq(a.imaginary,b.imaginary); }

If we compile now and run our test it will pass.

Now we are ready to add new operations and new tests. At this point a fixture would be handy. We would probably be better off when doing our tests if we decided to instantiate three or four complex numbers and reuse them across our tests.

Here is how we do it:

  1. Add member variables for each part of the fixture
  2. Override "setUp ()" to initialize the variables
  3. Override "tearDown ()" to release any permanent resources you allocated in "setUp ()"
	class ComplexNumberTest : public TestCase  {
	private:
        Complex 	*m_10_1, *m_1_1; *m_11_2;
	protected:
	void		setUp ()  {
			    m_10_1 = new Complex (10, 1);
			    m_1_1  = new Complex (1, 1);
			    m_11_2  = new Complex (11, 2);  
                        }
	void		tearDown ()  {
			    delete m_10_1, delete m_1_1, delete m_11_2;
			}
	};

Once we have this fixture, we can add the complex addition test case any any others that we need over the course of our development.

 

Test Case

How do you write and invoke individual tests using a fixture?

There are two steps to this process:

  1. Write the test case as a method in the fixture class
  2. Create a TestCaller which runs that particular method

Here is our test case class with a few extra case methods:

	class ComplexNumberTest : public TestCase  {
	private:
        Complex 	*m_10_1, *m_1_1; *m_11_2;
	protected:
	void		setUp ()  {
			    m_10_1 = new Complex (10, 1);
			    m_1_1  = new Complex (1, 1);
			    m_11_2 = new Complex (11, 2);  
                        }
	void		tearDown ()  {
			    delete m_10_1, delete m_1_1, delete m_11_2;
			}
	void		testEquality ()  {
			    assert (*m_10_1 == *m_10_1);
			    assert (!(*m_10_1 == *m_11_2));
			}
	void		testAddition ()  {
			    assert (*m_10_1 + *m_1_1 == *m_11_2);
                 	}
	};

Create and run instances for each test case like this:

	test = new TestCaller<ComplexNumberTest>("testEquality", ComplexNumberTest::testEquality);
        test->run (); 

The second argument to the test caller constructor is the address of a method on ComplexNumberTest. When the test caller is run, that specific method will be run.

Once you have several tests, organize them into a suite.

 

Suite

How do you set up your tests so that you can run them all at once?

CppUnit provides a TestSuite class that runs any number of TestCases together. For example, to run a single test case, you execute:

	TestResult result;
	TestCaller<ComplexNumberTest> test ("testAddition", ComplexNumberTest::testAddition);
	Test.run (&result);

 

To create a suite of two or more tests, you do the following:

	TestSuite suite;
	TestResult result;
	suite.addTest (new TestCaller<ComplexNumberTest>("testEquality", ComplexNumberTest::testEquality));
	suite.addTest (new TestCaller<ComplexNumberTest>("testAddition", ComplexNumberTest::testAddition));
	suite.run (&result);
           

TestSuites don't only have to contain callers for TestCases. They can contain any object that implements the Test interface. For example, you can create a TestSuite in your code and I can create one in mine, and we can run them together by creating a TestSuite that contains both:

	TestSuite suite;
	suite.addTest (ComplexNumberTest.suite ());
	suite.addTest (SurrealNumberTest.suite ());
	suite.run (&result);

 

TestRunner

How do you run your tests and collect their results?

Once you have a test suite, you'll want to run it. CppUnit provides tools to define the suite to be run and to display its results. You make your suite accessible to a TestRunner program with a static method suite that returns a test suite.
For example, to make a ComplexNumberTest suite available to a TestRunner, add the following code to ComplexNumberTest:

	public: static Test *suite ()  {
	    TestSuite *suiteOfTests = new TestSuite;
	    suiteOfTests->addTest (new TestCaller<ComplexNumberTest>("testEquality", testEquality));
	    suiteOfTests->addTest (new TestCaller<ComplexNumberTest>("testAddition", testAddition));
            return suiteOfTests;
	}

CppUnit provides both a textual version of a TestRunner tool, and a Micosoft Visual C++ 5.0 graphical version. If you are running on another platform, take a look at the graphical version. It is easy to port.

To use the text version, include the header file for the test in TestRunner.cpp:

	#include "ExampleTestCase.h"
	#include "ComplexNumberTest.h"

And add a call to "addTest (string, Test *) in the "main ()" function:

	int main (int ac, char **av)  {
	    TestRunner runner;
	    runner.addTest (ExampleTestCase::suite ());
	    runner.addTest (ComplexNumberTest::suite ());
	    runner.run ();
	    return 0;
	}

The TestRunner will run the tests. If all the tests pass, you'll get an informative message. If any fail, you'll get the following information:

  1. The name of the test case that failed
  2. The name of the source file that contains the test
  3. The line number where the failure occurred
  4. All of the text inside the call to assert which detected the failure

CppUnit distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like division by zero and other exceptions thrown by the C++ runtime or your code.

If you are running MS Developer's Studio, you can build the GUI version rather easily. There are three projects: culib, TestRunner, and HostApp. They make a static library for the framework, a dialog based TestRunner in a DLL and an example Hosting application, respectively. To incorporate a TestRunner in an application you are developing, link with the static library and the TestRunner DLL. Note that the TestRunner DLL must be in the home directory of your application, the system directory or the path. In your application, create an instance of TestRunnerDlg whenever you want to run tests. Pass tests you want to run to the dialog object and then execute.

Here is a screen shot of the TestRunner in use:

 

More notes about the implementation of CppUnit can be found in README.HTML.

 

 

poco-1.3.6p1-all/CppUnit/doc/license.htm0000644000076500001200000000512211313735443020535 0ustar guenteradmin00000000000000 License Agreement

Permission to reproduce and create derivative works from the Software ("Software Derivative Works") is hereby granted to you under the copyright of Michael Feathers.  Michael Feathers also grants you the right to distribute the Software and Software Derivative Works.

Michael Feathers licenses the Software to you on an "AS IS" basis, without warranty of any kind. Michael Feathers HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.  You are solely responsible for determining the appropriateness of using the Software and assume all risks associated with the use and distribution of this Software, including but not limited to the risks of program errors, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.  MICHAEL FEATHERS WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, INCIDENTAL, OR INDIRECT DAMAGES OR FOR ANY ECONOMIC CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN IF MICHAEL FEATHERS HAD BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  Michael Feathers will not be liable for the loss of, or damage to, your records or data, or any damages claimed by you based on a third party claim.

You agree to distribute the Software and any Software Derivatives under a license agreement that: 1) is sufficient to notify all licensees of the Software and Software Derivatives that Michael Feathers assumes no liability for any claim that may arise regarding the Software or Software Derivatives, and 2) that disclaims all warranties, both express and implied, from Michael Feathers regarding the Software and Software Derivatives.  (If you include this Agreement with any distribution of the Software and Software Derivatives you will have meet this requirement).  You agree that you will not delete any copyright notices in the Software.

This Agreement is the exclusive statement of your rights in the Software as provided by Michael Feathers.  Except for the licenses granted to you in the second paragraph above, no other licenses are granted hereunder, by estoppel, implication or otherwise.
 

poco-1.3.6p1-all/CppUnit/doc/README.html0000644000076500001200000001543111313735443020230 0ustar guenteradmin00000000000000 CppUnit 1.5

CppUnit 1.5

Last Revision: 12/15/99 - Michael Feathers (mfeathers@acm.org) - written in standard C++, tested under Microsoft Visual C++ 6.0


Background

CppUnit is a simple unit test framework for C++. It is a port from JUnit, a testing framework for Java, developed by Kent Beck and Erich Gamma.

Contents

README.html                     this file
    
    test                        the source code
        framework               the testing framework
		extensions	some framework extension classes 
        textui                  a command line interface to run tests 
    ms                          code for a Microsoft specific TestRunner
    samples                     some example test cases and extensions to the framework
        multicaster             a sample illustrating a publish/subscribe 
				multicaster under test
    doc                         documentation

Installation

To use the test framework, create a makefile or load all files in test\framework into your IDE. In this incarnation of CppUnit, all includes assume the current directory first. A makefile or project can be used to resolve the dependencies.

The directory test\textui contains a simple command line example that uses the framework.

Documentation

CppUnit comes with the following documentation:

  • a cookbook: doc\cookbook.htm
  • this file

Samples

You can find several sample test cases in the samples directory:

  • ExampleTestCase - some simple tests
  • Multicaster - test cases for a sample publish/subscribe multicaster class

Also, the wiki page http://c2.com/cgi/wiki?ClassHierarchyTestingInCppUnit shows how to automatically apply tests of classes to the classes' subclasses.

Extensions

You can find several classes that illustrate framework extensions in the extensions directory:

  • TestDecorator - A Decorator for Test. You can use it as the base class for decorators that extend test cases.
  • TestSetup - A Decorator that can be used to set up and tear down additional fixture state. Subclass TestSetup and insert it into your tests when you want to set up additional state once before the test is run.
  • Orthodox - a template class which can be used to verify operations on an arbitrary class.

Notes

Porting this framework has been fun. I've tried to maintain the spirit and utility of JUnit in a C++ environment. Naturally, the move from Java to standard C++ forces out several nice JUnit features:

  1. Platform independent GUI.
  2. Stack traces of test failures
  3. Active (threaded) tests
  4. Direct invocation of test cases via reflection
  5. Run-time loading of new tests

In addition, the lack of garbage collection in C++ requires some careful use of the framework classes. In particular, TestSuites are composites that manage the lifetime of any tests added to them. Holding onto a TestResult past the lifetime of the tests which filled it is a bad idea. This is because TestResults hold TestFailures and TestFailures hold pointers to the Tests that generated them.

On the plus side, we can use the C++ macro preprocessor to get the exact line at which a failure occurs, along with the actual text inside the assert () call that detected the failure. The features of C++ that enable this are the __LINE__ and __FILE__ preprocessor definitions, along with the stringizing operator. If you find that generating this much literal text bulks up your test executables, you can use the CPP_UNIT_SOURCEANNOT define to disable that portion of the reporting.

Note: If you use the C++ macro "assert ()" in your code, or include assert.h, you may have a name clash with CppUnit's assert macro. This can be remedied by changing the name of the macro to "cu_assert ()" in TestCase.h.

I'd like to thank Kent Beck and Erich Gamma for the inspiration, design, and a wonderful cookbook that was easily/shamelessly mutated to describe CppUnit. Double thanks to Erich for thinking up a way to implement TestCaller. Additional thanks to Kent, Ward Cunningham, Ron Jeffries, Martin Fowler, and several other netizens of the WikiWikiWeb. I don't think any other bunch of people could have convinced me that rapid development with unit tests can be both effective and easy.

Thanks also to Fred Huls for mentioning the idea of template-based testing. The orthodox template class demonstrates only a small part of what can be done with templated test cases.

History Of Changes

1.2 -- Added the TestCaller template class. There is now no need to use the CPP_UNIT_TESTCASEDISPATCH macro unless you are using a C++ compiler which does not support templates well. CPP_UNIT_TESTCASEDISPATCH remains in TestCase.h for backward compatibility. I've also kept the use of the macro in the Multicaster sample to leave in an example.

1.3 -- Retired the CPP_UNIT_TESTCASEDISPATCH macro and cleaned up the include structure. Fixed bug in the textui version.

1.4 -- Removed using directives for std in CppUnit headers. Merged the old AssertionFailedError into CppUnitException. Fixed a memory leak in the TestRunner class of the MS GUI TestRunner. Removed CppUnit.h file. Now headers for each class must be included directly.

1.5 -- Upgraded projects from VC++ 5.0 to 6.0.

poco-1.3.6p1-all/CppUnit/doc/test.gif0000644000076500001200000004562511313735443020063 0ustar guenteradmin00000000000000GIF87acv÷„ÿ„{„„aa„„„ËÁ¨Ë˨îäÜîîÜÿÿÿ!ù,cv@ÿH° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jÜȱ£Ç CŠ|à€‚RP@¥Ë—/(HÉReM˜8sêÜɳ§ÏŸ@ƒ J´¨Ñ£H“*]Ê´©Ó§P£J…yò¼Z)(yrªÙ³hÓª]˶­Û·pãÊ-š áذcM&Ôju«ß¾€ù þ;pðB¾#+^̸±ãÇ#Kž¼Ø°åƒZóV-ˆa玟 ¦Lº´éÓ¨S«^Íšph…šÿ¾Xr ÖÛ´mÿÍšûÀí’]kÿÝytëãÈ“+_ΣVu}_ìÚ[dɱµ "Ž-ºágãÆWÿ,îðµyÌèµ§ç¼¾»ú÷ìá»O¾ýÂíñË×_Ÿÿ}Âÿ‰àyûèß&( ‚ *H`æa úÇUeçÞlúqèÑuXy6w¡ñ5Ö(¦¨¢Š¬èâ‹ ´ãŒ(Êãm)þæ¢7ÚˆcXÑøâC iä‘H&©ä’L6éä“PF)å”TVieŠz©—Wt 67‘V_e‰Øg'æèc‹hÖXc+þ(£Ž7šÙ¦™l¹#lc›uö¹&A¦¹gWj衈&ªè¢Œ6*d–r' x]2ôlz(Ñe$2èå§ †*ꨤŽçé¥ jºé—v‘嚈ö…ÿ×á^‘'ßl¸ö‡ê»Øë‚¿«ë°÷ [,±¼"뫲À2kl²ÇF í´ËJ[-µ´6ûê†ûy¨*¬f[¡¸èjµW¤!¹™²Z¡­“š¯µÚbûìµøÖ›ï½úöËï¿ÎL/À l¯Á˜Vk»^d+¼ o;.¹†Û™¤–BÈUˆó8ße°>XߘÉq|§òÊé©Ü2Ëï¹3Ì(ÓÌíË8ÏœsÍ;߬óÏwümÐë•ØpÄC·W1Å c|«ÂávõÄ?{›ð¯SÏÚ³Ö@ûÌs×\-¶×d‡]öÉg—»5Úf·ÍöÛjmôÓ‡ îÝT3\^€P/ÿ ¯‡N“kò¸ Àáˆ'®øâŒ7îøãG.ùä”Wnùå˜g®ùæœwîùç ‡^ù HØñɦž*…P+¤)ÄÛ»0µ£+á¢ç®ûî¼÷îûïÀ/üðŒ“>»Èι¾óÜÙR:ö{’Z7ÑáNüõØg¯ýöÜwï=寝îéCÌ×>2}$·®üC{w5Ü‹›þùzÏ?¿¿jŒ·Ý¦»tÔÿã[ùǺvÉ€þÛߘÀüüiõã[ó–4÷É >µÍàXg.1±Kb:«`Ѳ¾Mkp²R•Ì@"ð….Œaÿ`8CІ-\úöV7õå«_“^cÈ‘ôÅR¢Â°öµû5kNl%ž ýF7¹ápªƒÃ…ð[•ºßŸÓ›ìlÑ7d™ùvƒE¥ Ð?cT—tÎ8Çê'ý;ȺØVÅ ZDuâëá÷6TMñtð˜ÿdçGk ‘„‰Üà¼ì÷AEºpG»¤™Å@¦Í]„¤%õæÆõùp”) !?–¿’•ˆ°3ÝÐö<­²}ˆ|Ö#¿µIêA‹–§,b­f´5Òí†\cb AÖ˾o|ÁœžÜ ÉÃPŽ…«Ê[¯œGIÛ d+á5!XÌä³AÄ ߥÃH‚r”ˆDØÜ˜gA‡%q¾|£7£)µVFñuüÔ`‘FÊf®²k³‰}¨³á䆌¼q¨nž“®,¶Q:‚1c…³ÅŠÎ‘Œä#&ó PVªí~³üdA}¶Ft.læ|=cyLRr\’äåÙL&Pía‚¤MûÙÿÁÍlK…¾ô›(ƒZÏq†›­¤RáiJrV3‘U}Þ ÕÉÎ®Ž”jQ$Û ="Nv5“Ÿ ’d ·šOÀ„“?c©ÊgöhÓ¯ŠCá˜t ’ÒB³§DÌš'×¼Þ®êBŒ†›3†µ¦Måaa ÂPꕱzMA&+GÃ2-Dx¬f‡fÔsÖõ‚,Ì!~Þj±péÝkLÚ§iÍæyº’JĵÏükp+ Ö¶Æm©)¬ZM\“·«­4•ˆÚ¾"¤´;œž‡ùÔ_ Äi¡)SŽŽÄ#F•7Iob‘šÆËÞ9ù¨½FJï”Îë(!ÑwN4”}u_(ÿ•·¿õ-”~Õ«Þ÷*¿ð€×ëÞÒa°h3(u‡«¾Ìœ‹Câ °†7ÌaD¸Ã ±ˆG`$R¤›yìúèé—0m&<¶Sƒµ'ùxIïýï ¥à˜Áì5ðs¬&)½B¾q”’\ãÓP:úÍ‚?Lâ%øOT®ò~áË`¹É;²á{Þôš¸º!j2o:\$ÆZ޳œçLç:ÛùÎ>Àk‘™G& w|ìTÜàŒçBúЈN´¢A¬g–ׇ£=­WyæÖfyјδ¦7ÍéC7ZÅhåî„Ó©\ƮӨNµªWÍêúVÚ‚gÍ-5m&"A„‚Эε®wÍk]{°–W¥½øŠ¯À×½N¶²—Íì9:«!dýxÈèV:ºÍζ¶·ÍíF!°(¦j`ãg6¥¾YvSDv·×Íîv»[E¿Žöt»¸\÷¹ÙD—~·¾÷ÍïU¿š©‘µo-^K÷ûàOxªã-¹Þ-u¸™÷+Õ&žÿµo0.NÈ–JÅñŽ{üã ‰«LX¢’›|ä('¹LR¾r•»¼å0¹ÌcNs•ÿ;ã Á®Äm£WŒFüŠø¬P^tñsCêØ%‰N¬ï êÊÅP·*oEÍÕ¥ÇÚ;±A.ò“ϼä,ÿz˽Nö”—ìh?;ÉÍ)F†FÊp»ÜçN÷ºÛ=îú2vŠOLá¾ßv’<³zkÊ*xÂswêéPý~3n>“™¼Å$ßxƳÆñ{¿–Kî×ð22^aÚhË•J„ Öd•õaÄÕuYŽmÌ¥'•ü… ϲ²¦ÙŸ§„ý#Q){ û™Ö^’ð¨{[0GîÓ¨Ÿy±²[:nSÿó:l.œ ¡Kù¡5cëÑXÇ×Çv]Y9£D>W-ò\ûèÏkm6vþ†b¤{zÏmë˜Þ~ç†íð'¯­Ç<»Ôå\XUUÆh&eWöáp¡svuPõä´¬rXx‚—&#h«HÂäSö{º5k‘4:ÕHSÑ6OïÄt‰tÖôC’múB‚Èsu/XƒaUħ]Åæ*s1„DX„Fx„H˜„J¸„Lxq.!*s4±rUx…+Ñ+1 …7Q_Ø,×…\Ø„fx†h˜†j¸†lX¥tßpWzцvx‡x˜‡z¸‡|Èÿtˆ|!¨[œ—„Xˆ†xˆ‡n„áfå²G¨òEÁ{M‡ˆ”X‰–Øqx%*Ø\Œ¸+D,C…<x‰¤XЦÈ™ˆY ±Xð×Q²E=rW EXÔ7Jê¦p¸˜‹ºÈ( ñy”Å€÷÷D¡&1›(µ¸ â…dãÅcd¶Œ f=&f͈_B6eav&Õ\¶‹ÜØð¶¸aa&Æb(l¸(Ž hI·èîøŽð#w÷oªµu#XHö‡ $DD\ÁöNY·/@øS|Zwi ‰Éù‘ 9Œ'mÑHË4lQdk2µ|'!<%J‹‘I’)¡‘'Y’(¹,Ù-i’/¹’Å…ð4p÷âgåSTµ{EµŠ„!QuDåˆÙáQöøü·bk¶”Å”q]Žæ”6•ûX•;i•(…•¸GA[ x\ù•^–Pé”Gx²fS¦YOi•o¿–ƒžØN$ƒSóS49ˆ‚…—ø¤—ÔÄ—ÌåiM~©Mû˜{7S2(njvƒ&½4V*n‹ÿxŒÇ…Žb=ß“™š¹™œÙ™žÙ=Æ’ÃØS›„‘ÒBšøXz÷•'Œ˜ù™°›²9›´9›á³@¼—U23—:h%E&¾Èw•.¯Y›ÆyœÈ™œÊÙ9·Y—|–|ù@™„x­Ù“t¹?¢yŠÚ¹Ü©eù|+¸–x£ˆ°f‚ÝsÃéƒi¦BH]%™D5n´W™èdHcSŸ÷¹O¦ŸôÉŸø)Vþ ý—Ÿ  3 ŸQ¹ŸÁhŽ^{V¥RˆÇ~Õ‰RÔ6xV ˜•…YŽ”‡/•›ÍEA—‘^©RVm"yTÕiEë×”Àd¢Ä¡á÷wÇE¢3¢¹€äVWÂÿ÷gψ šO¬µ];úGÓ‰/qéN˜˜±%[!2£VÁQ½™«è¡I”4×7”ç׊E¶ŽÓFl{tEõ¤ß·}¯ˆ¥Vz‚#ä áy–倳…›<™ƒ‚£* F¸¥˜LúžªÅ›IÅ’€º[eIj‹ iÑkˆ€æ)ž.èœ6˜”áI•nÚ•õh§ít{=x¥¦Tp™¨zJu¦©€yŽi™©¹\J¤ëÙTõ&Z^ó¨u¡Þ„‚×iyE™b£Vº¤÷Ä¡„éŒxQ´1ÅQe?çè×¢x¬EÆÊ~Å¥ *?µ‚Hé£(uëÄb49žæXzœ:nwÿZ{†iVª®QŪsZ%x­òÆè)œj¡¡úª¨ó©» ‹yÚ¯¦º§ª©øúƒª”@(U}VuЧÿ3U*Rp£¯pŠ”î©­óZ-;À˜_ѱݹ²"›‰…8²¨s‘æª »<tD€(À•Y}{•.×wŽqÈ%5kQÏãǬ«×›¼Jnö?‹jŒ<ËE?k¦Ã´=;{»‹Òú}ÝçŠgd”mÚHˆ7³Ì'GU›³eº´u}E‰­~¡\ EYsä¡6Û¬d‹³p®~²—Súy´\U7xnñ¸‚;¸Iòj"d]•jÀê÷c]ÖdDÿ¦dM¢cÙÈeFv¹Žk@F_òUfíõeÛø$efc4daöc÷ŹÎXd3fN†`W¢c¬¶` 'Êø¸Ò››¹¥³´‚y«“èžû±š}cRvd–oø%cÌKf}’'p‚^zbgÊ«$Ó›kžû'¨½ŽkºÞ{'ŸK$Ü»¹}rf§ÚVSu‘ä– ‹Æ»#8Âci‚þ•'X¶&r‚ºâ{½Ø½´K(ø»^Ñk»ôûºë$P(øû&uÂ$×ÛjÙ ÀœÆ½ÿ%»ò ½Ïȼãëd¶k¾çj>é{4ä¨@¦f.„{Â(ŒÂß–b/Ú¨|{˜ò1¬w•Â4\Ãîxthö® ûU²jt ØfÕkÃB<ÄÍf¸’Vzc9X+Kÿ¹YALÄPÅ­ö–¥º˜«Ê­êÄ8Ìí(Å^üŪfį4«Þ ¢[£­‹o`¼Æl<Åû°åyÆãT¯ZòÄm|Çx\eÏ&¡—ÔŸí¼Zõ„Ÿçyy\Ȇ\h 7ª:°ñ!Ã]|ÈÉŽB€·É!}ç‹À)ÉœÜɶÅaɤ¶z]ŠFëGWì)˜L‹[liŸ6´2L‘ÈuTôt¶ìt‰›Àë’¼ “ª’ÀŒ ®åu5WÌhgÌÈ,vÊŒÌb²z¶V¢œ—`Iª¥–z“éÁ~QrÚ¼ÍÜÜÍÞìÍ#GvßœváüÍfwÎäœÎi7ÎìÜÎîüÎðÜÎèlrñ,ÏÿÚ<Ïñ<Ïå\ÏüœÏ÷ìÎá¬ÏëÐÿ<ÐMÏmÐâ Î MÏmvÝÏ=ÑÇlƒDj«ÁøÂëá©çvwýÑ Ò"=Ò$]Ò&}Ò(Ò*½Ò,ÝÒ.ýÒ0ÓuwmÍ‘¡*«L¯ƒìÊB[µAùÓt$~Nʬ5¶]Ôä¡Q±˜EËÊEu¶mëXæÕ¯X äY¨¬éW|*nV÷ÕåÎ’ŒL°q*±•ÄÊ÷ÆC_DµXôEbË–øQqéáÈb] ¬?ÂèÇI;Í]]“"xËrš·ƒ–ðŠÅjæ˜ùG; ÄV{ù æT˜Jü¡eÃVɧ ëHVÒv¾ “ÓÿòÌöB\íJŠ¢‰‚Ù©=œ¸Ç„Ñ=ÌÙÔFƒW|Ú7E3âd{fÉš}°åš–“PÈ]Ç­ÜɽÜÉÍÜÏÝÒ=ÝÎÍÜËíÜÇ]ÝÕýÜÛÝÜÔíÝÝÝÒ­ÝÓ=ÞßÜÛÞæMÞèíÝÐ]Þß-ÞíýÞÖíÞõ ßçßóßáÝìÝÝø]ÞìàÜmÞNà.àþMßû Ý ~àþÞ×­àà áîÞòMß¾à¾áêmß nßý-áûÞÁI²(žâ*¾â}øâ0ã2>ã4ξ{_BheXr)á…\è…Z(…W†Y8`(ä[[XäeXãNþäPåRÞKë¡w1‡.nZ˜…E®…INe˜b8Vø…Hîå-aä71ålÞænþæxÈ%£Ç¬‹¤ãuçxžçz¾ç|î mç6Íâ‚>è„^èÿÁ¾G*©:j®†ÞèŽþèÉAË® ŒØ€ÙJÙžéš¾éNu•ÈX‹YÅ»Tœ^ê¦rWAѪ®ê =çwâ4Û~ÕÊ`{ÊZô¤éWÕ§¾ë¼^©è% 2‹ìxâßá¬eë³mk­T·={uÝÚëÐí!ñëwY”@¹EóçªÁ^y 5“®½­Ä„¸Â›Iä¤ån§è.Kê¾ÃŠ~îëÞîæïéÎî¹*ïï^ïóÎBí}ºXØÔ[—Q²rÁy1 â^àù}ðžáâÏð>ñ ÿð_ñOñÎá¯ðoñÿññ¿ñò Oò!ò#oò)ïò-ÿ/ò%/ó+_à1kâ«KuºQŒwív®ñÈž<ôD#7ë=-ÓJŸí“ B/¹[æÀ»;dÝ˺¸K^ß[$E¿õ®¦tMƒWM{(°ˆ‡+ܸÒ¹YO¹ŸÛ½˜KõÓxõÿ+ÀàKd Ëõxo%ñ†è‘Å“÷Ç1xk@/³vœ÷†ÇŸ–>±;ŸZ¼mÃÐ Ïû<Ñ ½Îã\Η¿ùÍù íùýù?ú¢_ú¡ú Ÿú¤ú«¯ú¦ïú¬ÿú­?û²_û±û°Ÿû´úýÎ2A@†'¯Y{Û5*˱½§ÛÌ/öËïüÍÿüÒýÔýÖ?ý×_ýØÿ¿ýÚßýÙÿýÜïÛ0“‚«Õt 5øaÙ§Vl¤îŸ’ð“Á,ÿñßË2éËøÿú?ÿö//àÀÀ$˜ð`A‚&4QáDŠ6ÄøP£B„p@ÄŒ=rÌHQ¢Å”ž¼S¦J”$m¶œi²&N77æÜù³'Ï @}%zt¨Ð¢K‘2UÚTjTªI­B½:“¥Í—)aî\úu+ÔžaqþÜ*°@È‘g€ ëS–+‹úì8Væ×“NýNÍú·ê\º‚&l81âÂŒ7 ùpd±5íÞÌkYoäŠe½Zìº13Ì•@м{ ®\!U éúuúÈÖ°_«®›fÉ´GïVþíX8åá“/&žü¸däË?/ÞœðÙÐ'’ÞìVoõºÔ­kî=q-j­ ä•¶úôrßÒVíZ6wð×µóõ¾w7èðü»ÿ÷/ÀïÜo@ DÐ>TÀLÍ·µ»/»ÒƺlÂÌ4|¨¯èðûÄÆkËBéÓoAàv[1&7ËðB®È¢Ñ¨;Ï3kԱǜqG!} ’HÞ†òH#q,Â/ÎÈËÃîÈì\dpCˆHTpEîªl‘®Åš²Âú®D3M5×d³M7ß„3N9申ÊÁ¢0L ï\SÏ3[ÚPË„ÿ¸ô-4¯„òÍDù\°I´•0R'}TÒJ'²?-¥´ÓL…SMēɪ¼Ôt4ë;”J7%K”N+ÑÁUÑvåµW_6Xa‡%¶XcE6Ye—e¶YgŸ…6Zi§¥¶ÚdX`»4ÁìR´XMÜôÓAÙ2Õ¥eüÏ!]­e·]wß…7^y祷^{ÅÖQ»ü”ÔÃK$³[&zˆÐ=Íá„Ö½·a‡†8b‰'¦Ù|ƒD0C55–_DÛ$”àü4âX#†+F9e•Wf¹å‰/Nø_ÅMØÐ üÕàPÙôl—:h¡‡&z×|ËÄØV’ý[ô³¥ÿw6³&cÆ ­ËN.:k­·æºkfa®´2AÔRÐþTä?0˜æƒ·øiYÇŽaºí®ûn½óæo¿÷þ»oÀ¼ðÀ'qÃg|qÇ8K™ù تêÅùæKšúΡÂlZÛÉ#D;lƲj²Õ¨I·õXU7ýu×!…=õÙY—ýI§¡”÷CQ}{UW¿M{§ÎWÇ\ø¤K/×ìs•äùmoÒÊr¾žz­Ç¾{íÿü>iïkä>üòÉ¿`î½u‹lâÑ/3Xƒªr…¦¦¾ã¹UÿãåwÿÌæ¾‘ÑîvÅˈ;6D #¸Ÿ©n_£ÿŸòDç»…ˆ*Ç—ùÚtA•L~Ý ëÝdPV%•k>çÉ€ÎK‘í¼’žÞÅNn±a OECOÝfƒNÊœÇxÇ44e®ˆ©Š52Q­Q&´Úå6)-ó‘mÎó QAt!û4&CÛ䆇6da÷¢ˆø ƒèjccS›7¾aqT“ç·Aàaïrkå¸ÈȅljÆ#×ðúu«ôQr}¥bÞ%“”",O‘JÔbý®èB%~ T‡äT%hÅô…?L%ÁGA)–ªOYÌK:GB…™T\¤¿Jç/_¾O–Š/•æ4·“ˆzžÿŸ˜ÂVu’~gƒåü胴r舸Êf#qǹH2r.SR¦ý®‰¤ugò¥ü·ºò_e£gÍ2·X¾ê`¥:¯¢ÈnÎ)ËS+•‡CÏiR-å¤eq:©¶[Ò —2ÓS3£ÙÄèùP”*´Ò’ËLnƒ¬i µ©Ð~SEÉ<çtPiN‘¤m)ÍÔæ'±YŠU³¥'ýJ/vš•”\*EJMgt‹6cæ:³÷U©½è‘ TáQÑ"vè=U8F?ŽÁ<_Q-‰Oé8r‚› é 5 §ÐµôšSí§<ÑéRyvñ˜Bµ(MçøJ£ÚÕ¦ÕJn."Gô±¬ YÍkkD8N$²±¡¬W3ÙŠªq‹ü)ºDÄM„òu£ Í¡4?ªEœÕu„ÂX#w·¨"}‰Í*d¬9A½Âó&ÿøóé?YÊÂJ²@»å(¬ ùY/Ú“U¹¬eTºÓ§õŠVʨ©¦ÌΞ´óníš\ØϤŒªi8¡—V¥ síd uýÓ¹¦Ôµ„în©ZáÊcÅSaÚ4”‹µÃ/lÅéR¤\æ¦$[Ëj$ë‘Klðð…_ÍÝï÷Â.мããbø¿/žò—Ç|æ5¿yÅ>òç|è+/zÀOïŸ'}êUoxËï}ô¯|ãozÉ7ï{ÿ|H¬|\þjnÝ7Šy?bûÖßžï„ï|ß/úåùÈW¾ëŸûéWßöÏ_>õµ|èk¿ôØŸ¾ìWúî—ßüÜ/óÉÿÿ}響úà?÷¯¿þÕ£õãÇÿøÅÏxòG?þðϾýÛ?º›; k»|º«Ó¡²1+µà?Æ›<ù;¾Ù›¿Ì3=åËÀÙ‹ÀÚƒ¼û ¿Å£½øË½¤=´ÀíÀÐË@ã;Á4A D¿ÓAË{<ÿë¿Ô@äAÒ{Á Ì¿ ܼÖ#>çK¿ ä?ÔAØË;ÂsÀßS¥“вâj!ÄÂ,ÔÂ-äÂ.ôÂ/Ã0Ã1ÃH2ãªýZ ¦š¢rú l¿ØC d=ïÃAëû¾ì{?9ÜCæ C:ôAú#Ã/,ÂÄü@D¿;<<éÀ8œ¿ã#¾ê-ÔÚ«ÿ%«­Ô°Bƒ€CúS¿E„¿Ôs>=LÄP4ÅD@=ìCÿ»>R4D@ÂP¬Àäó¼ $BAÚ/*Ä«yòyí9 »:«[º°[9”³9é…:pŠ¢<Ø@ÝÞîõ^:Ûï­ñQP#[.,r»˜LÞU.SM(îÒRÞó½ä¨éð-*µ_·Íž”u§ÍÅĆÊX›…_†ÃM•}$ §¬‚H'KWsØ]S=/(ÈÝL5ôÜè2.(”ÐÞsM~¯“H\ŠÛ£œã…&‚Rßks%° à) ´K2à˜•É•‚m›¸ïdÏöáâ â!&â"6â#Fâ$Vâ%fâ&vâ'†â(–â)¦â*¶â+Æâ,fb. €.öâ/ã0ã1ÿ&ã26ã3Fã4Vã5fã6vã7†ã8–ã9¦ã:¶ã;Æã<Öã=æã>.ãÄ1?äA&äB6äCFäDVäEfäFvä0þU€.ÞÖèâ]c¸d}äNöäOåPåQ&åRvcy5HJæb/Ï/^QVFÑHQYÖäM€V¾eMne\ÞåZÎe^ŽeSæa&æb6æcFæSî6XKå¨ä/O/ŽfYN€_våZÆä\îbñÔfmfj¶åiNæq&çr6çsFç<.D3JUUh®f[còìf\¦epçoþfqÞæxNçè€èæ‘`çG«3J&Ëk†æ`±¦e{æf~ææ^¾ç|ÆæZ6Oy&èæèŽöè¦ãuö‰µpgÔé“Fé”Vé•eÀºIvæñd–¦éš¶é›ÆéA®dòåéžöéŸê êž^Õ Æ×hŠJCµÝC}R¥vꦆj¦–ꥦ꧞j«®ê¨Îê«Öj¬öê®k®ë­&ë¯ëeÜiîE)NÙ̳ë²~k³†k·¦ë¹¶k¹Æë¸ÖëºÎk¾Þë»þë¾þ²˜ÿ¡f/E%ÁVìÀfl¿vlÀ~ìÅŽìÆ†ìÊ–l˦ìËÖl Ë•²â\Û¹ÂìÉ&íÑ6íÍ.mÔ>íÌfíÔníÕvmÒ^™f$ÅÅ_3ÕÖí×ÞíØ†íßîmàæíáöíà–lp½à¸RYNºm"îâ&îç–nãŽnê†îëžî²ÕKšÂ^æ8s*©NWì¶îì&ïêFïóVoófï¾VÝ#ê ý[a­ˆ ûnͤZÜônoþ.ïÿöï_o?ïû¶pë4Wðgðwp¨©Mk;´Q» pƒ¶­•6Üà!‡#ðþpñÿðq«6p¼–0×f_ùÿ†‰¢FÈ1òØP;·{“ð›=ññ'qÿq7ñ· Õ¯–qȶ1÷ ¯ d[¶6\ÛpŸÕZèr ò ×ò,çr,Ï&pJqˆÓ’w³J“,C¥WùFPØõŠ\­Ú¨-÷ò+§s9¯ó.¿sß sCjRRÚó€òÁöMÇZ)Œ®¥*Y&F'ÉGϲF—tH¿¶H§ôö™tK×ôJçtL¿ô»í`PwôMÿ«÷žàÒÉ[hóÜXêA·ïbóS¡|Ür/QÏôN·õOõ]u\çõ[÷tRÏuaÿu]ïõ`÷õcvU óÚEvpjõÒ‰>{MT¦²íÿÆöl×ömçön÷öowƒF *‘t‡·s7wtߣvçð¯³ù ;ï<pÐ{Ç÷s4Cõ4Ó££æå:µ{^° x«»ºigêÉ´÷|gø†§Æ—GT ÷ £¥L ŒE4FRÌ=ZTAÌÃA:ÌN‡'ùÅÜ CO­€5Øù‚u§DIÈSA¾ÓÀVŒ¼™‡ùÓ‹ÀG<Æ<ÌAÜã@ÇÛÃO´ù’'ú‡o 2ØŽú3ã]LPŽXøï¾™·¿œoAA¼Ã¬ÿÅa´>Äú˜Ç¾â+ú±C´!²¬àý^‰lKÌEùŒèDaÄyùÛyã ?ðÓz<¼ûö3½ûô#F (§{C$ûÂ×BˆÕñ Ìæ¦ªæŠ¸§Wˆ¨7üɧüËC|zŸ&`;ÎüµÿÜ5·vɯüÐ}ÛÌ9S³ü -ån>·¿Ÿ¡†ýØ—ýÙ§ýgÕY¦jFÝ]©öÚ÷ýßþà~}a·LáÄn;!•W{ ßáwþç‡þè?j@Íàk)ÄhqÌ×áDGótQkéÿðÚí ~/š[°üöv¦R>o°Õ'X,íÒI­ÿùÔügWú·ÿþˆ"HÐà‚dxp!B‡ #R„h±aEŒ:”xñ£G„"Žd¨ðdÆ#W®T9q`°|)ÒåF—8I¢Ü˜Ñ¦M‰;k-jô(Ò¤J—2mêô)Ô¨R§R­j²åÓ¡$‘^Õè±çÿÖ’µÂ”I³¨ÎšZ…n%ëö'Û@çÆõI÷ç]¹uÃîÍk·/`¼õ .Løð_ÉóUܘ±ßÇí2 iîØÉaY^æzS®Á˜3vT»¹"ÙÏKSWmíú5ìØ²gÓ®Ýú«f¼¦çVvL9iÚ”™0ËùtVäºU®®z1tÉÒ#S½ºoëÓµc‡Ìý{öðÞÅ_Ë:7QÜ×yK?ϼéPÑgñÊ$X»aõì÷cyñ¼m 8 xàq/(Ön¹¥¶`Í¥’|FɤLP† Ôa†õu8†$ŠØUƒüý·ƒã¹Xyø½(#Œ3vW#Ž4êxãÿŽàÙ¸Si-‚¶X`ñ¤›¿ ù^”)Ta[ÝGâ‡ehå"‚È¡ASN'ÜÔU$‚ešy&ših$NF¦ÈbƒdÅ „Ñ9”9Q‰‡÷mèg–Ur)b …éÕnL²$ié9úæsMJšd¤”"¦’™*·©Š2 饚zúh‚ú¹)•¢hyçmÃuRž˜NÊåf©Â7i­¤Fz*zéÆ$° Ëê¯ÃK,jÆ&‹¬¯Ëû¬³Ñ6;-¢ÌËZOv¾š ¥2¦_¨Få)ç^îÍêY§«ªzœéªù.¼ñÊ+à©Á¥Ø®»Ý~™¨žºŠêPq£Yî§•>dã½+Zª-·¸†;*¨²Bܰ¾œì°ÄW<1Æÿúk0Èýòêœk}ù·î˜MBx@¬b‹ò¢ W:²O&»|dµ)Ï™3Â5ãì ¯=G¹3Ð<}´ÑI½´‚>ÝôÐ(B­³Ôøâ»)Ã7Sz(§ÒN-´Ì÷’ð|DнðÉ ÛKêP6ËœµºýÆýsØr×M·Ýyã½÷Óz÷Í·Ô~øoƒÿ­³o‡;lÞzS/†b›C›ÜKãJL7×4—Êê[¢® wÇü°Æ!{ñé›.:ꬫNúèG½|¯m<»Ó#Þkê,ÿç-ÆŒodÀOüñÉ+¿üòÅ#¼óÊ=óÉSoüõÖ?_}öÒWý÷؇¿=÷ãw¯}øçƒŸ¾ùí³ÿþ÷ê‹ùô3/?ù÷»ÿúÏg}ôðW¼„LšcVª$T@%y¤e‘sÜåFbP°‚¼ 3¨Á r°ƒü C(Â’°„&ý)Pƒ*Ô¡æ4–P\M)UfOÐ42UºìB‹‰ž9ΫªV½*V³J¯aIuw[X›ÕÔÍhQ‡ušªVÓªÖµ²µ­9© ‰,Zž4“Æ´I1ÇËtYñsa:+dÖsÅ^•ô`Ò*l^ AÄ*–±‡5ì´YÈæŒ°”µ,\•YYº.Ó«•eZ'×EÚE—¶›+R=‡Ì… òun}-lc[׌)…´œ˜¾Î9ÎjÁ24¿s­h¡FÕ¨ 7mOôhƒ§Ü‰.7¹Ì}®s£{)LâºÓUV€L¥6MºÖ®ØE®·¢ÈÉÝ“¡­½Õqãj'Þ.P¶î}oJmLê×$Ýò®ˆt¨ç˜ruí©G¥oHŸÓÈÔ¶.³òü˜d?›`Ì6ö²‹uð‚œØÇNx²V0„« ±ÚµV¾ª+b´;“v2)ÿyõ._+8n²1µÔ0ŠY\øÒX¶ºUíjÛ¢V¬«êI˜gsû}Æ,©;^š„n›ÞÅ)ì–™’—ΛY‡Jš\©OX­Ì,G¹¼%ÁrM<¤c+WiUì1w‹,Ü®y¿fî'ð–Ÿß®öÆr¾ÅxË]ú†U¢„ zJ@>²M¢\ßt]¨K!úP¡µT%¬QJÌb¦tkm"B] Бö¡”ÓÐ@eÁ-Ú¡¤JZuTÅ{]ªï6æ6ßí£(Æâ©áL*3¤OXªò}h}f’fŽò‰H-è@ûRU–hw1‚ì]©ÑWBˆBÍ]išž?Öÿš’ùìef*uÌ$ƒÕo¥l²††;°pDñA‘”0(OºD€º˜Ýü³^KNÀ6¼t½]¥dwYH;)3®/Ço)Q©Ú.Ô½'MY“ä[×Hë*zã¬ÐÇõ¯ûº0Bü{ç}22Ç+¬¿‰[ï—Ç ­¬dÑb¿Â™ŸX—[²û³ÈE-Úníêˆz¹#cÈ3ѹ£Ÿ»‹æ”[yÁ9eWÙMÄj6ùè­Xã¶*¡%Æ[¼s~L’³rýöèzaöv³ÖH¢„M©ov#ÏÖæ²z1‡Ë笶äJã[Ìùu¨ÿ½=—ÜŒ5{öS‡÷Àn«9G )r™ÛS²2ÞîÏÿ×»çÅ3ɘÆ1âÒ<³šÚÝrV|z!Ov ç'¡;ku‡Í­t Çøã,G´Ä&Ï£,ÃXõä^äºc³s¿µ¼éi~ù<¹júºKö™·u4¥›ø³I×õ¯§üšw슼¸Î?ºÏW_ê›çU×»ó]¤ywùä^rÑ{}k±ÝY}ý{ånÿh÷]Ë)IÒ-`Þ~ÉRè±^ _dÞÖ1ï˜`Áyõõ}[þMÝþõP)‹Ù±'u®Lßû…ΉÑ]Æ1`ÌÝØàËÉÐÓ›Õšmà.±Nmž¾eTàΕÚE`ó}ØçÝÙ ÙXå™êÔŸÎ]ÿW¬•–5^ÂÝ«¹á°V~ÁX=Å þáÞyœQÙYÿ5ˆá ï ž¿’×ɪ "Ÿ~éÎÍ!VÈ¥›­¹ Éé¦iAí Øùœm8]ÿÑÌãÕRòݾÛ¨Eêy—ÞAÓÓñ¡$Žú–¬…ˆüÌ‘˜eÛHtNß彜¼XÖÊ àóE!þÞ`¬ßÒùáü-ž××!Z›Í]û5›©!ƒJˆ š ½5IÁÁag àÐFúŸ%öb^œì¡2¡ÊU)‹ï}×&Ÿ+F Æ1âªØVîÎÛ%Úˆ\² ¡I\¢eɉ Ü–<ÃDµa[ÃI\§ÛÓð—Æ½ *Î":ÎÕpÝömÒ+Š^ $tÉáÙEÎy¡ŽÛD./¢•¨=d6a’ [À \— c>‚ä;bÉŸyš;Š ð ÑÜ3ùX´‹q‡ÿ™[¸ù#¶WùÙÞé… â¡zÙ}áØpˆî"Äaˆ†ÐŠ<ŠÄ&ú ‡Œ³9š½ácSŠâ:6e–ÌÜda þŸw©š6cta:XÔÕõý£ÖY%Z Ó( BÒgÑU]âÿ× R íe\3YãÕœâà^ÚÕ¢-¢þ#öÛáÍÐ5ÞTM¢Vž8>b!R¦*(›/’’á8Äx-#Ç0h¶˜d†å$Š!U ¢ò¡Êd¶ŽKzM©u&_–!ޤȥâÅŸD’&º_YÌ€å$E ÝjV j4JÝÉ]¢ifã,¾ [.à³8”mVf]Wê "ØŠ•ã86ŽÂñäfâJ@œ'z¦çyšg°§z®ç{ºgzº'}Â'zÊç{Þ§~æ§zâ'þ'€æ§Ú'²§yú§|&h h€¶ç~h:è|NhƒîçƒV(ƒ.(Z(…¨†J¨‡vÿ¨„Z(‚2(„Ö'€¨ˆ~(†V¨ŠŽhŠFh‹ªçY&ZZ_íqâ·lE²Dq(@©i © )’)‘é’©‘ )©’Ji“&i‘:i•.é”f)’r©—v)“Zi˜Vé“Ré”>镎i˜ži”~iš¢)˜:©™¦)Æé™j)–Ú)™æ)˜n©Ÿ¾©”B©––i êšòiŸ&ªšòiâ霚©—ê)¥îi¡>ꤾi£V*yf4Ážp2#î‘ÞÄHL$@YUL8áªH«¾jE©¬Ä|ø#Å@Ûò]LªQD–Ä©òÉ&†!çëIhZ—)bkŽÿßZj§Ž&D°RåRF„(V„—l"pT+?ΚuÉ«}°dö‰äT?Ú%ƒEë¦Ù[¡¬Ä1Zœ!2EÙ|·´ *¦qMžº2×uLAì«Vn%hù%ÐeÇÁ\R]…º2e˜Í'Ž+œYÛGqå#À&ë£ šÀ^˜¦9ãêœ*¹JÛihl2ú¡RMÔ(DÒઉ BvоÒ*Ô#V¶ë¶¶ÄJD†0,Iú @ao &q]P\lVþš;’d».­>jeÍî£U š¶± U\¬HÚÆÛ>6m¨=-‰àãÊí´îì³¥¤GúZÒn,0†«:^nRb4îǯŽÀ ÿ\ÀE\¨0D¬ò‰RÚíÎBœ²uStÆú¤€,Ã-ÜVÞcCУS~-TF§dàekŽ”Ìò+äR.KF%— ‡¨ä;^kOúhæîI>¨…nÏ‚$uY­¢S7ž`õX<Õ“œîI†+¤‘¬Æ*ÕÅjîSÖ[T&#/¦Ý]¤wšªî.mñ2nVbëºÚG¡1Ûð⣖øSêÆÝ߈-»rY>:\RJï:cå-,ÓþíÑ.-¨-e×ï9p&,¨k2‘ãxºªÂFéÁ½k¡ÈÞÒ¥l|à§Ž!dCí­MÎ×Òâ]®ì¨DÝ6`*'T80ÊRãYÚÿa½êJÛß7§CŸr˜VYd ·° ¿0 ǰ Ï0 ×° ß0ç°ï0÷°ÿ0±1q “ç~IÍpàKî"±FÄQM1W±_1g±o1w±o±¬1ñ ›e¹‘Ø»u_q°ÐÔwqçT¿ñıJ½q‡Ô1Û1×ï±NÉñÇ »Ô ϱ² Oñ•ëq c±#¯Ô Ëq'òSrJEò"#²!¯ñh’è!ðÕõ*“FR O²†dr'çq¯2O-ò+Û1-«1+_²$çrK­±&«1,Ïñ+s²$ÿ21ÿr&òNÉÿ2+ƒHs03-¯22 33s2/c2"Ïr3ß²-U*?2$ër$·ò1gs1ûq%g³.ss.{ò¯¢(^o‘ÒäIñ:7³4“39g[2ws5c³8ô!373?[3;ãs%tB÷ÔAÃr#33Aóó8wó:órÛ2FÏr:²"[48S1@ ´:›3Dû3;§óH#4C#Ñ~`b0Ùá.©‚4Bot9/t?/óMó45§tA[4A#4:«³J÷´>¯´CgtR#õ>3µ0òE›sTu#7´TÇ2TOsHÿTE³FûôS356W´YЭra{0òöŽâ@TC¤qWÏ55]×µLqµ]çµ^ï5_ËÔ'¿!èÉQ †&×Yåàu_'¶b/6c7¶c?vKµtô™Ë®KÿÎY_„\C6gw¶g6h‡vOe"u6±ˆæ^J=µ%s1b¿ÔQ54u/ó1Pï´¿6gµhûr*ëtoõ$“4L•5IG3m£5¡+Ñ,Ìxf©rÄf7´2cô2ks,Ÿôl—3wã²wßvXõ0×20Wõv—÷1ÿvP9ru_²1ßÔW÷ö.·3V‡¶qu-c7z[5q+u+wêC+ÐJãJ¬¶MC3N_5‚ëö|‹³2gulôP×vzkwIûöBWs}÷s4ãôuo2|ó¶|Oõ…3¸bû7p÷ñ?£ôO·xBëñ¨j?Zgj÷+á®áoÒ„|MwT_µuç³lÿ㔓õ…9p5‰»ø9R[·‹¯wrs|ÏÔ”8u‹·hWù{/¹‚cr„KõY“6D¶¬®V'wÆšŒS[9›·¹›¿9œûÔýÂæl²¥vœp:–Eœï9Ÿ÷¹Ÿ»9€ƒ!®n†Í9}&J¬ùŸ/:£7º£w5뤒!…9 z”Õ>º¦o:§wúPEú³.wÞÈ"¼îGžC«‰{ºª¯:«/:/Ú:ôý G…=·:®çº®û9¨îéªøQ°H qªïº±;²ïõœÞIÑnäiðPOÜz²W»µ_{^Gº["dïÁµ;¶;¹—;Ozáv_yú룶ž›;¼Ç»¼vZ¿›9áeL_Hû‰û¼ÿ;À_û²cäþRºÉZ—ç{À/<Ãÿ{fCâÖ¤›-ZÌ6¼Å_<¶÷:`ƒå‡p çøP;Æ<ɳº¶üÅiäZ›1ç Ä)—§¿—¼ÌÏüˆÿõÇÇk¾ 6ÿYtg:Íÿ<Ð÷yŒÞ«âk6¨çnÐ/=Ó³yÒ#Þ4"¼-¦!È ˜¢7=Ög=ck¼7ykŽ Á̪˜GqÌk½ÙŸ½¿:.jræºT<ÚǽÜÏ5º‹ª¤Klj}ÛB÷Ü÷½ßwñó½2:&îL^.ÄÕÿ½â/¾œë86ÚÌ ‚rPöoQ$>ã_>æÓÔØ»ÿz£§¢Üg¾è¾_«,êñ˜7f¤tže^ò=é¿>ì«TÝ_§Z¡Á¡^­ÿ…åÇ>ïû=×w]*öVj¤£Ò÷¾ñ_þÀ¾¿N(W¢;SÙ¿ô—|ÝO ‹²V½Kˆüôw¿ÙÏìVcÅfÊ`‘äqÕ×Äî{¿úÓüÐëüfÂÙb&Në™zÏûÖúß?Ö«½ê7§í‡=@xÁ@&HÀ *DÀpAE‹1fÔ¸‘cGA†9’dI“'Q¦T¹’eK—/aÆ|y@ADƒo*´‰3§Nž:{"üi(DŸ 4¬I)™O¡F•:•jU«W±fÕú‘&QžBƒ5*ÖèP¦E{üªÖfÒ®iRÜ:—n]»wñæÕ»W#ÍŸCͲ%»(س8ÿîŒX¡Û¥hÈå;™reË—1g–é0­aÊ 3 ,ÑëáЂÇÿpŒ¡dͯaÇ–=›¶Ô·cq><»›woß¿ºequØàNk'W¾œyó×] | œzuëÝF4\¼´jäÎÁ‡?ž|ËÛL§£®>ztjëÙ!ù{yû÷ñçw~~húÀ‰jH Ä4¸Ó)»Ñ⨤ô‹P )Ü뼞½ ?ðÃOë;<#N)Ñ⪯ÂaŒQÆ•.´)=È$ŠÀ‚ l¨GASq·‚ô¯-¥H@%•\²È$™ŒÊ)›lrÊ+­ÌrI,¥¬²Ë/©ÓË0ÉÓL1Ñ,3M.¥dÓÍ3ÕŒÎ9Ó¤SÎ:ñ¼SO;ù̳ÿÏ=¥dHÉA¡$ÔÐB¿üSQ?¿¤IË-¹;ðFÐ>éÃPÄt@ˆ|äÔ½çƒï,î‹TÈI¯KUÕUYmÕÕWaUÖYi­õ=ÍQ/uíu×_} ö×O¼Í¬é¢3k8í+ð?¸0Aï.ô¬H¥¥ï­Ï>ÕÛ²rLm¾qdÖVVSWÝtÛ Ò\wÕ›¯(ÕsÞyß-ñÓ{íÍ·_hù‹¡_ æµ``Va„o ±Eb ÊP_Ÿ…·Ýn©åÍÔh¡Ã4Óã ¾øÞeñ·\“ëÅø\à¸ý·Þ‹Mô7å|ù]ùU’a¶9Õ¤Â<ôà„Th%¾”ZduBÕÿ@q¡eÙ]ny•)ùD»Ö+«›¶˜E€®ÒsÖ9Ö€]m¹eÞèöeÉ>y±ÎP–·íµ¹ž9)ƒ>3o ÷öbmkš6 €pà O\ñÅG¼pƇ<ñÈ?üqÆIœzŦݺñÏj¼òÑIŸüòÒ§õÕY'Ýñ×M·\öÓaŸöØeÿ¼uÜ%ÏÝöÝyW½tÊ ‡ÝxÓ·<ùÕ‹Þù硯|`_{æ;Qëû¶^5Ïeß|k±Á'lc›ßüóÑO_ýõÙoßý÷yCµ]œ¿W·kšûº)áïßÿÿ@€×9Û}#/êÀLd“¼ ˜@ÓDPÿgaCW«,HAº/ƒ,›'v¶ ºlû \ý¾¥?¦IPeé²Ní·,v¥†K[×·œfÃæo0@ ÔܶBºMP„ÜP;(CÔ(±‡bÙa·pÒ¦-IqŠU´R›Æ´¥GUqŠ„Ò"?6ª†è&H¿{^óG¼èNxÂÝáÇ8ÖîtrŒ¡‡G;îÒcêè95¾‘wu4dé˜FE¢N{t¤óNè2zðHo3!ݤFIMn’“ôä'U¥´m¡pk;|â´ 1ŽR=RËÙO¹DTÞn´œ_ÖlE2ZÒl¸´¡ý‚®‰Ý¬i¦ìï'Ä’¥,–¶_ —×(̹-c¥(3")SeëaHÅÆ'$M°'™ûMs¸©YŠCãÔÔlfÎw%Q–é 7KÁšQlˆô{¦%…éC¶}ïžh¨/º”cÅŒ\FS'9©#*nÿ…Ó(Â1g‡0ú!„Œh› ˆ0걈|Ôc(rXIúPýèc<ò”¥ztRŽŠh›2å(¦ÂnÖó—ÔT–@õWP`öæˆ3Û'3û™µ[r©æ¢gÝèV³kÚe)õèFÇÙ©ŽîôS™ü ÖJµ#›8L›ZŪKkŠÕK­­êô‘6"­•zŠ¥í4ˆ\µ‰Ó‘ªµð”'Wg©ÃeV¬…3«ŸP7ÈBöRˆ ( º¯RÖš<\Ue78U†¦ì¢îüØ6- áÄÇ{ ÉNæôŠ©Ôêõ³©%é;ûjW—Â6««E­j·êYÛzö®m%ˆYµJ[áš4¥Ž…*ÉÀ͆Vÿ—ˆuês3R"‡Ë5ntcøØ 5´Æ!Ê¢(³ZÒ´3õØFOÙá¨Ò\-–@qÉ]ïÎ×°óœeÅ›Øüž&Y<íïP©šÝª ŠëQaÔ6AûP¹ðup€‹`Ösƒ?Uˆf ¬ßÉÒ—¨ûó.Õ––Ia¾2¾Ò%edÓ ÕZQ—ŸdyZŠ£Yßë¶Ç¹/¦ïÈ:|âÀâÈ…51ï«à]RÃö­æ‘L¡Ì½ £1äûà|òr˜ ~!BaÜÄ$3Ëø•òˆ±Œbý>ùÈõ¥2‡ÌbƦظkŽñ…ƒd$Ã2ÖÊD$­a›L“+a‘‹{îs¿øç5]1‹‚ÿ6ô¡­è?oq‹‹4™¸xE?ZÒ®´£©iJGºÏ¾ô?ÍhN+ºÒ„Æt§êF úÒvBô¨SëOgúÕ¤®õÃUV]ïš×½öõ¯½ë ºå!屑le/»“d6²‹¡ä2ï&œ•ÕiO9XþVwÅ84f7¿ÝXÑËΤ%AOÖL®†ÛÚÉ\ZÅÒP:ÛÀqã6”s\îu_yÎÑNð5Ç?Ì»ŠõeÙ,Ý(VÆcënQ‡ÜÝ+¼Åõ*Š-¸pˆæø\O½7 ó‰@;K\=XÛrOý)B‹¹Ì,.85¹\Ô¥šyæòÖš);å‘›y§Æò²†3Ücõº ¿yƒUnÔ‰g²Nžnïƒ.UÂ/W[¼%;Dûø¿ Æ÷×±=ߢóÛÍøyÊoÌóëŸoÎz´onbˆÿ|Â`£8…£>w’Ÿ&R.¯±†^âå>›§K³x»®ïŠ‹äúÄqürt[\íŽgyÝmîð̯¼çZ>|¾1Ô¤Ÿû'I öéQŸzÕ¯žõ­wýëa{ÙÏžöµ·ýíqŸ{Ýïž÷½‡}@;poco-1.3.6p1-all/CppUnit/include/0000755000076500001200000000000011313735443017257 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/include/CppUnit/0000755000076500001200000000000011313735443020641 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/include/CppUnit/CppUnit.h0000644000076500001200000000320411313735443022373 0ustar guenteradmin00000000000000// // CppUnit.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/CppUnit.h#1 $ // #ifndef CppUnit_CppUnit_INCLUDED #define CppUnit_CppUnit_INCLUDED // // Ensure that POCO_DLL is default unless POCO_STATIC is defined // #if defined(_WIN32) && defined(_DLL) #if !defined(POCO_DLL) && !defined(POCO_STATIC) #define POCO_DLL #endif #endif // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the CppUnit_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // CppUnit_API functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) #if defined(CppUnit_EXPORTS) #define CppUnit_API __declspec(dllexport) #else #define CppUnit_API __declspec(dllimport) #endif #endif #if !defined(CppUnit_API) #define CppUnit_API #endif // Turn off some annoying warnings #ifdef _MSC_VER #pragma warning(disable:4786) // identifier truncation warning #pragma warning(disable:4503) // decorated name length exceeded - mainly a problem with STLPort #pragma warning(disable:4018) // signed/unsigned comparison #pragma warning(disable:4284) // return type for operator -> is not UDT #pragma warning(disable:4251) // ... needs to have dll-interface warning #pragma warning(disable:4273) #pragma warning(disable:4275) // ... non dll-interface class used as base for dll-interface class #endif #endif // CppUnit_CppUnit_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/CppUnitException.h0000644000076500001200000000725411313735443024263 0ustar guenteradmin00000000000000// // CppUnitException.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/CppUnitException.h#1 $ // #ifndef CppUnit_CppUnitException_INCLUDED #define CppUnit_CppUnitException_INCLUDED #include "CppUnit/CppUnit.h" #include #include namespace CppUnit { class CppUnit_API CppUnitException: public std::exception /// CppUnitException is an exception that serves /// descriptive strings through its what() method { public: CppUnitException(const std::string& message = "", long lineNumber = CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CPPUNIT_UNKNOWNFILENAME); CppUnitException(const std::string& message, long lineNumber, long data1lineNumber, const std::string& fileName); CppUnitException(const std::string& message, long lineNumber, long data1lineNumber, long data2lineNumber, const std::string& fileName); CppUnitException(const CppUnitException& other); virtual ~CppUnitException() throw(); CppUnitException& operator = (const CppUnitException& other); const char* what() const throw (); long lineNumber() const; long data1LineNumber() const; long data2LineNumber() const; const std::string& fileName() const; static const std::string CPPUNIT_UNKNOWNFILENAME; static const int CPPUNIT_UNKNOWNLINENUMBER; private: std::string _message; long _lineNumber; long _data1lineNumber; long _data2lineNumber; std::string _fileName; }; inline CppUnitException::CppUnitException(const CppUnitException& other): exception (other) { _message = other._message; _lineNumber = other._lineNumber; _data1lineNumber = other._data1lineNumber; _data2lineNumber = other._data2lineNumber; _fileName = other._fileName; } inline CppUnitException::CppUnitException (const std::string& message, long lineNumber, const std::string& fileName): _message(message), _lineNumber(lineNumber), _data1lineNumber(CPPUNIT_UNKNOWNLINENUMBER), _data2lineNumber(CPPUNIT_UNKNOWNLINENUMBER), _fileName(fileName) { } inline CppUnitException::CppUnitException (const std::string& message, long lineNumber, long data1lineNumber, const std::string& fileName): _message(message), _lineNumber(lineNumber), _data1lineNumber(data1lineNumber), _data2lineNumber(CPPUNIT_UNKNOWNLINENUMBER), _fileName(fileName) { } inline CppUnitException::CppUnitException (const std::string& message, long lineNumber, long data1lineNumber, long data2lineNumber, const std::string& fileName): _message(message), _lineNumber(lineNumber), _data1lineNumber(data1lineNumber), _data2lineNumber(data2lineNumber), _fileName(fileName) { } inline CppUnitException::~CppUnitException () throw() { } inline CppUnitException& CppUnitException::operator = (const CppUnitException& other) { exception::operator= (other); if (&other != this) { _message = other._message; _lineNumber = other._lineNumber; _data1lineNumber = other._data1lineNumber; _data2lineNumber = other._data2lineNumber; _fileName = other._fileName; } return *this; } inline const char* CppUnitException::what() const throw () { return _message.c_str(); } inline long CppUnitException::lineNumber() const { return _lineNumber; } inline long CppUnitException::data1LineNumber() const { return _data1lineNumber; } inline long CppUnitException::data2LineNumber() const { return _data2lineNumber; } // The file in which the error occurred inline const std::string& CppUnitException::fileName() const { return _fileName; } } // namespace CppUnit #endif // CppUnit_CppUnitException_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/estring.h0000644000076500001200000000233611313735443022471 0ustar guenteradmin00000000000000// // estring.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/estring.h#1 $ // #ifndef CppUnit_estring_INCLUDED #define CppUnit_estring_INCLUDED #include "CppUnit/CppUnit.h" #include #include namespace CppUnit { // Create a std::string from a const char pointer inline std::string estring(const char *cstring) { return std::string(cstring); } // Create a std::string from a std::string (for uniformities' sake) inline std::string estring(std::string& expandedString) { return expandedString; } // Create a std::string from an int inline std::string estring(int number) { char buffer[50]; sprintf(buffer, "%d", number); return std::string (buffer); } // Create a string from a long inline std::string estring(long number) { char buffer[50]; sprintf(buffer, "%ld", number); return std::string (buffer); } // Create a std::string from a double inline std::string estring(double number) { char buffer[50]; sprintf(buffer, "%lf", number); return std::string(buffer); } // Create a std::string from a double inline std::string estring(const void* ptr) { char buffer[50]; sprintf(buffer, "%p", ptr); return std::string(buffer); } } // namespace CppUnit #endif // CppUnit_estring_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/Guards.h0000644000076500001200000000056411313735443022244 0ustar guenteradmin00000000000000// // Guards.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/Guards.h#1 $ // #ifndef CppUnit_Guards_INCLUDED #define CppUnit_Guards_INCLUDED // Prevent copy construction and assignment for a class #define REFERENCEOBJECT(className) \ private: \ className(const className& other); \ className& operator = (const className& other); #endif // CppUnit_Guards_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/Orthodox.h0000644000076500001200000000423511313735443022624 0ustar guenteradmin00000000000000// // Orthodox.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/Orthodox.h#1 $ // #ifndef CppUnit_Orthodox_INCLUDED #define CppUnit_Orthodox_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/TestCase.h" namespace CppUnit { /* * Orthodox performs a simple set of tests on an arbitary * class to make sure that it supports at least the * following operations: * * default construction - constructor * equality/inequality - operator== && operator!= * assignment - operator= * negation - operator! * safe passage - copy construction * * If operations for each of these are not declared * the template will not instantiate. If it does * instantiate, tests are performed to make sure * that the operations have correct semantics. * * Adding an orthodox test to a suite is very * easy: * * public: Test *suite () { * TestSuite *suiteOfTests = new TestSuite; * suiteOfTests->addTest (new ComplexNumberTest ("testAdd"); * suiteOfTests->addTest (new TestCaller > ()); * return suiteOfTests; * } * * Templated test cases be very useful when you are want to * make sure that a group of classes have the same form. * * see TestSuite */ template class Orthodox: public TestCase { public: Orthodox(): TestCase("Orthodox") { } protected: ClassUnderTest call(ClassUnderTest object); void runTest (); }; // Run an orthodoxy test template void Orthodox::runTest() { // make sure we have a default constructor ClassUnderTest a, b, c; // make sure we have an equality operator assert (a == b); // check the inverse b.operator= (a.operator! ()); assert (a != b); // double inversion b = !!a; assert (a == b); // invert again b = !a; // check calls c = a; assert (c == call (a)); c = b; assert (c == call (b)); } // Exercise a call template ClassUnderTest Orthodox::call(ClassUnderTest object) { return object; } } // namespace CppUnit #endif // CppUnit_Orthodox_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/RepeatedTest.h0000644000076500001200000000244011313735443023403 0ustar guenteradmin00000000000000// // RepeatedTest.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/RepeatedTest.h#1 $ // #ifndef CppUnit_RepeatedTest_INCLUDED #define CppUnit_RepeatedTest_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/Guards.h" #include "CppUnit/TestDecorator.h" namespace CppUnit { class Test; class TestResult; /* * A decorator that runs a test repeatedly. * Does not assume ownership of the test it decorates * */ class CppUnit_API RepeatedTest: public TestDecorator { REFERENCEOBJECT (RepeatedTest) public: RepeatedTest(Test* test, int timesRepeat): TestDecorator (test), _timesRepeat (timesRepeat) { } int countTestCases(); std::string toString(); void run(TestResult *result); private: const int _timesRepeat; }; // Counts the number of test cases that will be run by this test. inline RepeatedTest::countTestCases () { return TestDecorator::countTestCases() * _timesRepeat; } // Returns the name of the test instance. inline std::string RepeatedTest::toString() { return TestDecorator::toString() + " (repeated)"; } // Runs a repeated test inline void RepeatedTest::run(TestResult *result) { for (int n = 0; n < _timesRepeat; n++) { if (result->shouldStop()) break; TestDecorator::run(result); } } } // namespace CppUnit #endif // CppUnit_RepeatedTest_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/Test.h0000644000076500001200000000157111313735443021735 0ustar guenteradmin00000000000000// // Test.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/Test.h#1 $ // #ifndef CppUnit_Test_INCLUDED #define CppUnit_Test_INCLUDED #include "CppUnit/CppUnit.h" #include namespace CppUnit { class TestResult; /* * A Test can be run and collect its results. * See TestResult. * */ class CppUnit_API Test { public: virtual ~Test() = 0; virtual void run(TestResult* result) = 0; virtual int countTestCases() = 0; virtual std::string toString() = 0; }; inline Test::~Test() { } // Runs a test and collects its result in a TestResult instance. inline void Test::run(TestResult *result) { } // Counts the number of test cases that will be run by this test. inline int Test::countTestCases() { return 0; } // Returns the name of the test instance. inline std::string Test::toString() { return ""; } } // namespace CppUnit #endif // CppUnit_Test_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestCaller.h0000644000076500001200000000326511313735443023062 0ustar guenteradmin00000000000000// // TestCaller.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestCaller.h#1 $ // #ifndef CppUnit_TestCaller_INCLUDED #define CppUnit_TestCaller_INCLUDED #include "CppUnit/CppUnit.h" #include "Guards.h" #include "TestCase.h" #include namespace CppUnit { /* * A test caller provides access to a test case method * on a test case class. Test callers are useful when * you want to run an individual test or add it to a * suite. * * Here is an example: * * class MathTest : public TestCase { * ... * public: * void setUp (); * void tearDown (); * * void testAdd (); * void testSubtract (); * }; * * Test *MathTest::suite () { * TestSuite *suite = new TestSuite; * * suite->addTest (new TestCaller ("testAdd", testAdd)); * return suite; * } * * You can use a TestCaller to bind any test method on a TestCase * class, as long as it returns accepts void and returns void. * * See TestCase */ template class TestCaller: public TestCase { REFERENCEOBJECT (TestCaller) typedef void (Fixture::*TestMethod)(); public: TestCaller(const std::string& name, TestMethod test): TestCase(name), _test(test), _fixture(new Fixture(name)) { } protected: void runTest() { (_fixture.get()->*_test)(); } void setUp() { _fixture.get()->setUp(); } void tearDown() { _fixture.get()->tearDown(); } private: TestMethod _test; std::auto_ptr _fixture; }; } // namespace CppUnit #define CppUnit_addTest(suite, cls, mth) \ suite->addTest(new CppUnit::TestCaller(#mth, &cls::mth)) #endif // CppUnit_TestCaller_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestCase.h0000644000076500001200000001732111313735443022531 0ustar guenteradmin00000000000000// // TestCase.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestCase.h#1 $ // #ifndef CppUnit_TestCase_INCLUDED #define CppUnit_TestCase_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/Guards.h" #include "CppUnit/Test.h" #include "CppUnit/CppUnitException.h" #include #include namespace CppUnit { class TestResult; /* * A test case defines the fixture to run multiple tests. To define a test case * 1) implement a subclass of TestCase * 2) define instance variables that store the state of the fixture * 3) initialize the fixture state by overriding setUp * 4) clean-up after a test by overriding tearDown. * * Each test runs in its own fixture so there * can be no side effects among test runs. * Here is an example: * * class MathTest : public TestCase { * protected: int m_value1; * protected: int m_value2; * * public: MathTest (std::string name) * : TestCase (name) { * } * * protected: void setUp () { * m_value1 = 2; * m_value2 = 3; * } * } * * * For each test implement a method which interacts * with the fixture. Verify the expected results with assertions specified * by calling assert on the expression you want to test: * * protected: void testAdd () { * int result = value1 + value2; * assert (result == 5); * } * * Once the methods are defined you can run them. To do this, use * a TestCaller. * * Test *test = new TestCaller("testAdd", MathTest::testAdd); * test->run (); * * * The tests to be run can be collected into a TestSuite. CppUnit provides * different test runners which can run a test suite and collect the results. * The test runners expect a static method suite as the entry * point to get a test to run. * * public: static MathTest::suite () { * TestSuite *suiteOfTests = new TestSuite; * suiteOfTests->addTest(new TestCaller("testAdd", testAdd)); * suiteOfTests->addTest(new TestCaller("testDivideByZero", testDivideByZero)); * return suiteOfTests; * } * * Note that the caller of suite assumes lifetime control * for the returned suite. * * see TestResult, TestSuite and TestCaller * */ class CppUnit_API TestCase: public Test { REFERENCEOBJECT (TestCase) public: TestCase(const std::string& Name); ~TestCase(); virtual void run(TestResult* result); virtual TestResult* run(); virtual int countTestCases(); const std::string& name() const; std::string toString(); virtual void setUp(); virtual void tearDown(); protected: virtual void runTest(); TestResult* defaultResult(); void assertImplementation(bool condition, const std::string& conditionExpression = "", long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void loop1assertImplementation(bool condition, const std::string& conditionExpression = "", long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, long dataLineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void loop2assertImplementation(bool condition, const std::string& conditionExpression = "", long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, long data1LineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, long data2LineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void assertEquals(long expected, long actual, long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void assertEquals(double expected, double actual, double delta, long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void assertEquals(const std::string& expected, const std::string& actual, long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void assertEquals(const void* expected, const void* actual, long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); std::string notEqualsMessage(long expected, long actual); std::string notEqualsMessage(double expected, double actual); std::string notEqualsMessage(const void* expected, const void* actual); std::string notEqualsMessage(const std::string& expected, const std::string& actual); void assertNotNull(const void* pointer, const std::string& pointerExpression = "", long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void assertNull(const void* pointer, const std::string& pointerExpression = "", long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); void fail(const std::string&message = "", long lineNumber = CppUnitException::CPPUNIT_UNKNOWNLINENUMBER, const std::string& fileName = CppUnitException::CPPUNIT_UNKNOWNFILENAME); private: const std::string _name; }; // Constructs a test case inline TestCase::TestCase(const std::string& name): _name (name) { } // Destructs a test case inline TestCase::~TestCase() { } // Returns a count of all the tests executed inline int TestCase::countTestCases() { return 1; } // Returns the name of the test case inline const std::string& TestCase::name() const { return _name; } // A hook for fixture set up inline void TestCase::setUp() { } // A hook for fixture tear down inline void TestCase::tearDown() { } // Returns the name of the test case instance inline std::string TestCase::toString() { const std::type_info& thisClass = typeid(*this); return std::string(thisClass.name()) + "." + name(); } // A set of macros which allow us to get the line number // and file name at the point of an error. // Just goes to show that preprocessors do have some // redeeming qualities. #undef assert #define assert(condition) \ (this->assertImplementation((condition), (#condition), __LINE__, __FILE__)) #define loop_1_assert(data1line, condition) \ (this->loop1assertImplementation((condition), (#condition), __LINE__, data1line, __FILE__)) #define loop_2_assert(data1line, data2line, condition) \ (this->loop2assertImplementation((condition), (#condition), __LINE__, data1line, data2line, __FILE__)) #define assertEqualDelta(expected, actual, delta) \ (this->assertEquals((expected), (actual), (delta), __LINE__, __FILE__)) #define assertEqual(expected, actual) \ (this->assertEquals((expected), (actual), __LINE__, __FILE__)) #define assertNullPtr(ptr) \ (this->assertNull((ptr), #ptr, __LINE__, __FILE__)) #define assertNotNullPtr(ptr) \ (this->assertNotNull((ptr), #ptr, __LINE__, __FILE__)) #define failmsg(msg) \ (this->fail(msg, __LINE__, __FILE__)) } // namespace CppUnit #endif // CppUnit_TestCase_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestDecorator.h0000644000076500001200000000131311313735443023572 0ustar guenteradmin00000000000000// // TestDecorator.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestDecorator.h#1 $ // #ifndef CppUnit_TestDecorator_INCLUDED #define CppUnit_TestDecorator_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/Guards.h" #include "CppUnit/Test.h" namespace CppUnit { class TestResult; /* * A Decorator for Tests * * Does not assume ownership of the test it decorates * */ class CppUnit_API TestDecorator: public Test { REFERENCEOBJECT(TestDecorator) public: TestDecorator(Test* test); virtual ~TestDecorator(); int countTestCases(); void run(TestResult* result); std::string toString(); protected: Test* _test; }; } // namespace CppUnit #endif // CppUnit_TestDecorator_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestFailure.h0000644000076500001200000000276511313735443023253 0ustar guenteradmin00000000000000// // TestFailure.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestFailure.h#1 $ // #ifndef CppUnit_TestFailure_INCLUDED #define CppUnit_TestFailure_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/CppUnitException.h" #include "CppUnit/Guards.h" namespace CppUnit { class Test; /* * A TestFailure collects a failed test together with * the caught exception. * * TestFailure assumes lifetime control for any exception * passed to it. The lifetime of tests is handled by * their TestSuite (if they have been added to one) or * whomever creates them. * * see TestResult * see TestSuite * */ class CppUnit_API TestFailure { REFERENCEOBJECT (TestFailure) public: TestFailure(Test* failedTest, CppUnitException* thrownException); ~TestFailure(); Test* failedTest(); CppUnitException* thrownException(); std::string toString(); protected: Test* _failedTest; CppUnitException *_thrownException; }; // Constructs a TestFailure with the given test and exception. inline TestFailure::TestFailure(Test* failedTest, CppUnitException* thrownException): _failedTest(failedTest), _thrownException(thrownException) { } // Deletes the owned exception. inline TestFailure::~TestFailure() { delete _thrownException; } // Gets the failed test. inline Test* TestFailure::failedTest() { return _failedTest; } // Gets the thrown exception. inline CppUnitException* TestFailure::thrownException() { return _thrownException; } } // namespace CppUnit #endif // CppUnit_TestFailure_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestResult.h0000644000076500001200000001127111313735443023132 0ustar guenteradmin00000000000000// // TestResult.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestResult.h#1 $ // #ifndef CppUnit_TestResult_INCLUDED #define CppUnit_TestResult_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/Guards.h" #include "CppUnit/TestFailure.h" #include namespace CppUnit { class CppUnitException; class Test; /* * A TestResult collects the results of executing a test case. It is an * instance of the Collecting Parameter pattern. * * The test framework distinguishes between failures and errors. * A failure is anticipated and checked for with assertions. Errors are * unanticipated problems signified by exceptions that are not generated * by the framework. * * TestResult supplies a template method 'setSynchronizationObject ()' * so that subclasses can provide mutual exclusion in the face of multiple * threads. This can be useful when tests execute in one thread and * they fill a subclass of TestResult which effects change in another * thread. To have mutual exclusion, override setSynchronizationObject () * and make sure that you create an instance of ExclusiveZone at the * beginning of each method. * * see Test */ class CppUnit_API TestResult { REFERENCEOBJECT (TestResult) public: TestResult(); virtual ~TestResult(); virtual void addError(Test* test, CppUnitException* e); virtual void addFailure(Test* test, CppUnitException* e); virtual void startTest(Test* test); virtual void endTest(Test* test); virtual int runTests(); virtual int testErrors(); virtual int testFailures(); virtual bool wasSuccessful(); virtual bool shouldStop(); virtual void stop(); virtual std::vector& errors(); virtual std::vector& failures(); class SynchronizationObject { public: SynchronizationObject() { } virtual ~SynchronizationObject() { } virtual void lock() { } virtual void unlock() { } }; class ExclusiveZone { SynchronizationObject* m_syncObject; public: ExclusiveZone(SynchronizationObject* syncObject): m_syncObject(syncObject) { m_syncObject->lock(); } ~ExclusiveZone() { m_syncObject->unlock(); } }; protected: virtual void setSynchronizationObject(SynchronizationObject* syncObject); std::vector _errors; std::vector _failures; int _runTests; bool _stop; SynchronizationObject* _syncObject; }; // Construct a TestResult inline TestResult::TestResult(): _syncObject(new SynchronizationObject()) { _runTests = 0; _stop = false; } // Adds an error to the list of errors. The passed in exception // caused the error inline void TestResult::addError(Test* test, CppUnitException* e) { ExclusiveZone zone(_syncObject); _errors.push_back(new TestFailure(test, e)); } // Adds a failure to the list of failures. The passed in exception // caused the failure. inline void TestResult::addFailure(Test* test, CppUnitException* e) { ExclusiveZone zone(_syncObject); _failures.push_back(new TestFailure(test, e)); } // Informs the result that a test will be started. inline void TestResult::startTest(Test* test) { ExclusiveZone zone(_syncObject); _runTests++; } // Informs the result that a test was completed. inline void TestResult::endTest(Test* test) { ExclusiveZone zone(_syncObject); } // Gets the number of run tests. inline int TestResult::runTests() { ExclusiveZone zone(_syncObject); return _runTests; } // Gets the number of detected errors. inline int TestResult::testErrors() { ExclusiveZone zone(_syncObject); return (int) _errors.size(); } // Gets the number of detected failures. inline int TestResult::testFailures() { ExclusiveZone zone(_syncObject); return (int) _failures.size(); } // Returns whether the entire test was successful or not. inline bool TestResult::wasSuccessful() { ExclusiveZone zone(_syncObject); return _failures.size() == 0 && _errors.size () == 0; } // Returns a std::vector of the errors. inline std::vector& TestResult::errors() { ExclusiveZone zone(_syncObject); return _errors; } // Returns a std::vector of the failures. inline std::vector& TestResult::failures() { ExclusiveZone zone(_syncObject); return _failures; } // Returns whether testing should be stopped inline bool TestResult::shouldStop() { ExclusiveZone zone(_syncObject); return _stop; } // Stop testing inline void TestResult::stop() { ExclusiveZone zone(_syncObject); _stop = true; } // Accept a new synchronization object for protection of this instance // TestResult assumes ownership of the object inline void TestResult::setSynchronizationObject(SynchronizationObject* syncObject) { delete _syncObject; _syncObject = syncObject; } } // namespace CppUnit #endif // CppUnit_TestResult_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestRunner.h0000644000076500001200000000317611313735443023132 0ustar guenteradmin00000000000000// // TestRunner.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestRunner.h#2 $ // #ifndef CppUnit_TestRunner_INCLUDED #define CppUnit_TestRunner_INCLUDED #include "CppUnit/CppUnit.h" #include #include #include namespace CppUnit { class Test; /* * A command line based tool to run tests. * TestRunner expects as its only argument the name of a TestCase class. * TestRunner prints out a trace as the tests are executed followed by a * summary at the end. * * You can add to the tests that the TestRunner knows about by * making additional calls to "addTest (...)" in main. * * Here is the synopsis: * * TestRunner [-all] [-print] [-wait] ExampleTestCase * */ class CppUnit_API TestRunner { typedef std::pair Mapping; typedef std::vector Mappings; public: TestRunner(); TestRunner(std::ostream& ostr); ~TestRunner(); bool run(const std::vector& args); void addTest(const std::string& name, Test* test); protected: bool run(Test* test); void printBanner(); void print(const std::string& name, Test* pTest, int indent); Test* find(const std::string& name, Test* pTest, const std::string& testName); private: std::ostream& _ostr; Mappings _mappings; }; } // namespace CppUnit #define CppUnitMain(testCase) \ int main(int ac, char **av) \ { \ std::vector args; \ for (int i = 0; i < ac; ++i) \ args.push_back(std::string(av[i])); \ CppUnit::TestRunner runner; \ runner.addTest(#testCase, testCase::suite()); \ return runner.run(args) ? 0 : 1; \ } #endif // CppUnit_TestRunner_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestSetup.h0000644000076500001200000000130611313735443022752 0ustar guenteradmin00000000000000// // TestSetup.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestSetup.h#1 $ // #ifndef CppUnit_TestSetup_INCLUDED #define CppUnit_TestSetup_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/Guards.h" #include "CppUnit/TestDecorator.h" namespace CppUnit { class Test; class TestResult; class CppUnit_API TestSetup: public TestDecorator { REFERENCEOBJECT (TestSetup) public: TestSetup(Test* test): TestDecorator(test) { } void run(TestResult* result); protected: void setUp() { } void tearDown() { } }; inline void TestSetup::run(TestResult* result) { setUp(); TestDecorator::run(result); tearDown(); } } // namespace CppUnit #endif // CppUnit_TestSetup_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TestSuite.h0000644000076500001200000000322311313735443022743 0ustar guenteradmin00000000000000// // TestSuite.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TestSuite.h#1 $ // #ifndef CppUnit_TestSuite_INCLUDED #define CppUnit_TestSuite_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/Guards.h" #include "CppUnit/Test.h" #include #include namespace CppUnit { class TestResult; /* * A TestSuite is a Composite of Tests. * It runs a collection of test cases. Here is an example. * * TestSuite *suite= new TestSuite(); * suite->addTest(new TestCaller ("testAdd", testAdd)); * suite->addTest(new TestCaller ("testDivideByZero", testDivideByZero)); * * Note that TestSuites assume lifetime * control for any tests added to them. * * see Test and TestCaller */ class CppUnit_API TestSuite: public Test { REFERENCEOBJECT (TestSuite) public: TestSuite(const std::string& name = ""); ~TestSuite(); void run(TestResult* result); int countTestCases(); void addTest(Test* test); std::string toString(); virtual void deleteContents(); const std::vector tests() const; private: std::vector _tests; const std::string _name; }; // Default constructor inline TestSuite::TestSuite(const std::string& name): _name(name) { } // Destructor inline TestSuite::~TestSuite() { deleteContents(); } // Adds a test to the suite. inline void TestSuite::addTest(Test* test) { _tests.push_back(test); } // Returns a std::string representation of the test suite. inline std::string TestSuite::toString() { return "suite " + _name; } // Returns all tests inline const std::vector TestSuite::tests() const { return _tests; } } // namespace CppUnit #endif // CppUnit_TestSuite_INCLUDED poco-1.3.6p1-all/CppUnit/include/CppUnit/TextTestResult.h0000644000076500001200000000207211313735443023776 0ustar guenteradmin00000000000000// // TextTestResult.h // // $Id: //poco/1.3/CppUnit/include/CppUnit/TextTestResult.h#2 $ // #ifndef CppUnit_TextTestResult_INCLUDED #define CppUnit_TextTestResult_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/TestResult.h" #include namespace CppUnit { class CppUnit_API TextTestResult: public TestResult { public: TextTestResult(); TextTestResult(std::ostream& ostr); virtual void addError(Test* test, CppUnitException* e); virtual void addFailure(Test* test, CppUnitException* e); virtual void startTest(Test* test); virtual void print(std::ostream& stream); virtual void printErrors(std::ostream& stream); virtual void printFailures(std::ostream& stream); virtual void printHeader(std::ostream& stream); protected: std::string shortName(const std::string& testName); private: std::ostream& _ostr; }; /* insertion operator for easy output */ inline std::ostream& operator<< (std::ostream& stream, TextTestResult& result) { result.print(stream); return stream; } } // namespace CppUnit #endif // CppUnit_TextTestResult_INCLUDED poco-1.3.6p1-all/CppUnit/Makefile0000644000076500001200000000052411313735443017275 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/CppUnit/Makefile#1 $ # # Makefile for Poco CppUnit # include $(POCO_BASE)/build/rules/global objects = CppUnitException TestDecorator TestResult TestSuite \ TestCase TestFailure TestRunner TextTestResult target = CppUnit target_version = 1 target_libs = include $(POCO_BASE)/build/rules/lib poco-1.3.6p1-all/CppUnit/src/0000755000076500001200000000000011313735443016423 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/src/CppUnitException.cpp0000644000076500001200000000047111313735443022372 0ustar guenteradmin00000000000000// // CppUnitException.cpp // // $Id: //poco/1.3/CppUnit/src/CppUnitException.cpp#1 $ // #include "CppUnit/CppUnitException.h" namespace CppUnit { const std::string CppUnitException::CPPUNIT_UNKNOWNFILENAME = ""; const int CppUnitException::CPPUNIT_UNKNOWNLINENUMBER = -1; } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TestCase.cpp0000644000076500001200000001122611313735443020644 0ustar guenteradmin00000000000000// // TestCase.cpp // // $Id: //poco/1.3/CppUnit/src/TestCase.cpp#1 $ // #include #include #include "CppUnit/TestCase.h" #include "CppUnit/TestResult.h" #include "CppUnit/estring.h" #include using namespace std; namespace CppUnit { // Create a default TestResult TestResult* TestCase::defaultResult() { return new TestResult; } // Check for a failed general assertion void TestCase::assertImplementation(bool condition, const std::string& conditionExpression, long lineNumber, const std::string& fileName) { if (!condition) throw CppUnitException(conditionExpression, lineNumber, fileName); } void TestCase::loop1assertImplementation(bool condition, const std::string& conditionExpression, long lineNumber, long data1lineNumber, const std::string& fileName) { if (!condition) throw CppUnitException(conditionExpression, lineNumber, data1lineNumber, fileName); } void TestCase::loop2assertImplementation(bool condition, const std::string& conditionExpression, long lineNumber, long data1lineNumber, long data2lineNumber, const std::string& fileName) { if (!condition) throw CppUnitException(conditionExpression, lineNumber, data1lineNumber, data2lineNumber, fileName); } // Check for a failed equality assertion void TestCase::assertEquals(long expected, long actual, long lineNumber, const std::string& fileName) { if (expected != actual) assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName); } // Check for a failed equality assertion void TestCase::assertEquals(double expected, double actual, double delta, long lineNumber, const std::string& fileName) { if (fabs(expected - actual) > delta) assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName); } // Check for a failed equality assertion void TestCase::assertEquals(const void* expected, const void* actual, long lineNumber, const std::string& fileName) { if (expected != actual) assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName); } // Check for a failed equality assertion void TestCase::assertEquals(const std::string& expected, const std::string& actual, long lineNumber, const std::string& fileName) { if (expected != actual) assertImplementation(false, notEqualsMessage(expected, actual), lineNumber, fileName); } void TestCase::assertNotNull(const void* pointer, const std::string& pointerExpression, long lineNumber, const std::string& fileName) { if (pointer == NULL) throw CppUnitException(pointerExpression + " must not be NULL", lineNumber, fileName); } void TestCase::assertNull(const void* pointer, const std::string& pointerExpression, long lineNumber, const std::string& fileName) { if (pointer != NULL) throw CppUnitException(pointerExpression + " must be NULL", lineNumber, fileName); } void TestCase::fail (const std::string& message, long lineNumber, const std::string& fileName) { throw CppUnitException(std::string("fail: ") + message, lineNumber, fileName); } // Run the test and catch any exceptions that are triggered by it void TestCase::run(TestResult *result) { result->startTest(this); setUp(); try { runTest(); } catch (CppUnitException& e) { CppUnitException* copy = new CppUnitException(e); result->addFailure(this, copy); } catch (std::exception& e) { std::string msg(typeid(e).name()); msg.append(": "); msg.append(e.what()); result->addError(this, new CppUnitException(msg)); } #if !defined(_WIN32) catch (...) { CppUnitException *e = new CppUnitException ("unknown exception"); result->addError (this, e); } #endif tearDown (); result->endTest(this); } // A default run method TestResult* TestCase::run() { TestResult* result = defaultResult(); run(result); return result; } // All the work for runTest is deferred to subclasses void TestCase::runTest() { } // Build a message about a failed equality check std::string TestCase::notEqualsMessage(long expected, long actual) { return "expected: " + estring(expected) + " but was: " + estring(actual); } // Build a message about a failed equality check std::string TestCase::notEqualsMessage(double expected, double actual) { return "expected: " + estring(expected) + " but was: " + estring(actual); } // Build a message about a failed equality check std::string TestCase::notEqualsMessage(const void* expected, const void* actual) { return "expected: " + estring(expected) + " but was: " + estring(actual); } // Build a message about a failed equality check std::string TestCase::notEqualsMessage(const std::string& expected, const std::string& actual) { return "expected: \"" + expected + "\" but was: \"" + actual + "\""; } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TestDecorator.cpp0000644000076500001200000000074511313735443021717 0ustar guenteradmin00000000000000// // TestDecorator.cpp // // $Id: //poco/1.3/CppUnit/src/TestDecorator.cpp#1 $ // #include "CppUnit/TestDecorator.h" namespace CppUnit { TestDecorator::TestDecorator(Test* test) { _test = test; } TestDecorator::~TestDecorator() { } int TestDecorator::countTestCases() { return _test->countTestCases(); } void TestDecorator::run(TestResult* result) { _test->run(result); } std::string TestDecorator::toString() { return _test->toString(); } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TestFailure.cpp0000644000076500001200000000053011313735443021354 0ustar guenteradmin00000000000000// // TestFailure.cpp // // $Id: //poco/1.3/CppUnit/src/TestFailure.cpp#1 $ // #include "CppUnit/TestFailure.h" #include "CppUnit/Test.h" namespace CppUnit { // Returns a short description of the failure. std::string TestFailure::toString() { return _failedTest->toString () + ": " + _thrownException->what(); } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TestResult.cpp0000644000076500001200000000064711313735443021254 0ustar guenteradmin00000000000000// // TestResult.cpp // // $Id: //poco/1.3/CppUnit/src/TestResult.cpp#1 $ // #include "CppUnit/TestResult.h" namespace CppUnit { // Destroys a test result TestResult::~TestResult() { std::vector::iterator it; for (it = _errors.begin(); it != _errors.end(); ++it) delete *it; for (it = _failures.begin(); it != _failures.end(); ++it) delete *it; delete _syncObject; } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TestRunner.cpp0000644000076500001200000000643311313735443021246 0ustar guenteradmin00000000000000// // TestRunner.cpp // // $Id: //poco/1.3/CppUnit/src/TestRunner.cpp#2 $ // #include "CppUnit/TestRunner.h" #include "CppUnit/Test.h" #include "CppUnit/TestSuite.h" #include "CppUnit/TextTestResult.h" #include namespace CppUnit { TestRunner::TestRunner(): _ostr(std::cout) { } TestRunner::TestRunner(std::ostream& ostr): _ostr(ostr) { } TestRunner::~TestRunner() { for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it) delete it->second; } void TestRunner::printBanner() { _ostr << "Usage: driver [-all] [-print] [-wait] [name] ..." << std::endl << " where name is the name of a test case class" << std::endl; } bool TestRunner::run(const std::vector& args) { std::string testCase; int numberOfTests = 0; bool success = true; bool all = false; bool wait = false; bool printed = false; for (int i = 1; i < args.size(); i++) { const std::string& arg = args[i]; if (arg == "-wait") { wait = true; continue; } else if (arg == "-all") { all = true; continue; } else if (arg == "-print") { for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it) { print(it->first, it->second, 0); } printed = true; continue; } if (!all) { testCase = arg; if (testCase == "") { printBanner(); return false; } Test* testToRun = 0; for (Mappings::iterator it = _mappings.begin(); !testToRun && it != _mappings.end(); ++it) { testToRun = find(testCase, it->second, it->first); } if (testToRun) { if (!run(testToRun)) success = false; } numberOfTests++; if (!testToRun) { _ostr << "Test " << testCase << " not found." << std::endl; return false; } } } if (all) { for (Mappings::iterator it = _mappings.begin(); it != _mappings.end(); ++it) { if (!run(it->second)) success = false; numberOfTests++; } } if (numberOfTests == 0 && !printed) { printBanner(); return false; } if (wait) { _ostr << " to continue" << std::endl; std::cin.get(); } return success; } bool TestRunner::run(Test* test) { TextTestResult result(_ostr); test->run(&result); _ostr << result << std::endl; return result.wasSuccessful(); } void TestRunner::addTest(const std::string& name, Test* test) { _mappings.push_back(Mapping(name, test)); } void TestRunner::print(const std::string& name, Test* pTest, int indent) { for (int i = 0; i < indent; ++i) _ostr << " "; _ostr << name << std::endl; TestSuite* pSuite = dynamic_cast(pTest); if (pSuite) { const std::vector& tests = pSuite->tests(); for (std::vector::const_iterator it = tests.begin(); it != tests.end(); ++it) { print((*it)->toString(), *it, indent + 1); } } } Test* TestRunner::find(const std::string& name, Test* pTest, const std::string& testName) { if (testName.find(name) != std::string::npos) { return pTest; } else { TestSuite* pSuite = dynamic_cast(pTest); if (pSuite) { const std::vector& tests = pSuite->tests(); for (std::vector::const_iterator it = tests.begin(); it != tests.end(); ++it) { Test* result = find(name, *it, (*it)->toString()); if (result) return result; } } return 0; } } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TestSuite.cpp0000644000076500001200000000157311313735443021066 0ustar guenteradmin00000000000000// // TestSuite.cpp // // $Id: //poco/1.3/CppUnit/src/TestSuite.cpp#1 $ // #include "CppUnit/TestSuite.h" #include "CppUnit/TestResult.h" namespace CppUnit { // Deletes all tests in the suite. void TestSuite::deleteContents() { for (std::vector::iterator it = _tests.begin(); it != _tests.end(); ++it) delete *it; } // Runs the tests and collects their result in a TestResult. void TestSuite::run(TestResult *result) { for (std::vector::iterator it = _tests.begin(); it != _tests.end(); ++it) { if (result->shouldStop ()) break; Test *test = *it; test->run(result); } } // Counts the number of test cases that will be run by this test. int TestSuite::countTestCases() { int count = 0; for (std::vector::iterator it = _tests.begin (); it != _tests.end (); ++it) count += (*it)->countTestCases(); return count; } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/src/TextTestResult.cpp0000644000076500001200000001000611313735443022107 0ustar guenteradmin00000000000000// // TextTestResult.cpp // // $Id: //poco/1.3/CppUnit/src/TextTestResult.cpp#2 $ // #include "CppUnit/TextTestResult.h" #include "CppUnit/CppUnitException.h" #include "CppUnit/Test.h" #include "CppUnit/estring.h" #include #include namespace CppUnit { TextTestResult::TextTestResult(): _ostr(std::cout) { } TextTestResult::TextTestResult(std::ostream& ostr): _ostr(ostr) { } void TextTestResult::addError(Test* test, CppUnitException* e) { TestResult::addError(test, e); _ostr << "ERROR" << std::flush; } void TextTestResult::addFailure(Test* test, CppUnitException* e) { TestResult::addFailure(test, e); _ostr << "FAILURE" << std::flush; } void TextTestResult::startTest(Test* test) { TestResult::startTest(test); _ostr << "\n" << shortName(test->toString()) << ": "; } void TextTestResult::printErrors(std::ostream& stream) { if (testErrors() != 0) { stream << "\n"; if (testErrors() == 1) stream << "There was " << testErrors() << " error: " << std::endl; else stream << "There were " << testErrors() << " errors: " << std::endl; int i = 1; for (std::vector::iterator it = errors().begin(); it != errors().end(); ++it) { TestFailure* failure = *it; CppUnitException* e = failure->thrownException(); stream << std::setw(2) << i << ": " << failure->failedTest()->toString() << "\n" << " \"" << (e ? e->what() : "") << "\"\n" << " in \"" << (e ? e->fileName() : std::string()) << "\", line "; if (e == 0) { stream << "0"; } else { stream << e->lineNumber(); if (e->data2LineNumber() != CppUnitException::CPPUNIT_UNKNOWNLINENUMBER) { stream << " data lines " << e->data1LineNumber() << ", " << e->data2LineNumber(); } else if (e->data1LineNumber() != CppUnitException::CPPUNIT_UNKNOWNLINENUMBER) { stream << " data line " << e->data1LineNumber(); } } stream << "\n"; i++; } } } void TextTestResult::printFailures(std::ostream& stream) { if (testFailures() != 0) { stream << "\n"; if (testFailures() == 1) stream << "There was " << testFailures() << " failure: " << std::endl; else stream << "There were " << testFailures() << " failures: " << std::endl; int i = 1; for (std::vector::iterator it = failures().begin(); it != failures().end(); ++it) { TestFailure* failure = *it; CppUnitException* e = failure->thrownException(); stream << std::setw(2) << i << ": " << failure->failedTest()->toString() << "\n" << " \"" << (e ? e->what() : "") << "\"\n" << " in \"" << (e ? e->fileName() : std::string()) << "\", line "; if (e == 0) { stream << "0"; } else { stream << e->lineNumber(); if (e->data2LineNumber() != CppUnitException::CPPUNIT_UNKNOWNLINENUMBER) { stream << " data lines " << e->data1LineNumber() << ", " << e->data2LineNumber(); } else if (e->data1LineNumber() != CppUnitException::CPPUNIT_UNKNOWNLINENUMBER) { stream << " data line " << e->data1LineNumber(); } } stream << "\n"; i++; } } } void TextTestResult::print(std::ostream& stream) { printHeader(stream); printErrors(stream); printFailures(stream); } void TextTestResult::printHeader(std::ostream& stream) { stream << "\n\n"; if (wasSuccessful()) stream << "OK (" << runTests() << " tests)" << std::endl; else stream << "!!!FAILURES!!!" << std::endl << "Runs: " << runTests () << " Failures: " << testFailures () << " Errors: " << testErrors () << std::endl; } std::string TextTestResult::shortName(const std::string& testName) { std::string::size_type pos = testName.rfind('.'); if (pos != std::string::npos) return std::string(testName, pos + 1); else return testName; } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/WinTestRunner/0000755000076500001200000000000011313735443020423 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/WinTestRunner/include/0000755000076500001200000000000011313735443022046 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/WinTestRunner/include/WinTestRunner/0000755000076500001200000000000011313735443024635 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/WinTestRunner/include/WinTestRunner/WinTestRunner.h0000644000076500001200000000276111313735443027603 0ustar guenteradmin00000000000000// // WinTestRunner.h // // $Id: //poco/1.3/CppUnit/WinTestRunner/include/WinTestRunner/WinTestRunner.h#3 $ // // Application shell for CppUnit's TestRunner dialog. // #ifndef WinTestRunner_H_INCLUDED #define WinTestRunner_H_INCLUDED #if !defined(POCO_STATIC) #if defined(WinTestRunner_EXPORTS) #define WinTestRunner_API __declspec(dllexport) #else #define WinTestRunner_API __declspec(dllimport) #endif #else #define WinTestRunner_API #endif #include "CppUnit/CppUnit.h" #include #include namespace CppUnit { class Test; class WinTestRunner_API WinTestRunner { public: WinTestRunner(); ~WinTestRunner(); void run(); void addTest(Test* pTest); private: std::vector _tests; }; class WinTestRunner_API WinTestRunnerApp: public CWinApp /// A simple application class that hosts the TestRunner dialog. /// Create a subclass and override the TestMain() method. /// /// WinTestRunnerApp supports a batch mode, which runs the /// test using the standard text-based TestRunner from CppUnit. /// To enable batch mode, start the application with the "/b" /// or "/B" argument. Optionally, a filename may be specified /// where the test output will be written to: "/b:" or /// "/B:". /// /// When run in batch mode, the exit code of the application /// will denote test success (0) or failure (1). { public: virtual BOOL InitInstance(); virtual void TestMain() = 0; DECLARE_MESSAGE_MAP() }; } // namespace CppUnit #endif // WinTestRunner_H_INCLUDED poco-1.3.6p1-all/CppUnit/WinTestRunner/res/0000755000076500001200000000000011313735443021214 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/WinTestRunner/res/Resource.h0000644000076500001200000000164411313735443023161 0ustar guenteradmin00000000000000//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by TestRunner.rc // #define IDD_DIALOG_TESTRUNNER 129 #define IDC_LIST 1000 #define ID_RUN 1001 #define ID_STOP 1002 #define IDC_PROGRESS 1003 #define IDC_INDICATOR 1004 #define IDC_COMBO_TEST 1005 #define IDC_STATIC_RUNS 1007 #define IDC_STATIC_ERRORS 1008 #define IDC_STATIC_FAILURES 1009 #define IDC_EDIT_TIME 1010 #define IDC_CHK_AUTORUN 1013 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 131 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1014 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif poco-1.3.6p1-all/CppUnit/WinTestRunner/res/WinTestRunner.rc0000644000076500001200000001135511313735443024336 0ustar guenteradmin00000000000000// Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "#define _AFX_NO_SPLITTER_RESOURCES\r\n" "#define _AFX_NO_OLE_RESOURCES\r\n" "#define _AFX_NO_TRACKER_RESOURCES\r\n" "#define _AFX_NO_PROPERTY_RESOURCES\r\n" "\r\n" "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" "#ifdef _WIN32\r\n" "LANGUAGE 9, 1\r\n" "#pragma code_page(1252)\r\n" "#endif\r\n" "#include ""..\\res\\WinTestRunner.rc2"" // non-Microsoft Visual C++ edited resources\r\n" "#include ""afxres.rc"" // Standard components\r\n" "#endif\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 1,0,0,1 PRODUCTVERSION 1,0,0,1 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "FileDescription", "CppUnit WinTestRunner DLL" VALUE "FileVersion", "1, 0, 0, 1" VALUE "InternalName", "WinTestRunner" VALUE "LegalCopyright", "Copyright (c) 2005" VALUE "OriginalFilename", "TestRunner.dll" VALUE "ProductName", "CppUnit WinTestRunner Dynamic Link Library" VALUE "ProductVersion", "1, 0, 0, 1" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_DIALOG_TESTRUNNER DIALOGEX 0, 0, 512, 300 STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "CppUnit WinTestRunner" FONT 8, "MS Sans Serif", 0, 0, 0x0 BEGIN COMBOBOX IDC_COMBO_TEST,7,20,424,273,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP DEFPUSHBUTTON "Run",ID_RUN,455,7,50,14 DEFPUSHBUTTON "Stop",ID_STOP,455,24,50,14 CONTROL "List1",IDC_LIST,"SysListView32",LVS_REPORT | WS_BORDER | WS_TABSTOP,7,110,498,160 PUSHBUTTON "Close",IDOK,455,279,50,14 LTEXT "Test Name:",IDC_STATIC,7,9,179,9 LTEXT "Progress:",IDC_STATIC,7,55,49,9 LTEXT "Errors and Failures:",IDC_STATIC,7,99,67,9 LTEXT "Runs:",IDC_STATIC,457,54,26,10 LTEXT "Failures:",IDC_STATIC,457,80,26,10 LTEXT "Errors:",IDC_STATIC,457,67,26,10 RTEXT "0",IDC_STATIC_RUNS,487,54,16,10 RTEXT "0",IDC_STATIC_ERRORS,487,67,16,10 RTEXT "0",IDC_STATIC_FAILURES,487,80,16,10 EDITTEXT IDC_EDIT_TIME,7,281,440,12,ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER LTEXT "",IDC_PROGRESS,7,67,424,20,SS_SUNKEN | NOT WS_VISIBLE CONTROL "Auto Run",IDC_CHK_AUTORUN,"Button",BS_AUTOCHECKBOX | BS_LEFTTEXT | WS_TABSTOP,383,38,46,10 END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO BEGIN IDD_DIALOG_TESTRUNNER, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 505 TOPMARGIN, 7 BOTTOMMARGIN, 293 END END #endif // APSTUDIO_INVOKED #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // #define _AFX_NO_SPLITTER_RESOURCES #define _AFX_NO_OLE_RESOURCES #define _AFX_NO_TRACKER_RESOURCES #define _AFX_NO_PROPERTY_RESOURCES #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE 9, 1 #pragma code_page(1252) #endif #include "afxres.rc" // Standard components #endif ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED poco-1.3.6p1-all/CppUnit/WinTestRunner/src/0000755000076500001200000000000011313735443021212 5ustar guenteradmin00000000000000poco-1.3.6p1-all/CppUnit/WinTestRunner/src/ActiveTest.cpp0000644000076500001200000000154411313735443023775 0ustar guenteradmin00000000000000// // ActiveTest.cpp // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/ActiveTest.cpp#1 $ // #include #include "ActiveTest.h" namespace CppUnit { // Spawn a thread to a test void ActiveTest::run(TestResult* result) { CWinThread* thread; setTestResult(result); _runCompleted.ResetEvent(); thread = AfxBeginThread(threadFunction, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); DuplicateHandle(GetCurrentProcess(), thread->m_hThread, GetCurrentProcess(), &_threadHandle, 0, FALSE, DUPLICATE_SAME_ACCESS); thread->ResumeThread(); } // Simple execution thread. Assuming that an ActiveTest instance // only creates one of these at a time. UINT ActiveTest::threadFunction(LPVOID thisInstance) { ActiveTest* test = (ActiveTest*) thisInstance; test->run(); test->_runCompleted.SetEvent(); return 0; } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/WinTestRunner/src/ActiveTest.h0000644000076500001200000000307311313735443023441 0ustar guenteradmin00000000000000// // ActiveTest.h // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/ActiveTest.h#1 $ // #ifndef ActiveTest_INCLUDED #define ActiveTest_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/TestDecorator.h" #include namespace CppUnit { /* A Microsoft-specific active test * * An active test manages its own * thread of execution. This one * is very simple and only sufficient * for the limited use we put it through * in the TestRunner. It spawns a thread * on run (TestResult *) and signals * completion of the test. * * We assume that only one thread * will be active at once for each * instance. * */ class ActiveTest: public TestDecorator { public: ActiveTest(Test* test); ~ActiveTest(); void run(TestResult* result); protected: HANDLE _threadHandle; CEvent _runCompleted; TestResult* _currentTestResult; void run (); void setTestResult(TestResult* result); static UINT threadFunction(LPVOID thisInstance); }; // Construct the active test inline ActiveTest::ActiveTest(Test *test): TestDecorator(test) { _currentTestResult = NULL; _threadHandle = INVALID_HANDLE_VALUE; } // Pend until the test has completed inline ActiveTest::~ActiveTest() { CSingleLock(&_runCompleted, TRUE); CloseHandle(_threadHandle); } // Set the test result that we are to run inline void ActiveTest::setTestResult(TestResult* result) { _currentTestResult = result; } // Run our test result inline void ActiveTest::run() { TestDecorator::run(_currentTestResult); } } // namespace CppUnit #endif // ActiveTest_INCLUDED poco-1.3.6p1-all/CppUnit/WinTestRunner/src/DLLMain.cpp0000644000076500001200000000304611313735443023141 0ustar guenteradmin00000000000000// // DLLMain.cpp // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/DLLMain.cpp#1 $ // #include #include static AFX_EXTENSION_MODULE TestRunnerDLL = { NULL, NULL }; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { // Remove this if you use lpReserved UNREFERENCED_PARAMETER(lpReserved); if (dwReason == DLL_PROCESS_ATTACH) { TRACE0("WinTestRunner.DLL Initializing\n"); // Extension DLL one-time initialization if (!AfxInitExtensionModule(TestRunnerDLL, hInstance)) return 0; // Insert this DLL into the resource chain // NOTE: If this Extension DLL is being implicitly linked to by // an MFC Regular DLL (such as an ActiveX Control) // instead of an MFC application, then you will want to // remove this line from DllMain and put it in a separate // function exported from this Extension DLL. The Regular DLL // that uses this Extension DLL should then explicitly call that // function to initialize this Extension DLL. Otherwise, // the CDynLinkLibrary object will not be attached to the // Regular DLL's resource chain, and serious problems will // result. new CDynLinkLibrary(TestRunnerDLL); } else if (dwReason == DLL_PROCESS_DETACH) { TRACE0("WinTestRunner.DLL Terminating\n"); // Terminate the library before destructors are called AfxTermExtensionModule(TestRunnerDLL); } return 1; // ok } poco-1.3.6p1-all/CppUnit/WinTestRunner/src/GUITestResult.cpp0000644000076500001200000000153711313735443024407 0ustar guenteradmin00000000000000// // GUITestResult.cpp // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/GUITestResult.cpp#2 $ // #include "TestRunnerDlg.h" #include "GUITestResult.h" namespace CppUnit { void GUITestResult::addError(Test *test, CppUnitException *e) { ExclusiveZone zone(_syncObject); TestResult::addError(test, e); _runner->addError(this, test, e); } void GUITestResult::addFailure(Test *test, CppUnitException *e) { ExclusiveZone zone(_syncObject); TestResult::addFailure(test, e); _runner->addFailure(this, test, e); } void GUITestResult::startTest(Test *test) { ExclusiveZone zone(_syncObject); TestResult::startTest(test); _runner->startTest(test); } void GUITestResult::endTest(Test *test) { ExclusiveZone zone(_syncObject); TestResult::endTest(test); _runner->endTest(this, test); } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/WinTestRunner/src/GUITestResult.h0000644000076500001200000000240111313735443024043 0ustar guenteradmin00000000000000// // GUITestResult.h // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/GUITestResult.h#2 $ // #ifndef GuiTestResult_INCLUDED #define GuiTestResult_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/TestResult.h" #include namespace CppUnit { class TestRunnerDlg; class GUITestResult: public TestResult { public: GUITestResult(TestRunnerDlg* runner); ~GUITestResult(); void addError(Test* test, CppUnitException* e); void addFailure(Test* test, CppUnitException* e); void startTest(Test* test); void endTest(Test* test); void stop(); protected: class LightweightSynchronizationObject: public TestResult::SynchronizationObject { public: void lock() { _syncObject.Lock(); } void unlock() { _syncObject.Unlock(); } private: CCriticalSection _syncObject; }; private: TestRunnerDlg *_runner; }; // Construct with lightweight synchronization inline GUITestResult::GUITestResult(TestRunnerDlg* runner): _runner(runner) { setSynchronizationObject(new LightweightSynchronizationObject()); } // Destructor inline GUITestResult::~GUITestResult() { } // Override without protection to prevent deadlock inline void GUITestResult::stop() { _stop = true; } } // namespace CppUnit #endif // GuiTestResult_INCLUDED poco-1.3.6p1-all/CppUnit/WinTestRunner/src/ProgressBar.cpp0000644000076500001200000000554411313735443024157 0ustar guenteradmin00000000000000// // ProgressBar.cpp // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/ProgressBar.cpp#1 $ // #include "ProgressBar.h" namespace CppUnit { // Paint the progress bar in response to a paint message void ProgressBar::paint(CDC& dc) { paintBackground (dc); paintStatus (dc); } // Paint the background of the progress bar region void ProgressBar::paintBackground (CDC& dc) { CBrush brshBackground; CPen penGray (PS_SOLID, 1, RGB (128, 128, 128)); CPen penWhite (PS_SOLID, 1, RGB (255, 255, 255)); VERIFY (brshBackground.CreateSolidBrush (::GetSysColor (COLOR_BTNFACE))); dc.FillRect (_bounds, &brshBackground); CPen *pOldPen; pOldPen = dc.SelectObject (&penGray); { dc.MoveTo (_bounds.left, _bounds.top); dc.LineTo (_bounds.left + _bounds.Width () -1, _bounds.top); dc.MoveTo (_bounds.left, _bounds.top); dc.LineTo (_bounds.left, _bounds.top + _bounds.Height () -1); } dc.SelectObject (&penWhite); { dc.MoveTo (_bounds.left + _bounds.Width () -1, _bounds.top); dc.LineTo (_bounds.left + _bounds.Width () -1, _bounds.top + _bounds.Height () -1); dc.MoveTo (_bounds.left, _bounds.top + _bounds.Height () -1); dc.LineTo (_bounds.left + _bounds.Width () -1, _bounds.top + _bounds.Height () -1); } dc.SelectObject (pOldPen); } // Paint the actual status of the progress bar void ProgressBar::paintStatus (CDC& dc) { if (_progress <= 0) return; CBrush brshStatus; CRect rect (_bounds.left, _bounds.top, _bounds.left + _progressX, _bounds.bottom); COLORREF statusColor = getStatusColor (); VERIFY (brshStatus.CreateSolidBrush (statusColor)); rect.DeflateRect (1, 1); dc.FillRect (rect, &brshStatus); } // Paint the current step void ProgressBar::paintStep (int startX, int endX) { // kludge: painting the whole region on each step _baseWindow->RedrawWindow (_bounds); _baseWindow->UpdateWindow (); } // Setup the progress bar for execution over a total number of steps void ProgressBar::start (int total) { _total = total; reset (); } // Take one step, indicating whether it was a successful step void ProgressBar::step (bool successful) { _progress++; int x = _progressX; _progressX = scale (_progress); if (!_error && !successful) { _error = true; x = 1; } paintStep (x, _progressX); } // Map from steps to display units int ProgressBar::scale (int value) { if (_total > 0) return max (1, value * (_bounds.Width () - 1) / _total); return value; } // Reset the progress bar void ProgressBar::reset () { _progressX = 1; _progress = 0; _error = false; _baseWindow->RedrawWindow (_bounds); _baseWindow->UpdateWindow (); } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/WinTestRunner/src/ProgressBar.h0000644000076500001200000000240111313735443023611 0ustar guenteradmin00000000000000// // ProgressBar.h // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/ProgressBar.h#1 $ // #ifndef ProgressBar_INCLUDED #define ProgressBar_INCLUDED #include "CppUnit/CppUnit.h" #include namespace CppUnit { /* A Simple ProgressBar for test execution display */ class ProgressBar { public: ProgressBar(CWnd* baseWindow, CRect& bounds); void step(bool successful); void paint(CDC& dc); int scale(int value); void reset(); void start(int total); protected: void paintBackground(CDC& dc); void paintStatus(CDC& dc); COLORREF getStatusColor(); void paintStep(int startX, int endX); CWnd* _baseWindow; CRect _bounds; bool _error; int _total; int _progress; int _progressX; }; // Construct a ProgressBar inline ProgressBar::ProgressBar(CWnd* baseWindow, CRect& bounds): _baseWindow(baseWindow), _bounds(bounds), _error(false), _total(0), _progress(0), _progressX(0) { WINDOWINFO wi; wi.cbSize = sizeof(WINDOWINFO); baseWindow->GetWindowInfo(&wi); _bounds.OffsetRect(-wi.rcClient.left, -wi.rcClient.top); } // Get the current color inline COLORREF ProgressBar::getStatusColor() { return _error ? RGB(255, 0, 0) : RGB(0, 255, 0); } } // namespace CppUnit #endif // ProgressBar_INCLUDED poco-1.3.6p1-all/CppUnit/WinTestRunner/src/SynchronizedTestResult.h0000644000076500001200000000624511313735443026110 0ustar guenteradmin00000000000000#ifndef SYNCHRONIZEDTESTRESULTDECORATOR_H #define SYNCHRONIZEDTESTRESULTDECORATOR_H #include #include "TestResultDecorator.h" class SynchronizedTestResult : public TestResultDecorator { public: SynchronizedTestResult (TestResult *result); ~SynchronizedTestResult (); bool shouldStop (); void addError (Test *test, CppUnitException *e); void addFailure (Test *test, CppUnitException *e); void startTest (Test *test); void endTest (Test *test); int runTests (); int testErrors (); int testFailures (); bool wasSuccessful (); void stop (); vector& errors (); vector& failures (); private: CCriticalSection m_criticalSection; }; // Constructor inline SynchronizedTestResult::SynchronizedTestResult (TestResult *result) : TestResultDecorator (result) {} // Destructor inline SynchronizedTestResult::~SynchronizedTestResult () {} // Returns whether the test should stop inline bool SynchronizedTestResult::shouldStop () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->shouldStop (); } // Adds an error to the list of errors. The passed in exception // caused the error inline void SynchronizedTestResult::addError (Test *test, CppUnitException *e) { CSingleLock sync (&m_criticalSection, TRUE); m_result->addError (test, e); } // Adds a failure to the list of failures. The passed in exception // caused the failure. inline void SynchronizedTestResult::addFailure (Test *test, CppUnitException *e) { CSingleLock sync (&m_criticalSection, TRUE); m_result->addFailure (test, e); } // Informs the result that a test will be started. inline void SynchronizedTestResult::startTest (Test *test) { CSingleLock sync (&m_criticalSection, TRUE); m_result->startTest (test); } // Informs the result that a test was completed. inline void SynchronizedTestResult::endTest (Test *test) { CSingleLock sync (&m_criticalSection, TRUE); m_result->endTest (test); } // Gets the number of run tests. inline int SynchronizedTestResult::runTests () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->runTests (); } // Gets the number of detected errors. inline int SynchronizedTestResult::testErrors () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->testErrors (); } // Gets the number of detected failures. inline int SynchronizedTestResult::testFailures () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->testFailures (); } // Returns whether the entire test was successful or not. inline bool SynchronizedTestResult::wasSuccessful () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->wasSuccessful (); } // Marks that the test run should stop. inline void SynchronizedTestResult::stop () { CSingleLock sync (&m_criticalSection, TRUE); m_result->stop (); } // Returns a vector of the errors. inline vector& SynchronizedTestResult::errors () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->errors (); } // Returns a vector of the failures. inline vector& SynchronizedTestResult::failures () { CSingleLock sync (&m_criticalSection, TRUE); return m_result->failures (); } #endif poco-1.3.6p1-all/CppUnit/WinTestRunner/src/TestResultDecorator.h0000644000076500001200000000504011313735443025343 0ustar guenteradmin00000000000000#ifndef CPP_UNIT_TESTRESULTDECORATOR_H #define CPP_UNIT_TESTRESULTDECORATOR_H #include "TestResult.h" class TestResultDecorator { public: TestResultDecorator (TestResult *result); virtual ~TestResultDecorator (); virtual bool shouldStop (); virtual void addError (Test *test, CppUnitException *e); virtual void addFailure (Test *test, CppUnitException *e); virtual void startTest (Test *test); virtual void endTest (Test *test); virtual int runTests (); virtual int testErrors (); virtual int testFailures (); virtual bool wasSuccessful (); virtual void stop (); vector& errors (); vector& failures (); protected: TestResult *m_result; }; inline TestResultDecorator::TestResultDecorator (TestResult *result) : m_result (result) {} inline TestResultDecorator::~TestResultDecorator () {} // Returns whether the test should stop inline bool TestResultDecorator::shouldStop () { return m_result->shouldStop (); } // Adds an error to the list of errors. The passed in exception // caused the error inline void TestResultDecorator::addError (Test *test, CppUnitException *e) { m_result->addError (test, e); } // Adds a failure to the list of failures. The passed in exception // caused the failure. inline void TestResultDecorator::addFailure (Test *test, CppUnitException *e) { m_result->addFailure (test, e); } // Informs the result that a test will be started. inline void TestResultDecorator::startTest (Test *test) { m_result->startTest (test); } // Informs the result that a test was completed. inline void TestResultDecorator::endTest (Test *test) { m_result->endTest (test); } // Gets the number of run tests. inline int TestResultDecorator::runTests () { return m_result->runTests (); } // Gets the number of detected errors. inline int TestResultDecorator::testErrors () { return m_result->testErrors (); } // Gets the number of detected failures. inline int TestResultDecorator::testFailures () { return m_result->testFailures (); } // Returns whether the entire test was successful or not. inline bool TestResultDecorator::wasSuccessful () { return m_result->wasSuccessful (); } // Marks that the test run should stop. inline void TestResultDecorator::stop () { m_result->stop (); } // Returns a vector of the errors. inline vector& TestResultDecorator::errors () { return m_result->errors (); } // Returns a vector of the failures. inline vector& TestResultDecorator::failures () { return m_result->failures (); } #endif poco-1.3.6p1-all/CppUnit/WinTestRunner/src/TestRunnerDlg.cpp0000644000076500001200000002312211313735443024456 0ustar guenteradmin00000000000000// // TestRunnerDlg.cpp // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/TestRunnerDlg.cpp#2 $ // #include #include #include #include #include "TestRunnerDlg.h" #include "ActiveTest.h" #include "GUITestResult.h" #include "ProgressBar.h" #include "CppUnit/TestSuite.h" #include "TestRunnerDlg.h" namespace CppUnit { TestRunnerDlg::TestRunnerDlg(CWnd* pParent): CDialog(TestRunnerDlg::IDD, pParent) { //{{AFX_DATA_INIT(TestRunnerDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT _testsProgress = 0; _selectedTest = 0; _currentTest = 0; } void TestRunnerDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(TestRunnerDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(TestRunnerDlg, CDialog) //{{AFX_MSG_MAP(TestRunnerDlg) ON_BN_CLICKED(ID_RUN, OnRun) ON_BN_CLICKED(ID_STOP, OnStop) ON_CBN_SELCHANGE(IDC_COMBO_TEST, OnSelchangeComboTest) ON_BN_CLICKED(IDC_CHK_AUTORUN, OnBnClickedAutorun) ON_WM_PAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL TestRunnerDlg::OnInitDialog() { CDialog::OnInitDialog(); CListCtrl *listCtrl = (CListCtrl *)GetDlgItem (IDC_LIST); CComboBox *comboBox = (CComboBox *)GetDlgItem (IDC_COMBO_TEST); ASSERT (listCtrl); ASSERT (comboBox); CString title; GetWindowText(title); #if defined(_DEBUG) title.Append(" [debug]"); #else title.Append(" [release]"); #endif SetWindowText(title); listCtrl->InsertColumn (0,"Type", LVCFMT_LEFT, 16 + listCtrl->GetStringWidth ("Type"), 1); listCtrl->InsertColumn (1,"Name", LVCFMT_LEFT, 16 * listCtrl->GetStringWidth ("X"), 2); listCtrl->InsertColumn (2,"Failed Condition", LVCFMT_LEFT, 24 * listCtrl->GetStringWidth ("M"), 3); listCtrl->InsertColumn (3,"Line", LVCFMT_LEFT, 16 + listCtrl->GetStringWidth ("0000"), 4); listCtrl->InsertColumn (4,"File Name", LVCFMT_LEFT, 36 * listCtrl->GetStringWidth ("M"), 5); int numberOfCases = 0; CWinApp* pApp = AfxGetApp(); CString lastTestCS = pApp->GetProfileString("Tests", "lastTest"); std::string lastTest((LPCSTR) lastTestCS); int sel = -1; for (std::vector::iterator it = _tests.begin (); it != _tests.end (); ++it) { std::string cbName(it->level*4, ' '); cbName.append(it->pTest->toString()); comboBox->AddString (cbName.c_str ()); if (sel < 0) { if (lastTest.empty() || lastTest == it->pTest->toString()) { _selectedTest = it->pTest; sel = numberOfCases; } } numberOfCases++; } if (numberOfCases > 0) { if (sel < 0) { _selectedTest = _tests[0].pTest; sel = 0; } comboBox->SetCurSel (sel); } else { beRunDisabled (); } CWnd *pProgress = GetDlgItem(IDC_PROGRESS); CRect rect; pProgress->GetWindowRect(&rect); _testsProgress = new ProgressBar (this, rect); CButton* autoRunBtn = (CButton*) GetDlgItem(IDC_CHK_AUTORUN); autoRunBtn->SetCheck(pApp->GetProfileInt("Tests", "autoRun", BST_UNCHECKED)); reset (); if (autoRunBtn->GetCheck() == BST_CHECKED) { OnRun(); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } TestRunnerDlg::~TestRunnerDlg () { freeState (); delete _testsProgress; } void TestRunnerDlg::OnRun() { if (_selectedTest == 0) return; freeState (); reset (); beRunning (); int numberOfTests = _selectedTest->countTestCases (); _testsProgress->start (numberOfTests); _result = new GUITestResult ((TestRunnerDlg *)this); _activeTest = new ActiveTest (_selectedTest); _testStartTime = timeGetTime (); _activeTest->run (_result); _testEndTime = timeGetTime (); } void TestRunnerDlg::addListEntry(const std::string& type, TestResult *result, Test *test, CppUnitException *e) { char stage [80]; LV_ITEM lvi; CListCtrl *listCtrl = (CListCtrl *)GetDlgItem (IDC_LIST); int currentEntry = result->testErrors () + result->testFailures () -1; sprintf (stage, "%s", type.c_str ()); lvi.mask = LVIF_TEXT; lvi.iItem = currentEntry; lvi.iSubItem = 0; lvi.pszText = stage; lvi.iImage = 0; lvi.stateMask = 0; lvi.state = 0; listCtrl->InsertItem (&lvi); // Set class string listCtrl->SetItemText (currentEntry, 1, test->toString ().c_str ()); // Set the asserted text listCtrl->SetItemText(currentEntry, 2, e->what ()); // Set the line number if (e->lineNumber () == CppUnitException::CPPUNIT_UNKNOWNLINENUMBER) sprintf (stage, ""); else sprintf (stage, "%ld", e->lineNumber ()); listCtrl->SetItemText(currentEntry, 3, stage); // Set the file name listCtrl->SetItemText(currentEntry, 4, e->fileName ().c_str ()); listCtrl->RedrawItems (currentEntry, currentEntry); listCtrl->UpdateWindow (); } void TestRunnerDlg::addError (TestResult *result, Test *test, CppUnitException *e) { addListEntry ("Error", result, test, e); _errors++; _currentTest = 0; updateCountsDisplay (); } void TestRunnerDlg::addFailure (TestResult *result, Test *test, CppUnitException *e) { addListEntry ("Failure", result, test, e); _failures++; _currentTest = 0; updateCountsDisplay (); } void TestRunnerDlg::startTest(Test* test) { _currentTest = test; updateCountsDisplay(); } void TestRunnerDlg::endTest (TestResult *result, Test *test) { if (_selectedTest == 0) return; _currentTest = 0; _testsRun++; updateCountsDisplay (); _testsProgress->step (_failures == 0 && _errors == 0); _testEndTime = timeGetTime (); updateCountsDisplay (); if (_testsRun >= _selectedTest->countTestCases ()) beIdle (); } void TestRunnerDlg::beRunning () { CButton *runButton = (CButton *)GetDlgItem (ID_RUN); CButton *closeButton = (CButton *)GetDlgItem (IDOK); runButton->EnableWindow (FALSE); closeButton->EnableWindow (FALSE); } void TestRunnerDlg::beIdle () { CButton *runButton = (CButton *)GetDlgItem (ID_RUN); CButton *closeButton = (CButton *)GetDlgItem (IDOK); runButton->EnableWindow (TRUE); closeButton->EnableWindow (TRUE); } void TestRunnerDlg::beRunDisabled () { CButton *runButton = (CButton *)GetDlgItem (ID_RUN); CButton *closeButton = (CButton *)GetDlgItem (IDOK); CButton *stopButton = (CButton *)GetDlgItem (ID_STOP); runButton->EnableWindow (FALSE); stopButton->EnableWindow (FALSE); closeButton->EnableWindow (TRUE); } void TestRunnerDlg::freeState () { delete _activeTest; delete _result; } void TestRunnerDlg::reset () { _testsRun = 0; _errors = 0; _failures = 0; _testEndTime = _testStartTime; updateCountsDisplay (); _activeTest = 0; _result = 0; CListCtrl *listCtrl = (CListCtrl *)GetDlgItem (IDC_LIST); listCtrl->DeleteAllItems (); _testsProgress->reset (); } void TestRunnerDlg::updateCountsDisplay () { CStatic *statTestsRun = (CStatic *)GetDlgItem (IDC_STATIC_RUNS); CStatic *statErrors = (CStatic *)GetDlgItem (IDC_STATIC_ERRORS); CStatic *statFailures = (CStatic *)GetDlgItem (IDC_STATIC_FAILURES); CEdit *editTime = (CEdit *)GetDlgItem (IDC_EDIT_TIME); CString argumentString; argumentString.Format ("%d", _testsRun); statTestsRun ->SetWindowText (argumentString); argumentString.Format ("%d", _errors); statErrors ->SetWindowText (argumentString); argumentString.Format ("%d", _failures); statFailures ->SetWindowText (argumentString); if (_currentTest) argumentString.Format ("Execution Time: %3.3lf seconds, Current Test: %s", (_testEndTime - _testStartTime) / 1000.0, _currentTest->toString().c_str()); else argumentString.Format ("Execution Time: %3.3lf seconds", (_testEndTime - _testStartTime) / 1000.0); editTime ->SetWindowText (argumentString); } void TestRunnerDlg::OnStop() { if (_result) _result->stop (); beIdle (); } void TestRunnerDlg::OnOK() { if (_result) _result->stop (); CDialog::OnOK (); } void TestRunnerDlg::OnSelchangeComboTest() { CComboBox *testsSelection = (CComboBox *)GetDlgItem (IDC_COMBO_TEST); int currentSelection = testsSelection->GetCurSel (); if (currentSelection >= 0 && currentSelection < _tests.size ()) { _selectedTest = (_tests.begin () + currentSelection)->pTest; beIdle (); CWinApp* pApp = AfxGetApp(); pApp->WriteProfileString("Tests", "lastTest", _selectedTest->toString().c_str()); } else { _selectedTest = 0; beRunDisabled (); } freeState (); reset (); } void TestRunnerDlg::OnBnClickedAutorun() { CButton *autoRunBtn = (CButton *)GetDlgItem (IDC_CHK_AUTORUN); CWinApp* pApp = AfxGetApp(); pApp->WriteProfileInt("Tests", "autoRun", autoRunBtn->GetCheck()); } void TestRunnerDlg::OnPaint() { CPaintDC dc (this); _testsProgress->paint (dc); } void TestRunnerDlg::setTests(const std::vector& tests) { _tests.clear(); for (std::vector::const_iterator it = tests.begin(); it != tests.end(); ++it) { addTest(*it, 0); } } void TestRunnerDlg::addTest(Test* pTest, int level) { TestInfo ti; ti.pTest = pTest; ti.level = level; _tests.push_back(ti); TestSuite* pSuite = dynamic_cast(pTest); if (pSuite) { const std::vector& tests = pSuite->tests(); for (std::vector::const_iterator it = tests.begin(); it != tests.end(); ++it) { addTest(*it, level + 1); } } } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/WinTestRunner/src/TestRunnerDlg.h0000644000076500001200000000400711313735443024124 0ustar guenteradmin00000000000000// // TestRunnerDlg.h // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/TestRunnerDlg.h#2 $ // #ifndef TestRunnerDlg_INCLUDED #define TestRunnerDlg_INCLUDED #include "CppUnit/CppUnit.h" #include "CppUnit/CppUnitException.h" #include "ActiveTest.h" #include #include "../res/Resource.h" #include #include "afxwin.h" namespace CppUnit { class ProgressBar; class TestRunnerDlg: public CDialog { public: TestRunnerDlg(CWnd* pParent = NULL); ~TestRunnerDlg(); void setTests(const std::vector& tests); void addError(TestResult* result, Test* test, CppUnitException* e); void addFailure(TestResult* result, Test* test, CppUnitException* e); void startTest(Test* test); void endTest(TestResult* result, Test* test); //{{AFX_DATA(TestRunnerDlg) enum { IDD = IDD_DIALOG_TESTRUNNER }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA //{{AFX_VIRTUAL(TestRunnerDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL protected: //{{AFX_MSG(TestRunnerDlg) virtual BOOL OnInitDialog(); afx_msg void OnRun(); afx_msg void OnStop(); virtual void OnOK(); afx_msg void OnSelchangeComboTest(); afx_msg void OnBnClickedAutorun(); afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() void addListEntry(const std::string& type, TestResult* result, Test* test, CppUnitException* e); void beIdle(); void beRunning(); void beRunDisabled(); void reset(); void freeState(); void updateCountsDisplay(); void addTest(Test* pTest, int level); struct TestInfo { Test* pTest; int level; }; std::vector _tests; ProgressBar* _testsProgress; Test* _selectedTest; ActiveTest* _activeTest; TestResult* _result; int _testsRun; int _errors; int _failures; DWORD _testStartTime; DWORD _testEndTime; Test* _currentTest; }; } // namespace CppUnit #endif // TestRunnerDlg_INCLUDED poco-1.3.6p1-all/CppUnit/WinTestRunner/src/WinTestRunner.cpp0000644000076500001200000000351011313735443024504 0ustar guenteradmin00000000000000// // WinTestRunner.cpp // // $Id: //poco/1.3/CppUnit/WinTestRunner/src/WinTestRunner.cpp#2 $ // #include "WinTestRunner/WinTestRunner.h" #include "TestRunnerDlg.h" #include "CppUnit/TestRunner.h" #include namespace CppUnit { WinTestRunner::WinTestRunner() { } WinTestRunner::~WinTestRunner() { for (std::vector::iterator it = _tests.begin(); it != _tests.end(); ++it) delete *it; } void WinTestRunner::run() { // Note: The following code is some evil hack to // add batch capability to the MFC based WinTestRunner. std::string cmdLine(AfxGetApp()->m_lpCmdLine); if (cmdLine.size() >= 2 && cmdLine[0] == '/' && (cmdLine[1] == 'b' || cmdLine[1] == 'B')) { // We're running in batch mode. std::string outPath; if (cmdLine.size() > 4 && cmdLine[2] == ':') outPath = cmdLine.substr(3); else outPath = "CON"; std::ofstream ostr(outPath.c_str()); if (ostr.good()) { TestRunner runner(ostr); for (std::vector::iterator it = _tests.begin(); it != _tests.end(); ++it) runner.addTest((*it)->toString(), *it); _tests.clear(); std::vector args; args.push_back("WinTestRunner"); args.push_back("-all"); bool success = runner.run(args); ExitProcess(success ? 0 : 1); } else ExitProcess(2); } else { // We're running in interactive mode. TestRunnerDlg dlg; dlg.setTests(_tests); dlg.DoModal(); } } void WinTestRunner::addTest(Test* pTest) { _tests.push_back(pTest); } BEGIN_MESSAGE_MAP(WinTestRunnerApp, CWinApp) END_MESSAGE_MAP() BOOL WinTestRunnerApp::InitInstance() { AllocConsole(); SetConsoleTitle("CppUnit WinTestRunner Console"); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); freopen("CONIN$", "r", stdin); TestMain(); FreeConsole(); return FALSE; } void WinTestRunnerApp::TestMain() { } } // namespace CppUnit poco-1.3.6p1-all/CppUnit/WinTestRunner/WinTestRunner_vs71.vcproj0000644000076500001200000002224611313735443025325 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/CppUnit/WinTestRunner/WinTestRunner_vs80.vcproj0000644000076500001200000002464111313735443025326 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/CppUnit/WinTestRunner/WinTestRunner_vs90.vcproj0000644000076500001200000002464511313735443025333 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/0000755000076500001200000000000011313735446015535 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/Crypto_VS71.sln0000644000076500001200000000450111313735446020313 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Crypto", "Crypto_VS71.vcproj", "{EEEE7259-32E9-4D56-B023-C733940AB2A0}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS71.vcproj", "{C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}" ProjectSection(ProjectDependencies) = postProject {EEEE7259-32E9-4D56-B023-C733940AB2A0} = {EEEE7259-32E9-4D56-B023-C733940AB2A0} EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared debug_static = debug_static release_static = release_static EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_shared.ActiveCfg = debug_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_shared.Build.0 = debug_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_shared.ActiveCfg = release_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_shared.Build.0 = release_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_static.ActiveCfg = debug_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_static.Build.0 = debug_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_static.ActiveCfg = release_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_static.Build.0 = release_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_shared.ActiveCfg = debug_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_shared.Build.0 = debug_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_shared.ActiveCfg = release_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_shared.Build.0 = release_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_static.ActiveCfg = debug_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_static.Build.0 = debug_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_static.ActiveCfg = release_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_static.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Crypto/Crypto_VS71.vcproj0000644000076500001200000002257011313735446021030 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/Crypto_VS80.sln0000644000076500001200000000461611313735446020322 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Crypto_VS80", "Crypto_VS80.vcproj", "{EEEE7259-32E9-4D56-B023-C733940AB2A0}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS80.vcproj", "{C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}" ProjectSection(ProjectDependencies) = postProject {EEEE7259-32E9-4D56-B023-C733940AB2A0} = {EEEE7259-32E9-4D56-B023-C733940AB2A0} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 debug_static|Win32 = debug_static|Win32 release_shared|Win32 = release_shared|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_shared|Win32.Build.0 = debug_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_static|Win32.ActiveCfg = debug_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_static|Win32.Build.0 = debug_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_shared|Win32.ActiveCfg = release_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_shared|Win32.Build.0 = release_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_static|Win32.ActiveCfg = release_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_static|Win32.Build.0 = release_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_shared|Win32.Build.0 = debug_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_static|Win32.ActiveCfg = debug_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_static|Win32.Build.0 = debug_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_shared|Win32.ActiveCfg = release_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_shared|Win32.Build.0 = release_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_static|Win32.ActiveCfg = release_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Crypto/Crypto_VS80.vcproj0000644000076500001200000002452511313735446021032 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/Crypto_VS90.sln0000644000076500001200000000460611313735446020322 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Crypto", "Crypto_VS90.vcproj", "{EEEE7259-32E9-4D56-B023-C733940AB2A0}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS90.vcproj", "{C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}" ProjectSection(ProjectDependencies) = postProject {EEEE7259-32E9-4D56-B023-C733940AB2A0} = {EEEE7259-32E9-4D56-B023-C733940AB2A0} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_shared|Win32.Build.0 = debug_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_shared|Win32.ActiveCfg = release_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_shared|Win32.Build.0 = release_shared|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_static|Win32.ActiveCfg = debug_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.debug_static|Win32.Build.0 = debug_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_static|Win32.ActiveCfg = release_static|Win32 {EEEE7259-32E9-4D56-B023-C733940AB2A0}.release_static|Win32.Build.0 = release_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_shared|Win32.Build.0 = debug_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_shared|Win32.ActiveCfg = release_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_shared|Win32.Build.0 = release_shared|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_static|Win32.ActiveCfg = debug_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.debug_static|Win32.Build.0 = debug_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_static|Win32.ActiveCfg = release_static|Win32 {C1B1BB96-5198-48EB-AB48-9A0A0B54FB15}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Crypto/Crypto_VS90.vcproj0000644000076500001200000002462311313735446021032 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/include/0000755000076500001200000000000011313735446017160 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/include/Poco/0000755000076500001200000000000011313735446020060 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/include/Poco/Crypto/0000755000076500001200000000000011313735446021340 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/include/Poco/Crypto/Cipher.h0000644000076500001200000001343011313735446022724 0ustar guenteradmin00000000000000// // Cipher.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/Cipher.h#3 $ // // Library: Crypto // Package: Cipher // Module: Cipher // // Definition of the Cipher class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_Cipher_INCLUDED #define Crypto_Cipher_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/RefCountedObject.h" #include "Poco/AutoPtr.h" #include #include #include namespace Poco { namespace Crypto { class CryptoTransform; class Crypto_API Cipher: public Poco::RefCountedObject /// Represents the abstract base class from which all implementations of /// symmetric/assymetric encryption algorithms must inherit. Use the CipherFactory /// class to obtain an instance of this class: /// /// CipherFactory& factory = CipherFactory::defaultFactory(); /// // Creates a 256-bit AES cipher /// Cipher* pCipher = factory.createCipher(CipherKey("aes-256")); /// Cipher* pRSACipher = factory.createCipher(RSAKey(RSAKey::KL_1024, RSAKey::EXP_SMALL)); /// /// Check the different Key constructors on how to initialize/create /// a key. The above example auto-generates random keys. /// /// Note that you won't be able to decrypt data encrypted with a random key /// once the Cipher is destroyed unless you persist the generated key and IV. /// An example usage for random keys is to encrypt data saved in a temporary /// file. /// /// Once your key is set up, you can use the Cipher object to encrypt or /// decrypt strings or, in conjunction with a CryptoInputStream or a /// CryptoOutputStream, to encrypt streams of data. /// /// Since encrypted strings will contain arbitary binary data that will cause /// problems in applications that are not binary-safe (eg., when sending /// encrypted data in e-mails), the encryptString() and decryptString() can /// encode (or decode, respectively) encrypted data using a "transport encoding". /// Supported encodings are Base64 and BinHex. /// /// The following example encrypts and decrypts a string utilizing Base64 /// encoding: /// /// std::string plainText = "This is my secret information"; /// std::string encrypted = pCipher->encryptString(plainText, Cipher::ENC_BASE64); /// std::string decrypted = pCipher->decryptString(encrypted, Cipher::ENC_BASE64); /// /// In order to encrypt a stream of data (eg. to encrypt files), you can use /// a CryptoStream: /// /// // Create an output stream that will encrypt all data going through it /// // and write pass it to the underlying file stream. /// Poco::FileOutputStream sink("encrypted.dat"); /// CryptoOutputStream encryptor(sink, pCipher->createEncryptor()); /// /// Poco::FileInputStream source("source.txt"); /// Poco::StreamCopier::copyStream(source, encryptor); /// /// // Always close output streams to flush all internal buffers /// encryptor.close(); /// sink.close(); { public: typedef Poco::AutoPtr Ptr; typedef std::vector ByteVec; enum Encoding /// Transport encoding to use for encryptString() and decryptString(). { ENC_NONE, /// Plain binary output ENC_BASE64, /// Base64-encoded output ENC_BINHEX /// BinHex-encoded output }; virtual ~Cipher(); /// Destroys the Cipher. virtual const std::string& name() const = 0; /// Returns the name of the Cipher. virtual CryptoTransform* createEncryptor() = 0; /// Creates an encrytor object to be used with a CryptoStream. virtual CryptoTransform* createDecryptor() = 0; /// Creates a decryptor object to be used with a CryptoStream. virtual std::string encryptString(const std::string& str, Encoding encoding = ENC_NONE); /// Directly encrypt a string and encode it using the given encoding. virtual std::string decryptString(const std::string& str, Encoding encoding = ENC_NONE); /// Directly decrypt a string that is encoded with the given encoding. virtual void encrypt(std::istream& source, std::ostream& sink, Encoding encoding = ENC_NONE); /// Directly encrypts an input stream and encodes it using the given encoding. virtual void decrypt(std::istream& source, std::ostream& sink, Encoding encoding = ENC_NONE); /// Directly decrypt an input stream that is encoded with the given encoding. protected: Cipher(); /// Creates a new Cipher object. private: Cipher(const Cipher&); Cipher& operator = (const Cipher&); }; } } // namespace Poco::Crypto #endif // Crypto_Cipher_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/CipherFactory.h0000644000076500001200000000576111313735446024264 0ustar guenteradmin00000000000000// // CipherFactory.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/CipherFactory.h#2 $ // // Library: Crypto // Package: Cipher // Module: CipherFactory // // Definition of the CipherFactory class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_CipherFactory_INCLUDED #define Crypto_CipherFactory_INCLUDED #include "Poco/Crypto/Crypto.h" namespace Poco { namespace Crypto { class Cipher; class CipherKey; class RSAKey; class Crypto_API CipherFactory /// A factory for Cipher objects. See the Cipher class for examples on how to /// use the CipherFactory. { public: CipherFactory(); /// Creates a new CipherFactory object. virtual ~CipherFactory(); /// Destroys the CipherFactory. Cipher* createCipher(const CipherKey& key); /// Creates a Cipher object for the given Cipher name. Valid cipher /// names depend on the OpenSSL version the library is linked with; /// see the output of /// /// openssl enc --help /// /// for a list of supported block and stream ciphers. /// /// Common examples are: /// /// * AES: "aes-128", "aes-256" /// * DES: "des", "des3" /// * Blowfish: "bf" Cipher* createCipher(const RSAKey& key, RSAPaddingMode paddingMode = RSA_PADDING_PKCS1); /// Creates a RSACipher using the given RSA key and padding mode /// for public key encryption/private key decryption. static CipherFactory& defaultFactory(); /// Returns the default CipherFactory. private: static int _instanceCount; CipherFactory(const CipherFactory&); CipherFactory& operator = (const CipherFactory&); }; } } // namespace Poco::Crypto #endif // Crypto_CipherFactory_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/CipherImpl.h0000644000076500001200000000477211313735446023557 0ustar guenteradmin00000000000000// // CipherImpl.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/CipherImpl.h#2 $ // // Library: Crypto // Package: Cipher // Module: CipherImpl // // Definition of the CipherImpl class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_CipherImpl_INCLUDED #define Crypto_CipherImpl_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/CipherKey.h" #include namespace Poco { namespace Crypto { class CipherImpl: public Cipher /// An implementation of the Cipher class for OpenSSL's crypto library. { public: CipherImpl(const CipherKey& key); /// Creates a new CipherImpl object for the given CipherKey. virtual ~CipherImpl(); /// Destroys the CipherImpl. const std::string& name() const; /// Returns the name of the cipher. CryptoTransform* createEncryptor(); /// Creates an encrytor object. CryptoTransform* createDecryptor(); /// Creates a decrytor object. private: CipherKey _key; }; // // Inlines // inline const std::string& CipherImpl::name() const { return _key.name(); } } } // namespace Poco::Crypto #endif // Crypto_CipherImpl_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/CipherKey.h0000644000076500001200000001203111313735446023371 0ustar guenteradmin00000000000000// // CipherKey.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/CipherKey.h#2 $ // // Library: Crypto // Package: Cipher // Module: CipherKey // // Definition of the CipherKey class. // // Copyright (c) 2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_CipherKey_INCLUDED #define Crypto_CipherKey_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/CipherKeyImpl.h" namespace Poco { namespace Crypto { class Crypto_API CipherKey /// CipherKey stores the key information for decryption/encryption of data. /// To create a random key, using the following code: /// /// CipherKey key("aes-256"); /// /// Note that you won't be able to decrypt data encrypted with a random key /// once the Cipher is destroyed unless you persist the generated key and IV. /// An example usage for random keys is to encrypt data saved in a temporary /// file. /// /// To create a key using a human-readable password /// string, use the following code. We create a AES Cipher and /// use a salt value to make the key more robust: /// /// std::string password = "secret"; /// std::string salt("asdff8723lasdf(**923412"); /// CipherKey key("aes-256", password, salt); /// { public: typedef CipherKeyImpl::Mode Mode; typedef CipherKeyImpl::ByteVec ByteVec; enum { DEFAULT_ITERATION_COUNT = 2000 /// Default iteration count to use with /// generateKey(). RSA security recommends /// an iteration count of at least 1000. }; CipherKey(const std::string& name, const std::string& passphrase, const std::string& salt = "", int iterationCount = DEFAULT_ITERATION_COUNT); /// Creates a new CipherKeyImpl object using the given /// cipher name, passphrase, salt value and iteration count. CipherKey(const std::string& name, const ByteVec& key, const ByteVec& iv); /// Creates a new CipherKeyImpl object using the given cipher /// name, key and initialization vector. CipherKey(const std::string& name); /// Creates a new CipherKeyImpl object. Autoinitializes key and /// initialization vector. ~CipherKey(); /// Destroys the CipherKeyImpl. const std::string& name() const; /// Returns the name of the Cipher. int keySize() const; /// Returns the key size of the Cipher. int blockSize() const; /// Returns the block size of the Cipher. int ivSize() const; /// Returns the IV size of the Cipher. Mode mode() const; /// Returns the Cipher's mode of operation. const ByteVec& getKey() const; /// Returns the key for the Cipher. void setKey(const ByteVec& key); /// Sets the key for the Cipher. const ByteVec& getIV() const; /// Returns the initialization vector (IV) for the Cipher. void setIV(const ByteVec& iv); /// Sets the initialization vector (IV) for the Cipher. CipherKeyImpl::Ptr impl(); /// Returns the impl object private: CipherKeyImpl::Ptr _pImpl; }; // // inlines // inline const std::string& CipherKey::name() const { return _pImpl->name(); } inline int CipherKey::keySize() const { return _pImpl->keySize(); } inline int CipherKey::blockSize() const { return _pImpl->blockSize(); } inline int CipherKey::ivSize() const { return _pImpl->ivSize(); } inline CipherKey::Mode CipherKey::mode() const { return _pImpl->mode(); } inline const CipherKey::ByteVec& CipherKey::getKey() const { return _pImpl->getKey(); } inline void CipherKey::setKey(const CipherKey::ByteVec& key) { _pImpl->setKey(key); } inline const CipherKey::ByteVec& CipherKey::getIV() const { return _pImpl->getIV(); } inline void CipherKey::setIV(const CipherKey::ByteVec& iv) { _pImpl->setIV(iv); } inline CipherKeyImpl::Ptr CipherKey::impl() { return _pImpl; } } } // namespace Poco::Crypto #endif // Crypto_CipherKey_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/CipherKeyImpl.h0000644000076500001200000001156411313735446024225 0ustar guenteradmin00000000000000// // CipherKeyImpl.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/CipherKeyImpl.h#2 $ // // Library: Crypto // Package: Cipher // Module: CipherKeyImpl // // Definition of the CipherKeyImpl class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_CipherKeyImpl_INCLUDED #define Crypto_CipherKeyImpl_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/RefCountedObject.h" #include "Poco/AutoPtr.h" #include struct evp_cipher_st; typedef struct evp_cipher_st EVP_CIPHER; namespace Poco { namespace Crypto { class CipherKeyImpl: public RefCountedObject /// An implementation of the CipherKey class for OpenSSL's crypto library. { public: typedef std::vector ByteVec; typedef Poco::AutoPtr Ptr; enum Mode /// Cipher mode of operation. This mode determines how multiple blocks /// are connected; this is essential to improve security. { MODE_STREAM_CIPHER, /// Stream cipher MODE_ECB, /// Electronic codebook (plain concatenation) MODE_CBC, /// Cipher block chaining (default) MODE_CFB, /// Cipher feedback MODE_OFB /// Output feedback }; CipherKeyImpl(const std::string& name, const std::string& passphrase, const std::string& salt, int iterationCount); /// Creates a new CipherKeyImpl object, using /// the given cipher name, passphrase, salt value /// and iteration count. CipherKeyImpl(const std::string& name, const ByteVec& key, const ByteVec& iv); /// Creates a new CipherKeyImpl object, using the /// given cipher name, key and initialization vector. CipherKeyImpl(const std::string& name); /// Creates a new CipherKeyImpl object. Autoinitializes key /// and initialization vector. virtual ~CipherKeyImpl(); /// Destroys the CipherKeyImpl. const std::string& name() const; /// Returns the name of the Cipher. int keySize() const; /// Returns the key size of the Cipher. int blockSize() const; /// Returns the block size of the Cipher. int ivSize() const; /// Returns the IV size of the Cipher. Mode mode() const; /// Returns the Cipher's mode of operation. const ByteVec& getKey() const; /// Returns the key for the Cipher. void setKey(const ByteVec& key); /// Sets the key for the Cipher. const ByteVec& getIV() const; /// Returns the initialization vector (IV) for the Cipher. void setIV(const ByteVec& iv); /// Sets the initialization vector (IV) for the Cipher. const EVP_CIPHER* cipher(); /// Returns the cipher object private: void generateKey(const std::string& passphrase, const std::string& salt, int iterationCount); /// Generates key and IV from a password and optional salt string. void generateKey(); /// Generates key and IV from random data. void getRandomBytes(ByteVec& vec, std::size_t count); /// Stores random bytes in vec. private: const EVP_CIPHER* _pCipher; std::string _name; ByteVec _key; ByteVec _iv; }; // // Inlines // inline const std::string& CipherKeyImpl::name() const { return _name; } inline const CipherKeyImpl::ByteVec& CipherKeyImpl::getKey() const { return _key; } inline void CipherKeyImpl::setKey(const ByteVec& key) { poco_assert(key.size() == keySize()); _key = key; } inline const CipherKeyImpl::ByteVec& CipherKeyImpl::getIV() const { return _iv; } inline void CipherKeyImpl::setIV(const ByteVec& iv) { poco_assert(iv.size() == ivSize()); _iv = iv; } inline const EVP_CIPHER* CipherKeyImpl::cipher() { return _pCipher; } } } // namespace Poco::Crypto #endif // Crypto_CipherKeyImpl_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/Crypto.h0000644000076500001200000000722711313735446023001 0ustar guenteradmin00000000000000// // Crypto.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/Crypto.h#2 $ // // Library: Crypto // Package: CryptoCore // Module: Crypto // // Basic definitions for the Poco Crypto library. // This file must be the first file included by every other Crypto // header file. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_Crypto_INCLUDED #define Crypto_Crypto_INCLUDED #include "Poco/Foundation.h" enum RSAPaddingMode /// The padding mode used for RSA public key encryption. { RSA_PADDING_PKCS1, /// PKCS #1 v1.5 padding. This currently is the most widely used mode. RSA_PADDING_PKCS1_OAEP, /// EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty /// encoding parameter. This mode is recommended for all new applications. RSA_PADDING_SSLV23, /// PKCS #1 v1.5 padding with an SSL-specific modification that denotes /// that the server is SSL3 capable. RSA_PADDING_NONE /// Raw RSA encryption. This mode should only be used to implement cryptographically /// sound padding modes in the application code. Encrypting user data directly with RSA /// is insecure. }; // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the Crypto_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // Crypto_API functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) #if defined(Crypto_EXPORTS) #define Crypto_API __declspec(dllexport) #else #define Crypto_API __declspec(dllimport) #endif #endif #if !defined(Crypto_API) #define Crypto_API #endif // // Automatically link Crypto library. // #if defined(_MSC_VER) #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Crypto_EXPORTS) #if defined(POCO_DLL) #if defined(_DEBUG) #pragma comment(lib, "PocoCryptod.lib") #else #pragma comment(lib, "PocoCrypto.lib") #endif #else #if defined(_DEBUG) #pragma comment(lib, "PocoCryptomtd.lib") #else #pragma comment(lib, "PocoCryptomt.lib") #endif #endif #endif #endif #endif // Crypto_Crypto_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/CryptoStream.h0000644000076500001200000001223711313735446024152 0ustar guenteradmin00000000000000// // CryptoStream.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/CryptoStream.h#4 $ // // Library: Crypto // Package: Cipher // Module: CryptoStream // // Definition of the CryptoStreamBuf, CryptoInputStream and CryptoOutputStream // classes. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_CryptoStream_INCLUDED #define Crypto_CryptoStream_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/BufferedStreamBuf.h" #include "Poco/Buffer.h" #include namespace Poco { namespace Crypto { class CryptoTransform; class Cipher; class Crypto_API CryptoStreamBuf: public Poco::BufferedStreamBuf /// This stream buffer performs cryptographic transformation on the data /// going through it. { public: CryptoStreamBuf(std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); CryptoStreamBuf(std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); virtual ~CryptoStreamBuf(); void close(); /// Flushes all buffers and finishes the encryption. protected: int readFromDevice(char* buffer, std::streamsize length); int writeToDevice(const char* buffer, std::streamsize length); private: CryptoTransform* _pTransform; std::istream* _pIstr; std::ostream* _pOstr; bool _eof; Poco::Buffer _buffer; CryptoStreamBuf(const CryptoStreamBuf&); CryptoStreamBuf& operator = (const CryptoStreamBuf&); }; class Crypto_API CryptoIOS: public virtual std::ios /// The base class for CryptoInputStream and CryptoOutputStream. /// /// This class is needed to ensure correct initialization order of the /// stream buffer and base classes. { public: CryptoIOS(std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); CryptoIOS(std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); ~CryptoIOS(); CryptoStreamBuf* rdbuf(); protected: CryptoStreamBuf _buf; }; class Crypto_API CryptoInputStream: public CryptoIOS, public std::istream /// This stream transforms all data passing through it using the given /// CryptoTransform. /// /// Use a CryptoTransform object provided by Cipher::createEncrytor() or /// Cipher::createDecryptor() to create an encrypting or decrypting stream, /// respectively. { public: CryptoInputStream(std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); /// Create a new CryptoInputStream object. The CryptoInputStream takes the /// ownership of the given CryptoTransform object. CryptoInputStream(std::istream& istr, Cipher& cipher, std::streamsize bufferSize = 8192); /// Create a new encrypting CryptoInputStream object using the given cipher. ~CryptoInputStream(); /// Destroys the CryptoInputStream. }; class Crypto_API CryptoOutputStream: public CryptoIOS, public std::ostream /// This stream transforms all data passing through it using the given /// CryptoTransform. /// /// Use a CryptoTransform object provided by Cipher::createEncrytor() or /// Cipher::createDecryptor() to create an encrypting or decrypting stream, /// respectively. /// /// After all data has been passed through the stream, close() must be called /// to ensure completion of cryptographic transformation. { public: CryptoOutputStream(std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize = 8192); /// Create a new CryptoOutputStream object. The CryptoOutputStream takes the /// ownership of the given CryptoTransform object. CryptoOutputStream(std::ostream& ostr, Cipher& cipher, std::streamsize bufferSize = 8192); /// Create a new decrypting CryptoOutputStream object using the given cipher. ~CryptoOutputStream(); /// Destroys the CryptoOutputStream. void close(); /// Flushes all buffers and finishes the encryption. }; } } // namespace Poco::Crypto #endif // Crypto_CryptoStream_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/CryptoTransform.h0000644000076500001200000000627511313735446024677 0ustar guenteradmin00000000000000// // CryptoTransform.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/CryptoTransform.h#3 $ // // Library: Crypto // Package: Cipher // Module: CryptoTransform // // Definition of the CryptoTransform class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_CryptoTransform_INCLUDED #define Crypto_CryptoTransform_INCLUDED #include "Poco/Crypto/Crypto.h" #include namespace Poco { namespace Crypto { class Crypto_API CryptoTransform /// This interface represents the basic operations for cryptographic /// transformations to be used with a CryptoInputStream or a /// CryptoOutputStream. /// /// Implementations of this class are returned by the Cipher class to /// perform encryption or decryption of data. { public: CryptoTransform(); /// Creates a new CryptoTransform object. virtual ~CryptoTransform(); /// Destroys the CryptoTransform. virtual std::size_t blockSize() const = 0; /// Returns the block size for this CryptoTransform. virtual std::streamsize transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength) = 0; /// Transforms a chunk of data. The inputLength is arbitrary and does not /// need to be a multiple of the block size. The output buffer has a maximum /// capacity of the given outputLength that must be at least /// inputLength + bufferSize() - 1 /// Returns the number of bytes written to the output buffer. virtual std::streamsize finalize(unsigned char* output, std::streamsize length) = 0; /// Finalizes the transformation. The output buffer must contain enough /// space for at least one block, ie. /// length >= bufferSize() /// must be true. Returns the number of bytes written to the output /// buffer. }; } } // namespace Poco::Crypto #endif // Crypto_CryptoTransform_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/OpenSSLInitializer.h0000644000076500001200000000567211313735446025212 0ustar guenteradmin00000000000000// // OpenSSLInitializer.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/OpenSSLInitializer.h#1 $ // // Library: Crypto // Package: CryptoCore // Module: OpenSSLInitializer // // Definition of the OpenSSLInitializer class. // // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_OpenSSLInitializer_INCLUDED #define Crypto_OpenSSLInitializer_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/Mutex.h" extern "C" { struct CRYPTO_dynlock_value { Poco::FastMutex _mutex; }; } namespace Poco { namespace Crypto { class Crypto_API OpenSSLInitializer /// Initalizes the OpenSSL library. /// /// The class ensures the earliest initialization and the /// latest shutdown of the OpenSSL library. { public: OpenSSLInitializer(); /// Automatically initialize OpenSSL on startup. ~OpenSSLInitializer(); /// Automatically shut down OpenSSL on exit. static void initialize(); /// Initializes the OpenSSL machinery. static void uninitialize(); /// Shuts down the OpenSSL machinery. protected: enum { SEEDSIZE = 256 }; // OpenSSL multithreading support static void lock(int mode, int n, const char* file, int line); static unsigned long id(); static struct CRYPTO_dynlock_value* dynlockCreate(const char* file, int line); static void dynlock(int mode, struct CRYPTO_dynlock_value* lock, const char* file, int line); static void dynlockDestroy(struct CRYPTO_dynlock_value* lock, const char* file, int line); private: static Poco::FastMutex* _mutexes; static int _rc; }; } } // namespace Poco::Crypto #endif // Crypto_OpenSSLInitializer_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/RSACipherImpl.h0000644000076500001200000000545111313735446024120 0ustar guenteradmin00000000000000// // RSACipherImpl.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/RSACipherImpl.h#2 $ // // Library: Crypto // Package: RSA // Module: RSACipherImpl // // Definition of the RSACipherImpl class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_RSACipherImpl_INCLUDED #define Crypto_RSACipherImpl_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/RSAKey.h" #include namespace Poco { namespace Crypto { class RSACipherImpl: public Cipher /// An implementation of the Cipher class for /// assymetric (public-private key) encryption /// based on the the RSA algorithm in OpenSSL's /// crypto library. /// /// Encryption is using the public key, decryption /// requires the private key. { public: RSACipherImpl(const RSAKey& key, RSAPaddingMode paddingMode); /// Creates a new RSACipherImpl object for the given RSAKey /// and using the given padding mode. virtual ~RSACipherImpl(); /// Destroys the RSACipherImpl. const std::string& name() const; /// Returns the name of the Cipher. CryptoTransform* createEncryptor(); /// Creates an encrytor object. CryptoTransform* createDecryptor(); /// Creates a decrytor object. private: RSAKey _key; RSAPaddingMode _paddingMode; }; // // Inlines // inline const std::string& RSACipherImpl::name() const { return _key.name(); } } } // namespace Poco::Crypto #endif // Crypto_RSACipherImpl_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/RSADigestEngine.h0000644000076500001200000000763411313735446024436 0ustar guenteradmin00000000000000// // RSADigestEngine.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/RSADigestEngine.h#3 $ // // Library: Crypto // Package: RSA // Module: RSADigestEngine // // Definition of the RSADigestEngine class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_RSADigestEngine_INCLUDED #define Crypto_RSADigestEngine_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/RSAKey.h" #include "Poco/DigestEngine.h" #include "Poco/MD5Engine.h" #include "Poco/SHA1Engine.h" #include #include #include namespace Poco { namespace Crypto { class Crypto_API RSADigestEngine: public Poco::DigestEngine /// This class implements a Poco::DigestEngine that can be /// used to compute a secure digital signature. /// /// First another Poco::DigestEngine (Poco::MD5Engine /// or Poco::SHA1Engine) is used to compute a cryptographic /// hash of the data to be signed. Then, the hash value is /// encrypted, using the RSA private key. /// /// To verify a signature, pass it to the verify() /// member function. It will decrypt the signature /// using the RSA public key and compare the resulting /// hash with the actual hash of the data. { public: enum DigestType { DIGEST_MD5, DIGEST_SHA1 }; RSADigestEngine(const RSAKey& key, DigestType digestType = DIGEST_SHA1); /// Creates the RSADigestEngine with the given RSA key, /// using the SHA-1 hash algorithm. ~RSADigestEngine(); /// Destroys the RSADigestEngine. unsigned digestLength() const; /// Returns the length of the digest in bytes. void reset(); /// Resets the engine so that a new /// digest can be computed. const DigestEngine::Digest& digest(); /// Finishes the computation of the digest /// (the first time it's called) and /// returns the message digest. /// /// Can be called multiple times. const DigestEngine::Digest& signature(); /// Signs the digest using the RSA algorithm /// and the private key (teh first time it's /// called) and returns the result. /// /// Can be called multiple times. bool verify(const DigestEngine::Digest& signature); /// Verifies the data against the signature. /// /// Returns true if the signature can be verified, false otherwise. protected: void updateImpl(const void* data, unsigned length); private: RSAKey _key; Poco::DigestEngine& _engine; int _type; Poco::DigestEngine::Digest _digest; Poco::DigestEngine::Digest _signature; Poco::MD5Engine _md5Engine; Poco::SHA1Engine _sha1Engine; }; } } // namespace Poco::Crypto #endif // Crypto_RSADigestEngine_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/RSAKey.h0000644000076500001200000001022111313735446022603 0ustar guenteradmin00000000000000// // RSAKey.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/RSAKey.h#4 $ // // Library: Crypto // Package: RSA // Module: RSAKey // // Definition of the RSAKey class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_RSAKey_INCLUDED #define Crypto_RSAKey_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/Crypto/RSAKeyImpl.h" namespace Poco { namespace Crypto { class X509Certificate; class Crypto_API RSAKey /// This class stores an RSA key pair, consisting /// of private and public key. Storage of the private /// key is optional. /// /// If a private key is available, the RSAKey can be /// used for decrypting data (encrypted with the public key) /// or computing secure digital signatures. { public: enum KeyLength { KL_512 = 512, KL_1024 = 1024, KL_2048 = 2048, KL_4096 = 4096 }; enum Exponent { EXP_SMALL = 0, EXP_LARGE }; explicit RSAKey(const X509Certificate& cert); /// Extracts the RSA public key from the given certificate. RSAKey(KeyLength keyLength, Exponent exp); /// Creates the RSAKey. Creates a new public/private keypair using the given parameters. /// Can be used to sign data and verify signatures. RSAKey(const std::string& publicKeyFile, const std::string& privateKeyFile = "", const std::string& privateKeyPassphrase = ""); /// Creates the RSAKey, by reading public and private key from the given files and /// using the given passphrase for the private key. Can only by used for signing if /// a private key is available. RSAKey(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream = 0, const std::string& privateKeyPassphrase = ""); /// Creates the RSAKey. Can only by used for signing if pPrivKey /// is not null. If a private key file is specified, you don't need to /// specify a public key file. OpenSSL will auto-create it from the private key. ~RSAKey(); /// Destroys the RSAKey. int size() const; /// Returns the RSA modulus size. void save(const std::string& publicKeyFile, const std::string& privateKeyFile = "", const std::string& privateKeyPassphrase = ""); /// Exports the public and private keys to the given files. /// /// If an empty filename is specified, the corresponding key /// is not exported. void save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStream = 0, const std::string& privateKeyPassphrase = ""); /// Exports the public and private key to the given streams. /// /// If a null pointer is passed for a stream, the corresponding /// key is not exported. RSAKeyImpl::Ptr impl(); /// Returns the impl object. const std::string& name() const; /// Returns "rsa" private: RSAKeyImpl::Ptr _pImpl; }; // // inlines // inline RSAKeyImpl::Ptr RSAKey::impl() { return _pImpl; } } } // namespace Poco::Crypto #endif // Crypto_RSAKey_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/RSAKeyImpl.h0000644000076500001200000001023111313735446023426 0ustar guenteradmin00000000000000// // RSAKeyImpl.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/RSAKeyImpl.h#4 $ // // Library: Crypto // Package: RSA // Module: RSAKeyImpl // // Definition of the RSAKeyImpl class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_RSAKeyImplImpl_INCLUDED #define Crypto_RSAKeyImplImpl_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/RefCountedObject.h" #include "Poco/AutoPtr.h" #include #include struct rsa_st; typedef struct rsa_st RSA; namespace Poco { namespace Crypto { class X509Certificate; class RSAKeyImpl: public Poco::RefCountedObject /// class RSAKeyImpl { public: typedef Poco::AutoPtr Ptr; explicit RSAKeyImpl(const X509Certificate& cert); /// Extracts the RSA public key from the given certificate. RSAKeyImpl(int keyLength, unsigned long exponent); /// Creates the RSAKey. Creates a new public/private keypair using the given parameters. /// Can be used to sign data and verify signatures. RSAKeyImpl(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase); /// Creates the RSAKey, by reading public and private key from the given files and /// using the given passphrase for the private key. Can only by used for signing if /// a private key is available. RSAKeyImpl(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase); /// Creates the RSAKey. Can only by used for signing if pPrivKey /// is not null. If a private key file is specified, you don't need to /// specify a public key file. OpenSSL will auto-create it from the private key. ~RSAKeyImpl(); /// Destroys the RSAKeyImpl. RSA* getRSA(); /// Returns the OpenSSL RSA object. const RSA* getRSA() const; /// Returns the OpenSSL RSA object. int size() const; /// Returns the RSA modulus size. void save(const std::string& publicKeyFile, const std::string& privateKeyFile = "", const std::string& privateKeyPassphrase = ""); /// Exports the public and private keys to the given files. /// /// If an empty filename is specified, the corresponding key /// is not exported. void save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStream = 0, const std::string& privateKeyPassphrase = ""); /// Exports the public and private key to the given streams. /// /// If a null pointer is passed for a stream, the corresponding /// key is not exported. private: void init(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase); void freeRSA(); private: RSA* _pRSA; }; // // inlines // inline RSA* RSAKeyImpl::getRSA() { return _pRSA; } inline const RSA* RSAKeyImpl::getRSA() const { return _pRSA; } } } // namespace Poco::Crypto #endif // Crypto_RSAKeyImplImpl_INCLUDED poco-1.3.6p1-all/Crypto/include/Poco/Crypto/X509Certificate.h0000644000076500001200000001376011313735446024330 0ustar guenteradmin00000000000000// // X509Certificate.h // // $Id: //poco/1.3/Crypto/include/Poco/Crypto/X509Certificate.h#6 $ // // Library: Crypto // Package: Certificate // Module: X509Certificate // // Definition of the X509Certificate class. // // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Crypto_X509Certificate_INCLUDED #define Crypto_X509Certificate_INCLUDED #include "Poco/Crypto/Crypto.h" #include "Poco/DateTime.h" #include "Poco/SharedPtr.h" #include #include #include namespace Poco { namespace Crypto { class Crypto_API X509Certificate /// This class represents a X509 Certificate. { public: enum NID /// Name identifier for extracting information from /// a certificate subject's or issuer's distinguished name. { NID_COMMON_NAME = 13, NID_COUNTRY = 14, NID_LOCALITY_NAME = 15, NID_STATE_OR_PROVINCE = 16, NID_ORGANIZATION_NAME = 17, NID_ORGANIZATION_UNIT_NAME = 18 }; explicit X509Certificate(std::istream& istr); /// Creates the X509Certificate object by reading /// a certificate in PEM format from a stream. explicit X509Certificate(const std::string& path); /// Creates the X509Certificate object by reading /// a certificate in PEM format from a file. explicit X509Certificate(X509* pCert); /// Creates the X509Certificate from an existing /// OpenSSL certificate. Ownership is taken of /// the certificate. X509Certificate(X509* pCert, bool shared); /// Creates the X509Certificate from an existing /// OpenSSL certificate. Ownership is taken of /// the certificate. If shared is true, the /// certificate's reference count is incremented. X509Certificate(const X509Certificate& cert); /// Creates the certificate by copying another one. X509Certificate& operator = (const X509Certificate& cert); /// Assigns a certificate. void swap(X509Certificate& cert); /// Exchanges the certificate with another one. ~X509Certificate(); /// Destroys the X509Certificate. const std::string& issuerName() const; /// Returns the certificate issuer's distinguished name. std::string issuerName(NID nid) const; /// Extracts the information specified by the given /// NID (name identifier) from the certificate issuer's /// distinguished name. const std::string& subjectName() const; /// Returns the certificate subject's distinguished name. std::string subjectName(NID nid) const; /// Extracts the information specified by the given /// NID (name identifier) from the certificate subject's /// distinguished name. std::string commonName() const; /// Returns the common name stored in the certificate /// subject's distinguished name. void extractNames(std::string& commonName, std::set& domainNames) const; /// Extracts the common name and the alias domain names from the /// certificate. Poco::DateTime validFrom() const; /// Returns the date and time the certificate is valid from. Poco::DateTime expiresOn() const; /// Returns the date and time the certificate expires. void save(std::ostream& stream) const; /// Writes the certificate to the given stream. /// The certificate is written in PEM format. void save(const std::string& path) const; /// Writes the certificate to the file given by path. /// The certificate is written in PEM format. bool issuedBy(const X509Certificate& issuerCertificate) const; /// Checks whether the certificate has been issued by /// the issuer given by issuerCertificate. This can be /// used to validate a certificate chain. /// /// Verifies if the certificate has been signed with the /// issuer's private key, using the public key from the issuer /// certificate. /// /// Returns true if verification against the issuer certificate /// was successfull, false otherwise. const X509* certificate() const; /// Returns the underlying OpenSSL certificate. protected: void load(std::istream& stream); /// Loads the certificate from the given stream. The /// certificate must be in PEM format. void load(const std::string& path); /// Loads the certificate from the given file. The /// certificate must be in PEM format. void init(); /// Extracts issuer and subject name from the certificate. private: enum { NAME_BUFFER_SIZE = 256 }; std::string _issuerName; std::string _subjectName; X509* _pCert; }; // // inlines // inline const std::string& X509Certificate::issuerName() const { return _issuerName; } inline const std::string& X509Certificate::subjectName() const { return _subjectName; } inline const X509* X509Certificate::certificate() const { return _pCert; } } } // namespace Poco::Crypto #endif // Crypto_X509Certificate_INCLUDED poco-1.3.6p1-all/Crypto/Makefile0000644000076500001200000000072311313735446017177 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Crypto/Makefile#2 $ # # Makefile for Poco Crypto # include $(POCO_BASE)/build/rules/global SYSLIBS += -lssl -lcrypto objects = Cipher CipherFactory CipherImpl CipherKey CipherKeyImpl CryptoStream CryptoTransform \ RSACipherImpl RSAKey RSAKeyImpl RSADigestEngine \ X509Certificate OpenSSLInitializer target = PocoCrypto target_version = $(LIBVERSION) target_libs = PocoFoundation include $(POCO_BASE)/build/rules/lib poco-1.3.6p1-all/Crypto/samples/0000755000076500001200000000000011313735446017201 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/samples/genrsakey/0000755000076500001200000000000011313735446021171 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/samples/genrsakey/genrsakey_VS71.vcproj0000644000076500001200000001003611313735446025166 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/samples/genrsakey/genrsakey_VS80.vcproj0000644000076500001200000001073011313735446025167 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/samples/genrsakey/genrsakey_VS90.vcproj0000644000076500001200000001110011313735446025160 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/samples/genrsakey/Makefile0000644000076500001200000000051011313735446022625 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/Main/template/sample.make#4 $ # # Makefile for Poco genrsakey # include $(POCO_BASE)/build/rules/global SYSLIBS += -lssl -lcrypto objects = genrsakey target = genrsakey target_version = 1 target_libs = PocoCrypto PocoUtil PocoXML PocoFoundation include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Crypto/samples/genrsakey/src/0000755000076500001200000000000011313735446021760 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/samples/genrsakey/src/genrsakey.cpp0000644000076500001200000001465411313735446024466 0ustar guenteradmin00000000000000// // genrsakey.cpp // // $Id: //poco/1.3/Crypto/samples/genrsakey/src/genrsakey.cpp#1 $ // // This sample demonstrates the XYZ class. // // Copyright (c) 2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Util/Application.h" #include "Poco/Util/Option.h" #include "Poco/Util/OptionException.h" #include "Poco/Util/OptionSet.h" #include "Poco/Util/HelpFormatter.h" #include "Poco/Util/AbstractConfiguration.h" #include "Poco/AutoPtr.h" #include "Poco/NumberFormatter.h" #include "Poco/NumberParser.h" #include "Poco/String.h" #include "Poco/Crypto/RSAKey.h" #include using Poco::Util::Application; using Poco::Util::Option; using Poco::Util::OptionSet; using Poco::Util::HelpFormatter; using Poco::Util::AbstractConfiguration; using Poco::Util::OptionCallback; using Poco::AutoPtr; using Poco::NumberParser; using Poco::Crypto::RSAKey; class RSAApp: public Application /// This sample demonstrates some of the features of the Util::Application class, /// such as configuration file handling and command line arguments processing. /// /// Try genrsakey --help (on Unix platforms) or genrsakey /help (elsewhere) for /// more information. { public: RSAApp(): _helpRequested(false), _length(RSAKey::KL_1024), _exp(RSAKey::EXP_LARGE), _name(), _pwd() { } protected: void initialize(Application& self) { loadConfiguration(); // load default configuration files, if present Application::initialize(self); } void uninitialize() { Application::uninitialize(); } void reinitialize(Application& self) { Application::reinitialize(self); } void defineOptions(OptionSet& options) { Application::defineOptions(options); options.addOption( Option("help", "h", "display help information on command line arguments") .required(false) .repeatable(false) .callback(OptionCallback(this, &RSAApp::handleHelp))); options.addOption( Option("?", "?", "display help information on command line arguments") .required(false) .repeatable(false) .callback(OptionCallback(this, &RSAApp::handleHelp))); options.addOption( Option("key", "k", "define the key length") .required(false) .repeatable(false) .argument("512|1024|2048|4096") .callback(OptionCallback(this, &RSAApp::handleKeyLength))); options.addOption( Option("exponent", "e", "defines the exponent of the key") .required(false) .repeatable(false) .argument("small|large") .callback(OptionCallback(this, &RSAApp::handleExponent))); options.addOption( Option("file", "f", "defines the file base name. creates a file.pub and a file.priv") .required(true) .repeatable(false) .argument("filebasename") .callback(OptionCallback(this, &RSAApp::handleFilePrefix))); options.addOption( Option("password", "p", "defines the password used to encrypt the private key file. If not defined user will be asked via stdin to provide in") .required(false) .repeatable(false) .argument("pwd") .callback(OptionCallback(this, &RSAApp::handlePassword))); } void handleHelp(const std::string& name, const std::string& value) { _helpRequested = true; displayHelp(); stopOptionsProcessing(); } void handleKeyLength(const std::string& name, const std::string& value) { int keyLen = Poco::NumberParser::parse(value); if (keyLen == 512 || keyLen == 1024 || keyLen == 2048 || keyLen == 4096) _length = (RSAKey::KeyLength)keyLen; else throw Poco::Util::IncompatibleOptionsException("Illegal key length value"); } void handleExponent(const std::string& name, const std::string& value) { if (Poco::icompare(value, "small") == 0) _exp = RSAKey::EXP_SMALL; else _exp = RSAKey::EXP_LARGE; } void handleFilePrefix(const std::string& name, const std::string& value) { if (value.empty()) throw Poco::Util::IncompatibleOptionsException("Empty file prefix forbidden"); _name = value; } void handlePassword(const std::string& name, const std::string& value) { _pwd = value; } void displayHelp() { HelpFormatter helpFormatter(options()); helpFormatter.setCommand(commandName()); helpFormatter.setUsage("OPTIONS"); helpFormatter.setHeader("Application for generating RSA public/private key pairs."); helpFormatter.format(std::cout); } int main(const std::vector& args) { if (!_helpRequested) { logger().information("Generating key with length " + Poco::NumberFormatter::format((int)_length)); logger().information(std::string("Exponent is ") + ((_exp == RSAKey::EXP_SMALL)?"small":"large")); logger().information("Generating key"); RSAKey key(_length, _exp); logger().information("Generating key: DONE"); std::string pubFile(_name + ".pub"); std::string privFile(_name + ".priv"); logger().information("Saving key to " + pubFile + " and " + privFile); key.save(pubFile, privFile, _pwd); logger().information("Key saved"); } return Application::EXIT_OK; } private: bool _helpRequested; RSAKey::KeyLength _length; RSAKey::Exponent _exp; std::string _name; std::string _pwd; }; POCO_APP_MAIN(RSAApp) poco-1.3.6p1-all/Crypto/samples/Makefile0000644000076500001200000000026711313735446020646 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/Main/Util/samples/Makefile#3 $ # # Makefile for Poco Util Samples # .PHONY: projects clean all: projects projects: $(MAKE) -C genrsakey $(MAKECMDGOALS) poco-1.3.6p1-all/Crypto/samples/samples_VS71.sln0000644000076500001200000000173111313735446022145 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "genrsakey", "genrsakey\genrsakey_VS71.vcproj", "{5347F6C5-C0ED-4583-92FB-560764B59938}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {5347F6C5-C0ED-4583-92FB-560764B59938}.debug_shared.ActiveCfg = debug_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.debug_shared.Build.0 = debug_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.release_shared.ActiveCfg = release_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.release_shared.Build.0 = release_shared|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Crypto/samples/samples_VS80.sln0000644000076500001200000000170111313735446022142 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "genrsakey", "genrsakey\genrsakey_VS80.vcproj", "{5347F6C5-C0ED-4583-92FB-560764B59938}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5347F6C5-C0ED-4583-92FB-560764B59938}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.debug_shared|Win32.Build.0 = debug_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.release_shared|Win32.ActiveCfg = release_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.release_shared|Win32.Build.0 = release_shared|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Crypto/samples/samples_VS90.sln0000644000076500001200000000170711313735446022151 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "genrsakey_VS90", "genrsakey\genrsakey_VS90.vcproj", "{5347F6C5-C0ED-4583-92FB-560764B59938}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5347F6C5-C0ED-4583-92FB-560764B59938}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.debug_shared|Win32.Build.0 = debug_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.release_shared|Win32.ActiveCfg = release_shared|Win32 {5347F6C5-C0ED-4583-92FB-560764B59938}.release_shared|Win32.Build.0 = release_shared|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Crypto/src/0000755000076500001200000000000011313735446016324 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/src/Cipher.cpp0000644000076500001200000000713711313735446020252 0ustar guenteradmin00000000000000// // Cipher.cpp // // $Id: //poco/1.3/Crypto/src/Cipher.cpp#3 $ // // Library: Crypto // Package: Cipher // Module: Cipher // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/CryptoStream.h" #include "Poco/Crypto/CryptoTransform.h" #include "Poco/Base64Encoder.h" #include "Poco/Base64Decoder.h" #include "Poco/HexBinaryEncoder.h" #include "Poco/HexBinaryDecoder.h" #include "Poco/StreamCopier.h" #include "Poco/Exception.h" #include #include namespace Poco { namespace Crypto { Cipher::Cipher() { } Cipher::~Cipher() { } std::string Cipher::encryptString(const std::string& str, Encoding encoding) { std::istringstream source(str); std::ostringstream sink; encrypt(source, sink, encoding); return sink.str(); } std::string Cipher::decryptString(const std::string& str, Encoding encoding) { std::istringstream source(str); std::ostringstream sink; decrypt(source, sink, encoding); return sink.str(); } void Cipher::encrypt(std::istream& source, std::ostream& sink, Encoding encoding) { CryptoInputStream encryptor(source, createEncryptor()); switch (encoding) { case ENC_NONE: StreamCopier::copyStream(encryptor, sink); break; case ENC_BASE64: { Poco::Base64Encoder encoder(sink); StreamCopier::copyStream(encryptor, encoder); encoder.close(); } break; case ENC_BINHEX: { Poco::HexBinaryEncoder encoder(sink); StreamCopier::copyStream(encryptor, encoder); encoder.close(); } break; default: throw Poco::InvalidArgumentException("Invalid argument", "encoding"); } } void Cipher::decrypt(std::istream& source, std::ostream& sink, Encoding encoding) { CryptoOutputStream decryptor(sink, createDecryptor()); switch (encoding) { case ENC_NONE: StreamCopier::copyStream(source, decryptor); decryptor.close(); break; case ENC_BASE64: { Poco::Base64Decoder decoder(source); StreamCopier::copyStream(decoder, decryptor); decryptor.close(); } break; case ENC_BINHEX: { Poco::HexBinaryDecoder decoder(source); StreamCopier::copyStream(decoder, decryptor); decryptor.close(); } break; default: throw Poco::InvalidArgumentException("Invalid argument", "encoding"); } } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/CipherFactory.cpp0000644000076500001200000000514411313735446021576 0ustar guenteradmin00000000000000// // CipherFactory.cpp // // $Id: //poco/1.3/Crypto/src/CipherFactory.cpp#2 $ // // Library: Crypto // Package: Cipher // Module: CipherFactory // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/CipherFactory.h" #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/CipherKey.h" #include "Poco/Crypto/RSAKey.h" #include "Poco/Crypto/CipherImpl.h" #include "Poco/Crypto/RSACipherImpl.h" #include "Poco/Exception.h" #include "Poco/SingletonHolder.h" #include #include namespace Poco { namespace Crypto { int CipherFactory::_instanceCount = 0; CipherFactory::CipherFactory() { if (_instanceCount == 0) { OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); } ++_instanceCount; } CipherFactory::~CipherFactory() { --_instanceCount; if (_instanceCount == 0) { ERR_free_strings(); EVP_cleanup(); } } CipherFactory& CipherFactory::defaultFactory() { static Poco::SingletonHolder holder; return *holder.get(); } Cipher* CipherFactory::createCipher(const CipherKey& key) { return new CipherImpl(key); } Cipher* CipherFactory::createCipher(const RSAKey& key, RSAPaddingMode paddingMode) { return new RSACipherImpl(key, paddingMode); } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/CipherImpl.cpp0000644000076500001200000001122111313735446021061 0ustar guenteradmin00000000000000// // CipherImpl.cpp // // $Id: //poco/1.3/Crypto/src/CipherImpl.cpp#4 $ // // Library: Crypto // Package: Cipher // Module: CipherImpl // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/CipherImpl.h" #include "Poco/Crypto/CryptoTransform.h" #include "Poco/Exception.h" #include namespace Poco { namespace Crypto { namespace { void throwError() { unsigned long err; std::string msg; while ((err = ERR_get_error())) { if (!msg.empty()) msg.append("; "); msg.append(ERR_error_string(err, 0)); } throw Poco::IOException(msg); } class CryptoTransformImpl: public CryptoTransform { public: typedef Cipher::ByteVec ByteVec; enum Direction { DIR_ENCRYPT, DIR_DECRYPT }; CryptoTransformImpl( const EVP_CIPHER* pCipher, const ByteVec& key, const ByteVec& iv, Direction dir); ~CryptoTransformImpl(); std::size_t blockSize() const; std::streamsize transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength); std::streamsize finalize( unsigned char* output, std::streamsize length); private: const EVP_CIPHER* _pCipher; EVP_CIPHER_CTX _ctx; ByteVec _key; ByteVec _iv; }; CryptoTransformImpl::CryptoTransformImpl( const EVP_CIPHER* pCipher, const ByteVec& key, const ByteVec& iv, Direction dir): _pCipher(pCipher), _key(key), _iv(iv) { EVP_CipherInit( &_ctx, _pCipher, &_key[0], &_iv[0], (dir == DIR_ENCRYPT) ? 1 : 0); } CryptoTransformImpl::~CryptoTransformImpl() { EVP_CIPHER_CTX_cleanup(&_ctx); } std::size_t CryptoTransformImpl::blockSize() const { return EVP_CIPHER_CTX_block_size(&_ctx); } std::streamsize CryptoTransformImpl::transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength) { poco_assert (outputLength >= (inputLength + blockSize() - 1)); int outLen = static_cast(outputLength); int rc = EVP_CipherUpdate( &_ctx, output, &outLen, input, static_cast(inputLength)); if (rc == 0) throwError(); return static_cast(outLen); } std::streamsize CryptoTransformImpl::finalize( unsigned char* output, std::streamsize length) { poco_assert (length >= blockSize()); int len = static_cast(length); // Use the '_ex' version that does not perform implicit cleanup since we // will call EVP_CIPHER_CTX_cleanup() from the dtor as there is no // guarantee that finalize() will be called if an error occurred. int rc = EVP_CipherFinal_ex(&_ctx, output, &len); if (rc == 0) throwError(); return static_cast(len); } } CipherImpl::CipherImpl(const CipherKey& key): _key(key) { } CipherImpl::~CipherImpl() { } CryptoTransform* CipherImpl::createEncryptor() { CipherKeyImpl::Ptr p = _key.impl(); return new CryptoTransformImpl(p->cipher(), p->getKey(), p->getIV(), CryptoTransformImpl::DIR_ENCRYPT); } CryptoTransform* CipherImpl::createDecryptor() { CipherKeyImpl::Ptr p = _key.impl(); return new CryptoTransformImpl(p->cipher(), p->getKey(), p->getIV(), CryptoTransformImpl::DIR_DECRYPT); } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/CipherKey.cpp0000644000076500001200000000413511313735446020716 0ustar guenteradmin00000000000000// // CipherKey.cpp // // $Id: //poco/1.3/Crypto/src/CipherKey.cpp#2 $ // // Library: Crypto // Package: Cipher // Module: CipherKey // // Copyright (c) 2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/CipherKey.h" namespace Poco { namespace Crypto { CipherKey::CipherKey(const std::string& name, const std::string& passphrase, const std::string& salt, int iterationCount): _pImpl(new CipherKeyImpl(name, passphrase, salt, iterationCount)) { } CipherKey::CipherKey(const std::string& name, const ByteVec& key, const ByteVec& iv): _pImpl(new CipherKeyImpl(name, key, iv)) { } CipherKey::CipherKey(const std::string& name): _pImpl(new CipherKeyImpl(name)) { } CipherKey::~CipherKey() { } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/CipherKeyImpl.cpp0000644000076500001200000001232511313735446021540 0ustar guenteradmin00000000000000// // CipherKeyImpl.cpp // // $Id: //poco/1.3/Crypto/src/CipherKeyImpl.cpp#4 $ // // Library: Crypto // Package: Cipher // Module: CipherKeyImpl // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/CipherKeyImpl.h" #include "Poco/Crypto/CryptoTransform.h" #include "Poco/Crypto/CipherFactory.h" #include "Poco/Exception.h" #include "Poco/RandomStream.h" #include #include namespace Poco { namespace Crypto { CipherKeyImpl::CipherKeyImpl(const std::string& name, const std::string& passphrase, const std::string& salt, int iterationCount): _pCipher(0), _name(name), _key(), _iv() { // dummy access to Cipherfactory so that the EVP lib is initilaized CipherFactory::defaultFactory(); _pCipher = EVP_get_cipherbyname(name.c_str()); if (!_pCipher) throw Poco::NotFoundException("Cipher " + name + " was not found"); _key = ByteVec(keySize()); _iv = ByteVec(ivSize()); generateKey(passphrase, salt, iterationCount); } CipherKeyImpl::CipherKeyImpl(const std::string& name, const ByteVec& key, const ByteVec& iv): _pCipher(0), _name(name), _key(key), _iv(iv) { // dummy access to Cipherfactory so that the EVP lib is initilaized CipherFactory::defaultFactory(); _pCipher = EVP_get_cipherbyname(name.c_str()); if (!_pCipher) throw Poco::NotFoundException("Cipher " + name + " was not found"); } CipherKeyImpl::CipherKeyImpl(const std::string& name): _pCipher(0), _name(name), _key(), _iv() { // dummy access to Cipherfactory so that the EVP lib is initilaized CipherFactory::defaultFactory(); _pCipher = EVP_get_cipherbyname(name.c_str()); if (!_pCipher) throw Poco::NotFoundException("Cipher " + name + " was not found"); _key = ByteVec(keySize()); _iv = ByteVec(ivSize()); generateKey(); } CipherKeyImpl::~CipherKeyImpl() { } CipherKeyImpl::Mode CipherKeyImpl::mode() const { switch (EVP_CIPHER_mode(_pCipher)) { case EVP_CIPH_STREAM_CIPHER: return MODE_STREAM_CIPHER; case EVP_CIPH_ECB_MODE: return MODE_ECB; case EVP_CIPH_CBC_MODE: return MODE_CBC; case EVP_CIPH_CFB_MODE: return MODE_CFB; case EVP_CIPH_OFB_MODE: return MODE_OFB; } throw Poco::IllegalStateException("Unexpected value of EVP_CIPHER_mode()"); } void CipherKeyImpl::generateKey() { ByteVec vec; getRandomBytes(vec, keySize()); setKey(vec); getRandomBytes(vec, ivSize()); setIV(vec); } void CipherKeyImpl::getRandomBytes(ByteVec& vec, std::size_t count) { Poco::RandomInputStream random; vec.clear(); vec.reserve(count); for (int i = 0; i < count; ++i) vec.push_back(static_cast(random.get())); } void CipherKeyImpl::generateKey( const std::string& password, const std::string& salt, int iterationCount) { unsigned char keyBytes[EVP_MAX_KEY_LENGTH]; unsigned char ivBytes[EVP_MAX_IV_LENGTH]; // OpenSSL documentation specifies that the salt must be an 8-byte array. unsigned char saltBytes[8]; if (!salt.empty()) { int len = static_cast(salt.size()); // Create the salt array from the salt string for (int i = 0; i < 8; ++i) saltBytes[i] = salt.at(i % len); for (int i = 8; i < len; ++i) saltBytes[i % 8] ^= salt.at(i); } // Now create the key and IV, using the MD5 digest algorithm. int keySize = EVP_BytesToKey( _pCipher, EVP_md5(), (salt.empty() ? 0 : saltBytes), reinterpret_cast(password.data()), static_cast(password.size()), iterationCount, keyBytes, ivBytes); // Copy the buffers to our member byte vectors. _key.assign(keyBytes, keyBytes + keySize); if (ivSize() == 0) _iv.clear(); else _iv.assign(ivBytes, ivBytes + ivSize()); } int CipherKeyImpl::keySize() const { return EVP_CIPHER_key_length(_pCipher); } int CipherKeyImpl::blockSize() const { return EVP_CIPHER_block_size(_pCipher); } int CipherKeyImpl::ivSize() const { return EVP_CIPHER_iv_length(_pCipher); } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/CryptoStream.cpp0000644000076500001200000001520711313735446021471 0ustar guenteradmin00000000000000// // CryptoStream.cpp // // $Id: //poco/1.3/Crypto/src/CryptoStream.cpp#3 $ // // Library: Crypto // Package: Cipher // Module: CryptoStream // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/CryptoStream.h" #include "Poco/Crypto/CryptoTransform.h" #include "Poco/Crypto/Cipher.h" #include "Poco/Exception.h" #include #undef min #undef max namespace Poco { namespace Crypto { // // CryptoStreamBuf // CryptoStreamBuf::CryptoStreamBuf( std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize) : Poco::BufferedStreamBuf(bufferSize, std::ios::in), _pTransform(pTransform), _pIstr(&istr), _pOstr(0), _eof(false), _buffer(bufferSize) { poco_check_ptr(pTransform); poco_assert(bufferSize >= 2 * pTransform->blockSize()); } CryptoStreamBuf::CryptoStreamBuf( std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize) : Poco::BufferedStreamBuf(bufferSize, std::ios::out), _pTransform(pTransform), _pIstr(0), _pOstr(&ostr), _eof(false), _buffer(bufferSize) { poco_check_ptr(pTransform); poco_assert(bufferSize >= 2 * pTransform->blockSize()); } CryptoStreamBuf::~CryptoStreamBuf() { try { close(); } catch (...) { } delete _pTransform; } void CryptoStreamBuf::close() { sync(); if (_pIstr) { _pIstr = 0; } else if (_pOstr) { // Close can be called multiple times. By zeroing the pointer we make // sure that we call finalize() only once, even if an exception is // thrown. std::ostream* pOstr = _pOstr; _pOstr = 0; // Finalize transformation. int n = _pTransform->finalize(_buffer.begin(), static_cast(_buffer.size())); if (n > 0) { pOstr->write(reinterpret_cast(_buffer.begin()), n); if (!pOstr->good()) throw Poco::IOException("Output stream failure"); } } } int CryptoStreamBuf::readFromDevice(char* buffer, std::streamsize length) { if (!_pIstr) return 0; int count = 0; while (!_eof) { int m = static_cast(length) - count - static_cast(_pTransform->blockSize() - 1); // Make sure we can read at least one more block. Explicitely check // for m < 0 since blockSize() returns an unsigned int and the // comparison might give fals results for m < 0. if (m < 0 || m < _pTransform->blockSize()) break; int n = 0; if (_pIstr->good()) { _pIstr->read(reinterpret_cast(_buffer.begin()), m); n = static_cast(_pIstr->gcount()); } if (n == 0) { _eof = true; // No more data, finalize transformation count += _pTransform->finalize( reinterpret_cast(buffer + count), length - count); } else { // Transform next chunk of data count += _pTransform->transform( _buffer.begin(), n, reinterpret_cast(buffer + count), length - count); } } return count; } int CryptoStreamBuf::writeToDevice(const char* buffer, std::streamsize length) { if (!_pOstr) return 0; std::size_t maxChunkSize = _buffer.size() - (_pTransform->blockSize() - 1); std::size_t count = 0; while (count < length) { // Truncate chunk size so that the maximum output fits into _buffer. std::size_t n = length - count; if (n > maxChunkSize) n = maxChunkSize; // Transform next chunk of data int k = _pTransform->transform( reinterpret_cast(buffer + count), static_cast(n), _buffer.begin(), static_cast(_buffer.size())); // Attention: (n != k) might be true. In count, we have to track how // many bytes from buffer have been consumed, not how many bytes have // been written to _pOstr! count += n; if (k > 0) { _pOstr->write(reinterpret_cast(_buffer.begin()), k); if (!_pOstr->good()) throw Poco::IOException("Output stream failure"); } } return static_cast(count); } // // CryptoIOS // CryptoIOS::CryptoIOS( std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize) : _buf(istr, pTransform, bufferSize) { poco_ios_init(&_buf); } CryptoIOS::CryptoIOS( std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize) : _buf(ostr, pTransform, bufferSize) { poco_ios_init(&_buf); } CryptoIOS::~CryptoIOS() { } CryptoStreamBuf* CryptoIOS::rdbuf() { return &_buf; } // // CryptoInputStream // CryptoInputStream::CryptoInputStream( std::istream& istr, CryptoTransform* pTransform, std::streamsize bufferSize) : CryptoIOS(istr, pTransform, bufferSize), std::istream(&_buf) { } CryptoInputStream::CryptoInputStream( std::istream& istr, Cipher& cipher, std::streamsize bufferSize) : CryptoIOS(istr, cipher.createEncryptor(), bufferSize), std::istream(&_buf) { } CryptoInputStream::~CryptoInputStream() { } // // CryptoOutputStream // CryptoOutputStream::CryptoOutputStream( std::ostream& ostr, CryptoTransform* pTransform, std::streamsize bufferSize) : CryptoIOS(ostr, pTransform, bufferSize), std::ostream(&_buf) { } CryptoOutputStream::CryptoOutputStream( std::ostream& ostr, Cipher& cipher, std::streamsize bufferSize): CryptoIOS(ostr, cipher.createDecryptor(), bufferSize), std::ostream(&_buf) { } CryptoOutputStream::~CryptoOutputStream() { } void CryptoOutputStream::close() { _buf.close(); } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/CryptoTransform.cpp0000644000076500001200000000337711313735446022216 0ustar guenteradmin00000000000000// // CryptoTransform.cpp // // $Id: //poco/1.3/Crypto/src/CryptoTransform.cpp#2 $ // // Library: Crypto // Package: Cipher // Module: CryptoTransform // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/CryptoTransform.h" namespace Poco { namespace Crypto { CryptoTransform::CryptoTransform() { } CryptoTransform::~CryptoTransform() { } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/OpenSSLInitializer.cpp0000644000076500001200000000747211313735446022531 0ustar guenteradmin00000000000000// // OpenSSLInitializer.cpp // // $Id: //poco/1.3/Crypto/src/OpenSSLInitializer.cpp#3 $ // // Library: Crypto // Package: CryotpCore // Module: OpenSSLInitializer // // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/OpenSSLInitializer.h" #include "Poco/RandomStream.h" #include "Poco/Thread.h" #include #include #include #include using Poco::RandomInputStream; using Poco::Thread; using Poco::FastMutex; namespace Poco { namespace Crypto { FastMutex* OpenSSLInitializer::_mutexes(0); int OpenSSLInitializer::_rc(0); static OpenSSLInitializer initializer; OpenSSLInitializer::OpenSSLInitializer() { initialize(); } OpenSSLInitializer::~OpenSSLInitializer() { uninitialize(); } void OpenSSLInitializer::initialize() { if (++_rc == 1) { poco_assert (1 == SSL_library_init()); // always returns 1 SSL_load_error_strings(); char seed[SEEDSIZE]; RandomInputStream rnd; rnd.read(seed, sizeof(seed)); RAND_seed(seed, SEEDSIZE); int nMutexes = CRYPTO_num_locks(); _mutexes = new FastMutex[nMutexes]; CRYPTO_set_locking_callback(&OpenSSLInitializer::lock); #ifndef POCO_OS_FAMILY_WINDOWS // SF# 1828231: random unhandled exceptions when linking with ssl CRYPTO_set_id_callback(&OpenSSLInitializer::id); #endif CRYPTO_set_dynlock_create_callback(&OpenSSLInitializer::dynlockCreate); CRYPTO_set_dynlock_lock_callback(&OpenSSLInitializer::dynlock); CRYPTO_set_dynlock_destroy_callback(&OpenSSLInitializer::dynlockDestroy); } } void OpenSSLInitializer::uninitialize() { if (--_rc == 0) { EVP_cleanup(); ERR_free_strings(); CRYPTO_set_locking_callback(0); delete [] _mutexes; } } void OpenSSLInitializer::lock(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) _mutexes[n].lock(); else _mutexes[n].unlock(); } unsigned long OpenSSLInitializer::id() { Thread* pThread = Thread::current(); return pThread ? pThread->id() : 0; } struct CRYPTO_dynlock_value* OpenSSLInitializer::dynlockCreate(const char* file, int line) { return new CRYPTO_dynlock_value; } void OpenSSLInitializer::dynlock(int mode, struct CRYPTO_dynlock_value* lock, const char* file, int line) { poco_check_ptr (lock); if (mode & CRYPTO_LOCK) lock->_mutex.lock(); else lock->_mutex.unlock(); } void OpenSSLInitializer::dynlockDestroy(struct CRYPTO_dynlock_value* lock, const char* file, int line) { delete lock; } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/RSACipherImpl.cpp0000644000076500001200000001642011313735446021435 0ustar guenteradmin00000000000000// // RSACipherImpl.cpp // // $Id: //poco/1.3/Crypto/src/RSACipherImpl.cpp#5 $ // // Library: Crypto // Package: RSA // Module: RSACipherImpl // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/RSACipherImpl.h" #include "Poco/Crypto/CryptoTransform.h" #include "Poco/Exception.h" #include #include #include namespace Poco { namespace Crypto { namespace { void throwError() { unsigned long err; std::string msg; while ((err = ERR_get_error())) { if (!msg.empty()) msg.append("; "); msg.append(ERR_error_string(err, 0)); } throw Poco::IOException(msg); } int mapPaddingMode(RSAPaddingMode paddingMode) { switch (paddingMode) { case RSA_PADDING_PKCS1: return RSA_PKCS1_PADDING; case RSA_PADDING_PKCS1_OAEP: return RSA_PKCS1_OAEP_PADDING; case RSA_PADDING_SSLV23: return RSA_SSLV23_PADDING; case RSA_PADDING_NONE: return RSA_NO_PADDING; default: poco_bugcheck(); return RSA_NO_PADDING; } } class RSAEncryptImpl: public CryptoTransform { public: enum { OVERFLOW = 11 }; RSAEncryptImpl(const RSA* pRSA, RSAPaddingMode paddingMode); ~RSAEncryptImpl(); std::size_t blockSize() const; std::streamsize transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength); std::streamsize finalize(unsigned char* output, std::streamsize length); private: const RSA* _pRSA; RSAPaddingMode _paddingMode; std::streamsize _pos; unsigned char* _pBuf; }; RSAEncryptImpl::RSAEncryptImpl(const RSA* pRSA, RSAPaddingMode paddingMode): _pRSA(pRSA), _paddingMode(paddingMode), _pos(0), _pBuf(0) { _pBuf = new unsigned char[blockSize()]; } RSAEncryptImpl::~RSAEncryptImpl() { delete _pBuf; } std::size_t RSAEncryptImpl::blockSize() const { return RSA_size(_pRSA); } std::streamsize RSAEncryptImpl::transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength) { // always fill up the buffer before writing! std::streamsize rsaSize = static_cast(blockSize()); poco_assert_dbg(_pos <= rsaSize); poco_assert (outputLength >= rsaSize); int rc = 0; while (inputLength > 0) { // check how many data bytes we are missing to get the buffer full poco_assert_dbg (rsaSize >= _pos); std::streamsize missing = rsaSize - _pos; if (missing == 0) { poco_assert (outputLength >= rsaSize); int tmp = RSA_public_encrypt(rsaSize, _pBuf, output, const_cast(_pRSA), RSA_NO_PADDING); if (tmp == -1) throwError(); rc += tmp; output += tmp; outputLength -= tmp; _pos = 0; } else { if (missing > inputLength) missing = inputLength; std::memcpy(_pBuf+_pos, input, missing); input += missing; _pos += missing; inputLength -= missing; } } return rc; } std::streamsize RSAEncryptImpl::finalize(unsigned char* output, std::streamsize length) { poco_assert (length >= blockSize()); int rc = 0; if (_pos > 0) { rc = RSA_public_encrypt(_pos, _pBuf, output, const_cast(_pRSA), mapPaddingMode(_paddingMode)); if (rc == -1) throwError(); } return rc; } class RSADecryptImpl: public CryptoTransform { public: enum { OVERFLOW = 11 }; RSADecryptImpl(const RSA* pRSA, RSAPaddingMode paddingMode); ~RSADecryptImpl(); std::size_t blockSize() const; std::streamsize transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength); std::streamsize finalize( unsigned char* output, std::streamsize length); private: const RSA* _pRSA; RSAPaddingMode _paddingMode; std::streamsize _pos; unsigned char* _pBuf; }; RSADecryptImpl::RSADecryptImpl(const RSA* pRSA, RSAPaddingMode paddingMode): _pRSA(pRSA), _paddingMode(paddingMode), _pos(0), _pBuf(0) { _pBuf = new unsigned char[blockSize()]; } RSADecryptImpl::~RSADecryptImpl() { delete _pBuf; } std::size_t RSADecryptImpl::blockSize() const { return RSA_size(_pRSA); } std::streamsize RSADecryptImpl::transform( const unsigned char* input, std::streamsize inputLength, unsigned char* output, std::streamsize outputLength) { // always fill up the buffer before decrypting! std::streamsize rsaSize = static_cast(blockSize()); poco_assert_dbg(_pos <= rsaSize); poco_assert (outputLength >= rsaSize); int rc = 0; while (inputLength > 0) { // check how many data bytes we are missing to get the buffer full poco_assert_dbg (rsaSize >= _pos); std::streamsize missing = rsaSize - _pos; if (missing == 0) { int tmp = RSA_private_decrypt(rsaSize, _pBuf, output, const_cast(_pRSA), RSA_NO_PADDING); if (tmp == -1) throwError(); rc += tmp; output += tmp; outputLength -= tmp; _pos = 0; } else { if (missing > inputLength) missing = inputLength; std::memcpy(_pBuf+_pos, input, missing); input += missing; _pos += missing; inputLength -= missing; } } return rc; } std::streamsize RSADecryptImpl::finalize(unsigned char* output, std::streamsize length) { poco_assert (length >= blockSize()); int rc = 0; if (_pos > 0) { rc = RSA_private_decrypt(_pos, _pBuf, output, const_cast(_pRSA), mapPaddingMode(_paddingMode)); if (rc == -1) throwError(); } return rc; } } RSACipherImpl::RSACipherImpl(const RSAKey& key, RSAPaddingMode paddingMode): _key(key), _paddingMode(paddingMode) { } RSACipherImpl::~RSACipherImpl() { } CryptoTransform* RSACipherImpl::createEncryptor() { return new RSAEncryptImpl(_key.impl()->getRSA(), _paddingMode); } CryptoTransform* RSACipherImpl::createDecryptor() { return new RSADecryptImpl(_key.impl()->getRSA(), _paddingMode); } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/RSADigestEngine.cpp0000644000076500001200000000625211313735446021750 0ustar guenteradmin00000000000000// // RSADigestEngine.cpp // // $Id: //poco/1.3/Crypto/src/RSADigestEngine.cpp#3 $ // // Library: Crypto // Package: RSA // Module: RSADigestEngine // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/RSADigestEngine.h" #include namespace Poco { namespace Crypto { RSADigestEngine::RSADigestEngine(const RSAKey& key, DigestType digestType): _key(key), _engine(digestType == DIGEST_MD5 ? static_cast(_md5Engine) : static_cast(_sha1Engine)), _type(digestType == DIGEST_MD5 ? NID_md5 : NID_sha1) { } RSADigestEngine::~RSADigestEngine() { } unsigned RSADigestEngine::digestLength() const { return _engine.digestLength(); } void RSADigestEngine::reset() { _engine.reset(); _digest.clear(); _signature.clear(); } const DigestEngine::Digest& RSADigestEngine::digest() { if (_digest.empty()) { _digest = _engine.digest(); } return _digest; } const DigestEngine::Digest& RSADigestEngine::signature() { if (_signature.empty()) { digest(); _signature.resize(_key.size()); unsigned sigLen = static_cast(_signature.size()); RSA_sign(_type, &_digest[0], static_cast(_digest.size()), &_signature[0], &sigLen, _key.impl()->getRSA()); // truncate _sig to sigLen if (sigLen < _signature.size()) _signature.resize(sigLen); } return _signature; } bool RSADigestEngine::verify(const DigestEngine::Digest& sig) { digest(); DigestEngine::Digest sigCpy = sig; // copy becausse RSA_verify can modify sigCpy int ret = RSA_verify(_type, &_digest[0], static_cast(_digest.size()), &sigCpy[0], static_cast(sigCpy.size()), _key.impl()->getRSA()); return ret != 0; } void RSADigestEngine::updateImpl(const void* data, unsigned length) { _engine.update(data, length); } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/RSAKey.cpp0000644000076500001200000000564511313735446020140 0ustar guenteradmin00000000000000// // RSAKey.cpp // // $Id: //poco/1.3/Crypto/src/RSAKey.cpp#4 $ // // Library: Crypto // Package: RSA // Module: RSAKey // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/RSAKey.h" #include namespace Poco { namespace Crypto { RSAKey::RSAKey(const X509Certificate& cert): _pImpl(new RSAKeyImpl(cert)) { } RSAKey::RSAKey(KeyLength keyLength, Exponent exp): _pImpl(0) { int keyLen = keyLength; unsigned long expVal = RSA_3; if (exp == EXP_LARGE) expVal = RSA_F4; _pImpl = new RSAKeyImpl(keyLen, expVal); } RSAKey::RSAKey(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase): _pImpl(new RSAKeyImpl(publicKeyFile, privateKeyFile, privateKeyPassphrase)) { } RSAKey::RSAKey(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase): _pImpl(new RSAKeyImpl(pPublicKeyStream, pPrivateKeyStream, privateKeyPassphrase)) { } RSAKey::~RSAKey() { } int RSAKey::size() const { return _pImpl->size(); } void RSAKey::save(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase) { _pImpl->save(publicKeyFile, privateKeyFile, privateKeyPassphrase); } void RSAKey::save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStream, const std::string& privateKeyPassphrase) { _pImpl->save(pPublicKeyStream, pPrivateKeyStream, privateKeyPassphrase); } const std::string& RSAKey::name() const { static const std::string n("rsa"); return n; } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/RSAKeyImpl.cpp0000644000076500001200000002012711313735446020752 0ustar guenteradmin00000000000000// // RSAKeyImpl.cpp // // $Id: //poco/1.3/Crypto/src/RSAKeyImpl.cpp#7 $ // // Library: Crypto // Package: RSA // Module: RSAKeyImpl // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/RSAKeyImpl.h" #include "Poco/Crypto/X509Certificate.h" #include "Poco/FileStream.h" #include "Poco/StreamCopier.h" #include "Poco/TemporaryFile.h" #include #include #if OPENSSL_VERSION_NUMBER >= 0x00908000L #include #endif namespace Poco { namespace Crypto { RSAKeyImpl::RSAKeyImpl(const X509Certificate& cert): _pRSA(0) { const X509* pCert = cert.certificate(); EVP_PKEY* pKey = X509_get_pubkey(const_cast(pCert)); RSA* pRSA = pKey->pkey.rsa; _pRSA = RSAPublicKey_dup(pRSA); } RSAKeyImpl::RSAKeyImpl(int keyLength, unsigned long exponent): _pRSA(0) { #if OPENSSL_VERSION_NUMBER >= 0x00908000L _pRSA = RSA_new(); int ret = 0; BIGNUM* bn = 0; try { bn = BN_new(); BN_set_word(bn, exponent); ret = RSA_generate_key_ex(_pRSA, keyLength, bn, 0); BN_free(bn); } catch (...) { BN_free(bn); throw; } if (!ret) throw Poco::InvalidArgumentException("Failed to create RSA context"); #else _pRSA = RSA_generate_key(keyLength, exponent, 0, 0); if (!_pRSA) throw Poco::InvalidArgumentException("Failed to create RSA context"); #endif } RSAKeyImpl::RSAKeyImpl( const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase): _pRSA(0) { init(publicKeyFile, privateKeyFile, privateKeyPassphrase); } RSAKeyImpl::RSAKeyImpl(std::istream* pPublicKeyStream, std::istream* pPrivateKeyStream, const std::string& privateKeyPassphrase): _pRSA(0) { // due to C lib not supporting streams, we create two temporary files std::string publicKeyFile; Poco::TemporaryFile pubFile; if (pPublicKeyStream) { if (!pubFile.createFile()) throw Poco::CreateFileException("Cannot create temporary file for writing public key"); publicKeyFile = pubFile.path(); Poco::FileOutputStream fout(publicKeyFile); Poco::StreamCopier::copyStream(*pPublicKeyStream, fout); } std::string privateKeyFile; Poco::TemporaryFile privFile; if (pPrivateKeyStream) { if (!privFile.createFile()) throw Poco::CreateFileException("Cannot create temporary file for writing private key"); privateKeyFile = privFile.path(); Poco::FileOutputStream fout(privateKeyFile); Poco::StreamCopier::copyStream(*pPrivateKeyStream, fout); } init(publicKeyFile, privateKeyFile, privateKeyPassphrase); } void RSAKeyImpl::init(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase) { poco_assert_dbg(_pRSA == 0); _pRSA = RSA_new(); if (!publicKeyFile.empty()) { BIO* out = BIO_new(BIO_s_file()); if (!out) throw Poco::IOException("Cannot create BIO for reading public key", publicKeyFile); int rc = BIO_read_filename(out, publicKeyFile.c_str()); if (rc) { RSA* pubKey = PEM_read_bio_RSAPublicKey(out, &_pRSA, 0, 0); BIO_free(out); if (!pubKey) { freeRSA(); throw Poco::FileException("Failed to load public key", publicKeyFile); } } else { freeRSA(); throw Poco::FileNotFoundException("Public key file", publicKeyFile); } } if (!privateKeyFile.empty()) { BIO* out = BIO_new(BIO_s_file()); if (!out) throw Poco::IOException("Cannot create BIO for reading private key", privateKeyFile); int rc = BIO_read_filename(out, privateKeyFile.c_str()); if (rc) { RSA* privKey = 0; if (privateKeyPassphrase.empty()) privKey = PEM_read_bio_RSAPrivateKey(out, &_pRSA, 0, 0); else privKey = PEM_read_bio_RSAPrivateKey(out, &_pRSA, 0, const_cast(privateKeyPassphrase.c_str())); BIO_free(out); if (!privKey) { freeRSA(); throw Poco::FileException("Failed to load private key", privateKeyFile); } } else { freeRSA(); throw Poco::FileNotFoundException("Private key file", privateKeyFile); } } } RSAKeyImpl::~RSAKeyImpl() { freeRSA(); } void RSAKeyImpl::freeRSA() { if (_pRSA) RSA_free(_pRSA); _pRSA = 0; } int RSAKeyImpl::size() const { return RSA_size(_pRSA); } void RSAKeyImpl::save(const std::string& publicKeyFile, const std::string& privateKeyFile, const std::string& privateKeyPassphrase) { if (!publicKeyFile.empty()) { BIO* out = BIO_new(BIO_s_file()); if (!out) throw Poco::IOException("Cannot create BIO for writing public key file", publicKeyFile); try { if (BIO_write_filename(out, const_cast(publicKeyFile.c_str()))) { if (!PEM_write_bio_RSAPublicKey(out, _pRSA)) throw Poco::WriteFileException("Failed to write public key to file", publicKeyFile); } else throw Poco::CreateFileException("Cannot create public key file"); } catch (...) { BIO_free(out); throw; } BIO_free(out); } if (!privateKeyFile.empty()) { BIO* out = BIO_new(BIO_s_file()); if (!out) throw Poco::IOException("Cannot create BIO for writing private key file", privateKeyFile); try { if (BIO_write_filename(out, const_cast(privateKeyFile.c_str()))) { int rc = 0; if (privateKeyPassphrase.empty()) rc = PEM_write_bio_RSAPrivateKey(out, _pRSA, EVP_des_ede3_cbc(), 0, 0, 0, 0); else rc = PEM_write_bio_RSAPrivateKey(out, _pRSA, EVP_des_ede3_cbc(), reinterpret_cast(const_cast(privateKeyPassphrase.c_str())), static_cast(privateKeyPassphrase.length()), 0, 0); if (!rc) throw Poco::FileException("Failed to write private key to file", privateKeyFile); } else throw Poco::CreateFileException("Cannot create private key file", privateKeyFile); } catch (...) { BIO_free(out); throw; } BIO_free(out); } } void RSAKeyImpl::save(std::ostream* pPublicKeyStream, std::ostream* pPrivateKeyStream, const std::string& privateKeyPassphrase) { if (!pPublicKeyStream && !pPrivateKeyStream) return; // due to C lib not supporting streams, we create two temporary files std::string publicKeyFile; Poco::TemporaryFile pubFile; if (pPublicKeyStream) { publicKeyFile = pubFile.path(); if (!pubFile.createFile()) throw Poco::CreateFileException("Cannot create temporary public file"); } std::string privateKeyFile; Poco::TemporaryFile privFile; if (pPrivateKeyStream) { privateKeyFile = privFile.path(); if (!privFile.createFile()) throw Poco::FileException("Cannot crate temporary private key file"); } save(publicKeyFile, privateKeyFile, privateKeyPassphrase); // now copy everything from the temp files to the original streams if (pPublicKeyStream) { Poco::FileInputStream istr(publicKeyFile); Poco::StreamCopier::copyStream(istr, *pPublicKeyStream); } if (pPrivateKeyStream) { Poco::FileInputStream istr(privateKeyFile); Poco::StreamCopier::copyStream(istr, *pPrivateKeyStream); } } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/src/X509Certificate.cpp0000644000076500001200000001673311313735446021652 0ustar guenteradmin00000000000000// // X509Certificate.cpp // // $Id: //poco/1.3/Crypto/src/X509Certificate.cpp#6 $ // // Library: Crypto // Package: Certificate // Module: X509Certificate // // Copyright (c) 2006-2009, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Crypto/X509Certificate.h" #include "Poco/StreamCopier.h" #include "Poco/String.h" #include "Poco/DateTimeParser.h" #include #include #include #include #include namespace Poco { namespace Crypto { X509Certificate::X509Certificate(std::istream& istr): _pCert(0) { load(istr); } X509Certificate::X509Certificate(const std::string& path): _pCert(0) { load(path); } X509Certificate::X509Certificate(X509* pCert): _pCert(pCert) { poco_check_ptr(_pCert); init(); } X509Certificate::X509Certificate(X509* pCert, bool shared): _pCert(pCert) { poco_check_ptr(_pCert); if (shared) { _pCert->references++; } init(); } X509Certificate::X509Certificate(const X509Certificate& cert): _issuerName(cert._issuerName), _subjectName(cert._subjectName), _pCert(cert._pCert) { _pCert = X509_dup(_pCert); } X509Certificate& X509Certificate::operator = (const X509Certificate& cert) { X509Certificate tmp(cert); swap(tmp); return *this; } void X509Certificate::swap(X509Certificate& cert) { using std::swap; swap(cert._issuerName, _issuerName); swap(cert._subjectName, _subjectName); swap(cert._pCert, _pCert); } X509Certificate::~X509Certificate() { X509_free(_pCert); } void X509Certificate::load(std::istream& istr) { poco_assert (!_pCert); std::stringstream certStream; Poco::StreamCopier::copyStream(istr, certStream); std::string cert = certStream.str(); BIO *pBIO = BIO_new_mem_buf(const_cast(cert.data()), static_cast(cert.size())); if (!pBIO) throw Poco::IOException("Cannot create BIO for reading certificate"); _pCert = PEM_read_bio_X509(pBIO, 0, 0, 0); BIO_free(pBIO); if (!_pCert) throw Poco::IOException("Faild to load certificate from stream"); init(); } void X509Certificate::load(const std::string& path) { poco_assert (!_pCert); BIO *pBIO = BIO_new(BIO_s_file()); if (!pBIO) throw Poco::IOException("Cannot create BIO for reading certificate file", path); if (!BIO_read_filename(pBIO, path.c_str())) { BIO_free(pBIO); throw Poco::OpenFileException("Cannot open certificate file for reading", path); } _pCert = PEM_read_bio_X509(pBIO, 0, 0, 0); BIO_free(pBIO); if (!_pCert) throw Poco::ReadFileException("Faild to load certificate from", path); init(); } void X509Certificate::save(std::ostream& stream) const { BIO *pBIO = BIO_new(BIO_s_mem()); if (!pBIO) throw Poco::IOException("Cannot create BIO for writing certificate"); try { if (!PEM_write_bio_X509(pBIO, _pCert)) throw Poco::IOException("Failed to write certificate to stream"); char *pData; long size; size = BIO_get_mem_data(pBIO, &pData); stream.write(pData, size); } catch (...) { BIO_free(pBIO); throw; } BIO_free(pBIO); } void X509Certificate::save(const std::string& path) const { BIO *pBIO = BIO_new(BIO_s_file()); if (!pBIO) throw Poco::IOException("Cannot create BIO for reading certificate file", path); if (!BIO_write_filename(pBIO, const_cast(path.c_str()))) { BIO_free(pBIO); throw Poco::CreateFileException("Cannot create certificate file", path); } try { if (!PEM_write_bio_X509(pBIO, _pCert)) throw Poco::WriteFileException("Failed to write certificate to file", path); } catch (...) { BIO_free(pBIO); throw; } BIO_free(pBIO); } void X509Certificate::init() { char buffer[NAME_BUFFER_SIZE]; X509_NAME_oneline(X509_get_issuer_name(_pCert), buffer, sizeof(buffer)); _issuerName = buffer; X509_NAME_oneline(X509_get_subject_name(_pCert), buffer, sizeof(buffer)); _subjectName = buffer; } std::string X509Certificate::commonName() const { return subjectName(NID_COMMON_NAME); } std::string X509Certificate::issuerName(NID nid) const { if (X509_NAME* issuer = X509_get_issuer_name(_pCert)) { char buffer[NAME_BUFFER_SIZE]; X509_NAME_get_text_by_NID(issuer, nid, buffer, sizeof(buffer)); return std::string(buffer); } else return std::string(); } std::string X509Certificate::subjectName(NID nid) const { if (X509_NAME* subj = X509_get_subject_name(_pCert)) { char buffer[NAME_BUFFER_SIZE]; X509_NAME_get_text_by_NID(subj, nid, buffer, sizeof(buffer)); return std::string(buffer); } else return std::string(); } void X509Certificate::extractNames(std::string& cmnName, std::set& domainNames) const { domainNames.clear(); if (STACK_OF(GENERAL_NAME)* names = static_cast(X509_get_ext_d2i(_pCert, NID_subject_alt_name, 0, 0))) { for (int i = 0; i < sk_GENERAL_NAME_num(names); ++i) { const GENERAL_NAME* name = sk_GENERAL_NAME_value(names, i); if (name->type == GEN_DNS) { const char* data = reinterpret_cast(ASN1_STRING_data(name->d.ia5)); std::size_t len = ASN1_STRING_length(name->d.ia5); domainNames.insert(std::string(data, len)); } } GENERAL_NAMES_free(names); } cmnName = commonName(); if (!cmnName.empty() && domainNames.empty()) { domainNames.insert(cmnName); } } Poco::DateTime X509Certificate::validFrom() const { ASN1_TIME* certTime = X509_get_notBefore(_pCert); std::string dateTime(reinterpret_cast(certTime->data)); int tzd; return DateTimeParser::parse("%y%m%d%H%M%S", dateTime, tzd); } Poco::DateTime X509Certificate::expiresOn() const { ASN1_TIME* certTime = X509_get_notAfter(_pCert); std::string dateTime(reinterpret_cast(certTime->data)); int tzd; return DateTimeParser::parse("%y%m%d%H%M%S", dateTime, tzd); } bool X509Certificate::issuedBy(const X509Certificate& issuerCertificate) const { X509* pCert = const_cast(_pCert); X509* pIssuerCert = const_cast(issuerCertificate.certificate()); EVP_PKEY* pIssuerPublicKey = X509_get_pubkey(pIssuerCert); if (!pIssuerPublicKey) throw Poco::InvalidArgumentException("Issuer certificate has no public key"); int rc = X509_verify(pCert, pIssuerPublicKey); EVP_PKEY_free(pIssuerPublicKey); return rc != 0; } } } // namespace Poco::Crypto poco-1.3.6p1-all/Crypto/testsuite/0000755000076500001200000000000011313735446017566 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/testsuite/Makefile0000644000076500001200000000055611313735446021234 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Crypto/testsuite/Makefile#4 $ # # Makefile for Poco Crypto testsuite # include $(POCO_BASE)/build/rules/global SYSLIBS += -lssl -lcrypto objects = CryptoTestSuite Driver \ CryptoTest RSATest target = testrunner target_version = 1 target_libs = PocoCrypto PocoFoundation CppUnit include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Crypto/testsuite/src/0000755000076500001200000000000011313735446020355 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Crypto/testsuite/src/CryptoTest.cpp0000644000076500001200000001367111313735446023211 0ustar guenteradmin00000000000000// // CryptoTest.cpp // // $Id: //poco/1.3/Crypto/testsuite/src/CryptoTest.cpp#3 $ // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CryptoTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/Crypto/CipherFactory.h" #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/CipherKey.h" #include "Poco/Crypto/X509Certificate.h" #include using namespace Poco::Crypto; static const std::string APPINF_PEM( "-----BEGIN CERTIFICATE-----\n" "MIIESzCCAzOgAwIBAgIBATALBgkqhkiG9w0BAQUwgdMxEzARBgNVBAMMCmFwcGlu\n" "Zi5jb20xNjA0BgNVBAoMLUFwcGxpZWQgSW5mb3JtYXRpY3MgU29mdHdhcmUgRW5n\n" "aW5lZXJpbmcgR21iSDEUMBIGA1UECwwLRGV2ZWxvcG1lbnQxEjAQBgNVBAgMCUNh\n" "cmludGhpYTELMAkGA1UEBhMCQVQxHjAcBgNVBAcMFVN0LiBKYWtvYiBpbSBSb3Nl\n" "bnRhbDEtMCsGCSqGSIb3DQEJARYeZ3VlbnRlci5vYmlsdHNjaG5pZ0BhcHBpbmYu\n" "Y29tMB4XDTA5MDUwNzE0NTY1NloXDTI5MDUwMjE0NTY1NlowgdMxEzARBgNVBAMM\n" "CmFwcGluZi5jb20xNjA0BgNVBAoMLUFwcGxpZWQgSW5mb3JtYXRpY3MgU29mdHdh\n" "cmUgRW5naW5lZXJpbmcgR21iSDEUMBIGA1UECwwLRGV2ZWxvcG1lbnQxEjAQBgNV\n" "BAgMCUNhcmludGhpYTELMAkGA1UEBhMCQVQxHjAcBgNVBAcMFVN0LiBKYWtvYiBp\n" "bSBSb3NlbnRhbDEtMCsGCSqGSIb3DQEJARYeZ3VlbnRlci5vYmlsdHNjaG5pZ0Bh\n" "cHBpbmYuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA89GolWCR\n" "KtLQclJ2M2QtpFqzNC54hUQdR6n8+DAeruH9WFwLSdWW2fEi+jrtd/WEWCdt4PxX\n" "F2/eBYeURus7Hg2ZtJGDd3je0+Ygsv7+we4cMN/knaBY7rATqhmnZWk+yBpkf5F2\n" "IHp9gBxUaJWmt/bq3XrvTtzrDXpCd4zg4zPXZ8IC8ket5o3K2vnkAOsIsgN+Ffqd\n" "4GjF4dsblG6u6E3VarGRLwGtgB8BAZOA/33mV4FHSMkc4OXpAChaK3tM8YhrLw+m\n" "XtsfqDiv1825S6OWFCKGj/iX8X2QAkrdB63vXCSpb3de/ByIUfp31PpMlMh6dKo1\n" "vf7yj0nb2w0utQIDAQABoyowKDAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAww\n" "CgYIKwYBBQUHAwMwDQYJKoZIhvcNAQEFBQADggEBAM0cpfb4BgiU/rkYe121P581\n" "ftg5Ck1PYYda1Fy/FgzbgJh2AwVo/6sn6GF79/QkEcWEgtCMNNO3LMTTddUUApuP\n" "jnEimyfmUhIThyud/vryzTMNa/eZMwaAqUQWqLf+AwgqjUsBSMenbSHavzJOpsvR\n" "LI0PQ1VvqB+3UGz0JUnBJiKvHs83Fdm4ewPAf3M5fGcIa+Fl2nU5Plzwzskj84f6\n" "73ZlEEi3aW9JieNy7RWsMM+1E8Sj2CGRZC4BM9V1Fgnsh4+VHX8Eu7eHucvfeIYx\n" "3mmLMoK4sCayL/FGhrUDw5AkWb8tKNpRXY+W60Et281yxQSeWLPIbatVzIWI0/M=\n" "-----END CERTIFICATE-----\n" ); CryptoTest::CryptoTest(const std::string& name): CppUnit::TestCase(name) { } CryptoTest::~CryptoTest() { } void CryptoTest::testEncryptDecrypt() { Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(CipherKey("aes256")); std::string in("1234567890"); std::string out = pCipher->encryptString(in, Cipher::ENC_BASE64); std::string result = pCipher->decryptString(out, Cipher::ENC_BASE64); poco_assert (in == result); } void CryptoTest::testEncryptDecryptWithSalt() { Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(CipherKey("aes256", "simplepwd", "Too much salt")); std::string in("1234567890"); std::string out = pCipher->encryptString(in, Cipher::ENC_BASE64); Cipher::Ptr pCipher2 = CipherFactory::defaultFactory().createCipher(CipherKey("aes256", "simplepwd", "Too much salt")); std::string result = pCipher2->decryptString(out, Cipher::ENC_BASE64); poco_assert (in == result); } void CryptoTest::testCertificate() { std::istringstream certStream(APPINF_PEM); X509Certificate cert(certStream); std::string subjectName(cert.subjectName()); std::string issuerName(cert.issuerName()); std::string commonName(cert.commonName()); std::string country(cert.subjectName(X509Certificate::NID_COUNTRY)); std::string localityName(cert.subjectName(X509Certificate::NID_LOCALITY_NAME)); std::string stateOrProvince(cert.subjectName(X509Certificate::NID_STATE_OR_PROVINCE)); std::string organizationName(cert.subjectName(X509Certificate::NID_ORGANIZATION_NAME)); std::string organizationUnitName(cert.subjectName(X509Certificate::NID_ORGANIZATION_UNIT_NAME)); assert (subjectName == "/CN=appinf.com/O=Applied Informatics Software Engineering GmbH/OU=Development/ST=Carinthia/C=AT/L=St. Jakob im Rosental/emailAddress=guenter.obiltschnig@appinf.com"); assert (issuerName == subjectName); assert (commonName == "appinf.com"); assert (country == "AT"); assert (localityName == "St. Jakob im Rosental"); assert (stateOrProvince == "Carinthia"); assert (organizationName == "Applied Informatics Software Engineering GmbH"); assert (organizationUnitName == "Development"); assert (cert.issuedBy(cert)); } void CryptoTest::setUp() { } void CryptoTest::tearDown() { } CppUnit::Test* CryptoTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CryptoTest"); CppUnit_addTest(pSuite, CryptoTest, testEncryptDecrypt); CppUnit_addTest(pSuite, CryptoTest, testEncryptDecryptWithSalt); CppUnit_addTest(pSuite, CryptoTest, testCertificate); return pSuite; } poco-1.3.6p1-all/Crypto/testsuite/src/CryptoTest.h0000644000076500001200000000371511313735446022654 0ustar guenteradmin00000000000000// // CryptoTest.h // // $Id: //poco/1.3/Crypto/testsuite/src/CryptoTest.h#2 $ // // Definition of the CryptoTest class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef CryptoTest_INCLUDED #define CryptoTest_INCLUDED #include "Poco/Crypto/Crypto.h" #include "CppUnit/TestCase.h" class CryptoTest: public CppUnit::TestCase { public: CryptoTest(const std::string& name); ~CryptoTest(); void testEncryptDecrypt(); void testEncryptDecryptWithSalt(); void testCertificate(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: }; #endif // CryptoTest_INCLUDED poco-1.3.6p1-all/Crypto/testsuite/src/CryptoTestSuite.cpp0000644000076500001200000000344011313735446024214 0ustar guenteradmin00000000000000// // CryptoTestSuite.cpp // // $Id: //poco/1.3/Crypto/testsuite/src/CryptoTestSuite.cpp#1 $ // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CryptoTestSuite.h" #include "CryptoTest.h" #include "RSATest.h" CppUnit::Test* CryptoTestSuite::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CryptoTestSuite"); pSuite->addTest(CryptoTest::suite()); pSuite->addTest(RSATest::suite()); return pSuite; } poco-1.3.6p1-all/Crypto/testsuite/src/CryptoTestSuite.h0000644000076500001200000000337211313735446023665 0ustar guenteradmin00000000000000// // CryptoTestSuite.h // // $Id: //poco/1.3/Crypto/testsuite/src/CryptoTestSuite.h#1 $ // // Definition of the CryptoTestSuite class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef CryptoTestSuite_INCLUDED #define CryptoTestSuite_INCLUDED #include "CppUnit/TestSuite.h" class CryptoTestSuite { public: static CppUnit::Test* suite(); }; #endif // CryptoTestSuite_INCLUDED poco-1.3.6p1-all/Crypto/testsuite/src/Driver.cpp0000644000076500001200000000317511313735446022322 0ustar guenteradmin00000000000000// // Driver.cpp // // $Id: //poco/1.3/Crypto/testsuite/src/Driver.cpp#1 $ // // Console-based test driver for Poco Crypto. // // Copyright (c) 2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CppUnit/TestRunner.h" #include "CryptoTestSuite.h" CppUnitMain(CryptoTestSuite) poco-1.3.6p1-all/Crypto/testsuite/src/RSATest.cpp0000644000076500001200000002001411313735446022343 0ustar guenteradmin00000000000000// // RSATest.cpp // // $Id: //poco/1.3/Crypto/testsuite/src/RSATest.cpp#4 $ // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "RSATest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/Crypto/RSADigestEngine.h" #include "Poco/Crypto/CipherFactory.h" #include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/X509Certificate.h" #include using namespace Poco::Crypto; static const std::string anyPem( "-----BEGIN CERTIFICATE-----\r\n" "MIICaDCCAdECCQCzfxSsk7yaLjANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJB\r\n" "VDESMBAGA1UECBMJQ2FyaW50aGlhMRIwEAYDVQQHEwlTdC4gSmFrb2IxDzANBgNV\r\n" "BAoTBkFwcEluZjEPMA0GA1UEAxMGQXBwSW5mMRowGAYJKoZIhvcNAQkBFgthcHBA\r\n" "aW5mLmNvbTAeFw0wNjAzMDExMzA3MzFaFw0wNjAzMzExMzA3MzFaMH4xCzAJBgNV\r\n" "BAYTAkFUMRIwEAYDVQQIEwlDYXJpbnRoaWExETAPBgNVBAcTCFN0IEpha29iMRww\r\n" "GgYDVQQKExNBcHBsaWVkIEluZm9ybWF0aWNzMQowCAYDVQQDFAEqMR4wHAYJKoZI\r\n" "hvcNAQkBFg9pbmZvQGFwcGluZi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ\r\n" "AoGBAJHGyXDHyCYoWz+65ltNwwZbhwOGnxr9P1WMATuFJh0bPBZxKbZRdbTm9KhZ\r\n" "OlvsEIsfgiYdsxURYIqXfEgISYLZcZY0pQwGEOmB+0NeC/+ENSfOlNSthx6zSVlc\r\n" "zhJ7+dJOGwepHAiLr1fRuc5jogYLraE+lKTnqAAFfzwvti77AgMBAAEwDQYJKoZI\r\n" "hvcNAQEFBQADgYEAY/ZoeY1ukkEJX7259NeoVM0oahlulWV0rlCqyaeosOiDORPT\r\n" "m6X1w/5MTCf9VyaD1zukoSZ4QqNVjHFXcXidbB7Tgt3yRuZ5PC5LIFCDPv9mgPne\r\n" "mUA70yfctNfza2z3ZiQ6NDkW3mZX+1tmxYIrJQIrkVeYeqf1Gh2nyZrUMcE=\r\n" "-----END CERTIFICATE-----\r\n" "-----BEGIN RSA PRIVATE KEY-----\r\n" "Proc-Type: 4,ENCRYPTED\r\n" "DEK-Info: DES-EDE3-CBC,E7AE93C9E49184EA\r\n" "\r\n" "A2IqzNcWs+I5vzV+i+woDk56+yr58eU0Onw8eEvXkLjnSc58JU4327IF7yUbKWdW\r\n" "Q7BYGGOkVFiZ7ANOwviDg5SUhxRDWCcW8dS6/p1vfdQ1C3qj2OwJjkpg0aDBIzJn\r\n" "FzgguT3MF3ama77vxv0S3kOfmCj62MLqPGpj5pQ0/1hefRFbL8oAX8bXUN7/rmGM\r\n" "Zc0QyzFZv2iQ04dY/6TNclwKPB4H0On4K+8BMs3PRkWA0clCaQaFO2+iwnk3XZfe\r\n" "+MsKUEbLCpAQeYspYv1cw38dCdWq1KTP5aJk+oXgwjfX5cAaPTz74NTqTIsCcaTD\r\n" "3vy7ukJYFlDR9Kyo7z8rMazYrKJslhnuRH0BhK9st9McwL957j5tZmrKyraCcmCx\r\n" "dMAGcsis1va3ayYZpIpFqA4EhYrTM+6N8ZRfUap20+b5IQwHfTQDejUhL6rBwy7j\r\n" "Ti5yD83/itoOMyXq2sV/XWfVD5zk/P5iv22O1EAQMhhnPB9K/I/JhuSGQJfn3cNh\r\n" "ykOUYT0+vDeSeEVa+FVEP1W35G0alTbKbNs5Tb8KxJ3iDJUxokM//SvPXZy9hOVX\r\n" "Y05imB04J15DaGbAHlNzunhuJi7121WV/JRXZRW9diE6hwpD8rwqi3FMuRUmy7U9\r\n" "aFA5poKRAYlo9YtZ3YpFyjGKB6MfCQcB2opuSnQ/gbugV41m67uQ4CDwWLaNRkTb\r\n" "GlsMBNcHnidg15Bsat5HaB7l250ukrI13Uw1MYdDUzaS3gPfw9aC4F2w0p3U+DPH\r\n" "80/zePxtroR7T4/+rI136Rl+aMXDMOEGCX1TVP8rjuZzuRyUSUKC8Q==\r\n" "-----END RSA PRIVATE KEY-----\r\n" "-----BEGIN CERTIFICATE-----\r\n" "MIICXTCCAcYCCQC1Vk/N8qR4AjANBgkqhkiG9w0BAQUFADBzMQswCQYDVQQGEwJB\r\n" "VDESMBAGA1UECBMJQ2FyaW50aGlhMRIwEAYDVQQHEwlTdC4gSmFrb2IxDzANBgNV\r\n" "BAoTBkFwcEluZjEPMA0GA1UEAxMGQXBwSW5mMRowGAYJKoZIhvcNAQkBFgthcHBA\r\n" "aW5mLmNvbTAeFw0wNjAyMjcxMzI3MThaFw0wNjAzMjkxMzI3MThaMHMxCzAJBgNV\r\n" "BAYTAkFUMRIwEAYDVQQIEwlDYXJpbnRoaWExEjAQBgNVBAcTCVN0LiBKYWtvYjEP\r\n" "MA0GA1UEChMGQXBwSW5mMQ8wDQYDVQQDEwZBcHBJbmYxGjAYBgkqhkiG9w0BCQEW\r\n" "C2FwcEBpbmYuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsFXiPuicN\r\n" "Im4oJwF8NuaFN+lgYwcZ6dAO3ILIR3kLA2PxF8HSQLfF8J8a4odZhLhctIMAKTxm\r\n" "k0w8TW5qhL8QLdGzY9vzvkgdKOkan2t3sMeXJAfrM1AphTsmgntAQazGZjOj5p4W\r\n" "jDnxQ+VXAylqwjHh49eSBxM3wgoscF4iLQIDAQABMA0GCSqGSIb3DQEBBQUAA4GB\r\n" "AIpfLdXiKchPvFMhQS8xTtXvrw5dVL3yImUMYs4GQi8RrjGmfGB3yMAR7B/b8v4a\r\n" "+ztfusgWAWiUKuSGTk4S8YB0fsFlmOv0WDr+PyZ4Lui/a8opbyzGE7rqpnF/s0GO\r\n" "M7uLCNNwIN7WhmxcWV0KZU1wTppoSWPJda1yTbBzF9XP\r\n" "-----END CERTIFICATE-----\r\n" ); RSATest::RSATest(const std::string& name): CppUnit::TestCase(name) { } RSATest::~RSATest() { } void RSATest::testNewKeys() { RSAKey key(RSAKey::KL_1024, RSAKey::EXP_SMALL); std::ostringstream strPub; std::ostringstream strPriv; key.save(&strPub, &strPriv, "testpwd"); std::string pubKey = strPub.str(); std::string privKey = strPriv.str(); // now do the round trip std::istringstream iPub(pubKey); std::istringstream iPriv(privKey); RSAKey key2(&iPub, &iPriv, "testpwd"); std::istringstream iPriv2(privKey); RSAKey key3(0, &iPriv2, "testpwd"); std::ostringstream strPub3; key3.save(&strPub3); std::string pubFromPrivate = strPub3.str(); assert (pubFromPrivate == pubKey); } void RSATest::testSign() { std::string msg("Test this sign message"); RSAKey key(RSAKey::KL_2048, RSAKey::EXP_LARGE); RSADigestEngine eng(key); eng.update(msg.c_str(), msg.length()); const Poco::DigestEngine::Digest& sig = eng.signature(); std::string hexDig = Poco::DigestEngine::digestToHex(sig); // verify std::ostringstream strPub; key.save(&strPub); std::string pubKey = strPub.str(); std::istringstream iPub(pubKey); RSAKey keyPub(&iPub); RSADigestEngine eng2(key); eng2.update(msg.c_str(), msg.length()); assert (eng2.verify(sig)); } void RSATest::testSignManipulated() { std::string msg("Test this sign message"); std::string msgManip("Test that sign message"); RSAKey key(RSAKey::KL_2048, RSAKey::EXP_LARGE); RSADigestEngine eng(key); eng.update(msg.c_str(), msg.length()); const Poco::DigestEngine::Digest& sig = eng.signature(); std::string hexDig = Poco::DigestEngine::digestToHex(sig); // verify std::ostringstream strPub; key.save(&strPub); std::string pubKey = strPub.str(); std::istringstream iPub(pubKey); RSAKey keyPub(&iPub); RSADigestEngine eng2(key); eng2.update(msgManip.c_str(), msgManip.length()); assert (!eng2.verify(sig)); } void RSATest::createRSACipher() { Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(RSAKey(RSAKey::KL_1024,RSAKey::EXP_SMALL)); std::string val("lets do some encryption"); std::string enc = pCipher->encryptString(val); std::string dec = pCipher->decryptString(enc); assert (dec == val); } void RSATest::createRSACipherLarge() { Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(RSAKey(RSAKey::KL_1024,RSAKey::EXP_SMALL)); std::string val(16385, 'x'); std::string enc = pCipher->encryptString(val); std::string dec = pCipher->decryptString(enc); assert (dec == val); } void RSATest::testCertificate() { std::istringstream str(anyPem); X509Certificate cert(str); RSAKey key(cert); Cipher::Ptr pCipher = CipherFactory::defaultFactory().createCipher(key); std::string val("lets do some encryption"); std::string enc = pCipher->encryptString(val); } void RSATest::setUp() { } void RSATest::tearDown() { } CppUnit::Test* RSATest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RSATest"); CppUnit_addTest(pSuite, RSATest, testNewKeys); CppUnit_addTest(pSuite, RSATest, testSign); CppUnit_addTest(pSuite, RSATest, testSignManipulated); CppUnit_addTest(pSuite, RSATest, createRSACipher); CppUnit_addTest(pSuite, RSATest, createRSACipherLarge); CppUnit_addTest(pSuite, RSATest, testCertificate); return pSuite; } poco-1.3.6p1-all/Crypto/testsuite/src/RSATest.h0000644000076500001200000000375511313735446022025 0ustar guenteradmin00000000000000// // RSATest.h // // $Id: //poco/1.3/Crypto/testsuite/src/RSATest.h#1 $ // // Definition of the RSATest class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef RSATest_INCLUDED #define RSATest_INCLUDED #include "Poco/Crypto/Crypto.h" #include "CppUnit/TestCase.h" class RSATest: public CppUnit::TestCase { public: RSATest(const std::string& name); ~RSATest(); void testNewKeys(); void testSign(); void testSignManipulated(); void createRSACipher(); void createRSACipherLarge(); void testCertificate(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: }; #endif // RSATest_INCLUDED poco-1.3.6p1-all/Crypto/testsuite/src/WinDriver.cpp0000644000076500001200000000345511313735446023001 0ustar guenteradmin00000000000000// // WinDriver.cpp // // $Id: //poco/1.3/Crypto/testsuite/src/WinDriver.cpp#1 $ // // Windows test driver for Poco Crypto. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "WinTestRunner/WinTestRunner.h" #include "CryptoTestSuite.h" class TestDriver: public CppUnit::WinTestRunnerApp { void TestMain() { CppUnit::WinTestRunner runner; runner.addTest(CryptoTestSuite::suite()); runner.run(); } }; TestDriver theDriver; poco-1.3.6p1-all/Crypto/testsuite/TestSuite.vmsbuild0000644000076500001200000000020611313735446023264 0ustar guenteradmin00000000000000# # TestSuite.vmsbuild # # $Id: //poco/Main/template/TestSuite.vmsbuild#3 $ # EXE=TestRunner CryptoTestSuite Driver poco-1.3.6p1-all/Crypto/testsuite/TestSuite_VS71.vcproj0000644000076500001200000002056711313735446023536 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/testsuite/TestSuite_VS80.vcproj0000644000076500001200000002256511313735446023536 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Crypto/testsuite/TestSuite_VS90.vcproj0000644000076500001200000002253411313735446023533 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/0000755000076500001200000000000011313735447015127 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/Data.vmsbuild0000644000076500001200000000056111313735446017550 0ustar guenteradmin00000000000000# # Data.vmsbuild # # $Id: //poco/1.3/Data/Data.vmsbuild#1 $ # LIB=PocoData AbstractBinder AbstractBinding AbstractExtraction AbstractExtractor AbstractPreparation AbstractPrepare BLOB BLOBStream DataException Limit PooledSessionHolder PooledSessionImpl Range Session SessionFactory SessionImpl SessionInstantiator SessionPool Statement StatementCreator StatementImpl poco-1.3.6p1-all/Data/Data_VS71.sln0000644000076500001200000000447511313735446017307 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Data", "Data_VS71.vcproj", "{240E83C3-368D-11DB-9FBC-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS71.vcproj", "{24134877-368D-11DB-9FBC-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {240E83C3-368D-11DB-9FBC-00123FC423B5} = {240E83C3-368D-11DB-9FBC-00123FC423B5} EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared debug_static = debug_static release_static = release_static EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_static.Build.0 = release_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_static.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/Data_VS71.vcproj0000644000076500001200000002556611313735446020022 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/Data_VS80.sln0000644000076500001200000000460111313735446017276 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Data", "Data_VS80.vcproj", "{240E83C3-368D-11DB-9FBC-00123FC423B5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS80.vcproj", "{24134877-368D-11DB-9FBC-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {240E83C3-368D-11DB-9FBC-00123FC423B5} = {240E83C3-368D-11DB-9FBC-00123FC423B5} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 debug_static|Win32 = debug_static|Win32 release_shared|Win32 = release_shared|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/Data_VS80.vcproj0000644000076500001200000002773411313735446020021 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/Data_vs90.sln0000644000076500001200000000460211313735446017400 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Data", "Data_vs90.vcproj", "{240E83C3-368D-11DB-9FBC-00123FC423B5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs90.vcproj", "{24134877-368D-11DB-9FBC-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {240E83C3-368D-11DB-9FBC-00123FC423B5} = {240E83C3-368D-11DB-9FBC-00123FC423B5} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {240E83C3-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {24134877-368D-11DB-9FBC-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/Data_vs90.vcproj0000644000076500001200000002777411313735446020126 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/doc/0000755000076500001200000000000011313735446015673 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/doc/00200-DataUserManual.page0000644000076500001200000005207511313735446022047 0ustar guenteradmin00000000000000POCO Data User Guide POCO Data Library !!!First Steps POCO Data is POCO's database abstraction layer which allows users to easily send/retrieve data to/from various different SQL databases. The following complete example shows how to use it: #include "Poco/Data/Common.h" #include "Poco/Data/SQLite/Connector.h" #include using namespace Poco::Data; void init() { SQLite::Connector::registerConnector(); } void shutdown() { SQLite::Connector::unregisterConnector(); } int main(int argc, char* argv[]) { init(); Session ses("SQLite", "sample.db"); int count = 0; ses << "SELECT COUNT(*) FROM PERSON", into(count), now; std::cout << "People in DB " << count; shutdown(); } ---- The above example is pretty much self explanatory. The <[Poco/Data/Common.h]> file pulls in some common includes, the SQLite::Connector is used to register the SQLite connector so that we can later create an SQLite session via the SessionFactory. The two-argument constructor Sesssion ses("SQLite", "sample.db"); ---- is actually equivalent to: Session ses(SessionFactory::instance()::create("SQLite", "sample.db")); ---- The << operator is used to send SQL statements to the Session, the <*into(count)*> simply informs the session where to store the result of the query. Take note of the at the end of the SQL statement. It is required, otherwise the statement would not be executed. The <* <[ using namespace Poco::Data ]> *> is for convenience only but highly recommended for good readable code (while <* <[ ses << "SELECT COUNT(*) FROM PERSON", Poco::Data::into(count), Poco::Data::now; ]> *> is valid, it simply looks... strange). The remainder of this tutorial is split up into the following parts: * Creating Sessions * Inserting and Retrieving Data: the magic of <* into *> and <*use*> * Working with Statements * Working with Collections: vector, set, multiset, map and multimap * Working with Limits * Working with complex data types: how to map C++ objects to a database table !!!Creating Sessions Sessions are always created via the SessionFactory create method, or implicitly via the two-argument Session constructor. Session create(const std::string& connectorKey, const std::string& connectionString); ---- The first parameter contains the type of the Session one wants to create. For the moment "SQLite" is supported directly, and via the ODBC driver support for Oracle, SQLite, DB2, SQLServer and PostgreSQL is available. The second parameter contains the (connector-specific) connection string. In the case of SQLite, the location of the database file is sufficient. !!!Inserting and Retrieving Data Inserting data works by <* using *> the content of other variables. Assume we have a table that stores only forenames: ForeName (Name VARCHAR(30)) ---- If we want to insert one single forename we could simply write: std::string aName("Peter"); ses << "INSERT INTO FORENAME VALUES(" << aName << ")", now; ---- Well, we could do that, but we won't. A much better solution is to use and connect each placeholder via a expression with a variable that will provide the value during execution. Placeholders are recognized by having a in front of their name. Rewriting the above code now simply gives std::string aName("Peter"); ses << "INSERT INTO FORENAME VALUES(:name)", use(aName), now; ---- In this example the expression matches the <* :name *> with the <*Peter*> value. Note that apart from the nicer syntax, the real benefit of placeholders - which is performance - doesn't show here. Check the <*Working with Statements*> section to find out more. Retrieving data from the Database works similar. The expression matches the returned database values to C++ objects, it also allows to provide a default value in case null data is returned from the database: std::string aName; ses << "SELECT NAME FROM FORENAME", into(aName), now; // the default is the empty string ses << "SELECT NAME FROM FORENAME", into(aName, "default"), now; ---- It is also possible to combine into and use expressions: std::string aName; std::string match("Peter") ses << "SELECT NAME FROM FORENAME WHERE NAME=:name", into(aName), use(match), now; poco_assert (aName == match); ---- Typically, tables will not be so trivial, ie. they will have more than one column which allows for more than one into/use. Lets assume we have a Person table that contains an age, a first and a last name: std::string firstName("Peter"; std::string lastName("Junior"); int age = 0; ses << INSERT INTO PERSON VALUES (:fn, :ln, :age)", use(firstName), use(lastName), use(age), now; ses << "SELECT (firstname, lastname, age) FROM Person", into(firstName), into(lastName), into(age), now; ---- Most important here is the of the into and use expressions. The first placeholder is matched by the first <*use*>, the 2nd by the 2nd <*use*> etc. The same is true for the <*into*> statement. We select <*firstname*> as the first column of the result set, thus <*into(firstName)*> must be the first into clause. !! Handling NULL entries A common case with databases are optional data fields that can contain NULL. To accomodate for NULL, the <*into*> expression allows you to define default values. For example, assume that age is such an optional field and we want to provide as default value which is done by writing : std::string firstName("Peter"; std::string lastName("Junior"); int age = 0; ses << INSERT INTO PERSON VALUES (:fn, :ln, :age)", use(firstName), use(lastName), use(age), now; ses << "SELECT (firstname, lastname, age) FROM Person", into(firstName), into(lastName), into(age, -1), now; ---- While you can achieve the same effect by initializing age previously to -1 (<*int age = -1*>), this won't work with collection types. Here you must provide the second parameter to init. Otherwise, values will be initialized to compiler specific values. !!!Working with Statements We often mentioned the term <*Statement*> in the previous section, yet we only worked with database session objects so far, or at least, that's what you have been made believe ;-). In reality, you have already worked with Statements. Lets take a look at the method signature of the << operator at Session: template Statement Session::operator << (const T& t) ---- Simply ignore the template stuff in front, you won't need it. The only thing that counts here is that the operator <[ << ]> creates a <*Statement*> internally and returns it. What happened in the previous examples is that the returned Statement was never assigned to a variable but simply passed on to the <*now*> part which executed the statement. Afterwards the statement was destroyed. Let's take one of the previous examples and change it so that we assign the statement: std::string aName("Peter"); Statement stmt = ( ses << "INSERT INTO FORENAME VALUES(:name)", use(aName) ); ---- Note that we must put brackets around the right part of the assignment, otherwise the compiler will complain. If you don't like the above syntax, the following alternative is equivalent: Statement stmt(ses); stmt << "INSERT INTO FORENAME VALUES(:name)", use(aName); ---- What did we achieve by assigning the statement to a variable? Well, currently nothing, apart that we can control when to <*execute*>: std::string aName("Peter"); Statement stmt = ( ses << "INSERT INTO FORENAME VALUES(:name)", use(aName) ); stmt.execute(); poco_assert (stmt.done()); ---- By calling <*execute*> we asserted that our query was executed and that the value was inserted. The check to <[stmt.done()]> simply guarantees that the statement was fully completed. !!Prepared Statements A prepared statement is created by omitting the <*now*> clause. Statement stmt = ( ses << "INSERT INTO FORENAME VALUES(:name)", use(aName) ); ---- The advantage of a prepared statement is performance. Assume the following loop: std::string aName(); Statement stmt = ( ses << "INSERT INTO FORENAME VALUES(:name)", use(aName) ); for (int i = 0; i < 100; ++i) { aName.append("x"); stmt.execute(); } ---- Instead of creating and parsing the Statement 100 times, we only do this once and then use the placeholder in combination with the <*use*> clause to insert 100 different values into the database. Still, this isn't the best way to insert a collection of values into a database. !!Things NOT To Do expects as input a parameter, which is bound later during execution. Thus, one can only use variables, but never constants. The following code will very likely fail (but this is platform/compiler dependent and also depends if your building in release or debug mode, it will work from Monday to Thursday but will always fail on Friday, so shortly spoken: the kind of bugs software developers <*really*> love): Statement stmt = (ses << INSERT INTO PERSON VALUES (:fn, :ln, :age)", use("Peter"), use("Junior"), use(4)); //ERR! stmt.execute(); ---- The constant values <*Junior*>, <*Peter*> and <*4*> must be assigned to variables prior, otherwise their values will be invalid when execute is called. !!!Collection Support If one needs to handle many values at once, one ought to use a collection class. Per default, the following collection types are supported: * vector: no requirements * set: the < operator must be supported by the datatype. Note that duplicate key/value pairs are ignored. * multiset: the < operator must be supported by the datatype * map: the () operator must be supported by the datatype and return the key of the object. Note that duplicate key/value pairs are ignored. * multimap: the () operator must be supported by the datatype and return the key of the object A bulk insert example via vector would be: std::string aName(""); std::vector data; for (int i = 0; i < 100; ++i) { aName.append("x"); data.push_back(aName); } ses << "INSERT INTO FORENAME VALUES(:name)", use(data), now; ---- The same example would work with set or multiset but not with map and multimap (std::string has no () operator). Note that requires <*non-empty*> collections! Now reconsider the following example: std::string aName; ses << "SELECT NAME FROM FORENAME", into(aName), now; ---- Previously, it worked because the table contained only one single entry but now the database table contains at least 100 strings, yet we only offer storage space for one single result. Thus, the above code will fail and throw an exception. One possible way to handle this is: std::vector names; ses << "SELECT NAME FROM FORENAME", into(names), now; ---- And again, instead of vector, one could use set or multiset. !!!The limit clause Working with collections might be convenient to bulk process data but there is also the risk that large operations will block your application for a very long time. In addition, you might want to have better fine-grained control over your query, e.g. you only want to extract a subset of data until a condition is met. To elevate that problem, one can use the keyword. Let's assume we are retrieving thousands of rows from a database to render the data to a GUI. To allow the user to stop fetching data any time (and to avoid having the user franatically click inside the GUI because it doesn't show anything for seconds), we have to partition this process: std::vector names; ses << "SELECT NAME FROM FORENAME", into(names), limit(50), now; ---- The above example will retrieve up to 50 rows from the database (note that returning nothing is valid!) and <*append*> it to the names collection, i.e. the collection is not cleared! If one wants to make sure that 50 rows are returned one must set the 2nd limit parameter (which per default is set to <*false*>) to <*true*>: std::vector names; ses << "SELECT NAME FROM FORENAME", into(names), limit(50, true), now; ---- Iterating over a complete result collection is done via the Statement object until statement.done() returns true. For the next example, we assume that our system knows about 101 forenames: std::vector names; Statement stmt = (ses << "SELECT NAME FROM FORENAME", into(names), limit(50)); stmt.execute(); //names.size() == 50 poco_assert (!stmt.done()); stmt.execute(); //names.size() == 100 poco_assert (!stmt.done()); stmt.execute(); //names.size() == 101 poco_assert (stmt.done()); ---- We previously stated that if no data is returned this is valid too. Thus, executing the following statement on an empty database table will work: std::string aName; ses << "SELECT NAME FROM FORENAME", into(aName), now; ---- To guarantee that at least one valid result row is returned use the clause: std::string aName; ses << "SELECT NAME FROM FORENAME", into(aName), lowerLimit(1), now; ---- If the table is now empty, an exception will be thrown. If the query succeeds, aName is guaranteed to be initialized. Note that is only the short name for . To iterate over a result set step-by-step, e.g. one wants to avoid using a collection class, one would write: std::string aName; Statement stmt = (ses << "SELECT NAME FROM FORENAME", into(aName), lowerLimit(1), upperLimit(1)); while (!stmt.done()) stmt.execute(); ---- And for the lazy ones, there is the command: std::string aName; Statement stmt = (ses << "SELECT NAME FROM FORENAME", into(aName), range(1,1)); while (!stmt.done()) stmt.execute(); ---- The third parameter to range is an optional boolean value which specifies if the upper limit is a hard limit, ie. if the amount of rows returned by the query must match exactly. Per default exact matching is off. !!!Complex Data Type Mapping All the previous examples were contented to work with only the most basic data types: integer, string, ... a situation, unlikely to occur in real-world scenarios. Assume you have a class Person: class Person { public: // default constructor+destr. // getter and setter methods for all members [...] bool operator <(const Person& p) const /// we need this for set and multiset support { return _socialSecNr < p._socialSecNr; } Poco::UInt64 operator()() const /// we need this operator to return the key for the map and multimap { return _socialSecNr; } private: std::string _firstName; std::string _lastName; Poco::UInt64 _socialSecNr; } ---- Ideally, one would like to use a Person as simple as one used a string. All that is needed is a template specialization of the <*TypeHandler*> template. Note that template specializations must be declared in the as the original template, i.e. <*Poco::Data*>. The template specialization must implement the following methods: namespace Poco { namespace Data { template <> class TypeHandler { public: static std::size_t size() { return 3; // we handle three columns of the Table! } static void bind(std::size_t pos, const Person& obj, AbstractBinder* pBinder) { poco_assert_dbg (pBinder != 0); // the table is defined as Person (FirstName VARCHAR(30), lastName VARCHAR, SocialSecNr INTEGER(3)) // Note that we advance pos by the number of columns the datatype uses! For string/int this is one. TypeHandler::bind(pos++, obj.getFirstName(), pBinder); TypeHandler::bind(pos++, obj.getLastName(), pBinder); TypeHandler::bind(pos++, obj.getSocialSecNr(), pBinder); } static void prepare(std::size_t pos, const Person& obj, AbstractPreparation* pPrepare) { poco_assert_dbg (pBinder != 0); // the table is defined as Person (FirstName VARCHAR(30), lastName VARCHAR, SocialSecNr INTEGER(3)) // Note that we advance pos by the number of columns the datatype uses! For string/int this is one. TypeHandler::prepare(pos++, obj.getFirstName(), pPrepare); TypeHandler::prepare(pos++, obj.getLastName(), pPrepare); TypeHandler::prepare(pos++, obj.getSocialSecNr(), pPrepare); } static void extract(std::size_t pos, Person& obj, const Person& defVal, AbstractExtractor* pExt) /// obj will contain the result, defVal contains values we should use when one column is NULL { poco_assert_dbg (pExt != 0); std::string firstName; std::string lastName; Poco::UInt64 socialSecNr = 0; TypeHandler::extract(pos++, firstName, defVal.getFirstName(), pExt); TypeHandler::extract(pos++, lastName, defVal.getLastName(), pExt); TypeHandler::extract(pos++, socialSecNr, defVal.getSocialSecNr(), pExt); obj.setFirstName(firstName); obj.setLastName(lastName); obj.setSocialSecNr(socialSecNr); } }; } } // namespace Poco::Data ---- And that's all you have to do. Working with Person is now as simple as working with a string: std::map people; ses << "SELECT * FROM Person", into(people), now; ---- !!!RecordSet The Poco::Data::RecordSet class provides a generic way to work with database tables. Using a <[RecordSet]>, one can: - iterate over all columns and rows in a table - obtain meta information about columns (such as name, type, length, etc.) To work with a RecordSet, first create a Statement, execute it, and create the RecordSet from the Statement, as follows: Statement select(session); select << "SELECT * FROM Person"; select.execute(); RecordSet rs(select); ---- The number of rows in the RecordSet can be limited by specifying a limit for the Statement. Following example demonstrates how to iterate over all rows and columns in a RecordSet: bool more = rs.moveFirst(); while (more) { for (std::size_t col = 0; col < cols; ++col) { std::cout << rs[col].convert() << " "; } std::cout << std::endl; more = rs.moveNext(); } ---- As mentioned above, the number of rows retrieved into a RecordSet at a time can be limited using the <[limit]> or <[range]> clause. Iterating over all rows in a table a bunch of rows at a time can thus be done as follows: Statement select(session); select << "SELECT * FROM Person", range(0, 10); RecordSet rs(select); while (!select.done()) { select.execute(); bool more = rs.moveFirst(); while (more) { for (std::size_t col = 0; col < cols; ++col) { std::cout << rs[col].convert() << " "; } std::cout << std::endl; more = rs.moveNext(); } } ---- !!!Tuples Poco::Tuple and vectors of Poco::Tuple provide a convenient way to work with rows when column types are known, because TypeHandlers for them are readily available. Consider the following example: typedef Poco::Tuple Person; typedef std::vector People; People people; people.push_back(Person("Bart Simpson", "Springfield", 12)); people.push_back(Person("Lisa Simpson", "Springfield", 10)); Statement insert(session); insert << "INSERT INTO Person VALUES(:name, :address, :age)", use(people), now; ---- Of course, tuples can also be used in queries: Statement select(session); select << "SELECT Name, Address, Age FROM Person", into(people), now; for (People::const_iterator it = people.begin(); it != people.end(); ++it) { std::cout << "Name: " << it->get<0>() << ", Address: " << it->get<1>() << ", Age: " << it->get<2>() < implementation is rather straight-forward. Just implement the following interfaces: * Poco::Data::AbstractBinder * Poco::Data::AbstractExtractor * Poco::Data::StatementImpl * Poco::Data::SessionImpl * Poco::Data::Connector * optional: Poco::Data::AbstractPreparation It is recommended to implement the classes from top to down (ie. start with Binder and Extractor) and to use a namespace that has <[ Poco::Data ]> as parent, e.g.<[ Poco::Data::SQLite ]>. !!!AbstractBinder An <[AbstractBinder]> is a class that maps values to placeholders. It is also responsible to bind primitive C++ data types to database data types. The constructor of the subclass should receive everything needed to bind variables to placeholders by position. An example taken from the SQLite implementation would be: Binder::Binder(sqlite3_stmt* pStmt): _pStmt(pStmt) { } void Binder::bind(std::size_t pos, const Poco::Int32& val) { int rc = sqlite3_bind_int(_pStmt, (int)pos, val); checkReturn(rc); } void Binder::bind(std::size_t pos, const Poco::Int16& val) { Poco::Int32 tmp = val; bind(pos, tmp); } ---- SQLite only needs an <*sqlite3_stmt*> as internal state, Int32 is bound via <*sqlite3_bind_int*> and Int16 values are mapped to Int32 values. !!Complete Interface All methods are public. AbstractBinder(); /// Creates the AbstractBinder. virtual ~AbstractBinder(); /// Destroys the AbstractBinder. virtual void bind(std::size_t pos, const Poco::Int8 &val) = 0; /// Binds an Int8. virtual void bind(std::size_t pos, const Poco::UInt8 &val) = 0; /// Binds an UInt8. virtual void bind(std::size_t pos, const Poco::Int16 &val) = 0; /// Binds an Int16. virtual void bind(std::size_t pos, const Poco::UInt16 &val) = 0; /// Binds an UInt16. virtual void bind(std::size_t pos, const Poco::Int32 &val) = 0; /// Binds an Int32. virtual void bind(std::size_t pos, const Poco::UInt32 &val) = 0; /// Binds an UInt32. virtual void bind(std::size_t pos, const Poco::Int64 &val) = 0; /// Binds an Int64. virtual void bind(std::size_t pos, const Poco::UInt64 &val) = 0; /// Binds an UInt64. virtual void bind(std::size_t pos, const bool &val) = 0; /// Binds a boolean. virtual void bind(std::size_t pos, const float &val) = 0; /// Binds a float. virtual void bind(std::size_t pos, const double &val) = 0; /// Binds a double. virtual void bind(std::size_t pos, const char &val) = 0; /// Binds a single character. virtual void bind(std::size_t pos, const char* const &pVal) = 0; /// Binds a const char ptr. virtual void bind(std::size_t pos, const std::string& val) = 0; /// Binds a string. virtual void bind(std::size_t pos, const BLOB& val) = 0; /// Binds a BLOB. virtual void reset() = 0; /// Resets the internal state, called before a rebind ---- !!!AbstractExtractor An <[AbstractExtractor]> takes a result row and extracts from a given position one single value. It performs the reverse operation to the <[AbstractBinder]>, ie. it maps database types to primitive C++ types. An <[AbstractExtractor]> also has to handle null values. If it detects a null value, it is not allowed to modify the incoming value but will simply return false. An example taken from the SQLite implementation: Extractor::Extractor(sqlite3_stmt* pStmt): _pStmt(pStmt) { } bool Extractor::extract(std::size_t pos, Poco::Int32& val) { if (isNull(pos<[ return false; val = sqlite3_column_int(_pStmt, (int)pos); return true; } bool Extractor::extract(std::size_t pos, Poco::Int16& val) { if (isNull(pos<[ return false; val = sqlite3_column_int(_pStmt, (int)pos); return true; } ---- !!Complete Interface All methods are public. AbstractExtractor(); /// Creates the AbstractExtractor. virtual ~AbstractExtractor(); /// Destroys the AbstractExtractor. virtual bool extract(std::size_t pos, Poco::Int8& val) = 0; /// Extracts an Int8. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt8& val) = 0; /// Extracts an UInt8. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::Int16& val) = 0; /// Extracts an Int16. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt16& val) = 0; /// Extracts an UInt16. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::Int32& val) = 0; /// Extracts an Int32. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt32& val) = 0; /// Extracts an UInt32. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::Int64& val) = 0; /// Extracts an Int64. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt64& val) = 0; /// Extracts an UInt64. Returns false if null was received. virtual bool extract(std::size_t pos, bool& val) = 0; /// Extracts a boolean. Returns false if null was received. virtual bool extract(std::size_t pos, float& val) = 0; /// Extracts a float. Returns false if null was received. virtual bool extract(std::size_t pos, double& val) = 0; /// Extracts a double. Returns false if null was received. virtual bool extract(std::size_t pos, char& val) = 0; /// Extracts a single character. Returns false if null was received. virtual bool extract(std::size_t pos, std::string& val) = 0; /// Extracts a string. Returns false if null was received. virtual bool extract(std::size_t pos, BLOB& val) = 0; /// Extracts a BLOB. Returns false if null was received. ---- !!!AbstractPreparation <[AbstractPreparation]> is an optional interface responsible for preparing an extract. If you need it depends on the <[DataConnector]> you implement. For example, SQLite can do perfectly without it, ODBC instead requires it. SQLite doesn't need it because it works as follows: * sendQuery * getNextResult * extract single row values from result set This works because SQLites <*getNextResult*> provides the data as string, i.e. it doesn't need any type information. The ODBC implementation is different: * register/prepare for each column an output location * getNextResult * extract for each row the value by copying the content of the previously registered output location <[AbstractPreparation]> is responsible for the first step. A typical prepare implementation will look like that: void prepare(std::size_t pos, Poco::Int32 val) { _myVec[pos] = Poco::Any a(val); int* i = AnyCast(&_myVec[pos]); //register int* i for output, Db specific } ---- Extract now changes to: bool Extractor::extract(std::size_t pos, Poco::Int16& val) { if (isNull(pos)) return false; val = AnyCast(_myVec[pos]); return true; } ---- !!Complete Interface AbstractPreparation(); /// Creates the AbstractPreparation. virtual ~AbstractPreparation(); /// Destroys the AbstractPreparation. virtual void prepare(std::size_t pos, Poco::Int8) = 0; /// Prepares an Int8. virtual void prepare(std::size_t pos, Poco::UInt8) = 0; /// Prepares an UInt8. virtual void prepare(std::size_t pos, Poco::Int16) = 0; /// Prepares an Int16. virtual void prepare(std::size_t pos, Poco::UInt16) = 0; /// Prepares an UInt16. virtual void prepare(std::size_t pos, Poco::Int32) = 0; /// Prepares an Int32. virtual void prepare(std::size_t pos, Poco::UInt32) = 0; /// Prepares an UInt32. virtual void prepare(std::size_t pos, Poco::Int64) = 0; /// Prepares an Int64. virtual void prepare(std::size_t pos, Poco::UInt64) = 0; /// Prepares an UInt64. virtual void prepare(std::size_t pos, bool) = 0; /// Prepares a boolean. virtual void prepare(std::size_t pos, float) = 0; /// Prepares a float. virtual void prepare(std::size_t pos, double) = 0; /// Prepares a double. virtual void prepare(std::size_t pos, char) = 0; /// Prepares a single character. virtual void prepare(std::size_t pos, const std::string& ) = 0; /// Prepares a string. virtual void prepare(std::size_t pos, const BLOB&) = 0; ---- Note that it is recommended to prepare a statement only once in the compileImpl of <[StatementImpl]>. The AbstractPrepare objects (which make use of <[AbstractPreparation]> can be created by iterating over the Extractor objects of the StatementImpl: Poco::Data::AbstractExtractingVec::iterator it = extractings().begin(); Poco::Data::AbstractExtractingVec::iterator itEnd = extractings().end(); std::size_t pos = 0; // sqlite starts with pos 0 for results! your DB maybe with 1 for (; it != itEnd; ++it) { AbstractPrepare* pPrep = (*it)->createPrepareObject(pPreparation, pos); _prepareVec.push_back(pPrep); (*it)->extract(pos); pos += (*it)->numOfColumnsHandled(); } ---- !!!StatementImpl A <[StatementImpl]> stores as member a Binder and an Extractor (optional a Preparation object) and is responsible for compiling, binding, fetching single rows from the database and invoking the <*Extracting*> objects. The interface it has to implement is given as: public: StatementImpl(); /// Creates the StatementImpl. virtual ~StatementImpl(); /// Destroys the StatementImpl. protected: virtual bool hasNext() = 0; /// Returns true if a call to next() will return data. Note that the /// implementation must support several consecutive calls to hasNext /// without data getting lost, ie. hasNext(); hasNext(); next() must /// be equal to hasNext(); next(); virtual void next() = 0; /// Retrieves the next row from the resultset. /// Will throw, if the resultset is empty. /// Expects the statement to be compiled and bound virtual bool canBind() const = 0; /// Returns if another bind is possible. virtual void compileImpl() = 0; /// Compiles the statement, doesn't bind yet. /// From now on AbstractBinder and AbstractExtractor /// will be used virtual void bindImpl() = 0; /// Binds parameters. virtual AbstractExtractor& extractor() = 0; /// Returns the concrete extractor used by the statement. virtual AbstractBinder& binder() = 0; /// Returns the concrete binder used by the statement. ---- The Extracting and Binding objects can be accessed via the calls to the super-class methods <*extractings()*> and <*bindings()*>. A high-level <*bind*> implementation will look like this: [...] Poco::Data::AbstractBindingVec& binds = bindings(); std::size_t pos = 1; // or 0 depending on your database Poco::Data::AbstractBindingVec::iterator it = binds.begin(); Poco::Data::AbstractBindingVec::iterator itEnd = binds.end(); for (; it != itEnd && (*it)->canBind(); ++it) { (*it)->bind(pos); pos += (*it)->numOfColumnsHandled(); } ---- A high-level <*next*> implementation: if (!hasNext()) throw Poco::Data::DataException("No data received"); int nCol = countColumnsInResult...; poco_assert (columnsHandled() == nCol); Poco::Data::AbstractExtractingVec::iterator it = extractings().begin(); Poco::Data::AbstractExtractingVec::iterator itEnd = extractings().end(); std::size_t pos = 0; // sqlite starts with pos 0 for results! your DB maybe with 1 for (; it != itEnd; ++it) { (*it)->extract(pos); pos += (*it)->numOfColumnsHandled(); } enableHasNext(); ---- A high-level <*hasNext*> implementation: if (enabledhasNext()) { checkIfItHasMoreData cacheResult disablehasNext() } return cachedResult; ---- A high-level <*compileImpl*>: if (compiled) return; std::string sqlStmt(toString()); if database expects placeholders in different format than ":name", parse and replace them compile statement; create Binder; create Extractor; ---- A high-level <*canBind*>: bool ret = false; if (!bindings().empty() && validCompiledStatement) ret = (*bindings().begin())->canBind(); return ret; ---- !!!SessionImpl The purpose of the <[SessionImpl]> is simply to open/close a connection to the database, to act as factory for <[StatementImpl]> objects, and to handle transactions. The connection is opened in the constructor, and closed in the destructor. Poco::Data::StatementImpl* createStatementImpl(); /// Returns an SQLite StatementImpl void begin(); /// Starts a transaction void commit(); /// Commits and ends a transaction void rollback(); /// Aborts a transaction ---- !!!Connector Finally, one needs to implement the <[Connector]>. Each <[Connector]> should have a public static const string member named <*KEY*> and must have a factory method to <*create*> <[ Poco::AutoPtr ]> objects of type <[SessionImpl]>. It should also have a static <*addToFactory()*> and a static <*removeFromFactory()*> method: class My_API Connector: public Poco::Data::Connector /// Connector instantiates SessionImpl objects. { public: static const std::string KEY; /// Keyword for creating sessions Connector(); /// Creates the Connector. ~Connector(); /// Destroys the Connector. Poco::AutoPtr < Poco::Data::SessionImpl > createSession(const std::string& connectionString); /// Creates a SessionImpl object and initializes it with the given connectionString. static void registerConnector(); /// Registers the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory static void unregisterConnector(); /// Unregisters the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory }; ---- poco-1.3.6p1-all/Data/doc/99100-DataReleaseNotes.page0000644000076500001200000000611711313735446022401 0ustar guenteradmin00000000000000POCO Data Release Notes POCO Data Library !!!Release 1.3.6 !!Summary of Changes - fixed SF# 2186643: Data::Statement::reset() not implemented in 1.3.3 - better error reporting in Data MySQL connector (patch #2881270 by Jan "HanzZ" Kaluza) - fixed SF# 2876179: MySQL Signed/Unsigned value bug - upgraded to SQLite 3.6.20 !!!Release 1.3.5 !!Summary of Changes - fixed SF# 2779410: Poco::Data::ODBC::HandleException impovement !!!Release 1.3.4 !!Summary of Changes - Upgraded to SQLite 3.6.13 - improved SQLite error reporting - Poco::Data::SessionPool: the janitor can be disabled by specifying a zero idle time. - added Poco::Data::SessionPool::customizeSession() - added support for different SQLite transaction modes (DEFERRED, IMMEDIATE, EXCLUSIVE) The transaction mode can be set with <[setProperty("transactionMode", mode);]> where mode is one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". Note that mode must be passed as a <[std::string]>. - Data::SQLite: added support for automatic retries if the database is locked. Automatic retires can be enabled with <[setProperty("maxRetryAttempts", nAttempts);]> where the number of attempts must be an <[int]>. Retry behavior can be further customized using the <[minRetrySleep]> and <[maxRetrySleep]> properties. See Poco::Data::SQLite::SessionImpl for more information. - improved SQLite data type mapping !!!Release 1.3.3 !!Summary of Changes - Upgraded to SQLite 3.6.2 - fixed SF# 1871946: no exception thrown on error - fixed SF# 2007486: Please clarify license for Data/samples/* - fixed SF# 2019857: Memory leak in Data::ODBC Extractor - fixed SF# 2118943: out_of_bound access in Poco::Data::BLOB:rawContent - fixed SF# 1891132: Poco::Data::StatementImpl::executeWithLimit is not correct !!!Release 1.3.2 !!Summary of Changes - fixed SF# 1724388: ODBC Diagnostics - fixed SF# 1804797: ODBC Statement multiple execution fails - fixed SF# 1803435: SessionPool onJanitorTimer called too often? - fixed SF# 1851997: Undefined Behavior in ODBC::Preparation - updated SQlite to 3.5.5 !!!Release 1.3.1 !!Summary of Changes - fixed SF# 1739989: Data::RecordSet::operator = () - fixed SF# 1747525: SQLite, Transactions and Session Pooling - upgraded to SQLite 3.4.1 !!!Release 1.3.0 !!Summary of Changes - Class Poco::Data::RecordSet has been added providing generic access to arbitrary tables. - SessionInstantiator has been renamed Poco::Data::Connector. - Poco::Data::BLOBInputStream and Poco::Data::BLOBOutputStream allow convenient access to Poco::Data::BLOB data. - Poco::Data::Session and Poco::Data::Statement can be used in simpler ways. - The DataConnectors project directory has been merged into the Data project directory. !!Incompatible Changes and Possible Transition Issues Release 1.3 of the POCO C++ Libraries is the first official release containing the Data library. The Data library has been available in a development state for the 1.2 release. For the 1.3 release, a few things have been changed in an incompatible way that requires changes to existing code. poco-1.3.6p1-all/Data/doc/info.txt0000644000076500001200000000014711313735446017371 0ustar guenteradmin00000000000000For the latest version of the documentation go to http://appinf.com/poco/wiki/tiki-index.php?page=Datapoco-1.3.6p1-all/Data/include/0000755000076500001200000000000011313735446016551 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/include/Poco/0000755000076500001200000000000011313735446017451 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/include/Poco/Data/0000755000076500001200000000000011313735446020322 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/include/Poco/Data/AbstractBinder.h0000644000076500001200000000663611313735446023375 0ustar guenteradmin00000000000000// // AbstractBinder.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractBinder.h#2 $ // // Library: Data // Package: DataCore // Module: AbstractBinder // // Definition of the AbstractBinder class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractBinder_INCLUDED #define Data_AbstractBinder_INCLUDED #include "Poco/Data/Data.h" #include namespace Poco { namespace Data { class BLOB; class Data_API AbstractBinder /// Interface for Binding data types to placeholders. The default placeholder format /// in the SQL query is ":name". { public: AbstractBinder(); /// Creates the AbstractBinder. virtual ~AbstractBinder(); /// Destroys the AbstractBinder. virtual void bind(std::size_t pos, const Poco::Int8& val) = 0; /// Binds an Int8. virtual void bind(std::size_t pos, const Poco::UInt8& val) = 0; /// Binds an UInt8. virtual void bind(std::size_t pos, const Poco::Int16& val) = 0; /// Binds an Int16. virtual void bind(std::size_t pos, const Poco::UInt16& val) = 0; /// Binds an UInt16. virtual void bind(std::size_t pos, const Poco::Int32& val) = 0; /// Binds an Int32. virtual void bind(std::size_t pos, const Poco::UInt32& val) = 0; /// Binds an UInt32. virtual void bind(std::size_t pos, const Poco::Int64& val) = 0; /// Binds an Int64. virtual void bind(std::size_t pos, const Poco::UInt64& val) = 0; /// Binds an UInt64. virtual void bind(std::size_t pos, const bool& val) = 0; /// Binds a boolean. virtual void bind(std::size_t pos, const float& val) = 0; /// Binds a float. virtual void bind(std::size_t pos, const double& val) = 0; /// Binds a double. virtual void bind(std::size_t pos, const char& val) = 0; /// Binds a single character. virtual void bind(std::size_t pos, const char* const &pVal) = 0; /// Binds a const char ptr. virtual void bind(std::size_t pos, const std::string& val) = 0; /// Binds a string. virtual void bind(std::size_t pos, const BLOB& val) = 0; /// Binds a BLOB. }; } } // namespace Poco::Data #endif // Data_AbstractBinder_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/AbstractBinding.h0000644000076500001200000000700211313735446023530 0ustar guenteradmin00000000000000// // AbstractBinding.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractBinding.h#1 $ // // Library: Data // Package: DataCore // Module: AbstractBinding // // Definition of the AbstractBinding class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractBinding_INCLUDED #define Data_AbstractBinding_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Any.h" #include "Poco/RefCountedObject.h" #include "Poco/AutoPtr.h" #include #include namespace Poco { namespace Data { class AbstractBinder; class Data_API AbstractBinding: public Poco::RefCountedObject /// AbstractBinding connects a value with a placeholder via an AbstractBinder interface. { public: AbstractBinding(); /// Creates the AbstractBinding. virtual ~AbstractBinding(); /// Destroys the AbstractBinding. void setBinder(AbstractBinder* pBinder); /// Sets the object used for binding; object does NOT take ownership of the pointer. AbstractBinder* getBinder() const; /// Returns the AbstractBinder used for binding data. virtual std::size_t numOfColumnsHandled() const = 0; /// Returns the number of columns that the binding handles. /// /// The trivial case will be one single column but when /// complex types are used this value can be larger than one. virtual std::size_t numOfRowsHandled() const = 0; /// Returns the number of rows that the binding handles. /// /// The trivial case will be one single row but /// for collection data types (ie vector) it can be larger. virtual bool canBind() const = 0; /// Returns true if we have enough data to bind virtual void bind(std::size_t pos) = 0; /// Binds a value to the given column position virtual void reset() = 0; /// Allows a binding to be reused. private: AbstractBinder* _pBinder; }; typedef Poco::AutoPtr AbstractBindingPtr; typedef std::vector AbstractBindingVec; // // inlines // inline void AbstractBinding::setBinder(AbstractBinder* pBinder) { _pBinder = pBinder; } inline AbstractBinder* AbstractBinding::getBinder() const { return _pBinder; } } } // namespace Poco::Data #endif // Data_AbstractBinding_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/AbstractExtraction.h0000644000076500001200000001102711313735446024300 0ustar guenteradmin00000000000000// // AbstractExtraction.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractExtraction.h#1 $ // // Library: Data // Package: DataCore // Module: AbstractExtraction // // Definition of the AbstractExtraction class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractExtraction_INCLUDED #define Data_AbstractExtraction_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractExtractor.h" #include "Poco/Data/Limit.h" #include "Poco/RefCountedObject.h" #include "Poco/AutoPtr.h" #include #include namespace Poco { namespace Data { class AbstractPrepare; class AbstractPreparation; class Data_API AbstractExtraction: public Poco::RefCountedObject /// AbstractExtraction is the interface class that connects output positions to concrete values /// retrieved via an AbstractExtractor. { public: AbstractExtraction(Poco::UInt32 limit = Limit::LIMIT_UNLIMITED); /// Creates the AbstractExtraction. A limit value equal to EXTRACT_UNLIMITED (0xffffffffu) /// means that we extract as much data as possible during one execute. /// Otherwise the limit value is used to partition data extracting to a limited amount of rows. virtual ~AbstractExtraction(); /// Destroys the AbstractExtraction. void setExtractor(AbstractExtractor* pExtractor); /// Sets the class used for extracting the data. Does not take ownership of the pointer. AbstractExtractor* getExtractor() const; /// Retrieves the extractor object virtual std::size_t numOfColumnsHandled() const = 0; /// Returns the number of columns that the extraction handles. /// /// The trivial case will be one single column but when /// complex types are used this value can be larger than one. virtual std::size_t numOfRowsHandled() const = 0; /// Returns the number of rows that the extraction handles. /// /// The trivial case will be one single row but /// for collection data types (ie vector) it can be larger. virtual std::size_t numOfRowsAllowed() const = 0; /// Returns the upper limit on number of rows that the extraction will handle. virtual void extract(std::size_t pos) = 0; /// Extracts a value from the param, starting at the given column position. virtual void reset() = 0; /// Resets the etxractor so that it can be re-used. virtual AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const = 0; /// Creates a Prepare object for the etxracting object void setLimit(Poco::UInt32 limit); /// Sets the limit. Poco::UInt32 getLimit() const; /// Gets the limit. private: AbstractExtractor* _pExtractor; Poco::UInt32 _limit; }; typedef Poco::AutoPtr AbstractExtractionPtr; typedef std::vector AbstractExtractionVec; // // inlines // inline void AbstractExtraction::setExtractor(AbstractExtractor* pExtractor) { _pExtractor = pExtractor; } inline AbstractExtractor* AbstractExtraction::getExtractor() const { return _pExtractor; } inline void AbstractExtraction::setLimit(Poco::UInt32 limit) { _limit = limit; } inline Poco::UInt32 AbstractExtraction::getLimit() const { return _limit; } } } // namespace Poco::Data #endif // Data_AbstractExtraction_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/AbstractExtractor.h0000644000076500001200000000754011313735446024140 0ustar guenteradmin00000000000000// // AbstractExtractor.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractExtractor.h#2 $ // // Library: Data // Package: DataCore // Module: AbstractExtractor // // Definition of the AbstractExtractor class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractExtractor_INCLUDED #define Data_AbstractExtractor_INCLUDED #include "Poco/Data/Data.h" #include namespace Poco { namespace Data { class BLOB; class Data_API AbstractExtractor /// Interface used to extract data from a single result row. /// If an extractor receives null it is not allowed to change val! { public: AbstractExtractor(); /// Creates the AbstractExtractor. virtual ~AbstractExtractor(); /// Destroys the AbstractExtractor. virtual bool extract(std::size_t pos, Poco::Int8& val) = 0; /// Extracts an Int8. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt8& val) = 0; /// Extracts an UInt8. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::Int16& val) = 0; /// Extracts an Int16. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt16& val) = 0; /// Extracts an UInt16. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::Int32& val) = 0; /// Extracts an Int32. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt32& val) = 0; /// Extracts an UInt32. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::Int64& val) = 0; /// Extracts an Int64. Returns false if null was received. virtual bool extract(std::size_t pos, Poco::UInt64& val) = 0; /// Extracts an UInt64. Returns false if null was received. virtual bool extract(std::size_t pos, bool& val) = 0; /// Extracts a boolean. Returns false if null was received. virtual bool extract(std::size_t pos, float& val) = 0; /// Extracts a float. Returns false if null was received. virtual bool extract(std::size_t pos, double& val) = 0; /// Extracts a double. Returns false if null was received. virtual bool extract(std::size_t pos, char& val) = 0; /// Extracts a single character. Returns false if null was received. virtual bool extract(std::size_t pos, std::string& val) = 0; /// Extracts a string. Returns false if null was received. virtual bool extract(std::size_t pos, BLOB& val) = 0; /// Extracts a BLOB. Returns false if null was received. }; } } // namespace Poco::Data #endif // Data_AbstractExtractor_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/AbstractPreparation.h0000644000076500001200000000723311313735446024450 0ustar guenteradmin00000000000000// // AbstractPreparation.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractPreparation.h#2 $ // // Library: Data // Package: DataCore // Module: AbstractPreparation // // Definition of the AbstractPreparation class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractPreparation_INCLUDED #define Data_AbstractPreparation_INCLUDED #include "Poco/Data/Data.h" #include "Poco/RefCountedObject.h" #include namespace Poco { namespace Data { class BLOB; class Data_API AbstractPreparation: public Poco::RefCountedObject /// Interface used for database preparation where we first have to register all data types (and memory output locations) /// before extracting data, i.e. extract works as two-pase extract: first we call prepare once, then extract n-times. /// Only some database connectors will need to implement this interface. /// Note that the values in the interface serve only the purpose of type distinction. { public: AbstractPreparation(); /// Creates the AbstractPreparation. virtual ~AbstractPreparation(); /// Destroys the AbstractPreparation. virtual void prepare(std::size_t pos, Poco::Int8) = 0; /// Prepares an Int8. virtual void prepare(std::size_t pos, Poco::UInt8) = 0; /// Prepares an UInt8. virtual void prepare(std::size_t pos, Poco::Int16) = 0; /// Prepares an Int16. virtual void prepare(std::size_t pos, Poco::UInt16) = 0; /// Prepares an UInt16. virtual void prepare(std::size_t pos, Poco::Int32) = 0; /// Prepares an Int32. virtual void prepare(std::size_t pos, Poco::UInt32) = 0; /// Prepares an UInt32. virtual void prepare(std::size_t pos, Poco::Int64) = 0; /// Prepares an Int64. virtual void prepare(std::size_t pos, Poco::UInt64) = 0; /// Prepares an UInt64. virtual void prepare(std::size_t pos, bool) = 0; /// Prepares a boolean. virtual void prepare(std::size_t pos, float) = 0; /// Prepares a float. virtual void prepare(std::size_t pos, double) = 0; /// Prepares a double. virtual void prepare(std::size_t pos, char) = 0; /// Prepares a single character. virtual void prepare(std::size_t pos, const std::string& ) = 0; /// Prepares a string. virtual void prepare(std::size_t pos, const BLOB&) = 0; /// Prepares a BLOB. }; } } // namespace Poco::Data #endif // Data_AbstractPreparation_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/AbstractPrepare.h0000644000076500001200000000462411313735446023563 0ustar guenteradmin00000000000000// // AbstractPrepare.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractPrepare.h#2 $ // // Library: Data // Package: DataCore // Module: AbstractPrepare // // Definition of the AbstractPrepare class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractPrepare_INCLUDED #define Data_AbstractPrepare_INCLUDED #include "Poco/Data/Data.h" #include namespace Poco { namespace Data { class AbstractPreparation; class Data_API AbstractPrepare /// Interface for calling the appropriate AbstractPreparation method { public: AbstractPrepare(AbstractPreparation* pPrepare); /// Creates the AbstractPrepare. virtual ~AbstractPrepare(); /// Destroys the AbstractPrepare. virtual void prepare() = 0; /// Prepares data. AbstractPreparation* preparation(); /// Returns the preparation object protected: AbstractPreparation* _pPrepare; }; // // inlines // inline AbstractPreparation* AbstractPrepare::preparation() { return _pPrepare; } } } // namespace Poco::Data #endif // Data_AbstractPrepare_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/AbstractSessionImpl.h0000644000076500001200000001317311313735446024431 0ustar guenteradmin00000000000000// // AbstractSessionImpl.h // // $Id: //poco/1.3/Data/include/Poco/Data/AbstractSessionImpl.h#2 $ // // Library: Data // Package: DataCore // Module: AbstractSessionImpl // // Definition of the AbstractSessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_AbstractSessionImpl_INCLUDED #define Data_AbstractSessionImpl_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/SessionImpl.h" #include "Poco/Data/DataException.h" #include namespace Poco { namespace Data { template class AbstractSessionImpl: public SessionImpl /// A partial implementation of SessionImpl, providing /// features and properties management. /// /// To implement a certain feature or property, a subclass /// must provide setter and getter methods and register /// them with addFeature() or addProperty(). { public: typedef void (C::*FeatureSetter)(const std::string&, bool); /// The setter method for a feature. typedef bool (C::*FeatureGetter)(const std::string&); /// The getter method for a feature. typedef void (C::*PropertySetter)(const std::string&, const Poco::Any&); /// The setter method for a property. typedef Poco::Any (C::*PropertyGetter)(const std::string&); /// The getter method for a property. AbstractSessionImpl() /// Creates the AbstractSessionImpl. { } ~AbstractSessionImpl() /// Destroys the AbstractSessionImpl. { } void setFeature(const std::string& name, bool state) /// Looks a feature up in the features map /// and calls the feature's setter, if there is one. { typename FeatureMap::const_iterator it = _features.find(name); if (it != _features.end()) { if (it->second.setter) (static_cast(this)->*it->second.setter)(name, state); else throw NotImplementedException("set", name); } else throw NotSupportedException(name); } bool getFeature(const std::string& name) /// Looks a feature up in the features map /// and calls the feature's getter, if there is one. { typename FeatureMap::const_iterator it = _features.find(name); if (it != _features.end()) { if (it->second.getter) return (static_cast(this)->*it->second.getter)(name); else throw NotImplementedException("get", name); } else throw NotSupportedException(name); } void setProperty(const std::string& name, const Poco::Any& value) /// Looks a property up in the properties map /// and calls the property's setter, if there is one. { typename PropertyMap::const_iterator it = _properties.find(name); if (it != _properties.end()) { if (it->second.setter) (static_cast(this)->*it->second.setter)(name, value); else throw NotImplementedException("set", name); } else throw NotSupportedException(name); } Poco::Any getProperty(const std::string& name) /// Looks a property up in the properties map /// and calls the property's getter, if there is one. { typename PropertyMap::const_iterator it = _properties.find(name); if (it != _properties.end()) { if (it->second.getter) return (static_cast(this)->*it->second.getter)(name); else throw NotImplementedException("set", name); } else throw NotSupportedException(name); } protected: void addFeature(const std::string& name, FeatureSetter setter, FeatureGetter getter) /// Adds a feature to the map of supported features. /// /// The setter or getter can be null, in case setting or getting a feature /// is not supported. { Feature feature; feature.setter = setter; feature.getter = getter; _features[name] = feature; } void addProperty(const std::string& name, PropertySetter setter, PropertyGetter getter) /// Adds a property to the map of supported properties. /// /// The setter or getter can be null, in case setting or getting a property /// is not supported. { Property property; property.setter = setter; property.getter = getter; _properties[name] = property; } private: struct Feature { FeatureSetter setter; FeatureGetter getter; }; struct Property { PropertySetter setter; PropertyGetter getter; }; typedef std::map FeatureMap; typedef std::map PropertyMap; FeatureMap _features; PropertyMap _properties; }; } } // namespace Poco::Data #endif // Data_AbstractSessionImpl_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Binding.h0000644000076500001200000001735511313735446022060 0ustar guenteradmin00000000000000// // Binding.h // // $Id: //poco/1.3/Data/include/Poco/Data/Binding.h#1 $ // // Library: Data // Package: DataCore // Module: Binding // // Definition of the Binding class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Binding_INCLUDED #define Data_Binding_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractBinding.h" #include "Poco/Data/DataException.h" #include "Poco/Data/TypeHandler.h" #include #include #include #include namespace Poco { namespace Data { template class Binding: public AbstractBinding /// A Binding maps a value to a column. { public: explicit Binding(const T& val): _val(val), _bound(false) /// Creates the Binding. { } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return 1; } bool canBind() const { return !_bound; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); TypeHandler::bind(pos, _val, getBinder()); _bound = true; } void reset () { _bound = false; } private: const T& _val; bool _bound; }; template class Binding >: public AbstractBinding /// Specialization for std::vector. { public: explicit Binding(const std::vector& val): _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler::bind(pos, *_begin, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::vector& _val; typename std::vector::const_iterator _begin; typename std::vector::const_iterator _end; }; template class Binding >: public AbstractBinding /// Specialization for std::set. { public: explicit Binding(const std::set& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler::bind(pos, *_begin, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::set& _val; typename std::set::const_iterator _begin; typename std::set::const_iterator _end; }; template class Binding >: public AbstractBinding /// Specialization for std::multiset. { public: explicit Binding(const std::multiset& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler::bind(pos, *_begin, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::multiset& _val; typename std::multiset::const_iterator _begin; typename std::multiset::const_iterator _end; }; template class Binding >: public AbstractBinding /// Specialization for std::map. { public: explicit Binding(const std::map& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler::bind(pos, _begin->second, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::map& _val; typename std::map::const_iterator _begin; typename std::map::const_iterator _end; }; template class Binding >: public AbstractBinding /// Specialization for std::multimap. { public: explicit Binding(const std::multimap& val): AbstractBinding(), _val(val), _begin(val.begin()), _end(val.end()) /// Creates the Binding. { if (numOfRowsHandled() == 0) throw BindingException("It is illegal to bind to an empty data collection"); } ~Binding() /// Destroys the Binding. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _val.size(); } bool canBind() const { return _begin != _end; } void bind(std::size_t pos) { poco_assert_dbg(getBinder() != 0); poco_assert_dbg(canBind()); TypeHandler::bind(pos, _begin->second, getBinder()); ++_begin; } void reset() { _begin = _val.begin(); _end = _val.end(); } private: const std::multimap& _val; typename std::multimap::const_iterator _begin; typename std::multimap::const_iterator _end; }; template Binding* use(const T& t) /// Convenience function for a more compact Binding creation. { return new Binding(t); } } } // namespace Poco::Data #endif // Data_Binding_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/BLOB.h0000644000076500001200000001525411313735446021220 0ustar guenteradmin00000000000000// // BLOB.h // // $Id: //poco/1.3/Data/include/Poco/Data/BLOB.h#9 $ // // Library: Data // Package: DataCore // Module: BLOB // // Definition of the BLOB class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_BLOB_INCLUDED #define Data_BLOB_INCLUDED #include "Poco/Data/Data.h" #include "Poco/SharedPtr.h" #include "Poco/DynamicAnyHolder.h" #include "Poco/Exception.h" #include namespace Poco { namespace Data { class Data_API BLOB /// Representation of a Binary Large OBject. /// /// A BLOB can hold arbitrary binary data. /// The maximum size depends on the underlying database. /// /// The BLOBInputStream and BLOBOutputStream classes provide /// a convenient way to access the data in a BLOB. { public: typedef std::vector::const_iterator Iterator; BLOB(); /// Creates an empty BLOB. BLOB(const std::vector& content); /// Creates the BLOB, content is deep-copied. BLOB(const char* const pContent, std::size_t size); /// Creates the BLOB by deep-copying pContent. BLOB(const std::string& content); /// Creates a BLOB from a string. BLOB(const BLOB& other); /// Creates a BLOB by copying another one. ~BLOB(); /// Destroys the BLOB. BLOB& operator = (const BLOB& other); /// Assignment operator. bool operator == (const BLOB& other) const; /// Compares for equality BLOB by value. bool operator != (const BLOB& other) const; /// Compares for inequality BLOB by value. void swap(BLOB& other); /// Swaps the BLOB with another one. const std::vector& content() const; /// Returns the content. const char* rawContent() const; /// Returns the raw content. /// /// If the BLOB is empty, returns NULL. void assignRaw(const char* pChar, std::size_t count); /// Assigns raw content to internal storage. void appendRaw(const char* pChar, std::size_t count); /// Assigns raw content to internal storage. void clear(bool doCompact = false); /// Clears the content of the blob. /// If doCompact is true, trims the excess capacity. void compact(); /// Trims the internal storage excess capacity. Iterator begin() const; Iterator end() const; std::size_t size() const; /// Returns the size of the BLOB in bytes. private: Poco::SharedPtr > _pContent; friend class BLOBStreamBuf; }; // // inlines // inline const std::vector& BLOB::content() const { return *_pContent; } inline const char* BLOB::rawContent() const { if (_pContent->empty()) return 0; else return &(*_pContent)[0]; } inline std::size_t BLOB::size() const { return _pContent->size(); } inline bool BLOB::operator == (const BLOB& other) const { return *_pContent == *other._pContent; } inline bool BLOB::operator != (const BLOB& other) const { return *_pContent != *other._pContent; } inline BLOB::Iterator BLOB::begin() const { return _pContent->begin(); } inline BLOB::Iterator BLOB::end() const { return _pContent->end(); } inline void BLOB::assignRaw(const char* pChar, std::size_t count) { poco_assert_dbg (pChar); BLOB tmp(pChar, count); swap(tmp); } inline void BLOB::appendRaw(const char* pChar, std::size_t count) { poco_assert_dbg (pChar); _pContent->insert(_pContent->end(), pChar, pChar+count); } inline void BLOB::swap(BLOB& other) { using std::swap; swap(_pContent, other._pContent); } inline void BLOB::clear(bool doCompact) { _pContent->clear(); if (doCompact) compact(); } inline void BLOB::compact() { std::vector(*_pContent).swap(*_pContent); } } } // namespace Poco::Data // // DynamicAnyHolderImpl // namespace Poco { template <> class DynamicAnyHolderImpl: public DynamicAnyHolder { public: DynamicAnyHolderImpl(const Data::BLOB& val): _val(val) { } ~DynamicAnyHolderImpl() { } const std::type_info& type() const { return typeid(Data::BLOB); } void convert(Int8&) const { throw Poco::BadCastException(); } void convert(Int16&) const { throw Poco::BadCastException(); } void convert(Int32&) const { throw Poco::BadCastException(); } void convert(Int64&) const { throw Poco::BadCastException(); } void convert(UInt8&) const { throw Poco::BadCastException(); } void convert(UInt16&) const { throw Poco::BadCastException(); } void convert(UInt32&) const { throw Poco::BadCastException(); } void convert(UInt64&) const { throw Poco::BadCastException(); } void convert(bool&) const { throw Poco::BadCastException(); } void convert(float&) const { throw Poco::BadCastException(); } void convert(double&) const { throw Poco::BadCastException(); } void convert(char&) const { throw Poco::BadCastException(); } void convert(std::string& val) const { val.assign(_val.begin(), _val.end()); } void convert(Poco::DateTime&) const { throw Poco::BadCastException(); } void convert(Poco::LocalDateTime&) const { throw Poco::BadCastException(); } void convert(Poco::Timestamp&) const { throw Poco::BadCastException(); } DynamicAnyHolder* clone() const { return new DynamicAnyHolderImpl(_val); } bool isArray() const { return false; } bool isInteger() const { return false; } bool isSigned() const { return false; } bool isNumeric() const { return false; } bool isString() const { return false; } private: Data::BLOB _val; }; } // namespace Poco #endif // Data_BLOB_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/BLOBStream.h0000644000076500001200000000645011313735446022372 0ustar guenteradmin00000000000000// // BLOBStream.h // // $Id: //poco/1.3/Data/include/Poco/Data/BLOBStream.h#3 $ // // Library: Data // Package: DataCore // Module: BLOBStream // // Definition of the BLOBStream class. // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_BLOBStream_INCLUDED #define Data_BLOBStream_INCLUDED #include "Poco/Foundation.h" #include "Poco/UnbufferedStreamBuf.h" #include "Poco/Data/BLOB.h" #include #include namespace Poco { namespace Data { class Data_API BLOBStreamBuf: public UnbufferedStreamBuf /// This is the streambuf class used for reading from and writing to a BLOB. { public: BLOBStreamBuf(BLOB& blob); /// Creates BLOBStreamBuf. ~BLOBStreamBuf(); /// Destroys BLOBStreamBuf. protected: int_type readFromDevice(); int_type writeToDevice(char c); private: BLOB& _blob; BLOB::Iterator _it; }; class Data_API BLOBIOS: public virtual std::ios /// The base class for BLOBInputStream and /// BLOBOutputStream. /// /// This class is needed to ensure the correct initialization /// order of the stream buffer and base classes. { public: BLOBIOS(BLOB& blob, openmode mode); /// Creates the BLOBIOS with the given BLOB. ~BLOBIOS(); /// Destroys the BLOBIOS. BLOBStreamBuf* rdbuf(); /// Returns a pointer to the internal BLOBStreamBuf. protected: BLOBStreamBuf _buf; }; class Data_API BLOBOutputStream: public BLOBIOS, public std::ostream /// An output stream for writing to a BLOB. { public: BLOBOutputStream(BLOB& blob); /// Creates the BLOBOutputStream with the given BLOB. ~BLOBOutputStream(); /// Destroys the BLOBOutputStream. }; class Data_API BLOBInputStream: public BLOBIOS, public std::istream /// An input stream for reading from a BLOB. { public: BLOBInputStream(BLOB& blob); /// Creates the BLOBInputStream with the given BLOB. ~BLOBInputStream(); /// Destroys the BLOBInputStream. }; } } // namespace Poco::Data #endif // Data_BLOBStream_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Column.h0000644000076500001200000001061311313735446021731 0ustar guenteradmin00000000000000// // Column.h // // $Id: //poco/1.3/Data/include/Poco/Data/Column.h#3 $ // // Library: Data // Package: DataCore // Module: Column // // Definition of the Column class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Column_INCLUDED #define Data_Column_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/MetaColumn.h" #include "Poco/SharedPtr.h" #include namespace Poco { namespace Data { template class Column /// Column class is column data container. /// Data (a pointer to vector of contained values) is assigned to the class /// through either constructor or set() member function. /// Construction with null pointer is not allowed. /// This class owns the data assigned to it and deletes the storage on destruction. { public: typedef std::vector DataVec; typedef typename DataVec::const_iterator Iterator; typedef typename DataVec::size_type Size; Column(const MetaColumn& metaColumn, std::vector* pData): _metaColumn(metaColumn), _pData(pData) /// Creates the Column. { poco_check_ptr (_pData); } Column(const Column& col): _metaColumn(col._metaColumn), _pData(col._pData) /// Creates the Column. { } ~Column() /// Destroys the Column. { } Column& operator = (const Column& col) /// Assignment operator. { Column tmp(col); swap(tmp); return *this; } void swap(Column& other) /// Swaps the column with another one. { std::swap(_metaColumn, other._metaColumn); std::swap(_pData, other._pData); } DataVec& data() /// Returns reference to contained data. { return *_pData; } const T& value(std::size_t row) const /// Returns the field value in specified row. { try { return _pData->at(row); } catch (std::out_of_range& ex) { throw RangeException(ex.what()); } } const T& operator [] (std::size_t row) const /// Returns the field value in specified row. { return value(row); } Size rowCount() const /// Returns number of rows. { return _pData->size(); } void reset() /// Clears and shrinks the storage. { std::vector().swap(*_pData); } const std::string& name() const /// Returns column name. { return _metaColumn.name(); } std::size_t length() const /// Returns column maximum length. { return _metaColumn.length(); } std::size_t precision() const /// Returns column precision. /// Valid for floating point fields only (zero for other data types). { return _metaColumn.precision(); } std::size_t position() const /// Returns column position. { return _metaColumn.position(); } MetaColumn::ColumnDataType type() const /// Returns column type. { return _metaColumn.type(); } Iterator begin() const /// Returns iterator pointing to the beginning of data storage vector. { return _pData->begin(); } Iterator end() const /// Returns iterator pointing to the end of data storage vector. { return _pData->end(); } private: Column(); MetaColumn _metaColumn; Poco::SharedPtr _pData; }; } } // namespace Poco::Data #endif // Data_Column_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Common.h0000644000076500001200000000356011313735446021727 0ustar guenteradmin00000000000000// // Common.h // // $Id: //poco/1.3/Data/include/Poco/Data/Common.h#1 $ // // Library: Data // Package: DataCore // Module: Common // // This header includes a bunch of Poco Data headers needed frequently. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Common_INCLUDED #define Data_Common_INCLUDED // Standard include files #include "Poco/Data/Binding.h" #include "Poco/Data/Extraction.h" #include "Poco/Data/Limit.h" #include "Poco/Data/SessionFactory.h" #endif // Data_Common_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Connector.h0000644000076500001200000000457111313735446022434 0ustar guenteradmin00000000000000// // Connector.h // // $Id: //poco/1.3/Data/include/Poco/Data/Connector.h#1 $ // // Library: Data // Package: DataCore // Module: Connector // // Definition of the Connector class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Connector_INCLUDED #define Data_Connector_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/SessionImpl.h" #include "Poco/AutoPtr.h" namespace Poco { namespace Data { class Data_API Connector /// A Connector creates SessionImpl objects. /// /// Every connector library (like the SQLite or the ODBC connector) /// provides a subclass of this class, an instance of which is /// registered with the SessionFactory. { public: Connector(); /// Creates the Connector. virtual ~Connector(); /// Destroys the Connector. virtual Poco::AutoPtr createSession(const std::string& connectionString) = 0; /// Create a SessionImpl object and initialize it with the given connectionString. }; } } // namespace Poco::Data #endif // Data_Connector_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Data.h0000644000076500001200000000562311313735446021352 0ustar guenteradmin00000000000000// // Data.h // // $Id: //poco/1.3/Data/include/Poco/Data/Data.h#2 $ // // Library: Data // Package: DataCore // Module: Data // // Basic definitions for the Poco Data library. // This file must be the first file included by every other Data // header file. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Data_INCLUDED #define Data_Data_INCLUDED #include "Poco/Foundation.h" // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the Data_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // Data_API functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) #if defined(Data_EXPORTS) #define Data_API __declspec(dllexport) #else #define Data_API __declspec(dllimport) #endif #endif #if !defined(Data_API) #define Data_API #endif // // Automatically link Data library. // #if defined(_MSC_VER) #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Data_EXPORTS) #if defined(POCO_DLL) #if defined(_DEBUG) #pragma comment(lib, "PocoDatad.lib") #else #pragma comment(lib, "PocoData.lib") #endif #else #if defined(_DEBUG) #pragma comment(lib, "PocoDatamtd.lib") #else #pragma comment(lib, "PocoDatamt.lib") #endif #endif #endif #endif #endif // Data_Data_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/DataException.h0000644000076500001200000000525211313735446023227 0ustar guenteradmin00000000000000// // DataException.h // // $Id: //poco/1.3/Data/include/Poco/Data/DataException.h#1 $ // // Library: Data // Package: DataCore // Module: DataException // // Definition of the DataException class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_DataException_INCLUDED #define Data_DataException_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Exception.h" namespace Poco { namespace Data { POCO_DECLARE_EXCEPTION(Data_API, DataException, Poco::IOException) POCO_DECLARE_EXCEPTION(Data_API, RowDataMissingException, DataException) POCO_DECLARE_EXCEPTION(Data_API, UnknownDataBaseException, DataException) POCO_DECLARE_EXCEPTION(Data_API, UnknownTypeException, DataException) POCO_DECLARE_EXCEPTION(Data_API, ExecutionException, DataException) POCO_DECLARE_EXCEPTION(Data_API, BindingException, DataException) POCO_DECLARE_EXCEPTION(Data_API, ExtractException, DataException) POCO_DECLARE_EXCEPTION(Data_API, LimitException, DataException) POCO_DECLARE_EXCEPTION(Data_API, NotSupportedException, DataException) POCO_DECLARE_EXCEPTION(Data_API, NotImplementedException, DataException) POCO_DECLARE_EXCEPTION(Data_API, SessionUnavailableException, DataException) POCO_DECLARE_EXCEPTION(Data_API, SessionPoolExhaustedException, DataException) } } // namespace Poco::Data #endif // Data_DataException_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Extraction.h0000644000076500001200000002563311313735446022624 0ustar guenteradmin00000000000000// // Extraction.h // // $Id: //poco/1.3/Data/include/Poco/Data/Extraction.h#2 $ // // Library: Data // Package: DataCore // Module: Extraction // // Definition of the Extraction class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Extraction_INCLUDED #define Data_Extraction_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractExtraction.h" #include "Poco/Data/Prepare.h" #include "Poco/Data/TypeHandler.h" #include "Poco/Data/Column.h" #include "Poco/Data/DataException.h" #include #include #include #include #include namespace Poco { namespace Data { template class Extraction: public AbstractExtraction /// Concrete Data Type specific extraction of values from a query result set. { public: Extraction(T& result): _rResult(result), _default(), _extracted(false) /// Creates an Extraction object, uses an empty object T as default value { } Extraction(T& result, const T& def): _rResult(result), _default(def), _extracted(false) /// Creates an Extraction object, uses the provided def object as default value { } ~Extraction() /// Destroys the Extraction object. { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return 1u; } std::size_t numOfRowsAllowed() const { return 1u; } void extract(std::size_t pos) { if (_extracted) throw ExtractException("value already extracted"); _extracted = true; TypeHandler::extract(pos, _rResult, _default, getExtractor()); } void reset() { _extracted = false; } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } private: T& _rResult; T _default; // copy the default bool _extracted; }; template class Extraction >: public AbstractExtraction /// Vector Data Type specialization for extraction of values from a query result set. { public: Extraction(std::vector& result): _rResult(result), _default() { } Extraction(std::vector& result, const T& def): _rResult(result), _default(def) { } virtual ~Extraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } void extract(std::size_t pos) { _rResult.push_back(_default); TypeHandler::extract(pos, _rResult.back(), _default, getExtractor()); } virtual void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } protected: const std::vector& result() const { return _rResult; } private: std::vector& _rResult; T _default; // copy the default }; template class Extraction >: public AbstractExtraction /// List Data Type specialization for extraction of values from a query result set. { public: Extraction(std::list& result): _rResult(result), _default() { } Extraction(std::list& result, const T& def): _rResult(result), _default(def) { } virtual ~Extraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } void extract(std::size_t pos) { _rResult.push_back(_default); TypeHandler::extract(pos, _rResult.back(), _default, getExtractor()); } virtual void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } protected: const std::list& result() const { return _rResult; } private: std::list& _rResult; T _default; // copy the default }; template > class InternalExtraction: public Extraction /// Container Data Type specialization extension for extraction of values from a query result set. /// /// This class is intended for PocoData internal use - it is used by StatementImpl /// to automaticaly create internal Extraction in cases when statement returns data and no external storage /// was supplied. It is later used by RecordSet to retrieve the fetched data after statement execution. /// It takes ownership of the Column pointer supplied as constructor argument. Column object, in turn /// owns the data vector pointer. /// /// InternalExtraction objects can not be copied or assigned. { public: explicit InternalExtraction(C& result, Column* pColumn): Extraction(result), _pColumn(pColumn) /// Creates InternalExtraction. { } ~InternalExtraction() /// Destroys InternalExtraction. { delete _pColumn; } void reset() { _pColumn->reset(); } const T& value(int index) const { try { return Extraction::result().at(index); } catch (std::out_of_range& ex) { throw RangeException(ex.what()); } } const Column& column() const { return *_pColumn; } private: InternalExtraction(); InternalExtraction(const InternalExtraction&); InternalExtraction& operator = (const InternalExtraction&); Column* _pColumn; }; template class Extraction >: public AbstractExtraction /// Set Data Type specialization for extraction of values from a query result set. { public: Extraction(std::set& result): _rResult(result), _default() { } Extraction(std::set& result, const T& def): _rResult(result), _default(def) { } ~Extraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } void extract(std::size_t pos) { T tmp; TypeHandler::extract(pos, tmp, _default, getExtractor()); _rResult.insert(tmp); } void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } private: std::set& _rResult; T _default; // copy the default }; template class Extraction >: public AbstractExtraction /// Multiset Data Type specialization for extraction of values from a query result set. { public: Extraction(std::multiset& result): _rResult(result), _default() { } Extraction(std::multiset& result, const T& def): _rResult(result), _default(def) { } ~Extraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } void extract(std::size_t pos) { T tmp; TypeHandler::extract(pos, tmp, _default, getExtractor()); _rResult.insert(tmp); } void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } private: std::multiset& _rResult; T _default; // copy the default }; template class Extraction >: public AbstractExtraction /// Map Data Type specialization for extraction of values from a query result set. { public: Extraction(std::map& result): _rResult(result), _default() { } Extraction(std::map& result, const V& def): _rResult(result), _default(def) { } ~Extraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } void extract(std::size_t pos) { V tmp; TypeHandler::extract(pos, tmp, _default, getExtractor()); _rResult.insert(std::make_pair(tmp(), tmp)); } void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } private: std::map& _rResult; V _default; // copy the default }; template class Extraction >: public AbstractExtraction /// Multimap Data Type specialization for extraction of values from a query result set. { public: Extraction(std::multimap& result): _rResult(result), _default() { } Extraction(std::multimap& result, const V& def): _rResult(result), _default(def) { } ~Extraction() { } std::size_t numOfColumnsHandled() const { return TypeHandler::size(); } std::size_t numOfRowsHandled() const { return _rResult.size(); } std::size_t numOfRowsAllowed() const { return getLimit(); } void extract(std::size_t pos) { V tmp; TypeHandler::extract(pos, tmp, _default, getExtractor()); _rResult.insert(std::make_pair(tmp(), tmp)); } void reset() { } AbstractPrepare* createPrepareObject(AbstractPreparation* pPrep, std::size_t pos) const { return new Prepare(pPrep, pos, _default); } private: std::multimap& _rResult; V _default; // copy the default }; template Extraction* into(T& t) /// Convenience function to allow for a more compact creation of a default extraction object { return new Extraction(t); } template Extraction* into(T& t, const T& def) /// Convenience function to allow for a more compact creation of an extraction object with the given default { return new Extraction(t, def); } } } // namespace Poco::Data #endif // Data_Extraction_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Limit.h0000644000076500001200000000561111313735446021554 0ustar guenteradmin00000000000000// // Limit.h // // $Id: //poco/1.3/Data/include/Poco/Data/Limit.h#1 $ // // Library: Data // Package: DataCore // Module: Limit // // Definition of the Limit class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Limit_INCLUDED #define Data_Limit_INCLUDED #include "Poco/Data/Data.h" namespace Poco { namespace Data { class Data_API Limit /// Limit stores information how many rows a query should return. { public: enum { LIMIT_UNLIMITED = 0xffffffffu }; Limit(Poco::UInt32 value, bool hardLimit, bool isLowerLimit); /// Creates the Limit. /// /// Value contains the upper row hint, if hardLimit is set to true, the limit acts as a hard /// border, ie. every query must return exactly value rows, returning more than value objects will throw an exception! /// LowerLimits always act as hard-limits! /// /// A value of LIMIT_UNLIMITED disables the limit. ~Limit(); /// Destroys the Limit. Poco::UInt32 value() const; /// Returns the value of the limit bool isHardLimit() const; /// Returns true if the limit is a hard limit. bool isLowerLimit() const; /// Returns true if the limit is a lower limit, otherwise it is an upperLimit private: Poco::UInt32 _value; bool _hardLimit; bool _isLowerLimit; }; // // inlines // inline Poco::UInt32 Limit::value() const { return _value; } inline bool Limit::isHardLimit() const { return _hardLimit; } inline bool Limit::isLowerLimit() const { return _isLowerLimit; } } } // namespace Poco::Data #endif // Data_Limit_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/MetaColumn.h0000644000076500001200000001042111313735446022535 0ustar guenteradmin00000000000000// // MetaColumn.h // // $Id: //poco/1.3/Data/include/Poco/Data/MetaColumn.h#2 $ // // Library: Data // Package: DataCore // Module: MetaColumn // // Definition of the MetaColumn class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MetaColumn_INCLUDED #define Data_MetaColumn_INCLUDED #include "Poco/Data/Data.h" #include namespace Poco { namespace Data { class Data_API MetaColumn /// MetaColumn class contains column metadata information. { public: enum ColumnDataType { FDT_BOOL, FDT_INT8, FDT_UINT8, FDT_INT16, FDT_UINT16, FDT_INT32, FDT_UINT32, FDT_INT64, FDT_UINT64, FDT_FLOAT, FDT_DOUBLE, FDT_STRING, FDT_BLOB, FDT_UNKNOWN }; MetaColumn(); /// Creates the MetaColumn. explicit MetaColumn(std::size_t position, const std::string& name = "", ColumnDataType type = FDT_UNKNOWN, std::size_t length = 0, std::size_t precision = 0, bool nullable = false); /// Creates the MetaColumn. virtual ~MetaColumn(); /// Destroys the MetaColumn. const std::string& name() const; /// Returns column name. std::size_t length() const; /// Returns column maximum length. std::size_t precision() const; /// Returns column precision. /// Valid for floating point fields only /// (zero for other data types). std::size_t position() const; /// Returns column position. ColumnDataType type() const; /// Returns column type. bool isNullable() const; /// Returns true if column allows null values, false otherwise. protected: void setName(const std::string& name); /// Sets the column name. void setLength(std::size_t length); /// Sets the column length. void setPrecision(std::size_t precision); /// Sets the column precision. void setType(ColumnDataType type); /// Sets the column data type. void setNullable(bool nullable); /// Sets the column nullability. private: std::string _name; std::size_t _length; std::size_t _precision; std::size_t _position; ColumnDataType _type; bool _nullable; }; /// /// inlines /// inline const std::string& MetaColumn::name() const { return _name; } inline std::size_t MetaColumn::length() const { return _length; } inline std::size_t MetaColumn::precision() const { return _precision; } inline std::size_t MetaColumn::position() const { return _position; } inline MetaColumn::ColumnDataType MetaColumn::type() const { return _type; } inline bool MetaColumn::isNullable() const { return _nullable; } inline void MetaColumn::setName(const std::string& name) { _name = name; } inline void MetaColumn::setLength(std::size_t length) { _length = length; } inline void MetaColumn::setPrecision(std::size_t precision) { _precision = precision; } inline void MetaColumn::setType(ColumnDataType type) { _type = type; } inline void MetaColumn::setNullable(bool nullable) { _nullable = nullable; } } } // namespace Poco::Data #endif // Data_MetaColumn_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/PooledSessionHolder.h0000644000076500001200000000623011313735446024420 0ustar guenteradmin00000000000000// // PooledSessionHolder.h // // $Id: //poco/1.3/Data/include/Poco/Data/PooledSessionHolder.h#1 $ // // Library: Data // Package: SessionPooling // Module: PooledSessionHolder // // Definition of the PooledSessionHolder class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_PooledSessionHolder_INCLUDED #define Data_PooledSessionHolder_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/SessionImpl.h" #include "Poco/AutoPtr.h" #include "Poco/Timestamp.h" #include "Poco/Mutex.h" namespace Poco { namespace Data { class SessionPool; class Data_API PooledSessionHolder: public Poco::RefCountedObject /// This class is used by SessionPool to manage SessionImpl objects. { public: PooledSessionHolder(SessionPool& owner, SessionImpl* pSessionImpl); /// Creates the PooledSessionHolder. ~PooledSessionHolder(); /// Destroys the PooledSessionHolder. SessionImpl* session(); /// Returns a pointer to the SessionImpl. SessionPool& owner(); /// Returns a reference to the SessionHolder's owner. void access(); /// Updates the last access timestamp. int idle() const; /// Returns the number of seconds the session has not been used. private: SessionPool& _owner; Poco::AutoPtr _pImpl; Poco::Timestamp _lastUsed; mutable Poco::FastMutex _mutex; }; // // inlines // inline SessionImpl* PooledSessionHolder::session() { return _pImpl; } inline SessionPool& PooledSessionHolder::owner() { return _owner; } inline void PooledSessionHolder::access() { Poco::FastMutex::ScopedLock lock(_mutex); _lastUsed.update(); } inline int PooledSessionHolder::idle() const { Poco::FastMutex::ScopedLock lock(_mutex); return (int) (_lastUsed.elapsed()/Poco::Timestamp::resolution()); } } } // namespace Poco::Data #endif // Data_PooledSessionHolder_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/PooledSessionImpl.h0000644000076500001200000000622311313735446024106 0ustar guenteradmin00000000000000// // PooledSessionImpl.h // // $Id: //poco/1.3/Data/include/Poco/Data/PooledSessionImpl.h#2 $ // // Library: Data // Package: SessionPooling // Module: PooledSessionImpl // // Definition of the PooledSessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_PooledSessionImpl_INCLUDED #define Data_PooledSessionImpl_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/SessionImpl.h" #include "Poco/Data/PooledSessionHolder.h" #include "Poco/AutoPtr.h" namespace Poco { namespace Data { class SessionPool; class Data_API PooledSessionImpl: public SessionImpl /// PooledSessionImpl is a decorator created by /// SessionPool that adds session pool /// management to SessionImpl objects. { public: PooledSessionImpl(PooledSessionHolder* pHolder); /// Creates the PooledSessionImpl. ~PooledSessionImpl(); /// Destroys the PooledSessionImpl. // SessionImpl StatementImpl* createStatementImpl(); void begin(); void commit(); void rollback(); void close(); bool isConnected(); bool isTransaction(); void setFeature(const std::string& name, bool state); bool getFeature(const std::string& name); void setProperty(const std::string& name, const Poco::Any& value); Poco::Any getProperty(const std::string& name); protected: SessionImpl* access(); /// Updates the last access timestamp, /// verifies validity of the session /// and returns the session if it is valid. /// /// Throws an SessionUnavailableException if the /// session is no longer valid. SessionImpl* impl(); /// Returns a pointer to the SessionImpl. private: Poco::AutoPtr _pHolder; }; // // inlines // inline SessionImpl* PooledSessionImpl::impl() { return _pHolder->session(); } } } // namespace Poco::Data #endif // Data_PooledSessionImpl_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Prepare.h0000644000076500001200000001161011313735446022070 0ustar guenteradmin00000000000000// // Prepare.h // // $Id: //poco/1.3/Data/include/Poco/Data/Prepare.h#2 $ // // Library: Data // Package: DataCore // Module: Prepare // // Definition of the Prepare class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Prepare_INCLUDED #define Data_Prepare_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractPrepare.h" #include "Poco/Data/TypeHandler.h" #include #include #include #include namespace Poco { namespace Data { class BLOB; template class Prepare: public AbstractPrepare /// Class for calling the appropriate AbstractPreparation method. { public: Prepare(AbstractPreparation* pPrepare, std::size_t pos, const T& val): AbstractPrepare(pPrepare), _pos(pos), _val(val) /// Creates the Prepare. { } ~Prepare() /// Destroys the Prepare. { } void prepare() /// Prepares data. { TypeHandler::prepare(_pos, _val, preparation()); } private: std::size_t _pos; const T& _val; }; template class Prepare >: public AbstractPrepare /// Class for calling the appropriate AbstractPreparation method. { public: Prepare(AbstractPreparation* pPrepare, std::size_t pos, const T& val): AbstractPrepare(pPrepare), _pos(pos), _val(val) /// Creates the Prepare. { } ~Prepare() /// Destroys the Prepare. { } void prepare() /// Prepares data. { TypeHandler::prepare(_pos, _val, preparation()); } private: std::size_t _pos; const T& _val; }; template class Prepare >: public AbstractPrepare /// Class for calling the appropriate AbstractPreparation method. { public: Prepare(AbstractPreparation* pPrepare, std::size_t pos, const T& val): AbstractPrepare(pPrepare), _pos(pos), _val(val) /// Creates the Prepare. { } ~Prepare() /// Destroys the Prepare. { } void prepare() /// Prepares data. { TypeHandler::prepare(_pos, _val, preparation()); } private: std::size_t _pos; const T& _val; }; template class Prepare >: public AbstractPrepare /// Class for calling the appropriate AbstractPreparation method. { public: Prepare(AbstractPreparation* pPrepare, std::size_t pos, const T& val): AbstractPrepare(pPrepare), _pos(pos), _val(val) /// Creates the Prepare. { } ~Prepare() /// Destroys the Prepare. { } void prepare() /// Prepares data. { TypeHandler::prepare(_pos, _val, preparation()); } private: std::size_t _pos; const T& _val; }; template class Prepare >: public AbstractPrepare /// Class for calling the appropriate AbstractPreparation method. { public: Prepare(AbstractPreparation* pPrepare, std::size_t pos, const V& val): AbstractPrepare(pPrepare), _pos(pos), _val(val) /// Creates the Prepare. { } ~Prepare() /// Destroys the Prepare. { } void prepare() /// Prepares data. { TypeHandler::prepare(_pos, _val, preparation()); } private: std::size_t _pos; const V& _val; }; template class Prepare >: public AbstractPrepare /// Class for calling the appropriate AbstractPreparation method. { public: Prepare(AbstractPreparation* pPrepare, std::size_t pos, const V& val): AbstractPrepare(pPrepare), _pos(pos), _val(val) /// Creates the Prepare. { } ~Prepare() /// Destroys the Prepare. { } void prepare() /// Prepares data. { TypeHandler::prepare(_pos, _val, preparation()); } private: std::size_t _pos; const V& _val; }; } } // namespace Poco::Data #endif // Data_Prepare_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Range.h0000644000076500001200000000555611313735446021542 0ustar guenteradmin00000000000000// // Range.h // // $Id: //poco/1.3/Data/include/Poco/Data/Range.h#2 $ // // Library: Data // Package: DataCore // Module: Range // // Definition of the Range class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Range_INCLUDED #define Data_Range_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/Limit.h" namespace Poco { namespace Data { class Data_API Range /// Range stores information how many rows a query should return. { public: Range(Poco::UInt32 lowValue, Poco::UInt32 upValue, bool hardLimit); /// Creates the Range. lowValue must be smaller equal than upValue ~Range(); /// Destroys the Limit. const Limit& lower() const; /// Returns the lower limit const Limit& upper() const; /// Returns the upper limit private: Limit _lower; Limit _upper; }; // // inlines // inline const Limit& Range::lower() const { return _lower; } inline const Limit& Range::upper() const { return _upper; } template Limit limit(T lim, bool hard = false) /// Creates an upperLimit { return Limit(static_cast(lim), hard, false); } template Limit upperLimit(T lim, bool hard = false) { return limit(lim, hard); } template Limit lowerLimit(T lim) { return Limit(static_cast(lim), true, true); } template Range range(T low, T upp, bool hard = false) { return Range(static_cast(low), static_cast(upp), hard); } } } // namespace Poco::Data #endif // Data_Range_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/RecordSet.h0000644000076500001200000002212511313735446022367 0ustar guenteradmin00000000000000// // RecordSet.h // // $Id: //poco/1.3/Data/include/Poco/Data/RecordSet.h#4 $ // // Library: Data // Package: DataCore // Module: RecordSet // // Definition of the RecordSet class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_RecordSet_INCLUDED #define Data_RecordSet_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/Extraction.h" #include "Poco/Data/Statement.h" #include "Poco/Data/BLOB.h" #include "Poco/String.h" #include "Poco/DynamicAny.h" #include "Poco/Exception.h" namespace Poco { namespace Data { class Data_API RecordSet: private Statement /// RecordSet provides access to data returned from a query. /// Data access indexes (row and column) are 0-based, as usual in C++. /// /// Recordset provides navigation methods to iterate through the /// recordset, retrieval methods to extract data, and methods /// to get metadata (type, etc.) about columns. /// /// To work with a RecordSet, first create a Statement, execute it, and /// create the RecordSet from the Statement, as follows: /// /// Statement select(session); /// select << "SELECT * FROM Person"; /// select.execute(); /// RecordSet rs(select); /// /// The number of rows in the RecordSet can be limited by specifying /// a limit for the Statement. { public: explicit RecordSet(const Statement& rStatement); /// Creates the RecordSet. ~RecordSet(); /// Destroys the RecordSet. Statement& operator = (const Statement& stmt); /// Assignment operator. std::size_t rowCount() const; /// Returns the number of rows in the recordset. std::size_t columnCount() const; /// Returns the number of rows in the recordset. template const Column& column(const std::string& name) const /// Returns the reference to the first Column with the specified name. { return column(columnPosition(name)); } template const Column& column(std::size_t pos) const /// Returns the reference to column at specified location. { typedef const InternalExtraction* ExtractionVecPtr; const AbstractExtractionVec& rExtractions = extractions(); std::size_t s = rExtractions.size(); if (0 == s || pos >= s) throw RangeException(format("Invalid column index: %z", pos)); ExtractionVecPtr pExtraction = dynamic_cast(rExtractions[pos].get()); if (pExtraction) { return pExtraction->column(); } else { throw Poco::BadCastException(format("Type cast failed!\nColumn: %z\nTarget type:\t%s", pos, std::string(typeid(T).name()))); } } template const T& value(std::size_t col, std::size_t row) const /// Returns the reference to data value at [col, row] location. { return column(col).value(row); } template const T& value(const std::string& name, std::size_t row) const /// Returns the reference to data value at named column, row location. { return column(name).value(row); } DynamicAny value(std::size_t col, std::size_t row) const; /// Returns the reference to data value at column, row location. DynamicAny value(const std::string& name, std::size_t row) const; /// Returns the reference to data value at named column, row location. bool moveFirst(); /// Moves the row cursor to the first row. /// /// Returns true if there is at least one row in the RecordSet, /// false otherwise. bool moveNext(); /// Moves the row cursor to the next row. /// /// Returns true if the row is available, or false /// if the end of the record set has been reached and /// no more rows are available. bool movePrevious(); /// Moves the row cursor to the previous row. /// /// Returns true if the row is available, or false /// if there are no more rows available. bool moveLast(); /// Moves the row cursor to the last row. /// /// Returns true if there is at least one row in the RecordSet, /// false otherwise. DynamicAny value(const std::string& name); /// Returns the value in the named column of the current row. DynamicAny value(std::size_t index); /// Returns the value in the given column of the current row. DynamicAny operator [] (const std::string& name); /// Returns the value in the named column of the current row. DynamicAny operator [] (std::size_t index); /// Returns the value in the named column of the current row. MetaColumn::ColumnDataType columnType(std::size_t pos) const; /// Returns the type for the column at specified position. MetaColumn::ColumnDataType columnType(const std::string& name) const; /// Returns the type for the column with specified name. const std::string& columnName(std::size_t pos) const; /// Returns column name for the column at specified position. std::size_t columnLength(std::size_t pos) const; /// Returns column maximum length for the column at specified position. std::size_t columnLength(const std::string& name) const; /// Returns column maximum length for the column with specified name. std::size_t columnPrecision(std::size_t pos) const; /// Returns column precision for the column at specified position. /// Valid for floating point fields only (zero for other data types). std::size_t columnPrecision(const std::string& name) const; /// Returns column precision for the column with specified name. /// Valid for floating point fields only (zero for other data types). private: RecordSet(); template std::size_t columnPosition(const std::string& name) const /// Returns the position of the column with specified name. { typedef const InternalExtraction* ExtractionVecPtr; const AbstractExtractionVec& rExtractions = extractions(); AbstractExtractionVec::const_iterator it = rExtractions.begin(); AbstractExtractionVec::const_iterator end = rExtractions.end(); for (; it != end; ++it) { ExtractionVecPtr pExtraction = dynamic_cast(it->get()); if (pExtraction) { const Column& col = pExtraction->column(); if (0 == Poco::icompare(name, col.name())) return col.position(); } } throw NotFoundException(format("Unknown column name: %s", name)); } std::size_t _currentRow; }; /// /// inlines /// inline std::size_t RecordSet::rowCount() const { poco_assert (extractions().size()); return extractions()[0].get()->numOfRowsHandled(); } inline std::size_t RecordSet::columnCount() const { return extractions().size(); } inline Statement& RecordSet::operator = (const Statement& stmt) { _currentRow = 0; return Statement::operator = (stmt); } inline DynamicAny RecordSet::value(const std::string& name) { return value(name, _currentRow); } inline DynamicAny RecordSet::value(std::size_t index) { return value(index, _currentRow); } inline DynamicAny RecordSet::operator [] (const std::string& name) { return value(name, _currentRow); } inline DynamicAny RecordSet::operator [] (std::size_t index) { return value(index, _currentRow); } inline MetaColumn::ColumnDataType RecordSet::columnType(std::size_t pos)const { return metaColumn(static_cast(pos)).type(); } inline MetaColumn::ColumnDataType RecordSet::columnType(const std::string& name)const { return metaColumn(name).type(); } inline const std::string& RecordSet::columnName(std::size_t pos) const { return metaColumn(static_cast(pos)).name(); } inline std::size_t RecordSet::columnLength(std::size_t pos) const { return metaColumn(static_cast(pos)).length(); } inline std::size_t RecordSet::columnLength(const std::string& name)const { return metaColumn(name).length(); } inline std::size_t RecordSet::columnPrecision(std::size_t pos) const { return metaColumn(static_cast(pos)).precision(); } inline std::size_t RecordSet::columnPrecision(const std::string& name)const { return metaColumn(name).precision(); } } } // namespace Poco::Data #endif // Data_RecordSet_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Session.h0000644000076500001200000002643111313735446022124 0ustar guenteradmin00000000000000// // Session.h // // $Id: //poco/1.3/Data/include/Poco/Data/Session.h#3 $ // // Library: Data // Package: DataCore // Module: Session // // Definition of the Session class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Session_INCLUDED #define Data_Session_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/SessionImpl.h" #include "Poco/Data/Statement.h" #include "Poco/Data/StatementCreator.h" #include "Poco/Data/Binding.h" #include "Poco/AutoPtr.h" #include "Poco/Any.h" namespace Poco { namespace Data { class StatementImpl; class Data_API Session /// A Session holds a connection to a Database and creates Statement objects. /// /// Sessions are always created via the SessionFactory: /// /// Session ses(SessionFactory::instance().create(connectorKey, connectionString)); /// /// where the first param presents the type of session one wants to create (e.g., for SQLite one would choose "SQLite", /// for ODBC the key is "ODBC") and the second param is the connection string that the session implementation /// requires to connect to the database. The format of the connection string is specific to the actual connector. /// /// A simpler form to create the session is to pass the connector key and connection string directly to /// the Session constructor. /// /// A concrete example to open an SQLite database stored in the file "dummy.db" would be /// /// Session ses("SQLite", "dummy.db"); /// /// Via a Session one can create two different types of statements. First, statements that should only be executed once and immediately, and /// second, statements that should be executed multiple times, using a separate execute() call. /// The simple one is immediate execution: /// /// ses << "CREATE TABLE Dummy (data INTEGER(10))", now; /// /// The now at the end of the statement is required, otherwise the statement /// would not be executed. /// /// If one wants to reuse a Statement (and avoid the overhead of repeatedly parsing an SQL statement) /// one uses an explicit Statement object and its execute() method: /// /// int i = 0; /// Statement stmt = (ses << "INSERT INTO Dummy VALUES(:data)", use(i)); /// /// for (i = 0; i < 100; ++i) /// { /// stmt.execute(); /// } /// /// The above example assigns the variable i to the ":data" placeholder in the SQL query. The query is parsed and compiled exactly /// once, but executed 100 times. At the end the values 0 to 99 will be present in the Table "DUMMY". /// /// A faster implementaton of the above code will simply create a vector of int /// and use the vector as parameter to the use clause (you could also use set or multiset instead): /// /// std::vector data; /// for (int i = 0; i < 100; ++i) /// { /// data.push_back(i); /// } /// ses << "INSERT INTO Dummy VALUES(:data)", use(data); /// /// NEVER try to bind to an empty collection. This will give a BindingException at run-time! /// /// Retrieving data from a database works similar, you could use simple data types, vectors, sets or multiset as your targets: /// /// std::set retData; /// ses << "SELECT * FROM Dummy", into(retData)); /// /// Due to the blocking nature of the above call it is possible to partition the data retrieval into chunks by setting a limit to /// the maximum number of rows retrieved from the database: /// /// std::set retData; /// Statement stmt = (ses << "SELECT * FROM Dummy", into(retData), limit(50)); /// while (!stmt.done()) /// { /// stmt.execute(); /// } /// /// The "into" keyword is used to inform the statement where output results should be placed. The limit value ensures /// that during each run at most 50 rows are retrieved. Assuming Dummy contains 100 rows, retData will contain 50 /// elements after the first run and 100 after the second run, i.e. /// the collection is not cleared between consecutive runs. After the second execute stmt.done() will return true. /// /// A prepared Statement will behave exactly the same but a further call to execute() will simply reset the Statement, /// execute it again and append more data to the result set. /// /// Note that it is possible to append several "bind" or "into" clauses to the statement. Theoretically, one could also have several /// limit clauses but only the last one that was added will be effective. /// Also several preconditions must be met concerning binds and intos. /// Take the following example: /// /// ses << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR, Age INTEGER(3))"; /// std::vector nameVec; // [...] add some elements /// std::vector ageVec; // [...] add some elements /// ses << "INSERT INTO Person (LastName, Age) VALUES(:ln, :age)", use(nameVec), use(ageVec); /// /// The size of all use parameters MUST be the same, otherwise an exception is thrown. Furthermore, /// the amount of use clauses must match the number of wildcards in the query (to be more precisely: /// each binding has a numberOfColumnsHandled() value which is per default 1. The sum of all these values must match the wildcard count in the query. /// But this is only important if you have written your own TypeHandler specializations). /// If you plan to map complex object types to tables see the TypeHandler documentation. /// For now, we simply assume we have written one TypeHandler for Person objects. Instead of having n different vectors, /// we have one collection: /// /// std::vector people; // [...] add some elements /// ses << "INSERT INTO Person (LastName, FirstName, Age) VALUES(:ln, :fn, :age)", use(people); /// /// which will insert all Person objects from the people vector to the database (and again, you can use set, multiset too, /// even map and multimap if Person provides an operator() which returns the key for the map). /// The same works for a SELECT statement with "into" clauses: /// /// std::vector people; /// ses << "SELECT * FROM PERSON", into(people); { public: Session(Poco::AutoPtr ptrImpl); /// Creates the Session. Session(const std::string& connector, const std::string& connectionString); /// Creates a new session, using the given connector (which must have /// been registered), and connectionString. Session(const Session&); /// Creates a session by copying another one. Session& operator = (const Session&); /// Assignement operator. ~Session(); /// Destroys the Session. void swap(Session& other); /// Swaps the session with another one. template Statement operator << (const T& t) /// Creates a Statement with the given data as SQLContent { return _statementCreator << t; } StatementImpl* createStatementImpl(); /// Creates a StatementImpl. void begin(); /// Starts a transaction. void commit(); /// Commits and ends a transaction. void rollback(); /// Rolls back and ends a transaction. void close(); /// Closes the session. bool isConnected(); /// Returns true iff session is connected, false otherwise. bool isTransaction(); /// Returns true iff a transaction is in progress, false otherwise. void setFeature(const std::string& name, bool state); /// Set the state of a feature. /// /// Features are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested feature is /// not supported by the underlying implementation. bool getFeature(const std::string& name) const; /// Look up the state of a feature. /// /// Features are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested feature is /// not supported by the underlying implementation. void setProperty(const std::string& name, const Poco::Any& value); /// Set the value of a property. /// /// Properties are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested property is /// not supported by the underlying implementation. Poco::Any getProperty(const std::string& name) const; /// Look up the value of a property. /// /// Properties are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested property is /// not supported by the underlying implementation. SessionImpl* impl(); /// Returns a pointer to the underlying SessionImpl. private: Session(); Poco::AutoPtr _ptrImpl; StatementCreator _statementCreator; }; // // inlines // inline StatementImpl* Session::createStatementImpl() { return _ptrImpl->createStatementImpl(); } inline void Session::begin() { return _ptrImpl->begin(); } inline void Session::commit() { return _ptrImpl->commit(); } inline void Session::rollback() { return _ptrImpl->rollback(); } inline void Session::close() { _ptrImpl->close(); } inline bool Session::isConnected() { return _ptrImpl->isConnected(); } inline bool Session::isTransaction() { return _ptrImpl->isTransaction(); } inline void Session::setFeature(const std::string& name, bool state) { _ptrImpl->setFeature(name, state); } inline bool Session::getFeature(const std::string& name) const { return const_cast(_ptrImpl.get())->getFeature(name); } inline void Session::setProperty(const std::string& name, const Poco::Any& value) { _ptrImpl->setProperty(name, value); } inline Poco::Any Session::getProperty(const std::string& name) const { return const_cast(_ptrImpl.get())->getProperty(name); } inline SessionImpl* Session::impl() { return _ptrImpl; } } } // namespace Poco::Data #endif // Data_Session_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/SessionFactory.h0000644000076500001200000000773011313735446023455 0ustar guenteradmin00000000000000// // SessionFactory.h // // $Id: //poco/1.3/Data/include/Poco/Data/SessionFactory.h#3 $ // // Library: Data // Package: DataCore // Module: SessionFactory // // Definition of the SessionFactory class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_SessionFactory_INCLUDED #define Data_SessionFactory_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/Connector.h" #include "Poco/Data/Session.h" #include "Poco/Mutex.h" #include "Poco/SharedPtr.h" #include namespace Poco { namespace Data { class Data_API SessionFactory /// A SessionFactory is a singleton class that stores Connectors and allows to /// create Sessions of the required type: /// /// Session ses(SessionFactory::instance().create(connector, connectionString)); /// /// where the first param presents the type of session one wants to create (e.g. for SQLite one would choose "SQLite") /// and the second param is the connection string that the connector requires to connect to the database. /// /// A concrete example to open an SQLite database stored in the file "dummy.db" would be /// /// Session ses(SessionFactory::instance().create(SQLite::Connector::KEY, "dummy.db")); /// /// An even simpler way to create a session is to use the two argument constructor of Session, which /// automatically invokes the SessionFactory: /// /// Session ses("SQLite", "dummy.db"); { public: static SessionFactory& instance(); /// returns the static instance of the singleton. void add(const std::string& key, Connector* pIn); /// Registers a Connector under the given key at the factory. If a registration for that /// key is already active, the first registration will be kept, only its reference count will be increased. /// Always takes ownership of parameter pIn. void remove(const std::string& key); /// Lowers the reference count for the Connector registered under that key. If the count reaches zero, /// the object is removed. Session create(const std::string& key, const std::string& connectionString); /// Creates a Session for the given key with the connectionString. Throws an Poco:Data::UnknownDataBaseException /// if no Connector is registered for that key. private: SessionFactory(); ~SessionFactory(); SessionFactory(const SessionFactory&); SessionFactory& operator = (const SessionFactory&); struct SessionInfo { int cnt; Poco::SharedPtr ptrSI; SessionInfo(Connector* pSI); }; typedef std::map Connectors; Connectors _connectors; Poco::FastMutex _mutex; }; } } // namespace Poco::Data #endif // Data_SessionFactory_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/SessionImpl.h0000644000076500001200000001037311313735446022744 0ustar guenteradmin00000000000000// // SessionImpl.h // // $Id: //poco/1.3/Data/include/Poco/Data/SessionImpl.h#2 $ // // Library: Data // Package: DataCore // Module: SessionImpl // // Definition of the SessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_SessionImpl_INCLUDED #define Data_SessionImpl_INCLUDED #include "Poco/Data/Data.h" #include "Poco/RefCountedObject.h" #include "Poco/Any.h" namespace Poco { namespace Data { class StatementImpl; class Data_API SessionImpl: public Poco::RefCountedObject /// Interface for Session functionality that subclasses must extend. /// SessionImpl objects are noncopyable. { public: SessionImpl(); /// Creates the SessionImpl. virtual ~SessionImpl(); /// Destroys the SessionImpl. virtual StatementImpl* createStatementImpl() = 0; /// Creates a StatementImpl. virtual void begin() = 0; /// Starts a transaction. virtual void commit() = 0; /// Commits and ends a transaction. virtual void rollback() = 0; /// Aborts a transaction. virtual void close() = 0; /// Closes the connection. virtual bool isConnected() = 0; /// Returns true iff session is connected, false otherwise. virtual bool isTransaction() = 0; /// Returns true iff a transaction is a transaction is in progress, false otherwise. virtual void setFeature(const std::string& name, bool state) = 0; /// Set the state of a feature. /// /// Features are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested feature is /// not supported by the underlying implementation. virtual bool getFeature(const std::string& name) = 0; /// Look up the state of a feature. /// /// Features are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested feature is /// not supported by the underlying implementation. virtual void setProperty(const std::string& name, const Poco::Any& value) = 0; /// Set the value of a property. /// /// Properties are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested property is /// not supported by the underlying implementation. virtual Poco::Any getProperty(const std::string& name) = 0; /// Look up the value of a property. /// /// Properties are a generic extension mechanism for session implementations. /// and are defined by the underlying SessionImpl instance. /// /// Throws a NotSupportedException if the requested property is /// not supported by the underlying implementation. private: SessionImpl(const SessionImpl&); SessionImpl& operator = (const SessionImpl&); }; } } // namespace Poco::Data #endif // Data_SessionImpl_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/SessionPool.h0000644000076500001200000001301011313735446022743 0ustar guenteradmin00000000000000// // SessionPool.h // // $Id: //poco/1.3/Data/include/Poco/Data/SessionPool.h#5 $ // // Library: Data // Package: SessionPooling // Module: SessionPool // // Definition of the SessionPool class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_SessionPool_INCLUDED #define Data_SessionPool_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/PooledSessionHolder.h" #include "Poco/Data/PooledSessionImpl.h" #include "Poco/Data/Session.h" #include "Poco/Timer.h" #include "Poco/Mutex.h" #include namespace Poco { namespace Data { class Data_API SessionPool /// This class implements session pooling for POCO Data. /// /// Creating a connection to a database is often a time consuming /// operation. Therefore it makes sense to reuse a session object /// once it is no longer needed. /// /// A SessionPool manages a collection of SessionImpl objects /// (decorated with a PooledSessionImpl). /// /// When a SessionImpl object is requested, the SessionPool first /// looks in its set of already initialized SessionImpl for an /// available object. If one is found, it is returned to the /// client and marked as "in-use". If no SessionImpl is available, /// the SessionPool attempts to create a new one for the client. /// To avoid excessive creation of SessionImpl objects, a limit /// can be set on the maximum number of objects. /// Sessions found not to be connected to the database are purged /// from the pool whenever one of the following events occurs: /// /// - JanitorTimer event /// - get() request /// - putBack() request /// /// Not connected idle sessions can not exist. /// /// Usage example: /// /// SessionPool pool("ODBC", "..."); /// ... /// Session sess(pool.get()); /// ... { public: SessionPool(const std::string& sessionKey, const std::string& connectionString, int minSessions = 1, int maxSessions = 32, int idleTime = 60); /// Creates the SessionPool for sessions with the given sessionKey /// and connectionString. /// /// The pool allows for at most maxSessions sessions to be created. /// If a session has been idle for more than idleTime seconds, and more than /// minSessions sessions are in the pool, the session is automatically destroyed. /// /// If idleTime is 0, automatic cleanup of unused sessions is disabled. virtual ~SessionPool(); /// Destroys the SessionPool. Session get(); /// Returns a Session. /// /// If there are unused sessions available, one of the /// unused sessions is recycled. Otherwise, a new session /// is created. /// /// If the maximum number of sessions for this pool has /// already been created, a SessionPoolExhaustedException /// is thrown. int capacity() const; /// Returns the maximum number of sessions the SessionPool will manage. int used() const; /// Returns the number of sessions currently in use. int idle() const; /// Returns the number of idle sessions. int dead(); /// Returns the number of not connected active sessions. int allocated() const; /// Returns the number of allocated sessions. int available() const; /// Returns the number of available (idle + remaining capacity) sessions. protected: virtual void customizeSession(Session& session); /// Can be overridden by subclass to perform custom initialization /// of a newly created database session. /// /// The default implementation does nothing. typedef Poco::AutoPtr PooledSessionHolderPtr; typedef Poco::AutoPtr PooledSessionImplPtr; typedef std::list SessionList; void purgeDeadSessions(); int deadImpl(SessionList& rSessions); void putBack(PooledSessionHolderPtr pHolder); void onJanitorTimer(Poco::Timer&); private: SessionPool(const SessionPool&); SessionPool& operator = (const SessionPool&); std::string _sessionKey; std::string _connectionString; int _minSessions; int _maxSessions; int _idleTime; int _nSessions; SessionList _idleSessions; SessionList _activeSessions; Poco::Timer _janitorTimer; mutable Poco::FastMutex _mutex; friend class PooledSessionImpl; }; } } // namespace Poco::Data #endif // Data_SessionPool_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/Statement.h0000644000076500001200000001345311313735446022445 0ustar guenteradmin00000000000000// // Statement.h // // $Id: //poco/1.3/Data/include/Poco/Data/Statement.h#4 $ // // Library: Data // Package: DataCore // Module: Statement // // Definition of the Statement class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_Statement_INCLUDED #define Data_Statement_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/Range.h" #include "Poco/SharedPtr.h" namespace Poco { namespace Data { class AbstractBinding; class AbstractExtraction; class Session; class Limit; class Data_API Statement /// A Statement is used to execute SQL statements. /// It does not contain code of its own. /// Its main purpose is to forward calls to the concrete StatementImpl stored inside. { public: typedef void (*Manipulator)(Statement&); Statement(StatementImpl* pImpl); /// Creates the Statement. explicit Statement(Session& session); /// Creates the Statement for the given Session. /// /// The following: /// /// Statement stmt(sess); /// stmt << "SELECT * FROM Table", ... /// /// is equivalent to: /// /// Statement stmt(sess << "SELECT * FROM Table", ...); /// /// but in some cases better readable. ~Statement(); /// Destroys the Statement. Statement(const Statement& stmt); /// Copy constructor Statement& operator = (const Statement& stmt); /// Assignment operator. void swap(Statement& other); /// Swaps the statement with another one. template Statement& operator << (const T& t) /// Concatenates the send data to a string version of the SQL statement. { _ptr->add(t); return *this; } Statement& operator , (Manipulator manip); /// Handles manipulators, such as now. Statement& operator , (AbstractBinding* info); /// Registers the Binding at the Statement Statement& operator , (AbstractExtraction* extract); /// Registers objects used for extracting data at the Statement. Statement& operator , (const Limit& extrLimit); /// Sets a limit on the maximum number of rows a select is allowed to return. /// /// Set per default to Limit::LIMIT_UNLIMITED which disables the limit. Statement& operator , (const Range& extrRange); /// Sets a an etxraction Range on the maximum number of rows a select is allowed to return. /// /// Set per default to Limit::LIMIT_UNLIMITED which disables the range. std::string toString() const; /// Creates a string from the accumulated SQL statement Poco::UInt32 execute(); /// Executes the whole statement. Stops when either a limit is hit or the whole statement was executed. /// Returns the number of rows extracted from the Database. bool done(); /// Returns if the statement was completely executed or if a previously set limit stopped it /// and there is more work to do. When no limit is set, it will always - after calling execute() - return true. protected: const AbstractExtractionVec& extractions() const; /// Returns the extractions vector. const MetaColumn& metaColumn(std::size_t pos) const; /// Returns the type for the column at specified position. const MetaColumn& metaColumn(const std::string& name) const; /// Returns the type for the column with specified name. private: typedef Poco::SharedPtr StatementImplPtr; bool _executed; StatementImplPtr _ptr; }; // // Manipulators // void Data_API now(Statement& statement); // // inlines // inline Statement& Statement::operator , (Manipulator manip) { manip(*this); return *this; } inline Statement& Statement::operator , (AbstractBinding* info) { _ptr->addBinding(info); return *this; } inline Statement& Statement::operator , (AbstractExtraction* extract) { _ptr->addExtract(extract); return *this; } inline Statement& Statement::operator , (const Limit& extrLimit) { _ptr->setExtractionLimit(extrLimit); return *this; } inline Statement& Statement::operator , (const Range& extrRange) { _ptr->setExtractionLimit(extrRange.lower()); _ptr->setExtractionLimit(extrRange.upper()); return *this; } inline std::string Statement::toString() const { return _ptr->toString(); } inline const AbstractExtractionVec& Statement::extractions() const { return _ptr->extractions(); } inline const MetaColumn& Statement::metaColumn(std::size_t pos) const { return _ptr->metaColumn(static_cast(pos)); } inline const MetaColumn& Statement::metaColumn(const std::string& name) const { return _ptr->metaColumn(name); } } } // namespace Poco::Data #endif // Data_Statement_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/StatementCreator.h0000644000076500001200000000534711313735446023770 0ustar guenteradmin00000000000000// // StatementCreator.h // // $Id: //poco/1.3/Data/include/Poco/Data/StatementCreator.h#2 $ // // Library: Data // Package: DataCore // Module: StatementCreator // // Definition of the StatementCreator class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_StatementCreator_INCLUDED #define Data_StatementCreator_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/SessionImpl.h" #include "Poco/Data/Statement.h" #include "Poco/AutoPtr.h" namespace Poco { namespace Data { class Data_API StatementCreator /// A StatementCreator creates Statements. { public: StatementCreator(); /// Creates an unitialized StatementCreator. StatementCreator(Poco::AutoPtr ptrImpl); /// Creates a StatementCreator. StatementCreator(const StatementCreator& other); /// Creates a StatementCreator by copying another one. ~StatementCreator(); /// Destroys the StatementCreator. StatementCreator& operator = (const StatementCreator& other); /// Assignment operator. void swap(StatementCreator& other); /// Swaps the StatementCreator with another one. template Statement operator << (const T& t) /// Creates a Statement. { Statement stmt(_ptrImpl->createStatementImpl()); stmt << t; return stmt; } private: Poco::AutoPtr _ptrImpl; }; } } // namespace Poco::Data #endif // Data_StatementCreator_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/StatementImpl.h0000644000076500001200000001612711313735446023270 0ustar guenteradmin00000000000000// // StatementImpl.h // // $Id: //poco/1.3/Data/include/Poco/Data/StatementImpl.h#2 $ // // Library: Data // Package: DataCore // Module: StatementImpl // // Definition of the StatementImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_StatementImpl_INCLUDED #define Data_StatementImpl_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractBinding.h" #include "Poco/Data/AbstractExtraction.h" #include "Poco/Data/Range.h" #include "Poco/Data/Column.h" #include "Poco/Data/Extraction.h" #include "Poco/RefCountedObject.h" #include "Poco/AutoPtr.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include #include namespace Poco { namespace Data { class Data_API StatementImpl: public Poco::RefCountedObject /// StatementImpl interface that subclasses must implement to define database dependent query execution. /// /// StatementImpl's are noncopyable. { public: enum State { ST_INITIALIZED, ST_COMPILED, ST_BOUND, ST_DONE, ST_RESET }; StatementImpl(); /// Creates the StatementImpl. virtual ~StatementImpl(); /// Destroys the StatementImpl. template void add(const T& t) /// Appends SQl statement (fragments). { _ostr << t; } void addBinding(AbstractBinding* info); /// Registers the Binding at the StatementImpl. void addExtract(AbstractExtraction* info); /// Registers objects used for extracting data at the StatementImpl. void setExtractionLimit(const Limit& extrLimit); /// Changes the extractionLimit to extrLimit. Per default no limit (EXTRACT_UNLIMITED) is set. std::string toString() const; /// Create a string version of the SQL statement. Poco::UInt32 execute(); /// Executes a statement. Returns the number of rows extracted. void reset(); /// Resets the statement, so that we can reuse all bindings and re-execute again. State getState() const; /// Returns the state of the Statement. protected: virtual Poco::UInt32 columnsReturned() const = 0; /// Returns number of columns returned by query. virtual const MetaColumn& metaColumn(Poco::UInt32 pos) const = 0; /// Returns column meta data. const MetaColumn& metaColumn(const std::string& name) const; /// Returns column meta data. virtual bool hasNext() = 0; /// Returns true if a call to next() will return data. /// /// Note that the implementation must support /// several consecutive calls to hasNext without data getting lost, /// ie. hasNext(); hasNext(); next() must be equal to hasNext(); next(); virtual void next() = 0; /// Retrieves the next row from the resultset. /// /// Will throw, if the resultset is empty. /// Expects the statement to be compiled and bound virtual bool canBind() const = 0; /// Returns if another bind is possible. virtual void compileImpl() = 0; /// Compiles the statement, doesn't bind yet. virtual void bindImpl() = 0; /// Binds parameters. virtual AbstractExtractor& extractor() = 0; /// Returns the concrete extractor used by the statement. const AbstractExtractionVec& extractions() const; /// Returns the extractions vector. virtual AbstractBinder& binder() = 0; /// Returns the concrete binder used by the statement. int columnsExtracted() const; /// Returns the number of columns that the extractors handle. const AbstractBindingVec& bindings() const; /// Returns the bindings. AbstractBindingVec& bindings(); /// Returns the bindings. AbstractExtractionVec& extractions(); /// Returns the extractions vector. void makeExtractors(Poco::UInt32 count); /// Creates extraction vector. Used in case when there is /// data returned, but no extraction supplied externally. private: void compile(); /// Compiles the statement, if not yet compiled. doesn't bind yet void bind(); /// Binds the statement, if not yet bound. Poco::UInt32 executeWithLimit(); /// Executes with an upper limit set. Poco::UInt32 executeWithoutLimit(); /// Executes without an upper limit set. void fixupExtraction(); /// Sets the AbstractExtractor at the extractors. void fixupBinding(); /// Sets the AbstractBinder at the bindings void resetBinding(); /// Resets binding so we can reuse it again. void resetExtraction(); /// Resets binding so we can reuse it again. template void addInternalExtract(const MetaColumn& mc) /// Utility function to create and add an internal extraction. { std::vector* pData = new C; Column* pCol = new Column(mc, pData); addExtract(new InternalExtraction(*pData, pCol)); } StatementImpl(const StatementImpl& stmt); StatementImpl& operator = (const StatementImpl& stmt); State _state; Limit _extrLimit; Poco::UInt32 _lowerLimit; int _columnsExtracted; std::ostringstream _ostr; AbstractBindingVec _bindings; AbstractExtractionVec _extractors; friend class Statement; }; // // inlines // inline void StatementImpl::addBinding(AbstractBinding* info) { _bindings.push_back(info); } inline void StatementImpl::addExtract(AbstractExtraction* info) { _extractors.push_back(info); } inline std::string StatementImpl::toString() const { return _ostr.str(); } inline const AbstractBindingVec& StatementImpl::bindings() const { return _bindings; } inline AbstractBindingVec& StatementImpl::bindings() { return _bindings; } inline const AbstractExtractionVec& StatementImpl::extractions() const { return _extractors; } inline AbstractExtractionVec& StatementImpl::extractions() { return _extractors; } inline int StatementImpl::columnsExtracted() const { return _columnsExtracted; } inline StatementImpl::State StatementImpl::getState() const { return _state; } } } // namespace Poco::Data #endif // Data_StatementImpl_INCLUDED poco-1.3.6p1-all/Data/include/Poco/Data/TypeHandler.h0000644000076500001200000021742011313735446022720 0ustar guenteradmin00000000000000// // TypeHandler.h // // $Id: //poco/1.3/Data/include/Poco/Data/TypeHandler.h#4 $ // // Library: Data // Package: DataCore // Module: TypeHandler // // Definition of the TypeHandler class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_TypeHandler_INCLUDED #define Data_TypeHandler_INCLUDED #include "Poco/Data/Data.h" #include "Poco/Data/AbstractBinder.h" #include "Poco/Data/AbstractExtractor.h" #include "Poco/Data/AbstractPreparation.h" #include "Poco/Tuple.h" #include namespace Poco { namespace Data { template class TypeHandler /// Converts Rows to a Type and the other way around. Provide template specializations to support your own complex types. /// /// Take as example the following (simplified) class: /// class Person /// { /// private: /// std::string _lastName; /// std::string _firstName; /// int _age; /// [....] // public set/get methods, a default constructor, optional < operator (for set, multiset) or function operator (for map, multimap) /// }; /// /// The TypeHandler must provide a costum bind, size, prepare and extract method: /// /// template <> /// class TypeHandler /// { /// public: /// static std::size_t size() /// { /// return 3; // lastName + firstname + age occupy three columns /// } /// /// static void bind(std::size_t pos, const Person& obj, AbstractBinder* pBinder) /// { /// // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Age INTEGER(3)) /// // Note that we advance pos by the number of columns the datatype uses! For string/int this is one. /// poco_assert_dbg (pBinder != 0); /// TypeHandler::bind(pos++, obj.getLastName(), pBinder); /// TypeHandler::bind(pos++, obj.getFirstName(), pBinder); /// TypeHandler::bind(pos++, obj.getAge(), pBinder); /// } /// /// static void prepare(std::size_t pos, const Person& obj, AbstractPreparation* pPrepare) /// { /// // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Age INTEGER(3)) /// poco_assert_dbg (pPrepare != 0); /// TypeHandler::prepare(pos++, obj.getLastName(), pPrepare); /// TypeHandler::prepare(pos++, obj.getFirstName(), pPrepare); /// TypeHandler::prepare(pos++, obj.getAge(), pPrepare); /// } /// /// static void extract(std::size_t pos, Person& obj, const Person& defVal, AbstractExtractor* pExt) /// { /// // defVal is the default person we should use if we encunter NULL entries, so we take the individual fields /// // as defaults. You can do more complex checking, ie return defVal if only one single entry of the fields is null etc... /// poco_assert_dbg (pExt != 0); /// std::string lastName; /// std::string firstName; /// int age = 0; /// // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Age INTEGER(3)) /// TypeHandler::extract(pos++, lastName, defVal.getLastName(), pExt); /// TypeHandler::extract(pos++, firstName, defVal.getFirstName(), pExt); /// TypeHandler::extract(pos++, age, defVal.getAge(), pExt); /// obj.setLastName(lastName); /// obj.setFirstName(firstName); /// obj.setAge(age); /// } /// }; /// /// Note that the TypeHandler template specialization must always be declared in the namespace Poco::Data. /// Apart from that no further work is needed. One can now use Person with into and use clauses. { public: static void bind(std::size_t pos, const T& obj, AbstractBinder* pBinder) { poco_assert_dbg (pBinder != 0); pBinder->bind(pos, obj); } static std::size_t size() { return 1; } static void extract(std::size_t pos, T& obj, const T& defVal, AbstractExtractor* pExt) { poco_assert_dbg (pExt != 0); if (!pExt->extract(pos, obj)) obj = defVal; } static void prepare(std::size_t pos, const T& obj, AbstractPreparation* pPrepare) { poco_assert_dbg (pPrepare != 0); pPrepare->prepare(pos, obj); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator = (const TypeHandler&); }; /// Poco::Tuple TypeHandler specializations // define this macro to nothing for smaller code size #define POCO_TUPLE_TYPE_HANDLER_INLINE inline template POCO_TUPLE_TYPE_HANDLER_INLINE void tupleBind(std::size_t& pos, TupleType tuple, AbstractBinder* pBinder) { TypeHandler::bind(pos, tuple.template get(), pBinder); pos += TypeHandler::size(); } template POCO_TUPLE_TYPE_HANDLER_INLINE void tuplePrepare(std::size_t& pos, TupleType tuple, AbstractPreparation* pPrepare) { TypeHandler::prepare(pos, tuple.template get(), pPrepare); pos += TypeHandler::size(); } template POCO_TUPLE_TYPE_HANDLER_INLINE void tupleExtract(std::size_t& pos, TupleType tuple, DefValType defVal, AbstractExtractor* pExt) { TypeHandler::extract(pos, tuple.template get(), defVal.template get(), pExt); pos += TypeHandler::size(); } template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size() + TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; template class TypeHandler > { public: typedef typename Poco::TypeWrapper >::CONSTREFTYPE TupleConstRef; typedef typename Poco::TypeWrapper >::REFTYPE TupleRef; static void bind(std::size_t pos, TupleConstRef tuple, AbstractBinder* pBinder) { poco_assert (pBinder != 0); tupleBind(pos, tuple, pBinder); } static void prepare(std::size_t pos, TupleConstRef tuple, AbstractPreparation* pPrepare) { poco_assert (pPrepare != 0); tuplePrepare(pos, tuple, pPrepare); } static std::size_t size() { return TypeHandler::size(); } static void extract(std::size_t pos, TupleRef tuple, TupleConstRef defVal, AbstractExtractor* pExt) { poco_assert (pExt != 0); tupleExtract(pos, tuple, defVal, pExt); } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; } } // namespace Poco::Data #endif // Data_TypeHandler_INCLUDED poco-1.3.6p1-all/Data/Makefile0000644000076500001200000000110211313735446016560 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/Makefile#2 $ # # Makefile for Poco Data # include $(POCO_BASE)/build/rules/global objects = AbstractBinder AbstractBinding AbstractExtraction \ AbstractExtractor AbstractPreparation AbstractPrepare \ BLOB BLOBStream DataException Limit MetaColumn \ PooledSessionHolder PooledSessionImpl \ Range RecordSet Session SessionFactory SessionImpl \ Connector SessionPool Statement StatementCreator StatementImpl target = PocoData target_version = $(LIBVERSION) target_libs = PocoFoundation include $(POCO_BASE)/build/rules/lib poco-1.3.6p1-all/Data/MySQL/0000755000076500001200000000000011313735447016074 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/include/0000755000076500001200000000000011313735447017517 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/include/Poco/0000755000076500001200000000000011313735447020417 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/0000755000076500001200000000000011313735447021270 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/0000755000076500001200000000000011313735447022235 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/Binder.h0000644000076500001200000000751111313735447023615 0ustar guenteradmin00000000000000// // Binder.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/Binder.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: Binder // // Definition of the Binder class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_Binder_INCLUDED #define Data_MySQL_Binder_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/AbstractBinder.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/MySQL/MySQLException.h" #include namespace Poco { namespace Data { namespace MySQL { class MySQL_API Binder: public Poco::Data::AbstractBinder /// Binds placeholders in the sql query to the provided values. Performs data types mapping. { public: Binder(); /// Creates the Binder. virtual ~Binder(); /// Destroys the Binder. virtual void bind(std::size_t pos, const Poco::Int8& val); /// Binds an Int8. virtual void bind(std::size_t pos, const Poco::UInt8& val); /// Binds an UInt8. virtual void bind(std::size_t pos, const Poco::Int16& val); /// Binds an Int16. virtual void bind(std::size_t pos, const Poco::UInt16& val); /// Binds an UInt16. virtual void bind(std::size_t pos, const Poco::Int32& val); /// Binds an Int32. virtual void bind(std::size_t pos, const Poco::UInt32& val); /// Binds an UInt32. virtual void bind(std::size_t pos, const Poco::Int64& val); /// Binds an Int64. virtual void bind(std::size_t pos, const Poco::UInt64& val); /// Binds an UInt64. virtual void bind(std::size_t pos, const bool& val); /// Binds a boolean. virtual void bind(std::size_t pos, const float& val); /// Binds a float. virtual void bind(std::size_t pos, const double& val); /// Binds a double. virtual void bind(std::size_t pos, const char& val); /// Binds a single character. virtual void bind(std::size_t pos, const std::string& val); /// Binds a string. virtual void bind(std::size_t pos, const Poco::Data::BLOB& val); /// Binds a BLOB. size_t size() const; /// Return count of binded parameters MYSQL_BIND* getBindArray() const; /// Return array private: virtual void bind(std::size_t, const char* const&) /// Binds a const char ptr. /// This is a private no-op in this implementation /// due to security risk. { } void realBind(std::size_t pos, enum_field_types type, const void* buffer, int length); /// Common bind implementation private: std::vector _bindArray; }; } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_Binder_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/Connector.h0000644000076500001200000000510211313735447024336 0ustar guenteradmin00000000000000// // Connector.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/Connector.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: Connector // // Definition of the Connector class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_Connector_INCLUDED #define Data_MySQL_Connector_INCLUDED #include "MySQL.h" #include "Poco/Data/Connector.h" namespace Poco { namespace Data { namespace MySQL { class MySQL_API Connector: public Poco::Data::Connector /// Connector instantiates MySQL SessionImpl objects. { public: static std::string KEY; Connector(); /// Creates the Connector. virtual ~Connector(); /// Destroys the Connector. virtual Poco::AutoPtr createSession(const std::string& connectionString); /// Creates a MySQL SessionImpl object and initializes it with the given connectionString. static void registerConnector(); /// Registers the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory. static void unregisterConnector(); /// Unregisters the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory. }; } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_Connector_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/Extractor.h0000644000076500001200000000747311313735447024374 0ustar guenteradmin00000000000000// // Extractor.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/Extractor.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: Extractor // // Definition of the Extractor class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_Extractor_INCLUDED #define Data_MySQL_Extractor_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/MySQL/StatementExecutor.h" #include "Poco/Data/MySQL/ResultMetadata.h" #include "Poco/Data/AbstractExtractor.h" #include "Poco/Data/BLOB.h" namespace Poco { namespace Data { namespace MySQL { class MySQL_API Extractor: public Poco::Data::AbstractExtractor /// Extracts and converts data values from the result row returned by MySQL. /// If NULL is received, the incoming val value is not changed and false is returned { public: Extractor(StatementExecutor& st, ResultMetadata& md); /// Creates the Extractor. virtual ~Extractor(); /// Destroys the Extractor. virtual bool extract(std::size_t pos, Poco::Int8& val); /// Extracts an Int8. virtual bool extract(std::size_t pos, Poco::UInt8& val); /// Extracts an UInt8. virtual bool extract(std::size_t pos, Poco::Int16& val); /// Extracts an Int16. virtual bool extract(std::size_t pos, Poco::UInt16& val); /// Extracts an UInt16. virtual bool extract(std::size_t pos, Poco::Int32& val); /// Extracts an Int32. virtual bool extract(std::size_t pos, Poco::UInt32& val); /// Extracts an UInt32. virtual bool extract(std::size_t pos, Poco::Int64& val); /// Extracts an Int64. virtual bool extract(std::size_t pos, Poco::UInt64& val); /// Extracts an UInt64. virtual bool extract(std::size_t pos, bool& val); /// Extracts a boolean. virtual bool extract(std::size_t pos, float& val); /// Extracts a float. virtual bool extract(std::size_t pos, double& val); /// Extracts a double. virtual bool extract(std::size_t pos, char& val); /// Extracts a single character. virtual bool extract(std::size_t pos, std::string& val); /// Extracts a string. virtual bool extract(std::size_t pos, Poco::Data::BLOB& val); /// Extracts a BLOB. private: bool realExtractFixed(std::size_t pos, enum_field_types type, void* buffer, size_t length = 0); // Prevent VC8 warning "operator= could not be generated" Extractor& operator=(const Extractor&); private: StatementExecutor& _stmt; ResultMetadata& _metadata; }; } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_Extractor_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/MySQL.h0000644000076500001200000000554011313735447023357 0ustar guenteradmin00000000000000// // MySQL.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/MySQL.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: MySQL // // Basic definitions for the MySQL library. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef MySQL_MySQL_INCLUDED #define MySQL_MySQL_INCLUDED #include "Poco/Foundation.h" // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the ODBC_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // ODBC_API functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) #if defined(MYSQL_EXPORTS) #define MySQL_API __declspec(dllexport) #else #define MySQL_API __declspec(dllimport) #endif #endif #if !defined(MySQL_API) #define MySQL_API #endif // // Automatically link Data library. // #if defined(_MSC_VER) #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(MYSQL_EXPORTS) #if defined(POCO_DLL) #if defined(_DEBUG) #pragma comment(lib, "PocoMySQLd.lib") #else #pragma comment(lib, "PocoMySQL.lib") #endif #else #if defined(_DEBUG) #pragma comment(lib, "PocoMySQLmtd.lib") #else #pragma comment(lib, "PocoMySQLmt.lib") #endif #endif #endif #endif #endif // MySQL_MySQL_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/MySQLException.h0000644000076500001200000001022011313735447025225 0ustar guenteradmin00000000000000// // MySQLException.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/MySQLException.h#4 $ // // Library: Data/MySQL // Package: MySQL // Module: MySQLException // // Definition of the MySQLException class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_MySQLException_INCLUDED #define Data_MySQL_MySQLException_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/DataException.h" #include #include typedef struct st_mysql MYSQL; typedef struct st_mysql_stmt MYSQL_STMT; namespace Poco { namespace Data { namespace MySQL { class MySQL_API MySQLException: public Poco::Data::DataException /// Base class for all MySQL exceptions { public: MySQLException(const std::string& msg, int code = 0); /// Creates MySQLException. MySQLException(const MySQLException& exc); /// Creates MySQLException. ~MySQLException() throw(); /// Destroys MySQLexception. MySQLException& operator=(const MySQLException& exc); /// Assignment operator. const char* name() const throw(); /// Returns exception name. const char* className() const throw(); /// Returns the name of the exception class. Poco::Exception* clone() const; /// Creates an exact copy of the exception. /// /// The copy can later be thrown again by /// invoking rethrow() on it. void rethrow() const; /// (Re)Throws the exception. /// /// This is useful for temporarily storing a /// copy of an exception (see clone()), then /// throwing it again. }; class ConnectionException : public MySQLException /// ConnectionException { public: ConnectionException(const std::string& msg); /// Creates ConnectionException. ConnectionException(const std::string& text, MYSQL* h); /// Destroys ConnectionException. private: static std::string compose(const std::string& text, MYSQL* h); }; class StatementException : public MySQLException /// StatementException { public: StatementException(const std::string& msg, int code = 0); /// Creates StatementException. StatementException(const std::string& text, MYSQL_STMT* h, const std::string& stmt = ""); /// Destroys StatementException. private: static std::string compose(const std::string& text, MYSQL_STMT* h, const std::string& stmt); }; // // inlines // inline MySQLException& MySQLException::operator=(const MySQLException& exc) { Poco::Data::DataException::operator=(exc); return *this; } inline const char* MySQLException::name() const throw() { return "MySQL"; } inline const char* MySQLException::className() const throw() { return typeid(*this).name(); } inline Poco::Exception* MySQLException::clone() const { return new MySQLException(*this); } inline void MySQLException::rethrow() const { throw *this; } } } } // namespace Poco::Data::MySQL #endif //Data_MySQL_MySQLException_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/MySQLStatementImpl.h0000644000076500001200000000700411313735447026063 0ustar guenteradmin00000000000000// // MySQLstatementImpl.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/MySQLStatementImpl.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: MySQLstatementImpl // // Definition of the MySQLStatementImpl class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_MySQLStatementImpl_INCLUDED #define Data_MySQL_MySQLStatementImpl_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/MySQL/SessionImpl.h" #include "Poco/Data/MySQL/Binder.h" #include "Poco/Data/MySQL/Extractor.h" #include "Poco/Data/MySQL/StatementExecutor.h" #include "Poco/Data/MySQL/ResultMetadata.h" #include "Poco/Data/StatementImpl.h" #include "Poco/SharedPtr.h" #include "Poco/Format.h" namespace Poco { namespace Data { namespace MySQL { class MySQL_API MySQLStatementImpl: public Poco::Data::StatementImpl /// Implements statement functionality needed for MySQL { public: MySQLStatementImpl(SessionHandle& h); /// Creates the MySQLStatementImpl. ~MySQLStatementImpl(); /// Destroys the MySQLStatementImpl. protected: virtual Poco::UInt32 columnsReturned() const; /// Returns number of columns returned by query. virtual const MetaColumn& metaColumn(Poco::UInt32 pos) const; /// Returns column meta data. virtual bool hasNext(); /// Returns true if a call to next() will return data. virtual void next(); /// Retrieves the next row from the resultset. /// Will throw, if the resultset is empty. virtual bool canBind() const; /// Returns true if a valid statement is set and we can bind. virtual void compileImpl(); /// Compiles the statement, doesn't bind yet virtual void bindImpl(); /// Binds parameters virtual AbstractExtractor& extractor(); /// Returns the concrete extractor used by the statement. virtual AbstractBinder& binder(); /// Returns the concrete binder used by the statement. private: enum { NEXT_DONTKNOW, NEXT_TRUE, NEXT_FALSE }; StatementExecutor _stmt; ResultMetadata _metadata; Binder _binder; Extractor _extractor; int _hasNext; }; } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_MySQLStatementImpl_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/ResultMetadata.h0000644000076500001200000000537211313735447025334 0ustar guenteradmin00000000000000// // ResultMetadata.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/ResultMetadata.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: ResultMetadata // // Definition of the ResultMetadata class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_ResultMetadata_INCLUDED #define Data_MySQL_ResultMetadata_INCLUDED #include #include #include "Poco/Data/MetaColumn.h" namespace Poco { namespace Data { namespace MySQL { class ResultMetadata /// MySQL result metadata { public: void reset(); /// Resets the metadata. void init(MYSQL_STMT* stmt); /// Initializes the metadata. Poco::UInt32 columnsReturned() const; /// Returns the number of columns in resultset. const MetaColumn& metaColumn(Poco::UInt32 pos) const; /// Returns the reference to the specified metacolumn. MYSQL_BIND* row(); /// Returns pointer to native row. std::size_t length(std::size_t pos) const; /// Returns the length. const char* rawData(std::size_t pos) const; /// Returns raw data. bool isNull(std::size_t pos) const; /// Returns true if value at pos is null. private: std::vector _columns; std::vector _row; std::vector _buffer; std::vector _lengths; std::vector _isNull; }; } } } // namespace Poco::Data::MySQL #endif //Data_MySQL_ResultMetadata_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/SessionHandle.h0000644000076500001200000000474511313735447025157 0ustar guenteradmin00000000000000// // SesssionHandle.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/SessionHandle.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: SessionHandle // // Definition of the SessionHandle class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_SessionHandle_INCLUDED #define Data_MySQL_SessionHandle_INCLUDED #include #include "Poco/Data/MySQL/MySQLException.h" #include namespace Poco { namespace Data { namespace MySQL { class SessionHandle /// MySQL session handle { public: explicit SessionHandle(MYSQL* mysql); ~SessionHandle(); void options(mysql_option opt); void options(mysql_option opt, bool b); void connect(const char* host, const char* user, const char* password, const char* db, unsigned int port); void close(); void query(const char* str); operator MYSQL* (); private: SessionHandle(const SessionHandle&); SessionHandle& operator=(const SessionHandle&); private: MYSQL* h; }; // // inlines // inline SessionHandle::operator MYSQL* () { return h; } } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_SessionHandle_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/SessionImpl.h0000644000076500001200000000710511313735447024656 0ustar guenteradmin00000000000000// // SessionImpl.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/SessionImpl.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: SessionImpl // // Definition of the SessionImpl class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_SessionImpl_INCLUDED #define Data_MySQL_SessionImpl_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/AbstractSessionImpl.h" #include "Poco/Data/MySQL/SessionHandle.h" namespace Poco { namespace Data { namespace MySQL { class MySQL_API SessionImpl: public Poco::Data::AbstractSessionImpl /// Implements SessionImpl interface { public: SessionImpl(const std::string& connectionString); /// Creates the SessionImpl. Opens a connection to the database /// /// Connection string format: /// == | ';' /// == '=' /// == 'host' | 'port' | 'user' | 'password' | 'db' } 'compress' | 'auto-reconnect' /// == [~;]* /// /// for compress and auto-reconnect correct values are true/false /// for port - numeric in decimal notation /// ~SessionImpl(); /// Destroys the SessionImpl. virtual Poco::Data::StatementImpl* createStatementImpl(); /// Returns an MySQL StatementImpl virtual void begin(); /// Starts a transaction virtual void commit(); /// Commits and ends a transaction virtual void rollback(); /// Aborts a transaction virtual void close(); /// Closes the connection virtual bool isConnected(); /// Returns true iff session is connected. virtual bool isTransaction(); /// Returns true iff a transaction is in progress. void setInsertId(const std::string&, const Poco::Any&); /// Try to set insert id - do nothing. Poco::Any getInsertId(const std::string&); /// Get insert id private: SessionHandle _mysql; bool _connected; int _inTransaction; }; // // inlines // inline void SessionImpl::setInsertId(const std::string&, const Poco::Any&) { } inline Poco::Any SessionImpl::getInsertId(const std::string&) { return Poco::Any(Poco::UInt64(mysql_insert_id(_mysql))); } } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_SessionImpl_INCLUDED poco-1.3.6p1-all/Data/MySQL/include/Poco/Data/MySQL/StatementExecutor.h0000644000076500001200000000573011313735447026076 0ustar guenteradmin00000000000000// // StatementExecutor.h // // $Id: //poco/1.3/Data/MySQL/include/Poco/Data/MySQL/StatementExecutor.h#3 $ // // Library: Data/MySQL // Package: MySQL // Module: StatementExecutor // // Definition of the StatementExecutor class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_MySQL_StatementHandle_INCLUDED #define Data_MySQL_StatementHandle_INCLUDED #include #include "Poco/Data/MySQL/MySQLException.h" #include namespace Poco { namespace Data { namespace MySQL { class StatementExecutor /// MySQL statement executor. { public: enum State { STMT_INITED, STMT_COMPILED, STMT_EXECUTED }; explicit StatementExecutor(MYSQL* mysql); /// Creates the StatementExecutor. ~StatementExecutor(); /// Destroys the StatementExecutor. int state() const; /// Returns the current state. void prepare(const std::string& query); /// Prepares the statement for execution. void bindParams(MYSQL_BIND* params, size_t count); /// Binds the params. void bindResult(MYSQL_BIND* result); /// Binds result. void execute(); /// Executes the statement. bool fetch(); /// Fetches the data. bool fetchColumn(size_t n, MYSQL_BIND *bind); /// Fetches the column. operator MYSQL_STMT* (); /// Cast operator to native handle type. private: StatementExecutor(const StatementExecutor&); StatementExecutor& operator=(const StatementExecutor&); private: MYSQL_STMT* h; int _state; std::string _query; }; // // inlines // inline StatementExecutor::operator MYSQL_STMT* () { return h; } } } } // namespace Poco::Data::MySQL #endif // Data_MySQL_StatementHandle_INCLUDED poco-1.3.6p1-all/Data/MySQL/Makefile0000644000076500001200000000122711313735447017536 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/MySQL/Makefile#4 $ # # Makefile for Poco MySQL # include $(POCO_BASE)/build/rules/global SYSLIBS += -L/usr/local/lib/mysql -L/usr/lib/mysql -L/usr/mysql/lib/mysql -L/usr/local/mysql/lib -lmysqlclient INCLUDE += -I/usr/local/include/mysql/ -I/usr/include/mysql -I/usr/mysql/include/mysql -I/usr/local/mysql/include SYSFLAGS += -DTHREADSAFE -DNO_TCL objects = Binder Extractor SessionImpl Connector \ MySQLStatementImpl ResultMetadata MySQLException \ SessionHandle StatementExecutor target = PocoMySQL target_version = $(LIBVERSION) target_libs = PocoData PocoFoundation include $(POCO_BASE)/build/rules/lib poco-1.3.6p1-all/Data/MySQL/MySQL_VS71.sln0000644000076500001200000000447711313735447020353 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MySQL", "MySQL_VS71.vcproj", "{55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS71.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E} = {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E} EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared debug_static = debug_static release_static = release_static EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.debug_shared.ActiveCfg = debug_shared|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.debug_shared.Build.0 = debug_shared|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.release_shared.ActiveCfg = release_shared|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.release_shared.Build.0 = release_shared|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.debug_static.ActiveCfg = debug_static|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.debug_static.Build.0 = debug_static|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.release_static.ActiveCfg = release_static|Win32 {55F99C16-6BDF-4009-ABDB-653F7EE6FE9E}.release_static.Build.0 = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/MySQL/MySQL_VS71.vcproj0000644000076500001200000002062311313735447021051 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/MySQL/MySQL_VS80.sln0000644000076500001200000000460711313735447020346 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS80.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {73E19FDE-1570-488C-B3DB-72A60FADD408} = {73E19FDE-1570-488C-B3DB-72A60FADD408} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MySQL", "MySQL_VS80.vcproj", "{73E19FDE-1570-488C-B3DB-72A60FADD408}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_shared|Win32.Build.0 = debug_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_shared|Win32.ActiveCfg = release_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_shared|Win32.Build.0 = release_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_static|Win32.ActiveCfg = debug_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_static|Win32.Build.0 = debug_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_static|Win32.ActiveCfg = release_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/MySQL/MySQL_VS80.vcproj0000644000076500001200000002171511313735447021054 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/MySQL/MySQL_vs90.sln0000644000076500001200000000461011313735447020441 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs90.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {73E19FDE-1570-488C-B3DB-72A60FADD408} = {73E19FDE-1570-488C-B3DB-72A60FADD408} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MySQL", "MySQL_vs90.vcproj", "{73E19FDE-1570-488C-B3DB-72A60FADD408}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_shared|Win32.Build.0 = debug_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_shared|Win32.ActiveCfg = release_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_shared|Win32.Build.0 = release_shared|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_static|Win32.ActiveCfg = debug_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.debug_static|Win32.Build.0 = debug_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_static|Win32.ActiveCfg = release_static|Win32 {73E19FDE-1570-488C-B3DB-72A60FADD408}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/MySQL/MySQL_vs90.vcproj0000644000076500001200000002171311313735447021153 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/MySQL/src/0000755000076500001200000000000011313735447016663 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/src/Binder.cpp0000644000076500001200000000771411313735447020603 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/Binder.cpp#4 $ // // Library: Data/MySQL // Package: MySQL // Module: Binder // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/Binder.h" namespace Poco { namespace Data { namespace MySQL { Binder::Binder() { } Binder::~Binder() { } void Binder::bind(std::size_t pos, const Poco::Int8& val) { realBind(pos, MYSQL_TYPE_TINY, &val, 0); } void Binder::bind(std::size_t pos, const Poco::UInt8& val) { realBind(pos, MYSQL_TYPE_TINY, &val, 0); } void Binder::bind(std::size_t pos, const Poco::Int16& val) { realBind(pos, MYSQL_TYPE_SHORT, &val, 0); } void Binder::bind(std::size_t pos, const Poco::UInt16& val) { realBind(pos, MYSQL_TYPE_SHORT, &val, 0); } void Binder::bind(std::size_t pos, const Poco::Int32& val) { realBind(pos, MYSQL_TYPE_LONG, &val, 0); } void Binder::bind(std::size_t pos, const Poco::UInt32& val) { realBind(pos, MYSQL_TYPE_LONG, &val, 0); } void Binder::bind(std::size_t pos, const Poco::Int64& val) { realBind(pos, MYSQL_TYPE_LONGLONG, &val, 0); } void Binder::bind(std::size_t pos, const Poco::UInt64& val) { realBind(pos, MYSQL_TYPE_LONGLONG, &val, 0); } void Binder::bind(std::size_t pos, const bool& val) { realBind(pos, MYSQL_TYPE_TINY, &val, 0); } void Binder::bind(std::size_t pos, const float& val) { realBind(pos, MYSQL_TYPE_FLOAT, &val, 0); } void Binder::bind(std::size_t pos, const double& val) { realBind(pos, MYSQL_TYPE_DOUBLE, &val, 0); } void Binder::bind(std::size_t pos, const char& val) { realBind(pos, MYSQL_TYPE_TINY, &val, 0); } void Binder::bind(std::size_t pos, const std::string& val) { realBind(pos, MYSQL_TYPE_STRING, val.c_str(), static_cast(val.length())); } void Binder::bind(std::size_t pos, const Poco::Data::BLOB& val) { realBind(pos, MYSQL_TYPE_STRING, val.rawContent(), static_cast(val.size())); } size_t Binder::size() const { return _bindArray.size(); } MYSQL_BIND* Binder::getBindArray() const { if (_bindArray.size() == 0) { return 0; } return const_cast(&_bindArray[0]); } void Binder::realBind(std::size_t pos, enum_field_types type, const void* buffer, int length) { if (pos > 1024) { throw StatementException("too many bind parameters"); } if (pos >= _bindArray.size()) { size_t s = _bindArray.size(); _bindArray.resize(pos + 1); std::memset(&_bindArray[s], 0, sizeof(MYSQL_BIND) * (_bindArray.size() - s)); } MYSQL_BIND b = {0}; b.buffer_type = type; b.buffer = const_cast(buffer); b.buffer_length = length; _bindArray[pos] = b; } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/Connector.cpp0000644000076500001200000000463411313735447021330 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/Connector.cpp#3 $ // // Library: Data/MySQL // Package: MySQL // Module: Connector // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/Connector.h" #include "Poco/Data/MySQL/SessionImpl.h" #include "Poco/Data/SessionFactory.h" #include "Poco/Exception.h" #include namespace Poco { namespace Data { namespace MySQL { std::string Connector::KEY("MySQL"); Connector::Connector() { } Connector::~Connector() { } Poco::AutoPtr Connector::createSession(const std::string& connectionString) { return Poco::AutoPtr(new SessionImpl(connectionString)); } void Connector::registerConnector() { if (mysql_library_init(0, 0, 0) != 0) { throw Exception("mysql_library_init error"); } Poco::Data::SessionFactory::instance().add(KEY, new Connector()); } void Connector::unregisterConnector() { Poco::Data::SessionFactory::instance().remove(KEY); mysql_library_end(); } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/Extractor.cpp0000644000076500001200000001115111313735447021341 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/Extractor.cpp#3 $ // // Library: Data/MySQL // Package: MySQL // Module: Extractor // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/Extractor.h" namespace Poco { namespace Data { namespace MySQL { Extractor::Extractor(StatementExecutor& st, ResultMetadata& md): _stmt(st), _metadata(md) { } Extractor::~Extractor() { } bool Extractor::extract(std::size_t pos, Poco::Int8& val) { return realExtractFixed(pos, MYSQL_TYPE_TINY, &val); } bool Extractor::extract(std::size_t pos, Poco::UInt8& val) { return realExtractFixed(pos, MYSQL_TYPE_TINY, &val); } bool Extractor::extract(std::size_t pos, Poco::Int16& val) { return realExtractFixed(pos, MYSQL_TYPE_SHORT, &val); } bool Extractor::extract(std::size_t pos, Poco::UInt16& val) { return realExtractFixed(pos, MYSQL_TYPE_SHORT, &val); } bool Extractor::extract(std::size_t pos, Poco::Int32& val) { return realExtractFixed(pos, MYSQL_TYPE_LONG, &val); } bool Extractor::extract(std::size_t pos, Poco::UInt32& val) { return realExtractFixed(pos, MYSQL_TYPE_LONG, &val); } bool Extractor::extract(std::size_t pos, Poco::Int64& val) { return realExtractFixed(pos, MYSQL_TYPE_LONGLONG, &val); } bool Extractor::extract(std::size_t pos, Poco::UInt64& val) { return realExtractFixed(pos, MYSQL_TYPE_LONGLONG, &val); } bool Extractor::extract(std::size_t pos, bool& val) { return realExtractFixed(pos, MYSQL_TYPE_TINY, &val); } bool Extractor::extract(std::size_t pos, float& val) { return realExtractFixed(pos, MYSQL_TYPE_FLOAT, &val); } bool Extractor::extract(std::size_t pos, double& val) { return realExtractFixed(pos, MYSQL_TYPE_DOUBLE, &val); } bool Extractor::extract(std::size_t pos, char& val) { return realExtractFixed(pos, MYSQL_TYPE_TINY, &val); } bool Extractor::extract(std::size_t pos, std::string& val) { if (_metadata.columnsReturned() <= pos) throw MySQLException("Extractor: attempt to extract more paremeters, than query result contain"); if (_metadata.isNull(static_cast(pos))) return false; if (_metadata.metaColumn(static_cast(pos)).type() != Poco::Data::MetaColumn::FDT_STRING) throw MySQLException("Extractor: not a string"); val.assign(_metadata.rawData(pos), _metadata.length(pos)); return true; } bool Extractor::extract(std::size_t pos, Poco::Data::BLOB& val) { if (_metadata.columnsReturned() <= pos) throw MySQLException("Extractor: attempt to extract more paremeters, than query result contain"); if (_metadata.isNull(static_cast(pos))) return false; if (_metadata.metaColumn(static_cast(pos)).type() != Poco::Data::MetaColumn::FDT_BLOB) throw MySQLException("Extractor: not a blob"); val.assignRaw(_metadata.rawData(pos), _metadata.length(pos)); return true; } bool Extractor::realExtractFixed(std::size_t pos, enum_field_types type, void* buffer, size_t length) { MYSQL_BIND bind = {0}; my_bool isNull = 0; bind.is_null = &isNull; bind.buffer_type = type; bind.buffer = buffer; bind.buffer_length = static_cast(length); if (!_stmt.fetchColumn(pos, &bind)) return false; return isNull == 0; } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/MySQLException.cpp0000644000076500001200000000636211313735447022222 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/MySQLException.cpp#5 $ // // Library: Data/MySQL // Package: MySQL // Module: MySQLException // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/MySQLException.h" #include #include namespace Poco { namespace Data { namespace MySQL { MySQLException::MySQLException(const std::string& msg, int code): Poco::Data::DataException(std::string("[MySQL]: ") + msg, code) { } MySQLException::MySQLException(const MySQLException& exc): Poco::Data::DataException(exc) { } MySQLException::~MySQLException() throw() { } ConnectionException::ConnectionException(const std::string& msg): MySQLException(msg) { } ConnectionException::ConnectionException(const std::string& text, MYSQL* h): MySQLException(compose(text, h)) { } StatementException::StatementException(const std::string& msg, int code): MySQLException(msg, code) { } StatementException::StatementException(const std::string& text, MYSQL_STMT* h, const std::string& stmt): MySQLException(compose(text, h, stmt), mysql_stmt_errno(h)) { } std::string ConnectionException::compose(const std::string& text, MYSQL* h) { std::ostringstream str; str << "[Comment]: << text\t[mysql_error]: " << mysql_error(h) << "\t[mysql_errno]: "; str << mysql_errno(h) << "\t[mysql_sqlstate]: " << mysql_sqlstate(h); return str.str(); } std::string StatementException::compose(const std::string& text, MYSQL_STMT* h, const std::string& stmt) { std::ostringstream str; str << "[Comment]: " << text; if (h != 0) { str << "\t[mysql_stmt_error]: "; str << mysql_stmt_error(h); str << "\t[mysql_stmt_errno]: " << mysql_stmt_errno(h); str << "\t[mysql_stmt_sqlstate]: "; str << mysql_stmt_sqlstate(h); } if (stmt.length() > 0) { str << "\t[statemnt]: "; str << stmt; } return str.str(); } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/MySQLStatementImpl.cpp0000644000076500001200000000746311313735447023055 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/MySQLStatementImpl.cpp#3 $ // // Library: Data/MySQL // Package: MySQL // Module: MySQLStatementImpl // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/MySQLStatementImpl.h" namespace Poco { namespace Data { namespace MySQL { MySQLStatementImpl::MySQLStatementImpl(SessionHandle& h): _stmt(h), _extractor(_stmt, _metadata), _hasNext(NEXT_DONTKNOW) { } MySQLStatementImpl::~MySQLStatementImpl() { } Poco::UInt32 MySQLStatementImpl::columnsReturned() const { return _metadata.columnsReturned(); } const MetaColumn& MySQLStatementImpl::metaColumn(Poco::UInt32 pos) const { return _metadata.metaColumn(pos); } bool MySQLStatementImpl::hasNext() { if (_hasNext == NEXT_DONTKNOW) { if (_metadata.columnsReturned() == 0) { return false; } if (_stmt.fetch()) { _hasNext = NEXT_TRUE; return true; } _hasNext = NEXT_FALSE; return false; } else if (_hasNext == NEXT_TRUE) { return true; } return false; } void MySQLStatementImpl::next() { if (!hasNext()) throw StatementException("No data received"); Poco::Data::AbstractExtractionVec::iterator it = extractions().begin(); Poco::Data::AbstractExtractionVec::iterator itEnd = extractions().end(); std::size_t pos = 0; for (; it != itEnd; ++it) { (*it)->extract(pos); pos += (*it)->numOfColumnsHandled(); } _hasNext = NEXT_DONTKNOW; } bool MySQLStatementImpl::canBind() const { bool ret = false; if ((_stmt.state() >= StatementExecutor::STMT_COMPILED) && !bindings().empty()) ret = (*bindings().begin())->canBind(); return ret; } void MySQLStatementImpl::compileImpl() { _metadata.reset(); _stmt.prepare(toString()); _metadata.init(_stmt); if (_metadata.columnsReturned() > 0) { _stmt.bindResult(_metadata.row()); } } void MySQLStatementImpl::bindImpl() { { Poco::Data::AbstractBindingVec& binds = bindings(); size_t pos = 0; Poco::Data::AbstractBindingVec::iterator it = binds.begin(); Poco::Data::AbstractBindingVec::iterator itEnd = binds.end(); for (; it != itEnd && (*it)->canBind(); ++it) { (*it)->bind(pos); pos += (*it)->numOfColumnsHandled(); } } _stmt.bindParams(_binder.getBindArray(), _binder.size()); _stmt.execute(); _hasNext = NEXT_DONTKNOW; } AbstractExtractor& MySQLStatementImpl::extractor() { return _extractor; } AbstractBinder& MySQLStatementImpl::binder() { return _binder; } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/ResultMetadata.cpp0000644000076500001200000001554711313735447022322 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/ResultMetadata.cpp#7 $ // // Library: Data/MySQL // Package: MySQL // Module: ResultMetadata // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/ResultMetadata.h" #include "Poco/Data/MySQL/MySQLException.h" #include namespace { class ResultMetadataHandle /// Simple exception-safe wrapper { public: explicit ResultMetadataHandle(MYSQL_STMT* stmt) { h = mysql_stmt_result_metadata(stmt); } ~ResultMetadataHandle() { if (h) { mysql_free_result(h); } } operator MYSQL_RES* () { return h; } private: MYSQL_RES* h; }; size_t fieldSize(const MYSQL_FIELD& field) /// Convert field MySQL-type and field MySQL-length to actual field length { switch (field.type) { case MYSQL_TYPE_TINY: return sizeof(char); case MYSQL_TYPE_SHORT: return sizeof(short); case MYSQL_TYPE_INT24: case MYSQL_TYPE_LONG: return sizeof(Poco::Int32); case MYSQL_TYPE_FLOAT: return sizeof(float); case MYSQL_TYPE_DOUBLE: return sizeof(double); case MYSQL_TYPE_LONGLONG: return sizeof(Poco::Int64); case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: case MYSQL_TYPE_STRING: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_NULL: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_YEAR: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_BIT: case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: case MYSQL_TYPE_GEOMETRY: default: return field.length; } throw Poco::Data::MySQL::StatementException("unknown field type"); } Poco::Data::MetaColumn::ColumnDataType fieldType(const MYSQL_FIELD& field) /// Convert field MySQL-type to Poco-type { bool unsig = ((field.flags & UNSIGNED_FLAG) == UNSIGNED_FLAG); switch (field.type) { case MYSQL_TYPE_TINY: if (unsig) return Poco::Data::MetaColumn::FDT_UINT8; return Poco::Data::MetaColumn::FDT_INT8; case MYSQL_TYPE_SHORT: if (unsig) return Poco::Data::MetaColumn::FDT_UINT16; return Poco::Data::MetaColumn::FDT_INT16; case MYSQL_TYPE_INT24: case MYSQL_TYPE_LONG: if (unsig) return Poco::Data::MetaColumn::FDT_UINT32; return Poco::Data::MetaColumn::FDT_INT32; case MYSQL_TYPE_FLOAT: return Poco::Data::MetaColumn::FDT_FLOAT; case MYSQL_TYPE_DOUBLE: return Poco::Data::MetaColumn::FDT_DOUBLE; case MYSQL_TYPE_LONGLONG: if (unsig) return Poco::Data::MetaColumn::FDT_UINT64; return Poco::Data::MetaColumn::FDT_INT64; case MYSQL_TYPE_STRING: case MYSQL_TYPE_VAR_STRING: return Poco::Data::MetaColumn::FDT_STRING; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: return Poco::Data::MetaColumn::FDT_BLOB; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: case MYSQL_TYPE_NULL: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_YEAR: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_BIT: case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: case MYSQL_TYPE_GEOMETRY: default: return Poco::Data::MetaColumn::FDT_UNKNOWN; } return Poco::Data::MetaColumn::FDT_UNKNOWN; } } // namespace namespace Poco { namespace Data { namespace MySQL { void ResultMetadata::reset() { _columns.resize(0); _row.resize(0); _buffer.resize(0); _lengths.resize(0); _isNull.resize(0); } void ResultMetadata::init(MYSQL_STMT* stmt) { ResultMetadataHandle h(stmt); if (!h) { // all right, it is normal // querys such an "INSERT INTO" just does not have result at all reset(); return; } size_t count = mysql_num_fields(h); MYSQL_FIELD* fields = mysql_fetch_fields(h); size_t commonSize = 0; _columns.reserve(count); for (size_t i = 0; i < count; i++) { _columns.push_back(MetaColumn( i, // position fields[i].name, // name fieldType(fields[i]), // type fieldSize(fields[i]), // length 0, // TODO: precision (Now I dont know how to get it) !IS_NOT_NULL(fields[i].flags) // nullable )); commonSize += _columns[i].length(); } _buffer.resize(commonSize); _row.resize(count); _lengths.resize(count); _isNull.resize(count); size_t offset = 0; for (size_t i = 0; i < count; i++) { std::memset(&_row[i], 0, sizeof(MYSQL_BIND)); _row[i].buffer_type = fields[i].type; _row[i].buffer_length = static_cast(_columns[i].length()); _row[i].buffer = &_buffer[0] + offset; _row[i].length = &_lengths[i]; _row[i].is_null = &_isNull[i]; _row[i].is_unsigned = (my_bool) ((fields[i].flags & UNSIGNED_FLAG) == UNSIGNED_FLAG); offset += _row[i].buffer_length; } } Poco::UInt32 ResultMetadata::columnsReturned() const { return static_cast(_columns.size()); } const MetaColumn& ResultMetadata::metaColumn(Poco::UInt32 pos) const { return _columns[pos]; } MYSQL_BIND* ResultMetadata::row() { return &_row[0]; } size_t ResultMetadata::length(size_t pos) const { return _lengths[pos]; } const char* ResultMetadata::rawData(size_t pos) const { return reinterpret_cast(_row[pos].buffer); } bool ResultMetadata::isNull(size_t pos) const { return (_isNull[pos] != 0); } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/SessionHandle.cpp0000644000076500001200000000556111313735447022135 0ustar guenteradmin00000000000000// // SesssionHandle.cpp // // $Id: //poco/1.3/Data/MySQL/src/SessionHandle.cpp#4 $ // // Library: Data/MySQL // Package: MySQL // Module: SessionHandle // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/SessionHandle.h" #include namespace Poco { namespace Data { namespace MySQL { SessionHandle::SessionHandle(MYSQL* mysql) { h = mysql_init(mysql); if (!h) { throw ConnectionException("mysql_init error"); } } SessionHandle::~SessionHandle() { close(); } void SessionHandle::options(mysql_option opt) { int res = mysql_options(h, opt, 0); if (res != 0) { throw ConnectionException("mysql_options error", h); } } void SessionHandle::options(mysql_option opt, bool b) { my_bool tmp = b; int res = mysql_options(h, opt, &tmp); if (res != 0) { throw ConnectionException("mysql_options error", h); } } void SessionHandle::connect(const char* host, const char* user, const char* password, const char* db, unsigned int port) { if (!mysql_real_connect(h, host, user, password, db, port, 0, 0)) { throw ConnectionException("create session: mysql_real_connect error", h); } } void SessionHandle::close() { if (h) { mysql_close(h); h = 0; } } void SessionHandle::query(const char* str) { int res = mysql_real_query(h, str, static_cast(std::strlen(str))); if (res != 0) { std::string msg; msg += "mysql_real_query('"; msg += str; msg += "') error"; throw ConnectionException(msg, h); } } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/SessionImpl.cpp0000644000076500001200000001213611313735447021637 0ustar guenteradmin00000000000000// // MySQLException.cpp // // $Id: //poco/1.3/Data/MySQL/src/SessionImpl.cpp#4 $ // // Library: Data/MySQL // Package: MySQL // Module: SessionImpl // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/MySQL/SessionImpl.h" #include "Poco/Data/MySQL/MySQLStatementImpl.h" #include "Poco/NumberParser.h" namespace { std::string copyStripped(std::string::const_iterator from, std::string::const_iterator to) { // skip leading spaces while ((from != to) && isspace(*from)) from++; // skip trailing spaces while ((from != to) && isspace(*(to - 1))) to--; return std::string(from, to); } } namespace Poco { namespace Data { namespace MySQL { SessionImpl::SessionImpl(const std::string& connectionString) : _mysql(0), _connected(false), _inTransaction(0) { addProperty("insertId", &SessionImpl::setInsertId, &SessionImpl::getInsertId); std::map options; // Default values options["host"] = "localhost"; options["port"] = "3306"; options["user"] = ""; options["password"] = ""; options["db"] = ""; options["compress"] = ""; options["auto-reconnect"] = ""; // // Parse string // for (std::string::const_iterator start = connectionString.begin();;) { // find next ';' std::string::const_iterator finish = std::find(start, connectionString.end(), ';'); // find '=' std::string::const_iterator middle = std::find(start, finish, '='); if (middle == finish) { throw MySQLException("create session: bad connection string format, can not find '='"); } // Parse name and value, skip all spaces options[copyStripped(start, middle)] = copyStripped(middle + 1, finish); if (finish == connectionString.end()) { // end of parse break; } // move start position after ';' start = finish + 1; } // // Checking // if (options["user"] == "") { throw MySQLException("create session: specify user name"); } if (options["db"] == "") { throw MySQLException("create session: specify database"); } unsigned int port = 0; if (!NumberParser::tryParseUnsigned(options["port"], port) || 0 == port || port > 65535) { throw MySQLException("create session: specify correct port (numeric in decimal notation)"); } // // Options // if (options["compress"] == "true") { _mysql.options(MYSQL_OPT_COMPRESS); } else if (options["compress"] == "false") { // do nothing } else if (options["compress"] != "") { throw MySQLException("create session: specify correct compress option (true or false) or skip it"); } if (options["auto-reconnect"] == "true") { _mysql.options(MYSQL_OPT_RECONNECT, true); } else if (options["auto-reconnect"] == "false") { _mysql.options(MYSQL_OPT_RECONNECT, false); } else if (options["auto-reconnect"] != "") { throw MySQLException("create session: specify correct auto-reconnect option (true or false) or skip it"); } // // Real connect // _mysql.connect( options["host"].c_str(), options["user"].c_str(), options["password"].c_str(), options["db"].c_str(), port); _connected = true; } SessionImpl::~SessionImpl() { close(); } Poco::Data::StatementImpl* SessionImpl::createStatementImpl() { return new MySQLStatementImpl(_mysql); } void SessionImpl::begin() { _mysql.query("START TRANSACTION"); _inTransaction++; } void SessionImpl::commit() { _mysql.query("COMMIT"); _inTransaction--; // ? // mysql_commit(fMysql); } void SessionImpl::rollback() { _mysql.query("ROLLBACK"); _inTransaction--; // ? // mysql_commit(fMysql); } void SessionImpl::close() { if (_connected) { _mysql.close(); _connected = false; } } bool SessionImpl::isConnected() { return _connected; } bool SessionImpl::isTransaction() { return (_inTransaction > 0); } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/src/StatementExecutor.cpp0000644000076500001200000001030011313735447023044 0ustar guenteradmin00000000000000// // StatementExecutor.cpp // // $Id: //poco/1.3/Data/MySQL/src/StatementExecutor.cpp#4 $ // // Library: Data/MySQL // Package: MySQL // Module: StatementExecutor // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include #include "Poco/Data/MySQL/StatementExecutor.h" #include namespace Poco { namespace Data { namespace MySQL { StatementExecutor::StatementExecutor(MYSQL* mysql) { h = mysql_stmt_init(mysql); if (!h) { throw StatementException("mysql_stmt_init error"); } _state = STMT_INITED; } StatementExecutor::~StatementExecutor() { mysql_stmt_close(h); } int StatementExecutor::state() const { return _state; } void StatementExecutor::prepare(const std::string& query) { if (_state >= STMT_COMPILED) { throw StatementException("Satement is already compiled"); } // compile int res = mysql_stmt_prepare(h, query.c_str(), static_cast(query.length())); if (res != 0) { throw StatementException("mysql_stmt_prepare error", h, query); } _query = query; _state = STMT_COMPILED; } void StatementExecutor::bindParams(MYSQL_BIND* params, size_t count) { if (_state < STMT_COMPILED) { throw StatementException("Satement is not compiled yet"); } if (count != mysql_stmt_param_count(h)) { throw StatementException("wrong bind parameters count", 0, _query); } if (count == 0) { return; } int res = mysql_stmt_bind_param(h, params); if (res != 0) { throw StatementException("mysql_stmt_bind_param() error ", h, _query); } } void StatementExecutor::bindResult(MYSQL_BIND* result) { if (_state < STMT_COMPILED) { throw StatementException("Satement is not compiled yet"); } int res = mysql_stmt_bind_result(h, result); if (res != 0) { throw StatementException("mysql_stmt_bind_result error ", h, _query); } } void StatementExecutor::execute() { if (_state < STMT_COMPILED) { throw StatementException("Satement is not compiled yet"); } int res = mysql_stmt_execute(h); if (res != 0) { throw StatementException("mysql_stmt_execute error", h, _query); } _state = STMT_EXECUTED; } bool StatementExecutor::fetch() { if (_state < STMT_EXECUTED) { throw StatementException("Satement is not executed yet"); } int res = mysql_stmt_fetch(h); if ((res != 0) && (res != MYSQL_NO_DATA)) { throw StatementException("mysql_stmt_fetch error", h, _query); } return (res == 0); } bool StatementExecutor::fetchColumn(size_t n, MYSQL_BIND *bind) { if (_state < STMT_EXECUTED) { throw StatementException("Satement is not executed yet"); } int res = mysql_stmt_fetch_column(h, bind, static_cast(n), 0); if ((res != 0) && (res != MYSQL_NO_DATA)) { std::ostringstream msg; msg << "mysql_stmt_fetch_column(" << n << ") error"; throw StatementException(msg.str(), h, _query); } return (res == 0); } } } } // namespace Poco::Data::MySQL poco-1.3.6p1-all/Data/MySQL/testsuite/0000755000076500001200000000000011313735447020125 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/testsuite/Makefile0000644000076500001200000000112411313735447021563 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/MySQL/testsuite/Makefile#4 $ # # Makefile for Poco MySQL testsuite # include $(POCO_BASE)/build/rules/global INCLUDE += -I./../include -I/usr/local/include/mysql -I/usr/include/mysql -I/usr/mysql/include/mysql -I/usr/local/mysql/include SYSLIBS += -L/usr/local/lib/mysql -L/usr/lib/mysql -L/usr/mysql/lib/mysql -L/usr/local/mysql/lib -lmysqlclient -lz objects = MySQLTestSuite Driver \ MySQLTest SQLExecutor target = testrunner target_version = 1 target_libs = PocoMySQL PocoData PocoFoundation CppUnit include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Data/MySQL/testsuite/src/0000755000076500001200000000000011313735447020714 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/MySQL/testsuite/src/Driver.cpp0000644000076500001200000000317711313735447022663 0ustar guenteradmin00000000000000// // Driver.cpp // // $Id: //poco/1.3/Data/MySQL/testsuite/src/Driver.cpp#2 $ // // Console-based test driver for Poco SQLite. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CppUnit/TestRunner.h" #include "MySQLTestSuite.h" CppUnitMain(MySQLTestSuite) poco-1.3.6p1-all/Data/MySQL/testsuite/src/MySQLTest.cpp0000644000076500001200000003573211313735447023237 0ustar guenteradmin00000000000000// // MySQLTest.cpp // // $Id: //poco/1.3/Data/MySQL/testsuite/src/MySQLTest.cpp#3 $ // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "MySQLTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/MySQL/Connector.h" #include "Poco/Data/MySQL/MySQLException.h" #include using namespace Poco::Data; using Poco::Data::MySQL::ConnectionException; using Poco::Data::MySQL::StatementException; using Poco::format; using Poco::NotFoundException; Poco::SharedPtr MySQLTest::_pSession = 0; Poco::SharedPtr MySQLTest::_pExecutor = 0; // Parameters for barebone-test #define MYSQL_USER "test" #define MYSQL_PWD "test" #define MYSQL_HOST "localhost" #define MYSQL_PORT 3306 #define MYSQL_DB "test" // Connection string to POCO std::string MySQLTest::_dbConnString = "user=test;password=test;db=test;compress=true;auto-reconnect=true"; MySQLTest::MySQLTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; MySQL::Connector::registerConnector(); if (!beenHere) { try { _pSession = new Session(SessionFactory::instance().create(MySQL::Connector::KEY, _dbConnString)); }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. MySQL tests will fail !!!" << std::endl; std::cout << ex.displayText() << std::endl; } if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << '(' << _dbConnString << ')' << std::endl; if (!_pExecutor) _pExecutor = new SQLExecutor("MySQL SQL Executor", _pSession); } beenHere = true; } MySQLTest::~MySQLTest() { MySQL::Connector::unregisterConnector(); } void MySQLTest::testBareboneMySQL() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third VARBINARY(30)," "Fourth INTEGER," "Fifth FLOAT)"; _pExecutor->bareboneMySQLTest(MYSQL_HOST, MYSQL_USER, MYSQL_PWD, MYSQL_DB, MYSQL_PORT, tableCreateString.c_str()); } void MySQLTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->simpleAccess(); } void MySQLTest::testComplexType() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->complexType(); } void MySQLTest::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->simpleAccessVector(); } void MySQLTest::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->complexTypeVector(); } void MySQLTest::testInsertVector() { if (!_pSession) fail ("Test not available."); recreateStringsTable(); _pExecutor->insertVector(); } void MySQLTest::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); recreateStringsTable(); _pExecutor->insertEmptyVector(); } void MySQLTest::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->insertSingleBulk(); } void MySQLTest::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->insertSingleBulkVec(); } void MySQLTest::testLimit() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limits(); } void MySQLTest::testLimitZero() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitZero(); } void MySQLTest::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void MySQLTest::testLimitPrepare() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitPrepare(); } void MySQLTest::testPrepare() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->prepare(); } void MySQLTest::testSetSimple() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->setSimple(); } void MySQLTest::testSetComplex() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->setComplex(); } void MySQLTest::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->setComplexUnique(); } void MySQLTest::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->multiSetSimple(); } void MySQLTest::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->multiSetComplex(); } void MySQLTest::testMapComplex() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->mapComplex(); } void MySQLTest::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->mapComplexUnique(); } void MySQLTest::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->multiMapComplex(); } void MySQLTest::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->selectIntoSingle(); } void MySQLTest::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->selectIntoSingleStep(); } void MySQLTest::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->selectIntoSingleFail(); } void MySQLTest::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->lowerLimitOk(); } void MySQLTest::testSingleSelect() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->singleSelect(); } void MySQLTest::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->lowerLimitFail(); } void MySQLTest::testCombinedLimits() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->combinedLimits(); } void MySQLTest::testRange() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->ranges(); } void MySQLTest::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->combinedIllegalLimits(); } void MySQLTest::testIllegalRange() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->illegalRange(); } void MySQLTest::testEmptyDB() { if (!_pSession) fail ("Test not available."); recreatePersonTable(); _pExecutor->emptyDB(); } void MySQLTest::testBLOB() { if (!_pSession) fail ("Test not available."); const std::size_t maxFldSize = 65534; _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize-1)); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize); fail ("must fail"); } catch (DataException&) { _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize)); } recreatePersonBLOBTable(); _pExecutor->blob(maxFldSize); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize+1); fail ("must fail"); } catch (DataException&) { } } void MySQLTest::testBLOBStmt() { if (!_pSession) fail ("Test not available."); recreatePersonBLOBTable(); _pExecutor->blobStmt(); } void MySQLTest::testFloat() { if (!_pSession) fail ("Test not available."); recreateFloatsTable(); _pExecutor->floats(); } void MySQLTest::testDouble() { if (!_pSession) fail ("Test not available."); recreateFloatsTable(); _pExecutor->doubles(); } void MySQLTest::testTuple() { if (!_pSession) fail ("Test not available."); recreateTuplesTable(); _pExecutor->tuples(); } void MySQLTest::testTupleVector() { if (!_pSession) fail ("Test not available."); recreateTuplesTable(); _pExecutor->tupleVector(); } void MySQLTest::testInternalExtraction() { if (!_pSession) fail ("Test not available."); recreateVectorsTable(); _pExecutor->internalExtraction(); } void MySQLTest::testNull() { if (!_pSession) fail ("Test not available."); recreateVectorsTable(); _pExecutor->doNull(); } void MySQLTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ) { //throw; } } void MySQLTest::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreatePersonTable()"); } } void MySQLTest::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image BLOB)", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreatePersonBLOBTable()"); } } void MySQLTest::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreateIntsTable()"); } } void MySQLTest::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreateStringsTable()"); } } void MySQLTest::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str FLOAT)", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreateFloatsTable()"); } } void MySQLTest::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(i0 INTEGER, i1 INTEGER, i2 INTEGER, i3 INTEGER, i4 INTEGER, i5 INTEGER, i6 INTEGER, " "i7 INTEGER, i8 INTEGER, i9 INTEGER, i10 INTEGER, i11 INTEGER, i12 INTEGER, i13 INTEGER," "i14 INTEGER, i15 INTEGER, i16 INTEGER, i17 INTEGER, i18 INTEGER, i19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreateTuplesTable()"); } } void MySQLTest::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (i0 INTEGER, flt0 FLOAT, str0 VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail ("recreateVectorsTable()"); } } void MySQLTest::setUp() { } void MySQLTest::tearDown() { dropTable("Person"); dropTable("Strings"); } CppUnit::Test* MySQLTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MySQLTest"); CppUnit_addTest(pSuite, MySQLTest, testBareboneMySQL); CppUnit_addTest(pSuite, MySQLTest, testSimpleAccess); CppUnit_addTest(pSuite, MySQLTest, testComplexType); CppUnit_addTest(pSuite, MySQLTest, testSimpleAccessVector); CppUnit_addTest(pSuite, MySQLTest, testComplexTypeVector); CppUnit_addTest(pSuite, MySQLTest, testInsertVector); CppUnit_addTest(pSuite, MySQLTest, testInsertEmptyVector); CppUnit_addTest(pSuite, MySQLTest, testInsertSingleBulk); CppUnit_addTest(pSuite, MySQLTest, testInsertSingleBulkVec); CppUnit_addTest(pSuite, MySQLTest, testLimit); CppUnit_addTest(pSuite, MySQLTest, testLimitOnce); CppUnit_addTest(pSuite, MySQLTest, testLimitPrepare); CppUnit_addTest(pSuite, MySQLTest, testLimitZero); CppUnit_addTest(pSuite, MySQLTest, testPrepare); CppUnit_addTest(pSuite, MySQLTest, testSetSimple); CppUnit_addTest(pSuite, MySQLTest, testSetComplex); CppUnit_addTest(pSuite, MySQLTest, testSetComplexUnique); CppUnit_addTest(pSuite, MySQLTest, testMultiSetSimple); CppUnit_addTest(pSuite, MySQLTest, testMultiSetComplex); CppUnit_addTest(pSuite, MySQLTest, testMapComplex); CppUnit_addTest(pSuite, MySQLTest, testMapComplexUnique); CppUnit_addTest(pSuite, MySQLTest, testMultiMapComplex); CppUnit_addTest(pSuite, MySQLTest, testSelectIntoSingle); CppUnit_addTest(pSuite, MySQLTest, testSelectIntoSingleStep); CppUnit_addTest(pSuite, MySQLTest, testSelectIntoSingleFail); CppUnit_addTest(pSuite, MySQLTest, testLowerLimitOk); CppUnit_addTest(pSuite, MySQLTest, testLowerLimitFail); CppUnit_addTest(pSuite, MySQLTest, testCombinedLimits); CppUnit_addTest(pSuite, MySQLTest, testCombinedIllegalLimits); CppUnit_addTest(pSuite, MySQLTest, testRange); CppUnit_addTest(pSuite, MySQLTest, testIllegalRange); CppUnit_addTest(pSuite, MySQLTest, testSingleSelect); CppUnit_addTest(pSuite, MySQLTest, testEmptyDB); //CppUnit_addTest(pSuite, MySQLTest, testBLOB); CppUnit_addTest(pSuite, MySQLTest, testBLOBStmt); CppUnit_addTest(pSuite, MySQLTest, testFloat); CppUnit_addTest(pSuite, MySQLTest, testDouble); CppUnit_addTest(pSuite, MySQLTest, testTuple); CppUnit_addTest(pSuite, MySQLTest, testTupleVector); CppUnit_addTest(pSuite, MySQLTest, testInternalExtraction); CppUnit_addTest(pSuite, MySQLTest, testNull); return pSuite; } poco-1.3.6p1-all/Data/MySQL/testsuite/src/MySQLTest.h0000644000076500001200000000726011313735447022677 0ustar guenteradmin00000000000000// // ODBCMySQLTest.h // // $Id: //poco/1.3/Data/MySQL/testsuite/src/MySQLTest.h#2 $ // // Definition of the MySQLTest class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef MySQLTest_INCLUDED #define MySQLTest_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/Session.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class MySQLTest: public CppUnit::TestCase /// MySQL test class /// Tested: /// /// Driver | DB | OS /// ----------------+---------------------------+------------------------------------------ /// 03.51.12.00 | MySQL 5.0.27-community-nt | MS Windows XP Professional x64 v.2003/SP1 /// { public: MySQLTest(const std::string& name); ~MySQLTest(); void testBareboneMySQL(); void testSimpleAccess(); void testComplexType(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void testNull(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorsTable(); static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // MySQLTest_INCLUDED poco-1.3.6p1-all/Data/MySQL/testsuite/src/MySQLTestSuite.cpp0000644000076500001200000000334111313735447024240 0ustar guenteradmin00000000000000// // ODBCTestSuite.cpp // // $Id: //poco/1.3/Data/MySQL/testsuite/src/MySQLTestSuite.cpp#2 $ // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "MySQLTestSuite.h" #include "MySQLTest.h" CppUnit::Test* MySQLTestSuite::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MySQLTestSuite"); pSuite->addTest(MySQLTest::suite()); return pSuite; } poco-1.3.6p1-all/Data/MySQL/testsuite/src/MySQLTestSuite.h0000644000076500001200000000336511313735447023713 0ustar guenteradmin00000000000000// // ODBCTestSuite.h // // $Id: //poco/1.3/Data/MySQL/testsuite/src/MySQLTestSuite.h#2 $ // // Definition of the ODBCTestSuite class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef MySQLTestSuite_INCLUDED #define MySQLTestSuite_INCLUDED #include "CppUnit/TestSuite.h" class MySQLTestSuite { public: static CppUnit::Test* suite(); }; #endif // MySQLTestSuite_INCLUDED poco-1.3.6p1-all/Data/MySQL/testsuite/src/SQLExecutor.cpp0000644000076500001200000015421711313735447023610 0ustar guenteradmin00000000000000// // SQLExecutor.cpp // // $Id: //poco/1.3/Data/MySQL/testsuite/src/SQLExecutor.cpp#3 $ // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CppUnit/TestCase.h" #include "SQLExecutor.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Tuple.h" #include "Poco/Any.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/RecordSet.h" #include "Poco/Data/MySQL/Connector.h" #include "Poco/Data/MySQL/MySQLException.h" #ifdef _WIN32 #include #endif #include #include using namespace Poco::Data; using Poco::Data::MySQL::ConnectionException; using Poco::Data::MySQL::StatementException; using Poco::format; using Poco::Tuple; using Poco::Any; using Poco::AnyCast; using Poco::NotFoundException; using Poco::InvalidAccessException; using Poco::BadCastException; using Poco::RangeException; struct Person { std::string lastName; std::string firstName; std::string address; int age; Person(){age = 0;} Person(const std::string& ln, const std::string& fn, const std::string& adr, int a):lastName(ln), firstName(fn), address(adr), age(a) { } bool operator==(const Person& other) const { return lastName == other.lastName && firstName == other.firstName && address == other.address && age == other.age; } bool operator < (const Person& p) const { if (age < p.age) return true; if (lastName < p.lastName) return true; if (firstName < p.firstName) return true; return (address < p.address); } const std::string& operator () () const /// This method is required so we can extract data to a map! { // we choose the lastName as examplary key return lastName; } }; namespace Poco { namespace Data { template <> class TypeHandler { public: static void bind(std::size_t pos, const Person& obj, AbstractBinder* pBinder) { // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Address VARCHAR, Age INTEGER(3)) poco_assert_dbg (pBinder != 0); pBinder->bind(pos++, obj.lastName); pBinder->bind(pos++, obj.firstName); pBinder->bind(pos++, obj.address); pBinder->bind(pos++, obj.age); } static void prepare(std::size_t pos, const Person& obj, AbstractPreparation* pPrepare) { // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Address VARCHAR, Age INTEGER(3)) poco_assert_dbg (pPrepare != 0); pPrepare->prepare(pos++, obj.lastName); pPrepare->prepare(pos++, obj.firstName); pPrepare->prepare(pos++, obj.address); pPrepare->prepare(pos++, obj.age); } static std::size_t size() { return 4; } static void extract(std::size_t pos, Person& obj, const Person& defVal, AbstractExtractor* pExt) { poco_assert_dbg (pExt != 0); if (!pExt->extract(pos++, obj.lastName)) obj.lastName = defVal.lastName; if (!pExt->extract(pos++, obj.firstName)) obj.firstName = defVal.firstName; if (!pExt->extract(pos++, obj.address)) obj.address = defVal.address; if (!pExt->extract(pos++, obj.age)) obj.age = defVal.age; } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; } } // namespace Poco::Data SQLExecutor::SQLExecutor(const std::string& name, Poco::Data::Session* pSession): CppUnit::TestCase(name), _pSession(pSession) { } SQLExecutor::~SQLExecutor() { } void SQLExecutor::bareboneMySQLTest(const char* host, const char* user, const char* pwd, const char* db, int port, const char* tableCreateString) { int rc; MYSQL* hsession = mysql_init(0); assert (hsession != 0); MYSQL* tmp = mysql_real_connect(hsession, host, user, pwd, db, port, 0, 0); assert(tmp == hsession); MYSQL_STMT* hstmt = mysql_stmt_init(hsession); assert(hstmt != 0); std::string sql = "DROP TABLE Test"; mysql_real_query(hsession, sql.c_str(), static_cast(sql.length())); sql = tableCreateString; rc = mysql_stmt_prepare(hstmt, sql.c_str(), static_cast(sql.length())); assert(rc == 0); rc = mysql_stmt_execute(hstmt); assert(rc == 0); sql = "INSERT INTO Test VALUES (?,?,?,?,?)"; rc = mysql_stmt_prepare(hstmt, sql.c_str(), static_cast(sql.length())); assert(rc == 0); std::string str[3] = { "111", "222", "333" }; int fourth = 4; float fifth = 1.5; MYSQL_BIND bind_param[5] = {{0}}; bind_param[0].buffer = const_cast(str[0].c_str()); bind_param[0].buffer_length = static_cast(str[0].length()); bind_param[0].buffer_type = MYSQL_TYPE_STRING; bind_param[1].buffer = const_cast(str[1].c_str()); bind_param[1].buffer_length = static_cast(str[1].length()); bind_param[1].buffer_type = MYSQL_TYPE_STRING; bind_param[2].buffer = const_cast(str[2].c_str()); bind_param[2].buffer_length = static_cast(str[2].length()); bind_param[2].buffer_type = MYSQL_TYPE_STRING; bind_param[3].buffer = &fourth; bind_param[3].buffer_type = MYSQL_TYPE_LONG; bind_param[4].buffer = &fifth; bind_param[4].buffer_type = MYSQL_TYPE_FLOAT; rc = mysql_stmt_bind_param(hstmt, bind_param); assert (rc == 0); rc = mysql_stmt_execute(hstmt); assert (rc == 0); sql = "SELECT * FROM Test"; rc = mysql_stmt_prepare(hstmt, sql.c_str(), static_cast(sql.length())); assert (rc == 0); char chr[3][5] = {{ 0 }}; unsigned long lengths[5] = { 0 }; fourth = 0; fifth = 0.0f; MYSQL_BIND bind_result[5] = {{0}}; bind_result[0].buffer = chr[0]; bind_result[0].buffer_length = sizeof(chr[0]); bind_result[0].buffer_type = MYSQL_TYPE_STRING; bind_result[0].length = &lengths[0]; bind_result[1].buffer = chr[1]; bind_result[1].buffer_length = sizeof(chr[1]); bind_result[1].buffer_type = MYSQL_TYPE_STRING; bind_result[1].length = &lengths[1]; bind_result[2].buffer = chr[2]; bind_result[2].buffer_length = sizeof(chr[2]); bind_result[2].buffer_type = MYSQL_TYPE_STRING; bind_result[2].length = &lengths[2]; bind_result[3].buffer = &fourth; bind_result[3].buffer_type = MYSQL_TYPE_LONG; bind_result[3].length = &lengths[3]; bind_result[4].buffer = &fifth; bind_result[4].buffer_type = MYSQL_TYPE_FLOAT; bind_result[4].length = &lengths[4]; rc = mysql_stmt_bind_result(hstmt, bind_result); assert (rc == 0); rc = mysql_stmt_execute(hstmt); assert (rc == 0); rc = mysql_stmt_fetch(hstmt); assert (rc == 0); assert (0 == std::strncmp("111", chr[0], 3)); assert (0 == std::strncmp("222", chr[1], 3)); assert (0 == std::strncmp("333", chr[2], 3)); assert (4 == fourth); assert (1.5 == fifth); rc = mysql_stmt_close(hstmt); assert(rc == 0); sql = "DROP TABLE Test"; rc = mysql_real_query(hsession, sql.c_str(), static_cast(sql.length())); assert(rc == 0); mysql_close(hsession); } void SQLExecutor::simpleAccess() { std::string funct = "simpleAccess()"; std::string lastName = "lastName"; std::string firstName("firstName"); std::string address("Address"); int age = 133132; int count = 0; std::string result; count = 0; try { Statement stmt(*_pSession); stmt << "INSERT INTO Person VALUES (?,?,?,?)", use(lastName), use(firstName), use(address), use(age);//, now; stmt.execute(); } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT LastName FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (lastName == result); try { *_pSession << "SELECT Age FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == age); } void SQLExecutor::complexType() { std::string funct = "complexType()"; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(p1), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(p2), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person c1; Person c2; try { *_pSession << "SELECT * FROM Person WHERE LastName = 'LN1'", into(c1), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (c1 == p1); } void SQLExecutor::simpleAccessVector() { std::string funct = "simpleAccessVector()"; std::vector lastNames; std::vector firstNames; std::vector addresses; std::vector ages; std::string tableName("Person"); lastNames.push_back("LN1"); lastNames.push_back("LN2"); firstNames.push_back("FN1"); firstNames.push_back("FN2"); addresses.push_back("ADDR1"); addresses.push_back("ADDR2"); ages.push_back(1); ages.push_back(2); int count = 0; std::string result; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastNames), use(firstNames), use(addresses), use(ages), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::vector lastNamesR; std::vector firstNamesR; std::vector addressesR; std::vector agesR; try { *_pSession << "SELECT * FROM Person", into(lastNamesR), into(firstNamesR), into(addressesR), into(agesR), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ages == agesR); assert (lastNames == lastNamesR); assert (firstNames == firstNamesR); assert (addresses == addressesR); } void SQLExecutor::complexTypeVector() { std::string funct = "complexTypeVector()"; std::vector people; people.push_back(Person("LN1", "FN1", "ADDR1", 1)); people.push_back(Person("LN2", "FN2", "ADDR2", 2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::vector result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result == people); } void SQLExecutor::insertVector() { std::string funct = "insertVector()"; std::vector str; str.push_back("s1"); str.push_back("s2"); str.push_back("s3"); str.push_back("s3"); int count = 100; { Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(str))); try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 0); try { stmt.execute(); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 4); } count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 4); } void SQLExecutor::insertEmptyVector() { std::string funct = "insertEmptyVector()"; std::vector str; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(str), now; fail("empty collections should not work"); } catch (Poco::Exception&) { } } void SQLExecutor::insertSingleBulk() { std::string funct = "insertSingleBulk()"; int x = 0; Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(x))); for (x = 0; x < 100; ++x) { int i = stmt.execute(); assert (i == 0); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 100); try { *_pSession << "SELECT SUM(str) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == ((0+99)*100/2)); } void SQLExecutor::floats() { std::string funct = "floats()"; float data = 1.5f; float ret = 0.0f; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT str FROM Strings", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ret == data); } void SQLExecutor::doubles() { std::string funct = "floats()"; double data = 1.5; double ret = 0.0; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT str FROM Strings", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ret == data); } void SQLExecutor::insertSingleBulkVec() { std::string funct = "insertSingleBulkVec()"; std::vector data; for (int x = 0; x < 100; ++x) data.push_back(x); Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(data))); stmt.execute(); int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 100); try { *_pSession << "SELECT SUM(str) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == ((0+99)*100/2)); } void SQLExecutor::limits() { std::string funct = "limit()"; std::vector data; for (int x = 0; x < 100; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } std::vector retData; try { *_pSession << "SELECT * FROM Strings", into(retData), limit(50), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (retData.size() == 50); for (int x = 0; x < 50; ++x) { assert(data[x] == retData[x]); } } void SQLExecutor::limitZero() { std::string funct = "limitZero()"; std::vector data; for (int x = 0; x < 100; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } std::vector retData; try { *_pSession << "SELECT * FROM Strings", into(retData), limit(0), now; }// stupid test, but at least we shouldn't crash catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (retData.size() == 0); } void SQLExecutor::limitOnce() { std::string funct = "limitOnce()"; std::vector data; for (int x = 0; x < 101; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } std::vector retData; Statement stmt = (*_pSession << "SELECT * FROM Strings", into(retData), limit(50), now); assert (!stmt.done()); assert (retData.size() == 50); stmt.execute(); assert (!stmt.done()); assert (retData.size() == 100); stmt.execute(); assert (stmt.done()); assert (retData.size() == 101); for (int x = 0; x < 101; ++x) { assert(data[x] == retData[x]); } } void SQLExecutor::limitPrepare() { std::string funct = "limitPrepare()"; std::vector data; for (int x = 0; x < 100; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } std::vector retData; Statement stmt = (*_pSession << "SELECT * FROM Strings", into(retData), limit(50)); assert (retData.size() == 0); assert (!stmt.done()); try { stmt.execute(); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (!stmt.done()); assert (retData.size() == 50); try { stmt.execute(); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (stmt.done()); assert (retData.size() == 100); try { stmt.execute(); }// will restart execution! catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (!stmt.done()); assert (retData.size() == 150); for (int x = 0; x < 150; ++x) { assert(data[x%100] == retData[x]); } } void SQLExecutor::prepare() { std::string funct = "prepare()"; std::vector data; for (int x = 0; x < 100; x += 2) { data.push_back(x); } { Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(data))); } // stmt should not have been executed when destroyed int count = 100; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 0); } void SQLExecutor::setSimple() { std::string funct = "setSimple()"; std::set lastNames; std::set firstNames; std::set addresses; std::set ages; std::string tableName("Person"); lastNames.insert("LN1"); lastNames.insert("LN2"); firstNames.insert("FN1"); firstNames.insert("FN2"); addresses.insert("ADDR1"); addresses.insert("ADDR2"); ages.insert(1); ages.insert(2); int count = 0; std::string result; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastNames), use(firstNames), use(addresses), use(ages), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::set lastNamesR; std::set firstNamesR; std::set addressesR; std::set agesR; try { *_pSession << "SELECT * FROM Person", into(lastNamesR), into(firstNamesR), into(addressesR), into(agesR), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ages == agesR); assert (lastNames == lastNamesR); assert (firstNames == firstNamesR); assert (addresses == addressesR); } void SQLExecutor::setComplex() { std::string funct = "setComplex()"; std::set people; people.insert(Person("LN1", "FN1", "ADDR1", 1)); people.insert(Person("LN2", "FN2", "ADDR2", 2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::set result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result == people); } void SQLExecutor::setComplexUnique() { std::string funct = "setComplexUnique()"; std::vector people; Person p1("LN1", "FN1", "ADDR1", 1); people.push_back(p1); people.push_back(p1); people.push_back(p1); people.push_back(p1); Person p2("LN2", "FN2", "ADDR2", 2); people.push_back(p2); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 5); std::set result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result.size() == 2); assert (*result.begin() == p1); assert (*++result.begin() == p2); } void SQLExecutor::multiSetSimple() { std::string funct = "multiSetSimple()"; std::multiset lastNames; std::multiset firstNames; std::multiset addresses; std::multiset ages; std::string tableName("Person"); lastNames.insert("LN1"); lastNames.insert("LN2"); firstNames.insert("FN1"); firstNames.insert("FN2"); addresses.insert("ADDR1"); addresses.insert("ADDR2"); ages.insert(1); ages.insert(2); int count = 0; std::string result; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastNames), use(firstNames), use(addresses), use(ages), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::multiset lastNamesR; std::multiset firstNamesR; std::multiset addressesR; std::multiset agesR; try { *_pSession << "SELECT * FROM Person", into(lastNamesR), into(firstNamesR), into(addressesR), into(agesR), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ages.size() == agesR.size()); assert (lastNames.size() == lastNamesR.size()); assert (firstNames.size() == firstNamesR.size()); assert (addresses.size() == addressesR.size()); } void SQLExecutor::multiSetComplex() { std::string funct = "multiSetComplex()"; std::multiset people; Person p1("LN1", "FN1", "ADDR1", 1); people.insert(p1); people.insert(p1); people.insert(p1); people.insert(p1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(p2); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 5); std::multiset result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result.size() == people.size()); } void SQLExecutor::mapComplex() { std::string funct = "mapComplex()"; std::map people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN2", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::map result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result == people); } void SQLExecutor::mapComplexUnique() { std::string funct = "mapComplexUnique()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN2", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 5); std::map result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result.size() == 2); } void SQLExecutor::multiMapComplex() { std::string funct = "multiMapComplex()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN2", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 5); std::multimap result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result.size() == people.size()); } void SQLExecutor::selectIntoSingle() { std::string funct = "selectIntoSingle()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), limit(1), now; }// will return 1 object into one single result catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result == p1); } void SQLExecutor::selectIntoSingleStep() { std::string funct = "selectIntoSingleStep()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; Statement stmt = (*_pSession << "SELECT * FROM Person", into(result), limit(1)); stmt.execute(); assert (result == p1); assert (!stmt.done()); stmt.execute(); assert (result == p2); assert (stmt.done()); } void SQLExecutor::selectIntoSingleFail() { std::string funct = "selectIntoSingleFail()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), limit(2, true), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), limit(1, true), now; // will fail now fail("hardLimit is set: must fail"); } catch(Poco::Data::LimitException&) { } } void SQLExecutor::lowerLimitOk() { std::string funct = "lowerLimitOk()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(2), now; // will return 2 objects into one single result but only room for one! fail("Not enough space for results"); } catch(Poco::Exception&) { } } void SQLExecutor::singleSelect() { std::string funct = "singleSelect()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; Statement stmt = (*_pSession << "SELECT * FROM Person", into(result), limit(1)); stmt.execute(); assert (result == p1); assert (!stmt.done()); stmt.execute(); assert (result == p2); assert (stmt.done()); } void SQLExecutor::lowerLimitFail() { std::string funct = "lowerLimitFail()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(3), now; // will fail fail("should fail. not enough data"); } catch(Poco::Exception&) { } } void SQLExecutor::combinedLimits() { std::string funct = "combinedLimits()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::vector result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(2), upperLimit(2), now; }// will return 2 objects catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result.size() == 2); assert (result[0] == p1); assert (result[1] == p2); } void SQLExecutor::ranges() { std::string funct = "range()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); std::vector result; try { *_pSession << "SELECT * FROM Person", into(result), range(2, 2), now; }// will return 2 objects catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (result.size() == 2); assert (result[0] == p1); assert (result[1] == p2); } void SQLExecutor::combinedIllegalLimits() { std::string funct = "combinedIllegalLimits()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(3), upperLimit(2), now; fail("lower > upper is not allowed"); } catch(LimitException&) { } } void SQLExecutor::illegalRange() { std::string funct = "illegalRange()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), range(3, 2), now; fail("lower > upper is not allowed"); } catch(LimitException&) { } } void SQLExecutor::emptyDB() { std::string funct = "emptyDB()"; int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 0); Person result; Statement stmt = (*_pSession << "SELECT * FROM Person", into(result), limit(1)); stmt.execute(); assert (result.firstName.empty()); assert (stmt.done()); } void SQLExecutor::blob(int bigSize) { std::string funct = "blob()"; std::string lastName("lastname"); std::string firstName("firstname"); std::string address("Address"); Poco::Data::BLOB img("0123456789", 10); int count = 0; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastName), use(firstName), use(address), use(img), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 1); Poco::Data::BLOB res; assert (res.size() == 0); try { *_pSession << "SELECT Image FROM Person", into(res), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (res == img); Poco::Data::BLOB big; std::vector v(bigSize, 'x'); big.assignRaw(&v[0], v.size()); assert (big.size() == bigSize); try { *_pSession << "DELETE FROM Person", now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "INSERT INTO Person VALUES(?,?,?,?)", use(lastName), use(firstName), use(address), use(big), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { *_pSession << "SELECT Image FROM Person", into(res), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (res == big); } void SQLExecutor::blobStmt() { std::string funct = "blobStmt()"; std::string lastName("lastname"); std::string firstName("firstname"); std::string address("Address"); Poco::Data::BLOB blob("0123456789", 10); int count = 0; Statement ins = (*_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastName), use(firstName), use(address), use(blob)); ins.execute(); try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 1); Poco::Data::BLOB res; poco_assert (res.size() == 0); Statement stmt = (*_pSession << "SELECT Image FROM Person", into(res)); try { stmt.execute(); } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } poco_assert (res == blob); } void SQLExecutor::tuples() { typedef Tuple TupleType; std::string funct = "tuples()"; TupleType t(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); try { *_pSession << "INSERT INTO Tuples VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", use(t), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } TupleType ret(-10,-11,-12,-13,-14,-15,-16,-17,-18,-19); assert (ret != t); try { *_pSession << "SELECT * FROM Tuples", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ret == t); } void SQLExecutor::tupleVector() { typedef Tuple TupleType; std::string funct = "tupleVector()"; TupleType t(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); Tuple t10(10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29); TupleType t100(100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119); std::vector v; v.push_back(t); v.push_back(t10); v.push_back(t100); try { *_pSession << "INSERT INTO Tuples VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", use(v), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Tuples", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (v.size() == count); std::vector > ret; try { *_pSession << "SELECT * FROM Tuples", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (ret == v); } void SQLExecutor::internalExtraction() { std::string funct = "internalExtraction()"; std::vector > v; v.push_back(Tuple(1, 1.5f, "3")); v.push_back(Tuple(2, 2.5f, "4")); v.push_back(Tuple(3, 3.5f, "5")); v.push_back(Tuple(4, 4.5f, "6")); try { *_pSession << "INSERT INTO Vectors VALUES (?,?,?)", use(v), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } try { Statement stmt = (*_pSession << "SELECT * FROM Vectors", now); RecordSet rset(stmt); assert (3 == rset.columnCount()); assert (4 == rset.rowCount()); int curVal = 3; do { assert (rset["str0"] == curVal); ++curVal; } while (rset.moveNext()); rset.moveFirst(); assert (rset["str0"] == "3"); rset.moveLast(); assert (rset["str0"] == "6"); RecordSet rset2(rset); assert (3 == rset2.columnCount()); assert (4 == rset2.rowCount()); int i = rset.value(0,0); assert (1 == i); std::string s = rset.value(0,0); assert ("1" == s); int a = rset.value(0,2); assert (3 == a); try { double d = rset.value(1,1); assert (2.5 == d); } catch (BadCastException&) { float f = rset.value(1,1); assert (2.5 == f); } s = rset.value(2,2); assert ("5" == s); i = rset.value("str0", 2); assert (5 == i); const Column& col = rset.column(0); Column::Iterator it = col.begin(); Column::Iterator end = col.end(); for (int i = 1; it != end; ++it, ++i) assert (*it == i); rset = (*_pSession << "SELECT COUNT(*) AS cnt FROM Vectors", now); //various results for COUNT(*) are received from different drivers try { //this is what most drivers will return int i = rset.value(0,0); assert (4 == i); } catch(BadCastException&) { try { //this is for Oracle double i = rset.value(0,0); assert (4 == int(i)); } catch(BadCastException&) { //this is for PostgreSQL Poco::Int64 big = rset.value(0,0); assert (4 == big); } } s = rset.value("cnt", 0).convert(); assert ("4" == s); try { const Column& col1 = rset.column(100); fail ("must fail"); } catch (RangeException&) { } try { rset.value(0,0); fail ("must fail"); } catch (BadCastException&) { } stmt = (*_pSession << "DELETE FROM Vectors", now); rset = stmt; try { const Column& col1 = rset.column(0); fail ("must fail"); } catch (RangeException&) { } } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } } void SQLExecutor::doNull() { std::string funct = "null()"; *_pSession << "INSERT INTO Vectors VALUES (null, null, null)", now; int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Vectors", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } assert (count == 1); int i0 = 0; Statement stmt1 = (*_pSession << "SELECT i0 FROM Vectors", into(i0, -1)); try { stmt1.execute(); } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } poco_assert (i0 == -1); float flt0 = 0; Statement stmt2 = (*_pSession << "SELECT flt0 FROM Vectors", into(flt0, 3.25f)); try { stmt2.execute(); } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } poco_assert (flt0 == 3.25); std::string str0("string"); Statement stmt3 = (*_pSession << "SELECT str0 FROM Vectors", into(str0, std::string("DEFAULT"))); try { stmt3.execute(); } catch(ConnectionException& ce){ std::cout << ce.displayText() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.displayText() << std::endl; fail (funct); } poco_assert (str0 == "DEFAULT"); } poco-1.3.6p1-all/Data/MySQL/testsuite/src/SQLExecutor.h0000644000076500001200000000643311313735447023251 0ustar guenteradmin00000000000000// // SQLExecutor.h // // $Id: //poco/1.3/Data/MySQL/testsuite/src/SQLExecutor.h#2 $ // // Definition of the SQLExecutor class. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef SQLExecutor_INCLUDED #define SQLExecutor_INCLUDED #include "Poco/Data/MySQL/MySQL.h" #include "Poco/Data/Session.h" class SQLExecutor: public CppUnit::TestCase { public: enum DataBinding { PB_IMMEDIATE, PB_AT_EXEC }; enum DataExtraction { DE_MANUAL, DE_BOUND }; SQLExecutor(const std::string& name, Poco::Data::Session* _pSession); ~SQLExecutor(); void bareboneMySQLTest(const char* host, const char* user, const char* pwd, const char* db, int port, const char* tableCreateString); /// This function uses "bare bone" MySQL API calls (i.e. calls are not /// "wrapped" in PocoData framework structures). /// The purpose of the function is to verify that driver behaves /// correctly. If this test passes, subsequent tests failures are likely ours. void simpleAccess(); void complexType(); void simpleAccessVector(); void complexTypeVector(); void insertVector(); void insertEmptyVector(); void insertSingleBulk(); void insertSingleBulkVec(); void limits(); void limitOnce(); void limitPrepare(); void limitZero(); void prepare(); void setSimple(); void setComplex(); void setComplexUnique(); void multiSetSimple(); void multiSetComplex(); void mapComplex(); void mapComplexUnique(); void multiMapComplex(); void selectIntoSingle(); void selectIntoSingleStep(); void selectIntoSingleFail(); void lowerLimitOk(); void lowerLimitFail(); void combinedLimits(); void combinedIllegalLimits(); void ranges(); void illegalRange(); void singleSelect(); void emptyDB(); void blob(int bigSize = 1024); void blobStmt(); void floats(); void doubles(); void tuples(); void tupleVector(); void internalExtraction(); void doNull(); private: Poco::Data::Session* _pSession; }; #endif // SQLExecutor_INCLUDED poco-1.3.6p1-all/Data/MySQL/testsuite/src/WinDriver.cpp0000644000076500001200000000345611313735447023341 0ustar guenteradmin00000000000000// // WinDriver.cpp // // $Id: //poco/1.3/Data/MySQL/testsuite/src/WinDriver.cpp#2 $ // // Windows test driver for Poco MySQL. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "WinTestRunner/WinTestRunner.h" #include "MySQLTestSuite.h" class TestDriver: public CppUnit::WinTestRunnerApp { void TestMain() { CppUnit::WinTestRunner runner; runner.addTest(MySQLTestSuite::suite()); runner.run(); } }; TestDriver theDriver; poco-1.3.6p1-all/Data/MySQL/testsuite/TestSuite_VS71.vcproj0000644000076500001200000002105011313735447024061 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/MySQL/testsuite/TestSuite_VS80.vcproj0000644000076500001200000002300711313735447024065 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/MySQL/testsuite/TestSuite_vs90.vcproj0000644000076500001200000002255711313735447024177 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/ODBC/0000755000076500001200000000000011313735447015636 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/include/0000755000076500001200000000000011313735447017261 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/include/Poco/0000755000076500001200000000000011313735447020161 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/0000755000076500001200000000000011313735447021032 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/0000755000076500001200000000000011313735447021541 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Binder.h0000644000076500001200000001520311313735447023116 0ustar guenteradmin00000000000000// // Binder.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Binder.h#5 $ // // Library: Data/ODBC // Package: ODBC // Module: Binder // // Definition of the Binder class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_ODBC_Binder_INCLUDED #define DataConnectors_ODBC_Binder_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/AbstractBinder.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/ODBC/Handle.h" #include "Poco/Data/ODBC/Parameter.h" #include "Poco/Data/ODBC/ODBCColumn.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Exception.h" #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API Binder: public Poco::Data::AbstractBinder /// Binds placeholders in the sql query to the provided values. Performs data types mapping. { public: enum ParameterBinding { PB_IMMEDIATE, PB_AT_EXEC }; Binder(const StatementHandle& rStmt, ParameterBinding dataBinding = PB_IMMEDIATE); /// Creates the Binder. ~Binder(); /// Destroys the Binder. void bind(std::size_t pos, const Poco::Int8& val); /// Binds an Int8. void bind(std::size_t pos, const Poco::UInt8& val); /// Binds an UInt8. void bind(std::size_t pos, const Poco::Int16& val); /// Binds an Int16. void bind(std::size_t pos, const Poco::UInt16& val); /// Binds an UInt16. void bind(std::size_t pos, const Poco::Int32& val); /// Binds an Int32. void bind(std::size_t pos, const Poco::UInt32& val); /// Binds an UInt32. void bind(std::size_t pos, const Poco::Int64& val); /// Binds an Int64. void bind(std::size_t pos, const Poco::UInt64& val); /// Binds an UInt64. void bind(std::size_t pos, const bool& val); /// Binds a boolean. void bind(std::size_t pos, const float& val); /// Binds a float. void bind(std::size_t pos, const double& val); /// Binds a double. void bind(std::size_t pos, const char& val); /// Binds a single character. void bind(std::size_t pos, const std::string& val); /// Binds a string. void bind(std::size_t pos, const Poco::Data::BLOB& val); /// Binds a BLOB. void setDataBinding(ParameterBinding binding); /// Set data binding type. ParameterBinding getDataBinding() const; /// Return data binding type. std::size_t dataSize(SQLPOINTER pAddr) const; /// Returns bound data size for parameter at specified position. private: typedef std::map SizeMap; void bind(std::size_t pos, const char* const &pVal); /// Binds a const char ptr. /// This is a private no-op in this implementation /// due to security risk. template void bindImpl(std::size_t pos, T& val, SQLSMALLINT cDataType) { _lengthIndicator.push_back(0); _dataSize.insert(SizeMap::value_type((SQLPOINTER) &val, sizeof(T))); int sqlDataType = Utility::sqlDataType(cDataType); SQLUINTEGER columnSize = 0; SQLSMALLINT decimalDigits = 0; // somewhat funky flow control, but not all // ODBC drivers will cooperate here try { Parameter p(_rStmt, pos); columnSize = (SQLUINTEGER) p.columnSize(); decimalDigits = (SQLSMALLINT) p.decimalDigits(); } catch (StatementException&) { try { ODBCColumn c(_rStmt, pos); columnSize = (SQLUINTEGER) c.length(); decimalDigits = (SQLSMALLINT) c.precision(); } catch (StatementException&) { } } if (Utility::isError(SQLBindParameter(_rStmt, (SQLUSMALLINT) pos + 1, SQL_PARAM_INPUT, cDataType, sqlDataType, columnSize, decimalDigits, (SQLPOINTER) &val, 0, _lengthIndicator.back()))) { throw StatementException(_rStmt, "SQLBindParameter()"); } } const StatementHandle& _rStmt; std::vector _lengthIndicator; SizeMap _dataSize; ParameterBinding _paramBinding; }; // // inlines // inline void Binder::bind(std::size_t pos, const Poco::Int8& val) { bindImpl(pos, val, SQL_C_STINYINT); } inline void Binder::bind(std::size_t pos, const Poco::UInt8& val) { bindImpl(pos, val, SQL_C_UTINYINT); } inline void Binder::bind(std::size_t pos, const Poco::Int16& val) { bindImpl(pos, val, SQL_C_SSHORT); } inline void Binder::bind(std::size_t pos, const Poco::UInt16& val) { bindImpl(pos, val, SQL_C_USHORT); } inline void Binder::bind(std::size_t pos, const Poco::UInt32& val) { bindImpl(pos, val, SQL_C_ULONG); } inline void Binder::bind(std::size_t pos, const Poco::Int32& val) { bindImpl(pos, val, SQL_C_SLONG); } inline void Binder::bind(std::size_t pos, const Poco::UInt64& val) { bindImpl(pos, val, SQL_C_UBIGINT); } inline void Binder::bind(std::size_t pos, const Poco::Int64& val) { bindImpl(pos, val, SQL_C_SBIGINT); } inline void Binder::bind(std::size_t pos, const float& val) { bindImpl(pos, val, SQL_C_FLOAT); } inline void Binder::bind(std::size_t pos, const double& val) { bindImpl(pos, val, SQL_C_DOUBLE); } inline void Binder::bind(std::size_t pos, const bool& val) { bindImpl(pos, val, SQL_C_BIT); } inline void Binder::bind(std::size_t pos, const char& val) { bindImpl(pos, val, SQL_C_STINYINT); } inline void Binder::setDataBinding(Binder::ParameterBinding binding) { _paramBinding = binding; } inline Binder::ParameterBinding Binder::getDataBinding() const { return _paramBinding; } } } } // namespace Poco::Data::ODBC #endif // DataConnectors_ODBC_Binder_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/ConnectionHandle.h0000644000076500001200000000574311313735447025136 0ustar guenteradmin00000000000000// // ConnectionHandle.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/ConnectionHandle.h#3 $ // // Library: Data/ODBC // Package: ODBC // Module: ConnectionHandle // // Definition of ConnectionHandle. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_ConnectionHandle_INCLUDED #define ODBC_ConnectionHandle_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/EnvironmentHandle.h" #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API ConnectionHandle /// ODBC connection handle class { public: ConnectionHandle(EnvironmentHandle* pEnvironment = 0); /// Creates the ConnectionHandle. ~ConnectionHandle(); /// Creates the ConnectionHandle. operator const SQLHDBC& () const; /// Const conversion operator into reference to native type. const SQLHDBC& handle() const; /// Returns const reference to handle; private: operator SQLHDBC& (); /// Conversion operator into reference to native type. SQLHDBC& handle(); /// Returns reference to handle; ConnectionHandle(const ConnectionHandle&); const ConnectionHandle& operator=(const ConnectionHandle&); const EnvironmentHandle* _pEnvironment; SQLHDBC _hdbc; bool _ownsEnvironment; }; // // inlines // inline ConnectionHandle::operator const SQLHDBC& () const { return handle(); } inline const SQLHDBC& ConnectionHandle::handle() const { return _hdbc; } inline ConnectionHandle::operator SQLHDBC& () { return handle(); } inline SQLHDBC& ConnectionHandle::handle() { return _hdbc; } } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Connector.h0000644000076500001200000000517311313735447023652 0ustar guenteradmin00000000000000// // Connector.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Connector.h#2 $ // // Library: Data/ODBC // Package: ODBC // Module: Connector // // Definition of the Connector class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_ODBC_Connector_INCLUDED #define DataConnectors_ODBC_Connector_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Connector.h" namespace Poco { namespace Data { namespace ODBC { class ODBC_API Connector: public Poco::Data::Connector /// Connector instantiates SqLite SessionImpl objects. { public: static const std::string KEY; /// Keyword for creating ODBC sessions Connector(); /// Creates the Connector. ~Connector(); /// Destroys the Connector. Poco::AutoPtr createSession(const std::string& connectionString); /// Creates a ODBC SessionImpl object and initializes it with the given connectionString. static void registerConnector(); /// Registers the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory static void unregisterConnector(); /// Unregisters the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory }; } } } // namespace Poco::Data::ODBC #endif // DataConnectors_ODBC_Connector_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/DataTypes.h0000644000076500001200000000467611313735447023625 0ustar guenteradmin00000000000000// // DataTypes.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/DataTypes.h#4 $ // // Library: Data/ODBC // Package: ODBC // Module: DataTypes // // Definition of DataTypes. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_DataTypes_INCLUDED #define ODBC_DataTypes_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include #if defined(POCO_OS_FAMILY_WINDOWS) || defined(__CYGWIN__) #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API DataTypes /// C <==> SQL datatypes mapping utility class. { public: typedef std::map DataTypeMap; typedef DataTypeMap::value_type ValueType; DataTypes(); /// Creates the DataTypes. ~DataTypes(); /// Destroys the DataTypes. int cDataType(int sqlDataType) const; /// Returns C data type corresponding to supplied SQL data type. int sqlDataType(int cDataType) const; /// Returns SQL data type corresponding to supplied C data type. private: DataTypeMap _cDataTypes; DataTypeMap _sqlDataTypes; }; } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Diagnostics.h0000644000076500001200000001572411313735447024172 0ustar guenteradmin00000000000000// // Diagnostics.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Diagnostics.h#7 $ // // Library: ODBC // Package: ODBC // Module: Diagnostics // // Definition of Diagnostics. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_ODBC_Diagnostics_INCLUDED #define Data_ODBC_Diagnostics_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include #include #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { template class Diagnostics /// Utility class providing functionality for retrieving ODBC diagnostic /// records. Diagnostics object must be created with corresponding handle /// as constructor argument. During construction, diagnostic records fields /// are populated and the object is ready for querying. { public: static const unsigned int SQL_STATE_SIZE = SQL_SQLSTATE_SIZE + 1; static const unsigned int SQL_MESSAGE_LENGTH = SQL_MAX_MESSAGE_LENGTH + 1; static const unsigned int SQL_NAME_LENGTH = 128; static const std::string DATA_TRUNCATED; struct DiagnosticFields { /// SQLGetDiagRec fields SQLCHAR _sqlState[SQL_STATE_SIZE]; SQLCHAR _message[SQL_MESSAGE_LENGTH]; SQLINTEGER _nativeError; }; typedef std::vector FieldVec; typedef typename FieldVec::const_iterator Iterator; explicit Diagnostics(const H& handle): _rHandle(handle) /// Creates and initializes the Diagnostics. { std::memset(_connectionName, 0, sizeof(_connectionName)); std::memset(_serverName, 0, sizeof(_serverName)); diagnostics(); } ~Diagnostics() /// Destroys the Diagnostics. { } std::string sqlState(int index) const /// Returns SQL state. { poco_assert (index < count()); return std::string((char*) _fields[index]._sqlState); } std::string message(int index) const /// Returns error message. { poco_assert (index < count()); return std::string((char*) _fields[index]._message); } long nativeError(int index) const /// Returns native error code. { poco_assert (index < count()); return _fields[index]._nativeError; } std::string connectionName() const /// Returns the connection name. /// If there is no active connection, connection name defaults to NONE. /// If connection name is not applicable for query context (such as when querying environment handle), /// connection name defaults to NOT_APPLICABLE. { return std::string((char*) _connectionName); } std::string serverName() const /// Returns the server name. /// If the connection has not been established, server name defaults to NONE. /// If server name is not applicable for query context (such as when querying environment handle), /// connection name defaults to NOT_APPLICABLE. { return std::string((char*) _serverName); } int count() const /// Returns the number of contained diagnostic records. { return (int) _fields.size(); } void reset() /// Resets the diagnostic fields container. { _fields.clear(); } const FieldVec& fields() const { return _fields; } Iterator begin() const { return _fields.begin(); } Iterator end() const { return _fields.end(); } const Diagnostics& diagnostics() { DiagnosticFields df; SQLSMALLINT count = 1; SQLSMALLINT messageLength = 0; static const std::string none = "None"; static const std::string na = "Not applicable"; reset(); while (!Utility::isError(SQLGetDiagRec(handleType, _rHandle, count, df._sqlState, &df._nativeError, df._message, SQL_MESSAGE_LENGTH, &messageLength))) { if (1 == count) { // success of the following two calls is optional // (they fail if connection has not been established yet // or return empty string if not applicable for the context) if (Utility::isError(SQLGetDiagField(handleType, _rHandle, count, SQL_DIAG_CONNECTION_NAME, _connectionName, sizeof(_connectionName), &messageLength))) { std::size_t len = sizeof(_connectionName) > none.length() ? none.length() : sizeof(_connectionName) - 1; std::memcpy(_connectionName, none.c_str(), len); } else if (0 == _connectionName[0]) { std::size_t len = sizeof(_connectionName) > na.length() ? na.length() : sizeof(_connectionName) - 1; std::memcpy(_connectionName, na.c_str(), len); } if (Utility::isError(SQLGetDiagField(handleType, _rHandle, count, SQL_DIAG_SERVER_NAME, _serverName, sizeof(_serverName), &messageLength))) { std::size_t len = sizeof(_serverName) > none.length() ? none.length() : sizeof(_serverName) - 1; std::memcpy(_serverName, none.c_str(), len); } else if (0 == _serverName[0]) { std::size_t len = sizeof(_serverName) > na.length() ? na.length() : sizeof(_serverName) - 1; std::memcpy(_serverName, na.c_str(), len); } } _fields.push_back(df); std::memset(df._sqlState, 0, SQL_STATE_SIZE); std::memset(df._message, 0, SQL_MESSAGE_LENGTH); df._nativeError = 0; ++count; } return *this; } private: Diagnostics(); /// SQLGetDiagField fields SQLCHAR _connectionName[SQL_NAME_LENGTH]; SQLCHAR _serverName[SQL_NAME_LENGTH]; /// Diagnostics container FieldVec _fields; /// Context handle const H& _rHandle; }; typedef Diagnostics EnvironmentDiagnostics; typedef Diagnostics ConnectionDiagnostics; typedef Diagnostics StatementDiagnostics; typedef Diagnostics DescriptorDiagnostics; } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/EnvironmentHandle.h0000644000076500001200000000562611313735447025343 0ustar guenteradmin00000000000000// // EnvironmentHandle.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/EnvironmentHandle.h#4 $ // // Library: Data/ODBC // Package: ODBC // Module: EnvironmentHandle // // Definition of EnvironmentHandle. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_EnvironmentHandle_INCLUDED #define ODBC_EnvironmentHandle_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #if defined(POCO_OS_FAMILY_WINDOWS) || defined(__CYGWIN__) #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API EnvironmentHandle /// ODBC environment handle class { public: EnvironmentHandle(); /// Creates the EnvironmentHandle. ~EnvironmentHandle(); /// Destroys the EnvironmentHandle. operator const SQLHENV& () const; /// Const conversion operator into reference to native type. const SQLHENV& handle() const; /// Returns const reference to handle. private: operator SQLHENV& (); /// Conversion operator into reference to native type. SQLHENV& handle(); /// Returns reference to handle. EnvironmentHandle(const EnvironmentHandle&); const EnvironmentHandle& operator=(const EnvironmentHandle&); SQLHENV _henv; bool _isOwner; }; /// /// inlines /// inline EnvironmentHandle::operator const SQLHENV& () const { return handle(); } inline const SQLHENV& EnvironmentHandle::handle() const { return _henv; } inline EnvironmentHandle::operator SQLHENV& () { return handle(); } inline SQLHENV& EnvironmentHandle::handle() { return _henv; } } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Error.h0000644000076500001200000000740711313735447023013 0ustar guenteradmin00000000000000// // Error.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Error.h#5 $ // // Library: ODBC // Package: ODBC // Module: Error // // Definition of Error. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_ODBC_Error_INCLUDED #define Data_ODBC_Error_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Format.h" #include #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { template class Error /// Class encapsulating ODBC diagnostic record collection. Collection is generated /// during construction. Class provides access and string generation for the collection /// as well as individual diagnostic records. { public: explicit Error(const H& handle) : _diagnostics(handle) /// Creates the Error. { } ~Error() /// Destroys the Error. { } const Diagnostics& diagnostics() const /// Returns the associated diagnostics. { return _diagnostics; } int count() const /// Returns the count of diagnostic records. { return (int) _diagnostics.count(); } std::string& toString(int index, std::string& str) const /// Generates the string for the diagnostic record. { if ((index < 0) || (index > (count() - 1))) return str; std::string s; Poco::format(s, "===========================\n" "ODBC Diagnostic record #%d:\n" "===========================\n" "SQLSTATE = %s\nNative Error Code = %ld\n%s\n\n", index + 1, _diagnostics.sqlState(index), _diagnostics.nativeError(index), _diagnostics.message(index)); str.append(s); return str; } std::string toString() const /// Generates the string for the diagnostic record collection. { std::string str; Poco::format(str, "Connection:%s\nServer:%s\n", _diagnostics.connectionName(), _diagnostics.serverName()); std::string s; for (int i = 0; i < count(); ++i) { s.clear(); str.append(toString(i, s)); } return str; } private: Error(); Diagnostics _diagnostics; }; typedef Error EnvironmentError; typedef Error ConnectionError; typedef Error StatementError; typedef Error DescriptorError; } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Extractor.h0000644000076500001200000001310011313735447023660 0ustar guenteradmin00000000000000// // Extractor.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Extractor.h#4 $ // // Library: Data/ODBC // Package: ODBC // Module: Extractor // // Definition of the Extractor class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_ODBC_Extractor_INCLUDED #define DataConnectors_ODBC_Extractor_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/AbstractExtractor.h" #include "Poco/Data/ODBC/Preparation.h" #include "Poco/Data/ODBC/ODBCColumn.h" #include "Poco/Data/ODBC/Error.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Exception.h" #include #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API Extractor: public Poco::Data::AbstractExtractor /// Extracts and converts data values from the result row returned by ODBC. /// If NULL is received, the incoming val value is not changed and false is returned { public: Extractor(const StatementHandle& rStmt, Preparation& rPreparation); /// Creates the Extractor. ~Extractor(); /// Destroys the Extractor. bool extract(std::size_t pos, Poco::Int8& val); /// Extracts an Int8. bool extract(std::size_t pos, Poco::UInt8& val); /// Extracts an UInt8. bool extract(std::size_t pos, Poco::Int16& val); /// Extracts an Int16. bool extract(std::size_t pos, Poco::UInt16& val); /// Extracts an UInt16. bool extract(std::size_t pos, Poco::Int32& val); /// Extracts an Int32. bool extract(std::size_t pos, Poco::UInt32& val); /// Extracts an UInt32. bool extract(std::size_t pos, Poco::Int64& val); /// Extracts an Int64. bool extract(std::size_t pos, Poco::UInt64& val); /// Extracts an UInt64. bool extract(std::size_t pos, bool& val); /// Extracts a boolean. bool extract(std::size_t pos, float& val); /// Extracts a float. bool extract(std::size_t pos, double& val); /// Extracts a double. bool extract(std::size_t pos, char& val); /// Extracts a single character. bool extract(std::size_t pos, std::string& val); /// Extracts a string. bool extract(std::size_t pos, Poco::Data::BLOB& val); /// Extracts a BLOB. bool extract(std::size_t pos, Poco::Any& val); /// Extracts an Any. void setDataExtraction(Preparation::DataExtraction ext); /// Set data extraction mode. Preparation::DataExtraction getDataExtraction() const; /// Returns data extraction mode. private: static const int CHUNK_SIZE = 1024; /// Amount of data retrieved in one SQLGetData() request when doing manual extract. static const std::string FLD_SIZE_EXCEEDED_FMT; /// String format for the exception message when the field size is exceeded. void checkDataSize(std::size_t size); /// This check is only performed for bound data /// retrieval from variable length columns. /// The reason for this check is to ensure we can /// accept the value ODBC driver is supplying /// (i.e. the bound buffer is large enough to receive /// the returned value) template bool extractBoundImpl(std::size_t pos, T& val) { poco_assert (typeid(T) == _rPreparation[pos].type()); val = *AnyCast(&_rPreparation[pos]); return true; } template bool extractManualImpl(std::size_t pos, T& val, SQLSMALLINT cType) { SQLRETURN rc = 0; SQLLEN len = 0; T value = (T) 0; rc = SQLGetData(_rStmt, (SQLUSMALLINT) pos + 1, cType, //C data type &value, //returned value 0, //buffer length (ignored) &len); //length indicator //for fixed-length data, buffer must be large enough //otherwise, driver may write past the end poco_assert_dbg (len <= sizeof(T)); if (Utility::isError(rc)) throw StatementException(_rStmt, "SQLGetData()"); if (SQL_NULL_DATA == len) val = (T) 0; else val = value; return true; } const StatementHandle& _rStmt; Preparation& _rPreparation; Preparation::DataExtraction _dataExtraction; }; /// /// inlines /// inline void Extractor::setDataExtraction(Preparation::DataExtraction ext) { _rPreparation.setDataExtraction(_dataExtraction = ext); } inline Preparation::DataExtraction Extractor::getDataExtraction() const { return _dataExtraction; } } } } // namespace Poco::Data::ODBC #endif // DataConnectors_ODBC_Extractor_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Handle.h0000644000076500001200000000626411313735447023115 0ustar guenteradmin00000000000000// // Handle.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Handle.h#3 $ // // Library: Data/ODBC // Package: ODBC // Module: Handle // // Definition of Handle. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_Handle_INCLUDED #define ODBC_Handle_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/EnvironmentHandle.h" #include "Poco/Data/ODBC/ConnectionHandle.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/Utility.h" #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { template class Handle /// ODBC handle class template { public: Handle(const ConnectionHandle& rConnection): _rConnection(rConnection), _handle(0) /// Creates the Handle. { if (Utility::isError(SQLAllocHandle(handleType, _rConnection, &_handle))) { throw ODBCException("Could not allocate statement handle."); } } ~Handle() /// Destroys the Handle. { SQLRETURN rc = SQLFreeHandle(handleType, _handle); poco_assert (!Utility::isError(rc)); } operator const H& () const /// Const conversion operator into reference to native type. { return handle(); } const H& handle() const /// Returns const reference to native type. { return _handle; } private: Handle(const Handle&); const Handle& operator=(const Handle&); operator H& () /// Conversion operator into reference to native type. { return handle(); } H& handle() /// Returns reference to native type. { return _handle; } const ConnectionHandle& _rConnection; H _handle; friend class ODBCStatementImpl; }; typedef Handle StatementHandle; typedef Handle DescriptorHandle; } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/ODBC.h0000644000076500001200000000567511313735447022436 0ustar guenteradmin00000000000000// // ODBC.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/ODBC.h#3 $ // // Library: Data/ODBC // Package: ODBC // Module: ODBC // // Basic definitions for the Poco ODBC library. // This file must be the first file included by every other ODBC // header file. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_ODBC_INCLUDED #define ODBC_ODBC_INCLUDED #include "Poco/Foundation.h" // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the ODBC_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // ODBC_API functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) #if defined(ODBC_EXPORTS) #define ODBC_API __declspec(dllexport) #else #define ODBC_API __declspec(dllimport) #endif #endif #if !defined(ODBC_API) #define ODBC_API #endif #define POCO_SQLCHAR SQLCHAR // // Automatically link Data library. // #if defined(_MSC_VER) #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(ODBC_EXPORTS) #if defined(POCO_DLL) #if defined(_DEBUG) #pragma comment(lib, "PocoODBCd.lib") #else #pragma comment(lib, "PocoODBC.lib") #endif #else #if defined(_DEBUG) #pragma comment(lib, "PocoODBCmtd.lib") #else #pragma comment(lib, "PocoODBCmt.lib") #endif #endif #endif #endif #endif // ODBC_ODBC_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/ODBCColumn.h0000644000076500001200000000630511313735447023603 0ustar guenteradmin00000000000000// // ODBCColumn.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/ODBCColumn.h#4 $ // // Library: Data/ODBC // Package: ODBC // Module: ODBCColumn // // Definition of ODBCColumn. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_ODBCColumn_INCLUDED #define ODBC_ODBCColumn_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/Error.h" #include "Poco/Data/ODBC/Handle.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/MetaColumn.h" #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API ODBCColumn: public MetaColumn { public: explicit ODBCColumn(const StatementHandle& rStmt, std::size_t position); /// Creates the ODBCColumn. ~ODBCColumn(); /// Destroys the ODBCColumn. std::size_t dataLength() const; /// A numeric value that is either the maximum or actual character length of a character /// string or binary data type. It is the maximum character length for a fixed-length data type, /// or the actual character length for a variable-length data type. Its value always excludes the /// null-termination byte that ends the character string. /// This information is returned from the SQL_DESC_LENGTH record field of the IRD. private: ODBCColumn(); static const int NAME_BUFFER_LENGTH = 2048; struct ColumnDescription { POCO_SQLCHAR name[NAME_BUFFER_LENGTH]; SQLSMALLINT nameBufferLength; SQLSMALLINT dataType; SQLULEN size; SQLSMALLINT decimalDigits; SQLSMALLINT isNullable; }; void init(); void getDescription(); SQLLEN _dataLength; const StatementHandle& _rStmt; ColumnDescription _columnDesc; }; /// /// inlines /// inline std::size_t ODBCColumn::dataLength() const { return _dataLength; } } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/ODBCException.h0000644000076500001200000001107211313735447024301 0ustar guenteradmin00000000000000// // ODBCException.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/ODBCException.h#5 $ // // Library: ODBC // Package: ODBC // Module: ODBCException // // Definition of ODBCException. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Data_ODBC_ODBCException_INCLUDED #define Data_ODBC_ODBCException_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/Error.h" #include "Poco/Data/DataException.h" #include "Poco/Format.h" namespace Poco { namespace Data { namespace ODBC { POCO_DECLARE_EXCEPTION(ODBC_API, ODBCException, Poco::Data::DataException) POCO_DECLARE_EXCEPTION(ODBC_API, InsufficientStorageException, ODBCException) POCO_DECLARE_EXCEPTION(ODBC_API, UnknownDataLengthException, ODBCException) POCO_DECLARE_EXCEPTION(ODBC_API, DataTruncatedException, ODBCException) template class HandleException: public ODBCException { public: HandleException(const H& handle): _error(handle) /// Creates HandleException { message(_error.toString()); } HandleException(const H& handle, const std::string& msg): ODBCException(msg), _error(handle) /// Creates HandleException { extendedMessage(_error.toString()); } HandleException(const H& handle, const std::string& msg, const std::string& arg): ODBCException(msg, arg), _error(handle) /// Creates HandleException { } HandleException(const H& handle, const std::string& msg, const Poco::Exception& exc): ODBCException(msg, exc), _error(handle) /// Creates HandleException { } HandleException(const HandleException& exc): ODBCException(exc), _error(exc._error) /// Creates HandleException { } ~HandleException() throw() /// Destroys HandleException { } HandleException& operator = (const HandleException& exc) /// Assignment operator { HandleException::operator = (exc); return *this; } const char* name() const throw() /// Returns the name of the exception { return "ODBC handle exception"; } const char* className() const throw() /// Returns the HandleException class name. { return typeid(*this).name(); } Poco::Exception* clone() const /// Clones the HandleException { return new HandleException(*this); } void rethrow() const /// Re-throws the HandleException. { throw *this; } const Diagnostics& diagnostics() const /// Returns error diagnostics. { return _error.diagnostics(); } std::string toString() const /// Returns the formatted error diagnostics for the handle. { return Poco::format("ODBC Error: %s\n===================\n%s\n", std::string(what()), _error.toString()); } static std::string errorString(const H& handle) /// Returns the error diagnostics string for the handle. { return Error(handle).toString(); } private: Error _error; }; typedef HandleException EnvironmentException; typedef HandleException ConnectionException; typedef HandleException StatementException; typedef HandleException DescriptorException; } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/ODBCStatementImpl.h0000644000076500001200000001240211313735447025127 0ustar guenteradmin00000000000000// // ODBCStatementImpl.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/ODBCStatementImpl.h#4 $ // // Library: Data/ODBC // Package: ODBC // Module: ODBCStatementImpl // // Definition of the ODBCStatementImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_ODBC_ODBCStatementImpl_INCLUDED #define DataConnectors_ODBC_ODBCStatementImpl_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/SessionImpl.h" #include "Poco/Data/ODBC/Binder.h" #include "Poco/Data/ODBC/Extractor.h" #include "Poco/Data/ODBC/Preparation.h" #include "Poco/Data/ODBC/ODBCColumn.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/Column.h" #include "Poco/SharedPtr.h" #include "Poco/Format.h" #include #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API ODBCStatementImpl: public Poco::Data::StatementImpl /// Implements statement functionality needed for ODBC { public: typedef std::vector ColumnPtrVec; ODBCStatementImpl(SessionImpl& rSession); /// Creates the ODBCStatementImpl. ~ODBCStatementImpl(); /// Destroys the ODBCStatementImpl. protected: Poco::UInt32 columnsReturned() const; /// Returns number of columns returned by query. const MetaColumn& metaColumn(Poco::UInt32 pos) const; /// Returns column meta data. bool hasNext(); /// Returns true if a call to next() will return data. void next(); /// Retrieves the next row from the resultset. /// Will throw, if the resultset is empty. bool canBind() const; /// Returns true if a valid statement is set and we can bind. void compileImpl(); /// Compiles the statement, doesn't bind yet void bindImpl(); /// Binds parameters AbstractExtractor& extractor(); /// Returns the concrete extractor used by the statement. AbstractBinder& binder(); /// Returns the concrete binder used by the statement. std::string nativeSQL(); /// Returns the SQL string as modified by the driver. private: typedef Poco::Data::AbstractBindingVec Bindings; typedef Poco::Data::AbstractExtractionVec Extractions; static const std::string INVALID_CURSOR_STATE; void clear(); /// Closes the cursor and resets indicator variables. bool hasData() const; /// Returns true if statement returns data. bool nextRowReady() const; /// Returns true if there is a row fetched but not yet extracted. void putData(); /// Called whenever SQLExecute returns SQL_NEED_DATA. This is expected /// behavior for PB_AT_EXEC binding mode. void fillColumns(); void checkError(SQLRETURN rc, const std::string& msg=""); SessionImpl& _rSession; const StatementHandle _stmt; Poco::SharedPtr _pPreparation; Poco::SharedPtr _pBinder; Poco::SharedPtr _pExtractor; bool _stepCalled; int _nextResponse; ColumnPtrVec _columnPtrs; }; // // inlines // inline AbstractExtractor& ODBCStatementImpl::extractor() { poco_assert_dbg (_pExtractor); return *_pExtractor; } inline AbstractBinder& ODBCStatementImpl::binder() { poco_assert_dbg (_pBinder); return *_pBinder; } inline Poco::UInt32 ODBCStatementImpl::columnsReturned() const { poco_assert_dbg (_pPreparation); return (Poco::UInt32) _pPreparation->columns(); } inline bool ODBCStatementImpl::hasData() const { poco_assert_dbg (_pPreparation); return (_pPreparation->columns() > 0); } inline bool ODBCStatementImpl::nextRowReady() const { return (!Utility::isError(_nextResponse)); } inline const MetaColumn& ODBCStatementImpl::metaColumn(Poco::UInt32 pos) const { std::size_t sz = _columnPtrs.size(); if (0 == sz || pos > sz - 1) throw InvalidAccessException(format("Invalid column number: %u", pos)); return *_columnPtrs[pos]; } } } } // namespace Poco::Data::ODBC #endif // DataConnectors_ODBC_ODBCStatementImpl_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Parameter.h0000644000076500001200000000642111313735447023635 0ustar guenteradmin00000000000000// // Parameter.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Parameter.h#3 $ // // Library: Data/ODBC // Package: ODBC // Module: Parameter // // Definition of Parameter. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_Parameter_INCLUDED #define ODBC_Parameter_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/Handle.h" #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API Parameter { public: explicit Parameter(const StatementHandle& rStmt, std::size_t colNum); /// Creates the Parameter. ~Parameter(); /// Destroys the Parameter. std::size_t number() const; /// Returns the column number. std::size_t dataType() const; /// Returns the SQL data type. std::size_t columnSize() const; /// Returns the the size of the column or expression of the corresponding /// parameter marker as defined by the data source. std::size_t decimalDigits() const; /// Returns the number of decimal digits of the column or expression /// of the corresponding parameter as defined by the data source. bool isNullable() const; /// Returns true if column allows null values, false otherwise. private: Parameter(); static const int BUFFER_LENGTH = 2048; void init(); SQLSMALLINT _dataType; SQLULEN _columnSize; SQLSMALLINT _decimalDigits; SQLSMALLINT _isNullable; const StatementHandle& _rStmt; std::size_t _number; }; /// /// inlines /// inline std::size_t Parameter::number() const { return _number; } inline std::size_t Parameter::dataType() const { return _dataType; } inline std::size_t Parameter::columnSize() const { return _columnSize; } inline std::size_t Parameter::decimalDigits() const { return _decimalDigits; } inline bool Parameter::isNullable() const { return SQL_NULLABLE == _isNullable; } } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Preparation.h0000644000076500001200000002144011313735447024177 0ustar guenteradmin00000000000000// // Preparation.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Preparation.h#6 $ // // Library: Data/ODBC // Package: ODBC // Module: Preparation // // Definition of the Preparation class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_ODBC_Preparation_INCLUDED #define DataConnectors_ODBC_Preparation_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/Handle.h" #include "Poco/Data/ODBC/ODBCColumn.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/AbstractPreparation.h" #include "Poco/Data/BLOB.h" #include "Poco/Any.h" #include "Poco/SharedPtr.h" #include #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class BLOB; class ODBC_API Preparation : public AbstractPreparation /// Class used for database preparation where we first have to register all data types /// with respective memory output locations before extracting data. /// Extraction works in two-phases: first prepare is called once, then extract n-times. /// In ODBC, SQLBindCol/SQLFetch is the preferred method of data retrieval (SQLGetData is available, /// however with numerous driver implementation dependent limitations). In order to fit this functionality /// into Poco DataConnectors framework, every ODBC SQL statement instantiates its own Preparation object. /// This is done once per statement execution (from StatementImpl::bindImpl()). /// /// Preparation object is used to : /// /// 1) Prepare SQL statement. /// 2) Provide and contain the memory locations where retrieved values are placed during recordset iteration. /// 3) Keep count of returned number of columns with their respective datatypes and sizes. /// /// Notes: /// /// - Value datatypes in this interface prepare() calls serve only for the purpose of type distinction. /// - Preparation keeps its own std::vector buffer for fetched data to be later retrieved by Extractor. /// - prepare() methods should not be called when extraction mode is DE_MANUAL /// { public: enum DataExtraction { DE_MANUAL, DE_BOUND }; Preparation(const StatementHandle& rStmt, const std::string& statement, std::size_t maxFieldSize, DataExtraction dataExtraction = DE_BOUND); /// Creates the Preparation. ~Preparation(); /// Destroys the Preparation. void prepare(std::size_t pos, Poco::Int8); /// Prepares an Int8. void prepare(std::size_t pos, Poco::UInt8); /// Prepares an UInt8. void prepare(std::size_t pos, Poco::Int16); /// Prepares an Int16. void prepare(std::size_t pos, Poco::UInt16); /// Prepares an UInt16. void prepare(std::size_t pos, Poco::Int32); /// Prepares an Int32. void prepare(std::size_t pos, Poco::UInt32); /// Prepares an UInt32. void prepare(std::size_t pos, Poco::Int64); /// Prepares an Int64. void prepare(std::size_t pos, Poco::UInt64); /// Prepares an UInt64. void prepare(std::size_t pos, bool); /// Prepares a boolean. void prepare(std::size_t pos, float); /// Prepares a float. void prepare(std::size_t pos, double); /// Prepares a double. void prepare(std::size_t pos, char); /// Prepares a single character. void prepare(std::size_t pos, const std::string&); /// Prepares a string. void prepare(std::size_t pos, const Poco::Data::BLOB&); /// Prepares a BLOB. void prepare(std::size_t pos, const Poco::Any&); /// Prepares an Any. std::size_t columns() const; /// Returns the number of columns. Poco::Any& operator [] (std::size_t pos); /// Returns reference to column data. void setMaxFieldSize(std::size_t size); /// Sets maximum supported field size. std::size_t getMaxFieldSize() const; // Returns maximum supported field size. std::size_t maxDataSize(std::size_t pos) const; /// Returns max supported size for column at position pos. /// Returned length for variable length fields is the one /// supported by this implementation, not the underlying DB. std::size_t actualDataSize(std::size_t pos) const; /// Returns the returned length. This is usually /// equal to the column size, except for variable length fields /// (BLOB and variable length strings). void setDataExtraction(DataExtraction ext); /// Set data extraction mode. DataExtraction getDataExtraction() const; /// Returns data extraction mode. private: template void preparePOD(std::size_t pos, SQLSMALLINT valueType) { poco_assert (DE_BOUND == _dataExtraction); poco_assert (pos >= 0 && pos < _pValues.size()); std::size_t dataSize = sizeof(T); _pValues[pos] = new Poco::Any(T()); _pLengths[pos] = new SQLLEN; *_pLengths[pos] = 0; T* pVal = AnyCast(_pValues[pos]); poco_assert_dbg (pVal); if (Utility::isError(SQLBindCol(_rStmt, (SQLUSMALLINT) pos + 1, valueType, (SQLPOINTER) pVal, (SQLINTEGER) dataSize, _pLengths[pos]))) { throw StatementException(_rStmt, "SQLBindCol()"); } } void prepareRaw(std::size_t pos, SQLSMALLINT valueType, std::size_t size); const StatementHandle& _rStmt; std::vector _pValues; std::vector _pLengths; std::size_t _maxFieldSize; DataExtraction _dataExtraction; std::vector _charPtrs; }; // // inlines // inline void Preparation::prepare(std::size_t pos, Poco::Int8) { preparePOD(pos, SQL_C_STINYINT); } inline void Preparation::prepare(std::size_t pos, Poco::UInt8) { preparePOD(pos, SQL_C_UTINYINT); } inline void Preparation::prepare(std::size_t pos, Poco::Int16) { preparePOD(pos, SQL_C_SSHORT); } inline void Preparation::prepare(std::size_t pos, Poco::UInt16) { preparePOD(pos, SQL_C_USHORT); } inline void Preparation::prepare(std::size_t pos, Poco::Int32) { preparePOD(pos, SQL_C_SLONG); } inline void Preparation::prepare(std::size_t pos, Poco::UInt32) { preparePOD(pos, SQL_C_ULONG); } inline void Preparation::prepare(std::size_t pos, Poco::Int64) { preparePOD(pos, SQL_C_SBIGINT); } inline void Preparation::prepare(std::size_t pos, Poco::UInt64) { preparePOD(pos, SQL_C_UBIGINT); } inline void Preparation::prepare(std::size_t pos, bool) { preparePOD(pos, SQL_C_BIT); } inline void Preparation::prepare(std::size_t pos, float) { preparePOD(pos, SQL_C_FLOAT); } inline void Preparation::prepare(std::size_t pos, double) { preparePOD(pos, SQL_C_DOUBLE); } inline void Preparation::prepare(std::size_t pos, char) { preparePOD(pos, SQL_C_STINYINT); } inline void Preparation::prepare(std::size_t pos, const std::string&) { prepareRaw(pos, SQL_C_CHAR, maxDataSize(pos)); } inline void Preparation::prepare(std::size_t pos, const Poco::Data::BLOB&) { prepareRaw(pos, SQL_C_BINARY, maxDataSize(pos)); } inline std::size_t Preparation::columns() const { return _pValues.size(); } inline std::size_t Preparation::actualDataSize(std::size_t pos) const { poco_assert (pos >= 0 && pos < _pValues.size()); poco_assert (_pLengths[pos]); return *_pLengths[pos]; } inline void Preparation::setMaxFieldSize(std::size_t size) { _maxFieldSize = size; } inline std::size_t Preparation::getMaxFieldSize() const { return _maxFieldSize; } inline void Preparation::setDataExtraction(Preparation::DataExtraction ext) { _dataExtraction = ext; } inline Preparation::DataExtraction Preparation::getDataExtraction() const { return _dataExtraction; } } } } // namespace Poco::Data::ODBC #endif // DataConnectors_ODBC_Preparation_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/SessionImpl.h0000644000076500001200000001331311313735447024160 0ustar guenteradmin00000000000000// // SessionImpl.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/SessionImpl.h#5 $ // // Library: Data/ODBC // Package: ODBC // Module: SessionImpl // // Definition of the SessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_ODBC_SessionImpl_INCLUDED #define DataConnectors_ODBC_SessionImpl_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/Binder.h" #include "Poco/Data/ODBC/Handle.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/AbstractSessionImpl.h" #include "Poco/SharedPtr.h" #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API SessionImpl: public Poco::Data::AbstractSessionImpl /// Implements SessionImpl interface { public: SessionImpl(const std::string& fileName, Poco::Any maxFieldSize = std::size_t(1024), bool enforceCapability=false, // @deprecated bool autoBind=false, bool autoExtract=false); /// Creates the SessionImpl. Opens a connection to the database ~SessionImpl(); /// Destroys the SessionImpl. Poco::Data::StatementImpl* createStatementImpl(); /// Returns an ODBC StatementImpl void begin(); /// Starts a transaction void commit(); /// Commits and ends a transaction void rollback(); /// Aborts a transaction void close(); /// Closes the connection bool isConnected(); /// Returns true iff session is connected. bool isTransaction(); /// Returns true iff a transaction is in progress. void setEnforceCapability(const std::string&, bool val); /// Configures session to enforce driver capability check /// after connection. /// If capability check is enforced and driver is not capable, /// connection is terminated. /// Since some drivers do not cooperate, the default behavior /// is not checking capability. bool getEnforceCapability(const std::string& name=""); /// Returns the driver capability check configuration value. bool canTransact(); /// Returns true if connection is transaction-capable. void autoCommit(const std::string&, bool val); /// Sets autocommit property for the session. bool isAutoCommit(const std::string& name=""); /// Returns autocommit property value. void autoBind(const std::string&, bool val); /// Sets automatic binding for the session. bool isAutoBind(const std::string& name=""); /// Returns true if binding is automatic for this session. void autoExtract(const std::string&, bool val); /// Sets automatic extraction for the session. bool isAutoExtract(const std::string& name=""); /// Returns true if extraction is automatic for this session. void setMaxFieldSize(const std::string& rName, const Poco::Any& rValue); /// Sets the max field size (the default used when column size is unknown). Poco::Any getMaxFieldSize(const std::string& rName=""); /// Returns the max field size (the default used when column size is unknown). int maxStatementLength(); /// Returns maximum length of SQL statement allowed by driver. const ConnectionHandle& dbc() const; /// Returns the connection handle. private: static const int FUNCTIONS = SQL_API_ODBC3_ALL_FUNCTIONS_SIZE; void open(); /// Opens a connection to the Database bool isCapable(); /// Returns true if driver supports specified function, or if /// specified function is zero, all required functions. void checkError(SQLRETURN rc, const std::string& msg=""); std::string _connect; const ConnectionHandle _db; Poco::Any _maxFieldSize; bool _enforceCapability; bool _autoBind; bool _autoExtract; }; /// /// inlines /// inline void SessionImpl::checkError(SQLRETURN rc, const std::string& msg) { if (Utility::isError(rc)) throw ConnectionException(_db, msg); } inline const ConnectionHandle& SessionImpl::dbc() const { return _db; } inline void SessionImpl::commit() { if (!isAutoCommit()) checkError(SQLEndTran(SQL_HANDLE_DBC, _db, SQL_COMMIT)); } inline void SessionImpl::rollback() { if (!isAutoCommit()) checkError(SQLEndTran(SQL_HANDLE_DBC, _db, SQL_ROLLBACK)); } inline void SessionImpl::setMaxFieldSize(const std::string& rName, const Poco::Any& rValue) { _maxFieldSize = rValue; } inline Poco::Any SessionImpl::getMaxFieldSize(const std::string& rName) { return _maxFieldSize; } } } } // namespace Poco::Data::ODBC #endif // DataConnectors_ODBC_SessionImpl_INCLUDED poco-1.3.6p1-all/Data/ODBC/include/Poco/Data/ODBC/Utility.h0000644000076500001200000000677311313735447023372 0ustar guenteradmin00000000000000// // Utility.h // // $Id: //poco/1.3/Data/ODBC/include/Poco/Data/ODBC/Utility.h#3 $ // // Library: Data/ODBC // Package: ODBC // Module: Utility // // Definition of Utility. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBC_Utility_INCLUDED #define ODBC_Utility_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/ODBC/DataTypes.h" #include #ifdef POCO_OS_FAMILY_WINDOWS #include #endif #include namespace Poco { namespace Data { namespace ODBC { class ODBC_API Utility /// Various utility functions { public: typedef std::map DSNMap; typedef DSNMap DriverMap; static bool isError(SQLRETURN rc); /// Returns true if return code is error static DriverMap& drivers(DriverMap& driverMap); /// Returns driver-attributes map of available ODBC drivers. static DSNMap& dataSources(DSNMap& dsnMap); /// Returns DSN-description map of available ODBC data sources. template static typename MapType::iterator mapInsert(MapType& m, const KeyArgType& k, const ValueArgType& v) /// Utility map "insert or replace" function (from S. Meyers: Effective STL, Item 24) { typename MapType::iterator lb = m.lower_bound(k); if (lb != m.end() && !(m.key_comp()(k, lb->first))) { lb->second = v; return lb; } else { typedef typename MapType::value_type MVT; return m.insert(lb, MVT(k,v)); } } static int cDataType(int sqlDataType); /// Returns C data type corresponding to supplied SQL data type. static int sqlDataType(int cDataType); /// Returns SQL data type corresponding to supplied C data type. static const SQLSMALLINT boolDataType; /// ODBC size for bool data type. private: static const DataTypes _dataTypes; /// C <==> SQL data type mapping }; /// /// inlines /// inline bool Utility::isError(SQLRETURN rc) { return (0 != (rc & (~1))); } inline int Utility::cDataType(int sqlDataType) { return _dataTypes.cDataType(sqlDataType); } inline int Utility::sqlDataType(int cDataType) { return _dataTypes.sqlDataType(cDataType); } } } } // namespace Poco::Data::ODBC #endif poco-1.3.6p1-all/Data/ODBC/Makefile0000644000076500001200000000344211313735447017301 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/Main/Data/ODBC/Makefile#2 $ # # Makefile for Poco ODBC # include $(POCO_BASE)/build/rules/global # adjust for the target system (usually '/usr/lib' or '/usr/local/lib') ODBCLIBDIR = /usr/lib INCLUDE += -I/usr/local/include -I/usr/include -I/usr/include/odbc -I/usr/local/include/odbc SYSLIBS += -L/usr/local/lib/odbc -L/usr/lib/odbc -L/usr/lib -L/usr/local/lib ifeq ($(POCO_CONFIG),MinGW) # Lack of unixODBC or iODBC is not an error for MinGW platform since it uses Windows odbc32.lib else ifeq ($(POCO_CONFIG),CYGWIN) # -DODBCVER=0x0300: SQLHandle declaration issue # -DNOMINMAX : MIN/MAX macros defined in windows conflict with libstdc++ CXXFLAGS += -DODBCVER=0x0300 -DNOMINMAX # CYGWIN platform has its own ODBC library in /lib/w32api SYSLIBS += -L/lib/w32api -lodbc32 -lodbccp32 else ifeq (0, $(shell test -e $(ODBCLIBDIR)/libodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -lodbc -lodbcinst COMMONFLAGS += -DPOCO_UNIXODBC else ifeq (0, $(shell test -h $(ODBCLIBDIR)/libodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -lodbc -lodbcinst COMMONFLAGS += -DPOCO_UNIXODBC else ifeq (0, $(shell test -e $(ODBCLIBDIR)/libiodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -liodbc -liodbcinst COMMONFLAGS += -DPOCO_IODBC else ifeq (0, $(shell test -h $(ODBCLIBDIR)/libiodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -liodbc -liodbcinst COMMONFLAGS += -DPOCO_IODBC else $(error No ODBC library found. Please install unixODBC or iODBC and try again) endif endif endif endif endif endif objects = Binder ConnectionHandle Connector DataTypes EnvironmentHandle \ Extractor ODBCColumn ODBCException ODBCStatementImpl \ Parameter Preparation SessionImpl Utility target = PocoODBC target_version = $(LIBVERSION) target_libs = PocoData PocoFoundation include $(POCO_BASE)/build/rules/lib poco-1.3.6p1-all/Data/ODBC/ODBC.vmsbuild0000644000076500001200000000031611313735447020114 0ustar guenteradmin00000000000000# # ODBC.vmsbuild # # $Id: //poco/1.3/Data/ODBC/ODBC.vmsbuild#1 $ # LIB=PocoODBC Binder Column DataTypes Extractor Handle ODBCException ODBCStatementImpl Preparation SessionImpl SessionInstantiator Utility poco-1.3.6p1-all/Data/ODBC/ODBC_VS71.sln0000644000076500001200000000447511313735447017655 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS71.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {1B29820D-375F-11DB-837B-00123FC423B5} = {1B29820D-375F-11DB-837B-00123FC423B5} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ODBC", "ODBC_VS71.vcproj", "{1B29820D-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared debug_static = debug_static release_static = release_static EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static.Build.0 = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/ODBC/ODBC_VS71.vcproj0000644000076500001200000002220611313735447020354 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/ODBC/ODBC_VS80.sln0000644000076500001200000000460111313735447017644 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS80.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {1B29820D-375F-11DB-837B-00123FC423B5} = {1B29820D-375F-11DB-837B-00123FC423B5} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ODBC", "ODBC_VS80.vcproj", "{1B29820D-375F-11DB-837B-00123FC423B5}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/ODBC/ODBC_VS80.vcproj0000644000076500001200000002424511313735447020361 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/ODBC/ODBC_vs90.sln0000644000076500001200000000460211313735447017746 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs90.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {1B29820D-375F-11DB-837B-00123FC423B5} = {1B29820D-375F-11DB-837B-00123FC423B5} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ODBC", "ODBC_vs90.vcproj", "{1B29820D-375F-11DB-837B-00123FC423B5}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/ODBC/ODBC_vs90.vcproj0000644000076500001200000002441711313735447020463 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/ODBC/src/0000755000076500001200000000000011313735447016425 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/src/Binder.cpp0000644000076500001200000000734211313735447020342 0ustar guenteradmin00000000000000// // Binder.cpp // // $Id: //poco/1.3/Data/ODBC/src/Binder.cpp#4 $ // // Library: Data/ODBC // Package: ODBC // Module: Binder // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/Binder.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Exception.h" #include namespace Poco { namespace Data { namespace ODBC { Binder::Binder(const StatementHandle& rStmt, Binder::ParameterBinding dataBinding): _rStmt(rStmt), _paramBinding(dataBinding) { } Binder::~Binder() { std::vector::iterator it = _lengthIndicator.begin(); std::vector::iterator itEnd = _lengthIndicator.end(); for(; it != itEnd; ++it) delete *it; } void Binder::bind(std::size_t pos, const std::string& val) { SQLINTEGER size = (SQLINTEGER) val.size(); SQLLEN* pLenIn = new SQLLEN; *pLenIn = SQL_NTS; if (PB_AT_EXEC == _paramBinding) *pLenIn = SQL_LEN_DATA_AT_EXEC(size); _lengthIndicator.push_back(pLenIn); _dataSize.insert(SizeMap::value_type((SQLPOINTER) val.c_str(), size)); if (Utility::isError(SQLBindParameter(_rStmt, (SQLUSMALLINT) pos + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, (SQLUINTEGER) size, 0, (SQLPOINTER) val.c_str(), (SQLINTEGER) size, _lengthIndicator.back()))) { throw StatementException(_rStmt, "SQLBindParameter()"); } } void Binder::bind(std::size_t pos, const Poco::Data::BLOB& val) { SQLINTEGER size = (SQLINTEGER) val.size(); SQLLEN* pLenIn = new SQLLEN; *pLenIn = size; if (PB_AT_EXEC == _paramBinding) *pLenIn = SQL_LEN_DATA_AT_EXEC(size); _lengthIndicator.push_back(pLenIn); _dataSize.insert(SizeMap::value_type((SQLPOINTER) val.rawContent(), size)); if (Utility::isError(SQLBindParameter(_rStmt, (SQLUSMALLINT) pos + 1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, (SQLUINTEGER) size, 0, (SQLPOINTER) val.rawContent(), (SQLINTEGER) size, _lengthIndicator.back()))) { throw StatementException(_rStmt, "SQLBindParameter()"); } } std::size_t Binder::dataSize(SQLPOINTER pAddr) const { SizeMap::const_iterator it = _dataSize.find(pAddr); if (it != _dataSize.end()) return it->second; throw NotFoundException("Requested data size not found."); } void Binder::bind(std::size_t pos, const char* const &pVal) { //no-op } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/ConnectionHandle.cpp0000644000076500001200000000454411313735447022353 0ustar guenteradmin00000000000000// // ConnectionHandle.cpp // // $Id: //poco/1.3/Data/ODBC/src/ConnectionHandle.cpp#3 $ // // Library: Data/ODBC // Package: ODBC // Module: ConnectionHandle // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/ConnectionHandle.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/ODBCException.h" namespace Poco { namespace Data { namespace ODBC { ConnectionHandle::ConnectionHandle(EnvironmentHandle* pEnvironment): _pEnvironment(pEnvironment ? pEnvironment : new EnvironmentHandle), _hdbc(SQL_NULL_HDBC), _ownsEnvironment(pEnvironment ? false : true) { if (Utility::isError(SQLAllocHandle(SQL_HANDLE_DBC, _pEnvironment->handle(), &_hdbc))) { throw ODBCException("Could not allocate connection handle."); } } ConnectionHandle::~ConnectionHandle() { SQLDisconnect(_hdbc); SQLRETURN rc = SQLFreeHandle(SQL_HANDLE_DBC, _hdbc); if (_ownsEnvironment) delete _pEnvironment; poco_assert (!Utility::isError(rc)); } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/Connector.cpp0000644000076500001200000000436111313735447021067 0ustar guenteradmin00000000000000// // Connector.cpp // // $Id: //poco/1.3/Data/ODBC/src/Connector.cpp#2 $ // // Library: Data/ODBC // Package: ODBC // Module: Connector // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/SessionImpl.h" #include "Poco/Data/SessionFactory.h" namespace Poco { namespace Data { namespace ODBC { const std::string Connector::KEY("ODBC"); Connector::Connector() { } Connector::~Connector() { } Poco::AutoPtr Connector::createSession(const std::string& connectionString) { return Poco::AutoPtr(new SessionImpl(connectionString)); } void Connector::registerConnector() { Poco::Data::SessionFactory::instance().add(KEY, new Connector()); } void Connector::unregisterConnector() { Poco::Data::SessionFactory::instance().remove(KEY); } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/DataTypes.cpp0000644000076500001200000001110411313735447021024 0ustar guenteradmin00000000000000// // DataTypes.cpp // // $Id: //poco/1.3/Data/ODBC/src/DataTypes.cpp#5 $ // // Library: Data/ODBC // Package: ODBC // Module: DataTypes // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/DataTypes.h" #include "Poco/Format.h" #include "Poco/Exception.h" namespace Poco { namespace Data { namespace ODBC { DataTypes::DataTypes() { _cDataTypes.insert(ValueType(SQL_CHAR, SQL_C_CHAR)); _cDataTypes.insert(ValueType(SQL_VARCHAR, SQL_C_CHAR)); _cDataTypes.insert(ValueType(SQL_LONGVARCHAR, SQL_C_CHAR)); _cDataTypes.insert(ValueType(SQL_DECIMAL, SQL_C_DOUBLE)); _cDataTypes.insert(ValueType(SQL_NUMERIC, SQL_C_DOUBLE)); _cDataTypes.insert(ValueType(SQL_BIT, SQL_C_BIT)); _cDataTypes.insert(ValueType(SQL_TINYINT, SQL_C_STINYINT)); _cDataTypes.insert(ValueType(SQL_SMALLINT, SQL_C_SSHORT)); _cDataTypes.insert(ValueType(SQL_INTEGER, SQL_C_SLONG)); _cDataTypes.insert(ValueType(SQL_BIGINT, SQL_C_SBIGINT)); _cDataTypes.insert(ValueType(SQL_REAL, SQL_C_FLOAT)); _cDataTypes.insert(ValueType(SQL_FLOAT, SQL_C_DOUBLE)); _cDataTypes.insert(ValueType(SQL_DOUBLE, SQL_C_DOUBLE)); _cDataTypes.insert(ValueType(SQL_BINARY, SQL_C_BINARY)); _cDataTypes.insert(ValueType(SQL_VARBINARY, SQL_C_BINARY)); _cDataTypes.insert(ValueType(SQL_LONGVARBINARY, SQL_C_BINARY)); _cDataTypes.insert(ValueType(SQL_TYPE_DATE, SQL_C_TYPE_DATE)); _cDataTypes.insert(ValueType(SQL_TYPE_TIME, SQL_C_TYPE_TIME)); _cDataTypes.insert(ValueType(SQL_TYPE_TIMESTAMP, SQL_C_TYPE_TIMESTAMP)); _sqlDataTypes.insert(ValueType(SQL_C_CHAR, SQL_LONGVARCHAR)); _sqlDataTypes.insert(ValueType(SQL_C_BIT, SQL_BIT)); _sqlDataTypes.insert(ValueType(SQL_C_TINYINT, SQL_TINYINT)); _sqlDataTypes.insert(ValueType(SQL_C_STINYINT, SQL_TINYINT)); _sqlDataTypes.insert(ValueType(SQL_C_UTINYINT, SQL_TINYINT)); _sqlDataTypes.insert(ValueType(SQL_C_SHORT, SQL_SMALLINT)); _sqlDataTypes.insert(ValueType(SQL_C_SSHORT, SQL_SMALLINT)); _sqlDataTypes.insert(ValueType(SQL_C_USHORT, SQL_SMALLINT)); _sqlDataTypes.insert(ValueType(SQL_C_LONG, SQL_INTEGER)); _sqlDataTypes.insert(ValueType(SQL_C_SLONG, SQL_INTEGER)); _sqlDataTypes.insert(ValueType(SQL_C_ULONG, SQL_INTEGER)); _sqlDataTypes.insert(ValueType(SQL_C_SBIGINT, SQL_BIGINT)); _sqlDataTypes.insert(ValueType(SQL_C_UBIGINT, SQL_BIGINT)); _sqlDataTypes.insert(ValueType(SQL_C_FLOAT, SQL_REAL)); _sqlDataTypes.insert(ValueType(SQL_C_DOUBLE, SQL_DOUBLE)); _sqlDataTypes.insert(ValueType(SQL_C_BINARY, SQL_LONGVARBINARY)); _sqlDataTypes.insert(ValueType(SQL_C_TYPE_DATE, SQL_TYPE_DATE)); _sqlDataTypes.insert(ValueType(SQL_C_TYPE_TIME, SQL_TYPE_TIME)); _sqlDataTypes.insert(ValueType(SQL_C_TYPE_TIMESTAMP, SQL_TYPE_TIMESTAMP)); } DataTypes::~DataTypes() { } int DataTypes::cDataType(int sqlDataType) const { DataTypeMap::const_iterator it = _cDataTypes.find(sqlDataType); if (_cDataTypes.end() == it) throw NotFoundException(format("C data type not found for SQL data type: %d", sqlDataType)); return it->second; } int DataTypes::sqlDataType(int cDataType) const { DataTypeMap::const_iterator it = _sqlDataTypes.find(cDataType); if (_sqlDataTypes.end() == it) throw NotFoundException(format("SQL data type not found for C data type: %d", cDataType)); return it->second; } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/EnvironmentHandle.cpp0000644000076500001200000000436211313735447022556 0ustar guenteradmin00000000000000// // EnvironmentHandle.cpp // // $Id: //poco/1.3/Data/ODBC/src/EnvironmentHandle.cpp#3 $ // // Library: Data/ODBC // Package: ODBC // Module: EnvironmentHandle // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/EnvironmentHandle.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/ODBCException.h" namespace Poco { namespace Data { namespace ODBC { EnvironmentHandle::EnvironmentHandle(): _henv(SQL_NULL_HENV) { if (Utility::isError(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &_henv)) || Utility::isError(SQLSetEnvAttr(_henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0))) { throw ODBCException("Could not initialize environment."); } } EnvironmentHandle::~EnvironmentHandle() { SQLRETURN rc = SQLFreeHandle(SQL_HANDLE_ENV, _henv); poco_assert (!Utility::isError(rc)); } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/Extractor.cpp0000644000076500001200000002320511313735447021106 0ustar guenteradmin00000000000000// // Extractor.cpp // // $Id: //poco/1.3/Data/ODBC/src/Extractor.cpp#8 $ // // Library: Data/ODBC // Package: ODBC // Module: Extractor // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/Extractor.h" #include "Poco/Data/ODBC/ODBCColumn.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/BLOB.h" #include "Poco/Buffer.h" #include "Poco/Exception.h" namespace Poco { namespace Data { namespace ODBC { const std::string Extractor::FLD_SIZE_EXCEEDED_FMT = "Specified data size (%z bytes) " "exceeds maximum value (%z).\n" "Use Session.setProperty(\"maxFieldSize\", value) " "to increase the maximum allowed data size\n"; Extractor::Extractor(const StatementHandle& rStmt, Preparation& rPreparation): _rStmt(rStmt), _rPreparation(rPreparation), _dataExtraction(rPreparation.getDataExtraction()) { } Extractor::~Extractor() { } template<> bool Extractor::extractBoundImpl(std::size_t pos, std::string& val) { std::size_t dataSize = _rPreparation.actualDataSize(pos); char*& sp = RefAnyCast(_rPreparation[pos]); poco_check_ptr (sp); std::size_t len = std::strlen(sp); if (len < dataSize) dataSize = len; checkDataSize(dataSize); val.assign(sp, dataSize); return true; } template<> bool Extractor::extractBoundImpl(std::size_t pos, Poco::Data::BLOB& val) { std::size_t dataSize = _rPreparation.actualDataSize(pos); checkDataSize(dataSize); char*& sp = RefAnyCast(_rPreparation[pos]); poco_check_ptr (sp); val.assignRaw(sp, dataSize); return true; } template<> bool Extractor::extractManualImpl(std::size_t pos, std::string& val, SQLSMALLINT cType) { std::size_t maxSize = _rPreparation.getMaxFieldSize(); std::size_t fetchedSize = 0; std::size_t totalSize = 0; SQLLEN len; Poco::Buffer apChar(CHUNK_SIZE); char* pChar = apChar.begin(); SQLRETURN rc = 0; val.clear(); do { std::memset(pChar, 0, CHUNK_SIZE); len = 0; rc = SQLGetData(_rStmt, (SQLUSMALLINT) pos + 1, cType, //C data type pChar, //returned value CHUNK_SIZE, //buffer length &len); //length indicator if (SQL_NO_DATA != rc && Utility::isError(rc)) throw StatementException(_rStmt, "SQLGetData()"); if (SQL_NO_TOTAL == len)//unknown length, throw throw UnknownDataLengthException("Could not determine returned data length."); if (SQL_NO_DATA == rc || SQL_NULL_DATA == len || !len) break; fetchedSize = len > CHUNK_SIZE ? CHUNK_SIZE : len; totalSize += fetchedSize; if (totalSize <= maxSize) val.append(pChar, fetchedSize); else throw DataException(format(FLD_SIZE_EXCEEDED_FMT, fetchedSize, maxSize)); }while (true); return true; } template<> bool Extractor::extractManualImpl(std::size_t pos, Poco::Data::BLOB& val, SQLSMALLINT cType) { std::size_t maxSize = _rPreparation.getMaxFieldSize(); std::size_t fetchedSize = 0; std::size_t totalSize = 0; SQLLEN len; Poco::Buffer apChar(CHUNK_SIZE); char* pChar = apChar.begin(); SQLRETURN rc = 0; val.clear(); do { std::memset(pChar, 0, CHUNK_SIZE); len = 0; rc = SQLGetData(_rStmt, (SQLUSMALLINT) pos + 1, cType, //C data type pChar, //returned value CHUNK_SIZE, //buffer length &len); //length indicator if (SQL_NO_DATA != rc && Utility::isError(rc)) throw StatementException(_rStmt, "SQLGetData()"); if (SQL_NO_TOTAL == len)//unknown length, throw throw UnknownDataLengthException("Could not determine returned data length."); if (SQL_NO_DATA == rc || SQL_NULL_DATA == len || !len) break; fetchedSize = len > CHUNK_SIZE ? CHUNK_SIZE : len; totalSize += fetchedSize; if (totalSize <= maxSize) val.appendRaw(pChar, fetchedSize); else throw DataException(format(FLD_SIZE_EXCEEDED_FMT, fetchedSize, maxSize)); }while (true); return true; } bool Extractor::extract(std::size_t pos, Poco::Int32& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_SLONG); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::Int64& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_SBIGINT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, double& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_DOUBLE); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, std::string& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_CHAR); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::Data::BLOB& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_BINARY); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::Int8& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_STINYINT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::UInt8& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_UTINYINT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::Int16& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_SSHORT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::UInt16& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_USHORT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::UInt32& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_ULONG); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::UInt64& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_SBIGINT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, bool& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_BIT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, float& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_FLOAT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, char& val) { if (Preparation::DE_MANUAL == _dataExtraction) return extractManualImpl(pos, val, SQL_C_STINYINT); else return extractBoundImpl(pos, val); } bool Extractor::extract(std::size_t pos, Poco::Any& val) { ODBCColumn column(_rStmt, pos); switch (column.type()) { case MetaColumn::FDT_INT8: { Poco::Int8 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_UINT8: { Poco::UInt8 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_INT16: { Poco::Int16 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_UINT16: { Poco::UInt16 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_INT32: { Poco::Int32 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_UINT32: { Poco::UInt32 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_INT64: { Poco::Int64 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_UINT64: { Poco::UInt64 i = 0; extract(pos, i); val = i; return true; } case MetaColumn::FDT_BOOL: { bool b; extract(pos, b); val = b; return true; } case MetaColumn::FDT_FLOAT: { float f; extract(pos, f); val = f; return true; } case MetaColumn::FDT_DOUBLE: { double d; extract(pos, d); val = d; return true; } case MetaColumn::FDT_STRING: { std::string s; extract(pos, s); val = s; return true; } case MetaColumn::FDT_BLOB: { Poco::Data::BLOB b; extract(pos, b); val = b; return true; } default: throw DataFormatException("Unsupported data type."); } return false; } void Extractor::checkDataSize(std::size_t size) { std::size_t maxSize = _rPreparation.getMaxFieldSize(); if (size > maxSize) { throw DataException(format(FLD_SIZE_EXCEEDED_FMT, size, maxSize)); } } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/ODBCColumn.cpp0000644000076500001200000000756611313735447021034 0ustar guenteradmin00000000000000// // ODBCColumn.cpp // // $Id: //poco/1.3/Data/ODBC/src/ODBCColumn.cpp#9 $ // // Library: Data/ODBC // Package: ODBC // Module: ODBCColumn // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/ODBCColumn.h" #include "Poco/Data/ODBC/Utility.h" namespace Poco { namespace Data { namespace ODBC { ODBCColumn::ODBCColumn(const StatementHandle& rStmt, std::size_t position) : MetaColumn(position), _rStmt(rStmt) { init(); } ODBCColumn::~ODBCColumn() { } void ODBCColumn::getDescription() { std::memset(_columnDesc.name, 0, NAME_BUFFER_LENGTH); _columnDesc.nameBufferLength = 0; _columnDesc.dataType = 0; _columnDesc.size = 0; _columnDesc.decimalDigits = 0; _columnDesc.isNullable = 0; if (Utility::isError(SQLDescribeCol(_rStmt, (SQLUSMALLINT) position() + 1, // ODBC columns are 1-based _columnDesc.name, NAME_BUFFER_LENGTH, &_columnDesc.nameBufferLength, &_columnDesc.dataType, &_columnDesc.size, &_columnDesc.decimalDigits, &_columnDesc.isNullable))) { throw StatementException(_rStmt); } } void ODBCColumn::init() { getDescription(); if (Utility::isError(SQLColAttribute(_rStmt, (SQLUSMALLINT) position() + 1, // ODBC columns are 1-based SQL_DESC_LENGTH, 0, 0, 0, &_dataLength))) { throw StatementException(_rStmt); } setName(std::string((char*) _columnDesc.name)); setLength(_columnDesc.size); setPrecision(_columnDesc.decimalDigits); setNullable(SQL_NULLABLE == _columnDesc.isNullable); switch(_columnDesc.dataType) { case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: case -9:// SQL Server NVARCHAR case -10:// PostgreSQL VARCHAR (without size specified) setType(MetaColumn::FDT_STRING); break; case SQL_BIT: setType(MetaColumn::FDT_BOOL); break; case SQL_TINYINT: setType(MetaColumn::FDT_INT8); break; case SQL_SMALLINT: setType(MetaColumn::FDT_INT16); break; case SQL_INTEGER: setType(MetaColumn::FDT_INT32); break; case SQL_BIGINT: setType(MetaColumn::FDT_INT64); break; case SQL_DOUBLE: case SQL_FLOAT: setType(MetaColumn::FDT_DOUBLE); break; case SQL_NUMERIC: case SQL_DECIMAL: if (0 == _columnDesc.decimalDigits) setType(MetaColumn::FDT_INT32); else setType(MetaColumn::FDT_DOUBLE); break; case SQL_REAL: setType(MetaColumn::FDT_FLOAT); break; case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: case -98:// IBM DB2 non-standard type setType(MetaColumn::FDT_BLOB); break; default: throw DataFormatException("Unsupported data type."); } } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/ODBCException.cpp0000644000076500001200000000416711313735447021527 0ustar guenteradmin00000000000000// // ODBCException.cpp // // $Id: //poco/1.3/Data/ODBC/src/ODBCException.cpp#3 $ // // Library: Data/ODBC // Package: ODBC // Module: ODBCException // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/ODBCException.h" #include namespace Poco { namespace Data { namespace ODBC { POCO_IMPLEMENT_EXCEPTION(ODBCException, Poco::Data::DataException, "Generic ODBC error") POCO_IMPLEMENT_EXCEPTION(InsufficientStorageException, ODBCException, "Insufficient storage error") POCO_IMPLEMENT_EXCEPTION(UnknownDataLengthException, ODBCException, "Unknown length of remaining data error") POCO_IMPLEMENT_EXCEPTION(DataTruncatedException, ODBCException, "Variable length character or binary data truncated") } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/ODBCStatementImpl.cpp0000644000076500001200000001721511313735447022355 0ustar guenteradmin00000000000000// // ODBCStatementImpl.cpp // // $Id: //poco/1.3/Data/ODBC/src/ODBCStatementImpl.cpp#9 $ // // Library: Data/ODBC // Package: ODBC // Module: ODBCStatementImpl // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include "Poco/Data/ODBC/Handle.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/AbstractPrepare.h" #include namespace Poco { namespace Data { namespace ODBC { const std::string ODBCStatementImpl::INVALID_CURSOR_STATE = "24000"; ODBCStatementImpl::ODBCStatementImpl(SessionImpl& rSession): _rSession(rSession), _stmt(_rSession.dbc()), _stepCalled(false), _nextResponse(0) { if (_rSession.getFeature("autoBind")) { SQLSetStmtAttr(_stmt, SQL_ATTR_PARAM_BIND_TYPE, (SQLPOINTER) SQL_PARAM_BIND_BY_COLUMN, 0); } else { SQLSetStmtAttr(_stmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER) 1, 0); } } ODBCStatementImpl::~ODBCStatementImpl() { ColumnPtrVec::iterator it = _columnPtrs.begin(); ColumnPtrVec::iterator itEnd = _columnPtrs.end(); for(; it != itEnd; ++it) delete *it; } void ODBCStatementImpl::compileImpl() { _stepCalled = false; _nextResponse = 0; std::string statement(toString()); if (statement.empty()) throw ODBCException("Empty statements are illegal"); Preparation::DataExtraction ext = _rSession.getFeature("autoExtract") ? Preparation::DE_BOUND : Preparation::DE_MANUAL; std::size_t maxFieldSize = AnyCast(_rSession.getProperty("maxFieldSize")); _pPreparation = new Preparation(_stmt, statement, maxFieldSize, ext); Binder::ParameterBinding bind = _rSession.getFeature("autoBind") ? Binder::PB_IMMEDIATE : Binder::PB_AT_EXEC; _pBinder = new Binder(_stmt, bind); _pExtractor = new Extractor(_stmt, *_pPreparation); bool dataAvailable = hasData(); if (dataAvailable && !extractions().size()) { fillColumns(); makeExtractors(columnsReturned()); } if (Preparation::DE_BOUND == ext && dataAvailable) { std::size_t pos = 0; Extractions& extracts = extractions(); Extractions::iterator it = extracts.begin(); Extractions::iterator itEnd = extracts.end(); for (; it != itEnd; ++it) { AbstractPrepare* pAP = (*it)->createPrepareObject(_pPreparation, pos); pAP->prepare(); pos += (*it)->numOfColumnsHandled(); delete pAP; } } } bool ODBCStatementImpl::canBind() const { if (!bindings().empty()) return (*bindings().begin())->canBind(); return false; } void ODBCStatementImpl::bindImpl() { clear(); Bindings& binds = bindings(); if (!binds.empty()) { std::size_t pos = 0; Bindings::iterator it = binds.begin(); Bindings::iterator itEnd = binds.end(); for (; it != itEnd && (*it)->canBind(); ++it) { (*it)->bind(pos); pos += (*it)->numOfColumnsHandled(); } } SQLRETURN rc = SQLExecute(_stmt); if (SQL_NEED_DATA == rc) putData(); else checkError(rc, "SQLExecute()"); } void ODBCStatementImpl::putData() { SQLPOINTER pParam = 0; SQLRETURN rc = SQLParamData(_stmt, &pParam); do { poco_assert_dbg (pParam); SQLINTEGER dataSize = (SQLINTEGER) _pBinder->dataSize(pParam); if (Utility::isError(SQLPutData(_stmt, pParam, dataSize))) throw StatementException(_stmt, "SQLPutData()"); }while (SQL_NEED_DATA == (rc = SQLParamData(_stmt, &pParam))); checkError(rc, "SQLParamData()"); } void ODBCStatementImpl::clear() { SQLRETURN rc = SQLCloseCursor(_stmt); _stepCalled = false; if (Utility::isError(rc)) { StatementError err(_stmt); bool ignoreError = false; const StatementDiagnostics& diagnostics = err.diagnostics(); //ignore "Invalid cursor state" error //(returned by 3.x drivers when cursor is not opened) for (int i = 0; i < diagnostics.count(); ++i) { ignoreError = (INVALID_CURSOR_STATE == std::string(diagnostics.sqlState(i))); if (ignoreError) { break; } } if (!ignoreError) throw StatementException(_stmt, "SQLCloseCursor()"); } } bool ODBCStatementImpl::hasNext() { if (hasData()) { if (_stepCalled) return _stepCalled = nextRowReady(); _stepCalled = true; _nextResponse = SQLFetch(_stmt); if (!nextRowReady()) return false; else if (Utility::isError(_nextResponse)) checkError(_nextResponse, "SQLFetch()"); return true; } return false; } void ODBCStatementImpl::next() { if (nextRowReady()) { poco_assert (columnsExtracted() == _pPreparation->columns()); Extractions& extracts = extractions(); Extractions::iterator it = extracts.begin(); Extractions::iterator itEnd = extracts.end(); std::size_t pos = 0; for (; it != itEnd; ++it) { (*it)->extract(pos); pos += (*it)->numOfColumnsHandled(); } _stepCalled = false; } else { throw StatementException(_stmt, std::string("Iterator Error: trying to access the next value")); } } std::string ODBCStatementImpl::nativeSQL() { std::string statement = toString(); //Hopefully, double the original statement length is enough. //If it is not, the total available length is indicated in the retlen parameter, //which is in turn used to resize the buffer and request the native SQL again. SQLINTEGER length = (SQLINTEGER) statement.size() * 2; char* pNative = 0; SQLINTEGER retlen = length; do { delete [] pNative; pNative = new char[retlen]; std::memset(pNative, 0, retlen); length = retlen; if (Utility::isError(SQLNativeSql(_rSession.dbc(), (POCO_SQLCHAR*) statement.c_str(), (SQLINTEGER) statement.size(), (POCO_SQLCHAR*) pNative, length, &retlen))) { delete [] pNative; throw ConnectionException(_rSession.dbc(), "SQLNativeSql()"); } ++retlen;//accomodate for terminating '\0' }while (retlen > length); std::string sql(pNative); delete [] pNative; return sql; } void ODBCStatementImpl::checkError(SQLRETURN rc, const std::string& msg) { if (SQL_NO_DATA == rc) return; if (Utility::isError(rc)) { std::ostringstream os; os << std::endl << "Requested SQL statement: " << toString() << std::endl; os << "Native SQL statement: " << nativeSQL() << std::endl; std::string str(msg); str += os.str(); throw StatementException(_stmt, str); } } void ODBCStatementImpl::fillColumns() { Poco::UInt32 colCount = columnsReturned(); for (int i = 0; i < colCount; ++i) _columnPtrs.push_back(new ODBCColumn(_stmt, i)); } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/Parameter.cpp0000644000076500001200000000422311313735447021052 0ustar guenteradmin00000000000000// // Parameter.cpp // // $Id: //poco/1.3/Data/ODBC/src/Parameter.cpp#5 $ // // Library: Data/ODBC // Package: ODBC // Module: Parameter // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/Parameter.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Error.h" #include "Poco/Data/ODBC/ODBCException.h" namespace Poco { namespace Data { namespace ODBC { Parameter::Parameter(const StatementHandle& rStmt, std::size_t colNum) : _rStmt(rStmt), _number(colNum) { init(); } Parameter::~Parameter() { } void Parameter::init() { if (Utility::isError(SQLDescribeParam(_rStmt, (SQLUSMALLINT) _number + 1, &_dataType, &_columnSize, &_decimalDigits, &_isNullable))) { throw StatementException(_rStmt); } } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/Preparation.cpp0000644000076500001200000001236411313735447021423 0ustar guenteradmin00000000000000// // Preparation.cpp // // $Id: //poco/1.3/Data/ODBC/src/Preparation.cpp#7 $ // // Library: Data/ODBC // Package: ODBC // Module: Preparation // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/Preparation.h" #include "Poco/Data/ODBC/ODBCColumn.h" namespace Poco { namespace Data { namespace ODBC { Preparation::Preparation(const StatementHandle& rStmt, const std::string& statement, std::size_t maxFieldSize, DataExtraction dataExtraction): _rStmt(rStmt), _maxFieldSize(maxFieldSize), _dataExtraction(dataExtraction) { POCO_SQLCHAR* pStr = (POCO_SQLCHAR*) statement.c_str(); if (Utility::isError(SQLPrepare(_rStmt, pStr, (SQLINTEGER) statement.length()))) throw StatementException(_rStmt); SQLSMALLINT nCol; if (Utility::isError(SQLNumResultCols(_rStmt, &nCol))) throw StatementException(_rStmt); if (nCol) { _pValues.resize(nCol, 0); _pLengths.resize(nCol, 0); } } Preparation::~Preparation() { std::vector::iterator itLen = _pLengths.begin(); std::vector::iterator itLenEnd = _pLengths.end(); for (; itLen != itLenEnd; ++itLen) delete *itLen; std::vector::iterator itVal = _pValues.begin(); std::vector::iterator itValEnd = _pValues.end(); for (; itVal != itValEnd; ++itVal) delete *itVal; std::vector::iterator itChr = _charPtrs.begin(); std::vector::iterator itChrEnd = _charPtrs.end(); for (; itChr != itChrEnd; ++itChr) delete [] *itChr; } Poco::Any& Preparation::operator [] (std::size_t pos) { poco_assert (pos >= 0 && pos < _pValues.size()); return *_pValues[pos]; } void Preparation::prepareRaw(std::size_t pos, SQLSMALLINT valueType, std::size_t size) { poco_assert (DE_BOUND == _dataExtraction); poco_assert (pos >= 0 && pos < _pValues.size()); char* pChr = new char[size]; _charPtrs.push_back(pChr); poco_assert_dbg (pChr); std::memset(pChr, 0, size); _pValues[pos] = new Any(pChr); _pLengths[pos] = new SQLLEN; *_pLengths[pos] = (SQLLEN) size; if (Utility::isError(SQLBindCol(_rStmt, (SQLUSMALLINT) pos + 1, valueType, (SQLPOINTER) pChr, (SQLINTEGER) size, _pLengths[pos]))) { throw StatementException(_rStmt, "SQLBindCol()"); } } void Preparation::prepare(std::size_t pos, const Poco::Any&) { ODBCColumn col(_rStmt, pos); switch (col.type()) { case MetaColumn::FDT_INT8: return preparePOD(pos, SQL_C_STINYINT); case MetaColumn::FDT_UINT8: return preparePOD(pos, SQL_C_UTINYINT); case MetaColumn::FDT_INT16: return preparePOD(pos, SQL_C_SSHORT); case MetaColumn::FDT_UINT16: return preparePOD(pos, SQL_C_USHORT); case MetaColumn::FDT_INT32: return preparePOD(pos, SQL_C_SLONG); case MetaColumn::FDT_UINT32: return preparePOD(pos, SQL_C_ULONG); case MetaColumn::FDT_INT64: return preparePOD(pos, SQL_C_SBIGINT); case MetaColumn::FDT_UINT64: return preparePOD(pos, SQL_C_UBIGINT); case MetaColumn::FDT_BOOL: return preparePOD(pos, SQL_C_BIT); case MetaColumn::FDT_FLOAT: return preparePOD(pos, SQL_C_FLOAT); case MetaColumn::FDT_DOUBLE: return preparePOD(pos, SQL_C_DOUBLE); case MetaColumn::FDT_STRING: return prepareRaw(pos, SQL_C_CHAR, maxDataSize(pos)); case MetaColumn::FDT_BLOB: return prepareRaw(pos, SQL_C_BINARY, maxDataSize(pos)); default: throw DataFormatException("Unsupported data type."); } prepareRaw(pos, SQL_C_BINARY, maxDataSize(pos)); } std::size_t Preparation::maxDataSize(std::size_t pos) const { poco_assert (pos >= 0 && pos < _pValues.size()); std::size_t sz = 0; std::size_t maxsz = getMaxFieldSize(); try { ODBCColumn col(_rStmt, pos); sz = col.length(); if (ODBCColumn::FDT_STRING == col.type()) ++sz; } catch (StatementException&) { } if (!sz || sz > maxsz) sz = maxsz; return sz; } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/SessionImpl.cpp0000644000076500001200000001543711313735447021410 0ustar guenteradmin00000000000000// // SessionImpl.cpp // // $Id: //poco/1.3/Data/ODBC/src/SessionImpl.cpp#5 $ // // Library: Data/ODBC // Package: ODBC // Module: SessionImpl // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/SessionImpl.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include "Poco/Data/ODBC/Error.h" #include "Poco/Data/ODBC/ODBCException.h" #include namespace Poco { namespace Data { namespace ODBC { SessionImpl::SessionImpl(const std::string& connect, Poco::Any maxFieldSize, bool enforceCapability, bool autoBind, bool autoExtract): _connect(connect), _maxFieldSize(maxFieldSize), _enforceCapability(enforceCapability), _autoBind(autoBind), _autoExtract(autoExtract) { open(); } SessionImpl::~SessionImpl() { close(); } Poco::Data::StatementImpl* SessionImpl::createStatementImpl() { return new ODBCStatementImpl(*this); } void SessionImpl::begin() { } void SessionImpl::open() { POCO_SQLCHAR connectOutput[512] = {0}; SQLSMALLINT result; if (Utility::isError(SQLDriverConnect(_db , NULL ,(POCO_SQLCHAR*) _connect.c_str() ,(SQLSMALLINT) SQL_NTS , connectOutput , sizeof(connectOutput) , &result , SQL_DRIVER_NOPROMPT))) { ConnectionException exc(_db); close(); throw exc; } addFeature("enforceCapability", &SessionImpl::setEnforceCapability, &SessionImpl::getEnforceCapability); addFeature("autoCommit", &SessionImpl::autoCommit, &SessionImpl::isAutoCommit); addFeature("autoBind", &SessionImpl::autoBind, &SessionImpl::isAutoBind); addFeature("autoExtract", &SessionImpl::autoExtract, &SessionImpl::isAutoExtract); addProperty("maxFieldSize", &SessionImpl::setMaxFieldSize, &SessionImpl::getMaxFieldSize); if (_enforceCapability && !isCapable()) { close(); throw ODBCException("Connection closed " "(capability enforcement required but not all required functions supported)."); } SQLSetConnectAttr(_db, SQL_ATTR_QUIET_MODE, 0, 0); if (!canTransact()) autoCommit("", true); } bool SessionImpl::canTransact() { SQLUSMALLINT ret; checkError(SQLGetInfo(_db, SQL_TXN_CAPABLE, &ret, 0, 0), "Failed to obtain transaction capability info."); return (SQL_TC_NONE != ret); } void SessionImpl::autoCommit(const std::string&, bool val) { checkError(SQLSetConnectAttr(_db, SQL_ATTR_AUTOCOMMIT, val ? (SQLPOINTER) SQL_AUTOCOMMIT_ON : (SQLPOINTER) SQL_AUTOCOMMIT_OFF, 0), "Failed to set automatic commit."); } bool SessionImpl::isAutoCommit(const std::string&) { Poco::UInt32 value = 0; checkError(SQLGetConnectAttr(_db, SQL_ATTR_AUTOCOMMIT, &value, 0, 0)); return (0 != value); } bool SessionImpl::isConnected() { Poco::UInt32 value = 0; if (Utility::isError(SQLGetConnectAttr(_db, SQL_ATTR_CONNECTION_DEAD, &value, 0, 0))) return false; return (0 == value); } bool SessionImpl::isTransaction() { Poco::UInt32 value = 0; checkError(SQLGetConnectAttr(_db, SQL_ATTR_AUTOCOMMIT, &value, 0, 0)); return (0 == value); } void SessionImpl::close() { if (!isConnected()) return; commit(); checkError(SQLDisconnect(_db)); } bool SessionImpl::isCapable() { SQLUSMALLINT exists[FUNCTIONS] = {0}; if (Utility::isError(SQLGetFunctions(_db, SQL_API_ODBC3_ALL_FUNCTIONS, exists))) { throw ConnectionException(_db, "SQLGetFunctions(SQL_API_ODBC3_ALL_FUNCTIONS)"); } return SQL_FUNC_EXISTS(exists, SQL_API_SQLBINDPARAMETER) && SQL_FUNC_EXISTS(exists, SQL_API_SQLBINDCOL) && SQL_FUNC_EXISTS(exists, SQL_API_SQLGETDATA) && SQL_FUNC_EXISTS(exists, SQL_API_SQLPUTDATA) && SQL_FUNC_EXISTS(exists, SQL_API_SQLPARAMDATA) && SQL_FUNC_EXISTS(exists, SQL_API_SQLDESCRIBECOL) && SQL_FUNC_EXISTS(exists, SQL_API_SQLDESCRIBEPARAM) && SQL_FUNC_EXISTS(exists, SQL_API_SQLGETINFO) && SQL_FUNC_EXISTS(exists, SQL_API_SQLGETDIAGREC) && SQL_FUNC_EXISTS(exists, SQL_API_SQLGETDIAGFIELD) && SQL_FUNC_EXISTS(exists, SQL_API_SQLPREPARE) && SQL_FUNC_EXISTS(exists, SQL_API_SQLEXECUTE) && SQL_FUNC_EXISTS(exists, SQL_API_SQLEXECDIRECT) && SQL_FUNC_EXISTS(exists, SQL_API_SQLFETCH) && SQL_FUNC_EXISTS(exists, SQL_API_SQLNUMRESULTCOLS) && SQL_FUNC_EXISTS(exists, SQL_API_SQLALLOCHANDLE) && SQL_FUNC_EXISTS(exists, SQL_API_SQLFREEHANDLE) && SQL_FUNC_EXISTS(exists, SQL_API_SQLCLOSECURSOR) && SQL_FUNC_EXISTS(exists, SQL_API_SQLSETCONNECTATTR) && SQL_FUNC_EXISTS(exists, SQL_API_SQLSETSTMTATTR) && SQL_FUNC_EXISTS(exists, SQL_API_SQLENDTRAN) && SQL_FUNC_EXISTS(exists, SQL_API_SQLNATIVESQL) && SQL_FUNC_EXISTS(exists, SQL_API_SQLCOLATTRIBUTE); } int SessionImpl::maxStatementLength() { SQLUINTEGER info; SQLRETURN rc = 0; if (Utility::isError(rc = SQLGetInfo(_db, SQL_MAXIMUM_STATEMENT_LENGTH, (SQLPOINTER) &info, 0, 0))) { throw ConnectionException(_db, "SQLGetInfo(SQL_MAXIMUM_STATEMENT_LENGTH)"); } return info; } void SessionImpl::setEnforceCapability(const std::string&, bool val) { _enforceCapability = val; } bool SessionImpl::getEnforceCapability(const std::string&) { return _enforceCapability; } void SessionImpl::autoBind(const std::string&, bool val) { _autoBind = val; } bool SessionImpl::isAutoBind(const std::string& name) { return _autoBind; } void SessionImpl::autoExtract(const std::string&, bool val) { _autoExtract = val; } bool SessionImpl::isAutoExtract(const std::string& name) { return _autoExtract; } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/src/Utility.cpp0000644000076500001200000000723311313735447020601 0ustar guenteradmin00000000000000// // Utility.cpp // // $Id: //poco/1.3/Data/ODBC/src/Utility.cpp#5 $ // // Library: Data/ODBC // Package: ODBC // Module: Utility // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Handle.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/NumberFormatter.h" namespace Poco { namespace Data { namespace ODBC { const DataTypes Utility::_dataTypes; const SQLSMALLINT Utility::boolDataType = (sizeof(bool) <= sizeof(char)) ? SQL_C_TINYINT : (sizeof(bool) == sizeof(short)) ? SQL_C_SHORT : SQL_C_LONG; Utility::DriverMap& Utility::drivers(Utility::DriverMap& driverMap) { static const EnvironmentHandle henv; const int length = sizeof(POCO_SQLCHAR) * 512; POCO_SQLCHAR desc[length]; std::memset(desc, 0, length); SQLSMALLINT len1 = length; POCO_SQLCHAR attr[length]; std::memset(attr, 0, length); SQLSMALLINT len2 = length; RETCODE rc = 0; if (!Utility::isError(rc = SQLDrivers(henv, SQL_FETCH_FIRST, desc, length, &len1, attr, len2, &len2))) { do { driverMap.insert(DSNMap::value_type(std::string((char *) desc), std::string((char *) attr))); std::memset(desc, 0, length); std::memset(attr, 0, length); len2 = length; }while (!Utility::isError(rc = SQLDrivers(henv, SQL_FETCH_NEXT, desc, length, &len1, attr, len2, &len2))); } if (SQL_NO_DATA != rc) throw EnvironmentError(henv); return driverMap; } Utility::DSNMap& Utility::dataSources(Utility::DSNMap& dsnMap) { static const EnvironmentHandle henv; const int length = sizeof(POCO_SQLCHAR) * 512; const int dsnLength = sizeof(POCO_SQLCHAR) * (SQL_MAX_DSN_LENGTH + 1); POCO_SQLCHAR dsn[dsnLength]; std::memset(dsn, 0, dsnLength); SQLSMALLINT len1 = sizeof(POCO_SQLCHAR) * SQL_MAX_DSN_LENGTH; POCO_SQLCHAR desc[length]; std::memset(desc, 0, length); SQLSMALLINT len2 = length; RETCODE rc = 0; while (!Utility::isError(rc = SQLDataSources(henv, SQL_FETCH_NEXT, dsn, SQL_MAX_DSN_LENGTH, &len1, desc, len2, &len2))) { dsnMap.insert(DSNMap::value_type(std::string((char *) dsn), std::string((char *) desc))); std::memset(dsn, 0, dsnLength); std::memset(desc, 0, length); len2 = length; } if (SQL_NO_DATA != rc) throw EnvironmentError(henv); return dsnMap; } } } } // namespace Poco::Data::ODBC poco-1.3.6p1-all/Data/ODBC/testsuite/0000755000076500001200000000000011313735447017667 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/testsuite/Makefile0000644000076500001200000000356111313735447021334 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/ODBC/testsuite/Makefile#8 $ # # Makefile for Poco SQLite testsuite # include $(POCO_BASE)/build/rules/global # adjust for the target system (usually '/usr/lib' or '/usr/local/lib') ODBCLIBDIR = /usr/lib INCLUDE += -I/usr/local/include -I/usr/include -I/usr/include/odbc -I/usr/local/include/odbc SYSLIBS += -L/usr/local/lib/odbc -L/usr/lib/odbc -L/usr/lib -L/usr/local/lib ifeq ($(POCO_CONFIG),MinGW) # Lack of unixODBC or iODBC is not an error for MinGW platform since it uses Windows odbc32.lib else ifeq ($(POCO_CONFIG),CYGWIN) # -DODBCVER=0x0300: SQLHandle declaration issue # -DNOMINMAX : MIN/MAX macros defined in windows conflict with libstdc++ CXXFLAGS += -DODBCVER=0x0300 -DNOMINMAX # CYGWIN platform has its own ODBC library in /lib/w32api SYSLIBS += -L/lib/w32api -lodbc32 -lodbccp32 else ifeq (0, $(shell test -e $(ODBCLIBDIR)/libodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -lodbc -lodbcinst COMMONFLAGS += -DPOCO_UNIXODBC else ifeq (0, $(shell test -h $(ODBCLIBDIR)/libodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -lodbc -lodbcinst COMMONFLAGS += -DPOCO_UNIXODBC else ifeq (0, $(shell test -e $(ODBCLIBDIR)/libiodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -liodbc -liodbcinst COMMONFLAGS += -DPOCO_IODBC else ifeq (0, $(shell test -h $(ODBCLIBDIR)/libiodbc$(SHAREDLIBLINKEXT); echo $$?)) SYSLIBS += -liodbc -liodbcinst COMMONFLAGS += -DPOCO_IODBC else $(error No ODBC library found. Please install unixODBC or iODBC and try again) endif endif endif endif endif endif objects = ODBCTestSuite Driver \ ODBCDB2Test ODBCMySQLTest ODBCOracleTest \ ODBCPostgreSQLTest ODBCSQLiteTest ODBCSQLServerTest SQLExecutor ifeq ($(POCO_CONFIG),MinGW) objects += ODBCAccessTest ODBCSQLServerTest endif target = testrunner target_version = 1 target_libs = PocoODBC PocoData PocoFoundation CppUnit include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Data/ODBC/testsuite/src/0000755000076500001200000000000011313735447020456 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/ODBC/testsuite/src/Driver.cpp0000644000076500001200000000317411313735447022422 0ustar guenteradmin00000000000000// // Driver.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/Driver.cpp#2 $ // // Console-based test driver for Poco SQLite. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CppUnit/TestRunner.h" #include "ODBCTestSuite.h" CppUnitMain(ODBCTestSuite) poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCAccessTest.cpp0000644000076500001200000001622611313735447023662 0ustar guenteradmin00000000000000// // ODBCAccessTest.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCAccessTest.cpp#3 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCAccessTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; Poco::SharedPtr ODBCAccessTest::_pSession = 0; std::string ODBCAccessTest::_dsn = "PocoDataAccessTest"; std::string ODBCAccessTest::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCAccessTest::_drivers; Poco::Data::ODBC::Utility::DSNMap ODBCAccessTest::_dataSources; ODBCAccessTest::ODBCAccessTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty() || _dataSources.empty()) { Utility::drivers(_drivers); Utility::dataSources(_dataSources); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. Access tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } //N.B. Access driver does not suport check for connection. if (_pSession) std::cout << "*** Connected to " << _dsn << '(' << _dbConnString << ')' << std::endl; } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. Access tests will fail !!!" << std::endl; beenHere = true; } ODBCAccessTest::~ODBCAccessTest() { ODBC::Connector::unregisterConnector(); } void ODBCAccessTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); std::string lastName = "lastName"; int age = 133132; int count = 0; std::string result; recreatePersonTable(); count = 0; try { *_pSession << "INSERT INTO PERSON VALUES('lastName', 'firstName', 'Address', 133132)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("testSimpleAccess()"); } catch(StatementException& ex){ std::cout << ex.toString() << std::endl; fail ("testSimpleAccess()");} try { *_pSession << "SELECT COUNT(*) FROM PERSON", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("testSimpleAccess()"); } catch(StatementException& ex){ std::cout << ex.toString() << std::endl; fail ("testSimpleAccess()"); } assert (count == 1); try { *_pSession << "SELECT LastName FROM PERSON", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("testSimpleAccess()"); } catch(StatementException& ex){ std::cout << ex.toString() << std::endl; fail ("testSimpleAccess()"); } assert (lastName == result); try { *_pSession << "SELECT Age FROM PERSON", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("testSimpleAccess()"); } catch(StatementException& ex){ std::cout << ex.toString() << std::endl; fail ("testSimpleAccess()"); } assert (count == age); } void ODBCAccessTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (-1305 == it->_nativeError)//MS Access -1305 (table does not exist) { ignoreError = true; break; } } if (!ignoreError) throw; } } void ODBCAccessTest::recreatePersonTable() { dropTable("Person"); *_pSession << "CREATE TABLE Person (LastName TEXT(30), FirstName TEXT(30), Address TEXT(30), Age INTEGER)", now; } void ODBCAccessTest::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; bool dsnFound = false; Utility::DriverMap::iterator itDrv = _drivers.begin(); for (; itDrv != _drivers.end(); ++itDrv) { if (((itDrv->first).find("Microsoft Access Driver") != std::string::npos)) { std::cout << "Driver found: " << itDrv->first << " (" << itDrv->second << ')' << std::endl; driverFound = true; break; } } if (!driverFound) { std::cout << "Driver NOT found, will throw." << std::endl; throw NotFoundException("Microsoft Access ODBC driver."); } Utility::DSNMap::iterator itDSN = _dataSources.begin(); for (; itDSN != _dataSources.end(); ++itDSN) { if (((itDSN->first).find(_dsn) != std::string::npos) && ((itDSN->second).find("Microsoft Access Driver") != std::string::npos)) { std::cout << "DSN found: " << itDSN->first << " (" << itDSN->second << ')' << std::endl; dsnFound = true; break; } } if (!dsnFound) { std::cout << "Access DSN NOT found, tests will fail." << std::endl; return; } } if (!_pSession) format(_dbConnString, "DSN=%s;Uid=Admin;Pwd=;", _dsn); } void ODBCAccessTest::setUp() { } void ODBCAccessTest::tearDown() { dropTable("Person"); } CppUnit::Test* ODBCAccessTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCAccessTest"); CppUnit_addTest(pSuite, ODBCAccessTest, testSimpleAccess); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCAccessTest.h0000644000076500001200000000513711313735447023326 0ustar guenteradmin00000000000000// // ODBCAccessTest.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCAccessTest.h#2 $ // // Definition of the ODBCAccessTest class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCAccessTest_INCLUDED #define ODBCAccessTest_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCAccessTest: public CppUnit::TestCase /// MS Access ODBC test class /// Tested: /// /// Driver | DB | OS /// ------------+-----------+------------------------------------------ /// 4.00.6305.00| Jet 4.0 | MS Windows XP Professional x64 v.2003/SP1 { public: ODBCAccessTest(const std::string& name); ~ODBCAccessTest(); void testSimpleAccess(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static Poco::Data::ODBC::Utility::DSNMap _dataSources; static std::string _dsn; static std::string _dbConnString; static Poco::SharedPtr _pSession; bool _owner; }; #endif // ODBCAccessTest_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCDB2Test.cpp0000644000076500001200000006075111313735447023032 0ustar guenteradmin00000000000000// // ODBCDB2Test.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCDB2Test.cpp#7 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCDB2Test.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; #define DB2_ODBC_DRIVER "IBM DB2 ODBC DRIVER - DB2COPY1" #define DB2_DSN "PocoDataDB2Test" #define DB2_SERVER "localhost" #define DB2_PORT "50000" #define DB2_DB "POCOTEST" #define DB2_UID "db2admin" #define DB2_PWD "db2admin" const bool ODBCDB2Test::bindValues[8] = {true, true, true, false, false, true, false, false}; Poco::SharedPtr ODBCDB2Test::_pSession = 0; Poco::SharedPtr ODBCDB2Test::_pExecutor = 0; std::string ODBCDB2Test::_dsn = "PocoDataDB2Test"; std::string ODBCDB2Test::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCDB2Test::_drivers; Poco::Data::ODBC::Utility::DSNMap ODBCDB2Test::_dataSources; ODBCDB2Test::ODBCDB2Test(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty() || _dataSources.empty()) { Utility::drivers(_drivers); Utility::dataSources(_dataSources); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. DB2 tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << _dsn << '(' << _dbConnString << ')' << std::endl; if (!_pExecutor) _pExecutor = new SQLExecutor("DB2 SQL Executor", _pSession); } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. DB2 tests will fail !!!" << std::endl; beenHere = true; } ODBCDB2Test::~ODBCDB2Test() { ODBC::Connector::unregisterConnector(); } void ODBCDB2Test::testBareboneODBC() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third BLOB," "Fourth INTEGER," "Fifth FLOAT," "Sixth TIMESTAMP)"; _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_BOUND); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_BOUND); } void ODBCDB2Test::testSimpleAccess() { if (!_pSession) fail ("Test not available."); std::string tableName("Person"); int count = 0; recreatePersonTable(); *_pSession << "SELECT count(*) FROM sysibm.systables WHERE name = 'PERSON' AND creator = 'DB2ADMIN'", into(count), use(tableName), now; assert (1 == count); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccess(); i += 2; } } void ODBCDB2Test::testComplexType() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexType(); i += 2; } } void ODBCDB2Test::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccessVector(); i += 2; } } void ODBCDB2Test::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeVector(); i += 2; } } void ODBCDB2Test::testInsertVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertVector(); i += 2; } } void ODBCDB2Test::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertEmptyVector(); i += 2; } } void ODBCDB2Test::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulk(); i += 2; } } void ODBCDB2Test::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulkVec(); i += 2; } } void ODBCDB2Test::testLimit() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limits(); i += 2; } } void ODBCDB2Test::testLimitZero() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitZero(); i += 2; } } void ODBCDB2Test::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void ODBCDB2Test::testLimitPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitPrepare(); i += 2; } } void ODBCDB2Test::testPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->prepare(); i += 2; } } void ODBCDB2Test::testSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setSimple(); i += 2; } } void ODBCDB2Test::testSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplex(); i += 2; } } void ODBCDB2Test::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplexUnique(); i += 2; } } void ODBCDB2Test::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetSimple(); i += 2; } } void ODBCDB2Test::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetComplex(); i += 2; } } void ODBCDB2Test::testMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplex(); i += 2; } } void ODBCDB2Test::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplexUnique(); i += 2; } } void ODBCDB2Test::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiMapComplex(); i += 2; } } void ODBCDB2Test::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingle(); i += 2; } } void ODBCDB2Test::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleStep(); i += 2; } } void ODBCDB2Test::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleFail(); i += 2; } } void ODBCDB2Test::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitOk(); i += 2; } } void ODBCDB2Test::testSingleSelect() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->singleSelect(); i += 2; } } void ODBCDB2Test::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitFail(); i += 2; } } void ODBCDB2Test::testCombinedLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedLimits(); i += 2; } } void ODBCDB2Test::testRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->ranges(); i += 2; } } void ODBCDB2Test::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedIllegalLimits(); i += 2; } } void ODBCDB2Test::testIllegalRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->illegalRange(); i += 2; } } void ODBCDB2Test::testEmptyDB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->emptyDB(); i += 2; } } void ODBCDB2Test::testBLOB() { if (!_pSession) fail ("Test not available."); const std::size_t maxFldSize = 1000000; _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize-1)); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize); fail ("must fail"); } catch (DataException&) { _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize)); } for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blob(maxFldSize); i += 2; } recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize+1); fail ("must fail"); } catch (DataException&) { } } void ODBCDB2Test::testBLOBStmt() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blobStmt(); i += 2; } } void ODBCDB2Test::testBool() { fail ("not supported"); /* if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateBoolsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->bools(); i += 2; }*/ } void ODBCDB2Test::testFloat() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->floats(); i += 2; } } void ODBCDB2Test::testDouble() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->doubles(); i += 2; } } void ODBCDB2Test::testTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tuples(); i += 2; } } void ODBCDB2Test::testTupleVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tupleVector(); i += 2; } } void ODBCDB2Test::testInternalExtraction() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateVectorsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->internalExtraction(); i += 2; } } void ODBCDB2Test::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (-204 == it->_nativeError)//(table does not exist) { ignoreError = true; break; } } if (!ignoreError) throw; } } void ODBCDB2Test::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTable()"); } } void ODBCDB2Test::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image BLOB)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } } void ODBCDB2Test::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateIntsTable()"); } } void ODBCDB2Test::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateStringsTable()"); } } void ODBCDB2Test::recreateBoolsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str SMALLINT)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateBoolsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateBoolsTable()"); } } void ODBCDB2Test::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str FLOAT)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateFloatsTable()"); } } void ODBCDB2Test::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(int0 INTEGER, int1 INTEGER, int2 INTEGER, int3 INTEGER, int4 INTEGER, int5 INTEGER, int6 INTEGER, " "int7 INTEGER, int8 INTEGER, int9 INTEGER, int10 INTEGER, int11 INTEGER, int12 INTEGER, int13 INTEGER," "int14 INTEGER, int15 INTEGER, int16 INTEGER, int17 INTEGER, int18 INTEGER, int19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateTuplesTable()"); } } void ODBCDB2Test::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (i0 INTEGER, flt0 FLOAT, str0 VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorsTable()"); } } void ODBCDB2Test::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; bool dsnFound = false; Utility::DriverMap::iterator itDrv = _drivers.begin(); for (; itDrv != _drivers.end(); ++itDrv) { if (((itDrv->first).find("IBM DB2") != std::string::npos)) { std::cout << "Driver found: " << itDrv->first << " (" << itDrv->second << ')' << std::endl; driverFound = true; break; } } if (!driverFound) { std::cout << "DB2 driver NOT found, tests will fail." << std::endl; return; } Utility::DSNMap::iterator itDSN = _dataSources.begin(); for (; itDSN != _dataSources.end(); ++itDSN) { if (((itDSN->first).find(_dsn) != std::string::npos) && ((itDSN->second).find("IBM DB2") != std::string::npos)) { std::cout << "DSN found: " << itDSN->first << " (" << itDSN->second << ')' << std::endl; dsnFound = true; break; } } if (!dsnFound) { if (!_pSession && _dbConnString.empty()) { std::cout << "DB2 DSN NOT found, will attempt to connect without it." << std::endl; _dbConnString = "Driver=" DB2_ODBC_DRIVER ";" "Database=" DB2_DB ";" "Hostname=" DB2_SERVER ";" "Port=" DB2_PORT ";" "Protocol=TCPIP;" "Uid=" DB2_UID ";" "Pwd=" DB2_PWD ";"; } else if (!_dbConnString.empty()) { std::cout << "DB2 tests not available." << std::endl; return; } } } if (!_pSession) format(_dbConnString, "DSN=%s;Uid=db2admin;Pwd=db2admin;", _dsn); } void ODBCDB2Test::setUp() { } void ODBCDB2Test::tearDown() { dropTable("Person"); dropTable("Strings"); } CppUnit::Test* ODBCDB2Test::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCDB2Test"); CppUnit_addTest(pSuite, ODBCDB2Test, testBareboneODBC); CppUnit_addTest(pSuite, ODBCDB2Test, testSimpleAccess); CppUnit_addTest(pSuite, ODBCDB2Test, testComplexType); CppUnit_addTest(pSuite, ODBCDB2Test, testSimpleAccessVector); CppUnit_addTest(pSuite, ODBCDB2Test, testComplexTypeVector); CppUnit_addTest(pSuite, ODBCDB2Test, testInsertVector); CppUnit_addTest(pSuite, ODBCDB2Test, testInsertEmptyVector); CppUnit_addTest(pSuite, ODBCDB2Test, testInsertSingleBulk); CppUnit_addTest(pSuite, ODBCDB2Test, testInsertSingleBulkVec); CppUnit_addTest(pSuite, ODBCDB2Test, testLimit); CppUnit_addTest(pSuite, ODBCDB2Test, testLimitOnce); CppUnit_addTest(pSuite, ODBCDB2Test, testLimitPrepare); CppUnit_addTest(pSuite, ODBCDB2Test, testLimitZero); CppUnit_addTest(pSuite, ODBCDB2Test, testPrepare); CppUnit_addTest(pSuite, ODBCDB2Test, testSetSimple); CppUnit_addTest(pSuite, ODBCDB2Test, testSetComplex); CppUnit_addTest(pSuite, ODBCDB2Test, testSetComplexUnique); CppUnit_addTest(pSuite, ODBCDB2Test, testMultiSetSimple); CppUnit_addTest(pSuite, ODBCDB2Test, testMultiSetComplex); CppUnit_addTest(pSuite, ODBCDB2Test, testMapComplex); CppUnit_addTest(pSuite, ODBCDB2Test, testMapComplexUnique); CppUnit_addTest(pSuite, ODBCDB2Test, testMultiMapComplex); CppUnit_addTest(pSuite, ODBCDB2Test, testSelectIntoSingle); CppUnit_addTest(pSuite, ODBCDB2Test, testSelectIntoSingleStep); CppUnit_addTest(pSuite, ODBCDB2Test, testSelectIntoSingleFail); CppUnit_addTest(pSuite, ODBCDB2Test, testLowerLimitOk); CppUnit_addTest(pSuite, ODBCDB2Test, testLowerLimitFail); CppUnit_addTest(pSuite, ODBCDB2Test, testCombinedLimits); CppUnit_addTest(pSuite, ODBCDB2Test, testCombinedIllegalLimits); CppUnit_addTest(pSuite, ODBCDB2Test, testRange); CppUnit_addTest(pSuite, ODBCDB2Test, testIllegalRange); CppUnit_addTest(pSuite, ODBCDB2Test, testSingleSelect); CppUnit_addTest(pSuite, ODBCDB2Test, testEmptyDB); CppUnit_addTest(pSuite, ODBCDB2Test, testBLOB); CppUnit_addTest(pSuite, ODBCDB2Test, testBLOBStmt); CppUnit_addTest(pSuite, ODBCDB2Test, testBool); CppUnit_addTest(pSuite, ODBCDB2Test, testFloat); CppUnit_addTest(pSuite, ODBCDB2Test, testDouble); CppUnit_addTest(pSuite, ODBCDB2Test, testTuple); CppUnit_addTest(pSuite, ODBCDB2Test, testTupleVector); CppUnit_addTest(pSuite, ODBCDB2Test, testInternalExtraction); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCDB2Test.h0000644000076500001200000001000611313735447022463 0ustar guenteradmin00000000000000// // ODBCDB2Test.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCDB2Test.h#4 $ // // Definition of the ODBCDB2Test class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCDB2Test_INCLUDED #define ODBCDB2Test_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCDB2Test: public CppUnit::TestCase /// IBM DB2 UDB ODBC test class /// Tested: /// /// Driver | DB | OS | Notes /// ------------+-------------------+-------------------------------------------+--------------------------- /// 9.01.00.356 | DB2 Express-C 9.1 | MS Windows XP Professional x64 v.2003/SP1 | bool binding not supported /// { public: ODBCDB2Test(const std::string& name); ~ODBCDB2Test(); void testBareboneODBC(); void testSimpleAccess(); void testComplexType(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testBool(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateBoolsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorsTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static Poco::Data::ODBC::Utility::DSNMap _dataSources; static std::string _dsn; static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // ODBCDB2Test_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCMySQLTest.cpp0000644000076500001200000006064711313735447023434 0ustar guenteradmin00000000000000// // ODBCMySQLTest.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCMySQLTest.cpp#8 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCMySQLTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include #define MYSQL_DRIVER_VERSION "5.1" #ifdef POCO_OS_FAMILY_WINDOWS #define MYSQL_ODBC_DRIVER "MySQL ODBC "##MYSQL_DRIVER_VERSION##" Driver" #else #define MYSQL_ODBC_DRIVER "MySQL" #endif #define MYSQL_DSN "PocoDataMySQLTest" #define MYSQL_SERVER "localhost" #define MYSQL_DB "test" #define MYSQL_UID "root" #define MYSQL_PWD "" using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; const bool ODBCMySQLTest::bindValues[8] = {true, true, true, false, false, true, false, false}; Poco::SharedPtr ODBCMySQLTest::_pSession = 0; Poco::SharedPtr ODBCMySQLTest::_pExecutor = 0; std::string ODBCMySQLTest::_dsn = "PocoDataMySQLTest"; std::string ODBCMySQLTest::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCMySQLTest::_drivers; Poco::Data::ODBC::Utility::DSNMap ODBCMySQLTest::_dataSources; ODBCMySQLTest::ODBCMySQLTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty() || _dataSources.empty()) { Utility::drivers(_drivers); Utility::dataSources(_dataSources); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << _dbConnString << std::endl; }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. MySQL tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } if (!_pExecutor) _pExecutor = new SQLExecutor("MySQL SQL Executor", _pSession); } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. MySQL tests will fail !!!" << std::endl; beenHere = true; } ODBCMySQLTest::~ODBCMySQLTest() { ODBC::Connector::unregisterConnector(); } void ODBCMySQLTest::testBareboneODBC() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third VARBINARY(30)," "Fourth INTEGER," "Fifth FLOAT," "Sixth DATETIME)"; _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_BOUND); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_BOUND); } void ODBCMySQLTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccess(); i += 2; } } void ODBCMySQLTest::testComplexType() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexType(); i += 2; } } void ODBCMySQLTest::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccessVector(); i += 2; } } void ODBCMySQLTest::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeVector(); i += 2; } } void ODBCMySQLTest::testInsertVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertVector(); i += 2; } } void ODBCMySQLTest::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertEmptyVector(); i += 2; } } void ODBCMySQLTest::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulk(); i += 2; } } void ODBCMySQLTest::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulkVec(); i += 2; } } void ODBCMySQLTest::testLimit() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limits(); i += 2; } } void ODBCMySQLTest::testLimitZero() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitZero(); i += 2; } } void ODBCMySQLTest::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void ODBCMySQLTest::testLimitPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitPrepare(); i += 2; } } void ODBCMySQLTest::testPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->prepare(); i += 2; } } void ODBCMySQLTest::testSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setSimple(); i += 2; } } void ODBCMySQLTest::testSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplex(); i += 2; } } void ODBCMySQLTest::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplexUnique(); i += 2; } } void ODBCMySQLTest::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetSimple(); i += 2; } } void ODBCMySQLTest::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetComplex(); i += 2; } } void ODBCMySQLTest::testMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplex(); i += 2; } } void ODBCMySQLTest::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplexUnique(); i += 2; } } void ODBCMySQLTest::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiMapComplex(); i += 2; } } void ODBCMySQLTest::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingle(); i += 2; } } void ODBCMySQLTest::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleStep(); i += 2; } } void ODBCMySQLTest::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleFail(); i += 2; } } void ODBCMySQLTest::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitOk(); i += 2; } } void ODBCMySQLTest::testSingleSelect() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->singleSelect(); i += 2; } } void ODBCMySQLTest::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitFail(); i += 2; } } void ODBCMySQLTest::testCombinedLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedLimits(); i += 2; } } void ODBCMySQLTest::testRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->ranges(); i += 2; } } void ODBCMySQLTest::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedIllegalLimits(); i += 2; } } void ODBCMySQLTest::testIllegalRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->illegalRange(); i += 2; } } void ODBCMySQLTest::testEmptyDB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->emptyDB(); i += 2; } } void ODBCMySQLTest::testBLOB() { if (!_pSession) fail ("Test not available."); const std::size_t maxFldSize = 65534; _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize-1)); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize); fail ("must fail"); } catch (DataException&) { _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize)); } for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blob(maxFldSize); i += 2; } recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize+1); fail ("must fail"); } catch (DataException&) { } } void ODBCMySQLTest::testBLOBStmt() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blobStmt(); i += 2; } } void ODBCMySQLTest::testBool() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateBoolsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->bools(); i += 2; } } void ODBCMySQLTest::testFloat() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->floats(); i += 2; } } void ODBCMySQLTest::testDouble() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->doubles(); i += 2; } } void ODBCMySQLTest::testTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tuples(); i += 2; } } void ODBCMySQLTest::testTupleVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tupleVector(); i += 2; } } void ODBCMySQLTest::testInternalExtraction() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateVectorsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->internalExtraction(); i += 2; } } void ODBCMySQLTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (1051 == it->_nativeError)//(table does not exist) { ignoreError = true; break; } } if (!ignoreError) throw; } } void ODBCMySQLTest::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTable()"); } } void ODBCMySQLTest::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image BLOB)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } } void ODBCMySQLTest::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateIntsTable()"); } } void ODBCMySQLTest::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateStringsTable()"); } } void ODBCMySQLTest::recreateBoolsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateBoolsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateBoolsTable()"); } } void ODBCMySQLTest::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str FLOAT)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateFloatsTable()"); } } void ODBCMySQLTest::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(i0 INTEGER, i1 INTEGER, i2 INTEGER, i3 INTEGER, i4 INTEGER, i5 INTEGER, i6 INTEGER, " "i7 INTEGER, i8 INTEGER, i9 INTEGER, i10 INTEGER, i11 INTEGER, i12 INTEGER, i13 INTEGER," "i14 INTEGER, i15 INTEGER, i16 INTEGER, i17 INTEGER, i18 INTEGER, i19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateTuplesTable()"); } } void ODBCMySQLTest::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (i0 INTEGER, flt0 FLOAT, str0 VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorsTable()"); } } void ODBCMySQLTest::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; bool dsnFound = false; Utility::DriverMap::iterator itDrv = _drivers.begin(); for (; itDrv != _drivers.end(); ++itDrv) { if (((itDrv->first).find("MySQL") != std::string::npos)) { std::cout << "Driver found: " << itDrv->first << " (" << itDrv->second << ')' << std::endl; driverFound = true; break; } } if (!driverFound) { std::cout << "MySQL driver NOT found, tests will fail." << std::endl; return; } Utility::DSNMap::iterator itDSN = _dataSources.begin(); for (; itDSN != _dataSources.end(); ++itDSN) { if (((itDSN->first).find(_dsn) != std::string::npos) && ((itDSN->second).find("MySQL") != std::string::npos)) { std::cout << "DSN found: " << itDSN->first << " (" << itDSN->second << ')' << std::endl; dsnFound = true; break; } } if (!dsnFound) { if (!_pSession && _dbConnString.empty()) { std::cout << "MySQL DSN NOT found, will attempt to connect without it." << std::endl; _dbConnString = "DRIVER=" MYSQL_ODBC_DRIVER ";" "DATABASE=" MYSQL_DB ";" "SERVER=" MYSQL_SERVER ";" "UID=" MYSQL_UID ";" "PWD=" MYSQL_PWD ";"; } else if (!_dbConnString.empty()) { std::cout << "MySQL tests not available." << std::endl; return; } } } if (!_pSession) format(_dbConnString, "DSN=%s;", _dsn); } void ODBCMySQLTest::setUp() { } void ODBCMySQLTest::tearDown() { dropTable("Person"); dropTable("Strings"); } CppUnit::Test* ODBCMySQLTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCMySQLTest"); CppUnit_addTest(pSuite, ODBCMySQLTest, testBareboneODBC); CppUnit_addTest(pSuite, ODBCMySQLTest, testSimpleAccess); CppUnit_addTest(pSuite, ODBCMySQLTest, testComplexType); CppUnit_addTest(pSuite, ODBCMySQLTest, testSimpleAccessVector); CppUnit_addTest(pSuite, ODBCMySQLTest, testComplexTypeVector); CppUnit_addTest(pSuite, ODBCMySQLTest, testInsertVector); CppUnit_addTest(pSuite, ODBCMySQLTest, testInsertEmptyVector); CppUnit_addTest(pSuite, ODBCMySQLTest, testInsertSingleBulk); CppUnit_addTest(pSuite, ODBCMySQLTest, testInsertSingleBulkVec); CppUnit_addTest(pSuite, ODBCMySQLTest, testLimit); CppUnit_addTest(pSuite, ODBCMySQLTest, testLimitOnce); CppUnit_addTest(pSuite, ODBCMySQLTest, testLimitPrepare); CppUnit_addTest(pSuite, ODBCMySQLTest, testLimitZero); CppUnit_addTest(pSuite, ODBCMySQLTest, testPrepare); CppUnit_addTest(pSuite, ODBCMySQLTest, testSetSimple); CppUnit_addTest(pSuite, ODBCMySQLTest, testSetComplex); CppUnit_addTest(pSuite, ODBCMySQLTest, testSetComplexUnique); CppUnit_addTest(pSuite, ODBCMySQLTest, testMultiSetSimple); CppUnit_addTest(pSuite, ODBCMySQLTest, testMultiSetComplex); CppUnit_addTest(pSuite, ODBCMySQLTest, testMapComplex); CppUnit_addTest(pSuite, ODBCMySQLTest, testMapComplexUnique); CppUnit_addTest(pSuite, ODBCMySQLTest, testMultiMapComplex); CppUnit_addTest(pSuite, ODBCMySQLTest, testSelectIntoSingle); CppUnit_addTest(pSuite, ODBCMySQLTest, testSelectIntoSingleStep); CppUnit_addTest(pSuite, ODBCMySQLTest, testSelectIntoSingleFail); CppUnit_addTest(pSuite, ODBCMySQLTest, testLowerLimitOk); CppUnit_addTest(pSuite, ODBCMySQLTest, testLowerLimitFail); CppUnit_addTest(pSuite, ODBCMySQLTest, testCombinedLimits); CppUnit_addTest(pSuite, ODBCMySQLTest, testCombinedIllegalLimits); CppUnit_addTest(pSuite, ODBCMySQLTest, testRange); CppUnit_addTest(pSuite, ODBCMySQLTest, testIllegalRange); CppUnit_addTest(pSuite, ODBCMySQLTest, testSingleSelect); CppUnit_addTest(pSuite, ODBCMySQLTest, testEmptyDB); CppUnit_addTest(pSuite, ODBCMySQLTest, testBLOB); CppUnit_addTest(pSuite, ODBCMySQLTest, testBLOBStmt); CppUnit_addTest(pSuite, ODBCMySQLTest, testBool); CppUnit_addTest(pSuite, ODBCMySQLTest, testFloat); CppUnit_addTest(pSuite, ODBCMySQLTest, testDouble); CppUnit_addTest(pSuite, ODBCMySQLTest, testTuple); CppUnit_addTest(pSuite, ODBCMySQLTest, testTupleVector); CppUnit_addTest(pSuite, ODBCMySQLTest, testInternalExtraction); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCMySQLTest.h0000644000076500001200000001037111313735447023066 0ustar guenteradmin00000000000000// // ODBCMySQLTest.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCMySQLTest.h#5 $ // // Definition of the ODBCMySQLTest class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCMySQLTest_INCLUDED #define ODBCMySQLTest_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCMySQLTest: public CppUnit::TestCase /// MySQL ODBC test class /// Tested: /// /// Driver | Manager | DB | OS /// ----------------+--------------------------+---------------------------+------------------------------------------ /// 03.51.12.00 | | MySQL 5.0.27-community-nt | MS Windows XP Professional x64 v.2003/SP1 /// 05.01.05.00 | | MySQL 5.0.67-community-nt | MS Windows XP Professional /// 03.51.15r409-2 | unixODBC 2.2.11-16build1 | MySQL 5.0.51a-3ubuntu5.1 | Ubuntu 2.6.24-19-generic #1 SMP (hardy) { public: ODBCMySQLTest(const std::string& name); ~ODBCMySQLTest(); void testBareboneODBC(); void testSimpleAccess(); void testComplexType(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testBool(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateBoolsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorsTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static Poco::Data::ODBC::Utility::DSNMap _dataSources; static std::string _dsn; static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // ODBCMySQLTest_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCOracleTest.cpp0000644000076500001200000006543411313735447023673 0ustar guenteradmin00000000000000// // ODBCOracleTest.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCOracleTest.cpp#9 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCOracleTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include #define ORACLE_ODBC_DRIVER "Oracle in XE" #define ORACLE_DSN "PocoDataOracleTest" #define ORACLE_SERVER "localhost" #define ORACLE_PORT "1521" #define ORACLE_SID "XE" #define ORACLE_UID "scott" #define ORACLE_PWD "tiger" using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; const bool ODBCOracleTest::bindValues[8] = {true, true, true, false, false, true, false, false}; Poco::SharedPtr ODBCOracleTest::_pSession = 0; Poco::SharedPtr ODBCOracleTest::_pExecutor = 0; std::string ODBCOracleTest::_dsn = ORACLE_DSN; std::string ODBCOracleTest::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCOracleTest::_drivers; Poco::Data::ODBC::Utility::DSNMap ODBCOracleTest::_dataSources; ODBCOracleTest::ODBCOracleTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty() || _dataSources.empty()) { Utility::drivers(_drivers); Utility::dataSources(_dataSources); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << _dbConnString << std::endl; }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. Oracle tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } if (!_pExecutor) _pExecutor = new SQLExecutor("Oracle SQL Executor", _pSession); } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. Oracle tests will fail !!!" << std::endl; beenHere = true; } ODBCOracleTest::~ODBCOracleTest() { ODBC::Connector::unregisterConnector(); } void ODBCOracleTest::testBareboneODBC() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third BLOB," "Fourth INTEGER," "Fifth NUMBER," "Sixth TIMESTAMP)"; _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_BOUND); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_BOUND); } void ODBCOracleTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); std::string tableName("Person"); int count = 0; recreatePersonTable(); *_pSession << "SELECT count(*) FROM sys.all_all_tables WHERE table_name = upper(?)", into(count), use(tableName), now; assert (1 == count); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccess(); i += 2; } } void ODBCOracleTest::testComplexType() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexType(); i += 2; } } void ODBCOracleTest::testComplexTypeTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTupleTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeTuple(); i += 2; } } void ODBCOracleTest::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccessVector(); i += 2; } } void ODBCOracleTest::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeVector(); i += 2; } } void ODBCOracleTest::testInsertVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertVector(); i += 2; } } void ODBCOracleTest::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertEmptyVector(); i += 2; } } void ODBCOracleTest::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulk(); i += 2; } } void ODBCOracleTest::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulkVec(); i += 2; } } void ODBCOracleTest::testLimit() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limits(); i += 2; } } void ODBCOracleTest::testLimitZero() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitZero(); i += 2; } } void ODBCOracleTest::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void ODBCOracleTest::testLimitPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitPrepare(); i += 2; } } void ODBCOracleTest::testPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->prepare(); i += 2; } } void ODBCOracleTest::testSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setSimple(); i += 2; } } void ODBCOracleTest::testSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplex(); i += 2; } } void ODBCOracleTest::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplexUnique(); i += 2; } } void ODBCOracleTest::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetSimple(); i += 2; } } void ODBCOracleTest::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetComplex(); i += 2; } } void ODBCOracleTest::testMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplex(); i += 2; } } void ODBCOracleTest::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplexUnique(); i += 2; } } void ODBCOracleTest::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiMapComplex(); i += 2; } } void ODBCOracleTest::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingle(); i += 2; } } void ODBCOracleTest::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleStep(); i += 2; } } void ODBCOracleTest::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleFail(); i += 2; } } void ODBCOracleTest::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitOk(); i += 2; } } void ODBCOracleTest::testSingleSelect() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->singleSelect(); i += 2; } } void ODBCOracleTest::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitFail(); i += 2; } } void ODBCOracleTest::testCombinedLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedLimits(); i += 2; } } void ODBCOracleTest::testRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->ranges(); i += 2; } } void ODBCOracleTest::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedIllegalLimits(); i += 2; } } void ODBCOracleTest::testIllegalRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->illegalRange(); i += 2; } } void ODBCOracleTest::testEmptyDB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->emptyDB(); i += 2; } } void ODBCOracleTest::testBLOB() { if (!_pSession) fail ("Test not available."); const std::size_t maxFldSize = 1000000; _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize-1)); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize); fail ("must fail"); } catch (DataException&) { _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize)); } for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blob(maxFldSize); i += 2; } recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize+1); fail ("must fail"); } catch (DataException&) { } } void ODBCOracleTest::testBLOBStmt() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blobStmt(); i += 2; } } void ODBCOracleTest::testBool() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateBoolsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->bools(); i += 2; } } void ODBCOracleTest::testFloat() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->floats(); i += 2; } } void ODBCOracleTest::testDouble() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->doubles(); i += 2; } } void ODBCOracleTest::testTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tuples(); i += 2; } } void ODBCOracleTest::testTupleVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tupleVector(); i += 2; } } void ODBCOracleTest::testInternalExtraction() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateVectorsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->internalExtraction(); i += 2; } } void ODBCOracleTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (942 == it->_nativeError)//ORA-00942 (table does not exist) { ignoreError = true; break; } } if (!ignoreError) { std::cout << ex.displayText() << std::endl; throw; } } } void ODBCOracleTest::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR2(30), FirstName VARCHAR2(30), Address VARCHAR2(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTable()"); } } void ODBCOracleTest::recreatePersonTupleTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName1 VARCHAR2(30), FirstName1 VARCHAR2(30), Address1 VARCHAR2(30), Age1 INTEGER," "LastName2 VARCHAR2(30), FirstName2 VARCHAR2(30), Address2 VARCHAR2(30), Age2 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTupleTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTupleTable()"); } } void ODBCOracleTest::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image BLOB)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } } void ODBCOracleTest::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateIntsTable()"); } } void ODBCOracleTest::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateStringsTable()"); } } void ODBCOracleTest::recreateBoolsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateBoolsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateBoolsTable()"); } } void ODBCOracleTest::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str NUMBER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateFloatsTable()"); } } void ODBCOracleTest::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(int0 INTEGER, int1 INTEGER, int2 INTEGER, int3 INTEGER, int4 INTEGER, int5 INTEGER, int6 INTEGER, " "int7 INTEGER, int8 INTEGER, int9 INTEGER, int10 INTEGER, int11 INTEGER, int12 INTEGER, int13 INTEGER," "int14 INTEGER, int15 INTEGER, int16 INTEGER, int17 INTEGER, int18 INTEGER, int19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateTuplesTable()"); } } void ODBCOracleTest::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (int0 INTEGER, flt0 NUMBER, str0 VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorsTable()"); } } void ODBCOracleTest::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; bool dsnFound = false; Utility::DriverMap::iterator itDrv = _drivers.begin(); for (; itDrv != _drivers.end(); ++itDrv) { if (((itDrv->first).find("Oracle") != std::string::npos) && ((itDrv->first).find("Microsoft") == std::string::npos)) { std::cout << "Driver found: " << itDrv->first << " (" << itDrv->second << ')' << std::endl; driverFound = true; break; } } if (!driverFound) { std::cout << "Oracle driver NOT found, tests will fail." << std::endl; return; } Utility::DSNMap::iterator itDSN = _dataSources.begin(); for (; itDSN != _dataSources.end(); ++itDSN) { if (((itDSN->first).find(_dsn) != std::string::npos) && ((itDSN->second).find("Oracle") != std::string::npos)) { std::cout << "DSN found: " << itDSN->first << " (" << itDSN->second << ')' << std::endl; dsnFound = true; break; } } if (!dsnFound) { if (!_pSession && _dbConnString.empty()) { std::cout << "Oracle DSN NOT found, will attempt to connect without it." << std::endl; _dbConnString = "DRIVER={" ORACLE_ODBC_DRIVER "};" "DBQ=" ORACLE_SERVER ":" ORACLE_PORT "/" ORACLE_SID ";" "UID=" ORACLE_UID ";" "PWD=" ORACLE_PWD ";" "TLO=O;" //? "FBS=60000;" // fetch buffer size (bytes), default 60000 "FWC=F;" // force SQL_WCHAR support (T/F), default F "CSR=F;" // close cursor (T/F), default F "MDI=Me;" // metadata (SQL_ATTR_METADATA_ID) ID default (T/F), default T "MTS=T;" //? "DPM=F;" // disable SQLDescribeParam (T/F), default F "NUM=NLS;" // numeric settings (NLS implies Globalization Support) "BAM=IfAllSuccessful;" // batch autocommit, (IfAllSuccessful/UpToFirstFailure/AllSuccessful), default IfAllSuccessful "BTD=F;" // bind timestamp as date (T/F), default F "RST=T;" // resultsets (T/F), default T "LOB=T;" // LOB writes (T/F), default T "FDL=0;" // failover delay (default 10) "FRC=0;" // failover retry count (default 10) "QTO=T;" // query timout option (T/F), default T "FEN=F;" // failover (T/F), default T "XSM=Default;" // schema field (Default/Database/Owner), default Default "EXC=F;" // EXEC syntax (T/F), default F "APA=T;" // thread safety (T/F), default T "DBA=W;"; // write access return; } else if (!_dbConnString.empty()) { std::cout << "Oracle tests not available." << std::endl; return; } } } if (!_pSession) format(_dbConnString, "DSN=%s;Uid=%s;Pwd=%s;", _dsn, std::string(ORACLE_UID), std::string(ORACLE_PWD)); } void ODBCOracleTest::setUp() { } void ODBCOracleTest::tearDown() { } CppUnit::Test* ODBCOracleTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCOracleTest"); CppUnit_addTest(pSuite, ODBCOracleTest, testBareboneODBC); CppUnit_addTest(pSuite, ODBCOracleTest, testSimpleAccess); CppUnit_addTest(pSuite, ODBCOracleTest, testComplexType); CppUnit_addTest(pSuite, ODBCOracleTest, testComplexTypeTuple); CppUnit_addTest(pSuite, ODBCOracleTest, testSimpleAccessVector); CppUnit_addTest(pSuite, ODBCOracleTest, testComplexTypeVector); CppUnit_addTest(pSuite, ODBCOracleTest, testInsertVector); CppUnit_addTest(pSuite, ODBCOracleTest, testInsertEmptyVector); CppUnit_addTest(pSuite, ODBCOracleTest, testInsertSingleBulk); CppUnit_addTest(pSuite, ODBCOracleTest, testInsertSingleBulkVec); CppUnit_addTest(pSuite, ODBCOracleTest, testLimit); CppUnit_addTest(pSuite, ODBCOracleTest, testLimitOnce); CppUnit_addTest(pSuite, ODBCOracleTest, testLimitPrepare); CppUnit_addTest(pSuite, ODBCOracleTest, testLimitZero); CppUnit_addTest(pSuite, ODBCOracleTest, testPrepare); CppUnit_addTest(pSuite, ODBCOracleTest, testSetSimple); CppUnit_addTest(pSuite, ODBCOracleTest, testSetComplex); CppUnit_addTest(pSuite, ODBCOracleTest, testSetComplexUnique); CppUnit_addTest(pSuite, ODBCOracleTest, testMultiSetSimple); CppUnit_addTest(pSuite, ODBCOracleTest, testMultiSetComplex); CppUnit_addTest(pSuite, ODBCOracleTest, testMapComplex); CppUnit_addTest(pSuite, ODBCOracleTest, testMapComplexUnique); CppUnit_addTest(pSuite, ODBCOracleTest, testMultiMapComplex); CppUnit_addTest(pSuite, ODBCOracleTest, testSelectIntoSingle); CppUnit_addTest(pSuite, ODBCOracleTest, testSelectIntoSingleStep); CppUnit_addTest(pSuite, ODBCOracleTest, testSelectIntoSingleFail); CppUnit_addTest(pSuite, ODBCOracleTest, testLowerLimitOk); CppUnit_addTest(pSuite, ODBCOracleTest, testLowerLimitFail); CppUnit_addTest(pSuite, ODBCOracleTest, testCombinedLimits); CppUnit_addTest(pSuite, ODBCOracleTest, testCombinedIllegalLimits); CppUnit_addTest(pSuite, ODBCOracleTest, testRange); CppUnit_addTest(pSuite, ODBCOracleTest, testIllegalRange); CppUnit_addTest(pSuite, ODBCOracleTest, testSingleSelect); CppUnit_addTest(pSuite, ODBCOracleTest, testEmptyDB); CppUnit_addTest(pSuite, ODBCOracleTest, testBLOB); CppUnit_addTest(pSuite, ODBCOracleTest, testBLOBStmt); CppUnit_addTest(pSuite, ODBCOracleTest, testBool); CppUnit_addTest(pSuite, ODBCOracleTest, testFloat); CppUnit_addTest(pSuite, ODBCOracleTest, testDouble); CppUnit_addTest(pSuite, ODBCOracleTest, testTuple); CppUnit_addTest(pSuite, ODBCOracleTest, testTupleVector); CppUnit_addTest(pSuite, ODBCOracleTest, testInternalExtraction); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCOracleTest.h0000644000076500001200000001061011313735447023322 0ustar guenteradmin00000000000000// // ODBCOracleTest.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCOracleTest.h#5 $ // // Definition of the ODBCOracleTest class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCOracleTest_INCLUDED #define ODBCOracleTest_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCOracleTest: public CppUnit::TestCase /// Oracle ODBC test class /// Tested: /// /// Driver | Manager | DB | OS /// ------------+--------------------------+------------------------------------------+------------------------------------------ /// 10.02.00.01 | | Oracle9i Release 9.2.0.4.0 | MS Windows XP Professional x64 v.2003/SP1 /// 10.02.00.01 | | Oracle XE Release 10.2.0.1.0 | MS Windows XP Professional x64 v.2003/SP1 /// 10.02.00.01 | unixODBC 2.2.11-16build1 | Oracle XE Release 10.2.0.1-1.1(unstable) | Ubuntu 2.6.24-19-generic #1 SMP (hardy) { public: ODBCOracleTest(const std::string& name); ~ODBCOracleTest(); void testBareboneODBC(); void testSimpleAccess(); void testComplexType(); void testComplexTypeTuple(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testBool(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonTupleTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateBoolsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorsTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static Poco::Data::ODBC::Utility::DSNMap _dataSources; static std::string _dsn; static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // ODBCOracleTest_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCPostgreSQLTest.cpp0000644000076500001200000006355411313735447024472 0ustar guenteradmin00000000000000// // ODBCPostgreSQLTest.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCPostgreSQLTest.cpp#7 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCPostgreSQLTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include #ifdef POCO_ODBC_USE_MAMMOTH_NG #define POSTGRESQL_ODBC_DRIVER "Mammoth ODBCng Beta" #elif defined (POCO_ODBC_UNICODE) #define POSTGRESQL_ODBC_DRIVER "PostgreSQL Unicode" #else #define POSTGRESQL_ODBC_DRIVER "PostgreSQL ANSI" #endif #define POSTGRESQL_DSN "PocoDataPgSQLTest" #define POSTGRESQL_SERVER "localhost" #define POSTGRESQL_PORT "5432" #define POSTGRESQL_DB "template1" #define POSTGRESQL_UID "postgres" #define POSTGRESQL_PWD "postgres" using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; const bool ODBCPostgreSQLTest::bindValues[8] = {true, true, true, false, false, true, false, false}; Poco::SharedPtr ODBCPostgreSQLTest::_pSession = 0; Poco::SharedPtr ODBCPostgreSQLTest::_pExecutor = 0; std::string ODBCPostgreSQLTest::_dsn = "PocoDataPgSQLTest"; std::string ODBCPostgreSQLTest::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCPostgreSQLTest::_drivers; Poco::Data::ODBC::Utility::DSNMap ODBCPostgreSQLTest::_dataSources; ODBCPostgreSQLTest::ODBCPostgreSQLTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty() || _dataSources.empty()) { Utility::drivers(_drivers); Utility::dataSources(_dataSources); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. PostgreSQL tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << _dsn << '(' << _dbConnString << ')' << std::endl; if (!_pExecutor) _pExecutor = new SQLExecutor("PostgreSQL SQL Executor", _pSession); } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. PostgreSQL tests will fail !!!" << std::endl; beenHere = true; } ODBCPostgreSQLTest::~ODBCPostgreSQLTest() { ODBC::Connector::unregisterConnector(); } void ODBCPostgreSQLTest::testBareboneODBC() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third BYTEA," "Fourth INTEGER," "Fifth FLOAT," "Sixth TIMESTAMP)"; _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_BOUND); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_BOUND); } void ODBCPostgreSQLTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); std::string tableName("Person"); recreatePersonTable(); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccess(); i += 2; } } void ODBCPostgreSQLTest::testComplexType() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexType(); i += 2; } } void ODBCPostgreSQLTest::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccessVector(); i += 2; } } void ODBCPostgreSQLTest::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeVector(); i += 2; } } void ODBCPostgreSQLTest::testInsertVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertVector(); i += 2; } } void ODBCPostgreSQLTest::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertEmptyVector(); i += 2; } } void ODBCPostgreSQLTest::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulk(); i += 2; } } void ODBCPostgreSQLTest::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulkVec(); i += 2; } } void ODBCPostgreSQLTest::testLimit() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limits(); i += 2; } } void ODBCPostgreSQLTest::testLimitZero() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitZero(); i += 2; } } void ODBCPostgreSQLTest::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void ODBCPostgreSQLTest::testLimitPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitPrepare(); i += 2; } } void ODBCPostgreSQLTest::testPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->prepare(); i += 2; } } void ODBCPostgreSQLTest::testSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setSimple(); i += 2; } } void ODBCPostgreSQLTest::testSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplex(); i += 2; } } void ODBCPostgreSQLTest::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplexUnique(); i += 2; } } void ODBCPostgreSQLTest::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetSimple(); i += 2; } } void ODBCPostgreSQLTest::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetComplex(); i += 2; } } void ODBCPostgreSQLTest::testMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplex(); i += 2; } } void ODBCPostgreSQLTest::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplexUnique(); i += 2; } } void ODBCPostgreSQLTest::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiMapComplex(); i += 2; } } void ODBCPostgreSQLTest::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingle(); i += 2; } } void ODBCPostgreSQLTest::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleStep(); i += 2; } } void ODBCPostgreSQLTest::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleFail(); i += 2; } } void ODBCPostgreSQLTest::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitOk(); i += 2; } } void ODBCPostgreSQLTest::testSingleSelect() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->singleSelect(); i += 2; } } void ODBCPostgreSQLTest::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitFail(); i += 2; } } void ODBCPostgreSQLTest::testCombinedLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedLimits(); i += 2; } } void ODBCPostgreSQLTest::testRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->ranges(); i += 2; } } void ODBCPostgreSQLTest::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedIllegalLimits(); i += 2; } } void ODBCPostgreSQLTest::testIllegalRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->illegalRange(); i += 2; } } void ODBCPostgreSQLTest::testEmptyDB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->emptyDB(); i += 2; } } void ODBCPostgreSQLTest::testBLOB() { if (!_pSession) fail ("Test not available."); const std::size_t maxFldSize = 1000000; _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize-1)); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize); fail ("must fail"); } catch (DataException&) { _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize)); } for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blob(1000000); i += 2; } } void ODBCPostgreSQLTest::testBLOBStmt() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blobStmt(); i += 2; } } void ODBCPostgreSQLTest::testBool() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateBoolsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->bools(); i += 2; } } void ODBCPostgreSQLTest::testFloat() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->floats(); i += 2; } } void ODBCPostgreSQLTest::testDouble() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->doubles(); i += 2; } } void ODBCPostgreSQLTest::testTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tuples(); i += 2; } } void ODBCPostgreSQLTest::testTupleVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tupleVector(); i += 2; } } void ODBCPostgreSQLTest::testInternalExtraction() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateVectorsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->internalExtraction(); i += 2; } } void ODBCPostgreSQLTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (7 == it->_nativeError)//(table does not exist) { ignoreError = true; break; } } if (!ignoreError) throw; } } void ODBCPostgreSQLTest::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTable()"); } } void ODBCPostgreSQLTest::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image BYTEA)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } } void ODBCPostgreSQLTest::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateIntsTable()"); } } void ODBCPostgreSQLTest::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateStringsTable()"); } } void ODBCPostgreSQLTest::recreateBoolsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateBoolsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateBoolsTable()"); } } void ODBCPostgreSQLTest::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str FLOAT)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateFloatsTable()"); } } void ODBCPostgreSQLTest::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(int0 INTEGER, int1 INTEGER, int2 INTEGER, int3 INTEGER, int4 INTEGER, int5 INTEGER, int6 INTEGER, " "int7 INTEGER, int8 INTEGER, int9 INTEGER, int10 INTEGER, int11 INTEGER, int12 INTEGER, int13 INTEGER," "int14 INTEGER, int15 INTEGER, int16 INTEGER, int17 INTEGER, int18 INTEGER, int19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateTuplesTable()"); } } void ODBCPostgreSQLTest::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (int0 INTEGER, flt0 FLOAT, str0 VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorsTable()"); } } void ODBCPostgreSQLTest::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; bool dsnFound = false; Utility::DriverMap::iterator itDrv = _drivers.begin(); for (; itDrv != _drivers.end(); ++itDrv) { if (((itDrv->first).find("PostgreSQL") != std::string::npos)) { std::cout << "Driver found: " << itDrv->first << " (" << itDrv->second << ')' << std::endl; driverFound = true; break; } } if (!driverFound) { std::cout << "PostgreSQL driver NOT found, tests will fail." << std::endl; return; } Utility::DSNMap::iterator itDSN = _dataSources.begin(); for (; itDSN != _dataSources.end(); ++itDSN) { if (((itDSN->first).find(_dsn) != std::string::npos) && ((itDSN->second).find("PostgreSQL") != std::string::npos)) { std::cout << "DSN found: " << itDSN->first << " (" << itDSN->second << ')' << std::endl; dsnFound = true; break; } } if (!dsnFound) { if (!_pSession && _dbConnString.empty()) { std::cout << "PostgreSQL DSN NOT found, will attempt to connect without it." << std::endl; _dbConnString = "DRIVER=" POSTGRESQL_ODBC_DRIVER ";" "DATABASE=" POSTGRESQL_DB ";" "SERVER=" POSTGRESQL_SERVER ";" "PORT=" POSTGRESQL_PORT ";" "UID=" POSTGRESQL_UID ";" "PWD=" POSTGRESQL_PWD ";" "SSLMODE=prefer;" "LowerCaseIdentifier=0;" "UseServerSidePrepare=0;" "ByteaAsLongVarBinary=1;" "BI=0;" "TrueIsMinus1=0;" "DisallowPremature=0;" "UpdatableCursors=0;" "LFConversion=1;" "CancelAsFreeStmt=0;" "Parse=0;" "BoolsAsChar=1;" "UnknownsAsLongVarchar=0;" "TextAsLongVarchar=1;" "UseDeclareFetch=0;" "Ksqo=1;" "Optimizer=1;" "CommLog=0;" "Debug=0;" "MaxLongVarcharSize=8190;" "MaxVarcharSize=254;" "UnknownSizes=0;" "Socket=8192;" "Fetch=100;" "ConnSettings=;" "ShowSystemTables=0;" "RowVersioning=0;" "ShowOidColumn=0;" "FakeOidIndex=0;" "ReadOnly=0;"; return; } else if (!_dbConnString.empty()) { std::cout << "PostgreSQL tests not available." << std::endl; return; } } } if (!_pSession) format(_dbConnString, "DSN=%s;", _dsn); } void ODBCPostgreSQLTest::setUp() { } void ODBCPostgreSQLTest::tearDown() { dropTable("Person"); dropTable("Strings"); } CppUnit::Test* ODBCPostgreSQLTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCPostgreSQLTest"); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testBareboneODBC); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSimpleAccess); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testComplexType); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSimpleAccessVector); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testComplexTypeVector); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testInsertVector); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testInsertEmptyVector); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testInsertSingleBulk); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testInsertSingleBulkVec); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testLimit); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testLimitOnce); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testLimitPrepare); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testLimitZero); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testPrepare); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSetSimple); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSetComplex); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSetComplexUnique); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testMultiSetSimple); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testMultiSetComplex); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testMapComplex); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testMapComplexUnique); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testMultiMapComplex); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSelectIntoSingle); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSelectIntoSingleStep); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSelectIntoSingleFail); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testLowerLimitOk); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testLowerLimitFail); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testCombinedLimits); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testCombinedIllegalLimits); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testRange); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testIllegalRange); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testSingleSelect); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testEmptyDB); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testBLOB); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testBLOBStmt); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testBool); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testFloat); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testDouble); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testTuple); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testTupleVector); CppUnit_addTest(pSuite, ODBCPostgreSQLTest, testInternalExtraction); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCPostgreSQLTest.h0000644000076500001200000001057411313735447024131 0ustar guenteradmin00000000000000// // ODBCPostgreSQLTest.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCPostgreSQLTest.h#4 $ // // Definition of the ODBCPostgreSQLTest class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCPostgreSQLTest_INCLUDED #define ODBCPostgreSQLTest_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCPostgreSQLTest: public CppUnit::TestCase /// PostgreSQL ODBC test class /// Tested: /// /// Driver | Manager | DB | OS | Notes /// ------------+--------------------------+--------------------+-------------------------------------------+-------------------------------- /// 07.03.02.60 | | PostgreSQL 7.4.6 | MS Windows XP Professional x64 v.2003/SP1 | BLOB fails (missing 'lo' module) /// 08.01.02.00 | | PostgreSQL 8.1.5-1 | MS Windows XP Professional x64 v.2003/SP1 | /// 08.01.02.00 | unixODBC 2.2.11-16build1 | PostgreSQL 8.1.5-1 | Ubuntu 2.6.24-19-generic #1 SMP (hardy) | { public: ODBCPostgreSQLTest(const std::string& name); ~ODBCPostgreSQLTest(); void testBareboneODBC(); void testSimpleAccess(); void testComplexType(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testBool(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateBoolsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorsTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static Poco::Data::ODBC::Utility::DSNMap _dataSources; static std::string _dsn; static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // ODBCPostgreSQLTest_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCSQLiteTest.cpp0000644000076500001200000005654111313735447023626 0ustar guenteradmin00000000000000// // ODBCSQLiteTest.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCSQLiteTest.cpp#7 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCSQLiteTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; const bool ODBCSQLiteTest::bindValues[8] = {true, true, true, false, false, true, false, false}; Poco::SharedPtr ODBCSQLiteTest::_pSession = 0; Poco::SharedPtr ODBCSQLiteTest::_pExecutor = 0; std::string ODBCSQLiteTest::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCSQLiteTest::_drivers; ODBCSQLiteTest::ODBCSQLiteTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty()) { Utility::drivers(_drivers); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << _dbConnString << std::endl; if (!_pExecutor) _pExecutor = new SQLExecutor("SQLite SQL Executor", _pSession); }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. SQLite tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. SQLite tests will fail !!!" << std::endl; beenHere = true; } ODBCSQLiteTest::~ODBCSQLiteTest() { ODBC::Connector::unregisterConnector(); } void ODBCSQLiteTest::testBareboneODBC() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third BLOB," "Fourth INTEGER," "Fifth REAL," "Sixth TIMESTAMP)"; _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_BOUND); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_MANUAL); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_BOUND); } void ODBCSQLiteTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); std::string tableName("Person"); std::string result; _pSession->setFeature("autoBind", false); recreatePersonTable(); try { *_pSession << "SELECT name FROM sqlite_master WHERE tbl_name=?", into(result), use(tableName), now; } catch(StatementException& ex) { std::cout << ex.toString() << std::endl; } assert (result == tableName); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccess(); i += 2; } } void ODBCSQLiteTest::testComplexType() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexType(); i += 2; } } void ODBCSQLiteTest::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccessVector(); i += 2; } } void ODBCSQLiteTest::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeVector(); i += 2; } } void ODBCSQLiteTest::testInsertVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertVector(); i += 2; } } void ODBCSQLiteTest::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertEmptyVector(); i += 2; } } void ODBCSQLiteTest::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulk(); i += 2; } } void ODBCSQLiteTest::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulkVec(); i += 2; } } void ODBCSQLiteTest::testLimit() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limits(); i += 2; } } void ODBCSQLiteTest::testLimitZero() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitZero(); i += 2; } } void ODBCSQLiteTest::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void ODBCSQLiteTest::testLimitPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitPrepare(); i += 2; } } void ODBCSQLiteTest::testPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->prepare(); i += 2; } } void ODBCSQLiteTest::testSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setSimple(); i += 2; } } void ODBCSQLiteTest::testSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplex(); i += 2; } } void ODBCSQLiteTest::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplexUnique(); i += 2; } } void ODBCSQLiteTest::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetSimple(); i += 2; } } void ODBCSQLiteTest::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetComplex(); i += 2; } } void ODBCSQLiteTest::testMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplex(); i += 2; } } void ODBCSQLiteTest::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplexUnique(); i += 2; } } void ODBCSQLiteTest::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiMapComplex(); i += 2; } } void ODBCSQLiteTest::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingle(); i += 2; } } void ODBCSQLiteTest::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleStep(); i += 2; } } void ODBCSQLiteTest::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleFail(); i += 2; } } void ODBCSQLiteTest::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitOk(); i += 2; } } void ODBCSQLiteTest::testSingleSelect() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->singleSelect(); i += 2; } } void ODBCSQLiteTest::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitFail(); i += 2; } } void ODBCSQLiteTest::testCombinedLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedLimits(); i += 2; } } void ODBCSQLiteTest::testRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->ranges(); i += 2; } } void ODBCSQLiteTest::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedIllegalLimits(); i += 2; } } void ODBCSQLiteTest::testIllegalRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->illegalRange(); i += 2; } } void ODBCSQLiteTest::testEmptyDB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->emptyDB(); i += 2; } } void ODBCSQLiteTest::testBLOB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blob(); i += 2; } } void ODBCSQLiteTest::testBLOBStmt() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blobStmt(); i += 2; } } void ODBCSQLiteTest::testBool() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateBoolsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->bools(); i += 2; } } void ODBCSQLiteTest::testFloat() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->floats(); i += 2; } } void ODBCSQLiteTest::testDouble() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->doubles(); i += 2; } } void ODBCSQLiteTest::testTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tuples(); i += 2; } } void ODBCSQLiteTest::testTupleVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tupleVector(); i += 2; } } void ODBCSQLiteTest::testInternalExtraction() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateVectorsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->internalExtraction(); i += 2; } } void ODBCSQLiteTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (1 == it->_nativeError)//(no such table) { ignoreError = true; break; } } if (!ignoreError) { std::cout << ex.displayText() << std::endl; throw; } } } void ODBCSQLiteTest::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR2(30), FirstName VARCHAR2(30), Address VARCHAR2(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTable()"); } } void ODBCSQLiteTest::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image BLOB)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } } void ODBCSQLiteTest::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateIntsTable()"); } } void ODBCSQLiteTest::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateStringsTable()"); } } void ODBCSQLiteTest::recreateBoolsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateBoolsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateBoolsTable()"); } } void ODBCSQLiteTest::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str REAL)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateFloatsTable()"); } } void ODBCSQLiteTest::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(int0 INTEGER, int1 INTEGER, int2 INTEGER, int3 INTEGER, int4 INTEGER, int5 INTEGER, int6 INTEGER, " "int7 INTEGER, int8 INTEGER, int9 INTEGER, int10 INTEGER, int11 INTEGER, int12 INTEGER, int13 INTEGER," "int14 INTEGER, int15 INTEGER, int16 INTEGER, int17 INTEGER, int18 INTEGER, int19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateTuplesTable()"); } } void ODBCSQLiteTest::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (int0 INTEGER, flt0 REAL, str0 VARCHAR)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorsTable()"); } } void ODBCSQLiteTest::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; std::string driverName; Utility::DriverMap::iterator itDriver = _drivers.begin(); for (; itDriver != _drivers.end(); ++itDriver) { if (((itDriver->first).find("SQLite3") != std::string::npos)) { std::cout << "Driver found: " << itDriver->first << " (" << itDriver->second << ')' << std::endl; driverName = itDriver->first; driverFound = true; break; } } if (driverFound) { if (_dbConnString.empty() && !driverName.empty()) { _dbConnString = format("Driver=%s;Database=dummy.db;", driverName); return; } else if (driverName.empty()) { std::cout << "SQLite3 driver not found. Tests not available." << std::endl; return; } } } } void ODBCSQLiteTest::setUp() { } void ODBCSQLiteTest::tearDown() { } CppUnit::Test* ODBCSQLiteTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCSQLiteTest"); CppUnit_addTest(pSuite, ODBCSQLiteTest, testBareboneODBC); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSimpleAccess); CppUnit_addTest(pSuite, ODBCSQLiteTest, testComplexType); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSimpleAccessVector); CppUnit_addTest(pSuite, ODBCSQLiteTest, testComplexTypeVector); CppUnit_addTest(pSuite, ODBCSQLiteTest, testInsertVector); CppUnit_addTest(pSuite, ODBCSQLiteTest, testInsertEmptyVector); CppUnit_addTest(pSuite, ODBCSQLiteTest, testInsertSingleBulk); CppUnit_addTest(pSuite, ODBCSQLiteTest, testInsertSingleBulkVec); CppUnit_addTest(pSuite, ODBCSQLiteTest, testLimit); CppUnit_addTest(pSuite, ODBCSQLiteTest, testLimitOnce); CppUnit_addTest(pSuite, ODBCSQLiteTest, testLimitPrepare); CppUnit_addTest(pSuite, ODBCSQLiteTest, testLimitZero); CppUnit_addTest(pSuite, ODBCSQLiteTest, testPrepare); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSetSimple); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSetComplex); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSetComplexUnique); CppUnit_addTest(pSuite, ODBCSQLiteTest, testMultiSetSimple); CppUnit_addTest(pSuite, ODBCSQLiteTest, testMultiSetComplex); CppUnit_addTest(pSuite, ODBCSQLiteTest, testMapComplex); CppUnit_addTest(pSuite, ODBCSQLiteTest, testMapComplexUnique); CppUnit_addTest(pSuite, ODBCSQLiteTest, testMultiMapComplex); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSelectIntoSingle); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSelectIntoSingleStep); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSelectIntoSingleFail); CppUnit_addTest(pSuite, ODBCSQLiteTest, testLowerLimitOk); CppUnit_addTest(pSuite, ODBCSQLiteTest, testLowerLimitFail); CppUnit_addTest(pSuite, ODBCSQLiteTest, testCombinedLimits); CppUnit_addTest(pSuite, ODBCSQLiteTest, testCombinedIllegalLimits); CppUnit_addTest(pSuite, ODBCSQLiteTest, testRange); CppUnit_addTest(pSuite, ODBCSQLiteTest, testIllegalRange); CppUnit_addTest(pSuite, ODBCSQLiteTest, testSingleSelect); CppUnit_addTest(pSuite, ODBCSQLiteTest, testEmptyDB); CppUnit_addTest(pSuite, ODBCSQLiteTest, testBLOB); CppUnit_addTest(pSuite, ODBCSQLiteTest, testBLOBStmt); CppUnit_addTest(pSuite, ODBCSQLiteTest, testBool); CppUnit_addTest(pSuite, ODBCSQLiteTest, testFloat); CppUnit_addTest(pSuite, ODBCSQLiteTest, testDouble); CppUnit_addTest(pSuite, ODBCSQLiteTest, testTuple); CppUnit_addTest(pSuite, ODBCSQLiteTest, testTupleVector); CppUnit_addTest(pSuite, ODBCSQLiteTest, testInternalExtraction); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCSQLiteTest.h0000644000076500001200000001005511313735447023261 0ustar guenteradmin00000000000000// // ODBCSQLiteTest.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCSQLiteTest.h#4 $ // // Definition of the ODBCSQLiteTest class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCSQLiteTest_INCLUDED #define ODBCSQLiteTest_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCSQLiteTest: public CppUnit::TestCase /// SQLite3 ODBC test class /// Tested: /// /// Driver | Manager | DB | OS /// ---------------+--------------------------+------------+------------------------------------------ /// 00.70.00.00 | | SQLite 3.* | MS Windows XP Professional x64 v.2003/SP1 /// 00.70-3 (hardy)| unixODBC 2.2.11-16build1 | SQLite 3.* | Ubuntu 2.6.24-19-generic #1 SMP (hardy) { public: ODBCSQLiteTest(const std::string& name); ~ODBCSQLiteTest(); void testBareboneODBC(); void testSimpleAccess(); void testComplexType(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testBool(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateBoolsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorsTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // ODBCSQLiteTest_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCSQLServerTest.cpp0000644000076500001200000006764011313735447024315 0ustar guenteradmin00000000000000// // ODBCSQLServerTest.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCSQLServerTest.cpp#7 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCSQLServerTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::NotFoundException; // uncomment to force FreeTDS on Windows //#define FORCE_FREE_TDS // uncomment to use native SQL driver #define POCO_ODBC_USE_SQL_NATIVE // FreeTDS version selection guide (from http://www.freetds.org/userguide/choosingtdsprotocol.htm) // (see #define FREE_TDS_VERSION below) // Product TDS Version Comment // ---------------------------------------------------+------------+------------------------------------------------------------ // Sybase before System 10, Microsoft SQL Server 6.x 4.2 Still works with all products, subject to its limitations. // Sybase System 10 and above 5.0 Still the most current protocol used by Sybase. // Sybase System SQL Anywhere 5.0 only Originally Watcom SQL Server, a completely separate codebase. // Our best information is that SQL Anywhere first supported TDS // in version 5.5.03 using the OpenServer Gateway (OSG), and native // TDS 5.0 support arrived with version 6.0. // Microsoft SQL Server 7.0 7.0 Includes support for the extended datatypes in SQL Server 7.0 // (such as char/varchar fields of more than 255 characters), and // support for Unicode. // Microsoft SQL Server 2000 8.0 Include support for bigint (64 bit integers), variant and collation // on all fields. variant is not supported; collation is not widely used. #if defined(POCO_OS_FAMILY_WINDOWS) && !defined(FORCE_FREE_TDS) #ifdef POCO_ODBC_USE_SQL_NATIVE #define MS_SQL_SERVER_ODBC_DRIVER "SQL Native Client" #else #define MS_SQL_SERVER_ODBC_DRIVER "SQL Server" #endif #pragma message ("Using " MS_SQL_SERVER_ODBC_DRIVER " driver") #else #define MS_SQL_SERVER_ODBC_DRIVER "FreeTDS" #define FREE_TDS_VERSION "8.0" #if defined(POCO_OS_FAMILY_WINDOWS) #pragma message ("Using " MS_SQL_SERVER_ODBC_DRIVER " driver, version " FREE_TDS_VERSION) #endif #endif #define MS_SQL_SERVER_DSN "PocoDataSQLServerTest" #define MS_SQL_SERVER_SERVER "localhost" #define MS_SQL_SERVER_PORT "1433" #define MS_SQL_SERVER_DB "test" #define MS_SQL_SERVER_UID "test" #define MS_SQL_SERVER_PWD "test" const bool ODBCSQLServerTest::bindValues[8] = {true, true, true, false, false, true, false, false}; Poco::SharedPtr ODBCSQLServerTest::_pSession = 0; Poco::SharedPtr ODBCSQLServerTest::_pExecutor = 0; std::string ODBCSQLServerTest::_dsn = "PocoDataSQLServerTest"; std::string ODBCSQLServerTest::_dbConnString; Poco::Data::ODBC::Utility::DriverMap ODBCSQLServerTest::_drivers; Poco::Data::ODBC::Utility::DSNMap ODBCSQLServerTest::_dataSources; ODBCSQLServerTest::ODBCSQLServerTest(const std::string& name): CppUnit::TestCase(name) { static bool beenHere = false; ODBC::Connector::registerConnector(); if (_drivers.empty() || _dataSources.empty()) { Utility::drivers(_drivers); Utility::dataSources(_dataSources); checkODBCSetup(); } if (!_pSession && !_dbConnString.empty() && !beenHere) { try { _pSession = new Session(SessionFactory::instance().create(ODBC::Connector::KEY, _dbConnString)); }catch (ConnectionException& ex) { std::cout << "!!! WARNING: Connection failed. SQL Server tests will fail !!!" << std::endl; std::cout << ex.toString() << std::endl; } if (_pSession && _pSession->isConnected()) std::cout << "*** Connected to " << _dbConnString << std::endl; if (!_pExecutor) _pExecutor = new SQLExecutor("SQLServer SQL Executor", _pSession); } else if (!_pSession && !beenHere) std::cout << "!!! WARNING: No driver or DSN found. SQL Server tests will fail !!!" << std::endl; beenHere = true; } ODBCSQLServerTest::~ODBCSQLServerTest() { ODBC::Connector::unregisterConnector(); } void ODBCSQLServerTest::testBareboneODBC() { if (!_pSession) fail ("Test not available."); std::string tableCreateString = "CREATE TABLE Test " "(First VARCHAR(30)," "Second VARCHAR(30)," "Third VARBINARY(30)," "Fourth INTEGER," "Fifth FLOAT," "Sixth DATETIME)"; _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_MANUAL, true, "CONVERT(VARBINARY(30),?)"); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_IMMEDIATE, SQLExecutor::DE_BOUND, true, "CONVERT(VARBINARY(30),?)"); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_MANUAL, true, "CONVERT(VARBINARY(30),?)"); _pExecutor->bareboneODBCTest(_dbConnString, tableCreateString, SQLExecutor::PB_AT_EXEC, SQLExecutor::DE_BOUND, true, "CONVERT(VARBINARY(30),?)"); } void ODBCSQLServerTest::testSimpleAccess() { if (!_pSession) fail ("Test not available."); std::string tableName("Person"); int count = 0; recreatePersonTable(); try { *_pSession << "SELECT count(*) FROM sys.tables WHERE name = 'Person'", into(count), use(tableName), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("testSimpleAccess()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("testSimpleAccess()"); } assert (1 == count); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccess(); i += 2; } } void ODBCSQLServerTest::testComplexType() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexType(); i += 2; } } void ODBCSQLServerTest::testSimpleAccessVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->simpleAccessVector(); i += 2; } } void ODBCSQLServerTest::testComplexTypeVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->complexTypeVector(); i += 2; } } void ODBCSQLServerTest::testInsertVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertVector(); i += 2; } } void ODBCSQLServerTest::testInsertEmptyVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateStringsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertEmptyVector(); i += 2; } } void ODBCSQLServerTest::testInsertSingleBulk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulk(); i += 2; } } void ODBCSQLServerTest::testInsertSingleBulkVec() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->insertSingleBulkVec(); i += 2; } } void ODBCSQLServerTest::testLimit() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limits(); i += 2; } } void ODBCSQLServerTest::testLimitZero() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitZero(); i += 2; } } void ODBCSQLServerTest::testLimitOnce() { if (!_pSession) fail ("Test not available."); recreateIntsTable(); _pExecutor->limitOnce(); } void ODBCSQLServerTest::testLimitPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->limitPrepare(); i += 2; } } void ODBCSQLServerTest::testPrepare() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateIntsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->prepare(); i += 2; } } void ODBCSQLServerTest::testSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setSimple(); i += 2; } } void ODBCSQLServerTest::testSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplex(); i += 2; } } void ODBCSQLServerTest::testSetComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->setComplexUnique(); i += 2; } } void ODBCSQLServerTest::testMultiSetSimple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetSimple(); i += 2; } } void ODBCSQLServerTest::testMultiSetComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiSetComplex(); i += 2; } } void ODBCSQLServerTest::testMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplex(); i += 2; } } void ODBCSQLServerTest::testMapComplexUnique() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->mapComplexUnique(); i += 2; } } void ODBCSQLServerTest::testMultiMapComplex() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->multiMapComplex(); i += 2; } } void ODBCSQLServerTest::testSelectIntoSingle() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingle(); i += 2; } } void ODBCSQLServerTest::testSelectIntoSingleStep() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleStep(); i += 2; } } void ODBCSQLServerTest::testSelectIntoSingleFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->selectIntoSingleFail(); i += 2; } } void ODBCSQLServerTest::testLowerLimitOk() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitOk(); i += 2; } } void ODBCSQLServerTest::testSingleSelect() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->singleSelect(); i += 2; } } void ODBCSQLServerTest::testLowerLimitFail() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->lowerLimitFail(); i += 2; } } void ODBCSQLServerTest::testCombinedLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedLimits(); i += 2; } } void ODBCSQLServerTest::testRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->ranges(); i += 2; } } void ODBCSQLServerTest::testCombinedIllegalLimits() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->combinedIllegalLimits(); i += 2; } } void ODBCSQLServerTest::testIllegalRange() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->illegalRange(); i += 2; } } void ODBCSQLServerTest::testEmptyDB() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->emptyDB(); i += 2; } } void ODBCSQLServerTest::testBLOB() { if (!_pSession) fail ("Test not available."); const std::size_t maxFldSize = 250000; _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize-1)); recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize, "CONVERT(VARBINARY(MAX),?)"); fail ("must fail"); } catch (DataException&) { _pSession->setProperty("maxFieldSize", Poco::Any(maxFldSize)); } for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blob(maxFldSize, "CONVERT(VARBINARY(MAX),?)"); i += 2; } recreatePersonBLOBTable(); try { _pExecutor->blob(maxFldSize+1); fail ("must fail"); } catch (DataException&) { } } void ODBCSQLServerTest::testBLOBStmt() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreatePersonBLOBTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->blobStmt(); i += 2; } } void ODBCSQLServerTest::testBool() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateBoolsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->bools(); i += 2; } } void ODBCSQLServerTest::testFloat() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->floats(); i += 2; } } void ODBCSQLServerTest::testDouble() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateFloatsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->doubles(); i += 2; } } void ODBCSQLServerTest::testTuple() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tuples(); i += 2; } } void ODBCSQLServerTest::testTupleVector() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateTuplesTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->tupleVector(); i += 2; } } void ODBCSQLServerTest::testInternalExtraction() { if (!_pSession) fail ("Test not available."); for (int i = 0; i < 8;) { recreateVectorsTable(); _pSession->setFeature("autoBind", bindValues[i]); _pSession->setFeature("autoExtract", bindValues[i+1]); _pExecutor->internalExtraction(); i += 2; } } void ODBCSQLServerTest::dropTable(const std::string& tableName) { try { *_pSession << format("DROP TABLE %s", tableName), now; } catch (StatementException& ex) { bool ignoreError = false; const StatementDiagnostics::FieldVec& flds = ex.diagnostics().fields(); StatementDiagnostics::Iterator it = flds.begin(); for (; it != flds.end(); ++it) { if (3701 == it->_nativeError)//(table does not exist) { ignoreError = true; break; } } if (!ignoreError) { std::cout << ex.displayText() << std::endl; throw; } } } void ODBCSQLServerTest::recreatePersonTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Age INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonTable()"); } } void ODBCSQLServerTest::recreatePersonBLOBTable() { dropTable("Person"); try { *_pSession << "CREATE TABLE Person (LastName VARCHAR(30), FirstName VARCHAR(30), Address VARCHAR(30), Image VARBINARY(MAX))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreatePersonBLOBTable()"); } } void ODBCSQLServerTest::recreateIntsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateIntsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateIntsTable()"); } } void ODBCSQLServerTest::recreateStringsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateStringsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateStringsTable()"); } } void ODBCSQLServerTest::recreateBoolsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str BIT)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateBoolsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateBoolsTable()"); } } void ODBCSQLServerTest::recreateFloatsTable() { dropTable("Strings"); try { *_pSession << "CREATE TABLE Strings (str FLOAT)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateFloatsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateFloatsTable()"); } } void ODBCSQLServerTest::recreateTuplesTable() { dropTable("Tuples"); try { *_pSession << "CREATE TABLE Tuples " "(int0 INTEGER, int1 INTEGER, int2 INTEGER, int3 INTEGER, int4 INTEGER, int5 INTEGER, int6 INTEGER, " "int7 INTEGER, int8 INTEGER, int9 INTEGER, int10 INTEGER, int11 INTEGER, int12 INTEGER, int13 INTEGER," "int14 INTEGER, int15 INTEGER, int16 INTEGER, int17 INTEGER, int18 INTEGER, int19 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateTuplesTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateTuplesTable()"); } } void ODBCSQLServerTest::recreateVectorTable() { dropTable("Vector"); try { *_pSession << "CREATE TABLE Vector (i0 INTEGER)", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorTable()"); } } void ODBCSQLServerTest::recreateVectorsTable() { dropTable("Vectors"); try { *_pSession << "CREATE TABLE Vectors (int0 INTEGER, flt0 FLOAT, str0 VARCHAR(30))", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail ("recreateVectorsTable()"); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail ("recreateVectorsTable()"); } } void ODBCSQLServerTest::checkODBCSetup() { static bool beenHere = false; if (!beenHere) { beenHere = true; bool driverFound = false; bool dsnFound = false; Utility::DriverMap::iterator itDrv = _drivers.begin(); for (; itDrv != _drivers.end(); ++itDrv) { if (((itDrv->first).find(MS_SQL_SERVER_ODBC_DRIVER) != std::string::npos)) { std::cout << "Driver found: " << itDrv->first << " (" << itDrv->second << ')' << std::endl; driverFound = true; break; } } if (!driverFound) { std::cout << "SQL Server driver NOT found, tests will fail." << std::endl; return; } Utility::DSNMap::iterator itDSN = _dataSources.begin(); for (; itDSN != _dataSources.end(); ++itDSN) { if (((itDSN->first).find(_dsn) != std::string::npos) && (((itDSN->second).find(MS_SQL_SERVER_ODBC_DRIVER) != std::string::npos))) { std::cout << "DSN found: " << itDSN->first << " (" << itDSN->second << ')' << std::endl; dsnFound = true; break; } } if (!dsnFound) { if (!_pSession && _dbConnString.empty()) { std::cout << "MS SQL Server DSN NOT found, will attempt to connect without it." << std::endl; _dbConnString = "DRIVER=" MS_SQL_SERVER_ODBC_DRIVER ";" "UID=" MS_SQL_SERVER_UID ";" "PWD=" MS_SQL_SERVER_PWD ";" "DATABASE=" MS_SQL_SERVER_DB ";" "SERVER=" MS_SQL_SERVER_SERVER ";" "PORT=" MS_SQL_SERVER_PORT ";" #ifdef FREE_TDS_VERSION "TDS_Version=" FREE_TDS_VERSION ";" #endif ; return; } else if (!_dbConnString.empty()) { std::cout << "MS SQL Server tests not available." << std::endl; return; } } } if (!_pSession) format(_dbConnString, "DSN=%s;Uid=test;Pwd=test;", _dsn); } void ODBCSQLServerTest::setUp() { } void ODBCSQLServerTest::tearDown() { } CppUnit::Test* ODBCSQLServerTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCSQLServerTest"); CppUnit_addTest(pSuite, ODBCSQLServerTest, testBareboneODBC); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSimpleAccess); CppUnit_addTest(pSuite, ODBCSQLServerTest, testComplexType); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSimpleAccessVector); CppUnit_addTest(pSuite, ODBCSQLServerTest, testComplexTypeVector); CppUnit_addTest(pSuite, ODBCSQLServerTest, testInsertVector); CppUnit_addTest(pSuite, ODBCSQLServerTest, testInsertEmptyVector); CppUnit_addTest(pSuite, ODBCSQLServerTest, testInsertSingleBulk); CppUnit_addTest(pSuite, ODBCSQLServerTest, testInsertSingleBulkVec); CppUnit_addTest(pSuite, ODBCSQLServerTest, testLimit); CppUnit_addTest(pSuite, ODBCSQLServerTest, testLimitOnce); CppUnit_addTest(pSuite, ODBCSQLServerTest, testLimitPrepare); CppUnit_addTest(pSuite, ODBCSQLServerTest, testLimitZero); CppUnit_addTest(pSuite, ODBCSQLServerTest, testPrepare); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSetSimple); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSetComplex); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSetComplexUnique); CppUnit_addTest(pSuite, ODBCSQLServerTest, testMultiSetSimple); CppUnit_addTest(pSuite, ODBCSQLServerTest, testMultiSetComplex); CppUnit_addTest(pSuite, ODBCSQLServerTest, testMapComplex); CppUnit_addTest(pSuite, ODBCSQLServerTest, testMapComplexUnique); CppUnit_addTest(pSuite, ODBCSQLServerTest, testMultiMapComplex); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSelectIntoSingle); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSelectIntoSingleStep); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSelectIntoSingleFail); CppUnit_addTest(pSuite, ODBCSQLServerTest, testLowerLimitOk); CppUnit_addTest(pSuite, ODBCSQLServerTest, testLowerLimitFail); CppUnit_addTest(pSuite, ODBCSQLServerTest, testCombinedLimits); CppUnit_addTest(pSuite, ODBCSQLServerTest, testCombinedIllegalLimits); CppUnit_addTest(pSuite, ODBCSQLServerTest, testRange); CppUnit_addTest(pSuite, ODBCSQLServerTest, testIllegalRange); CppUnit_addTest(pSuite, ODBCSQLServerTest, testSingleSelect); CppUnit_addTest(pSuite, ODBCSQLServerTest, testEmptyDB); CppUnit_addTest(pSuite, ODBCSQLServerTest, testBLOB); CppUnit_addTest(pSuite, ODBCSQLServerTest, testBLOBStmt); CppUnit_addTest(pSuite, ODBCSQLServerTest, testBool); CppUnit_addTest(pSuite, ODBCSQLServerTest, testFloat); CppUnit_addTest(pSuite, ODBCSQLServerTest, testDouble); CppUnit_addTest(pSuite, ODBCSQLServerTest, testTuple); CppUnit_addTest(pSuite, ODBCSQLServerTest, testTupleVector); CppUnit_addTest(pSuite, ODBCSQLServerTest, testInternalExtraction); return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCSQLServerTest.h0000644000076500001200000001110211313735447023740 0ustar guenteradmin00000000000000// // ODBCSQLServerTest.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCSQLServerTest.h#4 $ // // Definition of the ODBCSQLServerTest class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCSQLServerTest_INCLUDED #define ODBCSQLServerTest_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/SharedPtr.h" #include "CppUnit/TestCase.h" #include "SQLExecutor.h" class ODBCSQLServerTest: public CppUnit::TestCase /// SQLServer ODBC test class /// Tested: /// /// Driver | Manager | DB | OS /// ----------------------------------+--------------------------+-----------------------------+------------------------------------------ /// SQL Server 2000.86.3959.00 | | SQL Server Express 9.0.2047 | MS Windows XP Professional x64 v.2003/SP1 /// SQL Native Client 2005.90.3042.00 | | SQL Server Express 9.0.2047 | MS Windows XP Professional x64 v.2003/SP1 /// FreeTDS 0.82.00.8128 | | SQL Server Express 9.0.2047 | MS Windows XP Professional x64 v.2003/SP1 /// FreeTDS 0.82.00.8128 | unixODBC 2.2.11-16build1 | SQL Server Express 9.0.2047 | Ubuntu 2.6.24-19-generic #1 SMP (hardy) /// { public: ODBCSQLServerTest(const std::string& name); ~ODBCSQLServerTest(); void testBareboneODBC(); void testSimpleAccess(); void testComplexType(); void testSimpleAccessVector(); void testComplexTypeVector(); void testInsertVector(); void testInsertEmptyVector(); void testInsertSingleBulk(); void testInsertSingleBulkVec(); void testLimit(); void testLimitOnce(); void testLimitPrepare(); void testLimitZero(); void testPrepare(); void testSetSimple(); void testSetComplex(); void testSetComplexUnique(); void testMultiSetSimple(); void testMultiSetComplex(); void testMapComplex(); void testMapComplexUnique(); void testMultiMapComplex(); void testSelectIntoSingle(); void testSelectIntoSingleStep(); void testSelectIntoSingleFail(); void testLowerLimitOk(); void testLowerLimitFail(); void testCombinedLimits(); void testCombinedIllegalLimits(); void testRange(); void testIllegalRange(); void testSingleSelect(); void testEmptyDB(); void testBLOB(); void testBLOBStmt(); void testBool(); void testFloat(); void testDouble(); void testTuple(); void testTupleVector(); void testInternalExtraction(); void setUp(); void tearDown(); static CppUnit::Test* suite(); private: void checkODBCSetup(); void dropTable(const std::string& tableName); void recreatePersonTable(); void recreatePersonBLOBTable(); void recreateStringsTable(); void recreateBoolsTable(); void recreateIntsTable(); void recreateFloatsTable(); void recreateTuplesTable(); void recreateVectorTable(); void recreateVectorsTable(); static Poco::Data::ODBC::Utility::DriverMap _drivers; static Poco::Data::ODBC::Utility::DSNMap _dataSources; static std::string _dsn; static std::string _dbConnString; static Poco::SharedPtr _pSession; static Poco::SharedPtr _pExecutor; static const bool bindValues[8]; }; #endif // ODBCSQLServerTest_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCTestSuite.cpp0000644000076500001200000000540111313735447023543 0ustar guenteradmin00000000000000// // ODBCTestSuite.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCTestSuite.cpp#4 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ODBCTestSuite.h" #include "ODBCDB2Test.h" #include "ODBCMySQLTest.h" #include "ODBCOracleTest.h" #include "ODBCPostgreSQLTest.h" #include "ODBCSQLiteTest.h" #include "ODBCSQLServerTest.h" #if defined(POCO_OS_FAMILY_WINDOWS) #include "ODBCAccessTest.h" #endif CppUnit::Test* ODBCTestSuite::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ODBCTestSuite"); //!FIXME // On Win XP Pro: // // 1) The PostgreSQL connection fails if attempted after DB2 w/ following error: // // sqlState="IM003" // message="Specified driver could not be loaded due to system error 127 (PostgreSQL ANSI)." // nativeError=160 // System error 127 is "The specified procedure could not be found." // Workaround is to connect to PostgreSQL prior to connecting to DB2. // // 2) When Oracle test is loaded after DB2, the test application does not exit cleanly. // All tests pass, though. // pSuite->addTest(ODBCOracleTest::suite()); pSuite->addTest(ODBCPostgreSQLTest::suite()); pSuite->addTest(ODBCDB2Test::suite()); pSuite->addTest(ODBCMySQLTest::suite()); pSuite->addTest(ODBCSQLiteTest::suite()); pSuite->addTest(ODBCSQLServerTest::suite()); #if defined(POCO_OS_FAMILY_WINDOWS) pSuite->addTest(ODBCAccessTest::suite()); #endif return pSuite; } poco-1.3.6p1-all/Data/ODBC/testsuite/src/ODBCTestSuite.h0000644000076500001200000000335711313735447023220 0ustar guenteradmin00000000000000// // ODBCTestSuite.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/ODBCTestSuite.h#2 $ // // Definition of the ODBCTestSuite class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef ODBCTestSuite_INCLUDED #define ODBCTestSuite_INCLUDED #include "CppUnit/TestSuite.h" class ODBCTestSuite { public: static CppUnit::Test* suite(); }; #endif // ODBCTestSuite_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/SQLExecutor.cpp0000644000076500001200000017307311313735447023353 0ustar guenteradmin00000000000000// // SQLExecutor.cpp // // $Id: //poco/Main/DataConnectors/ODBC/testsuite/src/SQLExecutor.cpp#14 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "CppUnit/TestCase.h" #include "SQLExecutor.h" #include "Poco/String.h" #include "Poco/Format.h" #include "Poco/Tuple.h" #include "Poco/Any.h" #include "Poco/Exception.h" #include "Poco/Data/Common.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/RecordSet.h" #include "Poco/Data/ODBC/Connector.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/Diagnostics.h" #include "Poco/Data/ODBC/Preparation.h" #include "Poco/Data/ODBC/ODBCException.h" #include "Poco/Data/ODBC/ODBCStatementImpl.h" #include #include using namespace Poco::Data; using Poco::Data::ODBC::Utility; using Poco::Data::ODBC::Preparation; using Poco::Data::ODBC::ConnectionException; using Poco::Data::ODBC::StatementException; using Poco::Data::ODBC::DataTruncatedException; using Poco::Data::ODBC::StatementDiagnostics; using Poco::format; using Poco::Tuple; using Poco::Any; using Poco::AnyCast; using Poco::NotFoundException; using Poco::InvalidAccessException; using Poco::BadCastException; using Poco::RangeException; struct Person { std::string lastName; std::string firstName; std::string address; int age; Person(){age = 0;} Person(const std::string& ln, const std::string& fn, const std::string& adr, int a):lastName(ln), firstName(fn), address(adr), age(a) { } bool operator==(const Person& other) const { return lastName == other.lastName && firstName == other.firstName && address == other.address && age == other.age; } bool operator < (const Person& p) const { if (age < p.age) return true; if (lastName < p.lastName) return true; if (firstName < p.firstName) return true; return (address < p.address); } const std::string& operator () () const /// This method is required so we can extract data to a map! { // we choose the lastName as examplary key return lastName; } }; namespace Poco { namespace Data { template <> class TypeHandler { public: static void bind(std::size_t pos, const Person& obj, AbstractBinder* pBinder) { // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Address VARCHAR, Age INTEGER(3)) poco_assert_dbg (pBinder != 0); pBinder->bind(pos++, obj.lastName); pBinder->bind(pos++, obj.firstName); pBinder->bind(pos++, obj.address); pBinder->bind(pos++, obj.age); } static void prepare(std::size_t pos, const Person& obj, AbstractPreparation* pPrepare) { // the table is defined as Person (LastName VARCHAR(30), FirstName VARCHAR, Address VARCHAR, Age INTEGER(3)) poco_assert_dbg (pPrepare != 0); pPrepare->prepare(pos++, obj.lastName); pPrepare->prepare(pos++, obj.firstName); pPrepare->prepare(pos++, obj.address); pPrepare->prepare(pos++, obj.age); } static std::size_t size() { return 4; } static void extract(std::size_t pos, Person& obj, const Person& defVal, AbstractExtractor* pExt) { poco_assert_dbg (pExt != 0); if (!pExt->extract(pos++, obj.lastName)) obj.lastName = defVal.lastName; if (!pExt->extract(pos++, obj.firstName)) obj.firstName = defVal.firstName; if (!pExt->extract(pos++, obj.address)) obj.address = defVal.address; if (!pExt->extract(pos++, obj.age)) obj.age = defVal.age; } private: TypeHandler(); ~TypeHandler(); TypeHandler(const TypeHandler&); TypeHandler& operator=(const TypeHandler&); }; } } // namespace Poco::Data SQLExecutor::SQLExecutor(const std::string& name, Poco::Data::Session* pSession): CppUnit::TestCase(name), _pSession(pSession) { } SQLExecutor::~SQLExecutor() { } void SQLExecutor::bareboneODBCTest(const std::string& dbConnString, const std::string& tableCreateString, SQLExecutor::DataBinding bindMode, SQLExecutor::DataExtraction extractMode, bool doTime, const std::string& blobPlaceholder) { SQLRETURN rc; SQLHENV henv = SQL_NULL_HENV; SQLHDBC hdbc = SQL_NULL_HDBC; SQLHSTMT hstmt = SQL_NULL_HSTMT; // Environment begin rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); poco_odbc_check_env (rc, henv); rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0); poco_odbc_check_env (rc, henv); // Connection begin rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); poco_odbc_check_dbc (rc, hdbc); SQLCHAR connectOutput[1024] = {0}; SQLSMALLINT result; rc = SQLDriverConnect(hdbc , NULL ,(SQLCHAR*) dbConnString.c_str() ,(SQLSMALLINT) SQL_NTS , connectOutput , sizeof(connectOutput) , &result , SQL_DRIVER_NOPROMPT); poco_odbc_check_dbc (rc, hdbc); // retrieve datetime type information for this DBMS rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); poco_odbc_check_stmt (rc, hstmt); rc = SQLGetTypeInfo(hstmt, SQL_TYPE_TIMESTAMP); poco_odbc_check_stmt (rc, hstmt); rc = SQLFetch(hstmt); assert (SQL_SUCCEEDED(rc) || SQL_NO_DATA == rc); SQLINTEGER dateTimeColSize = 0; SQLSMALLINT dateTimeDecDigits = 0; if (SQL_SUCCEEDED(rc)) { SQLLEN ind = 0; rc = SQLGetData(hstmt, 3, SQL_C_SLONG, &dateTimeColSize, sizeof(SQLINTEGER), &ind); poco_odbc_check_stmt (rc, hstmt); rc = SQLGetData(hstmt, 14, SQL_C_SSHORT, &dateTimeDecDigits, sizeof(SQLSMALLINT), &ind); poco_odbc_check_stmt (rc, hstmt); assert (sizeof(SQL_TIMESTAMP_STRUCT) <= dateTimeColSize); } else if (SQL_NO_DATA == rc) std::cerr << '[' << name() << ']' << " Warning: no SQL_TYPE_TIMESTAMP data type info returned by driver." << std::endl; rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt); poco_odbc_check_stmt (rc, hstmt); // Statement begin rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt); poco_odbc_check_stmt (rc, hstmt); std::string sql = "DROP TABLE Test"; SQLCHAR* pStr = (SQLCHAR*) sql.c_str(); SQLExecDirect(hstmt, pStr, (SQLINTEGER) sql.length()); //no return code check - ignore drop errors // create table and go sql = tableCreateString; pStr = (SQLCHAR*) sql.c_str(); rc = SQLPrepare(hstmt, pStr, (SQLINTEGER) sql.length()); poco_odbc_check_stmt (rc, hstmt); rc = SQLExecute(hstmt); poco_odbc_check_stmt (rc, hstmt); sql = format("INSERT INTO Test VALUES (?,?,%s,?,?,?)", blobPlaceholder); pStr = (SQLCHAR*) sql.c_str(); rc = SQLPrepare(hstmt, pStr, (SQLINTEGER) sql.length()); poco_odbc_check_stmt (rc, hstmt); std::string str[3] = { "11111111111", "222222222222222222222222", "333333333333333333333333333" }; int fourth = 4; float fifth = 1.5; SQL_TIMESTAMP_STRUCT sixth; sixth.year = 1965; sixth.month = 6; sixth.day = 18; sixth.hour = 5; sixth.minute = 34; sixth.second = 59; // Fraction support is limited to milliseconds due to MS SQL Server limitation // see http://support.microsoft.com/kb/263872 sixth.fraction = 997000000; SQLLEN li[3] = { SQL_NTS, SQL_NTS, 0 }; SQLINTEGER size = (SQLINTEGER) str[0].size(); if (SQLExecutor::PB_AT_EXEC == bindMode) li[0] = SQL_LEN_DATA_AT_EXEC(size); rc = SQLBindParameter(hstmt, (SQLUSMALLINT) 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, (SQLUINTEGER) size, 0, (SQLPOINTER) str[0].c_str(), size, &li[0]); poco_odbc_check_stmt (rc, hstmt); size = (SQLINTEGER) str[1].size(); if (SQLExecutor::PB_AT_EXEC == bindMode) li[1] = SQL_LEN_DATA_AT_EXEC(size); else li[1] = SQL_NTS; rc = SQLBindParameter(hstmt, (SQLUSMALLINT) 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, (SQLUINTEGER) size, 0, (SQLPOINTER) str[1].c_str(), size, &li[1]); poco_odbc_check_stmt (rc, hstmt); size = (SQLINTEGER) str[2].size(); if (SQLExecutor::PB_AT_EXEC == bindMode) li[2] = SQL_LEN_DATA_AT_EXEC(size); else li[2] = size; rc = SQLBindParameter(hstmt, (SQLUSMALLINT) 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, (SQLUINTEGER) size, 0, (SQLPOINTER) str[2].data(), size, &li[2]); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindParameter(hstmt, (SQLUSMALLINT) 4, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER, 0, 0, (SQLPOINTER) &fourth, 0, 0); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindParameter(hstmt, (SQLUSMALLINT) 5, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_REAL, 0, 1, (SQLPOINTER) &fifth, 0, 0); poco_odbc_check_stmt (rc, hstmt); SQLSMALLINT dataType = 0; SQLULEN parameterSize = 0; SQLSMALLINT decimalDigits = 0; SQLSMALLINT nullable = 0; rc = SQLDescribeParam(hstmt, 6, &dataType, ¶meterSize, &decimalDigits, &nullable); if (SQL_SUCCEEDED(rc)) { if (parameterSize) dateTimeColSize = parameterSize; if (decimalDigits) dateTimeDecDigits = decimalDigits; } else std::cerr << '[' << name() << ']' << " Warning: could not get SQL_TYPE_TIMESTAMP parameter description." << std::endl; rc = SQLBindParameter(hstmt, (SQLUSMALLINT) 6, SQL_PARAM_INPUT, SQL_C_TYPE_TIMESTAMP, SQL_TYPE_TIMESTAMP, dateTimeColSize, dateTimeDecDigits, (SQLPOINTER) &sixth, 0, 0); poco_odbc_check_stmt (rc, hstmt); rc = SQLExecute(hstmt); if (!(SQL_NEED_DATA == rc || SQL_SUCCEEDED(rc))) { poco_odbc_check_stmt (rc, hstmt); } if (SQL_NEED_DATA == rc) { SQLPOINTER pParam = 0; while (SQL_NEED_DATA == (rc = SQLParamData(hstmt, &pParam))) { SQLINTEGER dataSize = 0; // Data size should be ignored for non-null, // non-variable length fields, but SQLite ODBC // driver insists on it always being the actual // data length if (pParam == (SQLPOINTER) str[0].c_str()) dataSize = (SQLINTEGER) str[0].size(); else if (pParam == (SQLPOINTER) str[1].c_str()) dataSize = (SQLINTEGER) str[1].size(); else if (pParam == (SQLPOINTER) str[2].c_str()) dataSize = (SQLINTEGER) str[2].size(); else if (pParam == (SQLPOINTER) &fourth) dataSize = (SQLINTEGER) sizeof(fourth); else if (pParam == (SQLPOINTER) &fifth) dataSize = (SQLINTEGER) sizeof(fifth); else if (pParam == (SQLPOINTER) &sixth) dataSize = (SQLINTEGER) sizeof(sixth); assert (0 != dataSize); rc = SQLPutData(hstmt, pParam, dataSize); poco_odbc_check_stmt (rc, hstmt); } } poco_odbc_check_stmt (rc, hstmt); sql = "SELECT * FROM Test"; pStr = (SQLCHAR*) sql.c_str(); rc = SQLPrepare(hstmt, pStr, (SQLINTEGER) sql.length()); poco_odbc_check_stmt (rc, hstmt); char chr[3][50] = {{ 0 }}; SQLLEN lengths[6] = { 0 }; fourth = 0; fifth = 0.0f; std::memset(&sixth, 0, sizeof(sixth)); if (SQLExecutor::DE_BOUND == extractMode) { rc = SQLBindCol(hstmt, (SQLUSMALLINT) 1, SQL_C_CHAR, (SQLPOINTER) chr[0], (SQLINTEGER) sizeof(chr[0]), &lengths[0]); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindCol(hstmt, (SQLUSMALLINT) 2, SQL_C_CHAR, (SQLPOINTER) chr[1], (SQLINTEGER) sizeof(chr[1]), &lengths[1]); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindCol(hstmt, (SQLUSMALLINT) 3, SQL_C_BINARY, (SQLPOINTER) chr[2], (SQLINTEGER) sizeof(chr[2]), &lengths[2]); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindCol(hstmt, (SQLUSMALLINT) 4, SQL_C_SLONG, (SQLPOINTER) &fourth, (SQLINTEGER) 0, &lengths[3]); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindCol(hstmt, (SQLUSMALLINT) 5, SQL_C_FLOAT, (SQLPOINTER) &fifth, (SQLINTEGER) 0, &lengths[4]); poco_odbc_check_stmt (rc, hstmt); rc = SQLBindCol(hstmt, (SQLUSMALLINT) 6, SQL_C_TYPE_TIMESTAMP, (SQLPOINTER) &sixth, (SQLINTEGER) 0, &lengths[5]); poco_odbc_check_stmt (rc, hstmt); } rc = SQLExecute(hstmt); poco_odbc_check_stmt (rc, hstmt); rc = SQLFetch(hstmt); poco_odbc_check_stmt (rc, hstmt); if (SQLExecutor::DE_MANUAL == extractMode) { SQLINTEGER len = lengths[0] = 0; while (SQL_SUCCESS_WITH_INFO == (rc = SQLGetData(hstmt, (SQLUSMALLINT) 1, SQL_C_CHAR, chr[0] + len, sizeof(chr[0]) - len, &lengths[0]))) { len += lengths[0]; if (!lengths[0] || len >= sizeof(chr[1])) break; } poco_odbc_check_stmt (rc, hstmt); len = lengths[1] = 0; while (SQL_SUCCESS_WITH_INFO == (rc = SQLGetData(hstmt, (SQLUSMALLINT) 2, SQL_C_CHAR, chr[1] + len, sizeof(chr[1]) - len, &lengths[1]))) { len += lengths[1]; if (!lengths[1] || len >= sizeof(chr[1])) break; } poco_odbc_check_stmt (rc, hstmt); len = lengths[2] = 0; while (SQL_SUCCESS_WITH_INFO == (rc = SQLGetData(hstmt, (SQLUSMALLINT) 3, SQL_C_BINARY, chr[2] + len, sizeof(chr[2]) - len, &lengths[2]))) { len += lengths[1]; if (!lengths[2] || len >= sizeof(chr[2])) break; } poco_odbc_check_stmt (rc, hstmt); rc = SQLGetData(hstmt, (SQLUSMALLINT) 4, SQL_C_SLONG, &fourth, 0, &lengths[3]); poco_odbc_check_stmt (rc, hstmt); rc = SQLGetData(hstmt, (SQLUSMALLINT) 5, SQL_C_FLOAT, &fifth, 0, &lengths[4]); poco_odbc_check_stmt (rc, hstmt); rc = SQLGetData(hstmt, (SQLUSMALLINT) 6, SQL_C_TYPE_TIMESTAMP, &sixth, 0, &lengths[5]); poco_odbc_check_stmt (rc, hstmt); } assert (0 == std::strncmp(str[0].c_str(), chr[0], str[0].size())); assert (0 == std::strncmp(str[1].c_str(), chr[1], str[1].size())); assert (0 == std::strncmp(str[2].c_str(), chr[2], str[2].size())); assert (4 == fourth); assert (1.5 == fifth); assert (1965 == sixth.year); assert (6 == sixth.month); assert (18 == sixth.day); if (doTime) { assert (5 == sixth.hour); assert (34 == sixth.minute); assert (59 == sixth.second); if (sixth.fraction)//MySQL does not support fraction assert (997000000 == sixth.fraction); } rc = SQLCloseCursor(hstmt); poco_odbc_check_stmt (rc, hstmt); sql = "DROP TABLE Test"; pStr = (SQLCHAR*) sql.c_str(); rc = SQLExecDirect(hstmt, pStr, (SQLINTEGER) sql.length()); poco_odbc_check_stmt (rc, hstmt); rc = SQLFreeHandle(SQL_HANDLE_STMT, hstmt); poco_odbc_check_stmt (rc, hstmt); // Connection end rc = SQLDisconnect(hdbc); poco_odbc_check_dbc (rc, hdbc); rc = SQLFreeHandle(SQL_HANDLE_DBC, hdbc); poco_odbc_check_dbc (rc, hdbc); // Environment end rc = SQLFreeHandle(SQL_HANDLE_ENV, henv); poco_odbc_check_env (rc, henv); } void SQLExecutor::simpleAccess() { std::string funct = "simpleAccess()"; std::string lastName = "lastName"; std::string firstName("firstName"); std::string address("Address"); int age = 133132; int count = 0; std::string result; count = 0; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastName), use(firstName), use(address), use(age), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT LastName FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (lastName == result); try { *_pSession << "SELECT Age FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == age); } void SQLExecutor::complexType() { std::string funct = "complexType()"; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(p1), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(p2), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person c1; Person c2; try { *_pSession << "SELECT * FROM Person WHERE LastName = 'LN1'", into(c1), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (c1 == p1); } void SQLExecutor::complexTypeTuple() { std::string funct = "complexTypeTuple()"; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); Tuple t(p1,p2); try { *_pSession << "INSERT INTO PERSON VALUES(?,?,?,?,?,?,?,?)", use(t), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } Tuple ret; assert (ret != t); try { *_pSession << "SELECT * FROM PERSON", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ret == t); } void SQLExecutor::simpleAccessVector() { std::string funct = "simpleAccessVector()"; std::vector lastNames; std::vector firstNames; std::vector addresses; std::vector ages; std::string tableName("Person"); lastNames.push_back("LN1"); lastNames.push_back("LN2"); firstNames.push_back("FN1"); firstNames.push_back("FN2"); addresses.push_back("ADDR1"); addresses.push_back("ADDR2"); ages.push_back(1); ages.push_back(2); int count = 0; std::string result; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastNames), use(firstNames), use(addresses), use(ages), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::vector lastNamesR; std::vector firstNamesR; std::vector addressesR; std::vector agesR; try { *_pSession << "SELECT * FROM Person", into(lastNamesR), into(firstNamesR), into(addressesR), into(agesR), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ages == agesR); assert (lastNames == lastNamesR); assert (firstNames == firstNamesR); assert (addresses == addressesR); } void SQLExecutor::complexTypeVector() { std::string funct = "complexTypeVector()"; std::vector people; people.push_back(Person("LN1", "FN1", "ADDR1", 1)); people.push_back(Person("LN2", "FN2", "ADDR2", 2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::vector result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result == people); } void SQLExecutor::insertVector() { std::string funct = "insertVector()"; std::vector str; str.push_back("s1"); str.push_back("s2"); str.push_back("s3"); str.push_back("s3"); int count = 100; { Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(str))); try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 0); try { stmt.execute(); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 4); } count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 4); } void SQLExecutor::insertEmptyVector() { std::string funct = "insertEmptyVector()"; std::vector str; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(str), now; fail("empty collections should not work"); } catch (Poco::Exception&) { } } void SQLExecutor::insertSingleBulk() { std::string funct = "insertSingleBulk()"; int x = 0; Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(x))); for (x = 0; x < 100; ++x) { int i = stmt.execute(); assert (i == 0); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 100); try { *_pSession << "SELECT SUM(str) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == ((0+99)*100/2)); } void SQLExecutor::bools() { std::string funct = "bools()"; bool data = true; bool ret = false; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT str FROM Strings", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ret); } void SQLExecutor::floats() { std::string funct = "floats()"; float data = 1.5f; float ret = 0.0f; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT str FROM Strings", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ret == data); } void SQLExecutor::doubles() { std::string funct = "floats()"; double data = 1.5; double ret = 0.0; try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 1); try { *_pSession << "SELECT str FROM Strings", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ret == data); } void SQLExecutor::insertSingleBulkVec() { std::string funct = "insertSingleBulkVec()"; std::vector data; for (int x = 0; x < 100; ++x) data.push_back(x); Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(data))); stmt.execute(); int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 100); try { *_pSession << "SELECT SUM(str) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == ((0+99)*100/2)); } void SQLExecutor::limits() { std::string funct = "limit()"; std::vector data; for (int x = 0; x < 100; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } std::vector retData; try { *_pSession << "SELECT * FROM Strings", into(retData), limit(50), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (retData.size() == 50); for (int x = 0; x < 50; ++x) { assert(data[x] == retData[x]); } } void SQLExecutor::limitZero() { std::string funct = "limitZero()"; std::vector data; for (int x = 0; x < 100; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } std::vector retData; try { *_pSession << "SELECT * FROM Strings", into(retData), limit(0), now; }// stupid test, but at least we shouldn't crash catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (retData.size() == 0); } void SQLExecutor::limitOnce() { std::string funct = "limitOnce()"; std::vector data; for (int x = 0; x < 101; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } std::vector retData; Statement stmt = (*_pSession << "SELECT * FROM Strings", into(retData), limit(50), now); assert (!stmt.done()); assert (retData.size() == 50); stmt.execute(); assert (!stmt.done()); assert (retData.size() == 100); stmt.execute(); assert (stmt.done()); assert (retData.size() == 101); for (int x = 0; x < 101; ++x) { assert(data[x] == retData[x]); } } void SQLExecutor::limitPrepare() { std::string funct = "limitPrepare()"; std::vector data; for (int x = 0; x < 100; ++x) { data.push_back(x); } try { *_pSession << "INSERT INTO Strings VALUES (?)", use(data), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } std::vector retData; Statement stmt = (*_pSession << "SELECT * FROM Strings", into(retData), limit(50)); assert (retData.size() == 0); assert (!stmt.done()); try { stmt.execute(); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (!stmt.done()); assert (retData.size() == 50); try { stmt.execute(); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (stmt.done()); assert (retData.size() == 100); try { stmt.execute(); }// will restart execution! catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (!stmt.done()); assert (retData.size() == 150); for (int x = 0; x < 150; ++x) { assert(data[x%100] == retData[x]); } } void SQLExecutor::prepare() { std::string funct = "prepare()"; std::vector data; for (int x = 0; x < 100; x += 2) { data.push_back(x); } { Statement stmt((*_pSession << "INSERT INTO Strings VALUES (?)", use(data))); } // stmt should not have been executed when destroyed int count = 100; try { *_pSession << "SELECT COUNT(*) FROM Strings", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 0); } void SQLExecutor::setSimple() { std::string funct = "setSimple()"; std::set lastNames; std::set firstNames; std::set addresses; std::set ages; std::string tableName("Person"); lastNames.insert("LN1"); lastNames.insert("LN2"); firstNames.insert("FN1"); firstNames.insert("FN2"); addresses.insert("ADDR1"); addresses.insert("ADDR2"); ages.insert(1); ages.insert(2); int count = 0; std::string result; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastNames), use(firstNames), use(addresses), use(ages), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::set lastNamesR; std::set firstNamesR; std::set addressesR; std::set agesR; try { *_pSession << "SELECT * FROM Person", into(lastNamesR), into(firstNamesR), into(addressesR), into(agesR), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ages == agesR); assert (lastNames == lastNamesR); assert (firstNames == firstNamesR); assert (addresses == addressesR); } void SQLExecutor::setComplex() { std::string funct = "setComplex()"; std::set people; people.insert(Person("LN1", "FN1", "ADDR1", 1)); people.insert(Person("LN2", "FN2", "ADDR2", 2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::set result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result == people); } void SQLExecutor::setComplexUnique() { std::string funct = "setComplexUnique()"; std::vector people; Person p1("LN1", "FN1", "ADDR1", 1); people.push_back(p1); people.push_back(p1); people.push_back(p1); people.push_back(p1); Person p2("LN2", "FN2", "ADDR2", 2); people.push_back(p2); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 5); std::set result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result.size() == 2); assert (*result.begin() == p1); assert (*++result.begin() == p2); } void SQLExecutor::multiSetSimple() { std::string funct = "multiSetSimple()"; std::multiset lastNames; std::multiset firstNames; std::multiset addresses; std::multiset ages; std::string tableName("Person"); lastNames.insert("LN1"); lastNames.insert("LN2"); firstNames.insert("FN1"); firstNames.insert("FN2"); addresses.insert("ADDR1"); addresses.insert("ADDR2"); ages.insert(1); ages.insert(2); int count = 0; std::string result; try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastNames), use(firstNames), use(addresses), use(ages), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::multiset lastNamesR; std::multiset firstNamesR; std::multiset addressesR; std::multiset agesR; try { *_pSession << "SELECT * FROM Person", into(lastNamesR), into(firstNamesR), into(addressesR), into(agesR), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ages.size() == agesR.size()); assert (lastNames.size() == lastNamesR.size()); assert (firstNames.size() == firstNamesR.size()); assert (addresses.size() == addressesR.size()); } void SQLExecutor::multiSetComplex() { std::string funct = "multiSetComplex()"; std::multiset people; Person p1("LN1", "FN1", "ADDR1", 1); people.insert(p1); people.insert(p1); people.insert(p1); people.insert(p1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(p2); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 5); std::multiset result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result.size() == people.size()); } void SQLExecutor::mapComplex() { std::string funct = "mapComplex()"; std::map people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN2", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::map result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result == people); } void SQLExecutor::mapComplexUnique() { std::string funct = "mapComplexUnique()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN2", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 5); std::map result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result.size() == 2); } void SQLExecutor::multiMapComplex() { std::string funct = "multiMapComplex()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN2", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 5); std::multimap result; try { *_pSession << "SELECT * FROM Person", into(result), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result.size() == people.size()); } void SQLExecutor::selectIntoSingle() { std::string funct = "selectIntoSingle()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), limit(1), now; }// will return 1 object into one single result catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result == p1); } void SQLExecutor::selectIntoSingleStep() { std::string funct = "selectIntoSingleStep()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; Statement stmt = (*_pSession << "SELECT * FROM Person", into(result), limit(1)); stmt.execute(); assert (result == p1); assert (!stmt.done()); stmt.execute(); assert (result == p2); assert (stmt.done()); } void SQLExecutor::selectIntoSingleFail() { std::string funct = "selectIntoSingleFail()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), limit(2, true), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), limit(1, true), now; // will fail now fail("hardLimit is set: must fail"); } catch(Poco::Data::LimitException&) { } } void SQLExecutor::lowerLimitOk() { std::string funct = "lowerLimitOk()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(2), now; // will return 2 objects into one single result but only room for one! fail("Not enough space for results"); } catch(Poco::Exception&) { } } void SQLExecutor::singleSelect() { std::string funct = "singleSelect()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; Statement stmt = (*_pSession << "SELECT * FROM Person", into(result), limit(1)); stmt.execute(); assert (result == p1); assert (!stmt.done()); stmt.execute(); assert (result == p2); assert (stmt.done()); } void SQLExecutor::lowerLimitFail() { std::string funct = "lowerLimitFail()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(3), now; // will fail fail("should fail. not enough data"); } catch(Poco::Exception&) { } } void SQLExecutor::combinedLimits() { std::string funct = "combinedLimits()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::vector result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(2), upperLimit(2), now; }// will return 2 objects catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result.size() == 2); assert (result[0] == p1); assert (result[1] == p2); } void SQLExecutor::ranges() { std::string funct = "range()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); std::vector result; try { *_pSession << "SELECT * FROM Person", into(result), range(2, 2), now; }// will return 2 objects catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (result.size() == 2); assert (result[0] == p1); assert (result[1] == p2); } void SQLExecutor::combinedIllegalLimits() { std::string funct = "combinedIllegalLimits()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), lowerLimit(3), upperLimit(2), now; fail("lower > upper is not allowed"); } catch(LimitException&) { } } void SQLExecutor::illegalRange() { std::string funct = "illegalRange()"; std::multimap people; Person p1("LN1", "FN1", "ADDR1", 1); Person p2("LN2", "FN2", "ADDR2", 2); people.insert(std::make_pair("LN1", p1)); people.insert(std::make_pair("LN1", p2)); try { *_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(people), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 2); Person result; try { *_pSession << "SELECT * FROM Person", into(result), range(3, 2), now; fail("lower > upper is not allowed"); } catch(LimitException&) { } } void SQLExecutor::emptyDB() { std::string funct = "emptyDB()"; int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 0); Person result; Statement stmt = (*_pSession << "SELECT * FROM Person", into(result), limit(1)); stmt.execute(); assert (result.firstName.empty()); assert (stmt.done()); } void SQLExecutor::blob(int bigSize, const std::string& blobPlaceholder) { std::string funct = "blob()"; std::string lastName("lastname"); std::string firstName("firstname"); std::string address("Address"); Poco::Data::BLOB img("0123456789", 10); int count = 0; try { *_pSession << format("INSERT INTO Person VALUES (?,?,?,%s)", blobPlaceholder), use(lastName), use(firstName), use(address), use(img), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 1); Poco::Data::BLOB res; assert (res.size() == 0); try { *_pSession << "SELECT Image FROM Person", into(res), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (res == img); Poco::Data::BLOB big; std::vector v(bigSize, 'x'); big.assignRaw(&v[0], v.size()); assert (big.size() == bigSize); try { *_pSession << "DELETE FROM Person", now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << format("INSERT INTO Person VALUES (?,?,?,%s)", blobPlaceholder), use(lastName), use(firstName), use(address), use(big), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { *_pSession << "SELECT Image FROM Person", into(res), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (res == big); } void SQLExecutor::blobStmt() { std::string funct = "blobStmt()"; std::string lastName("lastname"); std::string firstName("firstname"); std::string address("Address"); Poco::Data::BLOB blob("0123456789", 10); int count = 0; Statement ins = (*_pSession << "INSERT INTO Person VALUES (?,?,?,?)", use(lastName), use(firstName), use(address), use(blob)); ins.execute(); try { *_pSession << "SELECT COUNT(*) FROM Person", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (count == 1); Poco::Data::BLOB res; poco_assert (res.size() == 0); Statement stmt = (*_pSession << "SELECT Image FROM Person", into(res)); try { stmt.execute(); } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } poco_assert (res == blob); } void SQLExecutor::tuples() { typedef Tuple TupleType; std::string funct = "tuples()"; TupleType t(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); try { *_pSession << "INSERT INTO Tuples VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", use(t), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } TupleType ret(-10,-11,-12,-13,-14,-15,-16,-17,-18,-19); assert (ret != t); try { *_pSession << "SELECT * FROM Tuples", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ret == t); } void SQLExecutor::tupleVector() { typedef Tuple TupleType; std::string funct = "tupleVector()"; TupleType t(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); Tuple t10(10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29); TupleType t100(100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119); std::vector v; v.push_back(t); v.push_back(t10); v.push_back(t100); try { *_pSession << "INSERT INTO Tuples VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", use(v), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } int count = 0; try { *_pSession << "SELECT COUNT(*) FROM Tuples", into(count), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (v.size() == count); std::vector > ret; try { *_pSession << "SELECT * FROM Tuples", into(ret), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } assert (ret == v); } void SQLExecutor::internalExtraction() { std::string funct = "internalExtraction()"; std::vector > v; v.push_back(Tuple(1, 1.5f, "3")); v.push_back(Tuple(2, 2.5f, "4")); v.push_back(Tuple(3, 3.5f, "5")); v.push_back(Tuple(4, 4.5f, "6")); try { *_pSession << "INSERT INTO Vectors VALUES (?,?,?)", use(v), now; } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } try { Statement stmt = (*_pSession << "SELECT * FROM Vectors", now); RecordSet rset(stmt); assert (3 == rset.columnCount()); assert (4 == rset.rowCount()); int curVal = 3; do { assert (rset["str0"] == curVal); ++curVal; } while (rset.moveNext()); rset.moveFirst(); assert (rset["str0"] == "3"); rset.moveLast(); assert (rset["str0"] == "6"); RecordSet rset2(rset); assert (3 == rset2.columnCount()); assert (4 == rset2.rowCount()); int i = rset.value(0,0); assert (1 == i); std::string s = rset.value(0,0); assert ("1" == s); int a = rset.value(0,2); assert (3 == a); try { double d = rset.value(1,1); assert (2.5 == d); } catch (BadCastException&) { float f = rset.value(1,1); assert (2.5 == f); } s = rset.value(2,2); assert ("5" == s); i = rset.value("str0", 2); assert (5 == i); const Column& col = rset.column(0); Column::Iterator it = col.begin(); Column::Iterator end = col.end(); for (int i = 1; it != end; ++it, ++i) assert (*it == i); rset = (*_pSession << "SELECT COUNT(*) AS cnt FROM Vectors", now); //various results for COUNT(*) are received from different drivers try { //this is what most drivers will return int i = rset.value(0,0); assert (4 == i); } catch(BadCastException&) { try { //this is for Oracle double i = rset.value(0,0); assert (4 == int(i)); } catch(BadCastException&) { try { //this is for PostgreSQL Poco::Int64 big = rset.value(0,0); assert (4 == big); } catch(BadCastException&) { //this is for SQLite (on Linux) std::string str = rset.value(0,0); assert ("4" == str); } } } s = rset.value("cnt", 0).convert(); assert ("4" == s); try { const Column& col1 = rset.column(100); fail ("must fail"); } catch (RangeException&) { } try { rset.value(0,0); fail ("must fail"); } catch (BadCastException&) { } stmt = (*_pSession << "DELETE FROM Vectors", now); rset = stmt; try { const Column& col1 = rset.column(0); fail ("must fail"); } catch (RangeException&) { } } catch(ConnectionException& ce){ std::cout << ce.toString() << std::endl; fail (funct); } catch(StatementException& se){ std::cout << se.toString() << std::endl; fail (funct); } } poco-1.3.6p1-all/Data/ODBC/testsuite/src/SQLExecutor.h0000644000076500001200000001056711313735447023016 0ustar guenteradmin00000000000000// // SQLExecutor.h // // $Id: //poco/1.3/Data/ODBC/testsuite/src/SQLExecutor.h#6 $ // // Definition of the SQLExecutor class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef SQLExecutor_INCLUDED #define SQLExecutor_INCLUDED #include "Poco/Data/ODBC/ODBC.h" #include "Poco/Data/Session.h" #include "Poco/Data/ODBC/Utility.h" #include "Poco/Data/ODBC/ODBCException.h" #define poco_odbc_check_env(r, h) \ if (!SQL_SUCCEEDED(r)) \ { \ Poco::Data::ODBC::EnvironmentException ee(h); \ std::cout << ee.toString() << std::endl; \ } \ assert (SQL_SUCCEEDED(r)) #define poco_odbc_check_dbc(r, h) \ if (!SQL_SUCCEEDED(r)) \ { \ Poco::Data::ODBC::ConnectionException ce(h); \ std::cout << ce.toString() << std::endl; \ } \ assert (SQL_SUCCEEDED(r)) #define poco_odbc_check_stmt(r, h) \ if (!SQL_SUCCEEDED(r)) \ { \ Poco::Data::ODBC::StatementException se(h); \ std::cout << se.toString() << std::endl; \ } \ assert (SQL_SUCCEEDED(r)) #define poco_odbc_check_desc(r, h) \ if (!SQL_SUCCEEDED(r)) \ { \ Poco::Data::ODBC::DescriptorException de(h); \ std::cout << de.toString() << std::endl; \ } \ assert (SQL_SUCCEEDED(r)) class SQLExecutor: public CppUnit::TestCase { public: enum DataBinding { PB_IMMEDIATE, PB_AT_EXEC }; enum DataExtraction { DE_MANUAL, DE_BOUND }; SQLExecutor(const std::string& name, Poco::Data::Session* _pSession); ~SQLExecutor(); void bareboneODBCTest(const std::string& dbConnString, const std::string& tableCreateString, DataBinding bindMode, DataExtraction extractMode, bool doTime=true, const std::string& blobPlaceholder="?"); /// This function uses "bare bone" ODBC API calls (i.e. calls are not /// "wrapped" in PocoData framework structures). /// The purpose of the function is to verify that driver behaves /// correctly as well as to determine its capabilities /// (e.g. SQLGetData() restrictions relaxation policy, if any). /// If this test passes, subsequent tests failures are likely ours. void simpleAccess(); void complexType(); void complexTypeTuple(); void simpleAccessVector(); void complexTypeVector(); void insertVector(); void insertEmptyVector(); void insertSingleBulk(); void insertSingleBulkVec(); void limits(); void limitOnce(); void limitPrepare(); void limitZero(); void prepare(); void setSimple(); void setComplex(); void setComplexUnique(); void multiSetSimple(); void multiSetComplex(); void mapComplex(); void mapComplexUnique(); void multiMapComplex(); void selectIntoSingle(); void selectIntoSingleStep(); void selectIntoSingleFail(); void lowerLimitOk(); void lowerLimitFail(); void combinedLimits(); void combinedIllegalLimits(); void ranges(); void illegalRange(); void singleSelect(); void emptyDB(); void blob(int bigSize = 1024, const std::string& blobPlaceholder = "?"); void blobStmt(); void bools(); void floats(); void doubles(); void tuples(); void tupleVector(); void internalExtraction(); private: Poco::Data::Session* _pSession; }; #endif // SQLExecutor_INCLUDED poco-1.3.6p1-all/Data/ODBC/testsuite/src/WinDriver.cpp0000644000076500001200000000345211313735447023077 0ustar guenteradmin00000000000000// // WinDriver.cpp // // $Id: //poco/1.3/Data/ODBC/testsuite/src/WinDriver.cpp#2 $ // // Windows test driver for Poco ODBC. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "WinTestRunner/WinTestRunner.h" #include "ODBCTestSuite.h" class TestDriver: public CppUnit::WinTestRunnerApp { void TestMain() { CppUnit::WinTestRunner runner; runner.addTest(ODBCTestSuite::suite()); runner.run(); } }; TestDriver theDriver; poco-1.3.6p1-all/Data/ODBC/testsuite/TestSuite.vmsbuild0000644000076500001200000000021111313735447023361 0ustar guenteradmin00000000000000# # TestSuite.vmsbuild # # $Id: //poco/1.3/Data/ODBC/testsuite/TestSuite.vmsbuild#1 $ # EXE=TestRunner SQLiteTestSuite Driver SQLiteTest poco-1.3.6p1-all/Data/ODBC/testsuite/TestSuite_VS71.vcproj0000644000076500001200000002260111313735447023626 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/ODBC/testsuite/TestSuite_VS80.vcproj0000644000076500001200000002470511313735447023635 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/ODBC/testsuite/TestSuite_vs90.vcproj0000644000076500001200000002455511313735447023741 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/0000755000076500001200000000000011313735447016573 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/Binding/0000755000076500001200000000000011313735446020144 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/Binding/Binding_vs71.vcproj0000644000076500001200000000743411313735446023633 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/Binding/Binding_vs80.vcproj0000644000076500001200000001032611313735446023625 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/Binding/Binding_vs90.vcproj0000644000076500001200000001033011313735446023621 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/Binding/Makefile0000644000076500001200000000046311313735446021607 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/samples/Binding/Makefile#2 $ # # Makefile for Poco Data Binding sample # include $(POCO_BASE)/build/rules/global objects = Binding target = Binding target_version = 1 target_libs = PocoSQLite PocoData PocoFoundation include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Data/samples/Binding/src/0000755000076500001200000000000011313735446020733 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/Binding/src/Binding.cpp0000644000076500001200000000630311313735446023013 0ustar guenteradmin00000000000000// // Binding.cpp // // $Id: //poco/1.3/Data/samples/Binding/src/Binding.cpp#7 $ // // This sample demonstrates the Data library. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "Poco/SharedPtr.h" #include "Poco/Data/SessionFactory.h" #include "Poco/Data/Session.h" #include "Poco/Data/SQLite/Connector.h" #include #include using namespace Poco::Data; struct Person { std::string name; std::string address; int age; }; int main(int argc, char** argv) { // register SQLite connector Poco::Data::SQLite::Connector::registerConnector(); // create a session Session session("SQLite", "sample.db"); // drop sample table, if it exists session << "DROP TABLE IF EXISTS Person", now; // (re)create table session << "CREATE TABLE Person (Name VARCHAR(30), Address VARCHAR, Age INTEGER(3))", now; // insert some rows Person person = { "Bart Simpson", "Springfield", 12 }; Statement insert(session); insert << "INSERT INTO Person VALUES(?, ?, ?)", use(person.name), use(person.address), use(person.age); insert.execute(); person.name = "Lisa Simpson"; person.address = "Springfield"; person.age = 10; insert.execute(); // a simple query Statement select(session); select << "SELECT Name, Address, Age FROM Person", into(person.name), into(person.address), into(person.age), range(0, 1); // iterate over result set one row at a time while (!select.done()) { select.execute(); std::cout << person.name << " " << person.address << " " << person.age << std::endl; } // another query - store the result in a container std::vector names; session << "SELECT Name FROM Person", into(names), now; for (std::vector::const_iterator it = names.begin(); it != names.end(); ++it) { std::cout << *it << std::endl; } return 0; } poco-1.3.6p1-all/Data/samples/Makefile0000644000076500001200000000044411313735446020234 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/samples/Makefile#1 $ # # Makefile for Poco Data Samples # .PHONY: projects clean all: projects projects: $(MAKE) -C Binding $(MAKECMDGOALS) $(MAKE) -C TypeHandler $(MAKECMDGOALS) $(MAKE) -C RecordSet $(MAKECMDGOALS) $(MAKE) -C Tuple $(MAKECMDGOALS) poco-1.3.6p1-all/Data/samples/RecordSet/0000755000076500001200000000000011313735447020465 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/RecordSet/Makefile0000644000076500001200000000047411313735447022132 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/samples/RecordSet/Makefile#2 $ # # Makefile for Poco Data RecordSet sample # include $(POCO_BASE)/build/rules/global objects = RecordSet target = RecordSet target_version = 1 target_libs = PocoSQLite PocoData PocoFoundation include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Data/samples/RecordSet/RecordSet_vs71.vcproj0000644000076500001200000000744611313735447024477 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/RecordSet/RecordSet_vs80.vcproj0000644000076500001200000001034011313735447024462 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/RecordSet/RecordSet_vs90.vcproj0000644000076500001200000001034211313735447024465 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/RecordSet/src/0000755000076500001200000000000011313735447021254 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/RecordSet/src/RecordSet.cpp0000644000076500001200000000575611313735447023667 0ustar guenteradmin00000000000000// // RecordSet.cpp // // $Id: //poco/1.3/Data/samples/RecordSet/src/RecordSet.cpp#3 $ // // This sample demonstrates the Data library. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "Poco/SharedPtr.h" #include "Poco/Data/SessionFactory.h" #include "Poco/Data/Session.h" #include "Poco/Data/RecordSet.h" #include "Poco/Data/Column.h" #include "Poco/Data/SQLite/Connector.h" #include using namespace Poco::Data; struct Person { std::string name; std::string address; int age; }; int main(int argc, char** argv) { // register SQLite connector Poco::Data::SQLite::Connector::registerConnector(); // create a session Session session("SQLite", "sample.db"); // drop sample table, if it exists session << "DROP TABLE IF EXISTS Person", now; // (re)create table session << "CREATE TABLE Person (Name VARCHAR(30), Address VARCHAR, Age INTEGER(3))", now; // insert some rows session << "INSERT INTO Person VALUES('Bart Simpson', 'Springfield', 12)", now; session << "INSERT INTO Person VALUES('Lisa Simpson', 'Springfield', 10)", now; // a simple query Statement select(session); select << "SELECT * FROM Person"; select.execute(); // create a RecordSet RecordSet rs(select); std::size_t cols = rs.columnCount(); // print all column names for (std::size_t col = 0; col < cols; ++col) { std::cout << rs.columnName(col) << std::endl; } // iterate over all rows and columns bool more = rs.moveFirst(); while (more) { for (std::size_t col = 0; col < cols; ++col) { std::cout << rs[col].convert() << " "; } std::cout << std::endl; more = rs.moveNext(); } return 0; } poco-1.3.6p1-all/Data/samples/samples_vs71.sln0000644000076500001200000000515711313735446021644 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Binding", "Binding\Binding_vs71.vcproj", "{54BCEDA8-C241-4DCF-AEAD-6177F115B0D0}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TypeHandler", "TypeHandler\TypeHandler_vs71.vcproj", "{822AEE4A-48B6-4B45-AB04-5C3C21C365C5}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RecordSet", "RecordSet\RecordSet_vs71.vcproj", "{56F66D36-F11E-4AA1-AD37-4518A253059D}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Tuple", "Tuple\Tuple_vs71.vcproj", "{08C81227-3322-4DBD-A83F-55CCC933A5F7}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {54BCEDA8-C241-4DCF-AEAD-6177F115B0D0}.debug_shared.ActiveCfg = debug_shared|Win32 {54BCEDA8-C241-4DCF-AEAD-6177F115B0D0}.debug_shared.Build.0 = debug_shared|Win32 {54BCEDA8-C241-4DCF-AEAD-6177F115B0D0}.release_shared.ActiveCfg = release_shared|Win32 {54BCEDA8-C241-4DCF-AEAD-6177F115B0D0}.release_shared.Build.0 = release_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.debug_shared.ActiveCfg = debug_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.debug_shared.Build.0 = debug_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.release_shared.ActiveCfg = release_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.release_shared.Build.0 = release_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.debug_shared.ActiveCfg = debug_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.debug_shared.Build.0 = debug_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.release_shared.ActiveCfg = release_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.release_shared.Build.0 = release_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.debug_shared.ActiveCfg = debug_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.debug_shared.Build.0 = debug_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.release_shared.ActiveCfg = release_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.release_shared.Build.0 = release_shared|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/samples/samples_vs80.sln0000644000076500001200000000471511313735446021643 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Binding", "Binding\Binding_vs80.vcproj", "{F2972327-DCA7-49BB-B55D-66C554CF1205}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TypeHandler", "TypeHandler\TypeHandler_vs80.vcproj", "{822AEE4A-48B6-4B45-AB04-5C3C21C365C5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RecordSet", "RecordSet\RecordSet_vs80.vcproj", "{56F66D36-F11E-4AA1-AD37-4518A253059D}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Tuple", "Tuple\Tuple_vs80.vcproj", "{08C81227-3322-4DBD-A83F-55CCC933A5F7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F2972327-DCA7-49BB-B55D-66C554CF1205}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {F2972327-DCA7-49BB-B55D-66C554CF1205}.debug_shared|Win32.Build.0 = debug_shared|Win32 {F2972327-DCA7-49BB-B55D-66C554CF1205}.release_shared|Win32.ActiveCfg = release_shared|Win32 {F2972327-DCA7-49BB-B55D-66C554CF1205}.release_shared|Win32.Build.0 = release_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.release_shared|Win32.Build.0 = release_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.debug_shared|Win32.Build.0 = debug_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.release_shared|Win32.ActiveCfg = release_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.release_shared|Win32.Build.0 = release_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.debug_shared|Win32.Build.0 = debug_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.release_shared|Win32.ActiveCfg = release_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.release_shared|Win32.Build.0 = release_shared|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/samples/samples_vs90.sln0000644000076500001200000000471611313735446021645 0ustar guenteradmin00000000000000 Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Binding", "Binding\Binding_vs90.vcproj", "{F2972327-DCA7-49BB-B55D-66C554CF1205}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TypeHandler", "TypeHandler\TypeHandler_vs90.vcproj", "{822AEE4A-48B6-4B45-AB04-5C3C21C365C5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RecordSet", "RecordSet\RecordSet_vs90.vcproj", "{56F66D36-F11E-4AA1-AD37-4518A253059D}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Tuple", "Tuple\Tuple_vs90.vcproj", "{08C81227-3322-4DBD-A83F-55CCC933A5F7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F2972327-DCA7-49BB-B55D-66C554CF1205}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {F2972327-DCA7-49BB-B55D-66C554CF1205}.debug_shared|Win32.Build.0 = debug_shared|Win32 {F2972327-DCA7-49BB-B55D-66C554CF1205}.release_shared|Win32.ActiveCfg = release_shared|Win32 {F2972327-DCA7-49BB-B55D-66C554CF1205}.release_shared|Win32.Build.0 = release_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {822AEE4A-48B6-4B45-AB04-5C3C21C365C5}.release_shared|Win32.Build.0 = release_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.debug_shared|Win32.Build.0 = debug_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.release_shared|Win32.ActiveCfg = release_shared|Win32 {56F66D36-F11E-4AA1-AD37-4518A253059D}.release_shared|Win32.Build.0 = release_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.debug_shared|Win32.Build.0 = debug_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.release_shared|Win32.ActiveCfg = release_shared|Win32 {08C81227-3322-4DBD-A83F-55CCC933A5F7}.release_shared|Win32.Build.0 = release_shared|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/samples/Tuple/0000755000076500001200000000000011313735447017664 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/Tuple/Makefile0000644000076500001200000000045411313735447021327 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/samples/Tuple/Makefile#2 $ # # Makefile for Poco Data Tuple sample # include $(POCO_BASE)/build/rules/global objects = Tuple target = Tuple target_version = 1 target_libs = PocoSQLite PocoData PocoFoundation include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Data/samples/Tuple/src/0000755000076500001200000000000011313735447020453 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/Tuple/src/Tuple.cpp0000644000076500001200000000552511313735447022257 0ustar guenteradmin00000000000000// // Tuple.cpp // // $Id: //poco/1.3/Data/samples/Tuple/src/Tuple.cpp#4 $ // // This sample demonstrates the Data library. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "Poco/SharedPtr.h" #include "Poco/Tuple.h" #include "Poco/Data/SessionFactory.h" #include "Poco/Data/Session.h" #include "Poco/Data/SQLite/Connector.h" #include #include using namespace Poco::Data; int main(int argc, char** argv) { typedef Poco::Tuple Person; typedef std::vector People; // register SQLite connector Poco::Data::SQLite::Connector::registerConnector(); // create a session Session session("SQLite", "sample.db"); // drop sample table, if it exists session << "DROP TABLE IF EXISTS Person", now; // (re)create table session << "CREATE TABLE Person (Name VARCHAR(30), Address VARCHAR, Age INTEGER(3))", now; // insert some rows People people; people.push_back(Person("Bart Simpson", "Springfield", 12)); people.push_back(Person("Lisa Simpson", "Springfield", 10)); Statement insert(session); insert << "INSERT INTO Person VALUES(?, ?, ?)", use(people), now; people.clear(); // a simple query Statement select(session); select << "SELECT Name, Address, Age FROM Person", into(people), now; for (People::const_iterator it = people.begin(); it != people.end(); ++it) { std::cout << "Name: " << it->get<0>() << ", Address: " << it->get<1>() << ", Age: " << it->get<2>() < poco-1.3.6p1-all/Data/samples/Tuple/Tuple_vs80.vcproj0000644000076500001200000001031411313735447023061 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/Tuple/Tuple_vs90.vcproj0000644000076500001200000001031611313735447023064 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/TypeHandler/0000755000076500001200000000000011313735447021012 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/TypeHandler/Makefile0000644000076500001200000000050411313735447022451 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/samples/TypeHandler/Makefile#2 $ # # Makefile for Poco Data TypeHandler sample # include $(POCO_BASE)/build/rules/global objects = TypeHandler target = TypeHandler target_version = 1 target_libs = PocoSQLite PocoData PocoFoundation include $(POCO_BASE)/build/rules/exec poco-1.3.6p1-all/Data/samples/TypeHandler/src/0000755000076500001200000000000011313735447021601 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/samples/TypeHandler/src/TypeHandler.cpp0000644000076500001200000001054111313735447024525 0ustar guenteradmin00000000000000// // TypeHandler.cpp // // $Id: //poco/1.3/Data/samples/TypeHandler/src/TypeHandler.cpp#5 $ // // This sample demonstrates the Data library. // // Copyright (c) 2008, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "Poco/SharedPtr.h" #include "Poco/Data/SessionFactory.h" #include "Poco/Data/Session.h" #include "Poco/Data/TypeHandler.h" #include "Poco/Data/SQLite/Connector.h" #include #include using namespace Poco::Data; struct Person { std::string name; std::string address; int age; }; namespace Poco { namespace Data { template <> class TypeHandler /// Defining a specialization of TypeHandler for Person allows us /// to use the Person struct in use and into clauses. { public: static std::size_t size() { return 3; } static void bind(std::size_t pos, const Person& person, AbstractBinder* pBinder) { TypeHandler::bind(pos++, person.name, pBinder); TypeHandler::bind(pos++, person.address, pBinder); TypeHandler::bind(pos++, person.age, pBinder); } static void extract(std::size_t pos, Person& person, const Person& deflt, AbstractExtractor* pExtr) { TypeHandler::extract(pos++, person.name, deflt.name, pExtr); TypeHandler::extract(pos++, person.address, deflt.address, pExtr); TypeHandler::extract(pos++, person.age, deflt.age, pExtr); } static void prepare(std::size_t pos, const Person& person, AbstractPreparation* pPrep) { TypeHandler::prepare(pos++, person.name, pPrep); TypeHandler::prepare(pos++, person.address, pPrep); TypeHandler::prepare(pos++, person.age, pPrep); } }; } } // namespace Poco::Data int main(int argc, char** argv) { // register SQLite connector Poco::Data::SQLite::Connector::registerConnector(); // create a session Session session("SQLite", "sample.db"); // drop sample table, if it exists session << "DROP TABLE IF EXISTS Person", now; // (re)create table session << "CREATE TABLE Person (Name VARCHAR(30), Address VARCHAR, Age INTEGER(3))", now; // insert some rows Person person = { "Bart Simpson", "Springfield", 12 }; Statement insert(session); insert << "INSERT INTO Person VALUES(?, ?, ?)", use(person); insert.execute(); person.name = "Lisa Simpson"; person.address = "Springfield"; person.age = 10; insert.execute(); // a simple query Statement select(session); select << "SELECT Name, Address, Age FROM Person", into(person), range(0, 1); // iterate over result set one row at a time while (!select.done()) { select.execute(); std::cout << person.name << " " << person.address << " " << person.age << std::endl; } // another query - store the result in a container std::vector persons; session << "SELECT Name, Address, Age FROM Person", into(persons), now; for (std::vector::const_iterator it = persons.begin(); it != persons.end(); ++it) { std::cout << it->name << " " << it->address << " " << it->age << std::endl; } return 0; } poco-1.3.6p1-all/Data/samples/TypeHandler/TypeHandler_vs71.vcproj0000644000076500001200000000746011313735447025345 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/TypeHandler/TypeHandler_vs80.vcproj0000644000076500001200000001035211313735447025337 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/samples/TypeHandler/TypeHandler_vs90.vcproj0000644000076500001200000001035411313735447025342 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/SQLite/0000755000076500001200000000000011313735447016270 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/SQLite/include/0000755000076500001200000000000011313735447017713 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/SQLite/include/Poco/0000755000076500001200000000000011313735447020613 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/0000755000076500001200000000000011313735447021464 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/0000755000076500001200000000000011313735447022625 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/Binder.h0000644000076500001200000001117111313735447024202 0ustar guenteradmin00000000000000// // Binder.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/Binder.h#3 $ // // Library: Data/SQLite // Package: SQLite // Module: Binder // // Definition of the Binder class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_SQLite_Binder_INCLUDED #define DataConnectors_SQLite_Binder_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/AbstractBinder.h" #include "Poco/Any.h" struct sqlite3_stmt; namespace Poco { namespace Data { namespace SQLite { class SQLite_API Binder: public Poco::Data::AbstractBinder /// Binds placeholders in the sql query to the provided values. Performs data types mapping. { public: Binder(sqlite3_stmt* pStmt); /// Creates the Binder. ~Binder(); /// Destroys the Binder. void bind(std::size_t pos, const Poco::Int8 &val); /// Binds an Int8. void bind(std::size_t pos, const Poco::UInt8 &val); /// Binds an UInt8. void bind(std::size_t pos, const Poco::Int16 &val); /// Binds an Int16. void bind(std::size_t pos, const Poco::UInt16 &val); /// Binds an UInt16. void bind(std::size_t pos, const Poco::Int32 &val); /// Binds an Int32. void bind(std::size_t pos, const Poco::UInt32 &val); /// Binds an UInt32. void bind(std::size_t pos, const Poco::Int64 &val); /// Binds an Int64. void bind(std::size_t pos, const Poco::UInt64 &val); /// Binds an UInt64. void bind(std::size_t pos, const bool &val); /// Binds a boolean. void bind(std::size_t pos, const float &val); /// Binds a float. void bind(std::size_t pos, const double &val); /// Binds a double. void bind(std::size_t pos, const char &val); /// Binds a single character. void bind(std::size_t pos, const char* const &pVal); /// Binds a const char ptr. void bind(std::size_t pos, const std::string& val); /// Binds a string. void bind(std::size_t pos, const Poco::Data::BLOB& val); /// Binds a BLOB. private: void checkReturn(int rc); /// Checks the SQLite return code and throws an appropriate exception. private: sqlite3_stmt* _pStmt; }; // // inlines // inline void Binder::bind(std::size_t pos, const Poco::Int8 &val) { Poco::Int32 tmp = val; bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const Poco::UInt8 &val) { Poco::Int32 tmp = val; bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const Poco::Int16 &val) { Poco::Int32 tmp = val; bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const Poco::UInt16 &val) { Poco::Int32 tmp = val; bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const Poco::UInt32 &val) { Poco::Int32 tmp = static_cast(val); bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const Poco::UInt64 &val) { Poco::Int64 tmp = static_cast(val); bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const bool &val) { Poco::Int32 tmp = (val ? 1 : 0); bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const float &val) { double tmp = val; bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const char &val) { Poco::Int32 tmp = val; bind(pos, tmp); } inline void Binder::bind(std::size_t pos, const char* const &pVal) { std::string val(pVal); bind(pos, val); } } } } // namespace Poco::Data::SQLite #endif // DataConnectors_SQLite_Binder_INCLUDED poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/Connector.h0000644000076500001200000000612711313735447024736 0ustar guenteradmin00000000000000// // Connector.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/Connector.h#4 $ // // Library: Data/SQLite // Package: SQLite // Module: Connector // // Definition of the Connector class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_SQLite_Connector_INCLUDED #define DataConnectors_SQLite_Connector_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/Connector.h" namespace Poco { namespace Data { namespace SQLite { class SQLite_API Connector: public Poco::Data::Connector /// Connector instantiates SqLite SessionImpl objects. { public: static const std::string KEY; /// Keyword for creating SQLite sessions ("SQLite"). Connector(); /// Creates the Connector. ~Connector(); /// Destroys the Connector. Poco::AutoPtr createSession(const std::string& connectionString); /// Creates a SQLite SessionImpl object and initializes it with the given connectionString. static void registerConnector(); /// Registers the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory. static void unregisterConnector(); /// Unregisters the Connector under the Keyword Connector::KEY at the Poco::Data::SessionFactory. static void enableSharedCache(bool flag = true); /// Enables or disables SQlite shared cache mode /// (see http://www.sqlite.org/sharedcache.html for a discussion). static void enableSoftHeapLimit(int limit); /// Sets a soft upper limit to the amount of memory allocated /// by SQLite. For more information, please see the SQLite /// sqlite_soft_heap_limit() function (http://www.sqlite.org/c3ref/soft_heap_limit.html). }; } } } // namespace Poco::Data::SQLite #endif // DataConnectors_SQLite_Connector_INCLUDED poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/Extractor.h0000644000076500001200000000704411313735447024756 0ustar guenteradmin00000000000000// // Extractor.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/Extractor.h#3 $ // // Library: Data/SQLite // Package: SQLite // Module: Extractor // // Definition of the Extractor class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_SQLite_Extractor_INCLUDED #define DataConnectors_SQLite_Extractor_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/AbstractExtractor.h" #include "Poco/Any.h" struct sqlite3_stmt; namespace Poco { namespace Data { namespace SQLite { class SQLite_API Extractor: public Poco::Data::AbstractExtractor /// Extracts and converts data values form the result row returned by SQLite. /// If NULL is received, the incoming val value is not changed and false is returned { public: Extractor(sqlite3_stmt* pStmt); /// Creates the Extractor. ~Extractor(); /// Destroys the Extractor. bool extract(std::size_t pos, Poco::Int8& val); /// Extracts an Int8. bool extract(std::size_t pos, Poco::UInt8& val); /// Extracts an UInt8. bool extract(std::size_t pos, Poco::Int16& val); /// Extracts an Int16. bool extract(std::size_t pos, Poco::UInt16& val); /// Extracts an UInt16. bool extract(std::size_t pos, Poco::Int32& val); /// Extracts an Int32. bool extract(std::size_t pos, Poco::UInt32& val); /// Extracts an UInt32. bool extract(std::size_t pos, Poco::Int64& val); /// Extracts an Int64. bool extract(std::size_t pos, Poco::UInt64& val); /// Extracts an UInt64. bool extract(std::size_t pos, bool& val); /// Extracts a boolean. bool extract(std::size_t pos, float& val); /// Extracts a float. bool extract(std::size_t pos, double& val); /// Extracts a double. bool extract(std::size_t pos, char& val); /// Extracts a single character. bool extract(std::size_t pos, std::string& val); /// Extracts a string. bool extract(std::size_t pos, Poco::Data::BLOB& val); /// Extracts a BLOB. bool extract(std::size_t pos, Poco::Any& val); /// Extracts an Any. private: bool isNull(std::size_t pos); /// Returns true if a non null value can be extracted sqlite3_stmt* _pStmt; }; } } } // namespace Poco::Data::SQLite #endif // DataConnectors_SQLite_Extractor_INCLUDED poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/SessionImpl.h0000644000076500001200000001121411313735447025242 0ustar guenteradmin00000000000000// // SessionImpl.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/SessionImpl.h#8 $ // // Library: Data/SQLite // Package: SQLite // Module: SessionImpl // // Definition of the SessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_SQLite_SessionImpl_INCLUDED #define DataConnectors_SQLite_SessionImpl_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/SQLite/Binder.h" #include "Poco/Data/AbstractSessionImpl.h" #include "Poco/SharedPtr.h" struct sqlite3; struct sqlite3_stmt; namespace Poco { namespace Data { namespace SQLite { class SQLite_API SessionImpl: public Poco::Data::AbstractSessionImpl /// Implements SessionImpl interface. /// /// The following properties are supported: /// * transactionMode: "DEFERRED", "IMMEDIATE" or "EXCLUSIVE" /// * maxRetryAttempts: maximum number of attemptes to retry an operation if /// database is locked or busy. Between retry attempts, sleep for a random /// time. /// * minRetrySleep: the minimum time (in milliseconds) waited between two retry attempts. /// * maxRetrySleep: the maximum time (in milliseconds) waited between two retry attempts. /// /// Notes: For automatic retries to work, you should start every transaction that /// at one point will write to the database with IMMEDIATE or EXCLUSIVE mode. { public: enum { DEFAULT_MAX_RETRY_ATTEMPTS = 0, /// Default maximum number of attempts to retry an operation if the database is locked. DEFAULT_MIN_RETRY_SLEEP = 2, /// Default minimum sleep interval (milliseconds) between retry attempts. DEFAULT_MAX_RETRY_SLEEP = 20 /// Default maximum sleep interval (milliseconds) between retry attempts. }; SessionImpl(const std::string& fileName); /// Creates the SessionImpl. Opens a connection to the database. ~SessionImpl(); /// Destroys the SessionImpl. Poco::Data::StatementImpl* createStatementImpl(); /// Returns an SQLite StatementImpl. void begin(); /// Starts a transaction. void commit(); /// Commits and ends a transaction. void rollback(); /// Aborts a transaction. void close(); /// Closes the session. bool isTransaction(); /// Returns true iff a transaction is in progress. bool isConnected(); /// Returns true iff connected, false otherwise. protected: void setTransactionMode(const std::string& prop, const Poco::Any& value); Poco::Any getTransactionMode(const std::string& prop); void setMaxRetryAttempts(const std::string& prop, const Poco::Any& value); Poco::Any getMaxRetryAttempts(const std::string& prop); void setMinRetrySleep(const std::string& prop, const Poco::Any& value); Poco::Any getMinRetrySleep(const std::string& prop); void setMaxRetrySleep(const std::string& prop, const Poco::Any& value); Poco::Any getMaxRetrySleep(const std::string& prop); private: void open(); /// Opens a connection to the Database. std::string _dbFileName; sqlite3* _pDB; std::string _transactionMode; int _maxRetryAttempts; int _minRetrySleep; int _maxRetrySleep; bool _connected; static const std::string BEGIN_TRANSACTION; static const std::string COMMIT_TRANSACTION; static const std::string ABORT_TRANSACTION; }; } } } // namespace Poco::Data::SQLite #endif // DataConnectors_SQLite_SessionImpl_INCLUDED poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/SQLite.h0000644000076500001200000000572411313735447024147 0ustar guenteradmin00000000000000// // SQLite.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/SQLite.h#3 $ // // Library: Data/SQLite // Package: SQLIte // Module: SQLite // // Basic definitions for the Poco SQLite library. // This file must be the first file included by every other SQLite // header file. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef SQLite_SQLite_INCLUDED #define SQLite_SQLite_INCLUDED #include "Poco/Foundation.h" // // The following block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the SQLite_EXPORTS // symbol defined on the command line. this symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // SQLite_API functions as being imported from a DLL, wheras this DLL sees symbols // defined with this macro as being exported. // #if defined(_WIN32) && defined(POCO_DLL) #if defined(SQLite_EXPORTS) #define SQLite_API __declspec(dllexport) #else #define SQLite_API __declspec(dllimport) #endif #endif #if !defined(SQLite_API) #define SQLite_API #endif // // Automatically link Data library. // #if defined(_MSC_VER) #if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(SQLite_EXPORTS) #if defined(POCO_DLL) #if defined(_DEBUG) #pragma comment(lib, "PocoSQLited.lib") #else #pragma comment(lib, "PocoSQLite.lib") #endif #else #if defined(_DEBUG) #pragma comment(lib, "PocoSQLitemtd.lib") #else #pragma comment(lib, "PocoSQLitemt.lib") #endif #endif #endif #endif #endif // SQLite_SQLite_INCLUDED poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/SQLiteException.h0000644000076500001200000000750011313735447026020 0ustar guenteradmin00000000000000// // SQLiteException.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/SQLiteException.h#6 $ // // Library: Data/SQLite // Package: SQLite // Module: SQLiteException // // Definition of SQLiteException. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef SQLite_SQLiteException_INCLUDED #define SQLite_SQLiteException_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/DataException.h" namespace Poco { namespace Data { namespace SQLite { POCO_DECLARE_EXCEPTION(SQLite_API, SQLiteException, Poco::Data::DataException) POCO_DECLARE_EXCEPTION(SQLite_API, InvalidSQLStatementException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, InternalDBErrorException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, DBAccessDeniedException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, ExecutionAbortedException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, LockedException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, DBLockedException, LockedException) POCO_DECLARE_EXCEPTION(SQLite_API, TableLockedException, LockedException) POCO_DECLARE_EXCEPTION(SQLite_API, NoMemoryException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, ReadOnlyException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, InterruptException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, IOErrorException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, CorruptImageException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, TableNotFoundException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, DatabaseFullException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, CantOpenDBFileException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, LockProtocolException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, SchemaDiffersException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, RowTooBigException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, ConstraintViolationException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, DataTypeMismatchException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, ParameterCountMismatchException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, InvalidLibraryUseException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, OSFeaturesMissingException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, AuthorizationDeniedException, SQLiteException) POCO_DECLARE_EXCEPTION(SQLite_API, TransactionException, SQLiteException) } } } // namespace Poco::Data::SQLite #endif poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/SQLiteStatementImpl.h0000644000076500001200000001016411313735447026650 0ustar guenteradmin00000000000000// // SQLiteStatementImpl.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/SQLiteStatementImpl.h#4 $ // // Library: Data/SQLite // Package: SQLite // Module: SQLiteStatementImpl // // Definition of the SQLiteStatementImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef DataConnectors_SQLite_SQLiteStatementImpl_INCLUDED #define DataConnectors_SQLite_SQLiteStatementImpl_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/SQLite/Binder.h" #include "Poco/Data/SQLite/Extractor.h" #include "Poco/Data/StatementImpl.h" #include "Poco/Data/MetaColumn.h" #include "Poco/SharedPtr.h" #include "Poco/Random.h" struct sqlite3; struct sqlite3_stmt; namespace Poco { namespace Data { namespace SQLite { class SQLite_API SQLiteStatementImpl: public Poco::Data::StatementImpl /// Implements statement functionality needed for SQLite { public: SQLiteStatementImpl(sqlite3* pDB, int maxRetryAttempts, int minRetrySleep, int maxRetrySleep); /// Creates the SQLiteStatementImpl. ~SQLiteStatementImpl(); /// Destroys the SQLiteStatementImpl. protected: Poco::UInt32 columnsReturned() const; /// Returns number of columns returned by query. const MetaColumn& metaColumn(Poco::UInt32 pos) const; /// Returns column meta data. bool hasNext(); /// Returns true if a call to next() will return data. void next(); /// Retrieves the next row from the resultset. /// Will throw, if the resultset is empty. bool canBind() const; /// Returns true if a valid statement is set and we can bind. void compileImpl(); /// Compiles the statement, doesn't bind yet, retries if /// the database is locked. void compileImplImpl(); /// Compiles the statement, doesn't bind yet void bindImpl(); /// Binds parameters AbstractExtractor& extractor(); /// Returns the concrete extractor used by the statement. AbstractBinder& binder(); /// Returns the concrete binder used by the statement. private: void clear(); /// Removes the _pStmt void sleep(); /// Sleep for a random time (between retry attempts). typedef Poco::Data::AbstractBindingVec Bindings; typedef Poco::Data::AbstractExtractionVec Extractions; sqlite3* _pDB; sqlite3_stmt* _pStmt; int _maxRetryAttempts; int _minRetrySleep; int _maxRetrySleep; bool _stepCalled; int _nextResponse; Poco::SharedPtr _pBinder; Poco::SharedPtr _pExtractor; std::vector _columns; Poco::Random _rnd; }; // // inlines // inline AbstractExtractor& SQLiteStatementImpl::extractor() { return *_pExtractor; } inline AbstractBinder& SQLiteStatementImpl::binder() { return *_pBinder; } } } } // namespace Poco::Data::SQLite #endif // DataConnectors_SQLite_SQLiteStatementImpl_INCLUDED poco-1.3.6p1-all/Data/SQLite/include/Poco/Data/SQLite/Utility.h0000644000076500001200000000554011313735447024445 0ustar guenteradmin00000000000000// // Utility.h // // $Id: //poco/1.3/Data/SQLite/include/Poco/Data/SQLite/Utility.h#4 $ // // Library: Data/SQLite // Package: SQLite // Module: Utility // // Definition of Utility. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef SQLite_Utility_INCLUDED #define SQLite_Utility_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/MetaColumn.h" #include "Poco/Mutex.h" #include struct sqlite3; struct sqlite3_stmt; namespace Poco { namespace Data { namespace SQLite { class SQLite_API Utility /// Various utility functions for SQLite, mostly return code handling { public: typedef std::map TypeMap; Utility(); /// Maps SQLite column declared types to Poco::Data types through /// static TypeMap member. /// Note: SQLite is type-agnostic and it is the end-user responsibility /// to ensure that column declared data type corresponds to the type of /// data actually held in the database. /// Column types are case-insensitive. static std::string lastError(sqlite3* pDb); /// Retreives the last error code from sqlite and converts it to a string static void throwException(int rc, const std::string& addErrMsg = std::string()); /// Throws for an error code the appropriate exception static MetaColumn::ColumnDataType getColumnType(sqlite3_stmt* pStmt, std::size_t pos); /// Returns column data type. private: static TypeMap _types; Poco::FastMutex _mutex; }; } } } // namespace Poco::Data::SQLite #endif poco-1.3.6p1-all/Data/SQLite/Makefile0000644000076500001200000000123211313735447017726 0ustar guenteradmin00000000000000# # Makefile # # $Id: //poco/1.3/Data/SQLite/Makefile#8 $ # # Makefile for Poco SQLite # include $(POCO_BASE)/build/rules/global SYSFLAGS += -DSQLITE_THREADSAFE=1 -DSQLITE_DISABLE_LFS \ -DSQLITE_OMIT_UTF16 -DSQLITE_OMIT_PROGRESS_CALLBACK -DSQLITE_OMIT_COMPLETE \ -DSQLITE_OMIT_TCL_VARIABLE -DSQLITE_OMIT_DEPRECATED objects = Binder Extractor SessionImpl Connector \ SQLiteException SQLiteStatementImpl Utility sqlite_objects = sqlite3 ifdef POCO_UNBUNDLED SYSLIBS += -lsqlite3 else objects += $(sqlite_objects) endif target = PocoSQLite target_version = $(LIBVERSION) target_libs = PocoData PocoFoundation include $(POCO_BASE)/build/rules/lib poco-1.3.6p1-all/Data/SQLite/SQLite.vmsbuild0000644000076500001200000000100611313735447021175 0ustar guenteradmin00000000000000# # SQLite.vmsbuild # # $Id: //poco/1.3/Data/SQLite/SQLite.vmsbuild#1 $ # LIB=PocoSQLite Binder Extractor SessionImpl SessionInstantiator SQLiteException StatementImpl Utility alter analyze attach auth btree build callback complete ctable date delete expr func fts1 fts1_hash fts1_porter fts1_tokenizer1 hash insert legacy loadext main opcodes os os_unix os_win pager parse pragma prepare printf random select shell tclsqlite tokenize trigger update utf util vacuum vdbe vdbeapi vdbeaux vdbefifo vdbemem vtab where poco-1.3.6p1-all/Data/SQLite/SQLite_VS71.sln0000644000076500001200000000450111313735447020727 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SQLite", "SQLite_VS71.vcproj", "{1B29820D-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS71.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {1B29820D-375F-11DB-837B-00123FC423B5} = {1B29820D-375F-11DB-837B-00123FC423B5} EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution debug_shared = debug_shared release_shared = release_shared debug_static = debug_static release_static = release_static EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static.Build.0 = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/SQLite/SQLite_VS71.vcproj0000644000076500001200000002200011313735447021430 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/SQLite/SQLite_VS80.sln0000644000076500001200000000460511313735447020734 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SQLite", "SQLite_VS80.vcproj", "{1B29820D-375F-11DB-837B-00123FC423B5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_VS80.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {1B29820D-375F-11DB-837B-00123FC423B5} = {1B29820D-375F-11DB-837B-00123FC423B5} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/SQLite/SQLite_VS80.vcproj0000644000076500001200000002366211313735447021447 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/SQLite/SQLite_vs90.sln0000644000076500001200000000460611313735447021036 0ustar guenteradmin00000000000000Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SQLite", "SQLite_vs90.vcproj", "{1B29820D-375F-11DB-837B-00123FC423B5}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TestSuite", "testsuite\TestSuite_vs90.vcproj", "{1B30A91B-375F-11DB-837B-00123FC423B5}" ProjectSection(ProjectDependencies) = postProject {1B29820D-375F-11DB-837B-00123FC423B5} = {1B29820D-375F-11DB-837B-00123FC423B5} EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution debug_shared|Win32 = debug_shared|Win32 release_shared|Win32 = release_shared|Win32 debug_static|Win32 = debug_static|Win32 release_static|Win32 = release_static|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B29820D-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.ActiveCfg = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_shared|Win32.Build.0 = debug_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.ActiveCfg = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_shared|Win32.Build.0 = release_shared|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.ActiveCfg = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.debug_static|Win32.Build.0 = debug_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.ActiveCfg = release_static|Win32 {1B30A91B-375F-11DB-837B-00123FC423B5}.release_static|Win32.Build.0 = release_static|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal poco-1.3.6p1-all/Data/SQLite/SQLite_vs90.vcproj0000644000076500001200000002365611313735447021553 0ustar guenteradmin00000000000000 poco-1.3.6p1-all/Data/SQLite/src/0000755000076500001200000000000011313735447017057 5ustar guenteradmin00000000000000poco-1.3.6p1-all/Data/SQLite/src/Binder.cpp0000644000076500001200000000600511313735447020767 0ustar guenteradmin00000000000000// // Binder.cpp // // $Id: //poco/1.3/Data/SQLite/src/Binder.cpp#4 $ // // Library: Data/SQLite // Package: SQLite // Module: Binder // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/SQLite/Binder.h" #include "Poco/Data/SQLite/Utility.h" #include "Poco/Data/BLOB.h" #include "Poco/Exception.h" #if defined(POCO_UNBUNDLED) #include #else #include "sqlite3.h" #endif #include namespace Poco { namespace Data { namespace SQLite { Binder::Binder(sqlite3_stmt* pStmt): _pStmt(pStmt) { } Binder::~Binder() { } void Binder::bind(std::size_t pos, const Poco::Int32 &val) { int rc = sqlite3_bind_int(_pStmt, (int) pos, val); checkReturn(rc); } void Binder::bind(std::size_t pos, const Poco::Int64 &val) { int rc = sqlite3_bind_int64(_pStmt, (int) pos, val); checkReturn(rc); } void Binder::bind(std::size_t pos, const double &val) { int rc = sqlite3_bind_double(_pStmt, (int) pos, val); checkReturn(rc); } void Binder::bind(std::size_t pos, const std::string& val) { int rc = sqlite3_bind_text(_pStmt, (int) pos, val.c_str(), (int) val.size()*sizeof(char), SQLITE_TRANSIENT); checkReturn(rc); } void Binder::bind(std::size_t pos, const Poco::Data::BLOB& val) { // convert a blob to a an unsigned char* array const unsigned char* pData = reinterpret_cast(val.rawContent()); int valSize = static_cast(val.size()); int rc = sqlite3_bind_blob(_pStmt, static_cast(pos), pData, valSize, SQLITE_STATIC); // no deep copy, do not free memory checkReturn(rc); } void Binder::checkReturn(int rc) { if (rc != SQLITE_OK) Utility::throwException(rc); } } } } // namespace Poco::Data::SQLite poco-1.3.6p1-all/Data/SQLite/src/Connector.cpp0000644000076500001200000000501111313735447021512 0ustar guenteradmin00000000000000// // Connector.cpp // // $Id: //poco/1.3/Data/SQLite/src/Connector.cpp#6 $ // // Library: Data/SQLite // Package: SQLite // Module: Connector // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/SQLite/Connector.h" #include "Poco/Data/SQLite/SessionImpl.h" #include "Poco/Data/SessionFactory.h" #if defined(POCO_UNBUNDLED) #include #else #include "sqlite3.h" #endif namespace Poco { namespace Data { namespace SQLite { const std::string Connector::KEY("SQLite"); Connector::Connector() { } Connector::~Connector() { } Poco::AutoPtr Connector::createSession(const std::string& connectionString) { return Poco::AutoPtr(new SessionImpl(connectionString)); } void Connector::registerConnector() { Poco::Data::SessionFactory::instance().add(KEY, new Connector()); } void Connector::unregisterConnector() { Poco::Data::SessionFactory::instance().remove(KEY); } void Connector::enableSharedCache(bool flag) { sqlite3_enable_shared_cache(flag ? 1 : 0); } void Connector::enableSoftHeapLimit(int limit) { sqlite3_soft_heap_limit(limit); } } } } // namespace Poco::Data::SQLite poco-1.3.6p1-all/Data/SQLite/src/Extractor.cpp0000644000076500001200000001410611313735447021540 0ustar guenteradmin00000000000000// // Extractor.cpp // // $Id: //poco/1.3/Data/SQLite/src/Extractor.cpp#4 $ // // Library: Data/SQLite // Package: SQLite // Module: Extractor // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/SQLite/Extractor.h" #include "Poco/Data/SQLite/Utility.h" #include "Poco/Data/BLOB.h" #include "Poco/Data/DataException.h" #include "Poco/Exception.h" #if defined(POCO_UNBUNDLED) #include #else #include "sqlite3.h" #endif #include namespace Poco { namespace Data { namespace SQLite { Extractor::Extractor(sqlite3_stmt* pStmt): _pStmt(pStmt) { } Extractor::~Extractor() { } bool Extractor::extract(std::size_t pos, Poco::Int32& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::Int64& val) { if (isNull(pos)) return false; val = sqlite3_column_int64(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, double& val) { if (isNull(pos)) return false; val = sqlite3_column_double(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, std::string& val) { if (isNull(pos)) return false; const char *pBuf = reinterpret_cast(sqlite3_column_text(_pStmt, (int) pos)); if (!pBuf) val.clear(); else val = std::string(pBuf); return true; } bool Extractor::extract(std::size_t pos, Poco::Data::BLOB& val) { if (isNull(pos)) return false; int size = sqlite3_column_bytes(_pStmt, (int) pos); const char* pTmp = reinterpret_cast(sqlite3_column_blob(_pStmt, (int) pos)); val = Poco::Data::BLOB(pTmp, size); return true; } bool Extractor::extract(std::size_t pos, Poco::Int8& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::UInt8& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::Int16& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::UInt16& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::UInt32& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::UInt64& val) { if (isNull(pos)) return false; val = sqlite3_column_int64(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, bool& val) { if (isNull(pos)) return false; val = (0 != sqlite3_column_int(_pStmt, (int) pos)); return true; } bool Extractor::extract(std::size_t pos, float& val) { if (isNull(pos)) return false; val = static_cast(sqlite3_column_double(_pStmt, (int) pos)); return true; } bool Extractor::extract(std::size_t pos, char& val) { if (isNull(pos)) return false; val = sqlite3_column_int(_pStmt, (int) pos); return true; } bool Extractor::extract(std::size_t pos, Poco::Any& val) { if (isNull(pos)) return false; bool ret = false; switch (Utility::getColumnType(_pStmt, pos)) { case MetaColumn::FDT_BOOL: { bool i = false; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_INT8: { Poco::Int8 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_UINT8: { Poco::UInt8 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_INT16: { Poco::Int16 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_UINT16: { Poco::UInt16 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_INT32: { Poco::Int32 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_UINT32: { Poco::UInt32 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_INT64: { Poco::Int64 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_UINT64: { Poco::UInt64 i = 0; ret = extract(pos, i); val = i; break; } case MetaColumn::FDT_STRING: { std::string s; ret = extract(pos, s); val = s; break; } case MetaColumn::FDT_DOUBLE: { double d(0.0); ret = extract(pos, d); val = d; break; } case MetaColumn::FDT_FLOAT: { float f(0.0); ret = extract(pos, f); val = f; break; } case MetaColumn::FDT_BLOB: { BLOB b; ret = extract(pos, b); val = b; break; } default: throw Poco::Data::UnknownTypeException("Unknown type during extraction"); } return ret; } bool Extractor::isNull(std::size_t pos) { return sqlite3_column_type(_pStmt, (int) pos) == SQLITE_NULL; } } } } // namespace Poco::Data::SQLite poco-1.3.6p1-all/Data/SQLite/src/SessionImpl.cpp0000644000076500001200000001252111313735447022031 0ustar guenteradmin00000000000000// // SessionImpl.cpp // // $Id: //poco/1.3/Data/SQLite/src/SessionImpl.cpp#9 $ // // Library: Data/SQLite // Package: SQLite // Module: SessionImpl // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Data/SQLite/SessionImpl.h" #include "Poco/Data/SQLite/Utility.h" #include "Poco/Data/SQLite/SQLiteStatementImpl.h" #if defined(POCO_UNBUNDLED) #include #else #include "sqlite3.h" #endif #include namespace Poco { namespace Data { namespace SQLite { const std::string SessionImpl::BEGIN_TRANSACTION("BEGIN "); const std::string SessionImpl::COMMIT_TRANSACTION("COMMIT"); const std::string SessionImpl::ABORT_TRANSACTION("ROLLBACK"); SessionImpl::SessionImpl(const std::string& fileName): _dbFileName(fileName), _pDB(0), _transactionMode("DEFERRED"), _maxRetryAttempts(DEFAULT_MAX_RETRY_ATTEMPTS), _minRetrySleep(DEFAULT_MIN_RETRY_SLEEP), _maxRetrySleep(DEFAULT_MAX_RETRY_SLEEP), _connected(false) { addProperty("transactionMode", &SessionImpl::setTransactionMode, &SessionImpl::getTransactionMode); addProperty("maxRetryAttempts", &SessionImpl::setMaxRetryAttempts, &SessionImpl::getMaxRetryAttempts); addProperty("minRetrySleep", &SessionImpl::setMinRetrySleep, &SessionImpl::getMinRetrySleep); addProperty("maxRetrySleep", &SessionImpl::setMaxRetrySleep, &SessionImpl::getMaxRetrySleep); open(); } SessionImpl::~SessionImpl() { close(); } Poco::Data::StatementImpl* SessionImpl::createStatementImpl() { poco_check_ptr (_pDB); return new SQLiteStatementImpl(_pDB, _maxRetryAttempts, _minRetrySleep, _maxRetrySleep); } void SessionImpl::begin() { SQLiteStatementImpl tmp(_pDB, _maxRetryAttempts, _minRetrySleep, _maxRetrySleep); tmp.add(BEGIN_TRANSACTION + _transactionMode); tmp.execute(); } void SessionImpl::commit() { SQLiteStatementImpl tmp(_pDB, _maxRetryAttempts, _minRetrySleep, _maxRetrySleep); tmp.add(COMMIT_TRANSACTION); tmp.execute(); } void SessionImpl::rollback() { SQLiteStatementImpl tmp(_pDB, _maxRetryAttempts, _minRetrySleep, _maxRetrySleep); tmp.add(ABORT_TRANSACTION); tmp.execute(); } void SessionImpl::open() { int rc = sqlite3_open(_dbFileName.c_str(), &_pDB); if (rc != 0) { close(); Utility::throwException(rc); } sqlite3_extended_result_codes(_pDB, 1); _connected = true; } void SessionImpl::close() { if (_pDB) { sqlite3_close(_pDB); _pDB = 0; } _connected = false; } bool SessionImpl::isConnected() { return _connected; } bool SessionImpl::isTransaction() { return sqlite3_get_autocommit(_pDB) == 0; } void SessionImpl::setTransactionMode(const std::string& prop, const Poco::Any& value) { _transactionMode = Poco::RefAnyCast(value); } Poco::Any SessionImpl::getTransactionMode(const std::string& prop) { return Poco::Any(_transactionMode); } void SessionImpl::setMaxRetryAttempts(const std::string& prop, const Poco::Any& value) { int maxRetryAttempts = Poco::RefAnyCast(value); if (maxRetryAttempts < 0) throw Poco::InvalidArgumentException("maxRetryAttempts must be >= 0"); _maxRetryAttempts = maxRetryAttempts; } Poco::Any SessionImpl::getMaxRetryAttempts(const std::string& prop) { return Poco::Any(_maxRetryAttempts); } void SessionImpl::setMinRetrySleep(const std::string& prop, const Poco::Any& value) { int minRetrySleep = Poco::RefAnyCast(value); if (minRetrySleep < 0 || minRetrySleep > _maxRetrySleep) throw Poco::InvalidArgumentException("minRetrySleep must be >= 0 and <= maxRetrySleep"); _minRetrySleep = minRetrySleep; } Poco::Any SessionImpl::getMinRetrySleep(const std::string& prop) { return Poco::Any(_minRetrySleep); } void SessionImpl::setMaxRetrySleep(const std::string& prop, const Poco::Any& value) { int maxRetrySleep = Poco::RefAnyCast(value); if (maxRetrySleep < _minRetrySleep) throw Poco::InvalidArgumentException("maxRetrySleep must be >= minRetrySleep"); _maxRetrySleep = maxRetrySleep; } Poco::Any SessionImpl::getMaxRetrySleep(const std::string& prop) { return Poco::Any(_maxRetrySleep); } } } } // namespace Poco::Data::SQLite poco-1.3.6p1-all/Data/SQLite/src/sqlite3.c0000644000076500001200001655441311313735447020632 0ustar guenteradmin00000000000000/****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite ** version 3.6.20. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a one translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements ** of 5% are more are commonly seen when SQLite is compiled as a single ** translation unit. ** ** This file is all you need to compile SQLite. To use SQLite in other ** programs, you need this file and the "sqlite3.h" header file that defines ** the programming interface to the SQLite library. (If you do not have ** the "sqlite3.h" header file at hand, you will find a copy embedded within ** the text of this file. Search for "Begin file sqlite3.h" to find the start ** of the embedded sqlite3.h header file.) Additional code files may be needed ** if you want a wrapper to interface SQLite with your choice of programming ** language. The code for the "sqlite3" command-line shell is also in a ** separate file. This file contains only code for the core SQLite library. */ #define SQLITE_CORE 1 #define SQLITE_AMALGAMATION 1 #ifndef SQLITE_PRIVATE # define SQLITE_PRIVATE static #endif #ifndef SQLITE_API # define SQLITE_API #endif /************** Begin file sqliteInt.h ***************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Internal interface definitions for SQLite. ** */ #ifndef _SQLITEINT_H_ #define _SQLITEINT_H_ /* ** These #defines should enable >2GB file support on POSIX if the ** underlying operating system supports it. If the OS lacks ** large file support, or if the OS is windows, these should be no-ops. ** ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any ** system #includes. Hence, this block of code must be the very first ** code in all source files. ** ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch ** on the compiler command line. This is necessary if you are compiling ** on a recent machine (ex: Red Hat 7.2) but you want your code to work ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 ** without this option, LFS is enable. But LFS does not exist in the kernel ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary ** portability you should omit LFS. ** ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. */ #ifndef SQLITE_DISABLE_LFS # define _LARGE_FILE 1 # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif # define _LARGEFILE_SOURCE 1 #endif /* ** Include the configuration header output by 'configure' if we're using the ** autoconf-based build */ #ifdef _HAVE_SQLITE_CONFIG_H #include "config.h" #endif /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ /************** Begin file sqliteLimit.h *************************************/ /* ** 2007 May 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file defines various limits of what SQLite can process. ** ** @(#) $Id: sqliteLimit.h,v 1.10 2009/01/10 16:15:09 danielk1977 Exp $ */ /* ** The maximum length of a TEXT or BLOB in bytes. This also ** limits the size of a row in a table or index. ** ** The hard limit is the ability of a 32-bit signed integer ** to count the size: 2^31-1 or 2147483647. */ #ifndef SQLITE_MAX_LENGTH # define SQLITE_MAX_LENGTH 1000000000 #endif /* ** This is the maximum number of ** ** * Columns in a table ** * Columns in an index ** * Columns in a view ** * Terms in the SET clause of an UPDATE statement ** * Terms in the result set of a SELECT statement ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. ** * Terms in the VALUES clause of an INSERT statement ** ** The hard upper limit here is 32676. Most database people will ** tell you that in a well-normalized database, you usually should ** not have more than a dozen or so columns in any table. And if ** that is the case, there is no point in having more than a few ** dozen values in any of the other situations described above. */ #ifndef SQLITE_MAX_COLUMN # define SQLITE_MAX_COLUMN 2000 #endif /* ** The maximum length of a single SQL statement in bytes. ** ** It used to be the case that setting this value to zero would ** turn the limit off. That is no longer true. It is not possible ** to turn this limit off. */ #ifndef SQLITE_MAX_SQL_LENGTH # define SQLITE_MAX_SQL_LENGTH 1000000000 #endif /* ** The maximum depth of an expression tree. This is limited to ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might ** want to place more severe limits on the complexity of an ** expression. ** ** A value of 0 used to mean that the limit was not enforced. ** But that is no longer true. The limit is now strictly enforced ** at all times. */ #ifndef SQLITE_MAX_EXPR_DEPTH # define SQLITE_MAX_EXPR_DEPTH 1000 #endif /* ** The maximum number of terms in a compound SELECT statement. ** The code generator for compound SELECT statements does one ** level of recursion for each term. A stack overflow can result ** if the number of terms is too large. In practice, most SQL ** never has more than 3 or 4 terms. Use a value of 0 to disable ** any limit on the number of terms in a compount SELECT. */ #ifndef SQLITE_MAX_COMPOUND_SELECT # define SQLITE_MAX_COMPOUND_SELECT 500 #endif /* ** The maximum number of opcodes in a VDBE program. ** Not currently enforced. */ #ifndef SQLITE_MAX_VDBE_OP # define SQLITE_MAX_VDBE_OP 25000 #endif /* ** The maximum number of arguments to an SQL function. */ #ifndef SQLITE_MAX_FUNCTION_ARG # define SQLITE_MAX_FUNCTION_ARG 127 #endif /* ** The maximum number of in-memory pages to use for the main database ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE */ #ifndef SQLITE_DEFAULT_CACHE_SIZE # define SQLITE_DEFAULT_CACHE_SIZE 2000 #endif #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 #endif /* ** The maximum number of attached databases. This must be between 0 ** and 30. The upper bound on 30 is because a 32-bit integer bitmap ** is used internally to track attached databases. */ #ifndef SQLITE_MAX_ATTACHED # define SQLITE_MAX_ATTACHED 10 #endif /* ** The maximum value of a ?nnn wildcard that the parser will accept. */ #ifndef SQLITE_MAX_VARIABLE_NUMBER # define SQLITE_MAX_VARIABLE_NUMBER 999 #endif /* Maximum page size. The upper bound on this value is 32768. This a limit ** imposed by the necessity of storing the value in a 2-byte unsigned integer ** and the fact that the page size must be a power of 2. ** ** If this limit is changed, then the compiled library is technically ** incompatible with an SQLite library compiled with a different limit. If ** a process operating on a database with a page-size of 65536 bytes ** crashes, then an instance of SQLite compiled with the default page-size ** limit will not be able to rollback the aborted transaction. This could ** lead to database corruption. */ #ifndef SQLITE_MAX_PAGE_SIZE # define SQLITE_MAX_PAGE_SIZE 32768 #endif /* ** The default size of a database page. */ #ifndef SQLITE_DEFAULT_PAGE_SIZE # define SQLITE_DEFAULT_PAGE_SIZE 1024 #endif #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE # undef SQLITE_DEFAULT_PAGE_SIZE # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif /* ** Ordinarily, if no value is explicitly provided, SQLite creates databases ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain ** device characteristics (sector-size and atomic write() support), ** SQLite may choose a larger value. This constant is the maximum value ** SQLite will choose on its own. */ #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 #endif #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE # undef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE #endif /* ** Maximum number of pages in one database file. ** ** This is really just the default value for the max_page_count pragma. ** This value can be lowered (or raised) at run-time using that the ** max_page_count macro. */ #ifndef SQLITE_MAX_PAGE_COUNT # define SQLITE_MAX_PAGE_COUNT 1073741823 #endif /* ** Maximum length (in bytes) of the pattern in a LIKE or GLOB ** operator. */ #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 #endif /* ** Maximum depth of recursion for triggers. ** ** A value of 1 means that a trigger program will not be able to itself ** fire any triggers. A value of 0 means that no trigger programs at all ** may be executed. */ #ifndef SQLITE_MAX_TRIGGER_DEPTH #if defined(SQLITE_SMALL_STACK) # define SQLITE_MAX_TRIGGER_DEPTH 10 #else # define SQLITE_MAX_TRIGGER_DEPTH 1000 #endif #endif /************** End of sqliteLimit.h *****************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* Disable nuisance warnings on Borland compilers */ #if defined(__BORLANDC__) #pragma warn -rch /* unreachable code */ #pragma warn -ccc /* Condition is always true or false */ #pragma warn -aus /* Assigned value is never used */ #pragma warn -csu /* Comparing signed and unsigned */ #pragma warn -spa /* Suspicious pointer arithmetic */ #endif /* Needed for various definitions... */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif /* ** Include standard header files as necessary */ #ifdef HAVE_STDINT_H #include #endif #ifdef HAVE_INTTYPES_H #include #endif #define SQLITE_INDEX_SAMPLES 10 /* ** This macro is used to "hide" some ugliness in casting an int ** value to a ptr value under the MSVC 64-bit compiler. Casting ** non 64-bit values to ptr types results in a "hard" error with ** the MSVC 64-bit compiler which this attempts to avoid. ** ** A simple compiler pragma or casting sequence could not be found ** to correct this in all situations, so this macro was introduced. ** ** It could be argued that the intptr_t type could be used in this ** case, but that type is not available on all compilers, or ** requires the #include of specific headers which differs between ** platforms. ** ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). ** So we have to define the macros in different ways depending on the ** compiler. */ #if defined(__GNUC__) # if defined(HAVE_STDINT_H) # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) # else # define SQLITE_INT_TO_PTR(X) ((void*)(X)) # define SQLITE_PTR_TO_INT(X) ((int)(X)) # endif #else # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) #endif /* ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1. ** Older versions of SQLite used an optional THREADSAFE macro. ** We support that for legacy */ #if !defined(SQLITE_THREADSAFE) #if defined(THREADSAFE) # define SQLITE_THREADSAFE THREADSAFE #else # define SQLITE_THREADSAFE 1 #endif #endif /* ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. ** It determines whether or not the features related to ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can ** be overridden at runtime using the sqlite3_config() API. */ #if !defined(SQLITE_DEFAULT_MEMSTATUS) # define SQLITE_DEFAULT_MEMSTATUS 1 #endif /* ** Exactly one of the following macros must be defined in order to ** specify which memory allocation subsystem to use. ** ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() ** SQLITE_MEMDEBUG // Debugging version of system malloc() ** SQLITE_MEMORY_SIZE // internal allocator #1 ** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator ** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator ** ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as ** the default. */ #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ defined(SQLITE_POW2_MEMORY_SIZE)>1 # error "At most one of the following compile-time configuration options\ is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\ SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE" #endif #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ defined(SQLITE_POW2_MEMORY_SIZE)==0 # define SQLITE_SYSTEM_MALLOC 1 #endif /* ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the ** sizes of memory allocations below this value where possible. */ #if !defined(SQLITE_MALLOC_SOFT_LIMIT) # define SQLITE_MALLOC_SOFT_LIMIT 1024 #endif /* ** We need to define _XOPEN_SOURCE as follows in order to enable ** recursive mutexes on most Unix systems. But Mac OS X is different. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, ** so it is omitted there. See ticket #2673. ** ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly ** implemented on some systems. So we avoid defining it at all ** if it is already defined or if it is unneeded because we are ** not doing a threadsafe build. Ticket #2681. ** ** See also ticket #2741. */ #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ #endif /* ** The TCL headers are only needed when compiling the TCL bindings. */ #if defined(SQLITE_TCL) || defined(TCLSH) # include #endif /* ** Many people are failing to set -DNDEBUG=1 when compiling SQLite. ** Setting NDEBUG makes the code smaller and run faster. So the following ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1 ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out ** feature. */ #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) # define NDEBUG 1 #endif /* ** The testcase() macro is used to aid in coverage testing. When ** doing coverage testing, the condition inside the argument to ** testcase() must be evaluated both true and false in order to ** get full branch coverage. The testcase() macro is inserted ** to help ensure adequate test coverage in places where simple ** condition/decision coverage is inadequate. For example, testcase() ** can be used to make sure boundary values are tested. For ** bitmask tests, testcase() can be used to make sure each bit ** is significant and used at least once. On switch statements ** where multiple cases go to the same block of code, testcase() ** can insure that all cases are evaluated. ** */ #ifdef SQLITE_COVERAGE_TEST SQLITE_PRIVATE void sqlite3Coverage(int); # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } #else # define testcase(X) #endif /* ** The TESTONLY macro is used to enclose variable declarations or ** other bits of code that are needed to support the arguments ** within testcase() and assert() macros. */ #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) # define TESTONLY(X) X #else # define TESTONLY(X) #endif /* ** Sometimes we need a small amount of code such as a variable initialization ** to setup for a later assert() statement. We do not want this code to ** appear when assert() is disabled. The following macro is therefore ** used to contain that setup code. The "VVA" acronym stands for ** "Verification, Validation, and Accreditation". In other words, the ** code within VVA_ONLY() will only run during verification processes. */ #ifndef NDEBUG # define VVA_ONLY(X) X #else # define VVA_ONLY(X) #endif /* ** The ALWAYS and NEVER macros surround boolean expressions which ** are intended to always be true or false, respectively. Such ** expressions could be omitted from the code completely. But they ** are included in a few cases in order to enhance the resilience ** of SQLite to unexpected behavior - to make the code "self-healing" ** or "ductile" rather than being "brittle" and crashing at the first ** hint of unplanned behavior. ** ** In other words, ALWAYS and NEVER are added for defensive code. ** ** When doing coverage testing ALWAYS and NEVER are hard-coded to ** be true and false so that the unreachable code then specify will ** not be counted as untested code. */ #if defined(SQLITE_COVERAGE_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif /* ** The macro unlikely() is a hint that surrounds a boolean ** expression that is usually false. Macro likely() surrounds ** a boolean expression that is usually true. GCC is able to ** use these hints to generate better code, sometimes. */ #if defined(__GNUC__) && 0 # define likely(X) __builtin_expect((X),1) # define unlikely(X) __builtin_expect((X),0) #else # define likely(X) !!(X) # define unlikely(X) !!(X) #endif /************** Include sqlite3.h in the middle of sqliteInt.h ***************/ /************** Begin file sqlite3.h *****************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the SQLite library ** presents to client programs. If a C-function, structure, datatype, ** or constant definition does not appear in this file, then it is ** not a published API of SQLite, is subject to change without ** notice, and should not be referenced by programs that use SQLite. ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new ** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve the right to make minor changes ** if experience from use "in the wild" suggest such changes are prudent. ** ** The official C-language API documentation for SQLite is derived ** from comments in this file. This file is the authoritative source ** on how SQLite interfaces are suppose to operate. ** ** The name of this file under configuration management is "sqlite.h.in". ** The makefile makes some minor changes to this file (such as inserting ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. */ #ifndef _SQLITE3_H_ #define _SQLITE3_H_ #include /* Needed for the definition of va_list */ /* ** Make sure we can call this stuff from C++. */ #if 0 extern "C" { #endif /* ** Add the ability to override 'extern' */ #ifndef SQLITE_EXTERN # define SQLITE_EXTERN extern #endif #ifndef SQLITE_API # define SQLITE_API #endif /* ** These no-op macros are used in front of interfaces to mark those ** interfaces as either deprecated or experimental. New applications ** should not use deprecated interfaces - they are support for backwards ** compatibility only. Application writers should be aware that ** experimental interfaces are subject to change in point releases. ** ** These macros used to resolve to various kinds of compiler magic that ** would generate warning messages when they were used. But that ** compiler magic ended up generating such a flurry of bug reports ** that we have taken it all out and gone back to using simple ** noop macros. */ #define SQLITE_DEPRECATED #define SQLITE_EXPERIMENTAL /* ** Ensure these symbols were not defined by some previous header file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION #endif #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* ** CAPI3REF: Compile-Time Library Version Numbers {H10010} ** ** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in ** the sqlite3.h file specify the version of SQLite with which ** that header file is associated. ** ** The "version" of SQLite is a string of the form "W.X.Y" or "W.X.Y.Z". ** The W value is major version number and is always 3 in SQLite3. ** The W value only changes when backwards compatibility is ** broken and we intend to never break backwards compatibility. ** The X value is the minor version number and only changes when ** there are major feature enhancements that are forwards compatible ** but not backwards compatible. ** The Y value is the release number and is incremented with ** each release but resets back to 0 whenever X is incremented. ** The Z value only appears on branch releases. ** ** The SQLITE_VERSION_NUMBER is an integer that is computed as ** follows: ** **
** SQLITE_VERSION_NUMBER = W*1000000 + X*1000 + Y
** 
** ** Since version 3.6.18, SQLite source code has been stored in the **
fossil configuration management ** system. The SQLITE_SOURCE_ID ** macro is a string which identifies a particular check-in of SQLite ** within its configuration management system. The string contains the ** date and time of the check-in (UTC) and an SHA1 hash of the entire ** source tree. ** ** See also: [sqlite3_libversion()], ** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite_version()] and [sqlite_source_id()]. ** ** Requirements: [H10011] [H10014] */ #define SQLITE_VERSION "3.6.20" #define SQLITE_VERSION_NUMBER 3006020 #define SQLITE_SOURCE_ID "2009-11-04 13:30:02 eb7a544fe49d1626bacecfe53ddc03fe082e3243" /* ** CAPI3REF: Run-Time Library Version Numbers {H10020} ** KEYWORDS: sqlite3_version ** ** These interfaces provide the same information as the [SQLITE_VERSION], ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] #defines in the header, ** but are associated with the library instead of the header file. Cautious ** programmers might include assert() statements in their application to ** verify that values returned by these interfaces match the macros in ** the header, and thus insure that the application is ** compiled with matching library and header files. ** **
** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
** assert( strcmp(sqlite3_libversion,SQLITE_VERSION)==0 );
** 
** ** The sqlite3_libversion() function returns the same information as is ** in the sqlite3_version[] string constant. The function is provided ** for use in DLLs since DLL users usually do not have direct access to string ** constants within the DLL. Similarly, the sqlite3_sourceid() function ** returns the same information as is in the [SQLITE_SOURCE_ID] #define of ** the header file. ** ** See also: [sqlite_version()] and [sqlite_source_id()]. ** ** Requirements: [H10021] [H10022] [H10023] */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API const char *sqlite3_sourceid(void); SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Test To See If The Library Is Threadsafe {H10100} ** ** SQLite can be compiled with or without mutexes. When ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes ** are enabled and SQLite is threadsafe. When the ** [SQLITE_THREADSAFE] macro is 0, ** the mutexes are omitted. Without the mutexes, it is not safe ** to use SQLite concurrently from more than one thread. ** ** Enabling mutexes incurs a measurable performance penalty. ** So if speed is of utmost importance, it makes sense to disable ** the mutexes. But for maximum safety, mutexes should be enabled. ** The default behavior is for mutexes to be enabled. ** ** This interface can be used by an application to make sure that the ** version of SQLite that it is linking against was compiled with ** the desired setting of the [SQLITE_THREADSAFE] macro. ** ** This interface only reports on the compile-time mutex setting ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with ** SQLITE_THREADSAFE=1 then mutexes are enabled by default but ** can be fully or partially disabled using a call to [sqlite3_config()] ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], ** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows ** only the default compile-time setting, not any run-time changes ** to that setting. ** ** See the [threading mode] documentation for additional information. ** ** Requirements: [H10101] [H10102] */ SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle {H12000} ** KEYWORDS: {database connection} {database connections} ** ** Each open SQLite database is represented by a pointer to an instance of ** the opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] ** is its destructor. There are many other interfaces (such as ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and ** [sqlite3_busy_timeout()] to name but three) that are methods on an ** sqlite3 object. */ typedef struct sqlite3 sqlite3; /* ** CAPI3REF: 64-Bit Integer Types {H10200} ** KEYWORDS: sqlite_int64 sqlite_uint64 ** ** Because there is no cross-platform way to specify 64-bit integer types ** SQLite includes typedefs for 64-bit signed and unsigned integers. ** ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards ** compatibility only. ** ** Requirements: [H10201] [H10202] */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef __int64 sqlite_int64; typedef unsigned __int64 sqlite_uint64; #else typedef long long int sqlite_int64; typedef unsigned long long int sqlite_uint64; #endif typedef sqlite_int64 sqlite3_int64; typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point. */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 #endif /* ** CAPI3REF: Closing A Database Connection {H12010} ** ** This routine is the destructor for the [sqlite3] object. ** ** Applications must [sqlite3_finalize | finalize] all [prepared statements] ** and [sqlite3_blob_close | close] all [BLOB handles] associated with ** the [sqlite3] object prior to attempting to close the object. ** ** If [sqlite3_close()] is invoked while a transaction is open, ** the transaction is automatically rolled back. ** ** The C parameter to [sqlite3_close(C)] must be either a NULL ** pointer or an [sqlite3] object pointer obtained ** from [sqlite3_open()], [sqlite3_open16()], or ** [sqlite3_open_v2()], and not previously closed. ** ** Requirements: ** [H12011] [H12012] [H12013] [H12014] [H12015] [H12019] */ SQLITE_API int sqlite3_close(sqlite3 *); /* ** The type for a callback function. ** This is legacy and deprecated. It is included for historical ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface {H12100} ** ** The sqlite3_exec() interface is a convenient way of running one or more ** SQL statements without having to write a lot of C code. The UTF-8 encoded ** SQL statements are passed in as the second parameter to sqlite3_exec(). ** The statements are evaluated one by one until either an error or ** an interrupt is encountered, or until they are all done. The 3rd parameter ** is an optional callback that is invoked once for each row of any query ** results produced by the SQL statements. The 5th parameter tells where ** to write any error messages. ** ** The error message passed back through the 5th parameter is held ** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak, ** the calling application should call [sqlite3_free()] on any error ** message returned through the 5th parameter when it has finished using ** the error message. ** ** If the SQL statement in the 2nd parameter is NULL or an empty string ** or a string containing only whitespace and comments, then no SQL ** statements are evaluated and the database is not changed. ** ** The sqlite3_exec() interface is implemented in terms of ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. ** The sqlite3_exec() routine does nothing to the database that cannot be done ** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. ** ** The first parameter to [sqlite3_exec()] must be an valid and open ** [database connection]. ** ** The database connection must not be closed while ** [sqlite3_exec()] is running. ** ** The calling function should use [sqlite3_free()] to free ** the memory that *errmsg is left pointing at once the error ** message is no longer needed. ** ** The SQL statement text in the 2nd parameter to [sqlite3_exec()] ** must remain unchanged while [sqlite3_exec()] is running. ** ** Requirements: ** [H12101] [H12102] [H12104] [H12105] [H12107] [H12110] [H12113] [H12116] ** [H12119] [H12122] [H12125] [H12131] [H12134] [H12137] [H12138] */ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* ** CAPI3REF: Result Codes {H10210} ** KEYWORDS: SQLITE_OK {error code} {error codes} ** KEYWORDS: {result code} {result codes} ** ** Many SQLite functions return an integer result code from the set shown ** here in order to indicates success or failure. ** ** New error codes may be added in future versions of SQLite. ** ** See also: [SQLITE_IOERR_READ | extended result codes] */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* SQL error or missing database */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ #define SQLITE_EMPTY 16 /* Database is empty */ #define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_MISMATCH 20 /* Data type mismatch */ #define SQLITE_MISUSE 21 /* Library used incorrectly */ #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ #define SQLITE_AUTH 23 /* Authorization denied */ #define SQLITE_FORMAT 24 /* Auxiliary database format error */ #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ #define SQLITE_NOTADB 26 /* File opened that is not a database file */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */ /* ** CAPI3REF: Extended Result Codes {H10220} ** KEYWORDS: {extended error code} {extended error codes} ** KEYWORDS: {extended result code} {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer ** [SQLITE_OK | result codes]. However, experience has shown that many of ** these result codes are too coarse-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 and later) include ** support for additional result codes that provide more detailed information ** about errors. The extended result codes are enabled or disabled ** on a per database connection basis using the ** [sqlite3_extended_result_codes()] API. ** ** Some of the available extended result codes are listed here. ** One may expect the number of extended result codes will be expand ** over time. Software that uses extended result codes should expect ** to see new result codes in future releases of SQLite. ** ** The SQLITE_OK result code will never be extended. It will always ** be exactly zero. */ #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8) ) /* ** CAPI3REF: Flags For File Open Operations {H10230} ** ** These bit values are intended for use in the ** 3rd parameter to the [sqlite3_open_v2()] interface and ** in the 4th parameter to the xOpen method of the ** [sqlite3_vfs] object. */ #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ /* ** CAPI3REF: Device Characteristics {H10240} ** ** The xDeviceCapabilities method of the [sqlite3_io_methods] ** object returns an integer which is a vector of the these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] ** refers to. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). */ #define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC512 0x00000002 #define SQLITE_IOCAP_ATOMIC1K 0x00000004 #define SQLITE_IOCAP_ATOMIC2K 0x00000008 #define SQLITE_IOCAP_ATOMIC4K 0x00000010 #define SQLITE_IOCAP_ATOMIC8K 0x00000020 #define SQLITE_IOCAP_ATOMIC16K 0x00000040 #define SQLITE_IOCAP_ATOMIC32K 0x00000080 #define SQLITE_IOCAP_ATOMIC64K 0x00000100 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400 /* ** CAPI3REF: File Locking Levels {H10250} ** ** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 #define SQLITE_LOCK_RESERVED 2 #define SQLITE_LOCK_PENDING 3 #define SQLITE_LOCK_EXCLUSIVE 4 /* ** CAPI3REF: Synchronization Type Flags {H10260} ** ** When SQLite invokes the xSync() method of an ** [sqlite3_io_methods] object it uses a combination of ** these integer values as the second argument. ** ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode ** information need not be flushed. If the lower four bits of the flag ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. ** If the lower four bits equal SQLITE_SYNC_FULL, that means ** to use Mac OS X style fullsync instead of fsync(). */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 /* ** CAPI3REF: OS Interface Open File Handle {H11110} ** ** An [sqlite3_file] object represents an open file in the ** [sqlite3_vfs | OS interface layer]. Individual OS interface ** implementations will ** want to subclass this object by appending additional fields ** for their own use. The pMethods entry is a pointer to an ** [sqlite3_io_methods] object that defines methods for performing ** I/O operations on the open file. */ typedef struct sqlite3_file sqlite3_file; struct sqlite3_file { const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* ** CAPI3REF: OS Interface File Virtual Methods Object {H11120} ** ** Every file opened by the [sqlite3_vfs] xOpen method populates an ** [sqlite3_file] object (or, more commonly, a subclass of the ** [sqlite3_file] object) with a pointer to an instance of this object. ** This object defines the methods used to perform various operations ** against the open file represented by the [sqlite3_file] object. ** ** If the xOpen method sets the sqlite3_file.pMethods element ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method ** may be invoked even if the xOpen reported that it failed. The ** only way to prevent a call to xClose following a failed xOpen ** is for the xOpen to set the sqlite3_file.pMethods element to NULL. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] ** flag may be ORed in to indicate that only the data of the file ** and not its inode needs to be synced. ** ** The integer values to xLock() and xUnlock() are one of **
    **
  • [SQLITE_LOCK_NONE], **
  • [SQLITE_LOCK_SHARED], **
  • [SQLITE_LOCK_RESERVED], **
  • [SQLITE_LOCK_PENDING], or **
  • [SQLITE_LOCK_EXCLUSIVE]. **
** xLock() increases the lock. xUnlock() decreases the lock. ** The xCheckReservedLock() method checks whether any database connection, ** either in this process or in some other process, is holding a RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true ** if such a lock exists and false otherwise. ** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the ** [sqlite3_file_control()] interface. The second "op" argument is an ** integer opcode. The third argument is a generic pointer intended to ** point to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite ** core reserves all opcodes less than 100 for its own use. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. ** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. ** ** The xSectorSize() method returns the sector size of the ** device that underlies the file. The sector size is the ** minimum write that can be performed without disturbing ** other bytes in the file. The xDeviceCharacteristics() ** method returns a bit vector describing behaviors of the ** underlying device: ** **
    **
  • [SQLITE_IOCAP_ATOMIC] **
  • [SQLITE_IOCAP_ATOMIC512] **
  • [SQLITE_IOCAP_ATOMIC1K] **
  • [SQLITE_IOCAP_ATOMIC2K] **
  • [SQLITE_IOCAP_ATOMIC4K] **
  • [SQLITE_IOCAP_ATOMIC8K] **
  • [SQLITE_IOCAP_ATOMIC16K] **
  • [SQLITE_IOCAP_ATOMIC32K] **
  • [SQLITE_IOCAP_ATOMIC64K] **
  • [SQLITE_IOCAP_SAFE_APPEND] **
  • [SQLITE_IOCAP_SEQUENTIAL] **
** ** The SQLITE_IOCAP_ATOMIC property means that all writes of ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). ** ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill ** in the unread portions of the buffer with zeros. A VFS that ** fails to zero-fill short reads might seem to work. However, ** failure to zero-fill short reads will eventually lead to ** database corruption. */ typedef struct sqlite3_io_methods sqlite3_io_methods; struct sqlite3_io_methods { int iVersion; int (*xClose)(sqlite3_file*); int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); int (*xSync)(sqlite3_file*, int flags); int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); /* Additional methods may be added in future releases */ }; /* ** CAPI3REF: Standard File Control Opcodes {H11310} ** ** These integer constants are opcodes for the xFileControl method ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] ** interface. ** ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This ** opcode causes the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) ** into an integer that the pArg argument points to. This capability ** is used during testing and only needs to be supported when SQLITE_TEST ** is defined. */ #define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_GET_LOCKPROXYFILE 2 #define SQLITE_SET_LOCKPROXYFILE 3 #define SQLITE_LAST_ERRNO 4 /* ** CAPI3REF: Mutex Handle {H17110} ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an ** abstract type for a mutex object. The SQLite core never looks ** at the internal representation of an [sqlite3_mutex]. It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. */ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: OS Interface Object {H11140} ** ** An instance of the sqlite3_vfs object defines the interface between ** the SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". ** ** The value of the iVersion field is initially 1 but may be larger in ** future versions of SQLite. Additional fields may be appended to this ** object when the iVersion value is increased. Note that the structure ** of the sqlite3_vfs object changes in the transaction between ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not ** modified. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** ** Registered sqlite3_vfs objects are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface ** searches the list. Neither the application code nor the VFS ** implementation should use the pNext pointer. ** ** The pNext field is the only field in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs ** object once the object has been registered. ** ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** ** SQLite will guarantee that the zFilename parameter to xOpen ** is either a NULL pointer or string obtained ** from xFullPathname(). SQLite further guarantees that ** the string will be valid and unchanged until xClose() is ** called. Because of the previous sentence, ** the [sqlite3_file] can safely store a pointer to the ** filename if it needs to remember the filename for some reason. ** If the zFilename parameter is xOpen is a NULL pointer then xOpen ** must invent its own temporary name for the file. Whenever the ** xFilename parameter is NULL it will also be the case that the ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. ** If xOpen() opens a file read-only then it sets *pOutFlags to ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. ** ** SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** **
    **
  • [SQLITE_OPEN_MAIN_DB] **
  • [SQLITE_OPEN_MAIN_JOURNAL] **
  • [SQLITE_OPEN_TEMP_DB] **
  • [SQLITE_OPEN_TEMP_JOURNAL] **
  • [SQLITE_OPEN_TRANSIENT_DB] **
  • [SQLITE_OPEN_SUBJOURNAL] **
  • [SQLITE_OPEN_MASTER_JOURNAL] **
** ** The file I/O implementation can use the object type flags to ** change the way it deals with files. For example, an application ** that does not care about crash recovery or rollback might make ** the open of a journal file a no-op. Writes to this journal would ** also be no-ops, and any attempt to read the journal would return ** SQLITE_IOERR. Or the implementation might recognize that a database ** file will be doing page-aligned sector reads and writes in a random ** order and set up its I/O subsystem accordingly. ** ** SQLite might also add one of the following flags to the xOpen method: ** **
    **
  • [SQLITE_OPEN_DELETEONCLOSE] **
  • [SQLITE_OPEN_EXCLUSIVE] **
** ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE] ** will be set for TEMP databases, journals and for subjournals. ** ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction ** with the [SQLITE_OPEN_CREATE] flag, which are both directly ** analogous to the O_EXCL and O_CREAT flags of the POSIX open() ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the ** SQLITE_OPEN_CREATE, is used to indicate that file should always ** be created, and that it is an error if it already exists. ** It is not used to indicate the file should be opened ** for exclusive access. ** ** At least szOsFile bytes of memory are allocated by SQLite ** to hold the [sqlite3_file] structure passed as the third ** argument to xOpen. The xOpen method does not have to ** allocate the structure; it should just fill it in. Note that ** the xOpen method must set the sqlite3_file.pMethods to either ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods ** element will be valid after xOpen returns regardless of the success ** or failure of the xOpen call. ** ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] ** to test whether a file is at least readable. The file can be a ** directory. ** ** SQLite will always allocate at least mxPathname+1 bytes for the ** output buffer xFullPathname. The exact size of the output buffer ** is also passed as a parameter to both methods. If the output buffer ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is ** handled as a fatal error by SQLite, vfs implementations should endeavor ** to prevent this by setting mxPathname to a sufficiently large value. ** ** The xRandomness(), xSleep(), and xCurrentTime() interfaces ** are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is ** the actual number of bytes of randomness obtained. ** The xSleep() method causes the calling thread to sleep for at ** least the number of microseconds given. The xCurrentTime() ** method returns a Julian Day Number for the current date and time. ** */ typedef struct sqlite3_vfs sqlite3_vfs; struct sqlite3_vfs { int iVersion; /* Structure version number */ int szOsFile; /* Size of subclassed sqlite3_file */ int mxPathname; /* Maximum file pathname length */ sqlite3_vfs *pNext; /* Next registered VFS */ const char *zName; /* Name of this virtual file system */ void *pAppData; /* Pointer to application-specific data */ int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); void (*xDlClose)(sqlite3_vfs*, void*); int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); int (*xGetLastError)(sqlite3_vfs*, int, char *); /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */ }; /* ** CAPI3REF: Flags for the xAccess VFS method {H11190} ** ** These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. {END} They determine ** what kind of permissions the xAccess method is looking for. ** With SQLITE_ACCESS_EXISTS, the xAccess method ** simply checks whether the file exists. ** With SQLITE_ACCESS_READWRITE, the xAccess method ** checks whether the file is both readable and writable. ** With SQLITE_ACCESS_READ, the xAccess method ** checks whether the file is readable. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 #define SQLITE_ACCESS_READ 2 /* ** CAPI3REF: Initialize The SQLite Library {H10130} ** ** The sqlite3_initialize() routine initializes the ** SQLite library. The sqlite3_shutdown() routine ** deallocates any resources that were allocated by sqlite3_initialize(). ** This routines are designed to aid in process initialization and ** shutdown on embedded systems. Workstation applications using ** SQLite normally do not need to invoke either of these routines. ** ** A call to sqlite3_initialize() is an "effective" call if it is ** the first time sqlite3_initialize() is invoked during the lifetime of ** the process, or if it is the first time sqlite3_initialize() is invoked ** following a call to sqlite3_shutdown(). Only an effective call ** of sqlite3_initialize() does any initialization. All other calls ** are harmless no-ops. ** ** A call to sqlite3_shutdown() is an "effective" call if it is the first ** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only ** an effective call to sqlite3_shutdown() does any deinitialization. ** All other valid calls to sqlite3_shutdown() are harmless no-ops. ** ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() ** is not. The sqlite3_shutdown() interface must only be called from a ** single thread. All open [database connections] must be closed and all ** other SQLite resources must be deallocated prior to invoking ** sqlite3_shutdown(). ** ** Among other things, sqlite3_initialize() will invoke ** sqlite3_os_init(). Similarly, sqlite3_shutdown() ** will invoke sqlite3_os_end(). ** ** The sqlite3_initialize() routine returns [SQLITE_OK] on success. ** If for some reason, sqlite3_initialize() is unable to initialize ** the library (perhaps it is unable to allocate a needed resource such ** as a mutex) it returns an [error code] other than [SQLITE_OK]. ** ** The sqlite3_initialize() routine is called internally by many other ** SQLite interfaces so that an application usually does not need to ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] ** calls sqlite3_initialize() so the SQLite library will be automatically ** initialized when [sqlite3_open()] is called if it has not be initialized ** already. However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] ** compile-time option, then the automatic calls to sqlite3_initialize() ** are omitted and the application must call sqlite3_initialize() directly ** prior to using any other SQLite interface. For maximum portability, ** it is recommended that applications always invoke sqlite3_initialize() ** directly prior to using any other SQLite interface. Future releases ** of SQLite may require this. In other words, the behavior exhibited ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the ** default behavior in some future release of SQLite. ** ** The sqlite3_os_init() routine does operating-system specific ** initialization of the SQLite library. The sqlite3_os_end() ** routine undoes the effect of sqlite3_os_init(). Typical tasks ** performed by these routines include allocation or deallocation ** of static resources, initialization of global variables, ** setting up a default [sqlite3_vfs] module, or setting up ** a default configuration using [sqlite3_config()]. ** ** The application should never invoke either sqlite3_os_init() ** or sqlite3_os_end() directly. The application should only invoke ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() ** interface is called automatically by sqlite3_initialize() and ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate ** implementations for sqlite3_os_init() and sqlite3_os_end() ** are built into SQLite when it is compiled for Unix, Windows, or OS/2. ** When [custom builds | built for other platforms] ** (using the [SQLITE_OS_OTHER=1] compile-time ** option) the application must supply a suitable implementation for ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied ** implementation of sqlite3_os_init() or sqlite3_os_end() ** must return [SQLITE_OK] on success and some other [error code] upon ** failure. */ SQLITE_API int sqlite3_initialize(void); SQLITE_API int sqlite3_shutdown(void); SQLITE_API int sqlite3_os_init(void); SQLITE_API int sqlite3_os_end(void); /* ** CAPI3REF: Configuring The SQLite Library {H14100} ** EXPERIMENTAL ** ** The sqlite3_config() interface is used to make global configuration ** changes to SQLite in order to tune SQLite to the specific needs of ** the application. The default configuration is recommended for most ** applications and so this routine is usually not necessary. It is ** provided to support rare applications with unusual needs. ** ** The sqlite3_config() interface is not threadsafe. The application ** must insure that no other SQLite interfaces are invoked by other ** threads while sqlite3_config() is running. Furthermore, sqlite3_config() ** may only be invoked prior to library initialization using ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. ** Note, however, that sqlite3_config() can be called as part of the ** implementation of an application-defined [sqlite3_os_init()]. ** ** The first argument to sqlite3_config() is an integer ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines ** what property of SQLite is to be configured. Subsequent arguments ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option] ** in the first argument. ** ** When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. ** If the option is unknown or SQLite is unable to set the option ** then this routine returns a non-zero [error code]. ** ** Requirements: ** [H14103] [H14106] [H14120] [H14123] [H14126] [H14129] [H14132] [H14135] ** [H14138] [H14141] [H14144] [H14147] [H14150] [H14153] [H14156] [H14159] ** [H14162] [H14165] [H14168] */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...); /* ** CAPI3REF: Configure database connections {H14200} ** EXPERIMENTAL ** ** The sqlite3_db_config() interface is used to make configuration ** changes to a [database connection]. The interface is similar to ** [sqlite3_config()] except that the changes apply to a single ** [database connection] (specified in the first argument). The ** sqlite3_db_config() interface can only be used immediately after ** the database connection is created using [sqlite3_open()], ** [sqlite3_open16()], or [sqlite3_open_v2()]. ** ** The second argument to sqlite3_db_config(D,V,...) is the ** configuration verb - an integer code that indicates what ** aspect of the [database connection] is being configured. ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE]. ** New verbs are likely to be added in future releases of SQLite. ** Additional arguments depend on the verb. ** ** Requirements: ** [H14203] [H14206] [H14209] [H14212] [H14215] */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...); /* ** CAPI3REF: Memory Allocation Routines {H10155} ** EXPERIMENTAL ** ** An instance of this object defines the interface between SQLite ** and low-level memory allocation routines. ** ** This object is used in only one place in the SQLite interface. ** A pointer to an instance of this object is the argument to ** [sqlite3_config()] when the configuration option is ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. ** By creating an instance of this object ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) ** during configuration, an application can specify an alternative ** memory allocation subsystem for SQLite to use for all of its ** dynamic memory needs. ** ** Note that SQLite comes with several [built-in memory allocators] ** that are perfectly adequate for the overwhelming majority of applications ** and that this object is only useful to a tiny minority of applications ** with specialized memory allocation requirements. This object is ** also used during testing of SQLite in order to specify an alternative ** memory allocator that simulates memory out-of-memory conditions in ** order to verify that SQLite recovers gracefully from such ** conditions. ** ** The xMalloc and xFree methods must work like the ** malloc() and free() functions from the standard C library. ** The xRealloc method must work like realloc() from the standard C library ** with the exception that if the second argument to xRealloc is zero, ** xRealloc must be a no-op - it must not perform any allocation or ** deallocation. SQLite guaranteeds that the second argument to ** xRealloc is always a value returned by a prior call to xRoundup. ** And so in cases where xRoundup always returns a positive number, ** xRealloc can perform exactly as the standard library realloc() and ** still be in compliance with this specification. ** ** xSize should return the allocated size of a memory allocation ** previously obtained from xMalloc or xRealloc. The allocated size ** is always at least as big as the requested size but may be larger. ** ** The xRoundup method returns what would be the allocated size of ** a memory allocation given a particular requested size. Most memory ** allocators round up memory allocations at least to the next multiple ** of 8. Some allocators round up to a larger multiple or to a power of 2. ** Every memory allocation request coming in through [sqlite3_malloc()] ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, ** that causes the corresponding memory allocation to fail. ** ** The xInit method initializes the memory allocator. (For example, ** it might allocate any require mutexes or initialize internal data ** structures. The xShutdown method is invoked (indirectly) by ** [sqlite3_shutdown()] and should deallocate any resources acquired ** by xInit. The pAppData pointer is used as the only parameter to ** xInit and xShutdown. ** ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. For all other methods, SQLite ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which ** it is by default) and so the methods are automatically serialized. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other ** methods must be threadsafe or else make their own arrangements for ** serialization. ** ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). */ typedef struct sqlite3_mem_methods sqlite3_mem_methods; struct sqlite3_mem_methods { void *(*xMalloc)(int); /* Memory allocation function */ void (*xFree)(void*); /* Free a prior allocation */ void *(*xRealloc)(void*,int); /* Resize an allocation */ int (*xSize)(void*); /* Return the size of an allocation */ int (*xRoundup)(int); /* Round up request size to allocation size */ int (*xInit)(void*); /* Initialize the memory allocator */ void (*xShutdown)(void*); /* Deinitialize the memory allocator */ void *pAppData; /* Argument to xInit() and xShutdown() */ }; /* ** CAPI3REF: Configuration Options {H10160} ** EXPERIMENTAL ** ** These constants are the available integer configuration options that ** can be passed as the first argument to the [sqlite3_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_config()] to make sure that ** the call worked. The [sqlite3_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
**
SQLITE_CONFIG_SINGLETHREAD
**
There are no arguments to this option. This option disables ** all mutexing and puts SQLite into a mode where it can only be used ** by a single thread.
** **
SQLITE_CONFIG_MULTITHREAD
**
There are no arguments to this option. This option disables ** mutexing on [database connection] and [prepared statement] objects. ** The application is responsible for serializing access to ** [database connections] and [prepared statements]. But other mutexes ** are enabled so that SQLite will be safe to use in a multi-threaded ** environment as long as no two threads attempt to use the same ** [database connection] at the same time. See the [threading mode] ** documentation for additional information.
** **
SQLITE_CONFIG_SERIALIZED
**
There are no arguments to this option. This option enables ** all mutexes including the recursive ** mutexes on [database connection] and [prepared statement] objects. ** In this mode (which is the default when SQLite is compiled with ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access ** to [database connections] and [prepared statements] so that the ** application is free to use the same [database connection] or the ** same [prepared statement] in different threads at the same time. ** See the [threading mode] documentation for additional information.
** **
SQLITE_CONFIG_MALLOC
**
This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mem_methods] structure. The argument specifies ** alternative low-level memory allocation routines to be used in place of ** the memory allocation routines built into SQLite.
** **
SQLITE_CONFIG_GETMALLOC
**
This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] ** structure is filled with the currently defined memory allocation routines. ** This option can be used to overload the default memory allocation ** routines with a wrapper that simulations memory allocation failure or ** tracks memory usage, for example.
** **
SQLITE_CONFIG_MEMSTATUS
**
This option takes single argument of type int, interpreted as a ** boolean, which enables or disables the collection of memory allocation ** statistics. When disabled, the following SQLite interfaces become ** non-operational: **
    **
  • [sqlite3_memory_used()] **
  • [sqlite3_memory_highwater()] **
  • [sqlite3_soft_heap_limit()] **
  • [sqlite3_status()] **
**
** **
SQLITE_CONFIG_SCRATCH
**
This option specifies a static memory buffer that SQLite can use for ** scratch memory. There are three arguments: A pointer an 8-byte ** aligned memory buffer from which the scrach allocations will be ** drawn, the size of each scratch allocation (sz), ** and the maximum number of scratch allocations (N). The sz ** argument must be a multiple of 16. The sz parameter should be a few bytes ** larger than the actual scratch space required due to internal overhead. ** The first argument should pointer to an 8-byte aligned buffer ** of at least sz*N bytes of memory. ** SQLite will use no more than one scratch buffer at once per thread, so ** N should be set to the expected maximum number of threads. The sz ** parameter should be 6 times the size of the largest database page size. ** Scratch buffers are used as part of the btree balance operation. If ** The btree balancer needs additional memory beyond what is provided by ** scratch buffers or if no scratch buffer space is specified, then SQLite ** goes to [sqlite3_malloc()] to obtain the memory it needs.
** **
SQLITE_CONFIG_PAGECACHE
**
This option specifies a static memory buffer that SQLite can use for ** the database page cache with the default page cache implemenation. ** This configuration should not be used if an application-define page ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option. ** There are three arguments to this option: A pointer to 8-byte aligned ** memory, the size of each page buffer (sz), and the number of pages (N). ** The sz argument should be the size of the largest database page ** (a power of two between 512 and 32768) plus a little extra for each ** page header. The page header size is 20 to 40 bytes depending on ** the host architecture. It is harmless, apart from the wasted memory, ** to make sz a little too large. The first ** argument should point to an allocation of at least sz*N bytes of memory. ** SQLite will use the memory provided by the first argument to satisfy its ** memory needs for the first N pages that it adds to cache. If additional ** page cache memory is needed beyond what is provided by this option, then ** SQLite goes to [sqlite3_malloc()] for the additional storage space. ** The implementation might use one or more of the N buffers to hold ** memory accounting information. The pointer in the first argument must ** be aligned to an 8-byte boundary or subsequent behavior of SQLite ** will be undefined.
** **
SQLITE_CONFIG_HEAP
**
This option specifies a static memory buffer that SQLite will use ** for all of its dynamic memory allocation needs beyond those provided ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. ** There are three arguments: An 8-byte aligned pointer to the memory, ** the number of bytes in the memory buffer, and the minimum allocation size. ** If the first pointer (the memory pointer) is NULL, then SQLite reverts ** to using its default memory allocator (the system malloc() implementation), ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory ** allocator is engaged to handle all of SQLites memory allocation needs. ** The first pointer (the memory pointer) must be aligned to an 8-byte ** boundary or subsequent behavior of SQLite will be undefined.
** **
SQLITE_CONFIG_MUTEX
**
This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mutex_methods] structure. The argument specifies ** alternative low-level mutex routines to be used in place ** the mutex routines built into SQLite.
** **
SQLITE_CONFIG_GETMUTEX
**
This option takes a single argument which is a pointer to an ** instance of the [sqlite3_mutex_methods] structure. The ** [sqlite3_mutex_methods] ** structure is filled with the currently defined mutex routines. ** This option can be used to overload the default mutex allocation ** routines with a wrapper used to track mutex usage for performance ** profiling or testing, for example.
** **
SQLITE_CONFIG_LOOKASIDE
**
This option takes two arguments that determine the default ** memory allocation lookaside optimization. The first argument is the ** size of each lookaside buffer slot and the second is the number of ** slots allocated to each database connection. This option sets the ** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] ** verb to [sqlite3_db_config()] can be used to change the lookaside ** configuration on individual connections.
** **
SQLITE_CONFIG_PCACHE
**
This option takes a single argument which is a pointer to ** an [sqlite3_pcache_methods] object. This object specifies the interface ** to a custom page cache implementation. SQLite makes a copy of the ** object and uses it for page cache memory allocations.
** **
SQLITE_CONFIG_GETPCACHE
**
This option takes a single argument which is a pointer to an ** [sqlite3_pcache_methods] object. SQLite copies of the current ** page cache implementation into that object.
** **
*/ #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ /* ** CAPI3REF: Configuration Options {H10170} ** EXPERIMENTAL ** ** These constants are the available integer configuration options that ** can be passed as the second argument to the [sqlite3_db_config()] interface. ** ** New configuration options may be added in future releases of SQLite. ** Existing configuration options might be discontinued. Applications ** should check the return code from [sqlite3_db_config()] to make sure that ** the call worked. The [sqlite3_db_config()] interface will return a ** non-zero [error code] if a discontinued or unsupported configuration option ** is invoked. ** **
**
SQLITE_DBCONFIG_LOOKASIDE
**
This option takes three additional arguments that determine the ** [lookaside memory allocator] configuration for the [database connection]. ** The first argument (the third parameter to [sqlite3_db_config()] is a ** pointer to an memory buffer to use for lookaside memory. ** The first argument may be NULL in which case SQLite will allocate the ** lookaside buffer itself using [sqlite3_malloc()]. The second argument is the ** size of each lookaside buffer slot and the third argument is the number of ** slots. The size of the buffer in the first argument must be greater than ** or equal to the product of the second and third arguments. The buffer ** must be aligned to an 8-byte boundary. If the second argument is not ** a multiple of 8, it is internally rounded down to the next smaller ** multiple of 8. See also: [SQLITE_CONFIG_LOOKASIDE]
** **
*/ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ /* ** CAPI3REF: Enable Or Disable Extended Result Codes {H12200} ** ** The sqlite3_extended_result_codes() routine enables or disables the ** [extended result codes] feature of SQLite. The extended result ** codes are disabled by default for historical compatibility considerations. ** ** Requirements: ** [H12201] [H12202] */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid {H12220} ** ** Each entry in an SQLite table has a unique 64-bit signed ** integer key called the [ROWID | "rowid"]. The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those ** names are not also used by explicitly declared columns. If ** the table has a column of type [INTEGER PRIMARY KEY] then that column ** is another alias for the rowid. ** ** This routine returns the [rowid] of the most recent ** successful [INSERT] into the database from the [database connection] ** in the first argument. If no successful [INSERT]s ** have ever occurred on that database connection, zero is returned. ** ** If an [INSERT] occurs within a trigger, then the [rowid] of the inserted ** row is returned by this routine as long as the trigger is running. ** But once the trigger terminates, the value returned by this routine ** reverts to the last value inserted before the trigger fired. ** ** An [INSERT] that fails due to a constraint violation is not a ** successful [INSERT] and does not change the value returned by this ** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this ** routine when their insertion fails. When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change ** the return value of this interface. ** ** For the purposes of this routine, an [INSERT] is considered to ** be successful even if it is subsequently rolled back. ** ** Requirements: ** [H12221] [H12223] ** ** If a separate thread performs a new [INSERT] on the same ** database connection while the [sqlite3_last_insert_rowid()] ** function is running and thus changes the last insert [rowid], ** then the value returned by [sqlite3_last_insert_rowid()] is ** unpredictable and might not equal either the old or the new ** last insert [rowid]. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified {H12240} ** ** This function returns the number of database rows that were changed ** or inserted or deleted by the most recently completed SQL statement ** on the [database connection] specified by the first parameter. ** Only changes that are directly specified by the [INSERT], [UPDATE], ** or [DELETE] statement are counted. Auxiliary changes caused by ** triggers or [foreign key actions] are not counted. Use the ** [sqlite3_total_changes()] function to find the total number of changes ** including changes caused by triggers and foreign key actions. ** ** Changes to a view that are simulated by an [INSTEAD OF trigger] ** are not counted. Only real table changes are counted. ** ** A "row change" is a change to a single row of a single table ** caused by an INSERT, DELETE, or UPDATE statement. Rows that ** are changed as side effects of [REPLACE] constraint resolution, ** rollback, ABORT processing, [DROP TABLE], or by any other ** mechanisms do not count as direct row changes. ** ** A "trigger context" is a scope of execution that begins and ** ends with the script of a [CREATE TRIGGER | trigger]. ** Most SQL statements are ** evaluated outside of any trigger. This is the "top level" ** trigger context. If a trigger fires from the top level, a ** new trigger context is entered for the duration of that one ** trigger. Subtriggers create subcontexts for their duration. ** ** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does ** not create a new trigger context. ** ** This function returns the number of direct row changes in the ** most recent INSERT, UPDATE, or DELETE statement within the same ** trigger context. ** ** Thus, when called from the top level, this function returns the ** number of changes in the most recent INSERT, UPDATE, or DELETE ** that also occurred at the top level. Within the body of a trigger, ** the sqlite3_changes() interface can be called to find the number of ** changes in the most recently completed INSERT, UPDATE, or DELETE ** statement within the body of the same trigger. ** However, the number returned does not include changes ** caused by subtriggers since those have their own context. ** ** See also the [sqlite3_total_changes()] interface and the ** [count_changes pragma]. ** ** Requirements: ** [H12241] [H12243] ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_changes()] is running then the value returned ** is unpredictable and not meaningful. */ SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified {H12260} ** ** This function returns the number of row changes caused by [INSERT], ** [UPDATE] or [DELETE] statements since the [database connection] was opened. ** The count includes all changes from all [CREATE TRIGGER | trigger] ** contexts and changes made by [foreign key actions]. However, ** the count does not include changes used to implement [REPLACE] constraints, ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The ** count does not include rows of views that fire an [INSTEAD OF trigger], ** though if the INSTEAD OF trigger makes changes of its own, those changes ** are counted. ** The changes are counted as soon as the statement that makes them is ** completed (when the statement handle is passed to [sqlite3_reset()] or ** [sqlite3_finalize()]). ** ** See also the [sqlite3_changes()] interface and the ** [count_changes pragma]. ** ** Requirements: ** [H12261] [H12263] ** ** If a separate thread makes changes on the same database connection ** while [sqlite3_total_changes()] is running then the value ** returned is unpredictable and not meaningful. */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query {H12270} ** ** This function causes any pending database operation to abort and ** return at its earliest opportunity. This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** ** It is safe to call this routine from a thread different from the ** thread that is currently running the database operation. But it ** is not safe to call this routine with a [database connection] that ** is closed or might close before sqlite3_interrupt() returns. ** ** If an SQL operation is very nearly finished at the time when ** sqlite3_interrupt() is called, then it might not have an opportunity ** to be interrupted and might continue to completion. ** ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE ** that is inside an explicit transaction, then the entire transaction ** will be rolled back automatically. ** ** The sqlite3_interrupt(D) call is in effect until all currently running ** SQL statements on [database connection] D complete. Any new SQL statements ** that are started after the sqlite3_interrupt() call and before the ** running statements reaches zero are interrupted as if they had been ** running prior to the sqlite3_interrupt() call. New SQL statements ** that are started after the running statement count reaches zero are ** not effected by the sqlite3_interrupt(). ** A call to sqlite3_interrupt(D) that occurs when there are no running ** SQL statements is a no-op and has no effect on SQL statements ** that are started after the sqlite3_interrupt() call returns. ** ** Requirements: ** [H12271] [H12272] ** ** If the database connection closes while [sqlite3_interrupt()] ** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); /* ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} ** ** These routines are useful during command-line input to determine if the ** currently entered text seems to form a complete SQL statement or ** if additional input is needed before sending the text into ** SQLite for parsing. These routines return 1 if the input string ** appears to be a complete SQL statement. A statement is judged to be ** complete if it ends with a semicolon token and is not a prefix of a ** well-formed CREATE TRIGGER statement. Semicolons that are embedded within ** string literals or quoted identifier names or comments are not ** independent tokens (they are part of the token in which they are ** embedded) and thus do not count as a statement terminator. Whitespace ** and comments that follow the final semicolon are ignored. ** ** These routines return 0 if the statement is incomplete. If a ** memory allocation fails, then SQLITE_NOMEM is returned. ** ** These routines do not parse the SQL statements thus ** will not detect syntactically incorrect SQL. ** ** If SQLite has not been initialized using [sqlite3_initialize()] prior ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked ** automatically by sqlite3_complete16(). If that initialization fails, ** then the return value from sqlite3_complete16() will be non-zero ** regardless of whether or not the input SQL is complete. ** ** Requirements: [H10511] [H10512] ** ** The input to [sqlite3_complete()] must be a zero-terminated ** UTF-8 string. ** ** The input to [sqlite3_complete16()] must be a zero-terminated ** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {H12310} ** ** This routine sets a callback function that might be invoked whenever ** an attempt is made to open a database table that another thread ** or process has locked. ** ** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] ** is returned immediately upon encountering the lock. If the busy callback ** is not NULL, then the callback will be invoked with two arguments. ** ** The first argument to the handler is a copy of the void* pointer which ** is the third argument to sqlite3_busy_handler(). The second argument to ** the handler callback is the number of times that the busy handler has ** been invoked for this locking event. If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. ** If the callback returns non-zero, then another attempt ** is made to open the database for reading and the cycle repeats. ** ** The presence of a busy handler does not guarantee that it will be invoked ** when there is lock contention. If SQLite determines that invoking the busy ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying ** to promote to an exclusive lock. The first process cannot proceed ** because it is blocked by the second and the second process cannot ** proceed because it is blocked by the first. If both processes ** invoke the busy handlers, neither will make any progress. Therefore, ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** The default busy callback is NULL. ** ** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] ** when SQLite is in the middle of a large transaction where all the ** changes will not fit into the in-memory cache. SQLite will ** already hold a RESERVED lock on the database file, but it needs ** to promote this lock to EXCLUSIVE so that it can spill cache ** pages into the database file without harm to concurrent ** readers. If it is unable to promote the lock, then the in-memory ** cache will be left in an inconsistent state and so the error ** code is promoted from the relatively benign [SQLITE_BUSY] to ** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion ** forces an automatic rollback of the changes. See the ** ** CorruptionFollowingBusyError wiki page for a discussion of why ** this is important. ** ** There can only be a single busy handler defined for each ** [database connection]. Setting a new busy handler clears any ** previously set handler. Note that calling [sqlite3_busy_timeout()] ** will also set or clear the busy handler. ** ** The busy callback should not take any actions which modify the ** database connection that invoked the busy handler. Any such actions ** result in undefined behavior. ** ** Requirements: ** [H12311] [H12312] [H12314] [H12316] [H12318] ** ** A busy handler must not close the database connection ** or [prepared statement] that invoked the busy handler. */ SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* ** CAPI3REF: Set A Busy Timeout {H12340} ** ** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps ** for a specified amount of time when a table is locked. The handler ** will sleep multiple times until at least "ms" milliseconds of sleeping ** have accumulated. {H12343} After "ms" milliseconds of sleeping, ** the handler returns 0 which causes [sqlite3_step()] to return ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. ** ** Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** ** There can only be a single busy handler for a particular ** [database connection] any any given moment. If another busy handler ** was defined (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared. ** ** Requirements: ** [H12341] [H12343] [H12344] */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries {H12370} ** ** Definition: A result table is memory data structure created by the ** [sqlite3_get_table()] interface. A result table records the ** complete query results from one or more queries. ** ** The table conceptually has a number of rows and columns. But ** these numbers are not part of the result table itself. These ** numbers are obtained separately. Let N be the number of rows ** and M be the number of columns. ** ** A result table is an array of pointers to zero-terminated UTF-8 strings. ** There are (N+1)*M elements in the array. The first M pointers point ** to zero-terminated strings that contain the names of the columns. ** The remaining entries all point to query results. NULL values result ** in NULL pointers. All other values are in their UTF-8 zero-terminated ** string representation as returned by [sqlite3_column_text()]. ** ** A result table might consist of one or more memory allocations. ** It is not safe to pass a result table directly to [sqlite3_free()]. ** A result table should be deallocated using [sqlite3_free_table()]. ** ** As an example of the result table format, suppose a query result ** is as follows: ** **
**        Name        | Age
**        -----------------------
**        Alice       | 43
**        Bob         | 28
**        Cindy       | 21
** 
** ** There are two column (M==2) and three rows (N==3). Thus the ** result table has 8 entries. Suppose the result table is stored ** in an array names azResult. Then azResult holds this content: ** **
**        azResult[0] = "Name";
**        azResult[1] = "Age";
**        azResult[2] = "Alice";
**        azResult[3] = "43";
**        azResult[4] = "Bob";
**        azResult[5] = "28";
**        azResult[6] = "Cindy";
**        azResult[7] = "21";
** 
** ** The sqlite3_get_table() function evaluates one or more ** semicolon-separated SQL statements in the zero-terminated UTF-8 ** string of its 2nd parameter. It returns a result table to the ** pointer given in its 3rd parameter. ** ** After the calling function has finished using the result, it should ** pass the pointer to the result table to sqlite3_free_table() in order to ** release the memory that was malloced. Because of the way the ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling ** function must not try to call [sqlite3_free()] directly. Only ** [sqlite3_free_table()] is able to release the memory properly and safely. ** ** The sqlite3_get_table() interface is implemented as a wrapper around ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access ** to any internal data structures of SQLite. It uses only the public ** interface defined here. As a consequence, errors that occur in the ** wrapper layer outside of the internal [sqlite3_exec()] call are not ** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()]. ** ** Requirements: ** [H12371] [H12373] [H12374] [H12376] [H12379] [H12382] */ SQLITE_API int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows written here */ int *pnColumn, /* Number of result columns written here */ char **pzErrmsg /* Error msg written here */ ); SQLITE_API void sqlite3_free_table(char **result); /* ** CAPI3REF: Formatted String Printing Functions {H17400} ** ** These routines are work-alikes of the "printf()" family of functions ** from the standard C library. ** ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be ** released by [sqlite3_free()]. Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** ** In sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by ** the first parameter. Note that the order of the ** first two parameters is reversed from snprintf(). This is an ** historical accident that cannot be fixed without breaking ** backwards compatibility. Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer. We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** ** As long as the buffer size is greater than zero, sqlite3_snprintf() ** guarantees that the buffer is always zero-terminated. The first ** parameter "n" is the total size of the buffer, including space for ** the zero terminator. So the longest string that can be completely ** written will be n-1 characters. ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. ** All of the usual printf() formatting options apply. In addition, there ** is are "%q", "%Q", and "%z" options. ** ** The %q option works like %s in that it substitutes a null-terminated ** string from the argument list. But %q also doubles every '\'' character. ** %q is designed for use inside a string literal. By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** ** For example, assume the string variable zText contains text as follows: ** **
**  char *zText = "It's a happy day!";
** 
** ** One can use this text in an SQL statement as follows: ** **
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** 
** ** Because the %q format string is used, the '\'' character in zText ** is escaped and the SQL generated is as follows: ** **
**  INSERT INTO table1 VALUES('It''s a happy day!')
** 
** ** This is correct. Had we used %s instead of %q, the generated SQL ** would have looked like this: ** **
**  INSERT INTO table1 VALUES('It's a happy day!');
** 
** ** This second example is an SQL syntax error. As a general rule you should ** always use %q instead of %s when inserting text into a string literal. ** ** The %Q option works like %q except it also adds single quotes around ** the outside of the total string. Additionally, if the parameter in the ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without ** single quotes) in place of the %Q option. So, for example, one could say: ** **
**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** 
** ** The code above will render a correct SQL statement in the zSQL ** variable even if the zText variable is a NULL pointer. ** ** The "%z" formatting option works exactly like "%s" with the ** addition that after the string has been read and copied into ** the result, [sqlite3_free()] is called on the input string. {END} ** ** Requirements: ** [H17403] [H17406] [H17407] */ SQLITE_API char *sqlite3_mprintf(const char*,...); SQLITE_API char *sqlite3_vmprintf(const char*, va_list); SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); /* ** CAPI3REF: Memory Allocation Subsystem {H17300} ** ** The SQLite core uses these three routines for all of its own ** internal memory allocation needs. "Core" in the previous sentence ** does not include operating-system specific VFS implementation. The ** Windows VFS uses native malloc() and free() for some operations. ** ** The sqlite3_malloc() routine returns a pointer to a block ** of memory at least N bytes in length, where N is the parameter. ** If sqlite3_malloc() is unable to obtain sufficient free ** memory, it returns a NULL pointer. If the parameter N to ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns ** a NULL pointer. ** ** Calling sqlite3_free() with a pointer previously returned ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so ** that it might be reused. The sqlite3_free() routine is ** a no-op if is called with a NULL pointer. Passing a NULL pointer ** to sqlite3_free() is harmless. After being freed, memory ** should neither be read nor written. Even reading previously freed ** memory might result in a segmentation fault or other severe error. ** Memory corruption, a segmentation fault, or other severe error ** might result if sqlite3_free() is called with a non-NULL pointer that ** was not obtained from sqlite3_malloc() or sqlite3_realloc(). ** ** The sqlite3_realloc() interface attempts to resize a ** prior memory allocation to be at least N bytes, where N is the ** second parameter. The memory allocation to be resized is the first ** parameter. If the first parameter to sqlite3_realloc() ** is a NULL pointer then its behavior is identical to calling ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). ** If the second parameter to sqlite3_realloc() is zero or ** negative then the behavior is exactly the same as calling ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). ** sqlite3_realloc() returns a pointer to a memory allocation ** of at least N bytes in size or NULL if sufficient memory is unavailable. ** If M is the size of the prior allocation, then min(N,M) bytes ** of the prior allocation are copied into the beginning of buffer returned ** by sqlite3_realloc() and the prior allocation is freed. ** If sqlite3_realloc() returns NULL, then the prior allocation ** is not freed. ** ** The memory returned by sqlite3_malloc() and sqlite3_realloc() ** is always aligned to at least an 8 byte boundary. {END} ** ** The default implementation of the memory allocation subsystem uses ** the malloc(), realloc() and free() provided by the standard C library. ** {H17382} However, if SQLite is compiled with the ** SQLITE_MEMORY_SIZE=NNN C preprocessor macro (where NNN ** is an integer), then SQLite create a static array of at least ** NNN bytes in size and uses that array for all of its dynamic ** memory allocation needs. {END} Additional memory allocator options ** may be added in future releases. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability ** is no longer provided. Only built-in memory allocators can be used. ** ** The Windows OS interface layer calls ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite ** and whatever filename encoding is used by the particular Windows ** installation. Memory allocation errors are detected, but ** they are reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. ** ** Requirements: ** [H17303] [H17304] [H17305] [H17306] [H17310] [H17312] [H17315] [H17318] ** [H17321] [H17322] [H17323] ** ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] ** must be either NULL or else pointers obtained from a prior ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have ** not yet been released. ** ** The application must not read or write any part of ** a block of memory after it has been released using ** [sqlite3_free()] or [sqlite3_realloc()]. */ SQLITE_API void *sqlite3_malloc(int); SQLITE_API void *sqlite3_realloc(void*, int); SQLITE_API void sqlite3_free(void*); /* ** CAPI3REF: Memory Allocator Statistics {H17370} ** ** SQLite provides these two interfaces for reporting on the status ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] ** routines, which form the built-in memory allocation subsystem. ** ** Requirements: ** [H17371] [H17373] [H17374] [H17375] */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* ** CAPI3REF: Pseudo-Random Number Generator {H17390} ** ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to ** select random [ROWID | ROWIDs] when inserting new records into a table that ** already uses the largest possible [ROWID]. The PRNG is also used for ** the build-in random() and randomblob() SQL functions. This interface allows ** applications to access the same PRNG for other purposes. ** ** A call to this routine stores N bytes of randomness into buffer P. ** ** The first time this routine is invoked (either internally or by ** the application) the PRNG is seeded using randomness obtained ** from the xRandomness method of the default [sqlite3_vfs] object. ** On all subsequent invocations, the pseudo-randomness is generated ** internally and without recourse to the [sqlite3_vfs] xRandomness ** method. ** ** Requirements: ** [H17392] */ SQLITE_API void sqlite3_randomness(int N, void *P); /* ** CAPI3REF: Compile-Time Authorization Callbacks {H12500} ** ** This routine registers a authorizer callback with a particular ** [database connection], supplied in the first argument. ** The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. The authorizer callback should ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be ** rejected with an error. If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] ** then the [sqlite3_prepare_v2()] or equivalent call that triggered ** the authorizer will fail with an error message. ** ** When the callback returns [SQLITE_OK], that means the operation ** requested is ok. When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the ** authorizer will fail with an error message explaining that ** access is denied. ** ** The first parameter to the authorizer callback is a copy of the third ** parameter to the sqlite3_set_authorizer() interface. The second parameter ** to the callback is an integer [SQLITE_COPY | action code] that specifies ** the particular action to be authorized. The third through sixth parameters ** to the callback are zero-terminated strings that contain additional ** details about the action to be authorized. ** ** If the action code is [SQLITE_READ] ** and the callback returns [SQLITE_IGNORE] then the ** [prepared statement] statement is constructed to substitute ** a NULL value in place of the table column that would have ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] ** return can be used to deny an untrusted user access to individual ** columns of a table. ** If the action code is [SQLITE_DELETE] and the callback returns ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the ** [truncate optimization] is disabled and all rows are deleted individually. ** ** An authorizer is used when [sqlite3_prepare | preparing] ** SQL statements from an untrusted source, to ensure that the SQL statements ** do not try to access data they are not allowed to see, or that they do not ** try to execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the ** user-entered SQL is being [sqlite3_prepare | prepared] that ** disallows everything except [SELECT] statements. ** ** Applications that need to process SQL from untrusted sources ** might also consider lowering resource limits using [sqlite3_limit()] ** and limiting database size using the [max_page_count] [PRAGMA] ** in addition to using an authorizer. ** ** Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the ** previous call. Disable the authorizer by installing a NULL callback. ** The authorizer is disabled by default. ** ** The authorizer callback must not do anything that will modify ** the database connection that invoked the authorizer callback. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** When [sqlite3_prepare_v2()] is used to prepare a statement, the ** statement might be re-prepared during [sqlite3_step()] due to a ** schema change. Hence, the application should ensure that the ** correct authorizer callback remains in place during the [sqlite3_step()]. ** ** Note that the authorizer callback is invoked only during ** [sqlite3_prepare()] or its variants. Authorization is not ** performed during statement evaluation in [sqlite3_step()], unless ** as stated in the previous paragraph, sqlite3_step() invokes ** sqlite3_prepare_v2() to reprepare a statement after a schema change. ** ** Requirements: ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510] ** [H12511] [H12512] [H12520] [H12521] [H12522] */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* ** CAPI3REF: Authorizer Return Codes {H12590} ** ** The [sqlite3_set_authorizer | authorizer callback function] must ** return either [SQLITE_OK] or one of these two constants in order ** to signal SQLite whether or not the action is permitted. See the ** [sqlite3_set_authorizer | authorizer documentation] for additional ** information. */ #define SQLITE_DENY 1 /* Abort the SQL statement with an error */ #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ /* ** CAPI3REF: Authorizer Action Codes {H12550} ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorize certain SQL statement actions. The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that ** the authorizer callback may be passed. ** ** These action code values signify what kind of operation is to be ** authorized. The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these ** codes is used as the second parameter. The 5th parameter to the ** authorizer callback is the name of the database ("main", "temp", ** etc.) if applicable. The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for ** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. ** ** Requirements: ** [H12551] [H12552] [H12553] [H12554] */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ #define SQLITE_CREATE_VIEW 8 /* View Name NULL */ #define SQLITE_DELETE 9 /* Table Name NULL */ #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ #define SQLITE_DROP_TABLE 11 /* Table Name NULL */ #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ #define SQLITE_DROP_VIEW 17 /* View Name NULL */ #define SQLITE_INSERT 18 /* Table Name NULL */ #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ #define SQLITE_READ 20 /* Table Name Column Name */ #define SQLITE_SELECT 21 /* NULL NULL */ #define SQLITE_TRANSACTION 22 /* Operation NULL */ #define SQLITE_UPDATE 23 /* Table Name Column Name */ #define SQLITE_ATTACH 24 /* Filename NULL */ #define SQLITE_DETACH 25 /* Database Name NULL */ #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ #define SQLITE_REINDEX 27 /* Index Name NULL */ #define SQLITE_ANALYZE 28 /* Table Name NULL */ #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ #define SQLITE_FUNCTION 31 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ #define SQLITE_COPY 0 /* No longer used */ /* ** CAPI3REF: Tracing And Profiling Functions {H12280} ** EXPERIMENTAL ** ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** ** The callback function registered by sqlite3_trace() is invoked at ** various times when an SQL statement is being run by [sqlite3_step()]. ** The callback returns a UTF-8 rendering of the SQL statement text ** as the statement first begins executing. Additional callbacks occur ** as each triggered subprogram is entered. The callbacks for triggers ** contain a UTF-8 SQL comment that identifies the trigger. ** ** The callback function registered by sqlite3_profile() is invoked ** as each SQL statement finishes. The profile callback contains ** the original statement text and an estimate of wall-clock time ** of how long that statement took to run. ** ** Requirements: ** [H12281] [H12282] [H12283] [H12284] [H12285] [H12287] [H12288] [H12289] ** [H12290] */ SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* ** CAPI3REF: Query Progress Callbacks {H12910} ** ** This routine configures a callback function - the ** progress callback - that is invoked periodically during long ** running calls to [sqlite3_exec()], [sqlite3_step()] and ** [sqlite3_get_table()]. An example use for this ** interface is to keep a GUI updated during a large query. ** ** If the progress callback returns non-zero, the operation is ** interrupted. This feature can be used to implement a ** "Cancel" button on a GUI progress dialog box. ** ** The progress handler must not do anything that will modify ** the database connection that invoked the progress handler. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** Requirements: ** [H12911] [H12912] [H12913] [H12914] [H12915] [H12916] [H12917] [H12918] ** */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection {H12700} ** ** These routines open an SQLite database file whose name is given by the ** filename argument. The filename argument is interpreted as UTF-8 for ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte ** order for sqlite3_open16(). A [database connection] handle is usually ** returned in *ppDb, even if an error occurs. The only exception is that ** if SQLite is unable to allocate memory to hold the [sqlite3] object, ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] ** object. If the database is opened (and/or created) successfully, then ** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error. ** ** The default encoding for the database will be UTF-8 if ** sqlite3_open() or sqlite3_open_v2() is called and ** UTF-16 in the native byte order if sqlite3_open16() is used. ** ** Whether or not an error occurs when it is opened, resources ** associated with the [database connection] handle should be released by ** passing it to [sqlite3_close()] when it is no longer required. ** ** The sqlite3_open_v2() interface works like sqlite3_open() ** except that it accepts two additional parameters for additional control ** over the new database connection. The flags parameter can take one of ** the following three values, optionally combined with the ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], ** and/or [SQLITE_OPEN_PRIVATECACHE] flags: ** **
**
[SQLITE_OPEN_READONLY]
**
The database is opened in read-only mode. If the database does not ** already exist, an error is returned.
** **
[SQLITE_OPEN_READWRITE]
**
The database is opened for reading and writing if possible, or reading ** only if the file is write protected by the operating system. In either ** case the database must already exist, otherwise an error is returned.
** **
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
**
The database is opened for reading and writing, and is creates it if ** it does not already exist. This is the behavior that is always used for ** sqlite3_open() and sqlite3_open16().
**
** ** If the 3rd parameter to sqlite3_open_v2() is not one of the ** combinations shown above or one of the combinations shown above combined ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags, ** then the behavior is undefined. ** ** If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection ** opens in the multi-thread [threading mode] as long as the single-thread ** mode has not been set at compile-time or start-time. If the ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens ** in the serialized [threading mode] unless single-thread was ** previously selected at compile-time or start-time. ** The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be ** eligible to use [shared cache mode], regardless of whether or not shared ** cache is enabled using [sqlite3_enable_shared_cache()]. The ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not ** participate in [shared cache mode] even if it is enabled. ** ** If the filename is ":memory:", then a private, temporary in-memory database ** is created for the connection. This in-memory database will vanish when ** the database connection is closed. Future versions of SQLite might ** make use of additional special filenames that begin with the ":" character. ** It is recommended that when a database filename actually does begin with ** a ":" character you should prefix the filename with a pathname such as ** "./" to avoid ambiguity. ** ** If the filename is an empty string, then a private, temporary ** on-disk database will be created. This private database will be ** automatically deleted as soon as the database connection is closed. ** ** The fourth parameter to sqlite3_open_v2() is the name of the ** [sqlite3_vfs] object that defines the operating system interface that ** the new database connection should use. If the fourth parameter is ** a NULL pointer then the default [sqlite3_vfs] object is used. ** ** Note to Windows users: The encoding used for the filename argument ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into ** sqlite3_open() or sqlite3_open_v2(). ** ** Requirements: ** [H12701] [H12702] [H12703] [H12704] [H12706] [H12707] [H12709] [H12711] ** [H12712] [H12713] [H12714] [H12717] [H12719] [H12721] [H12723] */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open16( const void *filename, /* Database filename (UTF-16) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); SQLITE_API int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); /* ** CAPI3REF: Error Codes And Messages {H12800} ** ** The sqlite3_errcode() interface returns the numeric [result code] or ** [extended result code] for the most recent failed sqlite3_* API call ** associated with a [database connection]. If a prior API call failed ** but the most recent API call succeeded, the return value from ** sqlite3_errcode() is undefined. The sqlite3_extended_errcode() ** interface is the same except that it always returns the ** [extended result code] even when extended result codes are ** disabled. ** ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF-8 or UTF-16 respectively. ** Memory to hold the error message string is managed internally. ** The application does not need to worry about freeing the result. ** However, the error string might be overwritten or deallocated by ** subsequent calls to other SQLite interface functions. ** ** When the serialized [threading mode] is in use, it might be the ** case that a second error occurs on a separate thread in between ** the time of the first error and the call to these interfaces. ** When that happens, the second error will be reported since these ** interfaces always report the most recent result. To avoid ** this, each thread can obtain exclusive use of the [database connection] D ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after ** all calls to the interfaces listed here are completed. ** ** If an interface fails with SQLITE_MISUSE, that means the interface ** was invoked incorrectly by the application. In that case, the ** error code and message may or may not be set. ** ** Requirements: ** [H12801] [H12802] [H12803] [H12807] [H12808] [H12809] */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); SQLITE_API const void *sqlite3_errmsg16(sqlite3*); /* ** CAPI3REF: SQL Statement Object {H13000} ** KEYWORDS: {prepared statement} {prepared statements} ** ** An instance of this object represents a single SQL statement. ** This object is variously known as a "prepared statement" or a ** "compiled SQL statement" or simply as a "statement". ** ** The life of a statement object goes something like this: ** **
    **
  1. Create the object using [sqlite3_prepare_v2()] or a related ** function. **
  2. Bind values to [host parameters] using the sqlite3_bind_*() ** interfaces. **
  3. Run the SQL by calling [sqlite3_step()] one or more times. **
  4. Reset the statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. **
  5. Destroy the object using [sqlite3_finalize()]. **
** ** Refer to documentation on individual methods above for additional ** information. */ typedef struct sqlite3_stmt sqlite3_stmt; /* ** CAPI3REF: Run-time Limits {H12760} ** ** This interface allows the size of various constructs to be limited ** on a connection by connection basis. The first parameter is the ** [database connection] whose limit is to be set or queried. The ** second parameter is one of the [limit categories] that define a ** class of constructs to be size limited. The third parameter is the ** new limit for that construct. The function returns the old limit. ** ** If the new limit is a negative number, the limit is unchanged. ** For the limit category of SQLITE_LIMIT_XYZ there is a ** [limits | hard upper bound] ** set by a compile-time C preprocessor macro named ** [limits | SQLITE_MAX_XYZ]. ** (The "_LIMIT_" in the name is changed to "_MAX_".) ** Attempts to increase a limit above its hard upper bound are ** silently truncated to the hard upper limit. ** ** Run time limits are intended for use in applications that manage ** both their own internal database and also databases that are controlled ** by untrusted external sources. An example application might be a ** web browser that has its own databases for storing history and ** separate databases controlled by JavaScript applications downloaded ** off the Internet. The internal databases can be given the ** large, default limits. Databases managed by external sources can ** be given much smaller limits designed to prevent a denial of service ** attack. Developers might also want to use the [sqlite3_set_authorizer()] ** interface to further control untrusted SQL. The size of the database ** created by an untrusted script can be contained using the ** [max_page_count] [PRAGMA]. ** ** New run-time limit categories may be added in future releases. ** ** Requirements: ** [H12762] [H12766] [H12769] */ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); /* ** CAPI3REF: Run-Time Limit Categories {H12790} ** KEYWORDS: {limit category} {*limit categories} ** ** These constants define various performance limits ** that can be lowered at run-time using [sqlite3_limit()]. ** The synopsis of the meanings of the various limits is shown below. ** Additional information is available at [limits | Limits in SQLite]. ** **
**
SQLITE_LIMIT_LENGTH
**
The maximum size of any string or BLOB or table row.
** **
SQLITE_LIMIT_SQL_LENGTH
**
The maximum length of an SQL statement.
** **
SQLITE_LIMIT_COLUMN
**
The maximum number of columns in a table definition or in the ** result set of a [SELECT] or the maximum number of columns in an index ** or in an ORDER BY or GROUP BY clause.
** **
SQLITE_LIMIT_EXPR_DEPTH
**
The maximum depth of the parse tree on any expression.
** **
SQLITE_LIMIT_COMPOUND_SELECT
**
The maximum number of terms in a compound SELECT statement.
** **
SQLITE_LIMIT_VDBE_OP
**
The maximum number of instructions in a virtual machine program ** used to implement an SQL statement.
** **
SQLITE_LIMIT_FUNCTION_ARG
**
The maximum number of arguments on a function.
** **
SQLITE_LIMIT_ATTACHED
**
The maximum number of [ATTACH | attached databases].
** **
SQLITE_LIMIT_LIKE_PATTERN_LENGTH
**
The maximum length of the pattern argument to the [LIKE] or ** [GLOB] operators.
** **
SQLITE_LIMIT_VARIABLE_NUMBER
**
The maximum number of variables in an SQL statement that can ** be bound.
** **
SQLITE_LIMIT_TRIGGER_DEPTH
**
The maximum depth of recursion for triggers.
**
*/ #define SQLITE_LIMIT_LENGTH 0 #define SQLITE_LIMIT_SQL_LENGTH 1 #define SQLITE_LIMIT_COLUMN 2 #define SQLITE_LIMIT_EXPR_DEPTH 3 #define SQLITE_LIMIT_COMPOUND_SELECT 4 #define SQLITE_LIMIT_VDBE_OP 5 #define SQLITE_LIMIT_FUNCTION_ARG 6 #define SQLITE_LIMIT_ATTACHED 7 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 /* ** CAPI3REF: Compiling An SQL Statement {H13010} ** KEYWORDS: {SQL statement compiler} ** ** To execute an SQL query, it must first be compiled into a byte-code ** program using one of these routines. ** ** The first argument, "db", is a [database connection] obtained from a ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or ** [sqlite3_open16()]. The database connection must not have been closed. ** ** The second argument, "zSql", is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() ** use UTF-16. ** ** If the nByte argument is less than zero, then zSql is read up to the ** first zero terminator. If nByte is non-negative, then it is the maximum ** number of bytes read from zSql. When nByte is non-negative, the ** zSql string ends at either the first '\000' or '\u0000' character or ** the nByte-th byte, whichever comes first. If the caller knows ** that the supplied string is nul-terminated, then there is a small ** performance advantage to be gained by passing an nByte parameter that ** is equal to the number of bytes in the input string including ** the nul-terminator bytes. ** ** If pzTail is not NULL then *pzTail is made to point to the first byte ** past the end of the first SQL statement in zSql. These routines only ** compile the first statement in zSql, so *pzTail is left pointing to ** what remains uncompiled. ** ** *ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. If there is an error, *ppStmt is set ** to NULL. If the input text contains no SQL (if the input is an empty ** string or a comment) then *ppStmt is set to NULL. ** The calling procedure is responsible for deleting the compiled ** SQL statement using [sqlite3_finalize()] after it has finished with it. ** ppStmt may not be NULL. ** ** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned. ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. ** In the "v2" interfaces, the prepared statement ** that is returned (the [sqlite3_stmt] object) contains a copy of the ** original SQL text. This causes the [sqlite3_step()] interface to ** behave a differently in three ways: ** **
    **
  1. ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL ** statement and try to run it again. If the schema has changed in ** a way that makes the statement no longer valid, [sqlite3_step()] will still ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the ** error go away. Note: use [sqlite3_errmsg()] to find the text ** of the parsing error that results in an [SQLITE_SCHEMA] return. **
  2. ** **
  3. ** When an error occurs, [sqlite3_step()] will return one of the detailed ** [error codes] or [extended error codes]. The legacy behavior was that ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code ** and you would have to make a second call to [sqlite3_reset()] in order ** to find the underlying cause of the problem. With the "v2" prepare ** interfaces, the underlying reason for the error is returned immediately. **
  4. ** **
  5. ** ^If the value of a [parameter | host parameter] in the WHERE clause might ** change the query plan for a statement, then the statement may be ** automatically recompiled (as if there had been a schema change) on the first ** [sqlite3_step()] call following any change to the ** [sqlite3_bind_text | bindings] of the [parameter]. **
  6. **
** ** Requirements: ** [H13011] [H13012] [H13013] [H13014] [H13015] [H13016] [H13019] [H13021] ** */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* ** CAPI3REF: Retrieving Statement SQL {H13100} ** ** This interface can be used to retrieve a saved copy of the original ** SQL text used to create a [prepared statement] if that statement was ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. ** ** Requirements: ** [H13101] [H13102] [H13103] */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); /* ** CAPI3REF: Dynamically Typed Value Object {H15000} ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} ** ** SQLite uses the sqlite3_value object to represent all values ** that can be stored in a database table. SQLite uses dynamic typing ** for the values it stores. Values stored in sqlite3_value objects ** can be integers, floating point values, strings, BLOBs, or NULL. ** ** An sqlite3_value object may be either "protected" or "unprotected". ** Some interfaces require a protected sqlite3_value. Other interfaces ** will accept either a protected or an unprotected sqlite3_value. ** Every interface that accepts sqlite3_value arguments specifies ** whether or not it requires a protected sqlite3_value. ** ** The terms "protected" and "unprotected" refer to whether or not ** a mutex is held. A internal mutex is held for a protected ** sqlite3_value object but no mutex is held for an unprotected ** sqlite3_value object. If SQLite is compiled to be single-threaded ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) ** or if SQLite is run in one of reduced mutex modes ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] ** then there is no distinction between protected and unprotected ** sqlite3_value objects and they can be used interchangeably. However, ** for maximum code portability it is recommended that applications ** still make the distinction between between protected and unprotected ** sqlite3_value objects even when not strictly required. ** ** The sqlite3_value objects that are passed as parameters into the ** implementation of [application-defined SQL functions] are protected. ** The sqlite3_value object returned by ** [sqlite3_column_value()] is unprotected. ** Unprotected sqlite3_value objects may only be used with ** [sqlite3_result_value()] and [sqlite3_bind_value()]. ** The [sqlite3_value_blob | sqlite3_value_type()] family of ** interfaces require protected sqlite3_value objects. */ typedef struct Mem sqlite3_value; /* ** CAPI3REF: SQL Function Context Object {H16001} ** ** The context in which an SQL function executes is stored in an ** sqlite3_context object. A pointer to an sqlite3_context object ** is always first parameter to [application-defined SQL functions]. ** The application-defined SQL function implementation will pass this ** pointer through into calls to [sqlite3_result_int | sqlite3_result()], ** [sqlite3_aggregate_context()], [sqlite3_user_data()], ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], ** and/or [sqlite3_set_auxdata()]. */ typedef struct sqlite3_context sqlite3_context; /* ** CAPI3REF: Binding Values To Prepared Statements {H13500} ** KEYWORDS: {host parameter} {host parameters} {host parameter name} ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} ** ** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, ** literals may be replaced by a [parameter] that matches one of following ** templates: ** **
    **
  • ? **
  • ?NNN **
  • :VVV **
  • @VVV **
  • $VVV **
** ** In the templates above, NNN represents an integer literal, ** and VVV represents an alphanumeric identifer. The values of these ** parameters (also called "host parameter names" or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** ** The first argument to the sqlite3_bind_*() routines is always ** a pointer to the [sqlite3_stmt] object returned from ** [sqlite3_prepare_v2()] or its variants. ** ** The second argument is the index of the SQL parameter to be set. ** The leftmost SQL parameter has an index of 1. When the same named ** SQL parameter is used more than once, second and subsequent ** occurrences have the same index as the first occurrence. ** The index for named parameters can be looked up using the ** [sqlite3_bind_parameter_index()] API if desired. The index ** for "?NNN" parameters is the value of NNN. ** The NNN value must be between 1 and the [sqlite3_limit()] ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). ** ** The third argument is the value to bind to the parameter. ** ** In those routines that have a fourth argument, its value is the ** number of bytes in the parameter. To be clear: the value is the ** number of bytes in the value, not the number of characters. ** If the fourth parameter is negative, the length of the string is ** the number of bytes up to the first zero terminator. ** ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or ** string after SQLite has finished with it. If the fifth argument is ** the special value [SQLITE_STATIC], then SQLite assumes that the ** information is in static, unmanaged space and does not need to be freed. ** If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before ** the sqlite3_bind_*() routine returns. ** ** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeroes. A zeroblob uses a fixed amount of memory ** (just an integer to hold its size) while it is being processed. ** Zeroblobs are intended to serve as placeholders for BLOBs whose ** content is later written using ** [sqlite3_blob_open | incremental BLOB I/O] routines. ** A negative value for the zeroblob results in a zero-length BLOB. ** ** The sqlite3_bind_*() routines must be called after ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and ** before [sqlite3_step()]. ** Bindings are not cleared by the [sqlite3_reset()] routine. ** Unbound parameters are interpreted as NULL. ** ** These routines return [SQLITE_OK] on success or an error code if ** anything goes wrong. [SQLITE_RANGE] is returned if the parameter ** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails. ** [SQLITE_MISUSE] might be returned if these routines are called on a ** virtual machine that is the wrong state or which has already been finalized. ** Detection of misuse is unreliable. Applications should not depend ** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a ** a logic error in the application. Future versions of SQLite might ** panic rather than return SQLITE_MISUSE. ** ** See also: [sqlite3_bind_parameter_count()], ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13506] [H13509] [H13512] [H13515] [H13518] [H13521] [H13524] [H13527] ** [H13530] [H13533] [H13536] [H13539] [H13542] [H13545] [H13548] [H13551] ** */ SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); /* ** CAPI3REF: Number Of SQL Parameters {H13600} ** ** This routine can be used to find the number of [SQL parameters] ** in a [prepared statement]. SQL parameters are tokens of the ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as ** placeholders for values that are [sqlite3_bind_blob | bound] ** to the parameters at a later time. ** ** This routine actually returns the index of the largest (rightmost) ** parameter. For all forms except ?NNN, this will correspond to the ** number of unique parameters. If parameters of the ?NNN are used, ** there may be gaps in the list. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_name()], and ** [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13601] */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter {H13620} ** ** This routine returns a pointer to the name of the n-th ** [SQL parameter] in a [prepared statement]. ** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" ** respectively. ** In other words, the initial ":" or "$" or "@" or "?" ** is included as part of the name. ** Parameters of the form "?" without a following integer have no name ** and are also referred to as "anonymous parameters". ** ** The first host parameter has an index of 1, not 0. ** ** If the value n is out of range or if the n-th parameter is ** nameless, then NULL is returned. The returned string is ** always in UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13621] */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name {H13640} ** ** Return the index of an SQL parameter given its name. The ** index value returned is suitable for use as the second ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero ** is returned if no matching parameter is found. The parameter ** name must be given in UTF-8 even if the original statement ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. ** ** See also: [sqlite3_bind_blob|sqlite3_bind()], ** [sqlite3_bind_parameter_count()], and ** [sqlite3_bind_parameter_index()]. ** ** Requirements: ** [H13641] */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement {H13660} ** ** Contrary to the intuition of many, [sqlite3_reset()] does not reset ** the [sqlite3_bind_blob | bindings] on a [prepared statement]. ** Use this routine to reset all host parameters to NULL. ** ** Requirements: ** [H13661] */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set {H13710} ** ** Return the number of columns in the result set returned by the ** [prepared statement]. This routine returns 0 if pStmt is an SQL ** statement that does not return data (for example an [UPDATE]). ** ** Requirements: ** [H13711] */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set {H13720} ** ** These routines return the name assigned to a particular column ** in the result set of a [SELECT] statement. The sqlite3_column_name() ** interface returns a pointer to a zero-terminated UTF-8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated ** UTF-16 string. The first parameter is the [prepared statement] ** that implements the [SELECT] statement. The second parameter is the ** column number. The leftmost column is number 0. ** ** The returned string pointer is valid until either the [prepared statement] ** is destroyed by [sqlite3_finalize()] or until the next call to ** sqlite3_column_name() or sqlite3_column_name16() on the same column. ** ** If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. ** ** The name of a result column is the value of the "AS" clause for ** that column, if there is an AS clause. If there is no AS clause ** then the name of the column is unspecified and may change from ** one release of SQLite to the next. ** ** Requirements: ** [H13721] [H13723] [H13724] [H13725] [H13726] [H13727] */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result {H13740} ** ** These routines provide a means to determine what column of what ** table in which database a result of a [SELECT] statement comes from. ** The name of the database or table or column can be returned as ** either a UTF-8 or UTF-16 string. The _database_ routines return ** the database name, the _table_ routines return the table name, and ** the origin_ routines return the column name. ** The returned string is valid until the [prepared statement] is destroyed ** using [sqlite3_finalize()] or until the same information is requested ** again in a different encoding. ** ** The names returned are the original un-aliased names of the ** database, table, and column. ** ** The first argument to the following calls is a [prepared statement]. ** These functions return information about the Nth column returned by ** the statement, where N is the second function argument. ** ** If the Nth column returned by the statement is an expression or ** subquery and is not a column value, then all of these functions return ** NULL. These routine might also return NULL if a memory allocation error ** occurs. Otherwise, they return the name of the attached database, table ** and column that query result column was extracted from. ** ** As with all other SQLite APIs, those postfixed with "16" return ** UTF-16 encoded strings, the other functions return UTF-8. {END} ** ** These APIs are only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. ** ** {A13751} ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. ** ** Requirements: ** [H13741] [H13742] [H13743] [H13744] [H13745] [H13746] [H13748] ** ** If two or more threads call one or more ** [sqlite3_column_database_name | column metadata interfaces] ** for the same [prepared statement] and result column ** at the same time then the results are undefined. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result {H13760} ** ** The first parameter is a [prepared statement]. ** If this statement is a [SELECT] statement and the Nth column of the ** returned result set of that [SELECT] is a table column (not an ** expression or subquery) then the declared type of the table ** column is returned. If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. ** The returned string is always UTF-8 encoded. {END} ** ** For example, given the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** ** and the following statement to be compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** ** this routine would return the string "VARIANT" for the second result ** column (i==1), and a NULL pointer for the first result column (i==0). ** ** SQLite uses dynamic run-time typing. So just because a column ** is declared to contain a particular type does not mean that the ** data stored in that column is of the declared type. SQLite is ** strongly typed, but the typing is dynamic not static. Type ** is associated with individual values, not with the containers ** used to hold those values. ** ** Requirements: ** [H13761] [H13762] [H13763] */ SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* ** CAPI3REF: Evaluate An SQL Statement {H13200} ** ** After a [prepared statement] has been prepared using either ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function ** must be called one or more times to evaluate the statement. ** ** The details of the behavior of the sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** ** In the legacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. ** With the "v2" interface, any of the other [result codes] or ** [extended result codes] might be returned as well. ** ** [SQLITE_BUSY] means that the database engine was unable to acquire the ** database locks it needs to do its job. If the statement is a [COMMIT] ** or occurs outside of an explicit transaction, then you can retry the ** statement. If the statement is not a [COMMIT] and occurs within a ** explicit transaction then you should rollback the transaction before ** continuing. ** ** [SQLITE_DONE] means that the statement has finished executing ** successfully. sqlite3_step() should not be called again on this virtual ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** ** If the SQL statement being executed returns any data, then [SQLITE_ROW] ** is returned each time a new row of data is ready for processing by the ** caller. The values may be accessed using the [column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. ** ** [SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. ** With the legacy interface, a more specific error code (for example, ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the ** [prepared statement]. In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. ** Perhaps it was called on a [prepared statement] that has ** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** ** Goofy Interface Alert: In the legacy interface, the sqlite3_step() ** API always returns a generic error code, [SQLITE_ERROR], following any ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the ** specific [error codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, ** then the more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. ** ** Requirements: ** [H13202] [H15304] [H15306] [H15308] [H15310] */ SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set {H13770} ** ** Returns the number of values in the current row of the result set. ** ** Requirements: ** [H13771] [H13772] */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes {H10265} ** KEYWORDS: SQLITE_TEXT ** ** {H10266} Every value in SQLite has one of five fundamental datatypes: ** **
    **
  • 64-bit signed integer **
  • 64-bit IEEE floating point number **
  • string **
  • BLOB **
  • NULL **
{END} ** ** These constants are codes for each of those types. ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 #define SQLITE_FLOAT 2 #define SQLITE_BLOB 4 #define SQLITE_NULL 5 #ifdef SQLITE_TEXT # undef SQLITE_TEXT #else # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* ** CAPI3REF: Result Values From A Query {H13800} ** KEYWORDS: {column access functions} ** ** These routines form the "result set query" interface. ** ** These routines return information about a single column of the current ** result row of a query. In every case the first argument is a pointer ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] ** that was returned from [sqlite3_prepare_v2()] or one of its variants) ** and the second argument is the index of the column for which information ** should be returned. The leftmost column of the result set has the index 0. ** The number of columns in the result can be determined using ** [sqlite3_column_count()]. ** ** If the SQL statement does not currently point to a valid row, or if the ** column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines ** are pending, then the results are undefined. ** ** The sqlite3_column_type() routine returns the ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value ** returned by sqlite3_column_type() is only meaningful if no type ** conversions have occurred as described below. After a type conversion, ** the value returned by sqlite3_column_type() is undefined. Future ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** ** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. ** If the result is a numeric value then sqlite3_column_bytes() uses ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns ** the number of bytes in that string. ** The value returned does not include the zero terminator at the end ** of the string. For clarity: the value returned is the number of ** bytes in the string, not the number of characters. ** ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), ** even empty strings, are always zero terminated. The return ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary ** pointer, possibly even a NULL pointer. ** ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() ** but leaves the result in UTF-16 in native byte order instead of UTF-8. ** The zero terminator is not included in this count. ** ** The object returned by [sqlite3_column_value()] is an ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. ** If the [unprotected sqlite3_value] object returned by ** [sqlite3_column_value()] is used in any other way, including calls ** to routines like [sqlite3_value_int()], [sqlite3_value_text()], ** or [sqlite3_value_bytes()], then the behavior is undefined. ** ** These routines attempt to convert the value where appropriate. For ** example, if the internal representation is FLOAT and a text result ** is requested, [sqlite3_snprintf()] is used internally to perform the ** conversion automatically. The following table details the conversions ** that are applied: ** **
** **
Internal
Type
Requested
Type
Conversion ** **
NULL INTEGER Result is 0 **
NULL FLOAT Result is 0.0 **
NULL TEXT Result is NULL pointer **
NULL BLOB Result is NULL pointer **
INTEGER FLOAT Convert from integer to float **
INTEGER TEXT ASCII rendering of the integer **
INTEGER BLOB Same as INTEGER->TEXT **
FLOAT INTEGER Convert from float to integer **
FLOAT TEXT ASCII rendering of the float **
FLOAT BLOB Same as FLOAT->TEXT **
TEXT INTEGER Use atoi() **
TEXT FLOAT Use atof() **
TEXT BLOB No change **
BLOB INTEGER Convert to TEXT then use atoi() **
BLOB FLOAT Convert to TEXT then use atof() **
BLOB TEXT Add a zero terminator if needed **
**
** ** The table above makes reference to standard C library functions atoi() ** and atof(). SQLite does not really use these functions. It has its ** own equivalent internal routines. The atoi() and atof() names are ** used in the table for brevity and because they are familiar to most ** C programmers. ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or ** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** **
    **
  • The initial content is a BLOB and sqlite3_column_text() or ** sqlite3_column_text16() is called. A zero-terminator might ** need to be added to the string.
  • **
  • The initial content is UTF-8 text and sqlite3_column_bytes16() or ** sqlite3_column_text16() is called. The content must be converted ** to UTF-16.
  • **
  • The initial content is UTF-16 text and sqlite3_column_bytes() or ** sqlite3_column_text() is called. The content must be converted ** to UTF-8.
  • **
** ** Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer points to will have been modified. Other kinds ** of conversion are done in place when it is possible, but sometimes they ** are not possible and in those cases prior pointers are invalidated. ** ** The safest and easiest to remember policy is to invoke these routines ** in one of the following ways: ** **
    **
  • sqlite3_column_text() followed by sqlite3_column_bytes()
  • **
  • sqlite3_column_blob() followed by sqlite3_column_bytes()
  • **
  • sqlite3_column_text16() followed by sqlite3_column_bytes16()
  • **
** ** In other words, you should call sqlite3_column_text(), ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result ** into the desired format, then invoke sqlite3_column_bytes() or ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls ** to sqlite3_column_text() or sqlite3_column_blob() with calls to ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() ** with calls to sqlite3_column_bytes(). ** ** The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. The memory space used to hold strings ** and BLOBs is freed automatically. Do not pass the pointers returned ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** If a memory allocation error occurs during the evaluation of any ** of these routines, a default value is returned. The default value ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM]. ** ** Requirements: ** [H13803] [H13806] [H13809] [H13812] [H13815] [H13818] [H13821] [H13824] ** [H13827] [H13830] */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object {H13300} ** ** The sqlite3_finalize() function is called to delete a [prepared statement]. ** If the statement was executed successfully or not executed at all, then ** SQLITE_OK is returned. If execution of the statement failed then an ** [error code] or [extended error code] is returned. ** ** This routine can be called at any point during the execution of the ** [prepared statement]. If the virtual machine has not ** completed execution when this routine is called, that is like ** encountering an error or an [sqlite3_interrupt | interrupt]. ** Incomplete updates may be rolled back and transactions canceled, ** depending on the circumstances, and the ** [error code] returned will be [SQLITE_ABORT]. ** ** Requirements: ** [H11302] [H11304] */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object {H13330} ** ** The sqlite3_reset() function is called to reset a [prepared statement] ** object back to its initial state, ready to be re-executed. ** Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. ** ** {H11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S ** back to the beginning of its program. ** ** {H11334} If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], ** or if [sqlite3_step(S)] has never before been called on S, ** then [sqlite3_reset(S)] returns [SQLITE_OK]. ** ** {H11336} If the most recent call to [sqlite3_step(S)] for the ** [prepared statement] S indicated an error, then ** [sqlite3_reset(S)] returns an appropriate [error code]. ** ** {H11338} The [sqlite3_reset(S)] interface does not change the values ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions {H16100} ** KEYWORDS: {function creation routines} ** KEYWORDS: {application-defined SQL function} ** KEYWORDS: {application-defined SQL functions} ** ** These two functions (collectively known as "function creation routines") ** are used to add SQL functions or aggregates or to redefine the behavior ** of existing SQL functions or aggregates. The only difference between the ** two is that the second parameter, the name of the (scalar) function or ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16 ** for sqlite3_create_function16(). ** ** The first parameter is the [database connection] to which the SQL ** function is to be added. If a single program uses more than one database ** connection internally, then SQL functions must be added individually to ** each database connection. ** ** The second parameter is the name of the SQL function to be created or ** redefined. The length of the name is limited to 255 bytes, exclusive of ** the zero-terminator. Note that the name length limit is in bytes, not ** characters. Any attempt to create a function with a longer name ** will result in [SQLITE_ERROR] being returned. ** ** The third parameter (nArg) ** is the number of arguments that the SQL function or ** aggregate takes. If this parameter is -1, then the SQL function or ** aggregate may take any number of arguments between 0 and the limit ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third ** parameter is less than -1 or greater than 127 then the behavior is ** undefined. ** ** The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. Any SQL function implementation should be able to work ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be ** more efficient with one encoding than another. An application may ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple ** times with the same function but with different values of eTextRep. ** When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. ** If there is only a single implementation which does not care what text ** encoding is used, then the fourth argument should be [SQLITE_ANY]. ** ** The fifth parameter is an arbitrary pointer. The implementation of the ** function can gain access to this pointer using [sqlite3_user_data()]. ** ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are ** pointers to C-language functions that implement the SQL function or ** aggregate. A scalar SQL function requires an implementation of the xFunc ** callback only, NULL pointers should be passed as the xStep and xFinal ** parameters. An aggregate SQL function requires an implementation of xStep ** and xFinal and NULL should be passed for xFunc. To delete an existing ** SQL function or aggregate, pass NULL for all three function callbacks. ** ** It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of ** arguments or differing preferred text encodings. SQLite will use ** the implementation that most closely matches the way in which the ** SQL function is used. A function implementation with a non-negative ** nArg parameter is a better match than a function implementation with ** a negative nArg. A function where the preferred text encoding ** matches the database encoding is a better ** match than a function where the encoding is different. ** A function where the encoding difference is between UTF16le and UTF16be ** is a closer match than a function where the encoding difference is ** between UTF8 and UTF16. ** ** Built-in functions may be overloaded by new application-defined functions. ** The first application-defined function with a given name overrides all ** built-in functions in the same [database connection] with the same name. ** Subsequent application-defined functions of the same name only override ** prior application-defined functions that are an exact match for the ** number of parameters and preferred encoding. ** ** An application-defined function is permitted to call other ** SQLite interfaces. However, such calls must not ** close the database connection nor finalize or reset the prepared ** statement in which the function is running. ** ** Requirements: ** [H16103] [H16106] [H16109] [H16112] [H16118] [H16121] [H16127] ** [H16130] [H16133] [H16136] [H16139] [H16142] */ SQLITE_API int sqlite3_create_function( sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function16( sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); /* ** CAPI3REF: Text Encodings {H10267} ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 #define SQLITE_UTF16LE 2 #define SQLITE_UTF16BE 3 #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* sqlite3_create_function only */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ /* ** CAPI3REF: Deprecated Functions ** DEPRECATED ** ** These functions are [deprecated]. In order to maintain ** backwards compatibility with older code, these functions continue ** to be supported. However, new applications should avoid ** the use of these functions. To help encourage people to avoid ** using these functions, we are not going to tell you what they do. */ #ifndef SQLITE_OMIT_DEPRECATED SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); #endif /* ** CAPI3REF: Obtaining SQL Function Parameter Values {H15100} ** ** The C-language implementation of SQL functions and aggregates uses ** this set of interface routines to access the parameter values on ** the function or aggregate. ** ** The xFunc (for scalar functions) or xStep (for aggregates) parameters ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 4th parameter to these callbacks is an array of pointers to ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** ** These routines work only with [protected sqlite3_value] objects. ** Any attempt to use these routines on an [unprotected sqlite3_value] ** object results in undefined behavior. ** ** These routines work just like the corresponding [column access functions] ** except that these routines take a single [protected sqlite3_value] object ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. ** ** The sqlite3_value_text16() interface extracts a UTF-16 string ** in the native byte-order of the host machine. The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces ** extract UTF-16 strings as big-endian and little-endian respectively. ** ** The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other ** words, if the value is a string that looks like a number) ** then the conversion is performed. Otherwise no conversion occurs. ** The [SQLITE_INTEGER | datatype] after conversion is returned. ** ** Please pay particular attention to the fact that the pointer returned ** from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], ** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as ** the SQL function that supplied the [sqlite3_value*] parameters. ** ** Requirements: ** [H15103] [H15106] [H15109] [H15112] [H15115] [H15118] [H15121] [H15124] ** [H15127] [H15130] [H15133] [H15136] */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); SQLITE_API int sqlite3_value_int(sqlite3_value*); SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); SQLITE_API int sqlite3_value_type(sqlite3_value*); SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* ** CAPI3REF: Obtain Aggregate Function Context {H16210} ** ** The implementation of aggregate SQL functions use this routine to allocate ** a structure for storing their state. ** ** The first time the sqlite3_aggregate_context() routine is called for a ** particular aggregate, SQLite allocates nBytes of memory, zeroes out that ** memory, and returns a pointer to it. On second and subsequent calls to ** sqlite3_aggregate_context() for the same aggregate function index, ** the same buffer is returned. The implementation of the aggregate can use ** the returned buffer to accumulate data. ** ** SQLite automatically frees the allocated buffer when the aggregate ** query concludes. ** ** The first parameter should be a copy of the ** [sqlite3_context | SQL function context] that is the first parameter ** to the callback routine that implements the aggregate function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. ** ** Requirements: ** [H16211] [H16213] [H16215] [H16217] */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions {H16240} ** ** The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. {END} ** ** This routine must be called from the same thread in which ** the application-defined function is running. ** ** Requirements: ** [H16243] */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* ** CAPI3REF: Database Connection For Functions {H16250} ** ** The sqlite3_context_db_handle() interface returns a copy of ** the pointer to the [database connection] (the 1st parameter) ** of the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. ** ** Requirements: ** [H16253] */ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); /* ** CAPI3REF: Function Auxiliary Data {H16270} ** ** The following two functions may be used by scalar SQL functions to ** associate metadata with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under ** some circumstances the associated metadata may be preserved. This may ** be used, for example, to add a regular-expression matching scalar ** function. The compiled version of the regular expression is stored as ** metadata associated with the SQL value passed as the regular expression ** pattern. The compiled regular expression can be reused on multiple ** invocations of the same function so that the original pattern string ** does not need to be recompiled on each invocation. ** ** The sqlite3_get_auxdata() interface returns a pointer to the metadata ** associated by the sqlite3_set_auxdata() function with the Nth argument ** value to the application-defined function. If no metadata has been ever ** been set for the Nth argument of the function, or if the corresponding ** function parameter has changed since the meta-data was set, ** then sqlite3_get_auxdata() returns a NULL pointer. ** ** The sqlite3_set_auxdata() interface saves the metadata ** pointed to by its 3rd parameter as the metadata for the N-th ** argument of the application-defined function. Subsequent ** calls to sqlite3_get_auxdata() might return this data, if it has ** not been destroyed. ** If it is not NULL, SQLite will invoke the destructor ** function given by the 4th parameter to sqlite3_set_auxdata() on ** the metadata when the corresponding function parameter changes ** or when the SQL statement completes, whichever comes first. ** ** SQLite is free to call the destructor and drop metadata on any ** parameter of any function at any time. The only guarantee is that ** the destructor will be called before the metadata is dropped. ** ** In practice, metadata is preserved between function calls for ** expressions that are constant at compile time. This includes literal ** values and SQL variables. ** ** These routines must be called from the same thread in which ** the SQL function is running. ** ** Requirements: ** [H16272] [H16274] [H16276] [H16277] [H16278] [H16279] */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior {H10280} ** ** These are special values for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant ** and will never change. It does not need to be destroyed. The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. ** ** The typedef is necessary to work around problems in certain ** C++ compilers. See ticket #2191. */ typedef void (*sqlite3_destructor_type)(void*); #define SQLITE_STATIC ((sqlite3_destructor_type)0) #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) /* ** CAPI3REF: Setting The Result Of An SQL Function {H16400} ** ** These routines are used by the xFunc or xFinal callbacks that ** implement SQL functions and aggregates. See ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** ** These functions work very much like the [parameter binding] family of ** functions used to bind values to host parameters in prepared statements. ** Refer to the [SQL parameter] documentation for additional information. ** ** The sqlite3_result_blob() interface sets the result from ** an application-defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the ** third parameter. ** ** The sqlite3_result_zeroblob() interfaces set the result of ** the application-defined function to be a BLOB containing all zero ** bytes and N bytes in size, where N is the value of the 2nd parameter. ** ** The sqlite3_result_double() interface sets the result from ** an application-defined function to be a floating point value specified ** by its 2nd argument. ** ** The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. ** SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() ** as the text of an error message. SQLite interprets the error ** message string from sqlite3_result_error() as UTF-8. SQLite ** interprets the string from sqlite3_result_error16() as UTF-16 in native ** byte order. If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. ** If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. ** The sqlite3_result_error() and sqlite3_result_error16() ** routines make a private copy of the error message text before ** they return. Hence, the calling function can deallocate or ** modify the text after they return without harm. ** The sqlite3_result_error_code() function changes the error code ** returned by SQLite as a result of an error in a function. By default, ** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error() ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** ** The sqlite3_result_toobig() interface causes SQLite to throw an error ** indicating that a string or BLOB is to long to represent. ** ** The sqlite3_result_nomem() interface causes SQLite to throw an error ** indicating that a memory allocation failed. ** ** The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. ** The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** ** The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** ** The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. ** SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. ** If the 3rd parameter to the sqlite3_result_text* interfaces ** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. ** If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. ** If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that ** function as the destructor on the text or BLOB result when it has ** finished using that result. ** If the 4th parameter to the sqlite3_result_text* interfaces or to ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite ** assumes that the text or BLOB result is in constant space and does not ** copy the content of the parameter nor call a destructor on the content ** when it has finished using that result. ** If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** ** The sqlite3_result_value() interface sets the result of ** the application-defined function to be a copy the ** [unprotected sqlite3_value] object specified by the 2nd parameter. The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] ** so that the [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. ** A [protected sqlite3_value] object may always be used where an ** [unprotected sqlite3_value] object is required, so either ** kind of [sqlite3_value] object can be used with this interface. ** ** If these routines are called from within the different thread ** than the one containing the application-defined function that received ** the [sqlite3_context] pointer, the results are undefined. ** ** Requirements: ** [H16403] [H16406] [H16409] [H16412] [H16415] [H16418] [H16421] [H16424] ** [H16427] [H16430] [H16433] [H16436] [H16439] [H16442] [H16445] [H16448] ** [H16451] [H16454] [H16457] [H16460] [H16463] */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); /* ** CAPI3REF: Define New Collating Sequences {H16600} ** ** These functions are used to add new collation sequences to the ** [database connection] specified as the first argument. ** ** The name of the new collation sequence is specified as a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() ** and a UTF-16 string for sqlite3_create_collation16(). In all cases ** the name is passed as the second function argument. ** ** The third argument may be one of the constants [SQLITE_UTF8], ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied ** routine expects to be passed pointers to strings encoded using UTF-8, ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The ** third argument might also be [SQLITE_UTF16] to indicate that the routine ** expects pointers to be UTF-16 strings in the native byte order, or the ** argument can be [SQLITE_UTF16_ALIGNED] if the ** the routine expects pointers to 16-bit word aligned strings ** of UTF-16 in the native byte order. ** ** A pointer to the user supplied routine must be passed as the fifth ** argument. If it is NULL, this is the same as deleting the collation ** sequence (so that SQLite cannot call it anymore). ** Each time the application supplied function is invoked, it is passed ** as its first parameter a copy of the void* passed as the fourth argument ** to sqlite3_create_collation() or sqlite3_create_collation16(). ** ** The remaining arguments to the application-supplied routine are two strings, ** each represented by a (length, data) pair and encoded in the encoding ** that was passed as the third argument when the collation sequence was ** registered. {END} The application defined collation routine should ** return negative, zero or positive if the first string is less than, ** equal to, or greater than the second string. i.e. (STRING1 - STRING2). ** ** The sqlite3_create_collation_v2() works like sqlite3_create_collation() ** except that it takes an extra argument which is a destructor for ** the collation. The destructor is called when the collation is ** destroyed and is passed a copy of the fourth parameter void* pointer ** of the sqlite3_create_collation_v2(). ** Collations are destroyed when they are overridden by later calls to the ** collation creation functions or when the [database connection] is closed ** using [sqlite3_close()]. ** ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. ** ** Requirements: ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621] ** [H16624] [H16627] [H16630] */ SQLITE_API int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, void*, int(*xCompare)(void*,int,const void*,int,const void*) ); SQLITE_API int sqlite3_create_collation_v2( sqlite3*, const char *zName, int eTextRep, void*, int(*xCompare)(void*,int,const void*,int,const void*), void(*xDestroy)(void*) ); SQLITE_API int sqlite3_create_collation16( sqlite3*, const void *zName, int eTextRep, void*, int(*xCompare)(void*,int,const void*,int,const void*) ); /* ** CAPI3REF: Collation Needed Callbacks {H16700} ** ** To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the ** [database connection] to be called whenever an undefined collation ** sequence is required. ** ** If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings ** encoded in UTF-8. {H16703} If sqlite3_collation_needed16() is used, ** the names are passed as UTF-16 in machine native byte order. ** A call to either function replaces any existing callback. ** ** When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or ** sqlite3_collation_needed16(). The second argument is the database ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation ** sequence function required. The fourth parameter is the name of the ** required collation sequence. ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. ** ** Requirements: ** [H16702] [H16704] [H16706] */ SQLITE_API int sqlite3_collation_needed( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const char*) ); SQLITE_API int sqlite3_collation_needed16( sqlite3*, void*, void(*)(void*,sqlite3*,int eTextRep,const void*) ); /* ** Specify the key for an encrypted database. This routine should be ** called right after sqlite3_open(). ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_key( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The key */ ); /* ** Change the key on an open database. If the current database is not ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the ** database is decrypted. ** ** The code to implement this API is not available in the public release ** of SQLite. */ SQLITE_API int sqlite3_rekey( sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); /* ** CAPI3REF: Suspend Execution For A Short Time {H10530} ** ** The sqlite3_sleep() function causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** ** If the operating system does not support sleep requests with ** millisecond time resolution, then the time will be rounded up to ** the nearest second. The number of milliseconds of sleep actually ** requested from the operating system is returned. ** ** SQLite implements this interface by calling the xSleep() ** method of the default [sqlite3_vfs] object. ** ** Requirements: [H10533] [H10536] */ SQLITE_API int sqlite3_sleep(int); /* ** CAPI3REF: Name Of The Folder Holding Temporary Files {H10310} ** ** If this global variable is made to point to a string which is ** the name of a folder (a.k.a. directory), then all temporary files ** created by SQLite will be placed in that directory. If this variable ** is a NULL pointer, then SQLite performs a search for an appropriate ** temporary file directory. ** ** It is not safe to read or modify this variable in more than one ** thread at a time. It is not safe to read or modify this variable ** if a [database connection] is being used at the same time in a separate ** thread. ** It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been called and that this variable remain unchanged ** thereafter. ** ** The [temp_store_directory pragma] may modify this variable and cause ** it to point to memory obtained from [sqlite3_malloc]. Furthermore, ** the [temp_store_directory pragma] always assumes that any string ** that this variable points to is held in memory obtained from ** [sqlite3_malloc] and the pragma may attempt to free that memory ** using [sqlite3_free]. ** Hence, if this variable is modified directly, either it should be ** made NULL or made to point to memory obtained from [sqlite3_malloc] ** or else the use of the [temp_store_directory pragma] should be avoided. */ SQLITE_API char *sqlite3_temp_directory; /* ** CAPI3REF: Test For Auto-Commit Mode {H12930} ** KEYWORDS: {autocommit mode} ** ** The sqlite3_get_autocommit() interface returns non-zero or ** zero if the given database connection is or is not in autocommit mode, ** respectively. Autocommit mode is on by default. ** Autocommit mode is disabled by a [BEGIN] statement. ** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. ** ** If certain kinds of errors occur on a statement within a multi-statement ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the ** transaction might be rolled back automatically. The only way to ** find out whether SQLite automatically rolled back the transaction after ** an error is to use this function. ** ** If another thread changes the autocommit status of the database ** connection while this routine is running, then the return value ** is undefined. ** ** Requirements: [H12931] [H12932] [H12933] [H12934] */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* ** CAPI3REF: Find The Database Handle Of A Prepared Statement {H13120} ** ** The sqlite3_db_handle interface returns the [database connection] handle ** to which a [prepared statement] belongs. The [database connection] ** returned by sqlite3_db_handle is the same [database connection] that was the first argument ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to ** create the statement in the first place. ** ** Requirements: [H13123] */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); /* ** CAPI3REF: Find the next prepared statement {H13140} ** ** This interface returns a pointer to the next [prepared statement] after ** pStmt associated with the [database connection] pDb. If pStmt is NULL ** then this interface returns a pointer to the first prepared statement ** associated with the database connection pDb. If no prepared statement ** satisfies the conditions of this routine, it returns NULL. ** ** The [database connection] pointer D in a call to ** [sqlite3_next_stmt(D,S)] must refer to an open database ** connection and in particular must not be a NULL pointer. ** ** Requirements: [H13143] [H13146] [H13149] [H13152] */ SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks {H12950} ** ** The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is [COMMIT | committed]. ** Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. ** Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. ** The pArg argument is passed through to the callback. ** If the callback on a commit hook function returns non-zero, ** then the commit is converted into a rollback. ** ** If another function was previously registered, its ** pArg value is returned. Otherwise NULL is returned. ** ** The callback implementation must not do anything that will modify ** the database connection that invoked the callback. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the commit ** or rollback hook in the first place. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** Registering a NULL function disables the callback. ** ** When the commit hook callback routine returns zero, the [COMMIT] ** operation is allowed to continue normally. If the commit hook ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. ** The rollback hook is invoked on a rollback that results from a commit ** hook returning non-zero, just as it would be with any other rollback. ** ** For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. ** The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. ** The rollback callback is not invoked if a transaction is ** rolled back because a commit callback returned non-zero. ** Check on this ** ** See also the [sqlite3_update_hook()] interface. ** ** Requirements: ** [H12951] [H12952] [H12953] [H12954] [H12955] ** [H12961] [H12962] [H12963] [H12964] */ SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks {H12970} ** ** The sqlite3_update_hook() interface registers a callback function ** with the [database connection] identified by the first argument ** to be invoked whenever a row is updated, inserted or deleted. ** Any callback set by a previous call to this function ** for the same database connection is overridden. ** ** The second argument is a pointer to the function to invoke when a ** row is updated, inserted or deleted. ** The first argument to the callback is a copy of the third argument ** to sqlite3_update_hook(). ** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], ** or [SQLITE_UPDATE], depending on the operation that caused the callback ** to be invoked. ** The third and fourth arguments to the callback contain pointers to the ** database and table name containing the affected row. ** The final callback parameter is the [rowid] of the row. ** In the case of an update, this is the [rowid] after the update takes place. ** ** The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence). ** ** In the current implementation, the update hook ** is not invoked when duplication rows are deleted because of an ** [ON CONFLICT | ON CONFLICT REPLACE] clause. Nor is the update hook ** invoked when rows are deleted using the [truncate optimization]. ** The exceptions defined in this paragraph might change in a future ** release of SQLite. ** ** The update hook implementation must not do anything that will modify ** the database connection that invoked the update hook. Any actions ** to modify the database connection must be deferred until after the ** completion of the [sqlite3_step()] call that triggered the update hook. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their ** database connections for the meaning of "modify" in this paragraph. ** ** If another function was previously registered, its pArg value ** is returned. Otherwise NULL is returned. ** ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] ** interfaces. ** ** Requirements: ** [H12971] [H12973] [H12975] [H12977] [H12979] [H12981] [H12983] [H12986] */ SQLITE_API void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* ** CAPI3REF: Enable Or Disable Shared Pager Cache {H10330} ** KEYWORDS: {shared cache} ** ** This routine enables or disables the sharing of the database cache ** and schema data structures between [database connection | connections] ** to the same database. Sharing is enabled if the argument is true ** and disabled if the argument is false. ** ** Cache sharing is enabled and disabled for an entire process. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, ** sharing was enabled or disabled for each thread separately. ** ** The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. ** Existing database connections continue use the sharing mode ** that was in effect at the time they were opened. ** ** Virtual tables cannot be used with a shared cache. When shared ** cache is enabled, the [sqlite3_create_module()] API used to register ** virtual tables will always return an error. ** ** This routine returns [SQLITE_OK] if shared cache was enabled or disabled ** successfully. An [error code] is returned otherwise. ** ** Shared cache is disabled by default. But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. ** ** See Also: [SQLite Shared-Cache Mode] ** ** Requirements: [H10331] [H10336] [H10337] [H10339] */ SQLITE_API int sqlite3_enable_shared_cache(int); /* ** CAPI3REF: Attempt To Free Heap Memory {H17340} ** ** The sqlite3_release_memory() interface attempts to free N bytes ** of heap memory by deallocating non-essential memory allocations ** held by the database library. {END} Memory used to cache database ** pages to improve performance is an example of non-essential memory. ** sqlite3_release_memory() returns the number of bytes actually freed, ** which might be more or less than the amount requested. ** ** Requirements: [H17341] [H17342] */ SQLITE_API int sqlite3_release_memory(int); /* ** CAPI3REF: Impose A Limit On Heap Size {H17350} ** ** The sqlite3_soft_heap_limit() interface places a "soft" limit ** on the amount of heap memory that may be allocated by SQLite. ** If an internal allocation is requested that would exceed the ** soft heap limit, [sqlite3_release_memory()] is invoked one or ** more times to free up some space before the allocation is performed. ** ** The limit is called "soft", because if [sqlite3_release_memory()] ** cannot free sufficient memory to prevent the limit from being exceeded, ** the memory is allocated anyway and the current operation proceeds. ** ** A negative or zero value for N means that there is no soft heap limit and ** [sqlite3_release_memory()] will only be called when memory is exhausted. ** The default value for the soft heap limit is zero. ** ** SQLite makes a best effort to honor the soft heap limit. ** But if the soft heap limit cannot be honored, execution will ** continue without error or notification. This is why the limit is ** called a "soft" limit. It is advisory only. ** ** Prior to SQLite version 3.5.0, this routine only constrained the memory ** allocated by a single thread - the same thread in which this routine ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is ** applied to all threads. The value specified for the soft heap limit ** is an upper bound on the total memory allocation for all threads. In ** version 3.5.0 there is no mechanism for limiting the heap usage for ** individual threads. ** ** Requirements: ** [H16351] [H16352] [H16353] [H16354] [H16355] [H16358] */ SQLITE_API void sqlite3_soft_heap_limit(int); /* ** CAPI3REF: Extract Metadata About A Column Of A Table {H12850} ** ** This routine returns metadata about a specific column of a specific ** database table accessible using the [database connection] handle ** passed as the first function argument. ** ** The column is identified by the second, third and fourth parameters to ** this function. The second parameter is either the name of the database ** (i.e. "main", "temp" or an attached database) containing the specified ** table or NULL. If it is NULL, then all attached databases are searched ** for the table using the same algorithm used by the database engine to ** resolve unqualified table references. ** ** The third and fourth parameters to this function are the table and column ** name of the desired column, respectively. Neither of these parameters ** may be NULL. ** ** Metadata is returned by writing to the memory locations passed as the 5th ** and subsequent parameters to this function. Any of these arguments may be ** NULL, in which case the corresponding element of metadata is omitted. ** **
** **
Parameter Output
Type
Description ** **
5th const char* Data type **
6th const char* Name of default collation sequence **
7th int True if column has a NOT NULL constraint **
8th int True if column is part of the PRIMARY KEY **
9th int True if column is [AUTOINCREMENT] **
**
** ** The memory pointed to by the character pointers returned for the ** declaration type and collation sequence is valid only until the next ** call to any SQLite API function. ** ** If the specified table is actually a view, an [error code] is returned. ** ** If the specified column is "rowid", "oid" or "_rowid_" and an ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. If there is no ** explicitly declared [INTEGER PRIMARY KEY] column, then the output ** parameters are set as follows: ** **
**     data type: "INTEGER"
**     collation sequence: "BINARY"
**     not null: 0
**     primary key: 1
**     auto increment: 0
** 
** ** This function may load one or more schemas from database files. If an ** error occurs during this process, or if the requested table or column ** cannot be found, an [error code] is returned and an error message left ** in the [database connection] (to be retrieved using sqlite3_errmsg()). ** ** This API is only available if the library was compiled with the ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. */ SQLITE_API int sqlite3_table_column_metadata( sqlite3 *db, /* Connection handle */ const char *zDbName, /* Database name or NULL */ const char *zTableName, /* Table name */ const char *zColumnName, /* Column name */ char const **pzDataType, /* OUTPUT: Declared data type */ char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* ** CAPI3REF: Load An Extension {H12600} ** ** This interface loads an SQLite extension library from the named file. ** ** {H12601} The sqlite3_load_extension() interface attempts to load an ** SQLite extension library contained in the file zFile. ** ** {H12602} The entry point is zProc. ** ** {H12603} zProc may be 0, in which case the name of the entry point ** defaults to "sqlite3_extension_init". ** ** {H12604} The sqlite3_load_extension() interface shall return ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. ** ** {H12605} If an error occurs and pzErrMsg is not 0, then the ** [sqlite3_load_extension()] interface shall attempt to ** fill *pzErrMsg with error message text stored in memory ** obtained from [sqlite3_malloc()]. {END} The calling function ** should free this memory by calling [sqlite3_free()]. ** ** {H12606} Extension loading must be enabled using ** [sqlite3_enable_load_extension()] prior to calling this API, ** otherwise an error will be returned. */ SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ const char *zFile, /* Name of the shared library containing extension */ const char *zProc, /* Entry point. Derived from zFile if 0 */ char **pzErrMsg /* Put error message here if not 0 */ ); /* ** CAPI3REF: Enable Or Disable Extension Loading {H12620} ** ** So as not to open security holes in older applications that are ** unprepared to deal with extension loading, and as a means of disabling ** extension loading while evaluating user-entered SQL, the following API ** is provided to turn the [sqlite3_load_extension()] mechanism on and off. ** ** Extension loading is off by default. See ticket #1863. ** ** {H12621} Call the sqlite3_enable_load_extension() routine with onoff==1 ** to turn extension loading on and call it with onoff==0 to turn ** it back off again. ** ** {H12622} Extension loading is off by default. */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* ** CAPI3REF: Automatically Load An Extensions {H12640} ** ** This API can be invoked at program startup in order to register ** one or more statically linked extensions that will be available ** to all new [database connections]. {END} ** ** This routine stores a pointer to the extension in an array that is ** obtained from [sqlite3_malloc()]. If you run a memory leak checker ** on your program and it reports a leak because of this array, invoke ** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory. ** ** {H12641} This function registers an extension entry point that is ** automatically invoked whenever a new [database connection] ** is opened using [sqlite3_open()], [sqlite3_open16()], ** or [sqlite3_open_v2()]. ** ** {H12642} Duplicate extensions are detected so calling this routine ** multiple times with the same extension is harmless. ** ** {H12643} This routine stores a pointer to the extension in an array ** that is obtained from [sqlite3_malloc()]. ** ** {H12644} Automatic extensions apply across all threads. */ SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); /* ** CAPI3REF: Reset Automatic Extension Loading {H12660} ** ** This function disables all previously registered automatic ** extensions. {END} It undoes the effect of all prior ** [sqlite3_auto_extension()] calls. ** ** {H12661} This function disables all previously registered ** automatic extensions. ** ** {H12662} This function disables automatic extensions in all threads. */ SQLITE_API void sqlite3_reset_auto_extension(void); /* ****** EXPERIMENTAL - subject to change without notice ************** ** ** The interface to the virtual-table mechanism is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. */ /* ** Structures used by the virtual table interface */ typedef struct sqlite3_vtab sqlite3_vtab; typedef struct sqlite3_index_info sqlite3_index_info; typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; typedef struct sqlite3_module sqlite3_module; /* ** CAPI3REF: Virtual Table Object {H18000} ** KEYWORDS: sqlite3_module {virtual table module} ** EXPERIMENTAL ** ** This structure, sometimes called a a "virtual table module", ** defines the implementation of a [virtual tables]. ** This structure consists mostly of methods for the module. ** ** A virtual table module is created by filling in a persistent ** instance of this structure and passing a pointer to that instance ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. ** The registration remains valid until it is replaced by a different ** module or until the [database connection] closes. The content ** of this structure must not change while it is registered with ** any database connection. */ struct sqlite3_module { int iVersion; int (*xCreate)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xConnect)(sqlite3*, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char**); int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); int (*xDisconnect)(sqlite3_vtab *pVTab); int (*xDestroy)(sqlite3_vtab *pVTab); int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); int (*xClose)(sqlite3_vtab_cursor*); int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, int argc, sqlite3_value **argv); int (*xNext)(sqlite3_vtab_cursor*); int (*xEof)(sqlite3_vtab_cursor*); int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); int (*xBegin)(sqlite3_vtab *pVTab); int (*xSync)(sqlite3_vtab *pVTab); int (*xCommit)(sqlite3_vtab *pVTab); int (*xRollback)(sqlite3_vtab *pVTab); int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg); int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); }; /* ** CAPI3REF: Virtual Table Indexing Information {H18100} ** KEYWORDS: sqlite3_index_info ** EXPERIMENTAL ** ** The sqlite3_index_info structure and its substructures is used to ** pass information into and receive the reply from the [xBestIndex] ** method of a [virtual table module]. The fields under **Inputs** are the ** inputs to xBestIndex and are read-only. xBestIndex inserts its ** results into the **Outputs** fields. ** ** The aConstraint[] array records WHERE clause constraints of the form: ** **
column OP expr
** ** where OP is =, <, <=, >, or >=. The particular operator is ** stored in aConstraint[].op. The index of the column is stored in ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot. ** ** The optimizer automatically inverts terms of the form "expr OP column" ** and makes other simplifications to the WHERE clause in an attempt to ** get as many WHERE clause terms into the form shown above as possible. ** The aConstraint[] array only reports WHERE clause terms in the correct ** form that refer to the particular virtual table being queried. ** ** Information about the ORDER BY clause is stored in aOrderBy[]. ** Each term of aOrderBy records a column of the ORDER BY clause. ** ** The [xBestIndex] method must fill aConstraintUsage[] with information ** about what parameters to pass to xFilter. If argvIndex>0 then ** the right-hand side of the corresponding aConstraint[] is evaluated ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit ** is true, then the constraint is assumed to be fully handled by the ** virtual table and is not checked again by SQLite. ** ** The idxNum and idxPtr values are recorded and passed into the ** [xFilter] method. ** [sqlite3_free()] is used to free idxPtr if and only iff ** needToFreeIdxPtr is true. ** ** The orderByConsumed means that output from [xFilter]/[xNext] will occur in ** the correct order to satisfy the ORDER BY clause so that no separate ** sorting step is required. ** ** The estimatedCost value is an estimate of the cost of doing the ** particular lookup. A full scan of a table with N entries should have ** a cost of N. A binary search of a table of N entries should have a ** cost of approximately log(N). */ struct sqlite3_index_info { /* Inputs */ int nConstraint; /* Number of entries in aConstraint */ struct sqlite3_index_constraint { int iColumn; /* Column on left-hand side of constraint */ unsigned char op; /* Constraint operator */ unsigned char usable; /* True if this constraint is usable */ int iTermOffset; /* Used internally - xBestIndex should ignore */ } *aConstraint; /* Table of WHERE clause constraints */ int nOrderBy; /* Number of terms in the ORDER BY clause */ struct sqlite3_index_orderby { int iColumn; /* Column number */ unsigned char desc; /* True for DESC. False for ASC. */ } *aOrderBy; /* The ORDER BY clause */ /* Outputs */ struct sqlite3_index_constraint_usage { int argvIndex; /* if >0, constraint is part of argv to xFilter */ unsigned char omit; /* Do not code a test for this constraint */ } *aConstraintUsage; int idxNum; /* Number used to identify the index */ char *idxStr; /* String, possibly obtained from sqlite3_malloc */ int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ int orderByConsumed; /* True if output is already ordered */ double estimatedCost; /* Estimated cost of using this index */ }; #define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_MATCH 64 /* ** CAPI3REF: Register A Virtual Table Implementation {H18200} ** EXPERIMENTAL ** ** This routine is used to register a new [virtual table module] name. ** Module names must be registered before ** creating a new [virtual table] using the module, or before using a ** preexisting [virtual table] for the module. ** ** The module name is registered on the [database connection] specified ** by the first parameter. The name of the module is given by the ** second parameter. The third parameter is a pointer to ** the implementation of the [virtual table module]. The fourth ** parameter is an arbitrary client data pointer that is passed through ** into the [xCreate] and [xConnect] methods of the virtual table module ** when a new virtual table is be being created or reinitialized. ** ** This interface has exactly the same effect as calling ** [sqlite3_create_module_v2()] with a NULL client data destructor. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData /* Client data for xCreate/xConnect */ ); /* ** CAPI3REF: Register A Virtual Table Implementation {H18210} ** EXPERIMENTAL ** ** This routine is identical to the [sqlite3_create_module()] method, ** except that it has an extra parameter to specify ** a destructor function for the client data pointer. SQLite will ** invoke the destructor function (if it is not NULL) when SQLite ** no longer needs the pClientData pointer. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2( sqlite3 *db, /* SQLite connection to register module with */ const char *zName, /* Name of the module */ const sqlite3_module *p, /* Methods for the module */ void *pClientData, /* Client data for xCreate/xConnect */ void(*xDestroy)(void*) /* Module destructor function */ ); /* ** CAPI3REF: Virtual Table Instance Object {H18010} ** KEYWORDS: sqlite3_vtab ** EXPERIMENTAL ** ** Every [virtual table module] implementation uses a subclass ** of the following structure to describe a particular instance ** of the [virtual table]. Each subclass will ** be tailored to the specific needs of the module implementation. ** The purpose of this superclass is to define certain fields that are ** common to all module implementations. ** ** Virtual tables methods can set an error message by assigning a ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should ** take care that any prior string is freed by a call to [sqlite3_free()] ** prior to assigning a new string to zErrMsg. After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ int nRef; /* NO LONGER USED */ char *zErrMsg; /* Error message from sqlite3_mprintf() */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Virtual Table Cursor Object {H18020} ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} ** EXPERIMENTAL ** ** Every [virtual table module] implementation uses a subclass of the ** following structure to describe cursors that point into the ** [virtual table] and are used ** to loop through the virtual table. Cursors are created using the ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed ** by the [sqlite3_module.xClose | xClose] method. Cussors are used ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods ** of the module. Each module implementation will define ** the content of a cursor structure to suit its own needs. ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ /* Virtual table implementations will typically add additional fields */ }; /* ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} ** EXPERIMENTAL ** ** The [xCreate] and [xConnect] methods of a ** [virtual table module] call this interface ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL); /* ** CAPI3REF: Overload A Function For A Virtual Table {H18300} ** EXPERIMENTAL ** ** Virtual tables can provide alternative implementations of functions ** using the [xFindFunction] method of the [virtual table module]. ** But global versions of those functions ** must exist in order to be overloaded. ** ** This API makes sure a global version of a function with a particular ** name and number of parameters exists. If no such function exists ** before this API is called, a new function is created. The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only ** purpose is to be a placeholder function that can be overloaded ** by a [virtual table]. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** The interface to the virtual-table mechanism defined above (back up ** to a comment remarkably similar to this one) is currently considered ** to be experimental. The interface might change in incompatible ways. ** If this is a problem for you, do not use the interface at this time. ** ** When the virtual-table mechanism stabilizes, we will declare the ** interface fixed, support it indefinitely, and remove this comment. ** ****** EXPERIMENTAL - subject to change without notice ************** */ /* ** CAPI3REF: A Handle To An Open BLOB {H17800} ** KEYWORDS: {BLOB handle} {BLOB handles} ** ** An instance of this object represents an open BLOB on which ** [sqlite3_blob_open | incremental BLOB I/O] can be performed. ** Objects of this type are created by [sqlite3_blob_open()] ** and destroyed by [sqlite3_blob_close()]. ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces ** can be used to read or write small subsections of the BLOB. ** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O {H17810} ** ** This interfaces opens a [BLOB handle | handle] to the BLOB located ** in row iRow, column zColumn, table zTable in database zDb; ** in other words, the same BLOB that would be selected by: ** **
**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
** 
{END} ** ** If the flags parameter is non-zero, then the BLOB is opened for read ** and write access. If it is zero, the BLOB is opened for read access. ** It is not possible to open a column that is part of an index or primary ** key for writing. ^If [foreign key constraints] are enabled, it is ** not possible to open a column that is part of a [child key] for writing. ** ** Note that the database name is not the filename that contains ** the database but rather the symbolic name of the database that ** is assigned when the database is connected using [ATTACH]. ** For the main database file, the database name is "main". ** For TEMP tables, the database name is "temp". ** ** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set ** to be a null pointer. ** This function sets the [database connection] error code and message ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related ** functions. Note that the *ppBlob variable is always initialized in a ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob ** regardless of the success or failure of this routine. ** ** If the row that a BLOB handle points to is modified by an ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects ** then the BLOB handle is marked as "expired". ** This is true if any column of the row is changed, even a column ** other than the one the BLOB handle is open on. ** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for ** a expired BLOB handle fail with an return code of [SQLITE_ABORT]. ** Changes written into a BLOB prior to the BLOB expiring are not ** rollback by the expiration of the BLOB. Such changes will eventually ** commit if the transaction continues to completion. ** ** Use the [sqlite3_blob_bytes()] interface to determine the size of ** the opened blob. The size of a blob may not be changed by this ** interface. Use the [UPDATE] SQL command to change the size of a ** blob. ** ** The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces ** and the built-in [zeroblob] SQL function can be used, if desired, ** to create an empty, zero-filled blob in which to read or write using ** this interface. ** ** To avoid a resource leak, every open [BLOB handle] should eventually ** be released by a call to [sqlite3_blob_close()]. ** ** Requirements: ** [H17813] [H17814] [H17816] [H17819] [H17821] [H17824] */ SQLITE_API int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* ** CAPI3REF: Close A BLOB Handle {H17830} ** ** Closes an open [BLOB handle]. ** ** Closing a BLOB shall cause the current transaction to commit ** if there are no other BLOBs, no pending prepared statements, and the ** database connection is in [autocommit mode]. ** If any writes were made to the BLOB, they might be held in cache ** until the close operation if they will fit. ** ** Closing the BLOB often forces the changes ** out to disk and so if any I/O errors occur, they will likely occur ** at the time when the BLOB is closed. Any errors that occur during ** closing are reported as a non-zero return value. ** ** The BLOB is closed unconditionally. Even if this routine returns ** an error code, the BLOB is still closed. ** ** Calling this routine with a null pointer (which as would be returned ** by failed call to [sqlite3_blob_open()]) is a harmless no-op. ** ** Requirements: ** [H17833] [H17836] [H17839] */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* ** CAPI3REF: Return The Size Of An Open BLOB {H17840} ** ** Returns the size in bytes of the BLOB accessible via the ** successfully opened [BLOB handle] in its only argument. The ** incremental blob I/O routines can only read or overwriting existing ** blob content; they cannot change the size of a blob. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** Requirements: ** [H17843] */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* ** CAPI3REF: Read Data From A BLOB Incrementally {H17850} ** ** This function is used to read data from an open [BLOB handle] into a ** caller-supplied buffer. N bytes of data are copied into buffer Z ** from the open BLOB, starting at offset iOffset. ** ** If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is ** less than zero, [SQLITE_ERROR] is returned and no data is read. ** The size of the blob (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** An attempt to read from an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. ** ** On success, SQLITE_OK is returned. ** Otherwise, an [error code] or an [extended error code] is returned. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_write()]. ** ** Requirements: ** [H17853] [H17856] [H17859] [H17862] [H17863] [H17865] [H17868] */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); /* ** CAPI3REF: Write Data Into A BLOB Incrementally {H17870} ** ** This function is used to write data into an open [BLOB handle] from a ** caller-supplied buffer. N bytes of data are copied from the buffer Z ** into the open BLOB, starting at offset iOffset. ** ** If the [BLOB handle] passed as the first argument was not opened for ** writing (the flags parameter to [sqlite3_blob_open()] was zero), ** this function returns [SQLITE_READONLY]. ** ** This function may only modify the contents of the BLOB; it is ** not possible to increase the size of a BLOB using this API. ** If offset iOffset is less than N bytes from the end of the BLOB, ** [SQLITE_ERROR] is returned and no data is written. If N is ** less than zero [SQLITE_ERROR] is returned and no data is written. ** The size of the BLOB (and hence the maximum value of N+iOffset) ** can be determined using the [sqlite3_blob_bytes()] interface. ** ** An attempt to write to an expired [BLOB handle] fails with an ** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred ** before the [BLOB handle] expired are not rolled back by the ** expiration of the handle, though of course those changes might ** have been overwritten by the statement that expired the BLOB handle ** or by other independent statements. ** ** On success, SQLITE_OK is returned. ** Otherwise, an [error code] or an [extended error code] is returned. ** ** This routine only works on a [BLOB handle] which has been created ** by a prior successful call to [sqlite3_blob_open()] and which has not ** been closed by [sqlite3_blob_close()]. Passing any other pointer in ** to this routine results in undefined and probably undesirable behavior. ** ** See also: [sqlite3_blob_read()]. ** ** Requirements: ** [H17873] [H17874] [H17875] [H17876] [H17877] [H17879] [H17882] [H17885] ** [H17888] */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* ** CAPI3REF: Virtual File System Objects {H11200} ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact ** with the underlying operating system. Most SQLite builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** ** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. ** Names are case sensitive. ** Names are zero-terminated UTF-8 strings. ** If there is no match, a NULL pointer is returned. ** If zVfsName is NULL then the default VFS is returned. ** ** New VFSes are registered with sqlite3_vfs_register(). ** Each new VFS becomes the default VFS if the makeDflt flag is set. ** The same VFS can be registered multiple times without injury. ** To make an existing VFS into the default VFS, register it again ** with the makeDflt flag set. If two different VFSes with the ** same name are registered, the behavior is undefined. If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. ** ** Unregister a VFS with the sqlite3_vfs_unregister() interface. ** If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary. ** ** Requirements: ** [H11203] [H11206] [H11209] [H11212] [H11215] [H11218] */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* ** CAPI3REF: Mutexes {H17000} ** ** The SQLite core uses these routines for thread ** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** ** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: ** **
    **
  • SQLITE_MUTEX_OS2 **
  • SQLITE_MUTEX_PTHREAD **
  • SQLITE_MUTEX_W32 **
  • SQLITE_MUTEX_NOOP **
** ** The SQLITE_MUTEX_NOOP implementation is a set of routines ** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_OS2, ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations ** are appropriate for use on OS/2, Unix, and Windows. ** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex ** implementation is included with the library. In this case the ** application must supply a custom mutex implementation using the ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function ** before calling sqlite3_initialize() or any other public sqlite3_ ** function that calls sqlite3_initialize(). ** ** {H17011} The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. {H17012} If it returns NULL ** that means that a mutex could not be allocated. {H17013} SQLite ** will unwind its stack and return an error. {H17014} The argument ** to sqlite3_mutex_alloc() is one of these integer constants: ** **
    **
  • SQLITE_MUTEX_FAST **
  • SQLITE_MUTEX_RECURSIVE **
  • SQLITE_MUTEX_STATIC_MASTER **
  • SQLITE_MUTEX_STATIC_MEM **
  • SQLITE_MUTEX_STATIC_MEM2 **
  • SQLITE_MUTEX_STATIC_PRNG **
  • SQLITE_MUTEX_STATIC_LRU **
  • SQLITE_MUTEX_STATIC_LRU2 **
** ** {H17015} The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE ** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} ** The mutex implementation does not need to make a distinction ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does ** not want to. {H17016} But SQLite will only request a recursive mutex in ** cases where it really needs one. {END} If a faster non-recursive mutex ** implementation is available on the host platform, the mutex subsystem ** might return such a mutex in response to SQLITE_MUTEX_FAST. ** ** {H17017} The other allowed parameters to sqlite3_mutex_alloc() each return ** a pointer to a static preexisting mutex. {END} Six static mutexes are ** used by the current version of SQLite. Future versions of SQLite ** may add additional static mutexes. Static mutexes are for internal ** use by SQLite only. Applications that use SQLite mutexes should ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or ** SQLITE_MUTEX_RECURSIVE. ** ** {H17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() ** returns a different mutex on every call. {H17034} But for the static ** mutex types, the same mutex is returned on every call that has ** the same type number. ** ** {H17019} The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. {H17020} SQLite is careful to deallocate every ** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in ** use when they are deallocated. {A17022} Attempting to deallocate a static ** mutex results in undefined behavior. {H17023} SQLite never deallocates ** a static mutex. {END} ** ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. {H17024} If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. {H17025} The sqlite3_mutex_try() interface returns [SQLITE_OK] ** upon successful entry. {H17026} Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** {H17027} In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. {A17028} If the same thread tries to enter any other ** kind of mutex more than once, the behavior is undefined. ** {H17029} SQLite will never exhibit ** such behavior in its own use of mutexes. ** ** Some systems (for example, Windows 95) do not support the operation ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() ** will always return SQLITE_BUSY. {H17030} The SQLite core only ever uses ** sqlite3_mutex_try() as an optimization so this is acceptable behavior. ** ** {H17031} The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. {A17032} The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. {H17033} SQLite will ** never do either. {END} ** ** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or ** sqlite3_mutex_leave() is a NULL pointer, then all three routines ** behave as no-ops. ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* ** CAPI3REF: Mutex Methods Object {H17120} ** EXPERIMENTAL ** ** An instance of this structure defines the low-level routines ** used to allocate and use mutexes. ** ** Usually, the default mutex implementations provided by SQLite are ** sufficient, however the user has the option of substituting a custom ** implementation for specialized deployments or systems for which SQLite ** does not provide a suitable implementation. In this case, the user ** creates and populates an instance of this structure to pass ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. ** Additionally, an instance of this structure can be used as an ** output variable when querying the system for the current mutex ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. ** ** The xMutexInit method defined by this structure is invoked as ** part of system initialization by the sqlite3_initialize() function. ** {H17001} The xMutexInit routine shall be called by SQLite once for each ** effective call to [sqlite3_initialize()]. ** ** The xMutexEnd method defined by this structure is invoked as ** part of system shutdown by the sqlite3_shutdown() function. The ** implementation of this method is expected to release all outstanding ** resources obtained by the mutex methods implementation, especially ** those obtained by the xMutexInit method. {H17003} The xMutexEnd() ** interface shall be invoked once for each call to [sqlite3_shutdown()]. ** ** The remaining seven methods defined by this structure (xMutexAlloc, ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and ** xMutexNotheld) implement the following interfaces (respectively): ** **
    **
  • [sqlite3_mutex_alloc()]
  • **
  • [sqlite3_mutex_free()]
  • **
  • [sqlite3_mutex_enter()]
  • **
  • [sqlite3_mutex_try()]
  • **
  • [sqlite3_mutex_leave()]
  • **
  • [sqlite3_mutex_held()]
  • **
  • [sqlite3_mutex_notheld()]
  • **
** ** The only difference is that the public sqlite3_XXX functions enumerated ** above silently ignore any invocations that pass a NULL pointer instead ** of a valid mutex handle. The implementations of the methods defined ** by this structure are not required to handle this case, the results ** of passing a NULL pointer instead of a valid mutex handle are undefined ** (i.e. it is acceptable to provide an implementation that segfaults if ** it is passed a NULL pointer). ** ** The xMutexInit() method must be threadsafe. It must be harmless to ** invoke xMutexInit() mutiple times within the same process and without ** intervening calls to xMutexEnd(). Second and subsequent calls to ** xMutexInit() must be no-ops. ** ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory ** allocation for a static mutex. However xMutexAlloc() may use SQLite ** memory allocation for a fast or recursive mutex. ** ** SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is ** called, but only if the prior call to xMutexInit returned SQLITE_OK. ** If xMutexInit fails in any way, it is expected to clean up after itself ** prior to returning. */ typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; struct sqlite3_mutex_methods { int (*xMutexInit)(void); int (*xMutexEnd)(void); sqlite3_mutex *(*xMutexAlloc)(int); void (*xMutexFree)(sqlite3_mutex *); void (*xMutexEnter)(sqlite3_mutex *); int (*xMutexTry)(sqlite3_mutex *); void (*xMutexLeave)(sqlite3_mutex *); int (*xMutexHeld)(sqlite3_mutex *); int (*xMutexNotheld)(sqlite3_mutex *); }; /* ** CAPI3REF: Mutex Verification Routines {H17080} ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. {H17081} The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. {H17082} The core only ** provides implementations for these routines when it is compiled ** with the SQLITE_DEBUG flag. {A17087} External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** {H17083} These routines should return true if the mutex in their argument ** is held or not held, respectively, by the calling thread. ** ** {X17084} The implementation is not required to provided versions of these ** routines that actually work. If the implementation does not provide working ** versions of these routines, it should at least provide stubs that always ** return true so that one does not get spurious assertion failures. ** ** {H17085} If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. {END} This seems counter-intuitive since ** clearly the mutex cannot be held if it does not exist. But the ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is ** the appropriate thing to do. {H17086} The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); /* ** CAPI3REF: Mutex Types {H17001} ** ** The [sqlite3_mutex_alloc()] interface takes a single argument ** which is one of these integer constants. ** ** The set of static mutexes may change from one SQLite release to the ** next. Applications that override the built-in mutex logic must be ** prepared to accommodate additional static mutexes. */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MASTER 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */ /* ** CAPI3REF: Retrieve the mutex for a database connection {H17002} ** ** This interface returns a pointer the [sqlite3_mutex] object that ** serializes access to the [database connection] given in the argument ** when the [threading mode] is Serialized. ** If the [threading mode] is Single-thread or Multi-thread then this ** routine returns a NULL pointer. */ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); /* ** CAPI3REF: Low-Level Control Of Database Files {H11300} ** ** {H11301} The [sqlite3_file_control()] interface makes a direct call to the ** xFileControl method for the [sqlite3_io_methods] object associated ** with a particular database identified by the second argument. {H11302} The ** name of the database is the name assigned to the database by the ** ATTACH SQL command that opened the ** database. {H11303} To control the main database file, use the name "main" ** or a NULL pointer. {H11304} The third and fourth parameters to this routine ** are passed directly through to the second and third parameters of ** the xFileControl method. {H11305} The return value of the xFileControl ** method becomes the return value of this routine. ** ** {H11306} If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. {H11307} This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] ** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might ** also return SQLITE_ERROR. {A11309} There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. {END} ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); /* ** CAPI3REF: Testing Interface {H11400} ** ** The sqlite3_test_control() interface is used to read out internal ** state of SQLite and to inject faults into SQLite for testing ** purposes. The first parameter is an operation code that determines ** the number, meaning, and operation of all subsequent parameters. ** ** This interface is not for use by applications. It exists solely ** for verifying the correct operation of the SQLite library. Depending ** on how the SQLite library is compiled, this interface might not exist. ** ** The details of the operation codes, their meanings, the parameters ** they take, and what they do are all subject to change without notice. ** Unlike most of the SQLite API, this function is not guaranteed to ** operate consistently from one release to the next. */ SQLITE_API int sqlite3_test_control(int op, ...); /* ** CAPI3REF: Testing Interface Operation Codes {H11410} ** ** These constants are the valid operation code parameters used ** as the first argument to [sqlite3_test_control()]. ** ** These parameters and their meanings are subject to change ** without notice. These values are for testing purposes only. ** Applications should not use any of these parameters or the ** [sqlite3_test_control()] interface. */ #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 #define SQLITE_TESTCTRL_PENDING_BYTE 11 #define SQLITE_TESTCTRL_ASSERT 12 #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 /* ** CAPI3REF: SQLite Runtime Status {H17200} ** EXPERIMENTAL ** ** This interface is used to retrieve runtime status information ** about the preformance of SQLite, and optionally to reset various ** highwater marks. The first argument is an integer code for ** the specific parameter to measure. Recognized integer codes ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...]. ** The current value of the parameter is returned into *pCurrent. ** The highest recorded value is returned in *pHighwater. If the ** resetFlag is true, then the highest record value is reset after ** *pHighwater is written. Some parameters do not record the highest ** value. For those parameters ** nothing is written into *pHighwater and the resetFlag is ignored. ** Other parameters record only the highwater mark and not the current ** value. For these latter parameters nothing is written into *pCurrent. ** ** This routine returns SQLITE_OK on success and a non-zero ** [error code] on failure. ** ** This routine is threadsafe but is not atomic. This routine can be ** called while other threads are running the same or different SQLite ** interfaces. However the values returned in *pCurrent and ** *pHighwater reflect the status of SQLite at different points in time ** and it is possible that another thread might change the parameter ** in between the times when *pCurrent and *pHighwater are written. ** ** See also: [sqlite3_db_status()] */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); /* ** CAPI3REF: Status Parameters {H17250} ** EXPERIMENTAL ** ** These integer constants designate various run-time status parameters ** that can be returned by [sqlite3_status()]. ** **
**
SQLITE_STATUS_MEMORY_USED
**
This parameter is the current amount of memory checked out ** using [sqlite3_malloc()], either directly or indirectly. The ** figure includes calls made to [sqlite3_malloc()] by the application ** and internal memory usage by the SQLite library. Scratch memory ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** this parameter. The amount returned is the sum of the allocation ** sizes as reported by the xSize method in [sqlite3_mem_methods].
** **
SQLITE_STATUS_MALLOC_SIZE
**
This parameter records the largest memory allocation request ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their ** internal equivalents). Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
** **
SQLITE_STATUS_PAGECACHE_USED
**
This parameter returns the number of pages used out of the ** [pagecache memory allocator] that was configured using ** [SQLITE_CONFIG_PAGECACHE]. The ** value returned is in pages, not in bytes.
** **
SQLITE_STATUS_PAGECACHE_OVERFLOW
**
This parameter returns the number of bytes of page cache ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE] ** buffer and where forced to overflow to [sqlite3_malloc()]. The ** returned value includes allocations that overflowed because they ** where too large (they were larger than the "sz" parameter to ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because ** no space was left in the page cache.
** **
SQLITE_STATUS_PAGECACHE_SIZE
**
This parameter records the largest memory allocation request ** handed to [pagecache memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
** **
SQLITE_STATUS_SCRATCH_USED
**
This parameter returns the number of allocations used out of the ** [scratch memory allocator] configured using ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not ** in bytes. Since a single thread may only have one scratch allocation ** outstanding at time, this parameter also reports the number of threads ** using scratch memory at the same time.
** **
SQLITE_STATUS_SCRATCH_OVERFLOW
**
This parameter returns the number of bytes of scratch memory ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH] ** buffer and where forced to overflow to [sqlite3_malloc()]. The values ** returned include overflows because the requested allocation was too ** larger (that is, because the requested allocation was larger than the ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer ** slots were available. **
** **
SQLITE_STATUS_SCRATCH_SIZE
**
This parameter records the largest memory allocation request ** handed to [scratch memory allocator]. Only the value returned in the ** *pHighwater parameter to [sqlite3_status()] is of interest. ** The value written into the *pCurrent parameter is undefined.
** **
SQLITE_STATUS_PARSER_STACK
**
This parameter records the deepest parser stack. It is only ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
**
** ** New status parameters may be added from time to time. */ #define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_SCRATCH_USED 3 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_SCRATCH_SIZE 8 /* ** CAPI3REF: Database Connection Status {H17500} ** EXPERIMENTAL ** ** This interface is used to retrieve runtime status information ** about a single [database connection]. The first argument is the ** database connection object to be interrogated. The second argument ** is the parameter to interrogate. Currently, the only allowed value ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED]. ** Additional options will likely appear in future releases of SQLite. ** ** The current value of the requested parameter is written into *pCur ** and the highest instantaneous value is written into *pHiwtr. If ** the resetFlg is true, then the highest instantaneous value is ** reset back down to the current value. ** ** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); /* ** CAPI3REF: Status Parameters for database connections {H17520} ** EXPERIMENTAL ** ** These constants are the available integer "verbs" that can be passed as ** the second argument to the [sqlite3_db_status()] interface. ** ** New verbs may be added in future releases of SQLite. Existing verbs ** might be discontinued. Applications should check the return code from ** [sqlite3_db_status()] to make sure that the call worked. ** The [sqlite3_db_status()] interface will return a non-zero error code ** if a discontinued or unsupported verb is invoked. ** **
**
SQLITE_DBSTATUS_LOOKASIDE_USED
**
This parameter returns the number of lookaside memory slots currently ** checked out.
**
*/ #define SQLITE_DBSTATUS_LOOKASIDE_USED 0 /* ** CAPI3REF: Prepared Statement Status {H17550} ** EXPERIMENTAL ** ** Each prepared statement maintains various ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number ** of times it has performed specific operations. These counters can ** be used to monitor the performance characteristics of the prepared ** statements. For example, if the number of table steps greatly exceeds ** the number of table searches or result rows, that would tend to indicate ** that the prepared statement is using a full table scan rather than ** an index. ** ** This interface is used to retrieve and reset counter values from ** a [prepared statement]. The first argument is the prepared statement ** object to be interrogated. The second argument ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter] ** to be interrogated. ** The current value of the requested counter is returned. ** If the resetFlg is true, then the counter is reset to zero after this ** interface call returns. ** ** See also: [sqlite3_status()] and [sqlite3_db_status()]. */ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); /* ** CAPI3REF: Status Parameters for prepared statements {H17570} ** EXPERIMENTAL ** ** These preprocessor macros define integer codes that name counter ** values associated with the [sqlite3_stmt_status()] interface. ** The meanings of the various counters are as follows: ** **
**
SQLITE_STMTSTATUS_FULLSCAN_STEP
**
This is the number of times that SQLite has stepped forward in ** a table as part of a full table scan. Large numbers for this counter ** may indicate opportunities for performance improvement through ** careful use of indices.
** **
SQLITE_STMTSTATUS_SORT
**
This is the number of sort operations that have occurred. ** A non-zero value in this counter may indicate an opportunity to ** improvement performance through careful use of indices.
** **
*/ #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 #define SQLITE_STMTSTATUS_SORT 2 /* ** CAPI3REF: Custom Page Cache Object ** EXPERIMENTAL ** ** The sqlite3_pcache type is opaque. It is implemented by ** the pluggable module. The SQLite core has no knowledge of ** its size or internal structure and never deals with the ** sqlite3_pcache object except by holding and passing pointers ** to the object. ** ** See [sqlite3_pcache_methods] for additional information. */ typedef struct sqlite3_pcache sqlite3_pcache; /* ** CAPI3REF: Application Defined Page Cache. ** KEYWORDS: {page cache} ** EXPERIMENTAL ** ** The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can ** register an alternative page cache implementation by passing in an ** instance of the sqlite3_pcache_methods structure. The majority of the ** heap memory used by SQLite is used by the page cache to cache data read ** from, or ready to be written to, the database file. By implementing a ** custom page cache using this API, an application can control more ** precisely the amount of memory consumed by SQLite, the way in which ** that memory is allocated and released, and the policies used to ** determine exactly which parts of a database file are cached and for ** how long. ** ** The contents of the sqlite3_pcache_methods structure are copied to an ** internal buffer by SQLite within the call to [sqlite3_config]. Hence ** the application may discard the parameter after the call to ** [sqlite3_config()] returns. ** ** The xInit() method is called once for each call to [sqlite3_initialize()] ** (usually only once during the lifetime of the process). It is passed ** a copy of the sqlite3_pcache_methods.pArg value. It can be used to set ** up global structures and mutexes required by the custom page cache ** implementation. ** ** The xShutdown() method is called from within [sqlite3_shutdown()], ** if the application invokes this API. It can be used to clean up ** any outstanding resources before process shutdown, if required. ** ** SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes ** the xInit method, so the xInit method need not be threadsafe. The ** xShutdown method is only called from [sqlite3_shutdown()] so it does ** not need to be threadsafe either. All other methods must be threadsafe ** in multithreaded applications. ** ** SQLite will never invoke xInit() more than once without an intervening ** call to xShutdown(). ** ** The xCreate() method is used to construct a new cache instance. SQLite ** will typically create one cache instance for each open database file, ** though this is not guaranteed. The ** first parameter, szPage, is the size in bytes of the pages that must ** be allocated by the cache. szPage will not be a power of two. szPage ** will the page size of the database file that is to be cached plus an ** increment (here called "R") of about 100 or 200. SQLite will use the ** extra R bytes on each page to store metadata about the underlying ** database page on disk. The value of R depends ** on the SQLite version, the target platform, and how SQLite was compiled. ** R is constant for a particular build of SQLite. The second argument to ** xCreate(), bPurgeable, is true if the cache being created will ** be used to cache database pages of a file stored on disk, or ** false if it is used for an in-memory database. The cache implementation ** does not have to do anything special based with the value of bPurgeable; ** it is purely advisory. On a cache where bPurgeable is false, SQLite will ** never invoke xUnpin() except to deliberately delete a page. ** In other words, a cache created with bPurgeable set to false will ** never contain any unpinned pages. ** ** The xCachesize() method may be called at any time by SQLite to set the ** suggested maximum cache-size (number of pages stored by) the cache ** instance passed as the first argument. This is the value configured using ** the SQLite "[PRAGMA cache_size]" command. As with the bPurgeable parameter, ** the implementation is not required to do anything with this ** value; it is advisory only. ** ** The xPagecount() method should return the number of pages currently ** stored in the cache. ** ** The xFetch() method is used to fetch a page and return a pointer to it. ** A 'page', in this context, is a buffer of szPage bytes aligned at an ** 8-byte boundary. The page to be fetched is determined by the key. The ** mimimum key value is 1. After it has been retrieved using xFetch, the page ** is considered to be "pinned". ** ** If the requested page is already in the page cache, then the page cache ** implementation must return a pointer to the page buffer with its content ** intact. If the requested page is not already in the cache, then the ** behavior of the cache implementation is determined by the value of the ** createFlag parameter passed to xFetch, according to the following table: ** ** **
createFlag Behaviour when page is not already in cache **
0 Do not allocate a new page. Return NULL. **
1 Allocate a new page if it easy and convenient to do so. ** Otherwise return NULL. **
2 Make every effort to allocate a new page. Only return ** NULL if allocating a new page is effectively impossible. **
** ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1. If ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will ** attempt to unpin one or more cache pages by spilling the content of ** pinned pages to disk and synching the operating system disk cache. After ** attempting to unpin pages, the xFetch() method will be invoked again with ** a createFlag of 2. ** ** xUnpin() is called by SQLite with a pointer to a currently pinned page ** as its second argument. If the third parameter, discard, is non-zero, ** then the page should be evicted from the cache. In this case SQLite ** assumes that the next time the page is retrieved from the cache using ** the xFetch() method, it will be zeroed. If the discard parameter is ** zero, then the page is considered to be unpinned. The cache implementation ** may choose to evict unpinned pages at any time. ** ** The cache is not required to perform any reference counting. A single ** call to xUnpin() unpins the page regardless of the number of prior calls ** to xFetch(). ** ** The xRekey() method is used to change the key value associated with the ** page passed as the second argument from oldKey to newKey. If the cache ** previously contains an entry associated with newKey, it should be ** discarded. Any prior cache entry associated with newKey is guaranteed not ** to be pinned. ** ** When SQLite calls the xTruncate() method, the cache must discard all ** existing cache entries with page numbers (keys) greater than or equal ** to the value of the iLimit parameter passed to xTruncate(). If any ** of these pages are pinned, they are implicitly unpinned, meaning that ** they can be safely discarded. ** ** The xDestroy() method is used to delete a cache allocated by xCreate(). ** All resources associated with the specified cache should be freed. After ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] ** handle invalid, and will not use it with any other sqlite3_pcache_methods ** functions. */ typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; struct sqlite3_pcache_methods { void *pArg; int (*xInit)(void*); void (*xShutdown)(void*); sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); void (*xCachesize)(sqlite3_pcache*, int nCachesize); int (*xPagecount)(sqlite3_pcache*); void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); void (*xUnpin)(sqlite3_pcache*, void*, int discard); void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); void (*xDestroy)(sqlite3_pcache*); }; /* ** CAPI3REF: Online Backup Object ** EXPERIMENTAL ** ** The sqlite3_backup object records state information about an ongoing ** online backup operation. The sqlite3_backup object is created by ** a call to [sqlite3_backup_init()] and is destroyed by a call to ** [sqlite3_backup_finish()]. ** ** See Also: [Using the SQLite Online Backup API] */ typedef struct sqlite3_backup sqlite3_backup; /* ** CAPI3REF: Online Backup API. ** EXPERIMENTAL ** ** This API is used to overwrite the contents of one database with that ** of another. It is useful either for creating backups of databases or ** for copying in-memory databases to or from persistent files. ** ** See Also: [Using the SQLite Online Backup API] ** ** Exclusive access is required to the destination database for the ** duration of the operation. However the source database is only ** read-locked while it is actually being read, it is not locked ** continuously for the entire operation. Thus, the backup may be ** performed on a live database without preventing other users from ** writing to the database for an extended period of time. ** ** To perform a backup operation: **
    **
  1. sqlite3_backup_init() is called once to initialize the ** backup, **
  2. sqlite3_backup_step() is called one or more times to transfer ** the data between the two databases, and finally **
  3. sqlite3_backup_finish() is called to release all resources ** associated with the backup operation. **
** There should be exactly one call to sqlite3_backup_finish() for each ** successful call to sqlite3_backup_init(). ** ** sqlite3_backup_init() ** ** The first two arguments passed to [sqlite3_backup_init()] are the database ** handle associated with the destination database and the database name ** used to attach the destination database to the handle. The database name ** is "main" for the main database, "temp" for the temporary database, or ** the name specified as part of the [ATTACH] statement if the destination is ** an attached database. The third and fourth arguments passed to ** sqlite3_backup_init() identify the [database connection] ** and database name used ** to access the source database. The values passed for the source and ** destination [database connection] parameters must not be the same. ** ** If an error occurs within sqlite3_backup_init(), then NULL is returned ** and an error code and error message written into the [database connection] ** passed as the first argument. They may be retrieved using the ** [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] functions. ** Otherwise, if successful, a pointer to an [sqlite3_backup] object is ** returned. This pointer may be used with the sqlite3_backup_step() and ** sqlite3_backup_finish() functions to perform the specified backup ** operation. ** ** sqlite3_backup_step() ** ** Function [sqlite3_backup_step()] is used to copy up to nPage pages between ** the source and destination databases, where nPage is the value of the ** second parameter passed to sqlite3_backup_step(). If nPage is a negative ** value, all remaining source pages are copied. If the required pages are ** succesfully copied, but there are still more pages to copy before the ** backup is complete, it returns [SQLITE_OK]. If no error occured and there ** are no more pages to copy, then [SQLITE_DONE] is returned. If an error ** occurs, then an SQLite error code is returned. As well as [SQLITE_OK] and ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. ** ** As well as the case where the destination database file was opened for ** read-only access, sqlite3_backup_step() may return [SQLITE_READONLY] if ** the destination is an in-memory database with a different page size ** from the source database. ** ** If sqlite3_backup_step() cannot obtain a required file-system lock, then ** the [sqlite3_busy_handler | busy-handler function] ** is invoked (if one is specified). If the ** busy-handler returns non-zero before the lock is available, then ** [SQLITE_BUSY] is returned to the caller. In this case the call to ** sqlite3_backup_step() can be retried later. If the source ** [database connection] ** is being used to write to the source database when sqlite3_backup_step() ** is called, then [SQLITE_LOCKED] is returned immediately. Again, in this ** case the call to sqlite3_backup_step() can be retried later on. If ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or ** [SQLITE_READONLY] is returned, then ** there is no point in retrying the call to sqlite3_backup_step(). These ** errors are considered fatal. At this point the application must accept ** that the backup operation has failed and pass the backup operation handle ** to the sqlite3_backup_finish() to release associated resources. ** ** Following the first call to sqlite3_backup_step(), an exclusive lock is ** obtained on the destination file. It is not released until either ** sqlite3_backup_finish() is called or the backup operation is complete ** and sqlite3_backup_step() returns [SQLITE_DONE]. Additionally, each time ** a call to sqlite3_backup_step() is made a [shared lock] is obtained on ** the source database file. This lock is released before the ** sqlite3_backup_step() call returns. Because the source database is not ** locked between calls to sqlite3_backup_step(), it may be modified mid-way ** through the backup procedure. If the source database is modified by an ** external process or via a database connection other than the one being ** used by the backup operation, then the backup will be transparently ** restarted by the next call to sqlite3_backup_step(). If the source ** database is modified by the using the same database connection as is used ** by the backup operation, then the backup database is transparently ** updated at the same time. ** ** sqlite3_backup_finish() ** ** Once sqlite3_backup_step() has returned [SQLITE_DONE], or when the ** application wishes to abandon the backup operation, the [sqlite3_backup] ** object should be passed to sqlite3_backup_finish(). This releases all ** resources associated with the backup operation. If sqlite3_backup_step() ** has not yet returned [SQLITE_DONE], then any active write-transaction on the ** destination database is rolled back. The [sqlite3_backup] object is invalid ** and may not be used following a call to sqlite3_backup_finish(). ** ** The value returned by sqlite3_backup_finish is [SQLITE_OK] if no error ** occurred, regardless or whether or not sqlite3_backup_step() was called ** a sufficient number of times to complete the backup operation. Or, if ** an out-of-memory condition or IO error occured during a call to ** sqlite3_backup_step() then [SQLITE_NOMEM] or an ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] error code ** is returned. In this case the error code and an error message are ** written to the destination [database connection]. ** ** A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() is ** not a permanent error and does not affect the return value of ** sqlite3_backup_finish(). ** ** sqlite3_backup_remaining(), sqlite3_backup_pagecount() ** ** Each call to sqlite3_backup_step() sets two values stored internally ** by an [sqlite3_backup] object. The number of pages still to be backed ** up, which may be queried by sqlite3_backup_remaining(), and the total ** number of pages in the source database file, which may be queried by ** sqlite3_backup_pagecount(). ** ** The values returned by these functions are only updated by ** sqlite3_backup_step(). If the source database is modified during a backup ** operation, then the values are not updated to account for any extra ** pages that need to be updated or the size of the source database file ** changing. ** ** Concurrent Usage of Database Handles ** ** The source [database connection] may be used by the application for other ** purposes while a backup operation is underway or being initialized. ** If SQLite is compiled and configured to support threadsafe database ** connections, then the source database connection may be used concurrently ** from within other threads. ** ** However, the application must guarantee that the destination database ** connection handle is not passed to any other API (by any thread) after ** sqlite3_backup_init() is called and before the corresponding call to ** sqlite3_backup_finish(). Unfortunately SQLite does not currently check ** for this, if the application does use the destination [database connection] ** for some other purpose during a backup operation, things may appear to ** work correctly but in fact be subtly malfunctioning. Use of the ** destination database connection while a backup is in progress might ** also cause a mutex deadlock. ** ** Furthermore, if running in [shared cache mode], the application must ** guarantee that the shared cache used by the destination database ** is not accessed while the backup is running. In practice this means ** that the application must guarantee that the file-system file being ** backed up to is not accessed by any connection within the process, ** not just the specific connection that was passed to sqlite3_backup_init(). ** ** The [sqlite3_backup] object itself is partially threadsafe. Multiple ** threads may safely make multiple concurrent calls to sqlite3_backup_step(). ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() ** APIs are not strictly speaking threadsafe. If they are invoked at the ** same time as another thread is invoking sqlite3_backup_step() it is ** possible that they return invalid values. */ SQLITE_API sqlite3_backup *sqlite3_backup_init( sqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ sqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); /* ** CAPI3REF: Unlock Notification ** EXPERIMENTAL ** ** When running in shared-cache mode, a database operation may fail with ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or ** individual tables within the shared-cache cannot be obtained. See ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. ** This API may be used to register a callback that SQLite will invoke ** when the connection currently holding the required lock relinquishes it. ** This API is only available if the library was compiled with the ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. ** ** See Also: [Using the SQLite Unlock Notification Feature]. ** ** Shared-cache locks are released when a database connection concludes ** its current transaction, either by committing it or rolling it back. ** ** When a connection (known as the blocked connection) fails to obtain a ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the ** identity of the database connection (the blocking connection) that ** has locked the required resource is stored internally. After an ** application receives an SQLITE_LOCKED error, it may call the ** sqlite3_unlock_notify() method with the blocked connection handle as ** the first argument to register for a callback that will be invoked ** when the blocking connections current transaction is concluded. The ** callback is invoked from within the [sqlite3_step] or [sqlite3_close] ** call that concludes the blocking connections transaction. ** ** If sqlite3_unlock_notify() is called in a multi-threaded application, ** there is a chance that the blocking connection will have already ** concluded its transaction by the time sqlite3_unlock_notify() is invoked. ** If this happens, then the specified callback is invoked immediately, ** from within the call to sqlite3_unlock_notify(). ** ** If the blocked connection is attempting to obtain a write-lock on a ** shared-cache table, and more than one other connection currently holds ** a read-lock on the same table, then SQLite arbitrarily selects one of ** the other connections to use as the blocking connection. ** ** There may be at most one unlock-notify callback registered by a ** blocked connection. If sqlite3_unlock_notify() is called when the ** blocked connection already has a registered unlock-notify callback, ** then the new callback replaces the old. If sqlite3_unlock_notify() is ** called with a NULL pointer as its second argument, then any existing ** unlock-notify callback is cancelled. The blocked connections ** unlock-notify callback may also be canceled by closing the blocked ** connection using [sqlite3_close()]. ** ** The unlock-notify callback is not reentrant. If an application invokes ** any sqlite3_xxx API functions from within an unlock-notify callback, a ** crash or deadlock may be the result. ** ** Unless deadlock is detected (see below), sqlite3_unlock_notify() always ** returns SQLITE_OK. ** ** Callback Invocation Details ** ** When an unlock-notify callback is registered, the application provides a ** single void* pointer that is passed to the callback when it is invoked. ** However, the signature of the callback function allows SQLite to pass ** it an array of void* context pointers. The first argument passed to ** an unlock-notify callback is a pointer to an array of void* pointers, ** and the second is the number of entries in the array. ** ** When a blocking connections transaction is concluded, there may be ** more than one blocked connection that has registered for an unlock-notify ** callback. If two or more such blocked connections have specified the ** same callback function, then instead of invoking the callback function ** multiple times, it is invoked once with the set of void* context pointers ** specified by the blocked connections bundled together into an array. ** This gives the application an opportunity to prioritize any actions ** related to the set of unblocked database connections. ** ** Deadlock Detection ** ** Assuming that after registering for an unlock-notify callback a ** database waits for the callback to be issued before taking any further ** action (a reasonable assumption), then using this API may cause the ** application to deadlock. For example, if connection X is waiting for ** connection Y's transaction to be concluded, and similarly connection ** Y is waiting on connection X's transaction, then neither connection ** will proceed and the system may remain deadlocked indefinitely. ** ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock ** detection. If a given call to sqlite3_unlock_notify() would put the ** system in a deadlocked state, then SQLITE_LOCKED is returned and no ** unlock-notify callback is registered. The system is said to be in ** a deadlocked state if connection A has registered for an unlock-notify ** callback on the conclusion of connection B's transaction, and connection ** B has itself registered for an unlock-notify callback when connection ** A's transaction is concluded. Indirect deadlock is also detected, so ** the system is also considered to be deadlocked if connection B has ** registered for an unlock-notify callback on the conclusion of connection ** C's transaction, where connection C is waiting on connection A. Any ** number of levels of indirection are allowed. ** ** The "DROP TABLE" Exception ** ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost ** always appropriate to call sqlite3_unlock_notify(). There is however, ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, ** SQLite checks if there are any currently executing SELECT statements ** that belong to the same connection. If there are, SQLITE_LOCKED is ** returned. In this case there is no "blocking connection", so invoking ** sqlite3_unlock_notify() results in the unlock-notify callback being ** invoked immediately. If the application then re-attempts the "DROP TABLE" ** or "DROP INDEX" query, an infinite loop might be the result. ** ** One way around this problem is to check the extended error code returned ** by an sqlite3_step() call. If there is a blocking connection, then the ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in ** the special "DROP TABLE/INDEX" case, the extended error code is just ** SQLITE_LOCKED. */ SQLITE_API int sqlite3_unlock_notify( sqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); /* ** CAPI3REF: String Comparison ** EXPERIMENTAL ** ** The [sqlite3_strnicmp()] API allows applications and extensions to ** compare the contents of two buffers containing UTF-8 strings in a ** case-indendent fashion, using the same definition of case independence ** that SQLite uses internally when comparing identifiers. */ SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ #ifdef SQLITE_OMIT_FLOATING_POINT # undef double #endif #if 0 } /* End of the 'extern "C"' block */ #endif #endif /************** End of sqlite3.h *********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include hash.h in the middle of sqliteInt.h ******************/ /************** Begin file hash.h ********************************************/ /* ** 2001 September 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This is the header file for the generic hash-table implemenation ** used in SQLite. ** ** $Id: hash.h,v 1.15 2009/05/02 13:29:38 drh Exp $ */ #ifndef _SQLITE_HASH_H_ #define _SQLITE_HASH_H_ /* Forward declarations of structures. */ typedef struct Hash Hash; typedef struct HashElem HashElem; /* A complete hash table is an instance of the following structure. ** The internals of this structure are intended to be opaque -- client ** code should not attempt to access or modify the fields of this structure ** directly. Change this structure only by using the routines below. ** However, some of the "procedures" and "functions" for modifying and ** accessing this structure are really macros, so we can't really make ** this structure opaque. ** ** All elements of the hash table are on a single doubly-linked list. ** Hash.first points to the head of this list. ** ** There are Hash.htsize buckets. Each bucket points to a spot in ** the global doubly-linked list. The contents of the bucket are the ** element pointed to plus the next _ht.count-1 elements in the list. ** ** Hash.htsize and Hash.ht may be zero. In that case lookup is done ** by a linear search of the global list. For small tables, the ** Hash.ht table is never allocated because if there are few elements ** in the table, it is faster to do a linear search than to manage ** the hash table. */ struct Hash { unsigned int htsize; /* Number of buckets in the hash table */ unsigned int count; /* Number of entries in this table */ HashElem *first; /* The first element of the array */ struct _ht { /* the hash table */ int count; /* Number of entries with this hash */ HashElem *chain; /* Pointer to first entry with this hash */ } *ht; }; /* Each element in the hash table is an instance of the following ** structure. All elements are stored on a single doubly-linked list. ** ** Again, this structure is intended to be opaque, but it can't really ** be opaque because it is used by macros. */ struct HashElem { HashElem *next, *prev; /* Next and previous elements in the table */ void *data; /* Data associated with this element */ const char *pKey; int nKey; /* Key associated with this element */ }; /* ** Access routines. To delete, insert a NULL pointer. */ SQLITE_PRIVATE void sqlite3HashInit(Hash*); SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); SQLITE_PRIVATE void sqlite3HashClear(Hash*); /* ** Macros for looping over all elements of a hash table. The idiom is ** like this: ** ** Hash h; ** HashElem *p; ** ... ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ ** SomeStructure *pData = sqliteHashData(p); ** // do something with pData ** } */ #define sqliteHashFirst(H) ((H)->first) #define sqliteHashNext(E) ((E)->next) #define sqliteHashData(E) ((E)->data) /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ /* ** Number of entries in a hash table */ /* #define sqliteHashCount(H) ((H)->count) // NOT USED */ #endif /* _SQLITE_HASH_H_ */ /************** End of hash.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include parse.h in the middle of sqliteInt.h *****************/ /************** Begin file parse.h *******************************************/ #define TK_SEMI 1 #define TK_EXPLAIN 2 #define TK_QUERY 3 #define TK_PLAN 4 #define TK_BEGIN 5 #define TK_TRANSACTION 6 #define TK_DEFERRED 7 #define TK_IMMEDIATE 8 #define TK_EXCLUSIVE 9 #define TK_COMMIT 10 #define TK_END 11 #define TK_ROLLBACK 12 #define TK_SAVEPOINT 13 #define TK_RELEASE 14 #define TK_TO 15 #define TK_TABLE 16 #define TK_CREATE 17 #define TK_IF 18 #define TK_NOT 19 #define TK_EXISTS 20 #define TK_TEMP 21 #define TK_LP 22 #define TK_RP 23 #define TK_AS 24 #define TK_COMMA 25 #define TK_ID 26 #define TK_INDEXED 27 #define TK_ABORT 28 #define TK_ACTION 29 #define TK_AFTER 30 #define TK_ANALYZE 31 #define TK_ASC 32 #define TK_ATTACH 33 #define TK_BEFORE 34 #define TK_BY 35 #define TK_CASCADE 36 #define TK_CAST 37 #define TK_COLUMNKW 38 #define TK_CONFLICT 39 #define TK_DATABASE 40 #define TK_DESC 41 #define TK_DETACH 42 #define TK_EACH 43 #define TK_FAIL 44 #define TK_FOR 45 #define TK_IGNORE 46 #define TK_INITIALLY 47 #define TK_INSTEAD 48 #define TK_LIKE_KW 49 #define TK_MATCH 50 #define TK_NO 51 #define TK_KEY 52 #define TK_OF 53 #define TK_OFFSET 54 #define TK_PRAGMA 55 #define TK_RAISE 56 #define TK_REPLACE 57 #define TK_RESTRICT 58 #define TK_ROW 59 #define TK_TRIGGER 60 #define TK_VACUUM 61 #define TK_VIEW 62 #define TK_VIRTUAL 63 #define TK_REINDEX 64 #define TK_RENAME 65 #define TK_CTIME_KW 66 #define TK_ANY 67 #define TK_OR 68 #define TK_AND 69 #define TK_IS 70 #define TK_BETWEEN 71 #define TK_IN 72 #define TK_ISNULL 73 #define TK_NOTNULL 74 #define TK_NE 75 #define TK_EQ 76 #define TK_GT 77 #define TK_LE 78 #define TK_LT 79 #define TK_GE 80 #define TK_ESCAPE 81 #define TK_BITAND 82 #define TK_BITOR 83 #define TK_LSHIFT 84 #define TK_RSHIFT 85 #define TK_PLUS 86 #define TK_MINUS 87 #define TK_STAR 88 #define TK_SLASH 89 #define TK_REM 90 #define TK_CONCAT 91 #define TK_COLLATE 92 #define TK_BITNOT 93 #define TK_STRING 94 #define TK_JOIN_KW 95 #define TK_CONSTRAINT 96 #define TK_DEFAULT 97 #define TK_NULL 98 #define TK_PRIMARY 99 #define TK_UNIQUE 100 #define TK_CHECK 101 #define TK_REFERENCES 102 #define TK_AUTOINCR 103 #define TK_ON 104 #define TK_DELETE 105 #define TK_UPDATE 106 #define TK_SET 107 #define TK_DEFERRABLE 108 #define TK_FOREIGN 109 #define TK_DROP 110 #define TK_UNION 111 #define TK_ALL 112 #define TK_EXCEPT 113 #define TK_INTERSECT 114 #define TK_SELECT 115 #define TK_DISTINCT 116 #define TK_DOT 117 #define TK_FROM 118 #define TK_JOIN 119 #define TK_USING 120 #define TK_ORDER 121 #define TK_GROUP 122 #define TK_HAVING 123 #define TK_LIMIT 124 #define TK_WHERE 125 #define TK_INTO 126 #define TK_VALUES 127 #define TK_INSERT 128 #define TK_INTEGER 129 #define TK_FLOAT 130 #define TK_BLOB 131 #define TK_REGISTER 132 #define TK_VARIABLE 133 #define TK_CASE 134 #define TK_WHEN 135 #define TK_THEN 136 #define TK_ELSE 137 #define TK_INDEX 138 #define TK_ALTER 139 #define TK_ADD 140 #define TK_TO_TEXT 141 #define TK_TO_BLOB 142 #define TK_TO_NUMERIC 143 #define TK_TO_INT 144 #define TK_TO_REAL 145 #define TK_ISNOT 146 #define TK_END_OF_FILE 147 #define TK_ILLEGAL 148 #define TK_SPACE 149 #define TK_UNCLOSED_STRING 150 #define TK_FUNCTION 151 #define TK_COLUMN 152 #define TK_AGG_FUNCTION 153 #define TK_AGG_COLUMN 154 #define TK_CONST_FUNC 155 #define TK_UMINUS 156 #define TK_UPLUS 157 /************** End of parse.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ #include #include #include #include #include /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite_int64 # define LONGDOUBLE_TYPE sqlite_int64 # ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) # endif # define SQLITE_OMIT_DATETIME_FUNCS 1 # define SQLITE_OMIT_TRACE 1 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT # undef SQLITE_HAVE_ISNAN #endif #ifndef SQLITE_BIG_DBL # define SQLITE_BIG_DBL (1e99) #endif /* ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 ** afterward. Having this macro allows us to cause the C compiler ** to omit code used by TEMP tables without messy #ifndef statements. */ #ifdef SQLITE_OMIT_TEMPDB #define OMIT_TEMPDB 1 #else #define OMIT_TEMPDB 0 #endif /* ** If the following macro is set to 1, then NULL values are considered ** distinct when determining whether or not two entries are the same ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL, ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this ** is the way things are suppose to work. ** ** If the following macro is set to 0, the NULLs are indistinct for ** a UNIQUE index. In this mode, you can only have a single NULL entry ** for a column declared UNIQUE. This is the way Informix and SQL Server ** work. */ #define NULL_DISTINCT_FOR_UNIQUE 1 /* ** The "file format" number is an integer that is incremented whenever ** the VDBE-level file format changes. The following macros define the ** the default file format for new databases and the maximum file format ** that the library can read. */ #define SQLITE_MAX_FILE_FORMAT 4 #ifndef SQLITE_DEFAULT_FILE_FORMAT # define SQLITE_DEFAULT_FILE_FORMAT 1 #endif #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 #endif /* ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified ** on the command-line */ #ifndef SQLITE_TEMP_STORE # define SQLITE_TEMP_STORE 1 #endif /* ** GCC does not define the offsetof() macro so we'll have to do it ** ourselves. */ #ifndef offsetof #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) #endif /* ** Check to see if this machine uses EBCDIC. (Yes, believe it or ** not, there are still machines out there that use EBCDIC.) */ #if 'A' == '\301' # define SQLITE_EBCDIC 1 #else # define SQLITE_ASCII 1 #endif /* ** Integers of known sizes. These typedefs might change for architectures ** where the sizes very. Preprocessor macros are available so that the ** types can be conveniently redefined at compile-type. Like this: ** ** cc '-DUINTPTR_TYPE=long long int' ... */ #ifndef UINT32_TYPE # ifdef HAVE_UINT32_T # define UINT32_TYPE uint32_t # else # define UINT32_TYPE unsigned int # endif #endif #ifndef UINT16_TYPE # ifdef HAVE_UINT16_T # define UINT16_TYPE uint16_t # else # define UINT16_TYPE unsigned short int # endif #endif #ifndef INT16_TYPE # ifdef HAVE_INT16_T # define INT16_TYPE int16_t # else # define INT16_TYPE short int # endif #endif #ifndef UINT8_TYPE # ifdef HAVE_UINT8_T # define UINT8_TYPE uint8_t # else # define UINT8_TYPE unsigned char # endif #endif #ifndef INT8_TYPE # ifdef HAVE_INT8_T # define INT8_TYPE int8_t # else # define INT8_TYPE signed char # endif #endif #ifndef LONGDOUBLE_TYPE # define LONGDOUBLE_TYPE long double #endif typedef sqlite_int64 i64; /* 8-byte signed integer */ typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ typedef INT16_TYPE i16; /* 2-byte signed integer */ typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ typedef INT8_TYPE i8; /* 1-byte signed integer */ /* ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value ** that can be stored in a u32 without loss of data. The value ** is 0x00000000ffffffff. But because of quirks of some compilers, we ** have to specify the value in the less intuitive manner shown: */ #define SQLITE_MAX_U32 ((((u64)1)<<32)-1) /* ** Macros to determine whether the machine is big or little endian, ** evaluated at runtime. */ #ifdef SQLITE_AMALGAMATION SQLITE_PRIVATE const int sqlite3one = 1; #else SQLITE_PRIVATE const int sqlite3one; #endif #if defined(i386) || defined(__i386__) || defined(_M_IX86)\ || defined(__x86_64) || defined(__x86_64__) # define SQLITE_BIGENDIAN 0 # define SQLITE_LITTLEENDIAN 1 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE #else # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif /* ** Constants for the largest and smallest possible 64-bit signed integers. ** These macros are designed to work correctly on both 32-bit and 64-bit ** compilers. */ #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) /* ** Round up a number to the next larger multiple of 8. This is used ** to force 8-byte alignment on 64-bit architectures. */ #define ROUND8(x) (((x)+7)&~7) /* ** Round down to the nearest multiple of 8 */ #define ROUNDDOWN8(x) ((x)&~7) /* ** Assert that the pointer X is aligned to an 8-byte boundary. */ #define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) /* ** An instance of the following structure is used to store the busy-handler ** callback for a given sqlite handle. ** ** The sqlite.busyHandler member of the sqlite struct contains the busy ** callback for the database handle. Each pager opened via the sqlite ** handle is passed a pointer to sqlite.busyHandler. The busy-handler ** callback is currently invoked only from within pager.c. */ typedef struct BusyHandler BusyHandler; struct BusyHandler { int (*xFunc)(void *,int); /* The busy callback */ void *pArg; /* First arg to busy callback */ int nBusy; /* Incremented with each busy call */ }; /* ** Name of the master database table. The master database table ** is a special table that holds the names and attributes of all ** user tables and indices. */ #define MASTER_NAME "sqlite_master" #define TEMP_MASTER_NAME "sqlite_temp_master" /* ** The root-page of the master database table. */ #define MASTER_ROOT 1 /* ** The name of the schema table. */ #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) /* ** A convenience macro that returns the number of elements in ** an array. */ #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) /* ** The following value as a destructor means to use sqlite3DbFree(). ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT. */ #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree) /* ** When SQLITE_OMIT_WSD is defined, it means that the target platform does ** not support Writable Static Data (WSD) such as global and static variables. ** All variables must either be on the stack or dynamically allocated from ** the heap. When WSD is unsupported, the variable declarations scattered ** throughout the SQLite code must become constants instead. The SQLITE_WSD ** macro is used for this purpose. And instead of referencing the variable ** directly, we use its constant as a key to lookup the run-time allocated ** buffer that holds real variable. The constant is also the initializer ** for the run-time allocated buffer. ** ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL ** macros become no-ops and have zero performance impact. */ #ifdef SQLITE_OMIT_WSD #define SQLITE_WSD const #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) SQLITE_API int sqlite3_wsd_init(int N, int J); SQLITE_API void *sqlite3_wsd_find(void *K, int L); #else #define SQLITE_WSD #define GLOBAL(t,v) v #define sqlite3GlobalConfig sqlite3Config #endif /* ** The following macros are used to suppress compiler warnings and to ** make it clear to human readers when a function parameter is deliberately ** left unused within the body of a function. This usually happens when ** a function is called via a function pointer. For example the ** implementation of an SQL aggregate step callback may not use the ** parameter indicating the number of arguments passed to the aggregate, ** if it knows that this is enforced elsewhere. ** ** When a function parameter is not used at all within the body of a function, ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. ** However, these macros may also be used to suppress warnings related to ** parameters that may or may not be used depending on compilation options. ** For example those parameters only used in assert() statements. In these ** cases the parameters are named as per the usual conventions. */ #define UNUSED_PARAMETER(x) (void)(x) #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) /* ** Forward references to structures */ typedef struct AggInfo AggInfo; typedef struct AuthContext AuthContext; typedef struct AutoincInfo AutoincInfo; typedef struct Bitvec Bitvec; typedef struct RowSet RowSet; typedef struct CollSeq CollSeq; typedef struct Column Column; typedef struct Db Db; typedef struct Schema Schema; typedef struct Expr Expr; typedef struct ExprList ExprList; typedef struct ExprSpan ExprSpan; typedef struct FKey FKey; typedef struct FuncDef FuncDef; typedef struct FuncDefHash FuncDefHash; typedef struct IdList IdList; typedef struct Index Index; typedef struct IndexSample IndexSample; typedef struct KeyClass KeyClass; typedef struct KeyInfo KeyInfo; typedef struct Lookaside Lookaside; typedef struct LookasideSlot LookasideSlot; typedef struct Module Module; typedef struct NameContext NameContext; typedef struct Parse Parse; typedef struct Savepoint Savepoint; typedef struct Select Select; typedef struct SrcList SrcList; typedef struct StrAccum StrAccum; typedef struct Table Table; typedef struct TableLock TableLock; typedef struct Token Token; typedef struct TriggerPrg TriggerPrg; typedef struct TriggerStep TriggerStep; typedef struct Trigger Trigger; typedef struct UnpackedRecord UnpackedRecord; typedef struct VTable VTable; typedef struct Walker Walker; typedef struct WherePlan WherePlan; typedef struct WhereInfo WhereInfo; typedef struct WhereLevel WhereLevel; /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque ** pointer types (i.e. FuncDef) defined above. */ /************** Include btree.h in the middle of sqliteInt.h *****************/ /************** Begin file btree.h *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite B-Tree file ** subsystem. See comments in the source code for a detailed description ** of what each interface routine does. ** ** @(#) $Id: btree.h,v 1.120 2009/07/22 00:35:24 drh Exp $ */ #ifndef _BTREE_H_ #define _BTREE_H_ /* TODO: This definition is just included so other modules compile. It ** needs to be revisited. */ #define SQLITE_N_BTREE_META 10 /* ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise ** it must be turned on for each database using "PRAGMA auto_vacuum = 1". */ #ifndef SQLITE_DEFAULT_AUTOVACUUM #define SQLITE_DEFAULT_AUTOVACUUM 0 #endif #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ /* ** Forward declarations of structure */ typedef struct Btree Btree; typedef struct BtCursor BtCursor; typedef struct BtShared BtShared; typedef struct BtreeMutexArray BtreeMutexArray; /* ** This structure records all of the Btrees that need to hold ** a mutex before we enter sqlite3VdbeExec(). The Btrees are ** are placed in aBtree[] in order of aBtree[]->pBt. That way, ** we can always lock and unlock them all quickly. */ struct BtreeMutexArray { int nMutex; Btree *aBtree[SQLITE_MAX_ATTACHED+1]; }; SQLITE_PRIVATE int sqlite3BtreeOpen( const char *zFilename, /* Name of database file to open */ sqlite3 *db, /* Associated database connection */ Btree **ppBtree, /* Return open Btree* here */ int flags, /* Flags */ int vfsFlags /* Flags passed through to VFS open */ ); /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the ** following values. ** ** NOTE: These values must match the corresponding PAGER_ values in ** pager.h. */ #define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */ #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */ #define BTREE_MEMORY 4 /* In-memory DB. No argument */ #define BTREE_READONLY 8 /* Open the database in read-only mode */ #define BTREE_READWRITE 16 /* Open for both reading and writing */ #define BTREE_CREATE 32 /* Create the database if it does not exist */ SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int); SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*); SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*); SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR ** of the following flags: */ #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ #define BTREE_ZERODATA 2 /* Table has keys only - no data */ #define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */ SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); /* ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta ** should be one of the following values. The integer values are assigned ** to constants so that the offset of the corresponding field in an ** SQLite database header may be found using the following formula: ** ** offset = 36 + (idx * 4) ** ** For example, the free-page-count field is located at byte offset 36 of ** the database file header. The incr-vacuum-flag field is located at ** byte offset 64 (== 36+4*7). */ #define BTREE_FREE_PAGE_COUNT 0 #define BTREE_SCHEMA_VERSION 1 #define BTREE_FILE_FORMAT 2 #define BTREE_DEFAULT_CACHE_SIZE 3 #define BTREE_LARGEST_ROOT_PAGE 4 #define BTREE_TEXT_ENCODING 5 #define BTREE_USER_VERSION 6 #define BTREE_INCR_VACUUM 7 SQLITE_PRIVATE int sqlite3BtreeCursor( Btree*, /* BTree containing table to open */ int iTable, /* Index of root page */ int wrFlag, /* 1 for writing. 0 for read-only */ struct KeyInfo*, /* First argument to compare function */ BtCursor *pCursor /* Space to write cursor structure */ ); SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( BtCursor*, UnpackedRecord *pUnKey, i64 intKey, int bias, int *pRes ); SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, const void *pData, int nData, int nZero, int bias, int seekResult); SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); #ifndef NDEBUG SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); #endif #ifndef SQLITE_OMIT_BTREECOUNT SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); #endif /* ** If we are not using shared cache, then there is no need to ** use mutexes to access the BtShared structures. So make the ** Enter and Leave procedures no-ops. */ #ifndef SQLITE_OMIT_SHARED_CACHE SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); #else # define sqlite3BtreeEnter(X) # define sqlite3BtreeEnterAll(X) #endif #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*); SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*); SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); #ifndef NDEBUG /* These routines are used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); #endif #else # define sqlite3BtreeLeave(X) # define sqlite3BtreeEnterCursor(X) # define sqlite3BtreeLeaveCursor(X) # define sqlite3BtreeLeaveAll(X) # define sqlite3BtreeMutexArrayEnter(X) # define sqlite3BtreeMutexArrayLeave(X) # define sqlite3BtreeMutexArrayInsert(X,Y) # define sqlite3BtreeHoldsMutex(X) 1 # define sqlite3BtreeHoldsAllMutexes(X) 1 #endif #endif /* _BTREE_H_ */ /************** End of btree.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include vdbe.h in the middle of sqliteInt.h ******************/ /************** Begin file vdbe.h ********************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Header file for the Virtual DataBase Engine (VDBE) ** ** This header defines the interface to the virtual database engine ** or VDBE. The VDBE implements an abstract machine that runs a ** simple program to access and modify the underlying database. ** ** $Id: vdbe.h,v 1.142 2009/07/24 17:58:53 danielk1977 Exp $ */ #ifndef _SQLITE_VDBE_H_ #define _SQLITE_VDBE_H_ /* ** A single VDBE is an opaque structure named "Vdbe". Only routines ** in the source file sqliteVdbe.c are allowed to see the insides ** of this structure. */ typedef struct Vdbe Vdbe; /* ** The names of the following types declared in vdbeInt.h are required ** for the VdbeOp definition. */ typedef struct VdbeFunc VdbeFunc; typedef struct Mem Mem; typedef struct SubProgram SubProgram; /* ** A single instruction of the virtual machine has an opcode ** and as many as three operands. The instruction is recorded ** as an instance of the following structure: */ struct VdbeOp { u8 opcode; /* What operation to perform */ signed char p4type; /* One of the P4_xxx constants for p4 */ u8 opflags; /* Not currently used */ u8 p5; /* Fifth parameter is an unsigned character */ int p1; /* First operand */ int p2; /* Second parameter (often the jump destination) */ int p3; /* The third parameter */ union { /* fourth parameter */ int i; /* Integer value if p4type==P4_INT32 */ void *p; /* Generic pointer */ char *z; /* Pointer to data for string (char array) types */ i64 *pI64; /* Used when p4type is P4_INT64 */ double *pReal; /* Used when p4type is P4_REAL */ FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ Mem *pMem; /* Used when p4type is P4_MEM */ VTable *pVtab; /* Used when p4type is P4_VTAB */ KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ int *ai; /* Used when p4type is P4_INTARRAY */ SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ } p4; #ifdef SQLITE_DEBUG char *zComment; /* Comment to improve readability */ #endif #ifdef VDBE_PROFILE int cnt; /* Number of times this instruction was executed */ u64 cycles; /* Total time spent executing this instruction */ #endif }; typedef struct VdbeOp VdbeOp; /* ** A sub-routine used to implement a trigger program. */ struct SubProgram { VdbeOp *aOp; /* Array of opcodes for sub-program */ int nOp; /* Elements in aOp[] */ int nMem; /* Number of memory cells required */ int nCsr; /* Number of cursors required */ int nRef; /* Number of pointers to this structure */ void *token; /* id that may be used to recursive triggers */ }; /* ** A smaller version of VdbeOp used for the VdbeAddOpList() function because ** it takes up less space. */ struct VdbeOpList { u8 opcode; /* What operation to perform */ signed char p1; /* First operand */ signed char p2; /* Second parameter (often the jump destination) */ signed char p3; /* Third parameter */ }; typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p4type */ #define P4_NOTUSED 0 /* The P4 parameter is not used */ #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ #define P4_STATIC (-2) /* Pointer to a static string */ #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */ #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */ #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ #define P4_REAL (-12) /* P4 is a 64-bit floating point value */ #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure ** is made. That copy is freed when the Vdbe is finalized. But if the ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still ** gets freed when the Vdbe is finalized so it still should be obtained ** from a single sqliteMalloc(). But no copy is made and the calling ** function should *not* try to free the KeyInfo. */ #define P4_KEYINFO_HANDOFF (-16) #define P4_KEYINFO_STATIC (-17) /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the ** number of columns of data returned by the statement. */ #define COLNAME_NAME 0 #define COLNAME_DECLTYPE 1 #define COLNAME_DATABASE 2 #define COLNAME_TABLE 3 #define COLNAME_COLUMN 4 #ifdef SQLITE_ENABLE_COLUMN_METADATA # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ #else # ifdef SQLITE_OMIT_DECLTYPE # define COLNAME_N 1 /* Store only the name */ # else # define COLNAME_N 2 /* Store the name and decltype */ # endif #endif /* ** The following macro converts a relative address in the p2 field ** of a VdbeOp structure into a negative number so that ** sqlite3VdbeAddOpList() knows that the address is relative. Calling ** the macro again restores the address. */ #define ADDR(X) (-1-(X)) /* ** The makefile scans the vdbe.c source file and creates the "opcodes.h" ** header file that defines a number for each opcode used by the VDBE. */ /************** Include opcodes.h in the middle of vdbe.h ********************/ /************** Begin file opcodes.h *****************************************/ /* Automatically generated. Do not edit */ /* See the mkopcodeh.awk script for details */ #define OP_Goto 1 #define OP_Gosub 2 #define OP_Return 3 #define OP_Yield 4 #define OP_HaltIfNull 5 #define OP_Halt 6 #define OP_Integer 7 #define OP_Int64 8 #define OP_Real 130 /* same as TK_FLOAT */ #define OP_String8 94 /* same as TK_STRING */ #define OP_String 9 #define OP_Null 10 #define OP_Blob 11 #define OP_Variable 12 #define OP_Move 13 #define OP_Copy 14 #define OP_SCopy 15 #define OP_ResultRow 16 #define OP_Concat 91 /* same as TK_CONCAT */ #define OP_Add 86 /* same as TK_PLUS */ #define OP_Subtract 87 /* same as TK_MINUS */ #define OP_Multiply 88 /* same as TK_STAR */ #define OP_Divide 89 /* same as TK_SLASH */ #define OP_Remainder 90 /* same as TK_REM */ #define OP_CollSeq 17 #define OP_Function 18 #define OP_BitAnd 82 /* same as TK_BITAND */ #define OP_BitOr 83 /* same as TK_BITOR */ #define OP_ShiftLeft 84 /* same as TK_LSHIFT */ #define OP_ShiftRight 85 /* same as TK_RSHIFT */ #define OP_AddImm 20 #define OP_MustBeInt 21 #define OP_RealAffinity 22 #define OP_ToText 141 /* same as TK_TO_TEXT */ #define OP_ToBlob 142 /* same as TK_TO_BLOB */ #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ #define OP_ToInt 144 /* same as TK_TO_INT */ #define OP_ToReal 145 /* same as TK_TO_REAL */ #define OP_Eq 76 /* same as TK_EQ */ #define OP_Ne 75 /* same as TK_NE */ #define OP_Lt 79 /* same as TK_LT */ #define OP_Le 78 /* same as TK_LE */ #define OP_Gt 77 /* same as TK_GT */ #define OP_Ge 80 /* same as TK_GE */ #define OP_Permutation 23 #define OP_Compare 24 #define OP_Jump 25 #define OP_And 69 /* same as TK_AND */ #define OP_Or 68 /* same as TK_OR */ #define OP_Not 19 /* same as TK_NOT */ #define OP_BitNot 93 /* same as TK_BITNOT */ #define OP_If 26 #define OP_IfNot 27 #define OP_IsNull 73 /* same as TK_ISNULL */ #define OP_NotNull 74 /* same as TK_NOTNULL */ #define OP_Column 28 #define OP_Affinity 29 #define OP_MakeRecord 30 #define OP_Count 31 #define OP_Savepoint 32 #define OP_AutoCommit 33 #define OP_Transaction 34 #define OP_ReadCookie 35 #define OP_SetCookie 36 #define OP_VerifyCookie 37 #define OP_OpenRead 38 #define OP_OpenWrite 39 #define OP_OpenEphemeral 40 #define OP_OpenPseudo 41 #define OP_Close 42 #define OP_SeekLt 43 #define OP_SeekLe 44 #define OP_SeekGe 45 #define OP_SeekGt 46 #define OP_Seek 47 #define OP_NotFound 48 #define OP_Found 49 #define OP_IsUnique 50 #define OP_NotExists 51 #define OP_Sequence 52 #define OP_NewRowid 53 #define OP_Insert 54 #define OP_InsertInt 55 #define OP_Delete 56 #define OP_ResetCount 57 #define OP_RowKey 58 #define OP_RowData 59 #define OP_Rowid 60 #define OP_NullRow 61 #define OP_Last 62 #define OP_Sort 63 #define OP_Rewind 64 #define OP_Prev 65 #define OP_Next 66 #define OP_IdxInsert 67 #define OP_IdxDelete 70 #define OP_IdxRowid 71 #define OP_IdxLT 72 #define OP_IdxGE 81 #define OP_Destroy 92 #define OP_Clear 95 #define OP_CreateIndex 96 #define OP_CreateTable 97 #define OP_ParseSchema 98 #define OP_LoadAnalysis 99 #define OP_DropTable 100 #define OP_DropIndex 101 #define OP_DropTrigger 102 #define OP_IntegrityCk 103 #define OP_RowSetAdd 104 #define OP_RowSetRead 105 #define OP_RowSetTest 106 #define OP_Program 107 #define OP_Param 108 #define OP_FkCounter 109 #define OP_FkIfZero 110 #define OP_MemMax 111 #define OP_IfPos 112 #define OP_IfNeg 113 #define OP_IfZero 114 #define OP_AggStep 115 #define OP_AggFinal 116 #define OP_Vacuum 117 #define OP_IncrVacuum 118 #define OP_Expire 119 #define OP_TableLock 120 #define OP_VBegin 121 #define OP_VCreate 122 #define OP_VDestroy 123 #define OP_VOpen 124 #define OP_VFilter 125 #define OP_VColumn 126 #define OP_VNext 127 #define OP_VRename 128 #define OP_VUpdate 129 #define OP_Pagecount 131 #define OP_Trace 132 #define OP_Noop 133 #define OP_Explain 134 /* The following opcode values are never used */ #define OP_NotUsed_135 135 #define OP_NotUsed_136 136 #define OP_NotUsed_137 137 #define OP_NotUsed_138 138 #define OP_NotUsed_139 139 #define OP_NotUsed_140 140 /* Properties such as "out2" or "jump" that are specified in ** comments following the "case" for each opcode in the vdbe.c ** are encoded into bitvectors as follows: */ #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ #define OPFLG_IN1 0x0004 /* in1: P1 is an input */ #define OPFLG_IN2 0x0008 /* in2: P2 is an input */ #define OPFLG_IN3 0x0010 /* in3: P3 is an input */ #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */ #define OPFLG_INITIALIZER {\ /* 0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\ /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x04, 0x04,\ /* 16 */ 0x00, 0x00, 0x00, 0x04, 0x04, 0x05, 0x04, 0x00,\ /* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\ /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\ /* 40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\ /* 48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\ /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\ /* 64 */ 0x01, 0x01, 0x01, 0x08, 0x2c, 0x2c, 0x00, 0x02,\ /* 72 */ 0x11, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ /* 80 */ 0x15, 0x11, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\ /* 88 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x02, 0x04, 0x02, 0x00,\ /* 96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ /* 104 */ 0x08, 0x21, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\ /* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\ /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\ /* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\ /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\ /* 144 */ 0x04, 0x04,} /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ /* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int); SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); #endif SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int); SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8); SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int); SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*); SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); #ifndef NDEBUG SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); # define VdbeComment(X) sqlite3VdbeComment X SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); # define VdbeNoopComment(X) sqlite3VdbeNoopComment X #else # define VdbeComment(X) # define VdbeNoopComment(X) #endif #endif /************** End of vdbe.h ************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include pager.h in the middle of sqliteInt.h *****************/ /************** Begin file pager.h *******************************************/ /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. ** ** @(#) $Id: pager.h,v 1.104 2009/07/24 19:01:19 drh Exp $ */ #ifndef _PAGER_H_ #define _PAGER_H_ /* ** Default maximum size for persistent journal files. A negative ** value means no limit. This value may be overridden using the ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". */ #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 #endif /* ** The type used to represent a page number. The first page in a file ** is called page 1. 0 is used to represent "not a page". */ typedef u32 Pgno; /* ** Each open file is managed by a separate instance of the "Pager" structure. */ typedef struct Pager Pager; /* ** Handle type for pages. */ typedef struct PgHdr DbPage; /* ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is ** reserved for working around a windows/posix incompatibility). It is ** used in the journal to signify that the remainder of the journal file ** is devoted to storing a master journal name - there are no more pages to ** roll back. See comments for function writeMasterJournal() in pager.c ** for details. */ #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) /* ** Allowed values for the flags parameter to sqlite3PagerOpen(). ** ** NOTE: These values must match the corresponding BTREE_ values in btree.h. */ #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */ /* ** Valid values for the second argument to sqlite3PagerLockingMode(). */ #define PAGER_LOCKINGMODE_QUERY -1 #define PAGER_LOCKINGMODE_NORMAL 0 #define PAGER_LOCKINGMODE_EXCLUSIVE 1 /* ** Valid values for the second argument to sqlite3PagerJournalMode(). */ #define PAGER_JOURNALMODE_QUERY -1 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ /* ** The remainder of this file contains the declarations of the functions ** that make up the Pager sub-system API. See source code comments for ** a detailed description of each routine. */ /* Open and close a Pager connection. */ SQLITE_PRIVATE int sqlite3PagerOpen( sqlite3_vfs*, Pager **ppPager, const char*, int, int, int, void(*)(DbPage*) ); SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); /* Functions used to configure a Pager object. */ SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int); SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int); SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int); SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); /* Functions used to obtain and release page references. */ SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); /* Operations on page references. */ SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); /* Functions used to manage pager transactions and savepoints. */ SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*); SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); /* Functions used to query pager state and configuration. */ SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*); SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*); SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); /* Functions used to truncate the database file. */ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); /* Functions to support testing and debugging. */ #if !defined(NDEBUG) || defined(SQLITE_TEST) SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); void disable_simulated_io_errors(void); void enable_simulated_io_errors(void); #else # define disable_simulated_io_errors() # define enable_simulated_io_errors() #endif #endif /* _PAGER_H_ */ /************** End of pager.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include pcache.h in the middle of sqliteInt.h ****************/ /************** Begin file pcache.h ******************************************/ /* ** 2008 August 05 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This header file defines the interface that the sqlite page cache ** subsystem. ** ** @(#) $Id: pcache.h,v 1.20 2009/07/25 11:46:49 danielk1977 Exp $ */ #ifndef _PCACHE_H_ typedef struct PgHdr PgHdr; typedef struct PCache PCache; /* ** Every page in the cache is controlled by an instance of the following ** structure. */ struct PgHdr { void *pData; /* Content of this page */ void *pExtra; /* Extra content */ PgHdr *pDirty; /* Transient list of dirty pages */ Pgno pgno; /* Page number for this page */ Pager *pPager; /* The pager this page is part of */ #ifdef SQLITE_CHECK_PAGES u32 pageHash; /* Hash of page content */ #endif u16 flags; /* PGHDR flags defined below */ /********************************************************************** ** Elements above are public. All that follows is private to pcache.c ** and should not be accessed by other modules. */ i16 nRef; /* Number of users of this page */ PCache *pCache; /* Cache that owns this page */ PgHdr *pDirtyNext; /* Next element in list of dirty pages */ PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ }; /* Bit values for PgHdr.flags */ #define PGHDR_DIRTY 0x002 /* Page has changed */ #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before ** writing this page to the database */ #define PGHDR_NEED_READ 0x008 /* Content is unread */ #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ /* Initialize and shutdown the page cache subsystem */ SQLITE_PRIVATE int sqlite3PcacheInitialize(void); SQLITE_PRIVATE void sqlite3PcacheShutdown(void); /* Page cache buffer management: ** These routines implement SQLITE_CONFIG_PAGECACHE. */ SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); /* Create a new pager cache. ** Under memory stress, invoke xStress to try to make pages clean. ** Only clean and unpinned pages can be reclaimed. */ SQLITE_PRIVATE void sqlite3PcacheOpen( int szPage, /* Size of every page */ int szExtra, /* Extra space associated with each page */ int bPurgeable, /* True if pages are on backing store */ int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ void *pStress, /* Argument to xStress */ PCache *pToInit /* Preallocated space for the PCache */ ); /* Modify the page-size after the cache has been created. */ SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int); /* Return the size in bytes of a PCache object. Used to preallocate ** storage space. */ SQLITE_PRIVATE int sqlite3PcacheSize(void); /* One release per successful fetch. Page is pinned until released. ** Reference counted. */ SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ /* Change a page number. Used by incr-vacuum. */ SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); /* Remove all pages with pgno>x. Reset the cache if x==0 */ SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); /* Get a list of all dirty pages in the cache, sorted by page number */ SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); /* Reset and close the cache object */ SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); /* Clear flags from pages of the page cache */ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); /* Discard the contents of the cache */ SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); /* Return the total number of outstanding page references */ SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); /* Increment the reference count of an existing page */ SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); /* Return the total number of pages stored in the cache */ SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) /* Iterate through all dirty pages currently stored in the cache. This ** interface is only available if SQLITE_CHECK_PAGES is defined when the ** library is built. */ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); #endif /* Set and get the suggested cache-size for the specified pager-cache. ** ** If no global maximum is configured, then the system attempts to limit ** the total number of pages cached by purgeable pager-caches to the sum ** of the suggested cache-sizes. */ SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); #endif #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT /* Try to return memory used by the pcache module to the main memory heap */ SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); #endif #ifdef SQLITE_TEST SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); #endif SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); #endif /* _PCACHE_H_ */ /************** End of pcache.h **********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include os.h in the middle of sqliteInt.h ********************/ /************** Begin file os.h **********************************************/ /* ** 2001 September 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This header file (together with is companion C source-code file ** "os.c") attempt to abstract the underlying operating system so that ** the SQLite library will work on both POSIX and windows systems. ** ** This header file is #include-ed by sqliteInt.h and thus ends up ** being included by every source file. ** ** $Id: os.h,v 1.108 2009/02/05 16:31:46 drh Exp $ */ #ifndef _SQLITE_OS_H_ #define _SQLITE_OS_H_ /* ** Figure out if we are dealing with Unix, Windows, or some other ** operating system. After the following block of preprocess macros, ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER ** will defined to either 1 or 0. One of the four will be 1. The other ** three will be 0. */ #if defined(SQLITE_OS_OTHER) # if SQLITE_OS_OTHER==1 # undef SQLITE_OS_UNIX # define SQLITE_OS_UNIX 0 # undef SQLITE_OS_WIN # define SQLITE_OS_WIN 0 # undef SQLITE_OS_OS2 # define SQLITE_OS_OS2 0 # else # undef SQLITE_OS_OTHER # endif #endif #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) # define SQLITE_OS_OTHER 0 # ifndef SQLITE_OS_WIN # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) # define SQLITE_OS_WIN 1 # define SQLITE_OS_UNIX 0 # define SQLITE_OS_OS2 0 # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__) # define SQLITE_OS_WIN 0 # define SQLITE_OS_UNIX 0 # define SQLITE_OS_OS2 1 # else # define SQLITE_OS_WIN 0 # define SQLITE_OS_UNIX 1 # define SQLITE_OS_OS2 0 # endif # else # define SQLITE_OS_UNIX 0 # define SQLITE_OS_OS2 0 # endif #else # ifndef SQLITE_OS_WIN # define SQLITE_OS_WIN 0 # endif #endif /* ** Determine if we are dealing with WindowsCE - which has a much ** reduced API. */ #if defined(_WIN32_WCE) # define SQLITE_OS_WINCE 1 #else # define SQLITE_OS_WINCE 0 #endif /* ** Define the maximum size of a temporary filename */ #if SQLITE_OS_WIN # include # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50) #elif SQLITE_OS_OS2 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY) # include /* has to be included before os2.h for linking to work */ # endif # define INCL_DOSDATETIME # define INCL_DOSFILEMGR # define INCL_DOSERRORS # define INCL_DOSMISC # define INCL_DOSPROCESS # define INCL_DOSMODULEMGR # define INCL_DOSSEMAPHORES # include # include # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP) #else # define SQLITE_TEMPNAME_SIZE 200 #endif /* If the SET_FULLSYNC macro is not defined above, then make it ** a no-op */ #ifndef SET_FULLSYNC # define SET_FULLSYNC(x,y) #endif /* ** The default size of a disk sector */ #ifndef SQLITE_DEFAULT_SECTOR_SIZE # define SQLITE_DEFAULT_SECTOR_SIZE 512 #endif /* ** Temporary files are named starting with this prefix followed by 16 random ** alphanumeric characters, and no file extension. They are stored in the ** OS's standard temporary file directory, and are deleted prior to exit. ** If sqlite is being embedded in another program, you may wish to change the ** prefix to reflect your program's name, so that if your program exits ** prematurely, old temporary files can be easily identified. This can be done ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. ** ** 2006-10-31: The default prefix used to be "sqlite_". But then ** Mcafee started using SQLite in their anti-virus product and it ** started putting files with the "sqlite" name in the c:/temp folder. ** This annoyed many windows users. Those users would then do a ** Google search for "sqlite", find the telephone numbers of the ** developers and call to wake them up at night and complain. ** For this reason, the default name prefix is changed to be "sqlite" ** spelled backwards. So the temp files are still identified, but ** anybody smart enough to figure out the code is also likely smart ** enough to know that calling the developer will not help get rid ** of the file. */ #ifndef SQLITE_TEMP_FILE_PREFIX # define SQLITE_TEMP_FILE_PREFIX "etilqs_" #endif /* ** The following values may be passed as the second argument to ** sqlite3OsLock(). The various locks exhibit the following semantics: ** ** SHARED: Any number of processes may hold a SHARED lock simultaneously. ** RESERVED: A single process may hold a RESERVED lock on a file at ** any time. Other processes may hold and obtain new SHARED locks. ** PENDING: A single process may hold a PENDING lock on a file at ** any one time. Existing SHARED locks may persist, but no new ** SHARED locks may be obtained by other processes. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. ** ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a ** process that requests an EXCLUSIVE lock may actually obtain a PENDING ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to ** sqlite3OsLock(). */ #define NO_LOCK 0 #define SHARED_LOCK 1 #define RESERVED_LOCK 2 #define PENDING_LOCK 3 #define EXCLUSIVE_LOCK 4 /* ** File Locking Notes: (Mostly about windows but also some info for Unix) ** ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because ** those functions are not available. So we use only LockFile() and ** UnlockFile(). ** ** LockFile() prevents not just writing but also reading by other processes. ** A SHARED_LOCK is obtained by locking a single randomly-chosen ** byte out of a specific range of bytes. The lock byte is obtained at ** random so two separate readers can probably access the file at the ** same time, unless they are unlucky and choose the same lock byte. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. ** There can only be one writer. A RESERVED_LOCK is obtained by locking ** a single byte of the file that is designated as the reserved lock byte. ** A PENDING_LOCK is obtained by locking a designated byte different from ** the RESERVED_LOCK byte. ** ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, ** which means we can use reader/writer locks. When reader/writer locks ** are used, the lock is placed on the same range of bytes that is used ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme ** will support two or more Win95 readers or two or more WinNT readers. ** But a single Win95 reader will lock out all WinNT readers and a single ** WinNT reader will lock out all other Win95 readers. ** ** The following #defines specify the range of bytes used for locking. ** SHARED_SIZE is the number of bytes available in the pool from which ** a random byte is selected for a shared lock. The pool of bytes for ** shared locks begins at SHARED_FIRST. ** ** The same locking strategy and ** byte ranges are used for Unix. This leaves open the possiblity of having ** clients on win95, winNT, and unix all talking to the same shared file ** and all locking correctly. To do so would require that samba (or whatever ** tool is being used for file sharing) implements locks correctly between ** windows and unix. I'm guessing that isn't likely to happen, but by ** using the same locking range we are at least open to the possibility. ** ** Locking in windows is manditory. For this reason, we cannot store ** actual data in the bytes used for locking. The pager never allocates ** the pages involved in locking therefore. SHARED_SIZE is selected so ** that all locks will fit on a single page even at the minimum page size. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE ** is set high so that we don't have to allocate an unused page except ** for very large databases. But one should test the page skipping logic ** by setting PENDING_BYTE low and running the entire regression suite. ** ** Changing the value of PENDING_BYTE results in a subtly incompatible ** file format. Depending on how it is changed, you might not notice ** the incompatibility right away, even running a full regression test. ** The default location of PENDING_BYTE is the first byte past the ** 1GB boundary. ** */ #define PENDING_BYTE sqlite3PendingByte #define RESERVED_BYTE (PENDING_BYTE+1) #define SHARED_FIRST (PENDING_BYTE+2) #define SHARED_SIZE 510 /* ** Wrapper around OS specific sqlite3_os_init() function. */ SQLITE_PRIVATE int sqlite3OsInit(void); /* ** Functions for accessing sqlite3_file methods */ SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*); SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); /* ** Functions for accessing sqlite3_vfs methods */ SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); #ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); #endif /* SQLITE_OMIT_LOAD_EXTENSION */ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*); /* ** Convenience functions for opening and closing files using ** sqlite3_malloc() to obtain space for the file-handle structure. */ SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); #endif /* _SQLITE_OS_H_ */ /************** End of os.h **************************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /************** Include mutex.h in the middle of sqliteInt.h *****************/ /************** Begin file mutex.h *******************************************/ /* ** 2007 August 28 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains the common header for all mutex implementations. ** The sqliteInt.h header #includes this file so that it is available ** to all source files. We break it out in an effort to keep the code ** better organized. ** ** NOTE: source files should *not* #include this header file directly. ** Source files should #include the sqliteInt.h file and let that file ** include this one indirectly. ** ** $Id: mutex.h,v 1.9 2008/10/07 15:25:48 drh Exp $ */ /* ** Figure out what version of the code to use. The choices are ** ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The ** mutexes implemention cannot be overridden ** at start-time. ** ** SQLITE_MUTEX_NOOP For single-threaded applications. No ** mutual exclusion is provided. But this ** implementation can be overridden at ** start-time. ** ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. ** ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. ** ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2. */ #if !SQLITE_THREADSAFE # define SQLITE_MUTEX_OMIT #endif #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) # if SQLITE_OS_UNIX # define SQLITE_MUTEX_PTHREADS # elif SQLITE_OS_WIN # define SQLITE_MUTEX_W32 # elif SQLITE_OS_OS2 # define SQLITE_MUTEX_OS2 # else # define SQLITE_MUTEX_NOOP # endif #endif #ifdef SQLITE_MUTEX_OMIT /* ** If this is a no-op implementation, implement everything as macros. */ #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) #define sqlite3_mutex_free(X) #define sqlite3_mutex_enter(X) #define sqlite3_mutex_try(X) SQLITE_OK #define sqlite3_mutex_leave(X) #define sqlite3_mutex_held(X) 1 #define sqlite3_mutex_notheld(X) 1 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) #define sqlite3MutexInit() SQLITE_OK #define sqlite3MutexEnd() #endif /* defined(SQLITE_MUTEX_OMIT) */ /************** End of mutex.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ /* ** Each database file to be accessed by the system is an instance ** of the following structure. There are normally two of these structures ** in the sqlite.aDb[] array. aDb[0] is the main database file and ** aDb[1] is the database file used to hold temporary tables. Additional ** databases may be attached. */ struct Db { char *zName; /* Name of this database */ Btree *pBt; /* The B*Tree structure for this database file */ u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ u8 safety_level; /* How aggressive at syncing data to disk */ Schema *pSchema; /* Pointer to database schema (possibly shared) */ }; /* ** An instance of the following structure stores a database schema. ** ** If there are no virtual tables configured in this schema, the ** Schema.db variable is set to NULL. After the first virtual table ** has been added, it is set to point to the database connection ** used to create the connection. Once a virtual table has been ** added to the Schema structure and the Schema.db variable populated, ** only that database connection may use the Schema to prepare ** statements. */ struct Schema { int schema_cookie; /* Database schema version number for this file */ Hash tblHash; /* All tables indexed by name */ Hash idxHash; /* All (named) indices indexed by name */ Hash trigHash; /* All triggers indexed by name */ Hash fkeyHash; /* All foreign keys by referenced table name */ Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ u8 file_format; /* Schema format version for this file */ u8 enc; /* Text encoding used by this database */ u16 flags; /* Flags associated with this schema */ int cache_size; /* Number of pages to use in the cache */ #ifndef SQLITE_OMIT_VIRTUALTABLE sqlite3 *db; /* "Owner" connection. See comment above */ #endif }; /* ** These macros can be used to test, set, or clear bits in the ** Db.flags field. */ #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) /* ** Allowed values for the DB.flags field. ** ** The DB_SchemaLoaded flag is set after the database schema has been ** read into internal hash tables. ** ** DB_UnresetViews means that one or more views have column names that ** have been filled out. If the schema changes, these column names might ** changes and so the view will need to be reset. */ #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ #define DB_UnresetViews 0x0002 /* Some views have defined column names */ #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ /* ** The number of different kinds of things that can be limited ** using the sqlite3_limit() interface. */ #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) /* ** Lookaside malloc is a set of fixed-size buffers that can be used ** to satisfy small transient memory allocation requests for objects ** associated with a particular database connection. The use of ** lookaside malloc provides a significant performance enhancement ** (approx 10%) by avoiding numerous malloc/free requests while parsing ** SQL statements. ** ** The Lookaside structure holds configuration information about the ** lookaside malloc subsystem. Each available memory allocation in ** the lookaside subsystem is stored on a linked list of LookasideSlot ** objects. ** ** Lookaside allocations are only allowed for objects that are associated ** with a particular database connection. Hence, schema information cannot ** be stored in lookaside because in shared cache mode the schema information ** is shared by multiple database connections. Therefore, while parsing ** schema information, the Lookaside.bEnabled flag is cleared so that ** lookaside allocations are not used to construct the schema objects. */ struct Lookaside { u16 sz; /* Size of each buffer in bytes */ u8 bEnabled; /* False to disable new lookaside allocations */ u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ int nOut; /* Number of buffers currently checked out */ int mxOut; /* Highwater mark for nOut */ LookasideSlot *pFree; /* List of available buffers */ void *pStart; /* First byte of available memory space */ void *pEnd; /* First byte past end of available space */ }; struct LookasideSlot { LookasideSlot *pNext; /* Next buffer in the list of free buffers */ }; /* ** A hash table for function definitions. ** ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. ** Collisions are on the FuncDef.pHash chain. */ struct FuncDefHash { FuncDef *a[23]; /* Hash table for functions */ }; /* ** Each database is an instance of the following structure. ** ** The sqlite.lastRowid records the last insert rowid generated by an ** insert statement. Inserts on views do not affect its value. Each ** trigger has its own context, so that lastRowid can be updated inside ** triggers as usual. The previous value will be restored once the trigger ** exits. Upon entering a before or instead of trigger, lastRowid is no ** longer (since after version 2.8.12) reset to -1. ** ** The sqlite.nChange does not count changes within triggers and keeps no ** context. It is reset at start of sqlite3_exec. ** The sqlite.lsChange represents the number of changes made by the last ** insert, update, or delete statement. It remains constant throughout the ** length of a statement and is then updated by OP_SetCounts. It keeps a ** context stack just like lastRowid so that the count of changes ** within a trigger is not seen outside the trigger. Changes to views do not ** affect the value of lsChange. ** The sqlite.csChange keeps track of the number of current changes (since ** the last statement) and is used to update sqlite_lsChange. ** ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16 ** store the most recent error code and, if applicable, string. The ** internal function sqlite3Error() is used to set these variables ** consistently. */ struct sqlite3 { sqlite3_vfs *pVfs; /* OS Interface */ int nDb; /* Number of backends currently in use */ Db *aDb; /* All backends */ int flags; /* Miscellaneous flags. See below */ int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ int errCode; /* Most recent error code (SQLITE_*) */ int errMask; /* & result codes with this before returning */ u8 autoCommit; /* The auto-commit flag. */ u8 temp_store; /* 1: file 2: memory 0: default */ u8 mallocFailed; /* True if we have seen a malloc failure */ u8 dfltLockMode; /* Default locking-mode for attached dbs */ u8 dfltJournalMode; /* Default journal mode for attached dbs */ signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ int nextPagesize; /* Pagesize after VACUUM if >0 */ int nTable; /* Number of tables in the database */ CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ i64 lastRowid; /* ROWID of most recent insert (see above) */ u32 magic; /* Magic number for detect library misuse */ int nChange; /* Value returned by sqlite3_changes() */ int nTotalChange; /* Value returned by sqlite3_total_changes() */ sqlite3_mutex *mutex; /* Connection mutex */ int aLimit[SQLITE_N_LIMIT]; /* Limits */ struct sqlite3InitInfo { /* Information used during initialization */ int iDb; /* When back is being initialized */ int newTnum; /* Rootpage of table being initialized */ u8 busy; /* TRUE if currently initializing */ u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ } init; int nExtension; /* Number of loaded extensions */ void **aExtension; /* Array of shared library handles */ struct Vdbe *pVdbe; /* List of active virtual machines */ int activeVdbeCnt; /* Number of VDBEs currently executing */ int writeVdbeCnt; /* Number of active VDBEs that are writing */ void (*xTrace)(void*,const char*); /* Trace function */ void *pTraceArg; /* Argument to the trace function */ void (*xProfile)(void*,const char*,u64); /* Profiling function */ void *pProfileArg; /* Argument to profile function */ void *pCommitArg; /* Argument to xCommitCallback() */ int (*xCommitCallback)(void*); /* Invoked at every commit. */ void *pRollbackArg; /* Argument to xRollbackCallback() */ void (*xRollbackCallback)(void*); /* Invoked at every commit. */ void *pUpdateArg; void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); void *pCollNeededArg; sqlite3_value *pErr; /* Most recent error message */ char *zErrMsg; /* Most recent error message (UTF-8 encoded) */ char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */ union { volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ double notUsed1; /* Spacer */ } u1; Lookaside lookaside; /* Lookaside malloc configuration */ #ifndef SQLITE_OMIT_AUTHORIZATION int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); /* Access authorization function */ void *pAuthArg; /* 1st argument to the access auth function */ #endif #ifndef SQLITE_OMIT_PROGRESS_CALLBACK int (*xProgress)(void *); /* The progress callback */ void *pProgressArg; /* Argument to the progress callback */ int nProgressOps; /* Number of opcodes for progress callback */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE Hash aModule; /* populated by sqlite3_create_module() */ Table *pVTab; /* vtab with active Connect/Create method */ VTable **aVTrans; /* Virtual tables with open transactions */ int nVTrans; /* Allocated size of aVTrans */ VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ #endif FuncDefHash aFunc; /* Hash table of connection functions */ Hash aCollSeq; /* All collating sequences */ BusyHandler busyHandler; /* Busy callback */ int busyTimeout; /* Busy handler timeout, in msec */ Db aDbStatic[2]; /* Static space for the 2 default backends */ Savepoint *pSavepoint; /* List of active savepoints */ int nSavepoint; /* Number of non-transaction savepoints */ int nStatement; /* Number of nested statement-transactions */ u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ i64 nDeferredCons; /* Net deferred constraints this transaction. */ #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY /* The following variables are all protected by the STATIC_MASTER ** mutex, not by sqlite3.mutex. They are used by code in notify.c. ** ** When X.pUnlockConnection==Y, that means that X is waiting for Y to ** unlock so that it can proceed. ** ** When X.pBlockingConnection==Y, that means that something that X tried ** tried to do recently failed with an SQLITE_LOCKED error due to locks ** held by Y. */ sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ void *pUnlockArg; /* Argument to xUnlockNotify */ void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ #endif }; /* ** A macro to discover the encoding of a database. */ #define ENC(db) ((db)->aDb[0].pSchema->enc) /* ** Possible values for the sqlite.flags and or Db.flags fields. ** ** On sqlite.flags, the SQLITE_InTrans value means that we have ** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement ** transaction is active on that particular database file. */ #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ #define SQLITE_InTrans 0x00000008 /* True if in a transaction */ #define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */ #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */ #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ /* DELETE, or UPDATE and return */ /* the count using a callback. */ #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ /* result set is empty */ #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */ #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */ #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */ #define SQLITE_NoReadlock 0x00001000 /* Readlocks are omitted when ** accessing read-only databases */ #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */ #define SQLITE_ReadUncommitted 0x00004000 /* For shared-cache mode */ #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */ #define SQLITE_FullFSync 0x00010000 /* Use full fsync on the backend */ #define SQLITE_LoadExtension 0x00020000 /* Enable load_extension */ #define SQLITE_RecoveryMode 0x00040000 /* Ignore schema errors */ #define SQLITE_ReverseOrder 0x00100000 /* Reverse unordered SELECTs */ #define SQLITE_RecTriggers 0x00200000 /* Enable recursive triggers */ #define SQLITE_ForeignKeys 0x00400000 /* Enforce foreign key constraints */ /* ** Possible values for the sqlite.magic field. ** The numbers are obtained at random and have no special meaning, other ** than being distinct from one another. */ #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ /* ** Each SQL function is defined by an instance of the following ** structure. A pointer to this structure is stored in the sqlite.aFunc ** hash table. When multiple functions have the same name, the hash table ** points to a linked list of these structures. */ struct FuncDef { i16 nArg; /* Number of arguments. -1 means unlimited */ u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ u8 flags; /* Some combination of SQLITE_FUNC_* */ void *pUserData; /* User data parameter */ FuncDef *pNext; /* Next function with same name */ void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ char *zName; /* SQL name of the function. */ FuncDef *pHash; /* Next with a different name but the same hash */ }; /* ** Possible values for FuncDef.flags */ #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */ #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */ /* ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are ** used to create the initializers for the FuncDef structures. ** ** FUNCTION(zName, nArg, iArg, bNC, xFunc) ** Used to create a scalar function definition of a function zName ** implemented by C function xFunc that accepts nArg arguments. The ** value passed as iArg is cast to a (void*) and made available ** as the user-data (sqlite3_user_data()) for the function. If ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. ** ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) ** Used to create an aggregate function definition implemented by ** the C functions xStep and xFinal. The first four parameters ** are interpreted in the same way as the first 4 parameters to ** FUNCTION(). ** ** LIKEFUNC(zName, nArg, pArg, flags) ** Used to create a scalar function definition of a function zName ** that accepts nArg arguments and is implemented by a call to C ** function likeFunc. Argument pArg is cast to a (void *) and made ** available as the function user-data (sqlite3_user_data()). The ** FuncDef.flags variable is set to the value passed as the flags ** parameter. */ #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0} #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ pArg, 0, xFunc, 0, 0, #zName, 0} #define LIKEFUNC(zName, nArg, arg, flags) \ {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0} #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0} /* ** All current savepoints are stored in a linked list starting at ** sqlite3.pSavepoint. The first element in the list is the most recently ** opened savepoint. Savepoints are added to the list by the vdbe ** OP_Savepoint instruction. */ struct Savepoint { char *zName; /* Savepoint name (nul-terminated) */ i64 nDeferredCons; /* Number of deferred fk violations */ Savepoint *pNext; /* Parent savepoint (if any) */ }; /* ** The following are used as the second parameter to sqlite3Savepoint(), ** and as the P1 argument to the OP_Savepoint instruction. */ #define SAVEPOINT_BEGIN 0 #define SAVEPOINT_RELEASE 1 #define SAVEPOINT_ROLLBACK 2 /* ** Each SQLite module (virtual table definition) is defined by an ** instance of the following structure, stored in the sqlite3.aModule ** hash table. */ struct Module { const sqlite3_module *pModule; /* Callback pointers */ const char *zName; /* Name passed to create_module() */ void *pAux; /* pAux passed to create_module() */ void (*xDestroy)(void *); /* Module destructor function */ }; /* ** information about each column of an SQL table is held in an instance ** of this structure. */ struct Column { char *zName; /* Name of this column */ Expr *pDflt; /* Default value of this column */ char *zDflt; /* Original text of the default value */ char *zType; /* Data type for this column */ char *zColl; /* Collating sequence. If NULL, use the default */ u8 notNull; /* True if there is a NOT NULL constraint */ u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */ char affinity; /* One of the SQLITE_AFF_... values */ #ifndef SQLITE_OMIT_VIRTUALTABLE u8 isHidden; /* True if this column is 'hidden' */ #endif }; /* ** A "Collating Sequence" is defined by an instance of the following ** structure. Conceptually, a collating sequence consists of a name and ** a comparison routine that defines the order of that sequence. ** ** There may two separate implementations of the collation function, one ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine ** native byte order. When a collation sequence is invoked, SQLite selects ** the version that will require the least expensive encoding ** translations, if any. ** ** The CollSeq.pUser member variable is an extra parameter that passed in ** as the first argument to the UTF-8 comparison function, xCmp. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function, ** xCmp16. ** ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the ** collating sequence is undefined. Indices built on an undefined ** collating sequence may not be read or written. */ struct CollSeq { char *zName; /* Name of the collating sequence, UTF-8 encoded */ u8 enc; /* Text encoding handled by xCmp() */ u8 type; /* One of the SQLITE_COLL_... values below */ void *pUser; /* First argument to xCmp() */ int (*xCmp)(void*,int, const void*, int, const void*); void (*xDel)(void*); /* Destructor for pUser */ }; /* ** Allowed values of CollSeq.type: */ #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */ #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */ #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */ #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */ /* ** A sort order can be either ASC or DESC. */ #define SQLITE_SO_ASC 0 /* Sort in ascending order */ #define SQLITE_SO_DESC 1 /* Sort in ascending order */ /* ** Column affinity types. ** ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve ** the speed a little by numbering the values consecutively. ** ** But rather than start with 0 or 1, we begin with 'a'. That way, ** when multiple affinity types are concatenated into a string and ** used as the P4 operand, they will be more readable. ** ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. */ #define SQLITE_AFF_TEXT 'a' #define SQLITE_AFF_NONE 'b' #define SQLITE_AFF_NUMERIC 'c' #define SQLITE_AFF_INTEGER 'd' #define SQLITE_AFF_REAL 'e' #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) /* ** The SQLITE_AFF_MASK values masks off the significant bits of an ** affinity value. */ #define SQLITE_AFF_MASK 0x67 /* ** Additional bit values that can be ORed with an affinity without ** changing the affinity. */ #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ #define SQLITE_NULLEQ 0x80 /* NULL=NULL */ /* ** An object of this type is created for each virtual table present in ** the database schema. ** ** If the database schema is shared, then there is one instance of this ** structure for each database connection (sqlite3*) that uses the shared ** schema. This is because each database connection requires its own unique ** instance of the sqlite3_vtab* handle used to access the virtual table ** implementation. sqlite3_vtab* handles can not be shared between ** database connections, even when the rest of the in-memory database ** schema is shared, as the implementation often stores the database ** connection handle passed to it via the xConnect() or xCreate() method ** during initialization internally. This database connection handle may ** then used by the virtual table implementation to access real tables ** within the database. So that they appear as part of the callers ** transaction, these accesses need to be made via the same database ** connection as that used to execute SQL operations on the virtual table. ** ** All VTable objects that correspond to a single table in a shared ** database schema are initially stored in a linked-list pointed to by ** the Table.pVTable member variable of the corresponding Table object. ** When an sqlite3_prepare() operation is required to access the virtual ** table, it searches the list for the VTable that corresponds to the ** database connection doing the preparing so as to use the correct ** sqlite3_vtab* handle in the compiled query. ** ** When an in-memory Table object is deleted (for example when the ** schema is being reloaded for some reason), the VTable objects are not ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed ** immediately. Instead, they are moved from the Table.pVTable list to ** another linked list headed by the sqlite3.pDisconnect member of the ** corresponding sqlite3 structure. They are then deleted/xDisconnected ** next time a statement is prepared using said sqlite3*. This is done ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. ** Refer to comments above function sqlite3VtabUnlockList() for an ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect ** list without holding the corresponding sqlite3.mutex mutex. ** ** The memory for objects of this type is always allocated by ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as ** the first argument. */ struct VTable { sqlite3 *db; /* Database connection associated with this table */ Module *pMod; /* Pointer to module implementation */ sqlite3_vtab *pVtab; /* Pointer to vtab instance */ int nRef; /* Number of pointers to this structure */ VTable *pNext; /* Next in linked list (see above) */ }; /* ** Each SQL table is represented in memory by an instance of the ** following structure. ** ** Table.zName is the name of the table. The case of the original ** CREATE TABLE statement is stored, but case is not significant for ** comparisons. ** ** Table.nCol is the number of columns in this table. Table.aCol is a ** pointer to an array of Column structures, one for each column. ** ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of ** the column that is that key. Otherwise Table.iPKey is negative. Note ** that the datatype of the PRIMARY KEY must be INTEGER for this field to ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid ** is generated for each row of the table. TF_HasPrimaryKey is set if ** the table has any PRIMARY KEY, INTEGER or otherwise. ** ** Table.tnum is the page number for the root BTree page of the table in the ** database file. If Table.iDb is the index of the database table backend ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that ** holds temporary tables and indices. If TF_Ephemeral is set ** then the table is stored in a file that is automatically deleted ** when the VDBE cursor to the table is closed. In this case Table.tnum ** refers VDBE cursor number that holds the table open, not to the root ** page number. Transient tables are used to hold the results of a ** sub-query that appears instead of a real table name in the FROM clause ** of a SELECT statement. */ struct Table { sqlite3 *dbMem; /* DB connection used for lookaside allocations. */ char *zName; /* Name of the table or view */ int iPKey; /* If not negative, use aCol[iPKey] as the primary key */ int nCol; /* Number of columns in this table */ Column *aCol; /* Information about each column */ Index *pIndex; /* List of SQL indexes on this table. */ int tnum; /* Root BTree node for this table (see note above) */ Select *pSelect; /* NULL for tables. Points to definition if a view. */ u16 nRef; /* Number of pointers to this Table */ u8 tabFlags; /* Mask of TF_* values */ u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ FKey *pFKey; /* Linked list of all foreign keys in this table */ char *zColAff; /* String defining the affinity of each column */ #ifndef SQLITE_OMIT_CHECK Expr *pCheck; /* The AND of all CHECK constraints */ #endif #ifndef SQLITE_OMIT_ALTERTABLE int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ #endif #ifndef SQLITE_OMIT_VIRTUALTABLE VTable *pVTable; /* List of VTable objects. */ int nModuleArg; /* Number of arguments to the module */ char **azModuleArg; /* Text of all module args. [0] is module name */ #endif Trigger *pTrigger; /* List of triggers stored in pSchema */ Schema *pSchema; /* Schema that contains this table */ Table *pNextZombie; /* Next on the Parse.pZombieTab list */ }; /* ** Allowed values for Tabe.tabFlags. */ #define TF_Readonly 0x01 /* Read-only system table */ #define TF_Ephemeral 0x02 /* An ephemeral table */ #define TF_HasPrimaryKey 0x04 /* Table has a primary key */ #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ #define TF_Virtual 0x10 /* Is a virtual table */ #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */ /* ** Test to see whether or not a table is a virtual table. This is ** done as a macro so that it will be optimized out when virtual ** table support is omitted from the build. */ #ifndef SQLITE_OMIT_VIRTUALTABLE # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) # define IsHiddenColumn(X) ((X)->isHidden) #else # define IsVirtual(X) 0 # define IsHiddenColumn(X) 0 #endif /* ** Each foreign key constraint is an instance of the following structure. ** ** A foreign key is associated with two tables. The "from" table is ** the table that contains the REFERENCES clause that creates the foreign ** key. The "to" table is the table that is named in the REFERENCES clause. ** Consider this example: ** ** CREATE TABLE ex1( ** a INTEGER PRIMARY KEY, ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) ** ); ** ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". ** ** Each REFERENCES clause generates an instance of the following structure ** which is attached to the from-table. The to-table need not exist when ** the from-table is created. The existence of the to-table is not checked. */ struct FKey { Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ FKey *pNextFrom; /* Next foreign key in pFrom */ char *zTo; /* Name of table that the key points to (aka: Parent) */ FKey *pNextTo; /* Next foreign key on table named zTo */ FKey *pPrevTo; /* Previous foreign key on table named zTo */ int nCol; /* Number of columns in this key */ /* EV: R-30323-21917 */ u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ int iFrom; /* Index of column in pFrom */ char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ } aCol[1]; /* One entry for each of nCol column s */ }; /* ** SQLite supports many different ways to resolve a constraint ** error. ROLLBACK processing means that a constraint violation ** causes the operation in process to fail and for the current transaction ** to be rolled back. ABORT processing means the operation in process ** fails and any prior changes from that one operation are backed out, ** but the transaction is not rolled back. FAIL processing means that ** the operation in progress stops and returns an error code. But prior ** changes due to the same operation are not backed out and no rollback ** occurs. IGNORE means that the particular row that caused the constraint ** error is not inserted or updated. Processing continues and no error ** is returned. REPLACE means that preexisting database rows that caused ** a UNIQUE constraint violation are removed so that the new insert or ** update can proceed. Processing continues and no error is reported. ** ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the ** referenced table row is propagated into the row that holds the ** foreign key. ** ** The following symbolic values are used to record which type ** of action to take. */ #define OE_None 0 /* There is no constraint to check */ #define OE_Rollback 1 /* Fail the operation and rollback the transaction */ #define OE_Abort 2 /* Back out changes but do no rollback transaction */ #define OE_Fail 3 /* Stop the operation but leave all prior changes */ #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ #define OE_SetNull 7 /* Set the foreign key value to NULL */ #define OE_SetDflt 8 /* Set the foreign key value to its default */ #define OE_Cascade 9 /* Cascade the changes */ #define OE_Default 99 /* Do whatever the default action is */ /* ** An instance of the following structure is passed as the first ** argument to sqlite3VdbeKeyCompare and is used to control the ** comparison of the two index keys. */ struct KeyInfo { sqlite3 *db; /* The database connection */ u8 enc; /* Text encoding - one of the TEXT_Utf* values */ u16 nField; /* Number of entries in aColl[] */ u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */ CollSeq *aColl[1]; /* Collating sequence for each term of the key */ }; /* ** An instance of the following structure holds information about a ** single index record that has already been parsed out into individual ** values. ** ** A record is an object that contains one or more fields of data. ** Records are used to store the content of a table row and to store ** the key of an index. A blob encoding of a record is created by ** the OP_MakeRecord opcode of the VDBE and is disassembled by the ** OP_Column opcode. ** ** This structure holds a record that has already been disassembled ** into its constituent fields. */ struct UnpackedRecord { KeyInfo *pKeyInfo; /* Collation and sort-order information */ u16 nField; /* Number of entries in apMem[] */ u16 flags; /* Boolean settings. UNPACKED_... below */ i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ Mem *aMem; /* Values */ }; /* ** Allowed values of UnpackedRecord.flags */ #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */ #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */ #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */ #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */ #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */ #define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */ /* ** Each SQL index is represented in memory by an ** instance of the following structure. ** ** The columns of the table that are to be indexed are described ** by the aiColumn[] field of this structure. For example, suppose ** we have the following table and index: ** ** CREATE TABLE Ex1(c1 int, c2 int, c3 text); ** CREATE INDEX Ex2 ON Ex1(c3,c1); ** ** In the Table structure describing Ex1, nCol==3 because there are ** three columns in the table. In the Index structure describing ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. ** The second column to be indexed (c1) has an index of 0 in ** Ex1.aCol[], hence Ex2.aiColumn[1]==0. ** ** The Index.onError field determines whether or not the indexed columns ** must be unique and what to do if they are not. When Index.onError=OE_None, ** it means this is not a unique index. Otherwise it is a unique index ** and the value of Index.onError indicate the which conflict resolution ** algorithm to employ whenever an attempt is made to insert a non-unique ** element. */ struct Index { char *zName; /* Name of this index */ int nColumn; /* Number of columns in the table used by this index */ int *aiColumn; /* Which columns are used by this index. 1st is 0 */ unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */ Table *pTable; /* The SQL table being indexed */ int tnum; /* Page containing root of this index in database file */ u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */ char *zColAff; /* String defining the affinity of each column */ Index *pNext; /* The next index associated with the same table */ Schema *pSchema; /* Schema containing this index */ u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */ char **azColl; /* Array of collation sequence names for index */ IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */ }; /* ** Each sample stored in the sqlite_stat2 table is represented in memory ** using a structure of this type. */ struct IndexSample { union { char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */ double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */ } u; u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ u8 nByte; /* Size in byte of text or blob. */ }; /* ** Each token coming out of the lexer is an instance of ** this structure. Tokens are also used as part of an expression. ** ** Note if Token.z==0 then Token.dyn and Token.n are undefined and ** may contain random values. Do not make any assumptions about Token.dyn ** and Token.n when Token.z==0. */ struct Token { const char *z; /* Text of the token. Not NULL-terminated! */ unsigned int n; /* Number of characters in this token */ }; /* ** An instance of this structure contains information needed to generate ** code for a SELECT that contains aggregate functions. ** ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a ** pointer to this structure. The Expr.iColumn field is the index in ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate ** code for that node. ** ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the ** original Select structure that describes the SELECT statement. These ** fields do not need to be freed when deallocating the AggInfo structure. */ struct AggInfo { u8 directMode; /* Direct rendering mode means take data directly ** from source tables rather than from accumulators */ u8 useSortingIdx; /* In direct mode, reference the sorting index rather ** than the source table */ int sortingIdx; /* Cursor number of the sorting index */ ExprList *pGroupBy; /* The group by clause */ int nSortingColumn; /* Number of columns in the sorting index */ struct AggInfo_col { /* For each column used in source tables */ Table *pTab; /* Source table */ int iTable; /* Cursor number of the source table */ int iColumn; /* Column number within the source table */ int iSorterColumn; /* Column number in the sorting index */ int iMem; /* Memory location that acts as accumulator */ Expr *pExpr; /* The original expression */ } *aCol; int nColumn; /* Number of used entries in aCol[] */ int nColumnAlloc; /* Number of slots allocated for aCol[] */ int nAccumulator; /* Number of columns that show through to the output. ** Additional columns are used only as parameters to ** aggregate functions */ struct AggInfo_func { /* For each aggregate function */ Expr *pExpr; /* Expression encoding the function */ FuncDef *pFunc; /* The aggregate function implementation */ int iMem; /* Memory location that acts as accumulator */ int iDistinct; /* Ephemeral table used to enforce DISTINCT */ } *aFunc; int nFunc; /* Number of entries in aFunc[] */ int nFuncAlloc; /* Number of slots allocated for aFunc[] */ }; /* ** The datatype ynVar is a signed integer, either 16-bit or 32-bit. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater ** than 32767 we have to make it 32-bit. 16-bit is preferred because ** it uses less memory in the Expr object, which is a big memory user ** in systems with lots of prepared statements. And few applications ** need more than about 10 or 20 variables. But some extreme users want ** to have prepared statements with over 32767 variables, and for them ** the option is available (at compile-time). */ #if SQLITE_MAX_VARIABLE_NUMBER<=32767 typedef i64 ynVar; #else typedef int ynVar; #endif /* ** Each node of an expression in the parse tree is an instance ** of this structure. ** ** Expr.op is the opcode. The integer parser token codes are reused ** as opcodes here. For example, the parser defines TK_GE to be an integer ** code representing the ">=" operator. This same integer code is reused ** to represent the greater-than-or-equal-to operator in the expression ** tree. ** ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, ** or TK_STRING), then Expr.token contains the text of the SQL literal. If ** the expression is a variable (TK_VARIABLE), then Expr.token contains the ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), ** then Expr.token contains the name of the function. ** ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a ** binary operator. Either or both may be NULL. ** ** Expr.x.pList is a list of arguments if the expression is an SQL function, ** a CASE expression or an IN expression of the form " IN (, ...)". ** Expr.x.pSelect is used if the expression is a sub-select or an expression of ** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is ** valid. ** ** An expression of the form ID or ID.ID refers to a column in a table. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is ** the integer cursor number of a VDBE cursor pointing to that table and ** Expr.iColumn is the column number for the specific column. If the ** expression is used as a result in an aggregate SELECT, then the ** value is also stored in the Expr.iAgg column in the aggregate so that ** it can be accessed after all aggregates are computed. ** ** If the expression is an unbound variable marker (a question mark ** character '?' in the original SQL) then the Expr.iTable holds the index ** number for that variable. ** ** If the expression is a subquery then Expr.iColumn holds an integer ** register number containing the result of the subquery. If the ** subquery gives a constant result, then iTable is -1. If the subquery ** gives a different answer at different times during statement processing ** then iTable is the address of a subroutine that computes the subquery. ** ** If the Expr is of type OP_Column, and the table it is selecting from ** is a disk table or the "old.*" pseudo-table, then pTab points to the ** corresponding table definition. ** ** ALLOCATION NOTES: ** ** Expr objects can use a lot of memory space in database schema. To ** help reduce memory requirements, sometimes an Expr object will be ** truncated. And to reduce the number of memory allocations, sometimes ** two or more Expr objects will be stored in a single memory allocation, ** together with Expr.zToken strings. ** ** If the EP_Reduced and EP_TokenOnly flags are set when ** an Expr object is truncated. When EP_Reduced is set, then all ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees ** are contained within the same memory allocation. Note, however, that ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately ** allocated, regardless of whether or not EP_Reduced is set. */ struct Expr { u8 op; /* Operation performed by this node */ char affinity; /* The affinity of the column or 0 if not a column */ u16 flags; /* Various flags. EP_* See below */ union { char *zToken; /* Token value. Zero terminated and dequoted */ int iValue; /* Integer value if EP_IntValue */ } u; /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no ** space is allocated for the fields below this point. An attempt to ** access them will result in a segfault or malfunction. *********************************************************************/ Expr *pLeft; /* Left subnode */ Expr *pRight; /* Right subnode */ union { ExprList *pList; /* Function arguments or in " IN ( IN (