psqlodbc-09.03.0300/000777 001752 000000 00000000000 12335654034 014200 5ustar00saitowheel000000 000000 psqlodbc-09.03.0300/config/000777 001752 000000 00000000000 12335654033 015444 5ustar00saitowheel000000 000000 psqlodbc-09.03.0300/docs/000777 001752 000000 00000000000 12335654034 015130 5ustar00saitowheel000000 000000 psqlodbc-09.03.0300/installer/000777 001752 000000 00000000000 12335654034 016175 5ustar00saitowheel000000 000000 psqlodbc-09.03.0300/test/000777 001752 000000 00000000000 12335654034 015157 5ustar00saitowheel000000 000000 psqlodbc-09.03.0300/winbuild/000777 001752 000000 00000000000 12335654034 016015 5ustar00saitowheel000000 000000 psqlodbc-09.03.0300/configure.ac000644 001752 000000 00000023623 12335653444 016474 0ustar00saitowheel000000 000000 # Process this file with autoconf to produce a configure script. AC_INIT(psqlodbc, 09.03.0300, [pgsql-odbc@postgresql.org]) AC_PREREQ(2.57) AC_CONFIG_AUX_DIR(config) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([bind.c]) AM_CONFIG_HEADER([config.h]) AM_MAINTAINER_MODE # 0. Options processing AC_PROG_CC AM_CONDITIONAL([GCC], [test -n "$GCC"]) if test -n "$GCC" && test "$ac_test_CFLAGS" != set; then CFLAGS_ADD= CFLAGS_save="${CFLAGS}" AC_MSG_CHECKING(-Wall is a valid compile option) CFLAGS="${CFLAGS_save} -Wall" AC_COMPILE_IFELSE([AC_LANG_PROGRAM( [[#include ]], [])], [AC_MSG_RESULT(yes) CFLAGS_ADD="${CFLAGS_ADD} -Wall"], [AC_MSG_RESULT(no)]) CFLAGS=${CFLAGS_save} fi # # Whether unixODBC driver manager is used # AC_ARG_WITH(unixodbc, [ --with-unixodbc[[=DIR]] [[default=yes]] DIR is the unixODBC base install directory or the path to odbc_config], [], [with_unixodbc=yes]) # # Whether iODBC driver manager is used # AC_ARG_WITH(iodbc, [ --with-iodbc[[=DIR]] [[default=no]] DIR is the iODBC base install directory or the path to iodbc-config], [], [with_iodbc=no]) if test "$with_iodbc" != no; then with_unixodbc=no AC_DEFINE(WITH_IODBC, 1, [Define to 1 to build with iODBC support]) if test "$with_iodbc" = yes; then AC_PATH_PROGS(ODBC_CONFIG, iodbc-config) else ODBC_CONFIG=$with_iodbc fi if test ! -f "${ODBC_CONFIG}/bin/iodbc-config"; then if test ! -f "${ODBC_CONFIG}"; then AC_MSG_ERROR([iodbc-config not found (required for iODBC build)]) fi else ODBC_CONFIG=${ODBC_CONFIG}/bin/iodbc-config fi fi if test "$with_unixodbc" != no; then AC_DEFINE(WITH_UNIXODBC, 1, [Define to 1 to build with unixODBC support]) if test "$with_unixodbc" = yes; then AC_PATH_PROGS(ODBC_CONFIG, odbc_config) else ODBC_CONFIG=$with_unixodbc fi if test ! -f "${ODBC_CONFIG}/bin/odbc_config"; then if test ! -f "${ODBC_CONFIG}"; then AC_MSG_ERROR([odbc_config not found (required for unixODBC build)]) fi else ODBC_CONFIG=${ODBC_CONFIG}/bin/odbc_config fi fi # # ODBC include and library # if test "$ODBC_CONFIG" != ""; then if test "$with_iodbc" != no; then ODBC_INCLUDE=`${ODBC_CONFIG} --cflags` CPPFLAGS="$CPPFLAGS ${ODBC_INCLUDE}" # Linking libiodoc is rather problematic [ODBC_LIBDIR=`${ODBC_CONFIG} --libs | sed -e "s/^\(-L\|.*[ \t]-L\)\([^ \n\r\f\t]*\).*$/-L\2/"`] LDFLAGS="$LDFLAGS ${ODBC_LIBDIR}" else ODBC_INCLUDE=`${ODBC_CONFIG} --include-prefix` CPPFLAGS="$CPPFLAGS -I${ODBC_INCLUDE}" # Linking libodoc is rather problematic ODBC_LIBDIR=`${ODBC_CONFIG} --lib-prefix` LDFLAGS="$LDFLAGS -L${ODBC_LIBDIR}" fi AC_MSG_NOTICE([using $ODBC_INCLUDE $ODBC_LIBDIR]) fi # # SQLCOLATTRIBUTE_SQLLEN check # AC_COMPILE_IFELSE([AC_LANG_PROGRAM( [[#include > SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle,SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier, SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength, SQLLEN *NumercAttribute);]],[[]])], AC_DEFINE(SQLCOLATTRIBUTE_SQLLEN, 1, [Define to 1 if SQLColAttribute use SQLLEN])) # # Whether libpq functionalities are used # AC_ARG_WITH(libpq, [ --with-libpq[[=DIR]] [[default=yes]] DIR is the PostgreSQL base install directory or the path to pg_config --without-libpq specify when PostgreSQL package isn't installed], [], [with_libpq=yes]) if test "$with_libpq" != no; then AC_DEFINE(USE_LIBPQ, 1, [Define to 1 to build with libpq]) if test "$with_libpq" != yes; then if test -d "$with_libpq"; then PATH="$PATH:$with_libpq/bin" CPPFLAGS="$CPPFLAGS -I$with_libpq/include" LDFLAGS="$LDFLAGS -L$with_libpq/lib" else if test -x "$with_libpq"; then PG_CONFIG=$with_libpq else AC_MSG_ERROR([specified pg_config not found]) fi fi fi else enable_openssl=no fi # # Default odbc version number (--with-odbcver), default 0x0351 # PGAC_ARG_REQ(with, odbcver, [ --with-odbcver=VERSION change default ODBC version number [[0x0351]]], [], [with_odbcver=0x0351]) AC_DEFINE_UNQUOTED(ODBCVER, [$with_odbcver], [Define to ODBC version (--with-odbcver)]) # # Unicode support # PGAC_ARG_BOOL(enable, unicode, yes, [ --disable-unicode do not build Unicode support], [AC_DEFINE(UNICODE_SUPPORT, 1, [Define to 1 to build with Unicode support (--enable-unicode)])]) AM_CONDITIONAL(enable_unicode, [test x"$enable_unicode" = xyes]) # # SSL support # PGAC_ARG_BOOL(enable, openssl, yes, [ --disable-openssl do not build OpenSSL support], [AC_DEFINE(USE_SSL, 1, [Define to 1 to build with OpenSSL support (--enable-openssl)])]) AM_CONDITIONAL(enable_openssl, [test x"$enable_openssl" = xyes]) # # GSSAPI support # PGAC_ARG_BOOL(enable, gss, no, [ --disable-gss do not build GSSAPI support], [AC_DEFINE(USE_GSS, 1, [Define to 1 to build with GSSAPI support (--enable-gss)])]) AM_CONDITIONAL(enable_gss, [test x"$enable_gss" = xyes]) # # GKerberos 5 support # PGAC_ARG_BOOL(enable, krb5, no, [ --disable-krb5 do not build Kerberos5 support], [AC_DEFINE(USE_KRB5, 1, [Define to 1 to build with Kerberos 5 support (--enable-krb5)])]) AM_CONDITIONAL(enable_krb5, [test x"$enable_krb5" = xyes]) # # Pthreads # PGAC_ARG_BOOL(enable, pthreads, yes, [ --disable-pthreads do not build with POSIX threads], [AC_DEFINE(POSIX_MULTITHREAD_SUPPORT, 1, [Define to 1 to build with pthreads support (--enable-pthreads)]) AC_DEFINE(_REENTRANT, 1, [Define _REENTRANT for several plaforms])]) # # Find libpq headers and libraries # if test "$with_libpq" != no; then if test -z "$PG_CONFIG"; then AC_PATH_PROGS(PG_CONFIG, pg_config) fi if test -n "$PG_CONFIG"; then pg_includedir=`"$PG_CONFIG" --includedir` pg_libdir=`"$PG_CONFIG" --libdir` CPPFLAGS="$CPPFLAGS -I$pg_includedir" LDFLAGS="$LDFLAGS -L$pg_libdir" fi fi # 1. Programs # 2. Libraries AC_LIBTOOL_WIN32_DLL AC_DISABLE_STATIC AC_LIBTOOL_DLOPEN AC_PROG_LIBTOOL if test "$with_unixodbc" != no; then AC_SEARCH_LIBS(SQLGetPrivateProfileString, odbcinst, [], [AC_MSG_ERROR([unixODBC library "odbcinst" not found])]) fi if test "$with_iodbc" != no; then AC_SEARCH_LIBS(SQLGetPrivateProfileString, iodbcinst, [], [AC_MSG_ERROR([iODBC library "iodbcinst" not found])]) fi if test "$enable_pthreads" = yes; then AC_CHECK_LIB(pthreads, pthread_create, [], [AC_CHECK_LIB(pthread, pthread_create)]) fi if test "$with_libpq" != no; then AC_CHECK_LIB(pq, PQconnectdb, [], [AC_MSG_ERROR([libpq library not found])]) fi if test "$enable_openssl" = yes; then AC_CHECK_LIB(ssl, SSL_read, [], [AC_MSG_ERROR([ssl library not found])]) fi if test "$enable_gss" = yes; then AC_SEARCH_LIBS(gss_init_sec_context, [gssapi_krb5 gss 'gssapi -lkrb5 -lcrypto'], [], [AC_MSG_ERROR([gssapi library not found])]) fi if test "$enable_krb5" = yes; then AC_SEARCH_LIBS(krb5_sendauth, [krb5 'krb5 -lcrypto -ldes -lasn1 -lroken'], [], [AC_MSG_ERROR([krb5 library not found])]) AC_SEARCH_LIBS(com_err, [krb5 'krb5 -lcrypto -ldes -lasn1 -lroken' comerr 'comerr -lssl -lcrypto'], [], [AC_MSG_ERROR([comerr library not found])]) fi # 3. Header files AC_CHECK_HEADERS(locale.h sys/un.h sys/time.h) if test "$with_libpq" != no; then AC_CHECK_HEADER(libpq-fe.h,,[AC_MSG_ERROR([libpq header not found])]) fi if test "$enable_openssl" = yes; then AC_CHECK_HEADER([openssl/ssl.h],,[AC_MSG_ERROR([ssl header not found])]) fi if test "$enable_gss" = yes; then AC_CHECK_HEADERS([gssapi/gssapi.h], [], [AC_CHECK_HEADERS([gssapi.h], [], [AC_MSG_ERROR([gssapi header not found])])]) fi if test "$enable_krb5" = yes; then AC_CHECK_HEADER([krb5.h],,[AC_MSG_ERROR([krb5 header not found])]) fi AC_HEADER_TIME # 4. Types # unixODBC wants the following to get sane behavior for ODBCINT64 AC_CHECK_SIZEOF(long) AC_CHECK_SIZEOF(void *) AC_CHECK_TYPES(long long) AC_CHECK_TYPES(signed char) AC_CHECK_TYPES(ssize_t) AC_TYPE_SIZE_T # 5. Structures AC_STRUCT_TM PGAC_STRUCT_ADDRINFO # 6. Compiler characteristics AC_C_CONST # 7. Functions, global variables AC_FUNC_STRERROR_R AC_CHECK_FUNCS(strtoul strtoll strlcat strlcpy poll) if test x"$enable_unicode" = xyes; then AC_CHECK_FUNCS(iswascii) fi if test "$enable_pthreads" = yes; then AC_CHECK_FUNCS(localtime_r strtok_r pthread_mutexattr_settype) if test x"$ac_cv_func_pthread_mutexattr_settype" = xyes; then AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[int i = PTHREAD_MUTEX_RECURSIVE;]])], [AC_DEFINE(PG_RECURSIVE_MUTEXATTR, PTHREAD_MUTEX_RECURSIVE, [Define if you have PTHREAD_MUTEX_RECURSIVE])], [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[int i = PTHREAD_MUTEX_RECURSIVE_NP;]])], [AC_DEFINE(PG_RECURSIVE_MUTEXATTR, PTHREAD_MUTEX_RECURSIVE_NP, [Define if you have PTHREAD_MUTEX_RECURSIVE_NP])])]) fi fi if test "$enable_krb5" = yes; then AC_CHECK_MEMBERS(krb5_error.text.data, [], [AC_CHECK_MEMBERS(krb5_error.e_data, [], [AC_MSG_ERROR([could not determine how to extract Kerberos 5 error messages])], [#include ])], [#include ]) AC_MSG_CHECKING(for krb5_free_unparsed_name) AC_TRY_LINK([#include ], [krb5_free_unparsed_name(NULL,NULL);], [AC_DEFINE(HAVE_KRB5_FREE_UNPARSED_NAME, 1, [Define to 1 if you have krb5_free_unparsed_name]) AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) fi # 8. Libltdl This release doesn't need libltdl # AC_CHECK_LIB(ltdl, lt_dlopen) AC_CONFIG_FILES([Makefile test/Makefile]) AC_OUTPUT psqlodbc-09.03.0300/aclocal.m4000644 001752 000000 00000102137 12335653731 016043 0ustar00saitowheel000000 000000 # generated automatically by aclocal 1.10.1 -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(AC_AUTOCONF_VERSION, [2.69],, [m4_warning([this file was generated for autoconf 2.69. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically `autoreconf'.])]) # Copyright (C) 2002, 2003, 2005, 2006, 2007 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.10' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.10.1], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AC_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.10.1])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(AC_AUTOCONF_VERSION)]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to # `$srcdir', `$srcdir/..', or `$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is `.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [dnl Rely on autoconf to set up CDPATH properly. AC_PREREQ([2.50])dnl # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 8 # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ(2.52)dnl ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 9 # There are a few dirty hacks below to avoid letting `AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "GCJ", or "OBJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl ifelse([$1], CC, [depcc="$CC" am_compiler_list=], [$1], CXX, [depcc="$CXX" am_compiler_list=], [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], UPC, [depcc="$UPC" am_compiler_list=], [$1], GCJ, [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf case $depmode in nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; none) break ;; esac # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. if depmode=$depmode \ source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE(dependency-tracking, [ --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. #serial 3 # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [for mf in $CONFIG_FILES; do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each `.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 8 # AM_CONFIG_HEADER is obsolete. It has been replaced by AC_CONFIG_HEADERS. AU_DEFUN([AM_CONFIG_HEADER], [AC_CONFIG_HEADERS($@)]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, # 2005, 2006, 2008 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 13 # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.60])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) AM_MISSING_PROG(AUTOCONF, autoconf) AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) AM_MISSING_PROG(AUTOHEADER, autoheader) AM_MISSING_PROG(MAKEINFO, makeinfo) AM_PROG_INSTALL_SH AM_PROG_INSTALL_STRIP AC_REQUIRE([AM_PROG_MKDIR_P])dnl # We need awk for the "check" target. The system "awk" is bad on # some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES(CC)], [define([AC_PROG_CC], defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES(CXX)], [define([AC_PROG_CXX], defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES(OBJC)], [define([AC_PROG_OBJC], defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl ]) ]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} AC_SUBST(install_sh)]) # Copyright (C) 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Add --enable-maintainer-mode option to configure. -*- Autoconf -*- # From Jim Meyering # Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 4 AC_DEFUN([AM_MAINTAINER_MODE], [AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) dnl maintainer-mode is disabled by default AC_ARG_ENABLE(maintainer-mode, [ --enable-maintainer-mode enable make rules and dependencies not useful (and sometimes confusing) to the casual installer], USE_MAINTAINER_MODE=$enableval, USE_MAINTAINER_MODE=no) AC_MSG_RESULT([$USE_MAINTAINER_MODE]) AM_CONDITIONAL(MAINTAINER_MODE, [test $USE_MAINTAINER_MODE = yes]) MAINT=$MAINTAINER_MODE_TRUE AC_SUBST(MAINT)dnl ] ) AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE]) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 3 # AM_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo done .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # We grep out `Entering directory' and `Leaving directory' # messages which can occur if `w' ends up in MAKEFLAGS. # In particular we don't look at `^make:' because GNU make might # be invoked under some other name (usually "gmake"), in which # case it prints its new name instead of `make'. if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then am__include=include am__quote= _am_result=GNU fi # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then am__include=.include am__quote="\"" _am_result=BSD fi fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 5 # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it supports --run. # If it does, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= AC_MSG_WARN([`missing' script is too old or missing]) fi ]) # Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_MKDIR_P # --------------- # Check for `mkdir -p'. AC_DEFUN([AM_PROG_MKDIR_P], [AC_PREREQ([2.60])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P, dnl while keeping a definition of mkdir_p for backward compatibility. dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile. dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of dnl Makefile.ins that do not define MKDIR_P, so we do our own dnl adjustment using top_builddir (which is defined more often than dnl MKDIR_P). AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl case $mkdir_p in [[\\/$]]* | ?:[[\\/]]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 3 # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # ------------------------------ # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), 1)]) # _AM_SET_OPTIONS(OPTIONS) # ---------------------------------- # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005 # Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 4 # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Just in case sleep 1 echo timestamp > conftest.file # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t $srcdir/configure conftest.file` fi rm -f conftest.file if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT(yes)]) # Copyright (C) 2001, 2003, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor `install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in `make install-strip', and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be `maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004, 2005 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # serial 2 # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of `v7', `ustar', or `pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. AM_MISSING_PROG([AMTAR], [tar]) m4_if([$1], [v7], [am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'], [m4_case([$1], [ustar],, [pax],, [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' _am_tools=${am_cv_prog_tar_$1-$_am_tools} # Do not fold the above two line into one, because Tru64 sh and # Solaris sh will not grok spaces in the rhs of `-'. for _am_tool in $_am_tools do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([config/c-library.m4]) m4_include([config/general.m4]) m4_include([config/libtool.m4]) m4_include([config/ltoptions.m4]) m4_include([config/ltsugar.m4]) m4_include([config/ltversion.m4]) m4_include([config/lt~obsolete.m4]) psqlodbc-09.03.0300/Makefile.am000644 001752 000000 00000011101 12335653444 016226 0ustar00saitowheel000000 000000 #------------------------------------------------------------------------- # # Makefile.am for psqlodbc30w (PostgreSQL ODBC driver) # #------------------------------------------------------------------------- AUTOMAKE_OPTIONS = 1.8 foreign ACLOCAL_AMFLAGS = -I config if enable_unicode lib_LTLIBRARIES = psqlodbcw.la else lib_LTLIBRARIES = psqlodbca.la endif AM_LDFLAGS = -module -no-undefined -avoid-version psqlodbca_la_SOURCES = \ info.c bind.c columninfo.c connection.c convert.c drvconn.c \ environ.c execute.c lobj.c md5.c misc.c options.c \ pgtypes.c psqlodbc.c qresult.c results.c socket.c parse.c \ statement.c tuple.c dlg_specific.c loadlib.c \ multibyte.c odbcapi.c descriptor.c \ odbcapi30.c pgapi30.c info30.c mylog.c \ \ bind.h catfunc.h columninfo.h connection.h convert.h \ descriptor.h dlg_specific.h environ.h \ lobj.h md5.h misc.h multibyte.h pgapifunc.h pgtypes.h \ psqlodbc.h qresult.h resource.h socket.h statement.h tuple.h \ version.h loadlib.h pgenlist.h mylog.h psqlodbcw_la_SOURCES = $(psqlodbca_la_SOURCES) \ odbcapi30w.c odbcapiw.c win_unicode.c EXTRA_DIST = license.txt readme.txt readme_winbuild.txt \ psqlodbc.def psqlodbca.def editConfiguration.bat BuildAll.bat \ pgenlist.def pgenlista.def connexp.h \ dlg_wingui.c inouealc.c win_setup.h \ setup.c win_unicode.c win_md5.c psqlodbc.rc win64.mak \ win32.mak psqlodbc.reg psqlodbc.dsp psqlodbc.vcproj \ psqlodbc.sln msdtc_enlist.cpp pgxalib.cpp xalibname.c \ pgxalib.def odbc.sql odbc-drop.sql odbcapi25w.c \ sspisvcs.c sspisvcs.h gsssvcs.c gsssvcs.h \ buildx64.ps1 buildx86.ps1 \ \ docs/config-opt.html \ docs/config.html \ docs/README.txt \ docs/release-7.3.html \ docs/release.html \ docs/unix-compilation.html \ docs/win32-compilation.html \ \ installer/background.bmp \ installer/banner.bmp \ installer/buildX64-installer.ps1 \ installer/buildX86-installer.ps1 \ installer/lgpl.rtf \ installer/Make.bat \ installer/MakeX64.bat \ installer/modify_msi.vbs \ installer/psqlodbc-setup \ installer/psqlodbc-setup/Bundle.wxs \ installer/psqlodbc-setup/Make.bat \ installer/psqlodbc-setup/psqlodbc-setup.wixproj \ installer/psqlodbc-setup/vcredist.wxs \ installer/psqlodbc.wxs \ installer/psqlodbcm.wxs \ installer/psqlodbcm_cpu.wxs \ installer/psqlodbc_cpu.wxs \ installer/README.txt \ installer/upgrade.bat \ installer/upgrade_x64.bat \ \ winbuild/BuildAll.ps1 \ winbuild/configuration.ps1 \ winbuild/configuration_template.xml \ winbuild/editConfiguration.ps1 \ winbuild/pgenlist.vcxproj \ winbuild/pguser.Cpp.props \ winbuild/pgxalib.vcxproj \ winbuild/platformbuild.vcxproj \ winbuild/psqlodbc.Cpp.props \ winbuild/psqlodbc.vcxproj \ winbuild/readme.txt \ \ test/expected/alter.out \ test/expected/arraybinding.out \ test/expected/bindcol.out \ test/expected/boolsaschar.out \ test/expected/catalogfunctions.out \ test/expected/commands.out \ test/expected/connect.out \ test/expected/cte.out \ test/expected/cursors.out \ test/expected/cursors_1.out \ test/expected/cvtnulldate.out \ test/expected/dataatexecution.out \ test/expected/deprecated.out \ test/expected/diagnostic.out \ test/expected/error-rollback.out \ test/expected/getresult.out \ test/expected/insertreturning.out \ test/expected/lfconversion.out \ test/expected/multistmt.out \ test/expected/notice.out \ test/expected/params.out \ test/expected/positioned-update.out \ test/expected/prepare.out \ test/expected/quotes.out \ test/expected/sampletables.out \ test/expected/select.out \ test/expected/stmthandles.out \ test/launcher \ test/Makefile \ test/odbc.ini \ test/odbcinst.ini \ test/README.txt \ test/sql/sampletables.sql \ test/src/alter-test.c \ test/src/arraybinding-test.c \ test/src/bindcol-test.c \ test/src/boolsaschar-test.c \ test/src/catalogfunctions-test.c \ test/src/commands-test.c \ test/src/common.c \ test/src/common.h \ test/src/connect-test.c \ test/src/cte-test.c \ test/src/cursors-test.c \ test/src/cvtnulldate-test.c \ test/src/dataatexecution-test.c \ test/src/deprecated-test.c \ test/src/diagnostic-test.c \ test/src/error-rollback-test.c \ test/src/getresult-test.c \ test/src/insertreturning-test.c \ test/src/lfconversion-test.c \ test/src/multistmt-test.c \ test/src/notice-test.c \ test/src/params-test.c \ test/src/positioned-update-test.c \ test/src/prepare-test.c \ test/src/quotes-test.c \ test/src/select-test.c \ test/src/stmthandles-test.c MAINTAINERCLEANFILES = \ Makefile.in config/config.guess config.h.in config/config.sub configure \ config/install-sh config/missing aclocal.m4 config/ltmain.sh \ config/depcomp psqlodbc-09.03.0300/Makefile.in000644 001752 000000 00000067646 12335653736 016274 0ustar00saitowheel000000 000000 # Makefile.in generated by automake 1.10.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ #------------------------------------------------------------------------- # # Makefile.am for psqlodbc30w (PostgreSQL ODBC driver) # #------------------------------------------------------------------------- VPATH = @srcdir@ pkgdatadir = $(datadir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . DIST_COMMON = $(am__configure_deps) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(top_srcdir)/configure $(top_srcdir)/test/Makefile.in \ config/config.guess config/config.sub config/depcomp \ config/install-sh config/ltmain.sh config/missing ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/config/c-library.m4 \ $(top_srcdir)/config/general.m4 \ $(top_srcdir)/config/libtool.m4 \ $(top_srcdir)/config/ltoptions.m4 \ $(top_srcdir)/config/ltsugar.m4 \ $(top_srcdir)/config/ltversion.m4 \ $(top_srcdir)/config/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = test/Makefile am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; am__installdirs = "$(DESTDIR)$(libdir)" libLTLIBRARIES_INSTALL = $(INSTALL) LTLIBRARIES = $(lib_LTLIBRARIES) psqlodbca_la_LIBADD = am_psqlodbca_la_OBJECTS = info.lo bind.lo columninfo.lo connection.lo \ convert.lo drvconn.lo environ.lo execute.lo lobj.lo md5.lo \ misc.lo options.lo pgtypes.lo psqlodbc.lo qresult.lo \ results.lo socket.lo parse.lo statement.lo tuple.lo \ dlg_specific.lo loadlib.lo multibyte.lo odbcapi.lo \ descriptor.lo odbcapi30.lo pgapi30.lo info30.lo mylog.lo psqlodbca_la_OBJECTS = $(am_psqlodbca_la_OBJECTS) @enable_unicode_FALSE@am_psqlodbca_la_rpath = -rpath $(libdir) psqlodbcw_la_LIBADD = am__objects_1 = info.lo bind.lo columninfo.lo connection.lo convert.lo \ drvconn.lo environ.lo execute.lo lobj.lo md5.lo misc.lo \ options.lo pgtypes.lo psqlodbc.lo qresult.lo results.lo \ socket.lo parse.lo statement.lo tuple.lo dlg_specific.lo \ loadlib.lo multibyte.lo odbcapi.lo descriptor.lo odbcapi30.lo \ pgapi30.lo info30.lo mylog.lo am_psqlodbcw_la_OBJECTS = $(am__objects_1) odbcapi30w.lo odbcapiw.lo \ win_unicode.lo psqlodbcw_la_OBJECTS = $(am_psqlodbcw_la_OBJECTS) @enable_unicode_TRUE@am_psqlodbcw_la_rpath = -rpath $(libdir) DEFAULT_INCLUDES = -I.@am__isrc@ depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__depfiles_maybe = depfiles COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(psqlodbca_la_SOURCES) $(psqlodbcw_la_SOURCES) DIST_SOURCES = $(psqlodbca_la_SOURCES) $(psqlodbcw_la_SOURCES) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ { test ! -d $(distdir) \ || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -fr $(distdir); }; } DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best distuninstallcheck_listfiles = find . -type f -print distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ ODBC_CONFIG = @ODBC_CONFIG@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PG_CONFIG = @PG_CONFIG@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AUTOMAKE_OPTIONS = 1.8 foreign ACLOCAL_AMFLAGS = -I config @enable_unicode_FALSE@lib_LTLIBRARIES = psqlodbca.la @enable_unicode_TRUE@lib_LTLIBRARIES = psqlodbcw.la AM_LDFLAGS = -module -no-undefined -avoid-version psqlodbca_la_SOURCES = \ info.c bind.c columninfo.c connection.c convert.c drvconn.c \ environ.c execute.c lobj.c md5.c misc.c options.c \ pgtypes.c psqlodbc.c qresult.c results.c socket.c parse.c \ statement.c tuple.c dlg_specific.c loadlib.c \ multibyte.c odbcapi.c descriptor.c \ odbcapi30.c pgapi30.c info30.c mylog.c \ \ bind.h catfunc.h columninfo.h connection.h convert.h \ descriptor.h dlg_specific.h environ.h \ lobj.h md5.h misc.h multibyte.h pgapifunc.h pgtypes.h \ psqlodbc.h qresult.h resource.h socket.h statement.h tuple.h \ version.h loadlib.h pgenlist.h mylog.h psqlodbcw_la_SOURCES = $(psqlodbca_la_SOURCES) \ odbcapi30w.c odbcapiw.c win_unicode.c EXTRA_DIST = license.txt readme.txt readme_winbuild.txt \ psqlodbc.def psqlodbca.def editConfiguration.bat BuildAll.bat \ pgenlist.def pgenlista.def connexp.h \ dlg_wingui.c inouealc.c win_setup.h \ setup.c win_unicode.c win_md5.c psqlodbc.rc win64.mak \ win32.mak psqlodbc.reg psqlodbc.dsp psqlodbc.vcproj \ psqlodbc.sln msdtc_enlist.cpp pgxalib.cpp xalibname.c \ pgxalib.def odbc.sql odbc-drop.sql odbcapi25w.c \ sspisvcs.c sspisvcs.h gsssvcs.c gsssvcs.h \ buildx64.ps1 buildx86.ps1 \ \ docs/config-opt.html \ docs/config.html \ docs/README.txt \ docs/release-7.3.html \ docs/release.html \ docs/unix-compilation.html \ docs/win32-compilation.html \ \ installer/background.bmp \ installer/banner.bmp \ installer/buildX64-installer.ps1 \ installer/buildX86-installer.ps1 \ installer/lgpl.rtf \ installer/Make.bat \ installer/MakeX64.bat \ installer/modify_msi.vbs \ installer/psqlodbc-setup \ installer/psqlodbc-setup/Bundle.wxs \ installer/psqlodbc-setup/Make.bat \ installer/psqlodbc-setup/psqlodbc-setup.wixproj \ installer/psqlodbc-setup/vcredist.wxs \ installer/psqlodbc.wxs \ installer/psqlodbcm.wxs \ installer/psqlodbcm_cpu.wxs \ installer/psqlodbc_cpu.wxs \ installer/README.txt \ installer/upgrade.bat \ installer/upgrade_x64.bat \ \ winbuild/BuildAll.ps1 \ winbuild/configuration.ps1 \ winbuild/configuration_template.xml \ winbuild/editConfiguration.ps1 \ winbuild/pgenlist.vcxproj \ winbuild/pguser.Cpp.props \ winbuild/pgxalib.vcxproj \ winbuild/platformbuild.vcxproj \ winbuild/psqlodbc.Cpp.props \ winbuild/psqlodbc.vcxproj \ winbuild/readme.txt \ \ test/expected/alter.out \ test/expected/arraybinding.out \ test/expected/bindcol.out \ test/expected/boolsaschar.out \ test/expected/catalogfunctions.out \ test/expected/commands.out \ test/expected/connect.out \ test/expected/cte.out \ test/expected/cursors.out \ test/expected/cursors_1.out \ test/expected/cvtnulldate.out \ test/expected/dataatexecution.out \ test/expected/deprecated.out \ test/expected/diagnostic.out \ test/expected/error-rollback.out \ test/expected/getresult.out \ test/expected/insertreturning.out \ test/expected/lfconversion.out \ test/expected/multistmt.out \ test/expected/notice.out \ test/expected/params.out \ test/expected/positioned-update.out \ test/expected/prepare.out \ test/expected/quotes.out \ test/expected/sampletables.out \ test/expected/select.out \ test/expected/stmthandles.out \ test/launcher \ test/Makefile \ test/odbc.ini \ test/odbcinst.ini \ test/README.txt \ test/sql/sampletables.sql \ test/src/alter-test.c \ test/src/arraybinding-test.c \ test/src/bindcol-test.c \ test/src/boolsaschar-test.c \ test/src/catalogfunctions-test.c \ test/src/commands-test.c \ test/src/common.c \ test/src/common.h \ test/src/connect-test.c \ test/src/cte-test.c \ test/src/cursors-test.c \ test/src/cvtnulldate-test.c \ test/src/dataatexecution-test.c \ test/src/deprecated-test.c \ test/src/diagnostic-test.c \ test/src/error-rollback-test.c \ test/src/getresult-test.c \ test/src/insertreturning-test.c \ test/src/lfconversion-test.c \ test/src/multistmt-test.c \ test/src/notice-test.c \ test/src/params-test.c \ test/src/positioned-update-test.c \ test/src/prepare-test.c \ test/src/quotes-test.c \ test/src/select-test.c \ test/src/stmthandles-test.c MAINTAINERCLEANFILES = \ Makefile.in config/config.guess config.h.in config/config.sub configure \ config/install-sh config/missing aclocal.m4 config/ltmain.sh \ config/depcomp all: config.h $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj am--refresh: @: $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign '; \ cd $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ cd $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) config.h: stamp-h1 @if test ! -f $@; then \ rm -f stamp-h1; \ $(MAKE) $(AM_MAKEFLAGS) stamp-h1; \ else :; fi stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_srcdir) && $(AUTOHEADER) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 test/Makefile: $(top_builddir)/config.status $(top_srcdir)/test/Makefile.in cd $(top_builddir) && $(SHELL) ./config.status $@ install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ if test -f $$p; then \ f=$(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \ else :; fi; \ done uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ p=$(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done psqlodbca.la: $(psqlodbca_la_OBJECTS) $(psqlodbca_la_DEPENDENCIES) $(LINK) $(am_psqlodbca_la_rpath) $(psqlodbca_la_OBJECTS) $(psqlodbca_la_LIBADD) $(LIBS) psqlodbcw.la: $(psqlodbcw_la_OBJECTS) $(psqlodbcw_la_DEPENDENCIES) $(LINK) $(am_psqlodbcw_la_rpath) $(psqlodbcw_la_OBJECTS) $(psqlodbcw_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/bind.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/columninfo.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/connection.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/convert.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/descriptor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dlg_specific.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/drvconn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/environ.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/execute.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/info.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/info30.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/loadlib.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/lobj.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/md5.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/misc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/multibyte.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mylog.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/odbcapi.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/odbcapi30.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/odbcapi30w.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/odbcapiw.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/options.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pgapi30.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pgtypes.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/qresult.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/results.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/statement.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tuple.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/win_unicode.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonemtpy = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) tags=; \ here=`pwd`; \ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$tags $$unique; \ fi ctags: CTAGS CTAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) tags=; \ list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$tags$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$tags $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && cd $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) $$here distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) $(am__remove_distdir) test -d $(distdir) || mkdir $(distdir) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ fi; \ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ else \ test -f $(distdir)/$$file \ || cp -p $$d/$$file $(distdir)/$$file \ || exit 1; \ fi; \ done -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r $(distdir) dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2 $(am__remove_distdir) dist-lzma: distdir tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma $(am__remove_distdir) dist-tarZ: distdir tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__remove_distdir) dist-shar: distdir shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__remove_distdir) dist dist-all: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lzma*) \ unlzma -c $(distdir).tar.lzma | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir); chmod a+w $(distdir) mkdir $(distdir)/_build mkdir $(distdir)/_inst chmod a-w $(distdir) dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && cd $(distdir)/_build \ && ../configure --srcdir=.. --prefix="$$dc_install_base" \ $(DISTCHECK_CONFIGURE_FLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck $(am__remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @cd $(distuninstallcheck_dir) \ && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) config.h installdirs: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-am -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-hdr distclean-libtool distclean-tags dvi: dvi-am dvi-am: html: html-am info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-info: install-info-am install-man: install-pdf: install-pdf-am install-ps: install-ps-am installcheck-am: maintainer-clean: maintainer-clean-am -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: install-am install-strip .PHONY: CTAGS GTAGS all all-am am--refresh check check-am clean \ clean-generic clean-libLTLIBRARIES clean-libtool ctags dist \ dist-all dist-bzip2 dist-gzip dist-lzma dist-shar dist-tarZ \ dist-zip distcheck distclean distclean-compile \ distclean-generic distclean-hdr distclean-libtool \ distclean-tags distcleancheck distdir distuninstallcheck dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-libLTLIBRARIES \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \ uninstall-am uninstall-libLTLIBRARIES # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: psqlodbc-09.03.0300/config.h.in000644 001752 000000 00000012375 12335653734 016235 0ustar00saitowheel000000 000000 /* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the declaration of `strerror_r', and to 0 if you don't. */ #undef HAVE_DECL_STRERROR_R /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define to 1 if you have the header file. */ #undef HAVE_GSSAPI_GSSAPI_H /* Define to 1 if you have the header file. */ #undef HAVE_GSSAPI_H /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `iswascii' function. */ #undef HAVE_ISWASCII /* Define to 1 if `e_data' is a member of `krb5_error'. */ #undef HAVE_KRB5_ERROR_E_DATA /* Define to 1 if `text.data' is a member of `krb5_error'. */ #undef HAVE_KRB5_ERROR_TEXT_DATA /* Define to 1 if you have krb5_free_unparsed_name */ #undef HAVE_KRB5_FREE_UNPARSED_NAME /* Define to 1 if you have the `pq' library (-lpq). */ #undef HAVE_LIBPQ /* Define to 1 if you have the `pthread' library (-lpthread). */ #undef HAVE_LIBPTHREAD /* Define to 1 if you have the `pthreads' library (-lpthreads). */ #undef HAVE_LIBPTHREADS /* Define to 1 if you have the `ssl' library (-lssl). */ #undef HAVE_LIBSSL /* Define to 1 if you have the header file. */ #undef HAVE_LOCALE_H /* Define to 1 if you have the `localtime_r' function. */ #undef HAVE_LOCALTIME_R /* Define to 1 if the system has the type `long long'. */ #undef HAVE_LONG_LONG /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the `poll' function. */ #undef HAVE_POLL /* Define to 1 if you have the `pthread_mutexattr_settype' function. */ #undef HAVE_PTHREAD_MUTEXATTR_SETTYPE /* Define to 1 if the system has the type `signed char'. */ #undef HAVE_SIGNED_CHAR /* Define to 1 if the system has the type `ssize_t'. */ #undef HAVE_SSIZE_T /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the `strerror_r' function. */ #undef HAVE_STRERROR_R /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the `strlcat' function. */ #undef HAVE_STRLCAT /* Define to 1 if you have the `strlcpy' function. */ #undef HAVE_STRLCPY /* Define to 1 if you have the `strtok_r' function. */ #undef HAVE_STRTOK_R /* Define to 1 if you have the `strtoll' function. */ #undef HAVE_STRTOLL /* Define to 1 if you have the `strtoul' function. */ #undef HAVE_STRTOUL /* Define to 1 if the system has the type `struct addrinfo'. */ #undef HAVE_STRUCT_ADDRINFO /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_UN_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Define to ODBC version (--with-odbcver) */ #undef ODBCVER /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define if you have PTHREAD_MUTEX_RECURSIVE_NP */ #undef PG_RECURSIVE_MUTEXATTR /* Define to 1 to build with pthreads support (--enable-pthreads) */ #undef POSIX_MULTITHREAD_SUPPORT /* The size of `long', as computed by sizeof. */ #undef SIZEOF_LONG /* The size of `void *', as computed by sizeof. */ #undef SIZEOF_VOID_P /* Define to 1 if SQLColAttribute use SQLLEN */ #undef SQLCOLATTRIBUTE_SQLLEN /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define to 1 if strerror_r returns char *. */ #undef STRERROR_R_CHAR_P /* Define to 1 if you can safely include both and . */ #undef TIME_WITH_SYS_TIME /* Define to 1 if your declares `struct tm'. */ #undef TM_IN_SYS_TIME /* Define to 1 to build with Unicode support (--enable-unicode) */ #undef UNICODE_SUPPORT /* Define to 1 to build with GSSAPI support (--enable-gss) */ #undef USE_GSS /* Define to 1 to build with Kerberos 5 support (--enable-krb5) */ #undef USE_KRB5 /* Define to 1 to build with libpq */ #undef USE_LIBPQ /* Define to 1 to build with OpenSSL support (--enable-openssl) */ #undef USE_SSL /* Version number of package */ #undef VERSION /* Define to 1 to build with iODBC support */ #undef WITH_IODBC /* Define to 1 to build with unixODBC support */ #undef WITH_UNIXODBC /* Define _REENTRANT for several plaforms */ #undef _REENTRANT /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `unsigned int' if does not define. */ #undef size_t psqlodbc-09.03.0300/configure000755 001752 000000 00001610136 12335653733 016120 0ustar00saitowheel000000 000000 #! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for psqlodbc 09.03.0300. # # Report bugs to . # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org and $0: pgsql-odbc@postgresql.org about your system, including $0: any error possibly output before this message. Then $0: install a modern shell, or manually run the script $0: under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='psqlodbc' PACKAGE_TARNAME='psqlodbc' PACKAGE_VERSION='09.03.0300' PACKAGE_STRING='psqlodbc 09.03.0300' PACKAGE_BUGREPORT='pgsql-odbc@postgresql.org' PACKAGE_URL='' ac_unique_file="bind.c" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='LTLIBOBJS LIBOBJS CPP OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB ac_ct_AR AR LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP EGREP GREP SED LIBTOOL OBJDUMP DLLTOOL AS host_os host_vendor host_cpu host build_os build_vendor build_cpu build PG_CONFIG enable_krb5_FALSE enable_krb5_TRUE enable_gss_FALSE enable_gss_TRUE enable_openssl_FALSE enable_openssl_TRUE enable_unicode_FALSE enable_unicode_TRUE ODBC_CONFIG GCC_FALSE GCC_TRUE am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC MAINT MAINTAINER_MODE_FALSE MAINTAINER_MODE_TRUE am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_maintainer_mode enable_dependency_tracking with_unixodbc with_iodbc with_libpq with_odbcver enable_unicode enable_openssl enable_gss enable_krb5 enable_pthreads enable_static enable_shared with_pic enable_fast_install with_gnu_ld with_sysroot enable_libtool_lock ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures psqlodbc 09.03.0300 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/psqlodbc] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of psqlodbc 09.03.0300:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-maintainer-mode enable make rules and dependencies not useful (and sometimes confusing) to the casual installer --disable-dependency-tracking speeds up one-time build --enable-dependency-tracking do not reject slow dependency extractors --disable-unicode do not build Unicode support --disable-openssl do not build OpenSSL support --disable-gss do not build GSSAPI support --disable-krb5 do not build Kerberos5 support --disable-pthreads do not build with POSIX threads --enable-static[=PKGS] build static libraries [default=no] --enable-shared[=PKGS] build shared libraries [default=yes] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-unixodbc[=DIR] [default=yes] DIR is the unixODBC base install directory or the path to odbc_config --with-iodbc[=DIR] [default=no] DIR is the iODBC base install directory or the path to iodbc-config --with-libpq[=DIR] [default=yes] DIR is the PostgreSQL base install directory or the path to pg_config --without-libpq specify when PostgreSQL package isn't installed --with-odbcver=VERSION change default ODBC version number [0x0351] --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot=DIR Search for dependent libraries within DIR (or the compiler's sysroot if not specified). Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF psqlodbc configure 09.03.0300 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ---------------------------------------- ## ## Report this to pgsql-odbc@postgresql.org ## ## ---------------------------------------- ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_compute_int LINENO EXPR VAR INCLUDES # -------------------------------------------- # Tries to find the compile-time value of EXPR in a program that includes # INCLUDES, setting VAR accordingly. Returns whether the value could be # computed ac_fn_c_compute_int () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) >= 0)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_lo=0 ac_mid=0 while :; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) <= $ac_mid)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_hi=$ac_mid; break else as_fn_arith $ac_mid + 1 && ac_lo=$as_val if test $ac_lo -le $ac_mid; then ac_lo= ac_hi= break fi as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) < 0)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_hi=-1 ac_mid=-1 while :; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) >= $ac_mid)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_lo=$ac_mid; break else as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val if test $ac_mid -le $ac_hi; then ac_lo= ac_hi= break fi as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else ac_lo= ac_hi= fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # Binary search between lo and hi bounds. while test "x$ac_lo" != "x$ac_hi"; do as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) <= $ac_mid)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_hi=$ac_mid else as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in #(( ?*) eval "$3=\$ac_lo"; ac_retval=0 ;; '') ac_retval=1 ;; esac else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 static long int longval () { return $2; } static unsigned long int ulongval () { return $2; } #include #include int main () { FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; if (($2) < 0) { long int i = longval (); if (i != ($2)) return 1; fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); if (i != ($2)) return 1; fprintf (f, "%lu", i); } /* Do not output a trailing newline, as this causes \r\n confusion on some platforms. */ return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : echo >>conftest.val; read $3 &5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof ($2)) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { if (sizeof (($2))) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else eval "$3=yes" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_type # ac_fn_c_check_decl LINENO SYMBOL VAR INCLUDES # --------------------------------------------- # Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR # accordingly. ac_fn_c_check_decl () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack as_decl_name=`echo $2|sed 's/ *(.*//'` as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 $as_echo_n "checking whether $as_decl_name is declared... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { #ifndef $as_decl_name #ifdef __cplusplus (void) $as_decl_use; #else (void) $as_decl_name; #endif #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_decl # ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES # ---------------------------------------------------- # Tries to find if the field MEMBER exists in type AGGR, after including # INCLUDES, setting cache variable VAR accordingly. ac_fn_c_check_member () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 $as_echo_n "checking for $2.$3... " >&6; } if eval \${$4+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (sizeof ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else eval "$4=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$4 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_member cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by psqlodbc $as_me 09.03.0300, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_aux_dir= for ac_dir in config "$srcdir"/config; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in config \"$srcdir\"/config" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. am__api_version='1.10' # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Just in case sleep 1 echo timestamp > conftest.file # Do `set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t $srcdir/configure conftest.file` fi rm -f conftest.file if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing" # Use eval to expand $SHELL if eval "$MISSING --run true"; then am_missing_run="$MISSING --run " else am_missing_run= { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if ${ac_cv_path_mkdir+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi test -d ./--version && rmdir ./--version if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } mkdir_p="$MKDIR_P" case $mkdir_p in [\\/$]* | ?:[\\/]*) ;; */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; esac for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='psqlodbc' VERSION='09.03.0300' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"} # Installed binaries are usually stripped using `strip' when the user # run `make install-strip'. However `strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the `STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" # We need awk for the "check" target. The system "awk" is bad on # some platforms. # Always define AMTAR for backward compatibility. AMTAR=${AMTAR-"${am_missing_run}tar"} am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -' ac_config_headers="$ac_config_headers config.h" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable maintainer-specific portions of Makefiles" >&5 $as_echo_n "checking whether to enable maintainer-specific portions of Makefiles... " >&6; } # Check whether --enable-maintainer-mode was given. if test "${enable_maintainer_mode+set}" = set; then : enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval else USE_MAINTAINER_MODE=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $USE_MAINTAINER_MODE" >&5 $as_echo "$USE_MAINTAINER_MODE" >&6; } if test $USE_MAINTAINER_MODE = yes; then MAINTAINER_MODE_TRUE= MAINTAINER_MODE_FALSE='#' else MAINTAINER_MODE_TRUE='#' MAINTAINER_MODE_FALSE= fi MAINT=$MAINTAINER_MODE_TRUE # 0. Options processing ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo done .PHONY: am__doit END # If we don't find an include directive, just comment out the code. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 $as_echo_n "checking for style of include used by $am_make... " >&6; } am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # We grep out `Entering directory' and `Leaving directory' # messages which can occur if `w' ends up in MAKEFLAGS. # In particular we don't look at `^make:' because GNU make might # be invoked under some other name (usually "gmake"), in which # case it prints its new name instead of `make'. if test "`$am_make -s -f confmf 2> /dev/null | grep -v 'ing directory'`" = "done"; then am__include=include am__quote= _am_result=GNU fi # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf if test "`$am_make -s -f confmf 2> /dev/null`" = "done"; then am__include=.include am__quote="\"" _am_result=BSD fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 $as_echo "$_am_result" >&6; } rm -f confinc confmf # Check whether --enable-dependency-tracking was given. if test "${enable_dependency_tracking+set}" = set; then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named `D' -- because `-MD' means `put the output # in D'. mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with # Solaris 8's {/usr,}/bin/sh. touch sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf case $depmode in nosideeffect) # after this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; none) break ;; esac # We check with `-c' and `-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle `-M -o', and we need to detect this. if depmode=$depmode \ source=sub/conftest.c object=sub/conftest.${OBJEXT-o} \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi if test -n "$GCC"; then GCC_TRUE= GCC_FALSE='#' else GCC_TRUE='#' GCC_FALSE= fi if test -n "$GCC" && test "$ac_test_CFLAGS" != set; then CFLAGS_ADD= CFLAGS_save="${CFLAGS}" { $as_echo "$as_me:${as_lineno-$LINENO}: checking -Wall is a valid compile option" >&5 $as_echo_n "checking -Wall is a valid compile option... " >&6; } CFLAGS="${CFLAGS_save} -Wall" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } CFLAGS_ADD="${CFLAGS_ADD} -Wall" else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CFLAGS=${CFLAGS_save} fi # # Whether unixODBC driver manager is used # # Check whether --with-unixodbc was given. if test "${with_unixodbc+set}" = set; then : withval=$with_unixodbc; else with_unixodbc=yes fi # # Whether iODBC driver manager is used # # Check whether --with-iodbc was given. if test "${with_iodbc+set}" = set; then : withval=$with_iodbc; else with_iodbc=no fi if test "$with_iodbc" != no; then with_unixodbc=no $as_echo "#define WITH_IODBC 1" >>confdefs.h if test "$with_iodbc" = yes; then for ac_prog in iodbc-config do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ODBC_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ODBC_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ODBC_CONFIG="$ODBC_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ODBC_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ODBC_CONFIG=$ac_cv_path_ODBC_CONFIG if test -n "$ODBC_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ODBC_CONFIG" >&5 $as_echo "$ODBC_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ODBC_CONFIG" && break done else ODBC_CONFIG=$with_iodbc fi if test ! -f "${ODBC_CONFIG}/bin/iodbc-config"; then if test ! -f "${ODBC_CONFIG}"; then as_fn_error $? "iodbc-config not found (required for iODBC build)" "$LINENO" 5 fi else ODBC_CONFIG=${ODBC_CONFIG}/bin/iodbc-config fi fi if test "$with_unixodbc" != no; then $as_echo "#define WITH_UNIXODBC 1" >>confdefs.h if test "$with_unixodbc" = yes; then for ac_prog in odbc_config do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ODBC_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ODBC_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ODBC_CONFIG="$ODBC_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ODBC_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ODBC_CONFIG=$ac_cv_path_ODBC_CONFIG if test -n "$ODBC_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ODBC_CONFIG" >&5 $as_echo "$ODBC_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ODBC_CONFIG" && break done else ODBC_CONFIG=$with_unixodbc fi if test ! -f "${ODBC_CONFIG}/bin/odbc_config"; then if test ! -f "${ODBC_CONFIG}"; then as_fn_error $? "odbc_config not found (required for unixODBC build)" "$LINENO" 5 fi else ODBC_CONFIG=${ODBC_CONFIG}/bin/odbc_config fi fi # # ODBC include and library # if test "$ODBC_CONFIG" != ""; then if test "$with_iodbc" != no; then ODBC_INCLUDE=`${ODBC_CONFIG} --cflags` CPPFLAGS="$CPPFLAGS ${ODBC_INCLUDE}" # Linking libiodoc is rather problematic ODBC_LIBDIR=`${ODBC_CONFIG} --libs | sed -e "s/^\(-L\|.*[ \t]-L\)\([^ \n\r\f\t]*\).*$/-L\2/"` LDFLAGS="$LDFLAGS ${ODBC_LIBDIR}" else ODBC_INCLUDE=`${ODBC_CONFIG} --include-prefix` CPPFLAGS="$CPPFLAGS -I${ODBC_INCLUDE}" # Linking libodoc is rather problematic ODBC_LIBDIR=`${ODBC_CONFIG} --lib-prefix` LDFLAGS="$LDFLAGS -L${ODBC_LIBDIR}" fi { $as_echo "$as_me:${as_lineno-$LINENO}: using $ODBC_INCLUDE $ODBC_LIBDIR" >&5 $as_echo "$as_me: using $ODBC_INCLUDE $ODBC_LIBDIR" >&6;} fi # # SQLCOLATTRIBUTE_SQLLEN check # cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include > SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle,SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier, SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength, SQLLEN *NumercAttribute); int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : $as_echo "#define SQLCOLATTRIBUTE_SQLLEN 1" >>confdefs.h fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # # Whether libpq functionalities are used # # Check whether --with-libpq was given. if test "${with_libpq+set}" = set; then : withval=$with_libpq; else with_libpq=yes fi if test "$with_libpq" != no; then $as_echo "#define USE_LIBPQ 1" >>confdefs.h if test "$with_libpq" != yes; then if test -d "$with_libpq"; then PATH="$PATH:$with_libpq/bin" CPPFLAGS="$CPPFLAGS -I$with_libpq/include" LDFLAGS="$LDFLAGS -L$with_libpq/lib" else if test -x "$with_libpq"; then PG_CONFIG=$with_libpq else as_fn_error $? "specified pg_config not found" "$LINENO" 5 fi fi fi else enable_openssl=no fi # # Default odbc version number (--with-odbcver), default 0x0351 # pgac_args="$pgac_args with_odbcver" # Check whether --with-odbcver was given. if test "${with_odbcver+set}" = set; then : withval=$with_odbcver; case $withval in yes) as_fn_error $? "argument required for --with-odbcver option" "$LINENO" 5 ;; no) as_fn_error $? "argument required for --with-odbcver option" "$LINENO" 5 ;; *) ;; esac else with_odbcver=0x0351 fi cat >>confdefs.h <<_ACEOF #define ODBCVER $with_odbcver _ACEOF # # Unicode support # pgac_args="$pgac_args enable_unicode" # Check whether --enable-unicode was given. if test "${enable_unicode+set}" = set; then : enableval=$enable_unicode; case $enableval in yes) $as_echo "#define UNICODE_SUPPORT 1" >>confdefs.h ;; no) : ;; *) as_fn_error $? "no argument expected for --enable-unicode option" "$LINENO" 5 ;; esac else enable_unicode=yes $as_echo "#define UNICODE_SUPPORT 1" >>confdefs.h fi if test x"$enable_unicode" = xyes; then enable_unicode_TRUE= enable_unicode_FALSE='#' else enable_unicode_TRUE='#' enable_unicode_FALSE= fi # # SSL support # pgac_args="$pgac_args enable_openssl" # Check whether --enable-openssl was given. if test "${enable_openssl+set}" = set; then : enableval=$enable_openssl; case $enableval in yes) $as_echo "#define USE_SSL 1" >>confdefs.h ;; no) : ;; *) as_fn_error $? "no argument expected for --enable-openssl option" "$LINENO" 5 ;; esac else enable_openssl=yes $as_echo "#define USE_SSL 1" >>confdefs.h fi if test x"$enable_openssl" = xyes; then enable_openssl_TRUE= enable_openssl_FALSE='#' else enable_openssl_TRUE='#' enable_openssl_FALSE= fi # # GSSAPI support # pgac_args="$pgac_args enable_gss" # Check whether --enable-gss was given. if test "${enable_gss+set}" = set; then : enableval=$enable_gss; case $enableval in yes) $as_echo "#define USE_GSS 1" >>confdefs.h ;; no) : ;; *) as_fn_error $? "no argument expected for --enable-gss option" "$LINENO" 5 ;; esac else enable_gss=no fi if test x"$enable_gss" = xyes; then enable_gss_TRUE= enable_gss_FALSE='#' else enable_gss_TRUE='#' enable_gss_FALSE= fi # # GKerberos 5 support # pgac_args="$pgac_args enable_krb5" # Check whether --enable-krb5 was given. if test "${enable_krb5+set}" = set; then : enableval=$enable_krb5; case $enableval in yes) $as_echo "#define USE_KRB5 1" >>confdefs.h ;; no) : ;; *) as_fn_error $? "no argument expected for --enable-krb5 option" "$LINENO" 5 ;; esac else enable_krb5=no fi if test x"$enable_krb5" = xyes; then enable_krb5_TRUE= enable_krb5_FALSE='#' else enable_krb5_TRUE='#' enable_krb5_FALSE= fi # # Pthreads # pgac_args="$pgac_args enable_pthreads" # Check whether --enable-pthreads was given. if test "${enable_pthreads+set}" = set; then : enableval=$enable_pthreads; case $enableval in yes) $as_echo "#define POSIX_MULTITHREAD_SUPPORT 1" >>confdefs.h $as_echo "#define _REENTRANT 1" >>confdefs.h ;; no) : ;; *) as_fn_error $? "no argument expected for --enable-pthreads option" "$LINENO" 5 ;; esac else enable_pthreads=yes $as_echo "#define POSIX_MULTITHREAD_SUPPORT 1" >>confdefs.h $as_echo "#define _REENTRANT 1" >>confdefs.h fi # # Find libpq headers and libraries # if test "$with_libpq" != no; then if test -z "$PG_CONFIG"; then for ac_prog in pg_config do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_PG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $PG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_PG_CONFIG="$PG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_PG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi PG_CONFIG=$ac_cv_path_PG_CONFIG if test -n "$PG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PG_CONFIG" >&5 $as_echo "$PG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$PG_CONFIG" && break done fi if test -n "$PG_CONFIG"; then pg_includedir=`"$PG_CONFIG" --includedir` pg_libdir=`"$PG_CONFIG" --libdir` CPPFLAGS="$CPPFLAGS -I$pg_includedir" LDFLAGS="$LDFLAGS -L$pg_libdir" fi fi # 1. Programs # 2. Libraries # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}as", so it can be a program name with args. set dummy ${ac_tool_prefix}as; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AS+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AS"; then ac_cv_prog_AS="$AS" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AS="${ac_tool_prefix}as" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AS=$ac_cv_prog_AS if test -n "$AS"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AS" >&5 $as_echo "$AS" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_AS"; then ac_ct_AS=$AS # Extract the first word of "as", so it can be a program name with args. set dummy as; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AS+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AS"; then ac_cv_prog_ac_ct_AS="$ac_ct_AS" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AS="as" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AS=$ac_cv_prog_ac_ct_AS if test -n "$ac_ct_AS"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AS" >&5 $as_echo "$ac_ct_AS" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_AS" = x; then AS="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AS=$ac_ct_AS fi else AS="$ac_cv_prog_AS" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi ;; esac test -z "$AS" && AS=as test -z "$DLLTOOL" && DLLTOOL=dlltool test -z "$OBJDUMP" && OBJDUMP=objdump # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac else enable_static=no fi enable_dlopen=yes case `pwd` in *\ * | *\ *) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 $as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.2' macro_revision='1.3337' ltmain="$ac_aux_dir/ltmain.sh" # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case "$ECHO" in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in fgrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 $as_echo "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if ${lt_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 $as_echo "$lt_cv_path_NM" >&6; } if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 $as_echo "$DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 $as_echo "$ac_ct_DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 $as_echo_n "checking the name lister ($NM) interface... " >&6; } if ${lt_cv_nm_interface+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 $as_echo "$lt_cv_nm_interface" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 $as_echo_n "checking the maximum length of command line arguments... " >&6; } if ${lt_cv_sys_max_cmd_len+:} false; then : $as_echo_n "(cached) " >&6 else i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac fi if test -n $lt_cv_sys_max_cmd_len ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 $as_echo "$lt_cv_sys_max_cmd_len" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 $as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 $as_echo "$xsi_shell" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 $as_echo_n "checking whether the shell understands \"+=\"... " >&6; } lt_shell_append=no ( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 $as_echo "$lt_shell_append" >&6; } if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 $as_echo_n "checking how to convert $build file names to $host format... " >&6; } if ${lt_cv_to_host_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 $as_echo "$lt_cv_to_host_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 $as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } if ${lt_cv_to_tool_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 $as_echo "$lt_cv_to_tool_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 $as_echo_n "checking for $LD option to reload object files... " >&6; } if ${lt_cv_ld_reload_flag+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_reload_flag='-r' fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 $as_echo "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test "$GCC" != yes; then reload_cmds=false fi ;; darwin*) if test "$GCC" = yes; then reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 $as_echo_n "checking how to recognize dependent libraries... " >&6; } if ${lt_cv_deplibs_check_method+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # `unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # which responds to the $file_magic_cmd with a given extended regex. # If you have `file' or equivalent on your system and you're not sure # whether `pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin. if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; gnu*) lt_cv_deplibs_check_method=pass_all ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) lt_cv_deplibs_check_method=pass_all ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 $as_echo "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 $as_echo_n "checking how to associate runtime and link libraries... " >&6; } if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 $as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} : ${AR_FLAGS=cru} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 $as_echo_n "checking for archiver @FILE support... " >&6; } if ${lt_cv_ar_at_file+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 $as_echo "$lt_cv_ar_at_file" >&6; } if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } if ${lt_cv_sys_global_symbol_pipe+:} false; then : $as_echo_n "(cached) " >&6 else # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 $as_echo "failed" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 $as_echo_n "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test "${with_sysroot+set}" = set; then : withval=$with_sysroot; else with_sysroot=no fi lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5 $as_echo "${with_sysroot}" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 $as_echo "${lt_sysroot:-no}" >&6; } # Check whether --enable-libtool-lock was given. if test "${enable_libtool_lock+set}" = set; then : enableval=$enable_libtool_lock; fi test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_i386" ;; ppc64-*linux*|powerpc64-*linux*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; ppc*-*linux*|powerpc*-*linux*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 $as_echo_n "checking whether the C compiler needs -belf... " >&6; } if ${lt_cv_cc_needs_belf+:} false; then : $as_echo_n "(cached) " >&6 else ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_cc_needs_belf=yes else lt_cv_cc_needs_belf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 $as_echo "$lt_cv_cc_needs_belf" >&6; } if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 $as_echo "$MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 $as_echo "$ac_ct_MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 $as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if ${lt_cv_path_mainfest_tool+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 $as_echo "$lt_cv_path_mainfest_tool" >&6; } if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 $as_echo "$DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 $as_echo "$ac_ct_DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 $as_echo "$NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 $as_echo "$ac_ct_NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 $as_echo "$LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 $as_echo "$ac_ct_LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 $as_echo "$OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 $as_echo "$ac_ct_OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 $as_echo "$OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 $as_echo "$ac_ct_OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 $as_echo_n "checking for -single_module linker flag... " >&6; } if ${lt_cv_apple_cc_single_mod+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 $as_echo "$lt_cv_apple_cc_single_mod" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } if ${lt_cv_ld_exported_symbols_list+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_ld_exported_symbols_list=yes else lt_cv_ld_exported_symbols_list=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 $as_echo "$lt_cv_ld_exported_symbols_list" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 $as_echo_n "checking for -force_load linker flag... " >&6; } if ${lt_cv_ld_force_load+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR cru libconftest.a conftest.o" >&5 $AR cru libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 $as_echo "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[91]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[012]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_header in dlfcn.h do : ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DLFCN_H 1 _ACEOF fi done # Set options # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac else enable_shared=yes fi # Check whether --with-pic was given. if test "${with_pic+set}" = set; then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac else pic_mode=default fi test -z "$pic_mode" && pic_mode=default # Check whether --enable-fast-install was given. if test "${enable_fast_install+set}" = set; then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac else enable_fast_install=yes fi # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 $as_echo_n "checking for objdir... " >&6; } if ${lt_cv_objdir+:} false; then : $as_echo_n "(cached) " >&6 else rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 $as_echo "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir cat >>confdefs.h <<_ACEOF #define LT_OBJDIR "$lt_cv_objdir/" _ACEOF case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/${ac_tool_prefix}file; then lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 $as_echo_n "checking for file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/file; then lt_cv_path_MAGIC_CMD="$ac_dir/file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC="$CC" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test "$GCC" = yes; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test "$GCC" = yes; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic=$lt_prog_compiler_pic fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 $as_echo "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if ${lt_cv_prog_compiler_pic_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; } if test x"$lt_cv_prog_compiler_pic_works" = xyes; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 $as_echo "$lt_cv_prog_compiler_static_works" >&6; } if test x"$lt_cv_prog_compiler_static_works" = xyes; then : else lt_prog_compiler_static= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='${wl}--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs=yes ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test "$ld_shlibs" = no; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' ${wl}-bernotok' allow_undefined_flag=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test "$GCC" = yes; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 $as_echo_n "checking if $CC understands -b... " >&6; } if ${lt_cv_prog_compiler__b+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler__b=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 $as_echo "$lt_cv_prog_compiler__b" >&6; } if test x"$lt_cv_prog_compiler__b" = xyes; then archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if ${lt_cv_irix_exported_symbol+:} false; then : $as_echo_n "(cached) " >&6 else save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_irix_exported_symbol=yes else lt_cv_irix_exported_symbol=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 $as_echo "$lt_cv_irix_exported_symbol" >&6; } if test "$lt_cv_irix_exported_symbol" = yes; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' else case $host_os in openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-R$libdir' ;; *) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' ;; esac fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='${wl}-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='${wl}-z,text' allow_undefined_flag='${wl}-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='${wl}-Blargedynsym' ;; esac fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 $as_echo "$ld_shlibs" >&6; } test "$ld_shlibs" = no && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 $as_echo "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([A-Za-z]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test "X$hardcode_automatic" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && test "$hardcode_minus_L" != no; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 $as_echo "$hardcode_action" >&6; } if test "$hardcode_action" = relink || test "$inherit_rpath" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes fi ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes; then : lt_cv_dlopen="shl_load" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 $as_echo_n "checking for shl_load in -ldld... " >&6; } if ${ac_cv_lib_dld_shl_load+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char shl_load (); int main () { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_shl_load=yes else ac_cv_lib_dld_shl_load=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 $as_echo "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes; then : lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" else ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : lt_cv_dlopen="dlopen" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 $as_echo_n "checking for dlopen in -lsvld... " >&6; } if ${ac_cv_lib_svld_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_svld_dlopen=yes else ac_cv_lib_svld_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 $as_echo "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 $as_echo_n "checking for dld_link in -ldld... " >&6; } if ${ac_cv_lib_dld_dld_link+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dld_link (); int main () { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_dld_link=yes else ac_cv_lib_dld_dld_link=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 $as_echo "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes; then : lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" fi fi fi fi fi fi ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 $as_echo_n "checking whether a program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 $as_echo "$lt_cv_dlopen_self" >&6; } if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self_static+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 $as_echo "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 $as_echo_n "checking whether stripping libraries is possible... " >&6; } if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; esac fi # Report which library types will actually be built { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 $as_echo_n "checking if libtool supports shared libraries... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 $as_echo "$can_build_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 $as_echo_n "checking whether to build shared libraries... " >&6; } test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 $as_echo_n "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 $as_echo "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC="$lt_save_CC" ac_config_commands="$ac_config_commands libtool" # Only expand once: if test "$with_unixodbc" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing SQLGetPrivateProfileString" >&5 $as_echo_n "checking for library containing SQLGetPrivateProfileString... " >&6; } if ${ac_cv_search_SQLGetPrivateProfileString+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char SQLGetPrivateProfileString (); int main () { return SQLGetPrivateProfileString (); ; return 0; } _ACEOF for ac_lib in '' odbcinst; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_SQLGetPrivateProfileString=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_SQLGetPrivateProfileString+:} false; then : break fi done if ${ac_cv_search_SQLGetPrivateProfileString+:} false; then : else ac_cv_search_SQLGetPrivateProfileString=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_SQLGetPrivateProfileString" >&5 $as_echo "$ac_cv_search_SQLGetPrivateProfileString" >&6; } ac_res=$ac_cv_search_SQLGetPrivateProfileString if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else as_fn_error $? "unixODBC library \"odbcinst\" not found" "$LINENO" 5 fi fi if test "$with_iodbc" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing SQLGetPrivateProfileString" >&5 $as_echo_n "checking for library containing SQLGetPrivateProfileString... " >&6; } if ${ac_cv_search_SQLGetPrivateProfileString+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char SQLGetPrivateProfileString (); int main () { return SQLGetPrivateProfileString (); ; return 0; } _ACEOF for ac_lib in '' iodbcinst; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_SQLGetPrivateProfileString=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_SQLGetPrivateProfileString+:} false; then : break fi done if ${ac_cv_search_SQLGetPrivateProfileString+:} false; then : else ac_cv_search_SQLGetPrivateProfileString=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_SQLGetPrivateProfileString" >&5 $as_echo "$ac_cv_search_SQLGetPrivateProfileString" >&6; } ac_res=$ac_cv_search_SQLGetPrivateProfileString if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else as_fn_error $? "iODBC library \"iodbcinst\" not found" "$LINENO" 5 fi fi if test "$enable_pthreads" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreads" >&5 $as_echo_n "checking for pthread_create in -lpthreads... " >&6; } if ${ac_cv_lib_pthreads_pthread_create+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpthreads $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char pthread_create (); int main () { return pthread_create (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pthreads_pthread_create=yes else ac_cv_lib_pthreads_pthread_create=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_create" >&5 $as_echo "$ac_cv_lib_pthreads_pthread_create" >&6; } if test "x$ac_cv_lib_pthreads_pthread_create" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPTHREADS 1 _ACEOF LIBS="-lpthreads $LIBS" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5 $as_echo_n "checking for pthread_create in -lpthread... " >&6; } if ${ac_cv_lib_pthread_pthread_create+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpthread $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char pthread_create (); int main () { return pthread_create (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pthread_pthread_create=yes else ac_cv_lib_pthread_pthread_create=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5 $as_echo "$ac_cv_lib_pthread_pthread_create" >&6; } if test "x$ac_cv_lib_pthread_pthread_create" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPTHREAD 1 _ACEOF LIBS="-lpthread $LIBS" fi fi fi if test "$with_libpq" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQconnectdb in -lpq" >&5 $as_echo_n "checking for PQconnectdb in -lpq... " >&6; } if ${ac_cv_lib_pq_PQconnectdb+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpq $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char PQconnectdb (); int main () { return PQconnectdb (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pq_PQconnectdb=yes else ac_cv_lib_pq_PQconnectdb=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQconnectdb" >&5 $as_echo "$ac_cv_lib_pq_PQconnectdb" >&6; } if test "x$ac_cv_lib_pq_PQconnectdb" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPQ 1 _ACEOF LIBS="-lpq $LIBS" else as_fn_error $? "libpq library not found" "$LINENO" 5 fi fi if test "$enable_openssl" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SSL_read in -lssl" >&5 $as_echo_n "checking for SSL_read in -lssl... " >&6; } if ${ac_cv_lib_ssl_SSL_read+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lssl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char SSL_read (); int main () { return SSL_read (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_ssl_SSL_read=yes else ac_cv_lib_ssl_SSL_read=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssl_SSL_read" >&5 $as_echo "$ac_cv_lib_ssl_SSL_read" >&6; } if test "x$ac_cv_lib_ssl_SSL_read" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBSSL 1 _ACEOF LIBS="-lssl $LIBS" else as_fn_error $? "ssl library not found" "$LINENO" 5 fi fi if test "$enable_gss" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gss_init_sec_context" >&5 $as_echo_n "checking for library containing gss_init_sec_context... " >&6; } if ${ac_cv_search_gss_init_sec_context+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char gss_init_sec_context (); int main () { return gss_init_sec_context (); ; return 0; } _ACEOF for ac_lib in '' gssapi_krb5 gss 'gssapi -lkrb5 -lcrypto'; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_gss_init_sec_context=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_gss_init_sec_context+:} false; then : break fi done if ${ac_cv_search_gss_init_sec_context+:} false; then : else ac_cv_search_gss_init_sec_context=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gss_init_sec_context" >&5 $as_echo "$ac_cv_search_gss_init_sec_context" >&6; } ac_res=$ac_cv_search_gss_init_sec_context if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else as_fn_error $? "gssapi library not found" "$LINENO" 5 fi fi if test "$enable_krb5" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing krb5_sendauth" >&5 $as_echo_n "checking for library containing krb5_sendauth... " >&6; } if ${ac_cv_search_krb5_sendauth+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char krb5_sendauth (); int main () { return krb5_sendauth (); ; return 0; } _ACEOF for ac_lib in '' krb5 'krb5 -lcrypto -ldes -lasn1 -lroken'; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_krb5_sendauth=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_krb5_sendauth+:} false; then : break fi done if ${ac_cv_search_krb5_sendauth+:} false; then : else ac_cv_search_krb5_sendauth=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_krb5_sendauth" >&5 $as_echo "$ac_cv_search_krb5_sendauth" >&6; } ac_res=$ac_cv_search_krb5_sendauth if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else as_fn_error $? "krb5 library not found" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing com_err" >&5 $as_echo_n "checking for library containing com_err... " >&6; } if ${ac_cv_search_com_err+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char com_err (); int main () { return com_err (); ; return 0; } _ACEOF for ac_lib in '' krb5 'krb5 -lcrypto -ldes -lasn1 -lroken' comerr 'comerr -lssl -lcrypto'; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_com_err=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_com_err+:} false; then : break fi done if ${ac_cv_search_com_err+:} false; then : else ac_cv_search_com_err=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_com_err" >&5 $as_echo "$ac_cv_search_com_err" >&6; } ac_res=$ac_cv_search_com_err if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else as_fn_error $? "comerr library not found" "$LINENO" 5 fi fi # 3. Header files for ac_header in locale.h sys/un.h sys/time.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done if test "$with_libpq" != no; then ac_fn_c_check_header_mongrel "$LINENO" "libpq-fe.h" "ac_cv_header_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header_libpq_fe_h" = xyes; then : else as_fn_error $? "libpq header not found" "$LINENO" 5 fi fi if test "$enable_openssl" = yes; then ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" if test "x$ac_cv_header_openssl_ssl_h" = xyes; then : else as_fn_error $? "ssl header not found" "$LINENO" 5 fi fi if test "$enable_gss" = yes; then for ac_header in gssapi/gssapi.h do : ac_fn_c_check_header_mongrel "$LINENO" "gssapi/gssapi.h" "ac_cv_header_gssapi_gssapi_h" "$ac_includes_default" if test "x$ac_cv_header_gssapi_gssapi_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_GSSAPI_GSSAPI_H 1 _ACEOF else for ac_header in gssapi.h do : ac_fn_c_check_header_mongrel "$LINENO" "gssapi.h" "ac_cv_header_gssapi_h" "$ac_includes_default" if test "x$ac_cv_header_gssapi_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_GSSAPI_H 1 _ACEOF else as_fn_error $? "gssapi header not found" "$LINENO" 5 fi done fi done fi if test "$enable_krb5" = yes; then ac_fn_c_check_header_mongrel "$LINENO" "krb5.h" "ac_cv_header_krb5_h" "$ac_includes_default" if test "x$ac_cv_header_krb5_h" = xyes; then : else as_fn_error $? "krb5 header not found" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 $as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } if ${ac_cv_header_time+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main () { if ((struct tm *) 0) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_time=yes else ac_cv_header_time=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 $as_echo "$ac_cv_header_time" >&6; } if test $ac_cv_header_time = yes; then $as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h fi # 4. Types # unixODBC wants the following to get sane behavior for ODBCINT64 # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5 $as_echo_n "checking size of long... " >&6; } if ${ac_cv_sizeof_long+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then : else if test "$ac_cv_type_long" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (long) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_long=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long" >&5 $as_echo "$ac_cv_sizeof_long" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_LONG $ac_cv_sizeof_long _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5 $as_echo_n "checking size of void *... " >&6; } if ${ac_cv_sizeof_void_p+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then : else if test "$ac_cv_type_void_p" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (void *) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_void_p=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_void_p" >&5 $as_echo "$ac_cv_sizeof_void_p" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_VOID_P $ac_cv_sizeof_void_p _ACEOF ac_fn_c_check_type "$LINENO" "long long" "ac_cv_type_long_long" "$ac_includes_default" if test "x$ac_cv_type_long_long" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LONG_LONG 1 _ACEOF fi ac_fn_c_check_type "$LINENO" "signed char" "ac_cv_type_signed_char" "$ac_includes_default" if test "x$ac_cv_type_signed_char" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_SIGNED_CHAR 1 _ACEOF fi ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" if test "x$ac_cv_type_ssize_t" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_SSIZE_T 1 _ACEOF fi ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" if test "x$ac_cv_type_size_t" = xyes; then : else cat >>confdefs.h <<_ACEOF #define size_t unsigned int _ACEOF fi # 5. Structures { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in sys/time.h or time.h" >&5 $as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6; } if ${ac_cv_struct_tm+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { struct tm tm; int *p = &tm.tm_sec; return !p; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_struct_tm=time.h else ac_cv_struct_tm=sys/time.h fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5 $as_echo "$ac_cv_struct_tm" >&6; } if test $ac_cv_struct_tm = sys/time.h; then $as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h fi ac_fn_c_check_type "$LINENO" "struct addrinfo" "ac_cv_type_struct_addrinfo" "#include #include #include " if test "x$ac_cv_type_struct_addrinfo" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_ADDRINFO 1 _ACEOF fi # 6. Compiler characteristics { $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 $as_echo_n "checking for an ANSI C-conforming const... " >&6; } if ${ac_cv_c_const+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __cplusplus /* Ultrix mips cc rejects this sort of thing. */ typedef int charset[2]; const charset cs = { 0, 0 }; /* SunOS 4.1.1 cc rejects this. */ char const *const *pcpcc; char **ppc; /* NEC SVR4.0.2 mips cc rejects this. */ struct point {int x, y;}; static struct point const zero = {0,0}; /* AIX XL C 1.02.0.0 rejects this. It does not let you subtract one const X* pointer from another in an arm of an if-expression whose if-part is not a constant expression */ const char *g = "string"; pcpcc = &g + (g ? g-g : 0); /* HPUX 7.0 cc rejects these. */ ++pcpcc; ppc = (char**) pcpcc; pcpcc = (char const *const *) ppc; { /* SCO 3.2v4 cc rejects this sort of thing. */ char tx; char *t = &tx; char const *s = 0 ? (char *) 0 : (char const *) 0; *t++ = 0; if (s) return 0; } { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ int x[] = {25, 17}; const int *foo = &x[0]; ++foo; } { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ typedef const int *iptr; iptr p = 0; ++p; } { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ struct s { int j; const int *ap[3]; } bx; struct s *b = &bx; b->j = 5; } { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ const int foo = 10; if (!foo) return 0; } return !cs[0] && !zero.x; #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_const=yes else ac_cv_c_const=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 $as_echo "$ac_cv_c_const" >&6; } if test $ac_cv_c_const = no; then $as_echo "#define const /**/" >>confdefs.h fi # 7. Functions, global variables ac_fn_c_check_decl "$LINENO" "strerror_r" "ac_cv_have_decl_strerror_r" "$ac_includes_default" if test "x$ac_cv_have_decl_strerror_r" = xyes; then : ac_have_decl=1 else ac_have_decl=0 fi cat >>confdefs.h <<_ACEOF #define HAVE_DECL_STRERROR_R $ac_have_decl _ACEOF for ac_func in strerror_r do : ac_fn_c_check_func "$LINENO" "strerror_r" "ac_cv_func_strerror_r" if test "x$ac_cv_func_strerror_r" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STRERROR_R 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether strerror_r returns char *" >&5 $as_echo_n "checking whether strerror_r returns char *... " >&6; } if ${ac_cv_func_strerror_r_char_p+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_func_strerror_r_char_p=no if test $ac_cv_have_decl_strerror_r = yes; then cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { char buf[100]; char x = *strerror_r (0, buf, sizeof buf); char *p = strerror_r (0, buf, sizeof buf); return !p || x; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_func_strerror_r_char_p=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else # strerror_r is not declared. Choose between # systems that have relatively inaccessible declarations for the # function. BeOS and DEC UNIX 4.0 fall in this category, but the # former has a strerror_r that returns char*, while the latter # has a strerror_r that returns `int'. # This test should segfault on the DEC system. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default extern char *strerror_r (); int main () { char buf[100]; char x = *strerror_r (0, buf, sizeof buf); return ! isalpha (x); ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_func_strerror_r_char_p=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strerror_r_char_p" >&5 $as_echo "$ac_cv_func_strerror_r_char_p" >&6; } if test $ac_cv_func_strerror_r_char_p = yes; then $as_echo "#define STRERROR_R_CHAR_P 1" >>confdefs.h fi for ac_func in strtoul strtoll strlcat strlcpy poll do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done if test x"$enable_unicode" = xyes; then for ac_func in iswascii do : ac_fn_c_check_func "$LINENO" "iswascii" "ac_cv_func_iswascii" if test "x$ac_cv_func_iswascii" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_ISWASCII 1 _ACEOF fi done fi if test "$enable_pthreads" = yes; then for ac_func in localtime_r strtok_r pthread_mutexattr_settype do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done if test x"$ac_cv_func_pthread_mutexattr_settype" = xyes; then cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { int i = PTHREAD_MUTEX_RECURSIVE; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : $as_echo "#define PG_RECURSIVE_MUTEXATTR PTHREAD_MUTEX_RECURSIVE" >>confdefs.h else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { int i = PTHREAD_MUTEX_RECURSIVE_NP; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : $as_echo "#define PG_RECURSIVE_MUTEXATTR PTHREAD_MUTEX_RECURSIVE_NP" >>confdefs.h fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi fi if test "$enable_krb5" = yes; then ac_fn_c_check_member "$LINENO" "krb5_error" "text.data" "ac_cv_member_krb5_error_text_data" "#include " if test "x$ac_cv_member_krb5_error_text_data" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_KRB5_ERROR_TEXT_DATA 1 _ACEOF else ac_fn_c_check_member "$LINENO" "krb5_error" "e_data" "ac_cv_member_krb5_error_e_data" "#include " if test "x$ac_cv_member_krb5_error_e_data" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_KRB5_ERROR_E_DATA 1 _ACEOF else as_fn_error $? "could not determine how to extract Kerberos 5 error messages" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for krb5_free_unparsed_name" >&5 $as_echo_n "checking for krb5_free_unparsed_name... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { krb5_free_unparsed_name(NULL,NULL); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : $as_echo "#define HAVE_KRB5_FREE_UNPARSED_NAME 1" >>confdefs.h { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi # 8. Libltdl This release doesn't need libltdl # AC_CHECK_LIB(ltdl, lt_dlopen) ac_config_files="$ac_config_files Makefile test/Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"; then as_fn_error $? "conditional \"MAINTAINER_MODE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${GCC_TRUE}" && test -z "${GCC_FALSE}"; then as_fn_error $? "conditional \"GCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${enable_unicode_TRUE}" && test -z "${enable_unicode_FALSE}"; then as_fn_error $? "conditional \"enable_unicode\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${enable_openssl_TRUE}" && test -z "${enable_openssl_FALSE}"; then as_fn_error $? "conditional \"enable_openssl\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${enable_gss_TRUE}" && test -z "${enable_gss_FALSE}"; then as_fn_error $? "conditional \"enable_gss\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${enable_krb5_TRUE}" && test -z "${enable_krb5_FALSE}"; then as_fn_error $? "conditional \"enable_krb5\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by psqlodbc $as_me 09.03.0300, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Configuration commands: $config_commands Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ psqlodbc config.status 09.03.0300 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' AS='`$ECHO "$AS" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in AS \ DLLTOOL \ OBJDUMP \ SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ sharedlib_from_linklib_cmd \ AR \ AR_FLAGS \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ nm_file_list_spec \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ sys_lib_dlsearch_path_spec; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' xsi_shell='$xsi_shell' lt_shell_append='$lt_shell_append' # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "test/Makefile") CONFIG_FILES="$CONFIG_FILES test/Makefile" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. _am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || $as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$_am_arg" : 'X\(//\)[^/]' \| \ X"$_am_arg" : 'X\(//\)$' \| \ X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'`/stamp-h$_am_stamp_count ;; :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 $as_echo "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named `Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ X"$mf" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running `make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # When using ansi2knr, U may be empty or an underscore; expand it U=`sed -n 's/^U = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ X"$file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir=$dirpart/$fdir; as_fn_mkdir_p # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done ;; "libtool":C) # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="" # ### BEGIN LIBTOOL CONFIG # Assembler program. AS=$lt_AS # DLL creation program. DLLTOOL=$lt_DLLTOOL # Object dumper program. OBJDUMP=$lt_OBJDUMP # Whether or not to build static libraries. build_old_libs=$enable_static # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive. AR_FLAGS=$lt_AR_FLAGS # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and in which our libraries should be installed. lt_sysroot=$lt_sysroot # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain="$ac_aux_dir/ltmain.sh" # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) if test x"$xsi_shell" = xyes; then sed -e '/^func_dirname ()$/,/^} # func_dirname /c\ func_dirname ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ } # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_basename ()$/,/^} # func_basename /c\ func_basename ()\ {\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\ func_dirname_and_basename ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_stripname ()$/,/^} # func_stripname /c\ func_stripname ()\ {\ \ # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\ \ # positional parameters, so assign one to ordinary parameter first.\ \ func_stripname_result=${3}\ \ func_stripname_result=${func_stripname_result#"${1}"}\ \ func_stripname_result=${func_stripname_result%"${2}"}\ } # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\ func_split_long_opt ()\ {\ \ func_split_long_opt_name=${1%%=*}\ \ func_split_long_opt_arg=${1#*=}\ } # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\ func_split_short_opt ()\ {\ \ func_split_short_opt_arg=${1#??}\ \ func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\ } # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\ func_lo2o ()\ {\ \ case ${1} in\ \ *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\ \ *) func_lo2o_result=${1} ;;\ \ esac\ } # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_xform ()$/,/^} # func_xform /c\ func_xform ()\ {\ func_xform_result=${1%.*}.lo\ } # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_arith ()$/,/^} # func_arith /c\ func_arith ()\ {\ func_arith_result=$(( $* ))\ } # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_len ()$/,/^} # func_len /c\ func_len ()\ {\ func_len_result=${#1}\ } # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$lt_shell_append" = xyes; then sed -e '/^func_append ()$/,/^} # func_append /c\ func_append ()\ {\ eval "${1}+=\\${2}"\ } # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\ func_append_quoted ()\ {\ \ func_quote_for_eval "${2}"\ \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"\ } # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5 $as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;} fi mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi psqlodbc-09.03.0300/info.c000644 001752 000000 00000560432 12335653444 015311 0ustar00saitowheel000000 000000 /*-------- * Module: info.c * * Description: This module contains routines related to * ODBC informational functions. * * Classes: n/a * * API functions: SQLGetInfo, SQLGetTypeInfo, SQLGetFunctions, * SQLTables, SQLColumns, SQLStatistics, SQLSpecialColumns, * SQLPrimaryKeys, SQLForeignKeys, * SQLProcedureColumns, SQLProcedures, * SQLTablePrivileges, SQLColumnPrivileges(NI) * * Comments: See "readme.txt" for copyright and license information. *-------- */ #include "psqlodbc.h" #include #include #ifndef WIN32 #include #endif #include "tuple.h" #include "pgtypes.h" #include "dlg_specific.h" #include "environ.h" #include "connection.h" #include "statement.h" #include "qresult.h" #include "bind.h" #include "misc.h" #include "pgtypes.h" #include "pgapifunc.h" #include "multibyte.h" #include "catfunc.h" /* Trigger related stuff for SQLForeign Keys */ #define TRIGGER_SHIFT 3 #define TRIGGER_MASK 0x03 #define TRIGGER_DELETE 0x01 #define TRIGGER_UPDATE 0x02 #define NULL_IF_NULL(a) ((a) ? ((const char *) a) : "(NULL)") /* extern GLOBAL_VALUES globals; */ static const SQLCHAR *pubstr = (SQLCHAR *) "public"; static const char *likeop = "like"; static const char *eqop = "="; RETCODE SQL_API PGAPI_GetInfo(HDBC hdbc, SQLUSMALLINT fInfoType, PTR rgbInfoValue, SQLSMALLINT cbInfoValueMax, SQLSMALLINT FAR * pcbInfoValue) { CSTR func = "PGAPI_GetInfo"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci; const char *p = NULL; char tmp[MAX_INFO_STRING]; SQLULEN len = 0, value = 0; RETCODE result = SQL_ERROR; char odbcver[16]; int i_odbcver; mylog("%s: entering...fInfoType=%d\n", func, fInfoType); if (!conn) { CC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } ci = &(conn->connInfo); switch (fInfoType) { case SQL_ACCESSIBLE_PROCEDURES: /* ODBC 1.0 */ p = "N"; break; case SQL_ACCESSIBLE_TABLES: /* ODBC 1.0 */ p = CC_accessible_only(conn) ? "Y" : "N"; break; case SQL_ACTIVE_CONNECTIONS: /* ODBC 1.0 */ len = 2; value = 0; break; case SQL_ACTIVE_STATEMENTS: /* ODBC 1.0 */ len = 2; value = 0; break; case SQL_ALTER_TABLE: /* ODBC 2.0 */ len = 4; value = SQL_AT_ADD_COLUMN; if (PG_VERSION_GE(conn, 7.3)) value |= SQL_AT_DROP_COLUMN; #if (ODBCVER >= 0x0300) value |= SQL_AT_ADD_COLUMN_SINGLE; if (PG_VERSION_GE(conn, 7.1)) value |= SQL_AT_ADD_CONSTRAINT | SQL_AT_ADD_TABLE_CONSTRAINT | SQL_AT_CONSTRAINT_INITIALLY_DEFERRED | SQL_AT_CONSTRAINT_INITIALLY_IMMEDIATE | SQL_AT_CONSTRAINT_DEFERRABLE; if (PG_VERSION_GE(conn, 7.3)) value |= SQL_AT_DROP_TABLE_CONSTRAINT_RESTRICT | SQL_AT_DROP_TABLE_CONSTRAINT_CASCADE | SQL_AT_DROP_COLUMN_RESTRICT | SQL_AT_DROP_COLUMN_CASCADE; #endif /* ODBCVER */ break; case SQL_BOOKMARK_PERSISTENCE: /* ODBC 2.0 */ /* very simple bookmark support */ len = 4; value = ci->drivers.use_declarefetch && PG_VERSION_LT(conn, 7.4) ? 0 : (SQL_BP_SCROLL | SQL_BP_DELETE | SQL_BP_UPDATE | SQL_BP_TRANSACTION); break; case SQL_COLUMN_ALIAS: /* ODBC 2.0 */ p = "Y"; break; case SQL_CONCAT_NULL_BEHAVIOR: /* ODBC 1.0 */ len = 2; value = SQL_CB_NON_NULL; break; case SQL_CONVERT_INTEGER: case SQL_CONVERT_SMALLINT: case SQL_CONVERT_TINYINT: case SQL_CONVERT_BIT: case SQL_CONVERT_VARCHAR: /* ODBC 1.0 */ len = sizeof(SQLUINTEGER); value = SQL_CVT_BIT | SQL_CVT_INTEGER; mylog("SQL_CONVERT_ mask=" FORMAT_ULEN "\n", value); break; case SQL_CONVERT_BIGINT: case SQL_CONVERT_DECIMAL: case SQL_CONVERT_DOUBLE: case SQL_CONVERT_FLOAT: case SQL_CONVERT_NUMERIC: case SQL_CONVERT_REAL: case SQL_CONVERT_DATE: case SQL_CONVERT_TIME: case SQL_CONVERT_TIMESTAMP: case SQL_CONVERT_BINARY: case SQL_CONVERT_LONGVARBINARY: case SQL_CONVERT_VARBINARY: /* ODBC 1.0 */ case SQL_CONVERT_CHAR: case SQL_CONVERT_LONGVARCHAR: #if defined(UNICODE_SUPPORT) && (ODBCVER >= 0x0300) case SQL_CONVERT_WCHAR: case SQL_CONVERT_WLONGVARCHAR: case SQL_CONVERT_WVARCHAR: #endif /* UNICODE_SUPPORT */ len = sizeof(SQLUINTEGER); value = 0; /* CONVERT is unavailable */ break; case SQL_CONVERT_FUNCTIONS: /* ODBC 1.0 */ len = sizeof(SQLUINTEGER); value = SQL_FN_CVT_CONVERT; mylog("CONVERT_FUNCTIONS=" FORMAT_ULEN "\n", value); break; case SQL_CORRELATION_NAME: /* ODBC 1.0 */ /* * Saying no correlation name makes Query not work right. * value = SQL_CN_NONE; */ len = 2; value = SQL_CN_ANY; break; case SQL_CURSOR_COMMIT_BEHAVIOR: /* ODBC 1.0 */ len = 2; value = SQL_CB_CLOSE; if (!ci->drivers.use_declarefetch || PG_VERSION_GE(conn, 7.4)) value = SQL_CB_PRESERVE; break; case SQL_CURSOR_ROLLBACK_BEHAVIOR: /* ODBC 1.0 */ len = 2; value = SQL_CB_CLOSE; if (!ci->drivers.use_declarefetch) value = SQL_CB_PRESERVE; break; case SQL_DATA_SOURCE_NAME: /* ODBC 1.0 */ p = CC_get_DSN(conn); break; case SQL_DATA_SOURCE_READ_ONLY: /* ODBC 1.0 */ p = CC_is_onlyread(conn) ? "Y" : "N"; break; case SQL_DATABASE_NAME: /* Support for old ODBC 1.0 Apps */ /* * Returning the database name causes problems in MS Query. It * generates query like: "SELECT DISTINCT a FROM byronnbad3 * bad3" * * p = CC_get_database(conn); */ p = CurrCatString(conn); break; case SQL_DBMS_NAME: /* ODBC 1.0 */ if (CC_fake_mss(conn)) p = "Microsoft SQL Server"; else p = "PostgreSQL"; break; case SQL_DBMS_VER: /* ODBC 1.0 */ /* * The ODBC spec wants ##.##.#### ...whatever... so prepend * the driver */ /* version number to the dbms version string */ /* snprintf(tmp, sizeof(tmp) - 1, "%s %s", POSTGRESDRIVERVERSION, conn->pg_version); tmp[sizeof(tmp) - 1] = '\0'; */ if (CC_fake_mss(conn)) p = "09.00.1399"; else { strncpy_null(tmp, conn->pg_version, sizeof(tmp)); p = tmp; } break; case SQL_DEFAULT_TXN_ISOLATION: /* ODBC 1.0 */ len = 4; if (PG_VERSION_LT(conn, 6.5)) value = SQL_TXN_SERIALIZABLE; else value = SQL_TXN_READ_COMMITTED; break; case SQL_DRIVER_NAME: /* ODBC 1.0 */ p = DRIVER_FILE_NAME; break; case SQL_DRIVER_ODBC_VER: i_odbcver = conn->driver_version; snprintf(odbcver, sizeof(odbcver), "%02x.%02x", i_odbcver / 256, i_odbcver % 256); /* p = DRIVER_ODBC_VER; */ p = odbcver; break; case SQL_DRIVER_VER: /* ODBC 1.0 */ p = POSTGRESDRIVERVERSION; break; case SQL_EXPRESSIONS_IN_ORDERBY: /* ODBC 1.0 */ p = PG_VERSION_GE(conn, 6.5) ? "Y" : "N"; break; case SQL_FETCH_DIRECTION: /* ODBC 1.0 */ len = 4; value = (SQL_FD_FETCH_NEXT | SQL_FD_FETCH_FIRST | SQL_FD_FETCH_LAST | SQL_FD_FETCH_PRIOR | SQL_FD_FETCH_ABSOLUTE | SQL_FD_FETCH_RELATIVE | SQL_FD_FETCH_BOOKMARK); break; case SQL_FILE_USAGE: /* ODBC 2.0 */ len = 2; value = SQL_FILE_NOT_SUPPORTED; break; case SQL_GETDATA_EXTENSIONS: /* ODBC 2.0 */ len = 4; value = (SQL_GD_ANY_COLUMN | SQL_GD_ANY_ORDER | SQL_GD_BOUND | SQL_GD_BLOCK); break; case SQL_GROUP_BY: /* ODBC 2.0 */ len = 2; value = SQL_GB_GROUP_BY_EQUALS_SELECT; break; case SQL_IDENTIFIER_CASE: /* ODBC 1.0 */ /* * are identifiers case-sensitive (yes, but only when quoted. * If not quoted, they default to lowercase) */ len = 2; value = SQL_IC_LOWER; break; case SQL_IDENTIFIER_QUOTE_CHAR: /* ODBC 1.0 */ /* the character used to quote "identifiers" */ p = PG_VERSION_LE(conn, 6.2) ? " " : "\""; break; case SQL_KEYWORDS: /* ODBC 2.0 */ p = NULL_STRING; break; case SQL_LIKE_ESCAPE_CLAUSE: /* ODBC 2.0 */ /* * is there a character that escapes '%' and '_' in a LIKE * clause? not as far as I can tell */ p = "N"; break; case SQL_LOCK_TYPES: /* ODBC 2.0 */ len = 4; value = ci->drivers.lie ? (SQL_LCK_NO_CHANGE | SQL_LCK_EXCLUSIVE | SQL_LCK_UNLOCK) : SQL_LCK_NO_CHANGE; break; case SQL_MAX_BINARY_LITERAL_LEN: /* ODBC 2.0 */ len = 4; value = 0; break; case SQL_MAX_CHAR_LITERAL_LEN: /* ODBC 2.0 */ len = 4; value = 0; break; case SQL_MAX_COLUMN_NAME_LEN: /* ODBC 1.0 */ len = 2; if (PG_VERSION_GT(conn, 7.4)) value = CC_get_max_idlen(conn); #ifdef MAX_COLUMN_LEN else value = MAX_COLUMN_LEN; #endif /* MAX_COLUMN_LEN */ if (0 == value) { if (PG_VERSION_GE(conn, 7.3)) value = NAMEDATALEN_V73; else value = NAMEDATALEN_V72; } break; case SQL_MAX_COLUMNS_IN_GROUP_BY: /* ODBC 2.0 */ len = 2; value = 0; break; case SQL_MAX_COLUMNS_IN_INDEX: /* ODBC 2.0 */ len = 2; value = 0; break; case SQL_MAX_COLUMNS_IN_ORDER_BY: /* ODBC 2.0 */ len = 2; value = 0; break; case SQL_MAX_COLUMNS_IN_SELECT: /* ODBC 2.0 */ len = 2; value = 0; break; case SQL_MAX_COLUMNS_IN_TABLE: /* ODBC 2.0 */ len = 2; value = 0; break; case SQL_MAX_CURSOR_NAME_LEN: /* ODBC 1.0 */ len = 2; value = MAX_CURSOR_LEN; break; case SQL_MAX_INDEX_SIZE: /* ODBC 2.0 */ len = 4; value = 0; break; case SQL_MAX_OWNER_NAME_LEN: /* ODBC 1.0 */ len = 2; value = 0; if (PG_VERSION_GT(conn, 7.4)) value = CC_get_max_idlen(conn); #ifdef MAX_SCHEMA_LEN else if (conn->schema_support) value = MAX_SCHEMA_LEN; #endif /* MAX_SCHEMA_LEN */ if (0 == value) { if (PG_VERSION_GE(conn, 7.3)) value = NAMEDATALEN_V73; } break; case SQL_MAX_PROCEDURE_NAME_LEN: /* ODBC 1.0 */ len = 2; value = 0; break; case SQL_MAX_QUALIFIER_NAME_LEN: /* ODBC 1.0 */ len = 2; value = 0; break; case SQL_MAX_ROW_SIZE: /* ODBC 2.0 */ len = 4; if (PG_VERSION_GE(conn, 7.1)) { /* No limit with tuptoaster in 7.1+ */ value = 0; } else { /* Without the Toaster we're limited to the blocksize */ value = BLCKSZ; } break; case SQL_MAX_ROW_SIZE_INCLUDES_LONG: /* ODBC 2.0 */ /* * does the preceding value include LONGVARCHAR and * LONGVARBINARY fields? Well, it does include longvarchar, * but not longvarbinary. */ p = "Y"; break; case SQL_MAX_STATEMENT_LEN: /* ODBC 2.0 */ /* maybe this should be 0? */ len = 4; value = CC_get_max_query_len(conn); break; case SQL_MAX_TABLE_NAME_LEN: /* ODBC 1.0 */ len = 2; if (PG_VERSION_GT(conn, 7.4)) value = CC_get_max_idlen(conn); #ifdef MAX_TABLE_LEN else value = MAX_TABLE_LEN; #endif /* MAX_TABLE_LEN */ if (0 == value) { if (PG_VERSION_GE(conn, 7.3)) value = NAMEDATALEN_V73; else value = NAMEDATALEN_V72; } break; case SQL_MAX_TABLES_IN_SELECT: /* ODBC 2.0 */ len = 2; value = 0; break; case SQL_MAX_USER_NAME_LEN: len = 2; value = 0; break; case SQL_MULT_RESULT_SETS: /* ODBC 1.0 */ /* Don't support multiple result sets but say yes anyway? */ p = "Y"; break; case SQL_MULTIPLE_ACTIVE_TXN: /* ODBC 1.0 */ p = "Y"; break; case SQL_NEED_LONG_DATA_LEN: /* ODBC 2.0 */ /* * Don't need the length, SQLPutData can handle any size and * multiple calls */ p = "N"; break; case SQL_NON_NULLABLE_COLUMNS: /* ODBC 1.0 */ len = 2; value = SQL_NNC_NON_NULL; break; case SQL_NULL_COLLATION: /* ODBC 2.0 */ /* where are nulls sorted? */ len = 2; if (PG_VERSION_GE(conn, 7.2)) value = SQL_NC_HIGH; else value = SQL_NC_END; break; case SQL_NUMERIC_FUNCTIONS: /* ODBC 1.0 */ len = 4; value = 0; break; case SQL_ODBC_API_CONFORMANCE: /* ODBC 1.0 */ len = 2; value = SQL_OAC_LEVEL1; break; case SQL_ODBC_SAG_CLI_CONFORMANCE: /* ODBC 1.0 */ len = 2; value = SQL_OSCC_NOT_COMPLIANT; break; case SQL_ODBC_SQL_CONFORMANCE: /* ODBC 1.0 */ len = 2; value = SQL_OSC_CORE; break; case SQL_ODBC_SQL_OPT_IEF: /* ODBC 1.0 */ p = "N"; break; case SQL_OJ_CAPABILITIES: /* ODBC 2.01 */ len = 4; if (PG_VERSION_GE(conn, 7.1)) { /* OJs in 7.1+ */ value = (SQL_OJ_LEFT | SQL_OJ_RIGHT | SQL_OJ_FULL | SQL_OJ_NESTED | SQL_OJ_NOT_ORDERED | SQL_OJ_INNER | SQL_OJ_ALL_COMPARISON_OPS); } else /* OJs not in <7.1 */ value = 0; break; case SQL_ORDER_BY_COLUMNS_IN_SELECT: /* ODBC 2.0 */ p = (PG_VERSION_LE(conn, 6.3)) ? "Y" : "N"; break; case SQL_OUTER_JOINS: /* ODBC 1.0 */ if (PG_VERSION_GE(conn, 7.1)) /* OJs in 7.1+ */ p = "Y"; else /* OJs not in <7.1 */ p = "N"; break; case SQL_OWNER_TERM: /* ODBC 1.0 */ if (conn->schema_support) p = "schema"; else p = "owner"; break; case SQL_OWNER_USAGE: /* ODBC 2.0 */ len = 4; value = 0; if (conn->schema_support) value = SQL_OU_DML_STATEMENTS | SQL_OU_TABLE_DEFINITION | SQL_OU_INDEX_DEFINITION | SQL_OU_PRIVILEGE_DEFINITION ; break; case SQL_POS_OPERATIONS: /* ODBC 2.0 */ len = 4; value = (SQL_POS_POSITION | SQL_POS_REFRESH); if (0 != ci->updatable_cursors) value |= (SQL_POS_UPDATE | SQL_POS_DELETE | SQL_POS_ADD); break; case SQL_POSITIONED_STATEMENTS: /* ODBC 2.0 */ len = 4; value = ci->drivers.lie ? (SQL_PS_POSITIONED_DELETE | SQL_PS_POSITIONED_UPDATE | SQL_PS_SELECT_FOR_UPDATE) : 0; break; case SQL_PROCEDURE_TERM: /* ODBC 1.0 */ p = "procedure"; break; case SQL_PROCEDURES: /* ODBC 1.0 */ p = "Y"; break; case SQL_QUALIFIER_LOCATION: /* ODBC 2.0 */ len = 2; if (CurrCat(conn)) value = SQL_QL_START; else value = 0; break; case SQL_QUALIFIER_NAME_SEPARATOR: /* ODBC 1.0 */ if (CurrCat(conn)) p = "."; else p = NULL_STRING; break; case SQL_QUALIFIER_TERM: /* ODBC 1.0 */ if (CurrCat(conn)) p = "catalog"; else p = NULL_STRING; break; case SQL_QUALIFIER_USAGE: /* ODBC 2.0 */ len = 4; #if (ODBCVER >= 0x0300) if (CurrCat(conn)) value = SQL_CU_DML_STATEMENTS; else #endif /* ODBCVER */ value = 0; break; case SQL_QUOTED_IDENTIFIER_CASE: /* ODBC 2.0 */ /* are "quoted" identifiers case-sensitive? YES! */ len = 2; value = SQL_IC_SENSITIVE; break; case SQL_ROW_UPDATES: /* ODBC 1.0 */ /* * Driver doesn't support keyset-driven or mixed cursors, so * not much point in saying row updates are supported */ p = (0 != ci->updatable_cursors) ? "Y" : "N"; break; case SQL_SCROLL_CONCURRENCY: /* ODBC 1.0 */ len = 4; value = SQL_SCCO_READ_ONLY; if (0 != ci->updatable_cursors) value |= SQL_SCCO_OPT_ROWVER; if (ci->drivers.lie) value |= (SQL_SCCO_LOCK | SQL_SCCO_OPT_VALUES); break; case SQL_SCROLL_OPTIONS: /* ODBC 1.0 */ len = 4; value = SQL_SO_FORWARD_ONLY | SQL_SO_STATIC; if (0 != (ci->updatable_cursors & ALLOW_KEYSET_DRIVEN_CURSORS)) value |= SQL_SO_KEYSET_DRIVEN; if (ci->drivers.lie) value |= (SQL_SO_DYNAMIC | SQL_SO_MIXED); break; case SQL_SEARCH_PATTERN_ESCAPE: /* ODBC 1.0 */ if (PG_VERSION_GE(conn, 6.5)) p = "\\"; else p = NULL_STRING; break; case SQL_SERVER_NAME: /* ODBC 1.0 */ p = CC_get_server(conn); break; case SQL_SPECIAL_CHARACTERS: /* ODBC 2.0 */ p = "_"; break; case SQL_STATIC_SENSITIVITY: /* ODBC 2.0 */ len = 4; value = 0; if (0 != ci->updatable_cursors) value |= (SQL_SS_ADDITIONS | SQL_SS_DELETIONS | SQL_SS_UPDATES); break; case SQL_STRING_FUNCTIONS: /* ODBC 1.0 */ len = 4; value = (SQL_FN_STR_CONCAT | SQL_FN_STR_LCASE | SQL_FN_STR_LENGTH | SQL_FN_STR_LOCATE | SQL_FN_STR_LTRIM | SQL_FN_STR_RTRIM | SQL_FN_STR_SUBSTRING | SQL_FN_STR_UCASE); break; case SQL_SUBQUERIES: /* ODBC 2.0 */ /* postgres 6.3 supports subqueries */ len = 4; value = (SQL_SQ_QUANTIFIED | SQL_SQ_IN | SQL_SQ_EXISTS | SQL_SQ_COMPARISON); break; case SQL_SYSTEM_FUNCTIONS: /* ODBC 1.0 */ len = 4; value = 0; break; case SQL_TABLE_TERM: /* ODBC 1.0 */ p = "table"; break; case SQL_TIMEDATE_ADD_INTERVALS: /* ODBC 2.0 */ len = 4; value = 0; break; case SQL_TIMEDATE_DIFF_INTERVALS: /* ODBC 2.0 */ len = 4; value = 0; break; case SQL_TIMEDATE_FUNCTIONS: /* ODBC 1.0 */ len = 4; value = (SQL_FN_TD_NOW); break; case SQL_TXN_CAPABLE: /* ODBC 1.0 */ /* * Postgres can deal with create or drop table statements in a * transaction */ len = 2; value = SQL_TC_ALL; break; case SQL_TXN_ISOLATION_OPTION: /* ODBC 1.0 */ len = 4; if (PG_VERSION_LT(conn, 6.5)) value = SQL_TXN_SERIALIZABLE; else if (PG_VERSION_GE(conn, 7.1)) value = SQL_TXN_READ_COMMITTED | SQL_TXN_SERIALIZABLE; else value = SQL_TXN_READ_COMMITTED; break; case SQL_UNION: /* ODBC 2.0 */ /* unions with all supported in postgres 6.3 */ len = 4; value = (SQL_U_UNION | SQL_U_UNION_ALL); break; case SQL_USER_NAME: /* ODBC 1.0 */ p = CC_get_username(conn); break; default: /* unrecognized key */ CC_set_error(conn, CONN_NOT_IMPLEMENTED_ERROR, "Unrecognized key passed to PGAPI_GetInfo.", NULL); goto cleanup; } result = SQL_SUCCESS; mylog("%s: p='%s', len=%d, value=%d, cbMax=%d\n", func, p ? p : "", len, value, cbInfoValueMax); /* * NOTE, that if rgbInfoValue is NULL, then no warnings or errors * should result and just pcbInfoValue is returned, which indicates * what length would be required if a real buffer had been passed in. */ if (p) { /* char/binary data */ len = strlen(p); if (rgbInfoValue) { #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) { len = utf8_to_ucs2(p, len, (SQLWCHAR *) rgbInfoValue, cbInfoValueMax / WCLEN); len *= WCLEN; } else #endif /* UNICODE_SUPPORT */ strncpy_null((char *) rgbInfoValue, p, (size_t) cbInfoValueMax); if (len >= cbInfoValueMax) { result = SQL_SUCCESS_WITH_INFO; CC_set_error(conn, CONN_TRUNCATED, "The buffer was too small for the InfoValue.", func); } } #ifdef UNICODE_SUPPORT else if (CC_is_in_unicode_driver(conn)) len *= WCLEN; #endif /* UNICODE_SUPPORT */ } else { /* numeric data */ if (rgbInfoValue) { if (len == sizeof(SQLSMALLINT)) *((SQLUSMALLINT *) rgbInfoValue) = (SQLUSMALLINT) value; else if (len == sizeof(SQLINTEGER)) *((SQLUINTEGER *) rgbInfoValue) = (SQLUINTEGER) value; } } if (pcbInfoValue) *pcbInfoValue = (SQLSMALLINT) len; cleanup: return result; } RETCODE SQL_API PGAPI_GetTypeInfo(HSTMT hstmt, SQLSMALLINT fSqlType) { CSTR func = "PGAPI_GetTypeInfo"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; QResultClass *res = NULL; TupleField *tuple; int i, result_cols; /* Int4 type; */ Int4 pgType; Int2 sqlType; RETCODE result = SQL_SUCCESS; mylog("%s: entering...fSqlType = %d\n", func, fSqlType); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "Error creating result.", func); return SQL_ERROR; } SC_set_Result(stmt, res); #define return DONT_CALL_RETURN_FROM_HERE??? #if (ODBCVER >= 0x0300) result_cols = 19; #else result_cols = 15; #endif /* ODBCVER */ extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, 0, "TYPE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 1, "DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 2, "PRECISION", PG_TYPE_INT4, 4); QR_set_field_info_v(res, 3, "LITERAL_PREFIX", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 4, "LITERAL_SUFFIX", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 5, "CREATE_PARAMS", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 6, "NULLABLE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 7, "CASE_SENSITIVE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 8, "SEARCHABLE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 9, "UNSIGNED_ATTRIBUTE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 10, "MONEY", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 11, "AUTO_INCREMENT", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 12, "LOCAL_TYPE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 13, "MINIMUM_SCALE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 14, "MAXIMUM_SCALE", PG_TYPE_INT2, 2); #if (ODBCVER >=0x0300) QR_set_field_info_v(res, 15, "SQL_DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 16, "SQL_DATETIME_SUB", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 17, "NUM_PREC_RADIX", PG_TYPE_INT4, 4); QR_set_field_info_v(res, 18, "INTERVAL_PRECISION", PG_TYPE_INT2, 2); #endif /* ODBCVER */ for (i = 0, sqlType = sqlTypes[0]; sqlType; sqlType = sqlTypes[++i]) { pgType = sqltype_to_pgtype(conn, sqlType); if (sqlType == SQL_LONGVARBINARY) { ConnInfo *ci = &(conn->connInfo); inolog("%d sqltype=%d -> pgtype=%d\n", ci->bytea_as_longvarbinary, sqlType, pgType); } if (fSqlType == SQL_ALL_TYPES || fSqlType == sqlType) { int pgtcount = 1, aunq_match = -1, cnt; /*if (SQL_INTEGER == sqlType || SQL_TINYINT == sqlType)*/ if (SQL_INTEGER == sqlType) { mylog("sqlType=%d ms_jet=%d\n", sqlType, conn->ms_jet); if (conn->ms_jet && PG_VERSION_GE(conn, 6.4)) { aunq_match = 1; pgtcount = 2; } mylog("aunq_match=%d pgtcount=%d\n", aunq_match, pgtcount); } for (cnt = 0; cnt < pgtcount; cnt ++) { if (tuple = QR_AddNew(res), NULL == tuple) { result = SQL_ERROR; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't QR_AddNew.", func); goto cleanup; } /* These values can't be NULL */ if (aunq_match == cnt) { set_tuplefield_string(&tuple[0], pgtype_to_name(stmt, pgType, PG_UNSPECIFIED, TRUE)); set_tuplefield_int2(&tuple[6], SQL_NO_NULLS); inolog("serial in\n"); } else { set_tuplefield_string(&tuple[0], pgtype_to_name(stmt, pgType, PG_UNSPECIFIED, FALSE)); set_tuplefield_int2(&tuple[6], pgtype_nullable(conn, pgType)); } set_tuplefield_int2(&tuple[1], (Int2) sqlType); set_tuplefield_int2(&tuple[7], pgtype_case_sensitive(conn, pgType)); set_tuplefield_int2(&tuple[8], pgtype_searchable(conn, pgType)); set_tuplefield_int2(&tuple[10], pgtype_money(conn, pgType)); /* * Localized data-source dependent data type name (always * NULL) */ set_tuplefield_null(&tuple[12]); /* These values can be NULL */ set_nullfield_int4(&tuple[2], pgtype_column_size(stmt, pgType, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_nullfield_string(&tuple[3], pgtype_literal_prefix(conn, pgType)); set_nullfield_string(&tuple[4], pgtype_literal_suffix(conn, pgType)); set_nullfield_string(&tuple[5], pgtype_create_params(conn, pgType)); if (1 < pgtcount) set_tuplefield_int2(&tuple[9], SQL_TRUE); else set_nullfield_int2(&tuple[9], pgtype_unsigned(conn, pgType)); if (aunq_match == cnt) set_tuplefield_int2(&tuple[11], SQL_TRUE); else set_nullfield_int2(&tuple[11], pgtype_auto_increment(conn, pgType)); set_nullfield_int2(&tuple[13], pgtype_min_decimal_digits(conn, pgType)); set_nullfield_int2(&tuple[14], pgtype_max_decimal_digits(conn, pgType)); #if (ODBCVER >=0x0300) set_nullfield_int2(&tuple[15], pgtype_to_sqldesctype(stmt, pgType, PG_STATIC)); set_nullfield_int2(&tuple[16], pgtype_to_datetime_sub(stmt, pgType, PG_UNSPECIFIED)); set_nullfield_int4(&tuple[17], pgtype_radix(conn, pgType)); set_nullfield_int4(&tuple[18], 0); #endif /* ODBCVER */ } } } cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; stmt->currTuple = -1; if (SQL_SUCCEEDED(result)) SC_set_rowset_start(stmt, -1, FALSE); else SC_set_Result(stmt, NULL); SC_set_current_col(stmt, -1); if (stmt->internal) result = DiscardStatementSvp(stmt, result, FALSE); return result; } RETCODE SQL_API PGAPI_GetFunctions(HDBC hdbc, SQLUSMALLINT fFunction, SQLUSMALLINT FAR * pfExists) { CSTR func = "PGAPI_GetFunctions"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci = &(conn->connInfo); mylog("%s: entering...%u\n", func, fFunction); if (fFunction == SQL_API_ALL_FUNCTIONS) { #if (ODBCVER < 0x0300) if (ci->drivers.lie) { int i; memset(pfExists, 0, sizeof(pfExists[0]) * 100); pfExists[SQL_API_SQLALLOCENV] = TRUE; pfExists[SQL_API_SQLFREEENV] = TRUE; for (i = SQL_API_SQLALLOCCONNECT; i <= SQL_NUM_FUNCTIONS; i++) pfExists[i] = TRUE; for (i = SQL_EXT_API_START; i <= SQL_EXT_API_LAST; i++) pfExists[i] = TRUE; } else #endif { memset(pfExists, 0, sizeof(pfExists[0]) * 100); /* ODBC core functions */ pfExists[SQL_API_SQLALLOCCONNECT] = TRUE; pfExists[SQL_API_SQLALLOCENV] = TRUE; pfExists[SQL_API_SQLALLOCSTMT] = TRUE; pfExists[SQL_API_SQLBINDCOL] = TRUE; pfExists[SQL_API_SQLCANCEL] = TRUE; pfExists[SQL_API_SQLCOLATTRIBUTES] = TRUE; pfExists[SQL_API_SQLCONNECT] = TRUE; pfExists[SQL_API_SQLDESCRIBECOL] = TRUE; /* partial */ pfExists[SQL_API_SQLDISCONNECT] = TRUE; pfExists[SQL_API_SQLERROR] = TRUE; pfExists[SQL_API_SQLEXECDIRECT] = TRUE; pfExists[SQL_API_SQLEXECUTE] = TRUE; pfExists[SQL_API_SQLFETCH] = TRUE; pfExists[SQL_API_SQLFREECONNECT] = TRUE; pfExists[SQL_API_SQLFREEENV] = TRUE; pfExists[SQL_API_SQLFREESTMT] = TRUE; pfExists[SQL_API_SQLGETCURSORNAME] = TRUE; pfExists[SQL_API_SQLNUMRESULTCOLS] = TRUE; pfExists[SQL_API_SQLPREPARE] = TRUE; /* complete? */ pfExists[SQL_API_SQLROWCOUNT] = TRUE; pfExists[SQL_API_SQLSETCURSORNAME] = TRUE; pfExists[SQL_API_SQLSETPARAM] = FALSE; /* odbc 1.0 */ pfExists[SQL_API_SQLTRANSACT] = TRUE; /* ODBC level 1 functions */ pfExists[SQL_API_SQLBINDPARAMETER] = TRUE; pfExists[SQL_API_SQLCOLUMNS] = TRUE; pfExists[SQL_API_SQLDRIVERCONNECT] = TRUE; pfExists[SQL_API_SQLGETCONNECTOPTION] = TRUE; /* partial */ pfExists[SQL_API_SQLGETDATA] = TRUE; pfExists[SQL_API_SQLGETFUNCTIONS] = TRUE; pfExists[SQL_API_SQLGETINFO] = TRUE; pfExists[SQL_API_SQLGETSTMTOPTION] = TRUE; /* partial */ pfExists[SQL_API_SQLGETTYPEINFO] = TRUE; pfExists[SQL_API_SQLPARAMDATA] = TRUE; pfExists[SQL_API_SQLPUTDATA] = TRUE; pfExists[SQL_API_SQLSETCONNECTOPTION] = TRUE; /* partial */ pfExists[SQL_API_SQLSETSTMTOPTION] = TRUE; pfExists[SQL_API_SQLSPECIALCOLUMNS] = TRUE; pfExists[SQL_API_SQLSTATISTICS] = TRUE; pfExists[SQL_API_SQLTABLES] = TRUE; /* ODBC level 2 functions */ pfExists[SQL_API_SQLBROWSECONNECT] = FALSE; if (PG_VERSION_GE(conn, 7.4)) pfExists[SQL_API_SQLCOLUMNPRIVILEGES] = FALSE; else pfExists[SQL_API_SQLCOLUMNPRIVILEGES] = FALSE; pfExists[SQL_API_SQLDATASOURCES] = FALSE; /* only implemented by * DM */ if (SUPPORT_DESCRIBE_PARAM(ci)) pfExists[SQL_API_SQLDESCRIBEPARAM] = TRUE; else pfExists[SQL_API_SQLDESCRIBEPARAM] = FALSE; /* not properly * implemented */ pfExists[SQL_API_SQLDRIVERS] = FALSE; /* only implemented by * DM */ pfExists[SQL_API_SQLEXTENDEDFETCH] = TRUE; pfExists[SQL_API_SQLFOREIGNKEYS] = TRUE; pfExists[SQL_API_SQLMORERESULTS] = TRUE; pfExists[SQL_API_SQLNATIVESQL] = TRUE; pfExists[SQL_API_SQLNUMPARAMS] = TRUE; pfExists[SQL_API_SQLPARAMOPTIONS] = TRUE; pfExists[SQL_API_SQLPRIMARYKEYS] = TRUE; if (PG_VERSION_LT(conn, 6.5)) pfExists[SQL_API_SQLPROCEDURECOLUMNS] = FALSE; else pfExists[SQL_API_SQLPROCEDURECOLUMNS] = TRUE; if (PG_VERSION_LT(conn, 6.5)) pfExists[SQL_API_SQLPROCEDURES] = FALSE; else pfExists[SQL_API_SQLPROCEDURES] = TRUE; pfExists[SQL_API_SQLSETPOS] = TRUE; pfExists[SQL_API_SQLSETSCROLLOPTIONS] = TRUE; /* odbc 1.0 */ pfExists[SQL_API_SQLTABLEPRIVILEGES] = TRUE; #if (ODBCVER >= 0x0300) if (0 == ci->updatable_cursors) pfExists[SQL_API_SQLBULKOPERATIONS] = FALSE; else pfExists[SQL_API_SQLBULKOPERATIONS] = TRUE; #endif /* ODBCVER */ } } else { if (ci->drivers.lie) *pfExists = TRUE; else { switch (fFunction) { #if (ODBCVER < 0x0300) case SQL_API_SQLALLOCCONNECT: *pfExists = TRUE; break; case SQL_API_SQLALLOCENV: *pfExists = TRUE; break; case SQL_API_SQLALLOCSTMT: *pfExists = TRUE; break; #endif /* ODBCVER */ case SQL_API_SQLBINDCOL: *pfExists = TRUE; break; case SQL_API_SQLCANCEL: *pfExists = TRUE; break; #if (ODBCVER >= 0x0300) case SQL_API_SQLCOLATTRIBUTE: #else case SQL_API_SQLCOLATTRIBUTES: #endif /* ODBCVER */ *pfExists = TRUE; break; case SQL_API_SQLCONNECT: *pfExists = TRUE; break; case SQL_API_SQLDESCRIBECOL: *pfExists = TRUE; break; /* partial */ case SQL_API_SQLDISCONNECT: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLERROR: *pfExists = TRUE; break; #endif /* ODBCVER */ case SQL_API_SQLEXECDIRECT: *pfExists = TRUE; break; case SQL_API_SQLEXECUTE: *pfExists = TRUE; break; case SQL_API_SQLFETCH: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLFREECONNECT: *pfExists = TRUE; break; case SQL_API_SQLFREEENV: *pfExists = TRUE; break; #endif /* ODBCVER */ case SQL_API_SQLFREESTMT: *pfExists = TRUE; break; case SQL_API_SQLGETCURSORNAME: *pfExists = TRUE; break; case SQL_API_SQLNUMRESULTCOLS: *pfExists = TRUE; break; case SQL_API_SQLPREPARE: *pfExists = TRUE; break; case SQL_API_SQLROWCOUNT: *pfExists = TRUE; break; case SQL_API_SQLSETCURSORNAME: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLSETPARAM: *pfExists = FALSE; break; /* odbc 1.0 */ case SQL_API_SQLTRANSACT: *pfExists = TRUE; break; #endif /* ODBCVER */ /* ODBC level 1 functions */ case SQL_API_SQLBINDPARAMETER: *pfExists = TRUE; break; case SQL_API_SQLCOLUMNS: *pfExists = TRUE; break; case SQL_API_SQLDRIVERCONNECT: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLGETCONNECTOPTION: *pfExists = TRUE; break; /* partial */ #endif /* ODBCVER */ case SQL_API_SQLGETDATA: *pfExists = TRUE; break; case SQL_API_SQLGETFUNCTIONS: *pfExists = TRUE; break; case SQL_API_SQLGETINFO: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLGETSTMTOPTION: *pfExists = TRUE; break; /* partial */ #endif /* ODBCVER */ case SQL_API_SQLGETTYPEINFO: *pfExists = TRUE; break; case SQL_API_SQLPARAMDATA: *pfExists = TRUE; break; case SQL_API_SQLPUTDATA: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLSETCONNECTOPTION: *pfExists = TRUE; break; /* partial */ case SQL_API_SQLSETSTMTOPTION: *pfExists = TRUE; break; #endif /* ODBCVER */ case SQL_API_SQLSPECIALCOLUMNS: *pfExists = TRUE; break; case SQL_API_SQLSTATISTICS: *pfExists = TRUE; break; case SQL_API_SQLTABLES: *pfExists = TRUE; break; /* ODBC level 2 functions */ case SQL_API_SQLBROWSECONNECT: *pfExists = FALSE; break; case SQL_API_SQLCOLUMNPRIVILEGES: *pfExists = FALSE; break; case SQL_API_SQLDATASOURCES: *pfExists = FALSE; break; /* only implemented by DM */ case SQL_API_SQLDESCRIBEPARAM: if (SUPPORT_DESCRIBE_PARAM(ci)) *pfExists = TRUE; else *pfExists = FALSE; break; /* not properly implemented */ case SQL_API_SQLDRIVERS: *pfExists = FALSE; break; /* only implemented by DM */ case SQL_API_SQLEXTENDEDFETCH: *pfExists = TRUE; break; case SQL_API_SQLFOREIGNKEYS: *pfExists = TRUE; break; case SQL_API_SQLMORERESULTS: *pfExists = TRUE; break; case SQL_API_SQLNATIVESQL: *pfExists = TRUE; break; case SQL_API_SQLNUMPARAMS: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLPARAMOPTIONS: *pfExists = TRUE; break; #endif /* ODBCVER */ case SQL_API_SQLPRIMARYKEYS: *pfExists = TRUE; break; case SQL_API_SQLPROCEDURECOLUMNS: if (PG_VERSION_LT(conn, 6.5)) *pfExists = FALSE; else *pfExists = TRUE; break; case SQL_API_SQLPROCEDURES: if (PG_VERSION_LT(conn, 6.5)) *pfExists = FALSE; else *pfExists = TRUE; break; case SQL_API_SQLSETPOS: *pfExists = TRUE; break; #if (ODBCVER < 0x0300) case SQL_API_SQLSETSCROLLOPTIONS: *pfExists = TRUE; break; /* odbc 1.0 */ #endif /* ODBCVER */ case SQL_API_SQLTABLEPRIVILEGES: *pfExists = TRUE; break; #if (ODBCVER >= 0x0300) case SQL_API_SQLBULKOPERATIONS: /* 24 */ case SQL_API_SQLALLOCHANDLE: /* 1001 */ case SQL_API_SQLBINDPARAM: /* 1002 */ case SQL_API_SQLCLOSECURSOR: /* 1003 */ case SQL_API_SQLENDTRAN: /* 1005 */ case SQL_API_SQLFETCHSCROLL: /* 1021 */ case SQL_API_SQLFREEHANDLE: /* 1006 */ case SQL_API_SQLGETCONNECTATTR: /* 1007 */ case SQL_API_SQLGETDESCFIELD: /* 1008 */ case SQL_API_SQLGETDIAGFIELD: /* 1010 */ case SQL_API_SQLGETDIAGREC: /* 1011 */ case SQL_API_SQLGETENVATTR: /* 1012 */ case SQL_API_SQLGETSTMTATTR: /* 1014 */ case SQL_API_SQLSETCONNECTATTR: /* 1016 */ case SQL_API_SQLSETDESCFIELD: /* 1017 */ case SQL_API_SQLSETENVATTR: /* 1019 */ case SQL_API_SQLSETSTMTATTR: /* 1020 */ *pfExists = TRUE; break; case SQL_API_SQLGETDESCREC: /* 1009 */ case SQL_API_SQLSETDESCREC: /* 1018 */ case SQL_API_SQLCOPYDESC: /* 1004 */ *pfExists = FALSE; break; #endif /* ODBCVER */ default: *pfExists = FALSE; break; } } } return SQL_SUCCESS; } static char * simpleCatalogEscape(const SQLCHAR *src, SQLLEN srclen, int *result_len, const ConnectionClass *conn) { int i, outlen; const char *in; char *dest = NULL, escape_ch = CC_get_escape(conn); encoded_str encstr; if (result_len) *result_len = 0; if (!src || srclen == SQL_NULL_DATA) return dest; else if (srclen == SQL_NTS) srclen = (SQLLEN) strlen((char *) src); if (srclen <= 0) return dest; mylog("simple in=%s(%d)\n", src, srclen); encoded_str_constr(&encstr, conn->ccsc, (char *) src); dest = malloc(2 * srclen + 1); for (i = 0, in = (char *) src, outlen = 0; i < srclen; i++, in++) { encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) { dest[outlen++] = *in; continue; } if (LITERAL_QUOTE == *in || escape_ch == *in) dest[outlen++] = *in; dest[outlen++] = *in; } dest[outlen] = '\0'; if (result_len) *result_len = outlen; mylog("simple output=%s(%d)\n", dest, outlen); return dest; } /* * PostgreSQL needs 2 '\\' to escape '_' and '%'. */ static char * adjustLikePattern(const SQLCHAR *src, int srclen, char escape_ch, int *result_len, const ConnectionClass *conn) { int i, outlen; const char *in; char *dest = NULL, escape_in_literal = CC_get_escape(conn); BOOL escape_in = FALSE; encoded_str encstr; if (result_len) *result_len = 0; if (!src || srclen == SQL_NULL_DATA) return dest; else if (srclen == SQL_NTS) srclen = (int) strlen((char *) src); /* if (srclen <= 0) */ if (srclen < 0) return dest; mylog("adjust in=%.*s(%d)\n", srclen, src, srclen); encoded_str_constr(&encstr, conn->ccsc, (char *) src); dest = malloc(2 * srclen + 1); for (i = 0, in = (char *) src, outlen = 0; i < srclen; i++, in++) { encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) { dest[outlen++] = *in; continue; } if (escape_in) { switch (*in) { case '%': case '_': break; default: if (escape_ch == escape_in_literal) dest[outlen++] = escape_in_literal; dest[outlen++] = escape_ch; break; } } if (*in == escape_ch) { escape_in = TRUE; if (escape_ch == escape_in_literal) dest[outlen++] = escape_in_literal; /* insert 1 more LEXER escape */ } else { escape_in = FALSE; if (LITERAL_QUOTE == *in) dest[outlen++] = *in; } dest[outlen++] = *in; } if (escape_in) { if (escape_ch == escape_in_literal) dest[outlen++] = escape_in_literal; dest[outlen++] = escape_ch; } dest[outlen] = '\0'; if (result_len) *result_len = outlen; mylog("adjust output=%s(%d)\n", dest, outlen); return dest; } #define CSTR_SYS_TABLE "SYSTEM TABLE" #define CSTR_TABLE "TABLE" #define CSTR_VIEW "VIEW" CSTR like_op_sp = "like "; CSTR like_op_ext = "like E"; CSTR eq_op_sp = "= "; CSTR eq_op_ext = "= E"; #define IS_VALID_NAME(str) ((str) && (str)[0]) static const char *gen_opestr(const char *orig_opestr, const ConnectionClass * conn) { BOOL addE = (0 != CC_get_escape(conn) && PG_VERSION_GE(conn, 8.1)); if (0 == strcmp(orig_opestr, eqop)) return (addE ? eq_op_ext : eq_op_sp); return (addE ? like_op_ext : like_op_sp); } /* * If specified schema name == user_name and the current schema is * 'public', allowed to use the 'public' schema. */ static BOOL allow_public_schema(ConnectionClass *conn, const SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName) { const char *user = CC_get_username(conn); size_t userlen = strlen(user); if (NULL == szSchemaName) return FALSE; if (SQL_NTS == cbSchemaName) cbSchemaName = strlen((char *) szSchemaName); return (cbSchemaName == (SQLSMALLINT) userlen && strnicmp((char *) szSchemaName, user, userlen) == 0 && stricmp(CC_get_current_schema(conn), (char *) pubstr) == 0); } RETCODE SQL_API PGAPI_Tables(HSTMT hstmt, const SQLCHAR FAR * szTableQualifier, /* PV X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* PV E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* PV E*/ SQLSMALLINT cbTableName, const SQLCHAR FAR * szTableType, SQLSMALLINT cbTableType, UWORD flag) { CSTR func = "PGAPI_Tables"; StatementClass *stmt = (StatementClass *) hstmt; StatementClass *tbl_stmt; QResultClass *res; TupleField *tuple; HSTMT htbl_stmt = NULL; RETCODE ret = SQL_ERROR, result; int result_cols; char *tableType = NULL; char tables_query[INFO_INQUIRY_LEN]; char table_name[MAX_INFO_STRING], table_owner[MAX_INFO_STRING], relkind_or_hasrules[MAX_INFO_STRING]; #ifdef HAVE_STRTOK_R char *last; #endif /* HAVE_STRTOK_R */ ConnectionClass *conn; ConnInfo *ci; char *escCatName = NULL, *escSchemaName = NULL, *escTableName = NULL; /* Support up to 32 system table prefixes. Should be more than enough. */ #define MAX_PREFIXES 32 char *prefix[MAX_PREFIXES], prefixes[MEDIUM_REGISTRY_LEN]; int nprefixes; char show_system_tables, show_regular_tables, show_views; char regular_table, view, systable; int i; SQLSMALLINT internal_asis_type = SQL_C_CHAR, cbSchemaName; const char *like_or_eq, *op_string; const SQLCHAR *szSchemaName; BOOL search_pattern; BOOL list_cat = FALSE, list_schemas = FALSE, list_table_types = FALSE, list_some = FALSE; SQLLEN cbRelname, cbRelkind, cbSchName; mylog("%s: entering...stmt=%p scnm=%p len=%d\n", func, stmt, szTableOwner, cbTableOwner); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); ci = &(conn->connInfo); result = PGAPI_AllocStmt(conn, &htbl_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for PGAPI_Tables result.", func); return SQL_ERROR; } tbl_stmt = (StatementClass *) htbl_stmt; szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; #define return DONT_CALL_RETURN_FROM_HERE??? search_pattern = (0 == (flag & PODBC_NOT_SEARCH_PATTERN)); if (search_pattern) { like_or_eq = likeop; escCatName = adjustLikePattern(szTableQualifier, cbTableQualifier, SEARCH_PATTERN_ESCAPE, NULL, conn); escTableName = adjustLikePattern(szTableName, cbTableName, SEARCH_PATTERN_ESCAPE, NULL, conn); } else { like_or_eq = eqop; escCatName = simpleCatalogEscape(szTableQualifier, cbTableQualifier, NULL, conn); escTableName = simpleCatalogEscape(szTableName, cbTableName, NULL, conn); } retry_public_schema: if (escSchemaName) free(escSchemaName); if (search_pattern) escSchemaName = adjustLikePattern(szSchemaName, cbSchemaName, SEARCH_PATTERN_ESCAPE, NULL, conn); else escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, NULL, conn); /* * Create the query to find out the tables */ /* make_string mallocs memory */ tableType = make_string(szTableType, cbTableType, NULL, 0); #if (ODBCVER >= 0x0300) if (search_pattern && escTableName && '\0' == escTableName[0] && escCatName && escSchemaName) { if ('\0' == escSchemaName[0]) { if (stricmp(escCatName, SQL_ALL_CATALOGS) == 0) list_cat = TRUE; else if ('\0' == escCatName[0] && stricmp(tableType, SQL_ALL_TABLE_TYPES) == 0) list_table_types = TRUE; } else if ('\0' == escCatName[0] && stricmp(escSchemaName, SQL_ALL_SCHEMAS) == 0) list_schemas = TRUE; } #endif /* ODBCVER */ list_some = (list_cat || list_schemas || list_table_types); tables_query[0] = '\0'; if (list_cat) strncpy_null(tables_query, "select NULL, NULL, NULL", sizeof(tables_query)); else if (list_table_types) strncpy_null(tables_query, "select NULL, NULL, relkind from (select 'r' as relkind union select 'v') as a", sizeof(tables_query)); else if (list_schemas) { if (conn->schema_support) strncpy_null(tables_query, "select NULL, nspname, NULL" " from pg_catalog.pg_namespace n where true", sizeof(tables_query)); else strncpy_null(tables_query, "select NULL, NULL as nspname, NULL", sizeof(tables_query)); } else if (conn->schema_support) { /* view is represented by its relkind since 7.1 */ strcpy(tables_query, "select relname, nspname, relkind" " from pg_catalog.pg_class c, pg_catalog.pg_namespace n"); strcat(tables_query, " where relkind in ('r', 'v')"); } else if (PG_VERSION_GE(conn, 7.1)) { /* view is represented by its relkind since 7.1 */ strcpy(tables_query, "select relname, usename, relkind" " from pg_class c, pg_user u"); strcat(tables_query, " where relkind in ('r', 'v')"); } else { strcpy(tables_query, "select relname, usename, relhasrules from pg_class c, pg_user u"); strcat(tables_query, " where relkind = 'r'"); } op_string = gen_opestr(like_or_eq, conn); if (!list_some) { if (conn->schema_support) { schema_strcat1(tables_query, " and nspname %s'%.*s'", op_string, escSchemaName, SQL_NTS, szTableName, cbTableName, conn); /* strcat(tables_query, " and pg_catalog.pg_table_is_visible(c.oid)"); */ } else { if (IS_VALID_NAME(escSchemaName)) snprintf_add(tables_query, sizeof(tables_query), " and usename %s'%s'", op_string, escSchemaName); } if (IS_VALID_NAME(escTableName)) snprintf_add(tables_query, sizeof(tables_query), " and relname %s'%s'", op_string, escTableName); } /* * Parse the extra systable prefix configuration variable into an array * of prefixes. */ strcpy(prefixes, ci->drivers.extra_systable_prefixes); for (i = 0; i < MAX_PREFIXES; i++) { char *str = (i == 0) ? prefixes : NULL; #ifdef HAVE_STRTOK_R prefix[i] = strtok_r(str, ";", &last); #else prefix[i] = strtok(str, ";"); #endif /* HAVE_STRTOK_R */ if (prefix[i] == NULL) break; } nprefixes = i; /* Parse the desired table types to return */ show_system_tables = FALSE; show_regular_tables = FALSE; show_views = FALSE; /* TABLE_TYPE */ if (!tableType) { show_regular_tables = TRUE; show_views = TRUE; } #if (ODBCVER >= 0x0300) else if (list_some || stricmp(tableType, SQL_ALL_TABLE_TYPES) == 0) { show_regular_tables = TRUE; show_views = TRUE; } #endif /* ODBCVER */ else { /* Check for desired table types to return */ char *srcstr; for (srcstr = tableType;; srcstr = NULL) { char *typestr; #ifdef HAVE_STRTOK_R typestr = strtok_r(srcstr, ",", &last); #else typestr = strtok(srcstr, ","); #endif /* HAVE_STRTOK_R */ if (typestr == NULL) break; while (isspace((unsigned char) *typestr)) typestr++; if (*typestr == '\'') typestr++; if (strnicmp(typestr, CSTR_SYS_TABLE, strlen(CSTR_SYS_TABLE)) == 0) show_system_tables = TRUE; else if (strnicmp(typestr, CSTR_TABLE, strlen(CSTR_TABLE)) == 0) show_regular_tables = TRUE; else if (strnicmp(typestr, CSTR_VIEW, strlen(CSTR_VIEW)) == 0) show_views = TRUE; } } /* * If not interested in SYSTEM TABLES then filter them out to save * some time on the query. If treating system tables as regular * tables, then dont filter either. */ if ((list_schemas || !list_some) && !atoi(ci->show_system_tables) && !show_system_tables) { if (conn->schema_support) strcat(tables_query, " and nspname not in ('pg_catalog', 'information_schema', 'pg_toast', 'pg_temp_1')"); else if (!list_schemas) { strcat(tables_query, " and relname !~ '^" POSTGRES_SYS_PREFIX); /* Also filter out user-defined system table types */ for (i = 0; i < nprefixes; i++) { strcat(tables_query, "|^"); strcat(tables_query, prefix[i]); } strcat(tables_query, "'"); } } if (!list_some) { if (CC_accessible_only(conn)) strcat(tables_query, " and has_table_privilege(c.oid, 'select')"); } if (list_schemas) strcat(tables_query, " order by nspname"); else if (list_some) ; else if (conn->schema_support) strcat(tables_query, " and n.oid = relnamespace order by nspname, relname"); else { /* match users */ if (PG_VERSION_LT(conn, 7.1)) /* filter out large objects in older versions */ strcat(tables_query, " and relname !~ '^xinv[0-9]+'"); strcat(tables_query, " and usesysid = relowner order by relname"); } result = PGAPI_ExecDirect(htbl_stmt, (SQLCHAR *) tables_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, htbl_stmt, FALSE); goto cleanup; } /* If not found */ if (conn->schema_support && (res = SC_get_Result(tbl_stmt)) && 0 == QR_get_num_total_tuples(res)) { if (allow_public_schema(conn, szSchemaName, cbSchemaName)) { szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } } #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ result = PGAPI_BindCol(htbl_stmt, 1, internal_asis_type, table_name, MAX_INFO_STRING, &cbRelname); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 2, internal_asis_type, table_owner, MAX_INFO_STRING, &cbSchName); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 3, internal_asis_type, relkind_or_hasrules, MAX_INFO_STRING, &cbRelkind); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_Tables result.", func); goto cleanup; } SC_set_Result(stmt, res); /* the binding structure for a statement is not set up until */ /* * a statement is actually executed, so we'll have to do this * ourselves. */ result_cols = NUM_OF_TABLES_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; /* set the field names */ QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, TABLES_CATALOG_NAME, "TABLE_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, TABLES_SCHEMA_NAME, "TABLE_OWNER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, TABLES_TABLE_NAME, "TABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, TABLES_TABLE_TYPE, "TABLE_TYPE", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, TABLES_REMARKS, "REMARKS", PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); /* add the tuples */ table_name[0] = '\0'; table_owner[0] = '\0'; result = PGAPI_Fetch(htbl_stmt); while (SQL_SUCCEEDED(result)) { /* * Determine if this table name is a system table. If treating * system tables as regular tables, then no need to do this test. */ systable = FALSE; if (!atoi(ci->show_system_tables)) { if (conn->schema_support) { if (stricmp(table_owner, "pg_catalog") == 0 || stricmp(table_owner, "pg_toast") == 0 || strnicmp(table_owner, "pg_temp_", 8) == 0 || stricmp(table_owner, "information_schema") == 0) systable = TRUE; } else if (strncmp(table_name, POSTGRES_SYS_PREFIX, strlen(POSTGRES_SYS_PREFIX)) == 0) systable = TRUE; else { /* Check extra system table prefixes */ for (i = 0; i < nprefixes; i++) { mylog("table_name='%s', prefix[%d]='%s'\n", table_name, i, prefix[i]); if (strncmp(table_name, prefix[i], strlen(prefix[i])) == 0) { systable = TRUE; break; } } } } /* Determine if the table name is a view */ if (PG_VERSION_GE(conn, 7.1)) /* view is represented by its relkind since 7.1 */ view = (relkind_or_hasrules[0] == 'v'); else view = (relkind_or_hasrules[0] == '1'); /* It must be a regular table */ regular_table = (!systable && !view); /* Include the row in the result set if meets all criteria */ /* * NOTE: Unsupported table types (i.e., LOCAL TEMPORARY, ALIAS, * etc) will return nothing */ if ((systable && show_system_tables) || (view && show_views) || (regular_table && show_regular_tables)) { tuple = QR_AddNew(res); if (list_cat || !list_some) set_tuplefield_string(&tuple[TABLES_CATALOG_NAME], CurrCat(conn)); else set_tuplefield_null(&tuple[TABLES_CATALOG_NAME]); /* * I have to hide the table owner from Access, otherwise it * insists on referring to the table as 'owner.table'. (this * is valid according to the ODBC SQL grammar, but Postgres * won't support it.) * * set_tuplefield_string(&tuple[TABLES_SCHEMA_NAME], table_owner); */ mylog("%s: table_name = '%s'\n", func, table_name); if (list_schemas || (conn->schema_support && !list_some)) set_tuplefield_string(&tuple[TABLES_SCHEMA_NAME], GET_SCHEMA_NAME(table_owner)); else set_tuplefield_null(&tuple[TABLES_SCHEMA_NAME]); if (list_some) set_tuplefield_null(&tuple[TABLES_TABLE_NAME]); else set_tuplefield_string(&tuple[TABLES_TABLE_NAME], table_name); if (list_table_types || !list_some) set_tuplefield_string(&tuple[TABLES_TABLE_TYPE], systable ? "SYSTEM TABLE" : (view ? "VIEW" : "TABLE")); else set_tuplefield_null(&tuple[TABLES_TABLE_TYPE]); set_tuplefield_string(&tuple[TABLES_REMARKS], NULL_STRING); /*** set_tuplefield_string(&tuple[TABLES_REMARKS], "TABLE"); ***/ } result = PGAPI_Fetch(htbl_stmt); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, htbl_stmt, FALSE); goto cleanup; } ret = SQL_SUCCESS; cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; if (escCatName) free(escCatName); if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (tableType) free(tableType); /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (htbl_stmt) PGAPI_FreeStmt(htbl_stmt, SQL_DROP); if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); mylog("%s: EXIT, stmt=%p, ret=%d\n", func, stmt, ret); return ret; } RETCODE SQL_API PGAPI_Columns(HSTMT hstmt, const SQLCHAR FAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* PV E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* PV E*/ SQLSMALLINT cbTableName, const SQLCHAR FAR * szColumnName, /* PV E*/ SQLSMALLINT cbColumnName, UWORD flag, OID reloid, Int2 attnum) { CSTR func = "PGAPI_Columns"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; TupleField *tuple; HSTMT hcol_stmt = NULL; StatementClass *col_stmt; char columns_query[INFO_INQUIRY_LEN]; RETCODE result; char table_owner[MAX_INFO_STRING], table_name[MAX_INFO_STRING], field_name[MAX_INFO_STRING], field_type_name[MAX_INFO_STRING]; Int2 field_number, sqltype, concise_type, result_cols; Int4 mod_length, ordinal, typmod, relhasoids; OID field_type, the_type, greloid, basetype; #ifdef USE_OLD_IMPL Int2 decimal_digits; Int4 field_length, column_size; char useStaticPrecision, useStaticScale; #endif /* USE_OLD_IMPL */ char not_null[MAX_INFO_STRING], relhasrules[MAX_INFO_STRING], relkind[8]; char *escSchemaName = NULL, *escTableName = NULL, *escColumnName = NULL; BOOL search_pattern = TRUE, search_by_ids, relisaview; ConnInfo *ci; ConnectionClass *conn; SQLSMALLINT internal_asis_type = SQL_C_CHAR, cbSchemaName; const char *like_or_eq = likeop, *op_string; const SQLCHAR *szSchemaName; BOOL setIdentity = FALSE; mylog("%s: entering...stmt=%p scnm=%p len=%d\n", func, stmt, szTableOwner, cbTableOwner); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); ci = &(conn->connInfo); #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ #define return DONT_CALL_RETURN_FROM_HERE??? search_by_ids = ((flag & PODBC_SEARCH_BY_IDS) != 0); if (search_by_ids) { szSchemaName = NULL; cbSchemaName = SQL_NULL_DATA; } else { szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; reloid = 0; attnum = 0; /* * TableName or ColumnName is ordinarily an pattern value, */ search_pattern = ((flag & PODBC_NOT_SEARCH_PATTERN) == 0); if (search_pattern) { like_or_eq = likeop; escTableName = adjustLikePattern(szTableName, cbTableName, SEARCH_PATTERN_ESCAPE, NULL, conn); escColumnName = adjustLikePattern(szColumnName, cbColumnName, SEARCH_PATTERN_ESCAPE, NULL, conn); } else { like_or_eq = eqop; escTableName = simpleCatalogEscape(szTableName, cbTableName, NULL, conn); escColumnName = simpleCatalogEscape(szColumnName, cbColumnName, NULL, conn); } } retry_public_schema: if (!search_by_ids) { if (escSchemaName) free(escSchemaName); if (search_pattern) escSchemaName = adjustLikePattern(szSchemaName, cbSchemaName, SEARCH_PATTERN_ESCAPE, NULL, conn); else escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, NULL, conn); } /* * Create the query to find out the columns (Note: pre 6.3 did not * have the atttypmod field) */ op_string = gen_opestr(like_or_eq, conn); if (conn->schema_support) { snprintf(columns_query, sizeof(columns_query), "select n.nspname, c.relname, a.attname, a.atttypid" ", t.typname, a.attnum, a.attlen, a.atttypmod, a.attnotnull" ", c.relhasrules, c.relkind, c.oid, %s, %s, %s" " from (((pg_catalog.pg_class c" " inner join pg_catalog.pg_namespace n on n.oid = c.relnamespace", PG_VERSION_GE(conn, 7.4) ? "pg_get_expr(d.adbin, d.adrelid)" : "d.adsrc", PG_VERSION_GE(conn, 7.4) ? "case t.typtype when 'd' then t.typbasetype else 0 end, t.typtypmod" : "0, -1", PG_VERSION_GE(conn, 7.2) ? "c.relhasoids" : "1" ); if (search_by_ids) snprintf_add(columns_query, sizeof(columns_query), " and c.oid = %u", reloid); else { if (escTableName) snprintf_add(columns_query, sizeof(columns_query), " and c.relname %s'%s'", op_string, escTableName); schema_strcat1(columns_query, " and n.nspname %s'%.*s'", op_string, escSchemaName, SQL_NTS, szTableName, cbTableName, conn); } strcat(columns_query, ") inner join pg_catalog.pg_attribute a" " on (not a.attisdropped)"); if (0 == attnum && (NULL == escColumnName || like_or_eq != eqop)) strcat(columns_query, " and a.attnum > 0"); if (search_by_ids) { if (attnum != 0) snprintf_add(columns_query, sizeof(columns_query), " and a.attnum = %d", attnum); } else if (escColumnName) snprintf_add(columns_query, sizeof(columns_query), " and a.attname %s'%s'", op_string, escColumnName); strcat(columns_query, " and a.attrelid = c.oid) inner join pg_catalog.pg_type t" " on t.oid = a.atttypid) left outer join pg_attrdef d" " on a.atthasdef and d.adrelid = a.attrelid and d.adnum = a.attnum"); strcat(columns_query, " order by n.nspname, c.relname, attnum"); } else { snprintf(columns_query, sizeof(columns_query), "select u.usename, c.relname, a.attname, a.atttypid" ", t.typname, a.attnum, a.attlen, %s, a.attnotnull" ", c.relhasrules, c.relkind, c.oid, NULL, 0, -1 from" " pg_user u, pg_class c, pg_attribute a, pg_type t where" " u.usesysid = c.relowner and c.oid= a.attrelid" " and a.atttypid = t.oid and (a.attnum > 0)", PG_VERSION_LE(conn, 6.2) ? "a.attlen" : "a.atttypmod"); if (escTableName) snprintf_add(columns_query, sizeof(columns_query), " and c.relname %s'%s'", op_string, escTableName); if (IS_VALID_NAME(escSchemaName)) snprintf_add(columns_query, sizeof(columns_query), " and u.usename %s'%s'", op_string, escSchemaName); if (escColumnName) snprintf_add(columns_query, sizeof(columns_query), " and a.attname %s'%s'", op_string, escColumnName); strcat(columns_query, " order by c.relname, attnum"); } result = PGAPI_AllocStmt(conn, &hcol_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for PGAPI_Columns result.", func); result = SQL_ERROR; goto cleanup; } col_stmt = (StatementClass *) hcol_stmt; mylog("%s: hcol_stmt = %p, col_stmt = %p\n", func, hcol_stmt, col_stmt); col_stmt->internal = TRUE; result = PGAPI_ExecDirect(hcol_stmt, (SQLCHAR *) columns_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, col_stmt, FALSE); goto cleanup; } /* If not found */ if (conn->schema_support && (flag & PODBC_SEARCH_PUBLIC_SCHEMA) != 0 && (res = SC_get_Result(col_stmt)) && 0 == QR_get_num_total_tuples(res)) { if (!search_by_ids && allow_public_schema(conn, szSchemaName, cbSchemaName)) { PGAPI_FreeStmt(hcol_stmt, SQL_DROP); hcol_stmt = NULL; szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } } result = PGAPI_BindCol(hcol_stmt, 1, internal_asis_type, table_owner, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 2, internal_asis_type, table_name, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 3, internal_asis_type, field_name, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 4, SQL_C_ULONG, &field_type, 4, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 5, internal_asis_type, field_type_name, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 6, SQL_C_SHORT, &field_number, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } #ifdef NOT_USED result = PGAPI_BindCol(hcol_stmt, 7, SQL_C_LONG, &field_length, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } #endif /* NOT_USED */ result = PGAPI_BindCol(hcol_stmt, 8, SQL_C_LONG, &mod_length, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 9, internal_asis_type, not_null, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 10, internal_asis_type, relhasrules, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 11, internal_asis_type, relkind, sizeof(relkind), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 12, SQL_C_LONG, &greloid, sizeof(greloid), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 14, SQL_C_ULONG, &basetype, sizeof(basetype), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 15, SQL_C_LONG, &typmod, sizeof(typmod), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 16, SQL_C_LONG, &relhasoids, sizeof(relhasoids), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_Columns result.", func); goto cleanup; } SC_set_Result(stmt, res); /* the binding structure for a statement is not set up until */ /* * a statement is actually executed, so we'll have to do this * ourselves. */ result_cols = NUM_OF_COLUMNS_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); /* * Setting catalog_result here affects the behavior of * pgtype_xxx() functions. So set it later. * stmt->catalog_result = TRUE; */ /* set the field names */ QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, COLUMNS_CATALOG_NAME, "TABLE_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, COLUMNS_SCHEMA_NAME, "TABLE_OWNER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, COLUMNS_TABLE_NAME, "TABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, COLUMNS_COLUMN_NAME, "COLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, COLUMNS_DATA_TYPE, "DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, COLUMNS_TYPE_NAME, "TYPE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, COLUMNS_PRECISION, "PRECISION", PG_TYPE_INT4, 4); /* COLUMN_SIZE */ QR_set_field_info_v(res, COLUMNS_LENGTH, "LENGTH", PG_TYPE_INT4, 4); /* BUFFER_LENGTH */ QR_set_field_info_v(res, COLUMNS_SCALE, "SCALE", PG_TYPE_INT2, 2); /* DECIMAL_DIGITS ***/ QR_set_field_info_v(res, COLUMNS_RADIX, "RADIX", PG_TYPE_INT2, 2); QR_set_field_info_v(res, COLUMNS_NULLABLE, "NULLABLE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, COLUMNS_REMARKS, "REMARKS", PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); #if (ODBCVER >= 0x0300) QR_set_field_info_v(res, COLUMNS_COLUMN_DEF, "COLUMN_DEF", PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); QR_set_field_info_v(res, COLUMNS_SQL_DATA_TYPE, "SQL_DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, COLUMNS_SQL_DATETIME_SUB, "SQL_DATETIME_SUB", PG_TYPE_INT2, 2); QR_set_field_info_v(res, COLUMNS_CHAR_OCTET_LENGTH, "CHAR_OCTET_LENGTH", PG_TYPE_INT4, 4); QR_set_field_info_v(res, COLUMNS_ORDINAL_POSITION, "ORDINAL_POSITION", PG_TYPE_INT4, 4); QR_set_field_info_v(res, COLUMNS_IS_NULLABLE, "IS_NULLABLE", PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); #endif /* ODBCVER */ /* User defined fields */ QR_set_field_info_v(res, COLUMNS_DISPLAY_SIZE, "DISPLAY_SIZE", PG_TYPE_INT4, 4); QR_set_field_info_v(res, COLUMNS_FIELD_TYPE, "FIELD_TYPE", PG_TYPE_INT4, 4); QR_set_field_info_v(res, COLUMNS_AUTO_INCREMENT, "AUTO_INCREMENT", PG_TYPE_INT4, 4); QR_set_field_info_v(res, COLUMNS_PHYSICAL_NUMBER, "PHYSICAL NUMBER", PG_TYPE_INT2, 2); QR_set_field_info_v(res, COLUMNS_TABLE_OID, "TABLE OID", PG_TYPE_OID, 4); QR_set_field_info_v(res, COLUMNS_BASE_TYPEID, "BASE TYPEID", PG_TYPE_OID, 4); QR_set_field_info_v(res, COLUMNS_ATTTYPMOD, "TYPMOD", PG_TYPE_INT4, 4); ordinal = 1; result = PGAPI_Fetch(hcol_stmt); /* * Only show oid if option AND there are other columns AND it's not * being called by SQLStatistics . Always show OID if it's a system * table */ if (PG_VERSION_GE(conn, 7.1)) relisaview = (relkind[0] == 'v'); else relisaview = (relhasrules[0] == '1'); if (result != SQL_ERROR && !stmt->internal) { if (!relisaview && relhasoids && (atoi(ci->show_oid_column) || strncmp(table_name, POSTGRES_SYS_PREFIX, strlen(POSTGRES_SYS_PREFIX)) == 0) && (NULL == escColumnName || 0 == strcmp(escColumnName, OID_NAME))) { /* For OID fields */ the_type = PG_TYPE_OID; tuple = QR_AddNew(res); set_tuplefield_string(&tuple[COLUMNS_CATALOG_NAME], CurrCat(conn)); /* see note in SQLTables() */ if (conn->schema_support) set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], GET_SCHEMA_NAME(table_owner)); else set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], NULL_STRING); set_tuplefield_string(&tuple[COLUMNS_TABLE_NAME], table_name); set_tuplefield_string(&tuple[COLUMNS_COLUMN_NAME], OID_NAME); sqltype = pgtype_to_concise_type(stmt, the_type, PG_STATIC); set_tuplefield_int2(&tuple[COLUMNS_DATA_TYPE], sqltype); if (CC_fake_mss(conn)) { set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], "OID identity"); setIdentity = TRUE; } else set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], "OID"); set_tuplefield_int4(&tuple[COLUMNS_PRECISION], pgtype_column_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], pgtype_buffer_length(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_nullfield_int2(&tuple[COLUMNS_SCALE], pgtype_decimal_digits(stmt, the_type, PG_STATIC)); set_nullfield_int2(&tuple[COLUMNS_RADIX], pgtype_radix(conn, the_type)); set_tuplefield_int2(&tuple[COLUMNS_NULLABLE], SQL_NO_NULLS); set_tuplefield_string(&tuple[COLUMNS_REMARKS], NULL_STRING); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[COLUMNS_COLUMN_DEF]); set_tuplefield_int2(&tuple[COLUMNS_SQL_DATA_TYPE], sqltype); set_tuplefield_null(&tuple[COLUMNS_SQL_DATETIME_SUB]); set_tuplefield_null(&tuple[COLUMNS_CHAR_OCTET_LENGTH]); set_tuplefield_int4(&tuple[COLUMNS_ORDINAL_POSITION], ordinal); set_tuplefield_string(&tuple[COLUMNS_IS_NULLABLE], "No"); #endif /* ODBCVER */ set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], pgtype_display_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_FIELD_TYPE], the_type); set_tuplefield_int4(&tuple[COLUMNS_AUTO_INCREMENT], TRUE); set_tuplefield_int2(&tuple[COLUMNS_PHYSICAL_NUMBER], OID_ATTNUM); set_tuplefield_int4(&tuple[COLUMNS_TABLE_OID], greloid); set_tuplefield_int4(&tuple[COLUMNS_BASE_TYPEID], 0); set_tuplefield_int4(&tuple[COLUMNS_ATTTYPMOD], -1); ordinal++; } } while (SQL_SUCCEEDED(result)) { int auto_unique; SQLLEN len_needed; char *attdef; attdef = NULL; PGAPI_SetPos(hcol_stmt, 1, SQL_POSITION, 0); PGAPI_GetData(hcol_stmt, 13, internal_asis_type, NULL, 0, &len_needed); if (len_needed > 0) { mylog("len_needed=%d\n", len_needed); attdef = malloc(len_needed + 1); PGAPI_GetData(hcol_stmt, 13, internal_asis_type, attdef, len_needed + 1, &len_needed); mylog(" and the data=%s\n", attdef); } tuple = QR_AddNew(res); sqltype = SQL_TYPE_NULL; /* unspecified */ set_tuplefield_string(&tuple[COLUMNS_CATALOG_NAME], CurrCat(conn)); /* see note in SQLTables() */ if (conn->schema_support) set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], GET_SCHEMA_NAME(table_owner)); else set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], NULL_STRING); set_tuplefield_string(&tuple[COLUMNS_TABLE_NAME], table_name); set_tuplefield_string(&tuple[COLUMNS_COLUMN_NAME], field_name); auto_unique = SQL_FALSE; if (field_type = pg_true_type(conn, field_type, basetype), field_type == basetype) mod_length = typmod; switch (field_type) { case PG_TYPE_OID: if (0 != atoi(ci->fake_oid_index)) { auto_unique = SQL_TRUE; set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], "identity"); break; } case PG_TYPE_INT4: case PG_TYPE_INT8: if (attdef && strnicmp(attdef, "nextval(", 8) == 0 && not_null[0] != '0') { auto_unique = SQL_TRUE; if (!setIdentity && CC_fake_mss(conn)) { char tmp[32]; snprintf(tmp, sizeof(tmp), "%s identity", field_type_name); set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], tmp); break; } } default: set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], field_type_name); break; } /*---------- * Some Notes about Postgres Data Types: * * VARCHAR - the length is stored in the pg_attribute.atttypmod field * BPCHAR - the length is also stored as varchar is * * NUMERIC - the decimal_digits is stored in atttypmod as follows: * * column_size =((atttypmod - VARHDRSZ) >> 16) & 0xffff * decimal_digits = (atttypmod - VARHDRSZ) & 0xffff * *---------- */ qlog("%s: table='%s',field_name='%s',type=%d,name='%s'\n", func, table_name, field_name, field_type, field_type_name); #ifdef USE_OLD_IMPL useStaticPrecision = TRUE; useStaticScale = TRUE; if (field_type == PG_TYPE_NUMERIC) { if (mod_length >= 4) mod_length -= 4; /* the length is in atttypmod - 4 */ if (mod_length >= 0) { useStaticPrecision = FALSE; useStaticScale = FALSE; column_size = (mod_length >> 16) & 0xffff; decimal_digits = mod_length & 0xffff; mylog("%s: field type is NUMERIC: field_type = %d, mod_length=%d, precision=%d, scale=%d\n", func, field_type, mod_length, column_size, decimal_digits); set_tuplefield_int4(&tuple[COLUMNS_PRECISION], column_size); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], column_size + 2); /* sign+dec.point */ set_nullfield_int2(&tuple[COLUMNS_SCALE], decimal_digits); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[COLUMNS_CHAR_OCTET_LENGTH]); #endif /* ODBCVER */ set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], column_size + 2); /* sign+dec.point */ } } else if ((field_type == PG_TYPE_DATETIME) || (field_type == PG_TYPE_TIMESTAMP_NO_TMZONE)) { if (PG_VERSION_GE(conn, 7.2)) { useStaticScale = FALSE; set_nullfield_int2(&tuple[COLUMNS_SCALE], (Int2) mod_length); } } if ((field_type == PG_TYPE_VARCHAR) || (field_type == PG_TYPE_BPCHAR)) { useStaticPrecision = FALSE; if (mod_length >= 4) mod_length -= 4; /* the length is in atttypmod - 4 */ /* if (mod_length > ci->drivers.max_varchar_size || mod_length <= 0) */ if (mod_length <= 0) mod_length = ci->drivers.max_varchar_size; #ifdef __MS_REPORTS_ANSI_CHAR__ if (mod_length > ci->drivers.max_varchar_size) sqltype = SQL_LONGVARCHAR; else sqltype = (field_type == PG_TYPE_BPCHAR) ? SQL_CHAR : SQL_VARCHAR; #else if (mod_length > ci->drivers.max_varchar_size) sqltype = (ALLOW_WCHAR(conn) ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR); else sqltype = (field_type == PG_TYPE_BPCHAR) ? (ALLOW_WCHAR(conn) ? SQL_WCHAR : SQL_CHAR) : (ALLOW_WCHAR(conn) ? SQL_WVARCHAR : SQL_VARCHAR); #endif /* __MS_LOVES_REPORTS_CHAR__ */ mylog("%s: field type is VARCHAR,BPCHAR: field_type = %d, mod_length = %d\n", func, field_type, mod_length); set_tuplefield_int4(&tuple[COLUMNS_PRECISION], mod_length); field_length = mod_length; #ifdef UNICODE_SUPPORT if (0 < field_length && ALLOW_WCHAR(conn)) field_length *= WCLEN; #endif /* UNICODE_SUPPORT */ set_tuplefield_int4(&tuple[COLUMNS_LENGTH], field_length); #if (ODBCVER >= 0x0300) set_tuplefield_int4(&tuple[COLUMNS_CHAR_OCTET_LENGTH], pgtype_transfer_octet_length(conn, field_type, mod_length)); #endif /* ODBCVER */ set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], mod_length); } if (useStaticPrecision) { mylog("%s: field type is OTHER: field_type = %d, pgtype_length = %d\n", func, field_type, pgtype_buffer_length(stmt, field_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_PRECISION], pgtype_column_size(stmt, field_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], pgtype_buffer_length(stmt, field_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[COLUMNS_CHAR_OCTET_LENGTH]); #endif /* ODBCVER */ set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], pgtype_display_size(stmt, field_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); } if (useStaticScale) { set_nullfield_int2(&tuple[COLUMNS_SCALE], pgtype_decimal_digits(stmt, field_type, PG_STATIC)); } if (SQL_TYPE_NULL == sqltype) { sqltype = pgtype_attr_to_concise_type(conn, field_type, mod_length, -1); concise_type = pgtype_attr_to_sqldesctype(conn, field_type, mod_length); } else concise_type = sqltype; #else /* USE_OLD_IMPL */ /* Subtract the header length */ switch (field_type) { case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIME: case PG_TYPE_TIME_WITH_TMZONE: case PG_TYPE_BIT: break; default: if (mod_length >= 4) mod_length -= 4; } set_tuplefield_int4(&tuple[COLUMNS_PRECISION], pgtype_attr_column_size(conn, field_type, mod_length, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], pgtype_attr_buffer_length(conn, field_type, mod_length, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], pgtype_attr_display_size(conn, field_type, mod_length, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); set_nullfield_int2(&tuple[COLUMNS_SCALE], pgtype_attr_decimal_digits(conn, field_type, mod_length, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); sqltype = pgtype_attr_to_concise_type(conn, field_type, mod_length, PG_UNSPECIFIED); concise_type = pgtype_attr_to_sqldesctype(conn, field_type, mod_length); #endif /* USE_OLD_IMPL */ set_tuplefield_int2(&tuple[COLUMNS_DATA_TYPE], sqltype); set_nullfield_int2(&tuple[COLUMNS_RADIX], pgtype_radix(conn, field_type)); set_tuplefield_int2(&tuple[COLUMNS_NULLABLE], (Int2) (not_null[0] != '0' ? SQL_NO_NULLS : pgtype_nullable(conn, field_type))); set_tuplefield_string(&tuple[COLUMNS_REMARKS], NULL_STRING); #if (ODBCVER >= 0x0300) if (attdef && strlen(attdef) > INFO_VARCHAR_SIZE) set_tuplefield_string(&tuple[COLUMNS_COLUMN_DEF], "TRUNCATE"); else set_tuplefield_string(&tuple[COLUMNS_COLUMN_DEF], attdef); set_tuplefield_int2(&tuple[COLUMNS_SQL_DATA_TYPE], concise_type); set_nullfield_int2(&tuple[COLUMNS_SQL_DATETIME_SUB], pgtype_attr_to_datetime_sub(conn, field_type, mod_length)); set_tuplefield_int4(&tuple[COLUMNS_CHAR_OCTET_LENGTH], pgtype_attr_transfer_octet_length(conn, field_type, mod_length, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_ORDINAL_POSITION], ordinal); set_tuplefield_null(&tuple[COLUMNS_IS_NULLABLE]); #endif /* ODBCVER */ set_tuplefield_int4(&tuple[COLUMNS_FIELD_TYPE], field_type); set_tuplefield_int4(&tuple[COLUMNS_AUTO_INCREMENT], auto_unique); set_tuplefield_int2(&tuple[COLUMNS_PHYSICAL_NUMBER], field_number); set_tuplefield_int4(&tuple[COLUMNS_TABLE_OID], greloid); set_tuplefield_int4(&tuple[COLUMNS_BASE_TYPEID], basetype); set_tuplefield_int4(&tuple[COLUMNS_ATTTYPMOD], mod_length); ordinal++; result = PGAPI_Fetch(hcol_stmt); if (attdef) free(attdef); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, col_stmt, FALSE); goto cleanup; } /* * Put the row version column at the end so it might not be mistaken * for a key field. */ if (!relisaview && !stmt->internal && atoi(ci->row_versioning)) { /* For Row Versioning fields */ the_type = PG_TYPE_INT4; tuple = QR_AddNew(res); set_tuplefield_string(&tuple[COLUMNS_CATALOG_NAME], CurrCat(conn)); if (conn->schema_support) set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], GET_SCHEMA_NAME(table_owner)); else set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], NULL_STRING); set_tuplefield_string(&tuple[COLUMNS_TABLE_NAME], table_name); set_tuplefield_string(&tuple[COLUMNS_COLUMN_NAME], "xmin"); sqltype = pgtype_to_concise_type(stmt, the_type, PG_STATIC); set_tuplefield_int2(&tuple[COLUMNS_DATA_TYPE], sqltype); set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], pgtype_to_name(stmt, the_type, PG_UNSPECIFIED, FALSE)); set_tuplefield_int4(&tuple[COLUMNS_PRECISION], pgtype_column_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], pgtype_buffer_length(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_nullfield_int2(&tuple[COLUMNS_SCALE], pgtype_decimal_digits(stmt, the_type, PG_STATIC)); set_nullfield_int2(&tuple[COLUMNS_RADIX], pgtype_radix(conn, the_type)); set_tuplefield_int2(&tuple[COLUMNS_NULLABLE], SQL_NO_NULLS); set_tuplefield_string(&tuple[COLUMNS_REMARKS], NULL_STRING); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[COLUMNS_COLUMN_DEF]); set_tuplefield_int2(&tuple[COLUMNS_SQL_DATA_TYPE], sqltype); set_tuplefield_null(&tuple[COLUMNS_SQL_DATETIME_SUB]); set_tuplefield_null(&tuple[COLUMNS_CHAR_OCTET_LENGTH]); set_tuplefield_int4(&tuple[COLUMNS_ORDINAL_POSITION], ordinal); set_tuplefield_string(&tuple[COLUMNS_IS_NULLABLE], "No"); #endif /* ODBCVER */ set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], pgtype_display_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[COLUMNS_FIELD_TYPE], the_type); set_tuplefield_int4(&tuple[COLUMNS_AUTO_INCREMENT], FALSE); set_tuplefield_int2(&tuple[COLUMNS_PHYSICAL_NUMBER], XMIN_ATTNUM); set_tuplefield_int4(&tuple[COLUMNS_TABLE_OID], greloid); set_tuplefield_int4(&tuple[COLUMNS_BASE_TYPEID], 0); set_tuplefield_int4(&tuple[COLUMNS_ATTTYPMOD], -1); ordinal++; } result = SQL_SUCCESS; cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; stmt->catalog_result = TRUE; /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (escColumnName) free(escColumnName); if (hcol_stmt) PGAPI_FreeStmt(hcol_stmt, SQL_DROP); if (stmt->internal) result = DiscardStatementSvp(stmt, result, FALSE); mylog("%s: EXIT, stmt=%p\n", func, stmt); return result; } RETCODE SQL_API PGAPI_SpecialColumns(HSTMT hstmt, SQLUSMALLINT fColType, const SQLCHAR FAR * szTableQualifier, SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, SQLUSMALLINT fScope, SQLUSMALLINT fNullable) { CSTR func = "PGAPI_SpecialColumns"; TupleField *tuple; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; QResultClass *res; HSTMT hcol_stmt = NULL; StatementClass *col_stmt; char columns_query[INFO_INQUIRY_LEN]; char *escSchemaName = NULL, *escTableName = NULL; RETCODE result = SQL_SUCCESS; char relhasrules[MAX_INFO_STRING], relkind[8], relhasoids[8]; BOOL relisaview; SQLSMALLINT internal_asis_type = SQL_C_CHAR, cbSchemaName; const SQLCHAR *szSchemaName; const char *eq_string; mylog("%s: entering...stmt=%p scnm=%p len=%d colType=%d scope=%d\n", func, stmt, szTableOwner, cbTableOwner, fColType, fScope); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; escTableName = simpleCatalogEscape(szTableName, cbTableName, NULL, conn); if (!escTableName) { SC_set_error(stmt, STMT_INVALID_NULL_ARG, "The table name is required", func); return SQL_ERROR; } #define return DONT_CALL_RETURN_FROM_HERE??? retry_public_schema: if (escSchemaName) free(escSchemaName); escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, NULL, conn); eq_string = gen_opestr(eqop, conn); /* * Create the query to find out if this is a view or not... */ strcpy(columns_query, "select c.relhasrules, c.relkind"); if (PG_VERSION_GE(conn, 7.2)) strcat(columns_query, ", c.relhasoids"); if (conn->schema_support) strcat(columns_query, " from pg_catalog.pg_namespace u," " pg_catalog.pg_class c where " "u.oid = c.relnamespace"); else strcat(columns_query, " from pg_user u, pg_class c where " "u.usesysid = c.relowner"); /* TableName cannot contain a string search pattern */ /* my_strcat(columns_query, " and c.relname = '%.*s'", szTableName, cbTableName); */ if (escTableName) snprintf_add(columns_query, sizeof(columns_query), " and c.relname %s'%s'", eq_string, escTableName); /* SchemaName cannot contain a string search pattern */ if (conn->schema_support) schema_strcat1(columns_query, " and u.nspname %s'%.*s'", eq_string, escSchemaName, SQL_NTS, szTableName, cbTableName, conn); else { if (IS_VALID_NAME(escSchemaName)) snprintf_add(columns_query, sizeof(columns_query), " and u.usename %s'%s'", eq_string, escSchemaName); } result = PGAPI_AllocStmt(conn, &hcol_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for SQLSpecialColumns result.", func); result = SQL_ERROR; goto cleanup; } col_stmt = (StatementClass *) hcol_stmt; mylog("%s: hcol_stmt = %p, col_stmt = %p\n", func, hcol_stmt, col_stmt); result = PGAPI_ExecDirect(hcol_stmt, (SQLCHAR *) columns_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, col_stmt, FALSE); result = SQL_ERROR; goto cleanup; } /* If not found */ if (conn->schema_support && (res = SC_get_Result(col_stmt)) && 0 == QR_get_num_total_tuples(res)) { if (allow_public_schema(conn, szSchemaName, cbSchemaName)) { PGAPI_FreeStmt(hcol_stmt, SQL_DROP); hcol_stmt = NULL; szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } } result = PGAPI_BindCol(hcol_stmt, 1, internal_asis_type, relhasrules, sizeof(relhasrules), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); result = SQL_ERROR; goto cleanup; } result = PGAPI_BindCol(hcol_stmt, 2, internal_asis_type, relkind, sizeof(relkind), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); result = SQL_ERROR; goto cleanup; } relhasoids[0] = '1'; if (PG_VERSION_GE(conn, 7.2)) { result = PGAPI_BindCol(hcol_stmt, 3, internal_asis_type, relhasoids, sizeof(relhasoids), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); result = SQL_ERROR; goto cleanup; } } result = PGAPI_Fetch(hcol_stmt); if (PG_VERSION_GE(conn, 7.1)) relisaview = (relkind[0] == 'v'); else relisaview = (relhasrules[0] == '1'); PGAPI_FreeStmt(hcol_stmt, SQL_DROP); hcol_stmt = NULL; res = QR_Constructor(); SC_set_Result(stmt, res); extend_column_bindings(SC_get_ARDF(stmt), 8); stmt->catalog_result = TRUE; QR_set_num_fields(res, 8); QR_set_field_info_v(res, 0, "SCOPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 1, "COLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 2, "DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 3, "TYPE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 4, "PRECISION", PG_TYPE_INT4, 4); QR_set_field_info_v(res, 5, "LENGTH", PG_TYPE_INT4, 4); QR_set_field_info_v(res, 6, "SCALE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, 7, "PSEUDO_COLUMN", PG_TYPE_INT2, 2); if (relisaview) { /* there's no oid for views */ if (fColType == SQL_BEST_ROWID) { goto cleanup; } else if (fColType == SQL_ROWVER) { Int2 the_type = PG_TYPE_TID; tuple = QR_AddNew(res); set_tuplefield_null(&tuple[0]); set_tuplefield_string(&tuple[1], "ctid"); set_tuplefield_int2(&tuple[2], pgtype_to_concise_type(stmt, the_type, PG_STATIC)); set_tuplefield_string(&tuple[3], pgtype_to_name(stmt, the_type, PG_UNSPECIFIED, FALSE)); set_tuplefield_int4(&tuple[4], pgtype_column_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[5], pgtype_buffer_length(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int2(&tuple[6], pgtype_decimal_digits(stmt, the_type, PG_STATIC)); set_tuplefield_int2(&tuple[7], SQL_PC_NOT_PSEUDO); inolog("Add ctid\n"); } } else { /* use the oid value for the rowid */ if (fColType == SQL_BEST_ROWID) { Int2 the_type = PG_TYPE_OID; if (relhasoids[0] != '1') { goto cleanup; } tuple = QR_AddNew(res); set_tuplefield_int2(&tuple[0], SQL_SCOPE_SESSION); set_tuplefield_string(&tuple[1], OID_NAME); set_tuplefield_int2(&tuple[2], pgtype_to_concise_type(stmt, the_type, PG_STATIC)); set_tuplefield_string(&tuple[3], pgtype_to_name(stmt, the_type, PG_UNSPECIFIED, TRUE)); set_tuplefield_int4(&tuple[4], pgtype_column_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[5], pgtype_buffer_length(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int2(&tuple[6], pgtype_decimal_digits(stmt, the_type, PG_STATIC)); set_tuplefield_int2(&tuple[7], SQL_PC_PSEUDO); } else if (fColType == SQL_ROWVER) { Int2 the_type = PG_TYPE_XID; tuple = QR_AddNew(res); set_tuplefield_null(&tuple[0]); set_tuplefield_string(&tuple[1], "xmin"); set_tuplefield_int2(&tuple[2], pgtype_to_concise_type(stmt, the_type, PG_STATIC)); set_tuplefield_string(&tuple[3], pgtype_to_name(stmt, the_type, PG_UNSPECIFIED, FALSE)); set_tuplefield_int4(&tuple[4], pgtype_column_size(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[5], pgtype_buffer_length(stmt, the_type, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int2(&tuple[6], pgtype_decimal_digits(stmt, the_type, PG_STATIC)); set_tuplefield_int2(&tuple[7], SQL_PC_PSEUDO); } } cleanup: #undef return if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); stmt->status = STMT_FINISHED; stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (hcol_stmt) PGAPI_FreeStmt(hcol_stmt, SQL_DROP); if (stmt->internal) result = DiscardStatementSvp(stmt, result, FALSE); mylog("%s: EXIT, stmt=%p\n", func, stmt); return result; } #define INDOPTION_DESC 0x0001 /* values are in reverse order */ RETCODE SQL_API PGAPI_Statistics(HSTMT hstmt, const SQLCHAR FAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, SQLUSMALLINT fUnique, SQLUSMALLINT fAccuracy) { CSTR func = "PGAPI_Statistics"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; QResultClass *res; char index_query[INFO_INQUIRY_LEN]; HSTMT hcol_stmt = NULL, hindx_stmt = NULL; RETCODE ret = SQL_ERROR, result; char *escSchemaName = NULL, *table_name = NULL, *escTableName = NULL; char index_name[MAX_INFO_STRING]; short fields_vector[INDEX_KEYS_STORAGE_COUNT + 1]; short indopt_vector[INDEX_KEYS_STORAGE_COUNT + 1]; char isunique[10], isclustered[10], ishash[MAX_INFO_STRING]; SQLLEN index_name_len, fields_vector_len; TupleField *tuple; int i; StatementClass *col_stmt, *indx_stmt; char column_name[MAX_INFO_STRING], table_schemaname[MAX_INFO_STRING], relhasrules[10]; struct columns_idx { int pnum; char *col_name; } *column_names = NULL; /* char **column_names = NULL; */ SQLLEN column_name_len; int total_columns = 0, alcount; ConnInfo *ci; char buf[256]; SQLSMALLINT internal_asis_type = SQL_C_CHAR, cbSchemaName, field_number; const SQLCHAR *szSchemaName; const char *eq_string; OID ioid; Int4 relhasoids; mylog("%s: entering...stmt=%p scnm=%p len=%d\n", func, stmt, szTableOwner, cbTableOwner); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; table_name = make_string(szTableName, cbTableName, NULL, 0); if (!table_name) { SC_set_error(stmt, STMT_INVALID_NULL_ARG, "The table name is required", func); return result; } conn = SC_get_conn(stmt); ci = &(conn->connInfo); #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_Statistics result.", func); return SQL_ERROR; } SC_set_Result(stmt, res); /* the binding structure for a statement is not set up until */ /* * a statement is actually executed, so we'll have to do this * ourselves. */ extend_column_bindings(SC_get_ARDF(stmt), 13); stmt->catalog_result = TRUE; /* set the field names */ QR_set_num_fields(res, NUM_OF_STATS_FIELDS); QR_set_field_info_v(res, STATS_CATALOG_NAME, "TABLE_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, STATS_SCHEMA_NAME, "TABLE_OWNER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, STATS_TABLE_NAME, "TABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, STATS_NON_UNIQUE, "NON_UNIQUE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, STATS_INDEX_QUALIFIER, "INDEX_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, STATS_INDEX_NAME, "INDEX_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, STATS_TYPE, "TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, STATS_SEQ_IN_INDEX, "SEQ_IN_INDEX", PG_TYPE_INT2, 2); QR_set_field_info_v(res, STATS_COLUMN_NAME, "COLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, STATS_COLLATION, "COLLATION", PG_TYPE_CHAR, 1); QR_set_field_info_v(res, STATS_CARDINALITY, "CARDINALITY", PG_TYPE_INT4, 4); QR_set_field_info_v(res, STATS_PAGES, "PAGES", PG_TYPE_INT4, 4); QR_set_field_info_v(res, STATS_FILTER_CONDITION, "FILTER_CONDITION", PG_TYPE_VARCHAR, MAX_INFO_STRING); #define return DONT_CALL_RETURN_FROM_HERE??? szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; table_schemaname[0] = '\0'; if (conn->schema_support) schema_strcat(table_schemaname, "%.*s", szSchemaName, cbSchemaName, szTableName, cbTableName, conn); /* * we need to get a list of the field names first, so we can return * them later. */ result = PGAPI_AllocStmt(conn, &hcol_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in PGAPI_Statistics for columns.", func); goto cleanup; } col_stmt = (StatementClass *) hcol_stmt; /* * "internal" prevents SQLColumns from returning the oid if it is * being shown. This would throw everything off. */ col_stmt->internal = TRUE; /* * table_name parameter cannot contain a string search pattern. */ result = PGAPI_Columns(hcol_stmt, NULL, 0, (SQLCHAR *) table_schemaname, SQL_NTS, (SQLCHAR *) table_name, SQL_NTS, NULL, 0, PODBC_NOT_SEARCH_PATTERN | PODBC_SEARCH_PUBLIC_SCHEMA, 0, 0); col_stmt->internal = FALSE; if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, COLUMNS_COLUMN_NAME + 1, internal_asis_type, column_name, sizeof(column_name), &column_name_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hcol_stmt, COLUMNS_PHYSICAL_NUMBER + 1, SQL_C_SHORT, &field_number, sizeof(field_number), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, col_stmt, TRUE); goto cleanup; } alcount = 0; result = PGAPI_Fetch(hcol_stmt); while (SQL_SUCCEEDED(result)) { if (0 == total_columns) PGAPI_GetData(hcol_stmt, 2, internal_asis_type, table_schemaname, sizeof(table_schemaname), NULL); if (total_columns >= alcount) { if (0 == alcount) alcount = 4; else alcount *= 2; column_names = (struct columns_idx *) realloc(column_names, alcount * sizeof(struct columns_idx)); } column_names[total_columns].col_name = (char *) malloc(strlen(column_name) + 1); strcpy(column_names[total_columns].col_name, column_name); column_names[total_columns].pnum = field_number; total_columns++; mylog("%s: column_name = '%s'\n", func, column_name); result = PGAPI_Fetch(hcol_stmt); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, col_stmt, FALSE); goto cleanup; } PGAPI_FreeStmt(hcol_stmt, SQL_DROP); hcol_stmt = NULL; if (total_columns == 0) { /* Couldn't get column names in SQLStatistics.; */ ret = SQL_SUCCESS; goto cleanup; } /* get a list of indexes on this table */ result = PGAPI_AllocStmt(conn, &hindx_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in SQLStatistics for indices.", func); goto cleanup; } indx_stmt = (StatementClass *) hindx_stmt; /* TableName cannot contain a string search pattern */ escTableName = simpleCatalogEscape((SQLCHAR *) table_name, SQL_NTS, NULL, conn); eq_string = gen_opestr(eqop, conn); if (conn->schema_support) { escSchemaName = simpleCatalogEscape((SQLCHAR *) table_schemaname, SQL_NTS, NULL, conn); snprintf(index_query, sizeof(index_query), "select c.relname, i.indkey, i.indisunique" ", i.indisclustered, a.amname, c.relhasrules, n.nspname" ", c.oid, %s, %s" " from pg_catalog.pg_index i, pg_catalog.pg_class c," " pg_catalog.pg_class d, pg_catalog.pg_am a," " pg_catalog.pg_namespace n" " where d.relname %s'%s'" " and n.nspname %s'%s'" " and n.oid = d.relnamespace" " and d.oid = i.indrelid" " and i.indexrelid = c.oid" " and c.relam = a.oid order by" , PG_VERSION_GE(conn, 7.2) ? "d.relhasoids" : "1" , PG_VERSION_GE(conn, 8.3) ? "i.indoption" : "0" , eq_string, escTableName, eq_string, escSchemaName); } else snprintf(index_query, sizeof(index_query), "select c.relname, i.indkey, i.indisunique" ", i.indisclustered, a.amname, c.relhasrules, c.oid, %s, 0" " from pg_index i, pg_class c, pg_class d, pg_am a" " where d.relname %s'%s'" " and d.oid = i.indrelid" " and i.indexrelid = c.oid" " and c.relam = a.oid order by" , PG_VERSION_GE(conn, 7.2) ? "d.relhasoids" : "1" , eq_string, escTableName); if (PG_VERSION_GT(SC_get_conn(stmt), 6.4)) strcat(index_query, " i.indisprimary desc,"); if (conn->schema_support) strcat(index_query, " i.indisunique, n.nspname, c.relname"); else strcat(index_query, " i.indisunique, c.relname"); result = PGAPI_ExecDirect(hindx_stmt, (SQLCHAR *) index_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { /* * "Couldn't execute index query (w/SQLExecDirect) in * SQLStatistics."; */ SC_full_error_copy(stmt, indx_stmt, FALSE); goto cleanup; } /* bind the index name column */ result = PGAPI_BindCol(hindx_stmt, 1, internal_asis_type, index_name, MAX_INFO_STRING, &index_name_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); /* "Couldn't bind column * in SQLStatistics."; */ goto cleanup; } /* bind the vector column */ result = PGAPI_BindCol(hindx_stmt, 2, SQL_C_DEFAULT, fields_vector, sizeof(fields_vector), &fields_vector_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); /* "Couldn't bind column * in SQLStatistics."; */ goto cleanup; } /* bind the "is unique" column */ result = PGAPI_BindCol(hindx_stmt, 3, internal_asis_type, isunique, sizeof(isunique), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); /* "Couldn't bind column * in SQLStatistics."; */ goto cleanup; } /* bind the "is clustered" column */ result = PGAPI_BindCol(hindx_stmt, 4, internal_asis_type, isclustered, sizeof(isclustered), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); /* "Couldn't bind column * * in SQLStatistics."; */ goto cleanup; } /* bind the "is hash" column */ result = PGAPI_BindCol(hindx_stmt, 5, internal_asis_type, ishash, sizeof(ishash), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); /* "Couldn't bind column * * in SQLStatistics."; */ goto cleanup; } result = PGAPI_BindCol(hindx_stmt, 6, internal_asis_type, relhasrules, sizeof(relhasrules), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hindx_stmt, 8, SQL_C_ULONG, &ioid, sizeof(ioid), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(hindx_stmt, 9, SQL_C_ULONG, &relhasoids, sizeof(relhasoids), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); goto cleanup; } /* bind the vector column */ result = PGAPI_BindCol(hindx_stmt, 10, SQL_C_DEFAULT, indopt_vector, sizeof(fields_vector), &fields_vector_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, indx_stmt, TRUE); /* "Couldn't bind column * in SQLStatistics."; */ goto cleanup; } relhasrules[0] = '0'; result = PGAPI_Fetch(hindx_stmt); /* fake index of OID */ if (relhasoids && relhasrules[0] != '1' && atoi(ci->show_oid_column) && atoi(ci->fake_oid_index)) { tuple = QR_AddNew(res); /* no table qualifier */ set_tuplefield_string(&tuple[STATS_CATALOG_NAME], CurrCat(conn)); /* don't set the table owner, else Access tries to use it */ set_tuplefield_string(&tuple[STATS_SCHEMA_NAME], GET_SCHEMA_NAME(table_schemaname)); set_tuplefield_string(&tuple[STATS_TABLE_NAME], table_name); /* non-unique index? */ set_tuplefield_int2(&tuple[STATS_NON_UNIQUE], (Int2) (ci->drivers.unique_index ? FALSE : TRUE)); /* no index qualifier */ set_tuplefield_string(&tuple[STATS_INDEX_QUALIFIER], GET_SCHEMA_NAME(table_schemaname)); snprintf(buf, sizeof(buf), "%s_idx_fake_oid", table_name); set_tuplefield_string(&tuple[STATS_INDEX_NAME], buf); /* * Clustered/HASH index? */ set_tuplefield_int2(&tuple[STATS_TYPE], (Int2) SQL_INDEX_OTHER); set_tuplefield_int2(&tuple[STATS_SEQ_IN_INDEX], (Int2) 1); set_tuplefield_string(&tuple[STATS_COLUMN_NAME], OID_NAME); set_tuplefield_string(&tuple[STATS_COLLATION], "A"); set_tuplefield_null(&tuple[STATS_CARDINALITY]); set_tuplefield_null(&tuple[STATS_PAGES]); set_tuplefield_null(&tuple[STATS_FILTER_CONDITION]); } while (SQL_SUCCEEDED(result)) { /* If only requesting unique indexs, then just return those. */ if (fUnique == SQL_INDEX_ALL || (fUnique == SQL_INDEX_UNIQUE && atoi(isunique))) { int colcnt, attnum; /* add a row in this table for each field in the index */ colcnt = fields_vector[0]; for (i = 1; i <= colcnt; i++) { tuple = QR_AddNew(res); /* no table qualifier */ set_tuplefield_string(&tuple[STATS_CATALOG_NAME], CurrCat(conn)); /* don't set the table owner, else Access tries to use it */ set_tuplefield_string(&tuple[STATS_SCHEMA_NAME], GET_SCHEMA_NAME(table_schemaname)); set_tuplefield_string(&tuple[STATS_TABLE_NAME], table_name); /* non-unique index? */ if (ci->drivers.unique_index) set_tuplefield_int2(&tuple[STATS_NON_UNIQUE], (Int2) (atoi(isunique) ? FALSE : TRUE)); else set_tuplefield_int2(&tuple[STATS_NON_UNIQUE], TRUE); /* no index qualifier */ set_tuplefield_string(&tuple[STATS_INDEX_QUALIFIER], GET_SCHEMA_NAME(table_schemaname)); set_tuplefield_string(&tuple[STATS_INDEX_NAME], index_name); /* * Clustered/HASH index? */ set_tuplefield_int2(&tuple[STATS_TYPE], (Int2) (atoi(isclustered) ? SQL_INDEX_CLUSTERED : (!strncmp(ishash, "hash", 4)) ? SQL_INDEX_HASHED : SQL_INDEX_OTHER)); set_tuplefield_int2(&tuple[STATS_SEQ_IN_INDEX], (Int2) i); attnum = fields_vector[i]; if (OID_ATTNUM == attnum) { set_tuplefield_string(&tuple[STATS_COLUMN_NAME], OID_NAME); mylog("%s: column name = oid\n", func); } else if (0 == attnum) { char cmd[64]; QResultClass *res; snprintf(cmd, sizeof(cmd), "select pg_get_indexdef(%u, %d, true)", ioid, i); res = CC_send_query(conn, cmd, NULL, IGNORE_ABORT_ON_CONN, stmt); if (QR_command_maybe_successful(res)) set_tuplefield_string(&tuple[STATS_COLUMN_NAME], QR_get_value_backend_text(res, 0, 0)); QR_Destructor(res); } else { int j, matchidx; BOOL unknownf = TRUE; if (attnum > 0) { for (j = 0; j < total_columns; j++) { if (attnum == column_names[j].pnum) { matchidx = j; unknownf = FALSE; break; } } } if (unknownf) { set_tuplefield_string(&tuple[STATS_COLUMN_NAME], "UNKNOWN"); mylog("%s: column name = UNKNOWN\n", func); } else { set_tuplefield_string(&tuple[STATS_COLUMN_NAME], column_names[matchidx].col_name); mylog("%s: column name = '%s'\n", func, column_names[matchidx].col_name); } } if (i <= indopt_vector[0] && (indopt_vector[i] & INDOPTION_DESC) != 0) set_tuplefield_string(&tuple[STATS_COLLATION], "D"); else set_tuplefield_string(&tuple[STATS_COLLATION], "A"); set_tuplefield_null(&tuple[STATS_CARDINALITY]); set_tuplefield_null(&tuple[STATS_PAGES]); set_tuplefield_null(&tuple[STATS_FILTER_CONDITION]); } } result = PGAPI_Fetch(hindx_stmt); } if (result != SQL_NO_DATA_FOUND) { /* "SQLFetch failed in SQLStatistics."; */ SC_full_error_copy(stmt, indx_stmt, FALSE); goto cleanup; } ret = SQL_SUCCESS; cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; if (hcol_stmt) PGAPI_FreeStmt(hcol_stmt, SQL_DROP); if (hindx_stmt) PGAPI_FreeStmt(hindx_stmt, SQL_DROP); /* These things should be freed on any error ALSO! */ if (table_name) free(table_name); if (escTableName) free(escTableName); if (escSchemaName) free(escSchemaName); if (column_names) { for (i = 0; i < total_columns; i++) free(column_names[i].col_name); free(column_names); } /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); mylog("%s: EXIT, stmt=%p, ret=%d\n", func, stmt, ret); return ret; } RETCODE SQL_API PGAPI_ColumnPrivileges(HSTMT hstmt, const SQLCHAR FAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, const SQLCHAR FAR * szColumnName, /* PV E*/ SQLSMALLINT cbColumnName, UWORD flag) { CSTR func = "PGAPI_ColumnPrivileges"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn = SC_get_conn(stmt); RETCODE result = SQL_ERROR; char *escSchemaName = NULL, *escTableName = NULL, *escColumnName = NULL; const char *like_or_eq, *op_string, *eq_string; char column_query[INFO_INQUIRY_LEN]; size_t cq_len,cq_size; char *col_query; BOOL search_pattern; QResultClass *res = NULL; mylog("%s: entering...\n", func); /* Neither Access or Borland care about this. */ if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; if (PG_VERSION_LT(conn, 7.4)) SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "Function not implementedyet", func); escSchemaName = simpleCatalogEscape(szTableOwner, cbTableOwner, NULL, conn); escTableName = simpleCatalogEscape(szTableName, cbTableName, NULL, conn); search_pattern = (0 == (flag & PODBC_NOT_SEARCH_PATTERN)); if (search_pattern) { like_or_eq = likeop; escColumnName = adjustLikePattern(szColumnName, cbColumnName, SEARCH_PATTERN_ESCAPE, NULL, conn); } else { like_or_eq = eqop; escColumnName = simpleCatalogEscape(szColumnName, cbColumnName, NULL, conn); } strcpy(column_query, "select '' as TABLE_CAT, table_schema as TABLE_SCHEM," " table_name, column_name, grantor, grantee," " privilege_type as PRIVILEGE, is_grantable from" " information_schema.column_privileges where true"); cq_len = strlen(column_query); cq_size = sizeof(column_query); col_query = column_query; op_string = gen_opestr(like_or_eq, conn); eq_string = gen_opestr(eqop, conn); if (escSchemaName) { col_query += cq_len; cq_size -= cq_len; cq_len = snprintf_len(col_query, cq_size, " and table_schem %s'%s'", eq_string, escSchemaName); } if (escTableName) { col_query += cq_len; cq_size -= cq_len; cq_len += snprintf_len(col_query, cq_size, " and table_name %s'%s'", eq_string, escTableName); } if (escColumnName) { col_query += cq_len; cq_size -= cq_len; cq_len += snprintf_len(col_query, cq_size, " and column_name %s'%s'", op_string, escColumnName); } if (res = CC_send_query(conn, column_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_ColumnPrivileges query error", func); goto cleanup; } SC_set_Result(stmt, res); /* * also, things need to think that this statement is finished so the * results can be retrieved. */ extend_column_bindings(SC_get_ARDF(stmt), 8); /* set up the current tuple pointer for SQLFetch */ result = SQL_SUCCESS; cleanup: if (!SQL_SUCCEEDED(result)) QR_Destructor(res); /* set up the current tuple pointer for SQLFetch */ stmt->status = STMT_FINISHED; stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (escColumnName) free(escColumnName); return result; } /* * SQLPrimaryKeys() * * Retrieve the primary key columns for the specified table. */ RETCODE SQL_API PGAPI_PrimaryKeys(HSTMT hstmt, const SQLCHAR FAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, OID reloid) { CSTR func = "PGAPI_PrimaryKeys"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; ConnectionClass *conn; TupleField *tuple; RETCODE ret = SQL_SUCCESS, result; int seq = 0; HSTMT htbl_stmt = NULL; StatementClass *tbl_stmt; char tables_query[INFO_INQUIRY_LEN]; char attname[MAX_INFO_STRING]; SQLLEN attname_len; char *pktab = NULL, *pktbname; char pkscm[SCHEMA_NAME_STORAGE_LEN + 1]; SQLLEN pkscm_len; char tabname[TABLE_NAME_STORAGE_LEN + 1]; SQLLEN tabname_len; char pkname[TABLE_NAME_STORAGE_LEN + 1]; Int2 result_cols; int qno, qstart, qend; SQLSMALLINT internal_asis_type = SQL_C_CHAR, cbSchemaName; const SQLCHAR *szSchemaName; const char *eq_string; char *escSchemaName = NULL, *escTableName = NULL; mylog("%s: entering...stmt=%p scnm=%p len=%d\n", func, stmt, szTableOwner, cbTableOwner); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_PrimaryKeys result.", func); return SQL_ERROR; } SC_set_Result(stmt, res); /* the binding structure for a statement is not set up until * * a statement is actually executed, so we'll have to do this * ourselves. */ result_cols = NUM_OF_PKS_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; /* set the field names */ QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, PKS_TABLE_CAT, "TABLE_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PKS_TABLE_SCHEM, "TABLE_OWNER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PKS_TABLE_NAME, "TABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PKS_COLUMN_NAME, "COLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PKS_KEY_SQ, "KEY_SEQ", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PKS_PK_NAME, "PK_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); conn = SC_get_conn(stmt); result = PGAPI_AllocStmt(conn, &htbl_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for Primary Key result.", func); ret = SQL_ERROR; goto cleanup; } tbl_stmt = (StatementClass *) htbl_stmt; #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ #define return DONT_CALL_RETURN_FROM_HERE??? if (0 != reloid) { szSchemaName = NULL; cbSchemaName = SQL_NULL_DATA; } else { pktab = make_string(szTableName, cbTableName, NULL, 0); if (!pktab || pktab[0] == '\0') { SC_set_error(stmt, STMT_INTERNAL_ERROR, "No Table specified to PGAPI_PrimaryKeys.", func); ret = SQL_ERROR; goto cleanup; } szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; escTableName = simpleCatalogEscape(szTableName, cbTableName, NULL, conn); } eq_string = gen_opestr(eqop, conn); retry_public_schema: pkscm[0] = '\0'; if (0 == reloid) { if (escSchemaName) free(escSchemaName); escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, NULL, conn); if (conn->schema_support) schema_strcat(pkscm, "%.*s", (SQLCHAR *) escSchemaName, SQL_NTS, szTableName, cbTableName, conn); } result = PGAPI_BindCol(htbl_stmt, 1, internal_asis_type, attname, MAX_INFO_STRING, &attname_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); ret = SQL_ERROR; goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 3, internal_asis_type, pkname, TABLE_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); ret = SQL_ERROR; goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 4, internal_asis_type, pkscm, SCHEMA_NAME_STORAGE_LEN, &pkscm_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); ret = SQL_ERROR; goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 5, internal_asis_type, tabname, TABLE_NAME_STORAGE_LEN, &tabname_len); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); ret = SQL_ERROR; goto cleanup; } if (PG_VERSION_LE(conn, 6.4)) qstart = 2; else qstart = 1; if (0 == reloid) qend = 2; else qend = 1; for (qno = qstart; qno <= qend; qno++) { size_t qsize, tsize; char *tbqry; switch (qno) { case 1: /* * Simplified query to remove assumptions about number of * possible index columns. Courtesy of Tom Lane - thomas * 2000-03-21 */ if (conn->schema_support) { strncpy_null(tables_query, "select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname" " from pg_catalog.pg_attribute ta," " pg_catalog.pg_attribute ia, pg_catalog.pg_class tc," " pg_catalog.pg_index i, pg_catalog.pg_namespace n" ", pg_catalog.pg_class ic" , sizeof(tables_query)); qsize = strlen(tables_query); tsize = sizeof(tables_query) - qsize; tbqry = tables_query + qsize; if (0 == reloid) snprintf(tbqry, tsize, " where tc.relname %s'%s'" " AND n.nspname %s'%s'" , eq_string, escTableName, eq_string, pkscm); else snprintf(tbqry, tsize, " where tc.oid = " FORMAT_UINT4 , reloid); strlcat(tables_query, " AND tc.oid = i.indrelid" " AND n.oid = tc.relnamespace" " AND i.indisprimary = 't'" " AND ia.attrelid = i.indexrelid" " AND ta.attrelid = i.indrelid" " AND ta.attnum = i.indkey[ia.attnum-1]" " AND (NOT ta.attisdropped)" " AND (NOT ia.attisdropped)" " AND ic.oid = i.indexrelid" " order by ia.attnum" , sizeof(tables_query)); } else { strncpy_null(tables_query, "select ta.attname, ia.attnum, ic.relname, NULL, tc.relname" " from pg_attribute ta, pg_attribute ia, pg_class tc, pg_index i, pg_class ic" , sizeof(tables_query)); qsize = strlen(tables_query); tsize = sizeof(tables_query) - qsize; tbqry = tables_query + qsize; if (0 == reloid) snprintf(tbqry, tsize, " where tc.relname %s'%s'" , eq_string, escTableName); else snprintf(tbqry, tsize, " where tc.oid = " FORMAT_UINT4, reloid); strlcat(tables_query, " AND tc.oid = i.indrelid" " AND i.indisprimary = 't'" " AND ia.attrelid = i.indexrelid" " AND ta.attrelid = i.indrelid" " AND ta.attnum = i.indkey[ia.attnum-1]" " AND ic.oid = i.indexrelid" " order by ia.attnum" , sizeof(tables_query)); } break; case 2: /* * Simplified query to search old fashoned primary key */ if (conn->schema_support) snprintf(tables_query, sizeof(tables_query), "select ta.attname, ia.attnum, ic.relname, n.nspname, NULL" " from pg_catalog.pg_attribute ta," " pg_catalog.pg_attribute ia, pg_catalog.pg_class ic," " pg_catalog.pg_index i, pg_catalog.pg_namespace n" " where ic.relname %s'%s_pkey'" " AND n.nspname %s'%s'" " AND ic.oid = i.indexrelid" " AND n.oid = ic.relnamespace" " AND ia.attrelid = i.indexrelid" " AND ta.attrelid = i.indrelid" " AND ta.attnum = i.indkey[ia.attnum-1]" " AND (NOT ta.attisdropped)" " AND (NOT ia.attisdropped)" " order by ia.attnum", eq_string, escTableName, eq_string, pkscm); else snprintf(tables_query, sizeof(tables_query), "select ta.attname, ia.attnum, ic.relname, NULL, NULL" " from pg_attribute ta, pg_attribute ia, pg_class ic, pg_index i" " where ic.relname %s'%s_pkey'" " AND ic.oid = i.indexrelid" " AND ia.attrelid = i.indexrelid" " AND ta.attrelid = i.indrelid" " AND ta.attnum = i.indkey[ia.attnum-1]" " order by ia.attnum", eq_string, escTableName); break; } mylog("%s: tables_query='%s'\n", func, tables_query); result = PGAPI_ExecDirect(htbl_stmt, (SQLCHAR *) tables_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, tbl_stmt, FALSE); ret = SQL_ERROR; goto cleanup; } result = PGAPI_Fetch(htbl_stmt); if (result != SQL_NO_DATA_FOUND) break; } /* If not found */ if (conn->schema_support && SQL_NO_DATA_FOUND == result) { if (0 == reloid && allow_public_schema(conn, szSchemaName, cbSchemaName)) { szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } } while (SQL_SUCCEEDED(result)) { tuple = QR_AddNew(res); set_tuplefield_string(&tuple[PKS_TABLE_CAT], CurrCat(conn)); /* * I have to hide the table owner from Access, otherwise it * insists on referring to the table as 'owner.table'. (this is * valid according to the ODBC SQL grammar, but Postgres won't * support it.) */ if (SQL_NULL_DATA == pkscm_len) pkscm[0] = '\0'; set_tuplefield_string(&tuple[PKS_TABLE_SCHEM], GET_SCHEMA_NAME(pkscm)); if (SQL_NULL_DATA == tabname_len) tabname[0] = '\0'; pktbname = pktab ? pktab : tabname; set_tuplefield_string(&tuple[PKS_TABLE_NAME], pktbname); set_tuplefield_string(&tuple[PKS_COLUMN_NAME], attname); set_tuplefield_int2(&tuple[PKS_KEY_SQ], (Int2) (++seq)); set_tuplefield_string(&tuple[PKS_PK_NAME], pkname); mylog(">> primaryKeys: schema ='%s', pktab = '%s', attname = '%s', seq = %d\n", pkscm, pktbname, attname, seq); result = PGAPI_Fetch(htbl_stmt); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, htbl_stmt, FALSE); ret = SQL_ERROR; goto cleanup; } ret = SQL_SUCCESS; cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; if (htbl_stmt) PGAPI_FreeStmt(htbl_stmt, SQL_DROP); if (pktab) free(pktab); if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); mylog("%s: EXIT, stmt=%p, ret=%d\n", func, stmt, ret); return ret; } /* * Multibyte support stuff for SQLForeignKeys(). * There may be much more effective way in the * future version. The way is very forcible currently. */ static BOOL isMultibyte(const char *str) { for (; *str; str++) { if ((unsigned char) *str >= 0x80) return TRUE; } return FALSE; } static char * getClientColumnName(ConnectionClass *conn, UInt4 relid, char *serverColumnName, BOOL *nameAlloced) { char query[1024], saveattnum[16], *ret = serverColumnName; const char *eq_string; BOOL continueExec = TRUE, bError = FALSE; QResultClass *res = NULL; UWORD flag = IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR; *nameAlloced = FALSE; if (!conn->original_client_encoding || !isMultibyte(serverColumnName)) return ret; if (!conn->server_encoding) { if (res = CC_send_query(conn, "select getdatabaseencoding()", NULL, flag, NULL), QR_command_maybe_successful(res)) { if (QR_get_num_cached_tuples(res) > 0) conn->server_encoding = strdup(QR_get_value_backend_text(res, 0, 0)); } QR_Destructor(res); res = NULL; } if (!conn->server_encoding) return ret; snprintf(query, sizeof(query), "SET CLIENT_ENCODING TO '%s'", conn->server_encoding); bError = (!QR_command_maybe_successful((res = CC_send_query(conn, query, NULL, flag, NULL)))); QR_Destructor(res); eq_string = gen_opestr(eqop, conn); if (!bError && continueExec) { snprintf(query, sizeof(query), "select attnum from pg_attribute " "where attrelid = %u and attname %s'%s'", relid, eq_string, serverColumnName); if (res = CC_send_query(conn, query, NULL, flag, NULL), QR_command_maybe_successful(res)) { if (QR_get_num_cached_tuples(res) > 0) { strcpy(saveattnum, QR_get_value_backend_text(res, 0, 0)); } else continueExec = FALSE; } else bError = TRUE; QR_Destructor(res); } continueExec = (continueExec && !bError); /* restore the cleint encoding */ snprintf(query, sizeof(query), "SET CLIENT_ENCODING TO '%s'", conn->original_client_encoding); bError = (!QR_command_maybe_successful((res = CC_send_query(conn, query, NULL, flag, NULL)))); QR_Destructor(res); if (bError || !continueExec) return ret; snprintf(query, sizeof(query), "select attname from pg_attribute where attrelid = %u and attnum = %s", relid, saveattnum); if (res = CC_send_query(conn, query, NULL, flag, NULL), QR_command_maybe_successful(res)) { if (QR_get_num_cached_tuples(res) > 0) { ret = strdup(QR_get_value_backend_text(res, 0, 0)); *nameAlloced = TRUE; } } QR_Destructor(res); return ret; } static RETCODE SQL_API PGAPI_ForeignKeys_new(HSTMT hstmt, const SQLCHAR FAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR FAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR FAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR FAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR FAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR FAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName); static RETCODE SQL_API PGAPI_ForeignKeys_old(HSTMT hstmt, const SQLCHAR FAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR FAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR FAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR FAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR FAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR FAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName) { CSTR func = "PGAPI_ForeignKeys"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; TupleField *tuple; HSTMT htbl_stmt = NULL, hpkey_stmt = NULL; StatementClass *tbl_stmt; RETCODE ret = SQL_ERROR, result, keyresult; char tables_query[INFO_INQUIRY_LEN]; char trig_deferrable[2]; char trig_initdeferred[2]; char trig_args[1024]; char upd_rule[TABLE_NAME_STORAGE_LEN], del_rule[TABLE_NAME_STORAGE_LEN]; char *pk_table_needed = NULL, *escPkTableName = NULL; char fk_table_fetched[TABLE_NAME_STORAGE_LEN + 1]; char *fk_table_needed = NULL, *escFkTableName = NULL; char pk_table_fetched[TABLE_NAME_STORAGE_LEN + 1]; char schema_needed[SCHEMA_NAME_STORAGE_LEN + 1]; char schema_fetched[SCHEMA_NAME_STORAGE_LEN + 1]; char constrname[NAMESTORAGELEN + 1], pkname[TABLE_NAME_STORAGE_LEN + 1]; char *pkey_ptr, *pkey_text = NULL, *fkey_ptr, *fkey_text = NULL; ConnectionClass *conn; BOOL pkey_alloced, fkey_alloced, got_pkname; int i, j, k, num_keys; SQLSMALLINT trig_nargs, upd_rule_type = 0, del_rule_type = 0; SQLSMALLINT internal_asis_type = SQL_C_CHAR; #if (ODBCVER >= 0x0300) SQLSMALLINT defer_type; #endif char pkey[MAX_INFO_STRING]; Int2 result_cols; UInt4 relid1, relid2; const char *eq_string; mylog("%s: entering...stmt=%p\n", func, stmt); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_ForeignKeys result.", func); return SQL_ERROR; } SC_set_Result(stmt, res); /* the binding structure for a statement is not set up until */ /* * a statement is actually executed, so we'll have to do this * ourselves. */ result_cols = NUM_OF_FKS_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; /* set the field names */ QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, FKS_PKTABLE_CAT, "PKTABLE_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_PKTABLE_SCHEM, "PKTABLE_OWNER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_PKTABLE_NAME, "PKTABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_PKCOLUMN_NAME, "PKCOLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_FKTABLE_CAT, "FKTABLE_QUALIFIER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_FKTABLE_SCHEM, "FKTABLE_OWNER", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_FKTABLE_NAME, "FKTABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_FKCOLUMN_NAME, "FKCOLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_KEY_SEQ, "KEY_SEQ", PG_TYPE_INT2, 2); QR_set_field_info_v(res, FKS_UPDATE_RULE, "UPDATE_RULE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, FKS_DELETE_RULE, "DELETE_RULE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, FKS_FK_NAME, "FK_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, FKS_PK_NAME, "PK_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); #if (ODBCVER >= 0x0300) QR_set_field_info_v(res, FKS_DEFERRABILITY, "DEFERRABILITY", PG_TYPE_INT2, 2); #endif /* ODBCVER >= 0x0300 */ QR_set_field_info_v(res, FKS_TRIGGER_NAME, "TRIGGER_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); conn = SC_get_conn(stmt); result = PGAPI_AllocStmt(conn, &htbl_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for PGAPI_ForeignKeys result.", func); return SQL_ERROR; } #define return DONT_CALL_RETURN_FROM_HERE??? tbl_stmt = (StatementClass *) htbl_stmt; schema_needed[0] = '\0'; schema_fetched[0] = '\0'; pk_table_needed = make_string(szPkTableName, cbPkTableName, NULL, 0); fk_table_needed = make_string(szFkTableName, cbFkTableName, NULL, 0); #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ pkey_alloced = fkey_alloced = FALSE; eq_string = gen_opestr(eqop, conn); /* * Case #2 -- Get the foreign keys in the specified table (fktab) that * refer to the primary keys of other table(s). */ if (fk_table_needed && fk_table_needed[0] != '\0') { mylog("%s: entering Foreign Key Case #2", func); escFkTableName = simpleCatalogEscape((SQLCHAR *) fk_table_needed, SQL_NTS, NULL, conn); if (conn->schema_support) { char *escSchemaName; schema_strcat(schema_needed, "%.*s", szFkTableOwner, cbFkTableOwner, szFkTableName, cbFkTableName, conn); escSchemaName = simpleCatalogEscape((SQLCHAR *) schema_needed, SQL_NTS, NULL, conn); snprintf(tables_query, sizeof(tables_query), "SELECT pt.tgargs, " " pt.tgnargs, " " pt.tgdeferrable, " " pt.tginitdeferred, " " pp1.proname, " " pp2.proname, " " pc.oid, " " pc1.oid, " " pc1.relname, " " pt.tgconstrname, pn.nspname " "FROM pg_catalog.pg_class pc, " " pg_catalog.pg_proc pp1, " " pg_catalog.pg_proc pp2, " " pg_catalog.pg_trigger pt1, " " pg_catalog.pg_trigger pt2, " " pg_catalog.pg_proc pp, " " pg_catalog.pg_trigger pt, " " pg_catalog.pg_class pc1, " " pg_catalog.pg_namespace pn, " " pg_catalog.pg_namespace pn1 " "WHERE pt.tgrelid = pc.oid " "AND pp.oid = pt.tgfoid " "AND pt1.tgconstrrelid = pc.oid " "AND pp1.oid = pt1.tgfoid " "AND pt2.tgfoid = pp2.oid " "AND pt2.tgconstrrelid = pc.oid " "AND ((pc.relname %s'%s') " "AND (pn1.oid = pc.relnamespace) " "AND (pn1.nspname %s'%s') " "AND (pp.proname LIKE '%%ins') " "AND (pp1.proname LIKE '%%upd') " "AND (pp1.proname not LIKE '%%check%%') " "AND (pp2.proname LIKE '%%del') " "AND (pt1.tgrelid=pt.tgconstrrelid) " "AND (pt1.tgconstrname=pt.tgconstrname) " "AND (pt2.tgrelid=pt.tgconstrrelid) " "AND (pt2.tgconstrname=pt.tgconstrname) " "AND (pt.tgconstrrelid=pc1.oid) " "AND (pc1.relnamespace=pn.oid))" " order by pt.tgconstrname", eq_string, escFkTableName, eq_string, escSchemaName); free(escSchemaName); } else snprintf(tables_query, sizeof(tables_query), "SELECT pt.tgargs, " " pt.tgnargs, " " pt.tgdeferrable, " " pt.tginitdeferred, " " pp1.proname, " " pp2.proname, " " pc.oid, " " pc1.oid, " " pc1.relname, pt.tgconstrname " "FROM pg_class pc, " " pg_proc pp1, " " pg_proc pp2, " " pg_trigger pt1, " " pg_trigger pt2, " " pg_proc pp, " " pg_trigger pt, " " pg_class pc1 " "WHERE pt.tgrelid = pc.oid " "AND pp.oid = pt.tgfoid " "AND pt1.tgconstrrelid = pc.oid " "AND pp1.oid = pt1.tgfoid " "AND pt2.tgfoid = pp2.oid " "AND pt2.tgconstrrelid = pc.oid " "AND ((pc.relname %s'%s') " "AND (pp.proname LIKE '%%ins') " "AND (pp1.proname LIKE '%%upd') " "AND (pp1.proname not LIKE '%%check%%') " "AND (pp2.proname LIKE '%%del') " "AND (pt1.tgrelid=pt.tgconstrrelid) " "AND (pt1.tgconstrname=pt.tgconstrname) " "AND (pt2.tgrelid=pt.tgconstrrelid) " "AND (pt2.tgconstrname=pt.tgconstrname) " "AND (pt.tgconstrrelid=pc1.oid)) " "order by pt.tgconstrname", eq_string, escFkTableName); result = PGAPI_ExecDirect(htbl_stmt, (SQLCHAR *) tables_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, tbl_stmt, FALSE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 1, SQL_C_BINARY, trig_args, sizeof(trig_args), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 2, SQL_C_SHORT, &trig_nargs, 0, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 3, internal_asis_type, trig_deferrable, sizeof(trig_deferrable), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 4, internal_asis_type, trig_initdeferred, sizeof(trig_initdeferred), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 5, internal_asis_type, upd_rule, sizeof(upd_rule), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 6, internal_asis_type, del_rule, sizeof(del_rule), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 7, SQL_C_ULONG, &relid1, sizeof(relid1), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 8, SQL_C_ULONG, &relid2, sizeof(relid2), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 9, internal_asis_type, pk_table_fetched, TABLE_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 10, internal_asis_type, constrname, NAMESTORAGELEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } if (conn->schema_support) { result = PGAPI_BindCol(htbl_stmt, 11, internal_asis_type, schema_fetched, SCHEMA_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } } result = PGAPI_Fetch(htbl_stmt); if (result == SQL_NO_DATA_FOUND) { ret = SQL_SUCCESS; goto cleanup; } if (result != SQL_SUCCESS) { SC_full_error_copy(stmt, tbl_stmt, FALSE); goto cleanup; } keyresult = PGAPI_AllocStmt(conn, &hpkey_stmt, 0); if (!SQL_SUCCEEDED(keyresult)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for PGAPI_ForeignKeys (pkeys) result.", func); goto cleanup; } keyresult = PGAPI_BindCol(hpkey_stmt, 4, internal_asis_type, pkey, sizeof(pkey), NULL); if (keyresult != SQL_SUCCESS) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't bindcol for primary keys for PGAPI_ForeignKeys result.", func); goto cleanup; } while (result == SQL_SUCCESS) { /* Compute the number of keyparts. */ num_keys = (trig_nargs - 4) / 2; mylog("Foreign Key Case#2: trig_nargs = %d, num_keys = %d\n", trig_nargs, num_keys); /* If there is a pk table specified, then check it. */ if (pk_table_needed && pk_table_needed[0] != '\0') { /* If it doesn't match, then continue */ if (strcmp(pk_table_fetched, pk_table_needed)) { result = PGAPI_Fetch(htbl_stmt); continue; } } got_pkname = FALSE; keyresult = PGAPI_PrimaryKeys(hpkey_stmt, NULL, 0, (SQLCHAR *) schema_fetched, SQL_NTS, (SQLCHAR *) pk_table_fetched, SQL_NTS, 0); if (keyresult != SQL_SUCCESS) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't get primary keys for PGAPI_ForeignKeys result.", func); goto cleanup; } /* Get to first primary key */ pkey_ptr = trig_args; for (i = 0; i < 5; i++) pkey_ptr += strlen(pkey_ptr) + 1; for (k = 0; k < num_keys; k++) { /* Check that the key listed is the primary key */ keyresult = PGAPI_Fetch(hpkey_stmt); if (keyresult != SQL_SUCCESS) { num_keys = 0; break; } if (!got_pkname) { PGAPI_GetData(hpkey_stmt, 6, internal_asis_type, pkname, sizeof(pkname), NULL); got_pkname = TRUE; } pkey_text = getClientColumnName(conn, relid2, pkey_ptr, &pkey_alloced); mylog("%s: pkey_ptr='%s', pkey='%s'\n", func, pkey_text, pkey); if (strcmp(pkey_text, pkey)) { num_keys = 0; break; } if (pkey_alloced) free(pkey_text); pkey_alloced = FALSE; /* Get to next primary key */ for (k = 0; k < 2; k++) pkey_ptr += strlen(pkey_ptr) + 1; } PGAPI_FreeStmt(hpkey_stmt, SQL_CLOSE); /* Set to first fk column */ fkey_ptr = trig_args; for (k = 0; k < 4; k++) fkey_ptr += strlen(fkey_ptr) + 1; /* Set update and delete actions for foreign keys */ if (!strcmp(upd_rule, "RI_FKey_cascade_upd")) upd_rule_type = SQL_CASCADE; else if (!strcmp(upd_rule, "RI_FKey_noaction_upd")) upd_rule_type = SQL_NO_ACTION; else if (!strcmp(upd_rule, "RI_FKey_restrict_upd")) upd_rule_type = SQL_NO_ACTION; else if (!strcmp(upd_rule, "RI_FKey_setdefault_upd")) upd_rule_type = SQL_SET_DEFAULT; else if (!strcmp(upd_rule, "RI_FKey_setnull_upd")) upd_rule_type = SQL_SET_NULL; if (!strcmp(del_rule, "RI_FKey_cascade_del")) del_rule_type = SQL_CASCADE; else if (!strcmp(del_rule, "RI_FKey_noaction_del")) del_rule_type = SQL_NO_ACTION; else if (!strcmp(del_rule, "RI_FKey_restrict_del")) del_rule_type = SQL_NO_ACTION; else if (!strcmp(del_rule, "RI_FKey_setdefault_del")) del_rule_type = SQL_SET_DEFAULT; else if (!strcmp(del_rule, "RI_FKey_setnull_del")) del_rule_type = SQL_SET_NULL; #if (ODBCVER >= 0x0300) /* Set deferrability type */ if (!strcmp(trig_initdeferred, "y")) defer_type = SQL_INITIALLY_DEFERRED; else if (!strcmp(trig_deferrable, "y")) defer_type = SQL_INITIALLY_IMMEDIATE; else defer_type = SQL_NOT_DEFERRABLE; #endif /* ODBCVER >= 0x0300 */ /* Get to first primary key */ pkey_ptr = trig_args; for (i = 0; i < 5; i++) pkey_ptr += strlen(pkey_ptr) + 1; for (k = 0; k < num_keys; k++) { tuple = QR_AddNew(res); pkey_text = getClientColumnName(conn, relid2, pkey_ptr, &pkey_alloced); fkey_text = getClientColumnName(conn, relid1, fkey_ptr, &fkey_alloced); mylog("%s: pk_table = '%s', pkey_ptr = '%s'\n", func, pk_table_fetched, pkey_text); set_tuplefield_string(&tuple[FKS_PKTABLE_CAT], CurrCat(conn)); set_tuplefield_string(&tuple[FKS_PKTABLE_SCHEM], GET_SCHEMA_NAME(schema_fetched)); set_tuplefield_string(&tuple[FKS_PKTABLE_NAME], pk_table_fetched); set_tuplefield_string(&tuple[FKS_PKCOLUMN_NAME], pkey_text); mylog("%s: fk_table_needed = '%s', fkey_ptr = '%s'\n", func, fk_table_needed, fkey_text); set_tuplefield_string(&tuple[FKS_FKTABLE_CAT], CurrCat(conn)); set_tuplefield_string(&tuple[FKS_FKTABLE_SCHEM], GET_SCHEMA_NAME(schema_needed)); set_tuplefield_string(&tuple[FKS_FKTABLE_NAME], fk_table_needed); set_tuplefield_string(&tuple[FKS_FKCOLUMN_NAME], fkey_text); mylog("%s: upd_rule_type = '%i', del_rule_type = '%i'\n, trig_name = '%s'", func, upd_rule_type, del_rule_type, trig_args); set_tuplefield_int2(&tuple[FKS_KEY_SEQ], (Int2) (k + 1)); set_tuplefield_int2(&tuple[FKS_UPDATE_RULE], upd_rule_type); set_tuplefield_int2(&tuple[FKS_DELETE_RULE], del_rule_type); set_tuplefield_string(&tuple[FKS_FK_NAME], constrname); set_tuplefield_string(&tuple[FKS_PK_NAME], pkname); #if (ODBCVER >= 0x0300) set_tuplefield_int2(&tuple[FKS_DEFERRABILITY], defer_type); #endif /* ODBCVER >= 0x0300 */ set_tuplefield_string(&tuple[FKS_TRIGGER_NAME], trig_args); if (fkey_alloced) free(fkey_text); fkey_alloced = FALSE; if (pkey_alloced) free(pkey_text); pkey_alloced = FALSE; /* next primary/foreign key */ for (i = 0; i < 2; i++) { fkey_ptr += strlen(fkey_ptr) + 1; pkey_ptr += strlen(pkey_ptr) + 1; } } result = PGAPI_Fetch(htbl_stmt); } } /* * Case #1 -- Get the foreign keys in other tables that refer to the * primary key in the specified table (pktab). i.e., Who points to * me? */ else if (pk_table_needed[0] != '\0') { escPkTableName = simpleCatalogEscape((SQLCHAR *) pk_table_needed, SQL_NTS, NULL, conn); if (conn->schema_support) { char *escSchemaName; schema_strcat(schema_needed, "%.*s", szPkTableOwner, cbPkTableOwner, szPkTableName, cbPkTableName, conn); escSchemaName = simpleCatalogEscape((SQLCHAR *) schema_needed, SQL_NTS, NULL, conn); snprintf(tables_query, sizeof(tables_query), "SELECT pt.tgargs, " " pt.tgnargs, " " pt.tgdeferrable, " " pt.tginitdeferred, " " pp1.proname, " " pp2.proname, " " pc.oid, " " pc1.oid, " " pc1.relname, " " pt.tgconstrname, pn1.nspname " "FROM pg_catalog.pg_class pc, " " pg_catalog.pg_class pc1, " " pg_catalog.pg_proc pp, " " pg_catalog.pg_proc pp1, " " pg_catalog.pg_proc pp2, " " pg_catalog.pg_trigger pt, " " pg_catalog.pg_trigger pt1, " " pg_catalog.pg_trigger pt2, " " pg_catalog.pg_namespace pn, " " pg_catalog.pg_namespace pn1 " "WHERE pc.relname %s'%s' " " AND pn.nspname %s'%s' " " AND pc.relnamespace = pn.oid " " AND pt.tgconstrrelid = pc.oid " " AND pp.oid = pt.tgfoid " " AND pp.proname Like '%%ins' " " AND pt1.tgconstrname = pt.tgconstrname " " AND pt1.tgconstrrelid = pt.tgrelid " " AND pt1.tgrelid = pc.oid " " AND pc1.oid = pt.tgrelid " " AND pp1.oid = pt1.tgfoid " " AND pp1.proname like '%%upd' " " AND (pp1.proname not like '%%check%%') " " AND pt2.tgconstrname = pt.tgconstrname " " AND pt2.tgconstrrelid = pt.tgrelid " " AND pt2.tgrelid = pc.oid " " AND pp2.oid = pt2.tgfoid " " AND pp2.proname Like '%%del' " " AND pn1.oid = pc1.relnamespace " " order by pt.tgconstrname", eq_string, escPkTableName, eq_string, escSchemaName); free(escSchemaName); } else snprintf(tables_query, sizeof(tables_query), "SELECT pt.tgargs, " " pt.tgnargs, " " pt.tgdeferrable, " " pt.tginitdeferred, " " pp1.proname, " " pp2.proname, " " pc.oid, " " pc1.oid, " " pc1.relname, pt.tgconstrname " "FROM pg_class pc, " " pg_class pc1, " " pg_proc pp, " " pg_proc pp1, " " pg_proc pp2, " " pg_trigger pt, " " pg_trigger pt1, " " pg_trigger pt2 " "WHERE pc.relname %s'%s' " " AND pt.tgconstrrelid = pc.oid " " AND pp.oid = pt.tgfoid " " AND pp.proname Like '%%ins' " " AND pt1.tgconstrname = pt.tgconstrname " " AND pt1.tgconstrrelid = pt.tgrelid " " AND pt1.tgrelid = pc.oid " " AND pc1.oid = pt.tgrelid " " AND pp1.oid = pt1.tgfoid " " AND pp1.proname like '%%upd' " " AND pp1.(proname not like '%%check%%') " " AND pt2.tgconstrname = pt.tgconstrname " " AND pt2.tgconstrrelid = pt.tgrelid " " AND pt2.tgrelid = pc.oid " " AND pp2.oid = pt2.tgfoid " " AND pp2.proname Like '%%del'" " order by pt.tgconstrname", eq_string, escPkTableName); result = PGAPI_ExecDirect(htbl_stmt, (SQLCHAR *) tables_query, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 1, SQL_C_BINARY, trig_args, sizeof(trig_args), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 2, SQL_C_SHORT, &trig_nargs, 0, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 3, internal_asis_type, trig_deferrable, sizeof(trig_deferrable), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 4, internal_asis_type, trig_initdeferred, sizeof(trig_initdeferred), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 5, internal_asis_type, upd_rule, sizeof(upd_rule), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 6, internal_asis_type, del_rule, sizeof(del_rule), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 7, SQL_C_ULONG, &relid1, sizeof(relid1), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 8, SQL_C_ULONG, &relid2, sizeof(relid2), NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 9, internal_asis_type, fk_table_fetched, TABLE_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } result = PGAPI_BindCol(htbl_stmt, 10, internal_asis_type, constrname, NAMESTORAGELEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } if (conn->schema_support) { result = PGAPI_BindCol(htbl_stmt, 11, internal_asis_type, schema_fetched, SCHEMA_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { SC_error_copy(stmt, tbl_stmt, TRUE); goto cleanup; } } result = PGAPI_Fetch(htbl_stmt); if (result == SQL_NO_DATA_FOUND) { ret = SQL_SUCCESS; goto cleanup; } if (result != SQL_SUCCESS) { SC_full_error_copy(stmt, tbl_stmt, FALSE); goto cleanup; } /* * get pk_name here */ keyresult = PGAPI_AllocStmt(conn, &hpkey_stmt, 0); if (!SQL_SUCCEEDED(keyresult)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for PGAPI_ForeignKeys (pkeys) result.", func); goto cleanup; } keyresult = PGAPI_BindCol(hpkey_stmt, 6, internal_asis_type, pkname, sizeof(pkname), NULL); if (keyresult != SQL_SUCCESS) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't bindcol for primary keys for PGAPI_ForeignKeys result.", func); goto cleanup; } keyresult = PGAPI_PrimaryKeys(hpkey_stmt, NULL, 0, (SQLCHAR *) schema_needed, SQL_NTS, (SQLCHAR *) pk_table_needed, SQL_NTS, 0); if (keyresult != SQL_SUCCESS) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't get primary keys for PGAPI_ForeignKeys result.", func); goto cleanup; } pkname[0] = '\0'; keyresult = PGAPI_Fetch(hpkey_stmt); PGAPI_FreeStmt(hpkey_stmt, SQL_CLOSE); while (result == SQL_SUCCESS) { /* Calculate the number of key parts */ num_keys = (trig_nargs - 4) / 2;; /* Handle action (i.e., 'cascade', 'restrict', 'setnull') */ if (!strcmp(upd_rule, "RI_FKey_cascade_upd")) upd_rule_type = SQL_CASCADE; else if (!strcmp(upd_rule, "RI_FKey_noaction_upd")) upd_rule_type = SQL_NO_ACTION; else if (!strcmp(upd_rule, "RI_FKey_restrict_upd")) upd_rule_type = SQL_NO_ACTION; else if (!strcmp(upd_rule, "RI_FKey_setdefault_upd")) upd_rule_type = SQL_SET_DEFAULT; else if (!strcmp(upd_rule, "RI_FKey_setnull_upd")) upd_rule_type = SQL_SET_NULL; if (!strcmp(del_rule, "RI_FKey_cascade_del")) del_rule_type = SQL_CASCADE; else if (!strcmp(del_rule, "RI_FKey_noaction_del")) del_rule_type = SQL_NO_ACTION; else if (!strcmp(del_rule, "RI_FKey_restrict_del")) del_rule_type = SQL_NO_ACTION; else if (!strcmp(del_rule, "RI_FKey_setdefault_del")) del_rule_type = SQL_SET_DEFAULT; else if (!strcmp(del_rule, "RI_FKey_setnull_del")) del_rule_type = SQL_SET_NULL; #if (ODBCVER >= 0x0300) /* Set deferrability type */ if (!strcmp(trig_initdeferred, "y")) defer_type = SQL_INITIALLY_DEFERRED; else if (!strcmp(trig_deferrable, "y")) defer_type = SQL_INITIALLY_IMMEDIATE; else defer_type = SQL_NOT_DEFERRABLE; #endif /* ODBCVER >= 0x0300 */ mylog("Foreign Key Case#1: trig_nargs = %d, num_keys = %d\n", trig_nargs, num_keys); /* Get to first primary key */ pkey_ptr = trig_args; for (i = 0; i < 5; i++) pkey_ptr += strlen(pkey_ptr) + 1; /* Get to first foreign key */ fkey_ptr = trig_args; for (k = 0; k < 4; k++) fkey_ptr += strlen(fkey_ptr) + 1; for (k = 0; k < num_keys; k++) { pkey_text = getClientColumnName(conn, relid1, pkey_ptr, &pkey_alloced); fkey_text = getClientColumnName(conn, relid2, fkey_ptr, &fkey_alloced); mylog("pkey_ptr = '%s', fk_table = '%s', fkey_ptr = '%s'\n", pkey_text, fk_table_fetched, fkey_text); tuple = QR_AddNew(res); mylog("pk_table_needed = '%s', pkey_ptr = '%s'\n", pk_table_needed, pkey_text); set_tuplefield_string(&tuple[FKS_PKTABLE_CAT], CurrCat(conn)); set_tuplefield_string(&tuple[FKS_PKTABLE_SCHEM], GET_SCHEMA_NAME(schema_needed)); set_tuplefield_string(&tuple[FKS_PKTABLE_NAME], pk_table_needed); set_tuplefield_string(&tuple[FKS_PKCOLUMN_NAME], pkey_text); mylog("fk_table = '%s', fkey_ptr = '%s'\n", fk_table_fetched, fkey_text); set_tuplefield_string(&tuple[FKS_FKTABLE_CAT], CurrCat(conn)); set_tuplefield_string(&tuple[FKS_FKTABLE_SCHEM], GET_SCHEMA_NAME(schema_fetched)); set_tuplefield_string(&tuple[FKS_FKTABLE_NAME], fk_table_fetched); set_tuplefield_string(&tuple[FKS_FKCOLUMN_NAME], fkey_text); set_tuplefield_int2(&tuple[FKS_KEY_SEQ], (Int2) (k + 1)); mylog("upd_rule = %d, del_rule= %d", upd_rule_type, del_rule_type); set_nullfield_int2(&tuple[FKS_UPDATE_RULE], upd_rule_type); set_nullfield_int2(&tuple[FKS_DELETE_RULE], del_rule_type); set_tuplefield_string(&tuple[FKS_FK_NAME], constrname); set_tuplefield_string(&tuple[FKS_PK_NAME], pkname); set_tuplefield_string(&tuple[FKS_TRIGGER_NAME], trig_args); #if (ODBCVER >= 0x0300) mylog(" defer_type = %d\n", defer_type); set_tuplefield_int2(&tuple[FKS_DEFERRABILITY], defer_type); #endif /* ODBCVER >= 0x0300 */ if (pkey_alloced) free(pkey_text); pkey_alloced = FALSE; if (fkey_alloced) free(fkey_text); fkey_alloced = FALSE; /* next primary/foreign key */ for (j = 0; j < 2; j++) { pkey_ptr += strlen(pkey_ptr) + 1; fkey_ptr += strlen(fkey_ptr) + 1; } } result = PGAPI_Fetch(htbl_stmt); } } else { SC_set_error(stmt, STMT_INTERNAL_ERROR, "No tables specified to PGAPI_ForeignKeys.", func); goto cleanup; } ret = SQL_SUCCESS; cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; if (pkey_alloced) free(pkey_text); if (fkey_alloced) free(fkey_text); if (pk_table_needed) free(pk_table_needed); if (escPkTableName) free(escPkTableName); if (fk_table_needed) free(fk_table_needed); if (escFkTableName) free(escFkTableName); if (htbl_stmt) PGAPI_FreeStmt(htbl_stmt, SQL_DROP); if (hpkey_stmt) PGAPI_FreeStmt(hpkey_stmt, SQL_DROP); /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); mylog("%s(): EXIT, stmt=%p, ret=%d\n", func, stmt, ret); return ret; } RETCODE SQL_API PGAPI_ForeignKeys(HSTMT hstmt, const SQLCHAR FAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR FAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR FAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR FAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR FAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR FAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName) { ConnectionClass *conn = SC_get_conn(((StatementClass *) hstmt)); if (PG_VERSION_GE(conn, 8.1)) return PGAPI_ForeignKeys_new(hstmt, szPkTableQualifier, cbPkTableQualifier, szPkTableOwner, cbPkTableOwner, szPkTableName, cbPkTableName, szFkTableQualifier, cbFkTableQualifier, szFkTableOwner, cbFkTableOwner, szFkTableName, cbFkTableName); else return PGAPI_ForeignKeys_old(hstmt, szPkTableQualifier, cbPkTableQualifier, szPkTableOwner, cbPkTableOwner, szPkTableName, cbPkTableName, szFkTableQualifier, cbFkTableQualifier, szFkTableOwner, cbFkTableOwner, szFkTableName, cbFkTableName); } #define PRORET_COUNT #define DISPLAY_ARGNAME RETCODE SQL_API PGAPI_ProcedureColumns(HSTMT hstmt, const SQLCHAR FAR * szProcQualifier, /* OA X*/ SQLSMALLINT cbProcQualifier, const SQLCHAR FAR * szProcOwner, /* PV E*/ SQLSMALLINT cbProcOwner, const SQLCHAR FAR * szProcName, /* PV E*/ SQLSMALLINT cbProcName, const SQLCHAR FAR * szColumnName, /* PV X*/ SQLSMALLINT cbColumnName, UWORD flag) { CSTR func = "PGAPI_ProcedureColumns"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn = SC_get_conn(stmt); char proc_query[INFO_INQUIRY_LEN]; Int2 result_cols; TupleField *tuple; char *schema_name, *procname; char *escSchemaName = NULL, *escProcName = NULL; char *params, *proargnames; char *proargmodes; char *delim = NULL; char *atttypid, *attname, *column_name; QResultClass *res, *tres; SQLLEN tcount; OID pgtype; Int4 paramcount, column_size, i, j; RETCODE result; BOOL search_pattern, bRetset; const char *like_or_eq, *op_string, *retset; int ret_col = -1, ext_pos = -1, poid_pos = -1, attid_pos = -1, attname_pos = -1; UInt4 poid = 0, newpoid; mylog("%s: entering...\n", func); if (PG_VERSION_LT(conn, 6.5)) { SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "Version is too old", func); return SQL_ERROR; } if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; search_pattern = (0 == (flag & PODBC_NOT_SEARCH_PATTERN)); if (search_pattern) { like_or_eq = likeop; escSchemaName = adjustLikePattern(szProcOwner, cbProcOwner, SEARCH_PATTERN_ESCAPE, NULL, conn); escProcName = adjustLikePattern(szProcName, cbProcName, SEARCH_PATTERN_ESCAPE, NULL, conn); } else { like_or_eq = eqop; escSchemaName = simpleCatalogEscape(szProcOwner, cbProcOwner, NULL, conn); escProcName = simpleCatalogEscape(szProcName, cbProcName, NULL, conn); } op_string = gen_opestr(like_or_eq, conn); if (conn->schema_support) { strcpy(proc_query, "select proname, proretset, prorettype, " "pronargs, proargtypes, nspname, p.oid"); ret_col = ext_pos = 7; poid_pos = 6; #ifdef PRORET_COUNT strcat(proc_query, ", atttypid, attname"); attid_pos = ext_pos; attname_pos = ext_pos + 1; ret_col += 2; ext_pos = ret_col; #endif /* PRORET_COUNT */ if (PG_VERSION_GE(conn, 8.0)) { strcat(proc_query, ", proargnames"); ret_col++; } if (PG_VERSION_GE(conn, 8.1)) { strcat(proc_query, ", proargmodes, proallargtypes"); ret_col += 2; } #ifdef PRORET_COUNT strcat(proc_query, " from ((pg_catalog.pg_namespace n inner join" " pg_catalog.pg_proc p on p.pronamespace = n.oid)" " inner join pg_type t on t.oid = p.prorettype)" " left outer join pg_attribute a on a.attrelid = t.typrelid " " and attnum > 0 and not attisdropped where"); #else strcat(proc_query, " from pg_catalog.pg_namespace n," " pg_catalog.pg_proc p where"); " p.pronamespace = n.oid and" " (not proretset) and"); #endif /* PRORET_COUNT */ snprintf_add(proc_query, sizeof(proc_query), " has_function_privilege(p.oid, 'EXECUTE')"); if (IS_VALID_NAME(escSchemaName)) snprintf_add(proc_query, sizeof(proc_query), " and nspname %s'%s'", op_string, escSchemaName); if (escProcName) snprintf_add(proc_query, sizeof(proc_query), " and proname %s'%s'", op_string, escProcName); snprintf_add(proc_query, sizeof(proc_query), " order by nspname, proname, p.oid, attnum"); } else { strcpy(proc_query, "select proname, proretset, prorettype, " "pronargs, proargtypes from pg_proc where " "(not proretset)"); ret_col = 5; if (escProcName) snprintf_add(proc_query, sizeof(proc_query), " and proname %s'%s'", op_string, escProcName); snprintf_add(proc_query, sizeof(proc_query), " order by proname, proretset"); } if (tres = CC_send_query(conn, proc_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(tres)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_ProcedureColumns query error", func); QR_Destructor(tres); return SQL_ERROR; } if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_ProcedureColumns result.", func); return SQL_ERROR; } SC_set_Result(stmt, res); /* * the binding structure for a statement is not set up until * a statement is actually executed, so we'll have to do this * ourselves. */ result_cols = NUM_OF_PROCOLS_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; /* set the field names */ QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, PROCOLS_PROCEDURE_CAT, "PROCEDURE_CAT", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PROCOLS_PROCEDURE_SCHEM, "PROCEDUR_SCHEM", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PROCOLS_PROCEDURE_NAME, "PROCEDURE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PROCOLS_COLUMN_NAME, "COLUMN_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PROCOLS_COLUMN_TYPE, "COLUMN_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_DATA_TYPE, "DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_TYPE_NAME, "TYPE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PROCOLS_COLUMN_SIZE, "COLUMN_SIZE", PG_TYPE_INT4, 4); QR_set_field_info_v(res, PROCOLS_BUFFER_LENGTH, "BUFFER_LENGTH", PG_TYPE_INT4, 4); QR_set_field_info_v(res, PROCOLS_DECIMAL_DIGITS, "DECIMAL_DIGITS", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_NUM_PREC_RADIX, "NUM_PREC_RADIX", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_NULLABLE, "NULLABLE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_REMARKS, "REMARKS", PG_TYPE_VARCHAR, MAX_INFO_STRING); #if (ODBCVER >= 0x0300) QR_set_field_info_v(res, PROCOLS_COLUMN_DEF, "COLUMN_DEF", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, PROCOLS_SQL_DATA_TYPE, "SQL_DATA_TYPE", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_SQL_DATETIME_SUB, "SQL_DATETIME_SUB", PG_TYPE_INT2, 2); QR_set_field_info_v(res, PROCOLS_CHAR_OCTET_LENGTH, "CHAR_OCTET_LENGTH", PG_TYPE_INT4, 4); QR_set_field_info_v(res, PROCOLS_ORDINAL_POSITION, "ORDINAL_POSITION", PG_TYPE_INT4, 4); QR_set_field_info_v(res, PROCOLS_IS_NULLABLE, "IS_NULLABLE", PG_TYPE_VARCHAR, MAX_INFO_STRING); #endif /* ODBCVER >= 0x0300 */ column_name = make_string(szColumnName, cbColumnName, NULL, 0); if (column_name) /* column_name is unavailable now */ { tcount = 0; free(column_name); } else tcount = QR_get_num_total_tuples(tres); for (i = 0, poid = 0; i < tcount; i++) { if (conn->schema_support) schema_name = GET_SCHEMA_NAME(QR_get_value_backend_text(tres, i, 5)); else schema_name = NULL; procname = QR_get_value_backend_text(tres, i, 0); retset = QR_get_value_backend_text(tres, i, 1); pgtype = QR_get_value_backend_int(tres, i, 2, NULL); bRetset = retset && (retset[0] == 't' || retset[0] == 'y'); newpoid = 0; if (poid_pos >= 0) newpoid = QR_get_value_backend_int(tres, i, poid_pos, NULL); mylog("newpoid=%d\n", newpoid); atttypid = NULL; if (attid_pos >= 0) { atttypid = QR_get_value_backend_text(tres, i, attid_pos); mylog("atttypid=%s\n", atttypid ? atttypid : "(null)"); } if (poid == 0 || newpoid != poid) { poid = newpoid; proargmodes = NULL; proargnames = NULL; if (ext_pos >=0) { #ifdef DISPLAY_ARGNAME /* !! named parameter is unavailable !! */ if (PG_VERSION_GE(conn, 8.0)) proargnames = QR_get_value_backend_text(tres, i, ext_pos); #endif /* DISPLAY_ARGNAME */ if (PG_VERSION_GE(conn, 8.1)) proargmodes = QR_get_value_backend_text(tres, i, ext_pos + 1); } /* RETURN_VALUE info */ if (0 != pgtype && PG_TYPE_VOID != pgtype && !bRetset && !atttypid && !proargmodes) { tuple = QR_AddNew(res); set_tuplefield_string(&tuple[PROCOLS_PROCEDURE_CAT], CurrCat(conn)); set_nullfield_string(&tuple[PROCOLS_PROCEDURE_SCHEM], schema_name); set_tuplefield_string(&tuple[PROCOLS_PROCEDURE_NAME], procname); set_tuplefield_string(&tuple[PROCOLS_COLUMN_NAME], NULL_STRING); set_tuplefield_int2(&tuple[PROCOLS_COLUMN_TYPE], SQL_RETURN_VALUE); set_tuplefield_int2(&tuple[PROCOLS_DATA_TYPE], pgtype_to_concise_type(stmt, pgtype, PG_STATIC)); set_tuplefield_string(&tuple[PROCOLS_TYPE_NAME], pgtype_to_name(stmt, pgtype, PG_UNSPECIFIED, FALSE)); column_size = pgtype_column_size(stmt, pgtype, PG_STATIC, UNKNOWNS_AS_DEFAULT); set_nullfield_int4(&tuple[PROCOLS_COLUMN_SIZE], column_size); set_tuplefield_int4(&tuple[PROCOLS_BUFFER_LENGTH], pgtype_buffer_length(stmt, pgtype, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_nullfield_int2(&tuple[PROCOLS_DECIMAL_DIGITS], pgtype_decimal_digits(stmt, pgtype, PG_STATIC)); set_nullfield_int2(&tuple[PROCOLS_NUM_PREC_RADIX], pgtype_radix(conn, pgtype)); set_tuplefield_int2(&tuple[PROCOLS_NULLABLE], SQL_NULLABLE_UNKNOWN); set_tuplefield_null(&tuple[PROCOLS_REMARKS]); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[PROCOLS_COLUMN_DEF]); set_nullfield_int2(&tuple[PROCOLS_SQL_DATA_TYPE], pgtype_to_sqldesctype(stmt, pgtype, PG_STATIC)); set_nullfield_int2(&tuple[PROCOLS_SQL_DATETIME_SUB], pgtype_to_datetime_sub(stmt, pgtype, PG_UNSPECIFIED)); set_nullfield_int4(&tuple[PROCOLS_CHAR_OCTET_LENGTH], pgtype_attr_transfer_octet_length(conn, pgtype, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[PROCOLS_ORDINAL_POSITION], 0); set_tuplefield_string(&tuple[PROCOLS_IS_NULLABLE], NULL_STRING); #endif /* ODBCVER >= 0x0300 */ } if (proargmodes) { const char *p; paramcount = 0; for (p = proargmodes; *p; p++) { if (',' == (*p)) paramcount++; } paramcount++; params = QR_get_value_backend_text(tres, i, ext_pos + 2); if ('{' == *proargmodes) proargmodes++; if ('{' == *params) params++; } else { paramcount = QR_get_value_backend_int(tres, i, 3, NULL); params = QR_get_value_backend_text(tres, i, 4); } if (proargnames) { if ('{' == *proargnames) proargnames++; } /* PARAMETERS info */ for (j = 0; j < paramcount; j++) { /* PG type of parameters */ pgtype = 0; if (params) { while (isspace((unsigned char) *params) || ',' == *params) params++; if ('\0' == *params || '}' == *params) params = NULL; else { sscanf(params, "%u", &pgtype); while (isdigit((unsigned char) *params)) params++; } } /* input/output type of parameters */ if (proargmodes) { while (isspace((unsigned char) *proargmodes) || ',' == *proargmodes) proargmodes++; if ('\0' == *proargmodes || '}' == *proargmodes) proargmodes = NULL; } /* name of parameters */ if (proargnames) { while (isspace((unsigned char) *proargnames) || ',' == *proargnames) proargnames++; if ('\0' == *proargnames || '}' == *proargnames) proargnames = NULL; else if ('"' == *proargnames) { proargnames++; for (delim = proargnames; *delim && *delim != '"'; delim++) ; } else { for (delim = proargnames; *delim && !isspace((unsigned char) *delim) && ',' != *delim && '}' != *delim; delim++) ; } if (proargnames && '\0' == *delim) /* discard the incomplete name */ proargnames = NULL; } tuple = QR_AddNew(res); set_tuplefield_string(&tuple[PROCOLS_PROCEDURE_CAT], CurrCat(conn)); set_nullfield_string(&tuple[PROCOLS_PROCEDURE_SCHEM], schema_name); set_tuplefield_string(&tuple[PROCOLS_PROCEDURE_NAME], procname); if (proargnames) { *delim = '\0'; set_tuplefield_string(&tuple[PROCOLS_COLUMN_NAME], proargnames); proargnames = delim + 1; } else set_tuplefield_string(&tuple[PROCOLS_COLUMN_NAME], NULL_STRING); if (proargmodes) { int ptype; switch (*proargmodes) { case 'o': ptype = SQL_PARAM_OUTPUT; break; case 'b': ptype = SQL_PARAM_INPUT_OUTPUT; break; default: ptype = SQL_PARAM_INPUT; break; } set_tuplefield_int2(&tuple[PROCOLS_COLUMN_TYPE], ptype); proargmodes++; } else set_tuplefield_int2(&tuple[PROCOLS_COLUMN_TYPE], SQL_PARAM_INPUT); set_tuplefield_int2(&tuple[PROCOLS_DATA_TYPE], pgtype_to_concise_type(stmt, pgtype, PG_STATIC)); set_tuplefield_string(&tuple[PROCOLS_TYPE_NAME], pgtype_to_name(stmt, pgtype, PG_UNSPECIFIED, FALSE)); column_size = pgtype_column_size(stmt, pgtype, PG_STATIC, UNKNOWNS_AS_DEFAULT); set_nullfield_int4(&tuple[PROCOLS_COLUMN_SIZE], column_size); set_tuplefield_int4(&tuple[PROCOLS_BUFFER_LENGTH], pgtype_buffer_length(stmt, pgtype, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_nullfield_int2(&tuple[PROCOLS_DECIMAL_DIGITS], pgtype_decimal_digits(stmt, pgtype, PG_STATIC)); set_nullfield_int2(&tuple[PROCOLS_NUM_PREC_RADIX], pgtype_radix(conn, pgtype)); set_tuplefield_int2(&tuple[PROCOLS_NULLABLE], SQL_NULLABLE_UNKNOWN); set_tuplefield_null(&tuple[PROCOLS_REMARKS]); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[PROCOLS_COLUMN_DEF]); set_nullfield_int2(&tuple[PROCOLS_SQL_DATA_TYPE], pgtype_to_sqldesctype(stmt, pgtype, PG_STATIC)); set_nullfield_int2(&tuple[PROCOLS_SQL_DATETIME_SUB], pgtype_to_datetime_sub(stmt, pgtype, PG_UNSPECIFIED)); set_nullfield_int4(&tuple[PROCOLS_CHAR_OCTET_LENGTH], pgtype_attr_transfer_octet_length(conn, pgtype, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[PROCOLS_ORDINAL_POSITION], j + 1); set_tuplefield_string(&tuple[PROCOLS_IS_NULLABLE], NULL_STRING); #endif /* ODBCVER >= 0x0300 */ } } /* RESULT Columns info */ if (NULL != atttypid || bRetset) { int typid; if (bRetset) { typid = pgtype; attname = NULL; } else { typid = atoi(atttypid); attname = QR_get_value_backend_text(tres, i, attname_pos); } tuple = QR_AddNew(res); set_tuplefield_string(&tuple[PROCOLS_PROCEDURE_CAT], CurrCat(conn)); set_nullfield_string(&tuple[PROCOLS_PROCEDURE_SCHEM], schema_name); set_tuplefield_string(&tuple[PROCOLS_PROCEDURE_NAME], procname); set_tuplefield_string(&tuple[PROCOLS_COLUMN_NAME], attname); set_tuplefield_int2(&tuple[PROCOLS_COLUMN_TYPE], SQL_RESULT_COL); set_tuplefield_int2(&tuple[PROCOLS_DATA_TYPE], pgtype_to_concise_type(stmt, typid, PG_STATIC)); set_tuplefield_string(&tuple[PROCOLS_TYPE_NAME], pgtype_to_name(stmt, typid, PG_UNSPECIFIED, FALSE)); column_size = pgtype_column_size(stmt, typid, PG_STATIC, UNKNOWNS_AS_DEFAULT); set_nullfield_int4(&tuple[PROCOLS_COLUMN_SIZE], column_size); set_tuplefield_int4(&tuple[PROCOLS_BUFFER_LENGTH], pgtype_buffer_length(stmt, typid, PG_STATIC, UNKNOWNS_AS_DEFAULT)); set_nullfield_int2(&tuple[PROCOLS_DECIMAL_DIGITS], pgtype_decimal_digits(stmt, typid, PG_STATIC)); set_nullfield_int2(&tuple[PROCOLS_NUM_PREC_RADIX], pgtype_radix(conn, typid)); set_tuplefield_int2(&tuple[PROCOLS_NULLABLE], SQL_NULLABLE_UNKNOWN); set_tuplefield_null(&tuple[PROCOLS_REMARKS]); #if (ODBCVER >= 0x0300) set_tuplefield_null(&tuple[PROCOLS_COLUMN_DEF]); set_nullfield_int2(&tuple[PROCOLS_SQL_DATA_TYPE], pgtype_to_sqldesctype(stmt, typid, PG_STATIC)); set_nullfield_int2(&tuple[PROCOLS_SQL_DATETIME_SUB], pgtype_to_datetime_sub(stmt, typid, PG_UNSPECIFIED)); set_nullfield_int4(&tuple[PROCOLS_CHAR_OCTET_LENGTH], pgtype_attr_transfer_octet_length(conn, typid, PG_UNSPECIFIED, UNKNOWNS_AS_DEFAULT)); set_tuplefield_int4(&tuple[PROCOLS_ORDINAL_POSITION], 0); set_tuplefield_string(&tuple[PROCOLS_IS_NULLABLE], NULL_STRING); #endif /* ODBCVER >= 0x0300 */ } } QR_Destructor(tres); /* * also, things need to think that this statement is finished so the * results can be retrieved. */ if (escSchemaName) free(escSchemaName); if (escProcName) free(escProcName); stmt->status = STMT_FINISHED; /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); return SQL_SUCCESS; } RETCODE SQL_API PGAPI_Procedures(HSTMT hstmt, const SQLCHAR FAR * szProcQualifier, /* OA X*/ SQLSMALLINT cbProcQualifier, const SQLCHAR FAR * szProcOwner, /* PV E*/ SQLSMALLINT cbProcOwner, const SQLCHAR FAR * szProcName, /* PV E*/ SQLSMALLINT cbProcName, UWORD flag) { CSTR func = "PGAPI_Procedures"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn = SC_get_conn(stmt); char proc_query[INFO_INQUIRY_LEN]; char *escSchemaName = NULL, *escProcName = NULL; QResultClass *res; RETCODE result; const char *like_or_eq, *op_string; BOOL search_pattern; mylog("%s: entering... scnm=%p len=%d\n", func, szProcOwner, cbProcOwner); if (PG_VERSION_LT(conn, 6.5)) { SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "Version is too old", func); return SQL_ERROR; } if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; search_pattern = (0 == (flag & PODBC_NOT_SEARCH_PATTERN)); if (search_pattern) { like_or_eq = likeop; escSchemaName = adjustLikePattern(szProcOwner, cbProcOwner, SEARCH_PATTERN_ESCAPE, NULL, conn); escProcName = adjustLikePattern(szProcName, cbProcName, SEARCH_PATTERN_ESCAPE, NULL, conn); } else { like_or_eq = eqop; escSchemaName = simpleCatalogEscape(szProcOwner, cbProcOwner, NULL, conn); escProcName = simpleCatalogEscape(szProcName, cbProcName, NULL, conn); } /* * The following seems the simplest implementation */ op_string = gen_opestr(like_or_eq, conn); if (conn->schema_support) { strcpy(proc_query, "select '' as " "PROCEDURE_CAT" ", nspname as " "PROCEDURE_SCHEM" "," " proname as " "PROCEDURE_NAME" ", '' as " "NUM_INPUT_PARAMS" "," " '' as " "NUM_OUTPUT_PARAMS" ", '' as " "NUM_RESULT_SETS" "," " '' as " "REMARKS" "," " case when prorettype = 0 then 1::int2 else 2::int2 end" " as " "PROCEDURE_TYPE" " from pg_catalog.pg_namespace," " pg_catalog.pg_proc" " where pg_proc.pronamespace = pg_namespace.oid"); schema_strcat1(proc_query, " and nspname %s'%.*s'", op_string, escSchemaName, SQL_NTS, szProcName, cbProcName, conn); if (IS_VALID_NAME(escProcName)) snprintf_add(proc_query, sizeof(proc_query), " and proname %s'%s'", op_string, escProcName); } else { snprintf(proc_query, sizeof(proc_query), "select '' as " "PROCEDURE_CAT" ", '' as " "PROCEDURE_SCHEM" "," " proname as " "PROCEDURE_NAME" ", '' as " "NUM_INPUT_PARAMS" "," " '' as " "NUM_OUTPUT_PARAMS" ", '' as " "NUM_RESULT_SETS" "," " '' as " "REMARKS" "," " case when prorettype = 0 then 1::int2 else 2::int2 end as " "PROCEDURE_TYPE" " from pg_proc"); if (IS_VALID_NAME(escSchemaName)) snprintf_add(proc_query, sizeof(proc_query), " where proname %s'%s'", op_string, escSchemaName); } if (res = CC_send_query(conn, proc_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_Procedures query error", func); QR_Destructor(res); return SQL_ERROR; } SC_set_Result(stmt, res); /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; extend_column_bindings(SC_get_ARDF(stmt), 8); if (escSchemaName) free(escSchemaName); if (escProcName) free(escProcName); /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); return SQL_SUCCESS; } #define ACLMAX 8 #define ALL_PRIVILIGES "arwdRxt" static int usracl_auth(char *usracl, const char *auth) { int i, j, addcnt = 0; for (i = 0; auth[i]; i++) { for (j = 0; j < ACLMAX; j++) { if (usracl[j] == auth[i]) break; else if (!usracl[j]) { usracl[j]= auth[i]; addcnt++; break; } } } return addcnt; } static void useracl_upd(char (*useracl)[ACLMAX], QResultClass *allures, const char *user, const char *auth) { int usercount = (int) QR_get_num_cached_tuples(allures), i, addcnt = 0; mylog("user=%s auth=%s\n", user, auth); if (user[0]) for (i = 0; i < usercount; i++) { if (strcmp(QR_get_value_backend_text(allures, i, 0), user) == 0) { addcnt += usracl_auth(useracl[i], auth); break; } } else for (i = 0; i < usercount; i++) { addcnt += usracl_auth(useracl[i], auth); } mylog("addcnt=%d\n", addcnt); } RETCODE SQL_API PGAPI_TablePrivileges(HSTMT hstmt, const SQLCHAR FAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR FAR * szTableOwner, /* PV E*/ SQLSMALLINT cbTableOwner, const SQLCHAR FAR * szTableName, /* PV E*/ SQLSMALLINT cbTableName, UWORD flag) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_TablePrivileges"; ConnectionClass *conn = SC_get_conn(stmt); Int2 result_cols; char proc_query[INFO_INQUIRY_LEN]; QResultClass *res, *wres = NULL, *allures = NULL; TupleField *tuple; Int4 tablecount, usercount, i, j, k; BOOL grpauth, sys, su; char (*useracl)[ACLMAX] = NULL, *acl, *user, *delim, *auth; const char *reln, *owner, *priv, *schnm = NULL; RETCODE result, ret = SQL_SUCCESS; const char *like_or_eq, *op_string; const SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; char *escSchemaName = NULL, *escTableName = NULL; BOOL search_pattern; mylog("%s: entering... scnm=%p len-%d\n", func, szTableOwner, cbTableOwner); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; /* * a statement is actually executed, so we'll have to do this * ourselves. */ result_cols = 7; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; /* set the field names */ res = QR_Constructor(); SC_set_Result(stmt, res); QR_set_num_fields(res, result_cols); QR_set_field_info_v(res, 0, "TABLE_CAT", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 1, "TABLE_SCHEM", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 2, "TABLE_NAME", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 3, "GRANTOR", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 4, "GRANTEE", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 5, "PRIVILEGE", PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_v(res, 6, "IS_GRANTABLE", PG_TYPE_VARCHAR, MAX_INFO_STRING); /* * also, things need to think that this statement is finished so the * results can be retrieved. */ stmt->status = STMT_FINISHED; /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; #define return DONT_CALL_RETURN_FROM_HERE??? search_pattern = (0 == (flag & PODBC_NOT_SEARCH_PATTERN)); if (search_pattern) { like_or_eq = likeop; escTableName = adjustLikePattern(szTableName, cbTableName, SEARCH_PATTERN_ESCAPE, NULL, conn); } else { like_or_eq = eqop; escTableName = simpleCatalogEscape(szTableName, cbTableName, NULL, conn); } retry_public_schema: if (escSchemaName) free(escSchemaName); if (search_pattern) escSchemaName = adjustLikePattern(szSchemaName, cbSchemaName, SEARCH_PATTERN_ESCAPE, NULL, conn); else escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, NULL, conn); op_string = gen_opestr(like_or_eq, conn); if (conn->schema_support) strncpy_null(proc_query, "select relname, usename, relacl, nspname" " from pg_catalog.pg_namespace, pg_catalog.pg_class ," " pg_catalog.pg_user where", sizeof(proc_query)); else strncpy_null(proc_query, "select relname, usename, relacl" " from pg_class , pg_user where", sizeof(proc_query)); if (conn->schema_support) { if (escSchemaName) schema_strcat1(proc_query, " nspname %s'%.*s' and", op_string, escSchemaName, SQL_NTS, szTableName, cbTableName, conn); } if (escTableName) snprintf_add(proc_query, sizeof(proc_query), " relname %s'%s' and", op_string, escTableName); if (conn->schema_support) { strcat(proc_query, " pg_namespace.oid = relnamespace and relkind in ('r', 'v') and"); if ((!escTableName) && (!escSchemaName)) strcat(proc_query, " nspname not in ('pg_catalog', 'information_schema') and"); } strcat(proc_query, " pg_user.usesysid = relowner"); if (wres = CC_send_query(conn, proc_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(wres)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_TablePrivileges query error", func); ret = SQL_ERROR; goto cleanup; } tablecount = (Int4) QR_get_num_cached_tuples(wres); /* If not found */ if (conn->schema_support && (flag & PODBC_SEARCH_PUBLIC_SCHEMA) != 0 && 0 == tablecount) { if (allow_public_schema(conn, szSchemaName, cbSchemaName)) { QR_Destructor(wres); wres = NULL; szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } } strncpy_null(proc_query, "select usename, usesysid, usesuper from pg_user", sizeof(proc_query)); if (allures = CC_send_query(conn, proc_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(allures)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_TablePrivileges query error", func); ret = SQL_ERROR; goto cleanup; } usercount = (Int4) QR_get_num_cached_tuples(allures); useracl = (char (*)[ACLMAX]) malloc(usercount * sizeof(char [ACLMAX])); for (i = 0; i < tablecount; i++) { memset(useracl, 0, usercount * sizeof(char[ACLMAX])); acl = (char *) QR_get_value_backend_text(wres, i, 2); if (acl && acl[0] == '{') user = acl + 1; else user = NULL; for (; user && *user;) { grpauth = FALSE; if (user[0] == '"' && strncmp(user + 1, "group ", 6) == 0) { user += 7; grpauth = TRUE; } if (delim = strchr(user, '='), !delim) break; *delim = '\0'; auth = delim + 1; if (grpauth) { if (delim = strchr(auth, '"'), delim) { *delim = '\0'; delim++; } } else if (delim = strchr(auth, ','), delim) *delim = '\0'; else if (delim = strchr(auth, '}'), delim) *delim = '\0'; if (grpauth) /* handle group privilege */ { QResultClass *gres; int i; char *grolist, *uid, *delm; snprintf(proc_query, sizeof(proc_query) - 1, "select grolist from pg_group where groname = '%s'", user); if (gres = CC_send_query(conn, proc_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(gres)) { grolist = QR_get_value_backend_text(gres, 0, 0); if (grolist && grolist[0] == '{') { for (uid = grolist + 1; *uid;) { if (delm = strchr(uid, ','), delm) *delm = '\0'; else if (delm = strchr(uid, '}'), delm) *delm = '\0'; mylog("guid=%s\n", uid); for (i = 0; i < usercount; i++) { if (strcmp(QR_get_value_backend_text(allures, i, 1), uid) == 0) useracl_upd(useracl, allures, QR_get_value_backend_text(allures, i, 0), auth); } uid = delm + 1; } } } QR_Destructor(gres); } else useracl_upd(useracl, allures, user, auth); if (!delim) break; user = delim + 1; } reln = QR_get_value_backend_text(wres, i, 0); owner = QR_get_value_backend_text(wres, i, 1); if (conn->schema_support) schnm = QR_get_value_backend_text(wres, i, 3); /* The owner has all privileges */ useracl_upd(useracl, allures, owner, ALL_PRIVILIGES); for (j = 0; j < usercount; j++) { user = QR_get_value_backend_text(allures, j, 0); su = (strcmp(QR_get_value_backend_text(allures, j, 2), "t") == 0); sys = (strcmp(user, owner) == 0); /* Super user has all privileges */ if (su) useracl_upd(useracl, allures, user, ALL_PRIVILIGES); for (k = 0; k < ACLMAX; k++) { if (!useracl[j][k]) break; switch (useracl[j][k]) { case 'R': /* rule */ case 't': /* trigger */ continue; } tuple = QR_AddNew(res); set_tuplefield_string(&tuple[0], CurrCat(conn)); if (conn->schema_support) set_tuplefield_string(&tuple[1], GET_SCHEMA_NAME(schnm)); else set_tuplefield_string(&tuple[1], NULL_STRING); set_tuplefield_string(&tuple[2], reln); if (su || sys) set_tuplefield_string(&tuple[3], "_SYSTEM"); else set_tuplefield_string(&tuple[3], owner); mylog("user=%s\n", user); set_tuplefield_string(&tuple[4], user); switch (useracl[j][k]) { case 'a': priv = "INSERT"; break; case 'r': priv = "SELECT"; break; case 'w': priv = "UPDATE"; break; case 'd': priv = "DELETE"; break; case 'x': priv = "REFERENCES"; break; default: priv = NULL_STRING; } set_tuplefield_string(&tuple[5], priv); /* The owner and the super user are grantable */ if (sys || su) set_tuplefield_string(&tuple[6], "YES"); else set_tuplefield_string(&tuple[6], "NO"); } } } cleanup: #undef return if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (useracl) free(useracl); if (wres) QR_Destructor(wres); if (allures) QR_Destructor(allures); if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); return ret; } static RETCODE SQL_API PGAPI_ForeignKeys_new(HSTMT hstmt, const SQLCHAR FAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR FAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR FAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR FAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR FAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR FAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName) { CSTR func = "PGAPI_ForeignKeys"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res = NULL; RETCODE ret = SQL_ERROR, result; char tables_query[INFO_INQUIRY_LEN]; char *pk_table_needed = NULL, *escTableName = NULL; char *fk_table_needed = NULL; char schema_needed[SCHEMA_NAME_STORAGE_LEN + 1]; char catName[SCHEMA_NAME_STORAGE_LEN], scmName1[SCHEMA_NAME_STORAGE_LEN], scmName2[SCHEMA_NAME_STORAGE_LEN]; const char *relqual; ConnectionClass *conn = SC_get_conn(stmt); const char *eq_string; mylog("%s: entering...stmt=%p\n", func, stmt); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; schema_needed[0] = '\0'; #define return DONT_CALL_RETURN_FROM_HERE??? pk_table_needed = make_string(szPkTableName, cbPkTableName, NULL, 0); fk_table_needed = make_string(szFkTableName, cbFkTableName, NULL, 0); eq_string = gen_opestr(eqop, conn); /* * Case #2 -- Get the foreign keys in the specified table (fktab) that * refer to the primary keys of other table(s). */ if (NULL != fk_table_needed) { mylog("%s: entering Foreign Key Case #2", func); escTableName = simpleCatalogEscape((SQLCHAR *) fk_table_needed, SQL_NTS, NULL, conn); schema_strcat(schema_needed, "%.*s", szFkTableOwner, cbFkTableOwner, szFkTableName, cbFkTableName, conn); relqual = "\n and conrelid = c.oid"; } /* * Case #1 -- Get the foreign keys in other tables that refer to the * primary key in the specified table (pktab). i.e., Who points to * me? */ else if (NULL != pk_table_needed) { escTableName = simpleCatalogEscape((SQLCHAR *) pk_table_needed, SQL_NTS, NULL, conn); schema_strcat(schema_needed, "%.*s", szPkTableOwner, cbPkTableOwner, szPkTableName, cbPkTableName, conn); relqual = "\n and confrelid = c.oid"; } else { SC_set_error(stmt, STMT_INTERNAL_ERROR, "No tables specified to PGAPI_ForeignKeys.", func); goto cleanup; } if (conn->schema_support) { char *escSchemaName; if (NULL != CurrCat(conn)) snprintf(catName, sizeof(catName), "'%s'::name", CurrCat(conn)); else strcpy(catName, "NULL::name"); strcpy(scmName1, "n2.nspname"); strcpy(scmName2, "n1.nspname"); escSchemaName = simpleCatalogEscape((SQLCHAR *) schema_needed, SQL_NTS, NULL, conn); snprintf(tables_query, sizeof(tables_query), "select" " %s as PKTABLE_CAT" ",\n %s as PKTABLE_SCHEM" ",\n c2.relname as PKTABLE_NAME" ",\n a2.attname as PKCOLUMN_NAME" ",\n %s as FKTABLE_CAT" ",\n %s as FKTABLE_SCHEM" ",\n c1.relname as FKTABLE_NAME" ",\n a1.attname as FKCOLUMN_NAME" ",\n i::int2 as KEY_SEQ" ",\n case ref.confupdtype" "\n when 'c' then %d::int2" "\n when 'n' then %d::int2" "\n when 'd' then %d::int2" "\n when 'r' then %d::int2" "\n else %d::int2" "\n end as UPDATE_RULE" ",\n case ref.confdeltype" "\n when 'c' then %d::int2" "\n when 'n' then %d::int2" "\n when 'd' then %d::int2" "\n when 'r' then %d::int2" "\n else %d::int2" "\n end as DELETE_RULE" ",\n ref.conname as FK_NAME" ",\n cn.conname as PK_NAME" #if (ODBCVER >= 0x0300) ",\n case" "\n when ref.condeferrable then" "\n case" "\n when ref.condeferred then %d::int2" "\n else %d::int2" "\n end" "\n else %d::int2" "\n end as DEFERRABLITY" #endif /* ODBCVER */ "\n from" "\n (((((((" " (select cn.oid, conrelid, conkey, confrelid, confkey" ",\n generate_series(array_lower(conkey, 1), array_upper(conkey, 1)) as i" ",\n confupdtype, confdeltype, conname" ",\n condeferrable, condeferred" "\n from pg_catalog.pg_constraint cn" ",\n pg_catalog.pg_class c" ",\n pg_catalog.pg_namespace n" "\n where contype = 'f' %s" "\n and relname %s'%s'" "\n and n.oid = c.relnamespace" "\n and n.nspname %s'%s'" "\n ) ref" "\n inner join pg_catalog.pg_class c1" "\n on c1.oid = ref.conrelid)" "\n inner join pg_catalog.pg_namespace n1" "\n on n1.oid = c1.relnamespace)" "\n inner join pg_catalog.pg_attribute a1" "\n on a1.attrelid = c1.oid" "\n and a1.attnum = conkey[i])" "\n inner join pg_catalog.pg_class c2" "\n on c2.oid = ref.confrelid)" "\n inner join pg_catalog.pg_namespace n2" "\n on n2.oid = c2.relnamespace)" "\n inner join pg_catalog.pg_attribute a2" "\n on a2.attrelid = c2.oid" "\n and a2.attnum = confkey[i])" "\n left outer join pg_catalog.pg_constraint cn" "\n on cn.conrelid = ref.confrelid" "\n and cn.contype = 'p')" , catName , scmName1 , catName , scmName2 , SQL_CASCADE , SQL_SET_NULL , SQL_SET_DEFAULT , SQL_RESTRICT , SQL_NO_ACTION , SQL_CASCADE , SQL_SET_NULL , SQL_SET_DEFAULT , SQL_RESTRICT , SQL_NO_ACTION #if (ODBCVER >= 0x0300) , SQL_INITIALLY_DEFERRED , SQL_INITIALLY_IMMEDIATE , SQL_NOT_DEFERRABLE #endif /* ODBCVER */ , relqual , eq_string, escTableName , eq_string, escSchemaName); free(escSchemaName); if (NULL != pk_table_needed && NULL != fk_table_needed) { free(escTableName); escTableName = simpleCatalogEscape((SQLCHAR *) pk_table_needed, SQL_NTS, NULL, conn); snprintf_add(tables_query, sizeof(tables_query), "\n where c2.relname %s'%s'", eq_string, escTableName); } strcat(tables_query, "\n order by ref.oid, ref.i"); } else { strcpy(catName, "NULL::name"); strcpy(scmName1, "NULL::name"); strcpy(scmName2, "NULL::name"); snprintf(tables_query, sizeof(tables_query), "select %s as PKTABLE_CAT" ",\n %s as PKTABLE_SCHEM" ",\n c2.relname as PKTABLE_NAME" ",\n a2.attname as PKCOLUMN_NAME" ",\n %s as FKTABLE_CAT" ",\n %s as FKTABLE_SCHEM" ",\n c1.relname as FKTABLE_NAME" ",\n a1.attname as FKCOLUMN_NAME" ",\n i::int2 as KEY_SEQ" ",\n case confupdtype" "\n when 'c' then %d::int2" "\n when 'n' then %d::int2" "\n when 'd' then %d::int2" "\n when 'r' then %d::int2" "\n else %d::int2" "\n end as UPDATE_RULE" ",\n case confdeltype" "\n when 'c' then %d::int2" "\n when 'n' then %d::int2" "\n when 'd' then %d::int2" "\n when 'r' then %d::int2" "\n else %d::int2" "\n end as DELETE_RULE" ",\n conname as FK_NAME" ",\n NULL::name as PK_NAME" #if (ODBCVER >= 0x0300) ",\n case" "\n when condeferrable then" "\n case" "\n when condeferred then %d::int2" "\n else %d::int2" "\n end" "\n else %d::int2" "\n end as DEFERRABLITY" #endif /* ODBCVER */ "\n from" "\n (select conrelid, conkey, confrelid, confkey" ",\n generate_series(array_lower(conkey, 1), array_upper(conkey, 1)) as i" ",\n confupdtype, confdeltype, conname" ",\n condeferrable, condeferred" "\n from pg_catalog.pg_constraint cn" ",\n pg_catalog.pg_class c" "\n where contype = 'f' %s" "\n and relname %s'%s'" "\n ) ref" ",\n pg_catalog.pg_class c1" ",\n pg_catalog.pg_attribute a1" ",\n pg_catalog.pg_class c2" ",\n pg_catalog.pg_attribute a2" "\n where c1.oid = ref.conrelid" "\n and c2.oid = ref.confrelid" "\n and a1.attrelid = c1.oid" "\n and a1.attnum = conkey[i]" "\n and a2.attrelid = c2.oid" "\n and a2.attnum = confkey[i]" "\n order by ref.oid, ref.i" , catName , scmName1 , catName , scmName2 , SQL_CASCADE , SQL_SET_NULL , SQL_SET_DEFAULT , SQL_RESTRICT , SQL_NO_ACTION , SQL_CASCADE , SQL_SET_NULL , SQL_SET_DEFAULT , SQL_RESTRICT , SQL_NO_ACTION #if (ODBCVER >= 0x0300) , SQL_INITIALLY_DEFERRED , SQL_INITIALLY_IMMEDIATE , SQL_NOT_DEFERRABLE #endif /* ODBCVER */ , relqual, eq_string, escTableName); } if (res = CC_send_query(conn, tables_query, NULL, IGNORE_ABORT_ON_CONN, stmt), !QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_ForeignKeys query error", func); QR_Destructor(res); goto cleanup; } SC_set_Result(stmt, res); ret = SQL_SUCCESS; cleanup: #undef return /* * also, things need to think that this statement is finished so the * results can be retrieved. */ if (SQL_SUCCEEDED(ret)) { stmt->status = STMT_FINISHED; extend_column_bindings(SC_get_ARDF(stmt), QR_NumResultCols(res)); } if (pk_table_needed) free(pk_table_needed); if (escTableName) free(escTableName); if (fk_table_needed) free(fk_table_needed); /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); mylog("%s(): EXIT, stmt=%p, ret=%d\n", func, stmt, ret); return ret; } psqlodbc-09.03.0300/bind.c000644 001752 000000 00000064753 12335653444 015277 0ustar00saitowheel000000 000000 /*------- * Module: bind.c * * Description: This module contains routines related to binding * columns and parameters. * * Classes: BindInfoClass, ParameterInfoClass * * API functions: SQLBindParameter, SQLBindCol, SQLDescribeParam, SQLNumParams, * SQLParamOptions * * Comments: See "readme.txt" for copyright and license information. *------- */ /* #include */ #include #include #include "bind.h" #include "misc.h" #include "environ.h" #include "statement.h" #include "descriptor.h" #include "qresult.h" #include "pgtypes.h" #include "multibyte.h" #include "pgapifunc.h" /* Bind parameters on a statement handle */ RETCODE SQL_API PGAPI_BindParameter(HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT fParamType, SQLSMALLINT fCType, SQLSMALLINT fSqlType, SQLULEN cbColDef, SQLSMALLINT ibScale, PTR rgbValue, SQLLEN cbValueMax, SQLLEN FAR * pcbValue) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_BindParameter"; APDFields *apdopts; IPDFields *ipdopts; PutDataInfo *pdata_info; mylog("%s: entering...\n", func); if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } SC_clear_error(stmt); apdopts = SC_get_APDF(stmt); if (apdopts->allocated < ipar) extend_parameter_bindings(apdopts, ipar); ipdopts = SC_get_IPDF(stmt); if (ipdopts->allocated < ipar) extend_iparameter_bindings(ipdopts, ipar); pdata_info = SC_get_PDTI(stmt); if (pdata_info->allocated < ipar) extend_putdata_info(pdata_info, ipar, FALSE); /* use zero based column numbers for the below part */ ipar--; /* store the given info */ apdopts->parameters[ipar].buflen = cbValueMax; apdopts->parameters[ipar].buffer = rgbValue; apdopts->parameters[ipar].used = apdopts->parameters[ipar].indicator = pcbValue; apdopts->parameters[ipar].CType = fCType; ipdopts->parameters[ipar].SQLType = fSqlType; ipdopts->parameters[ipar].paramType = fParamType; ipdopts->parameters[ipar].column_size = cbColDef; ipdopts->parameters[ipar].decimal_digits = ibScale; ipdopts->parameters[ipar].precision = 0; ipdopts->parameters[ipar].scale = 0; #if (ODBCVER >= 0x0300) switch (fCType) { case SQL_C_NUMERIC: if (cbColDef > 0) ipdopts->parameters[ipar].precision = (UInt2) cbColDef; if (ibScale > 0) ipdopts->parameters[ipar].scale = ibScale; break; case SQL_C_TYPE_TIMESTAMP: if (ibScale > 0) ipdopts->parameters[ipar].precision = ibScale; break; case SQL_C_INTERVAL_DAY_TO_SECOND: case SQL_C_INTERVAL_HOUR_TO_SECOND: case SQL_C_INTERVAL_MINUTE_TO_SECOND: case SQL_C_INTERVAL_SECOND: ipdopts->parameters[ipar].precision = 6; break; } apdopts->parameters[ipar].precision = ipdopts->parameters[ipar].precision; apdopts->parameters[ipar].scale = ipdopts->parameters[ipar].scale; #endif /* ODBCVER */ /* * If rebinding a parameter that had data-at-exec stuff in it, then * free that stuff */ if (pdata_info->pdata[ipar].EXEC_used) { free(pdata_info->pdata[ipar].EXEC_used); pdata_info->pdata[ipar].EXEC_used = NULL; } if (pdata_info->pdata[ipar].EXEC_buffer) { free(pdata_info->pdata[ipar].EXEC_buffer); pdata_info->pdata[ipar].EXEC_buffer = NULL; } if (pcbValue && apdopts->param_offset_ptr) pcbValue = LENADDR_SHIFT(pcbValue, *apdopts->param_offset_ptr); #ifdef NOT_USED /* evaluation of pcbValue here is dangerous */ /* Data at exec macro only valid for C char/binary data */ if (pcbValue && (*pcbValue == SQL_DATA_AT_EXEC || *pcbValue <= SQL_LEN_DATA_AT_EXEC_OFFSET)) apdopts->parameters[ipar].data_at_exec = TRUE; else apdopts->parameters[ipar].data_at_exec = FALSE; #endif /* NOT_USED */ /* Clear premature result */ if (stmt->status == STMT_PREMATURE) SC_recycle_statement(stmt); mylog("%s: ipar=%d, paramType=%d, fCType=%d, fSqlType=%d, cbColDef=%d, ibScale=%d,", func, ipar, fParamType, fCType, fSqlType, cbColDef, ibScale); mylog("rgbValue=%p(%d), pcbValue=%p\n", rgbValue, cbValueMax, pcbValue); return SQL_SUCCESS; } /* Associate a user-supplied buffer with a database column. */ RETCODE SQL_API PGAPI_BindCol(HSTMT hstmt, SQLUSMALLINT icol, SQLSMALLINT fCType, PTR rgbValue, SQLLEN cbValueMax, SQLLEN FAR * pcbValue) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_BindCol"; ARDFields *opts; GetDataInfo *gdata_info; BindInfoClass *bookmark; RETCODE ret = SQL_SUCCESS; mylog("%s: entering...\n", func); mylog("**** PGAPI_BindCol: stmt = %p, icol = %d\n", stmt, icol); mylog("**** : fCType=%d rgb=%p valusMax=%d pcb=%p\n", fCType, rgbValue, cbValueMax, pcbValue); if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } opts = SC_get_ARDF(stmt); if (stmt->status == STMT_EXECUTING) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Can't bind columns while statement is still executing.", func); return SQL_ERROR; } #define return DONT_CALL_RETURN_FROM_HERE ??? SC_clear_error(stmt); /* If the bookmark column is being bound, then just save it */ if (icol == 0) { bookmark = opts->bookmark; if (rgbValue == NULL) { if (bookmark) { bookmark->buffer = NULL; bookmark->used = bookmark->indicator = NULL; } } else { /* Make sure it is the bookmark data type */ switch (fCType) { case SQL_C_BOOKMARK: #if (ODBCVER >= 0x0300) case SQL_C_VARBOOKMARK: #endif /* ODBCVER */ break; default: SC_set_error(stmt, STMT_PROGRAM_TYPE_OUT_OF_RANGE, "Bind column 0 is not of type SQL_C_BOOKMARK", func); inolog("Bind column 0 is type %d not of type SQL_C_BOOKMARK", fCType); ret = SQL_ERROR; goto cleanup; } bookmark = ARD_AllocBookmark(opts); bookmark->buffer = rgbValue; bookmark->used = bookmark->indicator = pcbValue; bookmark->buflen = cbValueMax; bookmark->returntype = fCType; } goto cleanup; } /* * Allocate enough bindings if not already done. Most likely, * execution of a statement would have setup the necessary bindings. * But some apps call BindCol before any statement is executed. */ if (icol > opts->allocated) extend_column_bindings(opts, icol); gdata_info = SC_get_GDTI(stmt); if (icol > gdata_info->allocated) extend_getdata_info(gdata_info, icol, FALSE); /* check to see if the bindings were allocated */ if (!opts->bindings) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for bindings.", func); ret = SQL_ERROR; goto cleanup; } /* use zero based col numbers from here out */ icol--; /* Reset for SQLGetData */ gdata_info->gdata[icol].data_left = -1; if (rgbValue == NULL) { /* we have to unbind the column */ opts->bindings[icol].buflen = 0; opts->bindings[icol].buffer = NULL; opts->bindings[icol].used = opts->bindings[icol].indicator = NULL; opts->bindings[icol].returntype = SQL_C_CHAR; opts->bindings[icol].precision = 0; opts->bindings[icol].scale = 0; if (gdata_info->gdata[icol].ttlbuf) free(gdata_info->gdata[icol].ttlbuf); gdata_info->gdata[icol].ttlbuf = NULL; gdata_info->gdata[icol].ttlbuflen = 0; gdata_info->gdata[icol].ttlbufused = 0; } else { /* ok, bind that column */ opts->bindings[icol].buflen = cbValueMax; opts->bindings[icol].buffer = rgbValue; opts->bindings[icol].used = opts->bindings[icol].indicator = pcbValue; opts->bindings[icol].returntype = fCType; opts->bindings[icol].precision = 0; #if (ODBCVER >= 0x0300) switch (fCType) { case SQL_C_NUMERIC: opts->bindings[icol].precision = 32; break; case SQL_C_TIMESTAMP: case SQL_C_INTERVAL_DAY_TO_SECOND: case SQL_C_INTERVAL_HOUR_TO_SECOND: case SQL_C_INTERVAL_MINUTE_TO_SECOND: case SQL_C_INTERVAL_SECOND: opts->bindings[icol].precision = 6; break; } #endif /* ODBCVER */ opts->bindings[icol].scale = 0; mylog(" bound buffer[%d] = %p\n", icol, opts->bindings[icol].buffer); } cleanup: #undef return if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); return ret; } /* * Returns the description of a parameter marker. * This function is listed as not being supported by SQLGetFunctions() because it is * used to describe "parameter markers" (not bound parameters), in which case, * the dbms should return info on the markers. Since Postgres doesn't support that, * it is best to say this function is not supported and let the application assume a * data type (most likely varchar). */ RETCODE SQL_API PGAPI_DescribeParam(HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT FAR * pfSqlType, SQLULEN FAR * pcbParamDef, SQLSMALLINT FAR * pibScale, SQLSMALLINT FAR * pfNullable) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_DescribeParam"; IPDFields *ipdopts; RETCODE ret = SQL_SUCCESS; int num_params; OID pgtype; mylog("%s: entering...%d\n", func, ipar); if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } SC_clear_error(stmt); ipdopts = SC_get_IPDF(stmt); /*if ((ipar < 1) || (ipar > ipdopts->allocated))*/ num_params = stmt->num_params; if (num_params < 0) { SQLSMALLINT num_p; PGAPI_NumParams(stmt, &num_p); num_params = num_p; } if ((ipar < 1) || (ipar > num_params)) { inolog("num_params=%d\n", stmt->num_params); SC_set_error(stmt, STMT_BAD_PARAMETER_NUMBER_ERROR, "Invalid parameter number for PGAPI_DescribeParam.", func); return SQL_ERROR; } extend_iparameter_bindings(ipdopts, stmt->num_params); #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(stmt); */ if (NOT_YET_PREPARED == stmt->prepared) { decideHowToPrepare(stmt, FALSE); inolog("howTo=%d\n", SC_get_prepare_method(stmt)); switch (SC_get_prepare_method(stmt)) { case NAMED_PARSE_REQUEST: case PARSE_TO_EXEC_ONCE: case PARSE_REQ_FOR_INFO: if (ret = prepareParameters(stmt), SQL_ERROR == ret) goto cleanup; } } ipar--; pgtype = PIC_get_pgtype(ipdopts->parameters[ipar]); /* * This implementation is not very good, since it is supposed to * describe */ /* parameter markers, not bound parameters. */ if (pfSqlType) { inolog("[%d].SQLType=%d .PGType=%d\n", ipar, ipdopts->parameters[ipar].SQLType, pgtype); if (ipdopts->parameters[ipar].SQLType) *pfSqlType = ipdopts->parameters[ipar].SQLType; else if (pgtype) *pfSqlType = pgtype_to_concise_type(stmt, pgtype, PG_STATIC); else { ret = SQL_ERROR; SC_set_error(stmt, STMT_EXEC_ERROR, "Unfortunatley couldn't get this paramater's info", func); goto cleanup; } } if (pcbParamDef) { *pcbParamDef = 0; if (ipdopts->parameters[ipar].SQLType) *pcbParamDef = ipdopts->parameters[ipar].column_size; if (0 == *pcbParamDef && pgtype) *pcbParamDef = pgtype_column_size(stmt, pgtype, PG_STATIC, PG_STATIC); } if (pibScale) { *pibScale = 0; if (ipdopts->parameters[ipar].SQLType) *pibScale = ipdopts->parameters[ipar].decimal_digits; else if (pgtype) *pibScale = pgtype_scale(stmt, pgtype, -1); } if (pfNullable) *pfNullable = pgtype_nullable(SC_get_conn(stmt), ipdopts->parameters[ipar].paramType); cleanup: #undef return if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); return ret; } #if (ODBCVER < 0x0300) /* Sets multiple values (arrays) for the set of parameter markers. */ RETCODE SQL_API PGAPI_ParamOptions(HSTMT hstmt, SQLULEN crow, SQLULEN FAR * pirow) { CSTR func = "PGAPI_ParamOptions"; StatementClass *stmt = (StatementClass *) hstmt; APDFields *apdopts; IPDFields *ipdopts; mylog("%s: entering... %d %p\n", func, crow, pirow); apdopts = SC_get_APDF(stmt); apdopts->paramset_size = crow; ipdopts = SC_get_IPDF(stmt); ipdopts->param_processed_ptr = pirow; return SQL_SUCCESS; } #endif /* ODBCVER */ /* * This function should really talk to the dbms to determine the number of * "parameter markers" (not bound parameters) in the statement. But, since * Postgres doesn't support that, the driver should just count the number of markers * and return that. The reason the driver just can't say this function is unsupported * like it does for SQLDescribeParam is that some applications don't care and try * to call it anyway. * If the statement does not have parameters, it should just return 0. */ RETCODE SQL_API PGAPI_NumParams(HSTMT hstmt, SQLSMALLINT FAR * pcpar) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_NumParams"; mylog("%s: entering...\n", func); if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } if (pcpar) *pcpar = 0; else { SC_set_error(stmt, STMT_EXEC_ERROR, "parameter count address is null", func); return SQL_ERROR; } inolog("num_params=%d,%d\n", stmt->num_params, stmt->proc_return); if (stmt->num_params >= 0) *pcpar = stmt->num_params; else if (!stmt->statement) { /* no statement has been allocated */ SC_set_error(stmt, STMT_SEQUENCE_ERROR, "PGAPI_NumParams called with no statement ready.", func); return SQL_ERROR; } else { po_ind_t multi = FALSE, proc_return = 0; stmt->proc_return = 0; SC_scanQueryAndCountParams(stmt->statement, SC_get_conn(stmt), NULL, pcpar, &multi, &proc_return); stmt->num_params = *pcpar; stmt->proc_return = proc_return; stmt->multi_statement = multi; if (multi) SC_no_parse_tricky(stmt); } inolog("num_params=%d,%d\n", stmt->num_params, stmt->proc_return); return SQL_SUCCESS; } /* * Bindings Implementation */ static BindInfoClass * create_empty_bindings(int num_columns) { BindInfoClass *new_bindings; int i; new_bindings = (BindInfoClass *) malloc(num_columns * sizeof(BindInfoClass)); if (!new_bindings) return NULL; for (i = 0; i < num_columns; i++) { new_bindings[i].buflen = 0; new_bindings[i].buffer = NULL; new_bindings[i].used = new_bindings[i].indicator = NULL; } return new_bindings; } void extend_parameter_bindings(APDFields *self, int num_params) { CSTR func = "extend_parameter_bindings"; ParameterInfoClass *new_bindings; mylog("%s: entering ... self=%p, parameters_allocated=%d, num_params=%d,%p\n", func, self, self->allocated, num_params, self->parameters); /* * if we have too few, allocate room for more, and copy the old * entries into the new structure */ if (self->allocated < num_params) { new_bindings = (ParameterInfoClass *) realloc(self->parameters, sizeof(ParameterInfoClass) * num_params); if (!new_bindings) { mylog("%s: unable to create %d new bindings from %d old bindings\n", func, num_params, self->allocated); self->parameters = NULL; self->allocated = 0; return; } memset(&new_bindings[self->allocated], 0, sizeof(ParameterInfoClass) * (num_params - self->allocated)); self->parameters = new_bindings; self->allocated = num_params; } mylog("exit %s=%p\n", func, self->parameters); } void extend_iparameter_bindings(IPDFields *self, int num_params) { CSTR func = "extend_iparameter_bindings"; ParameterImplClass *new_bindings; mylog("%s: entering ... self=%p, parameters_allocated=%d, num_params=%d\n", func, self, self->allocated, num_params); /* * if we have too few, allocate room for more, and copy the old * entries into the new structure */ if (self->allocated < num_params) { new_bindings = (ParameterImplClass *) realloc(self->parameters, sizeof(ParameterImplClass) * num_params); if (!new_bindings) { mylog("%s: unable to create %d new bindings from %d old bindings\n", func, num_params, self->allocated); self->parameters = NULL; self->allocated = 0; return; } memset(&new_bindings[self->allocated], 0, sizeof(ParameterImplClass) * (num_params - self->allocated)); self->parameters = new_bindings; self->allocated = num_params; } mylog("exit %s=%p\n", func, self->parameters); } void reset_a_parameter_binding(APDFields *self, int ipar) { CSTR func = "reset_a_parameter_binding"; mylog("%s: entering ... self=%p, parameters_allocated=%d, ipar=%d\n", func, self, self->allocated, ipar); if (ipar < 1 || ipar > self->allocated) return; ipar--; self->parameters[ipar].buflen = 0; self->parameters[ipar].buffer = NULL; self->parameters[ipar].used = self->parameters[ipar].indicator = NULL; self->parameters[ipar].CType = 0; self->parameters[ipar].data_at_exec = FALSE; self->parameters[ipar].precision = 0; self->parameters[ipar].scale = 0; } void reset_a_iparameter_binding(IPDFields *self, int ipar) { CSTR func = "reset_a_iparameter_binding"; mylog("%s: entering ... self=%p, parameters_allocated=%d, ipar=%d\n", func, self, self->allocated, ipar); if (ipar < 1 || ipar > self->allocated) return; ipar--; NULL_THE_NAME(self->parameters[ipar].paramName); self->parameters[ipar].paramType = 0; self->parameters[ipar].SQLType = 0; self->parameters[ipar].column_size = 0; self->parameters[ipar].decimal_digits = 0; self->parameters[ipar].precision = 0; self->parameters[ipar].scale = 0; PIC_set_pgtype(self->parameters[ipar], 0); } int CountParameters(const StatementClass *self, Int2 *inputCount, Int2 *ioCount, Int2 *outputCount) { IPDFields *ipdopts = SC_get_IPDF(self); int i, num_params, valid_count; if (inputCount) *inputCount = 0; if (ioCount) *ioCount = 0; if (outputCount) *outputCount = 0; if (!ipdopts) return -1; num_params = self->num_params; if (ipdopts->allocated < num_params) num_params = ipdopts->allocated; for (i = 0, valid_count = 0; i < num_params; i++) { if (SQL_PARAM_OUTPUT == ipdopts->parameters[i].paramType) { if (outputCount) { (*outputCount)++; valid_count++; } } else if (SQL_PARAM_INPUT_OUTPUT == ipdopts->parameters[i].paramType) { if (ioCount) { (*ioCount)++; valid_count++; } } else if (inputCount) { (*inputCount)++; valid_count++; } } return valid_count; } /* * Free parameters and free the memory. */ void APD_free_params(APDFields *apdopts, char option) { CSTR func = "APD_free_params"; mylog("%s: ENTER, self=%p\n", func, apdopts); if (!apdopts->parameters) return; if (option == STMT_FREE_PARAMS_ALL) { free(apdopts->parameters); apdopts->parameters = NULL; apdopts->allocated = 0; } mylog("%s: EXIT\n", func); } void PDATA_free_params(PutDataInfo *pdata, char option) { CSTR func = "PDATA_free_params"; int i; mylog("%s: ENTER, self=%p\n", func, pdata); if (!pdata->pdata) return; for (i = 0; i < pdata->allocated; i++) { if (pdata->pdata[i].EXEC_used) { free(pdata->pdata[i].EXEC_used); pdata->pdata[i].EXEC_used = NULL; } if (pdata->pdata[i].EXEC_buffer) { free(pdata->pdata[i].EXEC_buffer); pdata->pdata[i].EXEC_buffer = NULL; } } if (option == STMT_FREE_PARAMS_ALL) { free(pdata->pdata); pdata->pdata = NULL; pdata->allocated = 0; } mylog("%s: EXIT\n", func); } /* * Free parameters and free the memory. */ void IPD_free_params(IPDFields *ipdopts, char option) { CSTR func = "IPD_free_params"; mylog("%s: ENTER, self=%p\n", func, ipdopts); if (!ipdopts->parameters) return; if (option == STMT_FREE_PARAMS_ALL) { free(ipdopts->parameters); ipdopts->parameters = NULL; ipdopts->allocated = 0; } mylog("%s: EXIT\n", func); } void extend_column_bindings(ARDFields *self, int num_columns) { CSTR func = "extend_column_bindings"; BindInfoClass *new_bindings; int i; mylog("%s: entering ... self=%p, bindings_allocated=%d, num_columns=%d\n", func, self, self->allocated, num_columns); /* * if we have too few, allocate room for more, and copy the old * entries into the new structure */ if (self->allocated < num_columns) { new_bindings = create_empty_bindings(num_columns); if (!new_bindings) { mylog("%s: unable to create %d new bindings from %d old bindings\n", func, num_columns, self->allocated); if (self->bindings) { free(self->bindings); self->bindings = NULL; } self->allocated = 0; return; } if (self->bindings) { for (i = 0; i < self->allocated; i++) new_bindings[i] = self->bindings[i]; free(self->bindings); } self->bindings = new_bindings; self->allocated = num_columns; } /* * There is no reason to zero out extra bindings if there are more * than needed. If an app has allocated extra bindings, let it worry * about it by unbinding those columns. */ /* SQLBindCol(1..) ... SQLBindCol(10...) # got 10 bindings */ /* SQLExecDirect(...) # returns 5 cols */ /* SQLExecDirect(...) # returns 10 cols (now OK) */ mylog("exit %s=%p\n", func, self->bindings); } void reset_a_column_binding(ARDFields *self, int icol) { CSTR func = "reset_a_column_binding"; BindInfoClass *bookmark; mylog("%s: entering ... self=%p, bindings_allocated=%d, icol=%d\n", func, self, self->allocated, icol); if (icol > self->allocated) return; /* use zero based col numbers from here out */ if (0 == icol) { if (bookmark = self->bookmark, bookmark != NULL) { bookmark->buffer = NULL; bookmark->used = bookmark->indicator = NULL; } } else { icol--; /* we have to unbind the column */ self->bindings[icol].buflen = 0; self->bindings[icol].buffer = NULL; self->bindings[icol].used = self->bindings[icol].indicator = NULL; self->bindings[icol].returntype = SQL_C_CHAR; } } void ARD_unbind_cols(ARDFields *self, BOOL freeall) { Int2 lf; inolog("ARD_unbind_cols freeall=%d allocated=%d bindings=%p", freeall, self->allocated, self->bindings); for (lf = 1; lf <= self->allocated; lf++) reset_a_column_binding(self, lf); if (freeall) { if (self->bindings) free(self->bindings); self->bindings = NULL; self->allocated = 0; } } void GDATA_unbind_cols(GetDataInfo *self, BOOL freeall) { Int2 lf; inolog("GDATA_unbind_cols freeall=%d allocated=%d gdata=%p", freeall, self->allocated, self->gdata); if (self->fdata.ttlbuf) { free(self->fdata.ttlbuf); self->fdata.ttlbuf = NULL; } self->fdata.ttlbuflen = self->fdata.ttlbufused = 0; self->fdata.data_left = -1; for (lf = 1; lf <= self->allocated; lf++) reset_a_getdata_info(self, lf); if (freeall) { if (self->gdata) free(self->gdata); self->gdata = NULL; self->allocated = 0; } } void GetDataInfoInitialize(GetDataInfo *gdata_info) { gdata_info->fdata.data_left = -1; gdata_info->fdata.ttlbuf = NULL; gdata_info->fdata.ttlbuflen = gdata_info->fdata.ttlbufused = 0; gdata_info->allocated = 0; gdata_info->gdata = NULL; } static GetDataClass * create_empty_gdata(int num_columns) { GetDataClass *new_gdata; int i; new_gdata = (GetDataClass *) malloc(num_columns * sizeof(GetDataClass)); if (!new_gdata) return NULL; for (i = 0; i < num_columns; i++) { new_gdata[i].data_left = -1; new_gdata[i].ttlbuf = NULL; new_gdata[i].ttlbuflen = 0; new_gdata[i].ttlbufused = 0; } return new_gdata; } void extend_getdata_info(GetDataInfo *self, int num_columns, BOOL shrink) { CSTR func = "extend_getdata_info"; GetDataClass *new_gdata; mylog("%s: entering ... self=%p, gdata_allocated=%d, num_columns=%d\n", func, self, self->allocated, num_columns); /* * if we have too few, allocate room for more, and copy the old * entries into the new structure */ if (self->allocated < num_columns) { new_gdata = create_empty_gdata(num_columns); if (!new_gdata) { mylog("%s: unable to create %d new gdata from %d old gdata\n", func, num_columns, self->allocated); if (self->gdata) { free(self->gdata); self->gdata = NULL; } self->allocated = 0; return; } if (self->gdata) { size_t i; for (i = 0; i < self->allocated; i++) new_gdata[i] = self->gdata[i]; free(self->gdata); } self->gdata = new_gdata; self->allocated = num_columns; } else if (shrink && self->allocated > num_columns) { int i; for (i = self->allocated; i > num_columns; i--) reset_a_getdata_info(self, i); self->allocated = num_columns; if (0 == num_columns) { free(self->gdata); self->gdata = NULL; } } /* * There is no reason to zero out extra gdata if there are more * than needed. If an app has allocated extra gdata, let it worry * about it by unbinding those columns. */ mylog("exit extend_gdata_info=%p\n", self->gdata); } void reset_a_getdata_info(GetDataInfo *gdata_info, int icol) { if (icol < 1 || icol > gdata_info->allocated) return; icol--; if (gdata_info->gdata[icol].ttlbuf) { free(gdata_info->gdata[icol].ttlbuf); gdata_info->gdata[icol].ttlbuf = NULL; } gdata_info->gdata[icol].ttlbuflen = gdata_info->gdata[icol].ttlbufused = 0; gdata_info->gdata[icol].data_left = -1; } void PutDataInfoInitialize(PutDataInfo *pdata_info) { pdata_info->allocated = 0; pdata_info->pdata = NULL; } void extend_putdata_info(PutDataInfo *self, int num_params, BOOL shrink) { CSTR func = "extend_putdata_info"; PutDataClass *new_pdata; mylog("%s: entering ... self=%p, parameters_allocated=%d, num_params=%d\n", func, self, self->allocated, num_params); /* * if we have too few, allocate room for more, and copy the old * entries into the new structure */ if (self->allocated < num_params) { if (self->allocated <= 0 && self->pdata) { mylog("??? pdata is not null while allocated == 0\n"); self->pdata = NULL; } new_pdata = (PutDataClass *) realloc(self->pdata, sizeof(PutDataClass) * num_params); if (!new_pdata) { mylog("%s: unable to create %d new pdata from %d old pdata\n", func, num_params, self->allocated); self->pdata = NULL; self->allocated = 0; return; } memset(&new_pdata[self->allocated], 0, sizeof(PutDataClass) * (num_params - self->allocated)); self->pdata = new_pdata; self->allocated = num_params; } else if (shrink && self->allocated > num_params) { int i; for (i = self->allocated; i > num_params; i--) reset_a_putdata_info(self, i); self->allocated = num_params; if (0 == num_params) { free(self->pdata); self->pdata = NULL; } } mylog("exit %s=%p\n", func, self->pdata); } void reset_a_putdata_info(PutDataInfo *pdata_info, int ipar) { if (ipar < 1 || ipar > pdata_info->allocated) return; ipar--; if (pdata_info->pdata[ipar].EXEC_used) { free(pdata_info->pdata[ipar].EXEC_used); pdata_info->pdata[ipar].EXEC_used = NULL; } if (pdata_info->pdata[ipar].EXEC_buffer) { free(pdata_info->pdata[ipar].EXEC_buffer); pdata_info->pdata[ipar].EXEC_buffer = NULL; } pdata_info->pdata[ipar].lobj_oid = 0; } void SC_param_next(const StatementClass *stmt, int *param_number, ParameterInfoClass **apara, ParameterImplClass **ipara) { int next; IPDFields *ipdopts = SC_get_IPDF(stmt); if (*param_number < 0) next = stmt->proc_return; else next = *param_number + 1; if (stmt->discard_output_params) { for (;next < ipdopts->allocated && SQL_PARAM_OUTPUT == ipdopts->parameters[next].paramType; next++) ; } *param_number = next; if (ipara) { if (next < ipdopts->allocated) *ipara = ipdopts->parameters + next; else *ipara = NULL; } if (apara) { APDFields *apdopts = SC_get_APDF(stmt); if (next < apdopts->allocated) *apara = apdopts->parameters + next; else *apara = NULL; } } psqlodbc-09.03.0300/columninfo.c000644 001752 000000 00000010330 12335653444 016512 0ustar00saitowheel000000 000000 /*------- * Module: columninfo.c * * Description: This module contains routines related to * reading and storing the field information from a query. * * Classes: ColumnInfoClass (Functions prefix: "CI_") * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "pgtypes.h" #include "columninfo.h" #include "connection.h" #include "socket.h" #include #include #include "pgapifunc.h" ColumnInfoClass * CI_Constructor(void) { ColumnInfoClass *rv; rv = (ColumnInfoClass *) malloc(sizeof(ColumnInfoClass)); if (rv) { rv->refcount = 0; rv->num_fields = 0; rv->coli_array = NULL; } return rv; } void CI_Destructor(ColumnInfoClass *self) { CI_free_memory(self); free(self); } /* * Read in field descriptions. * If self is not null, then also store the information. * If self is null, then just read, don't store. */ char CI_read_fields(ColumnInfoClass *self, ConnectionClass *conn) { CSTR func = "CI_read_fields"; Int2 lf; int new_num_fields; OID new_adtid, new_relid = 0, new_attid = 0; Int2 new_adtsize; Int4 new_atttypmod = -1; /* COLUMN_NAME_STORAGE_LEN may be sufficient but for safety */ char new_field_name[2 * COLUMN_NAME_STORAGE_LEN + 1]; SocketClass *sock; ConnInfo *ci; sock = CC_get_socket(conn); ci = &conn->connInfo; /* at first read in the number of fields that are in the query */ new_num_fields = (Int2) SOCK_get_int(sock, sizeof(Int2)); mylog("num_fields = %d\n", new_num_fields); if (self) { /* according to that allocate memory */ CI_set_num_fields(self, new_num_fields, PROTOCOL_74(ci)); if (NULL == self->coli_array) return FALSE; } /* now read in the descriptions */ for (lf = 0; lf < new_num_fields; lf++) { SOCK_get_string(sock, new_field_name, 2 * COLUMN_NAME_STORAGE_LEN); if (PROTOCOL_74(ci)) /* tableid & columnid */ { new_relid = SOCK_get_int(sock, sizeof(Int4)); new_attid = SOCK_get_int(sock, sizeof(Int2)); } new_adtid = (OID) SOCK_get_int(sock, 4); new_adtsize = (Int2) SOCK_get_int(sock, 2); /* If 6.4 protocol, then read the atttypmod field */ if (PG_VERSION_GE(conn, 6.4)) { mylog("READING ATTTYPMOD\n"); new_atttypmod = (Int4) SOCK_get_int(sock, 4); /* Subtract the header length */ switch (new_adtid) { case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIME: case PG_TYPE_TIME_WITH_TMZONE: break; default: new_atttypmod -= 4; } if (new_atttypmod < 0) new_atttypmod = -1; if (PROTOCOL_74(ci)) /* format */ SOCK_get_int(sock, sizeof(Int2)); } mylog("%s: fieldname='%s', adtid=%d, adtsize=%d, atttypmod=%d (rel,att)=(%d,%d)\n", func, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid); if (self) CI_set_field_info(self, lf, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid); } return (SOCK_get_errcode(sock) == 0); } void CI_free_memory(ColumnInfoClass *self) { register Int2 lf; int num_fields = self->num_fields; /* Safe to call even if null */ self->num_fields = 0; if (self->coli_array) { for (lf = 0; lf < num_fields; lf++) { if (self->coli_array[lf].name) { free(self->coli_array[lf].name); self->coli_array[lf].name = NULL; } } free(self->coli_array); self->coli_array = NULL; } } void CI_set_num_fields(ColumnInfoClass *self, int new_num_fields, BOOL allocrelatt) { CI_free_memory(self); /* always safe to call */ self->num_fields = new_num_fields; self->coli_array = (struct srvr_info *) calloc(sizeof(struct srvr_info), self->num_fields); } void CI_set_field_info(ColumnInfoClass *self, int field_num, char *new_name, OID new_adtid, Int2 new_adtsize, Int4 new_atttypmod, OID new_relid, OID new_attid) { /* check bounds */ if ((field_num < 0) || (field_num >= self->num_fields)) return; /* store the info */ self->coli_array[field_num].name = strdup(new_name); self->coli_array[field_num].adtid= new_adtid; self->coli_array[field_num].adtsize = new_adtsize; self->coli_array[field_num].atttypmod = new_atttypmod; self->coli_array[field_num].display_size = 0; self->coli_array[field_num].relid = new_relid; self->coli_array[field_num].attid = new_attid; } psqlodbc-09.03.0300/connection.c000644 001752 000000 00000344220 12335653444 016510 0ustar00saitowheel000000 000000 /*------ * Module: connection.c * * Description: This module contains routines related to * connecting to and disconnecting from the Postgres DBMS. * * Classes: ConnectionClass (Functions prefix: "CC_") * * API functions: SQLAllocConnect, SQLConnect, SQLDisconnect, SQLFreeConnect, * SQLBrowseConnect(NI) * * Comments: See "readme.txt" for copyright and license information. *------- */ /* Multibyte support Eiji Tokuya 2001-03-15 */ /* TryEnterCritiaclSection needs the following #define */ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif /* _WIN32_WINNT */ #include "connection.h" #ifdef USE_LIBPQ #include #endif /* USE_LIBPQ */ #include "misc.h" #include #include #include #ifdef WIN32 #ifdef USE_SSPI #include "sspisvcs.h" #endif /* USE_SSPI */ #else #include #endif /* WIN32 */ #ifdef USE_KRB5 #include "krb5svcs.h" #endif /* USE_KRB5 */ #ifdef USE_GSS #include "gsssvcs.h" #endif /* USE_GSS */ #include "environ.h" #include "socket.h" #include "statement.h" #include "qresult.h" #include "lobj.h" #include "dlg_specific.h" #include "loadlib.h" #include "multibyte.h" #include "pgapifunc.h" #include "md5.h" #define STMT_INCREMENT 16 /* how many statement holders to allocate * at a time */ #define PRN_NULLCHECK static void CC_lookup_pg_version(ConnectionClass *self); static void CC_lookup_lo(ConnectionClass *self); static char *CC_create_errormsg(ConnectionClass *self); static int CC_close_eof_cursors(ConnectionClass *self); extern GLOBAL_VALUES globals; RETCODE SQL_API PGAPI_AllocConnect(HENV henv, HDBC FAR * phdbc) { EnvironmentClass *env = (EnvironmentClass *) henv; ConnectionClass *conn; CSTR func = "PGAPI_AllocConnect"; mylog("%s: entering...\n", func); conn = CC_Constructor(); mylog("**** %s: henv = %p, conn = %p\n", func, henv, conn); if (!conn) { env->errormsg = "Couldn't allocate memory for Connection object."; env->errornumber = ENV_ALLOC_ERROR; *phdbc = SQL_NULL_HDBC; EN_log_error(func, "", env); return SQL_ERROR; } if (!EN_add_connection(env, conn)) { env->errormsg = "Maximum number of connections exceeded."; env->errornumber = ENV_ALLOC_ERROR; CC_Destructor(conn); *phdbc = SQL_NULL_HDBC; EN_log_error(func, "", env); return SQL_ERROR; } if (phdbc) *phdbc = (HDBC) conn; return SQL_SUCCESS; } RETCODE SQL_API PGAPI_Connect(HDBC hdbc, const SQLCHAR FAR * szDSN, SQLSMALLINT cbDSN, const SQLCHAR FAR * szUID, SQLSMALLINT cbUID, const SQLCHAR FAR * szAuthStr, SQLSMALLINT cbAuthStr) { ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci; CSTR func = "PGAPI_Connect"; RETCODE ret = SQL_SUCCESS; char fchar, *tmpstr; mylog("%s: entering..cbDSN=%hi.\n", func, cbDSN); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } ci = &conn->connInfo; CC_conninfo_init(ci, COPY_GLOBALS); make_string(szDSN, cbDSN, ci->dsn, sizeof(ci->dsn)); /* get the values for the DSN from the registry */ getDSNinfo(ci, CONN_OVERWRITE); logs_on_off(1, ci->drivers.debug, ci->drivers.commlog); /* initialize pg_version from connInfo.protocol */ CC_initialize_pg_version(conn); /* * override values from DSN info with UID and authStr(pwd) This only * occurs if the values are actually there. */ fchar = ci->username[0]; /* save the first byte */ make_string(szUID, cbUID, ci->username, sizeof(ci->username)); if ('\0' == ci->username[0]) /* an empty string is specified */ ci->username[0] = fchar; /* restore the original username */ tmpstr = make_string(szAuthStr, cbAuthStr, NULL, 0); if (tmpstr) { if (tmpstr[0]) /* non-empty string is specified */ STR_TO_NAME(ci->password, tmpstr); free(tmpstr); } /* fill in any defaults */ getDSNdefaults(ci); qlog("conn = %p, %s(DSN='%s', UID='%s', PWD='%s')\n", conn, func, ci->dsn, ci->username, NAME_IS_VALID(ci->password) ? "xxxxx" : ""); if ((fchar = CC_connect(conn, AUTH_REQ_OK, NULL)) <= 0) { /* Error messages are filled in */ CC_log_error(func, "Error on CC_connect", conn); ret = SQL_ERROR; } if (SQL_SUCCESS == ret && 2 == fchar) ret = SQL_SUCCESS_WITH_INFO; mylog("%s: returning..%d.\n", func, ret); return ret; } RETCODE SQL_API PGAPI_BrowseConnect(HDBC hdbc, const SQLCHAR FAR * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR FAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT FAR * pcbConnStrOut) { CSTR func = "PGAPI_BrowseConnect"; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("%s: entering...\n", func); CC_set_error(conn, CONN_NOT_IMPLEMENTED_ERROR, "Function not implemented", func); return SQL_ERROR; } /* Drop any hstmts open on hdbc and disconnect from database */ RETCODE SQL_API PGAPI_Disconnect(HDBC hdbc) { ConnectionClass *conn = (ConnectionClass *) hdbc; CSTR func = "PGAPI_Disconnect"; mylog("%s: entering...\n", func); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } qlog("conn=%p, %s\n", conn, func); if (conn->status == CONN_EXECUTING) { CC_set_error(conn, CONN_IN_USE, "A transaction is currently being executed", func); return SQL_ERROR; } logs_on_off(-1, conn->connInfo.drivers.debug, conn->connInfo.drivers.commlog); mylog("%s: about to CC_cleanup\n", func); /* Close the connection and free statements */ CC_cleanup(conn, FALSE); mylog("%s: done CC_cleanup\n", func); mylog("%s: returning...\n", func); return SQL_SUCCESS; } RETCODE SQL_API PGAPI_FreeConnect(HDBC hdbc) { ConnectionClass *conn = (ConnectionClass *) hdbc; CSTR func = "PGAPI_FreeConnect"; EnvironmentClass *env; mylog("%s: entering...\n", func); mylog("**** in %s: hdbc=%p\n", func, hdbc); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } /* Remove the connection from the environment */ if (NULL != (env = CC_get_env(conn)) && !EN_remove_connection(env, conn)) { CC_set_error(conn, CONN_IN_USE, "A transaction is currently being executed", func); return SQL_ERROR; } CC_Destructor(conn); mylog("%s: returning...\n", func); return SQL_SUCCESS; } static void CC_conninfo_release(ConnInfo *conninfo) { NULL_THE_NAME(conninfo->password); NULL_THE_NAME(conninfo->conn_settings); finalize_globals(&conninfo->drivers); } void CC_conninfo_init(ConnInfo *conninfo, UInt4 option) { CSTR func = "CC_conninfo_init"; mylog("%s opt=%d\n", func, option); if (0 != (CLEANUP_FOR_REUSE & option)) CC_conninfo_release(conninfo); memset(conninfo, 0, sizeof(ConnInfo)); conninfo->disallow_premature = -1; conninfo->allow_keyset = -1; conninfo->lf_conversion = -1; conninfo->true_is_minus1 = -1; conninfo->int8_as = -101; conninfo->bytea_as_longvarbinary = -1; conninfo->use_server_side_prepare = -1; conninfo->lower_case_identifier = -1; conninfo->rollback_on_error = -1; conninfo->force_abbrev_connstr = -1; conninfo->bde_environment = -1; conninfo->fake_mss = -1; conninfo->cvt_null_date_string = -1; conninfo->autocommit_public = SQL_AUTOCOMMIT_ON; conninfo->accessible_only = -1; conninfo->ignore_round_trip_time = -1; conninfo->disable_keepalive = -1; conninfo->gssauth_use_gssapi = -1; #ifdef _HANDLE_ENLIST_IN_DTC_ conninfo->xa_opt = -1; #endif /* _HANDLE_ENLIST_IN_DTC_ */ if (0 != (COPY_GLOBALS & option)) copy_globals(&(conninfo->drivers), &globals); } #define CORR_STRCPY(item) strncpy_null(ci->item, sci->item, sizeof(ci->item)) #define CORR_VALCPY(item) (ci->item = sci->item) void CC_copy_conninfo(ConnInfo *ci, const ConnInfo *sci) { memset(ci, 0,sizeof(ConnInfo)); CORR_STRCPY(dsn); CORR_STRCPY(desc); CORR_STRCPY(drivername); CORR_STRCPY(server); CORR_STRCPY(database); CORR_STRCPY(username); NAME_TO_NAME(ci->password, sci->password); CORR_STRCPY(protocol); CORR_STRCPY(port); CORR_STRCPY(sslmode); CORR_STRCPY(onlyread); CORR_STRCPY(fake_oid_index); CORR_STRCPY(show_oid_column); CORR_STRCPY(row_versioning); CORR_STRCPY(show_system_tables); CORR_STRCPY(translation_dll); CORR_STRCPY(translation_option); CORR_VALCPY(focus_password); NAME_TO_NAME(ci->conn_settings, sci->conn_settings); CORR_VALCPY(disallow_premature); CORR_VALCPY(allow_keyset); CORR_VALCPY(updatable_cursors); CORR_VALCPY(lf_conversion); CORR_VALCPY(true_is_minus1); CORR_VALCPY(int8_as); CORR_VALCPY(bytea_as_longvarbinary); CORR_VALCPY(use_server_side_prepare); CORR_VALCPY(lower_case_identifier); CORR_VALCPY(rollback_on_error); CORR_VALCPY(force_abbrev_connstr); CORR_VALCPY(bde_environment); CORR_VALCPY(fake_mss); CORR_VALCPY(cvt_null_date_string); CORR_VALCPY(autocommit_public); CORR_VALCPY(accessible_only); CORR_VALCPY(ignore_round_trip_time); CORR_VALCPY(disable_keepalive); CORR_VALCPY(gssauth_use_gssapi); CORR_VALCPY(extra_opts); #ifdef _HANDLE_ENLIST_IN_DTC_ CORR_VALCPY(xa_opt); #endif copy_globals(&(ci->drivers), &(sci->drivers)); /* moved from driver's option */ } #undef CORR_STRCPY #undef CORR_VALCPY #ifdef WIN32 extern int platformId; #endif /* WIN32 */ /* * IMPLEMENTATION CONNECTION CLASS */ static void reset_current_schema(ConnectionClass *self) { if (self->current_schema) { free(self->current_schema); self->current_schema = NULL; } } static ConnectionClass * CC_alloc(void) { return (ConnectionClass *) calloc(sizeof(ConnectionClass), 1); } static void CC_lockinit(ConnectionClass *self) { INIT_CONNLOCK(self); INIT_CONN_CS(self); } static ConnectionClass * CC_initialize(ConnectionClass *rv, BOOL lockinit) { ConnectionClass *retrv = NULL; size_t clear_size; #if defined(WIN_MULTITHREAD_SUPPORT) || defined(POSIX_THREADMUTEX_SUPPORT) clear_size = (char *)&(rv->cs) - (char *)rv; #else clear_size = sizeof(ConnectionClass); #endif /* WIN_MULTITHREAD_SUPPORT */ memset(rv, 0, clear_size); rv->status = CONN_NOT_CONNECTED; rv->transact_status = CONN_IN_AUTOCOMMIT; /* autocommit by default */ rv->stmt_in_extquery = NULL; rv->stmts = (StatementClass **) malloc(sizeof(StatementClass *) * STMT_INCREMENT); if (!rv->stmts) goto cleanup; memset(rv->stmts, 0, sizeof(StatementClass *) * STMT_INCREMENT); rv->num_stmts = STMT_INCREMENT; #if (ODBCVER >= 0x0300) rv->descs = (DescriptorClass **) malloc(sizeof(DescriptorClass *) * STMT_INCREMENT); if (!rv->descs) goto cleanup; memset(rv->descs, 0, sizeof(DescriptorClass *) * STMT_INCREMENT); rv->num_descs = STMT_INCREMENT; #endif /* ODBCVER */ rv->lobj_type = PG_TYPE_LO_UNDEFINED; rv->driver_version = ODBCVER; #ifdef WIN32 if (VER_PLATFORM_WIN32_WINDOWS == platformId && rv->driver_version > 0x0300) rv->driver_version = 0x0300; #endif /* WIN32 */ if (isMsAccess()) rv->ms_jet = 1; rv->isolation = SQL_TXN_READ_COMMITTED; rv->mb_maxbyte_per_char = 1; rv->max_identifier_length = -1; rv->escape_in_literal = ESCAPE_IN_LITERAL; /* Initialize statement options to defaults */ /* Statements under this conn will inherit these options */ InitializeStatementOptions(&rv->stmtOptions); InitializeARDFields(&rv->ardOptions); InitializeAPDFields(&rv->apdOptions); #ifdef _HANDLE_ENLIST_IN_DTC_ rv->asdum = NULL; rv->gTranInfo = 0; #endif /* _HANDLE_ENLIST_IN_DTC_ */ if (lockinit) CC_lockinit(rv); retrv = rv; cleanup: if (rv && !retrv) CC_Destructor(rv); return retrv; } ConnectionClass * CC_Constructor() { ConnectionClass *rv, *retrv = NULL; if (rv = CC_alloc(), NULL != rv) retrv = CC_initialize(rv, TRUE); return retrv; } char CC_Destructor(ConnectionClass *self) { mylog("enter CC_Destructor, self=%p\n", self); if (self->status == CONN_EXECUTING) return 0; CC_cleanup(self, FALSE); /* cleanup socket and statements */ mylog("after CC_Cleanup\n"); /* Free up statement holders */ if (self->stmts) { free(self->stmts); self->stmts = NULL; } #if (ODBCVER >= 0x0300) if (self->descs) { free(self->descs); self->descs = NULL; } #endif /* ODBCVER */ mylog("after free statement holders\n"); NULL_THE_NAME(self->schemaIns); NULL_THE_NAME(self->tableIns); CC_conninfo_release(&self->connInfo); if (self->__error_message) free(self->__error_message); DELETE_CONN_CS(self); DELETE_CONNLOCK(self); free(self); mylog("exit CC_Destructor\n"); return 1; } /* Return how many cursors are opened on this connection */ int CC_cursor_count(ConnectionClass *self) { StatementClass *stmt; int i, count = 0; QResultClass *res; mylog("CC_cursor_count: self=%p, num_stmts=%d\n", self, self->num_stmts); CONNLOCK_ACQUIRE(self); for (i = 0; i < self->num_stmts; i++) { stmt = self->stmts[i]; if (stmt && (res = SC_get_Result(stmt)) && QR_get_cursor(res)) count++; } CONNLOCK_RELEASE(self); mylog("CC_cursor_count: returning %d\n", count); return count; } void CC_clear_error(ConnectionClass *self) { if (!self) return; CONNLOCK_ACQUIRE(self); self->__error_number = 0; if (self->__error_message) { free(self->__error_message); self->__error_message = NULL; } self->sqlstate[0] = '\0'; self->errormsg_created = FALSE; CONNLOCK_RELEASE(self); } void CC_examine_global_transaction(ConnectionClass *self) { if (!self) return; #ifdef _HANDLE_ENLIST_IN_DTC_ if (CC_is_in_global_trans(self)) CALL_IsolateDtcConn(self, TRUE); #endif /* _HANDLE_ENLIST_IN_DTC_ */ } static void CC_endup_authentication(ConnectionClass *self) { SocketClass *sock = CC_get_socket(self); if (!sock) return; #ifdef USE_SSPI if (0 != self->auth_svcs) { ReleaseSvcSpecData(sock, self->auth_svcs); self->auth_svcs = 0; } #endif /* USE_SSPI */ #ifdef USE_GSS pg_GSS_cleanup(sock); #endif /* USE_GSS */ } CSTR bgncmd = "BEGIN"; CSTR cmtcmd = "COMMIT"; CSTR rbkcmd = "ROLLBACK"; CSTR semi_colon = ";"; /* * Used to begin a transaction. */ char CC_begin(ConnectionClass *self) { char ret = TRUE; if (!CC_is_in_trans(self)) { QResultClass *res = CC_send_query(self, bgncmd, NULL, 0, NULL); mylog("CC_begin: sending BEGIN!\n"); ret = QR_command_maybe_successful(res); QR_Destructor(res); } return ret; } /* * Used to commit a transaction. * We are almost always in the middle of a transaction. */ char CC_commit(ConnectionClass *self) { char ret = TRUE; if (CC_is_in_trans(self)) { if (!CC_is_in_error_trans(self)) CC_close_eof_cursors(self); if (CC_is_in_trans(self)) { QResultClass *res = CC_send_query(self, cmtcmd, NULL, 0, NULL); mylog("CC_commit: sending COMMIT!\n"); ret = QR_command_maybe_successful(res); QR_Destructor(res); } } return ret; } /* * Used to cancel a transaction. * We are almost always in the middle of a transaction. */ char CC_abort(ConnectionClass *self) { char ret = TRUE; if (CC_is_in_trans(self)) { QResultClass *res = CC_send_query(self, rbkcmd, NULL, 0, NULL); mylog("CC_abort: sending ABORT!\n"); ret = QR_command_maybe_successful(res); QR_Destructor(res); } return ret; } /* This is called by SQLSetConnectOption etc also */ char CC_set_autocommit(ConnectionClass *self, BOOL on) { CSTR func = "CC_set_autocommit"; BOOL currsts = CC_is_in_autocommit(self); if ((on && currsts) || (!on && !currsts)) return on; mylog("%s: %d->%d\n", func, currsts, on); if (CC_is_in_trans(self)) CC_commit(self); if (on) self->transact_status |= CONN_IN_AUTOCOMMIT; else self->transact_status &= ~CONN_IN_AUTOCOMMIT; return on; } /* Clear cached table info */ static void CC_clear_col_info(ConnectionClass *self, BOOL destroy) { if (self->col_info) { int i; COL_INFO *coli; for (i = 0; i < self->ntables; i++) { if (coli = self->col_info[i], NULL != coli) { if (destroy || coli->refcnt == 0) { free_col_info_contents(coli); free(coli); self->col_info[i] = NULL; } else coli->acc_time = 0; } } self->ntables = 0; if (destroy) { free(self->col_info); self->col_info = NULL; self->coli_allocated = 0; } } } /* This is called by SQLDisconnect also */ char CC_cleanup(ConnectionClass *self, BOOL keepCommunication) { int i; StatementClass *stmt; DescriptorClass *desc; if (self->status == CONN_EXECUTING) return FALSE; mylog("in CC_Cleanup, self=%p\n", self); ENTER_CONN_CS(self); /* Cancel an ongoing transaction */ /* We are always in the middle of a transaction, */ /* even if we are in auto commit. */ if (self->sock) { if (!keepCommunication) { CC_abort(self); mylog("after CC_abort\n"); /* This actually closes the connection to the dbase */ SOCK_Destructor(self->sock); self->sock = NULL; } } mylog("after SOCK destructor\n"); /* Free all the stmts on this connection */ for (i = 0; i < self->num_stmts; i++) { stmt = self->stmts[i]; if (stmt) { stmt->hdbc = NULL; /* prevent any more dbase interactions */ SC_Destructor(stmt); self->stmts[i] = NULL; } } #if (ODBCVER >= 0x0300) /* Free all the descs on this connection */ for (i = 0; i < self->num_descs; i++) { desc = self->descs[i]; if (desc) { DC_get_conn(desc) = NULL; /* prevent any more dbase interactions */ DC_Destructor(desc); free(desc); self->descs[i] = NULL; } } #endif /* ODBCVER */ /* Check for translation dll */ #ifdef WIN32 if (!keepCommunication && self->translation_handle) { FreeLibrary(self->translation_handle); self->translation_handle = NULL; } #endif if (!keepCommunication) { self->status = CONN_NOT_CONNECTED; self->transact_status = CONN_IN_AUTOCOMMIT; } self->stmt_in_extquery = NULL; if (!keepCommunication) { CC_conninfo_init(&(self->connInfo), CLEANUP_FOR_REUSE); if (self->original_client_encoding) { free(self->original_client_encoding); self->original_client_encoding = NULL; } if (self->current_client_encoding) { free(self->current_client_encoding); self->current_client_encoding = NULL; } if (self->server_encoding) { free(self->server_encoding); self->server_encoding = NULL; } reset_current_schema(self); } /* Free cached table info */ CC_clear_col_info(self, TRUE); if (self->num_discardp > 0 && self->discardp) { for (i = 0; i < self->num_discardp; i++) free(self->discardp[i]); self->num_discardp = 0; } if (self->discardp) { free(self->discardp); self->discardp = NULL; } LEAVE_CONN_CS(self); mylog("exit CC_Cleanup\n"); return TRUE; } int CC_set_translation(ConnectionClass *self) { #ifdef WIN32 CSTR func = "CC_set_translation"; if (self->translation_handle != NULL) { FreeLibrary(self->translation_handle); self->translation_handle = NULL; } if (self->connInfo.translation_dll[0] == 0) return TRUE; self->translation_option = atoi(self->connInfo.translation_option); self->translation_handle = LoadLibrary(self->connInfo.translation_dll); if (self->translation_handle == NULL) { CC_set_error(self, CONN_UNABLE_TO_LOAD_DLL, "Could not load the translation DLL.", func); return FALSE; } self->DataSourceToDriver = (DataSourceToDriverProc) GetProcAddress(self->translation_handle, "SQLDataSourceToDriver"); self->DriverToDataSource = (DriverToDataSourceProc) GetProcAddress(self->translation_handle, "SQLDriverToDataSource"); if (self->DataSourceToDriver == NULL || self->DriverToDataSource == NULL) { CC_set_error(self, CONN_UNABLE_TO_LOAD_DLL, "Could not find translation DLL functions.", func); return FALSE; } #endif return TRUE; } static int md5_auth_send(ConnectionClass *self, const char *salt) { char *pwd1 = NULL, *pwd2 = NULL; ConnInfo *ci = &(self->connInfo); SocketClass *sock = self->sock; size_t md5len; inolog("md5 pwd=%s user=%s salt=%02x%02x%02x%02x%02x\n", PRINT_NAME(ci->password), ci->username, (UCHAR)salt[0], (UCHAR)salt[1], (UCHAR)salt[2], (UCHAR)salt[3], (UCHAR)salt[4]); if (!(pwd1 = malloc(MD5_PASSWD_LEN + 1))) return 1; if (!EncryptMD5(SAFE_NAME(ci->password), ci->username, strlen(ci->username), pwd1)) { free(pwd1); return 1; } if (!(pwd2 = malloc(MD5_PASSWD_LEN + 1))) { free(pwd1); return 1; } if (!EncryptMD5(pwd1 + strlen("md5"), salt, 4, pwd2)) { free(pwd2); free(pwd1); return 1; } free(pwd1); if (PROTOCOL_74(&(self->connInfo))) { inolog("putting p and %s\n", pwd2); SOCK_put_char(sock, 'p'); } md5len = strlen(pwd2); SOCK_put_int(sock, (Int4) (4 + md5len + 1), 4); SOCK_put_n_char(sock, pwd2, (md5len + 1)); SOCK_flush_output(sock); inolog("sockerr=%d\n", SOCK_get_errcode(sock)); free(pwd2); return 0; } int EatReadyForQuery(ConnectionClass *conn) { int id = 0; if (PROTOCOL_74(&(conn->connInfo))) { BOOL is_in_error_trans = CC_is_in_error_trans(conn); switch (id = SOCK_get_char(conn->sock)) { case 'I': if (CC_is_in_trans(conn)) { if (is_in_error_trans) CC_on_abort(conn, NO_TRANS); else CC_on_commit(conn); } break; case 'T': CC_set_in_trans(conn); CC_set_no_error_trans(conn); if (is_in_error_trans) CC_on_abort_partial(conn); break; case 'E': CC_set_in_error_trans(conn); break; } conn->stmt_in_extquery = NULL; } return id; } int handle_error_message(ConnectionClass *self, char *msgbuf, size_t buflen, char *sqlstate, const char *comment, QResultClass *res) { BOOL new_format = FALSE, msg_truncated = FALSE, truncated, hasmsg = FALSE; SocketClass *sock = self->sock; ConnInfo *ci = &(self->connInfo); char msgbuffer[ERROR_MSG_LENGTH]; UDWORD abort_opt; inolog("handle_error_message protocol=%s\n", ci->protocol); if (PROTOCOL_74(ci)) new_format = TRUE; else if (PROTOCOL_74REJECTED(ci)) { if (!SOCK_get_next_byte(sock, TRUE)) /* peek the next byte */ { uint32 leng; mylog("peek the next byte = \\0\n"); new_format = TRUE; strncpy_null(ci->protocol, PG74, sizeof(ci->protocol)); leng = SOCK_get_response_length(sock); inolog("get the response length=%d\n", leng); } } inolog("new_format=%d\n", new_format); truncated = SOCK_get_string(sock, new_format ? msgbuffer : msgbuf, new_format ? sizeof(msgbuffer) : (Int4) buflen); if (new_format) { msgbuf[0] = '\0'; for (;msgbuffer[0];) { mylog("%s: 'E' - %s\n", comment, msgbuffer); qlog("ERROR from backend during %s: '%s'\n", comment, msgbuffer); switch (msgbuffer[0]) { case 'S': strlcat(msgbuf, msgbuffer + 1, buflen); strlcat(msgbuf, ": ", buflen); break; case 'M': case 'D': if (hasmsg) strlcat(msgbuf, "\n", buflen); strlcat(msgbuf, msgbuffer + 1, buflen); if (truncated) msg_truncated = truncated; hasmsg = TRUE; break; case 'C': if (sqlstate) strncpy_null(sqlstate, msgbuffer + 1, 8); break; } while (truncated) truncated = SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); truncated = SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); } } else { msg_truncated = truncated; /* Remove a newline */ if (msgbuf[0] != '\0' && msgbuf[(int)strlen(msgbuf) - 1] == '\n') msgbuf[(int)strlen(msgbuf) - 1] = '\0'; mylog("%s: 'E' - %s\n", comment, msgbuf); qlog("ERROR from backend during %s: '%s'\n", comment, msgbuf); while (truncated) truncated = SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); } abort_opt = 0; if (!strncmp(msgbuf, "FATAL", 5)) { CC_set_errornumber(self, CONNECTION_SERVER_REPORTED_ERROR); abort_opt = CONN_DEAD; } else { CC_set_errornumber(self, CONNECTION_SERVER_REPORTED_WARNING); if (CC_is_in_trans(self)) CC_set_in_error_trans(self); } if (0 != abort_opt #ifdef _LEGACY_MODE_ || TRUE #endif /* _LEGACY_NODE_ */ ) CC_on_abort(self, abort_opt); if (res) { QR_set_rstatus(res, PORES_FATAL_ERROR); QR_set_message(res, msgbuf); QR_set_aborted(res, TRUE); } return msg_truncated; } int handle_notice_message(ConnectionClass *self, char *msgbuf, size_t buflen, char *sqlstate, const char *comment, QResultClass *res) { BOOL new_format = FALSE, msg_truncated = FALSE, truncated, hasmsg = FALSE; SocketClass *sock = self->sock; char msgbuffer[ERROR_MSG_LENGTH]; if (PROTOCOL_74(&(self->connInfo))) new_format = TRUE; if (new_format) { size_t dstlen = 0; msgbuf[0] = '\0'; for (;;) { truncated = SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); if (!msgbuffer[0]) break; mylog("%s: 'N' - %s\n", comment, msgbuffer); qlog("NOTICE from backend during %s: '%s'\n", comment, msgbuffer); switch (msgbuffer[0]) { case 'S': strlcat(msgbuf, msgbuffer + 1, buflen); dstlen = strlcat(msgbuf, ": ", buflen); break; case 'M': case 'D': if (hasmsg) strlcat(msgbuf, "\n", buflen); dstlen = strlcat(msgbuf, msgbuffer + 1, buflen); if (truncated) msg_truncated = truncated; hasmsg = TRUE; break; case 'C': if (sqlstate && !sqlstate[0] && strcmp(msgbuffer + 1, "00000")) strncpy_null(sqlstate, msgbuffer + 1, 8); break; } if (dstlen >= buflen) msg_truncated = TRUE; while (truncated) truncated = SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); } mylog("notice message len=%d\n", strlen(msgbuf)); } else { msg_truncated = SOCK_get_string(sock, msgbuf, (Int4) buflen); /* Remove a newline */ if (msgbuf[0] != '\0' && msgbuf[strlen(msgbuf) - 1] == '\n') msgbuf[strlen(msgbuf) - 1] = '\0'; mylog("%s: 'N' - %s\n", comment, msgbuf); qlog("NOTICE from backend during %s: '%s'\n", comment, msgbuf); for (truncated = msg_truncated; truncated;) truncated = SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); } if (res) { if (QR_command_successful(res)) QR_set_rstatus(res, PORES_NONFATAL_ERROR); QR_set_notice(res, msgbuf); /* will dup this string */ } return msg_truncated; } CSTR std_cnf_strs = "standard_conforming_strings"; void getParameterValues(ConnectionClass *conn) { SocketClass *sock = conn->sock; /* ERROR_MSG_LENGTH is suffcient */ char msgbuffer[ERROR_MSG_LENGTH + 1]; SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); inolog("parameter name=%s\n", msgbuffer); if (stricmp(msgbuffer, "server_encoding") == 0) { SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); if (conn->server_encoding) free(conn->server_encoding); conn->server_encoding = strdup(msgbuffer); } else if (stricmp(msgbuffer, "client_encoding") == 0) { SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); if (conn->current_client_encoding) free(conn->current_client_encoding); conn->current_client_encoding = strdup(msgbuffer); } else if (stricmp(msgbuffer, std_cnf_strs) == 0) { SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); mylog("%s=%s\n", std_cnf_strs, msgbuffer); if (stricmp(msgbuffer, "on") == 0) { conn->escape_in_literal = '\0'; } if (stricmp(msgbuffer, "off") == 0) { conn->escape_in_literal = ESCAPE_IN_LITERAL; } } else if (stricmp(msgbuffer, "server_version") == 0) { char szVersion[32]; int major, minor; SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); strncpy_null(conn->pg_version, msgbuffer, sizeof(conn->pg_version)); strcpy(szVersion, "0.0"); if (sscanf(conn->pg_version, "%d.%d", &major, &minor) >= 2) { snprintf(szVersion, sizeof(szVersion), "%d.%d", major, minor); conn->pg_version_major = major; conn->pg_version_minor = minor; } conn->pg_version_number = (float) atof(szVersion); if (PG_VERSION_GE(conn, 7.3)) conn->schema_support = 1; mylog("Got the PostgreSQL version string: '%s'\n", conn->pg_version); mylog("Extracted PostgreSQL version number: '%1.1f'\n", conn->pg_version_number); qlog(" [ PostgreSQL version string = '%s' ]\n", conn->pg_version); qlog(" [ PostgreSQL version number = '%1.1f' ]\n", conn->pg_version_number); } else SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); inolog("parameter value=%s\n", msgbuffer); } static int protocol3_opts_array(ConnectionClass *self, const char *opts[], const char *vals[], BOOL libpqopt, int dim_opts) { ConnInfo *ci = &(self->connInfo); const char *enc = NULL; int cnt; cnt = 0; if (libpqopt && ci->server[0]) { opts[cnt] = "host"; vals[cnt++] = ci->server; } if (libpqopt && ci->port[0]) { opts[cnt] = "port"; vals[cnt++] = ci->port; } if (ci->database[0]) { if (libpqopt) { opts[cnt] = "dbname"; vals[cnt++] = ci->database; } else { opts[cnt] = "database"; vals[cnt++] = ci->database; } } if (ci->username[0] || !libpqopt) { char *usrname = ci->username; #ifdef WIN32 DWORD namesize = sizeof(ci->username) - 2; #endif /* WIN32 */ opts[cnt] = "user"; if (!usrname[0]) { #ifdef WIN32 if (GetUserName(ci->username + 1, &namesize)) usrname = ci->username + 1; #endif /* WIN32 */ } mylog("!!! usrname=%s server=%s\n", usrname, ci->server); vals[cnt++] = usrname; } if (libpqopt) { switch (ci->sslmode[0]) { case '\0': break; case SSLLBYTE_VERIFY: opts[cnt] = "sslmode"; switch (ci->sslmode[1]) { case 'f': vals[cnt++] = SSLMODE_VERIFY_FULL; break; case 'c': vals[cnt++] = SSLMODE_VERIFY_CA; break; default: vals[cnt++] = ci->sslmode; } break; default: opts[cnt] = "sslmode"; vals[cnt++] = ci->sslmode; } if (NAME_IS_VALID(ci->password)) { opts[cnt] = "password"; vals[cnt++] = SAFE_NAME(ci->password); } if (ci->gssauth_use_gssapi) { opts[cnt] = "gsslib"; vals[cnt++] = "gssapi"; } if (ci->disable_keepalive) { opts[cnt] = "keepalives"; vals[cnt++] = "0"; } } else { /* DateStyle */ opts[cnt] = "DateStyle"; vals[cnt++] = "ISO"; /* extra_float_digits */ opts[cnt] = "extra_float_digits"; vals[cnt++] = "2"; /* geqo */ opts[cnt] = "geqo"; if (ci->drivers.disable_optimizer) vals[cnt++] = "off"; else vals[cnt++] = "on"; /* client_encoding */ enc = get_environment_encoding(self, self->original_client_encoding, NULL, TRUE); if (enc) { mylog("startup client_encoding=%s\n", enc); opts[cnt] = "client_encoding"; vals[cnt++] = enc; } } opts[cnt] = vals[cnt] = NULL; return cnt; } #define PROTOCOL3_OPTS_MAX 20 static int protocol3_packet_build(ConnectionClass *self) { CSTR func = "protocol3_packet_build"; SocketClass *sock = self->sock; size_t slen; char *packet, *ppacket; ProtocolVersion pversion; const char *opts[PROTOCOL3_OPTS_MAX], *vals[PROTOCOL3_OPTS_MAX]; int cnt, i; cnt = protocol3_opts_array(self, opts, vals, FALSE, sizeof(opts) / sizeof(opts[0])); if (cnt < 0) return 0; slen = sizeof(ProtocolVersion); for (i = 0; i < cnt; i++) { slen += (strlen(opts[i]) + 1); slen += (strlen(vals[i]) + 1); } slen++; if (packet = malloc(slen), !packet) { CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, "Could not allocate a startup packet", func); return 0; } mylog("sizeof startup packet = %d\n", slen); sock->pversion = PG_PROTOCOL_LATEST; /* Send length of Authentication Block */ SOCK_put_int(sock, (Int4) (slen + 4), 4); ppacket = packet; pversion = (ProtocolVersion) htonl(sock->pversion); memcpy(ppacket, &pversion, sizeof(pversion)); ppacket += sizeof(pversion); for (i = 0; i < cnt; i++) { strcpy(ppacket, opts[i]); ppacket += (strlen(opts[i]) + 1); strcpy(ppacket, vals[i]); ppacket += (strlen(vals[i]) + 1); } *ppacket = '\0'; SOCK_put_n_char(sock, packet, slen); SOCK_flush_output(sock); free(packet); return 1; } #ifdef USE_LIBPQ CSTR l_login_timeout = "connect_timeout"; static char *protocol3_opts_build(ConnectionClass *self) { CSTR func = "protocol3_opts_build"; size_t slen; char *conninfo, *ppacket; const char *opts[PROTOCOL3_OPTS_MAX], *vals[PROTOCOL3_OPTS_MAX]; int cnt, i; BOOL blankExist; cnt = protocol3_opts_array(self, opts, vals, TRUE, sizeof(opts) / sizeof(opts[0])); if (cnt < 0) return NULL; slen = sizeof(ProtocolVersion); for (i = 0, slen = 0; i < cnt; i++) { slen += (strlen(opts[i]) + 2 + 2); /* add 2 bytes for safety (literal quotes) */ slen += strlen(vals[i]); } if (self->login_timeout > 0) { char tmout[16]; slen += (strlen(l_login_timeout) + 2 + 2); snprintf(tmout, sizeof(tmout), FORMAT_UINTEGER, self->login_timeout); slen += strlen(tmout); } slen++; if (conninfo = malloc(slen), !conninfo) { CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, "Could not allocate a connectdb option", func); return 0; } mylog("sizeof connectdb option = %d\n", slen); for (i = 0, ppacket = conninfo; i < cnt; i++) { sprintf(ppacket, " %s=", opts[i]); ppacket += (strlen(opts[i]) + 2); blankExist = FALSE; if (strchr(vals[i], ' ')) blankExist = TRUE; if (blankExist) { *ppacket = '\''; ppacket++; } strcpy(ppacket, vals[i]); ppacket += strlen(vals[i]); if (blankExist) { *ppacket = '\''; ppacket++; } } if (self->login_timeout > 0) { sprintf(ppacket, " %s=", l_login_timeout); ppacket += (strlen(l_login_timeout) + 2); sprintf(ppacket, FORMAT_UINTEGER, self->login_timeout); ppacket = strchr(ppacket, '\0'); } *ppacket = '\0'; inolog("return conninfo=%s(%d)\n", conninfo, strlen(conninfo)); return conninfo; } #endif /* USE_LIBPQ */ static char CC_initial_log(ConnectionClass *self, const char *func) { const ConnInfo *ci = &self->connInfo; char *encoding, vermsg[128]; snprintf(vermsg, sizeof(vermsg), "Driver Version='%s,%s'" #ifdef WIN32 " linking %d" #ifdef _MT #ifdef _DLL " dynamic" #else " static" #endif /* _DLL */ " Multithread" #else " Singlethread" #endif /* _MT */ #ifdef _DEBUG " Debug" #endif /* DEBUG */ " library" #endif /* WIN32 */ "\n", POSTGRESDRIVERVERSION, PG_BUILD_VERSION #ifdef _MSC_VER , _MSC_VER #endif /* _MSC_VER */ ); qlog(vermsg); mylog(vermsg); qlog("Global Options: fetch=%d, socket=%d, unknown_sizes=%d, max_varchar_size=%d, max_longvarchar_size=%d\n", ci->drivers.fetch_max, ci->drivers.socket_buffersize, ci->drivers.unknown_sizes, ci->drivers.max_varchar_size, ci->drivers.max_longvarchar_size); qlog(" disable_optimizer=%d, ksqo=%d, unique_index=%d, use_declarefetch=%d\n", ci->drivers.disable_optimizer, ci->drivers.ksqo, ci->drivers.unique_index, ci->drivers.use_declarefetch); qlog(" text_as_longvarchar=%d, unknowns_as_longvarchar=%d, bools_as_char=%d NAMEDATALEN=%d\n", ci->drivers.text_as_longvarchar, ci->drivers.unknowns_as_longvarchar, ci->drivers.bools_as_char, TABLE_NAME_STORAGE_LEN); encoding = check_client_encoding(ci->conn_settings); if (encoding) self->original_client_encoding = encoding; else { encoding = check_client_encoding(ci->drivers.conn_settings); if (encoding) self->original_client_encoding = encoding; } if (self->original_client_encoding) self->ccsc = pg_CS_code(self->original_client_encoding); qlog(" extra_systable_prefixes='%s', conn_settings='%s' conn_encoding='%s'\n", ci->drivers.extra_systable_prefixes, PRINT_NAME(ci->drivers.conn_settings), encoding ? encoding : ""); if (self->status != CONN_NOT_CONNECTED) { CC_set_error(self, CONN_OPENDB_ERROR, "Already connected.", func); return 0; } mylog("%s: DSN = '%s', server = '%s', port = '%s', database = '%s', username = '%s', password='%s'\n", func, ci->dsn, ci->server, ci->port, ci->database, ci->username, NAME_IS_VALID(ci->password) ? "xxxxx" : ""); if (ci->port[0] == '\0') { CC_set_error(self, CONN_INIREAD_ERROR, "Missing port name in call to CC_connect.", func); return 0; } #ifdef WIN32 if (ci->server[0] == '\0') { CC_set_error(self, CONN_INIREAD_ERROR, "Missing server name in call to CC_connect.", func); return 0; } #endif /* WIN32 */ if (ci->database[0] == '\0') { CC_set_error(self, CONN_INIREAD_ERROR, "Missing database name in call to CC_connect.", func); return 0; } return 1; } static char CC_setenv(ConnectionClass *self); #ifdef USE_LIBPQ static int LIBPQ_connect(ConnectionClass *self); static char LIBPQ_CC_connect(ConnectionClass *self, char password_req, char *salt_para) { int ret; CSTR func = "LIBPQ_CC_connect"; mylog("%s: entering...\n", func); if (password_req == AUTH_REQ_OK) /* not yet connected */ { if (0 == CC_initial_log(self, func)) return 0; } if (ret = LIBPQ_connect(self), ret <= 0) return ret; CC_setenv(self); return 1; } #endif /* USE_LIBPQ */ #if defined(USE_SSPI) || defined(USE_GSS) /* * Callee should free hte returned pointer. */ static char *MakePrincHint(ConnInfo *ci, BOOL sspi) { size_t len; char *svcprinc; char *svcname; BOOL attrFound = FALSE; svcname = extract_extra_attribute_setting(ci->conn_settings, "krbsrvname"); mylog("!!! %s settings=%s svcname=%p\n", __FUNCTION__, ci->conn_settings, svcname); if (svcname) attrFound = TRUE; else if (svcname = getenv("PGKRBSRVNAME"), NULL == svcname) svcname = "postgres"; len = strlen(svcname) + 1 + strlen(ci->server) + 1; if (NULL != (svcprinc = malloc(len))) { if (sspi) snprintf(svcprinc, len, "%s/%s", svcname, ci->server); else snprintf(svcprinc, len, "%s@%s", svcname, ci->server); } if (attrFound) free(svcname); return svcprinc; } #endif /* USE_SSPI */ static char original_CC_connect(ConnectionClass *self, char password_req, char *salt_para) { StartupPacket sp; StartupPacket6_2 sp62; QResultClass *res; SocketClass *sock; ConnInfo *ci = &(self->connInfo); int areq = -1; int ret = 0, beresp, sockerr; char msgbuffer[ERROR_MSG_LENGTH]; char salt[5], notice[512]; CSTR func = "original_CC_connect"; BOOL startPacketReceived = FALSE, anotherVersionRetry; #ifdef USE_SSPI int ssl_try_count, ssl_try_no; char ssl_call[2]; int bReconnect = 0; #endif /* USE_SSPI */ mylog("%s: entering...\n", func); /* lock the connetion during authentication */ ENTER_CONN_CS(self); #define return DONT_CALL_RETURN_FROM_HERE???? if (password_req != AUTH_REQ_OK) { sock = self->sock; /* already connected, just authenticate */ CC_clear_error(self); } else { if (0 == CC_initial_log(self, func)) goto error_proc; #ifdef USE_SSPI ssl_try_count = 0; switch (self->connInfo.sslmode[0]) { case SSLLBYTE_REQUIRE: case SSLLBYTE_VERIFY: ssl_call[ssl_try_count++] = 'y'; break; case SSLLBYTE_PREFER: ssl_call[ssl_try_count++] = 'y'; ssl_call[ssl_try_count++] = 'n'; break; case SSLLBYTE_ALLOW: ssl_call[ssl_try_count++] = 'n'; ssl_call[ssl_try_count++] = 'y'; break; default: ssl_call[ssl_try_count++] = 'n'; break; } ssl_try_no = 0; #endif /* USE_SSPI */ anotherVersionRetry = FALSE; another_version_retry: if (anotherVersionRetry) { #ifdef USE_SSPI if (PROTOCOL_74(ci) || PROTOCOL_64(ci)) { if (ssl_try_no < ssl_try_count) ssl_try_no++; } else ssl_try_no = ssl_try_count; if (ssl_try_no >= ssl_try_count) { #endif /* USE_SSPI */ /* retry older version */ if (PROTOCOL_62(ci)) { CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, "Could not construct a socket to the server", func); goto error_proc; } if (PROTOCOL_63(ci)) strncpy_null(ci->protocol, PG62, sizeof(ci->protocol)); else if (PROTOCOL_64(ci)) strncpy_null(ci->protocol, PG63, sizeof(ci->protocol)); else strncpy_null(ci->protocol, PG64, sizeof(ci->protocol)); #ifdef USE_SSPI ssl_try_no = 0; } #endif /* USE_SSPI */ if (self->sock) { SOCK_Destructor(self->sock); self->sock = (SocketClass *) 0; } self->status = CONN_NOT_CONNECTED; CC_initialize_pg_version(self); anotherVersionRetry = FALSE; } /* * If the socket was closed for some reason (like a SQLDisconnect, * but no SQLFreeConnect then create a socket now. */ if (!self->sock) { self->sock = SOCK_Constructor(self); if (!self->sock) { CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, "Could not construct a socket to the server", func); goto error_proc; } } sock = self->sock; mylog("connecting to the server socket...\n"); SOCK_connect_to(sock, (short) atoi(ci->port), ci->server, self->login_timeout); if (SOCK_get_errcode(sock) != 0) { CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, "Could not connect to the server", func); goto error_proc; } mylog("connection to the server socket succeeded.\n"); inolog("protocol=%s version=%d,%d\n", ci->protocol, self->pg_version_major, self->pg_version_minor); #ifdef USE_SSPI if ('y' == ssl_call[ssl_try_no]) { struct { Int4 slen; ProtocolVersion pv; } nego_packet; char rnego; nego_packet.slen = htonl(sizeof(nego_packet)); nego_packet.pv = htonl(PG_NEGOTIATE_SSLMODE); SOCK_put_n_char(sock, (char *) &nego_packet, sizeof(nego_packet)); SOCK_flush_output(sock); if (0 != SOCK_get_errcode(sock)) { mylog("%s:failed to send a negotiation packet\n", func); goto sockerr_proc; } SOCK_get_n_char(sock, &rnego, 1); if (0 != SOCK_get_errcode(sock)) goto sockerr_proc; mylog("nego got '%c'\n", rnego); switch (rnego) { case 'S': if (!StartupSspiService(sock, SchannelService, ci, &bReconnect)) { if (bReconnect != 0) { anotherVersionRetry = TRUE; goto another_version_retry; } CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Service negotation failed", func); goto error_proc; } break; case 'N': ssl_try_no++; if (ssl_try_no < ssl_try_count && 'y' != ssl_call[ssl_try_no]) break; else { anotherVersionRetry = TRUE; goto another_version_retry; } default: CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Service negotation failed", func); goto error_proc; } } #endif /* USE_SSPI */ if (PROTOCOL_62(ci)) { sock->reverse = TRUE; /* make put_int and get_int work * for 6.2 */ memset(&sp62, 0, sizeof(StartupPacket6_2)); sock->pversion = PG_PROTOCOL_62; SOCK_put_int(sock, htonl(4 + sizeof(StartupPacket6_2)), 4); sp62.authtype = htonl(NO_AUTHENTICATION); strncpy_null(sp62.database, ci->database, PATH_SIZE); strncpy_null(sp62.user, ci->username, USRNAMEDATALEN); SOCK_put_n_char(sock, (char *) &sp62, sizeof(StartupPacket6_2)); SOCK_flush_output(sock); } else if (PROTOCOL_74(ci)) { if (!protocol3_packet_build(self)) goto error_proc; } else { memset(&sp, 0, sizeof(StartupPacket)); mylog("sizeof startup packet = %d\n", sizeof(StartupPacket)); if (PROTOCOL_63(ci)) sock->pversion = PG_PROTOCOL_63; else sock->pversion = PG_PROTOCOL_64; /* Send length of Authentication Block */ SOCK_put_int(sock, 4 + sizeof(StartupPacket), 4); sp.protoVersion = (ProtocolVersion) htonl(sock->pversion); strncpy_null(sp.database, ci->database, SM_DATABASE); strncpy_null(sp.user, ci->username, SM_USER); SOCK_put_n_char(sock, (char *) &sp, sizeof(StartupPacket)); SOCK_flush_output(sock); } if (SOCK_get_errcode(sock) != 0) { CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Failed to send the authentication packet", func); goto error_proc; } mylog("sent the authentication block successfully.\n"); } mylog("gonna do authentication\n"); /* * Now get the authentication request from backend */ if (!PROTOCOL_62(ci)) { BOOL beforeV2 = PG_VERSION_LT(self, 6.4), ReadyForQuery = FALSE, retry = FALSE; uint32 leng = 0; #if defined(USE_GSS) || defined(USE_SSPI) || defined(USE_KRB5) int authRet; #endif do { if (password_req != AUTH_REQ_OK) { beresp = 'R'; startPacketReceived = TRUE; } else { beresp = SOCK_get_id(sock); mylog("auth got '%c'\n", beresp); if (0 != SOCK_get_errcode(sock)) goto sockerr_proc; if (PROTOCOL_74(ci)) { if (beresp != 'E' || startPacketReceived) { leng = SOCK_get_response_length(sock); inolog("leng=%d\n", leng); if (0 != SOCK_get_errcode(sock)) goto sockerr_proc; } else strncpy_null(ci->protocol, PG74REJECTED, sizeof(ci->protocol)); } startPacketReceived = TRUE; } switch (beresp) { case 'E': inolog("Ekita retry=%d\n", retry); handle_error_message(self, msgbuffer, sizeof(msgbuffer), self->sqlstate, func, NULL); CC_set_error(self, CONN_INVALID_AUTHENTICATION, msgbuffer, func); qlog("ERROR from backend during authentication: '%s'\n", msgbuffer); if (PROTOCOL_74REJECTED(ci)) retry = TRUE; else if (0 == strncmp(msgbuffer, "FATAL:", 6)) { const char *emsg = msgbuffer + 8; if (0 == strnicmp(emsg, "unsupported frontend protocol", 29)) retry = TRUE; #ifdef USE_SSPI else if ('y' != ssl_call[ssl_try_no] && ssl_try_no + 1 < ssl_try_count) retry = TRUE; #endif /* USE_SSPI */ } else if (strnicmp(msgbuffer, "Unsupported frontend protocol", 29) == 0) retry = TRUE; if (retry) break; goto error_proc; case 'R': if (password_req != AUTH_REQ_OK) { mylog("in 'R' password_req=%s\n", ci->password); areq = password_req; if (salt_para) memcpy(salt, salt_para, sizeof(salt)); password_req = AUTH_REQ_OK; mylog("salt=%02x%02x%02x%02x%02x\n", (UCHAR)salt[0], (UCHAR)salt[1], (UCHAR)salt[2], (UCHAR)salt[3], (UCHAR)salt[4]); } else { areq = SOCK_get_int(sock, 4); memset(salt, 0, sizeof(salt)); if (areq == AUTH_REQ_MD5) SOCK_get_n_char(sock, salt, 4); else if (areq == AUTH_REQ_CRYPT) SOCK_get_n_char(sock, salt, 2); mylog("areq = %d salt=%02x%02x%02x%02x%02x\n", areq, (UCHAR)salt[0], (UCHAR)salt[1], (UCHAR)salt[2], (UCHAR)salt[3], (UCHAR)salt[4]); } switch (areq) { case AUTH_REQ_OK: break; case AUTH_REQ_KRB4: CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "Kerberos 4 authentication not supported", func); goto error_proc; case AUTH_REQ_KRB5: #ifdef USE_KRB5 // pglock_thread(); authRet = pg_krb5_sendauth(self); // pgunlock_thread(); if (authRet != 0) { /* Error message already filled in */ goto error_proc; } break; #endif /* USE_KRB5 */ CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "Kerberos 5 authentication not supported", func); goto error_proc; case AUTH_REQ_PASSWORD: mylog("in AUTH_REQ_PASSWORD\n"); if (NAME_IS_NULL(ci->password)) { CC_set_error(self, CONNECTION_NEED_PASSWORD, "A password is required for this connection.", func); ret = -areq; /* need password */ goto error_proc; } mylog("past need password\n"); if (PROTOCOL_74(&(self->connInfo))) SOCK_put_char(sock, 'p'); SOCK_put_int(sock, (Int4) (4 + strlen(SAFE_NAME(ci->password)) + 1), 4); SOCK_put_n_char(sock, SAFE_NAME(ci->password), strlen(SAFE_NAME(ci->password)) + 1); sockerr = SOCK_flush_output(sock); mylog("past flush %dbytes\n", sockerr); break; case AUTH_REQ_CRYPT: CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "Password crypt authentication not supported", func); goto error_proc; case AUTH_REQ_MD5: mylog("in AUTH_REQ_MD5\n"); if (NAME_IS_NULL(ci->password)) { CC_set_error(self, CONNECTION_NEED_PASSWORD, "A password is required for this connection.", func); if (salt_para) memcpy(salt_para, salt, sizeof(salt)); ret = -areq; /* need password */ goto error_proc; } if (md5_auth_send(self, salt)) { CC_set_error(self, CONN_INVALID_AUTHENTICATION, "md5 hashing failed", func); goto error_proc; } break; case AUTH_REQ_SCM_CREDS: CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "Unix socket credential authentication not supported", func); goto error_proc; case AUTH_REQ_GSS: mylog("in AUTH_REQ_GSS\n"); #if defined(USE_SSPI) if (!ci->gssauth_use_gssapi) { self->auth_svcs = KerberosService; authRet = StartupSspiService(sock, self->auth_svcs, MakePrincHint(ci, TRUE), &bReconnect); if (!authRet) { CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Service negotation failed", func); goto error_proc; } break; } #endif /* USE_SSPI */ #ifdef USE_GSS #ifdef USE_SSPI if (ci->gssauth_use_gssapi) #endif /* USE_SSPI */ { // pglock_thread(); authRet = pg_GSS_startup(self, MakePrincHint(ci, FALSE)); // pgunlock_thread(); if (authRet != 0) { CC_set_errornumber(self, CONN_INVALID_AUTHENTICATION); goto error_proc; } break; } #endif /* USE_GSS */ CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "GSS authentication not supported", func); goto error_proc; case AUTH_REQ_GSS_CONT: mylog("in AUTH_REQ_GSS_CONT\n"); #if defined(USE_SSPI) if (0 != self->auth_svcs) { authRet = ContinueSspiService(sock, self->auth_svcs, (void *) (leng - 4)); if (!authRet) { CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Service continuation failed", func); goto error_proc; } break; } #endif /* USE_SSPI */ #ifdef USE_GSS // pglock_thread(); authRet = pg_GSS_continue(self, leng - 4); // pgunlock_thread(); if (authRet != 0) { CC_set_errornumber(self, CONN_INVALID_AUTHENTICATION); goto error_proc; } break; #else CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "GSS authentication not supported", func); goto error_proc; #endif case AUTH_REQ_SSPI: mylog("in AUTH_REQ_SSPI\n"); #if defined(USE_SSPI) self->auth_svcs = ci->gssauth_use_gssapi ? KerberosService : NegotiateService; if (!StartupSspiService(sock, self->auth_svcs, MakePrincHint(ci, TRUE), &bReconnect)) { CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Service negotation failed", func); goto error_proc; } break; #else CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "SSPI authentication not supported", func); goto error_proc; #endif default: CC_set_error(self, CONN_AUTH_TYPE_UNSUPPORTED, "Unknown authentication type", func); goto error_proc; } break; case 'S': /* parameter status */ getParameterValues(self); break; case 'K': /* Secret key (6.4 protocol) */ self->be_pid = SOCK_get_int(sock, 4); /* pid */ self->be_key = SOCK_get_int(sock, 4); /* key */ break; case 'Z': /* Backend is ready for new query (6.4) */ EatReadyForQuery(self); ReadyForQuery = TRUE; break; case 'N': /* Notices may come */ handle_notice_message(self, notice, sizeof(notice), self->sqlstate, "CC_connect", NULL); break; default: snprintf(notice, sizeof(notice), "Unexpected protocol character='%c' during authentication", beresp); CC_set_error(self, CONN_INVALID_AUTHENTICATION, notice, func); goto error_proc; } if (retry) { anotherVersionRetry = TRUE; goto another_version_retry; } /* * There were no ReadyForQuery responce before 6.4. */ if (beforeV2 && areq == AUTH_REQ_OK) ReadyForQuery = TRUE; } while (!ReadyForQuery); } sockerr_proc: ret = 1; error_proc: #undef return CC_endup_authentication(self); LEAVE_CONN_CS(self); if (0 >= ret) return ret; if (0 != (sockerr = SOCK_get_errcode(sock))) { if (0 == CC_get_errornumber(self)) { if (SOCKET_CLOSED == sockerr) CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Communication closed during authentication", func); else CC_set_error(self, CONN_INVALID_AUTHENTICATION, "Communication error during authentication", func); } return 0; } CC_clear_error(self); /* clear any password error */ /* * send an empty query in order to find out whether the specified * database really exists on the server machine */ if (!PROTOCOL_74(ci)) { mylog("sending an empty query...\n"); res = CC_send_query(self, " ", NULL, 0, NULL); if (res == NULL || (QR_get_rstatus(res) != PORES_EMPTY_QUERY && QR_command_nonfatal(res))) { CC_set_error(self, CONNECTION_NO_SUCH_DATABASE, "The database does not exist on the server\nor user authentication failed.", func); QR_Destructor(res); return 0; } QR_Destructor(res); mylog("empty query seems to be OK.\n"); /* * Get the version number first so we can check it before * sending options that are now obsolete. DJP 21/06/2002 */ inolog("CC_lookup_pg_version\n"); CC_lookup_pg_version(self); /* Get PostgreSQL version for SQLGetInfo use */ CC_setenv(self); } return 1; } char CC_connect(ConnectionClass *self, char password_req, char *salt_para) { ConnInfo *ci = &(self->connInfo); CSTR func = "CC_connect"; char ret, *saverr = NULL, retsend; #ifdef USE_LIBPQ BOOL call_libpq = FALSE; #endif /* USE_LIBPQ */ mylog("%s: entering...\n", func); mylog("sslmode=%s\n", self->connInfo.sslmode); #ifdef USE_LIBPQ #ifdef USE_SSPI if (0 != self->svcs_allowed) ; else #endif /* USE_SSPI */ if (self->connInfo.username[0] == '\0') call_libpq = TRUE; else if (self->connInfo.sslmode[0] != SSLLBYTE_DISABLE) call_libpq = TRUE; if (call_libpq) { ret = LIBPQ_CC_connect(self, password_req, salt_para); #ifdef USE_SSPI /* * If libpq is unavailable, try SSPI instead. */ if (0 == ret && CONN_UNABLE_TO_LOAD_DLL == CC_get_errornumber(self)) { self->svcs_allowed |= (SchannelService | KerberosService | NegotiateService); ret = original_CC_connect(self, password_req, salt_para); } #endif /* USE_SSPI */ } else #endif /* USE_LIBPQ */ { ret = original_CC_connect(self, password_req, salt_para); #ifdef USE_LIBPQ if (0 == ret && CONN_AUTH_TYPE_UNSUPPORTED == CC_get_errornumber(self)) { SOCK_Destructor(self->sock); self->sock = (SocketClass *) 0; ret = LIBPQ_CC_connect(self, password_req, salt_para); } #endif /* USE_LIBPQ */ } if (ret <= 0) return ret; CC_set_translation(self); /* * Send any initial settings */ /* * Since these functions allocate statements, and since the connection * is not established yet, it would violate odbc state transition * rules. Therefore, these functions call the corresponding local * function instead. */ inolog("CC_send_settings\n"); retsend = CC_send_settings(self); if (CC_get_errornumber(self) > 0) saverr = strdup(CC_get_errormsg(self)); CC_clear_error(self); /* clear any error */ CC_lookup_lo(self); /* a hack to get the oid of our large object oid type */ /* * Multibyte handling is available ? */ if (PG_VERSION_GE(self, 6.4)) { CC_lookup_characterset(self); if (CC_get_errornumber(self) > 0) { ret = 0; goto cleanup; } #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(self)) { if (!self->original_client_encoding || UTF8 != self->ccsc) { QResultClass *res; if (PG_VERSION_LT(self, 7.1)) { CC_set_error(self, CONN_NOT_IMPLEMENTED_ERROR, "UTF-8 conversion isn't implemented before 7.1", func); ret = 0; goto cleanup; } if (self->original_client_encoding) free(self->original_client_encoding); self->original_client_encoding = NULL; if (res = CC_send_query(self, "set client_encoding to 'UTF8'", NULL, 0, NULL), QR_command_maybe_successful(res)) { self->original_client_encoding = strdup("UNICODE"); self->ccsc = pg_CS_code(self->original_client_encoding); } QR_Destructor(res); } } #else { } #endif /* UNICODE_SUPPORT */ } #ifdef UNICODE_SUPPORT else if (CC_is_in_unicode_driver(self)) { CC_set_error(self, CONN_NOT_IMPLEMENTED_ERROR, "Unicode isn't supported before 6.4", func); ret = 0; goto cleanup; } #endif /* UNICODE_SUPPORT */ ci->updatable_cursors = DISALLOW_UPDATABLE_CURSORS; if (ci->allow_keyset && PG_VERSION_GE(self, 7.0)) /* Tid scan since 7.0 */ { if (ci->drivers.lie || !ci->drivers.use_declarefetch) ci->updatable_cursors |= (ALLOW_STATIC_CURSORS | ALLOW_KEYSET_DRIVEN_CURSORS | ALLOW_BULK_OPERATIONS | SENSE_SELF_OPERATIONS); else { if (PG_VERSION_GE(self, 7.4)) /* HOLDABLE CURSORS since 7.4 */ ci->updatable_cursors |= (ALLOW_STATIC_CURSORS | SENSE_SELF_OPERATIONS); } } if (CC_get_errornumber(self) > 0) CC_clear_error(self); /* clear any initial command errors */ self->status = CONN_CONNECTED; if (CC_is_in_unicode_driver(self) && 0 < ci->bde_environment) self->unicode |= CONN_DISALLOW_WCHAR; mylog("conn->unicode=%d\n", self->unicode); ret = 1; cleanup: mylog("%s: returning...%d\n", func, ret); if (NULL != saverr) { if (ret > 0 && CC_get_errornumber(self) <= 0) CC_set_error(self, -1, saverr, func); free(saverr); } if (1 == ret && 0 == retsend) ret = 2; return ret; } char CC_add_statement(ConnectionClass *self, StatementClass *stmt) { int i; char ret = TRUE; mylog("CC_add_statement: self=%p, stmt=%p\n", self, stmt); CONNLOCK_ACQUIRE(self); for (i = 0; i < self->num_stmts; i++) { if (!self->stmts[i]) { stmt->hdbc = self; self->stmts[i] = stmt; break; } } if (i >= self->num_stmts) /* no more room -- allocate more memory */ { StatementClass **newstmts; Int2 new_num_stmts; new_num_stmts = STMT_INCREMENT + self->num_stmts; if (new_num_stmts > 0) newstmts = (StatementClass **) realloc(self->stmts, sizeof(StatementClass *) * new_num_stmts); else newstmts = NULL; /* num_stmts overflowed */ if (!newstmts) ret = FALSE; else { self->stmts = newstmts; memset(&self->stmts[self->num_stmts], 0, sizeof(StatementClass *) * STMT_INCREMENT); stmt->hdbc = self; self->stmts[self->num_stmts] = stmt; self->num_stmts = new_num_stmts; } } CONNLOCK_RELEASE(self); return ret; } static void CC_set_error_statements(ConnectionClass *self) { int i; mylog("CC_error_statements: self=%p\n", self); for (i = 0; i < self->num_stmts; i++) { if (NULL != self->stmts[i]) SC_ref_CC_error(self->stmts[i]); } } char CC_remove_statement(ConnectionClass *self, StatementClass *stmt) { int i; char ret = FALSE; CONNLOCK_ACQUIRE(self); for (i = 0; i < self->num_stmts; i++) { if (self->stmts[i] == stmt && stmt->status != STMT_EXECUTING) { self->stmts[i] = NULL; ret = TRUE; break; } } CONNLOCK_RELEASE(self); return ret; } int CC_get_max_idlen(ConnectionClass *self) { int len = self->max_identifier_length; if (len < 0) { QResultClass *res; res = CC_send_query(self, "show max_identifier_length", NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN, NULL); if (QR_command_maybe_successful(res)) len = self->max_identifier_length = atoi(res->command); QR_Destructor(res); } mylog("max_identifier_length=%d\n", len); return len < 0 ? 0 : len; } /* * Create a more informative error message by concatenating the connection * error message with its socket error message. */ static char * CC_create_errormsg(ConnectionClass *self) { SocketClass *sock = self->sock; size_t pos; char msg[4096]; const char *sockerrmsg; mylog("enter CC_create_errormsg\n"); msg[0] = '\0'; if (CC_get_errormsg(self)) strncpy_null(msg, CC_get_errormsg(self), sizeof(msg)); mylog("msg = '%s'\n", msg); if (sock && NULL != (sockerrmsg = SOCK_get_errmsg(sock)) && '\0' != sockerrmsg[0]) { pos = strlen(msg); snprintf(&msg[pos], sizeof(msg) - pos, ";\n%s", sockerrmsg); } mylog("exit CC_create_errormsg\n"); return strdup(msg); } void CC_set_error(ConnectionClass *self, int number, const char *message, const char *func) { CONNLOCK_ACQUIRE(self); if (self->__error_message) free(self->__error_message); self->__error_number = number; self->__error_message = message ? strdup(message) : NULL; if (0 != number) CC_set_error_statements(self); if (func && number != 0) CC_log_error(func, "", self); CONNLOCK_RELEASE(self); } void CC_set_errormsg(ConnectionClass *self, const char *message) { CONNLOCK_ACQUIRE(self); if (self->__error_message) free(self->__error_message); self->__error_message = message ? strdup(message) : NULL; CONNLOCK_RELEASE(self); } char CC_get_error(ConnectionClass *self, int *number, char **message) { int rv; char *msgcrt; mylog("enter CC_get_error\n"); CONNLOCK_ACQUIRE(self); /* Create a very informative errormsg if it hasn't been done yet. */ if (!self->errormsg_created) { msgcrt = CC_create_errormsg(self); if (self->__error_message) free(self->__error_message); self->__error_message = msgcrt; self->errormsg_created = TRUE; } if (CC_get_errornumber(self)) { *number = CC_get_errornumber(self); *message = CC_get_errormsg(self); } rv = (CC_get_errornumber(self) != 0); CONNLOCK_RELEASE(self); mylog("exit CC_get_error\n"); return rv; } static int CC_close_eof_cursors(ConnectionClass *self) { int i, ccount = 0; StatementClass *stmt; QResultClass *res; if (!self->ncursors) return ccount; CONNLOCK_ACQUIRE(self); for (i = 0; i < self->num_stmts; i++) { if (stmt = self->stmts[i], NULL == stmt) continue; if (res = SC_get_Result(stmt), NULL == res) continue; if (NULL != QR_get_cursor(res) && QR_is_withhold(res) && QR_once_reached_eof(res)) { if (QR_get_num_cached_tuples(res) >= QR_get_num_total_tuples(res) || SQL_CURSOR_FORWARD_ONLY == stmt->options.cursor_type) { QR_close(res); ccount++; } } } CONNLOCK_RELEASE(self); return ccount; } static void CC_clear_cursors(ConnectionClass *self, BOOL on_abort) { int i; StatementClass *stmt; QResultClass *res; if (!self->ncursors) return; CONNLOCK_ACQUIRE(self); for (i = 0; i < self->num_stmts; i++) { stmt = self->stmts[i]; if (stmt && (res = SC_get_Result(stmt)) && (NULL != QR_get_cursor(res))) { /* * non-holdable cursors are automatically closed * at commit time. * all non-permanent cursors are automatically closed * at rollback time. */ if ((on_abort && !QR_is_permanent(res)) || !QR_is_withhold(res)) { QR_on_close_cursor(res); } else if (!QR_is_permanent(res)) { QResultClass *wres; char cmd[64]; if (QR_needs_survival_check(res)) { snprintf(cmd, sizeof(cmd), "MOVE 0 in \"%s\"", QR_get_cursor(res)); CONNLOCK_RELEASE(self); wres = CC_send_query(self, cmd, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN, NULL); QR_set_no_survival_check(res); if (QR_command_maybe_successful(wres)) QR_set_permanent(res); else QR_set_cursor(res, NULL); QR_Destructor(wres); CONNLOCK_ACQUIRE(self); } else QR_set_permanent(res); } } } CONNLOCK_RELEASE(self); } static void CC_mark_cursors_doubtful(ConnectionClass *self) { int i; StatementClass *stmt; QResultClass *res; if (!self->ncursors) return; CONNLOCK_ACQUIRE(self); for (i = 0; i < self->num_stmts; i++) { stmt = self->stmts[i]; if (NULL != stmt && NULL != (res = SC_get_Result(stmt)) && NULL != QR_get_cursor(res) && !QR_is_permanent(res)) QR_set_survival_check(res); } CONNLOCK_RELEASE(self); } void CC_on_commit(ConnectionClass *conn) { CONNLOCK_ACQUIRE(conn); if (CC_is_in_trans(conn)) { CC_set_no_trans(conn); CC_set_no_manual_trans(conn); } CC_clear_cursors(conn, FALSE); CONNLOCK_RELEASE(conn); CC_discard_marked_objects(conn); CONNLOCK_ACQUIRE(conn); if (conn->result_uncommitted) { CONNLOCK_RELEASE(conn); ProcessRollback(conn, FALSE, FALSE); CONNLOCK_ACQUIRE(conn); conn->result_uncommitted = 0; } CONNLOCK_RELEASE(conn); } void CC_on_abort(ConnectionClass *conn, UDWORD opt) { BOOL set_no_trans = FALSE; mylog("CC_on_abort in\n"); CONNLOCK_ACQUIRE(conn); if (0 != (opt & CONN_DEAD)) /* CONN_DEAD implies NO_TRANS also */ opt |= NO_TRANS; if (CC_is_in_trans(conn)) { if (0 != (opt & NO_TRANS)) { CC_set_no_trans(conn); CC_set_no_manual_trans(conn); set_no_trans = TRUE; } } CC_clear_cursors(conn, TRUE); if (0 != (opt & CONN_DEAD)) { conn->status = CONN_DOWN; if (conn->sock) { CONNLOCK_RELEASE(conn); SOCK_Destructor(conn->sock); CONNLOCK_ACQUIRE(conn); conn->sock = NULL; } } else if (set_no_trans) { CONNLOCK_RELEASE(conn); CC_discard_marked_objects(conn); CONNLOCK_ACQUIRE(conn); } if (conn->result_uncommitted) { CONNLOCK_RELEASE(conn); ProcessRollback(conn, TRUE, FALSE); CONNLOCK_ACQUIRE(conn); conn->result_uncommitted = 0; } CONNLOCK_RELEASE(conn); } void CC_on_abort_partial(ConnectionClass *conn) { mylog("CC_on_abort_partial in\n"); ProcessRollback(conn, TRUE, TRUE); CONNLOCK_ACQUIRE(conn); CC_discard_marked_objects(conn); CONNLOCK_RELEASE(conn); } static BOOL is_setting_search_path(const char *query) { for (query += 4; *query; query++) { if (!isspace((unsigned char) *query)) { if (strnicmp(query, "search_path", 11) == 0) return TRUE; query++; while (*query && !isspace((unsigned char) *query)) query++; } } return FALSE; } BOOL static CC_fetch_tuples(QResultClass *res, ConnectionClass *conn, const char *cursor, BOOL *ReadyToReturn, BOOL *kill_conn) { BOOL success = TRUE; int lastMessageType; if (!QR_fetch_tuples(res, conn, cursor, &lastMessageType)) { qlog("fetch_tuples failed lastMessageType=%02x\n", lastMessageType); success = FALSE; if (0 >= CC_get_errornumber(conn)) { switch (QR_get_rstatus(res)) { case PORES_NO_MEMORY_ERROR: CC_set_error(conn, CONN_NO_MEMORY_ERROR, NULL, __FUNCTION__); break; case PORES_BAD_RESPONSE: CC_set_error(conn, CONNECTION_COMMUNICATION_ERROR, "communication error occured", __FUNCTION__); break; default: CC_set_error(conn, CONN_EXEC_ERROR, QR_get_message(res), __FUNCTION__); break; } } switch (lastMessageType) { case 'Z': if (ReadyToReturn) *ReadyToReturn = TRUE; break; case 'C': case 'E': break; default: if (ReadyToReturn) *ReadyToReturn = TRUE; if (kill_conn) *kill_conn = TRUE; break; } } return success; } /* * The "result_in" is only used by QR_next_tuple() to fetch another group of rows into * the same existing QResultClass (this occurs when the tuple cache is depleted and * needs to be re-filled). * * The "cursor" is used by SQLExecute to associate a statement handle as the cursor name * (i.e., C3326857) for SQL select statements. This cursor is then used in future * 'declare cursor C3326857 for ...' and 'fetch 100 in C3326857' statements. */ QResultClass * CC_send_query_append(ConnectionClass *self, const char *query, QueryInfo *qi, UDWORD flag, StatementClass *stmt, const char *appendq) { CSTR func = "CC_send_query"; QResultClass *cmdres = NULL, *retres = NULL, *res = NULL; BOOL ignore_abort_on_conn = ((flag & IGNORE_ABORT_ON_CONN) != 0), create_keyset = ((flag & CREATE_KEYSET) != 0), issue_begin = ((flag & GO_INTO_TRANSACTION) != 0 && !CC_is_in_trans(self)), rollback_on_error, query_rollback, end_with_commit; const char *wq; char swallow, *ptr; CSTR svpcmd = "SAVEPOINT"; CSTR per_query_svp = "_per_query_svp_"; CSTR rlscmd = "RELEASE"; static size_t lenbgncmd = 0, lenrbkcmd = 0, lensvpcmd = 0, lenrlscmd = 0, lenperqsvp = 0; size_t qrylen; int id; int maxlen, empty_reqs; BOOL ReadyToReturn = FALSE, query_completed = FALSE, beforeV2 = PG_VERSION_LT(self, 6.4), aborted = FALSE, used_passed_result_object = FALSE, discard_next_begin = FALSE, kill_conn = FALSE, discard_next_savepoint = FALSE, consider_rollback; Int4 response_length; UInt4 leng; ConnInfo *ci = &(self->connInfo); int func_cs_count = 0; /* ERROR_MSG_LENGTH is suffcient */ char msgbuffer[ERROR_MSG_LENGTH + 1]; /* QR_set_command() dups this string so doesn't need static */ char cmdbuffer[ERROR_MSG_LENGTH + 1]; BOOL reduce_round_trip_time = !(flag & IGNORE_ROUND_TRIP); if (appendq) { mylog("%s_append: conn=%p, query='%s'+'%s'\n", func, self, query, appendq); qlog("conn=%p, query='%s'+'%s'\n", self, query, appendq); } else { mylog("%s: conn=%p, query='%s'\n", func, self, query); qlog("conn=%p, query='%s'\n", self, query); } if (!self->sock) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send Query(connection dead)", func); CC_on_abort(self, CONN_DEAD); return NULL; } ENTER_INNER_CONN_CS(self, func_cs_count); /* Finish the pending extended query first */ if (!SyncParseRequest(self)) { if (CC_get_errornumber(self) <= 0) { CC_set_error(self, CONN_EXEC_ERROR, "error occured while calling SyncParseRequest() in CC_send_query_append()", func); CLEANUP_FUNC_CONN_CS(func_cs_count, self); return NULL; } } /* Indicate that we are sending a query to the backend */ maxlen = CC_get_max_query_len(self); qrylen = strlen(query); if (maxlen > 0 && maxlen < (int) qrylen + 1) { CC_set_error(self, CONNECTION_MSG_TOO_LONG, "Query string is too long", func); CLEANUP_FUNC_CONN_CS(func_cs_count, self); return NULL; } if ((NULL == query) || (query[0] == '\0')) { CLEANUP_FUNC_CONN_CS(func_cs_count, self); return NULL; } if (SOCK_get_errcode(self->sock) != 0) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send Query to backend", func); CC_on_abort(self, CONN_DEAD); CLEANUP_FUNC_CONN_CS(func_cs_count, self); return NULL; } /* * In case the round trip time can be ignored, the query * and the appeneded query would be issued separately. * Otherwise a multiple command query would be issued. */ if (appendq && !reduce_round_trip_time) { res = CC_send_query_append(self, query, qi, flag, stmt, NULL); if (QR_command_maybe_successful(res)) { cmdres = CC_send_query_append(self, appendq, qi, flag & (~(GO_INTO_TRANSACTION)), stmt, NULL); if (QR_command_maybe_successful(cmdres)) res->next = cmdres; else { QR_Destructor(res); res = cmdres; } } CLEANUP_FUNC_CONN_CS(func_cs_count, self); return res; } rollback_on_error = (flag & ROLLBACK_ON_ERROR) != 0; end_with_commit = (flag & END_WITH_COMMIT) != 0; #define return DONT_CALL_RETURN_FROM_HERE??? consider_rollback = (issue_begin || (CC_is_in_trans(self) && !CC_is_in_error_trans(self)) || strnicmp(query, "begin", 5) == 0); if (rollback_on_error) rollback_on_error = consider_rollback; query_rollback = (rollback_on_error && !end_with_commit && PG_VERSION_GE(self, 8.0)); if (!query_rollback && consider_rollback && !end_with_commit) { if (stmt) { StatementClass *astmt = SC_get_ancestor(stmt); if (!SC_accessed_db(astmt)) { if (SQL_ERROR == SetStatementSvp(astmt)) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal savepoint error", func); goto cleanup; } } } } SOCK_put_char(self->sock, 'Q'); if (SOCK_get_errcode(self->sock) != 0) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send Query to backend", func); goto cleanup; } if (stmt) SC_forget_unnamed(stmt); if (!lenbgncmd) { lenbgncmd = strlen(bgncmd); lensvpcmd = strlen(svpcmd); lenrbkcmd = strlen(rbkcmd); lenrlscmd = strlen(rlscmd); lenperqsvp = strlen(per_query_svp); } if (PROTOCOL_74(ci)) { leng = (UInt4) qrylen; if (appendq) leng += (UInt4) (strlen(appendq) + 1); if (issue_begin) leng += (UInt4) (lenbgncmd + 1); if (query_rollback) { leng += (UInt4) (lensvpcmd + 1 + lenperqsvp + 1); leng += (UInt4) (1 + lenrlscmd + 1 + lenperqsvp); } leng++; SOCK_put_int(self->sock, leng + 4, 4); inolog("leng=%d\n", leng); } if (issue_begin) { SOCK_put_n_char(self->sock, bgncmd, lenbgncmd); SOCK_put_n_char(self->sock, semi_colon, 1); discard_next_begin = TRUE; } if (query_rollback) { char cmd[64]; snprintf(cmd, sizeof(cmd), "%s %s;", svpcmd, per_query_svp); SOCK_put_n_char(self->sock, cmd, strlen(cmd)); discard_next_savepoint = TRUE; } SOCK_put_n_char(self->sock, query, qrylen); if (appendq) { SOCK_put_n_char(self->sock, semi_colon, 1); SOCK_put_n_char(self->sock, appendq, strlen(appendq)); } if (query_rollback) { char cmd[64]; snprintf(cmd, sizeof(cmd), ";%s %s", rlscmd, per_query_svp); SOCK_put_n_char(self->sock, cmd, strlen(cmd)); } SOCK_put_n_char(self->sock, NULL_STRING, 1); leng = SOCK_flush_output(self->sock); if (SOCK_get_errcode(self->sock) != 0) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send Query to backend", func); goto cleanup; } mylog("send_query: done sending query %dbytes flushed\n", leng); empty_reqs = 0; for (wq = query; isspace((UCHAR) *wq); wq++) ; if (*wq == '\0') empty_reqs = 1; cmdres = qi ? qi->result_in : NULL; if (cmdres) used_passed_result_object = TRUE; else { cmdres = QR_Constructor(); if (!cmdres) { CC_set_error(self, CONNECTION_COULD_NOT_RECEIVE, "Could not create result info in send_query.", func); goto cleanup; } } res = cmdres; while (!ReadyToReturn) { /* what type of message is coming now ? */ id = SOCK_get_id(self->sock); if ((SOCK_get_errcode(self->sock) != 0) || (id == EOF)) { CC_set_error(self, CONNECTION_NO_RESPONSE, "No response from the backend", func); mylog("send_query: 'id' - %s\n", CC_get_errormsg(self)); kill_conn = TRUE; break; } mylog("send_query: got id = '%c'\n", id); response_length = SOCK_get_response_length(self->sock); inolog("send_query response_length=%d\n", response_length); switch (id) { case 'A': /* Asynchronous Messages are ignored */ (void) SOCK_get_int(self->sock, 4); /* id of notification */ SOCK_get_string(self->sock, msgbuffer, ERROR_MSG_LENGTH); /* name of the relation the message comes from */ break; case 'C': /* portal query command, no tuples * returned */ /* read in the return message from the backend */ SOCK_get_string(self->sock, cmdbuffer, ERROR_MSG_LENGTH); if (SOCK_get_errcode(self->sock) != 0) { CC_set_error(self, CONNECTION_NO_RESPONSE, "No response from backend while receiving a portal query command", func); mylog("send_query: 'C' - %s\n", CC_get_errormsg(self)); ReadyToReturn = TRUE; } else { mylog("send_query: ok - 'C' - %s\n", cmdbuffer); if (query_completed) /* allow for "show" style notices */ { res->next = QR_Constructor(); res = res->next; } mylog("send_query: setting cmdbuffer = '%s'\n", cmdbuffer); my_trim(cmdbuffer); /* get rid of trailing space */ if (strnicmp(cmdbuffer, bgncmd, lenbgncmd) == 0) { CC_set_in_trans(self); if (discard_next_begin) /* discard the automatically issued BEGIN */ { discard_next_begin = FALSE; continue; /* discard the result */ } } else if (strnicmp(cmdbuffer, svpcmd, lensvpcmd) == 0) { if (discard_next_savepoint) { inolog("Discarded the first SAVEPOINT\n"); discard_next_savepoint = FALSE; continue; /* discard the result */ } } else if (strnicmp(cmdbuffer, rbkcmd, lenrbkcmd) == 0) { CC_mark_cursors_doubtful(self); if (PROTOCOL_74(&(self->connInfo))) CC_set_in_error_trans(self); /* mark the transaction error in case of manual rollback */ else CC_on_abort(self, NO_TRANS); } /* * DROP TABLE or ALTER TABLE may change * the table definition. So clear the * col_info cache though it may be too simple. */ else if (strnicmp(cmdbuffer, "DROP TABLE", 10) == 0 || strnicmp(cmdbuffer, "ALTER TABLE", 11) == 0) CC_clear_col_info(self, FALSE); else { ptr = strrchr(cmdbuffer, ' '); if (ptr) res->recent_processed_row_count = atoi(ptr + 1); else res->recent_processed_row_count = -1; if (PROTOCOL_74(&(self->connInfo))) { if (NULL != self->current_schema && strnicmp(cmdbuffer, "SET", 3) == 0) { if (is_setting_search_path(query)) reset_current_schema(self); } } else { if (strnicmp(cmdbuffer, cmtcmd, 6) == 0) CC_on_commit(self); else if (strnicmp(cmdbuffer, "END", 3) == 0) CC_on_commit(self); else if (strnicmp(cmdbuffer, "ABORT", 5) == 0) CC_on_abort(self, NO_TRANS); } } if (QR_command_successful(res)) QR_set_rstatus(res, PORES_COMMAND_OK); QR_set_command(res, cmdbuffer); query_completed = TRUE; mylog("send_query: returning res = %p\n", res); if (!beforeV2) break; /* * (Quotation from the original comments) since * backend may produce more than one result for some * commands we need to poll until clear so we send an * empty query, and keep reading out of the pipe until * an 'I' is received */ if (empty_reqs == 0) { SOCK_put_string(self->sock, "Q "); SOCK_flush_output(self->sock); empty_reqs++; } } break; case 'Z': /* Backend is ready for new query (6.4) */ if (empty_reqs == 0) { ReadyToReturn = TRUE; if (aborted || query_completed) retres = cmdres; else ReadyToReturn = FALSE; } EatReadyForQuery(self); break; case 'N': /* NOTICE: */ handle_notice_message(self, cmdbuffer, sizeof(cmdbuffer), res->sqlstate, "send_query", res); break; /* dont return a result -- continue * reading */ case 'I': /* The server sends an empty query */ /* There is a closing '\0' following the 'I', so we eat it */ if (PROTOCOL_74(ci) && 0 == response_length) swallow = '\0'; else swallow = SOCK_get_char(self->sock); if ((swallow != '\0') || SOCK_get_errcode(self->sock) != 0) { CC_set_errornumber(self, CONNECTION_BACKEND_CRAZY); QR_set_message(res, "Unexpected protocol character from backend (send_query - I)"); QR_set_rstatus(res, PORES_FATAL_ERROR); kill_conn = TRUE; ReadyToReturn = TRUE; break; } else { /* We return the empty query */ QR_set_rstatus(res, PORES_EMPTY_QUERY); } if (empty_reqs > 0) { if (--empty_reqs == 0) query_completed = TRUE; } else if (!beforeV2) query_completed = TRUE; break; case 'E': handle_error_message(self, msgbuffer, sizeof(msgbuffer), res->sqlstate, "send_query", res); /* We should report that an error occured. Zoltan */ aborted = TRUE; query_completed = TRUE; break; case 'P': /* get the Portal name */ SOCK_get_string(self->sock, msgbuffer, ERROR_MSG_LENGTH); break; case 'T': /* Tuple results start here */ if (query_completed) { res->next = QR_Constructor(); if (!res->next) { CC_set_error(self, CONNECTION_COULD_NOT_RECEIVE, "Could not create result info in send_query.", func); ReadyToReturn = TRUE; retres = NULL; break; } if (create_keyset) { QR_set_haskeyset(res->next); if (stmt) res->next->num_key_fields = stmt->num_key_fields; } mylog("send_query: 'T' no result_in: res = %p\n", res->next); res = res->next; if (qi) QR_set_cache_size(res, qi->row_size); } if (!used_passed_result_object) { const char *cursor = qi ? qi->cursor : NULL; if (create_keyset) { QR_set_haskeyset(res); if (stmt) res->num_key_fields = stmt->num_key_fields; if (cursor && cursor[0]) QR_set_synchronize_keys(res); } if (!CC_fetch_tuples(res, self, cursor, &ReadyToReturn, &kill_conn)) { if (QR_command_maybe_successful(res)) retres = NULL; else retres = cmdres; aborted = TRUE; } query_completed = TRUE; } else { /* next fetch, so reuse an existing result */ /* * called from QR_next_tuple and must return * immediately. */ ReadyToReturn = TRUE; if (!CC_fetch_tuples(res, NULL, NULL, &ReadyToReturn, &kill_conn)) { retres = NULL; break; } retres = cmdres; } break; case 'G': /* Copy in command began successfully */ { size_t alsize = 256, pos, len; char *buf = malloc(alsize), *tmpbuf, tchar; for (pos = 0; NULL != fgets(buf + pos, alsize - pos, stdin);) { len = strlen(buf); mylog("get copydata len=%d %02x%02x\n", len, ((UCHAR *) buf)[0], ((UCHAR *) buf)[1]); tchar = buf[len - 1]; if ('\n' == tchar) { buf[len - 1] = '\0'; len--; } else { if (len >= alsize - 1) { if (tmpbuf = realloc(buf, alsize * 2), NULL == tmpbuf) { aborted = TRUE; break; } else { buf = tmpbuf; alsize *= 2; pos = len; continue; } } } SOCK_put_char(self->sock, 'd'); /* CopyData */ SOCK_put_int(self->sock, 4 + len, 4); SOCK_put_n_char(self->sock, buf, len); pos = 0; } if (aborted) { mylog("copy fail\n"); SOCK_put_char(self->sock, 'f'); /* CopyFail */ SOCK_put_int(self->sock, 18, 4); SOCK_put_string(self->sock, "Out of memory"); } else { mylog("copy done\n"); SOCK_put_char(self->sock, 'c'); /* CopyDone */ SOCK_put_int(self->sock, 4, 4); } SOCK_flush_output(self->sock); free(buf); } break; case 'H': /* Copy out command began successfully */ break; case 'c': /* Copy out command donesuccessfully */ fclose(stdout); break; case 'd': /* CopyData comes */ mylog("!!! copydata len=%d\n", response_length); break; case 'f': /* CopyFail */ aborted = TRUE; break; case 'D': /* Copy in command began successfully */ if (query_completed) { res->next = QR_Constructor(); res = res->next; } QR_set_rstatus(res, PORES_COPY_IN); ReadyToReturn = TRUE; retres = cmdres; break; case 'B': /* Copy out command began successfully */ if (query_completed) { res->next = QR_Constructor(); res = res->next; } QR_set_rstatus(res, PORES_COPY_OUT); ReadyToReturn = TRUE; retres = cmdres; break; case 'S': /* parameter status */ getParameterValues(self); break; case 's': /* portal suspended * may not occur */ QR_set_no_fetching_tuples(res); res->dataFilled = TRUE; break; default: /* skip the unexpected response if possible */ if (response_length >= 0) break; CC_set_error(self, CONNECTION_BACKEND_CRAZY, "Unexpected protocol character from backend (send_query)", func); CC_on_abort(self, CONN_DEAD); mylog("send_query: error - %s\n", CC_get_errormsg(self)); ReadyToReturn = TRUE; retres = NULL; break; } if (SOCK_get_errcode(self->sock) != 0) break; if (CONN_DOWN == self->status) break; /* * There was no ReadyForQuery response before 6.4. */ if (beforeV2) { if (empty_reqs == 0 && query_completed) break; } } cleanup: if (SOCK_get_errcode(self->sock) != 0) { if (0 == CC_get_errornumber(self)) CC_set_error(self, CONNECTION_COMMUNICATION_ERROR, "Communication error while sending query", func); kill_conn = TRUE; } if (kill_conn) { CC_on_abort(self, CONN_DEAD); retres = NULL; } if (rollback_on_error && CC_is_in_trans(self) && !discard_next_savepoint) { char cmd[64]; cmd[0] = '\0'; if (query_rollback) { if (CC_is_in_error_trans(self)) { snprintf(cmd, sizeof(cmd), "%s TO %s;", rbkcmd, per_query_svp); snprintf_add(cmd, sizeof(cmd), "%s %s", rlscmd, per_query_svp); } } else if (CC_is_in_error_trans(self)) strcpy(cmd, rbkcmd); if (cmd[0]) QR_Destructor(CC_send_query(self, cmd, NULL, IGNORE_ABORT_ON_CONN, NULL)); } CLEANUP_FUNC_CONN_CS(func_cs_count, self); #undef return /* * Break before being ready to return. */ if (!ReadyToReturn) retres = cmdres; /* * Cleanup garbage results before returning. */ if (cmdres && retres != cmdres && !used_passed_result_object) QR_Destructor(cmdres); /* * Cleanup the aborted result if specified */ if (retres) { if (aborted) { /** if (ignore_abort_on_conn) { if (!used_passed_result_object) { QR_Destructor(retres); retres = NULL; } } **/ if (retres) { /* * discard results other than errors. */ QResultClass *qres; for (qres = retres; qres->next; qres = retres) { if (QR_get_aborted(qres)) break; retres = qres->next; qres->next = NULL; QR_Destructor(qres); } /* * If error message isn't set */ if (ignore_abort_on_conn) CC_set_errornumber(self, 0); else if (retres) { if (NULL == CC_get_errormsg(self) || !CC_get_errormsg(self)[0]) CC_set_errormsg(self, QR_get_message(retres)); if (!self->sqlstate[0]) strcpy(self->sqlstate, retres->sqlstate); } } } } return retres; } int CC_send_function(ConnectionClass *self, int fnid, void *result_buf, int *actual_result_len, int result_is_int, LO_ARG *args, int nargs) { CSTR func = "CC_send_function"; char id, done; SocketClass *sock = self->sock; /* ERROR_MSG_LENGTH is sufficient */ char msgbuffer[ERROR_MSG_LENGTH + 1]; int i; int ret = TRUE; UInt4 leng; Int4 response_length; ConnInfo *ci; int func_cs_count = 0; BOOL sinceV3, beforeV3, beforeV2, resultResponse; mylog("send_function(): conn=%p, fnid=%d, result_is_int=%d, nargs=%d\n", self, fnid, result_is_int, nargs); if (!self->sock) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send function(connection dead)", func); CC_on_abort(self, CONN_DEAD); return FALSE; } if (SOCK_get_errcode(sock) != 0) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send function to backend", func); CC_on_abort(self, CONN_DEAD); return FALSE; } /* Finish the pending extended query first */ if (!SyncParseRequest(self)) { if (CC_get_errornumber(self) <= 0) { CC_set_error(self, CONN_EXEC_ERROR, "error occured while calling SyncParseRequest() in CC_send_function()", func); return FALSE; } } #define return DONT_CALL_RETURN_FROM_HERE??? ENTER_INNER_CONN_CS(self, func_cs_count); ci = &(self->connInfo); sinceV3 = PROTOCOL_74(ci); beforeV3 = (!sinceV3); beforeV2 = (beforeV3 && !PROTOCOL_64(ci)); if (sinceV3) { leng = 4 + sizeof(uint32) + 2 + 2 + sizeof(uint16); for (i = 0; i < nargs; i++) { leng += 4; if (args[i].len >= 0) { if (args[i].isint) leng += 4; else leng += args[i].len; } } leng += 2; SOCK_put_char(sock, 'F'); SOCK_put_int(sock, leng, 4); } else SOCK_put_string(sock, "F "); if (SOCK_get_errcode(sock) != 0) { CC_set_error(self, CONNECTION_COULD_NOT_SEND, "Could not send function to backend", func); CC_on_abort(self, CONN_DEAD); ret = FALSE; goto cleanup; } SOCK_put_int(sock, fnid, 4); if (sinceV3) { SOCK_put_int(sock, 1, 2); /* # of formats */ SOCK_put_int(sock, 1, 2); /* the format is binary */ SOCK_put_int(sock, nargs, 2); } else SOCK_put_int(sock, nargs, 4); mylog("send_function: done sending function\n"); for (i = 0; i < nargs; ++i) { mylog(" arg[%d]: len = %d, isint = %d, integer = %d, ptr = %p\n", i, args[i].len, args[i].isint, args[i].u.integer, args[i].u.ptr); SOCK_put_int(sock, args[i].len, 4); if (args[i].isint) SOCK_put_int(sock, args[i].u.integer, 4); else SOCK_put_n_char(sock, (char *) args[i].u.ptr, args[i].len); } if (sinceV3) SOCK_put_int(sock, 1, 2); /* result format is binary */ mylog(" done sending args\n"); SOCK_flush_output(sock); mylog(" after flush output\n"); done = FALSE; resultResponse = FALSE; /* for before V3 only */ while (!done) { id = SOCK_get_id(sock); mylog(" got id = %c\n", id); response_length = SOCK_get_response_length(sock); inolog("send_func response_length=%d\n", response_length); switch (id) { case 'G': if (!resultResponse) { done = TRUE; ret = FALSE; break; } /* fall through */ case 'V': if ('V' == id) { if (beforeV3) /* FunctionResultResponse */ { resultResponse = TRUE; break; } } *actual_result_len = SOCK_get_int(sock, 4); if (-1 != *actual_result_len) { if (result_is_int) *((int *) result_buf) = SOCK_get_int(sock, 4); else SOCK_get_n_char(sock, (char *) result_buf, *actual_result_len); mylog(" after get result\n"); } if (beforeV3) { SOCK_get_char(sock); /* get the last '0' */ if (beforeV2) done = TRUE; resultResponse = FALSE; mylog(" after get 0\n"); } break; /* ok */ case 'N': handle_notice_message(self, msgbuffer, sizeof(msgbuffer), NULL, "send_function", NULL); /* continue reading */ break; case 'E': handle_error_message(self, msgbuffer, sizeof(msgbuffer), NULL, "send_function", NULL); CC_set_errormsg(self, msgbuffer); #ifdef _LEGACY_MODE_ CC_on_abort(self, 0); #endif /* _LEGACY_MODE_ */ mylog("send_function(V): 'E' - %s\n", CC_get_errormsg(self)); qlog("ERROR from backend during send_function: '%s'\n", CC_get_errormsg(self)); if (beforeV2) done = TRUE; ret = FALSE; break; case 'Z': EatReadyForQuery(self); done = TRUE; break; case '0': /* empty result */ if (resultResponse) { if (beforeV2) done = TRUE; resultResponse = FALSE; break; } /* fall through */ default: /* skip the unexpected response if possible */ if (response_length >= 0) break; CC_set_error(self, CONNECTION_BACKEND_CRAZY, "Unexpected protocol character from backend (send_function, args)", func); CC_on_abort(self, CONN_DEAD); mylog("send_function: error - %s\n", CC_get_errormsg(self)); done = TRUE; ret = FALSE; break; } } cleanup: #undef return CLEANUP_FUNC_CONN_CS(func_cs_count, self); return ret; } static char CC_setenv(ConnectionClass *self) { ConnInfo *ci = &(self->connInfo); HSTMT hstmt; StatementClass *stmt; RETCODE result; char status = TRUE; CSTR func = "CC_setenv"; mylog("%s: entering...\n", func); /* * This function must use the local odbc API functions since the odbc state * has not transitioned to "connected" yet. */ result = PGAPI_AllocStmt(self, &hstmt, 0); if (!SQL_SUCCEEDED(result)) return FALSE; stmt = (StatementClass *) hstmt; stmt->internal = TRUE; /* ensure no BEGIN/COMMIT/ABORT stuff */ /* Set the Datestyle to the format the driver expects it to be in */ result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) "set DateStyle to 'ISO'", SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; mylog("%s: result %d, status %d from set DateStyle\n", func, result, status); /* Disable genetic optimizer based on global flag */ if (ci->drivers.disable_optimizer) { result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) "set geqo to 'OFF'", SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; mylog("%s: result %d, status %d from set geqo\n", func, result, status); } /* KSQO (not applicable to 7.1+ - DJP 21/06/2002) */ if (ci->drivers.ksqo && PG_VERSION_LT(self, 7.1)) { result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) "set ksqo to 'ON'", SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; mylog("%s: result %d, status %d from set ksqo\n", func, result, status); } /* extra_float_digits (applicable since 7.4) */ if (PG_VERSION_GT(self, 7.3)) { result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) "set extra_float_digits to 2", SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; mylog("%s: result %d, status %d from set extra_float_digits\n", func, result, status); } PGAPI_FreeStmt(hstmt, SQL_DROP); return status; } char CC_send_settings(ConnectionClass *self) { /* char ini_query[MAX_MESSAGE_LEN]; */ ConnInfo *ci = &(self->connInfo); /* QResultClass *res; */ HSTMT hstmt; StatementClass *stmt; RETCODE result; char status = TRUE; char *cs, *ptr; #ifdef HAVE_STRTOK_R char *last; #endif /* HAVE_STRTOK_R */ CSTR func = "CC_send_settings"; mylog("%s: entering...\n", func); /* * This function must use the local odbc API functions since the odbc state * has not transitioned to "connected" yet. */ result = PGAPI_AllocStmt(self, &hstmt, 0); if (!SQL_SUCCEEDED(result)) return FALSE; stmt = (StatementClass *) hstmt; stmt->internal = TRUE; /* ensure no BEGIN/COMMIT/ABORT stuff */ /* Global settings */ if (NAME_IS_VALID(ci->drivers.conn_settings)) { cs = strdup(GET_NAME(ci->drivers.conn_settings)); if (cs) { #ifdef HAVE_STRTOK_R ptr = strtok_r(cs, semi_colon, &last); #else ptr = strtok(cs, semi_colon); #endif /* HAVE_STRTOK_R */ while (ptr) { result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) ptr, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; mylog("%s: result %d, status %d from '%s'\n", func, result, status, ptr); #ifdef HAVE_STRTOK_R ptr = strtok_r(NULL, semi_colon, &last); #else ptr = strtok(NULL, semi_colon); #endif /* HAVE_STRTOK_R */ } free(cs); } else status = FALSE; } /* Per Datasource settings */ if (NAME_IS_VALID(ci->conn_settings)) { cs = strdup(GET_NAME(ci->conn_settings)); if (cs) { #ifdef HAVE_STRTOK_R ptr = strtok_r(cs, semi_colon, &last); #else ptr = strtok(cs, semi_colon); #endif /* HAVE_STRTOK_R */ while (ptr) { result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) ptr, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; mylog("%s: result %d, status %d from '%s'\n", func, result, status, ptr); #ifdef HAVE_STRTOK_R ptr = strtok_r(NULL, semi_colon, &last); #else ptr = strtok(NULL, semi_colon); #endif /* HAVE_STRTOK_R */ } free(cs); } else status = FALSE; } PGAPI_FreeStmt(hstmt, SQL_DROP); return status; } /* * This function is just a hack to get the oid of our Large Object oid type. * If a real Large Object oid type is made part of Postgres, this function * will go away and the define 'PG_TYPE_LO' will be updated. */ static void CC_lookup_lo(ConnectionClass *self) { QResultClass *res; CSTR func = "CC_lookup_lo"; mylog("%s: entering...\n", func); if (PG_VERSION_GE(self, 7.4)) res = CC_send_query(self, "select oid, typbasetype from pg_type where typname = '" PG_TYPE_LO_NAME "'", NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL); else res = CC_send_query(self, "select oid, 0 from pg_type where typname='" PG_TYPE_LO_NAME "'", NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL); if (QR_command_maybe_successful(res) && QR_get_num_cached_tuples(res) > 0) { OID basetype; self->lobj_type = QR_get_value_backend_int(res, 0, 0, NULL); basetype = QR_get_value_backend_int(res, 0, 1, NULL); if (PG_TYPE_OID == basetype) self->lo_is_domain = 1; else if (0 != basetype) self->lobj_type = 0; } QR_Destructor(res); mylog("Got the large object oid: %d\n", self->lobj_type); qlog(" [ Large Object oid = %d ]\n", self->lobj_type); return; } /* * This function initializes the version of PostgreSQL from * connInfo.protocol that we're connected to. * h-inoue 01-2-2001 */ void CC_initialize_pg_version(ConnectionClass *self) { strcpy(self->pg_version, self->connInfo.protocol); if (PROTOCOL_62(&self->connInfo)) { self->pg_version_number = (float) 6.2; self->pg_version_major = 6; self->pg_version_minor = 2; } else if (PROTOCOL_63(&self->connInfo)) { self->pg_version_number = (float) 6.3; self->pg_version_major = 6; self->pg_version_minor = 3; } else if (PROTOCOL_64(&self->connInfo)) { self->pg_version_number = (float) 6.4; self->pg_version_major = 6; self->pg_version_minor = 4; } else { self->pg_version_number = (float) 7.4; self->pg_version_major = 7; self->pg_version_minor = 4; } } /* * This function gets the version of PostgreSQL that we're connected to. * This is used to return the correct info in SQLGetInfo * DJP - 25-1-2001 */ static void CC_lookup_pg_version(ConnectionClass *self) { HSTMT hstmt; RETCODE result; char szVersion[32]; int major, minor; CSTR func = "CC_lookup_pg_version"; mylog("%s: entering...\n", func); /* * This function must use the local odbc API functions since the odbc state * has not transitioned to "connected" yet. */ result = PGAPI_AllocStmt(self, &hstmt, 0); if (!SQL_SUCCEEDED(result)) return; /* get the server's version if possible */ result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) "select version()", SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) { PGAPI_FreeStmt(hstmt, SQL_DROP); return; } result = PGAPI_Fetch(hstmt); if (!SQL_SUCCEEDED(result)) { PGAPI_FreeStmt(hstmt, SQL_DROP); return; } result = PGAPI_GetData(hstmt, 1, SQL_C_CHAR, self->pg_version, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { PGAPI_FreeStmt(hstmt, SQL_DROP); return; } /* * Extract the Major and Minor numbers from the string. This assumes * the string starts 'Postgresql X.X' */ strcpy(szVersion, "0.0"); if (sscanf(self->pg_version, "%*s %d.%d", &major, &minor) >= 2) { snprintf(szVersion, sizeof(szVersion), "%d.%d", major, minor); self->pg_version_major = major; self->pg_version_minor = minor; } self->pg_version_number = (float) atof(szVersion); if (PG_VERSION_GE(self, 7.3)) self->schema_support = 1; mylog("Got the PostgreSQL version string: '%s'\n", self->pg_version); mylog("Extracted PostgreSQL version number: '%1.1f'\n", self->pg_version_number); qlog(" [ PostgreSQL version string = '%s' ]\n", self->pg_version); qlog(" [ PostgreSQL version number = '%1.1f' ]\n", self->pg_version_number); result = PGAPI_FreeStmt(hstmt, SQL_DROP); } void CC_log_error(const char *func, const char *desc, const ConnectionClass *self) { #ifdef PRN_NULLCHECK #define nullcheck(a) (a ? a : "(NULL)") #endif if (self) { qlog("CONN ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->__error_number, nullcheck(self->__error_message)); mylog("CONN ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->__error_number, nullcheck(self->__error_message)); qlog(" ------------------------------------------------------------\n"); qlog(" henv=%p, conn=%p, status=%u, num_stmts=%d\n", self->henv, self, self->status, self->num_stmts); qlog(" sock=%p, stmts=%p, lobj_type=%d\n", self->sock, self->stmts, self->lobj_type); qlog(" ---------------- Socket Info -------------------------------\n"); if (self->sock) { SocketClass *sock = self->sock; qlog(" socket=%d, reverse=%d, errornumber=%d, errormsg='%s'\n", sock->socket, sock->reverse, sock->errornumber, nullcheck(SOCK_get_errmsg(sock))); qlog(" buffer_in=%u, buffer_out=%u\n", sock->buffer_in, sock->buffer_out); qlog(" buffer_filled_in=%d, buffer_filled_out=%d, buffer_read_in=%d\n", sock->buffer_filled_in, sock->buffer_filled_out, sock->buffer_read_in); } } else { qlog("INVALID CONNECTION HANDLE ERROR: func=%s, desc='%s'\n", func, desc); mylog("INVALID CONNECTION HANDLE ERROR: func=%s, desc='%s'\n", func, desc); } #undef PRN_NULLCHECK } int CC_get_max_query_len(const ConnectionClass *conn) { int value; /* Long Queries in 7.0+ */ if (PG_VERSION_GE(conn, 7.0)) value = 0 /* MAX_STATEMENT_LEN */ ; /* Prior to 7.0 we used 2*BLCKSZ */ else if (PG_VERSION_GE(conn, 6.5)) value = (2 * BLCKSZ); else /* Prior to 6.5 we used BLCKSZ */ value = BLCKSZ; return value; } /* * This doesn't really return the CURRENT SCHEMA * but there's no alternative. */ const char * CC_get_current_schema(ConnectionClass *conn) { if (!conn->current_schema && conn->schema_support) { QResultClass *res; if (res = CC_send_query(conn, "select current_schema()", NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL), QR_command_maybe_successful(res)) { if (QR_get_num_total_tuples(res) == 1) conn->current_schema = strdup(QR_get_value_backend_text(res, 0, 0)); } QR_Destructor(res); } return (const char *) conn->current_schema; } static int LIBPQ_send_cancel_request(const ConnectionClass *conn); int CC_send_cancel_request(const ConnectionClass *conn) { int save_errno = SOCK_ERRNO; SOCKETFD tmpsock = -1; struct { uint32 packetlen; CancelRequestPacket cp; } crp; BOOL ret = TRUE; SocketClass *sock; struct sockaddr *sadr; /* Check we have an open connection */ if (!conn) return FALSE; sock = CC_get_socket(conn); if (!sock) return FALSE; #ifdef USE_LIBPQ if (sock->via_libpq) return LIBPQ_send_cancel_request(conn); #endif /* USE_LIBPQ */ /* * We need to open a temporary connection to the postmaster. Use the * information saved by connectDB to do this with only kernel calls. */ sadr = (struct sockaddr *) &(sock->sadr_area); if ((tmpsock = socket(sadr->sa_family, SOCK_STREAM, 0)) < 0) { return FALSE; } if (connect(tmpsock, sadr, sock->sadr_len) < 0) { closesocket(tmpsock); return FALSE; } /* * We needn't set nonblocking I/O or NODELAY options here. */ crp.packetlen = htonl((uint32) sizeof(crp)); crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE); crp.cp.backendPID = htonl(conn->be_pid); crp.cp.cancelAuthCode = htonl(conn->be_key); while (send(tmpsock, (char *) &crp, sizeof(crp), SEND_FLAG) != (int) sizeof(crp)) { if (SOCK_ERRNO != EINTR) { save_errno = SOCK_ERRNO; ret = FALSE; break; } } if (ret) { while (recv(tmpsock, (char *) &crp, 1, RECV_FLAG) < 0) { if (EINTR != SOCK_ERRNO) break; } } /* Sent it, done */ closesocket(tmpsock); SOCK_ERRNO_SET(save_errno); return ret; } int CC_mark_a_object_to_discard(ConnectionClass *conn, int type, const char *plan) { int cnt = conn->num_discardp + 1; char *pname; CC_REALLOC_return_with_error(conn->discardp, char *, (cnt * sizeof(char *)), conn, "Couldn't alloc discardp.", -1); CC_MALLOC_return_with_error(pname, char, (strlen(plan) + 2), conn, "Couldn't alloc discardp mem.", -1); pname[0] = (char) type; /* 's':prepared statement 'p':cursor */ strcpy(pname + 1, plan); conn->discardp[conn->num_discardp++] = pname; return 1; } int CC_discard_marked_objects(ConnectionClass *conn) { int i, cnt; QResultClass *res; char *pname, cmd[64]; if ((cnt = conn->num_discardp) <= 0) return 0; for (i = cnt - 1; i >= 0; i--) { pname = conn->discardp[i]; if ('s' == pname[0]) snprintf(cmd, sizeof(cmd), "DEALLOCATE \"%s\"", pname + 1); else snprintf(cmd, sizeof(cmd), "CLOSE \"%s\"", pname + 1); res = CC_send_query(conn, cmd, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN, NULL); QR_Destructor(res); free(conn->discardp[i]); conn->num_discardp--; } return 1; } #ifdef USE_LIBPQ static int LIBPQ_connect(ConnectionClass *self) { CSTR func = "LIBPQ_connect"; char ret = 0; char *conninfo = NULL; void *pqconn = NULL; SocketClass *sock; int socket = -1, pqret; BOOL libpqLoaded; mylog("connecting to the database using %s as the server\n",self->connInfo.server); sock = self->sock; inolog("sock=%p\n", sock); if (!sock) { sock = SOCK_Constructor(self); if (!sock) { CC_set_error(self, CONN_OPENDB_ERROR, "Could not construct a socket to the server", func); goto cleanup1; } } #ifdef NOT_USED /* currently not yet used */ if (FALSE && connect_with_param_available()) { const char *opts[PROTOCOL3_OPTS_MAX], *vals[PROTOCOL3_OPTS_MAX]; protocol3_opts_array(self, opts, vals, TRUE, sizeof(opts) / sizeof(opts[0])); pqconn = CALL_PQconnectdbParams(opts, vals, &libpqLoaded); } else #endif /* NOT_USED */ { if (!(conninfo = protocol3_opts_build(self))) { if (CC_get_errornumber(self) <= 0) CC_set_error(self, CONN_OPENDB_ERROR, "Couldn't allcate conninfo", func); goto cleanup1; } pqconn = CALL_PQconnectdb(conninfo, &libpqLoaded); free(conninfo); } if (!libpqLoaded) { CC_set_error(self, CONN_UNABLE_TO_LOAD_DLL, "Couldn't load libpq library", func); goto cleanup1; } sock->via_libpq = TRUE; if (!pqconn) { CC_set_error(self, CONN_OPENDB_ERROR, "PQconnectdb error", func); goto cleanup1; } sock->pqconn = pqconn; pqret = PQstatus(pqconn); if (CONNECTION_OK != pqret) { const char *errmsg; inolog("status=%d\n", pqret); errmsg = PQerrorMessage(pqconn); CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, errmsg, func); if (CONNECTION_BAD == pqret && strstr(errmsg, "no password")) { mylog("password retry\n"); PQfinish(pqconn); sock->pqconn = NULL; self->sock = sock; return -1; } mylog("Could not establish connection to the database; LIBPQ returned -> %s\n", errmsg); goto cleanup1; } ret = 1; cleanup1: if (!ret) { if (sock) SOCK_Destructor(sock); self->sock = NULL; return ret; } mylog("libpq connection to the database succeeded.\n"); ret = 0; socket = PQsocket(pqconn); inolog("socket=%d\n", socket); sock->socket = socket; #ifdef USE_SSL sock->ssl = PQgetssl(pqconn); inolog("ssl=%p\n", sock->ssl); #endif /* USE_SSL */ if (TRUE) { int pversion; ConnInfo *ci = &self->connInfo; sock->pversion = PG_PROTOCOL_74; strncpy_null(ci->protocol, PG74, sizeof(ci->protocol)); pversion = PQprotocolVersion(pqconn); switch (pversion) { case 2: sock->pversion = PG_PROTOCOL_64; strncpy_null(ci->protocol, PG64, sizeof(ci->protocol)); break; } } mylog("protocol=%s\n", self->connInfo.protocol); { int pversion; const char *conforming_strings; pversion = PQserverVersion(pqconn); self->pg_version_major = pversion / 10000; self->pg_version_minor = (pversion % 10000) / 100; sprintf(self->pg_version, "%d.%d.%d", self->pg_version_major, self->pg_version_minor, pversion % 100); self->pg_version_number = (float) atof(self->pg_version); if (PG_VERSION_GE(self, 7.3)) self->schema_support = 1; if (conforming_strings = PQparameterStatus(pqconn, std_cnf_strs), NULL != conforming_strings) { if (stricmp(conforming_strings, "on") == 0) self->escape_in_literal = '\0'; } /* blocking mode */ /* ioctlsocket(sock, FIONBIO , 0); setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)); */ } #ifdef USE_SSL if (sock->ssl) { /* flags = fcntl(sock, F_GETFL); fcntl(sock, F_SETFL, flags & (~O_NONBLOCKING));*/ } #endif /* USE_SSL */ mylog("Server version=%s\n", self->pg_version); ret = 1; if (ret) { self->sock = sock; if (!CC_get_username(self)[0]) { mylog("PQuser=%s\n", PQuser(pqconn)); strcpy(self->connInfo.username, PQuser(pqconn)); } } else { SOCK_Destructor(sock); self->sock = NULL; } mylog("%s: retuning %d\n", func, ret); return ret; } static int LIBPQ_send_cancel_request(const ConnectionClass *conn) { int ret = 0; char errbuf[256]; void *cancel; SocketClass *sock = CC_get_socket(conn); if (!sock) return FALSE; cancel = PQgetCancel(sock->pqconn); if (!cancel) return FALSE; ret = PQcancel(cancel, errbuf, sizeof(errbuf)); PQfreeCancel(cancel); if (1 == ret) return TRUE; else return FALSE; } #endif /* USE_LIBPQ */ const char *CurrCat(const ConnectionClass *conn) { /* * Returning the database name causes problems in MS Query. It * generates query like: "SELECT DISTINCT a FROM byronnbad3 * bad3" */ if (isMsQuery()) /* MS Query */ return NULL; else if (conn->schema_support) return conn->connInfo.database; else return NULL; } const char *CurrCatString(const ConnectionClass *conn) { const char *cat = CurrCat(conn); if (!cat) cat = NULL_STRING; return cat; } #ifdef _HANDLE_ENLIST_IN_DTC_ /* * Export the following functions so that the pgenlist dll * can handle ConnectionClass objects as opaque ones. */ #define _PGDTC_FUNCS_IMPLEMENT_ #include "connexp.h" #define SYNC_AUTOCOMMIT(conn) (SQL_AUTOCOMMIT_OFF != conn->connInfo.autocommit_public ? (conn->transact_status |= CONN_IN_AUTOCOMMIT) : (conn->transact_status &= ~CONN_IN_AUTOCOMMIT)) DLL_DECLARE void PgDtc_create_connect_string(void *self, char *connstr, int strsize) { ConnectionClass *conn = (ConnectionClass *) self; ConnInfo *ci = &(conn->connInfo); snprintf(connstr, strsize, "DRIVER={%s};SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s;" ABBR_SSLMODE "=%s", ci->drivername, ci->server, ci->port, ci->database, ci->username, SAFE_NAME(ci->password), ci->sslmode); } DLL_DECLARE void PgDtc_set_async(void *self, void *async) { ConnectionClass *conn = (ConnectionClass *) self; if (!conn) return; CONNLOCK_ACQUIRE(conn); if (NULL != async) CC_set_autocommit(conn, FALSE); else SYNC_AUTOCOMMIT(conn); conn->asdum = async; CONNLOCK_RELEASE(conn); } DLL_DECLARE void *PgDtc_get_async(void *self) { ConnectionClass *conn = (ConnectionClass *) self; return conn->asdum; } DLL_DECLARE void PgDtc_set_property(void *self, int property, void *value) { ConnectionClass *conn = (ConnectionClass *) self; CONNLOCK_ACQUIRE(conn); switch (property) { case inprogress: if (NULL != value) CC_set_dtc_executing(conn); else CC_no_dtc_executing(conn); break; case enlisted: if (NULL != value) CC_set_dtc_enlisted(conn); else CC_no_dtc_enlisted(conn); break; case prepareRequested: if (NULL != value) CC_set_dtc_prepareRequested(conn); else CC_no_dtc_prepareRequested(conn); break; } CONNLOCK_RELEASE(conn); } DLL_DECLARE void PgDtc_set_error(void *self, const char *message, const char *func) { ConnectionClass *conn = (ConnectionClass *) self; CC_set_error(conn, CONN_UNSUPPORTED_OPTION, message, func); } DLL_DECLARE int PgDtc_get_property(void *self, int property) { ConnectionClass *conn = (ConnectionClass *) self; int ret; CONNLOCK_ACQUIRE(conn); switch (property) { case inprogress: ret = CC_is_dtc_executing(conn); break; case enlisted: ret = CC_is_dtc_enlisted(conn); break; case inTrans: ret = CC_is_in_trans(conn); break; case errorNumber: ret = CC_get_errornumber(conn); break; case idleInGlobalTransaction: ret = CC_is_idle_in_global_transaction(conn); break; case connected: ret = (CONN_CONNECTED == conn->status); break; case prepareRequested: ret = CC_is_dtc_prepareRequested(conn); break; } CONNLOCK_RELEASE(conn); return ret; } DLL_DECLARE BOOL PgDtc_connect(void *self) { CSTR func = "PgDtc_connect"; ConnectionClass *conn = (ConnectionClass *) self; if (CONN_CONNECTED == conn->status) return TRUE; if (CC_connect(conn, AUTH_REQ_OK, NULL) <= 0) { /* Error messages are filled in */ CC_log_error(func, "Error on CC_connect", conn); return FALSE; } return TRUE; } DLL_DECLARE void PgDtc_free_connect(void *self) { ConnectionClass *conn = (ConnectionClass *) self; PGAPI_FreeConnect(conn); } DLL_DECLARE BOOL PgDtc_one_phase_operation(void *self, int operation) { ConnectionClass *conn = (ConnectionClass *) self; BOOL ret, is_in_progress = CC_is_dtc_executing(conn); if (!is_in_progress) CC_set_dtc_executing(conn); switch (operation) { case ONE_PHASE_COMMIT: ret = CC_commit(conn); break; default: ret = CC_abort(conn); break; } if (!is_in_progress) CC_no_dtc_executing(conn); return ret; } DLL_DECLARE BOOL PgDtc_two_phase_operation(void *self, int operation, const char *gxid) { ConnectionClass *conn = (ConnectionClass *) self; QResultClass *qres; BOOL ret = TRUE; char cmd[512]; switch (operation) { case PREPARE_TRANSACTION: snprintf(cmd, sizeof(cmd), "PREPARE TRANSACTION '%s'", gxid); break; case COMMIT_PREPARED: snprintf(cmd, sizeof(cmd), "COMMIT PREPARED '%s'", gxid); break; case ROLLBACK_PREPARED: snprintf(cmd, sizeof(cmd), "ROLLBACK PREPARED '%s'", gxid); break; } qres = CC_send_query(conn, cmd, NULL, 0, NULL); if (!QR_command_maybe_successful(qres)) ret = FALSE; QR_Destructor(qres); return ret; } DLL_DECLARE BOOL PgDtc_lock_cntrl(void *self, BOOL acquire, BOOL bTrial) { ConnectionClass *conn = (ConnectionClass *) self; BOOL ret = TRUE; if (acquire) if (bTrial) ret = TRY_ENTER_CONN_CS(conn); else ENTER_CONN_CS(conn); else LEAVE_CONN_CS(conn); return ret; } static ConnectionClass * CC_Copy(const ConnectionClass *conn) { ConnectionClass *newconn = CC_alloc(); if (newconn) { memcpy(newconn, conn, sizeof(ConnectionClass)); CC_lockinit(newconn); } return newconn; } #define CLEANUP_CONN_BEFORE_ISOLATION DLL_DECLARE void * PgDtc_isolate(void *self, DWORD option) { BOOL disposingConn = (0 != (disposingConnection & option)); ConnectionClass *sconn = (ConnectionClass *) self, *newconn = NULL; #ifndef CLEANUP_CONN_BEFORE_ISOLATION int i; #endif /* CLEANUP_CONN_BEFORE_ISOLATION */ #ifdef CLEANUP_CONN_BEFORE_ISOLATION if (0 == (useAnotherRoom & option)) #else if (disposingConn) #endif /* CLEANUP_CONN_BEFORE_ISOLATION */ { HENV henv = sconn->henv; #ifdef CLEANUP_CONN_BEFORE_ISOLATION CC_cleanup(sconn, TRUE); #endif /* CLEANUP_CONN_BEFORE_ISOLATION */ if (newconn = CC_Copy(sconn), NULL == newconn) return newconn; mylog("%s:newconn=%p from %p\n", __FUNCTION__, newconn, sconn); CC_initialize(sconn, FALSE); #ifdef CLEANUP_CONN_BEFORE_ISOLATION if (!disposingConn) CC_copy_conninfo(&sconn->connInfo, &newconn->connInfo); #endif /* CLEANUP_CONN_BEFORE_ISOLATION */ sconn->henv = newconn->henv; newconn->henv = NULL; SYNC_AUTOCOMMIT(sconn); #ifndef CLEANUP_CONN_BEFORE_ISOLATION for (i = 0; i < newconn->num_stmts; i++) { StatementClass *stmt; if (stmt = newconn->stmts[i], NULL != stmt) SC_get_conn(stmt) = newconn; } #if (ODBCVER >= 0x0300) for (i = 0; i < newconn->num_descs; i++) { DescriptorClass *desc; if (desc = newconn->descs[i], NULL != desc) DC_get_conn(desc) = newconn; } #endif /* ODBCVER */ #endif /* CLEANUP_CONN_BEFORE_ISOLATION */ return newconn; } newconn = CC_Constructor(); CC_copy_conninfo(&newconn->connInfo, &sconn->connInfo); newconn->asdum = sconn->asdum; newconn->gTranInfo = sconn->gTranInfo; CC_set_dtc_isolated(newconn); sconn->asdum = NULL; SYNC_AUTOCOMMIT(sconn); CC_set_dtc_clear(sconn); if (0 != (useAnotherRoom & option)) { mylog("generated connection=%p with %p\n", newconn, newconn->asdum); return newconn; } #ifndef CLEANUP_CONN_BEFORE_ISOLATION newconn->sock = sconn->sock; sconn->sock = NULL; mylog("Isolated connection=%p(status %d) with %p\n", newconn, sconn->status, sconn->asdum); newconn->__error_number = sconn->__error_number; sconn->__error_number = 0; newconn->__error_message = sconn->__error_message; sconn->__error_message = NULL; newconn->errormsg_created = sconn->errormsg_created; sconn->errormsg_created = FALSE; strcpy(newconn->sqlstate, sconn->sqlstate); sconn->sqlstate[0] = '\0'; // newconn->ardOptions = sconn->ardOptions; // newconn->apdOptions = sconn->apdOptions; newconn->status = sconn->status; sconn->status = CONN_NOT_CONNECTED; /* Cursors are no longer available */ for (i = 0; i < sconn->num_stmts; i++) { StatementClass *stmt; QResultClass *res; stmt = sconn->stmts[i]; if (stmt && (res = SC_get_Result(stmt)) && (NULL != QR_get_cursor(res))) QR_set_cursor(res, NULL); } sconn->ncursors = 0; newconn->lobj_type = sconn->lobj_type; newconn->driver_version = sconn->driver_version; newconn->transact_status = sconn->transact_status & (CONN_IN_TRANSACTION | CONN_IN_ERROR_BEFORE_IDLE); sconn->transact_status = 0; strcpy(newconn->pg_version, sconn->pg_version); newconn->pg_version_number = sconn->pg_version_number; newconn->pg_version_major = sconn->pg_version_major; newconn->pg_version_minor = sconn->pg_version_minor; newconn->ms_jet = sconn->ms_jet; newconn->unicode = sconn->unicode; newconn->schema_support = sconn->schema_support; newconn->lo_is_domain = sconn->lo_is_domain; newconn->escape_in_literal = sconn->escape_in_literal; newconn->original_client_encoding = sconn->original_client_encoding; sconn->original_client_encoding = NULL; newconn->current_client_encoding = sconn->current_client_encoding; sconn->current_client_encoding = NULL; newconn->server_encoding = sconn->server_encoding; sconn->server_encoding = NULL; newconn->ccsc = sconn->ccsc; newconn->mb_maxbyte_per_char = sconn->mb_maxbyte_per_char; newconn->be_pid = sconn->be_pid; sconn->be_pid = 0; newconn->isolation = sconn->isolation; newconn->current_schema = sconn->current_schema; sconn->current_schema = NULL; newconn->max_identifier_length = sconn->max_identifier_length; newconn->num_discardp = sconn->num_discardp; newconn->discardp = sconn->discardp; sconn->num_discardp = 0; sconn->discardp = NULL; #ifdef USE_SSPI newconn->svcs_allowed = sconn->svcs_allowed; sconn->svcs_allowed = 0; #endif /* USE_SSPI */ #endif /* CLEANUP_CONN_BEFORE_ISOLATION */ return newconn; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ psqlodbc-09.03.0300/convert.c000644 001752 000000 00000436721 12335653444 016041 0ustar00saitowheel000000 000000 /*------- * Module: convert.c * * Description: This module contains routines related to * converting parameters and columns into requested data types. * Parameters are converted from their SQL_C data types into * the appropriate postgres type. Columns are converted from * their postgres type (SQL type) into the appropriate SQL_C * data type. * * Classes: n/a * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ /* Multibyte support Eiji Tokuya 2001-03-15 */ #include "convert.h" #include "misc.h" #ifdef WIN32 #include #define HAVE_LOCALE_H #endif /* WIN32 */ #include #include #include #include "multibyte.h" #include #ifdef HAVE_LOCALE_H #include #endif #include #include #include "statement.h" #include "qresult.h" #include "bind.h" #include "pgtypes.h" #include "lobj.h" #include "connection.h" #include "catfunc.h" #include "pgapifunc.h" #if defined(UNICODE_SUPPORT) && defined(WIN32) #define WIN_UNICODE_SUPPORT #endif CSTR NAN_STRING = "NaN"; CSTR INFINITY_STRING = "Infinity"; CSTR MINFINITY_STRING = "-Infinity"; #ifdef __CYGWIN__ #define TIMEZONE_GLOBAL _timezone #elif defined(WIN32) || defined(HAVE_INT_TIMEZONE) #define TIMEZONE_GLOBAL timezone #endif /* * How to map ODBC scalar functions {fn func(args)} to Postgres. * This is just a simple substitution. List augmented from: * http://www.merant.com/datadirect/download/docs/odbc16/Odbcref/rappc.htm * - thomas 2000-04-03 */ char *mapFuncs[][2] = { /* { "ASCII", "ascii" }, built_in */ {"CHAR", "chr($*)" }, {"CONCAT", "textcat($*)" }, /* { "DIFFERENCE", "difference" }, how to ? */ {"INSERT", "substring($1 from 1 for $2 - 1) || $4 || substring($1 from $2 + $3)" }, {"LCASE", "lower($*)" }, {"LEFT", "ltrunc($*)" }, {"%2LOCATE", "strpos($2, $1)" }, /* 2 parameters */ {"%3LOCATE", "strpos(substring($2 from $3), $1) + $3 - 1" }, /* 3 parameters */ {"LENGTH", "char_length($*)"}, /* { "LTRIM", "ltrim" }, built_in */ {"RIGHT", "rtrunc($*)" }, {"SPACE", "repeat('' '', $1)" }, /* { "REPEAT", "repeat" }, built_in */ /* { "REPLACE", "replace" }, ??? */ /* { "RTRIM", "rtrim" }, built_in */ /* { "SOUNDEX", "soundex" }, how to ? */ {"SUBSTRING", "substr($*)" }, {"UCASE", "upper($*)" }, /* { "ABS", "abs" }, built_in */ /* { "ACOS", "acos" }, built_in */ /* { "ASIN", "asin" }, built_in */ /* { "ATAN", "atan" }, built_in */ /* { "ATAN2", "atan2" }, bui;t_in */ {"CEILING", "ceil($*)" }, /* { "COS", "cos" }, built_in */ /* { "COT", "cot" }, built_in */ /* { "DEGREES", "degrees" }, built_in */ /* { "EXP", "exp" }, built_in */ /* { "FLOOR", "floor" }, built_in */ {"LOG", "ln($*)" }, {"LOG10", "log($*)" }, /* { "MOD", "mod" }, built_in */ /* { "PI", "pi" }, built_in */ {"POWER", "pow($*)" }, /* { "RADIANS", "radians" }, built_in */ {"%0RAND", "random()" }, /* 0 parameters */ {"%1RAND", "(setseed($1) * .0 + random())" }, /* 1 parameters */ /* { "ROUND", "round" }, built_in */ /* { "SIGN", "sign" }, built_in */ /* { "SIN", "sin" }, built_in */ /* { "SQRT", "sqrt" }, built_in */ /* { "TAN", "tan" }, built_in */ {"TRUNCATE", "trunc($*)" }, {"CURRENT_DATE", "current_date" }, {"CURRENT_TIME", "current_time" }, {"CURRENT_TIMESTAMP", "current_timestamp" }, {"LOCALTIME", "localtime" }, {"LOCALTIMESTAMP", "localtimestamp" }, {"CURRENT_USER", "cast(current_user as text)" }, {"SESSION_USER", "cast(session_user as text)" }, {"CURDATE", "current_date" }, {"CURTIME", "current_time" }, {"DAYNAME", "to_char($1, 'Day')" }, {"DAYOFMONTH", "cast(extract(day from $1) as integer)" }, {"DAYOFWEEK", "(cast(extract(dow from $1) as integer) + 1)" }, {"DAYOFYEAR", "cast(extract(doy from $1) as integer)" }, {"HOUR", "cast(extract(hour from $1) as integer)" }, {"MINUTE", "cast(extract(minute from $1) as integer)" }, {"MONTH", "cast(extract(month from $1) as integer)" }, {"MONTHNAME", " to_char($1, 'Month')" }, /* { "NOW", "now" }, built_in */ {"QUARTER", "cast(extract(quarter from $1) as integer)" }, {"SECOND", "cast(extract(second from $1) as integer)" }, {"WEEK", "cast(extract(week from $1) as integer)" }, {"YEAR", "cast(extract(year from $1) as integer)" }, /* { "DATABASE", "database" }, */ {"IFNULL", "coalesce($*)" }, {"USER", "cast(current_user as text)" }, {0, 0} }; static const char *mapFunction(const char *func, int param_count); static int conv_from_octal(const char *s); static SQLLEN pg_bin2hex(const char *src, char *dst, SQLLEN length); #ifdef UNICODE_SUPPORT static SQLLEN pg_bin2whex(const char *src, SQLWCHAR *dst, SQLLEN length); #endif /* UNICODE_SUPPORT */ /*--------- * A Guide for date/time/timestamp conversions * * field_type fCType Output * ---------- ------ ---------- * PG_TYPE_DATE SQL_C_DEFAULT SQL_C_DATE * PG_TYPE_DATE SQL_C_DATE SQL_C_DATE * PG_TYPE_DATE SQL_C_TIMESTAMP SQL_C_TIMESTAMP (time = 0 (midnight)) * PG_TYPE_TIME SQL_C_DEFAULT SQL_C_TIME * PG_TYPE_TIME SQL_C_TIME SQL_C_TIME * PG_TYPE_TIME SQL_C_TIMESTAMP SQL_C_TIMESTAMP (date = current date) * PG_TYPE_ABSTIME SQL_C_DEFAULT SQL_C_TIMESTAMP * PG_TYPE_ABSTIME SQL_C_DATE SQL_C_DATE (time is truncated) * PG_TYPE_ABSTIME SQL_C_TIME SQL_C_TIME (date is truncated) * PG_TYPE_ABSTIME SQL_C_TIMESTAMP SQL_C_TIMESTAMP *--------- */ /* * Macros for unsigned long handling. */ #ifdef WIN32 #define ATOI32U(val) strtoul(val, NULL, 10) #elif defined(HAVE_STRTOUL) #define ATOI32U(val) strtoul(val, NULL, 10) #else /* HAVE_STRTOUL */ #define ATOI32U atol #endif /* WIN32 */ /* * Macros for BIGINT handling. */ #ifdef ODBCINT64 #ifdef WIN32 #define ATOI64(val) _strtoi64(val, NULL, 10) #define ATOI64U(val) _strtoui64(val, NULL, 10) #define FORMATI64 "%I64d" #define FORMATI64U "%I64u" #elif (SIZEOF_LONG == 8) #define ATOI64(val) strtol(val, NULL, 10) #define ATOI64U(val) strtoul(val, NULL, 10) #define FORMATI64 "%ld" #define FORMATI64U "%lu" #else #define FORMATI64 "%lld" #define FORMATI64U "%llu" #if defined(HAVE_STRTOLL) #define ATOI64(val) strtoll(val, NULL, 10) #define ATOI64U(val) strtoull(val, NULL, 10) #else static ODBCINT64 ATOI64(const char *val) { ODBCINT64 ll; sscanf(val, "%lld", &ll); return ll; } static unsigned ODBCINT64 ATOI64U(const char *val) { unsigned ODBCINT64 ll; sscanf(val, "%llu", &ll); return ll; } #endif /* HAVE_STRTOLL */ #endif /* WIN32 */ #endif /* ODBCINT64 */ /* * TIMESTAMP <-----> SIMPLE_TIME * precision support since 7.2. * time zone support is unavailable(the stuff is unreliable) */ static BOOL timestamp2stime(const char *str, SIMPLE_TIME *st, BOOL *bZone, int *zone) { char rest[64], bc[16], *ptr; int scnt, i; #ifdef TIMEZONE_GLOBAL long timediff; #endif BOOL withZone = *bZone; *bZone = FALSE; *zone = 0; st->fr = 0; st->infinity = 0; rest[0] = '\0'; bc[0] = '\0'; if ((scnt = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d%31s %15s", &st->y, &st->m, &st->d, &st->hh, &st->mm, &st->ss, rest, bc)) < 6) return FALSE; else if (scnt == 6) return TRUE; switch (rest[0]) { case '+': *bZone = TRUE; *zone = atoi(&rest[1]); break; case '-': *bZone = TRUE; *zone = -atoi(&rest[1]); break; case '.': if ((ptr = strchr(rest, '+')) != NULL) { *bZone = TRUE; *zone = atoi(&ptr[1]); *ptr = '\0'; } else if ((ptr = strchr(rest, '-')) != NULL) { *bZone = TRUE; *zone = -atoi(&ptr[1]); *ptr = '\0'; } for (i = 1; i < 10; i++) { if (!isdigit((UCHAR) rest[i])) break; } for (; i < 10; i++) rest[i] = '0'; rest[i] = '\0'; st->fr = atoi(&rest[1]); break; case 'B': if (stricmp(rest, "BC") == 0) st->y *= -1; return TRUE; default: return TRUE; } if (stricmp(bc, "BC") == 0) { st->y *= -1; } if (!withZone || !*bZone || st->y < 1970) return TRUE; #ifdef TIMEZONE_GLOBAL if (!tzname[0] || !tzname[0][0]) { *bZone = FALSE; return TRUE; } timediff = TIMEZONE_GLOBAL + (*zone) * 3600; if (!daylight && timediff == 0) /* the same timezone */ return TRUE; else { struct tm tm, *tm2; time_t time0; *bZone = FALSE; tm.tm_year = st->y - 1900; tm.tm_mon = st->m - 1; tm.tm_mday = st->d; tm.tm_hour = st->hh; tm.tm_min = st->mm; tm.tm_sec = st->ss; tm.tm_isdst = -1; time0 = mktime(&tm); if (time0 < 0) return TRUE; if (tm.tm_isdst > 0) timediff -= 3600; if (timediff == 0) /* the same time zone */ return TRUE; time0 -= timediff; #ifdef HAVE_LOCALTIME_R if (time0 >= 0 && (tm2 = localtime_r(&time0, &tm)) != NULL) #else if (time0 >= 0 && (tm2 = localtime(&time0)) != NULL) #endif /* HAVE_LOCALTIME_R */ { st->y = tm2->tm_year + 1900; st->m = tm2->tm_mon + 1; st->d = tm2->tm_mday; st->hh = tm2->tm_hour; st->mm = tm2->tm_min; st->ss = tm2->tm_sec; *bZone = TRUE; } } #endif /* TIMEZONE_GLOBAL */ return TRUE; } static BOOL stime2timestamp(const SIMPLE_TIME *st, char *str, BOOL bZone, int precision) { char precstr[16], zonestr[16]; int i; precstr[0] = '\0'; if (st->infinity > 0) { strcpy(str, INFINITY_STRING); return TRUE; } else if (st->infinity < 0) { strcpy(str, MINFINITY_STRING); return TRUE; } if (precision > 0 && st->fr) { sprintf(precstr, ".%09d", st->fr); if (precision < 9) precstr[precision + 1] = '\0'; for (i = precision; i > 0; i--) { if (precstr[i] != '0') break; precstr[i] = '\0'; } if (i == 0) precstr[i] = '\0'; } zonestr[0] = '\0'; #ifdef TIMEZONE_GLOBAL if (bZone && tzname[0] && tzname[0][0] && st->y >= 1970) { long zoneint; struct tm tm; time_t time0; zoneint = TIMEZONE_GLOBAL; if (daylight && st->y >= 1900) { tm.tm_year = st->y - 1900; tm.tm_mon = st->m - 1; tm.tm_mday = st->d; tm.tm_hour = st->hh; tm.tm_min = st->mm; tm.tm_sec = st->ss; tm.tm_isdst = -1; time0 = mktime(&tm); if (time0 >= 0 && tm.tm_isdst > 0) zoneint -= 3600; } if (zoneint > 0) sprintf(zonestr, "-%02d", (int) zoneint / 3600); else sprintf(zonestr, "+%02d", -(int) zoneint / 3600); } #endif /* TIMEZONE_GLOBAL */ if (st->y < 0) sprintf(str, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s BC", -st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr); else sprintf(str, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s", st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr); return TRUE; } #if (ODBCVER >= 0x0300) static SQLINTERVAL interval2itype(SQLSMALLINT ctype) { SQLINTERVAL sqlitv = 0; switch (ctype) { case SQL_C_INTERVAL_YEAR: sqlitv = SQL_IS_YEAR; break; case SQL_C_INTERVAL_MONTH: sqlitv = SQL_IS_MONTH; break; case SQL_C_INTERVAL_YEAR_TO_MONTH: sqlitv = SQL_IS_YEAR_TO_MONTH; break; case SQL_C_INTERVAL_DAY: sqlitv = SQL_IS_DAY; break; case SQL_C_INTERVAL_HOUR: sqlitv = SQL_IS_HOUR; break; case SQL_C_INTERVAL_DAY_TO_HOUR: sqlitv = SQL_IS_DAY_TO_HOUR; break; case SQL_C_INTERVAL_MINUTE: sqlitv = SQL_IS_MINUTE; break; case SQL_C_INTERVAL_DAY_TO_MINUTE: sqlitv = SQL_IS_DAY_TO_MINUTE; break; case SQL_C_INTERVAL_HOUR_TO_MINUTE: sqlitv = SQL_IS_HOUR_TO_MINUTE; break; case SQL_C_INTERVAL_SECOND: sqlitv = SQL_IS_SECOND; break; case SQL_C_INTERVAL_DAY_TO_SECOND: sqlitv = SQL_IS_DAY_TO_SECOND; break; case SQL_C_INTERVAL_HOUR_TO_SECOND: sqlitv = SQL_IS_HOUR_TO_SECOND; break; case SQL_C_INTERVAL_MINUTE_TO_SECOND: sqlitv = SQL_IS_MINUTE_TO_SECOND; break; } return sqlitv; } /* * Interval data <-----> SQL_INTERVAL_STRUCT */ static int getPrecisionPart(int precision, const char * precPart) { char fraction[] = "000000000"; int fracs = sizeof(fraction) - 1; size_t cpys; if (precision < 0) precision = 6; /* default */ if (precision == 0) return 0; cpys = strlen(precPart); if (cpys > fracs) cpys = fracs; memcpy(fraction, precPart, cpys); fraction[precision] = '\0'; return atoi(fraction); } static BOOL interval2istruct(SQLSMALLINT ctype, int precision, const char *str, SQL_INTERVAL_STRUCT *st) { char lit1[64], lit2[64]; int scnt, years, mons, days, hours, minutes, seconds; BOOL sign; SQLINTERVAL itype = interval2itype(ctype); memset(st, 0, sizeof(SQL_INTERVAL_STRUCT)); if ((scnt = sscanf(str, "%d-%d", &years, &mons)) >=2) { if (SQL_IS_YEAR_TO_MONTH == itype) { sign = years < 0 ? SQL_TRUE : SQL_FALSE; st->interval_type = itype; st->interval_sign = sign; st->intval.year_month.year = sign ? (-years) : years; st->intval.year_month.month = mons; return TRUE; } return FALSE; } else if (scnt = sscanf(str, "%d %02d:%02d:%02d.%09s", &days, &hours, &minutes, &seconds, lit2), 5 == scnt || 4 == scnt) { sign = days < 0 ? SQL_TRUE : SQL_FALSE; st->interval_type = itype; st->interval_sign = sign; st->intval.day_second.day = sign ? (-days) : days; st->intval.day_second.hour = hours; st->intval.day_second.minute = minutes; st->intval.day_second.second = seconds; if (scnt > 4) st->intval.day_second.fraction = getPrecisionPart(precision, lit2); return TRUE; } else if ((scnt = sscanf(str, "%d %10s %d %10s", &years, lit1, &mons, lit2)) >=4) { if (strnicmp(lit1, "year", 4) == 0 && strnicmp(lit2, "mon", 2) == 0 && (SQL_IS_MONTH == itype || SQL_IS_YEAR_TO_MONTH == itype)) { sign = years < 0 ? SQL_TRUE : SQL_FALSE; st->interval_type = itype; st->interval_sign = sign; st->intval.year_month.year = sign ? (-years) : years; st->intval.year_month.month = sign ? (-mons) : mons; return TRUE; } return FALSE; } if ((scnt = sscanf(str, "%d %10s %d", &years, lit1, &days)) == 2) { sign = years < 0 ? SQL_TRUE : SQL_FALSE; if (SQL_IS_YEAR == itype && (stricmp(lit1, "year") == 0 || stricmp(lit1, "years") == 0)) { st->interval_type = itype; st->interval_sign = sign; st->intval.year_month.year = sign ? (-years) : years; return TRUE; } if (SQL_IS_MONTH == itype && (stricmp(lit1, "mon") == 0 || stricmp(lit1, "mons") == 0)) { st->interval_type = itype; st->interval_sign = sign; st->intval.year_month.month = sign ? (-years) : years; return TRUE; } if (SQL_IS_DAY == itype && (stricmp(lit1, "day") == 0 || stricmp(lit1, "days") == 0)) { st->interval_type = itype; st->interval_sign = sign; st->intval.day_second.day = sign ? (-years) : years; return TRUE; } return FALSE; } if (itype == SQL_IS_YEAR || itype == SQL_IS_MONTH || itype == SQL_IS_YEAR_TO_MONTH) { /* these formats should've been handled above already */ return FALSE; } scnt = sscanf(str, "%d %10s %02d:%02d:%02d.%09s", &days, lit1, &hours, &minutes, &seconds, lit2); if (strnicmp(lit1, "day", 3) != 0) return FALSE; sign = days < 0 ? SQL_TRUE : SQL_FALSE; switch (scnt) { case 5: case 6: st->interval_type = itype; st->interval_sign = sign; st->intval.day_second.day = sign ? (-days) : days; st->intval.day_second.hour = sign ? (-hours) : hours; st->intval.day_second.minute = minutes; st->intval.day_second.second = seconds; if (scnt > 5) st->intval.day_second.fraction = getPrecisionPart(precision, lit2); return TRUE; } scnt = sscanf(str, "%02d:%02d:%02d.%09s", &hours, &minutes, &seconds, lit2); sign = hours < 0 ? SQL_TRUE : SQL_FALSE; switch (scnt) { case 3: case 4: st->interval_type = itype; st->interval_sign = sign; st->intval.day_second.hour = sign ? (-hours) : hours; st->intval.day_second.minute = minutes; st->intval.day_second.second = seconds; if (scnt > 3) st->intval.day_second.fraction = getPrecisionPart(precision, lit2); return TRUE; } return FALSE; } #endif /* ODBCVER */ #ifdef HAVE_LOCALE_H static char *current_locale = NULL; static char *current_decimal_point = NULL; static void current_numeric_locale(void) { char *loc = setlocale(LC_NUMERIC, NULL); if (NULL == current_locale || 0 != stricmp(loc, current_locale)) { struct lconv *lc = localeconv(); if (NULL != current_locale) free(current_locale); current_locale = strdup(loc); if (NULL != current_decimal_point) free(current_decimal_point); current_decimal_point = strdup(lc->decimal_point); } } static void set_server_decimal_point(char *num) { char *str; current_numeric_locale(); if ('.' == *current_decimal_point) return; for (str = num; '\0' != *str; str++) { if (*str == *current_decimal_point) { *str = '.'; break; } } } static void set_client_decimal_point(char *num) { char *str; current_numeric_locale(); if ('.' == *current_decimal_point) return; for (str = num; '\0' != *str; str++) { if (*str == '.') { *str = *current_decimal_point; break; } } } #else static void set_server_decimal_point(char *num) {} static void set_client_decimal_point(char *num, BOOL) {} #endif /* HAVE_LOCALE_H */ /* This is called by SQLFetch() */ int copy_and_convert_field_bindinfo(StatementClass *stmt, OID field_type, int atttypmod, void *value, int col) { ARDFields *opts = SC_get_ARDF(stmt); BindInfoClass *bic; SQLULEN offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0; if (opts->allocated <= col) extend_column_bindings(opts, col + 1); bic = &(opts->bindings[col]); SC_set_current_col(stmt, -1); return copy_and_convert_field(stmt, field_type, atttypmod, value, bic->returntype, bic->precision, (PTR) (bic->buffer + offset), bic->buflen, LENADDR_SHIFT(bic->used, offset), LENADDR_SHIFT(bic->indicator, offset)); } static double get_double_value(const char *str) { if (stricmp(str, NAN_STRING) == 0) #ifdef NAN return (double) NAN; #else { double a = .0; return .0 / a; } #endif /* NAN */ else if (stricmp(str, INFINITY_STRING) == 0) #ifdef INFINITY return (double) INFINITY; #else return (double) (HUGE_VAL * HUGE_VAL); #endif /* INFINITY */ else if (stricmp(str, MINFINITY_STRING) == 0) #ifdef INFINITY return (double) -INFINITY; #else return (double) -(HUGE_VAL * HUGE_VAL); #endif /* INFINITY */ return atof(str); } #if (ODBCVER >= 0x0350) static int char2guid(const char *str, SQLGUID *g) { /* * SQLGUID.Data1 is an "unsigned long" on some platforms, and * "unsigned int" on others. For format "%08X", it should be an * "unsigned int", so use a temporary variable for it. */ unsigned int Data1; if (sscanf(str, "%08X-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX", &Data1, &g->Data2, &g->Data3, &g->Data4[0], &g->Data4[1], &g->Data4[2], &g->Data4[3], &g->Data4[4], &g->Data4[5], &g->Data4[6], &g->Data4[7]) < 11) return COPY_GENERAL_ERROR; g->Data1 = Data1; return COPY_OK; } #endif /* ODBCVER */ /* This is called by SQLGetData() */ int copy_and_convert_field(StatementClass *stmt, OID field_type, int atttypmod, void *valuei, SQLSMALLINT fCType, int precision, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue, SQLLEN *pIndicator) { CSTR func = "copy_and_convert_field"; const char *value = valuei; ARDFields *opts = SC_get_ARDF(stmt); GetDataInfo *gdata = SC_get_GDTI(stmt); SQLLEN len = 0, copy_len = 0, needbuflen = 0; SIMPLE_TIME std_time; time_t stmt_t = SC_get_time(stmt); struct tm *tim; #ifdef HAVE_LOCALTIME_R struct tm tm; #endif /* HAVE_LOCALTIME_R */ SQLLEN pcbValueOffset, rgbValueOffset; char *rgbValueBindRow = NULL; SQLLEN *pcbValueBindRow = NULL, *pIndicatorBindRow = NULL; const char *ptr; SQLSETPOSIROW bind_row = stmt->bind_row; int bind_size = opts->bind_size; int result = COPY_OK; const ConnectionClass *conn = SC_get_conn(stmt); BOOL changed; BOOL text_handling, localize_needed; const char *neut_str = value; char midtemp[2][32]; int mtemp_cnt = 0; GetDataClass *pgdc; #ifdef UNICODE_SUPPORT BOOL wconverted = FALSE; #endif /* UNICODE_SUPPORT */ #ifdef WIN_UNICODE_SUPPORT SQLWCHAR *allocbuf = NULL; ssize_t wstrlen; #endif /* WIN_UNICODE_SUPPORT */ #if (ODBCVER >= 0x0350) SQLGUID g; #endif if (stmt->current_col >= 0) { if (stmt->current_col >= opts->allocated) { return SQL_ERROR; } if (gdata->allocated != opts->allocated) extend_getdata_info(gdata, opts->allocated, TRUE); pgdc = &gdata->gdata[stmt->current_col]; if (pgdc->data_left == -2) pgdc->data_left = (cbValueMax > 0) ? 0 : -1; /* This seems to be * * needed by ADO ? */ if (pgdc->data_left == 0) { if (pgdc->ttlbuf != NULL) { free(pgdc->ttlbuf); pgdc->ttlbuf = NULL; pgdc->ttlbuflen = 0; } pgdc->data_left = -2; /* needed by ADO ? */ return COPY_NO_DATA_FOUND; } } /*--------- * rgbValueOffset is *ONLY* for character and binary data. * pcbValueOffset is for computing any pcbValue location *--------- */ if (bind_size > 0) pcbValueOffset = rgbValueOffset = (bind_size * bind_row); else { pcbValueOffset = bind_row * sizeof(SQLLEN); rgbValueOffset = bind_row * cbValueMax; } /* * The following is applicable in case bind_size > 0 * or the fCType is of variable length. */ if (rgbValue) rgbValueBindRow = (char *) rgbValue + rgbValueOffset; if (pcbValue) pcbValueBindRow = LENADDR_SHIFT(pcbValue, pcbValueOffset); if (pIndicator) { pIndicatorBindRow = LENADDR_SHIFT(pIndicator, pcbValueOffset); *pIndicatorBindRow = 0; } memset(&std_time, 0, sizeof(SIMPLE_TIME)); /* Initialize current date */ #ifdef HAVE_LOCALTIME_R tim = localtime_r(&stmt_t, &tm); #else tim = localtime(&stmt_t); #endif /* HAVE_LOCALTIME_R */ std_time.m = tim->tm_mon + 1; std_time.d = tim->tm_mday; std_time.y = tim->tm_year + 1900; mylog("copy_and_convert: field_type = %d, fctype = %d, value = '%s', cbValueMax=%d\n", field_type, fCType, (value == NULL) ? "" : value, cbValueMax); if (!value) { mylog("null_cvt_date_string=%d\n", conn->connInfo.cvt_null_date_string); /* a speicial handling for FOXPRO NULL -> NULL_STRING */ if (conn->connInfo.cvt_null_date_string > 0 && (PG_TYPE_DATE == field_type || PG_TYPE_DATETIME == field_type || PG_TYPE_TIMESTAMP_NO_TMZONE == field_type) && (SQL_C_CHAR == fCType || #ifdef UNICODE_SUPPORT SQL_C_WCHAR == fCType || #endif /* UNICODE_SUPPORT */ SQL_C_DATE == fCType || #if (ODBCVER >= 0x0300) SQL_C_TYPE_DATE == fCType || #endif /* ODBCVER */ SQL_C_DEFAULT == fCType)) { if (pcbValueBindRow) *pcbValueBindRow = 0; switch (fCType) { case SQL_C_CHAR: if (rgbValueBindRow && cbValueMax > 0) rgbValueBindRow = '\0'; else result = COPY_RESULT_TRUNCATED; break; case SQL_C_DATE: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_DATE: #endif /* ODBCVER */ case SQL_C_DEFAULT: if (rgbValueBindRow && cbValueMax >= sizeof(DATE_STRUCT)) { memset(rgbValueBindRow, 0, cbValueMax); if (pcbValueBindRow) *pcbValueBindRow = sizeof(DATE_STRUCT); } else result = COPY_RESULT_TRUNCATED; break; #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: if (rgbValueBindRow && cbValueMax >= WCLEN) memset(rgbValueBindRow, 0, WCLEN); else result = COPY_RESULT_TRUNCATED; break; #endif /* UNICODE_SUPPORT */ } return result; } /* * handle a null just by returning SQL_NULL_DATA in pcbValue, and * doing nothing to the buffer. */ else if (pIndicator) { *pIndicatorBindRow = SQL_NULL_DATA; return COPY_OK; } else { SC_set_error(stmt, STMT_RETURN_NULL_WITHOUT_INDICATOR, "StrLen_or_IndPtr was a null pointer and NULL data was retrieved", func); return SQL_ERROR; } } if (stmt->hdbc->DataSourceToDriver != NULL) { size_t length = strlen(value); stmt->hdbc->DataSourceToDriver(stmt->hdbc->translation_option, SQL_CHAR, valuei, (SDWORD) length, valuei, (SDWORD) length, NULL, NULL, 0, NULL); } /* * First convert any specific postgres types into more useable data. * * NOTE: Conversions from PG char/varchar of a date/time/timestamp value * to SQL_C_DATE,SQL_C_TIME, SQL_C_TIMESTAMP not supported */ switch (field_type) { /* * $$$ need to add parsing for date/time/timestamp strings in * PG_TYPE_CHAR,VARCHAR $$$ */ case PG_TYPE_DATE: sscanf(value, "%4d-%2d-%2d", &std_time.y, &std_time.m, &std_time.d); break; case PG_TYPE_TIME: sscanf(value, "%2d:%2d:%2d", &std_time.hh, &std_time.mm, &std_time.ss); break; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: std_time.fr = 0; std_time.infinity = 0; if (strnicmp(value, INFINITY_STRING, 8) == 0) { std_time.infinity = 1; std_time.m = 12; std_time.d = 31; std_time.y = 9999; std_time.hh = 23; std_time.mm = 59; std_time.ss = 59; } if (strnicmp(value, MINFINITY_STRING, 9) == 0) { std_time.infinity = -1; std_time.m = 1; std_time.d = 1; // std_time.y = -4713; std_time.y = -9999; std_time.hh = 0; std_time.mm = 0; std_time.ss = 0; } if (strnicmp(value, "invalid", 7) != 0) { BOOL bZone = (field_type != PG_TYPE_TIMESTAMP_NO_TMZONE && PG_VERSION_GE(conn, 7.2)); int zone; /* * sscanf(value, "%4d-%2d-%2d %2d:%2d:%2d", &std_time.y, &std_time.m, * &std_time.d, &std_time.hh, &std_time.mm, &std_time.ss); */ bZone = FALSE; /* time zone stuff is unreliable */ timestamp2stime(value, &std_time, &bZone, &zone); inolog("2stime fr=%d\n", std_time.fr); } else { /* * The timestamp is invalid so set something conspicuous, * like the epoch */ time_t t = 0; #ifdef HAVE_LOCALTIME_R tim = localtime_r(&t, &tm); #else tim = localtime(&t); #endif /* HAVE_LOCALTIME_R */ std_time.m = tim->tm_mon + 1; std_time.d = tim->tm_mday; std_time.y = tim->tm_year + 1900; std_time.hh = tim->tm_hour; std_time.mm = tim->tm_min; std_time.ss = tim->tm_sec; } break; case PG_TYPE_BOOL: { /* change T/F to 1/0 */ char *s; const ConnInfo *ci = &(conn->connInfo); s = midtemp[mtemp_cnt]; switch (((char *)value)[0]) { case 'f': case 'F': case 'n': case 'N': case '0': strcpy(s, "0"); break; default: if (ci->true_is_minus1) strcpy(s, "-1"); else strcpy(s, "1"); } neut_str = midtemp[mtemp_cnt]; mtemp_cnt++; } break; /* This is for internal use by SQLStatistics() */ case PG_TYPE_INT2VECTOR: if (SQL_C_DEFAULT == fCType) { int i, nval, maxc; const char *vp; /* this is an array of eight integers */ short *short_array = (short *) rgbValueBindRow, shortv; maxc = 0; if (NULL != short_array) maxc = (int) cbValueMax / sizeof(short); vp = value; nval = 0; mylog("index=("); for (i = 0;; i++) { if (sscanf(vp, "%hi", &shortv) != 1) break; mylog(" %hi", shortv); if (0 == shortv && PG_VERSION_LT(conn, 7.2)) break; nval++; if (nval < maxc) short_array[i + 1] = shortv; /* skip the current token */ while ((*vp != '\0') && (!isspace((UCHAR) *vp))) vp++; /* and skip the space to the next token */ while ((*vp != '\0') && (isspace((UCHAR) *vp))) vp++; if (*vp == '\0') break; } mylog(") nval = %i\n", nval); if (maxc > 0) short_array[0] = nval; /* There is no corresponding fCType for this. */ len = (nval + 1) * sizeof(short); if (pcbValue) *pcbValueBindRow = len; if (len <= cbValueMax) return COPY_OK; /* dont go any further or the data will be * trashed */ else return COPY_RESULT_TRUNCATED; } break; /* * This is a large object OID, which is used to store * LONGVARBINARY objects. */ case PG_TYPE_LO_UNDEFINED: return convert_lo(stmt, value, fCType, rgbValueBindRow, cbValueMax, pcbValueBindRow); case 0: break; default: if (field_type == stmt->hdbc->lobj_type /* hack until permanent type available */ || (PG_TYPE_OID == field_type && SQL_C_BINARY == fCType && conn->lo_is_domain) ) return convert_lo(stmt, value, fCType, rgbValueBindRow, cbValueMax, pcbValueBindRow); } /* Change default into something useable */ if (fCType == SQL_C_DEFAULT) { fCType = pgtype_attr_to_ctype(conn, field_type, atttypmod); if (fCType == SQL_C_WCHAR && CC_default_is_c(conn)) fCType = SQL_C_CHAR; mylog("copy_and_convert, SQL_C_DEFAULT: fCType = %d\n", fCType); } text_handling = localize_needed = FALSE; switch (fCType) { case INTERNAL_ASIS_TYPE: #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: #endif /* UNICODE_SUPPORT */ case SQL_C_CHAR: text_handling = TRUE; break; case SQL_C_BINARY: switch (field_type) { case PG_TYPE_UNKNOWN: case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: case PG_TYPE_TEXT: case PG_TYPE_XML: case PG_TYPE_BPCHARARRAY: case PG_TYPE_VARCHARARRAY: case PG_TYPE_TEXTARRAY: case PG_TYPE_XMLARRAY: text_handling = TRUE; break; } break; } if (text_handling) { #ifdef WIN_UNICODE_SUPPORT if (SQL_C_CHAR == fCType || SQL_C_BINARY == fCType) localize_needed = TRUE; #endif /* WIN_UNICODE_SUPPORT */ } if (text_handling) { /* Special character formatting as required */ BOOL hex_bin_format = FALSE; /* * These really should return error if cbValueMax is not big * enough. */ switch (field_type) { case PG_TYPE_DATE: len = 10; if (cbValueMax > len) sprintf(rgbValueBindRow, "%.4d-%.2d-%.2d", std_time.y, std_time.m, std_time.d); break; case PG_TYPE_TIME: len = 8; if (cbValueMax > len) sprintf(rgbValueBindRow, "%.2d:%.2d:%.2d", std_time.hh, std_time.mm, std_time.ss); break; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: len = 19; if (cbValueMax > len) { /* sprintf(rgbValueBindRow, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d", std_time.y, std_time.m, std_time.d, std_time.hh, std_time.mm, std_time.ss); */ stime2timestamp(&std_time, rgbValueBindRow, FALSE, PG_VERSION_GE(conn, 7.2) ? (int) cbValueMax - len - 2 : 0); len = strlen(rgbValueBindRow); } break; case PG_TYPE_BOOL: len = strlen(neut_str); if (cbValueMax > len) { strcpy(rgbValueBindRow, neut_str); mylog("PG_TYPE_BOOL: rgbValueBindRow = '%s'\n", rgbValueBindRow); } break; case PG_TYPE_UUID: len = strlen(neut_str); if (cbValueMax > len) { int i; for (i = 0; i < len; i++) rgbValueBindRow[i] = toupper((UCHAR) neut_str[i]); rgbValueBindRow[i] = '\0'; mylog("PG_TYPE_UUID: rgbValueBindRow = '%s'\n", rgbValueBindRow); } break; /* * Currently, data is SILENTLY TRUNCATED for BYTEA and * character data types if there is not enough room in * cbValueMax because the driver can't handle multiple * calls to SQLGetData for these, yet. Most likely, the * buffer passed in will be big enough to handle the * maximum limit of postgres, anyway. * * LongVarBinary types are handled correctly above, observing * truncation and all that stuff since there is * essentially no limit on the large object used to store * those. */ case PG_TYPE_BYTEA:/* convert binary data to hex strings * (i.e, 255 = "FF") */ default: switch (field_type) { case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_NUMERIC: set_client_decimal_point((char *) neut_str); break; case PG_TYPE_BYTEA: if (0 == strnicmp(neut_str, "\\x", 2)) { hex_bin_format = TRUE; neut_str += 2; } break; } if (stmt->current_col < 0) { pgdc = &(gdata->fdata); pgdc->data_left = -1; } else pgdc = &gdata->gdata[stmt->current_col]; #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) wconverted = TRUE; #endif /* UNICODE_SUPPORT */ if (pgdc->data_left < 0) { BOOL lf_conv = conn->connInfo.lf_conversion; if (PG_TYPE_BYTEA == field_type) { if (hex_bin_format) len = strlen(neut_str); else { len = convert_from_pgbinary(neut_str, NULL, 0); len *= 2; } changed = TRUE; #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) len *= WCLEN; #endif /* UNICODE_SUPPORT */ } else #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) { len = utf8_to_ucs2_lf(neut_str, SQL_NTS, lf_conv, NULL, 0, FALSE); len *= WCLEN; changed = TRUE; } else #endif /* UNICODE_SUPPORT */ #ifdef WIN_UNICODE_SUPPORT if (localize_needed) { wstrlen = utf8_to_ucs2_lf(neut_str, SQL_NTS, lf_conv, NULL, 0, FALSE); allocbuf = (SQLWCHAR *) malloc(WCLEN * (wstrlen + 1)); wstrlen = utf8_to_ucs2_lf(neut_str, SQL_NTS, lf_conv, allocbuf, wstrlen + 1, FALSE); len = wstrtomsg(NULL, (const LPWSTR) allocbuf, (int) wstrlen, NULL, 0); changed = TRUE; } else #endif /* WIN_UNICODE_SUPPORT */ /* convert linefeeds to carriage-return/linefeed */ len = convert_linefeeds(neut_str, NULL, 0, lf_conv, &changed); if (cbValueMax == 0) /* just returns length * info */ { result = COPY_RESULT_TRUNCATED; #ifdef WIN_UNICODE_SUPPORT if (allocbuf) free(allocbuf); #endif /* WIN_UNICODE_SUPPORT */ break; } if (!pgdc->ttlbuf) pgdc->ttlbuflen = 0; needbuflen = len; switch (fCType) { #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: needbuflen += WCLEN; break; #endif /* UNICODE_SUPPORT */ case SQL_C_BINARY: break; default: needbuflen++; } if (changed || needbuflen > cbValueMax) { if (needbuflen > (SQLLEN) pgdc->ttlbuflen) { pgdc->ttlbuf = realloc(pgdc->ttlbuf, needbuflen); pgdc->ttlbuflen = needbuflen; } #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) { if (PG_TYPE_BYTEA == field_type && !hex_bin_format) { len = convert_from_pgbinary(neut_str, pgdc->ttlbuf, pgdc->ttlbuflen); len = pg_bin2whex(pgdc->ttlbuf, (SQLWCHAR *) pgdc->ttlbuf, len); } else utf8_to_ucs2_lf(neut_str, SQL_NTS, lf_conv, (SQLWCHAR *) pgdc->ttlbuf, len / WCLEN, FALSE); } else #endif /* UNICODE_SUPPORT */ if (PG_TYPE_BYTEA == field_type) { if (hex_bin_format) { len = strlen(neut_str); strncpy_null(pgdc->ttlbuf, neut_str, pgdc->ttlbuflen); } else { len = convert_from_pgbinary(neut_str, pgdc->ttlbuf, pgdc->ttlbuflen); len = pg_bin2hex(pgdc->ttlbuf, pgdc->ttlbuf, len); } } else #ifdef WIN_UNICODE_SUPPORT if (localize_needed) { len = wstrtomsg(NULL, allocbuf, (int) wstrlen, pgdc->ttlbuf, (int) pgdc->ttlbuflen); free(allocbuf); allocbuf = NULL; } else #endif /* WIN_UNICODE_SUPPORT */ convert_linefeeds(neut_str, pgdc->ttlbuf, pgdc->ttlbuflen, lf_conv, &changed); ptr = pgdc->ttlbuf; pgdc->ttlbufused = len; } else { if (pgdc->ttlbuf) { free(pgdc->ttlbuf); pgdc->ttlbuf = NULL; } ptr = neut_str; } } else { ptr = pgdc->ttlbuf; len = pgdc->ttlbufused; } mylog("DEFAULT: len = %d, ptr = '%.*s'\n", len, len, ptr); if (stmt->current_col >= 0) { if (pgdc->data_left > 0) { ptr += len - pgdc->data_left; len = pgdc->data_left; needbuflen = len + (pgdc->ttlbuflen - pgdc->ttlbufused); } else pgdc->data_left = len; } if (cbValueMax > 0) { BOOL already_copied = FALSE; if (fCType == SQL_C_BINARY) copy_len = (len > cbValueMax) ? cbValueMax : len; else copy_len = (len >= cbValueMax) ? (cbValueMax - 1) : len; #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) { copy_len /= WCLEN; copy_len *= WCLEN; } #endif /* UNICODE_SUPPORT */ if (!already_copied) { /* Copy the data */ memcpy(rgbValueBindRow, ptr, copy_len); /* Add null terminator */ #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) { if (copy_len + WCLEN <= cbValueMax) memset(rgbValueBindRow + copy_len, 0, WCLEN); } else #endif /* UNICODE_SUPPORT */ if (copy_len < cbValueMax) rgbValueBindRow[copy_len] = '\0'; } /* Adjust data_left for next time */ if (stmt->current_col >= 0) pgdc->data_left -= copy_len; } /* * Finally, check for truncation so that proper status can * be returned */ if (cbValueMax > 0 && needbuflen > cbValueMax) result = COPY_RESULT_TRUNCATED; else { if (pgdc->ttlbuf != NULL) { free(pgdc->ttlbuf); pgdc->ttlbuf = NULL; } } if (SQL_C_WCHAR == fCType) mylog(" SQL_C_WCHAR, default: len = %d, cbValueMax = %d, rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow); else if (SQL_C_BINARY == fCType) mylog(" SQL_C_BINARY, default: len = %d, cbValueMax = %d, rgbValueBindRow = '%.*s'\n", len, cbValueMax, copy_len, rgbValueBindRow); else mylog(" SQL_C_CHAR, default: len = %d, cbValueMax = %d, rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow); break; } #ifdef UNICODE_SUPPORT if (SQL_C_WCHAR == fCType && ! wconverted) { char *str = strdup(rgbValueBindRow); SQLLEN ucount = utf8_to_ucs2(str, len, (SQLWCHAR *) rgbValueBindRow, cbValueMax / WCLEN); if (cbValueMax < WCLEN * ucount) result = COPY_RESULT_TRUNCATED; len = ucount * WCLEN; free(str); } #endif /* UNICODE_SUPPORT */ } else { /* * for SQL_C_CHAR, it's probably ok to leave currency symbols in. * But to convert to numeric types, it is necessary to get rid of * those. */ if (field_type == PG_TYPE_MONEY) { if (convert_money(neut_str, midtemp[mtemp_cnt], sizeof(midtemp[0]))) { neut_str = midtemp[mtemp_cnt]; mtemp_cnt++; } else { qlog("couldn't convert money type to %d\n", fCType); return COPY_UNSUPPORTED_TYPE; } } switch (fCType) { case SQL_C_DATE: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_DATE: /* 91 */ #endif len = 6; { DATE_STRUCT *ds; if (bind_size > 0) ds = (DATE_STRUCT *) rgbValueBindRow; else ds = (DATE_STRUCT *) rgbValue + bind_row; ds->year = std_time.y; ds->month = std_time.m; ds->day = std_time.d; } break; case SQL_C_TIME: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_TIME: /* 92 */ #endif len = 6; { TIME_STRUCT *ts; if (bind_size > 0) ts = (TIME_STRUCT *) rgbValueBindRow; else ts = (TIME_STRUCT *) rgbValue + bind_row; ts->hour = std_time.hh; ts->minute = std_time.mm; ts->second = std_time.ss; } break; case SQL_C_TIMESTAMP: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_TIMESTAMP: /* 93 */ #endif len = 16; { TIMESTAMP_STRUCT *ts; if (bind_size > 0) ts = (TIMESTAMP_STRUCT *) rgbValueBindRow; else ts = (TIMESTAMP_STRUCT *) rgbValue + bind_row; ts->year = std_time.y; ts->month = std_time.m; ts->day = std_time.d; ts->hour = std_time.hh; ts->minute = std_time.mm; ts->second = std_time.ss; ts->fraction = std_time.fr; } break; case SQL_C_BIT: len = 1; if (bind_size > 0) *((UCHAR *) rgbValueBindRow) = atoi(neut_str); else *((UCHAR *) rgbValue + bind_row) = atoi(neut_str); /* * mylog("SQL_C_BIT: bind_row = %d val = %d, cb = %d, * rgb=%d\n", bind_row, atoi(neut_str), cbValueMax, * *((UCHAR *)rgbValue)); */ break; case SQL_C_STINYINT: case SQL_C_TINYINT: len = 1; if (bind_size > 0) *((SCHAR *) rgbValueBindRow) = atoi(neut_str); else *((SCHAR *) rgbValue + bind_row) = atoi(neut_str); break; case SQL_C_UTINYINT: len = 1; if (bind_size > 0) *((UCHAR *) rgbValueBindRow) = atoi(neut_str); else *((UCHAR *) rgbValue + bind_row) = atoi(neut_str); break; case SQL_C_FLOAT: set_client_decimal_point((char *) neut_str); len = 4; if (bind_size > 0) *((SFLOAT *) rgbValueBindRow) = (float) get_double_value(neut_str); else *((SFLOAT *) rgbValue + bind_row) = (float) get_double_value(neut_str); break; case SQL_C_DOUBLE: set_client_decimal_point((char *) neut_str); len = 8; if (bind_size > 0) *((SDOUBLE *) rgbValueBindRow) = get_double_value(neut_str); else *((SDOUBLE *) rgbValue + bind_row) = get_double_value(neut_str); break; #if (ODBCVER >= 0x0300) case SQL_C_NUMERIC: { SQL_NUMERIC_STRUCT *ns; int i, nlen, bit, hval, tv, dig, sta, olen; char calv[SQL_MAX_NUMERIC_LEN * 3]; const char *wv; BOOL dot_exist; len = sizeof(SQL_NUMERIC_STRUCT); if (bind_size > 0) ns = (SQL_NUMERIC_STRUCT *) rgbValueBindRow; else ns = (SQL_NUMERIC_STRUCT *) rgbValue + bind_row; for (wv = neut_str; *wv && isspace((unsigned char) *wv); wv++) ; ns->sign = 1; if (*wv == '-') { ns->sign = 0; wv++; } else if (*wv == '+') wv++; while (*wv == '0') wv++; ns->precision = 0; ns->scale = 0; for (nlen = 0, dot_exist = FALSE;; wv++) { if (*wv == '.') { if (dot_exist) break; dot_exist = TRUE; } else if (!isdigit((unsigned char) *wv)) break; else { if (dot_exist) ns->scale++; ns->precision++; calv[nlen++] = *wv; } } memset(ns->val, 0, sizeof(ns->val)); for (hval = 0, bit = 1L, sta = 0, olen = 0; sta < nlen;) { for (dig = 0, i = sta; i < nlen; i++) { tv = dig * 10 + calv[i] - '0'; dig = tv % 2; calv[i] = tv / 2 + '0'; if (i == sta && tv < 2) sta++; } if (dig > 0) hval |= bit; bit <<= 1; if (bit >= (1L << 8)) { ns->val[olen++] = hval; hval = 0; bit = 1L; if (olen >= SQL_MAX_NUMERIC_LEN - 1) { ns->scale = sta - ns->precision; break; } } } if (hval && olen < SQL_MAX_NUMERIC_LEN - 1) ns->val[olen++] = hval; } break; #endif /* ODBCVER */ case SQL_C_SSHORT: case SQL_C_SHORT: len = 2; if (bind_size > 0) *((SQLSMALLINT *) rgbValueBindRow) = atoi(neut_str); else *((SQLSMALLINT *) rgbValue + bind_row) = atoi(neut_str); break; case SQL_C_USHORT: len = 2; if (bind_size > 0) *((SQLUSMALLINT *) rgbValueBindRow) = atoi(neut_str); else *((SQLUSMALLINT *) rgbValue + bind_row) = atoi(neut_str); break; case SQL_C_SLONG: case SQL_C_LONG: len = 4; if (bind_size > 0) *((SQLINTEGER *) rgbValueBindRow) = atol(neut_str); else *((SQLINTEGER *) rgbValue + bind_row) = atol(neut_str); break; case SQL_C_ULONG: len = 4; if (bind_size > 0) *((SQLUINTEGER *) rgbValueBindRow) = ATOI32U(neut_str); else *((SQLUINTEGER *) rgbValue + bind_row) = ATOI32U(neut_str); break; #if (ODBCVER >= 0x0300) && defined(ODBCINT64) case SQL_C_SBIGINT: len = 8; if (bind_size > 0) *((SQLBIGINT *) rgbValueBindRow) = ATOI64(neut_str); else *((SQLBIGINT *) rgbValue + bind_row) = ATOI64(neut_str); break; case SQL_C_UBIGINT: len = 8; if (bind_size > 0) *((SQLUBIGINT *) rgbValueBindRow) = ATOI64U(neut_str); else *((SQLUBIGINT *) rgbValue + bind_row) = ATOI64U(neut_str); break; #endif /* ODBCINT64 */ case SQL_C_BINARY: if (PG_TYPE_UNKNOWN == field_type || PG_TYPE_TEXT == field_type || PG_TYPE_VARCHAR == field_type || PG_TYPE_BPCHAR == field_type || PG_TYPE_TEXTARRAY == field_type || PG_TYPE_VARCHARARRAY == field_type || PG_TYPE_BPCHARARRAY == field_type) { ssize_t len = SQL_NULL_DATA; if (neut_str) len = strlen(neut_str); if (pcbValue) *pcbValueBindRow = len; if (len > 0 && cbValueMax > 0) { memcpy(rgbValueBindRow, neut_str, len < cbValueMax ? len : cbValueMax); if (cbValueMax >= len + 1) rgbValueBindRow[len] = '\0'; } if (cbValueMax >= len) return COPY_OK; else return COPY_RESULT_TRUNCATED; } /* The following is for SQL_C_VARBOOKMARK */ else if (PG_TYPE_INT4 == field_type) { UInt4 ival = ATOI32U(neut_str); inolog("SQL_C_VARBOOKMARK value=%d\n", ival); if (pcbValue) *pcbValueBindRow = sizeof(ival); if (cbValueMax >= sizeof(ival)) { memcpy(rgbValueBindRow, &ival, sizeof(ival)); return COPY_OK; } else return COPY_RESULT_TRUNCATED; } #if (ODBCVER >= 0x0350) else if (PG_TYPE_UUID == field_type) { int rtn = char2guid(neut_str, &g); if (COPY_OK != rtn) return rtn; if (pcbValue) *pcbValueBindRow = sizeof(g); if (cbValueMax >= sizeof(g)) { memcpy(rgbValueBindRow, &g, sizeof(g)); return COPY_OK; } else return COPY_RESULT_TRUNCATED; } #endif /* ODBCVER */ else if (PG_TYPE_BYTEA != field_type) { mylog("couldn't convert the type %d to SQL_C_BINARY\n", field_type); qlog("couldn't convert the type %d to SQL_C_BINARY\n", field_type); return COPY_UNSUPPORTED_TYPE; } /* truncate if necessary */ /* convert octal escapes to bytes */ if (stmt->current_col < 0) { pgdc = &(gdata->fdata); pgdc->data_left = -1; } else pgdc = &gdata->gdata[stmt->current_col]; if (!pgdc->ttlbuf) pgdc->ttlbuflen = 0; if (pgdc->data_left < 0) { if (cbValueMax <= 0) { len = convert_from_pgbinary(neut_str, NULL, 0); result = COPY_RESULT_TRUNCATED; break; } if (len = strlen(neut_str), len >= (int) pgdc->ttlbuflen) { pgdc->ttlbuf = realloc(pgdc->ttlbuf, len + 1); pgdc->ttlbuflen = len + 1; } len = convert_from_pgbinary(neut_str, pgdc->ttlbuf, pgdc->ttlbuflen); pgdc->ttlbufused = len; } else len = pgdc->ttlbufused; ptr = pgdc->ttlbuf; if (stmt->current_col >= 0) { /* * Second (or more) call to SQLGetData so move the * pointer */ if (pgdc->data_left > 0) { ptr += len - pgdc->data_left; len = pgdc->data_left; } /* First call to SQLGetData so initialize data_left */ else pgdc->data_left = len; } if (cbValueMax > 0) { copy_len = (len > cbValueMax) ? cbValueMax : len; /* Copy the data */ memcpy(rgbValueBindRow, ptr, copy_len); /* Adjust data_left for next time */ if (stmt->current_col >= 0) pgdc->data_left -= copy_len; } /* * Finally, check for truncation so that proper status can * be returned */ if (len > cbValueMax) result = COPY_RESULT_TRUNCATED; else if (pgdc->ttlbuf) { free(pgdc->ttlbuf); pgdc->ttlbuf = NULL; } mylog("SQL_C_BINARY: len = %d, copy_len = %d\n", len, copy_len); break; #if (ODBCVER >= 0x0350) case SQL_C_GUID: result = char2guid(neut_str, &g); if (COPY_OK != result) { mylog("Could not convert to SQL_C_GUID"); return COPY_UNSUPPORTED_TYPE; } len = sizeof(g); if (bind_size > 0) *((SQLGUID *) rgbValueBindRow) = g; else *((SQLGUID *) rgbValue + bind_row) = g; break; #endif /* ODBCVER */ #if (ODBCVER >= 0x0300) case SQL_C_INTERVAL_YEAR: case SQL_C_INTERVAL_MONTH: case SQL_C_INTERVAL_YEAR_TO_MONTH: case SQL_C_INTERVAL_DAY: case SQL_C_INTERVAL_HOUR: case SQL_C_INTERVAL_DAY_TO_HOUR: case SQL_C_INTERVAL_MINUTE: case SQL_C_INTERVAL_HOUR_TO_MINUTE: case SQL_C_INTERVAL_SECOND: case SQL_C_INTERVAL_DAY_TO_SECOND: case SQL_C_INTERVAL_HOUR_TO_SECOND: case SQL_C_INTERVAL_MINUTE_TO_SECOND: interval2istruct(fCType, precision, neut_str, bind_size > 0 ? (SQL_INTERVAL_STRUCT *) rgbValueBindRow : (SQL_INTERVAL_STRUCT *) rgbValue + bind_row); break; #endif /* ODBCVER */ default: qlog("conversion to the type %d isn't supported\n", fCType); return COPY_UNSUPPORTED_TYPE; } } /* store the length of what was copied, if there's a place for it */ if (pcbValue) *pcbValueBindRow = len; if (result == COPY_OK && stmt->current_col >= 0) gdata->gdata[stmt->current_col].data_left = 0; return result; } /*-------------------------------------------------------------------- * Functions/Macros to get rid of query size limit. * * I always used the follwoing macros to convert from * old_statement to new_statement. Please improve it * if you have a better way. Hiroshi 2001/05/22 *-------------------------------------------------------------------- */ #define FLGP_PREPARE_DUMMY_CURSOR 1L #define FLGP_USING_CURSOR (1L << 1) #define FLGP_SELECT_INTO (1L << 2) #define FLGP_SELECT_FOR_UPDATE_OR_SHARE (1L << 3) #define FLGP_BUILDING_PREPARE_STATEMENT (1L << 4) #define FLGP_MULTIPLE_STATEMENT (1L << 5) #define FLGP_SELECT_FOR_READONLY (1L << 6) typedef struct _QueryParse { const char *statement; int statement_type; size_t opos; Int4 from_pos; /* PG comm length restriction */ Int4 where_pos; /* PG comm length restriction */ ssize_t stmt_len; char in_literal, in_identifier, in_escape, in_dollar_quote; const char *dollar_tag; ssize_t taglen; char token_save[64]; int token_len; char prev_token_end, in_line_comment; size_t declare_pos; UInt4 flags, comment_level; encoded_str encstr; } QueryParse; static void QP_initialize(QueryParse *q, const StatementClass *stmt) { q->statement = stmt->execute_statement ? stmt->execute_statement : stmt->statement; q->statement_type = stmt->statement_type; q->opos = 0; q->from_pos = -1; q->where_pos = -1; q->stmt_len = (q->statement) ? strlen(q->statement) : -1; q->in_literal = q->in_identifier = q->in_escape = q->in_dollar_quote = FALSE; q->dollar_tag = NULL; q->taglen = -1; q->token_save[0] = '\0'; q->token_len = 0; q->prev_token_end = TRUE; q->in_line_comment = FALSE; q->declare_pos = 0; q->flags = 0; q->comment_level = 0; make_encoded_str(&q->encstr, SC_get_conn(stmt), q->statement); } #define FLGB_PRE_EXECUTING 1L #define FLGB_BUILDING_PREPARE_STATEMENT (1L << 1) #define FLGB_BUILDING_BIND_REQUEST (1L << 2) #define FLGB_EXECUTE_PREPARED (1L << 3) #define FLGB_INACCURATE_RESULT (1L << 4) #define FLGB_CREATE_KEYSET (1L << 5) #define FLGB_KEYSET_DRIVEN (1L << 6) #define FLGB_CONVERT_LF (1L << 7) #define FLGB_DISCARD_OUTPUT (1L << 8) #define FLGB_BINARY_AS_POSSIBLE (1L << 9) #define FLGB_LITERAL_EXTENSION (1L << 10) #define FLGB_HEX_BIN_FORMAT (1L << 11) typedef struct _QueryBuild { char *query_statement; size_t str_size_limit; size_t str_alsize; size_t npos; SQLLEN current_row; Int2 param_number; Int2 dollar_number; Int2 num_io_params; Int2 num_output_params; Int2 num_discard_params; Int2 proc_return; Int2 brace_level; char parenthesize_the_first; APDFields *apdopts; IPDFields *ipdopts; PutDataInfo *pdata; size_t load_stmt_len; UInt4 flags; int ccsc; int errornumber; const char *errormsg; ConnectionClass *conn; /* mainly needed for LO handling */ StatementClass *stmt; /* needed to set error info in ENLARGE_.. */ } QueryBuild; #define INIT_MIN_ALLOC 4096 static ssize_t QB_initialize(QueryBuild *qb, size_t size, StatementClass *stmt, ConnectionClass *conn) { size_t newsize = 0; qb->flags = 0; qb->load_stmt_len = 0; qb->stmt = stmt; qb->apdopts = NULL; qb->ipdopts = NULL; qb->pdata = NULL; qb->proc_return = 0; qb->num_io_params = 0; qb->num_output_params = 0; qb->num_discard_params = 0; qb->brace_level = 0; qb->parenthesize_the_first = FALSE; if (conn) qb->conn = conn; else if (stmt) { Int2 dummy; qb->apdopts = SC_get_APDF(stmt); qb->ipdopts = SC_get_IPDF(stmt); qb->pdata = SC_get_PDTI(stmt); qb->conn = SC_get_conn(stmt); if (stmt->pre_executing) qb->flags |= FLGB_PRE_EXECUTING; if (stmt->discard_output_params) qb->flags |= FLGB_DISCARD_OUTPUT; qb->num_io_params = CountParameters(stmt, NULL, &dummy, &qb->num_output_params); qb->proc_return = stmt->proc_return; if (0 != (qb->flags & FLGB_DISCARD_OUTPUT)) qb->num_discard_params = qb->num_output_params; if (qb->num_discard_params < qb->proc_return) qb->num_discard_params = qb->proc_return; } else { qb->conn = NULL; return -1; } if (qb->conn->connInfo.lf_conversion) qb->flags |= FLGB_CONVERT_LF; qb->ccsc = qb->conn->ccsc; if (CC_get_escape(qb->conn) && PG_VERSION_GE(qb->conn, 8.1)) qb->flags |= FLGB_LITERAL_EXTENSION; if (PG_VERSION_GE(qb->conn, 9.0)) qb->flags |= FLGB_HEX_BIN_FORMAT; if (stmt) qb->str_size_limit = stmt->stmt_size_limit; else qb->str_size_limit = -1; if (qb->str_size_limit > 0) { if (size > qb->str_size_limit) return -1; newsize = qb->str_size_limit; } else { newsize = INIT_MIN_ALLOC; while (newsize <= size) newsize *= 2; } if ((qb->query_statement = malloc(newsize)) == NULL) { qb->str_alsize = 0; return -1; } qb->query_statement[0] = '\0'; qb->str_alsize = newsize; qb->npos = 0; qb->current_row = stmt->exec_current_row < 0 ? 0 : stmt->exec_current_row; qb->param_number = -1; qb->dollar_number = 0; qb->errornumber = 0; qb->errormsg = NULL; return newsize; } static int QB_initialize_copy(QueryBuild *qb_to, const QueryBuild *qb_from, UInt4 size) { memcpy(qb_to, qb_from, sizeof(QueryBuild)); if (qb_to->str_size_limit > 0) { if (size > qb_to->str_size_limit) return -1; } if ((qb_to->query_statement = malloc(size)) == NULL) { qb_to->str_alsize = 0; return -1; } qb_to->query_statement[0] = '\0'; qb_to->str_alsize = size; qb_to->npos = 0; return size; } static void QB_replace_SC_error(StatementClass *stmt, const QueryBuild *qb, const char *func) { int number; if (0 == qb->errornumber) return; if ((number = SC_get_errornumber(stmt)) > 0) return; if (number < 0 && qb->errornumber < 0) return; SC_set_error(stmt, qb->errornumber, qb->errormsg, func); } static void QB_Destructor(QueryBuild *qb) { if (qb->query_statement) { free(qb->query_statement); qb->query_statement = NULL; qb->str_alsize = 0; } } /* * New macros (Aceto) *-------------------- */ #define F_OldChar(qp) \ qp->statement[qp->opos] #define F_OldPtr(qp) \ (qp->statement + qp->opos) #define F_OldNext(qp) \ (++qp->opos) #define F_OldPrior(qp) \ (--qp->opos) #define F_OldPos(qp) \ qp->opos #define F_ExtractOldTo(qp, buf, ch, maxsize) \ do { \ size_t c = 0; \ while (qp->statement[qp->opos] != '\0' && qp->statement[qp->opos] != ch) \ { \ if (c >= maxsize) \ break; \ buf[c++] = qp->statement[qp->opos++]; \ } \ if (qp->statement[qp->opos] == '\0') \ {retval = SQL_ERROR; goto cleanup;} \ buf[c] = '\0'; \ } while (0) #define F_NewChar(qb) \ qb->query_statement[qb->npos] #define F_NewPtr(qb) \ (qb->query_statement + qb->npos) #define F_NewNext(qb) \ (++qb->npos) #define F_NewPos(qb) \ (qb->npos) static int convert_escape(QueryParse *qp, QueryBuild *qb); static int inner_process_tokens(QueryParse *qp, QueryBuild *qb); static int ResolveOneParam(QueryBuild *qb, QueryParse *qp); static int processParameters(QueryParse *qp, QueryBuild *qb, size_t *output_count, SQLLEN param_pos[][2]); static size_t convert_to_pgbinary(const char *in, char *out, size_t len, QueryBuild *qb); static ssize_t enlarge_query_statement(QueryBuild *qb, size_t newsize) { size_t newalsize = INIT_MIN_ALLOC; CSTR func = "enlarge_statement"; if (qb->str_size_limit > 0 && qb->str_size_limit < (int) newsize) { free(qb->query_statement); qb->query_statement = NULL; qb->str_alsize = 0; if (qb->stmt) { SC_set_error(qb->stmt, STMT_EXEC_ERROR, "Query buffer overflow in copy_statement_with_parameters", func); } else { qb->errormsg = "Query buffer overflow in copy_statement_with_parameters"; qb->errornumber = STMT_EXEC_ERROR; } return -1; } while (newalsize <= newsize) newalsize *= 2; if (!(qb->query_statement = realloc(qb->query_statement, newalsize))) { qb->str_alsize = 0; if (qb->stmt) { SC_set_error(qb->stmt, STMT_EXEC_ERROR, "Query buffer allocate error in copy_statement_with_parameters", func); } else { qb->errormsg = "Query buffer allocate error in copy_statement_with_parameters"; qb->errornumber = STMT_EXEC_ERROR; } return 0; } qb->str_alsize = newalsize; return newalsize; } /*---------- * Enlarge stmt_with_params if necessary. *---------- */ #define ENLARGE_NEWSTATEMENT(qb, newpos) \ if (newpos >= qb->str_alsize) \ { \ if (enlarge_query_statement(qb, newpos) <= 0) \ {retval = SQL_ERROR; goto cleanup;} \ } /*---------- * Terminate the stmt_with_params string with NULL. *---------- */ #define CVT_TERMINATE(qb) \ do { \ if (NULL == qb->query_statement) {retval = SQL_ERROR; goto cleanup;} \ qb->query_statement[qb->npos] = '\0'; \ } while (0) /*---------- * Append a data. *---------- */ #define CVT_APPEND_DATA(qb, s, len) \ do { \ size_t newpos = qb->npos + len; \ ENLARGE_NEWSTATEMENT(qb, newpos) \ memcpy(&qb->query_statement[qb->npos], s, len); \ qb->npos = newpos; \ qb->query_statement[newpos] = '\0'; \ } while (0) /*---------- * Append a string. *---------- */ #define CVT_APPEND_STR(qb, s) \ do { \ size_t len = strlen(s); \ CVT_APPEND_DATA(qb, s, len); \ } while (0) /*---------- * Append a char. *---------- */ #define CVT_APPEND_CHAR(qb, c) \ do { \ ENLARGE_NEWSTATEMENT(qb, qb->npos + 1); \ qb->query_statement[qb->npos++] = c; \ } while (0) /*---------- * Append a binary data. * Newly required size may be overestimated currently. *---------- */ #define CVT_APPEND_BINARY(qb, buf, used) \ do { \ size_t newlimit = qb->npos + ((qb->flags & FLGB_HEX_BIN_FORMAT) ? 2 * used + 4 : 5 * used); \ ENLARGE_NEWSTATEMENT(qb, newlimit); \ qb->npos += convert_to_pgbinary(buf, &qb->query_statement[qb->npos], used, qb); \ } while (0) /*---------- * *---------- */ #define CVT_SPECIAL_CHARS(qb, buf, used) \ do { \ size_t cnvlen = convert_special_chars(buf, NULL, used, qb->flags, qb->ccsc, CC_get_escape(qb->conn)); \ size_t newlimit = qb->npos + cnvlen; \ \ ENLARGE_NEWSTATEMENT(qb, newlimit); \ convert_special_chars(buf, &qb->query_statement[qb->npos], used, qb->flags, qb->ccsc, CC_get_escape(qb->conn)); \ qb->npos += cnvlen; \ } while (0) #ifdef NOT_USED #define CVT_TEXT_FIELD(qb, buf, used) \ do { \ char escape_ch = CC_get_escape(qb->conn); \ int flags = ((0 != qb->flags & FLGB_CONVERT_LF) ? CONVERT_CRLF_TO_LF : 0) | ((0 != qb->flags & FLGB_BUILDING_BIND_REQUEST) ? 0 : DOUBLE_LITERAL_QUOTE | (escape_ch ? DOUBLE_LITERAL_IN_ESCAPE : 0)); \ int cnvlen = (flags & (DOUBLE_LITERAL_QUOTE | DOUBLE_LITERAL_IN_ESCAPE)) != 0 ? used * 2 : used; \ if (used > 0 && qb->npos + cnvlen >= qb->str_alsize) \ { \ cnvlen = convert_text_field(buf, NULL, used, qb->ccsc, escape_ch, &flags); \ size_t newlimit = qb->npos + cnvlen; \ \ ENLARGE_NEWSTATEMENT(qb, newlimit); \ } \ cnvlen = convert_text_field(buf, &qb->query_statement[qb->npos], used, qb->ccsc, escape_ch, &flags); \ qb->npos += cnvlen; \ } while (0) #endif /* NOT_USED */ static RETCODE QB_start_brace(QueryBuild *qb) { BOOL replace_by_parenthesis = TRUE; RETCODE retval = SQL_ERROR; if (0 == qb->brace_level) { if (0 == F_NewPos(qb)) { qb->parenthesize_the_first = FALSE; replace_by_parenthesis = FALSE; } else qb->parenthesize_the_first = TRUE; } if (replace_by_parenthesis) CVT_APPEND_CHAR(qb, '('); qb->brace_level++; retval = SQL_SUCCESS; cleanup: return retval; } static RETCODE QB_end_brace(QueryBuild *qb) { BOOL replace_by_parenthesis = TRUE; RETCODE retval = SQL_ERROR; if (qb->brace_level <= 1 && !qb->parenthesize_the_first) replace_by_parenthesis = FALSE; if (replace_by_parenthesis) CVT_APPEND_CHAR(qb, ')'); qb->brace_level--; retval = SQL_SUCCESS; cleanup: return retval; } static RETCODE QB_append_space_to_separate_identifiers(QueryBuild *qb, const QueryParse *qp) { unsigned char tchar = F_OldChar(qp); encoded_str encstr; BOOL add_space = FALSE; RETCODE retval = SQL_ERROR; if (ODBC_ESCAPE_END != tchar) return SQL_SUCCESS; encoded_str_constr(&encstr, qb->ccsc, F_OldPtr(qp) + 1); tchar = encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) add_space = TRUE; else { if (isalnum(tchar)) add_space = TRUE; else { switch (tchar) { case '_': case '$': add_space = TRUE; } } } if (add_space) CVT_APPEND_CHAR(qb, ' '); retval = SQL_SUCCESS; cleanup: return retval; } /*---------- * Check if the statement is * SELECT ... INTO table FROM ..... * This isn't really a strict check but ... *---------- */ static BOOL into_table_from(const char *stmt) { if (strnicmp(stmt, "into", 4)) return FALSE; stmt += 4; if (!isspace((UCHAR) *stmt)) return FALSE; while (isspace((UCHAR) *(++stmt))); switch (*stmt) { case '\0': case ',': case LITERAL_QUOTE: return FALSE; case IDENTIFIER_QUOTE: /* double quoted table name ? */ do { do while (*(++stmt) != IDENTIFIER_QUOTE && *stmt); while (*stmt && *(++stmt) == IDENTIFIER_QUOTE); while (*stmt && !isspace((UCHAR) *stmt) && *stmt != IDENTIFIER_QUOTE) stmt++; } while (*stmt == IDENTIFIER_QUOTE); break; default: while (!isspace((UCHAR) *(++stmt))); break; } if (!*stmt) return FALSE; while (isspace((UCHAR) *(++stmt))); if (strnicmp(stmt, "from", 4)) return FALSE; return isspace((UCHAR) stmt[4]); } /*---------- * Check if the statement is * SELECT ... FOR UPDATE ..... * This isn't really a strict check but ... *---------- */ static UInt4 table_for_update_or_share(const char *stmt, size_t *endpos) { const char *wstmt = stmt; int advance; UInt4 flag = 0; while (isspace((UCHAR) *(++wstmt))); if (!*wstmt) return 0; if (0 == strnicmp(wstmt, "update", advance = 6)) flag |= FLGP_SELECT_FOR_UPDATE_OR_SHARE; else if (0 == strnicmp(wstmt, "share", advance = 5)) flag |= FLGP_SELECT_FOR_UPDATE_OR_SHARE; else if (0 == strnicmp(wstmt, "read", advance = 4)) flag |= FLGP_SELECT_FOR_READONLY; else return 0; wstmt += advance; if (0 != wstmt[0] && !isspace((UCHAR) wstmt[0])) return 0; else if (0 != (flag & FLGP_SELECT_FOR_READONLY)) { if (!isspace((UCHAR) wstmt[0])) return 0; while (isspace((UCHAR) *(++wstmt))); if (!*wstmt) return 0; if (0 != strnicmp(wstmt, "only", advance = 4)) return 0; wstmt += advance; } if (0 != wstmt[0] && !isspace((UCHAR) wstmt[0])) return 0; *endpos = wstmt - stmt; return flag; } /*---------- * Check if the statement has OUTER JOIN * This isn't really a strict check but ... *---------- */ static BOOL check_join(StatementClass *stmt, const char *curptr, size_t curpos) { const char *wstmt; ssize_t stapos, endpos, tokenwd; const int backstep = 4; BOOL outerj = TRUE; for (endpos = curpos, wstmt = curptr; endpos >= 0 && isspace((UCHAR) *wstmt); endpos--, wstmt--) ; if (endpos < 0) return FALSE; for (endpos -= backstep, wstmt -= backstep; endpos >= 0 && isspace((UCHAR) *wstmt); endpos--, wstmt--) ; if (endpos < 0) return FALSE; for (stapos = endpos; stapos >= 0 && !isspace((UCHAR) *wstmt); stapos--, wstmt--) ; if (stapos < 0) return FALSE; wstmt++; switch (tokenwd = endpos - stapos) { case 4: if (strnicmp(wstmt, "FULL", tokenwd) == 0 || strnicmp(wstmt, "LEFT", tokenwd) == 0) break; return FALSE; case 5: if (strnicmp(wstmt, "OUTER", tokenwd) == 0 || strnicmp(wstmt, "RIGHT", tokenwd) == 0) break; if (strnicmp(wstmt, "INNER", tokenwd) == 0 || strnicmp(wstmt, "CROSS", tokenwd) == 0) { outerj = FALSE; break; } return FALSE; default: return FALSE; } if (stmt) { if (outerj) SC_set_outer_join(stmt); else SC_set_inner_join(stmt); } return TRUE; } /*---------- * Check if the statement is * INSERT INTO ... () VALUES () * This isn't really a strict check but ... *---------- */ static BOOL insert_without_target(const char *stmt, size_t *endpos) { const char *wstmt = stmt; while (isspace((UCHAR) *(++wstmt))); if (!*wstmt) return FALSE; if (strnicmp(wstmt, "VALUES", 6)) return FALSE; wstmt += 6; if (!wstmt[0] || !isspace((UCHAR) wstmt[0])) return FALSE; while (isspace((UCHAR) *(++wstmt))); if (*wstmt != '(' || *(++wstmt) != ')') return FALSE; wstmt++; *endpos = wstmt - stmt; return !wstmt[0] || isspace((UCHAR) wstmt[0]) || ';' == wstmt[0]; } static RETCODE prep_params(StatementClass *stmt, QueryParse *qp, QueryBuild *qb, BOOL sync); static int Prepare_and_convert(StatementClass *stmt, QueryParse *qp, QueryBuild *qb) { CSTR func = "Prepare_and_convert"; char *exe_statement = NULL; RETCODE retval; ConnectionClass *conn = SC_get_conn(stmt); ConnInfo *ci = &(conn->connInfo); BOOL discardOutput, outpara; if (PROTOCOL_74(ci)) { switch (stmt->prepared) { case NOT_YET_PREPARED: case ONCE_DESCRIBED: break; default: return SQL_SUCCESS; } } if (QB_initialize(qb, qp->stmt_len, stmt, NULL) < 0) return SQL_ERROR; if (PROTOCOL_74(ci)) return prep_params(stmt, qp, qb, FALSE); discardOutput = (0 != (qb->flags & FLGB_DISCARD_OUTPUT)); if (NOT_YET_PREPARED == stmt->prepared) /* not yet prepared */ { ssize_t elen; int i, oc; SQLSMALLINT marker_count; const IPDFields *ipdopts = qb->ipdopts; char plan_name[32]; qb->flags |= FLGB_BUILDING_PREPARE_STATEMENT; sprintf(plan_name, "_PLAN%p", stmt); #ifdef NOT_USED new_statement = qb->query_statement; sprintf(new_statement, "PREPARE \"%s\"", plan_name); qb->npos = strlen(new_statement); #endif /* NOT_USED */ CVT_APPEND_STR(qb, "PREPARE \""); CVT_APPEND_STR(qb, plan_name); CVT_APPEND_CHAR(qb, IDENTIFIER_QUOTE); marker_count = stmt->num_params - qb->num_discard_params; if (!ipdopts || ipdopts->allocated < marker_count) { SC_set_error(stmt, STMT_COUNT_FIELD_INCORRECT, "The # of binded parameters < the # of parameter markers", func); retval = SQL_ERROR; goto cleanup; } if (marker_count > 0) { CVT_APPEND_CHAR(qb, '('); for (i = qb->proc_return, oc = 0; i < stmt->num_params; i++) { outpara = FALSE; if (i < ipdopts->allocated && SQL_PARAM_OUTPUT == ipdopts->parameters[i].paramType) { outpara = TRUE; if (discardOutput) continue; } if (oc > 0) CVT_APPEND_STR(qb, ", "); if (outpara) CVT_APPEND_STR(qb, "void"); else CVT_APPEND_STR(qb, pgtype_to_name(stmt, PIC_dsp_pgtype(conn, ipdopts->parameters[i]), -1, FALSE)); oc++; } CVT_APPEND_CHAR(qb, ')'); } CVT_APPEND_STR(qb, " as "); for (qp->opos = 0; qp->opos < qp->stmt_len; qp->opos++) { retval = inner_process_tokens(qp, qb); if (SQL_ERROR == retval) goto cleanup; } CVT_APPEND_CHAR(qb, ';'); /* build the execute statement */ exe_statement = malloc(30 + 2 * marker_count); sprintf(exe_statement, "EXECUTE \"%s\"", plan_name); if (marker_count > 0) { elen = strlen(exe_statement); exe_statement[elen++] = '('; for (i = 0; i < marker_count; i++) { if (i > 0) exe_statement[elen++] = ','; exe_statement[elen++] = '?'; } exe_statement[elen++] = ')'; exe_statement[elen] = '\0'; } inolog("exe_statement=%s\n", exe_statement); stmt->execute_statement = exe_statement; QP_initialize(qp, stmt); SC_set_planname(stmt, plan_name); } qb->flags &= FLGB_DISCARD_OUTPUT; qb->flags |= FLGB_EXECUTE_PREPARED; qb->param_number = -1; for (qp->opos = 0; qp->opos < qp->stmt_len; qp->opos++) { retval = inner_process_tokens(qp, qb); if (SQL_ERROR == retval) goto cleanup; } /* make sure new_statement is always null-terminated */ CVT_TERMINATE(qb); retval = SQL_SUCCESS; cleanup: if (SQL_SUCCEEDED(retval)) { if (exe_statement) SC_set_concat_prepare_exec(stmt); stmt->stmt_with_params = qb->query_statement; qb->query_statement = NULL; } else { QB_replace_SC_error(stmt, qb, func); if (exe_statement) { free(exe_statement); stmt->execute_statement = NULL; } QB_Destructor(qb); } return retval; } #define my_strchr(conn, s1,c1) pg_mbschr(conn->ccsc, s1,c1) static RETCODE prep_params(StatementClass *stmt, QueryParse *qp, QueryBuild *qb, BOOL sync) { CSTR func = "prep_params"; RETCODE retval; BOOL ret, once_descr; ConnectionClass *conn = SC_get_conn(stmt); QResultClass *res, *dest_res = NULL; char plan_name[32]; po_ind_t multi; int func_cs_count = 0; const char *orgquery = NULL, *srvquery = NULL; Int4 endp1, endp2; SQLSMALLINT num_pa = 0, num_p1, num_p2; inolog("prep_params\n"); once_descr = (ONCE_DESCRIBED == stmt->prepared); qb->flags |= FLGB_BUILDING_PREPARE_STATEMENT; for (qp->opos = 0; qp->opos < qp->stmt_len; qp->opos++) { retval = inner_process_tokens(qp, qb); if (SQL_ERROR == retval) { QB_replace_SC_error(stmt, qb, func); QB_Destructor(qb); return retval; } } CVT_TERMINATE(qb); retval = SQL_ERROR; #define return DONT_CALL_RETURN_FROM_HERE??? ENTER_INNER_CONN_CS(conn, func_cs_count); if (NAMED_PARSE_REQUEST == SC_get_prepare_method(stmt)) sprintf(plan_name, "_PLAN%p", stmt); else strcpy(plan_name, NULL_STRING); stmt->current_exec_param = 0; multi = stmt->multi_statement; if (multi > 0) { orgquery = stmt->statement; SC_scanQueryAndCountParams(orgquery, conn, &endp1, &num_p1, NULL, NULL); srvquery = qb->query_statement; SC_scanQueryAndCountParams(srvquery, conn, &endp2, NULL, NULL, NULL); mylog("%s:SendParseRequest for the first command length=%d(%d) num_p=%d\n", func, endp2, endp1, num_p1); ret = SendParseRequest(stmt, plan_name, srvquery, endp2, num_p1); } else ret = SendParseRequest(stmt, plan_name, qb->query_statement, SQL_NTS, -1); if (!ret) goto cleanup; if (!once_descr && (!SendDescribeRequest(stmt, plan_name, TRUE))) goto cleanup; SC_set_planname(stmt, plan_name); SC_set_prepared(stmt, plan_name[0] ? PREPARING_PERMANENTLY : PREPARING_TEMPORARILY); if (!sync) { retval = SQL_SUCCESS; goto cleanup; } if (!(res = SendSyncAndReceive(stmt, NULL, "prepare_and_describe"))) { SC_set_error(stmt, STMT_NO_RESPONSE, "commnication error while preapreand_describe", func); CC_on_abort(conn, CONN_DEAD); goto cleanup; } if (once_descr) dest_res = res; else SC_set_Result(stmt, res); if (!QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Error while preparing parameters", func); goto cleanup; } if (stmt->multi_statement <= 0) { retval = SQL_SUCCESS; goto cleanup; } while (multi > 0) { orgquery += (endp1 + 1); srvquery += (endp2 + 1); num_pa += num_p1; SC_scanQueryAndCountParams(orgquery, conn, &endp1, &num_p1, &multi, NULL); SC_scanQueryAndCountParams(srvquery, conn, &endp2, &num_p2, NULL, NULL); mylog("%s:SendParseRequest for the subsequent command length=%d(%d) num_p=%d\n", func, endp2, endp1, num_p1); if (num_p2 > 0) { stmt->current_exec_param = num_pa; ret = SendParseRequest(stmt, plan_name, srvquery, endp2 < 0 ? SQL_NTS : endp2, num_p1); if (!ret) goto cleanup; if (!once_descr && !SendDescribeRequest(stmt, plan_name, TRUE)) goto cleanup; if (!(res = SendSyncAndReceive(stmt, NULL, "prepare_and_describe"))) { SC_set_error(stmt, STMT_NO_RESPONSE, "commnication error while preapreand_describe", func); CC_on_abort(conn, CONN_DEAD); goto cleanup; } QR_Destructor(res); } } retval = SQL_SUCCESS; cleanup: #undef return if (dest_res) QR_Destructor(dest_res); CLEANUP_FUNC_CONN_CS(func_cs_count, conn); stmt->current_exec_param = -1; QB_Destructor(qb); return retval; } RETCODE prepareParameters(StatementClass *stmt) { switch (stmt->prepared) { QueryParse query_org, *qp; QueryBuild query_crt, *qb; case NOT_YET_PREPARED: case ONCE_DESCRIBED: inolog("prepareParameters\n"); qp = &query_org; QP_initialize(qp, stmt); qb = &query_crt; if (QB_initialize(qb, qp->stmt_len, stmt, NULL) < 0) return SQL_ERROR; return prep_params(stmt, qp, qb, TRUE); } return SQL_SUCCESS; } /* * This function inserts parameters into an SQL statements. * It will also modify a SELECT statement for use with declare/fetch cursors. * This function does a dynamic memory allocation to get rid of query size limit! */ int copy_statement_with_parameters(StatementClass *stmt, BOOL buildPrepareStatement) { CSTR func = "copy_statement_with_parameters"; RETCODE retval; QueryParse query_org, *qp; QueryBuild query_crt, *qb; char *new_statement; BOOL begin_first = FALSE, prepare_dummy_cursor = FALSE, bPrepConv; ConnectionClass *conn = SC_get_conn(stmt); ConnInfo *ci = &(conn->connInfo); const char *bestitem = NULL; inolog("%s: enter prepared=%d\n", func, stmt->prepared); if (!stmt->statement) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "No statement string", func); return SQL_ERROR; } qp = &query_org; QP_initialize(qp, stmt); if (stmt->statement_type != STMT_TYPE_SELECT) { stmt->options.cursor_type = SQL_CURSOR_FORWARD_ONLY; stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; } else if (stmt->options.cursor_type == SQL_CURSOR_FORWARD_ONLY) stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; else if (stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY) { if (SQL_CURSOR_DYNAMIC == stmt->options.cursor_type && 0 == (ci->updatable_cursors & ALLOW_DYNAMIC_CURSORS)) stmt->options.cursor_type = SQL_CURSOR_KEYSET_DRIVEN; if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type && 0 == (ci->updatable_cursors & ALLOW_KEYSET_DRIVEN_CURSORS)) stmt->options.cursor_type = SQL_CURSOR_STATIC; switch (stmt->options.cursor_type) { case SQL_CURSOR_DYNAMIC: case SQL_CURSOR_KEYSET_DRIVEN: if (SC_update_not_ready(stmt)) parse_statement(stmt, TRUE); if (SC_is_updatable(stmt) && stmt->ntab > 0) { if (bestitem = GET_NAME(stmt->ti[0]->bestitem), NULL == bestitem) stmt->options.cursor_type = SQL_CURSOR_STATIC; } break; } if (SQL_CURSOR_STATIC == stmt->options.cursor_type) { if (0 == (ci->updatable_cursors & ALLOW_STATIC_CURSORS)) stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; else if (SC_update_not_ready(stmt)) parse_statement(stmt, TRUE); } if (SC_parsed_status(stmt) == STMT_PARSE_FATAL) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN) stmt->options.cursor_type = SQL_CURSOR_STATIC; } else if (!stmt->updatable) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; stmt->options.cursor_type = SQL_CURSOR_STATIC; } else { qp->from_pos = stmt->from_pos; qp->where_pos = stmt->where_pos; } inolog("type=%d concur=%d\n", stmt->options.cursor_type, stmt->options.scroll_concurrency); } SC_miscinfo_clear(stmt); /* If the application hasn't set a cursor name, then generate one */ if (!SC_cursor_is_valid(stmt)) { char curname[32]; sprintf(curname, "SQL_CUR%p", stmt); STRX_TO_NAME(stmt->cursor_name, curname); } if (stmt->stmt_with_params) { free(stmt->stmt_with_params); stmt->stmt_with_params = NULL; } SC_no_fetchcursor(stmt); SC_no_pre_executable(stmt); if (SC_may_use_cursor(stmt)) SC_set_pre_executable(stmt); qb = &query_crt; qb->query_statement = NULL; bPrepConv = FALSE; if (PREPARED_PERMANENTLY == stmt->prepared) bPrepConv = TRUE; else if (buildPrepareStatement && SQL_CONCUR_READ_ONLY == stmt->options.scroll_concurrency) bPrepConv = TRUE; if (bPrepConv) { retval = Prepare_and_convert(stmt, qp, qb); goto cleanup; } SC_forget_unnamed(stmt); buildPrepareStatement = FALSE; if (ci->disallow_premature) prepare_dummy_cursor = stmt->pre_executing; if (prepare_dummy_cursor) qp->flags |= FLGP_PREPARE_DUMMY_CURSOR; if (QB_initialize(qb, qp->stmt_len, stmt, NULL) < 0) { retval = SQL_ERROR; goto cleanup; } new_statement = qb->query_statement; /* For selects, prepend a declare cursor to the statement */ if (SC_may_use_cursor(stmt) && !stmt->internal) { const char *opt_scroll = NULL_STRING, *opt_hold = NULL_STRING; if (prepare_dummy_cursor) { SC_set_fetchcursor(stmt); if (PG_VERSION_GE(conn, 7.4)) opt_scroll = " scroll"; if (!CC_is_in_trans(conn) && PG_VERSION_GE(conn, 7.1)) { strcpy(new_statement, "BEGIN;"); begin_first = TRUE; } } else if (ci->drivers.use_declarefetch /** && SQL_CONCUR_READ_ONLY == stmt->options.scroll_concurrency **/ ) { SC_set_fetchcursor(stmt); if (SC_is_with_hold(stmt)) opt_hold = " with hold"; if (PG_VERSION_GE(conn, 7.4)) { if (SQL_CURSOR_FORWARD_ONLY != stmt->options.cursor_type) opt_scroll = " scroll"; } } if (SC_is_fetchcursor(stmt)) { sprintf(new_statement, "%sdeclare \"%s\"%s cursor%s for ", new_statement, SC_cursor_name(stmt), opt_scroll, opt_hold); qb->npos = strlen(new_statement); qp->flags |= FLGP_USING_CURSOR; qp->declare_pos = qb->npos; } if (SQL_CONCUR_READ_ONLY != stmt->options.scroll_concurrency) { qb->flags |= FLGB_CREATE_KEYSET; if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type) qb->flags |= FLGB_KEYSET_DRIVEN; } } for (qp->opos = 0; qp->opos < qp->stmt_len; qp->opos++) { retval = inner_process_tokens(qp, qb); if (SQL_ERROR == retval) { QB_replace_SC_error(stmt, qb, func); QB_Destructor(qb); return retval; } } /* make sure new_statement is always null-terminated */ CVT_TERMINATE(qb); new_statement = qb->query_statement; stmt->statement_type = qp->statement_type; stmt->inaccurate_result = (0 != (qb->flags & FLGB_INACCURATE_RESULT)); if (0 == (qp->flags & FLGP_USING_CURSOR)) SC_no_fetchcursor(stmt); #ifdef NOT_USED /* this seems problematic */ else if (0 == (qp->flags & (FLGP_SELECT_FOR_UPDATE_OR_SHARE | FLGP_SELECT_FOR_READONLY)) && 0 == stmt->multi_statement && PG_VERSION_GE(conn, 8.3)) { BOOL semi_colon_found = FALSE; const UCHAR *ptr = NULL, semi_colon = ';'; int npos; if (npos = F_NewPos(qb) - 1, npos >= 0) ptr = F_NewPtr(qb) - 1; for (; npos >= 0 && isspace(*ptr); npos--, ptr--) ; if (npos >= 0 && semi_colon == *ptr) { qb->npos = npos; semi_colon_found = TRUE; } CVT_APPEND_STR(qb, " for read only"); if (semi_colon_found) CVT_APPEND_CHAR(qb, semi_colon); CVT_TERMINATE(qb); } #endif /* NOT_USED */ if (0 != (qp->flags & FLGP_SELECT_INTO) || 0 != (qp->flags & FLGP_MULTIPLE_STATEMENT)) { SC_no_pre_executable(stmt); stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; } if (0 != (qp->flags & FLGP_SELECT_FOR_UPDATE_OR_SHARE)) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; } if (conn->DriverToDataSource != NULL) { size_t length = strlen(new_statement); conn->DriverToDataSource(conn->translation_option, SQL_CHAR, new_statement, (SDWORD) length, new_statement, (SDWORD) length, NULL, NULL, 0, NULL); } if (!stmt->load_statement && qp->from_pos >= 0) { size_t npos = qb->load_stmt_len; if (0 == npos) { npos = qb->npos; for (; npos > 0; npos--) { if (isspace((unsigned char) new_statement[npos - 1])) continue; if (';' != new_statement[npos - 1]) break; } if (0 != (qb->flags & FLGB_KEYSET_DRIVEN)) { qb->npos = npos; /* ---------- * 1st query is for field information * 2nd query is keyset gathering */ CVT_APPEND_STR(qb, " where ctid = '(0,0)';select \"ctid"); if (bestitem) { CVT_APPEND_STR(qb, "\", \""); CVT_APPEND_STR(qb, bestitem); } CVT_APPEND_STR(qb, "\" from "); CVT_APPEND_DATA(qb, qp->statement + qp->from_pos + 5, npos - qp->from_pos - 5); } } npos -= qp->declare_pos; stmt->load_statement = malloc(npos + 1); memcpy(stmt->load_statement, qb->query_statement + qp->declare_pos, npos); stmt->load_statement[npos] = '\0'; } if (prepare_dummy_cursor && SC_is_pre_executable(stmt)) { char fetchstr[128]; sprintf(fetchstr, ";fetch backward in \"%s\";close \"%s\";", SC_cursor_name(stmt), SC_cursor_name(stmt)); if (begin_first && CC_is_in_autocommit(conn)) strcat(fetchstr, "COMMIT;"); CVT_APPEND_STR(qb, fetchstr); stmt->inaccurate_result = TRUE; } stmt->stmt_with_params = qb->query_statement; retval = SQL_SUCCESS; cleanup: return retval; } static void remove_declare_cursor(QueryBuild *qb, QueryParse *qp) { qp->flags &= ~FLGP_USING_CURSOR; if (qp->declare_pos <= 0) return; memmove(qb->query_statement, qb->query_statement + qp->declare_pos, qb->npos - qp->declare_pos); qb->npos -= qp->declare_pos; qp->declare_pos = 0; } Int4 findTag(const char *tag, char dollar_quote, int ccsc) { Int4 taglen = 0; encoded_str encstr; unsigned char tchar; const char *sptr; encoded_str_constr(&encstr, ccsc, tag + 1); for (sptr = tag + 1; *sptr; sptr++) { tchar = encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) continue; if (dollar_quote == tchar) { taglen = sptr - tag + 1; break; } if (isspace(tchar)) break; } return taglen; } static Int4 findIdentifier(const char *str, int ccsc, const char **nextdel) { Int4 strlen = 0; encoded_str encstr; unsigned char tchar; const char *sptr; BOOL dquote = FALSE; *nextdel = NULL; encoded_str_constr(&encstr, ccsc, str); for (sptr = str; *sptr; sptr++) { tchar = encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) continue; if (sptr == str) /* the first character */ { if (dquote = (IDENTIFIER_QUOTE == tchar), dquote) continue; if (!isalpha(tchar)) { strlen = 0; if (!isspace(tchar)) *nextdel = sptr; break; } } if (dquote) { if (IDENTIFIER_QUOTE == tchar) { if (IDENTIFIER_QUOTE == sptr[1]) { encoded_nextchar(&encstr); sptr++; continue; } strlen = sptr - str + 1; sptr++; break; } } else { if (isalnum(tchar)) continue; if (isspace(tchar)) { strlen = sptr - str; break; } switch (tchar) { case '_': case '$': continue; } strlen = sptr - str; *nextdel = sptr; break; } } if (NULL == *nextdel) { for (; *sptr; sptr++) { if (!isspace((UCHAR) *sptr)) { *nextdel = sptr; break; } } } return strlen; } static int inner_process_tokens(QueryParse *qp, QueryBuild *qb) { CSTR func = "inner_process_tokens"; BOOL lf_conv = ((qb->flags & FLGB_CONVERT_LF) != 0); const char *bestitem = NULL; RETCODE retval; Int4 opos; char oldchar; StatementClass *stmt = qb->stmt; char literal_quote = LITERAL_QUOTE, dollar_quote = DOLLAR_QUOTE, escape_in_literal = '\0'; if (stmt && stmt->ntab > 0) bestitem = GET_NAME(stmt->ti[0]->bestitem); opos = (Int4) qp->opos; if (opos < 0) { qb->errornumber = STMT_SEQUENCE_ERROR; qb->errormsg = "Function call for inner_process_tokens sequence error"; return SQL_ERROR; } if (qp->from_pos == opos) { if (0 == (qb->flags & FLGB_CREATE_KEYSET)) { qb->errornumber = STMT_SEQUENCE_ERROR; qb->errormsg = "Should come here only when handling updatable cursors"; return SQL_ERROR; } CVT_APPEND_STR(qb, ", \"ctid"); if (bestitem) { CVT_APPEND_STR(qb, "\", \""); CVT_APPEND_STR(qb, bestitem); } CVT_APPEND_STR(qb, "\" "); } else if (qp->where_pos == opos) { qb->load_stmt_len = qb->npos; if (0 != (qb->flags & FLGB_KEYSET_DRIVEN)) { CVT_APPEND_STR(qb, "where ctid = '(0,0)';select \"ctid"); if (bestitem) { CVT_APPEND_STR(qb, "\", \""); CVT_APPEND_STR(qb, bestitem); } CVT_APPEND_STR(qb, "\" from "); CVT_APPEND_DATA(qb, qp->statement + qp->from_pos + 5, qp->where_pos - qp->from_pos - 5); } } oldchar = encoded_byte_check(&qp->encstr, qp->opos); if (ENCODE_STATUS(qp->encstr) != 0) { CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } /* * From here we are guaranteed to handle a 1-byte character. */ if (qp->in_escape) /* escape check */ { qp->in_escape = FALSE; CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (qp->in_dollar_quote) /* dollar quote check */ { if (oldchar == dollar_quote) { if (strncmp(F_OldPtr(qp), qp->dollar_tag, qp->taglen) == 0) { CVT_APPEND_DATA(qb, F_OldPtr(qp), qp->taglen); qp->opos += (qp->taglen - 1); qp->in_dollar_quote = FALSE; qp->in_literal = FALSE; qp->dollar_tag = NULL; qp->taglen = -1; return SQL_SUCCESS; } } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (qp->in_literal) /* quote check */ { if (oldchar == escape_in_literal) qp->in_escape = TRUE; else if (oldchar == literal_quote) qp->in_literal = FALSE; CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (qp->in_identifier) /* double quote check */ { if (oldchar == IDENTIFIER_QUOTE) qp->in_identifier = FALSE; CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (qp->comment_level > 0) /* comment_level check */ { if ('/' == oldchar && '*' == F_OldPtr(qp)[1]) { qp->comment_level++; CVT_APPEND_CHAR(qb, oldchar); F_OldNext(qp); oldchar = F_OldChar(qp); } else if ('*' == oldchar && '/' == F_OldPtr(qp)[1]) { qp->comment_level--; CVT_APPEND_CHAR(qb, oldchar); F_OldNext(qp); oldchar = F_OldChar(qp); } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (qp->in_line_comment) /* line comment check */ { if (PG_LINEFEED == oldchar) qp->in_line_comment = FALSE; CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } /* * From here we are guranteed to be in neither a literal_escape, * a literal_quote nor an idetifier_quote. */ /* Squeeze carriage-return/linefeed pairs to linefeed only */ else if (lf_conv && PG_CARRIAGE_RETURN == oldchar && qp->opos + 1 < qp->stmt_len && PG_LINEFEED == qp->statement[qp->opos + 1]) return SQL_SUCCESS; /* * Handle literals (date, time, timestamp) and ODBC scalar * functions */ else if (oldchar == ODBC_ESCAPE_START) { if (SQL_ERROR == convert_escape(qp, qb)) { if (0 == qb->errornumber) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "ODBC escape convert error"; } mylog("%s convert_escape error\n", func); return SQL_ERROR; } return SQL_SUCCESS; } /* End of an escape sequence */ else if (oldchar == ODBC_ESCAPE_END) { return QB_end_brace(qb); } else if (oldchar == '@' && strnicmp(F_OldPtr(qp), "@@identity", 10) == 0) { ConnectionClass *conn = SC_get_conn(stmt); BOOL converted = FALSE; COL_INFO *coli; #ifdef NOT_USED /* lastval() isn't always appropriate */ if (PG_VERSION_GE(conn, 8.1)) { CVT_APPEND_STR(qb, "lastval()"); converted = TRUE; } else #endif /* NOT_USED */ if (NAME_IS_VALID(conn->tableIns)) { TABLE_INFO ti, *pti = &ti; memset(&ti, 0, sizeof(ti)); NAME_TO_NAME(ti.schema_name, conn->schemaIns); NAME_TO_NAME(ti.table_name, conn->tableIns); getCOLIfromTI(func, conn, qb->stmt, 0, &pti); coli = ti.col_info; NULL_THE_NAME(ti.schema_name); NULL_THE_NAME(ti.table_name); if (NULL != coli) { int i, num_fields = QR_NumResultCols(coli->result); for (i = 0; i < num_fields; i++) { if (*((char *)QR_get_value_backend_text(coli->result, i, COLUMNS_AUTO_INCREMENT)) == '1') { CVT_APPEND_STR(qb, "curr"); CVT_APPEND_STR(qb, (char *)QR_get_value_backend_text(coli->result, i, COLUMNS_COLUMN_DEF) + 4); converted = TRUE; break; } } } } if (!converted) CVT_APPEND_STR(qb, "NULL"); qp->opos += 10; return SQL_SUCCESS; } /* * Can you have parameter markers inside of quotes? I dont think * so. All the queries I've seen expect the driver to put quotes * if needed. */ else if (oldchar != '?') { if (oldchar == dollar_quote) { qp->taglen = findTag(F_OldPtr(qp), dollar_quote, qp->encstr.ccsc); if (qp->taglen > 0) { qp->in_literal = TRUE; qp->in_dollar_quote = TRUE; qp->dollar_tag = F_OldPtr(qp); CVT_APPEND_DATA(qb, F_OldPtr(qp), qp->taglen); qp->opos += (qp->taglen - 1); return SQL_SUCCESS; } } else if (oldchar == literal_quote) { if (!qp->in_identifier) { qp->in_literal = TRUE; escape_in_literal = CC_get_escape(qb->conn); if (!escape_in_literal) { if (LITERAL_EXT == F_OldPtr(qp)[-1]) escape_in_literal = ESCAPE_IN_LITERAL; } } } else if (oldchar == IDENTIFIER_QUOTE) { if (!qp->in_literal) qp->in_identifier = TRUE; } else if ('/' == oldchar && '*' == F_OldPtr(qp)[1]) { qp->comment_level++; } else if ('-' == oldchar && '-' == F_OldPtr(qp)[1]) { qp->in_line_comment = TRUE; } else if (oldchar == ';') { /* * can't parse multiple statement using protocol V3. * reset the dollar number here in case it is divided * to parse. */ qb->dollar_number = 0; if (0 != (qp->flags & FLGP_USING_CURSOR)) { const char *vp = &(qp->statement[qp->opos + 1]); while (*vp && isspace((unsigned char) *vp)) vp++; if (*vp) /* multiple statement */ { qp->flags |= FLGP_MULTIPLE_STATEMENT; qb->flags &= ~FLGB_KEYSET_DRIVEN; remove_declare_cursor(qb, qp); } } } else { if (isspace((UCHAR) oldchar)) { if (!qp->prev_token_end) { qp->prev_token_end = TRUE; qp->token_save[qp->token_len] = '\0'; if (qp->token_len == 4) { if (0 != (qp->flags & FLGP_USING_CURSOR) && into_table_from(&qp->statement[qp->opos - qp->token_len])) { qp->flags |= FLGP_SELECT_INTO; qb->flags &= ~FLGB_KEYSET_DRIVEN; qp->statement_type = STMT_TYPE_CREATE; remove_declare_cursor(qb, qp); } else if (stricmp(qp->token_save, "join") == 0) { if (stmt) check_join(stmt, F_OldPtr(qp), F_OldPos(qp)); } } else if (qp->token_len == 3) { if (0 != (qp->flags & FLGP_USING_CURSOR) && strnicmp(qp->token_save, "for", 3) == 0) { UInt4 flg; size_t endpos; flg = table_for_update_or_share(F_OldPtr(qp), &endpos); if (0 != (FLGP_SELECT_FOR_UPDATE_OR_SHARE & flg)) { if (qp->flags & FLGP_PREPARE_DUMMY_CURSOR) { qb->npos -= 4; qp->opos += endpos; } else { qp->flags |= flg; remove_declare_cursor(qb, qp); } } else qp->flags |= flg; } } else if (qp->token_len == 2) { size_t endpos; if (STMT_TYPE_INSERT == qp->statement_type && strnicmp(qp->token_save, "()", 2) == 0 && insert_without_target(F_OldPtr(qp), &endpos)) { qb->npos -= 2; CVT_APPEND_STR(qb, "DEFAULT VALUES"); qp->opos += endpos; return SQL_SUCCESS; } } } } else if (qp->prev_token_end) { qp->prev_token_end = FALSE; qp->token_save[0] = oldchar; qp->token_len = 1; } else if (qp->token_len + 1 < sizeof(qp->token_save)) qp->token_save[qp->token_len++] = oldchar; } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } /* * Its a '?' parameter alright */ if (retval = ResolveOneParam(qb, qp), retval < 0) return retval; if (SQL_SUCCESS_WITH_INFO == retval) /* means discarding output parameter */ { } retval = SQL_SUCCESS; cleanup: return retval; } #define MIN_ALC_SIZE 128 BOOL BuildBindRequest(StatementClass *stmt, const char *plan_name) { CSTR func = "BuildBindRequest"; QueryBuild qb; size_t leng, plen; UInt4 netleng; SQLSMALLINT num_p; Int2 netnum_p; int i, num_params; char *bindreq; ConnectionClass *conn = SC_get_conn(stmt); BOOL ret = TRUE, sockerr = FALSE, discard_output; RETCODE retval; const IPDFields *ipdopts = SC_get_IPDF(stmt); num_params = stmt->num_params; if (num_params < 0) { PGAPI_NumParams(stmt, &num_p); num_params = num_p; } if (ipdopts->allocated < num_params) { SC_set_error(stmt, STMT_COUNT_FIELD_INCORRECT, "The # of binded parameters < the # of parameter markers", func); return FALSE; } /* * Calculate minimum length of the packet. This doesn't take any of * the actual parameter values into account, but it's enough to make * sure there's enough space for all the fields before the parameter * values, without enlarging. */ plen = strlen(plan_name); netleng = sizeof(netleng) /* length fields */ + 2 * (plen + 1) /* portal and plan name */ + sizeof(Int2) /* number of param format codes */ + sizeof(Int2) * num_params /* parameter types (max) */ + sizeof(Int2) /* result format */ + 1; if (QB_initialize(&qb, netleng > MIN_ALC_SIZE ? netleng : MIN_ALC_SIZE, stmt, NULL) < 0) { return FALSE; } qb.flags |= FLGB_BUILDING_BIND_REQUEST; qb.flags |= FLGB_BINARY_AS_POSSIBLE; bindreq = qb.query_statement; leng = sizeof(netleng); memcpy(bindreq + leng, plan_name, plen + 1); /* portal name */ leng += (plen + 1); memcpy(bindreq + leng, plan_name, plen + 1); /* prepared plan name */ leng += (plen + 1); inolog("num_params=%d proc_return=%d\n", num_params, stmt->proc_return); num_p = num_params - qb.num_discard_params; inolog("num_p=%d\n", num_p); discard_output = (0 != (qb.flags & FLGB_DISCARD_OUTPUT)); netnum_p = htons(num_p); /* Network byte order */ if (0 != (qb.flags & FLGB_BINARY_AS_POSSIBLE) && num_p > 0) { int j; ParameterImplClass *parameters = ipdopts->parameters; Int2 net_one = htons(1); /* number of parameter formats */ memcpy(bindreq + leng, &netnum_p, sizeof(netnum_p)); leng += sizeof(Int2); /* initialize to text format */ memset(bindreq + leng, 0, sizeof(Int2) * num_p); for (i = stmt->proc_return, j = 0; i < num_params; i++) { inolog("%dth parameter type oid is %u\n", i, PIC_dsp_pgtype(conn, parameters[i])); if (discard_output && SQL_PARAM_OUTPUT == parameters[i].paramType) continue; if (PG_TYPE_BYTEA == PIC_dsp_pgtype(conn, parameters[i])) { mylog("%dth parameter is of binary format\n", j); /* use binary format for this param */ memcpy(bindreq + leng + sizeof(Int2) * j, &net_one, sizeof(net_one)); } j++; } leng += sizeof(Int2) * num_p; } else { memset(bindreq + leng, 0, sizeof(Int2)); /* text format */ leng += sizeof(Int2); } /* number of params */ memcpy(bindreq + leng, &netnum_p, sizeof(netnum_p)); leng += sizeof(Int2); /* * Now add the parameter values. * * Note: when you append more data to the packet after this, you must * check that there's enough space left! */ qb.npos = leng; for (i = 0; i < stmt->num_params; i++) { retval = ResolveOneParam(&qb, NULL); if (SQL_ERROR == retval) { QB_replace_SC_error(stmt, &qb, func); ret = FALSE; goto cleanup; } } leng = qb.npos; /* result format is text */ if (leng + sizeof(Int2) >= qb.str_alsize) { if (enlarge_query_statement(&qb, leng + sizeof(Int2)) <= 0) { ret = FALSE; goto cleanup; } } memset(qb.query_statement + leng, 0, sizeof(Int2)); leng += sizeof(Int2); /* now that we know the final length of the packet, fill that in */ inolog("bind leng=%d\n", leng); netleng = htonl((UInt4) leng); /* Network byte order */ memcpy(qb.query_statement, &netleng, sizeof(netleng)); if (CC_is_in_trans(conn) && !SC_accessed_db(stmt)) { if (SQL_ERROR == SetStatementSvp(stmt)) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal savepoint error in SendBindRequest", func); ret = FALSE; goto cleanup; } } SOCK_put_char(conn->sock, 'B'); /* Bind Message */ if (SOCK_get_errcode(conn->sock) != 0) { sockerr = TRUE; goto cleanup; } SOCK_put_n_char(conn->sock, qb.query_statement, leng); if (SOCK_get_errcode(conn->sock) != 0) sockerr = TRUE; cleanup: QB_Destructor(&qb); if (sockerr) { CC_set_error(conn, CONNECTION_COULD_NOT_SEND, "Could not send D Request to backend", func); CC_on_abort(conn, CONN_DEAD); ret = FALSE; } return ret; } #if (ODBCVER >= 0x0300) static BOOL ResolveNumericParam(const SQL_NUMERIC_STRUCT *ns, char *chrform) { static const int prec[] = {1, 3, 5, 8, 10, 13, 15, 17, 20, 22, 25, 27, 29, 32, 34, 37, 39}; Int4 i, j, k, ival, vlen, len, newlen; UCHAR calv[40]; const UCHAR *val = (const UCHAR *) ns->val; BOOL next_figure; inolog("C_NUMERIC [prec=%d scale=%d]", ns->precision, ns->scale); if (0 == ns->precision) { strcpy(chrform, "0"); return TRUE; } else if (ns->precision < prec[sizeof(Int4)]) { for (i = 0, ival = 0; i < sizeof(Int4) && prec[i] <= ns->precision; i++) { inolog("(%d)", val[i]); ival += (val[i] << (8 * i)); /* ns->val is little endian */ } inolog(" ival=%d,%d", ival, (val[3] << 24) | (val[2] << 16) | (val[1] << 8) | val[0]); if (0 == ns->scale) { if (0 == ns->sign) ival *= -1; sprintf(chrform, "%d", ival); } else if (ns->scale > 0) { Int4 i, div, o1val, o2val; for (i = 0, div = 1; i < ns->scale; i++) div *= 10; o1val = ival / div; o2val = ival % div; if (0 == ns->sign) sprintf(chrform, "-%d.%0*d", o1val, ns->scale, o2val); else sprintf(chrform, "%d.%0*d", o1val, ns->scale, o2val); } inolog(" convval=%s\n", chrform); return TRUE; } for (i = 0; i < SQL_MAX_NUMERIC_LEN && prec[i] <= ns->precision; i++) ; vlen = i; len = 0; memset(calv, 0, sizeof(calv)); inolog(" len1=%d", vlen); for (i = vlen - 1; i >= 0; i--) { for (j = len - 1; j >= 0; j--) { if (!calv[j]) continue; ival = (((Int4)calv[j]) << 8); calv[j] = (ival % 10); ival /= 10; calv[j + 1] += (ival % 10); ival /= 10; calv[j + 2] += (ival % 10); ival /= 10; calv[j + 3] += ival; for (k = j;; k++) { next_figure = FALSE; if (calv[k] > 0) { if (k >= len) len = k + 1; while (calv[k] > 9) { calv[k + 1]++; calv[k] -= 10; next_figure = TRUE; } } if (k >= j + 3 && !next_figure) break; } } ival = val[i]; if (!ival) continue; calv[0] += (ival % 10); ival /= 10; calv[1] += (ival % 10); ival /= 10; calv[2] += ival; for (j = 0;; j++) { next_figure = FALSE; if (calv[j] > 0) { if (j >= len) len = j + 1; while (calv[j] > 9) { calv[j + 1]++; calv[j] -= 10; next_figure = TRUE; } } if (j >= 2 && !next_figure) break; } } inolog(" len2=%d", len); newlen = 0; if (0 == ns->sign) chrform[newlen++] = '-'; if (i = len - 1, i < ns->scale) i = ns->scale; for (; i >= ns->scale; i--) chrform[newlen++] = calv[i] + '0'; if (ns->scale > 0) { chrform[newlen++] = '.'; for (; i >= 0; i--) chrform[newlen++] = calv[i] + '0'; } if (0 == len) chrform[newlen++] = '0'; chrform[newlen] = '\0'; inolog(" convval(2) len=%d %s\n", newlen, chrform); return TRUE; } #endif /* ODBCVER */ /* * */ static int ResolveOneParam(QueryBuild *qb, QueryParse *qp) { CSTR func = "ResolveOneParam"; ConnectionClass *conn = qb->conn; const APDFields *apdopts = qb->apdopts; const IPDFields *ipdopts = qb->ipdopts; PutDataInfo *pdata = qb->pdata; int param_number; char param_string[128], tmp[256], cbuf[PG_NUMERIC_MAX_PRECISION * 2]; /* seems big enough to handle the data in this function */ OID param_pgtype; SQLSMALLINT param_ctype, param_sqltype; SIMPLE_TIME st; time_t t; struct tm *tim; #ifdef HAVE_LOCALTIME_R struct tm tm; #endif /* HAVE_LOCALTIME_R */ SQLLEN used; char *buffer, *buf, *allocbuf = NULL, *lastadd = NULL; OID lobj_oid; int lobj_fd; SQLULEN offset = apdopts->param_offset_ptr ? *apdopts->param_offset_ptr : 0; size_t current_row = qb->current_row; int npos = 0; BOOL handling_large_object = FALSE, req_bind, add_quote = FALSE; ParameterInfoClass *apara; ParameterImplClass *ipara; BOOL outputDiscard, valueOutput; SDOUBLE dbv; SFLOAT flv; #if (ODBCVER >= 0x0300) SQL_INTERVAL_STRUCT *ivstruct; const char *ivsign; #endif /* ODBCVER */ RETCODE retval = SQL_ERROR; outputDiscard = (0 != (qb->flags & FLGB_DISCARD_OUTPUT)); valueOutput = (0 == (qb->flags & (FLGB_PRE_EXECUTING | FLGB_BUILDING_PREPARE_STATEMENT))); if (qb->proc_return < 0 && qb->stmt) qb->proc_return = qb->stmt->proc_return; /* * Its a '?' parameter alright */ param_number = ++qb->param_number; inolog("resolveOneParam %d(%d,%d)\n", param_number, ipdopts->allocated, apdopts->allocated); apara = NULL; ipara = NULL; if (param_number < apdopts->allocated) apara = apdopts->parameters + param_number; if (param_number < ipdopts->allocated) ipara = ipdopts->parameters + param_number; if ((!apara || !ipara) && valueOutput) { mylog("!!! The # of binded parameters (%d, %d) < the # of parameter markers %d\n", apdopts->allocated, ipdopts->allocated, param_number); qb->errormsg = "The # of binded parameters < the # of parameter markers"; qb->errornumber = STMT_COUNT_FIELD_INCORRECT; CVT_TERMINATE(qb); /* just in case */ return SQL_ERROR; } if (0 != (qb->flags & FLGB_EXECUTE_PREPARED) && (outputDiscard || param_number < qb->proc_return) ) { while (ipara && SQL_PARAM_OUTPUT == ipara->paramType) { apara = NULL; ipara = NULL; param_number = ++qb->param_number; if (param_number < apdopts->allocated) apara = apdopts->parameters + param_number; if (param_number < ipdopts->allocated) ipara = ipdopts->parameters + param_number; } } inolog("ipara=%p paramType=%d %d proc_return=%d\n", ipara, ipara ? ipara->paramType : -1, PG_VERSION_LT(conn, 8.1), qb->proc_return); if (param_number < qb->proc_return) { if (ipara && SQL_PARAM_OUTPUT != ipara->paramType) { qb->errormsg = "The function return value isn't marked as output parameter"; qb->errornumber = STMT_EXEC_ERROR; CVT_TERMINATE(qb); /* just in case */ return SQL_ERROR; } return SQL_SUCCESS; } if (ipara && SQL_PARAM_OUTPUT == ipara->paramType) { if (PG_VERSION_LT(conn, 8.1)) { qb->errormsg = "Output parameter isn't available before 8.1 version"; qb->errornumber = STMT_INTERNAL_ERROR; CVT_TERMINATE(qb); /* just in case */ return SQL_ERROR; } if (outputDiscard) { for (npos = qb->npos - 1; npos >= 0 && isspace((unsigned char) qb->query_statement[npos]) ; npos--) ; if (npos >= 0) { switch (qb->query_statement[npos]) { case ',': qb->npos = npos; qb->query_statement[npos] = '\0'; break; case '(': if (!qp) break; for (npos = qp->opos + 1; isspace((unsigned char) qp->statement[npos]); npos++) ; if (qp->statement[npos] == ',') qp->opos = npos; break; } } return SQL_SUCCESS_WITH_INFO; } } if (!apara || !ipara) { if (0 != (qb->flags & FLGB_PRE_EXECUTING)) { CVT_APPEND_STR(qb, "NULL"); qb->flags |= FLGB_INACCURATE_RESULT; return SQL_SUCCESS; } } if (0 != (qb->flags & FLGB_BUILDING_PREPARE_STATEMENT)) { char pnum[16]; #ifdef NOT_USED /* !! named parameter is unavailable !! */ if (ipara && SAFE_NAME(ipara->paramName)[0]) { CVT_APPEND_CHAR(qb, '"'); CVT_APPEND_STR(qb, SAFE_NAME(ipara->paramName)); CVT_APPEND_CHAR(qb, '"'); CVT_APPEND_STR(qb, " = "); } #endif /* NOT_USED */ qb->dollar_number++; sprintf(pnum, "$%d", qb->dollar_number); CVT_APPEND_STR(qb, pnum); return SQL_SUCCESS; } /* Assign correct buffers based on data at exec param or not */ if (apara->data_at_exec) { if (pdata->allocated != apdopts->allocated) extend_putdata_info(pdata, apdopts->allocated, TRUE); used = pdata->pdata[param_number].EXEC_used ? *pdata->pdata[param_number].EXEC_used : SQL_NTS; buffer = pdata->pdata[param_number].EXEC_buffer; if (pdata->pdata[param_number].lobj_oid) handling_large_object = TRUE; } else { UInt4 bind_size = apdopts->param_bind_type; UInt4 ctypelen; BOOL bSetUsed = FALSE; buffer = apara->buffer + offset; if (current_row > 0) { if (bind_size > 0) buffer += (bind_size * current_row); else if (ctypelen = ctype_length(apara->CType), ctypelen > 0) buffer += current_row * ctypelen; else buffer += current_row * apara->buflen; } if (apara->used || apara->indicator) { SQLULEN p_offset = offset; if (bind_size > 0) p_offset = offset + bind_size * current_row; else p_offset = offset + sizeof(SQLLEN) * current_row; if (apara->indicator) { used = *LENADDR_SHIFT(apara->indicator, p_offset); if (SQL_NULL_DATA == used) bSetUsed = TRUE; } if (!bSetUsed && apara->used) { used = *LENADDR_SHIFT(apara->used, p_offset); bSetUsed = TRUE; } } if (!bSetUsed) used = SQL_NTS; } req_bind = (0 != (FLGB_BUILDING_BIND_REQUEST & qb->flags)); /* Handle DEFAULT_PARAM parameter data. Should be NULL ? if (used == SQL_DEFAULT_PARAM) { return SQL_SUCCESS; } */ if (req_bind) { npos = qb->npos; ENLARGE_NEWSTATEMENT(qb, npos + 4); qb->npos += 4; } /* Handle NULL parameter data */ if ((ipara && SQL_PARAM_OUTPUT == ipara->paramType) || used == SQL_NULL_DATA || used == SQL_DEFAULT_PARAM) { if (req_bind) { DWORD len = htonl(-1); memcpy(qb->query_statement + npos, &len, sizeof(len)); } else CVT_APPEND_STR(qb, "NULL"); return SQL_SUCCESS; } /* * If no buffer, and it's not null, then what the hell is it? Just * leave it alone then. */ if (!buffer) { if (0 != (qb->flags & FLGB_PRE_EXECUTING)) { CVT_APPEND_STR(qb, "NULL"); qb->flags |= FLGB_INACCURATE_RESULT; return SQL_SUCCESS; } else if (!handling_large_object) { CVT_APPEND_CHAR(qb, '?'); return SQL_SUCCESS; } } param_ctype = apara->CType; param_sqltype = ipara->SQLType; param_pgtype = PIC_dsp_pgtype(qb->conn, *ipara); mylog("%s: from(fcType)=%d, to(fSqlType)=%d(%u)\n", func, param_ctype, param_sqltype, param_pgtype); /* replace DEFAULT with something we can use */ if (param_ctype == SQL_C_DEFAULT) { param_ctype = sqltype_to_default_ctype(conn, param_sqltype); if (param_ctype == SQL_C_WCHAR && CC_default_is_c(conn)) param_ctype =SQL_C_CHAR; } allocbuf = buf = NULL; param_string[0] = '\0'; cbuf[0] = '\0'; memset(&st, 0, sizeof(st)); t = SC_get_time(qb->stmt); #ifdef HAVE_LOCALTIME_R tim = localtime_r(&t, &tm); #else tim = localtime(&t); #endif /* HAVE_LOCALTIME_R */ st.m = tim->tm_mon + 1; st.d = tim->tm_mday; st.y = tim->tm_year + 1900; #if (ODBCVER >= 0x0300) ivstruct = (SQL_INTERVAL_STRUCT *) buffer; #endif /* ODBCVER */ /* Convert input C type to a neutral format */ switch (param_ctype) { case SQL_C_BINARY: buf = buffer; break; case SQL_C_CHAR: #ifdef WIN_UNICODE_SUPPORT if (SQL_NTS == used) used = strlen(buffer); allocbuf = malloc(WCLEN * (used + 1)); used = msgtowstr(NULL, buffer, (int) used, (LPWSTR) allocbuf, (int) (used + 1)); buf = ucs2_to_utf8((SQLWCHAR *) allocbuf, used, &used, FALSE); free(allocbuf); allocbuf = buf; #else buf = buffer; #endif /* WIN_UNICODE_SUPPORT */ break; #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: mylog("C_WCHAR=%s(%d)\n", buffer, used); buf = allocbuf = ucs2_to_utf8((SQLWCHAR *) buffer, used > 0 ? used / WCLEN : used, &used, FALSE); /* used *= WCLEN; */ break; #endif /* UNICODE_SUPPORT */ case SQL_C_DOUBLE: dbv = *((SDOUBLE *) buffer); #ifdef WIN32 if (_finite(dbv)) #endif /* WIN32 */ { sprintf(param_string, "%.15g", dbv); set_server_decimal_point(param_string); } #ifdef WIN32 else if (_isnan(dbv)) strcpy(param_string, NAN_STRING); else if (dbv < .0) strcpy(param_string, MINFINITY_STRING); else strcpy(param_string, INFINITY_STRING); #endif /* WIN32 */ break; case SQL_C_FLOAT: flv = *((SFLOAT *) buffer); #ifdef WIN32 if (_finite(flv)) #endif /* WIN32 */ { sprintf(param_string, "%.6g", flv); set_server_decimal_point(param_string); } #ifdef WIN32 else if (_isnan(flv)) strcpy(param_string, NAN_STRING); else if (flv < .0) strcpy(param_string, MINFINITY_STRING); else strcpy(param_string, INFINITY_STRING); #endif /* WIN32 */ break; case SQL_C_SLONG: case SQL_C_LONG: sprintf(param_string, FORMAT_INTEGER, *((SQLINTEGER *) buffer)); break; #if (ODBCVER >= 0x0300) && defined(ODBCINT64) case SQL_C_SBIGINT: case SQL_BIGINT: /* Is this needed ? */ sprintf(param_string, FORMATI64, *((SQLBIGINT *) buffer)); break; case SQL_C_UBIGINT: sprintf(param_string, FORMATI64U, *((SQLUBIGINT *) buffer)); break; #endif /* ODBCINT64 */ case SQL_C_SSHORT: case SQL_C_SHORT: sprintf(param_string, "%d", *((SQLSMALLINT *) buffer)); break; case SQL_C_STINYINT: case SQL_C_TINYINT: sprintf(param_string, "%d", *((SCHAR *) buffer)); break; case SQL_C_ULONG: sprintf(param_string, FORMAT_UINTEGER, *((SQLUINTEGER *) buffer)); break; case SQL_C_USHORT: sprintf(param_string, "%u", *((SQLUSMALLINT *) buffer)); break; case SQL_C_UTINYINT: sprintf(param_string, "%u", *((UCHAR *) buffer)); break; case SQL_C_BIT: { int i = *((UCHAR *) buffer); sprintf(param_string, "%d", i ? 1 : 0); break; } case SQL_C_DATE: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_DATE: /* 91 */ #endif { DATE_STRUCT *ds = (DATE_STRUCT *) buffer; st.m = ds->month; st.d = ds->day; st.y = ds->year; break; } case SQL_C_TIME: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_TIME: /* 92 */ #endif { TIME_STRUCT *ts = (TIME_STRUCT *) buffer; st.hh = ts->hour; st.mm = ts->minute; st.ss = ts->second; break; } case SQL_C_TIMESTAMP: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_TIMESTAMP: /* 93 */ #endif { TIMESTAMP_STRUCT *tss = (TIMESTAMP_STRUCT *) buffer; st.m = tss->month; st.d = tss->day; st.y = tss->year; st.hh = tss->hour; st.mm = tss->minute; st.ss = tss->second; st.fr = tss->fraction; mylog("m=%d,d=%d,y=%d,hh=%d,mm=%d,ss=%d\n", st.m, st.d, st.y, st.hh, st.mm, st.ss); break; } #if (ODBCVER >= 0x0300) case SQL_C_NUMERIC: if (ResolveNumericParam((SQL_NUMERIC_STRUCT *) buffer, param_string)) break; case SQL_C_INTERVAL_YEAR: ivsign = ivstruct->interval_sign ? "-" : ""; sprintf(param_string, "%s%d years", ivsign, ivstruct->intval.year_month.year); break; case SQL_C_INTERVAL_MONTH: case SQL_C_INTERVAL_YEAR_TO_MONTH: ivsign = ivstruct->interval_sign ? "-" : ""; sprintf(param_string, "%s%d years %s%d mons", ivsign, ivstruct->intval.year_month.year, ivsign, ivstruct->intval.year_month.month); break; case SQL_C_INTERVAL_DAY: ivsign = ivstruct->interval_sign ? "-" : ""; sprintf(param_string, "%s%d days", ivsign, ivstruct->intval.day_second.day); break; case SQL_C_INTERVAL_HOUR: case SQL_C_INTERVAL_DAY_TO_HOUR: ivsign = ivstruct->interval_sign ? "-" : ""; sprintf(param_string, "%s%d days %s%02d:00:00", ivsign, ivstruct->intval.day_second.day, ivsign, ivstruct->intval.day_second.hour); break; case SQL_C_INTERVAL_MINUTE: case SQL_C_INTERVAL_HOUR_TO_MINUTE: case SQL_C_INTERVAL_DAY_TO_MINUTE: ivsign = ivstruct->interval_sign ? "-" : ""; sprintf(param_string, "%s%d days %s%02d:%02d:00", ivsign, ivstruct->intval.day_second.day, ivsign, ivstruct->intval.day_second.hour, ivstruct->intval.day_second.minute); break; case SQL_C_INTERVAL_SECOND: case SQL_C_INTERVAL_DAY_TO_SECOND: case SQL_C_INTERVAL_HOUR_TO_SECOND: case SQL_C_INTERVAL_MINUTE_TO_SECOND: ivsign = ivstruct->interval_sign ? "-" : ""; sprintf(param_string, "%s%d days %s%02d:%02d:%02d", ivsign, ivstruct->intval.day_second.day, ivsign, ivstruct->intval.day_second.hour, ivstruct->intval.day_second.minute, ivstruct->intval.day_second.second); if (ivstruct->intval.day_second.fraction > 0) { int fraction = ivstruct->intval.day_second.fraction, prec = apara->precision; while (fraction % 10 == 0) { fraction /= 10; prec--; } sprintf(¶m_string[strlen(param_string)], ".%0*d", prec, fraction); } break; #endif #if (ODBCVER >= 0x0350) case SQL_C_GUID: { /* * SQLGUID.Data1 is an "unsigned long" on some platforms, and * "unsigned int" on others. */ SQLGUID *g = (SQLGUID *) buffer; snprintf (param_string, sizeof(param_string), "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", (unsigned int) g->Data1, g->Data2, g->Data3, g->Data4[0], g->Data4[1], g->Data4[2], g->Data4[3], g->Data4[4], g->Data4[5], g->Data4[6], g->Data4[7]); } break; #endif default: /* error */ qb->errormsg = "Unrecognized C_parameter type in copy_statement_with_parameters"; qb->errornumber = STMT_NOT_IMPLEMENTED_ERROR; CVT_TERMINATE(qb); /* just in case */ retval = SQL_ERROR; goto cleanup; } /* * Now that the input data is in a neutral format, convert it to * the desired output format (sqltype) */ /* Special handling NULL string For FOXPRO */ mylog("cvt_null_date_string=%d pgtype=%d buf=%p\n", conn->connInfo.cvt_null_date_string, param_pgtype, buf); if (conn->connInfo.cvt_null_date_string > 0 && (PG_TYPE_DATE == param_pgtype || PG_TYPE_DATETIME == param_pgtype || PG_TYPE_TIMESTAMP_NO_TMZONE == param_pgtype) && NULL != buf && ( (SQL_C_CHAR == param_ctype && '\0' == buf[0]) #ifdef UNICODE_SUPPORT || (SQL_C_WCHAR ==param_ctype && '\0' == buf[0] && '\0' == buf[1]) #endif /* UNICODE_SUPPORT */ )) { if (req_bind) { DWORD len = htonl(-1); memcpy(qb->query_statement + npos, &len, sizeof(len)); } else CVT_APPEND_STR(qb, "NULL"); retval = SQL_SUCCESS; goto cleanup; } if (!req_bind) { switch (param_sqltype) { case SQL_INTEGER: case SQL_SMALLINT: break; case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: #ifdef UNICODE_SUPPORT case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: #endif /* UNICODE_SUPPORT */ mylog("buf=%p flag=%d\n", buf, qb->flags); if (buf && (qb->flags & FLGB_LITERAL_EXTENSION) != 0) { CVT_APPEND_CHAR(qb, LITERAL_EXT); } default: CVT_APPEND_CHAR(qb, LITERAL_QUOTE); add_quote = TRUE; break; } } switch (param_sqltype) { case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: #ifdef UNICODE_SUPPORT case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: #endif /* UNICODE_SUPPORT */ switch (param_pgtype) { case PG_TYPE_BOOL: /* consider True is -1 case */ if (NULL != buf) { if ('-' == buf[0] && '1' == buf[1]) strcpy(buf, "1"); } else if ('-' == param_string[0] && '1' == param_string[1]) strcpy(param_string, "1"); break; case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_NUMERIC: if (NULL != buf) set_server_decimal_point(buf); else set_server_decimal_point(param_string); break; } /* it was a SQL_C_CHAR */ if (buf) CVT_SPECIAL_CHARS(qb, buf, used); /* it was a numeric type */ else if (param_string[0] != '\0') CVT_APPEND_STR(qb, param_string); /* it was date,time,timestamp -- use m,d,y,hh,mm,ss */ else { snprintf(tmp, sizeof(tmp), "%.4d-%.2d-%.2d %.2d:%.2d:%.2d", st.y, st.m, st.d, st.hh, st.mm, st.ss); CVT_APPEND_STR(qb, tmp); } break; case SQL_DATE: #if (ODBCVER >= 0x0300) case SQL_TYPE_DATE: /* 91 */ #endif if (buf) { /* copy char data to time */ my_strcpy(cbuf, sizeof(cbuf), buf, used); parse_datetime(cbuf, &st); } if (st.y < 0) sprintf(tmp, "%.4d-%.2d-%.2d BC", -st.y, st.m, st.d); else sprintf(tmp, "%.4d-%.2d-%.2d", st.y, st.m, st.d); lastadd = "::date"; CVT_APPEND_STR(qb, tmp); break; case SQL_TIME: #if (ODBCVER >= 0x0300) case SQL_TYPE_TIME: /* 92 */ #endif if (buf) { /* copy char data to time */ my_strcpy(cbuf, sizeof(cbuf), buf, used); parse_datetime(cbuf, &st); } sprintf(tmp, "%.2d:%.2d:%.2d", st.hh, st.mm, st.ss); lastadd = "::time"; CVT_APPEND_STR(qb, tmp); break; case SQL_TIMESTAMP: #if (ODBCVER >= 0x0300) case SQL_TYPE_TIMESTAMP: /* 93 */ #endif if (buf) { my_strcpy(cbuf, sizeof(cbuf), buf, used); parse_datetime(cbuf, &st); } /* * sprintf(tmp, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d", st.y, * st.m, st.d, st.hh, st.mm, st.ss); */ /* Time zone stuff is unreliable */ stime2timestamp(&st, tmp, USE_ZONE, PG_VERSION_GE(conn, 7.2) ? 6 : 0); lastadd = "::timestamp"; CVT_APPEND_STR(qb, tmp); break; case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: switch (param_ctype) { case SQL_C_BINARY: break; case SQL_C_CHAR: #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: #endif /* UNICODE_SUPPORT */ switch (used) { case SQL_NTS: used = strlen(buf); break; } allocbuf = malloc(used / 2 + 1); if (allocbuf) { pg_hex2bin(buf, allocbuf, used); buf = allocbuf; used /= 2; } break; default: qb->errormsg = "Could not convert the ctype to binary type"; qb->errornumber = STMT_EXEC_ERROR; retval = SQL_ERROR; goto cleanup; } if (param_pgtype == PG_TYPE_BYTEA) { if (0 != (qb->flags & FLGB_BINARY_AS_POSSIBLE)) { mylog("sending binary data leng=%d\n", used); CVT_APPEND_DATA(qb, buf, used); } else { /* non-ascii characters should be * converted to octal */ mylog("SQL_VARBINARY: about to call convert_to_pgbinary, used = %d\n", used); CVT_APPEND_BINARY(qb, buf, used); } break; } if (PG_TYPE_OID == param_pgtype && conn->lo_is_domain) ; else if (param_pgtype != conn->lobj_type) { qb->errormsg = "Could not convert binary other than LO type"; qb->errornumber = STMT_EXEC_ERROR; retval = SQL_ERROR; goto cleanup; } if (apara->data_at_exec) lobj_oid = pdata->pdata[param_number].lobj_oid; else { BOOL is_in_trans_at_entry = CC_is_in_trans(conn); /* begin transaction if needed */ if (!is_in_trans_at_entry) { if (!CC_begin(conn)) { qb->errormsg = "Could not begin (in-line) a transaction"; qb->errornumber = STMT_EXEC_ERROR; retval = SQL_ERROR; goto cleanup; } } /* store the oid */ lobj_oid = odbc_lo_creat(conn, INV_READ | INV_WRITE); if (lobj_oid == 0) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "Couldnt create (in-line) large object."; retval = SQL_ERROR; goto cleanup; } /* store the fd */ lobj_fd = odbc_lo_open(conn, lobj_oid, INV_WRITE); if (lobj_fd < 0) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "Couldnt open (in-line) large object for writing."; retval = SQL_ERROR; goto cleanup; } retval = odbc_lo_write(conn, lobj_fd, buffer, (Int4) used); odbc_lo_close(conn, lobj_fd); /* commit transaction if needed */ if (!is_in_trans_at_entry) { if (!CC_commit(conn)) { qb->errormsg = "Could not commit (in-line) a transaction"; qb->errornumber = STMT_EXEC_ERROR; retval = SQL_ERROR; goto cleanup; } } } /* * the oid of the large object -- just put that in for the * parameter marker -- the data has already been sent to * the large object */ sprintf(param_string, "%u", lobj_oid); lastadd = "::lo"; CVT_APPEND_STR(qb, param_string); break; /* * because of no conversion operator for bool and int4, * SQL_BIT */ /* must be quoted (0 or 1 is ok to use inside the quotes) */ case SQL_REAL: if (buf) my_strcpy(param_string, sizeof(param_string), buf, used); set_server_decimal_point(param_string); lastadd = "::float4"; CVT_APPEND_STR(qb, param_string); break; case SQL_FLOAT: case SQL_DOUBLE: if (buf) my_strcpy(param_string, sizeof(param_string), buf, used); set_server_decimal_point(param_string); lastadd = "::float8"; CVT_APPEND_STR(qb, param_string); break; case SQL_NUMERIC: if (buf) { my_strcpy(cbuf, sizeof(cbuf), buf, used); } else sprintf(cbuf, "%s", param_string); CVT_APPEND_STR(qb, cbuf); break; default: /* a numeric type or SQL_BIT */ if (buf) { switch (used) { case SQL_NULL_DATA: break; case SQL_NTS: CVT_APPEND_STR(qb, buf); break; default: CVT_APPEND_DATA(qb, buf, used); } } else CVT_APPEND_STR(qb, param_string); break; } if (add_quote) { CVT_APPEND_CHAR(qb, LITERAL_QUOTE); if (lastadd) CVT_APPEND_STR(qb, lastadd); } if (req_bind) { UInt4 slen = htonl((UInt4) (qb->npos - npos - 4)); memcpy(qb->query_statement + npos, &slen, sizeof(slen)); } retval = SQL_SUCCESS; cleanup: if (allocbuf) free(allocbuf); return retval; } static const char * mapFunction(const char *func, int param_count) { int i; for (i = 0; mapFuncs[i][0]; i++) { if (mapFuncs[i][0][0] == '%') { if (mapFuncs[i][0][1] - '0' == param_count && !stricmp(mapFuncs[i][0] + 2, func)) return mapFuncs[i][1]; } else if (!stricmp(mapFuncs[i][0], func)) return mapFuncs[i][1]; } return NULL; } /* * processParameters() * Process function parameters and work with embedded escapes sequences. */ static int processParameters(QueryParse *qp, QueryBuild *qb, size_t *output_count, SQLLEN param_pos[][2]) { CSTR func = "processParameters"; int retval, innerParenthesis, param_count; BOOL stop; /* begin with outer '(' */ innerParenthesis = 0; param_count = 0; if (NULL != output_count) *output_count = 0; stop = FALSE; for (; F_OldPos(qp) < qp->stmt_len; F_OldNext(qp)) { retval = inner_process_tokens(qp, qb); if (retval == SQL_ERROR) return retval; if (ENCODE_STATUS(qp->encstr) != 0) continue; if (qp->in_identifier || qp->in_literal || qp->in_escape) continue; switch (F_OldChar(qp)) { case ',': if (1 == innerParenthesis) { param_pos[param_count][1] = F_NewPos(qb) - 2; param_count++; param_pos[param_count][0] = F_NewPos(qb); param_pos[param_count][1] = -1; } break; case '(': if (0 == innerParenthesis) { param_pos[param_count][0] = F_NewPos(qb); param_pos[param_count][1] = -1; } innerParenthesis++; break; case ')': innerParenthesis--; if (0 == innerParenthesis) { param_pos[param_count][1] = F_NewPos(qb) - 2; param_count++; param_pos[param_count][0] = param_pos[param_count][1] = -1; } if (output_count) *output_count = F_NewPos(qb); break; case ODBC_ESCAPE_END: stop = (0 == innerParenthesis); break; } if (stop) /* returns with the last } position */ break; } if (param_pos[param_count][0] >= 0) { mylog("%s closing ) not found %d\n", func, innerParenthesis); qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "processParameters closing ) not found"; return SQL_ERROR; } else if (1 == param_count) /* the 1 parameter is really valid ? */ { BOOL param_exist = FALSE; SQLLEN i; for (i = param_pos[0][0]; i <= param_pos[0][1]; i++) { if (!isspace((unsigned char) qb->query_statement[i])) { param_exist = TRUE; break; } } if (!param_exist) { param_pos[0][0] = param_pos[0][1] = -1; } } return SQL_SUCCESS; } /* * convert_escape() * This function doesn't return a pointer to static memory any longer ! */ static int convert_escape(QueryParse *qp, QueryBuild *qb) { CSTR func = "convert_escape"; ConnectionClass *conn = qb->conn; RETCODE retval = SQL_SUCCESS; char buf[1024], buf_small[128], key[65]; UCHAR ucv; UInt4 prtlen; QueryBuild nqb; BOOL nqb_is_valid = FALSE; if (F_OldChar(qp) == ODBC_ESCAPE_START) /* skip the first { */ F_OldNext(qp); /* Separate off the key, skipping leading and trailing whitespace */ while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv)) F_OldNext(qp); /* * procedure calls */ /* '?=' to accept return values exists ? */ if (F_OldChar(qp) == '?') { qb->param_number++; qb->proc_return = 1; if (qb->stmt) qb->stmt->proc_return = 1; while (isspace((UCHAR) qp->statement[++qp->opos])); if (F_OldChar(qp) != '=') { F_OldPrior(qp); return SQL_SUCCESS; } while (isspace((UCHAR) qp->statement[++qp->opos])); } /** if (qp->statement_type == STMT_TYPE_PROCCALL) { int lit_call_len = 4; // '?=' to accept return values exists ? if (F_OldChar(qp) == '?') { qb->param_number++; qb->proc_return = 1; if (qb->stmt) qb->stmt->proc_return = 1; while (isspace((UCHAR) qp->statement[++qp->opos])); if (F_OldChar(qp) != '=') { F_OldPrior(qp); return SQL_SUCCESS; } while (isspace((UCHAR) qp->statement[++qp->opos])); } if (strnicmp(F_OldPtr(qp), "call", lit_call_len) || !isspace((UCHAR) F_OldPtr(qp)[lit_call_len])) { F_OldPrior(qp); return SQL_SUCCESS; } qp->opos += lit_call_len; if (qb->num_io_params > 1 || (0 == qb->proc_return && PG_VERSION_GE(conn, 7.3))) CVT_APPEND_STR(qb, "SELECT * FROM"); else CVT_APPEND_STR(qb, "SELECT"); if (my_strchr(conn, F_OldPtr(qp), '(')) qp->proc_no_param = FALSE; return SQL_SUCCESS; } **/ sscanf(F_OldPtr(qp), "%32s", key); while ((ucv = F_OldChar(qp)) != '\0' && (!isspace(ucv))) F_OldNext(qp); while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv)) F_OldNext(qp); /* Avoid the concatenation of the function name with the previous word. Aceto */ if (stricmp(key, "call") == 0) { Int4 funclen; const char *nextdel; if (SQL_ERROR == QB_start_brace(qb)) { retval = SQL_ERROR; goto cleanup; } if (qb->num_io_params > 1 || (0 == qb->proc_return && PG_VERSION_GE(conn, 7.3))) CVT_APPEND_STR(qb, "SELECT * FROM "); else CVT_APPEND_STR(qb, "SELECT "); funclen = findIdentifier(F_OldPtr(qp), qb->ccsc, &nextdel); if (nextdel && ODBC_ESCAPE_END == *nextdel) { CVT_APPEND_DATA(qb, F_OldPtr(qp), funclen); CVT_APPEND_STR(qb, "()"); if (SQL_ERROR == QB_end_brace(qb)) { retval = SQL_ERROR; goto cleanup; } /* positioned at } */ qp->opos += (nextdel - F_OldPtr(qp)); } else { /* Continue at inner_process_tokens loop */ F_OldPrior(qp); return SQL_SUCCESS; } } else if (stricmp(key, "d") == 0) { /* Literal; return the escape part adding type cast */ F_ExtractOldTo(qp, buf_small, ODBC_ESCAPE_END, sizeof(buf_small)); if (PG_VERSION_LT(conn, 7.3)) prtlen = snprintf(buf, sizeof(buf), "%s", buf_small); else prtlen = snprintf(buf, sizeof(buf), "%s::date", buf_small); CVT_APPEND_DATA(qb, buf, prtlen); retval = QB_append_space_to_separate_identifiers(qb, qp); } else if (stricmp(key, "t") == 0) { /* Literal; return the escape part adding type cast */ F_ExtractOldTo(qp, buf_small, ODBC_ESCAPE_END, sizeof(buf_small)); prtlen = snprintf(buf, sizeof(buf), "%s::time", buf_small); CVT_APPEND_DATA(qb, buf, prtlen); retval = QB_append_space_to_separate_identifiers(qb, qp); } else if (stricmp(key, "ts") == 0) { /* Literal; return the escape part adding type cast */ F_ExtractOldTo(qp, buf_small, ODBC_ESCAPE_END, sizeof(buf_small)); if (PG_VERSION_LT(conn, 7.1)) prtlen = snprintf(buf, sizeof(buf), "%s::datetime", buf_small); else prtlen = snprintf(buf, sizeof(buf), "%s::timestamp", buf_small); CVT_APPEND_DATA(qb, buf, prtlen); retval = QB_append_space_to_separate_identifiers(qb, qp); } else if (stricmp(key, "oj") == 0) /* {oj syntax support for 7.1 * servers */ { if (qb->stmt) SC_set_outer_join(qb->stmt); retval = QB_start_brace(qb); /* Continue at inner_process_tokens loop */ F_OldPrior(qp); goto cleanup; } else if (stricmp(key, "escape") == 0) /* like escape syntax support for 7.1+ servers */ { /* Literal; return the escape part adding type cast */ F_ExtractOldTo(qp, buf_small, ODBC_ESCAPE_END, sizeof(buf_small)); prtlen = snprintf(buf, sizeof(buf), "%s %s", key, buf_small); CVT_APPEND_DATA(qb, buf, prtlen); retval = QB_append_space_to_separate_identifiers(qb, qp); } else if (stricmp(key, "fn") == 0) { const char *mapExpr; int i, param_count; SQLLEN from, to; size_t param_consumed; SQLLEN param_pos[16][2]; BOOL cvt_func = FALSE; /* Separate off the func name, skipping leading and trailing whitespace */ i = 0; while ((ucv = F_OldChar(qp)) != '\0' && ucv != '(' && (!isspace(ucv))) { if (i < sizeof(key) - 1) key[i++] = ucv; F_OldNext(qp); } key[i] = '\0'; while ((ucv = F_OldChar(qp)) != '\0' && isspace(ucv)) F_OldNext(qp); /* * We expect left parenthesis here, else return fn body as-is * since it is one of those "function constants". */ if (F_OldChar(qp) != '(') { CVT_APPEND_STR(qb, key); goto cleanup; } /* * Process parameter list and inner escape * sequences * Aceto 2002-01-29 */ QB_initialize_copy(&nqb, qb, 1024); nqb_is_valid = TRUE; if (retval = processParameters(qp, &nqb, ¶m_consumed, param_pos), retval == SQL_ERROR) { qb->errornumber = nqb.errornumber; qb->errormsg = nqb.errormsg; goto cleanup; } for (param_count = 0;; param_count++) { if (param_pos[param_count][0] < 0) break; } if (param_count == 1 && param_pos[0][1] < param_pos[0][0]) param_count = 0; mapExpr = NULL; if (stricmp(key, "convert") == 0) cvt_func = TRUE; else mapExpr = mapFunction(key, param_count); if (cvt_func) { if (2 == param_count) { BOOL add_cast = FALSE, add_quote = FALSE; const char *pptr; from = param_pos[0][0]; to = param_pos[0][1]; for (pptr = nqb.query_statement + from; *pptr && isspace((unsigned char) *pptr); pptr++) ; if (LITERAL_QUOTE == *pptr) ; else if ('-' == *pptr) add_quote = TRUE; else if (isdigit((unsigned char) *pptr)) add_quote = TRUE; else add_cast = TRUE; if (add_quote) CVT_APPEND_CHAR(qb, LITERAL_QUOTE); else if (add_cast) CVT_APPEND_CHAR(qb, '('); CVT_APPEND_DATA(qb, nqb.query_statement + from, to - from + 1); if (add_quote) CVT_APPEND_CHAR(qb, LITERAL_QUOTE); else if (add_cast) { const char *cast_form = NULL; CVT_APPEND_CHAR(qb, ')'); from = param_pos[1][0]; to = param_pos[1][1]; if (to < from + 9) { char num[10]; memcpy(num, nqb.query_statement + from, to - from + 1); num[to - from + 1] = '\0'; mylog("%d-%d num=%s SQL_BIT=%d\n", to, from, num, SQL_BIT); switch (atoi(num)) { case SQL_BIT: cast_form = "boolean"; break; case SQL_INTEGER: cast_form = "int4"; break; } } if (NULL != cast_form) { CVT_APPEND_STR(qb, "::"); CVT_APPEND_STR(qb, cast_form); } } } else { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "convert param count must be 2"; retval = SQL_ERROR; } } else if (mapExpr == NULL) { CVT_APPEND_STR(qb, key); CVT_APPEND_DATA(qb, nqb.query_statement, nqb.npos); } else { const char *mapptr; SQLLEN paramlen; int pidx; for (prtlen = 0, mapptr = mapExpr; *mapptr; mapptr++) { if (*mapptr != '$') { CVT_APPEND_CHAR(qb, *mapptr); continue; } mapptr++; if (*mapptr == '*') { from = 1; to = param_consumed - 2; } else if (isdigit((unsigned char) *mapptr)) { pidx = *mapptr - '0' - 1; if (pidx < 0 || param_pos[pidx][0] < 0) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "param not found"; qlog("%s %dth param not found for the expression %s\n", pidx + 1, mapExpr); retval = SQL_ERROR; break; } from = param_pos[pidx][0]; to = param_pos[pidx][1]; } else { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "internal expression error"; qlog("%s internal expression error %s\n", func, mapExpr); retval = SQL_ERROR; break; } paramlen = to - from + 1; if (paramlen > 0) CVT_APPEND_DATA(qb, nqb.query_statement + from, paramlen); } } if (0 == qb->errornumber) { qb->errornumber = nqb.errornumber; qb->errormsg = nqb.errormsg; } if (SQL_ERROR != retval) { qb->param_number = nqb.param_number; qb->flags = nqb.flags; } } else { /* Bogus key, leave untranslated */ retval = SQL_ERROR; } cleanup: if (nqb_is_valid) QB_Destructor(&nqb); return retval; } BOOL convert_money(const char *s, char *sout, size_t soutmax) { size_t i = 0, out = 0; for (i = 0; s[i]; i++) { if (s[i] == '$' || s[i] == ',' || s[i] == ')') ; /* skip these characters */ else { if (out + 1 >= soutmax) return FALSE; /* sout is too short */ if (s[i] == '(') sout[out++] = '-'; else sout[out++] = s[i]; } } sout[out] = '\0'; return TRUE; } /* * This function parses a character string for date/time info and fills in SIMPLE_TIME * It does not zero out SIMPLE_TIME in case it is desired to initialize it with a value */ char parse_datetime(const char *buf, SIMPLE_TIME *st) { int y, m, d, hh, mm, ss; int nf; y = m = d = hh = mm = ss = 0; st->fr = 0; st->infinity = 0; /* escape sequence ? */ if (buf[0] == ODBC_ESCAPE_START) { while (*(++buf) && *buf != LITERAL_QUOTE); if (!(*buf)) return FALSE; buf++; } if (buf[4] == '-') /* year first */ nf = sscanf(buf, "%4d-%2d-%2d %2d:%2d:%2d", &y, &m, &d, &hh, &mm, &ss); else nf = sscanf(buf, "%2d-%2d-%4d %2d:%2d:%2d", &m, &d, &y, &hh, &mm, &ss); if (nf == 5 || nf == 6) { st->y = y; st->m = m; st->d = d; st->hh = hh; st->mm = mm; st->ss = ss; return TRUE; } if (buf[4] == '-') /* year first */ nf = sscanf(buf, "%4d-%2d-%2d", &y, &m, &d); else nf = sscanf(buf, "%2d-%2d-%4d", &m, &d, &y); if (nf == 3) { st->y = y; st->m = m; st->d = d; return TRUE; } nf = sscanf(buf, "%2d:%2d:%2d", &hh, &mm, &ss); if (nf == 2 || nf == 3) { st->hh = hh; st->mm = mm; st->ss = ss; return TRUE; } return FALSE; } /* Change linefeed to carriage-return/linefeed */ size_t convert_linefeeds(const char *si, char *dst, size_t max, BOOL convlf, BOOL *changed) { size_t i = 0, out = 0; if (max == 0) max = 0xffffffff; *changed = FALSE; for (i = 0; si[i] && out < max - 1; i++) { if (convlf && si[i] == '\n') { /* Only add the carriage-return if needed */ if (i > 0 && PG_CARRIAGE_RETURN == si[i - 1]) { if (dst) dst[out++] = si[i]; else out++; continue; } *changed = TRUE; if (dst) { dst[out++] = PG_CARRIAGE_RETURN; dst[out++] = '\n'; } else out += 2; } else { if (dst) dst[out++] = si[i]; else out++; } } if (dst) dst[out] = '\0'; return out; } /* * Change carriage-return/linefeed to just linefeed * Plus, escape any special characters. */ size_t convert_special_chars(const char *si, char *dst, SQLLEN used, UInt4 flags, int ccsc, int escape_in_literal) { size_t i = 0, out = 0, max; char *p = NULL, literal_quote = LITERAL_QUOTE, tchar; encoded_str encstr; BOOL convlf = (0 != (flags & FLGB_CONVERT_LF)), double_special = (0 == (flags & FLGB_BUILDING_BIND_REQUEST)); if (used == SQL_NTS) max = strlen(si); else max = used; if (dst) { p = dst; p[0] = '\0'; } encoded_str_constr(&encstr, ccsc, si); for (i = 0; i < max && si[i]; i++) { tchar = encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) { if (p) p[out] = tchar; out++; continue; } if (convlf && /* CR/LF -> LF */ PG_CARRIAGE_RETURN == tchar && PG_LINEFEED == si[i + 1]) continue; else if (double_special && /* double special chars ? */ (tchar == literal_quote || tchar == escape_in_literal)) { if (p) p[out++] = tchar; else out++; } if (p) p[out++] = tchar; else out++; } if (p) p[out] = '\0'; return out; } #ifdef NOT_USED #define CVT_CRLF_TO_LF 1L #define DOUBLE_LITERAL_QUOTE (1L << 1) #define DOUBLE_ESCAPE_IN_LITERAL (1L << 2) static int convert_text_field(const char *si, char *dst, int used, int ccsc, int escape_in_literal, UInt4 *flags) { size_t i = 0, out = 0, max; UInt4 iflags = *flags; char *p = NULL, literal_quote = LITERAL_QUOTE, tchar; encoded_str encstr; BOOL convlf = (0 != (iflags & CVT_CRLF_TO_LF)), double_literal_quote = (0 != (iflags & DOUBLE_LITERAL_QUOTE)), double_escape_in_literal = (0 != (iflags & DOUBLE_ESCAPE_IN_LITERAL)); if (SQL_NTS == used) max = strlen(si); else max = used; if (0 == iflags) { if (dst) strncpy_null(dst, si, max + 1); else return max; } if (dst) { p = dst; p[0] = '\0'; } encoded_str_constr(&encstr, ccsc, si); *flags = 0; for (i = 0; i < max && si[i]; i++) { tchar = encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) { if (p) p[out] = tchar; out++; continue; } if (convlf && /* CR/LF -> LF */ PG_CARRIAGE_RETURN == tchar && PG_LINEFEED == si[i + 1]) { *flags |= CVT_CRLF_TO_LF; continue; } else if (double_literal_quote && /* double literal quote ? */ tchar == literal_quote) { if (p) p[out] = tchar; out++; *flags |= DOUBLE_LITERAL_QUOTE; } else if (double_escape_in_literal && /* double escape ? */ tchar == escape_in_literal) { if (p) p[out] = tchar; out++; *flags |= DOUBLE_ESCAPE_IN_LITERAL; } if (p) p[out] = tchar; out++; } if (p) p[out] = '\0'; return out; } #endif /* NOT_USED */ /* !!! Need to implement this function !!! */ int convert_pgbinary_to_char(const char *value, char *rgbValue, ssize_t cbValueMax) { mylog("convert_pgbinary_to_char: value = '%s'\n", value); strncpy_null(rgbValue, value, cbValueMax); return 0; } static int conv_from_octal(const char *s) { ssize_t i; int y = 0; for (i = 1; i <= 3; i++) y += (s[i] - '0') << (3 * (3 - i)); return y; } /* convert octal escapes to bytes */ size_t convert_from_pgbinary(const char *value, char *rgbValue, SQLLEN cbValueMax) { size_t i, ilen = strlen(value); size_t o = 0; for (i = 0; i < ilen;) { if (value[i] == BYTEA_ESCAPE_CHAR) { if (value[i + 1] == BYTEA_ESCAPE_CHAR) { if (rgbValue) rgbValue[o] = value[i]; o++; i += 2; } else if (value[i + 1] == 'x') { i += 2; if (i < ilen) { ilen -= i; if (rgbValue) pg_hex2bin(value + i, rgbValue + o, ilen); o += ilen / 2; } break; } else { if (rgbValue) rgbValue[o] = conv_from_octal(&value[i]); o++; i += 4; } } else { if (rgbValue) rgbValue[o] = value[i]; o++; i++; } /** if (rgbValue) mylog("convert_from_pgbinary: i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]); ***/ } if (rgbValue) rgbValue[o] = '\0'; /* extra protection */ mylog("convert_from_pgbinary: in=%d, out = %d\n", ilen, o); return o; } static UInt2 conv_to_octal(UCHAR val, char *octal, char escape_ch) { int i, pos = 0, len; if (escape_ch) octal[pos++] = escape_ch; octal[pos] = BYTEA_ESCAPE_CHAR; len = 4 + pos; octal[len] = '\0'; for (i = len - 1; i > pos; i--) { octal[i] = (val & 7) + '0'; val >>= 3; } return (UInt2) len; } static char * conv_to_octal2(UCHAR val, char *octal) { int i; octal[0] = BYTEA_ESCAPE_CHAR; octal[4] = '\0'; for (i = 3; i > 0; i--) { octal[i] = (val & 7) + '0'; val >>= 3; } return octal; } /* convert non-ascii bytes to octal escape sequences */ static size_t convert_to_pgbinary(const char *in, char *out, size_t len, QueryBuild *qb) { CSTR func = "convert_to_pgbinary"; UCHAR inc; size_t i, o = 0; char escape_in_literal = CC_get_escape(qb->conn); BOOL esc_double = (0 == (qb->flags & FLGB_BUILDING_BIND_REQUEST) && 0 != escape_in_literal); /* use hex format for 9.0 or later servers */ if (0 != (qb->flags & FLGB_HEX_BIN_FORMAT)) { if (esc_double) out[o++] = escape_in_literal; out[o++] = '\\'; out[o++] = 'x'; o += pg_bin2hex(in, out + o, len); return o; } for (i = 0; i < len; i++) { inc = in[i]; inolog("%s: in[%d] = %d, %c\n", func, i, inc, inc); if (inc < 128 && (isalnum(inc) || inc == ' ')) out[o++] = inc; else { if (esc_double) { o += conv_to_octal(inc, &out[o], escape_in_literal); } else { conv_to_octal2(inc, &out[o]); o += 4; } } } mylog("%s: returning %d, out='%.*s'\n", func, o, o, out); return o; } static const char *hextbl = "0123456789ABCDEF"; #define def_bin2hex(type) \ (const char *src, type *dst, SQLLEN length) \ { \ const char *src_wk; \ UCHAR chr; \ type *dst_wk; \ BOOL backwards; \ int i; \ \ backwards = FALSE; \ if ((char *) dst < src) \ { \ if ((char *) (dst + 2 * (length - 1)) > src + length - 1) \ return -1; \ } \ else if ((char *) dst < src + length) \ backwards = TRUE; \ if (backwards) \ { \ for (i = 0, src_wk = src + length - 1, dst_wk = dst + 2 * length - 1; i < length; i++, src_wk--) \ { \ chr = *src_wk; \ *dst_wk-- = hextbl[chr % 16]; \ *dst_wk-- = hextbl[chr >> 4]; \ } \ } \ else \ { \ for (i = 0, src_wk = src, dst_wk = dst; i < length; i++, src_wk++) \ { \ chr = *src_wk; \ *dst_wk++ = hextbl[chr >> 4]; \ *dst_wk++ = hextbl[chr % 16]; \ } \ } \ dst[2 * length] = '\0'; \ return 2 * length * sizeof(type); \ } #ifdef UNICODE_SUPPORT static SQLLEN pg_bin2whex def_bin2hex(SQLWCHAR) #endif /* UNICODE_SUPPORT */ static SQLLEN pg_bin2hex def_bin2hex(char) SQLLEN pg_hex2bin(const char *src, char *dst, SQLLEN length) { UCHAR chr; const char *src_wk; char *dst_wk; SQLLEN i; int val; BOOL HByte = TRUE; for (i = 0, src_wk = src, dst_wk = dst; i < length; i++, src_wk++) { chr = *src_wk; if (!chr) break; if (chr >= 'a' && chr <= 'f') val = chr - 'a' + 10; else if (chr >= 'A' && chr <= 'F') val = chr - 'A' + 10; else val = chr - '0'; if (HByte) *dst_wk = (val << 4); else { *dst_wk += val; dst_wk++; } HByte = !HByte; } *dst_wk = '\0'; return length; } /*------- * 1. get oid (from 'value') * 2. open the large object * 3. read from the large object (handle multiple GetData) * 4. close when read less than requested? -OR- * lseek/read each time * handle case where application receives truncated and * decides not to continue reading. * * CURRENTLY, ONLY LONGVARBINARY is handled, since that is the only * data type currently mapped to a PG_TYPE_LO. But, if any other types * are desired to map to a large object (PG_TYPE_LO), then that would * need to be handled here. For example, LONGVARCHAR could possibly be * mapped to PG_TYPE_LO someday, instead of PG_TYPE_TEXT as it is now. *------- */ int convert_lo(StatementClass *stmt, const void *value, SQLSMALLINT fCType, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue) { CSTR func = "convert_lo"; OID oid; int retval, result; SQLLEN left = -1; GetDataClass *gdata = NULL; ConnectionClass *conn = SC_get_conn(stmt); ConnInfo *ci = &(conn->connInfo); GetDataInfo *gdata_info = SC_get_GDTI(stmt); int factor; oid = ATOI32U(value); if (0 == oid) { if (pcbValue) *pcbValue = SQL_NULL_DATA; return COPY_OK; } switch (fCType) { case SQL_C_CHAR: factor = 2; break; case SQL_C_BINARY: factor = 1; break; default: SC_set_error(stmt, STMT_EXEC_ERROR, "Could not convert lo to the c-type", func); return COPY_GENERAL_ERROR; } /* If using SQLGetData, then current_col will be set */ if (stmt->current_col >= 0) { gdata = &gdata_info->gdata[stmt->current_col]; left = gdata->data_left; } /* * if this is the first call for this column, open the large object * for reading */ if (!gdata || gdata->data_left == -1) { /* begin transaction if needed */ if (!CC_is_in_trans(conn)) { if (!CC_begin(conn)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Could not begin (in-line) a transaction", func); return COPY_GENERAL_ERROR; } } stmt->lobj_fd = odbc_lo_open(conn, oid, INV_READ); if (stmt->lobj_fd < 0) { SC_set_error(stmt, STMT_EXEC_ERROR, "Couldnt open large object for reading.", func); return COPY_GENERAL_ERROR; } /* Get the size */ retval = odbc_lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_END); if (retval >= 0) { left = odbc_lo_tell(conn, stmt->lobj_fd); if (gdata) gdata->data_left = left; /* return to beginning */ odbc_lo_lseek(conn, stmt->lobj_fd, 0L, SEEK_SET); } } else if (left == 0) return COPY_NO_DATA_FOUND; mylog("lo data left = %d\n", left); if (stmt->lobj_fd < 0) { SC_set_error(stmt, STMT_EXEC_ERROR, "Large object FD undefined for multiple read.", func); return COPY_GENERAL_ERROR; } if (0 >= cbValueMax) retval = 0; else retval = odbc_lo_read(conn, stmt->lobj_fd, (char *) rgbValue, (Int4) (factor > 1 ? (cbValueMax - 1) / factor : cbValueMax)); if (retval < 0) { odbc_lo_close(conn, stmt->lobj_fd); /* commit transaction if needed */ if (!ci->drivers.use_declarefetch && CC_does_autocommit(conn)) { if (!CC_commit(conn)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Could not commit (in-line) a transaction", func); return COPY_GENERAL_ERROR; } } stmt->lobj_fd = -1; SC_set_error(stmt, STMT_EXEC_ERROR, "Error reading from large object.", func); return COPY_GENERAL_ERROR; } if (factor > 1) pg_bin2hex((char *) rgbValue, (char *) rgbValue, retval); if (retval < left) result = COPY_RESULT_TRUNCATED; else result = COPY_OK; if (pcbValue) *pcbValue = left < 0 ? SQL_NO_TOTAL : left * factor; if (gdata && gdata->data_left > 0) gdata->data_left -= retval; if (!gdata || gdata->data_left == 0) { odbc_lo_close(conn, stmt->lobj_fd); /* commit transaction if needed */ if (!ci->drivers.use_declarefetch && CC_does_autocommit(conn)) { if (!CC_commit(conn)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Could not commit (in-line) a transaction", func); return COPY_GENERAL_ERROR; } } stmt->lobj_fd = -1; /* prevent further reading */ } return result; } psqlodbc-09.03.0300/drvconn.c000644 001752 000000 00000032656 12335653444 016031 0ustar00saitowheel000000 000000 /*------- Module: drvconn.c * * Description: This module contains only routines related to * implementing SQLDriverConnect. * * Classes: n/a * * API functions: SQLDriverConnect * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "psqlodbc.h" #include #include #include "connection.h" #include "misc.h" #ifndef WIN32 #include #include #define NEAR #else #include #endif #include #ifdef WIN32 #include #include "resource.h" #endif #include "pgapifunc.h" #include "dlg_specific.h" #define FORCE_PASSWORD_DISPLAY #define NULL_IF_NULL(a) (a ? a : "(NULL)") #ifndef FORCE_PASSWORD_DISPLAY static char * hide_password(const char *str) { char *outstr, *pwdp; if (!str) return NULL; outstr = strdup(str); if (pwdp = strstr(outstr, "PWD="), !pwdp) pwdp = strstr(outstr, "pwd="); if (pwdp) { char *p; for (p=pwdp + 4; *p && *p != ';'; p++) *p = 'x'; } return outstr; } #endif /* prototypes */ static void dconn_get_connect_attributes(const char *connect_string, ConnInfo *ci); static void dconn_get_common_attributes(const char *connect_string, ConnInfo *ci); #ifdef WIN32 LRESULT CALLBACK dconn_FDriverConnectProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); RETCODE dconn_DoDialog(HWND hwnd, ConnInfo *ci); extern HINSTANCE NEAR s_hModule; /* Saved module handle. */ #endif RETCODE SQL_API PGAPI_DriverConnect(HDBC hdbc, HWND hwnd, const SQLCHAR FAR * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR FAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT FAR * pcbConnStrOut, SQLUSMALLINT fDriverCompletion) { CSTR func = "PGAPI_DriverConnect"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci; #ifdef WIN32 RETCODE dialog_result; #endif BOOL paramRequired, didUI = FALSE; RETCODE result; char *connStrIn = NULL; char connStrOut[MAX_CONNECT_STRING]; int retval; char salt[5]; char password_required = AUTH_REQ_OK; ssize_t len = 0; SQLSMALLINT lenStrout; mylog("%s: entering...\n", func); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } connStrIn = make_string(szConnStrIn, cbConnStrIn, NULL, 0); #ifdef FORCE_PASSWORD_DISPLAY mylog("**** PGAPI_DriverConnect: fDriverCompletion=%d, connStrIn='%s'\n", fDriverCompletion, connStrIn); qlog("conn=%p, PGAPI_DriverConnect( in)='%s', fDriverCompletion=%d\n", conn, connStrIn, fDriverCompletion); #else if (get_qlog() || get_mylog()) { char *hide_str = hide_password(connStrIn); mylog("**** PGAPI_DriverConnect: fDriverCompletion=%d, connStrIn='%s'\n", fDriverCompletion, NULL_IF_NULL(hide_str)); qlog("conn=%p, PGAPI_DriverConnect( in)='%s', fDriverCompletion=%d\n", conn, NULL_IF_NULL(hide_str), fDriverCompletion); if (hide_str) free(hide_str); } #endif /* FORCE_PASSWORD_DISPLAY */ ci = &(conn->connInfo); /* Parse the connect string and fill in conninfo for this hdbc. */ dconn_get_connect_attributes(connStrIn, ci); /* * If the ConnInfo in the hdbc is missing anything, this function will * fill them in from the registry (assuming of course there is a DSN * given -- if not, it does nothing!) */ getDSNinfo(ci, CONN_DONT_OVERWRITE); dconn_get_common_attributes(connStrIn, ci); logs_on_off(1, ci->drivers.debug, ci->drivers.commlog); if (connStrIn) { free(connStrIn); connStrIn = NULL; } /* Fill in any default parameters if they are not there. */ getDSNdefaults(ci); /* initialize pg_version */ CC_initialize_pg_version(conn); memset(salt, 0, sizeof(salt)); #ifdef WIN32 dialog: #endif ci->focus_password = password_required; inolog("DriverCompletion=%d\n", fDriverCompletion); switch (fDriverCompletion) { #ifdef WIN32 case SQL_DRIVER_PROMPT: dialog_result = dconn_DoDialog(hwnd, ci); didUI = TRUE; if (dialog_result != SQL_SUCCESS) return dialog_result; break; case SQL_DRIVER_COMPLETE_REQUIRED: /* Fall through */ case SQL_DRIVER_COMPLETE: paramRequired = password_required; /* Password is not a required parameter. */ if (ci->database[0] == '\0') paramRequired = TRUE; else if (ci->port[0] == '\0') paramRequired = TRUE; #ifdef WIN32 else if (ci->server[0] == '\0') paramRequired = TRUE; #endif /* WIN32 */ if (paramRequired) { dialog_result = dconn_DoDialog(hwnd, ci); didUI = TRUE; if (dialog_result != SQL_SUCCESS) return dialog_result; } break; #else case SQL_DRIVER_PROMPT: case SQL_DRIVER_COMPLETE: case SQL_DRIVER_COMPLETE_REQUIRED: #endif case SQL_DRIVER_NOPROMPT: break; } /* * Password is not a required parameter unless authentication asks for * it. For now, I think it's better to just let the application ask * over and over until a password is entered (the user can always hit * Cancel to get out) */ paramRequired = FALSE; if (ci->database[0] == '\0') paramRequired = TRUE; else if (ci->port[0] == '\0') paramRequired = TRUE; #ifdef WIN32 else if (ci->server[0] == '\0') paramRequired = TRUE; #endif /* WIN32 */ if (paramRequired) { if (didUI) return SQL_NO_DATA_FOUND; CC_set_error(conn, CONN_OPENDB_ERROR, "connction string lacks some options", func); return SQL_ERROR; } inolog("before CC_connect\n"); /* do the actual connect */ retval = CC_connect(conn, password_required, salt); if (retval < 0) { /* need a password */ if (fDriverCompletion == SQL_DRIVER_NOPROMPT) { CC_log_error(func, "Need password but Driver_NoPrompt", conn); return SQL_ERROR; /* need a password but not allowed to * prompt so error */ } else { #ifdef WIN32 password_required = -retval; goto dialog; #else return SQL_ERROR; /* until a better solution is found. */ #endif } } else if (retval == 0) { /* error msg filled in above */ CC_log_error(func, "Error from CC_Connect", conn); return SQL_ERROR; } /* * Create the Output Connection String */ result = (1 == retval ? SQL_SUCCESS : SQL_SUCCESS_WITH_INFO); lenStrout = cbConnStrOutMax; if (conn->ms_jet && lenStrout > 255) lenStrout = 255; makeConnectString(connStrOut, ci, lenStrout); len = strlen(connStrOut); if (szConnStrOut) { /* * Return the completed string to the caller. The correct method * is to only construct the connect string if a dialog was put up, * otherwise, it should just copy the connection input string to * the output. However, it seems ok to just always construct an * output string. There are possible bad side effects on working * applications (Access) by implementing the correct behavior, * anyway. */ /*strncpy_null(szConnStrOut, connStrOut, cbConnStrOutMax);*/ strncpy((char *) szConnStrOut, connStrOut, cbConnStrOutMax); if (len >= cbConnStrOutMax) { int clen; for (clen = cbConnStrOutMax - 1; clen >= 0 && szConnStrOut[clen] != ';'; clen--) szConnStrOut[clen] = '\0'; result = SQL_SUCCESS_WITH_INFO; CC_set_error(conn, CONN_TRUNCATED, "The buffer was too small for the ConnStrOut.", func); } } if (pcbConnStrOut) *pcbConnStrOut = (SQLSMALLINT) len; #ifdef FORCE_PASSWORD_DISPLAY if (cbConnStrOutMax > 0) { mylog("szConnStrOut = '%s' len=%d,%d\n", NULL_IF_NULL((char *) szConnStrOut), len, cbConnStrOutMax); qlog("conn=%p, PGAPI_DriverConnect(out)='%s'\n", conn, NULL_IF_NULL((char *) szConnStrOut)); } #else if (get_qlog() || get_mylog()) { char *hide_str = NULL; if (cbConnStrOutMax > 0) hide_str = hide_password(szConnStrOut); mylog("szConnStrOut = '%s' len=%d,%d\n", NULL_IF_NULL(hide_str), len, cbConnStrOutMax); qlog("conn=%p, PGAPI_DriverConnect(out)='%s'\n", conn, NULL_IF_NULL(hide_str)); if (hide_str) free(hide_str); } #endif /* FORCE_PASSWORD_DISPLAY */ if (connStrIn) free(connStrIn); mylog("PGAPI_DriverConnect: returning %d\n", result); return result; } #ifdef WIN32 RETCODE dconn_DoDialog(HWND hwnd, ConnInfo *ci) { LRESULT dialog_result; mylog("dconn_DoDialog: ci = %p\n", ci); if (hwnd) { dialog_result = DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_CONFIG), hwnd, dconn_FDriverConnectProc, (LPARAM) ci); if (!dialog_result || (dialog_result == -1)) return SQL_NO_DATA_FOUND; else return SQL_SUCCESS; } return SQL_ERROR; } LRESULT CALLBACK dconn_FDriverConnectProc( HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci; char strbuf[64]; switch (wMsg) { case WM_INITDIALOG: ci = (ConnInfo *) lParam; /* Change the caption for the setup dialog */ SetWindowText(hdlg, "PostgreSQL Connection"); LoadString(s_hModule, IDS_ADVANCE_CONNECTION, strbuf, sizeof(strbuf)); SetWindowText(GetDlgItem(hdlg, IDC_DATASOURCE), strbuf); /* Hide the DSN and description fields */ ShowWindow(GetDlgItem(hdlg, IDC_DSNAMETEXT), SW_HIDE); ShowWindow(GetDlgItem(hdlg, IDC_DSNAME), SW_HIDE); ShowWindow(GetDlgItem(hdlg, IDC_DESCTEXT), SW_HIDE); ShowWindow(GetDlgItem(hdlg, IDC_DESC), SW_HIDE); ShowWindow(GetDlgItem(hdlg, IDC_DRIVER), SW_HIDE); ShowWindow(GetDlgItem(hdlg, IDC_TEST), SW_HIDE); if ('\0' != ci->server[0]) EnableWindow(GetDlgItem(hdlg, IDC_SERVER), FALSE); if ('\0' != ci->port[0]) EnableWindow(GetDlgItem(hdlg, IDC_PORT), FALSE); SetWindowLongPtr(hdlg, DWLP_USER, lParam); /* Save the ConnInfo for * the "OK" */ SetDlgStuff(hdlg, ci); if (ci->database[0] == '\0') ; /* default focus */ else if (ci->server[0] == '\0') SetFocus(GetDlgItem(hdlg, IDC_SERVER)); else if (ci->port[0] == '\0') SetFocus(GetDlgItem(hdlg, IDC_PORT)); else if (ci->username[0] == '\0') SetFocus(GetDlgItem(hdlg, IDC_USER)); else if (ci->focus_password) SetFocus(GetDlgItem(hdlg, IDC_PASSWORD)); break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); GetDlgStuff(hdlg, ci); case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; case IDC_DATASOURCE: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, ds_options1Proc, (LPARAM) ci); break; case IDC_DRIVER: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, driver_optionsProc, (LPARAM) ci); break; } } return FALSE; } #endif /* WIN32 */ #define ATTRIBUTE_DELIMITER ';' #define OPENING_BRACKET '{' #define CLOSING_BRACKET '}' typedef BOOL (*copyfunc)(ConnInfo *, const char *attribute, const char *value); static void dconn_get_attributes(copyfunc func, const char *connect_string, ConnInfo *ci) { char *our_connect_string; const char *pair, *attribute, *value, *termp; BOOL eoftok; char *equals, *delp; char *strtok_arg; #ifdef HAVE_STRTOK_R char *last; #endif /* HAVE_STRTOK_R */ if (our_connect_string = strdup(connect_string), NULL == our_connect_string) return; strtok_arg = our_connect_string; #ifdef FORCE_PASSWORD_DISPLAY mylog("our_connect_string = '%s'\n", our_connect_string); #else if (get_mylog()) { char *hide_str = hide_password(our_connect_string); mylog("our_connect_string = '%s'\n", hide_str); free(hide_str); } #endif /* FORCE_PASSWORD_DISPLAY */ termp = strchr(our_connect_string, '\0'); eoftok = FALSE; while (!eoftok) { #ifdef HAVE_STRTOK_R pair = strtok_r(strtok_arg, ";", &last); #else pair = strtok(strtok_arg, ";"); #endif /* HAVE_STRTOK_R */ if (strtok_arg) strtok_arg = NULL; if (!pair) break; equals = strchr(pair, '='); if (!equals) continue; *equals = '\0'; attribute = pair; /* ex. DSN */ value = equals + 1; /* ex. 'CEO co1' */ /* * Values enclosed with braces({}) can contain ; etc * We don't remove the braces here because * decode_or_remove_braces() in dlg_specifi.c * would remove them later. * Just correct the misdetected delimter(;). */ if (OPENING_BRACKET == *value) { delp = strchr(value, '\0'); if (NULL == delp) continue; /* shouldn't occur */ if (delp == termp) { /* there's a corresponding closing bracket? */ if (CLOSING_BRACKET == delp[-1]) eoftok = TRUE; } else { char *closep; /* Where's a corresponding closing bracket? */ closep = strchr(value, CLOSING_BRACKET); if (NULL == closep) { closep = strchr(delp + 1, CLOSING_BRACKET); if (NULL != closep) /* the delimiter is misdetected */ { *delp = ATTRIBUTE_DELIMITER; strtok_arg = closep + 1; if (delp = strchr(closep + 1, ATTRIBUTE_DELIMITER), NULL != delp) { *delp = '\0'; strtok_arg = delp + 1; } if (strtok_arg + 1 >= termp) eoftok = TRUE; } } } } #ifndef FORCE_PASSWORD_DISPLAY if (stricmp(attribute, INI_PASSWORD) == 0 || stricmp(attribute, "pwd") == 0) mylog("attribute = '%s', value = 'xxxxx'\n", attribute); else #endif /* FORCE_PASSWORD_DISPLAY */ mylog("attribute = '%s', value = '%s'\n", attribute, value); if (!attribute || !value) continue; /* Copy the appropriate value to the conninfo */ (*func)(ci, attribute, value); } free(our_connect_string); } static void dconn_get_connect_attributes(const char *connect_string, ConnInfo *ci) { CC_conninfo_init(ci, COPY_GLOBALS); dconn_get_attributes(copyAttributes, connect_string, ci); } static void dconn_get_common_attributes(const char *connect_string, ConnInfo *ci) { dconn_get_attributes(copyCommonAttributes, connect_string, ci); } psqlodbc-09.03.0300/environ.c000644 001752 000000 00000040300 12335653444 016021 0ustar00saitowheel000000 000000 /*------- * Module: environ.c * * Description: This module contains routines related to * the environment, such as storing connection handles, * and returning errors. * * Classes: EnvironmentClass (Functions prefix: "EN_") * * API functions: SQLAllocEnv, SQLFreeEnv, SQLError * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "environ.h" #include "misc.h" #include "connection.h" #include "dlg_specific.h" #include "statement.h" #include #include #include "pgapifunc.h" #ifdef WIN32 #include #endif /* WIN32 */ #include "loadlib.h" extern GLOBAL_VALUES globals; /* The one instance of the handles */ static int conns_count = 0; static ConnectionClass **conns = NULL; #if defined(WIN_MULTITHREAD_SUPPORT) CRITICAL_SECTION conns_cs; CRITICAL_SECTION common_cs; /* commonly used for short term blocking */ CRITICAL_SECTION common_lcs; /* commonly used for not necessarily short term blocking */ #elif defined(POSIX_MULTITHREAD_SUPPORT) pthread_mutex_t conns_cs; pthread_mutex_t common_cs; pthread_mutex_t common_lcs; #endif /* WIN_MULTITHREAD_SUPPORT */ void shortterm_common_lock(void) { ENTER_COMMON_CS; } void shortterm_common_unlock(void) { LEAVE_COMMON_CS; } int getConnCount(void) { return conns_count; } ConnectionClass * const *getConnList(void) { return conns; } RETCODE SQL_API PGAPI_AllocEnv(HENV FAR * phenv) { CSTR func = "PGAPI_AllocEnv"; SQLRETURN ret = SQL_SUCCESS; mylog("**** in %s ** \n", func); /* * Hack for systems on which none of the constructor-making techniques * in psqlodbc.c work: if globals appears not to have been * initialized, then cause it to be initialized. Since this should be * the first function called in this shared library, doing it here * should work. */ if (globals.socket_buffersize <= 0) { initialize_global_cs(); getCommonDefaults(DBMS_NAME, ODBCINST_INI, NULL); } *phenv = (HENV) EN_Constructor(); if (!*phenv) { *phenv = SQL_NULL_HENV; EN_log_error(func, "Error allocating environment", NULL); ret = SQL_ERROR; } mylog("** exit %s: phenv = %p **\n", func, *phenv); return ret; } RETCODE SQL_API PGAPI_FreeEnv(HENV henv) { CSTR func = "PGAPI_FreeEnv"; SQLRETURN ret = SQL_SUCCESS; EnvironmentClass *env = (EnvironmentClass *) henv; mylog("**** in PGAPI_FreeEnv: env = %p ** \n", env); if (env && EN_Destructor(env)) { mylog(" ok\n"); goto cleanup; } mylog(" error\n"); ret = SQL_ERROR; EN_log_error(func, "Error freeing environment", env); cleanup: return ret; } static void pg_sqlstate_set(const EnvironmentClass *env, UCHAR *szSqlState, const char *ver3str, const char *ver2str) { strcpy((char *) szSqlState, EN_is_odbc3(env) ? ver3str : ver2str); } PG_ErrorInfo * ER_Constructor(SDWORD errnumber, const char *msg) { PG_ErrorInfo *error; ssize_t aladd, errsize; if (DESC_OK == errnumber) return NULL; if (msg) { errsize = strlen(msg); aladd = errsize; } else { errsize = -1; aladd = 0; } error = (PG_ErrorInfo *) malloc(sizeof(PG_ErrorInfo) + aladd); if (error) { memset(error, 0, sizeof(PG_ErrorInfo)); error->status = errnumber; error->errorsize = (Int4) errsize; if (errsize > 0) memcpy(error->__error_message, msg, errsize); error->__error_message[aladd] = '\0'; error->recsize = -1; } return error; } void ER_Destructor(PG_ErrorInfo *self) { free(self); } PG_ErrorInfo * ER_Dup(const PG_ErrorInfo *self) { PG_ErrorInfo *new; Int4 alsize; if (!self) return NULL; alsize = sizeof(PG_ErrorInfo); if (self->errorsize > 0) alsize += self->errorsize; new = (PG_ErrorInfo *) malloc(alsize); memcpy(new, self, alsize); return new; } #define DRVMNGRDIV 511 /* Returns the next SQL error information. */ RETCODE SQL_API ER_ReturnError(PG_ErrorInfo **pgerror, SQLSMALLINT RecNumber, SQLCHAR FAR * szSqlState, SQLINTEGER FAR * pfNativeError, SQLCHAR FAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT FAR * pcbErrorMsg, UWORD flag) { CSTR func = "ER_ReturnError"; /* CC: return an error of a hstmt */ PG_ErrorInfo *error; BOOL partial_ok = ((flag & PODBC_ALLOW_PARTIAL_EXTRACT) != 0), clear_str = ((flag & PODBC_ERROR_CLEAR) != 0); const char *msg; SWORD msglen, stapos, wrtlen, pcblen; if (!pgerror || !*pgerror) return SQL_NO_DATA_FOUND; error = *pgerror; msg = error->__error_message; mylog("%s: status = %d, msg = #%s#\n", func, error->status, msg); msglen = (SQLSMALLINT) strlen(msg); /* * Even though an application specifies a larger error message * buffer, the driver manager changes it silently. * Therefore we divide the error message into ... */ if (error->recsize < 0) { if (cbErrorMsgMax > 0) error->recsize = cbErrorMsgMax - 1; /* apply the first request */ else error->recsize = DRVMNGRDIV; } if (RecNumber < 0) { if (0 == error->errorpos) RecNumber = 1; else RecNumber = 2 + (error->errorpos - 1) / error->recsize; } stapos = (RecNumber - 1) * error->recsize; if (stapos > msglen) return SQL_NO_DATA_FOUND; pcblen = wrtlen = msglen - stapos; if (pcblen > error->recsize) pcblen = error->recsize; if (0 == cbErrorMsgMax) wrtlen = 0; else if (wrtlen >= cbErrorMsgMax) { if (partial_ok) wrtlen = cbErrorMsgMax - 1; else if (cbErrorMsgMax <= error->recsize) wrtlen = 0; else wrtlen = error->recsize; } if (wrtlen > pcblen) wrtlen = pcblen; if (NULL != pcbErrorMsg) *pcbErrorMsg = pcblen; if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) { memcpy(szErrorMsg, msg + stapos, wrtlen); szErrorMsg[wrtlen] = '\0'; } if (NULL != pfNativeError) *pfNativeError = error->status; if (NULL != szSqlState) strncpy_null((char *) szSqlState, error->sqlstate, 6); mylog(" szSqlState = '%s',len=%d, szError='%s'\n", szSqlState, pcblen, szErrorMsg); if (clear_str) { error->errorpos = stapos + wrtlen; if (error->errorpos >= msglen) { ER_Destructor(error); *pgerror = NULL; } } if (wrtlen == 0) return SQL_SUCCESS_WITH_INFO; else return SQL_SUCCESS; } RETCODE SQL_API PGAPI_ConnectError(HDBC hdbc, SQLSMALLINT RecNumber, SQLCHAR FAR * szSqlState, SQLINTEGER FAR * pfNativeError, SQLCHAR FAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT FAR * pcbErrorMsg, UWORD flag) { ConnectionClass *conn = (ConnectionClass *) hdbc; EnvironmentClass *env = (EnvironmentClass *) conn->henv; char *msg; int status; BOOL once_again = FALSE; ssize_t msglen; mylog("**** PGAPI_ConnectError: hdbc=%p <%d>\n", hdbc, cbErrorMsgMax); if (RecNumber != 1 && RecNumber != -1) return SQL_NO_DATA_FOUND; if (cbErrorMsgMax < 0) return SQL_ERROR; if (CONN_EXECUTING == conn->status || !CC_get_error(conn, &status, &msg) || NULL == msg) { mylog("CC_Get_error returned nothing.\n"); if (NULL != szSqlState) strcpy((char *) szSqlState, "00000"); if (NULL != pcbErrorMsg) *pcbErrorMsg = 0; if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) szErrorMsg[0] = '\0'; return SQL_NO_DATA_FOUND; } mylog("CC_get_error: status = %d, msg = #%s#\n", status, msg); msglen = strlen(msg); if (NULL != pcbErrorMsg) { *pcbErrorMsg = (SQLSMALLINT) msglen; if (cbErrorMsgMax == 0) once_again = TRUE; else if (msglen >= cbErrorMsgMax) *pcbErrorMsg = cbErrorMsgMax - 1; } if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) strncpy_null((char *) szErrorMsg, msg, cbErrorMsgMax); if (NULL != pfNativeError) *pfNativeError = status; if (NULL != szSqlState) { if (conn->sqlstate[0]) strcpy((char *) szSqlState, conn->sqlstate); else switch (status) { case CONN_OPTION_VALUE_CHANGED: pg_sqlstate_set(env, szSqlState, "01S02", "01S02"); break; case CONN_TRUNCATED: pg_sqlstate_set(env, szSqlState, "01004", "01004"); /* data truncated */ break; case CONN_INIREAD_ERROR: pg_sqlstate_set(env, szSqlState, "IM002", "IM002"); /* data source not found */ break; case CONNECTION_SERVER_NOT_REACHED: case CONN_OPENDB_ERROR: pg_sqlstate_set(env, szSqlState, "08001", "08001"); /* unable to connect to data source */ break; case CONN_INVALID_AUTHENTICATION: case CONN_AUTH_TYPE_UNSUPPORTED: pg_sqlstate_set(env, szSqlState, "28000", "28000"); break; case CONN_STMT_ALLOC_ERROR: pg_sqlstate_set(env, szSqlState, "HY001", "S1001"); /* memory allocation failure */ break; case CONN_IN_USE: pg_sqlstate_set(env, szSqlState, "HY000", "S1000"); /* general error */ break; case CONN_UNSUPPORTED_OPTION: pg_sqlstate_set(env, szSqlState, "HYC00", "IM001"); /* driver does not support this function */ break; case CONN_INVALID_ARGUMENT_NO: pg_sqlstate_set(env, szSqlState, "HY009", "S1009"); /* invalid argument value */ break; case CONN_TRANSACT_IN_PROGRES: pg_sqlstate_set(env, szSqlState, "HY010", "S1010"); /* * when the user tries to switch commit mode in a * transaction */ /* -> function sequence error */ break; case CONN_NO_MEMORY_ERROR: pg_sqlstate_set(env, szSqlState, "HY001", "S1001"); break; case CONN_NOT_IMPLEMENTED_ERROR: pg_sqlstate_set(env, szSqlState, "HYC00", "S1C00"); break; case CONN_VALUE_OUT_OF_RANGE: pg_sqlstate_set(env, szSqlState, "HY019", "22003"); break; case CONNECTION_COULD_NOT_SEND: case CONNECTION_COULD_NOT_RECEIVE: case CONNECTION_COMMUNICATION_ERROR: case CONNECTION_NO_RESPONSE: pg_sqlstate_set(env, szSqlState, "08S01", "08S01"); break; default: pg_sqlstate_set(env, szSqlState, "HY000", "S1000"); /* general error */ break; } } mylog(" szSqlState = '%s',len=%d, szError='%s'\n", szSqlState ? (char *) szSqlState : PRINT_NULL, msglen, szErrorMsg ? (char *) szErrorMsg : PRINT_NULL); if (once_again) { CC_set_errornumber(conn, status); return SQL_SUCCESS_WITH_INFO; } else return SQL_SUCCESS; } RETCODE SQL_API PGAPI_EnvError(HENV henv, SQLSMALLINT RecNumber, SQLCHAR FAR * szSqlState, SQLINTEGER FAR * pfNativeError, SQLCHAR FAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT FAR * pcbErrorMsg, UWORD flag) { EnvironmentClass *env = (EnvironmentClass *) henv; char *msg; int status; mylog("**** PGAPI_EnvError: henv=%p <%d>\n", henv, cbErrorMsgMax); if (RecNumber != 1 && RecNumber != -1) return SQL_NO_DATA_FOUND; if (cbErrorMsgMax < 0) return SQL_ERROR; if (!EN_get_error(env, &status, &msg) || NULL == msg) { mylog("EN_get_error: status = %d, msg = #%s#\n", status, msg); if (NULL != szSqlState) pg_sqlstate_set(env, szSqlState, "00000", "00000"); if (NULL != pcbErrorMsg) *pcbErrorMsg = 0; if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) szErrorMsg[0] = '\0'; return SQL_NO_DATA_FOUND; } mylog("EN_get_error: status = %d, msg = #%s#\n", status, msg); if (NULL != pcbErrorMsg) *pcbErrorMsg = (SQLSMALLINT) strlen(msg); if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) strncpy_null((char *) szErrorMsg, msg, cbErrorMsgMax); if (NULL != pfNativeError) *pfNativeError = status; if (szSqlState) { switch (status) { case ENV_ALLOC_ERROR: /* memory allocation failure */ pg_sqlstate_set(env, szSqlState, "HY001", "S1001"); break; default: pg_sqlstate_set(env, szSqlState, "HY000", "S1000"); /* general error */ break; } } return SQL_SUCCESS; } /* Returns the next SQL error information. */ RETCODE SQL_API PGAPI_Error(HENV henv, HDBC hdbc, HSTMT hstmt, SQLCHAR FAR * szSqlState, SQLINTEGER FAR * pfNativeError, SQLCHAR FAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT FAR * pcbErrorMsg) { RETCODE ret; UWORD flag = PODBC_ALLOW_PARTIAL_EXTRACT | PODBC_ERROR_CLEAR; mylog("**** PGAPI_Error: henv=%p, hdbc=%p hstmt=%d\n", henv, hdbc, hstmt); if (cbErrorMsgMax < 0) return SQL_ERROR; if (SQL_NULL_HSTMT != hstmt) ret = PGAPI_StmtError(hstmt, -1, szSqlState, pfNativeError, szErrorMsg, cbErrorMsgMax, pcbErrorMsg, flag); else if (SQL_NULL_HDBC != hdbc) ret = PGAPI_ConnectError(hdbc, -1, szSqlState, pfNativeError, szErrorMsg, cbErrorMsgMax, pcbErrorMsg, flag); else if (SQL_NULL_HENV != henv) ret = PGAPI_EnvError(henv, -1, szSqlState, pfNativeError, szErrorMsg, cbErrorMsgMax, pcbErrorMsg, flag); else { if (NULL != szSqlState) strcpy((char *) szSqlState, "00000"); if (NULL != pcbErrorMsg) *pcbErrorMsg = 0; if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) szErrorMsg[0] = '\0'; ret = SQL_NO_DATA_FOUND; } mylog("**** PGAPI_Error exit code=%d\n", ret); return ret; } /* * EnvironmentClass implementation */ EnvironmentClass * EN_Constructor(void) { EnvironmentClass *rv = NULL; #ifdef WIN32 WORD wVersionRequested; WSADATA wsaData; const int major = 2, minor = 2; /* Load the WinSock Library */ wVersionRequested = MAKEWORD(major, minor); if (WSAStartup(wVersionRequested, &wsaData)) { mylog("%s: WSAStartup error\n", __FUNCTION__); return rv; } /* Verify that this is the minimum version of WinSock */ if (LOBYTE(wsaData.wVersion) >= 1 && (LOBYTE(wsaData.wVersion) >= 2 || HIBYTE(wsaData.wVersion) >= 1)) ; else { mylog("%s: WSAStartup version=(%d,%d)\n", __FUNCTION__, LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion)); goto cleanup; } #endif /* WIN32 */ rv = (EnvironmentClass *) malloc(sizeof(EnvironmentClass)); if (NULL == rv) { mylog("%s: malloc error\n", __FUNCTION__); goto cleanup; } rv->errormsg = 0; rv->errornumber = 0; rv->flag = 0; INIT_ENV_CS(rv); cleanup: #ifdef WIN32 if (NULL == rv) { WSACleanup(); } #endif /* WIN32 */ return rv; } char EN_Destructor(EnvironmentClass *self) { int lf, nullcnt; char rv = 1; mylog("in EN_Destructor, self=%p\n", self); if (!self) return 0; /* * the error messages are static strings distributed throughout the * source--they should not be freed */ /* Free any connections belonging to this environment */ ENTER_CONNS_CS; for (lf = 0, nullcnt = 0; lf < conns_count; lf++) { if (NULL == conns[lf]) nullcnt++; else if (conns[lf]->henv == self) { if (CC_Destructor(conns[lf])) conns[lf] = NULL; else rv = 0; nullcnt++; } } if (conns && nullcnt >= conns_count) { mylog("clearing conns count=%d\n", conns_count); free(conns); conns = NULL; conns_count = 0; } LEAVE_CONNS_CS; DELETE_ENV_CS(self); free(self); #ifdef WIN32 WSACleanup(); #endif mylog("exit EN_Destructor: rv = %d\n", rv); #ifdef _MEMORY_DEBUG_ debug_memory_check(); #endif /* _MEMORY_DEBUG_ */ return rv; } char EN_get_error(EnvironmentClass *self, int *number, char **message) { if (self && self->errormsg && self->errornumber) { *message = self->errormsg; *number = self->errornumber; self->errormsg = 0; self->errornumber = 0; return 1; } else return 0; } #define INIT_CONN_COUNT 128 char EN_add_connection(EnvironmentClass *self, ConnectionClass *conn) { int i, alloc; ConnectionClass **newa; char ret = FALSE; mylog("EN_add_connection: self = %p, conn = %p\n", self, conn); ENTER_CONNS_CS; for (i = 0; i < conns_count; i++) { if (!conns[i]) { conn->henv = self; conns[i] = conn; ret = TRUE; mylog(" added at i=%d, conn->henv = %p, conns[i]->henv = %p\n", i, conn->henv, conns[i]->henv); goto cleanup; } } if (conns_count > 0) alloc = 2 * conns_count; else alloc = INIT_CONN_COUNT; if (newa = (ConnectionClass **) realloc(conns, alloc * sizeof(ConnectionClass *)), NULL == newa) goto cleanup; conn->henv = self; newa[conns_count] = conn; conns = newa; ret = TRUE; mylog(" added at %d, conn->henv = %p, conns[%d]->henv = %p\n", conns_count, conn->henv, conns_count, conns[conns_count]->henv); for (i = conns_count + 1; i < alloc; i++) conns[i] = NULL; conns_count = alloc; cleanup: LEAVE_CONNS_CS; return ret; } char EN_remove_connection(EnvironmentClass *self, ConnectionClass *conn) { int i; for (i = 0; i < conns_count; i++) if (conns[i] == conn && conns[i]->status != CONN_EXECUTING) { ENTER_CONNS_CS; conns[i] = NULL; LEAVE_CONNS_CS; return TRUE; } return FALSE; } void EN_log_error(const char *func, char *desc, EnvironmentClass *self) { if (self) qlog("ENVIRON ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->errornumber, self->errormsg); else qlog("INVALID ENVIRON HANDLE ERROR: func=%s, desc='%s'\n", func, desc); } psqlodbc-09.03.0300/execute.c000644 001752 000000 00000125557 12335653444 016025 0ustar00saitowheel000000 000000 /*------- * Module: execute.c * * Description: This module contains routines related to * preparing and executing an SQL statement. * * Classes: n/a * * API functions: SQLPrepare, SQLExecute, SQLExecDirect, SQLTransact, * SQLCancel, SQLNativeSql, SQLParamData, SQLPutData * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "psqlodbc.h" #include "misc.h" #include #include #ifndef WIN32 #include #endif /* WIN32 */ #include "environ.h" #include "connection.h" #include "statement.h" #include "qresult.h" #include "convert.h" #include "bind.h" #include "pgtypes.h" #include "lobj.h" #include "pgapifunc.h" /*extern GLOBAL_VALUES globals;*/ /* Perform a Prepare on the SQL statement */ RETCODE SQL_API PGAPI_Prepare(HSTMT hstmt, const SQLCHAR FAR * szSqlStr, SQLINTEGER cbSqlStr) { CSTR func = "PGAPI_Prepare"; StatementClass *self = (StatementClass *) hstmt; RETCODE retval = SQL_SUCCESS; BOOL prepared; mylog("%s: entering...\n", func); #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(self); */ if (!self) { SC_log_error(func, "", NULL); retval = SQL_INVALID_HANDLE; goto cleanup; } /* * According to the ODBC specs it is valid to call SQLPrepare multiple * times. In that case, the bound SQL statement is replaced by the new * one */ prepared = self->prepared; SC_set_prepared(self, NOT_YET_PREPARED); switch (self->status) { case STMT_PREMATURE: mylog("**** PGAPI_Prepare: STMT_PREMATURE, recycle\n"); SC_recycle_statement(self); /* recycle the statement, but do * not remove parameter bindings */ break; case STMT_FINISHED: mylog("**** PGAPI_Prepare: STMT_FINISHED, recycle\n"); SC_recycle_statement(self); /* recycle the statement, but do * not remove parameter bindings */ break; case STMT_ALLOCATED: mylog("**** PGAPI_Prepare: STMT_ALLOCATED, copy\n"); self->status = STMT_READY; break; case STMT_READY: mylog("**** PGAPI_Prepare: STMT_READY, change SQL\n"); if (NOT_YET_PREPARED != prepared) SC_recycle_statement(self); /* recycle the statement */ break; case STMT_EXECUTING: mylog("**** PGAPI_Prepare: STMT_EXECUTING, error!\n"); SC_set_error(self, STMT_SEQUENCE_ERROR, "PGAPI_Prepare(): The handle does not point to a statement that is ready to be executed", func); retval = SQL_ERROR; goto cleanup; default: SC_set_error(self, STMT_INTERNAL_ERROR, "An Internal Error has occured -- Unknown statement status.", func); retval = SQL_ERROR; goto cleanup; } SC_initialize_stmts(self, TRUE); if (!szSqlStr) { SC_set_error(self, STMT_NO_MEMORY_ERROR, "the query is NULL", func); retval = SQL_ERROR; goto cleanup; } if (!szSqlStr[0]) self->statement = strdup(""); else self->statement = make_string(szSqlStr, cbSqlStr, NULL, 0); if (!self->statement) { SC_set_error(self, STMT_NO_MEMORY_ERROR, "No memory available to store statement", func); retval = SQL_ERROR; goto cleanup; } self->prepare = PREPARE_STATEMENT; self->statement_type = statement_type(self->statement); /* Check if connection is onlyread (only selects are allowed) */ if (CC_is_onlyread(SC_get_conn(self)) && STMT_UPDATE(self)) { SC_set_error(self, STMT_EXEC_ERROR, "Connection is readonly, only select statements are allowed.", func); retval = SQL_ERROR; goto cleanup; } cleanup: #undef return inolog("SQLPrepare return=%d\n", retval); if (self->internal) retval = DiscardStatementSvp(self, retval, FALSE); return retval; } /* Performs the equivalent of SQLPrepare, followed by SQLExecute. */ RETCODE SQL_API PGAPI_ExecDirect(HSTMT hstmt, const SQLCHAR FAR * szSqlStr, SQLINTEGER cbSqlStr, UWORD flag) { StatementClass *stmt = (StatementClass *) hstmt; RETCODE result; CSTR func = "PGAPI_ExecDirect"; const ConnectionClass *conn = SC_get_conn(stmt); mylog("%s: entering...%x\n", func, flag); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; /* * keep a copy of the un-parametrized statement, in case they try to * execute this statement again */ stmt->statement = make_string(szSqlStr, cbSqlStr, NULL, 0); inolog("a2\n"); if (!stmt->statement) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "No memory available to store statement", func); return SQL_ERROR; } mylog("**** %s: hstmt=%p, statement='%s'\n", func, hstmt, stmt->statement); if (0 != (flag & PODBC_WITH_HOLD)) SC_set_with_hold(stmt); /* * If an SQLPrepare was performed prior to this, but was left in the * premature state because an error occurred prior to SQLExecute then * set the statement to finished so it can be recycled. */ if (stmt->status == STMT_PREMATURE) stmt->status = STMT_FINISHED; stmt->statement_type = statement_type(stmt->statement); /* Check if connection is onlyread (only selects are allowed) */ if (CC_is_onlyread(conn) && STMT_UPDATE(stmt)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Connection is readonly, only select statements are allowed.", func); return SQL_ERROR; } mylog("%s: calling PGAPI_Execute...\n", func); flag = SC_is_with_hold(stmt) ? PODBC_WITH_HOLD : 0; result = PGAPI_Execute(hstmt, flag); mylog("%s: returned %hd from PGAPI_Execute\n", func, result); return result; } static int inquireHowToPrepare(const StatementClass *stmt) { ConnectionClass *conn; ConnInfo *ci; int ret = 0; conn = SC_get_conn(stmt); ci = &(conn->connInfo); if (!ci->use_server_side_prepare || PG_VERSION_LT(conn, 7.3)) { /* Do prepare operations by the driver itself */ return PREPARE_BY_THE_DRIVER; } if (NOT_YET_PREPARED == stmt->prepared) { SQLSMALLINT num_params; if (STMT_TYPE_DECLARE == stmt->statement_type && PG_VERSION_LT(conn, 8.0)) { return PREPARE_BY_THE_DRIVER; } if (stmt->multi_statement < 0) PGAPI_NumParams((StatementClass *) stmt, &num_params); if (stmt->multi_statement > 0) /* would divide the query into multiple commands and apply V3 parse requests for each of them */ ret = PROTOCOL_74(ci) ? PARSE_REQ_FOR_INFO : PREPARE_BY_THE_DRIVER; else if (PROTOCOL_74(ci)) { if (SC_may_use_cursor(stmt)) { if (ci->drivers.use_declarefetch) return PARSE_REQ_FOR_INFO; else if (SQL_CURSOR_FORWARD_ONLY != stmt->options.cursor_type) ret = PARSE_REQ_FOR_INFO; else ret = PARSE_TO_EXEC_ONCE; } else ret = PARSE_TO_EXEC_ONCE; } else { if (SC_may_use_cursor(stmt) && (SQL_CURSOR_FORWARD_ONLY != stmt->options.cursor_type || ci->drivers.use_declarefetch)) ret = PREPARE_BY_THE_DRIVER; else if (SC_is_prepare_statement(stmt)) ret = USING_PREPARE_COMMAND; else ret = PREPARE_BY_THE_DRIVER; } } if (SC_is_prepare_statement(stmt) && (PARSE_TO_EXEC_ONCE == ret)) ret = NAMED_PARSE_REQUEST; return ret; } int decideHowToPrepare(StatementClass *stmt, BOOL force) { int method = SC_get_prepare_method(stmt); if (0 != method) /* a method was already determined */ return method; if (stmt->inaccurate_result) return method; switch (stmt->prepare) { case NON_PREPARE_STATEMENT: /* not a prepare statement */ if (!force) return method; break; } method = inquireHowToPrepare(stmt); stmt->prepare |= method; if (PREPARE_BY_THE_DRIVER == method) stmt->discard_output_params = 1; return method; } /* dont/should/can send Parse request ? */ enum { doNothing = 0 ,allowParse ,preferParse ,shouldParse ,usingCommand }; #define ONESHOT_CALL_PARSE allowParse #define NOPARAM_ONESHOT_CALL_PARSE doNothing static int HowToPrepareBeforeExec(StatementClass *stmt, BOOL checkOnly) { SQLSMALLINT num_params = stmt->num_params; ConnectionClass *conn = SC_get_conn(stmt); ConnInfo *ci = &(conn->connInfo); int nCallParse = doNothing, how_to_prepare = 0; BOOL bNeedsTrans = FALSE; if (num_params < 0) PGAPI_NumParams(stmt, &num_params); how_to_prepare = decideHowToPrepare(stmt, checkOnly); if (checkOnly) { if (num_params <= 0) return doNothing; } else { switch (how_to_prepare) { case USING_PREPARE_COMMAND: return checkOnly ? doNothing : usingCommand; case NAMED_PARSE_REQUEST: return shouldParse; case PARSE_TO_EXEC_ONCE: switch (stmt->prepared) { case PREPARED_TEMPORARILY: nCallParse = preferParse; break; default: if (num_params <= 0) nCallParse = NOPARAM_ONESHOT_CALL_PARSE; else nCallParse = ONESHOT_CALL_PARSE; } break; default: return doNothing; } } if (PG_VERSION_LE(conn, 7.3) || !PROTOCOL_74(ci)) return nCallParse; if (num_params > 0) { int param_number = -1; ParameterInfoClass *apara; ParameterImplClass *ipara; OID pgtype; while (TRUE) { SC_param_next(stmt, ¶m_number, &apara, &ipara); if (!ipara || !apara) break; pgtype = PIC_get_pgtype(*ipara); if (checkOnly) { switch (ipara->SQLType) { case SQL_LONGVARBINARY: if (0 == pgtype) { if (ci->bytea_as_longvarbinary && 0 != conn->lobj_type) nCallParse = shouldParse; } break; case SQL_CHAR: if (ci->cvt_null_date_string) nCallParse = shouldParse; break; case SQL_VARCHAR: if (ci->drivers.bools_as_char && PG_WIDTH_OF_BOOLS_AS_CHAR == ipara->column_size) nCallParse = shouldParse; break; } } else { BOOL bBytea = FALSE; switch (ipara->SQLType) { case SQL_LONGVARBINARY: if (conn->lobj_type == pgtype || PG_TYPE_OID == pgtype) bNeedsTrans = TRUE; else if (PG_TYPE_BYTEA == pgtype) bBytea = TRUE; else if (0 == pgtype) { if (ci->bytea_as_longvarbinary) bBytea = TRUE; else bNeedsTrans = TRUE; } if (bBytea) if (nCallParse < preferParse) nCallParse = preferParse; break; } } } } if (bNeedsTrans && PARSE_TO_EXEC_ONCE == how_to_prepare) { if (!CC_is_in_trans(conn) && CC_does_autocommit(conn)) nCallParse = doNothing; } return nCallParse; } /* * The execution after all parameters were resolved. */ static RETCODE Exec_with_parameters_resolved(StatementClass *stmt, BOOL *exec_end) { CSTR func = "Exec_with_parameters_resolved"; RETCODE retval; SQLLEN end_row; SQLINTEGER cursor_type, scroll_concurrency; ConnectionClass *conn; QResultClass *res; APDFields *apdopts; IPDFields *ipdopts; BOOL prepare_before_exec = FALSE; *exec_end = FALSE; conn = SC_get_conn(stmt); mylog("%s: copying statement params: trans_status=%d, len=%d, stmt='%s'\n", func, conn->transact_status, strlen(stmt->statement), stmt->statement); #define return DONT_CALL_RETURN_FROM_HERE??? #define RETURN(code) { retval = code; goto cleanup; } ENTER_CONN_CS(conn); /* save the cursor's info before the execution */ cursor_type = stmt->options.cursor_type; scroll_concurrency = stmt->options.scroll_concurrency; /* Prepare the statement if possible at backend side */ if (!stmt->inaccurate_result) { if (HowToPrepareBeforeExec(stmt, FALSE) >= allowParse) prepare_before_exec = TRUE; } inolog("prepare_before_exec=%d srv=%d\n", prepare_before_exec, conn->connInfo.use_server_side_prepare); /* Create the statement with parameters substituted. */ retval = copy_statement_with_parameters(stmt, prepare_before_exec); stmt->current_exec_param = -1; if (retval != SQL_SUCCESS) { stmt->exec_current_row = -1; *exec_end = TRUE; RETURN(retval) /* error msg is passed from the above */ } mylog(" stmt_with_params = '%s'\n", stmt->stmt_with_params); /* * Dummy exection to get the column info. */ if (stmt->inaccurate_result && SC_is_parse_tricky(stmt)) { BOOL in_trans = CC_is_in_trans(conn); BOOL issued_begin = FALSE; QResultClass *curres; stmt->exec_current_row = -1; *exec_end = TRUE; if (!SC_is_pre_executable(stmt)) RETURN(SQL_SUCCESS) if (strnicmp(stmt->stmt_with_params, "BEGIN;", 6) == 0) { /* do nothing */ } else if (!in_trans) { if (issued_begin = CC_begin(conn), !issued_begin) { SC_set_error(stmt, STMT_EXEC_ERROR, "Handle prepare error", func); RETURN(SQL_ERROR) } } /* we are now in a transaction */ res = CC_send_query(conn, stmt->stmt_with_params, NULL, 0, SC_get_ancestor(stmt)); if (!QR_command_maybe_successful(res)) { #ifndef _LEGACY_MODE_ if (PG_VERSION_LT(conn, 8.0)) CC_abort(conn); #endif /* LEGACY_MODE_ */ SC_set_error(stmt, STMT_EXEC_ERROR, "Handle prepare error", func); QR_Destructor(res); RETURN(SQL_ERROR) } SC_set_Result(stmt, res); for (curres = res; !curres->num_fields; curres = curres->next) ; SC_set_Curres(stmt, curres); if (CC_does_autocommit(conn)) { if (issued_begin) CC_commit(conn); } stmt->status = STMT_FINISHED; RETURN(SQL_SUCCESS) } /* * The real execution. */ mylog("about to begin SC_execute\n"); retval = SC_execute(stmt); if (retval == SQL_ERROR) { stmt->exec_current_row = -1; *exec_end = TRUE; RETURN(retval) } res = SC_get_Result(stmt); /* special handling of result for keyset driven cursors */ if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type && SQL_CONCUR_READ_ONLY != stmt->options.scroll_concurrency) { QResultClass *kres; if (kres = res->next, kres) { QR_set_fields(kres, QR_get_fields(res)); QR_set_fields(res, NULL); kres->num_fields = res->num_fields; res->next = NULL; SC_set_Result(stmt, kres); res = kres; } } #ifdef NOT_USED else if (SC_is_concat_prepare_exec(stmt)) { if (res && QR_command_maybe_successful(res)) { QResultClass *kres; kres = res->next; inolog("res->next=%p\n", kres); res->next = NULL; SC_set_Result(stmt, kres); res = kres; SC_set_prepared(stmt, PREPARED_PERMANENTLY); } else { retval = SQL_ERROR; if (stmt->execute_statement) free(stmt->execute_statement); stmt->execute_statement = NULL; } } #endif /* NOT_USED */ #if (ODBCVER >= 0x0300) ipdopts = SC_get_IPDF(stmt); if (ipdopts->param_status_ptr) { switch (retval) { case SQL_SUCCESS: ipdopts->param_status_ptr[stmt->exec_current_row] = SQL_PARAM_SUCCESS; break; case SQL_SUCCESS_WITH_INFO: ipdopts->param_status_ptr[stmt->exec_current_row] = SQL_PARAM_SUCCESS_WITH_INFO; break; default: ipdopts->param_status_ptr[stmt->exec_current_row] = SQL_PARAM_ERROR; break; } } #endif /* ODBCVER */ if (end_row = stmt->exec_end_row, end_row < 0) { apdopts = SC_get_APDF(stmt); end_row = (SQLINTEGER) apdopts->paramset_size - 1; } if (stmt->inaccurate_result || stmt->exec_current_row >= end_row) { *exec_end = TRUE; stmt->exec_current_row = -1; } else stmt->exec_current_row++; if (res) { #if (ODBCVER >= 0x0300) EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); const char *cmd = QR_get_command(res); SQLLEN start_row; if (start_row = stmt->exec_start_row, start_row < 0) start_row = 0; if (retval == SQL_SUCCESS && NULL != cmd && start_row >= end_row && NULL != env && EN_is_odbc3(env)) { int count; if (sscanf(cmd , "UPDATE %d", &count) == 1) ; else if (sscanf(cmd , "DELETE %d", &count) == 1) ; else count = -1; if (0 == count) retval = SQL_NO_DATA; } #endif /* ODBCVER */ stmt->diag_row_count = res->recent_processed_row_count; } /* * The cursor's info was changed ? */ if (retval == SQL_SUCCESS && (stmt->options.cursor_type != cursor_type || stmt->options.scroll_concurrency != scroll_concurrency)) { SC_set_error(stmt, STMT_OPTION_VALUE_CHANGED, "cursor updatability changed", func); retval = SQL_SUCCESS_WITH_INFO; } cleanup: #undef RETURN #undef return LEAVE_CONN_CS(conn); return retval; } int StartRollbackState(StatementClass *stmt) { CSTR func = "StartRollbackState"; int ret; ConnectionClass *conn; ConnInfo *ci = NULL; inolog("%s:%p->internal=%d\n", func, stmt, stmt->internal); conn = SC_get_conn(stmt); if (conn) ci = &conn->connInfo; ret = 0; if (!ci || ci->rollback_on_error < 0) /* default */ { if (conn && PG_VERSION_GE(conn, 8.0)) ret = 2; /* statement rollback */ else ret = 1; /* transaction rollback */ } else { ret = ci->rollback_on_error; if (2 == ret && PG_VERSION_LT(conn, 8.0)) ret = 1; } switch (ret) { case 1: SC_start_tc_stmt(stmt); break; case 2: SC_start_rb_stmt(stmt); break; } return ret; } /* * Must be in a transaction or the subsequent execution * invokes a transaction. */ RETCODE SetStatementSvp(StatementClass *stmt) { CSTR func = "SetStatementSvp"; char esavepoint[32], cmd[64]; ConnectionClass *conn = SC_get_conn(stmt); QResultClass *res; RETCODE ret = SQL_SUCCESS_WITH_INFO; if (CC_is_in_error_trans(conn)) return ret; if (0 == stmt->lock_CC_for_rb) { ENTER_CONN_CS(conn); stmt->lock_CC_for_rb++; } switch (stmt->statement_type) { case STMT_TYPE_SPECIAL: case STMT_TYPE_TRANSACTION: return ret; } if (!SC_accessed_db(stmt)) { BOOL need_savep = FALSE; if (stmt->internal) { if (PG_VERSION_GE(conn, 8.0)) SC_start_rb_stmt(stmt); else SC_start_tc_stmt(stmt); } if (SC_is_rb_stmt(stmt)) { if (CC_is_in_trans(conn)) { need_savep = TRUE; } } if (need_savep) { sprintf(esavepoint, "_EXEC_SVP_%p", stmt); snprintf(cmd, sizeof(cmd), "SAVEPOINT %s", esavepoint); res = CC_send_query(conn, cmd, NULL, 0, NULL); if (QR_command_maybe_successful(res)) { SC_set_accessed_db(stmt); SC_start_rbpoint(stmt); ret = SQL_SUCCESS; } else { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal SAVEPOINT failed", func); ret = SQL_ERROR; } QR_Destructor(res); } else SC_set_accessed_db(stmt); } inolog("%s:%p->accessed=%d\n", func, stmt, SC_accessed_db(stmt)); return ret; } RETCODE DiscardStatementSvp(StatementClass *stmt, RETCODE ret, BOOL errorOnly) { CSTR func = "DiscardStatementSvp"; char esavepoint[32], cmd[64]; ConnectionClass *conn = SC_get_conn(stmt); QResultClass *res; BOOL cmd_success, start_stmt = FALSE; inolog("%s:%p->accessed=%d is_in=%d is_rb=%d is_tc=%d\n", func, stmt, SC_accessed_db(stmt), CC_is_in_trans(conn), SC_is_rb_stmt(stmt), SC_is_tc_stmt(stmt)); switch (ret) { case SQL_NEED_DATA: break; case SQL_ERROR: start_stmt = TRUE; break; default: if (!errorOnly) start_stmt = TRUE; break; } if (!SC_accessed_db(stmt) || !CC_is_in_trans(conn)) goto cleanup; if (!SC_is_rb_stmt(stmt) && !SC_is_tc_stmt(stmt)) goto cleanup; sprintf(esavepoint, "_EXEC_SVP_%p", stmt); if (SQL_ERROR == ret) { if (SC_started_rbpoint(stmt)) { snprintf(cmd, sizeof(cmd), "ROLLBACK to %s", esavepoint); res = CC_send_query(conn, cmd, NULL, IGNORE_ABORT_ON_CONN, NULL); cmd_success = QR_command_maybe_successful(res); QR_Destructor(res); if (!cmd_success) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal ROLLBACK failed", func); CC_abort(conn); goto cleanup; } } else { CC_abort(conn); goto cleanup; } } else if (errorOnly) return ret; inolog("ret=%d\n", ret); if (SQL_NEED_DATA != ret && SC_started_rbpoint(stmt)) { snprintf(cmd, sizeof(cmd), "RELEASE %s", esavepoint); res = CC_send_query(conn, cmd, NULL, IGNORE_ABORT_ON_CONN, NULL); cmd_success = QR_command_maybe_successful(res); QR_Destructor(res); if (!cmd_success) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal RELEASE failed", func); CC_abort(conn); ret = SQL_ERROR; } } cleanup: if (SQL_NEED_DATA != ret) SC_forget_unnamed(stmt); /* unnamed plan is no longer reliable */ if (!SC_is_prepare_statement(stmt) && ONCE_DESCRIBED == stmt->prepared) SC_set_prepared(stmt, NOT_YET_PREPARED); if (start_stmt || SQL_ERROR == ret) { if (stmt->lock_CC_for_rb > 0) { LEAVE_CONN_CS(conn); stmt->lock_CC_for_rb--; } SC_start_stmt(stmt); } return ret; } void SC_setInsertedTable(StatementClass *stmt, RETCODE retval) { const char *cmd = stmt->statement, *ptr; ConnectionClass *conn; size_t len; if (STMT_TYPE_INSERT != stmt->statement_type) return; if (SQL_NEED_DATA == retval) return; conn = SC_get_conn(stmt); #ifdef NOT_USED /* give up the use of lastval() */ if (PG_VERSION_GE(conn, 8.1)) /* lastval() is available */ return; #endif /* NOT_USED */ /*if (!CC_fake_mss(conn)) return;*/ while (isspace((UCHAR) *cmd)) cmd++; if (!*cmd) return; len = 6; if (strnicmp(cmd, "insert", len)) return; cmd += len; while (isspace((UCHAR) *(++cmd))); if (!*cmd) return; len = 4; if (strnicmp(cmd, "into", len)) return; cmd += len; while (isspace((UCHAR) *(++cmd))); if (!*cmd) return; NULL_THE_NAME(conn->schemaIns); NULL_THE_NAME(conn->tableIns); if (!SQL_SUCCEEDED(retval)) return; ptr = NULL; if (IDENTIFIER_QUOTE == *cmd) { if (ptr = strchr(cmd + 1, IDENTIFIER_QUOTE), NULL == ptr) return; if ('.' == ptr[1]) { len = ptr - cmd - 1; STRN_TO_NAME(conn->schemaIns, cmd + 1, len); cmd = ptr + 2; ptr = NULL; } } else { if (ptr = strchr(cmd + 1, '.'), NULL != ptr) { len = ptr - cmd; STRN_TO_NAME(conn->schemaIns, cmd, len); cmd = ptr + 1; ptr = NULL; } } if (IDENTIFIER_QUOTE == *cmd && NULL == ptr) { if (ptr = strchr(cmd + 1, IDENTIFIER_QUOTE), NULL == ptr) return; } if (IDENTIFIER_QUOTE == *cmd) { len = ptr - cmd - 1; STRN_TO_NAME(conn->tableIns, cmd + 1, len); } else { ptr = cmd; while (*ptr && !isspace((UCHAR) *ptr)) ptr++; len = ptr - cmd; STRN_TO_NAME(conn->tableIns, cmd, len); } } /* Execute a prepared SQL statement */ RETCODE SQL_API PGAPI_Execute(HSTMT hstmt, UWORD flag) { CSTR func = "PGAPI_Execute"; StatementClass *stmt = (StatementClass *) hstmt; RETCODE retval = SQL_SUCCESS; ConnectionClass *conn; APDFields *apdopts; IPDFields *ipdopts; SQLLEN i, start_row, end_row; BOOL exec_end, recycled = FALSE, recycle = TRUE; SQLSMALLINT num_params; mylog("%s: entering...%x\n", func, flag); if (!stmt) { SC_log_error(func, "", NULL); mylog("%s: NULL statement so return SQL_INVALID_HANDLE\n", func); return SQL_INVALID_HANDLE; } conn = SC_get_conn(stmt); apdopts = SC_get_APDF(stmt); /* * If the statement is premature, it means we already executed it from * an SQLPrepare/SQLDescribeCol type of scenario. So just return * success. */ if (stmt->prepare && stmt->status == STMT_PREMATURE) { if (stmt->inaccurate_result) { stmt->exec_current_row = -1; SC_recycle_statement(stmt); } else { stmt->status = STMT_FINISHED; if (NULL == SC_get_errormsg(stmt)) { mylog("%s: premature statement but return SQL_SUCCESS\n", func); retval = SQL_SUCCESS; goto cleanup; } else { SC_set_error(stmt,STMT_INTERNAL_ERROR, "premature statement so return SQL_ERROR", func); retval = SQL_ERROR; goto cleanup; } } } mylog("%s: clear errors...\n", func); SC_clear_error(stmt); if (!stmt->statement) { SC_set_error(stmt, STMT_NO_STMTSTRING, "This handle does not have a SQL statement stored in it", func); mylog("%s: problem with handle\n", func); return SQL_ERROR; } #define return DONT_CALL_RETURN_FROM_HERE??? if (stmt->exec_current_row > 0) { /* * executing an array of parameters. * Don't recycle the statement. */ recycle = FALSE; } else if (PREPARED_PERMANENTLY == stmt->prepared || PREPARED_TEMPORARILY == stmt->prepared) { QResultClass *res; /* * re-executing an prepared statement. * Don't recycle the statement but * discard the old result. */ recycle = FALSE; if (res = SC_get_Result(stmt), res) QR_close_result(res, FALSE); } /* * If SQLExecute is being called again, recycle the statement. Note * this should have been done by the application in a call to * SQLFreeStmt(SQL_CLOSE) or SQLCancel. */ else if (stmt->status == STMT_FINISHED) { mylog("%s: recycling statement (should have been done by app)...\n", func); /******** Is this really NEEDED ? ******/ SC_recycle_statement(stmt); recycled = TRUE; } /* Check if the statement is in the correct state */ else if ((stmt->prepare && stmt->status != STMT_READY) || (stmt->status != STMT_ALLOCATED && stmt->status != STMT_READY)) { SC_set_error(stmt, STMT_STATUS_ERROR, "The handle does not point to a statement that is ready to be executed", func); mylog("%s: problem with statement\n", func); retval = SQL_ERROR; goto cleanup; } if (start_row = stmt->exec_start_row, start_row < 0) start_row = 0; if (end_row = stmt->exec_end_row, end_row < 0) end_row = (SQLINTEGER) apdopts->paramset_size - 1; if (stmt->exec_current_row < 0) stmt->exec_current_row = start_row; ipdopts = SC_get_IPDF(stmt); num_params = stmt->num_params; if (num_params < 0) PGAPI_NumParams(stmt, &num_params); if (stmt->exec_current_row == start_row) { /* We sometimes need to know about the PG type of binding parameters even in case of non-prepared statements. */ int nCallParse = doNothing; if (NOT_YET_PREPARED == stmt->prepared) { switch (nCallParse = HowToPrepareBeforeExec(stmt, TRUE)) { case shouldParse: if (retval = prepareParameters(stmt), SQL_ERROR == retval) goto cleanup; break; } } mylog("prepareParameters was %s called, prepare state:%d\n", shouldParse == nCallParse ? "" : "not", stmt->prepare); if (ipdopts->param_processed_ptr) *ipdopts->param_processed_ptr = 0; #if (ODBCVER >= 0x0300) /* * Initialize param_status_ptr */ if (ipdopts->param_status_ptr) { for (i = 0; i <= end_row; i++) ipdopts->param_status_ptr[i] = SQL_PARAM_UNUSED; } #endif /* ODBCVER */ if (recycle && !recycled) SC_recycle_statement(stmt); if (isSqlServr() && !stmt->internal && 0 != stmt->prepare && PG_VERSION_LT(conn, 8.4) && SC_can_parse_statement(stmt)) parse_sqlsvr(stmt); } next_param_row: #if (ODBCVER >= 0x0300) if (apdopts->param_operation_ptr) { while (apdopts->param_operation_ptr[stmt->exec_current_row] == SQL_PARAM_IGNORE) { if (stmt->exec_current_row >= end_row) { stmt->exec_current_row = -1; retval = SQL_SUCCESS; goto cleanup; } ++stmt->exec_current_row; } } /* * Initialize the current row status */ if (ipdopts->param_status_ptr) ipdopts->param_status_ptr[stmt->exec_current_row] = SQL_PARAM_ERROR; #endif /* ODBCVER */ /* * Check if statement has any data-at-execute parameters when it is * not in SC_pre_execute. */ if (!stmt->pre_executing) { /* * The bound parameters could have possibly changed since the last * execute of this statement? Therefore check for params and * re-copy. */ SQLULEN offset = apdopts->param_offset_ptr ? *apdopts->param_offset_ptr : 0; SQLINTEGER bind_size = apdopts->param_bind_type; SQLLEN current_row = stmt->exec_current_row < 0 ? 0 : stmt->exec_current_row; Int4 num_p = num_params < apdopts->allocated ? num_params : apdopts->allocated; /* * Increment the number of currently processed rows */ if (ipdopts->param_processed_ptr) (*ipdopts->param_processed_ptr)++; stmt->data_at_exec = -1; for (i = 0; i < num_p; i++) { SQLLEN *pcVal = apdopts->parameters[i].used; apdopts->parameters[i].data_at_exec = FALSE; if (pcVal) { if (bind_size > 0) pcVal = LENADDR_SHIFT(pcVal, offset + bind_size * current_row); else pcVal = LENADDR_SHIFT(pcVal, offset) + current_row; if (*pcVal == SQL_DATA_AT_EXEC || *pcVal <= SQL_LEN_DATA_AT_EXEC_OFFSET) apdopts->parameters[i].data_at_exec = TRUE; } /* Check for data at execution parameters */ if (apdopts->parameters[i].data_at_exec) { mylog("The %dth parameter of %d-row is data at exec(%d)\n", i, current_row, *pcVal); if (stmt->data_at_exec < 0) stmt->data_at_exec = 1; else stmt->data_at_exec++; } } /* * If there are some data at execution parameters, return need * data */ /* * SQLParamData and SQLPutData will be used to send params and * execute the statement. */ if (stmt->data_at_exec > 0) { retval = SQL_NEED_DATA; goto cleanup; } } if (0 != (flag & PODBC_WITH_HOLD)) SC_set_with_hold(stmt); retval = Exec_with_parameters_resolved(stmt, &exec_end); if (!exec_end) { stmt->curr_param_result = 0; goto next_param_row; } cleanup: mylog("retval=%d\n", retval); SC_setInsertedTable(stmt, retval); #undef return if (stmt->internal) retval = DiscardStatementSvp(stmt, retval, FALSE); return retval; } RETCODE SQL_API PGAPI_Transact(HENV henv, HDBC hdbc, SQLUSMALLINT fType) { CSTR func = "PGAPI_Transact"; ConnectionClass *conn; char ok; int lf; mylog("entering %s: hdbc=%p, henv=%p\n", func, hdbc, henv); if (hdbc == SQL_NULL_HDBC && henv == SQL_NULL_HENV) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } /* * If hdbc is null and henv is valid, it means transact all * connections on that henv. */ if (hdbc == SQL_NULL_HDBC && henv != SQL_NULL_HENV) { ConnectionClass * const *conns = getConnList(); const int conn_count = getConnCount(); for (lf = 0; lf < conn_count; lf++) { conn = conns[lf]; if (conn && CC_get_env(conn) == henv) if (PGAPI_Transact(henv, (HDBC) conn, fType) != SQL_SUCCESS) return SQL_ERROR; } return SQL_SUCCESS; } conn = (ConnectionClass *) hdbc; if (fType != SQL_COMMIT && fType != SQL_ROLLBACK) { CC_set_error(conn, CONN_INVALID_ARGUMENT_NO, "PGAPI_Transact can only be called with SQL_COMMIT or SQL_ROLLBACK as parameter", func); return SQL_ERROR; } /* If manual commit and in transaction, then proceed. */ if (CC_loves_visible_trans(conn) && CC_is_in_trans(conn)) { mylog("PGAPI_Transact: sending on conn %p '%d'\n", conn, fType); ok = (SQL_COMMIT == fType) ? CC_commit(conn) : CC_abort(conn); if (!ok) { /* error msg will be in the connection */ CC_on_abort(conn, NO_TRANS); CC_log_error(func, "", conn); return SQL_ERROR; } } return SQL_SUCCESS; } RETCODE SQL_API PGAPI_Cancel(HSTMT hstmt) /* Statement to cancel. */ { CSTR func = "PGAPI_Cancel"; StatementClass *stmt = (StatementClass *) hstmt, *estmt; ConnectionClass *conn; RETCODE ret = SQL_SUCCESS; BOOL entered_cs = FALSE; mylog("%s: entering...\n", func); /* Check if this can handle canceling in the middle of a SQLPutData? */ if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } conn = SC_get_conn(stmt); #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(stmt); */ if (stmt->execute_delegate) estmt = stmt->execute_delegate; else estmt = stmt; /* * Not in the middle of SQLParamData/SQLPutData so cancel like a * close. */ if (estmt->data_at_exec < 0) { /* * Tell the Backend that we're cancelling this request */ if (estmt->status == STMT_EXECUTING) { if (!CC_send_cancel_request(conn)) { ret = SQL_ERROR; } goto cleanup; } /* * MAJOR HACK for Windows to reset the driver manager's cursor * state: Because of what seems like a bug in the Odbc driver * manager, SQLCancel does not act like a SQLFreeStmt(CLOSE), as * many applications depend on this behavior. So, this brute * force method calls the driver manager's function on behalf of * the application. */ if (conn->driver_version < 0x0350) { #ifdef WIN32 ConnInfo *ci = &(conn->connInfo); if (ci->drivers.cancel_as_freestmt) { typedef SQLRETURN (SQL_API *SQLAPIPROC)(); HMODULE hmodule; SQLAPIPROC addr; hmodule = GetModuleHandle("ODBC32"); addr = (SQLAPIPROC) GetProcAddress(hmodule, "SQLFreeStmt"); ret = addr((char *) (stmt->phstmt) - 96, SQL_CLOSE); } else #endif /* WIN32 */ { ENTER_STMT_CS(stmt); entered_cs = TRUE; SC_clear_error(hstmt); ret = PGAPI_FreeStmt(hstmt, SQL_CLOSE); } mylog("PGAPI_Cancel: PGAPI_FreeStmt returned %d\n", ret); } goto cleanup; } /* In the middle of SQLParamData/SQLPutData, so cancel that. */ /* * Note, any previous data-at-exec buffers will be freed in the * recycle */ /* if they call SQLExecDirect or SQLExecute again. */ ENTER_STMT_CS(stmt); entered_cs = TRUE; SC_clear_error(stmt); estmt->data_at_exec = -1; estmt->current_exec_param = -1; estmt->put_data = FALSE; cancelNeedDataState(estmt); cleanup: #undef return if (entered_cs) { if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); } return ret; } /* * Returns the SQL string as modified by the driver. * Currently, just copy the input string without modification * observing buffer limits and truncation. */ RETCODE SQL_API PGAPI_NativeSql(HDBC hdbc, const SQLCHAR FAR * szSqlStrIn, SQLINTEGER cbSqlStrIn, SQLCHAR FAR * szSqlStr, SQLINTEGER cbSqlStrMax, SQLINTEGER FAR * pcbSqlStr) { CSTR func = "PGAPI_NativeSql"; size_t len = 0; char *ptr; ConnectionClass *conn = (ConnectionClass *) hdbc; RETCODE result; mylog("%s: entering...cbSqlStrIn=%d\n", func, cbSqlStrIn); ptr = (cbSqlStrIn == 0) ? "" : make_string(szSqlStrIn, cbSqlStrIn, NULL, 0); if (!ptr) { CC_set_error(conn, CONN_NO_MEMORY_ERROR, "No memory available to store native sql string", func); return SQL_ERROR; } result = SQL_SUCCESS; len = strlen(ptr); if (szSqlStr) { strncpy_null((char *) szSqlStr, ptr, cbSqlStrMax); if (len >= cbSqlStrMax) { result = SQL_SUCCESS_WITH_INFO; CC_set_error(conn, CONN_TRUNCATED, "The buffer was too small for the NativeSQL.", func); } } if (pcbSqlStr) *pcbSqlStr = (SQLINTEGER) len; if (cbSqlStrIn) free(ptr); return result; } /* * Supplies parameter data at execution time. * Used in conjuction with SQLPutData. */ RETCODE SQL_API PGAPI_ParamData(HSTMT hstmt, PTR FAR * prgbValue) { CSTR func = "PGAPI_ParamData"; StatementClass *stmt = (StatementClass *) hstmt, *estmt; APDFields *apdopts; IPDFields *ipdopts; RETCODE retval; int i; Int2 num_p; ConnectionClass *conn = NULL; mylog("%s: entering...\n", func); if (!stmt) { SC_log_error(func, "", NULL); retval = SQL_INVALID_HANDLE; goto cleanup; } conn = SC_get_conn(stmt); estmt = stmt->execute_delegate ? stmt->execute_delegate : stmt; apdopts = SC_get_APDF(estmt); mylog("%s: data_at_exec=%d, params_alloc=%d\n", func, estmt->data_at_exec, apdopts->allocated); #define return DONT_CALL_RETURN_FROM_HERE??? if (SC_AcceptedCancelRequest(stmt)) { SC_set_error(stmt, STMT_OPERATION_CANCELLED, "Cancel the statement, sorry", func); retval = SQL_ERROR; goto cleanup; } if (estmt->data_at_exec < 0) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "No execution-time parameters for this statement", func); retval = SQL_ERROR; goto cleanup; } if (estmt->data_at_exec > apdopts->allocated) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Too many execution-time parameters were present", func); retval = SQL_ERROR; goto cleanup; } /* close the large object */ if (estmt->lobj_fd >= 0) { odbc_lo_close(conn, estmt->lobj_fd); /* commit transaction if needed */ if (!CC_cursor_count(conn) && CC_does_autocommit(conn)) { if (!CC_commit(conn)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Could not commit (in-line) a transaction", func); retval = SQL_ERROR; goto cleanup; } } estmt->lobj_fd = -1; } /* Done, now copy the params and then execute the statement */ ipdopts = SC_get_IPDF(estmt); inolog("ipdopts=%p\n", ipdopts); if (estmt->data_at_exec == 0) { BOOL exec_end; UWORD flag = SC_is_with_hold(stmt) ? PODBC_WITH_HOLD : 0; retval = Exec_with_parameters_resolved(estmt, &exec_end); if (exec_end) { /**SC_reset_delegate(retval, stmt);**/ retval = dequeueNeedDataCallback(retval, stmt); goto cleanup; } else { stmt->curr_param_result = 0; } if (retval = PGAPI_Execute(estmt, flag), SQL_NEED_DATA != retval) { goto cleanup; } } /* * Set beginning param; if first time SQLParamData is called , start * at 0. Otherwise, start at the last parameter + 1. */ i = estmt->current_exec_param >= 0 ? estmt->current_exec_param + 1 : 0; num_p = estmt->num_params; if (num_p < 0) PGAPI_NumParams(estmt, &num_p); inolog("i=%d allocated=%d num_p=%d\n", i, apdopts->allocated, num_p); if (num_p > apdopts->allocated) num_p = apdopts->allocated; /* At least 1 data at execution parameter, so Fill in the token value */ for (; i < num_p; i++) { inolog("i=%d", i); if (apdopts->parameters[i].data_at_exec) { inolog(" at exec buffer=%p", apdopts->parameters[i].buffer); estmt->data_at_exec--; estmt->current_exec_param = i; estmt->put_data = FALSE; if (prgbValue) { /* returns token here */ if (stmt->execute_delegate) { SQLULEN offset = apdopts->param_offset_ptr ? *apdopts->param_offset_ptr : 0; SQLLEN perrow = apdopts->param_bind_type > 0 ? apdopts->param_bind_type : apdopts->parameters[i].buflen; inolog(" offset=%d perrow=%d", offset, perrow); *prgbValue = apdopts->parameters[i].buffer + offset + estmt->exec_current_row * perrow; } else *prgbValue = apdopts->parameters[i].buffer; } break; } inolog("\n"); } retval = SQL_NEED_DATA; inolog("return SQL_NEED_DATA\n"); cleanup: #undef return SC_setInsertedTable(stmt, retval); if (stmt->internal) retval = DiscardStatementSvp(stmt, retval, FALSE); mylog("%s: returning %d\n", func, retval); return retval; } /* * Supplies parameter data at execution time. * Used in conjunction with SQLParamData. */ RETCODE SQL_API PGAPI_PutData(HSTMT hstmt, PTR rgbValue, SQLLEN cbValue) { CSTR func = "PGAPI_PutData"; StatementClass *stmt = (StatementClass *) hstmt, *estmt; ConnectionClass *conn; RETCODE retval = SQL_SUCCESS; APDFields *apdopts; IPDFields *ipdopts; PutDataInfo *pdata; SQLLEN old_pos; ParameterInfoClass *current_param; ParameterImplClass *current_iparam; PutDataClass *current_pdata; char *buffer, *putbuf, *allocbuf = NULL; Int2 ctype; SQLLEN putlen; BOOL lenset = FALSE, handling_lo = FALSE; mylog("%s: entering...\n", func); #define return DONT_CALL_RETURN_FROM_HERE??? if (!stmt) { SC_log_error(func, "", NULL); retval = SQL_INVALID_HANDLE; goto cleanup; } if (SC_AcceptedCancelRequest(stmt)) { SC_set_error(stmt, STMT_OPERATION_CANCELLED, "Cancel the statement, sorry.", func); retval = SQL_ERROR; goto cleanup; } estmt = stmt->execute_delegate ? stmt->execute_delegate : stmt; apdopts = SC_get_APDF(estmt); if (estmt->current_exec_param < 0) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Previous call was not SQLPutData or SQLParamData", func); retval = SQL_ERROR; goto cleanup; } current_param = &(apdopts->parameters[estmt->current_exec_param]); ipdopts = SC_get_IPDF(estmt); current_iparam = &(ipdopts->parameters[estmt->current_exec_param]); pdata = SC_get_PDTI(estmt); current_pdata = &(pdata->pdata[estmt->current_exec_param]); ctype = current_param->CType; conn = SC_get_conn(estmt); if (ctype == SQL_C_DEFAULT) { ctype = sqltype_to_default_ctype(conn, current_iparam->SQLType); if (SQL_C_WCHAR == ctype && CC_default_is_c(conn)) ctype = SQL_C_CHAR; } if (SQL_NTS == cbValue) { #ifdef UNICODE_SUPPORT if (SQL_C_WCHAR == ctype) { putlen = WCLEN * ucs2strlen((SQLWCHAR *) rgbValue); lenset = TRUE; } else #endif /* UNICODE_SUPPORT */ if (SQL_C_CHAR == ctype) { putlen = strlen(rgbValue); lenset = TRUE; } } if (!lenset) { if (cbValue < 0) putlen = cbValue; else #ifdef UNICODE_SUPPORT if (ctype == SQL_C_CHAR || ctype == SQL_C_BINARY || ctype == SQL_C_WCHAR) #else if (ctype == SQL_C_CHAR || ctype == SQL_C_BINARY) #endif /* UNICODE_SUPPORT */ putlen = cbValue; else putlen = ctype_length(ctype); } putbuf = rgbValue; handling_lo = (PIC_dsp_pgtype(conn, *current_iparam) == conn->lobj_type); if (handling_lo && SQL_C_CHAR == ctype) { allocbuf = malloc(putlen / 2 + 1); if (allocbuf) { pg_hex2bin(rgbValue, allocbuf, putlen); putbuf = allocbuf; putlen /= 2; } } if (!estmt->put_data) { /* first call */ mylog("PGAPI_PutData: (1) cbValue = %d\n", cbValue); estmt->put_data = TRUE; current_pdata->EXEC_used = (SQLLEN *) malloc(sizeof(SQLLEN)); if (!current_pdata->EXEC_used) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_PutData (1)", func); retval = SQL_ERROR; goto cleanup; } *current_pdata->EXEC_used = putlen; if (cbValue == SQL_NULL_DATA) { retval = SQL_SUCCESS; goto cleanup; } /* Handle Long Var Binary with Large Objects */ /* if (current_iparam->SQLType == SQL_LONGVARBINARY) */ if (handling_lo) { /* begin transaction if needed */ if (!CC_is_in_trans(conn)) { if (!CC_begin(conn)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Could not begin (in-line) a transaction", func); retval = SQL_ERROR; goto cleanup; } } /* store the oid */ current_pdata->lobj_oid = odbc_lo_creat(conn, INV_READ | INV_WRITE); if (current_pdata->lobj_oid == 0) { SC_set_error(stmt, STMT_EXEC_ERROR, "Couldnt create large object.", func); retval = SQL_ERROR; goto cleanup; } /* * major hack -- to allow convert to see somethings there have * to modify convert to handle this better */ /***current_param->EXEC_buffer = (char *) ¤t_param->lobj_oid;***/ /* store the fd */ estmt->lobj_fd = odbc_lo_open(conn, current_pdata->lobj_oid, INV_WRITE); if (estmt->lobj_fd < 0) { SC_set_error(stmt, STMT_EXEC_ERROR, "Couldnt open large object for writing.", func); retval = SQL_ERROR; goto cleanup; } retval = odbc_lo_write(conn, estmt->lobj_fd, putbuf, (Int4) putlen); mylog("lo_write: cbValue=%d, wrote %d bytes\n", putlen, retval); } else { current_pdata->EXEC_buffer = malloc(putlen + 1); if (!current_pdata->EXEC_buffer) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_PutData (2)", func); retval = SQL_ERROR; goto cleanup; } memcpy(current_pdata->EXEC_buffer, putbuf, putlen); current_pdata->EXEC_buffer[putlen] = '\0'; } } else { /* calling SQLPutData more than once */ mylog("PGAPI_PutData: (>1) cbValue = %d\n", cbValue); /* if (current_iparam->SQLType == SQL_LONGVARBINARY) */ if (handling_lo) { /* the large object fd is in EXEC_buffer */ retval = odbc_lo_write(conn, estmt->lobj_fd, putbuf, (Int4) putlen); mylog("lo_write(2): cbValue = %d, wrote %d bytes\n", putlen, retval); *current_pdata->EXEC_used += putlen; } else { buffer = current_pdata->EXEC_buffer; old_pos = *current_pdata->EXEC_used; if (putlen > 0) { SQLLEN used = *current_pdata->EXEC_used + putlen, allocsize; for (allocsize = (1 << 4); allocsize <= used; allocsize <<= 1) ; mylog(" cbValue = %d, old_pos = %d, *used = %d\n", putlen, old_pos, used); /* dont lose the old pointer in case out of memory */ buffer = realloc(current_pdata->EXEC_buffer, allocsize); if (!buffer) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR,"Out of memory in PGAPI_PutData (3)", func); retval = SQL_ERROR; goto cleanup; } memcpy(&buffer[old_pos], putbuf, putlen); buffer[used] = '\0'; /* reassign buffer incase realloc moved it */ *current_pdata->EXEC_used = used; current_pdata->EXEC_buffer = buffer; } else { SC_set_error(stmt, STMT_INTERNAL_ERROR, "bad cbValue", func); retval = SQL_ERROR; goto cleanup; } } } retval = SQL_SUCCESS; cleanup: #undef return if (allocbuf) free(allocbuf); if (stmt->internal) retval = DiscardStatementSvp(stmt, retval, TRUE); return retval; } psqlodbc-09.03.0300/lobj.c000644 001752 000000 00000006000 12335653444 015266 0ustar00saitowheel000000 000000 /*-------- * Module: lobj.c * * Description: This module contains routines related to manipulating * large objects. * * Classes: none * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *-------- */ #include "lobj.h" #include "connection.h" OID odbc_lo_creat(ConnectionClass *conn, int mode) { LO_ARG argv[1]; Int4 retval, result_len; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = mode; if (!CC_send_function(conn, LO_CREAT, &retval, &result_len, 1, argv, 1)) return 0; /* invalid oid */ else return (OID) retval; } int odbc_lo_open(ConnectionClass *conn, int lobjId, int mode) { int fd; int result_len; LO_ARG argv[2]; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = lobjId; argv[1].isint = 1; argv[1].len = 4; argv[1].u.integer = mode; if (!CC_send_function(conn, LO_OPEN, &fd, &result_len, 1, argv, 2)) return -1; if (fd >= 0 && odbc_lo_lseek(conn, fd, 0L, SEEK_SET) < 0) return -1; return fd; } int odbc_lo_close(ConnectionClass *conn, int fd) { LO_ARG argv[1]; int retval, result_len; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; if (!CC_send_function(conn, LO_CLOSE, &retval, &result_len, 1, argv, 1)) return -1; else return retval; } Int4 odbc_lo_read(ConnectionClass *conn, int fd, char *buf, Int4 len) { LO_ARG argv[2]; Int4 result_len; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; argv[1].isint = 1; argv[1].len = 4; argv[1].u.integer = len; if (!CC_send_function(conn, LO_READ, (int *) buf, &result_len, 0, argv, 2)) return -1; else return result_len; } Int4 odbc_lo_write(ConnectionClass *conn, int fd, char *buf, Int4 len) { LO_ARG argv[2]; Int4 retval, result_len; if (len <= 0) return 0; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; argv[1].isint = 0; argv[1].len = len; argv[1].u.ptr = (char *) buf; if (!CC_send_function(conn, LO_WRITE, &retval, &result_len, 1, argv, 2)) return -1; else return retval; } Int4 odbc_lo_lseek(ConnectionClass *conn, int fd, int offset, Int4 whence) { LO_ARG argv[3]; Int4 retval, result_len; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; argv[1].isint = 1; argv[1].len = 4; argv[1].u.integer = offset; argv[2].isint = 1; argv[2].len = 4; argv[2].u.integer = whence; if (!CC_send_function(conn, LO_LSEEK, &retval, &result_len, 1, argv, 3)) return -1; else return retval; } Int4 odbc_lo_tell(ConnectionClass *conn, int fd) { LO_ARG argv[1]; Int4 retval, result_len; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; if (!CC_send_function(conn, LO_TELL, &retval, &result_len, 1, argv, 1)) return -1; else return retval; } Int4 odbc_lo_unlink(ConnectionClass *conn, OID lobjId) { LO_ARG argv[1]; Int4 retval, result_len; argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = lobjId; if (!CC_send_function(conn, LO_UNLINK, &retval, &result_len, 1, argv, 1)) return -1; else return retval; } psqlodbc-09.03.0300/md5.c000644 001752 000000 00000023436 12335653444 015041 0ustar00saitowheel000000 000000 /* * md5.c * * Implements the MD5 Message-Digest Algorithm as specified in * RFC 1321. This implementation is a simple one, in that it * needs every input byte to be buffered before doing any * calculations. I do not expect this file to be used for * general purpose MD5'ing of large amounts of data, only for * generating hashed passwords from limited input. * * Sverre H. Huseby * * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California */ /* * NOTE: * * This file was copied from backend/libpq once. */ #include "md5.h" /* * PRIVATE FUNCTIONS */ /* * The returned array is allocated using malloc. the caller should free it * when it is no longer needed. */ static uint8 * createPaddedCopyWithLength(uint8 *b, uint32 *l) { uint8 *ret; uint32 q; uint32 len, newLen448; uint32 len_high, len_low; /* 64-bit value split into 32-bit sections */ len = ((b == NULL) ? 0 : *l); newLen448 = len + 64 - (len % 64) - 8; if (newLen448 <= len) newLen448 += 64; *l = newLen448 + 8; if ((ret = (uint8 *) malloc(sizeof(uint8) * *l)) == NULL) return NULL; if (b != NULL) memcpy(ret, b, sizeof(uint8) * len); /* pad */ ret[len] = 0x80; for (q = len + 1; q < newLen448; q++) ret[q] = 0x00; /* append length as a 64 bit bitcount */ len_low = len; /* split into two 32-bit values */ /* we only look at the bottom 32-bits */ len_high = len >> 29; len_low <<= 3; q = newLen448; ret[q++] = (len_low & 0xff); len_low >>= 8; ret[q++] = (len_low & 0xff); len_low >>= 8; ret[q++] = (len_low & 0xff); len_low >>= 8; ret[q++] = (len_low & 0xff); ret[q++] = (len_high & 0xff); len_high >>= 8; ret[q++] = (len_high & 0xff); len_high >>= 8; ret[q++] = (len_high & 0xff); len_high >>= 8; ret[q] = (len_high & 0xff); return ret; } #define F(x, y, z) (((x) & (y)) | (~(x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | ~(z))) #define ROT_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) static void doTheRounds(uint32 X[16], uint32 state[4]) { uint32 a, b, c, d; a = state[0]; b = state[1]; c = state[2]; d = state[3]; /* round 1 */ a = b + ROT_LEFT((a + F(b, c, d) + X[0] + 0xd76aa478), 7); /* 1 */ d = a + ROT_LEFT((d + F(a, b, c) + X[1] + 0xe8c7b756), 12); /* 2 */ c = d + ROT_LEFT((c + F(d, a, b) + X[2] + 0x242070db), 17); /* 3 */ b = c + ROT_LEFT((b + F(c, d, a) + X[3] + 0xc1bdceee), 22); /* 4 */ a = b + ROT_LEFT((a + F(b, c, d) + X[4] + 0xf57c0faf), 7); /* 5 */ d = a + ROT_LEFT((d + F(a, b, c) + X[5] + 0x4787c62a), 12); /* 6 */ c = d + ROT_LEFT((c + F(d, a, b) + X[6] + 0xa8304613), 17); /* 7 */ b = c + ROT_LEFT((b + F(c, d, a) + X[7] + 0xfd469501), 22); /* 8 */ a = b + ROT_LEFT((a + F(b, c, d) + X[8] + 0x698098d8), 7); /* 9 */ d = a + ROT_LEFT((d + F(a, b, c) + X[9] + 0x8b44f7af), 12); /* 10 */ c = d + ROT_LEFT((c + F(d, a, b) + X[10] + 0xffff5bb1), 17); /* 11 */ b = c + ROT_LEFT((b + F(c, d, a) + X[11] + 0x895cd7be), 22); /* 12 */ a = b + ROT_LEFT((a + F(b, c, d) + X[12] + 0x6b901122), 7); /* 13 */ d = a + ROT_LEFT((d + F(a, b, c) + X[13] + 0xfd987193), 12); /* 14 */ c = d + ROT_LEFT((c + F(d, a, b) + X[14] + 0xa679438e), 17); /* 15 */ b = c + ROT_LEFT((b + F(c, d, a) + X[15] + 0x49b40821), 22); /* 16 */ /* round 2 */ a = b + ROT_LEFT((a + G(b, c, d) + X[1] + 0xf61e2562), 5); /* 17 */ d = a + ROT_LEFT((d + G(a, b, c) + X[6] + 0xc040b340), 9); /* 18 */ c = d + ROT_LEFT((c + G(d, a, b) + X[11] + 0x265e5a51), 14); /* 19 */ b = c + ROT_LEFT((b + G(c, d, a) + X[0] + 0xe9b6c7aa), 20); /* 20 */ a = b + ROT_LEFT((a + G(b, c, d) + X[5] + 0xd62f105d), 5); /* 21 */ d = a + ROT_LEFT((d + G(a, b, c) + X[10] + 0x02441453), 9); /* 22 */ c = d + ROT_LEFT((c + G(d, a, b) + X[15] + 0xd8a1e681), 14); /* 23 */ b = c + ROT_LEFT((b + G(c, d, a) + X[4] + 0xe7d3fbc8), 20); /* 24 */ a = b + ROT_LEFT((a + G(b, c, d) + X[9] + 0x21e1cde6), 5); /* 25 */ d = a + ROT_LEFT((d + G(a, b, c) + X[14] + 0xc33707d6), 9); /* 26 */ c = d + ROT_LEFT((c + G(d, a, b) + X[3] + 0xf4d50d87), 14); /* 27 */ b = c + ROT_LEFT((b + G(c, d, a) + X[8] + 0x455a14ed), 20); /* 28 */ a = b + ROT_LEFT((a + G(b, c, d) + X[13] + 0xa9e3e905), 5); /* 29 */ d = a + ROT_LEFT((d + G(a, b, c) + X[2] + 0xfcefa3f8), 9); /* 30 */ c = d + ROT_LEFT((c + G(d, a, b) + X[7] + 0x676f02d9), 14); /* 31 */ b = c + ROT_LEFT((b + G(c, d, a) + X[12] + 0x8d2a4c8a), 20); /* 32 */ /* round 3 */ a = b + ROT_LEFT((a + H(b, c, d) + X[5] + 0xfffa3942), 4); /* 33 */ d = a + ROT_LEFT((d + H(a, b, c) + X[8] + 0x8771f681), 11); /* 34 */ c = d + ROT_LEFT((c + H(d, a, b) + X[11] + 0x6d9d6122), 16); /* 35 */ b = c + ROT_LEFT((b + H(c, d, a) + X[14] + 0xfde5380c), 23); /* 36 */ a = b + ROT_LEFT((a + H(b, c, d) + X[1] + 0xa4beea44), 4); /* 37 */ d = a + ROT_LEFT((d + H(a, b, c) + X[4] + 0x4bdecfa9), 11); /* 38 */ c = d + ROT_LEFT((c + H(d, a, b) + X[7] + 0xf6bb4b60), 16); /* 39 */ b = c + ROT_LEFT((b + H(c, d, a) + X[10] + 0xbebfbc70), 23); /* 40 */ a = b + ROT_LEFT((a + H(b, c, d) + X[13] + 0x289b7ec6), 4); /* 41 */ d = a + ROT_LEFT((d + H(a, b, c) + X[0] + 0xeaa127fa), 11); /* 42 */ c = d + ROT_LEFT((c + H(d, a, b) + X[3] + 0xd4ef3085), 16); /* 43 */ b = c + ROT_LEFT((b + H(c, d, a) + X[6] + 0x04881d05), 23); /* 44 */ a = b + ROT_LEFT((a + H(b, c, d) + X[9] + 0xd9d4d039), 4); /* 45 */ d = a + ROT_LEFT((d + H(a, b, c) + X[12] + 0xe6db99e5), 11); /* 46 */ c = d + ROT_LEFT((c + H(d, a, b) + X[15] + 0x1fa27cf8), 16); /* 47 */ b = c + ROT_LEFT((b + H(c, d, a) + X[2] + 0xc4ac5665), 23); /* 48 */ /* round 4 */ a = b + ROT_LEFT((a + I(b, c, d) + X[0] + 0xf4292244), 6); /* 49 */ d = a + ROT_LEFT((d + I(a, b, c) + X[7] + 0x432aff97), 10); /* 50 */ c = d + ROT_LEFT((c + I(d, a, b) + X[14] + 0xab9423a7), 15); /* 51 */ b = c + ROT_LEFT((b + I(c, d, a) + X[5] + 0xfc93a039), 21); /* 52 */ a = b + ROT_LEFT((a + I(b, c, d) + X[12] + 0x655b59c3), 6); /* 53 */ d = a + ROT_LEFT((d + I(a, b, c) + X[3] + 0x8f0ccc92), 10); /* 54 */ c = d + ROT_LEFT((c + I(d, a, b) + X[10] + 0xffeff47d), 15); /* 55 */ b = c + ROT_LEFT((b + I(c, d, a) + X[1] + 0x85845dd1), 21); /* 56 */ a = b + ROT_LEFT((a + I(b, c, d) + X[8] + 0x6fa87e4f), 6); /* 57 */ d = a + ROT_LEFT((d + I(a, b, c) + X[15] + 0xfe2ce6e0), 10); /* 58 */ c = d + ROT_LEFT((c + I(d, a, b) + X[6] + 0xa3014314), 15); /* 59 */ b = c + ROT_LEFT((b + I(c, d, a) + X[13] + 0x4e0811a1), 21); /* 60 */ a = b + ROT_LEFT((a + I(b, c, d) + X[4] + 0xf7537e82), 6); /* 61 */ d = a + ROT_LEFT((d + I(a, b, c) + X[11] + 0xbd3af235), 10); /* 62 */ c = d + ROT_LEFT((c + I(d, a, b) + X[2] + 0x2ad7d2bb), 15); /* 63 */ b = c + ROT_LEFT((b + I(c, d, a) + X[9] + 0xeb86d391), 21); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; } static int calculateDigestFromBuffer(uint8 *b, uint32 len, uint8 sum[16]) { register uint32 i, j, k, newI; uint32 l; uint8 *input; register uint32 *wbp; uint32 workBuff[16], state[4]; l = len; state[0] = 0x67452301; state[1] = 0xEFCDAB89; state[2] = 0x98BADCFE; state[3] = 0x10325476; if ((input = createPaddedCopyWithLength(b, &l)) == NULL) return 0; for (i = 0;;) { if ((newI = i + 16 * 4) > l) break; k = i + 3; for (j = 0; j < 16; j++) { wbp = (workBuff + j); *wbp = input[k--]; *wbp <<= 8; *wbp |= input[k--]; *wbp <<= 8; *wbp |= input[k--]; *wbp <<= 8; *wbp |= input[k]; k += 7; } doTheRounds(workBuff, state); i = newI; } free(input); j = 0; for (i = 0; i < 4; i++) { k = state[i]; sum[j++] = (k & 0xff); k >>= 8; sum[j++] = (k & 0xff); k >>= 8; sum[j++] = (k & 0xff); k >>= 8; sum[j++] = (k & 0xff); } return 1; } static void bytesToHex(uint8 b[16], char *s) { static const char *hex = "0123456789abcdef"; int q, w; for (q = 0, w = 0; q < 16; q++) { s[w++] = hex[(b[q] >> 4) & 0x0F]; s[w++] = hex[b[q] & 0x0F]; } s[w] = '\0'; } /* * PUBLIC FUNCTIONS */ /* * md5_hash * * Calculates the MD5 sum of the bytes in a buffer. * * SYNOPSIS #include "crypt.h" * int md5_hash(const void *buff, size_t len, char *hexsum) * * INPUT buff the buffer containing the bytes that you want * the MD5 sum of. * len number of bytes in the buffer. * * OUTPUT hexsum the MD5 sum as a '\0'-terminated string of * hexadecimal digits. an MD5 sum is 16 bytes long. * each byte is represented by two heaxadecimal * characters. you thus need to provide an array * of 33 characters, including the trailing '\0'. * * RETURNS false on failure (out of memory for internal buffers) or * true on success. * * STANDARDS MD5 is described in RFC 1321. * * AUTHOR Sverre H. Huseby * */ bool md5_hash(const void *buff, size_t len, char *hexsum) { uint8 sum[16]; if (!calculateDigestFromBuffer((uint8 *) buff, (uint32) len, sum)) return false; bytesToHex(sum, hexsum); return true; } /* * Computes MD5 checksum of "passwd" (a null-terminated string) followed * by "salt" (which need not be null-terminated). * * Output format is "md5" followed by a 32-hex-digit MD5 checksum. * Hence, the output buffer "buf" must be at least 36 bytes long. * * Returns TRUE if okay, FALSE on error (out of memory). */ bool EncryptMD5(const char *passwd, const char *salt, size_t salt_len, char *buf) { size_t passwd_len = strlen(passwd); char *crypt_buf = malloc(passwd_len + salt_len + 1); bool ret; if (!crypt_buf) return false; /* * Place salt at the end because it may be known by users trying to * crack the MD5 output. */ memcpy(crypt_buf, passwd, passwd_len); memcpy(crypt_buf + passwd_len, salt, salt_len); strcpy(buf, "md5"); ret = md5_hash(crypt_buf, passwd_len + salt_len, buf + 3); free(crypt_buf); return ret; } psqlodbc-09.03.0300/misc.c000644 001752 000000 00000017172 12335653444 015307 0ustar00saitowheel000000 000000 /*------- * Module: misc.c * * Description: This module contains miscellaneous routines * such as for debugging/logging and string functions. * * Classes: n/a * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "psqlodbc.h" #include "misc.h" #include #include #include #include #include #ifndef WIN32 #include #include #include #else #include /* Byron: is this where Windows keeps def. * of getpid ? */ #endif #include "connection.h" #include "multibyte.h" /* * returns STRCPY_FAIL, STRCPY_TRUNCATED, or #bytes copied * (not including null term) */ ssize_t my_strcpy(char *dst, ssize_t dst_len, const char *src, ssize_t src_len) { if (dst_len <= 0) return STRCPY_FAIL; if (src_len == SQL_NULL_DATA) { dst[0] = '\0'; return STRCPY_NULL; } else if (src_len == SQL_NTS) src_len = strlen(src); if (src_len <= 0) return STRCPY_FAIL; else { if (src_len < dst_len) { memcpy(dst, src, src_len); dst[src_len] = '\0'; } else { memcpy(dst, src, dst_len - 1); dst[dst_len - 1] = '\0'; /* truncated */ return STRCPY_TRUNCATED; } } return strlen(dst); } /* * strncpy copies up to len characters, and doesn't terminate * the destination string if src has len characters or more. * instead, I want it to copy up to len-1 characters and always * terminate the destination string. */ char * strncpy_null(char *dst, const char *src, ssize_t len) { int i; if (NULL != dst) { /* Just in case, check for special lengths */ if (len == SQL_NULL_DATA) { dst[0] = '\0'; return NULL; } else if (len == SQL_NTS) len = strlen(src) + 1; for (i = 0; src[i] && i < len - 1; i++) dst[i] = src[i]; if (len > 0) dst[i] = '\0'; } return dst; } /*------ * Create a null terminated string (handling the SQL_NTS thing): * 1. If buf is supplied, place the string in there * (assumes enough space) and return buf. * 2. If buf is not supplied, malloc space and return this string *------ */ char * make_string(const SQLCHAR *s, SQLINTEGER len, char *buf, size_t bufsize) { size_t length; char *str; if (!s || SQL_NULL_DATA == len) return NULL; if (len >= 0) length =len; else if (SQL_NTS == len) length = strlen((char *) s); else { mylog("make_string invalid length=%d\n", len); return NULL; } if (buf) { strncpy_null(buf, (char *) s, bufsize > length ? length + 1 : bufsize); return buf; } inolog("malloc size=%d\n", length); str = malloc(length + 1); inolog("str=%p\n", str); if (!str) return NULL; strncpy_null(str, (char *) s, length + 1); return str; } /*------ * Create a null terminated lower-case string if the * original string contains upper-case characters. * The SQL_NTS length is considered. *------ */ SQLCHAR * make_lstring_ifneeded(ConnectionClass *conn, const SQLCHAR *s, ssize_t len, BOOL ifallupper) { ssize_t length = len; char *str = NULL; const char *ccs = (const char *) s; if (s && (len > 0 || (len == SQL_NTS && (length = strlen(ccs)) > 0))) { int i; const UCHAR *ptr; encoded_str encstr; make_encoded_str(&encstr, conn, ccs); for (i = 0, ptr = (const UCHAR *) ccs; i < length; i++, ptr++) { encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) continue; if (ifallupper && islower(*ptr)) { if (str) { free(str); str = NULL; } break; } if (tolower(*ptr) != *ptr) { if (!str) { str = malloc(length + 1); memcpy(str, s, length); str[length] = '\0'; } str[i] = tolower(*ptr); } } } return (SQLCHAR *) str; } /* * Concatenate a single formatted argument to a given buffer handling the SQL_NTS thing. * "fmt" must contain somewhere in it the single form '%.*s'. * This is heavily used in creating queries for info routines (SQLTables, SQLColumns). * This routine could be modified to use vsprintf() to handle multiple arguments. */ static char * my_strcat(char *buf, const char *fmt, const char *s, ssize_t len) { if (s && (len > 0 || (len == SQL_NTS && strlen(s) > 0))) { size_t length = (len > 0) ? len : strlen(s); size_t pos = strlen(buf); sprintf(&buf[pos], fmt, length, s); return buf; } return NULL; } char * schema_strcat(char *buf, const char *fmt, const SQLCHAR *s, SQLLEN len, const SQLCHAR *tbname, SQLLEN tbnmlen, ConnectionClass *conn) { if (!s || 0 == len) { /* * Note that this driver assumes the implicit schema is * the CURRENT_SCHEMA() though it doesn't worth the * naming. */ if (conn->schema_support && tbname && (tbnmlen > 0 || tbnmlen == SQL_NTS)) return my_strcat(buf, fmt, CC_get_current_schema(conn), SQL_NTS); return NULL; } return my_strcat(buf, fmt, (char *) s, len); } char * my_trim(char *s) { char *last; for (last = s + strlen(s) - 1; last >= s; last--) { if (*last == ' ') *last = '\0'; else break; } return s; } /* * my_strcat1 is a extension of my_strcat. * It can have 1 more parameter than my_strcat. */ static char * my_strcat1(char *buf, const char *fmt, const char *s1, const char *s, ssize_t len) { ssize_t length = len; if (s && (len > 0 || (len == SQL_NTS && (length = strlen(s)) > 0))) { size_t pos = strlen(buf); if (s1) sprintf(&buf[pos], fmt, s1, length, s); else sprintf(&buf[pos], fmt, length, s); return buf; } return NULL; } char * schema_strcat1(char *buf, const char *fmt, const char *s1, const char *s, ssize_t len, const SQLCHAR *tbname, int tbnmlen, ConnectionClass *conn) { if (!s || 0 == len) { if (conn->schema_support && tbname && (tbnmlen > 0 || tbnmlen == SQL_NTS)) return my_strcat1(buf, fmt, s1, CC_get_current_schema(conn), SQL_NTS); return NULL; } return my_strcat1(buf, fmt, s1, s, len); } /* * snprintf_add is a extension to snprintf * It add format to buf at given pos */ int snprintf_add(char *buf, size_t size, const char *format, ...) { int len; size_t pos = strlen(buf); va_list arglist; va_start(arglist, format); len = vsnprintf(buf + pos, size - pos, format, arglist); va_end(arglist); return len; } /* * snprintf_addlen is a extension to snprintf * It returns strlen of buf every time (not -1 when truncated) */ size_t snprintf_len(char *buf, size_t size, const char *format, ...) { ssize_t len; va_list arglist; va_start(arglist, format); if ((len = vsnprintf(buf, size, format, arglist)) < 0) len = size; va_end(arglist); return len; } #ifndef HAVE_STRLCAT size_t strlcat(char *dst, const char *src, size_t size) { size_t ttllen; char *pd = dst; const char *ps= src; for (ttllen = 0; ttllen < size; ttllen++, pd++) { if (0 == *pd) break; } if (ttllen >= size - 1) return ttllen + strlen(src); for (; ttllen < size - 1; ttllen++, pd++, ps++) { if (0 == (*pd = *ps)) return ttllen; } *pd = 0; for (; *ps; ttllen++, ps++) ; return ttllen; } #endif /* HAVE_STRLCAT */ /* * Proprly quote and escape a possibly schema-qualified table name. * Returns a statically allocated buffer. */ char * quote_table(const pgNAME schema, pgNAME table) { static char buf[200]; const char *ptr; int i; i = 0; if (NAME_IS_VALID(schema)) { buf[i++] = '"'; for (ptr = SAFE_NAME(schema); *ptr != '\0' && i < sizeof(buf) - 6; ptr++) { buf[i++] = *ptr; if (*ptr == '"') buf[i++] = '"'; /* escape quotes by doubling them */ } buf[i++] = '"'; buf[i++] = '.'; } buf[i++] = '"'; for (ptr = SAFE_NAME(table); *ptr != '\0' && i < sizeof(buf) - 3; ptr++) { buf[i++] = *ptr; if (*ptr == '"') buf[i++] = '"'; /* escape quotes by doubling them */ } buf[i++] = '"'; buf[i] = '\0'; return buf; } psqlodbc-09.03.0300/options.c000644 001752 000000 00000052175 12335653444 016051 0ustar00saitowheel000000 000000 /*-------- * Module: options.c * * Description: This module contains routines for getting/setting * connection and statement options. * * Classes: n/a * * API functions: SQLSetConnectOption, SQLSetStmtOption, SQLGetConnectOption, * SQLGetStmtOption * * Comments: See "readme.txt" for copyright and license information. *-------- */ #include "psqlodbc.h" #include #include "misc.h" #include "environ.h" #include "connection.h" #include "statement.h" #include "qresult.h" #include "pgapifunc.h" RETCODE set_statement_option(ConnectionClass *conn, StatementClass *stmt, SQLUSMALLINT fOption, SQLULEN vParam) { CSTR func = "set_statement_option"; char changed = FALSE; ConnInfo *ci = NULL; SQLULEN setval; if (conn) ci = &(conn->connInfo); else if (stmt) ci = &(SC_get_conn(stmt)->connInfo); switch (fOption) { case SQL_ASYNC_ENABLE: /* ignored */ break; case SQL_BIND_TYPE: /* now support multi-column and multi-row binding */ if (conn) conn->ardOptions.bind_size = (SQLUINTEGER) vParam; if (stmt) SC_get_ARDF(stmt)->bind_size = (SQLUINTEGER) vParam; break; case SQL_CONCURRENCY: /* * positioned update isn't supported so cursor concurrency is * read-only */ mylog("SetStmtOption(): SQL_CONCURRENCY = " FORMAT_LEN " ", vParam); setval = SQL_CONCUR_READ_ONLY; if (SQL_CONCUR_READ_ONLY == vParam) ; else if (ci->drivers.lie) setval = vParam; else if (0 != ci->updatable_cursors) setval = SQL_CONCUR_ROWVER; if (conn) conn->stmtOptions.scroll_concurrency = (SQLUINTEGER) setval; else if (stmt) { if (SC_get_Result(stmt)) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "The attr can't be changed because the cursor is open.", func); return SQL_ERROR; } stmt->options.scroll_concurrency = stmt->options_orig.scroll_concurrency = (SQLUINTEGER) setval; } if (setval != vParam) changed = TRUE; mylog("-> " FORMAT_LEN "\n", setval); break; case SQL_CURSOR_TYPE: /* * if declare/fetch, then type can only be forward. otherwise, * it can only be forward or static. */ mylog("SetStmtOption(): SQL_CURSOR_TYPE = " FORMAT_LEN " ", vParam); setval = SQL_CURSOR_FORWARD_ONLY; if (ci->drivers.lie) setval = vParam; else if (SQL_CURSOR_STATIC == vParam) setval = vParam; else if (SQL_CURSOR_KEYSET_DRIVEN == vParam) { if (0 != (ci->updatable_cursors & ALLOW_KEYSET_DRIVEN_CURSORS)) setval = vParam; else setval = SQL_CURSOR_STATIC; /* at least scrollable */ } else if (SQL_CURSOR_DYNAMIC == vParam) { if (0 != (ci->updatable_cursors & ALLOW_DYNAMIC_CURSORS)) setval = vParam; else if (0 != (ci->updatable_cursors & ALLOW_KEYSET_DRIVEN_CURSORS)) setval = SQL_CURSOR_KEYSET_DRIVEN; else setval = SQL_CURSOR_STATIC; /* at least scrollable */ } if (conn) conn->stmtOptions.cursor_type = (SQLUINTEGER) setval; else if (stmt) { if (SC_get_Result(stmt)) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "The attr can't be changed because the cursor is open.", func); return SQL_ERROR; } stmt->options_orig.cursor_type = stmt->options.cursor_type = (SQLUINTEGER) setval; } if (setval != vParam) changed = TRUE; mylog("-> " FORMAT_LEN "\n", setval); break; case SQL_KEYSET_SIZE: /* ignored, but saved and returned */ mylog("SetStmtOption(): SQL_KEYSET_SIZE, vParam = " FORMAT_LEN "\n", vParam); if (conn) conn->stmtOptions.keyset_size = vParam; if (stmt) { stmt->options_orig.keyset_size = vParam; if (!SC_get_Result(stmt)) stmt->options.keyset_size = vParam; if (stmt->options.keyset_size != (SQLLEN) vParam) changed = TRUE; } break; case SQL_MAX_LENGTH: /* ignored, but saved */ mylog("SetStmtOption(): SQL_MAX_LENGTH, vParam = " FORMAT_LEN "\n", vParam); if (conn) conn->stmtOptions.maxLength = vParam; if (stmt) { stmt->options_orig.maxLength = vParam; if (!SC_get_Result(stmt)) stmt->options.maxLength = vParam; if (stmt->options.maxLength != (SQLLEN) vParam) changed = TRUE; } break; case SQL_MAX_ROWS: /* ignored, but saved */ mylog("SetStmtOption(): SQL_MAX_ROWS, vParam = " FORMAT_LEN "\n", vParam); if (conn) conn->stmtOptions.maxRows = vParam; if (stmt) { stmt->options_orig.maxRows = vParam; if (!SC_get_Result(stmt)) stmt->options.maxRows = vParam; if (stmt->options.maxRows != (SQLLEN)vParam) changed = TRUE; } break; case SQL_NOSCAN: /* ignored */ mylog("SetStmtOption: SQL_NOSCAN, vParam = " FORMAT_LEN "\n", vParam); break; case SQL_QUERY_TIMEOUT: /* ignored */ mylog("SetStmtOption: SQL_QUERY_TIMEOUT, vParam = " FORMAT_LEN "\n", vParam); /* "0" returned in SQLGetStmtOption */ break; case SQL_RETRIEVE_DATA: mylog("SetStmtOption(): SQL_RETRIEVE_DATA, vParam = " FORMAT_LEN "\n", vParam); if (conn) conn->stmtOptions.retrieve_data = (SQLUINTEGER) vParam; if (stmt) stmt->options.retrieve_data = (SQLUINTEGER) vParam; break; case SQL_ROWSET_SIZE: mylog("SetStmtOption(): SQL_ROWSET_SIZE, vParam = " FORMAT_LEN "\n", vParam); if (vParam < 1) { vParam = 1; changed = TRUE; } if (conn) conn->ardOptions.size_of_rowset_odbc2 = vParam; if (stmt) SC_get_ARDF(stmt)->size_of_rowset_odbc2 = vParam; break; case SQL_SIMULATE_CURSOR: /* NOT SUPPORTED */ if (stmt) { SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "Simulated positioned update/delete not supported. Use the cursor library.", func); } if (conn) { CC_set_error(conn, CONN_NOT_IMPLEMENTED_ERROR, "Simulated positioned update/delete not supported. Use the cursor library.", func); } return SQL_ERROR; case SQL_USE_BOOKMARKS: if (stmt) { #if (ODBCVER >= 0x0300) mylog("USE_BOOKMARKS %s\n", (vParam == SQL_UB_OFF) ? "off" : ((vParam == SQL_UB_VARIABLE) ? "variable" : "fixed")); #endif /* ODBCVER */ setval = vParam; stmt->options.use_bookmarks = (SQLUINTEGER) setval; } if (conn) conn->stmtOptions.use_bookmarks = (SQLUINTEGER) vParam; break; case 1204: /* SQL_COPT_SS_PRESERVE_CURSORS ? */ if (stmt) { SC_set_error(stmt, STMT_OPTION_NOT_FOR_THE_DRIVER, "The option may be for MS SQL Server(Set)", func); } else if (conn) { CC_set_error(conn, CONN_OPTION_NOT_FOR_THE_DRIVER, "The option may be for MS SQL Server(Set)", func); } return SQL_ERROR; case 1227: /* SQL_SOPT_SS_HIDDEN_COLUMNS ? */ case 1228: /* SQL_SOPT_SS_NOBROWSETABLE ? */ if (stmt) { #ifndef NOT_USED if (0 != vParam) changed = TRUE; break; #endif /* NOT_USED */ SC_set_error(stmt, STMT_OPTION_NOT_FOR_THE_DRIVER, "The option may be for MS SQL Server(Set)", func); } else if (conn) { CC_set_error(conn, CONN_OPTION_NOT_FOR_THE_DRIVER, "The option may be for MS SQL Server(Set)", func); } return SQL_ERROR; default: { char option[64]; if (stmt) { SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "Unknown statement option (Set)", func); sprintf(option, "fOption=%d, vParam=" FORMAT_ULEN, fOption, vParam); SC_log_error(func, option, stmt); } if (conn) { CC_set_error(conn, CONN_NOT_IMPLEMENTED_ERROR, "Unknown statement option (Set)", func); sprintf(option, "fOption=%d, vParam=" FORMAT_ULEN, fOption, vParam); CC_log_error(func, option, conn); } return SQL_ERROR; } } if (changed) { if (stmt) { SC_set_error(stmt, STMT_OPTION_VALUE_CHANGED, "Requested value changed.", func); } if (conn) { CC_set_error(conn, CONN_OPTION_VALUE_CHANGED, "Requested value changed.", func); } return SQL_SUCCESS_WITH_INFO; } else return SQL_SUCCESS; } /* Implements only SQL_AUTOCOMMIT */ RETCODE SQL_API PGAPI_SetConnectOption(HDBC hdbc, SQLUSMALLINT fOption, SQLULEN vParam) { CSTR func = "PGAPI_SetConnectOption"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci = &(conn->connInfo); char changed = FALSE; RETCODE retval; BOOL autocomm_on; mylog("%s: entering fOption = %d vParam = " FORMAT_LEN "\n", func, fOption, vParam); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } switch (fOption) { /* * Statement Options (apply to all stmts on the connection and * become defaults for new stmts) */ case SQL_ASYNC_ENABLE: case SQL_BIND_TYPE: case SQL_CONCURRENCY: case SQL_CURSOR_TYPE: case SQL_KEYSET_SIZE: case SQL_MAX_LENGTH: case SQL_MAX_ROWS: case SQL_NOSCAN: case SQL_QUERY_TIMEOUT: case SQL_RETRIEVE_DATA: case SQL_ROWSET_SIZE: case SQL_SIMULATE_CURSOR: case SQL_USE_BOOKMARKS: #if (ODBCVER < 0x0300) { int i; /* Affect all current Statements */ for (i = 0; i < conn->num_stmts; i++) { if (conn->stmts[i]) set_statement_option(NULL, conn->stmts[i], fOption, vParam); } } #endif /* ODBCVER */ /* * Become the default for all future statements on this * connection */ retval = set_statement_option(conn, NULL, fOption, vParam); if (retval == SQL_SUCCESS_WITH_INFO) changed = TRUE; else if (retval == SQL_ERROR) return SQL_ERROR; break; /* * Connection Options */ case SQL_ACCESS_MODE: /* ignored */ break; case SQL_AUTOCOMMIT: switch (vParam) { case SQL_AUTOCOMMIT_ON: autocomm_on = TRUE; break; case SQL_AUTOCOMMIT_OFF: autocomm_on = FALSE; break; default: CC_set_error(conn, CONN_INVALID_ARGUMENT_NO, "Illegal parameter value for SQL_AUTOCOMMIT", func); return SQL_ERROR; } if (autocomm_on && SQL_AUTOCOMMIT_OFF != ci->autocommit_public) break; else if (!autocomm_on && SQL_AUTOCOMMIT_OFF == ci->autocommit_public) break; ci->autocommit_public = (autocomm_on ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF); mylog("%s: AUTOCOMMIT: transact_status=%d, vparam=" FORMAT_LEN "\n", func, conn->transact_status, vParam); #ifdef _HANDLE_ENLIST_IN_DTC_ if (CC_is_in_global_trans(conn)) { CC_set_error(conn, CONN_TRANSACT_IN_PROGRES, "Don't change AUTOCOMMIT mode in a distributed transaction", func); return SQL_ERROR; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ CC_set_autocommit(conn, autocomm_on); break; case SQL_CURRENT_QUALIFIER: /* ignored */ break; case SQL_LOGIN_TIMEOUT: conn->login_timeout = (SQLUINTEGER) vParam; break; case SQL_PACKET_SIZE: /* ignored */ break; case SQL_QUIET_MODE: /* ignored */ break; case SQL_TXN_ISOLATION: retval = SQL_SUCCESS; if (conn->isolation == vParam) break; switch (vParam) { case SQL_TXN_SERIALIZABLE: if (PG_VERSION_GE(conn, 6.5) && PG_VERSION_LE(conn, 7.0)) retval = SQL_ERROR; break; case SQL_TXN_REPEATABLE_READ: if (PG_VERSION_LT(conn, 8.0)) retval = SQL_ERROR; break; case SQL_TXN_READ_COMMITTED: if (PG_VERSION_LT(conn, 6.5)) retval = SQL_ERROR; break; case SQL_TXN_READ_UNCOMMITTED: if (PG_VERSION_LT(conn, 8.0)) retval = SQL_ERROR; break; default: retval = SQL_ERROR; } if (SQL_ERROR == retval) { CC_set_error(conn, CONN_INVALID_ARGUMENT_NO, "Illegal parameter value for SQL_TXN_ISOLATION", func); return SQL_ERROR; } else { char *query; QResultClass *res; if (CC_is_in_trans(conn)) { if (CC_does_autocommit(conn) && !CC_is_in_error_trans(conn)) CC_commit(conn); else { CC_set_error(conn, CONN_TRANSACT_IN_PROGRES, "Cannot switch isolation level while a transaction is in progress", func); return SQL_ERROR; } } switch (vParam) { case SQL_TXN_SERIALIZABLE: query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE"; break; case SQL_TXN_REPEATABLE_READ: query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ"; break; case SQL_TXN_READ_UNCOMMITTED: query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"; break; default: query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED"; break; } res = CC_send_query(conn, query, NULL, 0, NULL); if (!QR_command_maybe_successful(res)) retval = SQL_ERROR; else conn->isolation = (UInt4) vParam; QR_Destructor(res); if (SQL_ERROR == retval) { CC_set_error(conn, CONN_EXEC_ERROR, "ISOLATION change request to the server error", func); return SQL_ERROR; } } break; /* These options should be handled by driver manager */ case SQL_ODBC_CURSORS: case SQL_OPT_TRACE: case SQL_OPT_TRACEFILE: case SQL_TRANSLATE_DLL: case SQL_TRANSLATE_OPTION: CC_log_error(func, "This connect option (Set) is only used by the Driver Manager", conn); break; default: { char option[64]; CC_set_error(conn, CONN_UNSUPPORTED_OPTION, "Unknown connect option (Set)", func); sprintf(option, "fOption=%d, vParam=" FORMAT_LEN, fOption, vParam); #ifdef WIN32 if (fOption == 30002 && vParam) { int cmp; #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) { char *asPara = ucs2_to_utf8((SQLWCHAR *) vParam, SQL_NTS, NULL, FALSE); cmp = strcmp(asPara, "Microsoft Jet"); free(asPara); } else #endif /* UNICODE_SUPPORT */ cmp = strncmp((char *) vParam, "Microsoft Jet", 13); if (0 == cmp) { mylog("Microsoft Jet !!!!\n"); CC_set_errornumber(conn, 0); conn->ms_jet = 1; return SQL_SUCCESS; } } #endif /* WIN32 */ CC_log_error(func, option, conn); return SQL_ERROR; } } if (changed) { CC_set_error(conn, CONN_OPTION_VALUE_CHANGED, "Requested value changed.", func); return SQL_SUCCESS_WITH_INFO; } else return SQL_SUCCESS; } /* This function just can tell you whether you are in Autcommit mode or not */ RETCODE SQL_API PGAPI_GetConnectOption(HDBC hdbc, SQLUSMALLINT fOption, PTR pvParam, SQLINTEGER *StringLength, SQLINTEGER BufferLength) { CSTR func = "PGAPI_GetConnectOption"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci = &(conn->connInfo); const char *p = NULL; SQLLEN len = sizeof(SQLINTEGER); SQLRETURN result = SQL_SUCCESS; mylog("%s: entering...\n", func); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } switch (fOption) { case SQL_ACCESS_MODE: /* NOT SUPPORTED */ *((SQLUINTEGER *) pvParam) = SQL_MODE_READ_WRITE; break; case SQL_AUTOCOMMIT: *((SQLUINTEGER *) pvParam) = ci->autocommit_public; break; case SQL_CURRENT_QUALIFIER: /* don't use qualifiers */ len = 0; p = CurrCatString(conn); break; case SQL_LOGIN_TIMEOUT: *((SQLUINTEGER *) pvParam) = conn->login_timeout; break; case SQL_PACKET_SIZE: /* NOT SUPPORTED */ *((SQLUINTEGER *) pvParam) = ci->drivers.socket_buffersize; break; case SQL_QUIET_MODE: /* NOT SUPPORTED */ *((SQLULEN *) pvParam) = 0; break; case SQL_TXN_ISOLATION: *((SQLUINTEGER *) pvParam) = conn->isolation; break; #ifdef SQL_ATTR_CONNECTION_DEAD case SQL_ATTR_CONNECTION_DEAD: #else case 1209: #endif /* SQL_ATTR_CONNECTION_DEAD */ mylog("CONNECTION_DEAD status=%d", conn->status); *((SQLUINTEGER *) pvParam) = (conn->status == CONN_NOT_CONNECTED || conn->status == CONN_DOWN); mylog(" val=%d\n", *((SQLUINTEGER *) pvParam)); break; #if (ODBCVER >= 0x0351) case SQL_ATTR_ANSI_APP: *((SQLUINTEGER *) pvParam) = CC_is_in_ansi_app(conn); mylog("ANSI_APP val=%d\n", *((SQLUINTEGER *) pvParam)); break; #endif /* ODBCVER */ /* These options should be handled by driver manager */ case SQL_ODBC_CURSORS: case SQL_OPT_TRACE: case SQL_OPT_TRACEFILE: case SQL_TRANSLATE_DLL: case SQL_TRANSLATE_OPTION: CC_log_error(func, "This connect option (Get) is only used by the Driver Manager", conn); break; default: { char option[64]; CC_set_error(conn, CONN_UNSUPPORTED_OPTION, "Unknown connect option (Get)", func); sprintf(option, "fOption=%d", fOption); CC_log_error(func, option, conn); return SQL_ERROR; break; } } if (NULL != p && 0 == len) { /* char/binary data */ len = strlen(p); if (pvParam) { #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) { len = utf8_to_ucs2(p, len, (SQLWCHAR *) pvParam , BufferLength / WCLEN); len *= WCLEN; } else #endif /* UNICODE_SUPPORT */ strncpy_null((char *) pvParam, p, (size_t) BufferLength); if (len >= BufferLength) { result = SQL_SUCCESS_WITH_INFO; CC_set_error(conn, CONN_TRUNCATED, "The buffer was too small for the pvParam.", func); } } } if (StringLength) *StringLength = (SQLINTEGER) len; return result; } RETCODE SQL_API PGAPI_SetStmtOption(HSTMT hstmt, SQLUSMALLINT fOption, SQLULEN vParam) { CSTR func = "PGAPI_SetStmtOption"; StatementClass *stmt = (StatementClass *) hstmt; RETCODE retval; mylog("%s: entering...\n", func); /* * Though we could fake Access out by just returning SQL_SUCCESS all * the time, but it tries to set a huge value for SQL_MAX_LENGTH and * expects the driver to reduce it to the real value. */ if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } /* StartRollbackState(stmt); */ retval = set_statement_option(NULL, stmt, fOption, vParam); if (stmt->internal) retval = DiscardStatementSvp(stmt, retval, FALSE); return retval; } RETCODE SQL_API PGAPI_GetStmtOption(HSTMT hstmt, SQLUSMALLINT fOption, PTR pvParam, SQLINTEGER *StringLength, SQLINTEGER BufferLength) { CSTR func = "PGAPI_GetStmtOption"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; SQLLEN ridx; SQLINTEGER len = sizeof(SQLINTEGER); mylog("%s: entering...\n", func); /* * thought we could fake Access out by just returning SQL_SUCCESS all * the time, but it tries to set a huge value for SQL_MAX_LENGTH and * expects the driver to reduce it to the real value */ if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } switch (fOption) { case SQL_GET_BOOKMARK: case SQL_ROW_NUMBER: res = SC_get_Curres(stmt); if (!res) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "The cursor has no result.", func); return SQL_ERROR; } ridx = GIdx2CacheIdx(stmt->currTuple, stmt, res); if (!SC_is_fetchcursor(stmt)) { /* make sure we're positioned on a valid row */ if ((ridx < 0) || (((SQLULEN) ridx) >= QR_get_num_cached_tuples(res))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Not positioned on a valid row.", func); return SQL_ERROR; } } else { if (stmt->currTuple < 0 || !res->tupleField) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Not positioned on a valid row.", func); return SQL_ERROR; } } if (fOption == SQL_GET_BOOKMARK && stmt->options.use_bookmarks == SQL_UB_OFF) { SC_set_error(stmt, STMT_OPERATION_INVALID, "Operation invalid because use bookmarks not enabled.", func); return SQL_ERROR; } *((SQLULEN *) pvParam) = SC_get_bookmark(stmt); break; case SQL_ASYNC_ENABLE: /* NOT SUPPORTED */ *((SQLINTEGER *) pvParam) = SQL_ASYNC_ENABLE_OFF; break; case SQL_BIND_TYPE: *((SQLINTEGER *) pvParam) = SC_get_ARDF(stmt)->bind_size; break; case SQL_CONCURRENCY: /* NOT REALLY SUPPORTED */ mylog("GetStmtOption(): SQL_CONCURRENCY %d\n", stmt->options.scroll_concurrency); *((SQLINTEGER *) pvParam) = stmt->options.scroll_concurrency; break; case SQL_CURSOR_TYPE: /* PARTIAL SUPPORT */ mylog("GetStmtOption(): SQL_CURSOR_TYPE %d\n", stmt->options.cursor_type); *((SQLINTEGER *) pvParam) = stmt->options.cursor_type; break; case SQL_KEYSET_SIZE: /* NOT SUPPORTED, but saved */ mylog("GetStmtOption(): SQL_KEYSET_SIZE\n"); *((SQLLEN *) pvParam) = stmt->options.keyset_size; break; case SQL_MAX_LENGTH: /* NOT SUPPORTED, but saved */ *((SQLLEN *) pvParam) = stmt->options.maxLength; break; case SQL_MAX_ROWS: /* NOT SUPPORTED, but saved */ *((SQLLEN *) pvParam) = stmt->options.maxRows; mylog("GetSmtOption: MAX_ROWS, returning %d\n", stmt->options.maxRows); break; case SQL_NOSCAN: /* NOT SUPPORTED */ *((SQLINTEGER *) pvParam) = SQL_NOSCAN_ON; break; case SQL_QUERY_TIMEOUT: /* NOT SUPPORTED */ *((SQLINTEGER *) pvParam) = 0; break; case SQL_RETRIEVE_DATA: *((SQLINTEGER *) pvParam) = stmt->options.retrieve_data; break; case SQL_ROWSET_SIZE: *((SQLLEN *) pvParam) = SC_get_ARDF(stmt)->size_of_rowset_odbc2; break; case SQL_SIMULATE_CURSOR: /* NOT SUPPORTED */ *((SQLINTEGER *) pvParam) = SQL_SC_NON_UNIQUE; break; case SQL_USE_BOOKMARKS: *((SQLINTEGER *) pvParam) = stmt->options.use_bookmarks; break; case 1227: /* SQL_SOPT_SS_HIDDEN_COLUMNS ? */ case 1228: /* SQL_SOPT_SS_NOBROWSETABLE ? */ *((SQLINTEGER *) pvParam) = 0; break; default: { char option[64]; SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "Unknown statement option (Get)", func); sprintf(option, "fOption=%d", fOption); SC_log_error(func, option, stmt); return SQL_ERROR; } } if (StringLength) *StringLength = len; return SQL_SUCCESS; } psqlodbc-09.03.0300/pgtypes.c000644 001752 000000 00000153253 12335653444 016050 0ustar00saitowheel000000 000000 /*-------- * Module: pgtypes.c * * Description: This module contains routines for getting information * about the supported Postgres data types. Only the * function pgtype_to_sqltype() returns an unknown condition. * All other functions return a suitable default so that * even data types that are not directly supported can be * used (it is handled as char data). * * Classes: n/a * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *-------- */ #include "pgtypes.h" #include "dlg_specific.h" #include "statement.h" #include "connection.h" #include "environ.h" #include "qresult.h" #define EXPERIMENTAL_CURRENTLY Int4 getCharColumnSize(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); /* * these are the types we support. all of the pgtype_ functions should * return values for each one of these. * Even types not directly supported are handled as character types * so all types should work (points, etc.) */ /* * ALL THESE TYPES ARE NO LONGER REPORTED in SQLGetTypeInfo. Instead, all * the SQL TYPES are reported and mapped to a corresponding Postgres Type */ /* OID pgtypes_defined[][2] = { {PG_TYPE_CHAR, 0} ,{PG_TYPE_CHAR2, 0} ,{PG_TYPE_CHAR4, 0} ,{PG_TYPE_CHAR8, 0} ,{PG_TYPE_CHAR16, 0} ,{PG_TYPE_NAME, 0} ,{PG_TYPE_VARCHAR, 0} ,{PG_TYPE_BPCHAR, 0} ,{PG_TYPE_DATE, 0} ,{PG_TYPE_TIME, 0} ,{PG_TYPE_TIME_WITH_TMZONE, 0} ,{PG_TYPE_DATETIME, 0} ,{PG_TYPE_ABSTIME, 0} ,{PG_TYPE_TIMESTAMP_NO_TMZONE, 0} ,{PG_TYPE_TIMESTAMP, 0} ,{PG_TYPE_TEXT, 0} ,{PG_TYPE_INT2, 0} ,{PG_TYPE_INT4, 0} ,{PG_TYPE_FLOAT4, 0} ,{PG_TYPE_FLOAT8, 0} ,{PG_TYPE_OID, 0} ,{PG_TYPE_MONEY, 0} ,{PG_TYPE_BOOL, 0} ,{PG_TYPE_BYTEA, 0} ,{PG_TYPE_NUMERIC, 0} ,{PG_TYPE_XID, 0} ,{PG_TYPE_LO_UNDEFINED, 0} ,{0, 0} }; */ /* These are NOW the SQL Types reported in SQLGetTypeInfo. */ SQLSMALLINT sqlTypes[] = { SQL_BIGINT, /* SQL_BINARY, -- Commented out because VarBinary is more correct. */ SQL_BIT, SQL_CHAR, #if (ODBCVER >= 0x0300) SQL_TYPE_DATE, #endif /* ODBCVER */ SQL_DATE, SQL_DECIMAL, SQL_DOUBLE, SQL_FLOAT, SQL_INTEGER, SQL_LONGVARBINARY, SQL_LONGVARCHAR, SQL_NUMERIC, SQL_REAL, SQL_SMALLINT, #if (ODBCVER >= 0x0300) SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP, #endif /* ODBCVER */ SQL_TIME, SQL_TIMESTAMP, SQL_TINYINT, SQL_VARBINARY, SQL_VARCHAR, #ifdef UNICODE_SUPPORT SQL_WCHAR, SQL_WVARCHAR, SQL_WLONGVARCHAR, #endif /* UNICODE_SUPPORT */ #if (ODBCVER >= 0x0350) SQL_GUID, #endif /* ODBCVER */ /* AFAIK SQL_INTERVAL types cause troubles in some spplications */ #ifdef PG_INTERVAL_AS_SQL_INTERVAL SQL_INTERVAL_MONTH, SQL_INTERVAL_YEAR, SQL_INTERVAL_YEAR_TO_MONTH, SQL_INTERVAL_DAY, SQL_INTERVAL_HOUR, SQL_INTERVAL_MINUTE, SQL_INTERVAL_SECOND, SQL_INTERVAL_DAY_TO_HOUR, SQL_INTERVAL_DAY_TO_MINUTE, SQL_INTERVAL_DAY_TO_SECOND, SQL_INTERVAL_HOUR_TO_MINUTE, SQL_INTERVAL_HOUR_TO_SECOND, SQL_INTERVAL_MINUTE_TO_SECOND, #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ 0 }; #if (ODBCVER >= 0x0300) && defined(ODBCINT64) #define ALLOWED_C_BIGINT SQL_C_SBIGINT /* #define ALLOWED_C_BIGINT SQL_C_CHAR */ /* Delphi should be either ? */ #else #define ALLOWED_C_BIGINT SQL_C_CHAR #endif OID pg_true_type(const ConnectionClass *conn, OID type, OID basetype) { if (0 == basetype) return type; else if (0 == type) return basetype; else if (type == conn->lobj_type) return type; return basetype; } #define MONTH_BIT (1 << 17) #define YEAR_BIT (1 << 18) #define DAY_BIT (1 << 19) #define HOUR_BIT (1 << 26) #define MINUTE_BIT (1 << 27) #define SECOND_BIT (1 << 28) #if (ODBCVER >= 0x0300) static SQLSMALLINT get_interval_type(Int4 atttypmod, const char **name) { mylog("!!! %s atttypmod=%x\n", __FUNCTION__, atttypmod); if ((-1) == atttypmod) return 0; if (0 != (YEAR_BIT & atttypmod)) { if (0 != (MONTH_BIT & atttypmod)) { if (name) *name = "interval year to month"; return SQL_INTERVAL_YEAR_TO_MONTH; } if (name) *name = "interval year"; return SQL_INTERVAL_YEAR; } else if (0 != (MONTH_BIT & atttypmod)) { if (name) *name = "interval month"; return SQL_INTERVAL_MONTH; } else if (0 != (DAY_BIT & atttypmod)) { if (0 != (SECOND_BIT & atttypmod)) { if (name) *name = "interval day to second"; return SQL_INTERVAL_DAY_TO_SECOND; } else if (0 != (MINUTE_BIT & atttypmod)) { if (name) *name = "interval day to minute"; return SQL_INTERVAL_DAY_TO_MINUTE; } else if (0 != (HOUR_BIT & atttypmod)) { if (name) *name = "interval day to hour"; return SQL_INTERVAL_DAY_TO_HOUR; } if (name) *name = "interval day"; return SQL_INTERVAL_DAY; } else if (0 != (HOUR_BIT & atttypmod)) { if (0 != (SECOND_BIT & atttypmod)) { if (name) *name = "interval hour to second"; return SQL_INTERVAL_HOUR_TO_SECOND; } else if (0 != (MINUTE_BIT & atttypmod)) { if (name) *name = "interval hour to minute"; return SQL_INTERVAL_HOUR_TO_MINUTE; } if (name) *name = "interval hour"; return SQL_INTERVAL_HOUR; } else if (0 != (MINUTE_BIT & atttypmod)) { if (0 != (SECOND_BIT & atttypmod)) { if (name) *name = "interval minute to second"; return SQL_INTERVAL_MINUTE_TO_SECOND; } if (name) *name = "interval minute"; return SQL_INTERVAL_MINUTE; } else if (0 != (SECOND_BIT & atttypmod)) { if (name) *name = "interval second"; return SQL_INTERVAL_SECOND; } if (name) *name = "interval"; return 0; } #endif /* ODBCVER */ static Int4 getCharColumnSizeX(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { int p = -1, maxsize; const ConnInfo *ci = &(conn->connInfo); mylog("%s: type=%d, atttypmod=%d, adtsize_or=%d, unknown = %d\n", __FUNCTION__, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); /* Assign Maximum size based on parameters */ switch (type) { case PG_TYPE_TEXT: if (ci->drivers.text_as_longvarchar) maxsize = ci->drivers.max_longvarchar_size; else maxsize = ci->drivers.max_varchar_size; break; case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: maxsize = ci->drivers.max_varchar_size; break; default: if (ci->drivers.unknowns_as_longvarchar) maxsize = ci->drivers.max_longvarchar_size; else maxsize = ci->drivers.max_varchar_size; break; } #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn) && isSqlServr() && maxsize > 4000) maxsize = 4000; #endif /* UNICODE_SUPPORT */ if (maxsize == TEXT_FIELD_SIZE + 1) /* magic length for testing */ { if (PG_VERSION_GE(conn, 7.1)) maxsize = 0; else maxsize = TEXT_FIELD_SIZE; } /* * Static ColumnSize (i.e., the Maximum ColumnSize of the datatype) This * has nothing to do with a result set. */ inolog("!!! atttypmod < 0 ?\n"); if (atttypmod < 0 && adtsize_or_longestlen < 0) return maxsize; /* * Catalog Result Sets -- use assigned column width (i.e., from * set_tuplefield_string) */ inolog("!!! catalog_result=%d\n", handle_unknown_size_as); if (UNKNOWNS_AS_CATALOG == handle_unknown_size_as) { if (adtsize_or_longestlen > 0) return adtsize_or_longestlen; return maxsize; } if (TYPE_MAY_BE_ARRAY(type)) { if (adtsize_or_longestlen > 0) return adtsize_or_longestlen; return maxsize; } inolog("!!! adtsize_or_logngest=%d\n", adtsize_or_longestlen); p = adtsize_or_longestlen; /* longest */ /* Size is unknown -- handle according to parameter */ if (atttypmod > 0) /* maybe the length is known */ { if (atttypmod >= p) return atttypmod; switch (type) { case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: #if (ODBCVER >= 0x0300) return atttypmod; #else if (CC_is_in_unicode_driver(conn) || conn->ms_jet) return atttypmod; return p; #endif /* ODBCVER */ } } /* The type is really unknown */ switch (handle_unknown_size_as) { case UNKNOWNS_AS_DONTKNOW: return -1; case UNKNOWNS_AS_LONGEST: mylog("%s: LONGEST: p = %d\n", __FUNCTION__, p); if (p > 0) return p; break; case UNKNOWNS_AS_MAX: break; default: return -1; } if (maxsize <= 0) return maxsize; switch (type) { case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: case PG_TYPE_TEXT: return maxsize; } if (p > maxsize) maxsize = p; return maxsize; } static SQLSMALLINT getNumericDecimalDigitsX(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int handle_unknown_size_as) { Int4 default_decimal_digits = 6; mylog("%s: type=%d, atttypmod=%d\n", __FUNCTION__, type, atttypmod); if (atttypmod < 0 && adtsize_or_longest < 0) return default_decimal_digits; if (atttypmod > -1) return (atttypmod & 0xffff); if (adtsize_or_longest <= 0) return default_decimal_digits; adtsize_or_longest >>= 16; /* extract the scale part */ return adtsize_or_longest; } static Int4 /* PostgreSQL restritiction */ getNumericColumnSizeX(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int handle_unknown_size_as) { Int4 default_column_size = 28; mylog("%s: type=%d, typmod=%d\n", __FUNCTION__, type, atttypmod); if (atttypmod > -1) return (atttypmod >> 16) & 0xffff; switch (handle_unknown_size_as) { case UNKNOWNS_AS_DONTKNOW: return SQL_NO_TOTAL; } if (adtsize_or_longest <= 0) return default_column_size; adtsize_or_longest %= (1 << 16); /* extract the precision part */ switch (handle_unknown_size_as) { case UNKNOWNS_AS_MAX: return adtsize_or_longest > default_column_size ? adtsize_or_longest : default_column_size; case UNKNOWNS_AS_CATALOG: break; default: if (adtsize_or_longest < 10) adtsize_or_longest = 10; } return adtsize_or_longest; } static SQLSMALLINT getTimestampDecimalDigitsX(const ConnectionClass *conn, OID type, int atttypmod) { mylog("%s: type=%d, atttypmod=%d\n", __FUNCTION__, type, atttypmod); if (PG_VERSION_LT(conn, 7.2)) return 0; return (atttypmod > -1 ? atttypmod : 6); } static SQLSMALLINT getTimestampColumnSizeX(const ConnectionClass *conn, OID type, int atttypmod) { Int4 fixed, scale; mylog("%s: type=%d, atttypmod=%d\n", __FUNCTION__, type, atttypmod); switch (type) { case PG_TYPE_TIME: fixed = 8; break; case PG_TYPE_TIME_WITH_TMZONE: fixed = 11; break; case PG_TYPE_TIMESTAMP_NO_TMZONE: fixed = 19; break; default: if (USE_ZONE) fixed = 22; else fixed = 19; break; } scale = getTimestampDecimalDigitsX(conn, type, atttypmod); return (scale > 0) ? fixed + 1 + scale : fixed; } static SQLSMALLINT getIntervalDecimalDigits(OID type, int atttypmod) { Int4 prec; mylog("%s: type=%d, atttypmod=%d\n", __FUNCTION__, type, atttypmod); if ((atttypmod & SECOND_BIT) == 0) return 0; return (prec = atttypmod & 0xffff) == 0xffff ? 6 : prec ; } static SQLSMALLINT getIntervalColumnSize(OID type, int atttypmod) { Int4 ttl, leading_precision = 9, scale; mylog("%s: type=%d, atttypmod=%d\n", __FUNCTION__, type, atttypmod); ttl = leading_precision; #if (ODBCVER >= 0x0300) switch (get_interval_type(atttypmod, NULL)) { case 0: ttl = 25; break; case SQL_INTERVAL_YEAR: ttl = 16; break; case SQL_INTERVAL_MONTH: ttl = 16; break; case SQL_INTERVAL_DAY: ttl = 16; break; case SQL_INTERVAL_DAY_TO_SECOND: case SQL_INTERVAL_DAY_TO_MINUTE: case SQL_INTERVAL_DAY_TO_HOUR: ttl = 25; break; case SQL_INTERVAL_HOUR_TO_SECOND: case SQL_INTERVAL_HOUR_TO_MINUTE: case SQL_INTERVAL_HOUR: ttl = 17; break; case SQL_INTERVAL_MINUTE_TO_SECOND: case SQL_INTERVAL_MINUTE: ttl = 15; break; case SQL_INTERVAL_YEAR_TO_MONTH: ttl = 24; break; } #else ttl += 9; #endif /* ODBCVER */ scale = getIntervalDecimalDigits(type, atttypmod); return (scale > 0) ? ttl + 1 + scale : ttl; } SQLSMALLINT pgtype_attr_to_concise_type(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen) { const ConnInfo *ci = &(conn->connInfo); #if (ODBCVER >= 0x0300) EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); #ifdef PG_INTERVAL_AS_SQL_INTERVAL SQLSMALLINT sqltype; #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ #endif /* ODBCVER */ switch (type) { case PG_TYPE_CHAR: case PG_TYPE_CHAR2: case PG_TYPE_CHAR4: case PG_TYPE_CHAR8: return ALLOW_WCHAR(conn) ? SQL_WCHAR : SQL_CHAR; case PG_TYPE_NAME: case PG_TYPE_REFCURSOR: return ALLOW_WCHAR(conn) ? SQL_WVARCHAR : SQL_VARCHAR; #ifdef UNICODE_SUPPORT case PG_TYPE_BPCHAR: if (getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, UNKNOWNS_AS_DEFAULT) > ci->drivers.max_varchar_size) return ALLOW_WCHAR(conn) ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR; return ALLOW_WCHAR(conn) ? SQL_WCHAR : SQL_CHAR; case PG_TYPE_VARCHAR: if (getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, UNKNOWNS_AS_DEFAULT) > ci->drivers.max_varchar_size) return ALLOW_WCHAR(conn) ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR; return ALLOW_WCHAR(conn) ? SQL_WVARCHAR : SQL_VARCHAR; case PG_TYPE_TEXT: return ci->drivers.text_as_longvarchar ? (ALLOW_WCHAR(conn) ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR) : (ALLOW_WCHAR(conn) ? SQL_WVARCHAR : SQL_VARCHAR); #else case PG_TYPE_BPCHAR: if (getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, UNKNOWNS_AS_DEFAULT) > ci->drivers.max_varchar_size) return SQL_LONGVARCHAR; return SQL_CHAR; case PG_TYPE_VARCHAR: if (getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, UNKNOWNS_AS_DEFAULT) > ci->drivers.max_varchar_size) return SQL_LONGVARCHAR; return SQL_VARCHAR; case PG_TYPE_TEXT: return ci->drivers.text_as_longvarchar ? SQL_LONGVARCHAR : SQL_VARCHAR; #endif /* UNICODE_SUPPORT */ case PG_TYPE_BYTEA: if (ci->bytea_as_longvarbinary) return SQL_LONGVARBINARY; else return SQL_VARBINARY; case PG_TYPE_LO_UNDEFINED: return SQL_LONGVARBINARY; case PG_TYPE_INT2: return SQL_SMALLINT; case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: return SQL_INTEGER; /* Change this to SQL_BIGINT for ODBC v3 bjm 2001-01-23 */ case PG_TYPE_INT8: if (ci->int8_as != 0) return ci->int8_as; if (conn->ms_jet) return SQL_NUMERIC; /* maybe a little better than SQL_VARCHAR */ #if (ODBCVER >= 0x0300) return SQL_BIGINT; #else return SQL_VARCHAR; #endif /* ODBCVER */ case PG_TYPE_NUMERIC: return SQL_NUMERIC; case PG_TYPE_FLOAT4: return SQL_REAL; case PG_TYPE_FLOAT8: return SQL_FLOAT; case PG_TYPE_DATE: #if (ODBCVER >= 0x0300) if (EN_is_odbc3(env)) return SQL_TYPE_DATE; #endif /* ODBCVER */ return SQL_DATE; case PG_TYPE_TIME: #if (ODBCVER >= 0x0300) if (EN_is_odbc3(env)) return SQL_TYPE_TIME; #endif /* ODBCVER */ return SQL_TIME; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: #if (ODBCVER >= 0x0300) if (EN_is_odbc3(env)) return SQL_TYPE_TIMESTAMP; #endif /* ODBCVER */ return SQL_TIMESTAMP; case PG_TYPE_MONEY: return SQL_FLOAT; case PG_TYPE_BOOL: return ci->drivers.bools_as_char ? SQL_VARCHAR : SQL_BIT; case PG_TYPE_XML: return ALLOW_WCHAR(conn) ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR; case PG_TYPE_INET: case PG_TYPE_CIDR: case PG_TYPE_MACADDR: return ALLOW_WCHAR(conn) ? SQL_WVARCHAR : SQL_VARCHAR; case PG_TYPE_UUID: #if (ODBCVER >= 0x0350) return SQL_GUID; #endif /* ODBCVER */ return ALLOW_WCHAR(conn) ? SQL_WVARCHAR : SQL_VARCHAR; case PG_TYPE_INTERVAL: #ifdef PG_INTERVAL_AS_SQL_INTERVAL if (sqltype = get_interval_type(atttypmod, NULL), 0 != sqltype) return sqltype; #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ return CC_is_in_unicode_driver(conn) ? SQL_WVARCHAR : SQL_VARCHAR; default: /* * first, check to see if 'type' is in list. If not, look up * with query. Add oid, name to list. If it's already in * list, just return. */ /* hack until permanent type is available */ if (type == conn->lobj_type) return SQL_LONGVARBINARY; #ifdef EXPERIMENTAL_CURRENTLY if (ALLOW_WCHAR(conn)) return ci->drivers.unknowns_as_longvarchar ? SQL_WLONGVARCHAR : SQL_WVARCHAR; #endif /* EXPERIMENTAL_CURRENTLY */ return ci->drivers.unknowns_as_longvarchar ? SQL_LONGVARCHAR : SQL_VARCHAR; } } SQLSMALLINT pgtype_attr_to_sqldesctype(const ConnectionClass *conn, OID type, int atttypmod) { SQLSMALLINT rettype; #ifdef PG_INTERVAL_AS_SQL_INTERVAL if (PG_TYPE_INTERVAL == type) return SQL_INTERVAL; #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ switch (rettype = pgtype_attr_to_concise_type(conn, type, atttypmod, PG_UNSPECIFIED)) { #if (ODBCVER >= 0x0300) case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: return SQL_DATETIME; #endif /* ODBCVER */ } return rettype; } SQLSMALLINT pgtype_attr_to_datetime_sub(const ConnectionClass *conn, OID type, int atttypmod) { SQLSMALLINT rettype; switch (rettype = pgtype_attr_to_concise_type(conn, type, atttypmod, PG_UNSPECIFIED)) { #if (ODBCVER >= 0x0300) case SQL_TYPE_DATE: return SQL_CODE_DATE; case SQL_TYPE_TIME: return SQL_CODE_TIME; case SQL_TYPE_TIMESTAMP: return SQL_CODE_TIMESTAMP; case SQL_INTERVAL_MONTH: case SQL_INTERVAL_YEAR: case SQL_INTERVAL_YEAR_TO_MONTH: case SQL_INTERVAL_DAY: case SQL_INTERVAL_HOUR: case SQL_INTERVAL_MINUTE: case SQL_INTERVAL_SECOND: case SQL_INTERVAL_DAY_TO_HOUR: case SQL_INTERVAL_DAY_TO_MINUTE: case SQL_INTERVAL_DAY_TO_SECOND: case SQL_INTERVAL_HOUR_TO_MINUTE: case SQL_INTERVAL_HOUR_TO_SECOND: case SQL_INTERVAL_MINUTE_TO_SECOND: return rettype - 100; #endif /* ODBCVER */ } return -1; } SQLSMALLINT pgtype_attr_to_ctype(const ConnectionClass *conn, OID type, int atttypmod) { const ConnInfo *ci = &(conn->connInfo); #if (ODBCVER >= 0x0300) EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); #ifdef PG_INTERVAL_AS_SQL_INTERVAL SQLSMALLINT ctype; #endif /* PG_INTERVAL_A_SQL_INTERVAL */ #endif /* ODBCVER */ switch (type) { case PG_TYPE_INT8: #if (ODBCVER >= 0x0300) if (!conn->ms_jet) return ALLOWED_C_BIGINT; #endif /* ODBCVER */ return SQL_C_CHAR; case PG_TYPE_NUMERIC: return SQL_C_CHAR; case PG_TYPE_INT2: return SQL_C_SSHORT; case PG_TYPE_OID: case PG_TYPE_XID: return SQL_C_ULONG; case PG_TYPE_INT4: return SQL_C_SLONG; case PG_TYPE_FLOAT4: return SQL_C_FLOAT; case PG_TYPE_FLOAT8: return SQL_C_DOUBLE; case PG_TYPE_DATE: #if (ODBCVER >= 0x0300) if (EN_is_odbc3(env)) return SQL_C_TYPE_DATE; #endif /* ODBCVER */ return SQL_C_DATE; case PG_TYPE_TIME: #if (ODBCVER >= 0x0300) if (EN_is_odbc3(env)) return SQL_C_TYPE_TIME; #endif /* ODBCVER */ return SQL_C_TIME; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: #if (ODBCVER >= 0x0300) if (EN_is_odbc3(env)) return SQL_C_TYPE_TIMESTAMP; #endif /* ODBCVER */ return SQL_C_TIMESTAMP; case PG_TYPE_MONEY: return SQL_C_FLOAT; case PG_TYPE_BOOL: return ci->drivers.bools_as_char ? SQL_C_CHAR : SQL_C_BIT; case PG_TYPE_BYTEA: return SQL_C_BINARY; case PG_TYPE_LO_UNDEFINED: return SQL_C_BINARY; #ifdef UNICODE_SUPPORT case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: case PG_TYPE_TEXT: return ALLOW_WCHAR(conn) ? SQL_C_WCHAR : SQL_C_CHAR; #endif /* UNICODE_SUPPORT */ case PG_TYPE_UUID: #if (ODBCVER >= 0x0350) if (!conn->ms_jet) return SQL_C_GUID; #endif /* ODBCVER */ return ALLOW_WCHAR(conn) ? SQL_C_WCHAR : SQL_C_CHAR; case PG_TYPE_INTERVAL: #ifdef PG_INTERVAL_AS_SQL_INTERVAL if (ctype = get_interval_type(atttypmod, NULL), 0 != ctype) return ctype; #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ return CC_is_in_unicode_driver(conn) ? SQL_C_WCHAR : SQL_CHAR; default: /* hack until permanent type is available */ if (type == conn->lobj_type) return SQL_C_BINARY; /* Experimental, Does this work ? */ #ifdef EXPERIMENTAL_CURRENTLY if (ALLOW_WCHAR(conn)) return SQL_C_WCHAR; #endif /* EXPERIMENTAL_CURRENTLY */ return SQL_C_CHAR; } } const char * pgtype_attr_to_name(const ConnectionClass *conn, OID type, int atttypmod, BOOL auto_increment) { const char *tname = NULL; switch (type) { case PG_TYPE_CHAR: return "char"; case PG_TYPE_CHAR2: return "char2"; case PG_TYPE_CHAR4: return "char4"; case PG_TYPE_CHAR8: return "char8"; case PG_TYPE_INT8: return auto_increment ? "bigserial" : "int8"; case PG_TYPE_NUMERIC: return "numeric"; case PG_TYPE_VARCHAR: return "varchar"; case PG_TYPE_BPCHAR: return "char"; case PG_TYPE_TEXT: return "text"; case PG_TYPE_NAME: return "name"; case PG_TYPE_REFCURSOR: return "refcursor"; case PG_TYPE_INT2: return "int2"; case PG_TYPE_OID: return OID_NAME; case PG_TYPE_XID: return "xid"; case PG_TYPE_INT4: inolog("pgtype_to_name int4\n"); return auto_increment ? "serial" : "int4"; case PG_TYPE_FLOAT4: return "float4"; case PG_TYPE_FLOAT8: return "float8"; case PG_TYPE_DATE: return "date"; case PG_TYPE_TIME: return "time"; case PG_TYPE_ABSTIME: return "abstime"; case PG_TYPE_DATETIME: if (PG_VERSION_GT(conn, 7.1)) return "timestamptz"; else if (PG_VERSION_LT(conn, 7.0)) return "datetime"; else return "timestamp"; case PG_TYPE_TIMESTAMP_NO_TMZONE: return "timestamp without time zone"; case PG_TYPE_TIMESTAMP: return "timestamp"; case PG_TYPE_MONEY: return "money"; case PG_TYPE_BOOL: return "bool"; case PG_TYPE_BYTEA: return "bytea"; case PG_TYPE_XML: return "xml"; case PG_TYPE_MACADDR: return "macaddr"; case PG_TYPE_INET: return "inet"; case PG_TYPE_CIDR: return "cidr"; case PG_TYPE_UUID: return "uuid"; #if (ODBCVER >= 0x0300) case PG_TYPE_INTERVAL: get_interval_type(atttypmod, &tname); return tname; #endif /* ODBCVER */ case PG_TYPE_LO_UNDEFINED: return PG_TYPE_LO_NAME; default: /* hack until permanent type is available */ if (type == conn->lobj_type) return PG_TYPE_LO_NAME; /* * "unknown" can actually be used in alter table because it is * a real PG type! */ return "unknown"; } } Int4 /* PostgreSQL restriction */ pgtype_attr_column_size(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int handle_unknown_size_as) { const ConnInfo *ci = &(conn->connInfo); if (handle_unknown_size_as == UNKNOWNS_AS_DEFAULT) handle_unknown_size_as = ci->drivers.unknown_sizes; switch (type) { case PG_TYPE_CHAR: return 1; case PG_TYPE_CHAR2: return 2; case PG_TYPE_CHAR4: return 4; case PG_TYPE_CHAR8: return 8; case PG_TYPE_NAME: case PG_TYPE_REFCURSOR: { int value = 0; if (PG_VERSION_GT(conn, 7.4)) { /* * 'conn' argument is marked as const, * because this function just reads * stuff from the already-filled in * fields in the struct. But this is * an exception: CC_get_max_idlen() can * send a SHOW query to the backend to * get the identifier length. Thus cast * away the const here. */ value = CC_get_max_idlen((ConnectionClass *) conn); } #ifdef NAME_FIELD_SIZE else value = NAME_FIELD_SIZE; #endif /* NAME_FIELD_SIZE */ if (0 == value) { if (PG_VERSION_GE(conn, 7.3)) value = NAMEDATALEN_V73; else value = NAMEDATALEN_V72; } return value; } case PG_TYPE_INT2: return 5; case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: return 10; case PG_TYPE_INT8: return 19; /* signed */ case PG_TYPE_NUMERIC: return getNumericColumnSizeX(conn, type, atttypmod, adtsize_or_longest, handle_unknown_size_as); case PG_TYPE_FLOAT4: case PG_TYPE_MONEY: return 7; case PG_TYPE_FLOAT8: return 15; case PG_TYPE_DATE: return 10; case PG_TYPE_TIME: return 8; case PG_TYPE_ABSTIME: case PG_TYPE_TIMESTAMP: return 22; case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: /* return 22; */ return getTimestampColumnSizeX(conn, type, atttypmod); case PG_TYPE_BOOL: return ci->drivers.bools_as_char ? PG_WIDTH_OF_BOOLS_AS_CHAR : 1; case PG_TYPE_MACADDR: return 17; case PG_TYPE_INET: case PG_TYPE_CIDR: return sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128"); case PG_TYPE_UUID: return sizeof("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"); case PG_TYPE_LO_UNDEFINED: return SQL_NO_TOTAL; case PG_TYPE_INTERVAL: return getIntervalColumnSize(type, atttypmod); default: if (type == conn->lobj_type) /* hack until permanent * type is available */ return SQL_NO_TOTAL; if (PG_TYPE_BYTEA == type && ci->bytea_as_longvarbinary) return SQL_NO_TOTAL; /* Handle Character types and unknown types */ return getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longest, handle_unknown_size_as); } } SQLSMALLINT pgtype_attr_precision(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int handle_unknown_size_as) { switch (type) { case PG_TYPE_NUMERIC: return getNumericColumnSizeX(conn, type, atttypmod, adtsize_or_longest, handle_unknown_size_as); case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: return getTimestampDecimalDigitsX(conn, type, atttypmod); #ifdef PG_INTERVAL_AS_SQL_INTERVAL case PG_TYPE_INTERVAL: return getIntervalDecimalDigits(type, atttypmod); #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ } return -1; } Int4 pgtype_attr_display_size(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { int dsize; switch (type) { case PG_TYPE_INT2: return 6; case PG_TYPE_OID: case PG_TYPE_XID: return 10; case PG_TYPE_INT4: return 11; case PG_TYPE_INT8: return 20; /* signed: 19 digits + sign */ case PG_TYPE_NUMERIC: dsize = getNumericColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); return dsize <= 0 ? dsize : dsize + 2; case PG_TYPE_MONEY: return 15; /* ($9,999,999.99) */ case PG_TYPE_FLOAT4: return 13; case PG_TYPE_FLOAT8: return 22; case PG_TYPE_MACADDR: return 17; case PG_TYPE_INET: case PG_TYPE_CIDR: return sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128"); #if (ODBCVER >= 0x0350) case PG_TYPE_UUID: return 36; #endif /* ODBCVER */ case PG_TYPE_INTERVAL: return 30; /* Character types use regular precision */ default: return pgtype_attr_column_size(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); } } Int4 pgtype_attr_buffer_length(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { int dsize; switch (type) { case PG_TYPE_INT2: return 2; /* sizeof(SQLSMALLINT) */ case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: return 4; /* sizeof(SQLINTEGER) */ case PG_TYPE_INT8: if (SQL_C_CHAR == pgtype_attr_to_ctype(conn, type, atttypmod)) return 20; /* signed: 19 digits + sign */ return 8; /* sizeof(SQLSBININT) */ case PG_TYPE_NUMERIC: dsize = getNumericColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); return dsize <= 0 ? dsize : dsize + 2; case PG_TYPE_FLOAT4: case PG_TYPE_MONEY: return 4; /* sizeof(SQLREAL) */ case PG_TYPE_FLOAT8: return 8; /* sizeof(SQLFLOAT) */ case PG_TYPE_DATE: case PG_TYPE_TIME: return 6; /* sizeof(DATE(TIME)_STRUCT) */ case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP: case PG_TYPE_TIMESTAMP_NO_TMZONE: return 16; /* sizeof(TIMESTAMP_STRUCT) */ case PG_TYPE_MACADDR: return 17; case PG_TYPE_INET: case PG_TYPE_CIDR: return sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128"); case PG_TYPE_UUID: #if (ODBCVER >= 0x0350) return 16; /* sizeof(SQLGUID) */ #endif /* ODBCVER */ return 36; /* Character types use the default precision */ case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: { int coef = 1; Int4 prec = pgtype_attr_column_size(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as), maxvarc; if (SQL_NO_TOTAL == prec) return prec; #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) return prec * WCLEN; #endif /* UNICODE_SUPPORT */ /* after 7.2 */ if (PG_VERSION_GE(conn, 7.2)) coef = conn->mb_maxbyte_per_char; if (coef < 2 && (conn->connInfo).lf_conversion) /* CR -> CR/LF */ coef = 2; if (coef == 1) return prec; maxvarc = conn->connInfo.drivers.max_varchar_size; if (prec <= maxvarc && prec * coef > maxvarc) return maxvarc; return coef * prec; } #ifdef PG_INTERVAL_AS_SQL_INTERVAL case PG_TYPE_INTERVAL: return sizeof(SQL_INTERVAL_STRUCT); #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ default: return pgtype_attr_column_size(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); } } /* */ Int4 pgtype_attr_desclength(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { int dsize; switch (type) { case PG_TYPE_INT2: return 2; case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: return 4; case PG_TYPE_INT8: return 20; /* signed: 19 digits + sign */ case PG_TYPE_NUMERIC: dsize = getNumericColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); return dsize <= 0 ? dsize : dsize + 2; case PG_TYPE_FLOAT4: case PG_TYPE_MONEY: return 4; case PG_TYPE_FLOAT8: return 8; case PG_TYPE_DATE: case PG_TYPE_TIME: case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: return pgtype_attr_column_size(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); default: return pgtype_attr_column_size(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); } } Int2 pgtype_attr_decimal_digits(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_MONEY: case PG_TYPE_BOOL: /* * Number of digits to the right of the decimal point in * "yyyy-mm=dd hh:mm:ss[.f...]" */ case PG_TYPE_ABSTIME: case PG_TYPE_TIMESTAMP: return 0; case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: /* return 0; */ return getTimestampDecimalDigitsX(conn, type, atttypmod); case PG_TYPE_NUMERIC: return getNumericDecimalDigitsX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); #ifdef PG_INTERVAL_AS_SQL_INTERVAL case PG_TYPE_INTERVAL: return getIntervalDecimalDigits(type, atttypmod); #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ default: return -1; } } Int2 pgtype_attr_scale(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { switch (type) { case PG_TYPE_NUMERIC: return getNumericDecimalDigitsX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); } return -1; } Int4 pgtype_attr_transfer_octet_length(const ConnectionClass *conn, OID type, int atttypmod, int handle_unknown_size_as) { int coef = 1; Int4 maxvarc, column_size; switch (type) { case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: case PG_TYPE_TEXT: column_size = pgtype_attr_column_size(conn, type, atttypmod, PG_UNSPECIFIED, handle_unknown_size_as); if (SQL_NO_TOTAL == column_size) return column_size; #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) return column_size * WCLEN; #endif /* UNICODE_SUPPORT */ /* after 7.2 */ if (PG_VERSION_GE(conn, 7.2)) coef = conn->mb_maxbyte_per_char; if (coef < 2 && (conn->connInfo).lf_conversion) /* CR -> CR/LF */ coef = 2; if (coef == 1) return column_size; maxvarc = conn->connInfo.drivers.max_varchar_size; if (column_size <= maxvarc && column_size * coef > maxvarc) return maxvarc; return coef * column_size; case PG_TYPE_BYTEA: return pgtype_attr_column_size(conn, type, atttypmod, PG_UNSPECIFIED, handle_unknown_size_as); default: if (type == conn->lobj_type) return pgtype_attr_column_size(conn, type, atttypmod, PG_UNSPECIFIED, handle_unknown_size_as); } return -1; } OID sqltype_to_pgtype(const ConnectionClass *conn, SQLSMALLINT fSqlType) { OID pgType; const ConnInfo *ci = &(conn->connInfo); pgType = 0; /* ??? */ switch (fSqlType) { case SQL_BINARY: pgType = PG_TYPE_BYTEA; break; case SQL_CHAR: pgType = PG_TYPE_BPCHAR; break; #ifdef UNICODE_SUPPORT case SQL_WCHAR: pgType = PG_TYPE_BPCHAR; break; #endif /* UNICODE_SUPPORT */ case SQL_BIT: pgType = ci->drivers.bools_as_char ? PG_TYPE_CHAR : PG_TYPE_BOOL; break; #if (ODBCVER >= 0x0300) case SQL_TYPE_DATE: #endif /* ODBCVER */ case SQL_DATE: pgType = PG_TYPE_DATE; break; case SQL_DOUBLE: case SQL_FLOAT: pgType = PG_TYPE_FLOAT8; break; case SQL_DECIMAL: case SQL_NUMERIC: pgType = PG_TYPE_NUMERIC; break; case SQL_BIGINT: pgType = PG_TYPE_INT8; break; case SQL_INTEGER: pgType = PG_TYPE_INT4; break; case SQL_LONGVARBINARY: if (ci->bytea_as_longvarbinary) pgType = PG_TYPE_BYTEA; else pgType = conn->lobj_type; break; case SQL_LONGVARCHAR: pgType = ci->drivers.text_as_longvarchar ? PG_TYPE_TEXT : PG_TYPE_VARCHAR; break; #ifdef UNICODE_SUPPORT case SQL_WLONGVARCHAR: pgType = ci->drivers.text_as_longvarchar ? PG_TYPE_TEXT : PG_TYPE_VARCHAR; break; #endif /* UNICODE_SUPPORT */ case SQL_REAL: pgType = PG_TYPE_FLOAT4; break; case SQL_SMALLINT: case SQL_TINYINT: pgType = PG_TYPE_INT2; break; case SQL_TIME: #if (ODBCVER >= 0x0300) case SQL_TYPE_TIME: #endif /* ODBCVER */ pgType = PG_TYPE_TIME; break; case SQL_TIMESTAMP: #if (ODBCVER >= 0x0300) case SQL_TYPE_TIMESTAMP: #endif /* ODBCVER */ pgType = PG_TYPE_DATETIME; break; case SQL_VARBINARY: pgType = PG_TYPE_BYTEA; break; case SQL_VARCHAR: pgType = PG_TYPE_VARCHAR; break; #if UNICODE_SUPPORT case SQL_WVARCHAR: pgType = PG_TYPE_VARCHAR; break; #endif /* UNICODE_SUPPORT */ #if (ODBCVER >= 0x0350) case SQL_GUID: if (PG_VERSION_GE(conn, 8.3)) pgType = PG_TYPE_UUID; break; #endif /* ODBCVER */ case SQL_INTERVAL_MONTH: case SQL_INTERVAL_YEAR: case SQL_INTERVAL_YEAR_TO_MONTH: case SQL_INTERVAL_DAY: case SQL_INTERVAL_HOUR: case SQL_INTERVAL_MINUTE: case SQL_INTERVAL_SECOND: case SQL_INTERVAL_DAY_TO_HOUR: case SQL_INTERVAL_DAY_TO_MINUTE: case SQL_INTERVAL_DAY_TO_SECOND: case SQL_INTERVAL_HOUR_TO_MINUTE: case SQL_INTERVAL_HOUR_TO_SECOND: case SQL_INTERVAL_MINUTE_TO_SECOND: pgType = PG_TYPE_INTERVAL; break; } return pgType; } static int getAtttypmodEtc(const StatementClass *stmt, int col, int *adtsize_or_longestlen) { int atttypmod = -1; if (NULL != adtsize_or_longestlen) *adtsize_or_longestlen = -1; if (col >= 0) { const QResultClass *res; if (res = SC_get_Curres(stmt), NULL != res) { atttypmod = QR_get_atttypmod(res, col); if (NULL != adtsize_or_longestlen) { if (stmt->catalog_result) *adtsize_or_longestlen = QR_get_fieldsize(res, col); else { *adtsize_or_longestlen = QR_get_display_size(res, col); if (PG_TYPE_NUMERIC == QR_get_field_type(res, col) && atttypmod < 0 && *adtsize_or_longestlen > 0) { int i, sval, maxscale = 0; const char *tval, *sptr; for (i = 0; i < res->num_cached_rows; i++) { if (tval = QR_get_value_backend_text(res, i, col), NULL != tval) { if (sptr = strchr(tval, '.'), NULL != sptr) if (sval = strlen(tval) - (sptr + 1 - tval), sval > maxscale) maxscale = sval; } } *adtsize_or_longestlen += (maxscale << 16); } } } } } return atttypmod; } /* * There are two ways of calling this function: * * 1. When going through the supported PG types (SQLGetTypeInfo) * * 2. When taking any type id (SQLColumns, SQLGetData) * * The first type will always work because all the types defined are returned here. * The second type will return a default based on global parameter when it does not * know. This allows for supporting * types that are unknown. All other pg routines in here return a suitable default. */ SQLSMALLINT pgtype_to_concise_type(const StatementClass *stmt, OID type, int col) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_to_concise_type(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen); } SQLSMALLINT pgtype_to_sqldesctype(const StatementClass *stmt, OID type, int col) { int atttypmod = getAtttypmodEtc(stmt, col, NULL); return pgtype_attr_to_sqldesctype(SC_get_conn(stmt), type, atttypmod); } SQLSMALLINT pgtype_to_datetime_sub(const StatementClass *stmt, OID type, int col) { int atttypmod = getAtttypmodEtc(stmt, col, NULL); return pgtype_attr_to_datetime_sub(SC_get_conn(stmt), type, atttypmod); } const char * pgtype_to_name(const StatementClass *stmt, OID type, int col, BOOL auto_increment) { int atttypmod = getAtttypmodEtc(stmt, col, NULL); return pgtype_attr_to_name(SC_get_conn(stmt), type, atttypmod, auto_increment); } #ifdef NOT_USED static SQLSMALLINT getNumericDecimalDigits(const StatementClass *stmt, OID type, int col) { Int4 atttypmod = -1, default_decimal_digits = 6; QResultClass *result; ColumnInfoClass *flds; mylog("getNumericDecimalDigits: type=%d, col=%d\n", type, col); if (col < 0) return default_decimal_digits; result = SC_get_Curres(stmt); /* * Manual Result Sets -- use assigned column width (i.e., from * set_tuplefield_string) */ atttypmod = QR_get_atttypmod(result, col); if (atttypmod > -1) return (atttypmod & 0xffff); if (stmt->catalog_result) { flds = QR_get_fields(result); if (flds) { int fsize = CI_get_fieldsize(flds, col); if (fsize > 0) return fsize; } return default_decimal_digits; } else { Int4 dsp_size = QR_get_display_size(result, col); if (dsp_size <= 0) return default_decimal_digits; if (dsp_size < 5) dsp_size = 5; return dsp_size; } } static Int4 /* PostgreSQL restritiction */ getNumericColumnSize(const StatementClass *stmt, OID type, int col) { Int4 atttypmod = -1, default_column_size = 28; QResultClass *result; ColumnInfoClass *flds; mylog("getNumericColumnSize: type=%d, col=%d\n", type, col); if (col < 0) return default_column_size; result = SC_get_Curres(stmt); /* * Manual Result Sets -- use assigned column width (i.e., from * set_tuplefield_string) */ atttypmod = QR_get_atttypmod(result, col); if (atttypmod > -1) return (atttypmod >> 16) & 0xffff; if (stmt->catalog_result) { flds = QR_get_fields(result); if (flds) { int fsize = CI_get_fieldsize(flds, col); if (fsize > 0) return 2 * fsize; } return default_column_size; } else { Int4 dsp_size = QR_get_display_size(result, col); if (dsp_size <= 0) return default_column_size; dsp_size *= 2; if (dsp_size < 10) dsp_size = 10; return dsp_size; } } #ifdef NOT_USED Int4 getCharColumnSize(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { CSTR func = "getCharColumnSize"; int p = -1, attlen = -1, adtsize = -1, maxsize; QResultClass *result; ConnectionClass *conn = SC_get_conn(stmt); ConnInfo *ci = &(conn->connInfo); mylog("%s: type=%d, col=%d, unknown = %d\n", func, type, col, handle_unknown_size_as); /* Assign Maximum size based on parameters */ switch (type) { case PG_TYPE_TEXT: if (ci->drivers.text_as_longvarchar) maxsize = ci->drivers.max_longvarchar_size; else maxsize = ci->drivers.max_varchar_size; break; case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: maxsize = ci->drivers.max_varchar_size; break; default: if (ci->drivers.unknowns_as_longvarchar) maxsize = ci->drivers.max_longvarchar_size; else maxsize = ci->drivers.max_varchar_size; break; } #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn) && isSqlServr() && maxsize > 4000) maxsize = 4000; #endif /* UNICODE_SUPPORT */ if (maxsize == TEXT_FIELD_SIZE + 1) /* magic length for testing */ { if (PG_VERSION_GE(conn, 7.1)) maxsize = 0; else maxsize = TEXT_FIELD_SIZE; } /* * Static ColumnSize (i.e., the Maximum ColumnSize of the datatype) This * has nothing to do with a result set. */ if (col < 0) return maxsize; if (result = SC_get_Curres(stmt), NULL == result) return maxsize; /* * Catalog Result Sets -- use assigned column width (i.e., from * set_tuplefield_string) */ adtsize = QR_get_fieldsize(result, col); if (stmt->catalog_result) { if (adtsize > 0) return adtsize; return maxsize; } p = QR_get_display_size(result, col); /* longest */ attlen = QR_get_atttypmod(result, col); /* Size is unknown -- handle according to parameter */ if (attlen > 0) /* maybe the length is known */ { if (attlen >= p) return attlen; switch (type) { case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: #if (ODBCVER >= 0x0300) return attlen; #else if (CC_is_in_unicode_driver(conn) || conn->ms_jet) return attlen; return p; #endif /* ODBCVER */ } } /* The type is really unknown */ switch (handle_unknown_size_as) { case UNKNOWNS_AS_DONTKNOW: return -1; case UNKNOWNS_AS_LONGEST: mylog("%s: LONGEST: p = %d\n", func, p); if (p > 0) return p; break; case UNKNOWNS_AS_MAX: break; default: return -1; } if (maxsize <= 0) return maxsize; switch (type) { case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: case PG_TYPE_TEXT: return maxsize; } if (p > maxsize) maxsize = p; return maxsize; } #endif /* NOT_USED */ static SQLSMALLINT getTimestampDecimalDigits(const StatementClass *stmt, OID type, int col) { ConnectionClass *conn = SC_get_conn(stmt); Int4 atttypmod; QResultClass *result; mylog("getTimestampDecimalDigits: type=%d, col=%d\n", type, col); if (col < 0) return 0; if (PG_VERSION_LT(conn, 7.2)) return 0; result = SC_get_Curres(stmt); atttypmod = QR_get_atttypmod(result, col); mylog("atttypmod2=%d\n", atttypmod); return (atttypmod > -1 ? atttypmod : 6); } static SQLSMALLINT getTimestampColumnSize(const StatementClass *stmt, OID type, int col) { Int4 fixed, scale; mylog("getTimestampColumnSize: type=%d, col=%d\n", type, col); switch (type) { case PG_TYPE_TIME: fixed = 8; break; case PG_TYPE_TIME_WITH_TMZONE: fixed = 11; break; case PG_TYPE_TIMESTAMP_NO_TMZONE: fixed = 19; break; default: if (USE_ZONE) fixed = 22; else fixed = 19; break; } scale = getTimestampDecimalDigits(stmt, type, col); return (scale > 0) ? fixed + 1 + scale : fixed; } #endif /* NOT_USED */ /* * This corresponds to "precision" in ODBC 2.x. * * For PG_TYPE_VARCHAR, PG_TYPE_BPCHAR, PG_TYPE_NUMERIC, SQLColumns will * override this length with the atttypmod length from pg_attribute . * * If col >= 0, then will attempt to get the info from the result set. * This is used for functions SQLDescribeCol and SQLColAttributes. */ Int4 /* PostgreSQL restriction */ pgtype_column_size(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_column_size(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : handle_unknown_size_as); } /* * precision in ODBC 3.x. */ SQLSMALLINT pgtype_precision(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_precision(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : handle_unknown_size_as); } Int4 pgtype_display_size(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_display_size(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : handle_unknown_size_as); } /* * The length in bytes of data transferred on an SQLGetData, SQLFetch, * or SQLFetchScroll operation if SQL_C_DEFAULT is specified. */ Int4 pgtype_buffer_length(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_buffer_length(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : handle_unknown_size_as); } /* */ Int4 pgtype_desclength(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_desclength(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : handle_unknown_size_as); } #ifdef NOT_USED /* * Transfer octet length. */ Int4 pgtype_transfer_octet_length(const StatementClass *stmt, OID type, int column_size) { ConnectionClass *conn = SC_get_conn(stmt); int coef = 1; Int4 maxvarc; switch (type) { case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: case PG_TYPE_TEXT: if (SQL_NO_TOTAL == column_size) return column_size; #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) return column_size * WCLEN; #endif /* UNICODE_SUPPORT */ /* after 7.2 */ if (PG_VERSION_GE(conn, 7.2)) coef = conn->mb_maxbyte_per_char; if (coef < 2 && (conn->connInfo).lf_conversion) /* CR -> CR/LF */ coef = 2; if (coef == 1) return column_size; maxvarc = conn->connInfo.drivers.max_varchar_size; if (column_size <= maxvarc && column_size * coef > maxvarc) return maxvarc; return coef * column_size; case PG_TYPE_BYTEA: return column_size; default: if (type == conn->lobj_type) return column_size; } return -1; } #endif /* NOT_USED */ /* * corrsponds to "min_scale" in ODBC 2.x. */ Int2 pgtype_min_decimal_digits(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_MONEY: case PG_TYPE_BOOL: case PG_TYPE_ABSTIME: case PG_TYPE_TIMESTAMP: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_NUMERIC: return 0; default: return -1; } } /* * corrsponds to "max_scale" in ODBC 2.x. */ Int2 pgtype_max_decimal_digits(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_MONEY: case PG_TYPE_BOOL: case PG_TYPE_ABSTIME: case PG_TYPE_TIMESTAMP: return 0; case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: return 38; case PG_TYPE_NUMERIC: return getNumericDecimalDigitsX(conn, type, -1, -1, UNKNOWNS_AS_DEFAULT); default: return -1; } } /* * corrsponds to "scale" in ODBC 2.x. */ Int2 pgtype_decimal_digits(const StatementClass *stmt, OID type, int col) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_decimal_digits(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : UNKNOWNS_AS_DEFAULT); } /* * "scale" in ODBC 3.x. */ Int2 pgtype_scale(const StatementClass *stmt, OID type, int col) { int atttypmod, adtsize_or_longestlen; atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_scale(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, stmt->catalog_result ? UNKNOWNS_AS_CATALOG : UNKNOWNS_AS_DEFAULT); } Int2 pgtype_radix(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_XID: case PG_TYPE_OID: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_NUMERIC: case PG_TYPE_FLOAT4: case PG_TYPE_MONEY: case PG_TYPE_FLOAT8: return 10; default: return -1; } } Int2 pgtype_nullable(const ConnectionClass *conn, OID type) { return SQL_NULLABLE; /* everything should be nullable */ } Int2 pgtype_auto_increment(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: case PG_TYPE_FLOAT4: case PG_TYPE_MONEY: case PG_TYPE_BOOL: case PG_TYPE_FLOAT8: case PG_TYPE_INT8: case PG_TYPE_NUMERIC: case PG_TYPE_DATE: case PG_TYPE_TIME_WITH_TMZONE: case PG_TYPE_TIME: case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: return FALSE; default: return -1; } } Int2 pgtype_case_sensitive(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_CHAR: case PG_TYPE_CHAR2: case PG_TYPE_CHAR4: case PG_TYPE_CHAR8: case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: case PG_TYPE_TEXT: case PG_TYPE_NAME: case PG_TYPE_REFCURSOR: return TRUE; default: return FALSE; } } Int2 pgtype_money(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_MONEY: return TRUE; default: return FALSE; } } Int2 pgtype_searchable(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_CHAR: case PG_TYPE_CHAR2: case PG_TYPE_CHAR4: case PG_TYPE_CHAR8: case PG_TYPE_VARCHAR: case PG_TYPE_BPCHAR: case PG_TYPE_TEXT: case PG_TYPE_NAME: case PG_TYPE_REFCURSOR: return SQL_SEARCHABLE; default: if (conn && type == conn->lobj_type) return SQL_UNSEARCHABLE; return SQL_ALL_EXCEPT_LIKE; } } Int2 pgtype_unsigned(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_OID: case PG_TYPE_XID: return TRUE; case PG_TYPE_INT2: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_NUMERIC: case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_MONEY: return FALSE; default: return -1; } } const char * pgtype_literal_prefix(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_NUMERIC: case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_MONEY: return NULL; default: return "'"; } } const char * pgtype_literal_suffix(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_INT2: case PG_TYPE_OID: case PG_TYPE_XID: case PG_TYPE_INT4: case PG_TYPE_INT8: case PG_TYPE_NUMERIC: case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_MONEY: return NULL; default: return "'"; } } const char * pgtype_create_params(const ConnectionClass *conn, OID type) { switch (type) { case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: return "max. length"; case PG_TYPE_NUMERIC: return "precision, scale"; default: return NULL; } } SQLSMALLINT sqltype_to_default_ctype(const ConnectionClass *conn, SQLSMALLINT sqltype) { /* * from the table on page 623 of ODBC 2.0 Programmer's Reference * (Appendix D) */ switch (sqltype) { case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: case SQL_DECIMAL: case SQL_NUMERIC: #if (ODBCVER < 0x0300) case SQL_BIGINT: return SQL_C_CHAR; #else return SQL_C_CHAR; case SQL_BIGINT: return ALLOWED_C_BIGINT; #endif #ifdef UNICODE_SUPPORT case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: if (!ALLOW_WCHAR(conn)) return SQL_C_CHAR; return SQL_C_WCHAR; #endif /* UNICODE_SUPPORT */ case SQL_BIT: return SQL_C_BIT; case SQL_TINYINT: return SQL_C_STINYINT; case SQL_SMALLINT: return SQL_C_SSHORT; case SQL_INTEGER: return SQL_C_SLONG; case SQL_REAL: return SQL_C_FLOAT; case SQL_FLOAT: case SQL_DOUBLE: return SQL_C_DOUBLE; case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: return SQL_C_BINARY; case SQL_DATE: return SQL_C_DATE; case SQL_TIME: return SQL_C_TIME; case SQL_TIMESTAMP: return SQL_C_TIMESTAMP; #if (ODBCVER >= 0x0300) case SQL_TYPE_DATE: return SQL_C_TYPE_DATE; case SQL_TYPE_TIME: return SQL_C_TYPE_TIME; case SQL_TYPE_TIMESTAMP: return SQL_C_TYPE_TIMESTAMP; #endif /* ODBCVER */ #if (ODBCVER >= 0x0350) case SQL_GUID: if (conn->ms_jet) return SQL_C_CHAR; else return SQL_C_GUID; #endif /* ODBCVER */ default: /* should never happen */ return SQL_C_CHAR; } } Int4 ctype_length(SQLSMALLINT ctype) { switch (ctype) { case SQL_C_SSHORT: case SQL_C_SHORT: return sizeof(SWORD); case SQL_C_USHORT: return sizeof(UWORD); case SQL_C_SLONG: case SQL_C_LONG: return sizeof(SDWORD); case SQL_C_ULONG: return sizeof(UDWORD); case SQL_C_FLOAT: return sizeof(SFLOAT); case SQL_C_DOUBLE: return sizeof(SDOUBLE); case SQL_C_BIT: return sizeof(UCHAR); case SQL_C_STINYINT: case SQL_C_TINYINT: return sizeof(SCHAR); case SQL_C_UTINYINT: return sizeof(UCHAR); case SQL_C_DATE: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_DATE: #endif /* ODBCVER */ return sizeof(DATE_STRUCT); case SQL_C_TIME: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_TIME: #endif /* ODBCVER */ return sizeof(TIME_STRUCT); case SQL_C_TIMESTAMP: #if (ODBCVER >= 0x0300) case SQL_C_TYPE_TIMESTAMP: #endif /* ODBCVER */ return sizeof(TIMESTAMP_STRUCT); #if (ODBCVER >= 0x0350) case SQL_C_GUID: return sizeof(SQLGUID); #endif /* ODBCVER */ #if (ODBCVER >= 0x0300) case SQL_C_INTERVAL_YEAR: case SQL_C_INTERVAL_MONTH: case SQL_C_INTERVAL_YEAR_TO_MONTH: case SQL_C_INTERVAL_DAY: case SQL_C_INTERVAL_HOUR: case SQL_C_INTERVAL_DAY_TO_HOUR: case SQL_C_INTERVAL_MINUTE: case SQL_C_INTERVAL_DAY_TO_MINUTE: case SQL_C_INTERVAL_HOUR_TO_MINUTE: case SQL_C_INTERVAL_SECOND: case SQL_C_INTERVAL_DAY_TO_SECOND: case SQL_C_INTERVAL_HOUR_TO_SECOND: case SQL_C_INTERVAL_MINUTE_TO_SECOND: return sizeof(SQL_INTERVAL_STRUCT); #endif /* ODBCVER */ case SQL_C_BINARY: case SQL_C_CHAR: #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: #endif /* UNICODE_SUPPORT */ return 0; default: /* should never happen */ return 0; } } psqlodbc-09.03.0300/psqlodbc.c000644 001752 000000 00000014023 12335653444 016153 0ustar00saitowheel000000 000000 /*-------- * Module: psqlodbc.c * * Description: This module contains the main entry point (DllMain) * for the library. It also contains functions to get * and set global variables for the driver in the registry. * * Classes: n/a * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *-------- */ #ifdef WIN32 #ifdef _DEBUG #include #endif /* _DEBUG */ #endif /* WIN32 */ #include "psqlodbc.h" #include "dlg_specific.h" #include "environ.h" #ifdef USE_SSPI #include "sspisvcs.h" #endif /* USE_SSPI */ #include "misc.h" #ifdef WIN32 #include "loadlib.h" int platformId = 0; #endif static int exepgm = 0; BOOL isMsAccess(void) {return 1 == exepgm;} BOOL isMsQuery(void) {return 2 == exepgm;} BOOL isSqlServr(void) {return 3 == exepgm;} GLOBAL_VALUES globals; RETCODE SQL_API SQLDummyOrdinal(void); #if defined(WIN_MULTITHREAD_SUPPORT) extern CRITICAL_SECTION conns_cs, common_cs; #elif defined(POSIX_MULTITHREAD_SUPPORT) extern pthread_mutex_t conns_cs, common_cs; #ifdef POSIX_THREADMUTEX_SUPPORT #ifdef PG_RECURSIVE_MUTEXATTR static pthread_mutexattr_t recur_attr; const pthread_mutexattr_t* getMutexAttr(void) { static int init = 1; if (init) { if (0 != pthread_mutexattr_init(&recur_attr)) return NULL; if (0 != pthread_mutexattr_settype(&recur_attr, PG_RECURSIVE_MUTEXATTR)) return NULL; } init = 0; return &recur_attr; } #else const pthread_mutexattr_t* getMutexAttr(void) { return NULL; } #endif /* PG_RECURSIVE_MUTEXATTR */ #endif /* POSIX_THREADMUTEX_SUPPORT */ #endif /* WIN_MULTITHREAD_SUPPORT */ int initialize_global_cs(void) { static int init = 1; if (!init) return 0; init = 0; #ifdef WIN32 #ifdef _DEBUG #ifdef _MEMORY_DEBUG_ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); #endif /* _MEMORY_DEBUG_ */ #endif /* _DEBUG */ #endif /* WIN32 */ #ifdef POSIX_THREADMUTEX_SUPPORT getMutexAttr(); #endif /* POSIX_THREADMUTEX_SUPPORT */ InitializeLogging(); memset(&globals, 0, sizeof(globals)); INIT_CONNS_CS; INIT_COMMON_CS; return 0; } #define CORR_STRCPY(item) strncpy_null(to->item, from->item, sizeof(to->item)) #define CORR_VALCPY(item) (to->item = from->item) void copy_globals(GLOBAL_VALUES *to, const GLOBAL_VALUES *from) { memset(to, 0, sizeof(*to)); /*** memcpy(to, from, sizeof(GLOBAL_VALUES)); SET_NAME_DIRECTLY(to->drivername, NULL); SET_NAME_DIRECTLY(to->conn_settings, NULL); ***/ NAME_TO_NAME(to->drivername, from->drivername); CORR_VALCPY(fetch_max); CORR_VALCPY(socket_buffersize); CORR_VALCPY(unknown_sizes); CORR_VALCPY(max_varchar_size); CORR_VALCPY(max_longvarchar_size); CORR_VALCPY(debug); CORR_VALCPY(commlog); CORR_VALCPY(disable_optimizer); CORR_VALCPY(ksqo); CORR_VALCPY(unique_index); CORR_VALCPY(onlyread); /* readonly is reserved on Digital C++ * compiler */ CORR_VALCPY(use_declarefetch); CORR_VALCPY(text_as_longvarchar); CORR_VALCPY(unknowns_as_longvarchar); CORR_VALCPY(bools_as_char); CORR_VALCPY(lie); CORR_VALCPY(parse); CORR_VALCPY(cancel_as_freestmt); CORR_STRCPY(extra_systable_prefixes); CORR_STRCPY(protocol); NAME_TO_NAME(to->conn_settings, from->conn_settings); mylog("copy_globals driver=%s socket_buffersize=%d\n", SAFE_NAME(to->drivername), to->socket_buffersize); } #undef CORR_STRCPY #undef CORR_VALCPY void finalize_globals(GLOBAL_VALUES *glbv) { NULL_THE_NAME(glbv->drivername); NULL_THE_NAME(glbv->conn_settings); } static void finalize_global_cs(void) { DELETE_COMMON_CS; DELETE_CONNS_CS; finalize_globals(&globals); FinalizeLogging(); #ifdef _DEBUG #ifdef _MEMORY_DEBUG_ // _CrtDumpMemoryLeaks(); #endif /* _MEMORY_DEBUG_ */ #endif /* _DEBUG */ } #ifdef WIN32 HINSTANCE NEAR s_hModule; /* Saved module handle. */ /* This is where the Driver Manager attaches to this Driver */ BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: s_hModule = hInst; /* Save for dialog boxes */ if (initialize_global_cs() == 0) { char pathname[_MAX_PATH], fname[_MAX_FNAME]; OSVERSIONINFO osversion; getCommonDefaults(DBMS_NAME, ODBCINST_INI, NULL); if (GetModuleFileName(NULL, pathname, sizeof(pathname)) > 0) { _splitpath(pathname, NULL, NULL, fname, NULL); if (stricmp(fname, "msaccess") == 0) exepgm = 1; else if (strnicmp(fname, "msqry", 5) == 0) exepgm = 2; else if (strnicmp(fname, "sqlservr", 8) == 0) exepgm = 3; } osversion.dwOSVersionInfoSize = sizeof(osversion); if (GetVersionEx(&osversion)) { platformId=osversion.dwPlatformId; } mylog("exe name=%s plaformId=%d\n", fname, platformId); } break; case DLL_THREAD_ATTACH: break; case DLL_PROCESS_DETACH: mylog("DETACHING PROCESS\n"); #ifdef USE_SSPI LeaveSSPIService(); #endif /* USE_SSPI */ CleanupDelayLoadedDLLs(); /* my(q)log is unavailable from here */ finalize_global_cs(); return TRUE; case DLL_THREAD_DETACH: break; default: break; } return TRUE; UNREFERENCED_PARAMETER(lpReserved); } #else /* not WIN32 */ #ifdef __GNUC__ /* Shared library initializer and destructor, using gcc's attributes */ static void __attribute__((constructor)) psqlodbc_init(void) { initialize_global_cs(); getCommonDefaults(DBMS_NAME, ODBCINST_INI, NULL); } static void __attribute__((destructor)) psqlodbc_fini(void) { finalize_global_cs(); } #else /* not __GNUC__ */ /* Shared library initialization on non-gcc systems. */ BOOL _init(void) { initialize_global_cs(); getCommonDefaults(DBMS_NAME, ODBCINST_INI, NULL); return TRUE; } BOOL _fini(void) { finalize_global_cs(); return TRUE; } #endif /* not __GNUC__ */ #endif /* not WIN32 */ /* * This function is used to cause the Driver Manager to * call functions by number rather than name, which is faster. * The ordinal value of this function must be 199 to have the * Driver Manager do this. Also, the ordinal values of the * functions must match the value of fFunction in SQLGetFunctions() */ RETCODE SQL_API SQLDummyOrdinal(void) { return SQL_SUCCESS; } psqlodbc-09.03.0300/qresult.c000644 001752 000000 00000126616 12335653444 016057 0ustar00saitowheel000000 000000 /*--------- * Module: qresult.c * * Description: This module contains functions related to * managing result information (i.e, fetching rows * from the backend, managing the tuple cache, etc.) * and retrieving it. Depending on the situation, a * QResultClass will hold either data from the backend * or a manually built result. * * Classes: QResultClass (Functions prefix: "QR_") * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *--------- */ #include "qresult.h" #include "statement.h" #include "misc.h" #include #include #include static char QR_read_a_tuple_from_db(QResultClass *, char); /* * Used for building a Manual Result only * All info functions call this function to create the manual result set. */ void QR_set_num_fields(QResultClass *self, int new_num_fields) { BOOL allocrelatt = FALSE; if (!self) return; mylog("in QR_set_num_fields\n"); CI_set_num_fields(QR_get_fields(self), new_num_fields, allocrelatt); mylog("exit QR_set_num_fields\n"); } void QR_set_position(QResultClass *self, SQLLEN pos) { self->tupleField = self->backend_tuples + ((QR_get_rowstart_in_cache(self) + pos) * self->num_fields); } void QR_set_cache_size(QResultClass *self, SQLLEN cache_size) { self->cache_size = cache_size; } void QR_set_rowset_size(QResultClass *self, Int4 rowset_size) { self->rowset_size_include_ommitted = rowset_size; } void QR_set_cursor(QResultClass *self, const char *name) { ConnectionClass *conn = QR_get_conn(self); if (self->cursor_name) { if (name && 0 == strcmp(name, self->cursor_name)) return; free(self->cursor_name); if (conn) { CONNLOCK_ACQUIRE(conn); conn->ncursors--; CONNLOCK_RELEASE(conn); } self->cursTuple = -1; QR_set_no_cursor(self); QR_set_no_fetching_tuples(self); } else if (NULL == name) return; if (name) { self->cursor_name = strdup(name); if (conn) { CONNLOCK_ACQUIRE(conn); conn->ncursors++; CONNLOCK_RELEASE(conn); } } else { QResultClass *res; self->cursor_name = NULL; for (res = self->next; NULL != res; res = res->next) { if (NULL != res->cursor_name) free(res->cursor_name); res->cursor_name = NULL; } } } void QR_set_num_cached_rows(QResultClass *self, SQLLEN num_rows) { self->num_cached_rows = num_rows; if (QR_synchronize_keys(self)) self->num_cached_keys = self->num_cached_rows; } void QR_set_rowstart_in_cache(QResultClass *self, SQLLEN start) { if (QR_synchronize_keys(self)) self->key_base = start; self->base = start; } void QR_inc_rowstart_in_cache(QResultClass *self, SQLLEN base_inc) { if (!QR_has_valid_base(self)) mylog("QR_inc_rowstart_in_cache called while the cache is not ready\n"); self->base += base_inc; if (QR_synchronize_keys(self)) self->key_base = self->base; } void QR_set_fields(QResultClass *self, ColumnInfoClass *fields) { ColumnInfoClass *curfields = QR_get_fields(self); if (curfields == fields) return; /* * Unlink the old columninfo from this result set, freeing it if this * was the last reference. */ if (NULL != curfields) { if (curfields->refcount > 1) curfields->refcount--; else CI_Destructor(curfields); } self->fields = fields; if (NULL != fields) fields->refcount++; } /* * CLASS QResult */ QResultClass * QR_Constructor(void) { QResultClass *rv; mylog("in QR_Constructor\n"); rv = (QResultClass *) malloc(sizeof(QResultClass)); if (rv != NULL) { ColumnInfoClass *fields; rv->rstatus = PORES_EMPTY_QUERY; rv->pstatus = 0; /* construct the column info */ rv->fields = NULL; if (fields = CI_Constructor(), NULL == fields) { free(rv); return NULL; } QR_set_fields(rv, fields); rv->backend_tuples = NULL; rv->sqlstate[0] = '\0'; rv->message = NULL; rv->messageref = NULL; rv->command = NULL; rv->notice = NULL; rv->conn = NULL; rv->next = NULL; rv->pstatus = 0; rv->count_backend_allocated = 0; rv->count_keyset_allocated = 0; rv->num_total_read = 0; rv->num_cached_rows = 0; rv->num_cached_keys = 0; rv->fetch_number = 0; rv->flags = 0; /* must be cleared before calling QR_set_rowstart_in_cache() */ QR_set_rowstart_in_cache(rv, -1); rv->key_base = -1; rv->recent_processed_row_count = -1; rv->cursTuple = -1; rv->move_offset = 0; rv->num_fields = 0; rv->num_key_fields = PG_NUM_NORMAL_KEYS; /* CTID + OID */ rv->tupleField = NULL; rv->cursor_name = NULL; rv->aborted = FALSE; rv->cache_size = 0; rv->rowset_size_include_ommitted = 1; rv->move_direction = 0; rv->keyset = NULL; rv->reload_count = 0; rv->rb_alloc = 0; rv->rb_count = 0; rv->dataFilled = FALSE; rv->rollback = NULL; rv->ad_alloc = 0; rv->ad_count = 0; rv->added_keyset = NULL; rv->added_tuples = NULL; rv->up_alloc = 0; rv->up_count = 0; rv->updated = NULL; rv->updated_keyset = NULL; rv->updated_tuples = NULL; rv->dl_alloc = 0; rv->dl_count = 0; rv->deleted = NULL; rv->deleted_keyset = NULL; } mylog("exit QR_Constructor\n"); return rv; } void QR_close_result(QResultClass *self, BOOL destroy) { ConnectionClass *conn; QResultClass *next; BOOL top = TRUE; if (!self) return; mylog("QResult: in QR_close_result\n"); while(self) { /* * If conn is defined, then we may have used "backend_tuples", so in * case we need to, free it up. Also, close the cursor. */ if ((conn = QR_get_conn(self)) && conn->sock) { if (CC_is_in_trans(conn) || QR_is_withhold(self)) { if (!QR_close(self)) /* close the cursor if there is one */ { } } } QR_free_memory(self); /* safe to call anyway */ /* * Should have been freed in the close() but just in case... * QR_set_cursor clears the cursor name of all the chained results too, * so we only need to do this for the first result in the chain. */ if (top) QR_set_cursor(self, NULL); /* Free up column info */ if (destroy) QR_set_fields(self, NULL); /* Free command info (this is from strdup()) */ if (self->command) { free(self->command); self->command = NULL; } /* Free message info (this is from strdup()) */ if (self->message) { free(self->message); self->message = NULL; } /* Free notice info (this is from strdup()) */ if (self->notice) { free(self->notice); self->notice = NULL; } /* Destruct the result object in the chain */ next = self->next; self->next = NULL; if (destroy) free(self); /* Repeat for the next result in the chain */ self = next; destroy = TRUE; /* always destroy chained results */ top = FALSE; } mylog("QResult: exit close_result\n"); } void QR_Destructor(QResultClass *self) { mylog("QResult: enter DESTRUCTOR\n"); if (!self) return; QR_close_result(self, TRUE); mylog("QResult: exit DESTRUCTOR\n"); } void QR_set_command(QResultClass *self, const char *msg) { if (self->command) free(self->command); self->command = msg ? strdup(msg) : NULL; } void QR_set_message(QResultClass *self, const char *msg) { if (self->message) free(self->message); self->messageref = NULL; self->message = msg ? strdup(msg) : NULL; } void QR_add_message(QResultClass *self, const char *msg) { char *message = self->message; size_t alsize, pos; if (!msg || !msg[0]) return; if (message) { pos = strlen(message) + 1; alsize = pos + strlen(msg) + 1; } else { pos = 0; alsize = strlen(msg) + 1; } if (message = realloc(message, alsize), NULL == message) return; if (pos > 0) message[pos - 1] = ';'; strcpy(message + pos, msg); self->message = message; } void QR_set_notice(QResultClass *self, const char *msg) { if (self->notice) free(self->notice); self->notice = msg ? strdup(msg) : NULL; } void QR_add_notice(QResultClass *self, const char *msg) { char *message = self->notice; size_t alsize, pos; if (!msg || !msg[0]) return; if (message) { pos = strlen(message) + 1; alsize = pos + strlen(msg) + 1; } else { pos = 0; alsize = strlen(msg) + 1; } if (message = realloc(message, alsize), NULL == message) return; if (pos > 0) message[pos - 1] = ';'; strcpy(message + pos, msg); self->notice = message; } TupleField *QR_AddNew(QResultClass *self) { size_t alloc; UInt4 num_fields; if (!self) return NULL; inolog("QR_AddNew %dth row(%d fields) alloc=%d\n", self->num_cached_rows, QR_NumResultCols(self), self->count_backend_allocated); if (num_fields = QR_NumResultCols(self), !num_fields) return NULL; if (self->num_fields <= 0) { self->num_fields = num_fields; QR_set_reached_eof(self); } alloc = self->count_backend_allocated; if (!self->backend_tuples) { self->num_cached_rows = 0; alloc = TUPLE_MALLOC_INC; QR_MALLOC_return_with_error(self->backend_tuples, TupleField, alloc * sizeof(TupleField) * num_fields, self, "Out of memory in QR_AddNew.", NULL); } else if (self->num_cached_rows >= self->count_backend_allocated) { alloc = self->count_backend_allocated * 2; QR_REALLOC_return_with_error(self->backend_tuples, TupleField, alloc * sizeof(TupleField) * num_fields, self, "Out of memory in QR_AddNew.", NULL); } self->count_backend_allocated = alloc; if (self->backend_tuples) { memset(self->backend_tuples + num_fields * self->num_cached_rows, 0, num_fields * sizeof(TupleField)); self->num_cached_rows++; self->ad_count++; } return self->backend_tuples + num_fields * (self->num_cached_rows - 1); } void QR_free_memory(QResultClass *self) { SQLLEN num_backend_rows = self->num_cached_rows; int num_fields = self->num_fields; mylog("QResult: free memory in, fcount=%d\n", num_backend_rows); if (self->backend_tuples) { ClearCachedRows(self->backend_tuples, num_fields, num_backend_rows); free(self->backend_tuples); self->count_backend_allocated = 0; self->backend_tuples = NULL; self->dataFilled = FALSE; } if (self->keyset) { ConnectionClass *conn = QR_get_conn(self); free(self->keyset); self->keyset = NULL; self->count_keyset_allocated = 0; if (self->reload_count > 0 && conn && conn->sock) { char plannm[32]; snprintf(plannm, sizeof(plannm), "_KEYSET_%p", self); if (CC_is_in_error_trans(conn)) { CC_mark_a_object_to_discard(conn, 's',plannm); } else { QResultClass *res; char cmd[64]; snprintf(cmd, sizeof(cmd), "DEALLOCATE \"%s\"", plannm); res = CC_send_query(conn, cmd, NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL); QR_Destructor(res); } } self->reload_count = 0; } if (self->rollback) { free(self->rollback); self->rb_alloc = 0; self->rb_count = 0; self->rollback = NULL; } if (self->deleted) { free(self->deleted); self->deleted = NULL; } if (self->deleted_keyset) { free(self->deleted_keyset); self->deleted_keyset = NULL; } self->dl_alloc = 0; self->dl_count = 0; /* clear added info */ if (self->added_keyset) { free(self->added_keyset); self->added_keyset = NULL; } if (self->added_tuples) { ClearCachedRows(self->added_tuples, num_fields, self->ad_count); free(self->added_tuples); self->added_tuples = NULL; } self->ad_alloc = 0; self->ad_count = 0; /* clear updated info */ if (self->updated) { free(self->updated); self->updated = NULL; } if (self->updated_keyset) { free(self->updated_keyset); self->updated_keyset = NULL; } if (self->updated_tuples) { ClearCachedRows(self->updated_tuples, num_fields, self->up_count); free(self->updated_tuples); self->updated_tuples = NULL; } self->up_alloc = 0; self->up_count = 0; self->num_total_read = 0; self->num_cached_rows = 0; self->num_cached_keys = 0; self->cursTuple = -1; self->pstatus = 0; mylog("QResult: free memory out\n"); } /* This function is called by send_query() */ char QR_fetch_tuples(QResultClass *self, ConnectionClass *conn, const char *cursor, int *LastMessageType) { CSTR func = "QR_fetch_tuples"; SQLLEN tuple_size; /* * If called from send_query the first time (conn != NULL), then set * the inTuples state, and read the tuples. If conn is NULL, it * implies that we are being called from next_tuple(), like to get * more rows so don't call next_tuple again! */ if (conn != NULL) { ConnInfo *ci = &(conn->connInfo); BOOL fetch_cursor = (cursor && cursor[0]); if (NULL != LastMessageType) *LastMessageType = 0; QR_set_conn(self, conn); mylog("%s: cursor = '%s', self->cursor=%p\n", func, (cursor == NULL) ? "" : cursor, QR_get_cursor(self)); if (cursor && !cursor[0]) cursor = NULL; if (fetch_cursor) { if (!cursor) { QR_set_rstatus(self, PORES_INTERNAL_ERROR); QR_set_message(self, "Internal Error -- no cursor for fetch"); return FALSE; } } QR_set_cursor(self, cursor); /* * Read the field attributes. * * $$$$ Should do some error control HERE! $$$$ */ if (CI_read_fields(QR_get_fields(self), QR_get_conn(self))) { QR_set_rstatus(self, PORES_FIELDS_OK); self->num_fields = CI_get_num_fields(QR_get_fields(self)); if (QR_haskeyset(self)) self->num_fields -= self->num_key_fields; } else { if (NULL == QR_get_fields(self)->coli_array) { QR_set_rstatus(self, PORES_NO_MEMORY_ERROR); QR_set_messageref(self, "Out of memory while reading field information"); } else { QR_set_rstatus(self, PORES_BAD_RESPONSE); QR_set_message(self, "Error reading field information"); } return FALSE; } mylog("%s: past CI_read_fields: num_fields = %d\n", func, self->num_fields); if (fetch_cursor) { if (self->cache_size <= 0) self->cache_size = ci->drivers.fetch_max; tuple_size = self->cache_size; } else tuple_size = TUPLE_MALLOC_INC; /* allocate memory for the tuple cache */ mylog("MALLOC: tuple_size = %d, size = %d\n", tuple_size, self->num_fields * sizeof(TupleField) * tuple_size); self->count_backend_allocated = self->count_keyset_allocated = 0; if (self->num_fields > 0) { QR_MALLOC_return_with_error(self->backend_tuples, TupleField, self->num_fields * sizeof(TupleField) * tuple_size, self, "Could not get memory for tuple cache.", FALSE); self->count_backend_allocated = tuple_size; } if (QR_haskeyset(self)) { QR_MALLOC_return_with_error(self->keyset, KeySet, sizeof(KeySet) * tuple_size, self, "Could not get memory for key cache.", FALSE); memset(self->keyset, 0, sizeof(KeySet) * tuple_size); self->count_keyset_allocated = tuple_size; } QR_set_fetching_tuples(self); /* Force a read to occur in next_tuple */ QR_set_num_cached_rows(self, 0); QR_set_next_in_cache(self, 0); QR_set_rowstart_in_cache(self, 0); self->key_base = 0; return QR_next_tuple(self, NULL, LastMessageType); } else { /* * Always have to read the field attributes. But we dont have to * reallocate memory for them! */ if (!CI_read_fields(NULL, QR_get_conn(self))) { QR_set_rstatus(self, PORES_BAD_RESPONSE); QR_set_message(self, "Error reading field information"); return FALSE; } return TRUE; } } /* * Procedure needed when closing cursors. */ void QR_on_close_cursor(QResultClass *self) { QR_set_cursor(self, NULL); QR_set_has_valid_base(self); } /* * Close the cursor and end the transaction (if no cursors left) * We only close the cursor if other cursors are used. */ int QR_close(QResultClass *self) { ConnectionClass *conn; QResultClass *res; int ret = TRUE; conn = QR_get_conn(self); if (self && QR_get_cursor(self)) { if (CC_is_in_error_trans(conn)) { if (QR_is_withhold(self)) CC_mark_a_object_to_discard(conn, 'p', QR_get_cursor(self)); } else { BOOL does_commit = FALSE; UDWORD flag = 0; char buf[64]; if (QR_needs_survival_check(self)) flag = ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN; snprintf(buf, sizeof(buf), "close \"%s\"", QR_get_cursor(self)); /* End the transaction if there are no cursors left on this conn */ if (CC_is_in_trans(conn) && CC_does_autocommit(conn) && CC_cursor_count(conn) <= 1) { mylog("QResult: END transaction on conn=%p\n", conn); if ((ROLLBACK_ON_ERROR & flag) == 0) { strlcat(buf, ";commit", sizeof(buf)); flag |= END_WITH_COMMIT; QR_set_cursor(self, NULL); } else does_commit = TRUE; } res = CC_send_query(conn, buf, NULL, flag, NULL); QR_Destructor(res); if (does_commit) { if (!CC_commit(conn)) { QR_set_rstatus(self, PORES_FATAL_ERROR); QR_set_message(self, "Error ending transaction on autocommit."); ret = FALSE; } } } QR_on_close_cursor(self); if (!ret) return ret; #ifdef NOT_USED /* End the transaction if there are no cursors left on this conn */ if (CC_does_autocommit(conn) && CC_cursor_count(conn) == 0) { mylog("QResult: END transaction on conn=%p\n", conn); if (!CC_commit(conn)) { QR_set_rstatus(self, PORES_FATAL_ERROR); QR_set_message(self, "Error ending transaction."); ret = FALSE; } } #endif /* NOT_USED */ } return ret; } BOOL QR_get_tupledata(QResultClass *self, BOOL binary) { BOOL haskeyset = QR_haskeyset(self); SQLULEN num_total_rows = QR_get_num_total_tuples(self); inolog("QR_get_tupledata %p->num_fields=%d\n", self, self->num_fields); if (!QR_get_cursor(self)) { if (self->num_fields > 0 && num_total_rows >= self->count_backend_allocated) { SQLLEN tuple_size = self->count_backend_allocated; mylog("REALLOC: old_count = %d, size = %d\n", tuple_size, self->num_fields * sizeof(TupleField) * tuple_size); if (tuple_size < 1) tuple_size = TUPLE_MALLOC_INC; else tuple_size *= 2; QR_REALLOC_return_with_error(self->backend_tuples, TupleField, tuple_size * self->num_fields * sizeof(TupleField), self, "Out of memory while reading tuples.", FALSE); self->count_backend_allocated = tuple_size; } if (haskeyset && self->num_cached_keys >= self->count_keyset_allocated) { SQLLEN tuple_size = self->count_keyset_allocated; if (tuple_size < 1) tuple_size = TUPLE_MALLOC_INC; else tuple_size *= 2; QR_REALLOC_return_with_error(self->keyset, KeySet, sizeof(KeySet) * tuple_size, self, "Out of mwmory while allocating keyset", FALSE); self->count_keyset_allocated = tuple_size; } } if (!QR_read_a_tuple_from_db(self, (char) binary)) { if (0 == QR_get_rstatus(self)) { QR_set_rstatus(self, PORES_BAD_RESPONSE); QR_set_message(self, "Error reading the tuple"); } return FALSE; } inolog("!!%p->cursTup=%d total_read=%d\n", self, self->cursTuple, self->num_total_read); if (!QR_once_reached_eof(self) && self->cursTuple >= (Int4) self->num_total_read) self->num_total_read = self->cursTuple + 1; inolog("!!cursTup=%d total_read=%d\n", self->cursTuple, self->num_total_read); if (self->num_fields > 0) { QR_inc_num_cache(self); } else if (haskeyset) self->num_cached_keys++; return TRUE; } static SQLLEN enlargeKeyCache(QResultClass *self, SQLLEN add_size, const char *message) { size_t alloc, alloc_req; Int4 num_fields = self->num_fields; BOOL curs = (NULL != QR_get_cursor(self)); if (add_size <= 0) return self->count_keyset_allocated; alloc = self->count_backend_allocated; if (num_fields > 0 && ((alloc_req = (Int4)self->num_cached_rows + add_size) > alloc || !self->backend_tuples)) { if (1 > alloc) { if (curs) alloc = alloc_req; else alloc = (alloc_req > TUPLE_MALLOC_INC ? alloc_req : TUPLE_MALLOC_INC); } else { do { alloc *= 2; } while (alloc < alloc_req); } self->count_backend_allocated = 0; QR_REALLOC_return_with_error(self->backend_tuples, TupleField, num_fields * sizeof(TupleField) * alloc, self, message, -1); self->count_backend_allocated = alloc; } alloc = self->count_keyset_allocated; if (QR_haskeyset(self) && ((alloc_req = (Int4)self->num_cached_keys + add_size) > alloc || !self->keyset)) { if (1 > alloc) { if (curs) alloc = alloc_req; else alloc = (alloc_req > TUPLE_MALLOC_INC ? alloc_req : TUPLE_MALLOC_INC); } else { do { alloc *= 2; } while (alloc < alloc_req); } self->count_keyset_allocated = 0; QR_REALLOC_return_with_error(self->keyset, KeySet, sizeof(KeySet) * alloc, self, message, -1); self->count_keyset_allocated = alloc; } return alloc; } /* This function is called by fetch_tuples() AND SQLFetch() */ int QR_next_tuple(QResultClass *self, StatementClass *stmt, int *LastMessageType) { CSTR func = "QR_next_tuple"; int id, ret = TRUE; SocketClass *sock; /* Speed up access */ SQLLEN fetch_number = self->fetch_number, cur_fetch = 0; SQLLEN num_total_rows; SQLLEN num_backend_rows = self->num_cached_rows, num_rows_in; Int4 num_fields = self->num_fields, fetch_size, req_size; SQLLEN offset = 0, end_tuple; char boundary_adjusted = FALSE; TupleField *the_tuples = self->backend_tuples; /* ERROR_MSG_LENGTH is sufficient */ char msgbuffer[ERROR_MSG_LENGTH + 1]; /* QR_set_command() dups this string so doesn't need static */ char cmdbuffer[ERROR_MSG_LENGTH + 1]; char fetch[128]; QueryInfo qi; ConnectionClass *conn; ConnInfo *ci = NULL; BOOL rcvend, loopend, kill_conn, internally_invoked = FALSE; BOOL reached_eof_now = FALSE, curr_eof; /* detecting EOF is pretty important */ BOOL ExecuteRequest = FALSE; Int4 response_length; inolog("Oh %p->fetch_number=%d\n", self, self->fetch_number); inolog("in total_read=%d cursT=%d currT=%d ad=%d total=%d rowsetSize=%d\n", self->num_total_read, self->cursTuple, stmt ? stmt->currTuple : -1, self->ad_count, QR_get_num_total_tuples(self), self->rowset_size_include_ommitted); if (NULL != LastMessageType) *LastMessageType = 0; num_total_rows = QR_get_num_total_tuples(self); conn = QR_get_conn(self); curr_eof = FALSE; req_size = self->rowset_size_include_ommitted; if (QR_once_reached_eof(self) && self->cursTuple >= (Int4) QR_get_num_total_read(self)) curr_eof = TRUE; #define return DONT_CALL_RETURN_FROM_HERE??? #define RETURN(code) { ret = code; goto cleanup;} ENTER_CONN_CS(conn); if (0 != self->move_offset) { char movecmd[256]; QResultClass *mres; SQLULEN movement, moved; movement = self->move_offset; if (QR_is_moving_backward(self)) { if (self->cache_size > req_size) { SQLLEN incr_move = self->cache_size - (req_size < 0 ? 1 : req_size); movement += incr_move; if (movement > (UInt4)(self->cursTuple + 1)) movement = self->cursTuple + 1; } else self->cache_size = req_size; inolog("cache=%d rowset=%d movement=" FORMAT_ULEN "\n", self->cache_size, req_size, movement); snprintf(movecmd, sizeof(movecmd), "move backward " FORMAT_ULEN " in \"%s\"", movement, QR_get_cursor(self)); } else if (QR_is_moving_forward(self)) snprintf(movecmd, sizeof(movecmd), "move " FORMAT_ULEN " in \"%s\"", movement, QR_get_cursor(self)); else { snprintf(movecmd, sizeof(movecmd), "move all in \"%s\"", QR_get_cursor(self)); movement = INT_MAX; } mres = CC_send_query(conn, movecmd, NULL, 0, stmt); if (!QR_command_maybe_successful(mres)) { QR_Destructor(mres); if (stmt) SC_set_error(stmt, STMT_EXEC_ERROR, "move error occured", func); RETURN(-1) } moved = movement; if (sscanf(mres->command, "MOVE " FORMAT_ULEN, &moved) > 0) { inolog("moved=%d ? " FORMAT_ULEN "\n", moved, movement); if (moved < movement) { if (0 < moved) moved++; else if (QR_is_moving_backward(self) && self->cursTuple < 0) ; else if (QR_is_moving_not_backward(self) && curr_eof) ; else moved++; if (QR_is_moving_not_backward(self)) { curr_eof = TRUE; if (!QR_once_reached_eof(self)) { self->num_total_read = self->cursTuple + moved; QR_set_reached_eof(self); } } if (QR_is_moving_from_the_last(self)) /* in case of FETCH LAST */ { SQLULEN bmovement, mback; SQLLEN rowset_start = self->cursTuple + 1, back_offset = self->move_offset, backpt; inolog("FETCH LAST case\n"); if (getNthValid(self, QR_get_num_total_tuples(self) - 1, SQL_FETCH_PRIOR, self->move_offset, &backpt) < 0) { /* the rowset_start is on BOF */ self->tupleField = NULL; SC_set_rowset_start(stmt, -1, TRUE); stmt->currTuple = -1; RETURN(-1) } back_offset = QR_get_num_total_tuples(self) - backpt; inolog("back_offset=%d and move_offset=%d\n", back_offset, self->move_offset); if (back_offset + 1 > (Int4) self->ad_count) { bmovement = back_offset + 1 - self->ad_count; snprintf(movecmd, sizeof(movecmd), "move backward " FORMAT_ULEN " in \"%s\"", bmovement, QR_get_cursor(self)); QR_Destructor(mres); mres = CC_send_query(conn, movecmd, NULL, 0, stmt); if (!QR_command_maybe_successful(mres)) { QR_Destructor(mres); if (stmt) SC_set_error(stmt, STMT_EXEC_ERROR, "move error occured", func); RETURN(-1) } if (sscanf(mres->command, "MOVE " FORMAT_ULEN, &mback) > 0) { if (mback < bmovement) mback++; if (moved < mback) { QR_set_move_backward(self); mback -= moved; moved = mback; self->move_offset = moved; rowset_start = self->cursTuple - moved + 1; } else { QR_set_move_forward(self); moved-= mback; self->move_offset = moved; rowset_start = self->cursTuple + moved + 1; } } } else { QR_set_move_forward(self); self->move_offset = moved + self->ad_count - back_offset - 1; rowset_start = self->cursTuple +self->move_offset + 1; /* adjust move_offset */ /*** self->move_offset++; ***/ } if (stmt) { SC_set_rowset_start(stmt, rowset_start, TRUE); /* affects the result's rowset_start but it is reset immediately ... */ stmt->currTuple = RowIdx2GIdx(-1, stmt); } } } } /* ... by the following call */ QR_set_rowstart_in_cache(self, -1); if (QR_is_moving_backward(self)) { self->cursTuple -= moved; offset = moved - self->move_offset; } else { self->cursTuple += moved; offset = self->move_offset - moved; } QR_Destructor(mres); self->move_offset = 0; num_backend_rows = self->num_cached_rows; } else if (fetch_number < num_backend_rows) { if (!self->dataFilled) /* should never occur */ { if (stmt) SC_set_error(stmt, STMT_EXEC_ERROR, "Hmm where are fetched data?", func); RETURN(-1) } /* return a row from cache */ mylog("%s: fetch_number < fcount: returning tuple %d, fcount = %d\n", func, fetch_number, num_backend_rows); self->tupleField = the_tuples + (fetch_number * num_fields); inolog("tupleField=%p\n", self->tupleField); /* move to next row */ QR_inc_next_in_cache(self); RETURN(TRUE) } else if (QR_once_reached_eof(self)) { BOOL reached_eod = FALSE; SQLULEN num_total_read = self->num_total_read; if (stmt) { if (stmt->currTuple + 1 >= num_total_rows) reached_eod = TRUE; } else if (self->cursTuple + 1 >= (Int4)num_total_read) { if (self->ad_count == 0) reached_eod = TRUE; } if (reached_eod) { mylog("next_tuple: fetch end\n"); self->tupleField = NULL; /* end of tuples */ RETURN(-1) } } end_tuple = req_size + QR_get_rowstart_in_cache(self); /* * See if we need to fetch another group of rows. We may be being * called from send_query(), and if so, don't send another fetch, * just fall through and read the tuples. */ self->tupleField = NULL; fetch_size = 0; if (!QR_is_fetching_tuples(self)) { ci = &(conn->connInfo); if (!QR_get_cursor(self)) { mylog("%s: ALL_ROWS: done, fcount = %d, fetch_number = %d\n", func, QR_get_num_total_tuples(self), fetch_number); self->tupleField = NULL; QR_set_reached_eof(self); RETURN(-1) /* end of tuples */ } if (QR_get_rowstart_in_cache(self) >= num_backend_rows || QR_is_moving(self)) { TupleField *tuple = self->backend_tuples; /* not a correction */ /* Determine the optimum cache size. */ if (ci->drivers.fetch_max % req_size == 0) fetch_size = ci->drivers.fetch_max; else if ((Int4)req_size < ci->drivers.fetch_max) /*fetch_size = (ci->drivers.fetch_max / req_size + 1) * req_size;*/ fetch_size = (ci->drivers.fetch_max / req_size) * req_size; else fetch_size = req_size; self->cache_size = fetch_size; /* clear obsolete tuples */ inolog("clear obsolete %d tuples\n", num_backend_rows); ClearCachedRows(tuple, num_fields, num_backend_rows); self->dataFilled = FALSE; QR_stop_movement(self); self->move_offset = 0; QR_set_next_in_cache(self, offset + 1); } else { /* * The rowset boundary doesn't match that of * the inner resultset. Enlarge the resultset * and fetch the rest of the rowset. */ /* The next fetch size is */ fetch_size = (Int4) (end_tuple - num_backend_rows); if (fetch_size <= 0) { mylog("corrupted fetch_size end_tuple=%d <= cached_rows=%d\n", end_tuple, num_backend_rows); RETURN(-1) } /* and enlarge the cache size */ self->cache_size += fetch_size; offset = self->fetch_number; QR_inc_next_in_cache(self); boundary_adjusted = TRUE; } if (enlargeKeyCache(self, self->cache_size - num_backend_rows, "Out of memory while reading tuples") < 0) RETURN(FALSE) if (PROTOCOL_74(ci) && !QR_is_permanent(self) /* Execute seems an invalid operation after COMMIT */ ) { ExecuteRequest = TRUE; if (!SendExecuteRequest(stmt, QR_get_cursor(self), fetch_size)) RETURN(FALSE) if (!SendSyncRequest(conn)) RETURN(FALSE) } else { QResultClass *res; snprintf(fetch, sizeof(fetch), "fetch %d in \"%s\"", fetch_size, QR_get_cursor(self)); mylog("%s: sending actual fetch (%d) query '%s'\n", func, fetch_size, fetch); /* don't read ahead for the next tuple (self) ! */ qi.row_size = self->cache_size; qi.result_in = self; qi.cursor = NULL; res = CC_send_query(conn, fetch, &qi, 0, stmt); if (!QR_command_maybe_successful(res)) { if (!QR_get_message(self)) QR_set_message(self, "Error fetching next group."); RETURN(FALSE) } } internally_invoked = TRUE; cur_fetch = 0; QR_set_fetching_tuples(self); } else { mylog("%s: inTuples = true, falling through: fcount = %d, fetch_number = %d\n", func, self->num_cached_rows, self->fetch_number); /* * This is a pre-fetch (fetching rows right after query but * before any real SQLFetch() calls. This is done so the * field attributes are available. */ QR_set_next_in_cache(self, 0); } if (!boundary_adjusted) { QR_set_rowstart_in_cache(self, offset); QR_set_num_cached_rows(self, 0); } sock = CC_get_socket(conn); self->tupleField = NULL; ci = &(conn->connInfo); num_rows_in = self->num_cached_rows; curr_eof = reached_eof_now = (QR_once_reached_eof(self) && self->cursTuple >= (Int4)self->num_total_read); inolog("reached_eof_now=%d\n", reached_eof_now); for (kill_conn = loopend = rcvend = FALSE; !loopend;) { id = SOCK_get_id(sock); if (0 != SOCK_get_errcode(sock)) break; if (NULL != LastMessageType) *LastMessageType = id; response_length = SOCK_get_response_length(sock); if (0 != SOCK_get_errcode(sock)) break; inolog("id='%c' response_length=%d\n", id, response_length); switch (id) { case 'P': mylog("Portal name within tuples ?? just ignore\n"); SOCK_get_string(sock, msgbuffer, ERROR_MSG_LENGTH); break; case 'T': mylog("Tuples within tuples ?? OK try to handle them\n"); QR_set_no_fetching_tuples(self); if (self->num_total_read > 0) { mylog("fetched %d rows\n", self->num_total_read); /* set to first row */ self->tupleField = self->backend_tuples + (offset * num_fields); } else { mylog(" [ fetched 0 rows ]\n"); } /* add new Result class */ self->next = QR_Constructor(); if (!self->next) { CC_set_error(conn, CONNECTION_COULD_NOT_RECEIVE, "Could not create result info in QR_next_tuple.", func); CC_on_abort(conn, CONN_DEAD); RETURN(FALSE) } QR_set_cache_size(self->next, self->cache_size); self = self->next; if (!QR_fetch_tuples(self, conn, NULL, LastMessageType)) { CC_set_error(conn, CONNECTION_COULD_NOT_RECEIVE, QR_get_message(self), func); RETURN(FALSE) } loopend = rcvend = TRUE; break; case 'B': /* Tuples in binary format */ case 'D': /* Tuples in ASCII format */ if (!QR_get_tupledata(self, id == 'B')) { ret = FALSE; loopend = TRUE; } cur_fetch++; break; /* continue reading */ case 'C': /* End of tuple list */ SOCK_get_string(sock, cmdbuffer, ERROR_MSG_LENGTH); QR_set_command(self, cmdbuffer); mylog("end of tuple list -- setting inUse to false: this = %p %s\n", self, cmdbuffer); qlog(" [ fetched %d rows ]\n", self->num_total_read); mylog("_%s: 'C' fetch_total = %d & this_fetch = %d\n", func, self->num_total_read, self->num_cached_rows); if (QR_is_fetching_tuples(self)) { self->dataFilled = TRUE; QR_set_no_fetching_tuples(self); if (internally_invoked) { if (ExecuteRequest) /* Execute completed without accepting Portal Suspend */ reached_eof_now = TRUE; else if (cur_fetch < fetch_size) reached_eof_now = TRUE; } else if (self->num_cached_rows < self->cache_size) reached_eof_now = TRUE; else if (!QR_get_cursor(self)) reached_eof_now = TRUE; } if (reached_eof_now) { /* last row from cache */ /* We are done because we didn't even get CACHE_SIZE tuples */ mylog("%s: backend_rows < CACHE_SIZE: brows = %d, cache_size = %d\n", func, num_backend_rows, self->cache_size); } if (!internally_invoked || PG_VERSION_LE(conn, 6.3)) loopend = rcvend = TRUE; break; case 'E': /* Error */ handle_error_message(conn, msgbuffer, sizeof(msgbuffer), self->sqlstate, "next_tuple", self); mylog("ERROR from backend in next_tuple: '%s'\n", msgbuffer); qlog("ERROR from backend in next_tuple: '%s'\n", msgbuffer); if (!internally_invoked || PG_VERSION_LE(conn, 6.3)) loopend = rcvend = TRUE; ret = FALSE; break; case 'N': /* Notice */ handle_notice_message(conn, cmdbuffer, sizeof(cmdbuffer), self->sqlstate, "next_tuple", self); qlog("NOTICE from backend in next_tuple: '%s'\n", msgbuffer); continue; case 'Z': /* Ready for query */ EatReadyForQuery(conn); if (QR_is_fetching_tuples(self)) { reached_eof_now = TRUE; QR_set_no_fetching_tuples(self); } loopend = rcvend = TRUE; break; case 's': /* portal suspend */ mylog("portal suspend"); QR_set_no_fetching_tuples(self); self->dataFilled = TRUE; break; default: /* skip the unexpected response if possible */ if (response_length >= 0) break; /* this should only happen if the backend * dumped core ??? */ mylog("%s: Unexpected result from backend: id = '%c' (%d)\n", func, id, id); qlog("%s: Unexpected result from backend: id = '%c' (%d)\n", func, id, id); QR_set_message(self, "Unexpected result from backend. It probably crashed"); loopend = kill_conn = TRUE; } if (0 != SOCK_get_errcode(sock)) break; } if (!kill_conn && !rcvend && 0 == SOCK_get_errcode(sock)) { if (PROTOCOL_74(ci)) { for (;;) /* discard the result until ReadyForQuery comes */ { id = SOCK_get_id(sock); if (0 != SOCK_get_errcode(sock)) break; if (NULL != LastMessageType) *LastMessageType = id; response_length = SOCK_get_response_length(sock); if (0 != SOCK_get_errcode(sock)) break; if ('Z' == id) /* ready for query */ { EatReadyForQuery(conn); qlog("%s discarded data until ReadyForQuery comes\n", __FUNCTION__); if (QR_is_fetching_tuples(self)) { reached_eof_now = TRUE; QR_set_no_fetching_tuples(self); } break; } } } else kill_conn = TRUE; } if (0 != SOCK_get_errcode(sock)) { if (QR_command_maybe_successful(self)) QR_set_message(self, "Communication error while getting a tuple"); kill_conn = TRUE; } if (kill_conn) { if (0 == QR_get_rstatus(self)) QR_set_rstatus(self, PORES_BAD_RESPONSE); CC_on_abort(conn, CONN_DEAD); ret = FALSE; } if (!ret) RETURN(ret) if (!QR_is_fetching_tuples(self)) { SQLLEN start_idx = 0; num_backend_rows = self->num_cached_rows; if (reached_eof_now) { mylog("%s: reached eof now\n", func); QR_set_reached_eof(self); if (!curr_eof) { if (self->cursTuple >= (Int4) self->num_total_read) { self->num_total_read = self->cursTuple + 1; inolog("mayumi setting total_read to %d\n", self->num_total_read); } self->cursTuple++; } if (self->ad_count > 0 && cur_fetch < fetch_size) { /* We have to append the tuples(keys) info from the added tuples(keys) here */ SQLLEN add_size; TupleField *tuple, *added_tuple; if (curr_eof) { start_idx = CacheIdx2GIdx(offset, stmt, self) - self->num_total_read; add_size = self->ad_count - start_idx; if (0 == num_backend_rows) { offset = 0; QR_set_rowstart_in_cache(self, offset); QR_set_next_in_cache(self, offset); } } else { start_idx = 0; add_size = self->ad_count; } if (add_size > fetch_size - cur_fetch) add_size = fetch_size - cur_fetch; inolog("will add %d added_tuples from %d and select the %dth added tuple\n", add_size, start_idx, offset - num_backend_rows + start_idx); if (add_size > fetch_size - cur_fetch) add_size = fetch_size - cur_fetch; else if (add_size < 0) add_size = 0; if (enlargeKeyCache(self, add_size, "Out of memory while adding tuples") < 0) RETURN(FALSE) /* append the KeySet info first */ memcpy(self->keyset + num_backend_rows, (void *)(self->added_keyset + start_idx), sizeof(KeySet) * add_size); /* and append the tuples info */ tuple = self->backend_tuples + num_fields * num_backend_rows; memset(tuple, 0, sizeof(TupleField) * num_fields * add_size); added_tuple = self->added_tuples + num_fields * start_idx; ReplaceCachedRows(tuple, added_tuple, num_fields, add_size); self->num_cached_rows += add_size; self->num_cached_keys += add_size; num_backend_rows = self->num_cached_rows; } } if (offset < num_backend_rows) { /* set to first row */ self->tupleField = self->backend_tuples + (offset * num_fields); } else { /* We are surely done here (we read 0 tuples) */ mylog("_%s: 'C': DONE (fcount == %d)\n", func, num_backend_rows); ret = -1; /* end of tuples */ } } /* If the cursor operation was invoked inside this function, we have to set the status bits here. */ if (internally_invoked && self->keyset && (self->dl_count > 0 || self->up_count > 0)) { SQLLEN i, lf; SQLLEN lidx, hidx; SQLLEN *deleted = self->deleted, *updated = self->updated; num_backend_rows = QR_get_num_cached_tuples(self); /* For simplicty, use CURS_NEEDS_REREAD bit to mark the row */ for (i = num_rows_in; i < num_backend_rows; i++) self->keyset[i].status |= CURS_NEEDS_REREAD; hidx = RowIdx2GIdx(num_backend_rows, stmt); lidx = hidx - num_backend_rows; /* deleted info */ for (i = 0; i < self->dl_count && hidx > deleted[i]; i++) { if (lidx <= deleted[i]) { lf = num_backend_rows - hidx + deleted[i]; self->keyset[lf].status = self->deleted_keyset[i].status; /* mark the row off */ self->keyset[lf].status &= (~CURS_NEEDS_REREAD); } } for (i = self->up_count - 1; i >= 0; i--) { if (hidx > updated[i] && lidx <= updated[i]) { lf = num_backend_rows - hidx + updated[i]; /* in case the row is marked off */ if (0 == (self->keyset[lf].status & CURS_NEEDS_REREAD)) continue; self->keyset[lf] = self->updated_keyset[i]; ReplaceCachedRows(self->backend_tuples + lf * num_fields, self->updated_tuples + i * num_fields, num_fields, 1); self->keyset[lf].status &= (~CURS_NEEDS_REREAD); } } /* reset CURS_NEEDS_REREAD bit */ for (i = 0; i < num_backend_rows; i++) { self->keyset[i].status &= (~CURS_NEEDS_REREAD); /*inolog("keyset[%d].status=%x\n", i, self->keyset[i].status);*/ } } cleanup: LEAVE_CONN_CS(conn); #undef RETURN #undef return inolog("%s returning %d offset=%d\n", func, ret, offset); return ret; } static char QR_read_a_tuple_from_db(QResultClass *self, char binary) { Int2 field_lf; TupleField *this_tuplefield; KeySet *this_keyset = NULL; char bmp = 0, bitmap[MAX_FIELDS]; /* Max. len of the bitmap */ Int2 bitmaplen; /* len of the bitmap in bytes */ Int2 bitmap_pos; Int2 bitcnt; Int4 len; char *buffer; int ci_num_fields = QR_NumResultCols(self); /* speed up access */ int num_fields = self->num_fields; /* speed up access */ SocketClass *sock = CC_get_socket(QR_get_conn(self)); ColumnInfoClass *flds; int effective_cols; char tidoidbuf[32]; ConnInfo *ci = &(QR_get_conn(self)->connInfo); /* set the current row to read the fields into */ effective_cols = QR_NumPublicResultCols(self); this_tuplefield = self->backend_tuples + (self->num_cached_rows * num_fields); if (QR_haskeyset(self)) { /* this_keyset = self->keyset + self->cursTuple + 1; */ this_keyset = self->keyset + self->num_cached_keys; this_keyset->status = 0; } /* * At first the server sends a bitmap that indicates which database * fields are null */ if (PROTOCOL_74(ci)) { int numf = SOCK_get_int(sock, sizeof(Int2)); if (effective_cols > 0) {inolog("%dth record in cache numf=%d\n", self->num_cached_rows, numf);} else {inolog("%dth record in key numf=%d\n", self->num_cached_keys, numf);} } else { bitmaplen = (Int2) ci_num_fields / BYTELEN; if ((ci_num_fields % BYTELEN) > 0) bitmaplen++; SOCK_get_n_char(sock, bitmap, bitmaplen); bitmap_pos = 0; bitcnt = 0; bmp = bitmap[bitmap_pos]; } flds = QR_get_fields(self); for (field_lf = 0; field_lf < ci_num_fields; field_lf++) { BOOL isnull = FALSE; if (!PROTOCOL_74(ci)) { isnull = ((bmp & 0200) == 0); /* move to next bit in the bitmap */ bitcnt++; if (BYTELEN == bitcnt) { bitmap_pos++; bmp = bitmap[bitmap_pos]; bitcnt = 0; } else bmp <<= 1; if (!isnull) { /* get the length of the field (four bytes) */ len = SOCK_get_int(sock, sizeof(Int4)); /* * In the old protocol version, the length * field of an AsciiRow message includes the * 4-byte length field itself, while the * length field in the BinaryRow does not. */ if (!binary) len -= sizeof(Int4); } } else { /* get the length of the field (four bytes) */ len = SOCK_get_int(sock, sizeof(Int4)); /* -1 means NULL */ if (len < 0) isnull = TRUE; } if (isnull) { this_tuplefield[field_lf].len = 0; this_tuplefield[field_lf].value = 0; continue; } else { if (field_lf >= effective_cols) buffer = tidoidbuf; else { QR_MALLOC_return_with_error(buffer, char, len + 1, self, "Out of memory in allocating item buffer.", FALSE); } SOCK_get_n_char(sock, buffer, len); buffer[len] = '\0'; mylog("qresult: len=%d, buffer='%s'\n", len, buffer); if (field_lf >= effective_cols) { if (field_lf == effective_cols) sscanf(buffer, "(%u,%hu)", &this_keyset->blocknum, &this_keyset->offset); else this_keyset->oid = strtoul(buffer, NULL, 10); } else { this_tuplefield[field_lf].len = len; this_tuplefield[field_lf].value = buffer; /* * This can be used to set the longest length of the column * for any row in the tuple cache. It would not be accurate * for varchar and text fields to use this since a tuple cache * is only 100 rows. Bpchar can be handled since the strlen of * all rows is fixed, assuming there are not 100 nulls in a * row! */ if (flds && flds->coli_array && CI_get_display_size(flds, field_lf) < len) CI_get_display_size(flds, field_lf) = len; } } } self->cursTuple++; return TRUE; } psqlodbc-09.03.0300/results.c000644 001752 000000 00000353734 12335653444 016064 0ustar00saitowheel000000 000000 /* * Module: results.c * * Description: This module contains functions related to * retrieving result information through the ODBC API. * * Classes: n/a * * API functions: SQLRowCount, SQLNumResultCols, SQLDescribeCol, * SQLColAttributes, SQLGetData, SQLFetch, SQLExtendedFetch, * SQLMoreResults, SQLSetPos, SQLSetScrollOptions(NI), * SQLSetCursorName, SQLGetCursorName * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "psqlodbc.h" #include #include "misc.h" #include "dlg_specific.h" #include "environ.h" #include "connection.h" #include "statement.h" #include "bind.h" #include "qresult.h" #include "convert.h" #include "pgtypes.h" #include #include #include "pgapifunc.h" /* Helper macro */ #define getEffectiveOid(conn, fi) pg_true_type((conn), (fi)->columntype, FI_type(fi)) #define NULL_IF_NULL(a) ((a) ? ((const char *)(a)) : "(null)") RETCODE SQL_API PGAPI_RowCount(HSTMT hstmt, SQLLEN FAR * pcrow) { CSTR func = "PGAPI_RowCount"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; mylog("%s: entering...\n", func); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } if (stmt->proc_return > 0) { if (pcrow) { *pcrow = 0; inolog("returning RowCount=%d\n", *pcrow); } return SQL_SUCCESS; } res = SC_get_Curres(stmt); if (res && pcrow) { if (stmt->status != STMT_FINISHED) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Can't get row count while statement is still executing.", func); return SQL_ERROR; } if (res->recent_processed_row_count >= 0) { *pcrow = res->recent_processed_row_count; mylog("**** %s: THE ROWS: *pcrow = %d\n", func, *pcrow); return SQL_SUCCESS; } else if (QR_NumResultCols(res) > 0) { *pcrow = QR_get_cursor(res) ? -1 : QR_get_num_total_tuples(res) - res->dl_count; mylog("RowCount=%d\n", *pcrow); return SQL_SUCCESS; } } *pcrow = -1; return SQL_SUCCESS; } static BOOL SC_pre_execute_ok(StatementClass *stmt, BOOL build_fi, int col_idx, const char *func) { Int2 num_fields = SC_pre_execute(stmt); QResultClass *result = SC_get_Curres(stmt); BOOL exec_ok = TRUE; mylog("%s: result = %p, status = %d, numcols = %d\n", func, result, stmt->status, result != NULL ? QR_NumResultCols(result) : -1); /****if ((!result) || ((stmt->status != STMT_FINISHED) && (stmt->status != STMT_PREMATURE))) ****/ if (!QR_command_maybe_successful(result) || num_fields < 0) { /* no query has been executed on this statement */ SC_set_error(stmt, STMT_EXEC_ERROR, "No query has been executed with that handle", func); exec_ok = FALSE; } else if (col_idx >= 0 && col_idx < num_fields) { OID reloid = QR_get_relid(result, col_idx); IRDFields *irdflds = SC_get_IRDF(stmt); FIELD_INFO *fi; TABLE_INFO *ti = NULL; inolog("build_fi=%d reloid=%u\n", build_fi, reloid); if (build_fi && 0 != QR_get_attid(result, col_idx)) getCOLIfromTI(func, NULL, stmt, reloid, &ti); inolog("nfields=%d\n", irdflds->nfields); if (irdflds->fi && col_idx < (int) irdflds->nfields) { fi = irdflds->fi[col_idx]; if (fi) { if (ti) { if (NULL == fi->ti) fi->ti = ti; if (!FI_is_applicable(fi) && 0 != (ti->flags & TI_COLATTRIBUTE)) fi->flag |= FIELD_COL_ATTRIBUTE; } fi->basetype = QR_get_field_type(result, col_idx); if (0 == fi->columntype) fi->columntype = fi->basetype; } } } return exec_ok; } /* * This returns the number of columns associated with the database * attached to "hstmt". */ RETCODE SQL_API PGAPI_NumResultCols(HSTMT hstmt, SQLSMALLINT FAR * pccol) { CSTR func = "PGAPI_NumResultCols"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *result; char parse_ok; RETCODE ret = SQL_SUCCESS; mylog("%s: entering...\n", func); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } SC_clear_error(stmt); #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(stmt); */ if (stmt->proc_return > 0) { *pccol = 0; goto cleanup; } parse_ok = FALSE; if (!stmt->catalog_result && SC_is_parse_forced(stmt) && SC_can_parse_statement(stmt)) { if (SC_parsed_status(stmt) == STMT_PARSE_NONE) { mylog("%s: calling parse_statement on stmt=%p\n", func, stmt); parse_statement(stmt, FALSE); } if (SC_parsed_status(stmt) != STMT_PARSE_FATAL) { parse_ok = TRUE; *pccol = SC_get_IRDF(stmt)->nfields; mylog("PARSE: %s: *pccol = %d\n", func, *pccol); } } if (!parse_ok) { if (!SC_pre_execute_ok(stmt, FALSE, -1, func)) { ret = SQL_ERROR; goto cleanup; } result = SC_get_Curres(stmt); *pccol = QR_NumPublicResultCols(result); } cleanup: #undef return if (stmt->internal) ret = DiscardStatementSvp(stmt, ret, FALSE); return ret; } /* * Return information about the database column the user wants * information about. */ RETCODE SQL_API PGAPI_DescribeCol(HSTMT hstmt, SQLUSMALLINT icol, SQLCHAR FAR * szColName, SQLSMALLINT cbColNameMax, SQLSMALLINT FAR * pcbColName, SQLSMALLINT FAR * pfSqlType, SQLULEN FAR * pcbColDef, SQLSMALLINT FAR * pibScale, SQLSMALLINT FAR * pfNullable) { CSTR func = "PGAPI_DescribeCol"; /* gets all the information about a specific column */ StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; IRDFields *irdflds; QResultClass *res = NULL; char *col_name = NULL; OID fieldtype = 0; SQLLEN column_size = 0; SQLINTEGER decimal_digits = 0; ConnInfo *ci; FIELD_INFO *fi; char buf[255]; int len = 0; RETCODE result = SQL_SUCCESS; mylog("%s: entering.%d..\n", func, icol); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } conn = SC_get_conn(stmt); ci = &(conn->connInfo); SC_clear_error(stmt); #define return DONT_CALL_RETURN_FROM_HERE??? irdflds = SC_get_IRDF(stmt); #if (ODBCVER >= 0x0300) if (0 == icol) /* bookmark column */ { SQLSMALLINT fType = stmt->options.use_bookmarks == SQL_UB_VARIABLE ? SQL_BINARY : SQL_INTEGER; inolog("answering bookmark info\n"); if (szColName && cbColNameMax > 0) *szColName = '\0'; if (pcbColName) *pcbColName = 0; if (pfSqlType) *pfSqlType = fType; if (pcbColDef) *pcbColDef = 10; if (pibScale) *pibScale = 0; if (pfNullable) *pfNullable = SQL_NO_NULLS; result = SQL_SUCCESS; goto cleanup; } #endif /* ODBCVER */ /* * Dont check for bookmark column. This is the responsibility of the * driver manager. */ icol--; /* use zero based column numbers */ fi = NULL; if (icol < irdflds->nfields && irdflds->fi) fi = irdflds->fi[icol]; if (!FI_is_applicable(fi) && !stmt->catalog_result && SC_is_parse_forced(stmt) && SC_can_parse_statement(stmt)) { if (SC_parsed_status(stmt) == STMT_PARSE_NONE) { mylog("%s: calling parse_statement on stmt=%p\n", func, stmt); parse_statement(stmt, FALSE); } mylog("PARSE: DescribeCol: icol=%d, stmt=%p, stmt->nfld=%d, stmt->fi=%p\n", icol, stmt, irdflds->nfields, irdflds->fi); if (SC_parsed_status(stmt) != STMT_PARSE_FATAL && irdflds->fi) { if (icol < irdflds->nfields) fi = irdflds->fi[icol]; else { SC_set_error(stmt, STMT_INVALID_COLUMN_NUMBER_ERROR, "Invalid column number in DescribeCol.", func); result = SQL_ERROR; goto cleanup; } mylog("DescribeCol: getting info for icol=%d\n", icol); } } if (!FI_is_applicable(fi)) { /* * If couldn't parse it OR the field being described was not parsed * (i.e., because it was a function or expression, etc, then do it the * old fashioned way. */ BOOL build_fi = PROTOCOL_74(ci) && (NULL != pfNullable || NULL != pfSqlType); fi = NULL; if (!SC_pre_execute_ok(stmt, build_fi, icol, func)) { result = SQL_ERROR; goto cleanup; } res = SC_get_Curres(stmt); if (icol >= QR_NumPublicResultCols(res)) { SC_set_error(stmt, STMT_INVALID_COLUMN_NUMBER_ERROR, "Invalid column number in DescribeCol.", func); snprintf(buf, sizeof(buf), "Col#=%d, #Cols=%d,%d keys=%d", icol, QR_NumResultCols(res), QR_NumPublicResultCols(res), res->num_key_fields); SC_log_error(func, buf, stmt); result = SQL_ERROR; goto cleanup; } if (icol < irdflds->nfields && irdflds->fi) fi = irdflds->fi[icol]; } if (FI_is_applicable(fi)) { fieldtype = getEffectiveOid(conn, fi); if (NAME_IS_VALID(fi->column_alias)) col_name = GET_NAME(fi->column_alias); else col_name = GET_NAME(fi->column_name); column_size = fi->column_size; decimal_digits = fi->decimal_digits; mylog("PARSE: fieldtype=%d, col_name='%s', column_size=%d\n", fieldtype, NULL_IF_NULL(col_name), column_size); } else { col_name = QR_get_fieldname(res, icol); fieldtype = QR_get_field_type(res, icol); /* atoi(ci->unknown_sizes) */ column_size = pgtype_column_size(stmt, fieldtype, icol, ci->drivers.unknown_sizes); decimal_digits = pgtype_decimal_digits(stmt, fieldtype, icol); } mylog("describeCol: col %d fieldname = '%s'\n", icol, NULL_IF_NULL(col_name)); mylog("describeCol: col %d fieldtype = %d\n", icol, fieldtype); mylog("describeCol: col %d column_size = %d\n", icol, column_size); result = SQL_SUCCESS; /* * COLUMN NAME */ len = col_name ? (int) strlen(col_name) : 0; if (pcbColName) *pcbColName = len; if (szColName && cbColNameMax > 0) { if (NULL != col_name) strncpy_null((char *) szColName, col_name, cbColNameMax); else szColName[0] = '\0'; if (len >= cbColNameMax) { result = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_TRUNCATED, "The buffer was too small for the colName.", func); } } /* * CONCISE(SQL) TYPE */ if (pfSqlType) { *pfSqlType = pgtype_to_concise_type(stmt, fieldtype, icol); mylog("describeCol: col %d *pfSqlType = %d\n", icol, *pfSqlType); } /* * COLUMN SIZE(PRECISION in 2.x) */ if (pcbColDef) { if (column_size < 0) column_size = 0; /* "I dont know" */ *pcbColDef = column_size; mylog("describeCol: col %d *pcbColDef = %d\n", icol, *pcbColDef); } /* * DECIMAL DIGITS(SCALE in 2.x) */ if (pibScale) { if (decimal_digits < 0) decimal_digits = 0; *pibScale = (SQLSMALLINT) decimal_digits; mylog("describeCol: col %d *pibScale = %d\n", icol, *pibScale); } /* * NULLABILITY */ if (pfNullable) { if (SC_has_outer_join(stmt)) *pfNullable = TRUE; else *pfNullable = fi ? fi->nullable : pgtype_nullable(conn, fieldtype); mylog("describeCol: col %d *pfNullable = %d\n", icol, *pfNullable); } cleanup: #undef return if (stmt->internal) result = DiscardStatementSvp(stmt, result, FALSE); return result; } /* Returns result column descriptor information for a result set. */ RETCODE SQL_API PGAPI_ColAttributes(HSTMT hstmt, SQLUSMALLINT icol, SQLUSMALLINT fDescType, PTR rgbDesc, SQLSMALLINT cbDescMax, SQLSMALLINT FAR * pcbDesc, SQLLEN FAR * pfDesc) { CSTR func = "PGAPI_ColAttributes"; StatementClass *stmt = (StatementClass *) hstmt; IRDFields *irdflds; OID field_type = 0; Int2 col_idx; ConnectionClass *conn; ConnInfo *ci; int column_size, unknown_sizes; int cols = 0; RETCODE result; const char *p = NULL; SQLLEN value = 0; const FIELD_INFO *fi = NULL; const TABLE_INFO *ti = NULL; QResultClass *res; BOOL stmt_updatable; mylog("%s: entering..col=%d %d len=%d.\n", func, icol, fDescType, cbDescMax); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } stmt_updatable = SC_is_updatable(stmt) /* The following doesn't seem appropriate for client side cursors && stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY */ ; if (pcbDesc) *pcbDesc = 0; irdflds = SC_get_IRDF(stmt); conn = SC_get_conn(stmt); ci = &(conn->connInfo); /* * Dont check for bookmark column. This is the responsibility of the * driver manager. For certain types of arguments, the column number * is ignored anyway, so it may be 0. */ res = SC_get_Curres(stmt); #if (ODBCVER >= 0x0300) if (0 == icol && SQL_DESC_COUNT != fDescType) /* bookmark column */ { inolog("answering bookmark info\n"); switch (fDescType) { case SQL_DESC_OCTET_LENGTH: if (pfDesc) *pfDesc = 4; break; case SQL_DESC_TYPE: if (pfDesc) *pfDesc = stmt->options.use_bookmarks == SQL_UB_VARIABLE ? SQL_BINARY : SQL_INTEGER; break; } return SQL_SUCCESS; } #endif /* ODBCVER */ col_idx = icol - 1; /* atoi(ci->unknown_sizes); */ unknown_sizes = ci->drivers.unknown_sizes; /* not appropriate for SQLColAttributes() */ if (stmt->catalog_result) unknown_sizes = UNKNOWNS_AS_CATALOG; else if (unknown_sizes == UNKNOWNS_AS_DONTKNOW) unknown_sizes = UNKNOWNS_AS_MAX; if (!stmt->catalog_result && SC_is_parse_forced(stmt) && SC_can_parse_statement(stmt)) { if (SC_parsed_status(stmt) == STMT_PARSE_NONE) { mylog("%s: calling parse_statement\n", func); parse_statement(stmt, FALSE); } cols = irdflds->nfields; /* * Column Count is a special case. The Column number is ignored * in this case. */ #if (ODBCVER >= 0x0300) if (fDescType == SQL_DESC_COUNT) #else if (fDescType == SQL_COLUMN_COUNT) #endif /* ODBCVER */ { if (pfDesc) *pfDesc = cols; return SQL_SUCCESS; } if (SC_parsed_status(stmt) != STMT_PARSE_FATAL && irdflds->fi) { if (col_idx >= cols) { SC_set_error(stmt, STMT_INVALID_COLUMN_NUMBER_ERROR, "Invalid column number in ColAttributes.", func); return SQL_ERROR; } } } if (col_idx < irdflds->nfields && irdflds->fi) fi = irdflds->fi[col_idx]; if (FI_is_applicable(fi)) field_type = getEffectiveOid(conn, fi); else { BOOL build_fi = FALSE; fi = NULL; if (PROTOCOL_74(ci)) { switch (fDescType) { case SQL_COLUMN_OWNER_NAME: case SQL_COLUMN_TABLE_NAME: case SQL_COLUMN_TYPE: case SQL_COLUMN_TYPE_NAME: case SQL_COLUMN_AUTO_INCREMENT: #if (ODBCVER >= 0x0300) case SQL_DESC_NULLABLE: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_BASE_COLUMN_NAME: #else case SQL_COLUMN_NULLABLE: #endif /* ODBCVER */ case SQL_COLUMN_UPDATABLE: case 1212: /* SQL_CA_SS_COLUMN_KEY ? */ build_fi = TRUE; break; } } if (!SC_pre_execute_ok(stmt, build_fi, col_idx, func)) return SQL_ERROR; res = SC_get_Curres(stmt); cols = QR_NumPublicResultCols(res); /* * Column Count is a special case. The Column number is ignored * in this case. */ #if (ODBCVER >= 0x0300) if (fDescType == SQL_DESC_COUNT) #else if (fDescType == SQL_COLUMN_COUNT) #endif /* ODBCVER */ { if (pfDesc) *pfDesc = cols; return SQL_SUCCESS; } if (col_idx >= cols) { SC_set_error(stmt, STMT_INVALID_COLUMN_NUMBER_ERROR, "Invalid column number in ColAttributes.", func); return SQL_ERROR; } field_type = QR_get_field_type(res, col_idx); if (col_idx < irdflds->nfields && irdflds->fi) fi = irdflds->fi[col_idx]; } if (FI_is_applicable(fi)) { ti = fi->ti; field_type = getEffectiveOid(conn, fi); } mylog("colAttr: col %d field_type=%d fi,ti=%p,%p\n", col_idx, field_type, fi, ti); column_size = (fi != NULL && fi->column_size > 0) ? fi->column_size : pgtype_column_size(stmt, field_type, col_idx, unknown_sizes); switch (fDescType) { case SQL_COLUMN_AUTO_INCREMENT: /* == SQL_DESC_AUTO_UNIQUE_VALUE */ if (fi && fi->auto_increment) value = TRUE; else value = pgtype_auto_increment(conn, field_type); if (value == -1) /* non-numeric becomes FALSE (ODBC Doc) */ value = FALSE; mylog("AUTO_INCREMENT=%d\n", value); break; case SQL_COLUMN_CASE_SENSITIVE: /* == SQL_DESC_CASE_SENSITIVE */ value = pgtype_case_sensitive(conn, field_type); break; /* * This special case is handled above. * * case SQL_COLUMN_COUNT: */ case SQL_COLUMN_DISPLAY_SIZE: /* == SQL_DESC_DISPLAY_SIZE */ value = (fi && 0 != fi->display_size) ? fi->display_size : pgtype_display_size(stmt, field_type, col_idx, unknown_sizes); mylog("%s: col %d, display_size= %d\n", func, col_idx, value); break; case SQL_COLUMN_LABEL: /* == SQL_DESC_LABEL */ if (fi && (NAME_IS_VALID(fi->column_alias))) { p = GET_NAME(fi->column_alias); mylog("%s: COLUMN_LABEL = '%s'\n", func, p); break; } /* otherwise same as column name -- FALL THROUGH!!! */ #if (ODBCVER >= 0x0300) case SQL_DESC_NAME: #else case SQL_COLUMN_NAME: #endif /* ODBCVER */ inolog("fi=%p", fi); if (fi) inolog(" (%s,%s)", PRINT_NAME(fi->column_alias), PRINT_NAME(fi->column_name)); p = fi ? (NAME_IS_NULL(fi->column_alias) ? SAFE_NAME(fi->column_name) : GET_NAME(fi->column_alias)) : QR_get_fieldname(res, col_idx); mylog("%s: COLUMN_NAME = '%s'\n", func, p); break; case SQL_COLUMN_LENGTH: value = (fi && fi->length > 0) ? fi->length : pgtype_buffer_length(stmt, field_type, col_idx, unknown_sizes); if (0 > value) /* if (-1 == value) I'm not sure which is right */ value = 0; mylog("%s: col %d, column_length = %d\n", func, col_idx, value); break; case SQL_COLUMN_MONEY: /* == SQL_DESC_FIXED_PREC_SCALE */ value = pgtype_money(conn, field_type); inolog("COLUMN_MONEY=%d\n", value); break; #if (ODBCVER >= 0x0300) case SQL_DESC_NULLABLE: #else case SQL_COLUMN_NULLABLE: #endif /* ODBCVER */ if (SC_has_outer_join(stmt)) value = TRUE; else value = fi ? fi->nullable : pgtype_nullable(conn, field_type); inolog("COLUMN_NULLABLE=%d\n", value); break; case SQL_COLUMN_OWNER_NAME: /* == SQL_DESC_SCHEMA_NAME */ p = ti ? SAFE_NAME(ti->schema_name) : NULL_STRING; mylog("%s: SCHEMA_NAME = '%s'\n", func, p); break; case SQL_COLUMN_PRECISION: /* in 2.x */ value = column_size; if (value < 0) value = 0; mylog("%s: col %d, column_size = %d\n", func, col_idx, value); break; case SQL_COLUMN_QUALIFIER_NAME: /* == SQL_DESC_CATALOG_NAME */ p = ti ? CurrCatString(conn) : NULL_STRING; /* empty string means *not supported* */ break; case SQL_COLUMN_SCALE: /* in 2.x */ value = pgtype_decimal_digits(stmt, field_type, col_idx); inolog("COLUMN_SCALE=%d\n", value); if (value < 0) value = 0; break; case SQL_COLUMN_SEARCHABLE: /* == SQL_DESC_SEARCHABLE */ value = pgtype_searchable(conn, field_type); break; case SQL_COLUMN_TABLE_NAME: /* == SQL_DESC_TABLE_NAME */ p = ti ? SAFE_NAME(ti->table_name) : NULL_STRING; mylog("%s: TABLE_NAME = '%s'\n", func, p); break; case SQL_COLUMN_TYPE: /* == SQL_DESC_CONCISE_TYPE */ value = pgtype_to_concise_type(stmt, field_type, col_idx); mylog("COLUMN_TYPE=%d\n", value); break; case SQL_COLUMN_TYPE_NAME: /* == SQL_DESC_TYPE_NAME */ p = pgtype_to_name(stmt, field_type, col_idx, fi && fi->auto_increment); break; case SQL_COLUMN_UNSIGNED: /* == SQL_DESC_UNSINGED */ value = pgtype_unsigned(conn, field_type); if (value == -1) /* non-numeric becomes TRUE (ODBC Doc) */ value = SQL_TRUE; break; case SQL_COLUMN_UPDATABLE: /* == SQL_DESC_UPDATABLE */ /* * Neither Access or Borland care about this. * * if (field_type == PG_TYPE_OID) pfDesc = SQL_ATTR_READONLY; * else */ if (!stmt_updatable) value = SQL_ATTR_READONLY; else value = fi ? (fi->updatable ? SQL_ATTR_WRITE : SQL_ATTR_READONLY) : (QR_get_attid(res, col_idx) > 0 ? SQL_ATTR_WRITE : (PROTOCOL_74(ci) ? SQL_ATTR_READONLY : SQL_ATTR_READWRITE_UNKNOWN)); if (SQL_ATTR_READONLY != value) { const char *name = fi ? SAFE_NAME(fi->column_name) : QR_get_fieldname(res, col_idx); if (stricmp(name, OID_NAME) == 0 || stricmp(name, "ctid") == 0 || stricmp(name, "xmin") == 0) value = SQL_ATTR_READONLY; else if (conn->ms_jet && fi && fi->auto_increment) value = SQL_ATTR_READONLY; } mylog("%s: UPDATEABLE = %d\n", func, value); break; #if (ODBCVER >= 0x0300) case SQL_DESC_BASE_COLUMN_NAME: p = fi ? SAFE_NAME(fi->column_name) : QR_get_fieldname(res, col_idx); mylog("%s: BASE_COLUMN_NAME = '%s'\n", func, p); break; case SQL_DESC_BASE_TABLE_NAME: /* the same as TABLE_NAME ok ? */ p = ti ? SAFE_NAME(ti->table_name) : NULL_STRING; mylog("%s: BASE_TABLE_NAME = '%s'\n", func, p); break; case SQL_DESC_LENGTH: /* different from SQL_COLUMN_LENGTH */ value = (fi && column_size > 0) ? column_size : pgtype_desclength(stmt, field_type, col_idx, unknown_sizes); if (-1 == value) value = 0; mylog("%s: col %d, desc_length = %d\n", func, col_idx, value); break; case SQL_DESC_OCTET_LENGTH: value = (fi && fi->length > 0) ? fi->length : pgtype_attr_transfer_octet_length(conn, field_type, column_size, unknown_sizes); if (-1 == value) value = 0; mylog("%s: col %d, octet_length = %d\n", func, col_idx, value); break; case SQL_DESC_PRECISION: /* different from SQL_COLUMN_PRECISION */ if (value = FI_precision(fi), value <= 0) value = pgtype_precision(stmt, field_type, col_idx, unknown_sizes); if (value < 0) value = 0; mylog("%s: col %d, desc_precision = %d\n", func, col_idx, value); break; case SQL_DESC_SCALE: /* different from SQL_COLUMN_SCALE */ value = pgtype_scale(stmt, field_type, col_idx); if (value < 0) value = 0; break; case SQL_DESC_LOCAL_TYPE_NAME: p = pgtype_to_name(stmt, field_type, col_idx, fi && fi->auto_increment); break; case SQL_DESC_TYPE: value = pgtype_to_sqldesctype(stmt, field_type, col_idx); break; case SQL_DESC_NUM_PREC_RADIX: value = pgtype_radix(conn, field_type); break; case SQL_DESC_LITERAL_PREFIX: p = pgtype_literal_prefix(conn, field_type); break; case SQL_DESC_LITERAL_SUFFIX: p = pgtype_literal_suffix(conn, field_type); break; case SQL_DESC_UNNAMED: value = (fi && NAME_IS_NULL(fi->column_name) && NAME_IS_NULL(fi->column_alias)) ? SQL_UNNAMED : SQL_NAMED; break; #endif /* ODBCVER */ case 1211: /* SQL_CA_SS_COLUMN_HIDDEN ? */ value = 0; break; case 1212: /* SQL_CA_SS_COLUMN_KEY ? */ if (fi) { if (fi->columnkey < 0) { SC_set_SS_columnkey(stmt); } value = fi->columnkey; mylog("%s:SS_COLUMN_KEY=%d\n", func, value); break; } SC_set_error(stmt, STMT_OPTION_NOT_FOR_THE_DRIVER, "this request may be for MS SQL Server", func); return SQL_ERROR; default: SC_set_error(stmt, STMT_INVALID_OPTION_IDENTIFIER, "ColAttribute for this type not implemented yet", func); return SQL_ERROR; } result = SQL_SUCCESS; if (p) { /* char/binary data */ size_t len = strlen(p); if (rgbDesc) { strncpy_null((char *) rgbDesc, p, (size_t) cbDescMax); if (len >= cbDescMax) { result = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_TRUNCATED, "The buffer was too small for the rgbDesc.", func); } } if (pcbDesc) *pcbDesc = (SQLSMALLINT) len; } else { /* numeric data */ if (pfDesc) *pfDesc = value; } return result; } /* Returns result data for a single column in the current row. */ RETCODE SQL_API PGAPI_GetData(HSTMT hstmt, SQLUSMALLINT icol, SQLSMALLINT fCType, PTR rgbValue, SQLLEN cbValueMax, SQLLEN FAR * pcbValue) { CSTR func = "PGAPI_GetData"; QResultClass *res; StatementClass *stmt = (StatementClass *) hstmt; UInt2 num_cols; SQLLEN num_rows; OID field_type; int atttypmod; void *value = NULL; RETCODE result = SQL_SUCCESS; char get_bookmark = FALSE; SQLSMALLINT target_type; int precision = -1; mylog("%s: enter, stmt=%p icol=%d\n", func, stmt, icol); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } res = SC_get_Curres(stmt); if (STMT_EXECUTING == stmt->status) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Can't get data while statement is still executing.", func); return SQL_ERROR; } if (stmt->status != STMT_FINISHED) { SC_set_error(stmt, STMT_STATUS_ERROR, "GetData can only be called after the successful execution on a SQL statement", func); return SQL_ERROR; } #if (ODBCVER >= 0x0300) if (SQL_ARD_TYPE == fCType) { ARDFields *opts; BindInfoClass *binfo = NULL; opts = SC_get_ARDF(stmt); if (0 == icol) binfo = opts->bookmark; else if (icol <= opts->allocated && opts->bindings) binfo = &opts->bindings[icol - 1]; if (binfo) { target_type = binfo->returntype; mylog("SQL_ARD_TYPE=%d\n", target_type); precision = binfo->precision; } else { SC_set_error(stmt, STMT_STATUS_ERROR, "GetData can't determine the type via ARD", func); return SQL_ERROR; } } else #endif /* ODBCVER */ target_type = fCType; if (icol == 0) { if (stmt->options.use_bookmarks == SQL_UB_OFF) { SC_set_error(stmt, STMT_COLNUM_ERROR, "Attempt to retrieve bookmark with bookmark usage disabled", func); return SQL_ERROR; } /* Make sure it is the bookmark data type */ switch (target_type) { case SQL_C_BOOKMARK: #if (ODBCVER >= 0x0300) case SQL_C_VARBOOKMARK: #endif /* ODBCVER */ break; default: inolog("GetData Column 0 is type %d not of type SQL_C_BOOKMARK", target_type); SC_set_error(stmt, STMT_PROGRAM_TYPE_OUT_OF_RANGE, "Column 0 is not of type SQL_C_BOOKMARK", func); return SQL_ERROR; } get_bookmark = TRUE; } else { /* use zero-based column numbers */ icol--; /* make sure the column number is valid */ num_cols = QR_NumPublicResultCols(res); if (icol >= num_cols) { SC_set_error(stmt, STMT_INVALID_COLUMN_NUMBER_ERROR, "Invalid column number.", func); return SQL_ERROR; } } #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(stmt); */ if (!SC_is_fetchcursor(stmt)) { /* make sure we're positioned on a valid row */ num_rows = QR_get_num_total_tuples(res); if ((stmt->currTuple < 0) || (stmt->currTuple >= num_rows)) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Not positioned on a valid row for GetData.", func); result = SQL_ERROR; goto cleanup; } mylog(" num_rows = %d\n", num_rows); if (!get_bookmark) { SQLLEN curt = GIdx2CacheIdx(stmt->currTuple, stmt, res); value = QR_get_value_backend_row(res, curt, icol); inolog("currT=%d base=%d rowset=%d\n", stmt->currTuple, QR_get_rowstart_in_cache(res), SC_get_rowset_start(stmt)); mylog(" value = '%s'\n", NULL_IF_NULL(value)); } } else { /* it's a SOCKET result (backend data) */ if (stmt->currTuple == -1 || !res || !res->tupleField) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Not positioned on a valid row for GetData.", func); result = SQL_ERROR; goto cleanup; } if (!get_bookmark) { /** value = QR_get_value_backend(res, icol); maybe thiw doesn't work */ SQLLEN curt = GIdx2CacheIdx(stmt->currTuple, stmt, res); value = QR_get_value_backend_row(res, curt, icol); } mylog(" socket: value = '%s'\n", NULL_IF_NULL(value)); } if (get_bookmark) { BOOL contents_get = FALSE; if (rgbValue) { if (SQL_C_BOOKMARK == target_type || 4 <= cbValueMax) { contents_get = TRUE; *((SQLULEN *) rgbValue) = SC_get_bookmark(stmt); } } if (pcbValue) *pcbValue = sizeof(SQLULEN); if (contents_get) result = SQL_SUCCESS; else { SC_set_error(stmt, STMT_TRUNCATED, "The buffer was too small for the GetData.", func); result = SQL_SUCCESS_WITH_INFO; } goto cleanup; } field_type = QR_get_field_type(res, icol); atttypmod = QR_get_atttypmod(res, icol); mylog("**** %s: icol = %d, target_type = %d, field_type = %d, value = '%s'\n", func, icol, target_type, field_type, NULL_IF_NULL(value)); SC_set_current_col(stmt, icol); result = copy_and_convert_field(stmt, field_type, atttypmod, value, target_type, precision, rgbValue, cbValueMax, pcbValue, pcbValue); switch (result) { case COPY_OK: result = SQL_SUCCESS; break; case COPY_UNSUPPORTED_TYPE: SC_set_error(stmt, STMT_RESTRICTED_DATA_TYPE_ERROR, "Received an unsupported type from Postgres.", func); result = SQL_ERROR; break; case COPY_UNSUPPORTED_CONVERSION: SC_set_error(stmt, STMT_RESTRICTED_DATA_TYPE_ERROR, "Couldn't handle the necessary data type conversion.", func); result = SQL_ERROR; break; case COPY_RESULT_TRUNCATED: SC_set_error(stmt, STMT_TRUNCATED, "The buffer was too small for the GetData.", func); result = SQL_SUCCESS_WITH_INFO; break; case COPY_GENERAL_ERROR: /* error msg already filled in */ result = SQL_ERROR; break; case COPY_NO_DATA_FOUND: /* SC_log_error(func, "no data found", stmt); */ result = SQL_NO_DATA_FOUND; break; default: SC_set_error(stmt, STMT_INTERNAL_ERROR, "Unrecognized return value from copy_and_convert_field.", func); result = SQL_ERROR; break; } cleanup: #undef return if (stmt->internal) result = DiscardStatementSvp(stmt, result, FALSE); inolog("%s returning %d\n", __FUNCTION__, result); return result; } /* * Returns data for bound columns in the current row ("hstmt->iCursor"), * advances the cursor. */ RETCODE SQL_API PGAPI_Fetch(HSTMT hstmt) { CSTR func = "PGAPI_Fetch"; StatementClass *stmt = (StatementClass *) hstmt; ARDFields *opts; QResultClass *res; BindInfoClass *bookmark; RETCODE retval = SQL_SUCCESS; mylog("%s: stmt = %p, stmt->result= %p\n", func, stmt, stmt ? SC_get_Curres(stmt) : NULL); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } SC_clear_error(stmt); if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in PGAPI_Fetch.", func); return SQL_ERROR; } /* Not allowed to bind a bookmark column when using SQLFetch. */ opts = SC_get_ARDF(stmt); if ((bookmark = opts->bookmark) && bookmark->buffer) { SC_set_error(stmt, STMT_COLNUM_ERROR, "Not allowed to bind a bookmark column when using PGAPI_Fetch", func); return SQL_ERROR; } if (stmt->status == STMT_EXECUTING) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Can't fetch while statement is still executing.", func); return SQL_ERROR; } if (stmt->status != STMT_FINISHED) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Fetch can only be called after the successful execution on a SQL statement", func); return SQL_ERROR; } if (opts->bindings == NULL) { if (!SC_may_fetch_rows(stmt)) return SQL_NO_DATA_FOUND; /* just to avoid a crash if the user insists on calling this */ /* function even if SQL_ExecDirect has reported an Error */ SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Bindings were not allocated properly.", func); return SQL_ERROR; } #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(stmt); */ if (stmt->rowset_start < 0) SC_set_rowset_start(stmt, 0, TRUE); QR_set_rowset_size(res, 1); /* QR_inc_rowstart_in_cache(res, stmt->last_fetch_count_include_ommitted); */ SC_inc_rowset_start(stmt, stmt->last_fetch_count_include_ommitted); retval = SC_fetch(stmt); #undef return if (stmt->internal) retval = DiscardStatementSvp(stmt, retval, FALSE); return retval; } static RETCODE SQL_API SC_pos_reload_needed(StatementClass *stmt, SQLULEN req_size, UDWORD flag); SQLLEN getNthValid(const QResultClass *res, SQLLEN sta, UWORD orientation, SQLULEN nth, SQLLEN *nearest) { SQLLEN i, num_tuples = QR_get_num_total_tuples(res), nearp; SQLULEN count; KeySet *keyset; if (!QR_once_reached_eof(res)) num_tuples = INT_MAX; /* Note that the parameter nth is 1-based */ inolog("get %dth Valid data from %d to %s [dlt=%d]", nth, sta, orientation == SQL_FETCH_PRIOR ? "backward" : "forward", res->dl_count); if (0 == res->dl_count) { if (SQL_FETCH_PRIOR == orientation) { if (sta + 1 >= (SQLLEN) nth) { *nearest = sta + 1 - nth; return nth; } *nearest = -1; return -(SQLLEN)(sta + 1); } else { nearp = sta - 1 + nth; if (nearp < num_tuples) { *nearest = nearp; return nth; } *nearest = num_tuples; return -(SQLLEN)(num_tuples - sta); } } count = 0; if (QR_get_cursor(res)) { SQLLEN *deleted = res->deleted; *nearest = sta - 1 + nth; if (SQL_FETCH_PRIOR == orientation) { for (i = res->dl_count - 1; i >=0 && *nearest <= deleted[i]; i--) { inolog("deleted[%d]=%d\n", i, deleted[i]); if (sta >= deleted[i]) (*nearest)--; } inolog("nearest=%d\n", *nearest); if (*nearest < 0) { *nearest = -1; count = sta + 1; } else return nth; } else { if (!QR_once_reached_eof(res)) num_tuples = INT_MAX; for (i = 0; i < res->dl_count && *nearest >= deleted[i]; i++) { if (sta <= deleted[i]) (*nearest)++; } if (*nearest >= num_tuples) { *nearest = num_tuples; count = *nearest - sta; } else return nth; } } else if (SQL_FETCH_PRIOR == orientation) { for (i = sta, keyset = res->keyset + sta; i >= 0; i--, keyset--) { if (0 == (keyset->status & (CURS_SELF_DELETING | CURS_SELF_DELETED | CURS_OTHER_DELETED))) { *nearest = i; inolog(" nearest=%d\n", *nearest); if (++count == nth) return count; } } *nearest = -1; } else { for (i = sta, keyset = res->keyset + sta; i < num_tuples; i++, keyset++) { if (0 == (keyset->status & (CURS_SELF_DELETING | CURS_SELF_DELETED | CURS_OTHER_DELETED))) { *nearest = i; inolog(" nearest=%d\n", *nearest); if (++count == nth) return count; } } *nearest = num_tuples; } inolog(" nearest not found\n"); return -(SQLLEN)count; } static void move_cursor_position_if_needed(StatementClass *self, QResultClass *res) { SQLLEN move_offset; /* * The move direction must be initialized to is_not_moving or * is_moving_from_the_last in advance. */ if (!QR_get_cursor(res)) { QR_stop_movement(res); /* for safety */ res->move_offset = 0; return; } inolog("BASE=%d numb=%d curr=%d cursT=%d\n", QR_get_rowstart_in_cache(res), res->num_cached_rows, self->currTuple, res->cursTuple); /* retrieve "move from the last" case first */ if (QR_is_moving_from_the_last(res)) { mylog("must MOVE from the last\n"); if (QR_once_reached_eof(res) || self->rowset_start <= QR_get_num_total_tuples(res)) /* this shouldn't happen */ mylog("strange situation in move from the last\n"); if (0 == res->move_offset) res->move_offset = INT_MAX - self->rowset_start; else { inolog("!!move_offset=%d calc=%d\n", res->move_offset, INT_MAX - self->rowset_start); } return; } /* normal case */ res->move_offset = 0; move_offset = self->currTuple - res->cursTuple; if (QR_get_rowstart_in_cache(res) >= 0 && QR_get_rowstart_in_cache(res) <= res->num_cached_rows) { QR_set_next_in_cache(res, (QR_get_rowstart_in_cache(res) < 0) ? 0 : QR_get_rowstart_in_cache(res)); return; } if (0 == move_offset) return; if (move_offset > 0) { QR_set_move_forward(res); res->move_offset = move_offset; } else { QR_set_move_backward(res); res->move_offset = -move_offset; } } /* * return NO_DATA_FOUND macros * save_rowset_start or num_tuples must be defined */ #define EXTFETCH_RETURN_BOF(stmt, res) \ { \ inolog("RETURN_BOF\n"); \ SC_set_rowset_start(stmt, -1, TRUE); \ stmt->currTuple = -1; \ /* move_cursor_position_if_needed(stmt, res); */ \ return SQL_NO_DATA_FOUND; \ } #define EXTFETCH_RETURN_EOF(stmt, res) \ { \ inolog("RETURN_EOF\n"); \ SC_set_rowset_start(stmt, num_tuples, TRUE); \ stmt->currTuple = -1; \ /* move_cursor_position_if_needed(stmt, res); */ \ return SQL_NO_DATA_FOUND; \ } /* This fetchs a block of data (rowset). */ RETCODE SQL_API PGAPI_ExtendedFetch(HSTMT hstmt, SQLUSMALLINT fFetchType, SQLLEN irow, SQLULEN FAR * pcrow, SQLUSMALLINT FAR * rgfRowStatus, SQLLEN bookmark_offset, SQLLEN rowsetSize) { CSTR func = "PGAPI_ExtendedFetch"; StatementClass *stmt = (StatementClass *) hstmt; ARDFields *opts; QResultClass *res; BindInfoClass *bookmark; SQLLEN num_tuples, i, fc_io; SQLLEN save_rowset_size, progress_size; SQLLEN rowset_start; RETCODE result = SQL_SUCCESS; char truncated, error, should_set_rowset_start = FALSE; SQLLEN currp; UWORD pstatus; BOOL currp_is_valid, reached_eof, useCursor; mylog("%s: stmt=%p rowsetSize=%d\n", func, stmt, rowsetSize); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } /* if (SC_is_fetchcursor(stmt) && !stmt->manual_result) */ if (SQL_CURSOR_FORWARD_ONLY == stmt->options.cursor_type) { if (fFetchType != SQL_FETCH_NEXT) { SC_set_error(stmt, STMT_FETCH_OUT_OF_RANGE, "The fetch type for PGAPI_ExtendedFetch isn't allowed with ForwardOnly cursor.", func); return SQL_ERROR; } } SC_clear_error(stmt); if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in PGAPI_ExtendedFetch.", func); return SQL_ERROR; } opts = SC_get_ARDF(stmt); /* * If a bookmark colunmn is bound but bookmark usage is off, then * error */ if ((bookmark = opts->bookmark) && bookmark->buffer && stmt->options.use_bookmarks == SQL_UB_OFF) { SC_set_error(stmt, STMT_COLNUM_ERROR, "Attempt to retrieve bookmark with bookmark usage disabled", func); return SQL_ERROR; } if (stmt->status == STMT_EXECUTING) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Can't fetch while statement is still executing.", func); return SQL_ERROR; } if (stmt->status != STMT_FINISHED) { SC_set_error(stmt, STMT_STATUS_ERROR, "ExtendedFetch can only be called after the successful execution on a SQL statement", func); return SQL_ERROR; } if (opts->bindings == NULL) { if (!SC_may_fetch_rows(stmt)) return SQL_NO_DATA_FOUND; /* just to avoid a crash if the user insists on calling this */ /* function even if SQL_ExecDirect has reported an Error */ SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Bindings were not allocated properly.", func); return SQL_ERROR; } /* Initialize to no rows fetched */ if (rgfRowStatus) for (i = 0; i < rowsetSize; i++) *(rgfRowStatus + i) = SQL_ROW_NOROW; if (pcrow) *pcrow = 0; useCursor = (SC_is_fetchcursor(stmt) && NULL != QR_get_cursor(res)); num_tuples = QR_get_num_total_tuples(res); reached_eof = QR_once_reached_eof(res) && QR_get_cursor(res); if (useCursor && !reached_eof) num_tuples = INT_MAX; inolog("num_tuples=%d\n", num_tuples); /* Save and discard the saved rowset size */ save_rowset_size = stmt->save_rowset_size; stmt->save_rowset_size = -1; rowset_start = SC_get_rowset_start(stmt); QR_stop_movement(res); res->move_offset = 0; switch (fFetchType) { case SQL_FETCH_NEXT: /* * From the odbc spec... If positioned before the start of the * RESULT SET, then this should be equivalent to * SQL_FETCH_FIRST. */ progress_size = (save_rowset_size > 0 ? save_rowset_size : rowsetSize); if (rowset_start < 0) SC_set_rowset_start(stmt, 0, TRUE); else if (res->keyset) { if (stmt->last_fetch_count <= progress_size) { SC_inc_rowset_start(stmt, stmt->last_fetch_count_include_ommitted); progress_size -= stmt->last_fetch_count; } if (progress_size > 0) { if (getNthValid(res, SC_get_rowset_start(stmt), SQL_FETCH_NEXT, progress_size + 1, &rowset_start) <= 0) { EXTFETCH_RETURN_EOF(stmt, res) } else should_set_rowset_start =TRUE; } } else SC_inc_rowset_start(stmt, progress_size); mylog("SQL_FETCH_NEXT: num_tuples=%d, currtuple=%d, rowst=%d\n", num_tuples, stmt->currTuple, rowset_start); break; case SQL_FETCH_PRIOR: mylog("SQL_FETCH_PRIOR: num_tuples=%d, currtuple=%d\n", num_tuples, stmt->currTuple); /* * From the odbc spec... If positioned after the end of the * RESULT SET, then this should be equivalent to * SQL_FETCH_LAST. */ if (SC_get_rowset_start(stmt) <= 0) { EXTFETCH_RETURN_BOF(stmt, res) } if (SC_get_rowset_start(stmt) >= num_tuples) { if (rowsetSize > num_tuples) { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch prior from eof and before the beginning", func); } SC_set_rowset_start(stmt, num_tuples <= 0 ? 0 : (num_tuples - rowsetSize), TRUE); } else if (QR_haskeyset(res)) { if (i = getNthValid(res, SC_get_rowset_start(stmt) - 1, SQL_FETCH_PRIOR, rowsetSize, &rowset_start), i < -1) { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch prior and before the beggining", func); SC_set_rowset_start(stmt, 0, TRUE); } else if (i <= 0) { EXTFETCH_RETURN_BOF(stmt, res) } else should_set_rowset_start = TRUE; } else if (SC_get_rowset_start(stmt) < rowsetSize) { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch prior from eof and before the beggining", func); SC_set_rowset_start(stmt, 0, TRUE); } else SC_inc_rowset_start(stmt, -rowsetSize); break; case SQL_FETCH_FIRST: mylog("SQL_FETCH_FIRST: num_tuples=%d, currtuple=%d\n", num_tuples, stmt->currTuple); SC_set_rowset_start(stmt, 0, TRUE); break; case SQL_FETCH_LAST: mylog("SQL_FETCH_LAST: num_tuples=%d, currtuple=%d\n", num_tuples, stmt->currTuple); if (!reached_eof) { QR_set_move_from_the_last(res); res->move_offset = rowsetSize; } SC_set_rowset_start(stmt, num_tuples <= 0 ? 0 : (num_tuples - rowsetSize), TRUE); break; case SQL_FETCH_ABSOLUTE: mylog("SQL_FETCH_ABSOLUTE: num_tuples=%d, currtuple=%d, irow=%d\n", num_tuples, stmt->currTuple, irow); /* Position before result set, but dont fetch anything */ if (irow == 0) { EXTFETCH_RETURN_BOF(stmt, res) } /* Position before the desired row */ else if (irow > 0) { if (getNthValid(res, 0, SQL_FETCH_NEXT, irow, &rowset_start) <= 0) { EXTFETCH_RETURN_EOF(stmt, res) } else should_set_rowset_start = TRUE; } /* Position with respect to the end of the result set */ else { if (getNthValid(res, num_tuples - 1, SQL_FETCH_PRIOR, -irow, &rowset_start) <= 0) { EXTFETCH_RETURN_BOF(stmt, res) } else { if (!reached_eof) { QR_set_move_from_the_last(res); res->move_offset = -irow; } should_set_rowset_start = TRUE; } } break; case SQL_FETCH_RELATIVE: /* * Refresh the current rowset -- not currently implemented, * but lie anyway */ if (irow == 0) break; if (irow > 0) { if (getNthValid(res, SC_get_rowset_start(stmt) + 1, SQL_FETCH_NEXT, irow, &rowset_start) <= 0) { EXTFETCH_RETURN_EOF(stmt, res) } else should_set_rowset_start = TRUE; } else { if (getNthValid(res, SC_get_rowset_start(stmt) - 1, SQL_FETCH_PRIOR, -irow, &rowset_start) <= 0) { EXTFETCH_RETURN_BOF(stmt, res) } else should_set_rowset_start = TRUE; } break; case SQL_FETCH_BOOKMARK: { SQLLEN bidx = SC_resolve_bookmark(irow); if (bidx < 0) { if (!reached_eof) { QR_set_move_from_the_last(res); res->move_offset = 1 + res->ad_count + bidx; } bidx = num_tuples - 1 - res->ad_count - bidx; } rowset_start = bidx; if (bookmark_offset >= 0) { if (getNthValid(res, bidx, SQL_FETCH_NEXT, bookmark_offset + 1, &rowset_start) <= 0) { EXTFETCH_RETURN_EOF(stmt, res) } else should_set_rowset_start = TRUE; } else if (getNthValid(res, bidx, SQL_FETCH_PRIOR, 1 - bookmark_offset, &rowset_start) <= 0) { stmt->currTuple = -1; EXTFETCH_RETURN_BOF(stmt, res) } else should_set_rowset_start = TRUE; } break; default: SC_set_error(stmt, STMT_FETCH_OUT_OF_RANGE, "Unsupported PGAPI_ExtendedFetch Direction", func); return SQL_ERROR; } /* * CHECK FOR PROPER CURSOR STATE */ /* * Handle Declare Fetch style specially because the end is not really * the end... */ if (!should_set_rowset_start) rowset_start = SC_get_rowset_start(stmt); if (useCursor) { if (reached_eof && rowset_start >= num_tuples) { EXTFETCH_RETURN_EOF(stmt, res) } } else { /* If *new* rowset is after the result_set, return no data found */ if (rowset_start >= num_tuples) { EXTFETCH_RETURN_EOF(stmt, res) } } /* If *new* rowset is prior to result_set, return no data found */ if (rowset_start < 0) { if (rowset_start + rowsetSize <= 0) { EXTFETCH_RETURN_BOF(stmt, res) } else { /* overlap with beginning of result set, * so get first rowset */ SC_set_rowset_start(stmt, 0, TRUE); } should_set_rowset_start = FALSE; } #define return DONT_CALL_RETURN_FROM_HERE??? /* increment the base row in the tuple cache */ QR_set_rowset_size(res, (Int4) rowsetSize); /* set the rowset_start if needed */ if (should_set_rowset_start) SC_set_rowset_start(stmt, rowset_start, TRUE); /* currTuple is always 1 row prior to the rowset start */ stmt->currTuple = RowIdx2GIdx(-1, stmt); if (SC_is_fetchcursor(stmt) || SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type) { move_cursor_position_if_needed(stmt, res); } else QR_set_rowstart_in_cache(res, SC_get_rowset_start(stmt)); if (res->keyset && !QR_get_cursor(res)) { UDWORD flag = 0; SQLLEN rowset_end, req_size; getNthValid(res, rowset_start, SQL_FETCH_NEXT, rowsetSize, &rowset_end); req_size = rowset_end - rowset_start + 1; if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type) { if (fFetchType != SQL_FETCH_NEXT || QR_get_rowstart_in_cache(res) + req_size > QR_get_num_cached_tuples(res)) { flag = 1; } } if (SQL_RD_ON == stmt->options.retrieve_data || flag != 0) { SC_pos_reload_needed(stmt, req_size, flag); } } /* Physical Row advancement occurs for each row fetched below */ mylog("PGAPI_ExtendedFetch: new currTuple = %d\n", stmt->currTuple); truncated = error = FALSE; currp = -1; stmt->bind_row = 0; /* set the binding location */ result = SC_fetch(stmt); if (SQL_ERROR == result) goto cleanup; if (SQL_NO_DATA_FOUND != result && res->keyset) { currp = GIdx2KResIdx(SC_get_rowset_start(stmt), stmt, res); inolog("currp=%d\n", currp); if (currp < 0) { result = SQL_ERROR; mylog("rowset_start=%d but currp=%d\n", SC_get_rowset_start(stmt), currp); SC_set_error(stmt, STMT_INTERNAL_ERROR, "rowset_start not in the keyset", func); goto cleanup; } } for (i = 0, fc_io = 0; SQL_NO_DATA_FOUND != result && SQL_ERROR != result; currp++) { fc_io++; currp_is_valid = FALSE; if (res->keyset) { if (currp < res->num_cached_keys) { currp_is_valid = TRUE; res->keyset[currp].status &= ~CURS_IN_ROWSET; /* Off the flag first */ } else { mylog("Umm current row is out of keyset\n"); break; } } inolog("ExtFetch result=%d\n", result); if (currp_is_valid && SQL_SUCCESS_WITH_INFO == result && 0 == stmt->last_fetch_count) { inolog("just skipping deleted row %d\n", currp); QR_set_rowset_size(res, (Int4) (rowsetSize - i + fc_io)); result = SC_fetch(stmt); if (SQL_ERROR == result) break; continue; } /* Determine Function status */ if (result == SQL_SUCCESS_WITH_INFO) truncated = TRUE; else if (result == SQL_ERROR) error = TRUE; /* Determine Row Status */ if (rgfRowStatus) { if (result == SQL_ERROR) *(rgfRowStatus + i) = SQL_ROW_ERROR; else if (currp_is_valid) { pstatus = (res->keyset[currp].status & KEYSET_INFO_PUBLIC); if (pstatus != 0 && pstatus != SQL_ROW_ADDED) { rgfRowStatus[i] = pstatus; } else rgfRowStatus[i] = SQL_ROW_SUCCESS; /* refresh the status */ /* if (SQL_ROW_DELETED != pstatus) */ res->keyset[currp].status &= (~KEYSET_INFO_PUBLIC); } else *(rgfRowStatus + i) = SQL_ROW_SUCCESS; } if (SQL_ERROR != result && currp_is_valid) res->keyset[currp].status |= CURS_IN_ROWSET; /* This is the unique place where the CURS_IN_ROWSET bit is turned on */ i++; if (i >= rowsetSize) break; stmt->bind_row = (SQLSETPOSIROW) i; /* set the binding location */ result = SC_fetch(stmt); } if (SQL_ERROR == result) goto cleanup; /* Save the fetch count for SQLSetPos */ stmt->last_fetch_count = i; stmt->save_rowset_size = rowsetSize; /* currp = KResIdx2GIdx(currp, stmt, res); stmt->last_fetch_count_include_ommitted = GIdx2RowIdx(currp, stmt); */ stmt->last_fetch_count_include_ommitted = fc_io; /* Reset next binding row */ stmt->bind_row = 0; /* Move the cursor position to the first row in the result set. */ stmt->currTuple = RowIdx2GIdx(0, stmt); /* For declare/fetch, need to reset cursor to beginning of rowset */ if (useCursor) QR_set_position(res, 0); /* Set the number of rows retrieved */ if (pcrow) *pcrow = i; inolog("pcrow=%d\n", i); if (i == 0) /* Only DeclareFetch should wind up here */ result = SQL_NO_DATA_FOUND; else if (error) result = SQL_ERROR; else if (truncated) result = SQL_SUCCESS_WITH_INFO; else if (SC_get_errornumber(stmt) == STMT_POS_BEFORE_RECORDSET) result = SQL_SUCCESS_WITH_INFO; else result = SQL_SUCCESS; cleanup: #undef return if (stmt->internal) result = DiscardStatementSvp(stmt, result, FALSE); return result; } /* * This determines whether there are more results sets available for * the "hstmt". */ /* CC: return SQL_NO_DATA_FOUND since we do not support multiple result sets */ RETCODE SQL_API PGAPI_MoreResults(HSTMT hstmt) { CSTR func = "PGAPI_MoreResults"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; RETCODE ret = SQL_SUCCESS; mylog("%s: entering...\n", func); if (stmt && (res = SC_get_Curres(stmt))) SC_set_Curres(stmt, res->next); if (res = SC_get_Curres(stmt), res) { SQLSMALLINT num_p; if (stmt->multi_statement < 0) PGAPI_NumParams(stmt, &num_p); if (stmt->multi_statement > 0) { const char *cmdstr; SC_initialize_cols_info(stmt, FALSE, TRUE); stmt->statement_type = STMT_TYPE_UNKNOWN; if (cmdstr = QR_get_command(res), NULL != cmdstr) stmt->statement_type = statement_type(cmdstr); stmt->join_info = 0; SC_clear_parse_method(stmt); } stmt->diag_row_count = res->recent_processed_row_count; SC_set_rowset_start(stmt, -1, FALSE); stmt->currTuple = -1; } else { PGAPI_FreeStmt(hstmt, SQL_CLOSE); ret = SQL_NO_DATA_FOUND; } mylog("%s: returning %d\n", func, ret); return ret; } /* * Stuff for updatable cursors. */ static Int2 getNumResultCols(const QResultClass *res) { Int2 res_cols = QR_NumPublicResultCols(res); return res_cols; } static OID getOid(const QResultClass *res, SQLLEN index) { return res->keyset[index].oid; } static void getTid(const QResultClass *res, SQLLEN index, UInt4 *blocknum, UInt2 *offset) { *blocknum = res->keyset[index].blocknum; *offset = res->keyset[index].offset; } static void KeySetSet(const TupleField *tuple, int num_fields, int num_key_fields, KeySet *keyset) { sscanf(tuple[num_fields - num_key_fields].value, "(%u,%hu)", &keyset->blocknum, &keyset->offset); if (num_key_fields > 1) sscanf(tuple[num_fields - 1].value, "%u", &keyset->oid); else keyset->oid = 0; } static void AddRollback(StatementClass *stmt, QResultClass *res, SQLLEN index, const KeySet *keyset, Int4 dmlcode) { ConnectionClass *conn = SC_get_conn(stmt); Rollback *rollback; if (!CC_is_in_trans(conn)) return; inolog("AddRollback %d(%u,%u) %s\n", index, keyset->blocknum, keyset->offset, dmlcode == SQL_ADD ? "ADD" : (dmlcode == SQL_UPDATE ? "UPDATE" : (dmlcode == SQL_DELETE ? "DELETE" : "REFRESH"))); if (!res->rollback) { res->rb_count = 0; res->rb_alloc = 10; rollback = res->rollback = malloc(sizeof(Rollback) * res->rb_alloc); } else { if (res->rb_count >= res->rb_alloc) { res->rb_alloc *= 2; if (rollback = realloc(res->rollback, sizeof(Rollback) * res->rb_alloc), !rollback) { res->rb_alloc = res->rb_count = 0; return; } res->rollback = rollback; } rollback = res->rollback + res->rb_count; } rollback->index = index; rollback->option = dmlcode; rollback->offset = 0; rollback->blocknum = 0; if (keyset) { rollback->blocknum = keyset->blocknum; rollback->offset = keyset->offset; } conn->result_uncommitted = 1; res->rb_count++; } SQLLEN ClearCachedRows(TupleField *tuple, int num_fields, SQLLEN num_rows) { SQLLEN i; for (i = 0; i < num_fields * num_rows; i++, tuple++) { if (tuple->value) { inolog("freeing tuple[%d][%d].value=%p\n", i / num_fields, i % num_fields, tuple->value); free(tuple->value); tuple->value = NULL; } tuple->len = -1; } return i; } SQLLEN ReplaceCachedRows(TupleField *otuple, const TupleField *ituple, int num_fields, SQLLEN num_rows) { SQLLEN i; inolog("ReplaceCachedRows %p num_fields=%d num_rows=%d\n", otuple, num_fields, num_rows); for (i = 0; i < num_fields * num_rows; i++, ituple++, otuple++) { if (otuple->value) { free(otuple->value); otuple->value = NULL; } if (ituple->value) { otuple->value = strdup(ituple->value); inolog("[%d,%d] %s copied\n", i / num_fields, i % num_fields, otuple->value); } otuple->len = ituple->len; } return i; } static int MoveCachedRows(TupleField *otuple, TupleField *ituple, Int2 num_fields, SQLLEN num_rows) { int i; inolog("MoveCachedRows %p num_fields=%d num_rows=%d\n", otuple, num_fields, num_rows); for (i = 0; i < num_fields * num_rows; i++, ituple++, otuple++) { if (otuple->value) { free(otuple->value); otuple->value = NULL; } if (ituple->value) { otuple->value = ituple->value; ituple->value = NULL; inolog("[%d,%d] %s copied\n", i / num_fields, i % num_fields, otuple->value); } otuple->len = ituple->len; ituple->len = -1; } return i; } static BOOL tupleExists(const StatementClass *stmt, const KeySet *keyset) { char selstr[256]; const TABLE_INFO *ti = stmt->ti[0]; QResultClass *res; RETCODE ret = FALSE; snprintf(selstr, sizeof(selstr), "select 1 from %s where ctid = '(%u,%u)'", quote_table(ti->schema_name, ti->table_name), keyset->blocknum, keyset->offset); res = CC_send_query(SC_get_conn(stmt), selstr, NULL, 0, NULL); if (QR_command_maybe_successful(res) && 1 == res->num_cached_rows) ret = TRUE; QR_Destructor(res); return ret; } static BOOL enlargeAdded(QResultClass *res, UInt4 number, const StatementClass *stmt) { UInt4 alloc; int num_fields = res->num_fields; alloc = res->ad_alloc; if (0 == alloc) alloc = number > 10 ? number : 10; else while (alloc < number) { alloc *= 2; } if (alloc <= res->ad_alloc) return TRUE; QR_REALLOC_return_with_error(res->added_keyset, KeySet, sizeof(KeySet) * alloc, res, "enlargeAdded failed", FALSE); if (SQL_CURSOR_KEYSET_DRIVEN != stmt->options.cursor_type) QR_REALLOC_return_with_error(res->added_tuples, TupleField, sizeof(TupleField) * num_fields * alloc, res, "enlargeAdded failed 2", FALSE); res->ad_alloc = alloc; return TRUE; } static void AddAdded(StatementClass *stmt, QResultClass *res, SQLLEN index, const TupleField *tuple_added) { KeySet *added_keyset, *keyset, keys; TupleField *added_tuples = NULL, *tuple; UInt4 ad_count; Int2 num_fields; if (!res) return; num_fields = res->num_fields; inolog("AddAdded index=%d, tuple=%p, num_fields=%d\n", index, tuple_added, num_fields); ad_count = res->ad_count; res->ad_count++; if (QR_get_cursor(res)) index = -(SQLLEN)res->ad_count; if (!tuple_added) return; KeySetSet(tuple_added, num_fields + res->num_key_fields, res->num_key_fields, &keys); keys.status = SQL_ROW_ADDED; if (CC_is_in_trans(SC_get_conn(stmt))) keys.status |= CURS_SELF_ADDING; else keys.status |= CURS_SELF_ADDED; AddRollback(stmt, res, index, &keys, SQL_ADD); if (!QR_get_cursor(res)) return; if (ad_count > 0 && 0 == res->ad_alloc) return; if (!enlargeAdded(res, ad_count + 1, stmt)) return; added_keyset = res->added_keyset; added_tuples = res->added_tuples; keyset = added_keyset + ad_count; *keyset = keys; if (added_tuples) { tuple = added_tuples + num_fields * ad_count; memset(tuple, 0, sizeof(TupleField) * num_fields); ReplaceCachedRows(tuple, tuple_added, num_fields, 1); } } static void RemoveAdded(QResultClass *, SQLLEN); static void RemoveUpdated(QResultClass *, SQLLEN); static void RemoveUpdatedAfterTheKey(QResultClass *, SQLLEN, const KeySet*); static void RemoveDeleted(QResultClass *, SQLLEN); static void RemoveAdded(QResultClass *res, SQLLEN index) { SQLLEN rmidx, mv_count; Int2 num_fields = res->num_fields; KeySet *added_keyset; TupleField *added_tuples; mylog("RemoveAdded index=%d\n", index); if (index < 0) rmidx = -index - 1; else rmidx = index - res->num_total_read; if (rmidx >= res->ad_count) return; added_keyset = res->added_keyset + rmidx; added_tuples = res->added_tuples + num_fields * rmidx; ClearCachedRows(added_tuples, num_fields, 1); mv_count = res->ad_count - rmidx - 1; if (mv_count > 0) { memmove(added_keyset, added_keyset + 1, mv_count * sizeof(KeySet)); memmove(added_tuples, added_tuples + num_fields, mv_count * num_fields * sizeof(TupleField)); } RemoveDeleted(res, index); RemoveUpdated(res, index); res->ad_count--; mylog("RemoveAdded removed=1 count=%d\n", res->ad_count); } static void CommitAdded(QResultClass *res) { KeySet *added_keyset; int i; UWORD status; mylog("CommitAdded res=%p\n", res); if (!res || !res->added_keyset) return; added_keyset = res->added_keyset; for (i = res->ad_count - 1; i >= 0; i--) { status = added_keyset[i].status; if (0 != (status & CURS_SELF_ADDING)) { status |= CURS_SELF_ADDED; status &= ~CURS_SELF_ADDING; } if (0 != (status & CURS_SELF_UPDATING)) { status |= CURS_SELF_UPDATED; status &= ~CURS_SELF_UPDATING; } if (0 != (status & CURS_SELF_DELETING)) { status |= CURS_SELF_DELETED; status &= ~CURS_SELF_DELETING; } if (status != added_keyset[i].status) { inolog("!!Commit Added=%d(%d)\n", QR_get_num_total_read(res) + i, i); added_keyset[i].status = status; } } } int AddDeleted(QResultClass *res, SQLULEN index, KeySet *keyset) { int i; Int2 dl_count, new_alloc; SQLLEN *deleted; KeySet *deleted_keyset; UWORD status; Int2 num_fields = res->num_fields; inolog("AddDeleted %d\n", index); if (!res) return FALSE; dl_count = res->dl_count; res->dl_count++; if (!QR_get_cursor(res)) return TRUE; if (!res->deleted) { dl_count = 0; new_alloc = 10; QR_MALLOC_return_with_error(res->deleted, SQLLEN, sizeof(SQLLEN) * new_alloc, res, "Deleted index malloc error", FALSE); QR_MALLOC_return_with_error(res->deleted_keyset, KeySet, sizeof(KeySet) * new_alloc, res, "Deleted keyset malloc error", FALSE); deleted = res->deleted; deleted_keyset = res->deleted_keyset; res->dl_alloc = new_alloc; } else { if (dl_count >= res->dl_alloc) { new_alloc = res->dl_alloc * 2; res->dl_alloc = 0; QR_REALLOC_return_with_error(res->deleted, SQLLEN, sizeof(SQLLEN) * new_alloc, res, "Deleted index realloc error", FALSE); deleted = res->deleted; QR_REALLOC_return_with_error(res->deleted_keyset, KeySet, sizeof(KeySet) * new_alloc, res, "Deleted KeySet realloc error", FALSE); deleted_keyset = res->deleted_keyset; res->dl_alloc = new_alloc; } /* sort deleted indexes in ascending order */ for (i = 0, deleted = res->deleted, deleted_keyset = res->deleted_keyset; i < dl_count; i++, deleted++, deleted_keyset += num_fields) { if (index < *deleted) break; } memmove(deleted + 1, deleted, sizeof(SQLLEN) * (dl_count - i)); memmove(deleted_keyset + 1, deleted_keyset, sizeof(KeySet) * (dl_count - i)); } *deleted = index; *deleted_keyset = *keyset; status = keyset->status; status &= (~KEYSET_INFO_PUBLIC); status |= SQL_ROW_DELETED; if (CC_is_in_trans(QR_get_conn(res))) { status |= CURS_SELF_DELETING; QR_get_conn(res)->result_uncommitted = 1; } else { status &= ~(CURS_SELF_ADDING | CURS_SELF_UPDATING | CURS_SELF_DELETING); status |= CURS_SELF_DELETED; } deleted_keyset->status = status; res->dl_count = dl_count + 1; return TRUE; } static void RemoveDeleted(QResultClass *res, SQLLEN index) { int i, mv_count, rm_count = 0; SQLLEN pidx, midx; SQLLEN *deleted, num_read = QR_get_num_total_read(res); KeySet *deleted_keyset; mylog("RemoveDeleted index=%d\n", index); if (index < 0) { midx = index; pidx = num_read - index - 1; } else { pidx = index; if (index >= num_read) midx = num_read - index - 1; else midx = index; } for (i = 0; i < res->dl_count; i++) { if (pidx == res->deleted[i] || midx == res->deleted[i]) { mv_count = res->dl_count - i - 1; if (mv_count > 0) { deleted = res->deleted + i; deleted_keyset = res->deleted_keyset + i; memmove(deleted, deleted + 1, mv_count * sizeof(SQLLEN)); memmove(deleted_keyset, deleted_keyset + 1, mv_count * sizeof(KeySet)); } res->dl_count--; rm_count++; } } mylog("RemoveDeleted removed count=%d,%d\n", rm_count, res->dl_count); } static void CommitDeleted(QResultClass *res) { int i; SQLLEN *deleted; KeySet *deleted_keyset; UWORD status; if (!res->deleted) return; for (i = 0, deleted = res->deleted, deleted_keyset = res->deleted_keyset; i < res->dl_count; i++, deleted++, deleted_keyset++) { status = deleted_keyset->status; if (0 != (status & CURS_SELF_ADDING)) { status |= CURS_SELF_ADDED; status &= ~CURS_SELF_ADDING; } if (0 != (status & CURS_SELF_UPDATING)) { status |= CURS_SELF_UPDATED; status &= ~CURS_SELF_UPDATING; } if (0 != (status & CURS_SELF_DELETING)) { status |= CURS_SELF_DELETED; status &= ~CURS_SELF_DELETING; } if (status != deleted_keyset->status) { inolog("!!Commit Deleted=%d(%d)\n", *deleted, i); deleted_keyset->status = status; } } } static BOOL enlargeUpdated(QResultClass *res, Int4 number, const StatementClass *stmt) { Int2 alloc; alloc = res->up_alloc; if (0 == alloc) alloc = number > 10 ? number : 10; else while (alloc < number) { alloc *= 2; } if (alloc <= res->up_alloc) return TRUE; QR_REALLOC_return_with_error(res->updated, SQLLEN, sizeof(SQLLEN) * alloc, res, "enlargeUpdated failed", FALSE); QR_REALLOC_return_with_error(res->updated_keyset, KeySet, sizeof(KeySet) * alloc, res, "enlargeUpdated failed 2", FALSE); if (SQL_CURSOR_KEYSET_DRIVEN != stmt->options.cursor_type) QR_REALLOC_return_with_error(res->updated_tuples, TupleField, sizeof(TupleField) * res->num_fields * alloc, res, "enlargeUpdated failed 3", FALSE); res->up_alloc = alloc; return TRUE; } static void AddUpdated(StatementClass *stmt, SQLLEN index) { QResultClass *res; SQLLEN *updated; KeySet *updated_keyset, *keyset; TupleField *updated_tuples = NULL, *tuple_updated, *tuple; SQLLEN kres_ridx; UInt2 up_count; BOOL is_in_trans; SQLLEN upd_idx, upd_add_idx; Int2 num_fields; int i; UWORD status; inolog("AddUpdated index=%d\n", index); if (!stmt) return; if (res = SC_get_Curres(stmt), !res) return; if (!res->keyset) return; kres_ridx = GIdx2KResIdx(index, stmt, res); if (kres_ridx < 0 || kres_ridx >= res->num_cached_keys) return; keyset = res->keyset + kres_ridx; if (0 != (keyset->status & CURS_SELF_ADDING)) AddRollback(stmt, res, index, res->keyset + kres_ridx, SQL_REFRESH); if (!QR_get_cursor(res)) return; up_count = res->up_count; if (up_count > 0 && 0 == res->up_alloc) return; num_fields = res->num_fields; tuple_updated = res->backend_tuples + kres_ridx * num_fields; if (!tuple_updated) return; upd_idx = -1; upd_add_idx = -1; updated = res->updated; is_in_trans = CC_is_in_trans(SC_get_conn(stmt)); updated_keyset = res->updated_keyset; status = keyset->status; status &= (~KEYSET_INFO_PUBLIC); status |= SQL_ROW_UPDATED; if (is_in_trans) status |= CURS_SELF_UPDATING; else { for (i = up_count - 1; i >= 0; i--) { if (updated[i] == index) break; } if (i >= 0) upd_idx = i; else { SQLLEN num_totals = QR_get_num_total_tuples(res); if (index >= num_totals) upd_add_idx = num_totals - index; } status |= CURS_SELF_UPDATED; status &= ~(CURS_SELF_ADDING | CURS_SELF_UPDATING | CURS_SELF_DELETING); } tuple = NULL; /* update the corresponding add(updat)ed info */ if (upd_add_idx >= 0) { res->added_keyset[upd_add_idx].status = status; if (res->added_tuples) { tuple = res->added_tuples + num_fields * upd_add_idx; ClearCachedRows(tuple, num_fields, 1); } } else if (upd_idx >= 0) { res->updated_keyset[upd_idx].status = status; if (res->updated_tuples) { tuple = res->added_tuples + num_fields * upd_add_idx; ClearCachedRows(tuple, num_fields, 1); } } else { if (!enlargeUpdated(res, res->up_count + 1, stmt)) return; updated = res->updated; updated_keyset = res->updated_keyset; updated_tuples = res->updated_tuples; upd_idx = up_count; updated[up_count] = index; updated_keyset[up_count] = *keyset; updated_keyset[up_count].status = status; if (updated_tuples) { tuple = updated_tuples + num_fields * up_count; memset(tuple, 0, sizeof(TupleField) * num_fields); } res->up_count++; } if (tuple) ReplaceCachedRows(tuple, tuple_updated, num_fields, 1); if (is_in_trans) SC_get_conn(stmt)->result_uncommitted = 1; mylog("up_count=%d\n", res->up_count); } static void RemoveUpdated(QResultClass *res, SQLLEN index) { mylog("RemoveUpdated index=%d\n", index); RemoveUpdatedAfterTheKey(res, index, NULL); } static void RemoveUpdatedAfterTheKey(QResultClass *res, SQLLEN index, const KeySet *keyset) { SQLLEN *updated, num_read = QR_get_num_total_read(res); KeySet *updated_keyset; TupleField *updated_tuples = NULL; SQLLEN pidx, midx, mv_count; int i, num_fields = res->num_fields, rm_count = 0; mylog("RemoveUpdatedAfterTheKey %d,(%u,%u)\n", index, keyset ? keyset->blocknum : 0, keyset ? keyset->offset : 0); if (index < 0) { midx = index; pidx = num_read - index - 1; } else { pidx = index; if (index >= num_read) midx = num_read - index - 1; else midx = index; } for (i = 0; i < res->up_count; i++) { updated = res->updated + i; if (pidx == *updated || midx == *updated) { updated_keyset = res->updated_keyset + i; if (keyset && updated_keyset->blocknum == keyset->blocknum && updated_keyset->offset == keyset->offset) break; updated_tuples = NULL; if (res->updated_tuples) { updated_tuples = res->updated_tuples + i * num_fields; ClearCachedRows(updated_tuples, num_fields, 1); } mv_count = res->up_count - i -1; if (mv_count > 0) { memmove(updated, updated + 1, sizeof(SQLLEN) * mv_count); memmove(updated_keyset, updated_keyset + 1, sizeof(KeySet) * mv_count); if (updated_tuples) memmove(updated_tuples, updated_tuples + num_fields, sizeof(TupleField) * num_fields * mv_count); } res->up_count--; rm_count++; } } mylog("RemoveUpdatedAfter removed count=%d,%d\n", rm_count, res->up_count); } static void CommitUpdated(QResultClass *res) { KeySet *updated_keyset; int i; UWORD status; mylog("CommitUpdated res=%p\n", res); if (!res) return; if (!QR_get_cursor(res)) return; if (res->up_count <= 0) return; if (updated_keyset = res->updated_keyset, !updated_keyset) return; for (i = res->up_count - 1; i >= 0; i--) { status = updated_keyset[i].status; if (0 != (status & CURS_SELF_UPDATING)) { status &= ~CURS_SELF_UPDATING; status |= CURS_SELF_UPDATED; } if (0 != (status & CURS_SELF_ADDING)) { status &= ~CURS_SELF_ADDING; status |= CURS_SELF_ADDED; } if (0 != (status & CURS_SELF_DELETING)) { status &= ~CURS_SELF_DELETING; status |= CURS_SELF_DELETED; } if (status != updated_keyset[i].status) { inolog("!!Commit Updated=%d(%d)\n", res->updated[i], i); updated_keyset[i].status = status; } } } static void DiscardRollback(StatementClass *stmt, QResultClass *res) { int i; SQLLEN index, kres_ridx; UWORD status; Rollback *rollback; KeySet *keyset; BOOL kres_is_valid; inolog("DiscardRollback"); if (QR_get_cursor(res)) { CommitAdded(res); CommitUpdated(res); CommitDeleted(res); return; } if (0 == res->rb_count || NULL == res->rollback) return; rollback = res->rollback; keyset = res->keyset; for (i = 0; i < res->rb_count; i++) { index = rollback[i].index; status = 0; kres_is_valid = FALSE; if (index >= 0) { kres_ridx = GIdx2KResIdx(index, stmt, res); if (kres_ridx >= 0 && kres_ridx < res->num_cached_keys) { kres_is_valid = TRUE; status = keyset[kres_ridx].status; } } if (kres_is_valid) { keyset[kres_ridx].status &= ~(CURS_SELF_DELETING | CURS_SELF_UPDATING | CURS_SELF_ADDING); keyset[kres_ridx].status |= ((status & (CURS_SELF_DELETING | CURS_SELF_UPDATING | CURS_SELF_ADDING)) << 3); } } free(rollback); res->rollback = NULL; res->rb_count = res->rb_alloc = 0; } static QResultClass *positioned_load(StatementClass *stmt, UInt4 flag, const UInt4 *oidint, const char *tid); static void UndoRollback(StatementClass *stmt, QResultClass *res, BOOL partial) { Int4 i, rollbp; SQLLEN index, ridx, kres_ridx; UWORD status; Rollback *rollback; KeySet *keyset, keys, *wkey = NULL; BOOL curs = (NULL != QR_get_cursor(res)), texist, kres_is_valid; if (0 == res->rb_count || NULL == res->rollback) return; rollback = res->rollback; keyset = res->keyset; rollbp = 0; if (partial) { SQLLEN pidx, midx; Int2 doubtp, rollbps; int j; rollbps = rollbp = res->rb_count; for (i = 0, doubtp = 0; i < res->rb_count; i++) { index = rollback[i].index; keys.blocknum = rollback[i].blocknum; keys.offset = rollback[i].offset; texist = tupleExists(stmt, &keys); inolog("texist[%d]=%d", i, texist); if (SQL_ADD == rollback[i].option) { if (texist) doubtp = i + 1; } else if (SQL_REFRESH == rollback[i].option) { if (texist || doubtp == i) doubtp = i + 1; } else { if (texist) break; if (doubtp == i) doubtp = i + 1; } inolog(" doubtp=%d\n", doubtp); } rollbp = i; inolog(" doubtp=%d,rollbp=%d\n", doubtp, rollbp); if (doubtp < 0) doubtp = 0; do { rollbps = rollbp; for (i = doubtp; i < rollbp; i++) { index = rollback[i].index; if (SQL_ADD == rollback[i].option) { inolog("index[%d]=%d\n", i, index); if (index < 0) { midx = index; pidx = res->num_total_read - index - 1; } else { pidx = index; midx = res->num_total_read - index - 1; } inolog("pidx=%d,midx=%d\n", pidx, midx); for (j = rollbp - 1; j > i; j--) { if (rollback[j].index == midx || rollback[j].index == pidx) { if (SQL_DELETE == rollback[j].option) { inolog("delete[%d].index=%d\n", j, rollback[j].index); break; } /*else if (SQL_UPDATE == rollback[j].option) { inolog("update[%d].index=%d\n", j, rollback[j].index); if (IndexExists(stmt, res, rollback + j)) break; }*/ } } if (j <= i) { rollbp = i; break; } } } } while (rollbp < rollbps); } inolog("rollbp=%d\n", rollbp); for (i = res->rb_count - 1; i >= rollbp; i--) { inolog("UndoRollback %d(%d)\n", i, rollback[i].option); index = rollback[i].index; if (curs) { if (SQL_ADD == rollback[i].option) RemoveAdded(res, index); RemoveDeleted(res, index); keys.blocknum = rollback[i].blocknum; keys.offset = rollback[i].offset; RemoveUpdatedAfterTheKey(res, index, &keys); } status = 0; kres_is_valid = FALSE; if (index >= 0) { kres_ridx = GIdx2KResIdx(index, stmt, res); if (kres_ridx >= 0 && kres_ridx < res->num_cached_keys) { kres_is_valid = TRUE; wkey = keyset + kres_ridx; status = wkey->status; } } inolog(" index=%d status=%hx", index, status); if (kres_is_valid) { QResultClass *qres; Int2 num_fields = res->num_fields; ridx = GIdx2CacheIdx(index, stmt, res); if (SQL_ADD == rollback[i].option) { if (ridx >=0 && ridx < res->num_cached_rows) { TupleField *tuple = res->backend_tuples + res->num_fields * ridx; ClearCachedRows(tuple, res->num_fields, 1); res->num_cached_rows--; } res->num_cached_keys--; if (!curs) res->ad_count--; } else if (SQL_REFRESH == rollback[i].option) continue; else { inolog(" (%u, %u)", wkey->blocknum, wkey->offset); wkey->blocknum = rollback[i].blocknum; wkey->offset = rollback[i].offset; inolog("->(%u, %u)\n", wkey->blocknum, wkey->offset); wkey->status &= ~KEYSET_INFO_PUBLIC; if (SQL_DELETE == rollback[i].option) wkey->status &= ~CURS_SELF_DELETING; else if (SQL_UPDATE == rollback[i].option) wkey->status &= ~CURS_SELF_UPDATING; wkey->status |= CURS_NEEDS_REREAD; if (ridx >=0 && ridx < res->num_cached_rows) { char tidval[32]; snprintf(tidval, sizeof(tidval), "(%u,%u)", wkey->blocknum, wkey->offset); qres = positioned_load(stmt, 0, NULL, tidval); if (QR_command_maybe_successful(qres) && QR_get_num_cached_tuples(qres) == 1) { MoveCachedRows(res->backend_tuples + num_fields * ridx, qres->backend_tuples, num_fields, 1); wkey->status &= ~CURS_NEEDS_REREAD; } QR_Destructor(qres); } } } } res->rb_count = rollbp; if (0 == rollbp) { free(rollback); res->rollback = NULL; res->rb_alloc = 0; } } void ProcessRollback(ConnectionClass *conn, BOOL undo, BOOL partial) { int i; StatementClass *stmt; QResultClass *res; for (i = 0; i < conn->num_stmts; i++) { if (stmt = conn->stmts[i], !stmt) continue; for (res = SC_get_Result(stmt); res; res = res->next) { if (undo) UndoRollback(stmt, res, partial); else DiscardRollback(stmt, res); } } } #define LATEST_TUPLE_LOAD 1L #define USE_INSERTED_TID (1L << 1) static QResultClass * positioned_load(StatementClass *stmt, UInt4 flag, const UInt4 *oidint, const char *tidval) { CSTR func = "positioned_load"; CSTR andqual = " and "; QResultClass *qres = NULL; char *selstr, oideqstr[256]; BOOL latest = ((flag & LATEST_TUPLE_LOAD) != 0); size_t len; TABLE_INFO *ti = stmt->ti[0]; const char *bestitem = GET_NAME(ti->bestitem); const char *bestqual = GET_NAME(ti->bestqual); inolog("%s bestitem=%s bestqual=%s\n", func, SAFE_NAME(ti->bestitem), SAFE_NAME(ti->bestqual)); if (!bestitem || !oidint) *oideqstr = '\0'; else { /*snprintf(oideqstr, sizeof(oideqstr), " and \"%s\" = %u", bestitem, oid);*/ strcpy(oideqstr, andqual); snprintf_add(oideqstr, sizeof(oideqstr), bestqual, *oidint); } len = strlen(stmt->load_statement); len += strlen(oideqstr); if (tidval) len += 100; else if ((flag & USE_INSERTED_TID) != 0) len += 50; else len += 20; selstr = malloc(len); if (tidval) { if (latest) { snprintf(selstr, len, "%s where ctid = currtid2('%s', '%s') %s", stmt->load_statement, quote_table(ti->schema_name, ti->table_name), tidval, oideqstr); } else snprintf(selstr, len, "%s where ctid = '%s' %s", stmt->load_statement, tidval, oideqstr); } else if ((flag & USE_INSERTED_TID) != 0) snprintf(selstr, len, "%s where ctid = currtid(0, '(0,0)') %s", stmt->load_statement, oideqstr); else if (bestitem && oidint) { /*snprintf(selstr, len, "%s where \"%s\" = %u", stmt->load_statement, bestitem, *oid);*/ snprintf(selstr, len, "%s where ", stmt->load_statement); snprintf_add(selstr, len, bestqual, *oidint); } else { SC_set_error(stmt,STMT_INTERNAL_ERROR, "can't find the add and updating row because of the lack of oid", func); goto cleanup; } mylog("selstr=%s\n", selstr); qres = CC_send_query(SC_get_conn(stmt), selstr, NULL, 0, stmt); cleanup: free(selstr); return qres; } static RETCODE SC_pos_reload_with_tid(StatementClass *stmt, SQLULEN global_ridx, UInt2 *count, Int4 logKind, const char *tid) { CSTR func = "SC_pos_reload"; int res_cols; UInt2 offset; UInt2 rcnt; SQLLEN res_ridx, kres_ridx; OID oidint; UInt4 blocknum; QResultClass *res, *qres; IRDFields *irdflds = SC_get_IRDF(stmt); RETCODE ret = SQL_ERROR; char tidval[32]; BOOL use_ctid = TRUE, data_in_cache = TRUE, key_in_cache = TRUE; mylog("positioned load fi=%p ti=%p\n", irdflds->fi, stmt->ti); rcnt = 0; if (count) *count = 0; if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_reload.", func); return SQL_ERROR; } res_ridx = GIdx2CacheIdx(global_ridx, stmt, res); if (res_ridx < 0 || res_ridx >= QR_get_num_cached_tuples(res)) { data_in_cache = FALSE; SC_set_error(stmt, STMT_ROW_OUT_OF_RANGE, "the target rows is out of the rowset", func); return SQL_ERROR; } kres_ridx = GIdx2KResIdx(global_ridx, stmt, res); if (kres_ridx < 0 || kres_ridx >= res->num_cached_keys) { key_in_cache = FALSE; SC_set_error(stmt, STMT_ROW_OUT_OF_RANGE, "the target rows is out of the rowset", func); return SQL_ERROR; } else if (0 != (res->keyset[kres_ridx].status & CURS_SELF_ADDING)) { if (NULL == tid) { use_ctid = FALSE; mylog("The tuple is currently being added and can't use ctid\n"); } } if (SC_update_not_ready(stmt)) parse_statement(stmt, TRUE); /* not preferable */ if (!SC_is_updatable(stmt)) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; SC_set_error(stmt, STMT_INVALID_OPTION_IDENTIFIER, "the statement is read-only", func); return SQL_ERROR; } if (!(oidint = getOid(res, kres_ridx))) { if (!strcmp(SAFE_NAME(stmt->ti[0]->bestitem), OID_NAME)) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the row was already deleted ?", func); return SQL_SUCCESS_WITH_INFO; } } getTid(res, kres_ridx, &blocknum, &offset); snprintf(tidval, sizeof(tidval), "(%u, %u)", blocknum, offset); res_cols = getNumResultCols(res); if (tid) qres = positioned_load(stmt, 0, &oidint, tid); else qres = positioned_load(stmt, use_ctid ? LATEST_TUPLE_LOAD : 0, &oidint, use_ctid ? tidval : NULL); if (!QR_command_maybe_successful(qres)) { ret = SQL_ERROR; SC_replace_error_with_res(stmt, STMT_ERROR_TAKEN_FROM_BACKEND, "positioned_load failed", qres, TRUE); } else { TupleField *tuple_old, *tuple_new; ConnectionClass *conn = SC_get_conn(stmt); rcnt = (UInt2) QR_get_num_cached_tuples(qres); tuple_old = res->backend_tuples + res->num_fields * res_ridx; if (0 != logKind && CC_is_in_trans(conn)) AddRollback(stmt, res, global_ridx, res->keyset + kres_ridx, logKind); if (rcnt == 1) { int effective_fields = res_cols; QR_set_position(qres, 0); tuple_new = qres->tupleField; if (res->keyset && key_in_cache) { if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type && strcmp(tuple_new[qres->num_fields - res->num_key_fields].value, tidval)) res->keyset[kres_ridx].status |= SQL_ROW_UPDATED; KeySetSet(tuple_new, qres->num_fields, res->num_key_fields, res->keyset + kres_ridx); } if (data_in_cache) MoveCachedRows(tuple_old, tuple_new, effective_fields, 1); ret = SQL_SUCCESS; } else { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the content was deleted after last fetch", func); ret = SQL_SUCCESS_WITH_INFO; if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN) { res->keyset[kres_ridx].status |= SQL_ROW_DELETED; } } } QR_Destructor(qres); if (count) *count = rcnt; return ret; } RETCODE SC_pos_reload(StatementClass *stmt, SQLULEN global_ridx, UInt2 *count, Int4 logKind) { return SC_pos_reload_with_tid(stmt, global_ridx, count, logKind, NULL); } static const int pre_fetch_count = 32; static SQLLEN LoadFromKeyset(StatementClass *stmt, QResultClass * res, int rows_per_fetch, SQLLEN limitrow) { CSTR func = "LoadFromKeyset"; ConnectionClass *conn = SC_get_conn(stmt); SQLLEN i; int j, rowc, rcnt = 0; BOOL prepare; OID oid; UInt4 blocknum; SQLLEN kres_ridx; UInt2 offset; char *qval = NULL, *sval = NULL; int keys_per_fetch = 10; prepare = PG_VERSION_GE(conn, 7.3); for (i = SC_get_rowset_start(stmt), kres_ridx = GIdx2KResIdx(i, stmt, res), rowc = 0;; i++) { if (i >= limitrow) { if (!rowc) break; if (res->reload_count > 0) { for (j = rowc; j < keys_per_fetch; j++) { if (j) strcpy(sval, ",NULL"); else strcpy(sval, "NULL"); sval = strchr(sval, '\0'); } } rowc = -1; /* end of loop */ } if (rowc < 0 || rowc >= keys_per_fetch) { QResultClass *qres; strcpy(sval, ")"); qres = CC_send_query(conn, qval, NULL, CREATE_KEYSET, stmt); if (QR_command_maybe_successful(qres)) { SQLLEN j, k, l; Int2 m; TupleField *tuple, *tuplew; for (j = 0; j < QR_get_num_total_read(qres); j++) { oid = getOid(qres, j); getTid(qres, j, &blocknum, &offset); for (k = SC_get_rowset_start(stmt); k < limitrow; k++) { if (oid == getOid(res, k)) { l = GIdx2CacheIdx(k, stmt, res); tuple = res->backend_tuples + res->num_fields * l; tuplew = qres->backend_tuples + qres->num_fields * j; for (m = 0; m < res->num_fields; m++, tuple++, tuplew++) { if (tuple->len > 0 && tuple->value) free(tuple->value); tuple->value = tuplew->value; tuple->len = tuplew->len; tuplew->value = NULL; tuplew->len = -1; } res->keyset[k].status &= ~CURS_NEEDS_REREAD; break; } } } } else { SC_set_error(stmt, STMT_EXEC_ERROR, "Data Load Error", func); rcnt = -1; QR_Destructor(qres); break; } QR_Destructor(qres); if (rowc < 0) break; rowc = 0; } if (!rowc) { size_t lodlen = 0; if (!qval) { size_t allen; if (prepare) { if (res->reload_count > 0) keys_per_fetch = res->reload_count; else { char planname[32]; int j; QResultClass *qres; if (rows_per_fetch >= pre_fetch_count * 2) keys_per_fetch = pre_fetch_count; else keys_per_fetch = rows_per_fetch; if (!keys_per_fetch) keys_per_fetch = 2; lodlen = strlen(stmt->load_statement); sprintf(planname, "_KEYSET_%p", res); allen = 8 + strlen(planname) + 3 + 4 * keys_per_fetch + 1 + 1 + 2 + lodlen + 20 + 4 * keys_per_fetch + 1; SC_MALLOC_return_with_error(qval, char, allen, stmt, "Couldn't alloc qval", -1); sprintf(qval, "PREPARE \"%s\"", planname); sval = strchr(qval, '\0'); for (j = 0; j < keys_per_fetch; j++) { if (j == 0) strcpy(sval, "(tid"); else strcpy(sval, ",tid"); sval = strchr(sval, '\0'); } sprintf(sval, ") as %s where ctid in ", stmt->load_statement); sval = strchr(sval, '\0'); for (j = 0; j < keys_per_fetch; j++) { if (j == 0) strcpy(sval, "($1"); else sprintf(sval, ",$%d", j + 1); sval = strchr(sval, '\0'); } strcpy(sval, ")"); qres = CC_send_query(conn, qval, NULL, 0, stmt); if (QR_command_maybe_successful(qres)) { res->reload_count = keys_per_fetch; } else { SC_set_error(stmt, STMT_EXEC_ERROR, "Prepare for Data Load Error", func); rcnt = -1; QR_Destructor(qres); break; } QR_Destructor(qres); } allen = 25 + 23 * keys_per_fetch; } else { keys_per_fetch = pre_fetch_count; lodlen = strlen(stmt->load_statement); allen = lodlen + 20 + 23 * keys_per_fetch; } SC_REALLOC_return_with_error(qval, char, allen, stmt, "Couldn't alloc qval", -1); } if (res->reload_count > 0) { sprintf(qval, "EXECUTE \"_KEYSET_%p\"(", res); sval = qval; } else { memcpy(qval, stmt->load_statement, lodlen); sval = qval + lodlen; sval[0]= '\0'; strcpy(sval, " where ctid in ("); } sval = strchr(sval, '\0'); } if (0 != (res->keyset[kres_ridx].status & CURS_NEEDS_REREAD)) { getTid(res, i, &blocknum, &offset); if (rowc) sprintf(sval, ",'(%u,%u)'", blocknum, offset); else sprintf(sval, "'(%u,%u)'", blocknum, offset); sval = strchr(sval, '\0'); rowc++; rcnt++; } } if (qval) free(qval); return rcnt; } static RETCODE SQL_API SC_pos_reload_needed(StatementClass *stmt, SQLULEN req_size, UDWORD flag) { CSTR func = "SC_pos_reload_needed"; Int4 req_rows_size; SQLLEN i, limitrow; UInt2 qcount; QResultClass *res; RETCODE ret = SQL_ERROR; SQLLEN kres_ridx, rowc; Int4 rows_per_fetch; BOOL create_from_scratch = (0 != flag); mylog("%s\n", func); if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_reload_needed.", func); return SQL_ERROR; } if (SC_update_not_ready(stmt)) parse_statement(stmt, TRUE); /* not preferable */ if (!SC_is_updatable(stmt)) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; SC_set_error(stmt, STMT_INVALID_OPTION_IDENTIFIER, "the statement is read-only", func); return SQL_ERROR; } rows_per_fetch = 0; req_rows_size = QR_get_reqsize(res); if (req_size > req_rows_size) req_rows_size = (UInt4) req_size; if (create_from_scratch) { rows_per_fetch = ((pre_fetch_count - 1) / req_rows_size + 1) * req_rows_size; limitrow = RowIdx2GIdx(rows_per_fetch, stmt); } else { limitrow = RowIdx2GIdx(req_rows_size, stmt); } if (limitrow > res->num_cached_keys) limitrow = res->num_cached_keys; if (create_from_scratch || !res->dataFilled) { ClearCachedRows(res->backend_tuples, res->num_fields, res->num_cached_rows); res->dataFilled = FALSE; } if (!res->dataFilled) { SQLLEN brows = GIdx2RowIdx(limitrow, stmt); if (brows > res->count_backend_allocated) { QR_REALLOC_return_with_error(res->backend_tuples, TupleField, sizeof(TupleField) * res->num_fields * brows, res, "pos_reload_needed failed", SQL_ERROR); res->count_backend_allocated = brows; } if (brows > 0) memset(res->backend_tuples, 0, sizeof(TupleField) * res->num_fields * brows); QR_set_num_cached_rows(res, brows); QR_set_rowstart_in_cache(res, 0); if (SQL_RD_ON != stmt->options.retrieve_data) return SQL_SUCCESS; for (i = SC_get_rowset_start(stmt), kres_ridx = GIdx2KResIdx(i, stmt,res); i < limitrow; i++, kres_ridx++) { if (0 == (res->keyset[kres_ridx].status & (CURS_SELF_DELETING | CURS_SELF_DELETED | CURS_OTHER_DELETED))) res->keyset[kres_ridx].status |= CURS_NEEDS_REREAD; } } if (rowc = LoadFromKeyset(stmt, res, rows_per_fetch, limitrow), rowc < 0) { return SQL_ERROR; } for (i = SC_get_rowset_start(stmt), kres_ridx = GIdx2KResIdx(i, stmt, res); i < limitrow; i++) { if (0 != (res->keyset[kres_ridx].status & CURS_NEEDS_REREAD)) { ret = SC_pos_reload(stmt, i, &qcount, 0); if (SQL_ERROR == ret) { break; } if (SQL_ROW_DELETED == (res->keyset[kres_ridx].status & KEYSET_INFO_PUBLIC)) { res->keyset[kres_ridx].status |= CURS_OTHER_DELETED; } res->keyset[kres_ridx].status &= ~CURS_NEEDS_REREAD; } } res->dataFilled = TRUE; return ret; } static RETCODE SQL_API SC_pos_newload(StatementClass *stmt, const UInt4 *oidint, BOOL tidRef, const char *tidval) { CSTR func = "SC_pos_newload"; int i; QResultClass *res, *qres; RETCODE ret = SQL_ERROR; mylog("positioned new ti=%p\n", stmt->ti); if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_newload.", func); return SQL_ERROR; } if (SC_update_not_ready(stmt)) parse_statement(stmt, TRUE); /* not preferable */ if (!SC_is_updatable(stmt)) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; SC_set_error(stmt, STMT_INVALID_OPTION_IDENTIFIER, "the statement is read-only", func); return SQL_ERROR; } qres = positioned_load(stmt, (tidRef && NULL == tidval) ? USE_INSERTED_TID : 0, oidint, tidRef ? tidval : NULL); if (!qres || !QR_command_maybe_successful(qres)) { SC_set_error(stmt, STMT_ERROR_TAKEN_FROM_BACKEND, "positioned_load in pos_newload failed", func); } else { SQLLEN count = QR_get_num_cached_tuples(qres); QR_set_position(qres, 0); if (count == 1) { int effective_fields = res->num_fields; ssize_t tuple_size; SQLLEN num_total_rows, num_cached_rows, kres_ridx; BOOL appendKey = FALSE, appendData = FALSE; TupleField *tuple_old, *tuple_new; tuple_new = qres->tupleField; num_total_rows = QR_get_num_total_tuples(res); AddAdded(stmt, res, num_total_rows, tuple_new); num_cached_rows = QR_get_num_cached_tuples(res); kres_ridx = GIdx2KResIdx(num_total_rows, stmt, res); if (QR_haskeyset(res)) { if (!QR_get_cursor(res)) { appendKey = TRUE; if (num_total_rows == CacheIdx2GIdx(num_cached_rows, stmt, res)) appendData = TRUE; else { inolog("total %d <> backend %d - base %d + start %d cursor_type=%d\n", num_total_rows, num_cached_rows, QR_get_rowstart_in_cache(res), SC_get_rowset_start(stmt), stmt->options.cursor_type); } } else if (kres_ridx >= 0 && kres_ridx < res->cache_size) { appendKey = TRUE; appendData = TRUE; } } if (appendKey) { if (res->num_cached_keys >= res->count_keyset_allocated) { if (!res->count_keyset_allocated) tuple_size = TUPLE_MALLOC_INC; else tuple_size = res->count_keyset_allocated * 2; QR_REALLOC_return_with_error(res->keyset, KeySet, sizeof(KeySet) * tuple_size, res, "pos_newload failed", SQL_ERROR); res->count_keyset_allocated = tuple_size; } KeySetSet(tuple_new, qres->num_fields, res->num_key_fields, res->keyset + kres_ridx); res->num_cached_keys++; } if (appendData) { inolog("total %d == backend %d - base %d + start %d cursor_type=%d\n", num_total_rows, num_cached_rows, QR_get_rowstart_in_cache(res), SC_get_rowset_start(stmt), stmt->options.cursor_type); if (num_cached_rows >= res->count_backend_allocated) { if (!res->count_backend_allocated) tuple_size = TUPLE_MALLOC_INC; else tuple_size = res->count_backend_allocated * 2; QR_REALLOC_return_with_error(res->backend_tuples, TupleField, res->num_fields * sizeof(TupleField) * tuple_size, res, "SC_pos_newload failed", SQL_ERROR); /* res->backend_tuples = (TupleField *) realloc( res->backend_tuples, res->num_fields * sizeof(TupleField) * tuple_size); if (!res->backend_tuples) { SC_set_error(stmt, QR_set_rstatus(res, PORES_FATAL_ERROR), "Out of memory while reading tuples.", func); QR_Destructor(qres); return SQL_ERROR; } */ res->count_backend_allocated = tuple_size; } tuple_old = res->backend_tuples + res->num_fields * num_cached_rows; for (i = 0; i < effective_fields; i++) { tuple_old[i].len = tuple_new[i].len; tuple_new[i].len = -1; tuple_old[i].value = tuple_new[i].value; tuple_new[i].value = NULL; } res->num_cached_rows++; } ret = SQL_SUCCESS; } else if (0 == count) ret = SQL_NO_DATA_FOUND; else { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the driver cound't identify inserted rows", func); ret = SQL_ERROR; } /* stmt->currTuple = SC_get_rowset_start(stmt) + ridx; */ } QR_Destructor(qres); return ret; } static RETCODE SQL_API irow_update(RETCODE ret, StatementClass *stmt, StatementClass *ustmt, SQLSETPOSIROW irow, SQLULEN global_ridx) { CSTR func = "irow_update"; if (ret != SQL_ERROR) { int updcnt; QResultClass *tres = SC_get_Curres(ustmt); const char *cmdstr = QR_get_command(tres); if (cmdstr && sscanf(cmdstr, "UPDATE %d", &updcnt) == 1) { if (updcnt == 1) { const char *tidval = NULL; if (NULL != tres->backend_tuples && 1 == QR_get_num_cached_tuples(tres)) tidval = QR_get_value_backend_text(tres, 0, 0); ret = SC_pos_reload_with_tid(stmt, global_ridx, (UInt2 *) 0, SQL_UPDATE, tidval); if (SQL_ERROR != ret) AddUpdated(stmt, global_ridx); } else if (updcnt == 0) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the content was changed before updation", func); ret = SQL_ERROR; if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN) SC_pos_reload(stmt, global_ridx, (UInt2 *) 0, 0); } else ret = SQL_ERROR; } else ret = SQL_ERROR; if (ret == SQL_ERROR && SC_get_errornumber(stmt) == 0) { SC_set_error(stmt, STMT_ERROR_TAKEN_FROM_BACKEND, "SetPos update return error", func); } } return ret; } /* SQL_NEED_DATA callback for SC_pos_update */ typedef struct { BOOL updyes; QResultClass *res; StatementClass *stmt, *qstmt; IRDFields *irdflds; SQLSETPOSIROW irow; SQLULEN global_ridx; } pup_cdata; static RETCODE pos_update_callback(RETCODE retcode, void *para) { CSTR func = "pos_update_callback"; RETCODE ret = retcode; pup_cdata *s = (pup_cdata *) para; SQLLEN kres_ridx; if (s->updyes) { mylog("pos_update_callback in\n"); ret = irow_update(ret, s->stmt, s->qstmt, s->irow, s->global_ridx); inolog("irow_update ret=%d,%d\n", ret, SC_get_errornumber(s->qstmt)); if (ret != SQL_SUCCESS) SC_error_copy(s->stmt, s->qstmt, TRUE); PGAPI_FreeStmt(s->qstmt, SQL_DROP); s->qstmt = NULL; } s->updyes = FALSE; kres_ridx = GIdx2KResIdx(s->global_ridx, s->stmt, s->res); if (kres_ridx < 0 || kres_ridx >= s->res->num_cached_keys) { SC_set_error(s->stmt, STMT_ROW_OUT_OF_RANGE, "the target rows is out of the rowset", func); inolog("gidx=%d num_keys=%d kresidx=%d\n", s->global_ridx, s->res->num_cached_keys, kres_ridx); return SQL_ERROR; } if (SQL_SUCCESS == ret && s->res->keyset) { ConnectionClass *conn = SC_get_conn(s->stmt); if (CC_is_in_trans(conn)) { s->res->keyset[kres_ridx].status |= (SQL_ROW_UPDATED | CURS_SELF_UPDATING); } else s->res->keyset[kres_ridx].status |= (SQL_ROW_UPDATED | CURS_SELF_UPDATED); } #if (ODBCVER >= 0x0300) if (s->irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_UPDATED; break; default: s->irdflds->rowStatusArray[s->irow] = ret; } } #endif /* ODBCVER */ return ret; } RETCODE SC_pos_update(StatementClass *stmt, SQLSETPOSIROW irow, SQLULEN global_ridx) { CSTR func = "SC_pos_update"; int i, num_cols, upd_cols; pup_cdata s; ConnectionClass *conn; ARDFields *opts = SC_get_ARDF(stmt); BindInfoClass *bindings = opts->bindings; TABLE_INFO *ti; FIELD_INFO **fi; char updstr[4096]; RETCODE ret; OID oid; UInt4 blocknum; UInt2 pgoffset; SQLLEN offset; SQLLEN *used, kres_ridx; Int4 bind_size = opts->bind_size; s.stmt = stmt; s.irow = irow; s.global_ridx = global_ridx; s.irdflds = SC_get_IRDF(s.stmt); fi = s.irdflds->fi; if (!(s.res = SC_get_Curres(s.stmt))) { SC_set_error(s.stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_update.", func); return SQL_ERROR; } mylog("POS UPDATE %d+%d fi=%p ti=%p\n", s.irow, QR_get_rowstart_in_cache(s.res), fi, s.stmt->ti); if (SC_update_not_ready(stmt)) parse_statement(s.stmt, TRUE); /* not preferable */ if (!SC_is_updatable(s.stmt)) { s.stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; SC_set_error(s.stmt, STMT_INVALID_OPTION_IDENTIFIER, "the statement is read-only", func); return SQL_ERROR; } kres_ridx = GIdx2KResIdx(s.global_ridx, s.stmt, s.res); if (kres_ridx < 0 || kres_ridx >= s.res->num_cached_keys) { SC_set_error(s.stmt, STMT_ROW_OUT_OF_RANGE, "the target rows is out of the rowset", func); return SQL_ERROR; } if (!(oid = getOid(s.res, kres_ridx))) { if (!strcmp(SAFE_NAME(stmt->ti[0]->bestitem), OID_NAME)) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the row was already deleted ?", func); return SQL_ERROR; } } getTid(s.res, kres_ridx, &blocknum, &pgoffset); ti = s.stmt->ti[0]; snprintf(updstr, sizeof(updstr), "update %s set", quote_table(ti->schema_name, ti->table_name)); num_cols = s.irdflds->nfields; offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0; for (i = upd_cols = 0; i < num_cols; i++) { if (used = bindings[i].used, used != NULL) { used = LENADDR_SHIFT(used, offset); if (bind_size > 0) used = LENADDR_SHIFT(used, bind_size * s.irow); else used = LENADDR_SHIFT(used, s.irow * sizeof(SQLLEN)); mylog("%d used=%d,%p\n", i, *used, used); if (*used != SQL_IGNORE && fi[i]->updatable) { if (upd_cols) snprintf_add(updstr, sizeof(updstr), ", \"%s\" = ?", GET_NAME(fi[i]->column_name)); else snprintf_add(updstr, sizeof(updstr), " \"%s\" = ?", GET_NAME(fi[i]->column_name)); upd_cols++; } } else mylog("%d null bind\n", i); } conn = SC_get_conn(s.stmt); s.updyes = FALSE; if (upd_cols > 0) { HSTMT hstmt; int j; ConnInfo *ci = &(conn->connInfo); APDFields *apdopts; IPDFields *ipdopts; OID fieldtype = 0; const char *bestitem = GET_NAME(ti->bestitem); const char *bestqual = GET_NAME(ti->bestqual); snprintf_add(updstr, sizeof(updstr), " where ctid = '(%u, %u)'", blocknum, pgoffset); if (bestitem) { /*sprintf(updstr, "%s and \"%s\" = %u", updstr, bestitem, oid);*/ snprintf_add(updstr, sizeof(updstr), " and "); snprintf_add(updstr, sizeof(updstr), bestqual, oid); } if (PG_VERSION_GE(conn, 8.2)) snprintf_add(updstr, sizeof(updstr), " returning ctid"); mylog("updstr=%s\n", updstr); if (PGAPI_AllocStmt(conn, &hstmt, 0) != SQL_SUCCESS) { SC_set_error(s.stmt, STMT_NO_MEMORY_ERROR, "internal AllocStmt error", func); return SQL_ERROR; } s.qstmt = (StatementClass *) hstmt; apdopts = SC_get_APDF(s.qstmt); apdopts->param_bind_type = opts->bind_size; apdopts->param_offset_ptr = opts->row_offset_ptr; ipdopts = SC_get_IPDF(s.qstmt); SC_set_delegate(s.stmt, s.qstmt); extend_iparameter_bindings(ipdopts, num_cols); for (i = j = 0; i < num_cols; i++) { if (used = bindings[i].used, used != NULL) { used = LENADDR_SHIFT(used, offset); if (bind_size > 0) used = LENADDR_SHIFT(used, bind_size * s.irow); else used = LENADDR_SHIFT(used, s.irow * sizeof(SQLLEN)); mylog("%d used=%d\n", i, *used); if (*used != SQL_IGNORE && fi[i]->updatable) { /* fieldtype = QR_get_field_type(s.res, i); */ fieldtype = getEffectiveOid(conn, fi[i]); PIC_set_pgtype(ipdopts->parameters[j], fieldtype); PGAPI_BindParameter(hstmt, (SQLUSMALLINT) ++j, SQL_PARAM_INPUT, bindings[i].returntype, pgtype_to_concise_type(s.stmt, fieldtype, i), fi[i]->column_size > 0 ? fi[i]->column_size : pgtype_column_size(s.stmt, fieldtype, i, ci->drivers.unknown_sizes), (SQLSMALLINT) fi[i]->decimal_digits, bindings[i].buffer, bindings[i].buflen, bindings[i].used); } } } s.qstmt->exec_start_row = s.qstmt->exec_end_row = s.irow; s.updyes = TRUE; ret = PGAPI_ExecDirect(hstmt, (SQLCHAR *) updstr, SQL_NTS, 0); if (ret == SQL_NEED_DATA) { pup_cdata *cbdata = (pup_cdata *) malloc(sizeof(pup_cdata)); memcpy(cbdata, &s, sizeof(pup_cdata)); if (0 == enqueueNeedDataCallback(s.stmt, pos_update_callback, cbdata)) ret = SQL_ERROR; return ret; } /* else if (ret != SQL_SUCCESS) this is unneccesary SC_error_copy(s.stmt, s.qstmt, TRUE); */ } else { ret = SQL_SUCCESS_WITH_INFO; SC_set_error(s.stmt, STMT_INVALID_CURSOR_STATE_ERROR, "update list null", func); } ret = pos_update_callback(ret, &s); return ret; } RETCODE SC_pos_delete(StatementClass *stmt, SQLSETPOSIROW irow, SQLULEN global_ridx) { CSTR func = "SC_pos_update"; UWORD offset; QResultClass *res, *qres; ConnectionClass *conn = SC_get_conn(stmt); IRDFields *irdflds = SC_get_IRDF(stmt); char dltstr[4096]; RETCODE ret; SQLLEN kres_ridx; OID oid; UInt4 blocknum, qflag; TABLE_INFO *ti; const char *bestitem; const char *bestqual; mylog("POS DELETE ti=%p\n", stmt->ti); if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_delete.", func); return SQL_ERROR; } if (SC_update_not_ready(stmt)) parse_statement(stmt, TRUE); /* not preferable */ if (!SC_is_updatable(stmt)) { stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; SC_set_error(stmt, STMT_INVALID_OPTION_IDENTIFIER, "the statement is read-only", func); return SQL_ERROR; } kres_ridx = GIdx2KResIdx(global_ridx, stmt, res); if (kres_ridx < 0 || kres_ridx >= res->num_cached_keys) { SC_set_error(stmt, STMT_ROW_OUT_OF_RANGE, "the target rows is out of the rowset", func); return SQL_ERROR; } ti = stmt->ti[0]; bestitem = GET_NAME(ti->bestitem); if (!(oid = getOid(res, kres_ridx))) { if (bestitem && !strcmp(bestitem, OID_NAME)) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the row was already deleted ?", func); return SQL_ERROR; } } bestqual = GET_NAME(ti->bestqual); getTid(res, kres_ridx, &blocknum, &offset); /*sprintf(dltstr, "delete from \"%s\" where ctid = '%s' and oid = %s",*/ snprintf(dltstr, sizeof(dltstr), "delete from %s where ctid = '(%u, %u)'", quote_table(ti->schema_name, ti->table_name), blocknum, offset); if (bestitem) { /*sprintf(dltstr, "%s and \"%s\" = %u", dltstr, bestitem, oid);*/ snprintf_add(dltstr, sizeof(dltstr), " and "); snprintf_add(dltstr, sizeof(dltstr), bestqual, oid); } mylog("dltstr=%s\n", dltstr); qflag = 0; if (!stmt->internal && !CC_is_in_trans(conn) && (!CC_does_autocommit(conn))) qflag |= GO_INTO_TRANSACTION; qres = CC_send_query(conn, dltstr, NULL, qflag, stmt); ret = SQL_SUCCESS; if (QR_command_maybe_successful(qres)) { int dltcnt; const char *cmdstr = QR_get_command(qres); if (cmdstr && sscanf(cmdstr, "DELETE %d", &dltcnt) == 1) { if (dltcnt == 1) { RETCODE tret = SC_pos_reload(stmt, global_ridx, (UInt2 *) 0, SQL_DELETE); if (!SQL_SUCCEEDED(tret)) ret = tret; } else if (dltcnt == 0) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the content was changed before deletion", func); ret = SQL_ERROR; if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN) SC_pos_reload(stmt, global_ridx, (UInt2 *) 0, 0); } else ret = SQL_ERROR; } else ret = SQL_ERROR; } else { ret = SQL_ERROR; strcpy(res->sqlstate, qres->sqlstate); res->message = qres->message; qres->message = NULL; } if (ret == SQL_ERROR && SC_get_errornumber(stmt) == 0) { SC_set_error(stmt, STMT_ERROR_TAKEN_FROM_BACKEND, "SetPos delete return error", func); } if (qres) QR_Destructor(qres); if (SQL_SUCCESS == ret && res->keyset) { AddDeleted(res, global_ridx, res->keyset + kres_ridx); res->keyset[kres_ridx].status &= (~KEYSET_INFO_PUBLIC); if (CC_is_in_trans(conn)) { res->keyset[kres_ridx].status |= (SQL_ROW_DELETED | CURS_SELF_DELETING); } else res->keyset[kres_ridx].status |= (SQL_ROW_DELETED | CURS_SELF_DELETED); inolog(".status[%d]=%x\n", global_ridx, res->keyset[kres_ridx].status); } #if (ODBCVER >= 0x0300) if (irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: irdflds->rowStatusArray[irow] = SQL_ROW_DELETED; break; default: irdflds->rowStatusArray[irow] = ret; } } #endif /* ODBCVER */ return ret; } static RETCODE SQL_API irow_insert(RETCODE ret, StatementClass *stmt, StatementClass *istmt, SQLLEN addpos) { CSTR func = "irow_insert"; if (ret != SQL_ERROR) { int addcnt; OID oid, *poid = NULL; ARDFields *opts = SC_get_ARDF(stmt); QResultClass *ires = SC_get_Curres(istmt), *tres; const char *cmdstr; BindInfoClass *bookmark; tres = (ires->next ? ires->next : ires); cmdstr = QR_get_command(tres); if (cmdstr && sscanf(cmdstr, "INSERT %u %d", &oid, &addcnt) == 2 && addcnt == 1) { ConnectionClass *conn = SC_get_conn(stmt); RETCODE qret; if (0 != oid) poid = &oid; qret = SQL_NO_DATA_FOUND; if (PG_VERSION_GE(conn, 7.2)) { const char * tidval = NULL; if (NULL != tres->backend_tuples && 1 == QR_get_num_cached_tuples(tres)) tidval = QR_get_value_backend_text(tres, 0, 0); qret = SC_pos_newload(stmt, poid, TRUE, tidval); if (SQL_ERROR == qret) return qret; } if (SQL_NO_DATA_FOUND == qret) { qret = SC_pos_newload(stmt, poid, FALSE, NULL); if (SQL_ERROR == qret) return qret; } bookmark = opts->bookmark; if (bookmark && bookmark->buffer) { char buf[32]; SQLULEN offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0; snprintf(buf, sizeof(buf), FORMAT_LEN, SC_make_bookmark(addpos)); SC_set_current_col(stmt, -1); copy_and_convert_field(stmt, PG_TYPE_INT4, PG_UNSPECIFIED, buf, bookmark->returntype, 0, bookmark->buffer + offset, bookmark->buflen, LENADDR_SHIFT(bookmark->used, offset), LENADDR_SHIFT(bookmark->used, offset)); } } else { SC_set_error(stmt, STMT_ERROR_TAKEN_FROM_BACKEND, "SetPos insert return error", func); } } return ret; } /* SQL_NEED_DATA callback for SC_pos_add */ typedef struct { BOOL updyes; QResultClass *res; StatementClass *stmt, *qstmt; IRDFields *irdflds; SQLSETPOSIROW irow; } padd_cdata; static RETCODE pos_add_callback(RETCODE retcode, void *para) { RETCODE ret = retcode; padd_cdata *s = (padd_cdata *) para; SQLLEN addpos; if (s->updyes) { SQLSETPOSIROW brow_save; mylog("pos_add_callback in ret=%d\n", ret); brow_save = s->stmt->bind_row; s->stmt->bind_row = s->irow; if (QR_get_cursor(s->res)) addpos = -(SQLLEN)(s->res->ad_count + 1); else addpos = QR_get_num_total_tuples(s->res); ret = irow_insert(ret, s->stmt, s->qstmt, addpos); s->stmt->bind_row = brow_save; } s->updyes = FALSE; SC_setInsertedTable(s->qstmt, ret); if (ret != SQL_SUCCESS) SC_error_copy(s->stmt, s->qstmt, TRUE); PGAPI_FreeStmt((HSTMT) s->qstmt, SQL_DROP); s->qstmt = NULL; if (SQL_SUCCESS == ret && s->res->keyset) { SQLLEN global_ridx = QR_get_num_total_tuples(s->res) - 1; ConnectionClass *conn = SC_get_conn(s->stmt); SQLLEN kres_ridx; UWORD status = SQL_ROW_ADDED; if (CC_is_in_trans(conn)) status |= CURS_SELF_ADDING; else status |= CURS_SELF_ADDED; kres_ridx = GIdx2KResIdx(global_ridx, s->stmt, s->res); if (kres_ridx >= 0 || kres_ridx < s->res->num_cached_keys) { s->res->keyset[kres_ridx].status = status; } } #if (ODBCVER >= 0x0300) if (s->irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_ADDED; break; default: s->irdflds->rowStatusArray[s->irow] = ret; } } #endif /* ODBCVER */ return ret; } RETCODE SC_pos_add(StatementClass *stmt, SQLSETPOSIROW irow) { CSTR func = "SC_pos_add"; int num_cols, add_cols, i; HSTMT hstmt; padd_cdata s; ConnectionClass *conn; ConnInfo *ci; ARDFields *opts = SC_get_ARDF(stmt); APDFields *apdopts; IPDFields *ipdopts; BindInfoClass *bindings = opts->bindings; FIELD_INFO **fi = SC_get_IRDF(stmt)->fi; char addstr[4096]; RETCODE ret; SQLULEN offset; SQLLEN *used; Int4 bind_size = opts->bind_size; OID fieldtype; int func_cs_count = 0; mylog("POS ADD fi=%p ti=%p\n", fi, stmt->ti); s.stmt = stmt; s.irow = irow; if (!(s.res = SC_get_Curres(s.stmt))) { SC_set_error(s.stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_add.", func); return SQL_ERROR; } if (SC_update_not_ready(stmt)) parse_statement(s.stmt, TRUE); /* not preferable */ if (!SC_is_updatable(s.stmt)) { s.stmt->options.scroll_concurrency = SQL_CONCUR_READ_ONLY; SC_set_error(s.stmt, STMT_INVALID_OPTION_IDENTIFIER, "the statement is read-only", func); return SQL_ERROR; } s.irdflds = SC_get_IRDF(s.stmt); num_cols = s.irdflds->nfields; conn = SC_get_conn(s.stmt); snprintf(addstr, sizeof(addstr), "insert into %s (", quote_table(s.stmt->ti[0]->schema_name, s.stmt->ti[0]->table_name)); if (PGAPI_AllocStmt(conn, &hstmt, 0) != SQL_SUCCESS) { SC_set_error(s.stmt, STMT_NO_MEMORY_ERROR, "internal AllocStmt error", func); return SQL_ERROR; } if (opts->row_offset_ptr) offset = *opts->row_offset_ptr; else offset = 0; s.qstmt = (StatementClass *) hstmt; apdopts = SC_get_APDF(s.qstmt); apdopts->param_bind_type = opts->bind_size; apdopts->param_offset_ptr = opts->row_offset_ptr; ipdopts = SC_get_IPDF(s.qstmt); SC_set_delegate(s.stmt, s.qstmt); ci = &(conn->connInfo); extend_iparameter_bindings(ipdopts, num_cols); for (i = add_cols = 0; i < num_cols; i++) { if (used = bindings[i].used, used != NULL) { used = LENADDR_SHIFT(used, offset); if (bind_size > 0) used = LENADDR_SHIFT(used, bind_size * s.irow); else used = LENADDR_SHIFT(used, s.irow * sizeof(SQLLEN)); mylog("%d used=%d\n", i, *used); if (*used != SQL_IGNORE && fi[i]->updatable) { /* fieldtype = QR_get_field_type(s.res, i); */ fieldtype = getEffectiveOid(conn, fi[i]); if (add_cols) snprintf_add(addstr, sizeof(addstr), ", \"%s\"", GET_NAME(fi[i]->column_name)); else snprintf_add(addstr, sizeof(addstr), "\"%s\"", GET_NAME(fi[i]->column_name)); PIC_set_pgtype(ipdopts->parameters[add_cols], fieldtype); PGAPI_BindParameter(hstmt, (SQLUSMALLINT) ++add_cols, SQL_PARAM_INPUT, bindings[i].returntype, pgtype_to_concise_type(s.stmt, fieldtype, i), fi[i]->column_size > 0 ? fi[i]->column_size : pgtype_column_size(s.stmt, fieldtype, i, ci->drivers.unknown_sizes), (SQLSMALLINT) fi[i]->decimal_digits, bindings[i].buffer, bindings[i].buflen, bindings[i].used); } } else mylog("%d null bind\n", i); } s.updyes = FALSE; #define return DONT_CALL_RETURN_FROM_HERE??? ENTER_INNER_CONN_CS(conn, func_cs_count); if (add_cols > 0) { snprintf_add(addstr, sizeof(addstr), ") values ("); for (i = 0; i < add_cols; i++) { if (i) snprintf_add(addstr, sizeof(addstr), ", ?"); else snprintf_add(addstr, sizeof(addstr), "?"); } snprintf_add(addstr, sizeof(addstr), ")"); if (PG_VERSION_GE(conn, 8.2)) snprintf_add(addstr, sizeof(addstr), " returning ctid"); mylog("addstr=%s\n", addstr); s.qstmt->exec_start_row = s.qstmt->exec_end_row = s.irow; s.updyes = TRUE; ret = PGAPI_ExecDirect(hstmt, (SQLCHAR *) addstr, SQL_NTS, 0); if (ret == SQL_NEED_DATA) { padd_cdata *cbdata = (padd_cdata *) malloc(sizeof(padd_cdata)); memcpy(cbdata, &s, sizeof(padd_cdata)); if (0 == enqueueNeedDataCallback(s.stmt, pos_add_callback, cbdata)) ret = SQL_ERROR; goto cleanup; } /* else if (ret != SQL_SUCCESS) this is unneccesary SC_error_copy(s.stmt, s.qstmt, TRUE); */ } else { ret = SQL_SUCCESS_WITH_INFO; SC_set_error(s.stmt, STMT_INVALID_CURSOR_STATE_ERROR, "insert list null", func); } ret = pos_add_callback(ret, &s); cleanup: #undef return CLEANUP_FUNC_CONN_CS(func_cs_count, conn); return ret; } /* * Stuff for updatable cursors end. */ RETCODE SC_pos_refresh(StatementClass *stmt, SQLSETPOSIROW irow , SQLULEN global_ridx) { RETCODE ret; #if (ODBCVER >= 0x0300) IRDFields *irdflds = SC_get_IRDF(stmt); #endif /* ODBCVER */ /* save the last_fetch_count */ SQLLEN last_fetch = stmt->last_fetch_count; SQLLEN last_fetch2 = stmt->last_fetch_count_include_ommitted; SQLSETPOSIROW bind_save = stmt->bind_row; BOOL tuple_reload = FALSE; if (stmt->options.cursor_type == SQL_CURSOR_KEYSET_DRIVEN) tuple_reload = TRUE; else { QResultClass *res = SC_get_Curres(stmt); if (res && res->keyset) { SQLLEN kres_ridx = GIdx2KResIdx(global_ridx, stmt, res); if (kres_ridx >= 0 && kres_ridx < QR_get_num_cached_tuples(res)) { if (0 != (CURS_NEEDS_REREAD & res->keyset[kres_ridx].status)) tuple_reload = TRUE; } } } if (tuple_reload) SC_pos_reload(stmt, global_ridx, (UInt2 *) 0, 0); stmt->bind_row = irow; ret = SC_fetch(stmt); /* restore the last_fetch_count */ stmt->last_fetch_count = last_fetch; stmt->last_fetch_count_include_ommitted = last_fetch2; stmt->bind_row = bind_save; #if (ODBCVER >= 0x0300) if (irdflds->rowStatusArray) { switch (ret) { case SQL_ERROR: irdflds->rowStatusArray[irow] = SQL_ROW_ERROR; break; case SQL_SUCCESS: irdflds->rowStatusArray[irow] = SQL_ROW_SUCCESS; break; case SQL_SUCCESS_WITH_INFO: default: irdflds->rowStatusArray[irow] = ret; break; } } #endif /* ODBCVER */ return SQL_SUCCESS; } /* SQL_NEED_DATA callback for PGAPI_SetPos */ typedef struct { BOOL need_data_callback, auto_commit_needed; QResultClass *res; StatementClass *stmt; ARDFields *opts; GetDataInfo *gdata; SQLLEN idx, start_row, end_row, ridx; UWORD fOption; SQLSETPOSIROW irow, nrow, processed; } spos_cdata; static RETCODE spos_callback(RETCODE retcode, void *para) { CSTR func = "spos_callback"; RETCODE ret; spos_cdata *s = (spos_cdata *) para; QResultClass *res; ARDFields *opts; ConnectionClass *conn; SQLULEN global_ridx; SQLLEN kres_ridx, pos_ridx = 0; ret = retcode; mylog("%s: %d in\n", func, s->need_data_callback); if (s->need_data_callback) { s->processed++; if (SQL_ERROR != retcode) { s->nrow++; s->idx++; } } else { s->ridx = -1; s->idx = s->nrow = s->processed = 0; } res = s->res; opts = s->opts; if (!res || !opts) { SC_set_error(s->stmt, STMT_SEQUENCE_ERROR, "Passed res or opts for spos_callback is NULL", func); return SQL_ERROR; } s->need_data_callback = FALSE; for (; SQL_ERROR != ret && s->nrow <= s->end_row; s->idx++) { global_ridx = RowIdx2GIdx(s->idx, s->stmt); if (SQL_ADD != s->fOption) { if ((int) global_ridx >= QR_get_num_total_tuples(res)) break; if (res->keyset) { kres_ridx = GIdx2KResIdx(global_ridx, s->stmt, res); if (kres_ridx >= res->num_cached_keys) break; if (kres_ridx >= 0) /* the row may be deleted and not in the rowset */ { if (0 == (res->keyset[kres_ridx].status & CURS_IN_ROWSET)) continue; } } } if (s->nrow < s->start_row) { s->nrow++; continue; } s->ridx = s->nrow; pos_ridx = s->idx; #if (ODBCVER >= 0x0300) if (0 != s->irow || !opts->row_operation_ptr || opts->row_operation_ptr[s->nrow] == SQL_ROW_PROCEED) { #endif /* ODBCVER */ switch (s->fOption) { case SQL_UPDATE: ret = SC_pos_update(s->stmt, s->nrow, global_ridx); break; case SQL_DELETE: ret = SC_pos_delete(s->stmt, s->nrow, global_ridx); break; case SQL_ADD: ret = SC_pos_add(s->stmt, s->nrow); break; case SQL_REFRESH: ret = SC_pos_refresh(s->stmt, s->nrow, global_ridx); break; } if (SQL_NEED_DATA == ret) { spos_cdata *cbdata = (spos_cdata *) malloc(sizeof(spos_cdata)); memcpy(cbdata, s, sizeof(spos_cdata)); cbdata->need_data_callback = TRUE; if (0 == enqueueNeedDataCallback(s->stmt, spos_callback, cbdata)) ret = SQL_ERROR; return ret; } s->processed++; #if (ODBCVER >= 0x0300) } #endif /* ODBCVER */ if (SQL_ERROR != ret) s->nrow++; } conn = SC_get_conn(s->stmt); if (s->auto_commit_needed) CC_set_autocommit(conn, TRUE); if (s->irow > 0) { if (SQL_ADD != s->fOption && s->ridx >= 0) /* for SQLGetData */ { s->stmt->currTuple = RowIdx2GIdx(pos_ridx, s->stmt); QR_set_position(res, pos_ridx); } } else if (SC_get_IRDF(s->stmt)->rowsFetched) *(SC_get_IRDF(s->stmt)->rowsFetched) = s->processed; res->recent_processed_row_count = s->stmt->diag_row_count = s->processed; if (opts) { inolog("processed=%d ret=%d rowset=%d", s->processed, ret, opts->size_of_rowset_odbc2); #if (ODBCVER >= 0x0300) inolog(",%d\n", opts->size_of_rowset); #else inolog("\n"); #endif /* ODBCVER */ } return ret; } /* * This positions the cursor within a rowset, that was positioned using SQLExtendedFetch. * This will be useful (so far) only when using SQLGetData after SQLExtendedFetch. */ RETCODE SQL_API PGAPI_SetPos(HSTMT hstmt, SQLSETPOSIROW irow, SQLUSMALLINT fOption, SQLUSMALLINT fLock) { CSTR func = "PGAPI_SetPos"; RETCODE ret; ConnectionClass *conn; SQLLEN rowsetSize; int i; UInt2 gdata_allocated; GetDataInfo *gdata_info; GetDataClass *gdata = NULL; spos_cdata s; s.stmt = (StatementClass *) hstmt; if (!s.stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } s.irow = irow; s.fOption = fOption; s.auto_commit_needed = FALSE; s.opts = SC_get_ARDF(s.stmt); gdata_info = SC_get_GDTI(s.stmt); gdata = gdata_info->gdata; mylog("%s fOption=%d irow=%d lock=%d currt=%d\n", func, s.fOption, s.irow, fLock, s.stmt->currTuple); if (s.stmt->options.scroll_concurrency != SQL_CONCUR_READ_ONLY) ; else if (s.fOption != SQL_POSITION && s.fOption != SQL_REFRESH) { SC_set_error(s.stmt, STMT_NOT_IMPLEMENTED_ERROR, "Only SQL_POSITION/REFRESH is supported for PGAPI_SetPos", func); return SQL_ERROR; } if (!(s.res = SC_get_Curres(s.stmt))) { SC_set_error(s.stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in PGAPI_SetPos.", func); return SQL_ERROR; } #if (ODBCVER >= 0x0300) rowsetSize = (s.stmt->transition_status == STMT_TRANSITION_EXTENDED_FETCH ? s.opts->size_of_rowset_odbc2 : s.opts->size_of_rowset); #else rowsetSize = s.opts->size_of_rowset_odbc2; #endif /* ODBCVER */ if (s.irow == 0) /* bulk operation */ { if (SQL_POSITION == s.fOption) { SC_set_error(s.stmt, STMT_INVALID_CURSOR_POSITION, "Bulk Position operations not allowed.", func); return SQL_ERROR; } s.start_row = 0; s.end_row = rowsetSize - 1; } else { if (SQL_ADD != s.fOption && s.irow > s.stmt->last_fetch_count) { SC_set_error(s.stmt, STMT_ROW_OUT_OF_RANGE, "Row value out of range", func); return SQL_ERROR; } s.start_row = s.end_row = s.irow - 1; } gdata_allocated = gdata_info->allocated; mylog("num_cols=%d gdatainfo=%d\n", QR_NumPublicResultCols(s.res), gdata_allocated); /* Reset for SQLGetData */ if (gdata) { for (i = 0; i < gdata_allocated; i++) gdata[i].data_left = -1; } ret = SQL_SUCCESS; conn = SC_get_conn(s.stmt); switch (s.fOption) { case SQL_UPDATE: case SQL_DELETE: case SQL_ADD: if (s.auto_commit_needed = CC_does_autocommit(conn), s.auto_commit_needed) CC_set_autocommit(conn, FALSE); break; case SQL_POSITION: break; } s.need_data_callback = FALSE; #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(s.stmt); */ ret = spos_callback(SQL_SUCCESS, &s); #undef return if (s.stmt->internal) ret = DiscardStatementSvp(s.stmt, ret, FALSE); mylog("%s returning %d\n", func, ret); return ret; } /* Sets options that control the behavior of cursors. */ RETCODE SQL_API PGAPI_SetScrollOptions(HSTMT hstmt, SQLUSMALLINT fConcurrency, SQLLEN crowKeyset, SQLUSMALLINT crowRowset) { CSTR func = "PGAPI_SetScrollOptions"; StatementClass *stmt = (StatementClass *) hstmt; mylog("%s: fConcurrency=%d crowKeyset=%d crowRowset=%d\n", func, fConcurrency, crowKeyset, crowRowset); SC_set_error(stmt, STMT_NOT_IMPLEMENTED_ERROR, "SetScroll option not implemeted", func); return SQL_ERROR; } /* Set the cursor name on a statement handle */ RETCODE SQL_API PGAPI_SetCursorName(HSTMT hstmt, const SQLCHAR FAR * szCursor, SQLSMALLINT cbCursor) { CSTR func = "PGAPI_SetCursorName"; StatementClass *stmt = (StatementClass *) hstmt; mylog("%s: hstmt=%p, szCursor=%p, cbCursorMax=%d\n", func, hstmt, szCursor, cbCursor); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } SET_NAME_DIRECTLY(stmt->cursor_name, make_string(szCursor, cbCursor, NULL, 0)); return SQL_SUCCESS; } /* Return the cursor name for a statement handle */ RETCODE SQL_API PGAPI_GetCursorName(HSTMT hstmt, SQLCHAR FAR * szCursor, SQLSMALLINT cbCursorMax, SQLSMALLINT FAR * pcbCursor) { CSTR func = "PGAPI_GetCursorName"; StatementClass *stmt = (StatementClass *) hstmt; size_t len = 0; RETCODE result; mylog("%s: hstmt=%p, szCursor=%p, cbCursorMax=%d, pcbCursor=%p\n", func, hstmt, szCursor, cbCursorMax, pcbCursor); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } result = SQL_SUCCESS; len = strlen(SC_cursor_name(stmt)); if (szCursor) { strncpy_null((char *) szCursor, SC_cursor_name(stmt), cbCursorMax); if (len >= cbCursorMax) { result = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_TRUNCATED, "The buffer was too small for the GetCursorName.", func); } } if (pcbCursor) *pcbCursor = (SQLSMALLINT) len; /* * Because this function causes no db-access, there's * no need to call DiscardStatementSvp() */ return result; } psqlodbc-09.03.0300/socket.c000644 001752 000000 00000062333 12335653444 015643 0ustar00saitowheel000000 000000 /*------- * Module: socket.c * * Description: This module contains functions for low level socket * operations (connecting/reading/writing to the backend) * * Classes: SocketClass (Functions prefix: "SOCK_") * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "socket.h" #ifdef USE_SSPI #include "sspisvcs.h" #endif /* USE_SSPI */ #ifdef USE_GSS #include "gsssvcs.h" #endif /* USE_GSS */ #ifdef USE_LIBPQ #include #ifdef USE_SSL #include #endif /* USE_SSL */ #endif /* USE_LIBPQ */ #include "misc.h" #include "loadlib.h" #include "connection.h" #ifdef WIN32 #include #include /* Ensure to support the backward-compatibility version of getaddrinfo() etc */ #else #include #include /* for memset */ #ifdef TIME_WITH_SYS_TIME #include #include #else #ifdef HAVE_SYS_TIME_H #include #else #include #endif /* HAVE_SYS_TIME_H */ #endif /* TIME_WITH__SYS_TIME */ #endif /* WIN32 */ extern GLOBAL_VALUES globals; static int SOCK_get_next_n_bytes(SocketClass *s, int n, char *buf); static void SOCK_set_error(SocketClass *s, int _no, const char *_msg) { int gerrno = SOCK_ERRNO; s->errornumber = _no; if (NULL != s->_errormsg_) free(s->_errormsg_); if (NULL != _msg) s->_errormsg_ = strdup(_msg); else s->_errormsg_ = NULL; mylog("(%d)%s ERRNO=%d\n", _no, _msg, gerrno); } SocketClass * SOCK_Constructor(const ConnectionClass *conn) { SocketClass *rv; rv = (SocketClass *) malloc(sizeof(SocketClass)); if (rv != NULL) { rv->socket = (SOCKETFD) -1; #ifdef USE_SSPI rv->ssd = NULL; rv->sspisvcs = 0; #endif /* USE_SSPI */ #ifdef USE_GSS rv->gctx = NULL; rv->gtarg_nam = NULL; #endif /* USE_GSS */ #ifdef USE_LIBPQ rv->via_libpq = FALSE; #ifdef USE_SSL rv->ssl = NULL; #endif rv->pqconn = NULL; #endif /* USE_LIBPQ */ rv->pversion = 0; rv->reslen = 0; rv->buffer_filled_in = 0; rv->buffer_filled_out = 0; rv->buffer_read_in = 0; if (conn) { rv->buffer_size = conn->connInfo.drivers.socket_buffersize; rv->keepalive = !conn->connInfo.disable_keepalive; } else { rv->buffer_size = globals.socket_buffersize; rv->keepalive = TRUE; } rv->buffer_in = (UCHAR *) malloc(rv->buffer_size); if (!rv->buffer_in) { free(rv); return NULL; } rv->buffer_out = (UCHAR *) malloc(rv->buffer_size); if (!rv->buffer_out) { free(rv->buffer_in); free(rv); return NULL; } rv->_errormsg_ = NULL; rv->errornumber = 0; rv->reverse = FALSE; } return rv; } void SOCK_Destructor(SocketClass *self) { mylog("SOCK_Destructor\n"); if (!self) return; #ifdef USE_LIBPQ if (self->pqconn) { if (self->via_libpq) { PQfinish(self->pqconn); /* UnloadDelayLoadedDLLs(NULL != self->ssl); */ } self->via_libpq = FALSE; self->pqconn = NULL; #ifdef USE_SSL self->ssl = NULL; #endif } else #endif /* USE_LIBPQ */ { if (self->socket != (SOCKETFD) -1) { SOCK_put_char(self, 'X'); if (PG_PROTOCOL_74 == self->pversion) SOCK_put_int(self, 4, 4); SOCK_flush_output(self); closesocket(self->socket); } #ifdef USE_SSPI if (self->ssd) { ReleaseSvcSpecData(self, (UInt4) -1); free(self->ssd); self->ssd = NULL; } self->sspisvcs = 0; #endif /* USE_SSPI */ #ifdef USE_GSS pg_GSS_cleanup(self); #endif /* USE_GSS */ } if (self->buffer_in) free(self->buffer_in); if (self->buffer_out) free(self->buffer_out); if (self->_errormsg_) free(self->_errormsg_); free(self); } #ifdef WIN32 static inet_pton_func inet_pton_ptr = NULL; static HMODULE ws2_hnd = NULL; #else static inet_pton_func inet_pton_ptr = inet_pton; #endif /* WIN32 */ #if defined(_MSC_VER) && (_MSC_VER < 1300) static freeaddrinfo_func freeaddrinfo_ptr = NULL; static getaddrinfo_func getaddrinfo_ptr = NULL; static getnameinfo_func getnameinfo_ptr = NULL; #else static freeaddrinfo_func freeaddrinfo_ptr = freeaddrinfo; static getaddrinfo_func getaddrinfo_ptr = getaddrinfo; #endif /* _MSC_VER */ static BOOL format_sockerr(char *errmsg, size_t buflen, int errnum, const char *cmd, const char *host, int portno) { BOOL ret = FALSE; #ifdef WIN32 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errnum, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), errmsg, (DWORD)buflen, NULL)) ret = TRUE; #else #if defined(POSIX_MULTITHREAD_SUPPORT) && defined(HAVE_STRERROR_R) #ifdef STRERROR_R_CHAR_P const char *pchar; pchar = (const char *) strerror_r(errnum, errmsg, buflen); if (NULL != pchar) { if (pchar != errmsg) strncpy_null(errmsg, pchar, buflen); ret = TRUE; } #else if (0 == strerror_r(errnum, errmsg, buflen)) ret = TRUE; #endif /* STRERROR_R_CHAR_P */ #else strncpy_null(errmsg, strerror(errnum), buflen); ret = TRUE; #endif /* POSIX_MULTITHREAD_SUPPORT */ #endif /* WIN32 */ if (ret) { size_t tlen = strlen(errmsg); errmsg += tlen; buflen -= tlen; snprintf(errmsg, buflen, " [%s:%d]", host, portno); } else snprintf(errmsg, buflen, "%s failed for [%s:%d] ", cmd, host, portno); return ret; } static int is_numeric_address(const char *hostname) { if (inet_pton_ptr != NULL) { char unused[16]; return (inet_pton_ptr(AF_INET, hostname, &unused) || inet_pton_ptr(AF_INET6, hostname, &unused)); } return (inet_addr(hostname) != INADDR_NONE); } char SOCK_connect_to(SocketClass *self, unsigned short port, char *hostname, long timeout) { struct addrinfo rest, *addrs = NULL, *curadr = NULL; int family = 0; char retval = 0; int gerrno; if (self->socket != (SOCKETFD) -1) { SOCK_set_error(self, SOCKET_ALREADY_CONNECTED, "Socket is already connected"); return 0; } #ifdef WIN32 if (ws2_hnd == NULL) { ws2_hnd = GetModuleHandle("ws2_32.dll"); if (inet_pton_ptr == NULL) inet_pton_ptr = (inet_pton_func)GetProcAddress(ws2_hnd, "inet_pton"); } #endif /* WIN32 */ #if defined(_MSC_VER) && (_MSC_VER < 1300) if (freeaddrinfo_ptr == NULL) freeaddrinfo_ptr = (freeaddrinfo_func)GetProcAddress(ws2_hnd, "freeaddrinfo"); if (getaddrinfo_ptr == NULL) getaddrinfo_ptr = (getaddrinfo_func)GetProcAddress(ws2_hnd, "getaddrinfo"); if (getnameinfo_ptr == NULL) getnameinfo_ptr = (getnameinfo_func)GetProcAddress(ws2_hnd, "getnameinfo"); #endif /* * Hostname lookup. */ if (hostname && hostname[0] #ifndef WIN32 && '/' != hostname[0] #endif /* WIN32 */ ) { char portstr[16]; int ret; memset(&rest, 0, sizeof(rest)); rest.ai_socktype = SOCK_STREAM; rest.ai_family = AF_UNSPEC; snprintf(portstr, sizeof(portstr), "%d", port); #ifdef AI_NUMERICSERV rest.ai_flags |= AI_NUMERICSERV; #endif /* AI_NUMERICSERV */ if (is_numeric_address(hostname)) /* don't resolve address in getaddrinfo() if not necessary */ rest.ai_flags |= AI_NUMERICHOST; ret = getaddrinfo_ptr(hostname, portstr, &rest, &addrs); if (ret || !addrs) { SOCK_set_error(self, SOCKET_HOST_NOT_FOUND, "Could not resolve hostname."); if (addrs) freeaddrinfo_ptr(addrs); return 0; } curadr = addrs; } else #ifdef HAVE_UNIX_SOCKETS { struct sockaddr_un *un = (struct sockaddr_un *) &(self->sadr_area); family = un->sun_family = AF_UNIX; /* passing NULL or '' means pg default "/tmp" */ UNIXSOCK_PATH(un, port, hostname); self->sadr_len = UNIXSOCK_LEN(un); } #else { SOCK_set_error(self, SOCKET_HOST_NOT_FOUND, "Hostname isn't specified."); return 0; } #endif /* HAVE_UNIX_SOCKETS */ retry: if (curadr) family = curadr->ai_family; self->socket = socket(family, SOCK_STREAM, 0); if (self->socket == (SOCKETFD) -1) { SOCK_set_error(self, SOCKET_COULD_NOT_CREATE_SOCKET, "Could not create Socket."); goto cleanup; } #ifdef TCP_NODELAY if (family != AF_UNIX) { int i; socklen_t len; i = 1; len = sizeof(i); if (setsockopt(self->socket, IPPROTO_TCP, TCP_NODELAY, (char *) &i, len) < 0) { SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, "Could not set socket to NODELAY."); goto cleanup; } } #endif /* TCP_NODELAY */ #ifdef SO_KEEPALIVE if (family != AF_UNIX && self->keepalive) { int i; socklen_t len; i = 1; len = sizeof(i); if (setsockopt(self->socket, SOL_SOCKET, SO_KEEPALIVE, (char *) &i, len) < 0) { SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, "Could not set socket to SO_KEEPALIVE."); goto cleanup; } } #endif /* SO_KEEPALIVE */ #ifdef WIN32 { long ioctlsocket_ret = 1; /* Returns non-0 on failure, while fcntl() returns -1 on failure */ ioctlsocket(self->socket, FIONBIO, &ioctlsocket_ret); } #else fcntl(self->socket, F_SETFL, O_NONBLOCK); #endif if (curadr) { struct sockaddr *in = (struct sockaddr *) &(self->sadr_area); memset((char *) in, 0, sizeof(self->sadr_area)); memcpy(in, curadr->ai_addr, curadr->ai_addrlen); self->sadr_len = (int) curadr->ai_addrlen; } if (connect(self->socket, (struct sockaddr *) &(self->sadr_area), self->sadr_len) < 0) { int ret, optval; int wait_sec = 0; #ifdef HAVE_POLL struct pollfd fds; #else fd_set fds, except_fds; struct timeval tm; #endif /* HAVE_POLL */ socklen_t optlen = sizeof(optval); time_t t_now, t_finish = 0; BOOL tm_exp = FALSE; gerrno = SOCK_ERRNO; switch (gerrno) { case 0: case EINPROGRESS: case EINTR: #ifdef EAGAIN case EAGAIN: #endif /* EAGAIN */ #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif /* EWOULDBLOCK */ break; default: SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, "Could not connect to remote socket immedaitely"); goto cleanup; } if (timeout > 0) { t_now = time(NULL); t_finish = t_now + timeout; wait_sec = timeout; } do { #ifdef HAVE_POLL fds.fd = self->socket; fds.events = POLLOUT; fds.revents = 0; ret = poll(&fds, 1, timeout > 0 ? wait_sec * 1000 : -1); #else tm.tv_sec = wait_sec; tm.tv_usec = 0; FD_ZERO(&fds); FD_ZERO(&except_fds); FD_SET(self->socket, &fds); FD_SET(self->socket, &except_fds); ret = select((int) self->socket + 1, NULL, &fds, &except_fds, timeout > 0 ? &tm : NULL); #endif /* HAVE_POLL */ gerrno = SOCK_ERRNO; if (0 < ret) break; else if (0 == ret) tm_exp = TRUE; else if (EINTR != gerrno) break; else if (timeout > 0) { if (t_now = time(NULL), t_now >= t_finish) tm_exp = TRUE; else wait_sec = (int) (t_finish - t_now); } } while (!tm_exp); if (tm_exp) { SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, "Could not connect .. timeout occured."); goto cleanup; } else if (0 > ret) { SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, "Could not connect .. select error occured."); mylog("select error ret=%d ERROR=%d\n", ret, gerrno); goto cleanup; } if (getsockopt(self->socket, SOL_SOCKET, SO_ERROR, (char *) &optval, &optlen) == -1) { SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, "Could not connect .. getsockopt error."); } else if (optval != 0) { char errmsg[256], host[64]; host[0] = '\0'; #if defined(_MSC_VER) && (_MSC_VER < 1300) getnameinfo_ptr #else getnameinfo #endif ((struct sockaddr *) &(self->sadr_area), self->sadr_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST); /* snprintf(errmsg, sizeof(errmsg), "connect getsockopt val %d addr=%s\n", optval, host); */ format_sockerr(errmsg, sizeof(errmsg), optval, "connect", host, port); mylog(errmsg); SOCK_set_error(self, SOCKET_COULD_NOT_CONNECT, errmsg); } else retval = 1; } else retval = 1; cleanup: if (0 == retval) { if (self->socket >= 0) { closesocket(self->socket); self->socket = (SOCKETFD) -1; } if (curadr && curadr->ai_next) { curadr = curadr->ai_next; goto retry; } } else SOCK_set_error(self, 0, NULL); if (addrs) freeaddrinfo_ptr(addrs); return retval; } /* * To handle EWOULDBLOCK etc (mainly for libpq non-blocking connection). */ #define MAX_RETRY_COUNT 30 static int SOCK_wait_for_ready(SocketClass *sock, BOOL output, int retry_count) { int ret, gerrno; #ifdef HAVE_POLL struct pollfd fds; #else fd_set fds, except_fds; struct timeval tm; #endif /* HAVE_POLL */ BOOL no_timeout = TRUE; if (0 == retry_count) no_timeout = FALSE; else if (0 > retry_count) no_timeout = TRUE; #ifdef USE_SSL else if (sock->ssl == NULL) no_timeout = TRUE; #endif /* USE_SSL */ do { #ifdef HAVE_POLL fds.fd = sock->socket; fds.events = output ? POLLOUT : POLLIN; fds.revents = 0; ret = poll(&fds, 1, no_timeout ? -1 : retry_count * 1000); mylog("!!! poll ret=%d revents=%x\n", ret, fds.revents); #else FD_ZERO(&fds); FD_ZERO(&except_fds); FD_SET(sock->socket, &fds); FD_SET(sock->socket, &except_fds); if (!no_timeout) { tm.tv_sec = retry_count; tm.tv_usec = 0; } ret = select((int) sock->socket + 1, output ? NULL : &fds, output ? &fds : NULL, &except_fds, no_timeout ? NULL : &tm); #endif /* HAVE_POLL */ gerrno = SOCK_ERRNO; } while (ret < 0 && EINTR == gerrno); if (retry_count < 0) retry_count *= -1; if (0 == ret && retry_count > MAX_RETRY_COUNT) { ret = -1; SOCK_set_error(sock, output ? SOCKET_WRITE_TIMEOUT : SOCKET_READ_TIMEOUT, "SOCK_wait_for_ready timeout"); } return ret; } static int SOCK_SSPI_recv(SocketClass *self, void *buffer, int len) { #ifdef USE_SSPI if (self->sspisvcs && self->ssd) return SSPI_recv(self, (char *) buffer, len); else #endif /* USE_SSPI */ return recv(self->socket, (char *) buffer, len, RECV_FLAG); } static int SOCK_SSPI_send(SocketClass *self, const void *buffer, int len) { #ifdef USE_SSPI if (self->sspisvcs && self->ssd) return SSPI_send(self, buffer, len); else #endif /* USE_SSPI */ return send(self->socket, (char *) buffer, len, SEND_FLAG); } #ifdef USE_SSL /* * The stuff for SSL. */ /* included in #define SSL_ERROR_NONE 0 #define SSL_ERROR_SSL 1 #define SSL_ERROR_WANT_READ 2 #define SSL_ERROR_WANT_WRITE 3 #define SSL_ERROR_WANT_X509_LOOKUP 4 #define SSL_ERROR_SYSCALL 5 // look at error stack/return value/errno #define SSL_ERROR_ZERO_RETURN 6 #define SSL_ERROR_WANT_CONNECT 7 #define SSL_ERROR_WANT_ACCEPT 8 */ /* * recv more than 1 bytes using SSL. */ static int SOCK_SSL_recv(SocketClass *sock, void *buffer, int len) { CSTR func = "SOCK_SSL_recv"; int n, err, gerrno, retry_count = 0; retry: n = SSL_read(sock->ssl, buffer, len); err = SSL_get_error(sock->ssl, len); gerrno = SOCK_ERRNO; inolog("%s: %d get_error=%d Lasterror=%d\n", func, n, err, gerrno); switch (err) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_READ: retry_count++; if (SOCK_wait_for_ready(sock, FALSE, retry_count) >= 0) goto retry; n = -1; break; case SSL_ERROR_WANT_WRITE: goto retry; break; case SSL_ERROR_SYSCALL: if (-1 != n) { n = -1; SOCK_ERRNO_SET(ECONNRESET); } break; case SSL_ERROR_SSL: case SSL_ERROR_ZERO_RETURN: n = -1; SOCK_ERRNO_SET(ECONNRESET); break; default: n = -1; } return n; } /* * send more than 1 bytes using SSL. */ static int SOCK_SSL_send(SocketClass *sock, void *buffer, int len) { CSTR func = "SOCK_SSL_send"; int n, err, gerrno, retry_count = 0; retry: n = SSL_write(sock->ssl, buffer, len); err = SSL_get_error(sock->ssl, len); gerrno = SOCK_ERRNO; inolog("%s: %d get_error=%d Lasterror=%d\n", func, n, err, gerrno); switch (err) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: retry_count++; if (SOCK_wait_for_ready(sock, TRUE, retry_count) >= 0) goto retry; n = -1; break; case SSL_ERROR_SYSCALL: if (-1 != n) { n = -1; SOCK_ERRNO_SET(ECONNRESET); } break; case SSL_ERROR_SSL: case SSL_ERROR_ZERO_RETURN: n = -1; SOCK_ERRNO_SET(ECONNRESET); break; default: n = -1; } return n; } #endif /* USE_SSL */ int SOCK_get_id(SocketClass *self) { int id; if (0 != self->errornumber) return 0; if (self->reslen > 0) { mylog("SOCK_get_id has to eat %d bytes\n", self->reslen); /* do { SOCK_get_next_byte(self, FALSE); if (0 != self->errornumber) return 0; } while (self->reslen > 0); */ SOCK_get_next_n_bytes(self, self->reslen, NULL); } id = SOCK_get_next_byte(self, FALSE); self->reslen = 0; return id; } void SOCK_get_n_char(SocketClass *self, char *buffer, Int4 len) { if (!self) return; if (!buffer) { SOCK_set_error(self, SOCKET_NULLPOINTER_PARAMETER, "get_n_char was called with NULL-Pointer"); return; } /* for (lf = 0; lf < len; lf++) { if (0 != self->errornumber) break; buffer[lf] = SOCK_get_next_byte(self, FALSE); } */ SOCK_get_next_n_bytes(self, len, buffer); } void SOCK_put_n_char(SocketClass *self, const char *buffer, size_t len) { size_t lf; if (!self) return; if (!buffer) { SOCK_set_error(self, SOCKET_NULLPOINTER_PARAMETER, "put_n_char was called with NULL-Pointer"); return; } for (lf = 0; lf < len; lf++) { if (0 != self->errornumber) break; SOCK_put_next_byte(self, (UCHAR) buffer[lf]); } } /* * bufsize must include room for the null terminator * will read at most bufsize-1 characters + null. * returns TRUE if truncation occurs. */ BOOL SOCK_get_string(SocketClass *self, char *buffer, Int4 bufsize) { int lf; for (lf = 0; lf < bufsize - 1; lf++) if (!(buffer[lf] = SOCK_get_next_byte(self, FALSE))) return FALSE; buffer[bufsize - 1] = '\0'; return TRUE; } void SOCK_put_string(SocketClass *self, const char *string) { size_t lf, len; len = strlen(string) + 1; for (lf = 0; lf < len; lf++) { if (0 != self->errornumber) break; SOCK_put_next_byte(self, (UCHAR) string[lf]); } } #define REVERSE_SHORT(val) ((val & 0xff) << 8) | (val >> 8) #define REVERSE_INT(val) ((val & 0xff) << 24) | ((val & 0xff00) << 8) | ((val & 0xff0000) >> 8) | (val >> 24) int SOCK_get_int(SocketClass *self, short len) { if (!self) return 0; switch (len) { case 2: { unsigned short buf; SOCK_get_n_char(self, (char *) &buf, len); if (self->reverse) return REVERSE_SHORT(ntohs(buf)); else return ntohs(buf); } case 4: { unsigned int buf; SOCK_get_n_char(self, (char *) &buf, len); if (self->reverse) return REVERSE_INT(htonl(buf)); else return ntohl(buf); } default: SOCK_set_error(self, SOCKET_GET_INT_WRONG_LENGTH, "Cannot read ints of that length"); return 0; } } void SOCK_put_int(SocketClass *self, int value, short len) { unsigned int rv; unsigned short rsv; if (!self) return; switch (len) { case 2: rsv = htons((unsigned short) value); if (self->reverse) rsv = REVERSE_SHORT(rsv); SOCK_put_n_char(self, (char *) &rsv, 2); return; case 4: rv = htonl((unsigned int) value); if (self->reverse) rv = REVERSE_INT(rv); SOCK_put_n_char(self, (char *) &rv, 4); return; default: SOCK_set_error(self, SOCKET_PUT_INT_WRONG_LENGTH, "Cannot write ints of that length"); return; } } Int4 SOCK_flush_output(SocketClass *self) { int written, pos = 0, retry_count = 0, ttlsnd = 0, gerrno; if (!self) return -1; if (0 != self->errornumber) return -1; while (self->buffer_filled_out > 0) { #ifdef USE_SSL if (self->ssl) written = SOCK_SSL_send(self, (char *) self->buffer_out + pos, self->buffer_filled_out); else #endif /* USE_SSL */ { written = SOCK_SSPI_send(self, (char *) self->buffer_out + pos, self->buffer_filled_out); } gerrno = SOCK_ERRNO; if (written < 0) { switch (gerrno) { case EINTR: continue; break; #ifdef EAGAIN case EAGAIN: #endif /* EAGAIN */ #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif /* EWOULDBLOCK */ retry_count++; if (SOCK_wait_for_ready(self, TRUE, retry_count) >= 0) continue; break; } SOCK_set_error(self, SOCKET_WRITE_ERROR, "Could not flush socket buffer."); return -1; } pos += written; self->buffer_filled_out -= written; ttlsnd += written; retry_count = 0; } return ttlsnd; } UCHAR SOCK_get_next_byte(SocketClass *self, BOOL peek) { int retry_count = 0, gerrno; BOOL maybeEOF = FALSE; if (!self) return 0; if (self->buffer_read_in >= self->buffer_filled_in) { /* * there are no more bytes left in the buffer so reload the buffer */ self->buffer_read_in = 0; retry: #ifdef USE_SSL if (self->ssl) self->buffer_filled_in = SOCK_SSL_recv(self, (char *) self->buffer_in, self->buffer_size); else #endif /* USE_SSL */ self->buffer_filled_in = SOCK_SSPI_recv(self, (char *) self->buffer_in, self->buffer_size); gerrno = SOCK_ERRNO; mylog("read %d, global_socket_buffersize=%d\n", self->buffer_filled_in, self->buffer_size); if (self->buffer_filled_in < 0) { mylog("Lasterror=%d\n", gerrno); switch (gerrno) { case EINTR: goto retry; break; #ifdef EAGAIN case EAGAIN: #endif /* EAGAIN */ #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif /* EWOULDBLOCK */ retry_count++; if (SOCK_wait_for_ready(self, FALSE, retry_count) >= 0) goto retry; break; case ECONNRESET: inolog("ECONNRESET\n"); maybeEOF = TRUE; SOCK_set_error(self, SOCKET_CLOSED, "Connection reset by peer."); break; } if (0 == self->errornumber) SOCK_set_error(self, SOCKET_READ_ERROR, "Error while reading from the socket."); self->buffer_filled_in = 0; return 0; } if (self->buffer_filled_in == 0) { if (!maybeEOF) { int nready = SOCK_wait_for_ready(self, FALSE, 0); if (nready > 0) { maybeEOF = TRUE; goto retry; } else if (0 == nready) maybeEOF = TRUE; } if (maybeEOF) SOCK_set_error(self, SOCKET_CLOSED, "Socket has been closed."); else SOCK_set_error(self, SOCKET_READ_ERROR, "Error while reading from the socket."); return 0; } } if (peek) return self->buffer_in[self->buffer_read_in]; if (PG_PROTOCOL_74 == self->pversion) self->reslen--; return self->buffer_in[self->buffer_read_in++]; } static int SOCK_get_next_n_bytes(SocketClass *self, int n, char *buf) { int retry_count = 0, gerrno, rest, rlen; BOOL maybeEOF = FALSE; if (!self || !n) return 0; for (rest = n; 0 < rest;) { if (self->buffer_read_in >= self->buffer_filled_in) { /* * there are no more bytes left in the buffer so reload the buffer */ self->buffer_read_in = 0; retry: #ifdef USE_SSL if (self->ssl) self->buffer_filled_in = SOCK_SSL_recv(self, (char *) self->buffer_in, self->buffer_size); else #endif /* USE_SSL */ self->buffer_filled_in = SOCK_SSPI_recv(self, (char *) self->buffer_in, self->buffer_size); gerrno = SOCK_ERRNO; mylog("read %d, global_socket_buffersize=%d\n", self->buffer_filled_in, self->buffer_size); if (self->buffer_filled_in < 0) { mylog("Lasterror=%d\n", gerrno); switch (gerrno) { case EINTR: goto retry; break; #ifdef EAGAIN case EAGAIN: #endif /* EAGAIN */ #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif /* EWOULDBLOCK */ retry_count++; if (SOCK_wait_for_ready(self, FALSE, retry_count) >= 0) goto retry; break; case ECONNRESET: inolog("ECONNRESET\n"); maybeEOF = TRUE; SOCK_set_error(self, SOCKET_CLOSED, "Connection reset by peer."); break; } if (0 == self->errornumber) SOCK_set_error(self, SOCKET_READ_ERROR, "Error while reading from the socket."); self->buffer_filled_in = 0; return -1; } if (self->buffer_filled_in == 0) { if (!maybeEOF) { int nready = SOCK_wait_for_ready(self, FALSE, 0); if (nready > 0) { maybeEOF = TRUE; goto retry; } else if (0 == nready) maybeEOF = TRUE; } if (maybeEOF) { SOCK_set_error(self, SOCKET_CLOSED, "Socket has been closed."); break; } else { SOCK_set_error(self, SOCKET_READ_ERROR, "Error while reading from the socket."); return -1; } } } rlen = self->buffer_filled_in - self->buffer_read_in; if (rlen > rest) rlen = rest; if (buf) memcpy(buf + n - rest, self->buffer_in + self->buffer_read_in, rlen); rest -= rlen; if (PG_PROTOCOL_74 == self->pversion) self->reslen -= rlen; self->buffer_read_in += rlen; } return n - rest; } void SOCK_put_next_byte(SocketClass *self, UCHAR next_byte) { int bytes_sent, pos = 0, retry_count = 0, gerrno; if (!self) return; if (0 != self->errornumber) return; self->buffer_out[self->buffer_filled_out++] = next_byte; if (self->buffer_filled_out == self->buffer_size) { /* buffer is full, so write it out */ do { #ifdef USE_SSL if (self->ssl) bytes_sent = SOCK_SSL_send(self, (char *) self->buffer_out + pos, self->buffer_filled_out); else #endif /* USE_SSL */ { bytes_sent = SOCK_SSPI_send(self, (char *) self->buffer_out + pos, self->buffer_filled_out); } gerrno = SOCK_ERRNO; if (bytes_sent < 0) { switch (gerrno) { case EINTR: continue; #ifdef EAGAIN case EAGAIN: #endif /* EAGAIN */ #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif /* EWOULDBLOCK */ retry_count++; if (SOCK_wait_for_ready(self, TRUE, retry_count) >= 0) continue; } if (0 == self->errornumber) SOCK_set_error(self, SOCKET_WRITE_ERROR, "Error while writing to the socket."); break; } pos += bytes_sent; self->buffer_filled_out -= bytes_sent; retry_count = 0; } while (self->buffer_filled_out > 0); } } Int4 SOCK_get_response_length(SocketClass *self) { int leng = -1; if (PG_PROTOCOL_74 == self->pversion) { leng = SOCK_get_int(self, 4) - 4; self->reslen = leng; } return leng; } psqlodbc-09.03.0300/parse.c000644 001752 000000 00000144136 12335653444 015467 0ustar00saitowheel000000 000000 /*-------- * Module: parse.c * * Description: This module contains routines related to parsing SQL * statements. This can be useful for two reasons: * * 1. So the query does not actually have to be executed * to return data about it * * 2. To be able to return information about precision, * nullability, aliases, etc. in the functions * SQLDescribeCol and SQLColAttributes. Currently, * Postgres doesn't return any information about * these things in a query. * * Classes: none * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *-------- */ /* Multibyte support Eiji Tokuya 2001-03-15 */ #include "psqlodbc.h" #include #include #include #include "statement.h" #include "connection.h" #include "qresult.h" #include "pgtypes.h" #include "pgapifunc.h" #include "catfunc.h" #include "multibyte.h" #define FLD_INCR 32 #define TAB_INCR 8 #define COLI_INCR 16 #define COLI_RECYCLE 128 static char *getNextToken(int ccsc, char escape_in_literal, char *s, char *token, int smax, char *delim, char *quote, char *dquote, char *numeric); static void getColInfo(COL_INFO *col_info, FIELD_INFO *fi, int k); static char searchColInfo(COL_INFO *col_info, FIELD_INFO *fi); static BOOL getColumnsInfo(ConnectionClass *, TABLE_INFO *, OID, StatementClass *); Int4 FI_precision(const FIELD_INFO *fi) { OID ftype; if (!fi) return -1; ftype = FI_type(fi); switch (ftype) { case PG_TYPE_NUMERIC: return fi->column_size; case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: return fi->decimal_digits; } return 0; } Int4 FI_scale(const FIELD_INFO *fi) { OID ftype; if (!fi) return -1; ftype = FI_type(fi); switch (ftype) { case PG_TYPE_NUMERIC: return fi->decimal_digits; } return 0; } static char * getNextToken( int ccsc, /* client encoding */ char escape_ch, char *s, char *token, int smax, char *delim, char *quote, char *dquote, char *numeric) { int i = 0; int out = 0, taglen; char qc, in_quote, in_dollar_quote, in_escape; const char *tag, *tagend; encoded_str encstr; char literal_quote = LITERAL_QUOTE, identifier_quote = IDENTIFIER_QUOTE, dollar_quote = DOLLAR_QUOTE, escape_in_literal; if (smax <= 1) return NULL; smax--; /* skip leading delimiters */ while (isspace((UCHAR) s[i]) || s[i] == ',') { /* mylog("skipping '%c'\n", s[i]); */ i++; } if (s[i] == '\0') { token[0] = '\0'; return NULL; } if (quote) *quote = FALSE; if (dquote) *dquote = FALSE; if (numeric) *numeric = FALSE; encoded_str_constr(&encstr, ccsc, &s[i]); /* get the next token */ while (s[i] != '\0' && out < smax) { encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) { token[out++] = s[i++]; continue; } if (isspace((UCHAR) s[i]) || s[i] == ',') break; /* Handle quoted stuff */ in_quote = in_dollar_quote = FALSE; taglen = 0; tag = NULL; escape_in_literal = '\0'; if (out == 0) { qc = s[i]; if (qc == dollar_quote) { in_quote = in_dollar_quote = TRUE; tag = s + i; taglen = 1; if (tagend = strchr(s + i + 1, dollar_quote), NULL != tagend) taglen = tagend - s - i + 1; i += (taglen - 1); encoded_position_shift(&encstr, taglen - 1); if (quote) *quote = TRUE; } else if (qc == literal_quote) { in_quote = TRUE; if (quote) *quote = TRUE; escape_in_literal = escape_ch; if (!escape_in_literal) { if (LITERAL_EXT == s[i - 1]) escape_in_literal = ESCAPE_IN_LITERAL; } } else if (qc == identifier_quote) { in_quote = TRUE; if (dquote) *dquote = TRUE; } } if (in_quote) { i++; /* dont return the quote */ in_escape = FALSE; while (s[i] != '\0' && out != smax) { encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) { token[out++] = s[i++]; continue; } if (in_escape) in_escape = FALSE; else if (s[i] == qc) { if (!in_dollar_quote) break; if (strncmp(s + i, tag, taglen) == 0) { i += (taglen - 1); encoded_position_shift(&encstr, taglen - 1); break; } token[out++] = s[i]; } else if (literal_quote == qc && s[i] == escape_in_literal) { in_escape = TRUE; } else { token[out++] = s[i]; } i++; } if (s[i] == qc) i++; break; } /* Check for numeric literals */ if (out == 0 && isdigit((UCHAR) s[i])) { if (numeric) *numeric = TRUE; token[out++] = s[i++]; while (isalnum((UCHAR) s[i]) || s[i] == '.') token[out++] = s[i++]; break; } if (ispunct((UCHAR) s[i]) && s[i] != '_') { mylog("got ispunct: s[%d] = '%c'\n", i, s[i]); if (out == 0) { token[out++] = s[i++]; break; } else break; } if (out != smax) token[out++] = s[i]; i++; } /* mylog("done -- s[%d] = '%c'\n", i, s[i]); */ token[out] = '\0'; /* find the delimiter */ while (isspace((UCHAR) s[i])) i++; /* return the most priority delimiter */ if (s[i] == ',') { if (delim) *delim = s[i]; } else if (s[i] == '\0') { if (delim) *delim = '\0'; } else { if (delim) *delim = ' '; } /* skip trailing blanks */ while (isspace((UCHAR) s[i])) i++; return &s[i]; } static void getColInfo(COL_INFO *col_info, FIELD_INFO *fi, int k) { char *str; inolog("getColInfo non-manual result\n"); fi->dquote = TRUE; STR_TO_NAME(fi->column_name, QR_get_value_backend_text(col_info->result, k, COLUMNS_COLUMN_NAME)); fi->columntype = (OID) QR_get_value_backend_int(col_info->result, k, COLUMNS_FIELD_TYPE, NULL); fi->column_size = QR_get_value_backend_int(col_info->result, k, COLUMNS_PRECISION, NULL); fi->length = QR_get_value_backend_int(col_info->result, k, COLUMNS_LENGTH, NULL); if (str = QR_get_value_backend_text(col_info->result, k, COLUMNS_SCALE), str) fi->decimal_digits = atoi(str); else fi->decimal_digits = -1; fi->nullable = QR_get_value_backend_int(col_info->result, k, COLUMNS_NULLABLE, NULL); fi->display_size = QR_get_value_backend_int(col_info->result, k, COLUMNS_DISPLAY_SIZE, NULL); fi->auto_increment = QR_get_value_backend_int(col_info->result, k, COLUMNS_AUTO_INCREMENT, NULL); } static char searchColInfo(COL_INFO *col_info, FIELD_INFO *fi) { int k, cmp, attnum, atttypmod; OID basetype; const char *col; inolog("searchColInfo num_cols=%d col=%s\n", QR_get_num_cached_tuples(col_info->result), PRINT_NAME(fi->column_name)); if (fi->attnum < 0) return FALSE; for (k = 0; k < QR_get_num_cached_tuples(col_info->result); k++) { if (fi->attnum > 0) { attnum = QR_get_value_backend_int(col_info->result, k, COLUMNS_PHYSICAL_NUMBER, NULL); if (basetype = (OID) strtoul(QR_get_value_backend_text(col_info->result, k, COLUMNS_BASE_TYPEID), NULL, 10), 0 == basetype) basetype = (OID) strtoul(QR_get_value_backend_text(col_info->result, k, COLUMNS_FIELD_TYPE), NULL, 10); atttypmod = QR_get_value_backend_int(col_info->result, k, COLUMNS_ATTTYPMOD, NULL); inolog("searchColInfo %d attnum=%d\n", k, attnum); if (attnum == fi->attnum && basetype == fi->basetype && atttypmod == fi->typmod) { getColInfo(col_info, fi, k); mylog("PARSE: searchColInfo by attnum=%d\n", attnum); return TRUE; } } else if (NAME_IS_VALID(fi->column_name)) { col = QR_get_value_backend_text(col_info->result, k, COLUMNS_COLUMN_NAME); inolog("searchColInfo %d col=%s\n", k, col); if (fi->dquote) cmp = strcmp(col, GET_NAME(fi->column_name)); else cmp = stricmp(col, GET_NAME(fi->column_name)); if (!cmp) { if (!fi->dquote) STR_TO_NAME(fi->column_name, col); getColInfo(col_info, fi, k); mylog("PARSE: searchColInfo: \n"); return TRUE; } } } return FALSE; } /* * lower the unquoted name */ static void lower_the_name(char *name, ConnectionClass *conn, BOOL dquote) { if (!dquote) { char *ptr; encoded_str encstr; make_encoded_str(&encstr, conn, name); /* lower case table name */ for (ptr = name; *ptr; ptr++) { encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) == 0) *ptr = tolower((UCHAR) *ptr); } } } static BOOL CheckHasOids(StatementClass * stmt) { QResultClass *res; BOOL hasoids = TRUE, foundKey = FALSE; char query[512]; ConnectionClass *conn = SC_get_conn(stmt); TABLE_INFO *ti; if (0 != SC_checked_hasoids(stmt)) return TRUE; if (!stmt->ti || !stmt->ti[0]) return FALSE; ti = stmt->ti[0]; snprintf(query, sizeof(query), "select relhasoids, c.oid from pg_class c, pg_namespace n where relname = '%s' and nspname = '%s' and c.relnamespace = n.oid", SAFE_NAME(ti->table_name), SAFE_NAME(ti->schema_name)); res = CC_send_query(conn, query, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN, NULL); if (QR_command_maybe_successful(res)) { stmt->num_key_fields = PG_NUM_NORMAL_KEYS; if (1 == QR_get_num_total_tuples(res)) { const char *value = QR_get_value_backend_text(res, 0, 0); if (value && ('f' == *value || '0' == *value)) { hasoids = FALSE; TI_set_has_no_oids(ti); } else { TI_set_hasoids(ti); foundKey = TRUE; STR_TO_NAME(ti->bestitem, OID_NAME); sprintf(query, "\"%s\" = %%u", OID_NAME); STRX_TO_NAME(ti->bestqual, query); } TI_set_hasoids_checked(ti); ti->table_oid = (OID) strtoul(QR_get_value_backend_text(res, 0, 1), NULL, 10); } QR_Destructor(res); res = NULL; if (!hasoids) { sprintf(query, "select a.attname, a.atttypid from pg_index i, pg_attribute a where indrelid=%u and indnatts=1 and indisunique and indexprs is null and indpred is null and i.indrelid = a.attrelid and a.attnum=i.indkey[0] and attnotnull and atttypid in (%d, %d)", ti->table_oid, PG_TYPE_INT4, PG_TYPE_OID); res = CC_send_query(conn, query, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN, NULL); if (QR_command_maybe_successful(res) && QR_get_num_total_tuples(res) > 0) { foundKey = TRUE; STR_TO_NAME(ti->bestitem, QR_get_value_backend_text(res, 0, 0)); sprintf(query, "\"%s\" = %%", SAFE_NAME(ti->bestitem)); if (PG_TYPE_INT4 == (OID) QR_get_value_backend_int(res, 0, 1, NULL)) strcat(query, "d"); else strcat(query, "u"); STRX_TO_NAME(ti->bestqual, query); } else { /* stmt->updatable = FALSE; */ foundKey = TRUE; stmt->num_key_fields--; } } } QR_Destructor(res); SC_set_checked_hasoids(stmt, foundKey); return TRUE; } static BOOL increaseNtab(StatementClass *stmt, const char *func) { TABLE_INFO **ti = stmt->ti, *wti; if (!(stmt->ntab % TAB_INCR)) { SC_REALLOC_return_with_error(ti, TABLE_INFO *, (stmt->ntab + TAB_INCR) * sizeof(TABLE_INFO *), stmt, "PGAPI_AllocStmt failed in parse_statement for TABLE_INFO", FALSE); stmt->ti = ti; } wti = ti[stmt->ntab] = (TABLE_INFO *) malloc(sizeof(TABLE_INFO)); if (wti == NULL) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in parse_statement for TABLE_INFO(2).", func); return FALSE; } TI_Constructor(wti, SC_get_conn(stmt)); stmt->ntab++; return TRUE; } static void setNumFields(IRDFields *irdflds, size_t numFields) { FIELD_INFO **fi = irdflds->fi; size_t nfields = irdflds->nfields; if (numFields < nfields) { int i; for (i = (int) numFields; i < (int) nfields; i++) { if (fi[i]) fi[i]->flag = 0; } } irdflds->nfields = (UInt4) numFields; } void SC_initialize_cols_info(StatementClass *stmt, BOOL DCdestroy, BOOL parseReset) { IRDFields *irdflds = SC_get_IRDF(stmt); /* Free the parsed table information */ if (stmt->ti) { TI_Destructor(stmt->ti, stmt->ntab); free(stmt->ti); stmt->ti = NULL; } stmt->ntab = 0; if (DCdestroy) /* Free the parsed field information */ DC_Destructor((DescriptorClass *) SC_get_IRD(stmt)); else setNumFields(irdflds, 0); if (parseReset) { stmt->parse_status = STMT_PARSE_NONE; SC_reset_updatable(stmt); } } static BOOL allocateFields(IRDFields *irdflds, size_t sizeRequested) { FIELD_INFO **fi = irdflds->fi; size_t alloc_size, incr_size; if (sizeRequested <= irdflds->allocated) return TRUE; alloc_size = (0 != irdflds->allocated ? irdflds->allocated : FLD_INCR); for (; alloc_size < sizeRequested; alloc_size *= 2) ; incr_size = sizeof(FIELD_INFO *) * (alloc_size - irdflds->allocated); fi = (FIELD_INFO **) realloc(fi, alloc_size * sizeof(FIELD_INFO *)); if (!fi) { irdflds->fi = NULL; irdflds->allocated = irdflds->nfields = 0; return FALSE; } memset(&fi[irdflds->allocated], 0, incr_size); irdflds->fi = fi; irdflds->allocated = (SQLSMALLINT) alloc_size; return TRUE; } /* * This function may not be called but when it is called ... */ static void xxxxx(StatementClass *stmt, FIELD_INFO *fi, QResultClass *res, int i) { STR_TO_NAME(fi->column_alias, QR_get_fieldname(res, i)); fi->basetype = QR_get_field_type(res, i); if (0 == fi->columntype) fi->columntype = fi->basetype; if (fi->attnum < 0) { fi->nullable = FALSE; fi->updatable = FALSE; } else if (fi->attnum > 0) { int unknowns_as = 0; int type = pg_true_type(SC_get_conn(stmt), fi->columntype, fi->basetype); fi->nullable = TRUE; /* probably ? */ fi->column_size = pgtype_column_size(stmt, type, i, unknowns_as); fi->length = pgtype_buffer_length(stmt, type, i, unknowns_as); fi->decimal_digits = pgtype_decimal_digits(stmt, type, i); fi->display_size = pgtype_display_size(stmt, type, i, unknowns_as); } if (NAME_IS_NULL(fi->column_name)) { switch (fi->attnum) { case CTID_ATTNUM: STR_TO_NAME(fi->column_name, "ctid"); break; case OID_ATTNUM: STR_TO_NAME(fi->column_name, OID_NAME); break; case XMIN_ATTNUM: STR_TO_NAME(fi->column_name, "xmin"); break; } } } static BOOL has_multi_table(const StatementClass *stmt) { BOOL multi_table = FALSE; QResultClass *res; inolog("has_multi_table ntab=%d", stmt->ntab); if (1 < stmt->ntab) multi_table = TRUE; else if (SC_has_join(stmt)) multi_table = TRUE; else if (res = SC_get_Curres(stmt), NULL != res) { int i, num_fields = QR_NumPublicResultCols(res); OID reloid = 0, greloid; for (i = 0; i < num_fields; i++) { greloid = QR_get_relid(res, i); if (0 != greloid) { if (0 == reloid) reloid = greloid; else if (reloid != greloid) { inolog(" dohhhhhh"); multi_table = TRUE; break; } } } } inolog(" multi=%d\n", multi_table); return multi_table; } /* * SQLColAttribute tries to set the FIELD_INFO (using protocol 3). */ static BOOL ColAttSet(StatementClass *stmt, TABLE_INFO *rti) { QResultClass *res = SC_get_Curres(stmt); IRDFields *irdflds = SC_get_IRDF(stmt); COL_INFO *col_info = NULL; FIELD_INFO **fi, *wfi; OID reloid = 0; Int2 attid; int i, num_fields; BOOL fi_reuse, updatable, call_xxxxx; mylog("ColAttSet in\n"); if (rti) { if (reloid = rti->table_oid, 0 == reloid) return FALSE; if (0 != (rti->flags & TI_COLATTRIBUTE)) return TRUE; col_info = rti->col_info; } if (!QR_command_maybe_successful(res)) return FALSE; if (num_fields = QR_NumPublicResultCols(res), num_fields <= 0) return FALSE; fi = irdflds->fi; if (num_fields > (int) irdflds->allocated) { if (!allocateFields(irdflds, num_fields)) return FALSE; fi = irdflds->fi; } setNumFields(irdflds, num_fields); updatable = rti ? TI_is_updatable(rti) : FALSE; mylog("updatable=%d tab=%d fields=%d", updatable, stmt->ntab, num_fields); if (updatable) { if (1 > stmt->ntab) updatable = FALSE; else if (has_multi_table(stmt)) updatable = FALSE; } mylog("->%d\n", updatable); if (stmt->updatable < 0) SC_set_updatable(stmt, updatable); for (i = 0; i < num_fields; i++) { if (reloid == (OID) QR_get_relid(res, i)) { if (wfi = fi[i], NULL == wfi) { wfi = (FIELD_INFO *) malloc(sizeof(FIELD_INFO)); fi_reuse = FALSE; fi[i] = wfi; } else if (FI_is_applicable(wfi)) continue; else fi_reuse = TRUE; FI_Constructor(wfi, fi_reuse); attid = (Int2) QR_get_attid(res, i); wfi->attnum = attid; wfi->basetype = QR_get_field_type(res, i); wfi->typmod = QR_get_atttypmod(res, i); call_xxxxx = TRUE; if (searchColInfo(col_info, wfi)) { STR_TO_NAME(wfi->column_alias, QR_get_fieldname(res, i)); wfi->basetype = QR_get_field_type(res, i); wfi->updatable = updatable; call_xxxxx = FALSE; } else { if (attid > 0) { if (getColumnsInfo(NULL, rti, reloid, stmt) && searchColInfo(col_info, wfi)) { STR_TO_NAME(wfi->column_alias, QR_get_fieldname(res, i)); wfi->basetype = QR_get_field_type(res, i); wfi->updatable = updatable; call_xxxxx= FALSE; } } } if (call_xxxxx) xxxxx(stmt, wfi, res, i); wfi->ti = rti; wfi->flag |= FIELD_COL_ATTRIBUTE; } } if (rti) rti->flags |= TI_COLATTRIBUTE; return TRUE; } static BOOL getCOLIfromTable(ConnectionClass *conn, pgNAME *schema_name, pgNAME table_name, COL_INFO **coli) { int colidx; BOOL found = FALSE; *coli = NULL; if (NAME_IS_NULL(table_name)) return TRUE; if (conn->schema_support) { if (NAME_IS_NULL(*schema_name)) { const char *curschema = CC_get_current_schema(conn); /* * Though current_schema() doesn't have * much sense in PostgreSQL, we first * check the current_schema() when no * explicit schema name is specified. */ for (colidx = 0; colidx < conn->ntables; colidx++) { if (!NAMEICMP(conn->col_info[colidx]->table_name, table_name) && !stricmp(SAFE_NAME(conn->col_info[colidx]->schema_name), curschema)) { mylog("FOUND col_info table='%s' current schema='%s'\n", PRINT_NAME(table_name), curschema); found = TRUE; STR_TO_NAME(*schema_name, curschema); break; } } if (!found) { QResultClass *res; char token[256]; BOOL tblFound = FALSE; /* * We also have to check as follows. */ snprintf(token, sizeof(token), "select nspname from pg_namespace n, pg_class c" " where c.relnamespace=n.oid and c.oid='\"%s\"'::regclass", SAFE_NAME(table_name)); res = CC_send_query(conn, token, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN, NULL); if (QR_command_maybe_successful(res)) { if (QR_get_num_total_tuples(res) == 1) { tblFound = TRUE; STR_TO_NAME(*schema_name, QR_get_value_backend_text(res, 0, 0)); } } QR_Destructor(res); if (!tblFound) return FALSE; } } if (!found && NAME_IS_VALID(*schema_name)) { for (colidx = 0; colidx < conn->ntables; colidx++) { if (!NAMEICMP(conn->col_info[colidx]->table_name, table_name) && !NAMEICMP(conn->col_info[colidx]->schema_name, *schema_name)) { mylog("FOUND col_info table='%s' schema='%s'\n", PRINT_NAME(table_name), PRINT_NAME(*schema_name)); found = TRUE; break; } } } } else { for (colidx = 0; colidx < conn->ntables; colidx++) { if (!NAMEICMP(conn->col_info[colidx]->table_name, table_name)) { mylog("FOUND col_info table='%s'\n", table_name); found = TRUE; break; } } } *coli = found ? conn->col_info[colidx] : NULL; return TRUE; /* success */ } static BOOL getColumnsInfo(ConnectionClass *conn, TABLE_INFO *wti, OID greloid, StatementClass *stmt) { BOOL found = FALSE; RETCODE result; HSTMT hcol_stmt = NULL; StatementClass *col_stmt; QResultClass *res; mylog("PARSE: Getting PG_Columns for table %u(%s)\n", greloid, PRINT_NAME(wti->table_name)); if (NULL == conn) conn = SC_get_conn(stmt); result = PGAPI_AllocStmt(conn, &hcol_stmt, 0); if (!SQL_SUCCEEDED(result)) { if (stmt) SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in parse_statement for columns.", __FUNCTION__); goto cleanup; } col_stmt = (StatementClass *) hcol_stmt; col_stmt->internal = TRUE; if (greloid) result = PGAPI_Columns(hcol_stmt, NULL, 0, NULL, 0, NULL, 0, NULL, 0, PODBC_SEARCH_BY_IDS, greloid, 0); else result = PGAPI_Columns(hcol_stmt, NULL, 0, (SQLCHAR *) SAFE_NAME(wti->schema_name), SQL_NTS, (SQLCHAR *) SAFE_NAME(wti->table_name), SQL_NTS, NULL, 0, PODBC_NOT_SEARCH_PATTERN, 0, 0); mylog(" Past PG_Columns\n"); res = SC_get_Curres(col_stmt); if (SQL_SUCCEEDED(result) && res != NULL && QR_get_num_cached_tuples(res) > 0) { BOOL coli_exist = FALSE; COL_INFO *coli = NULL, *ccoli = NULL, *tcoli; int k; time_t acctime = 0; mylog(" Success\n"); if (greloid != 0) { for (k = 0; k < conn->ntables; k++) { tcoli = conn->col_info[k]; if (tcoli->table_oid == greloid) { coli = tcoli; coli_exist = TRUE; break; } } } if (!coli_exist) { for (k = 0; k < conn->ntables; k++) { tcoli = conn->col_info[k]; if (0 < tcoli->refcnt) continue; if ((0 == tcoli->table_oid && NAME_IS_NULL(tcoli->table_name)) || strnicmp(SAFE_NAME(tcoli->schema_name), "pg_temp_", 8) == 0) { coli = tcoli; coli_exist = TRUE; break; } if (NULL == ccoli || tcoli->acc_time < acctime) { ccoli = tcoli; acctime = tcoli->acc_time; } } if (!coli_exist && NULL != ccoli && conn->ntables >= COLI_RECYCLE) { coli_exist = TRUE; coli = ccoli; } } if (coli_exist) { free_col_info_contents(coli); } else { if (conn->ntables >= conn->coli_allocated) { Int2 new_alloc; COL_INFO **col_info; new_alloc = conn->coli_allocated * 2; if (new_alloc <= conn->ntables) new_alloc = COLI_INCR; mylog("PARSE: Allocating col_info at ntables=%d\n", conn->ntables); col_info = (COL_INFO **) realloc(conn->col_info, new_alloc * sizeof(COL_INFO *)); if (!col_info) { if (stmt) SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in parse_statement for col_info.", __FUNCTION__); goto cleanup; } conn->col_info = col_info; conn->coli_allocated = new_alloc; } mylog("PARSE: malloc at conn->col_info[%d]\n", conn->ntables); coli = conn->col_info[conn->ntables] = (COL_INFO *) malloc(sizeof(COL_INFO)); } if (!coli) { if (stmt) SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in parse_statement for col_info(2).", __FUNCTION__); goto cleanup; } col_info_initialize(coli); coli->result = res; if (res && QR_get_num_cached_tuples(res) > 0) { if (!greloid) greloid = (OID) strtoul(QR_get_value_backend_text(res, 0, COLUMNS_TABLE_OID), NULL, 10); if (!wti->table_oid) wti->table_oid = greloid; if (NAME_IS_NULL(wti->schema_name)) STR_TO_NAME(wti->schema_name, QR_get_value_backend_text(res, 0, COLUMNS_SCHEMA_NAME)); if (NAME_IS_NULL(wti->table_name)) STR_TO_NAME(wti->table_name, QR_get_value_backend_text(res, 0, COLUMNS_TABLE_NAME)); } inolog("#2 %p->table_name=%s(%u)\n", wti, PRINT_NAME(wti->table_name), wti->table_oid); /* * Store the table name and the SQLColumns result * structure */ if (NAME_IS_VALID(wti->schema_name)) { NAME_TO_NAME(coli->schema_name, wti->schema_name); } else NULL_THE_NAME(coli->schema_name); NAME_TO_NAME(coli->table_name, wti->table_name); coli->table_oid = wti->table_oid; /* * The connection will now free the result structures, so * make sure that the statement doesn't free it */ SC_init_Result(col_stmt); if (!coli_exist) conn->ntables++; if (res && QR_get_num_cached_tuples(res) > 0) inolog("oid item == %s\n", QR_get_value_backend_text(res, 0, 3)); mylog("Created col_info table='%s', ntables=%d\n", PRINT_NAME(wti->table_name), conn->ntables); /* Associate a table from the statement with a SQLColumn info */ found = TRUE; coli->refcnt++; wti->col_info = coli; } cleanup: if (hcol_stmt) PGAPI_FreeStmt(hcol_stmt, SQL_DROP); return found; } BOOL getCOLIfromTI(const char *func, ConnectionClass *conn, StatementClass *stmt, const OID reloid, TABLE_INFO **pti) { BOOL colatt = FALSE, found = FALSE; OID greloid = reloid; TABLE_INFO *wti = *pti; COL_INFO *coli; inolog("getCOLIfromTI reloid=%u ti=%p\n", reloid, wti); if (!conn) conn = SC_get_conn(stmt); if (!wti) /* SQLColAttribute case */ { int i; if (0 == greloid) return FALSE; if (!stmt) return FALSE; colatt = TRUE; for (i = 0; i < stmt->ntab; i++) { if (stmt->ti[i]->table_oid == greloid) { wti = stmt->ti[i]; break; } } if (!wti) { inolog("before increaseNtab\n"); if (!increaseNtab(stmt, func)) return FALSE; wti = stmt->ti[stmt->ntab - 1]; wti->table_oid = greloid; } *pti = wti; } inolog("fi=%p greloid=%d col_info=%p\n", wti, greloid, wti->col_info); if (0 == greloid) greloid = wti->table_oid; if (NULL != wti->col_info) { found = TRUE; goto cleanup; } if (greloid != 0) { int colidx; for (colidx = 0; colidx < conn->ntables; colidx++) { if (conn->col_info[colidx]->table_oid == greloid) { mylog("FOUND col_info table=%ul\n", greloid); found = TRUE; wti->col_info = conn->col_info[colidx]; wti->col_info->refcnt++; break; } } } else { if (!getCOLIfromTable(conn, &wti->schema_name, wti->table_name, &coli)) { if (stmt) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); SC_set_error(stmt, STMT_EXEC_ERROR, "Table not found", func); SC_reset_updatable(stmt); } return FALSE; } else if (NULL != coli) { found = TRUE; coli->refcnt++; wti->col_info = coli; } } if (found) goto cleanup; else if (0 != greloid || NAME_IS_VALID(wti->table_name)) found = getColumnsInfo(conn, wti, greloid, stmt); cleanup: if (found) { QResultClass *res = wti->col_info->result; if (res && QR_get_num_cached_tuples(res) > 0) { if (!greloid) greloid = (OID) strtoul(QR_get_value_backend_text(res, 0, COLUMNS_TABLE_OID), NULL, 10); if (!wti->table_oid) wti->table_oid = greloid; if (NAME_IS_NULL(wti->schema_name)) STR_TO_NAME(wti->schema_name, QR_get_value_backend_text(res, 0, COLUMNS_SCHEMA_NAME)); if (NAME_IS_NULL(wti->table_name)) STR_TO_NAME(wti->table_name, QR_get_value_backend_text(res, 0, COLUMNS_TABLE_NAME)); } inolog("#1 %p->table_name=%s(%u)\n", wti, PRINT_NAME(wti->table_name), wti->table_oid); if (colatt /* SQLColAttribute case */ && 0 == (wti->flags & TI_COLATTRIBUTE)) { if (stmt) ColAttSet(stmt, wti); } wti->col_info->acc_time = SC_get_time(stmt); } else if (!colatt && stmt) SC_set_parse_status(stmt, STMT_PARSE_FATAL); inolog("getCOLIfromTI returns %d\n", found); return found; } SQLRETURN SC_set_SS_columnkey(StatementClass *stmt) { CSTR func = "SC_set_SS_columnkey"; IRDFields *irdflds = SC_get_IRDF(stmt); FIELD_INFO **fi = irdflds->fi, *tfi; size_t nfields = irdflds->nfields; HSTMT pstmt = NULL; SQLRETURN ret = SQL_SUCCESS; BOOL contains_key = FALSE; int i; inolog("%s:fields=%d ntab=%d\n", func, nfields, stmt->ntab); if (!fi) return ret; if (0 >= nfields) return ret; if (!has_multi_table(stmt) && 1 == stmt->ntab) { TABLE_INFO **ti = stmt->ti, *oneti; ConnectionClass *conn = SC_get_conn(stmt); OID internal_asis_type = SQL_C_CHAR; char keycolnam[MAX_INFO_STRING]; SQLLEN keycollen; ret = PGAPI_AllocStmt(conn, &pstmt, 0); if (!SQL_SUCCEEDED(ret)) return ret; oneti = ti[0]; ret = PGAPI_PrimaryKeys(pstmt, NULL, 0, NULL, 0, NULL, 0, oneti->table_oid); if (!SQL_SUCCEEDED(ret)) goto cleanup; #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) internal_asis_type = INTERNAL_ASIS_TYPE; #endif /* UNICODE_SUPPORT */ ret = PGAPI_BindCol(pstmt, 4, internal_asis_type, keycolnam, MAX_INFO_STRING, &keycollen); if (!SQL_SUCCEEDED(ret)) goto cleanup; contains_key = TRUE; ret = PGAPI_Fetch(pstmt); while (SQL_SUCCEEDED(ret)) { for (i = 0; i < nfields; i++) { if (tfi = fi[i], NULL == tfi) continue; if (!FI_is_applicable(tfi)) continue; if (oneti == tfi->ti && strcmp(keycolnam, SAFE_NAME(tfi->column_name)) == 0) { inolog("%s:key %s found at %p\n", func, keycolnam, fi + i); tfi->columnkey = TRUE; break; } } if (i >= nfields) { mylog("%s: %s not found\n", func, keycolnam); break; } ret = PGAPI_Fetch(pstmt); } if (SQL_SUCCEEDED(ret)) contains_key = FALSE; else if (SQL_NO_DATA_FOUND != ret) goto cleanup; ret = SQL_SUCCESS; } inolog("%s: contains_key=%d\n", func, contains_key); for (i = 0; i < nfields; i++) { if (tfi = fi[i], NULL == tfi) continue; if (!FI_is_applicable(tfi)) continue; if (!contains_key || tfi->columnkey < 0) tfi->columnkey = FALSE; } cleanup: if (pstmt) PGAPI_FreeStmt(pstmt, SQL_DROP); return ret; } static BOOL include_alias_wo_as(const char *token, const char *btoken) { mylog("alias ? token=%s btoken=%s\n", token, btoken); if ('\0' == btoken[0]) return FALSE; else if (0 == stricmp(")", token)) return FALSE; else if (0 == stricmp("as", btoken) || 0 == stricmp("and", btoken) || 0 == stricmp("or", btoken) || 0 == stricmp("not", btoken) || 0 == stricmp(",", btoken)) return FALSE; else { CSTR ops = "+-*/%^|!@&#~<>=."; const char *cptr, *optr; for (cptr = btoken; *cptr; cptr++) { for (optr = ops; *optr; optr++) { if (*optr != *cptr) return TRUE; } } } return FALSE; } static char *insert_as_to_the_statement(char *stmt, char **pptr, char **ptr) { size_t stsize = strlen(stmt), ppos = *pptr - stmt, remsize = stsize - ppos; const int ins_size = 3; char *newstmt = realloc(stmt, stsize + ins_size + 1); if (newstmt) { char *sptr = newstmt + ppos; memmove(sptr + ins_size, sptr, remsize + 1); sptr[0] = 'a'; sptr[1] = 's'; sptr[2] = ' '; *ptr = sptr + (*ptr - *pptr) + ins_size; *pptr = sptr + ins_size; } return newstmt; } #define TOKEN_SIZE 256 static char parse_the_statement(StatementClass *stmt, BOOL check_hasoids, BOOL sqlsvr_check) { CSTR func = "parse_the_statement"; char delimdsp[2], token[TOKEN_SIZE], stoken[TOKEN_SIZE], btoken[TOKEN_SIZE]; char delim, quote, dquote, numeric, unquoted; char *ptr, *pptr = NULL; char in_select = FALSE, in_distinct = FALSE, in_on = FALSE, in_from = FALSE, in_where = FALSE, in_table = FALSE, out_table = TRUE; char in_field = FALSE, in_expr = FALSE, in_func = FALSE, in_dot = FALSE, in_as = FALSE; int j, i, k = 0, n, blevel = 0, old_blevel, subqlevel = 0, tbl_blevel = 0, allocated_size = -1, new_size, nfields; FIELD_INFO **fi, *wfi; TABLE_INFO **ti, *wti; char parse = FALSE, maybe_join = 0; ConnectionClass *conn = SC_get_conn(stmt); IRDFields *irdflds; BOOL updatable = TRUE, column_has_alias = FALSE; mylog("%s: entering...\n", func); if (SC_parsed_status(stmt) != STMT_PARSE_NONE) { if (check_hasoids) CheckHasOids(stmt); return TRUE; } nfields = 0; wfi = NULL; wti = NULL; ptr = stmt->statement; if (sqlsvr_check) { irdflds = NULL; fi = NULL; ti = NULL; } else { SC_set_updatable(stmt, FALSE); irdflds = SC_get_IRDF(stmt); fi = irdflds->fi; ti = stmt->ti; allocated_size = irdflds->allocated; SC_initialize_cols_info(stmt, FALSE, TRUE); stmt->from_pos = -1; stmt->where_pos = -1; } #define return DONT_CALL_RETURN_FROM_HERE??? delim = '\0'; token[0] = '\0'; while (pptr = ptr, (delim != ',') ? strcpy(btoken, token) : (btoken[0] = '\0', NULL), (ptr = getNextToken(conn->ccsc, CC_get_escape(conn), pptr, token, sizeof(token), &delim, "e, &dquote, &numeric)) != NULL) { unquoted = !(quote || dquote); if (delim) { delimdsp[0] = delim; delimdsp[1] = '\0'; } else delimdsp[0] = '\0'; mylog("unquoted=%d, quote=%d, dquote=%d, numeric=%d, delim='%s', token='%s', ptr='%s'\n", unquoted, quote, dquote, numeric, delimdsp, token, ptr); old_blevel = blevel; if (unquoted && blevel == 0) { if (in_select) { if (!stricmp(token, "distinct")) { in_distinct = TRUE; updatable = FALSE; mylog("DISTINCT\n"); continue; } else if (!stricmp(token, "into")) { in_select = FALSE; mylog("INTO\n"); stmt->statement_type = STMT_TYPE_CREATE; SC_set_parse_status(stmt, STMT_PARSE_FATAL); goto cleanup; } else if (!stricmp(token, "from")) { if (sqlsvr_check) { parse = TRUE; goto cleanup; } in_select = FALSE; in_from = TRUE; if (stmt->from_pos < 0 && (!strnicmp(pptr, "from", 4))) { mylog("First "); stmt->from_pos = pptr - stmt->statement; } mylog("FROM\n"); continue; } } /* in_select && unquoted && blevel == 0 */ else if ((!stricmp(token, "where") || !stricmp(token, "union") || !stricmp(token, "intersect") || !stricmp(token, "except") || !stricmp(token, "order") || !stricmp(token, "group") || !stricmp(token, "having"))) { in_from = FALSE; in_where = TRUE; if (stmt->where_pos < 0) stmt->where_pos = pptr - stmt->statement; mylog("%s...\n", token); if (stricmp(token, "where") && stricmp(token, "order")) { updatable = FALSE; break; } continue; } } /* unquoted && blevel == 0 */ /* check the change of blevel etc */ if (unquoted) { if (!stricmp(token, "select")) { stoken[0] = '\0'; if (0 == blevel) { in_select = TRUE; mylog("SELECT\n"); continue; } else { mylog("SUBSELECT\n"); if (0 == subqlevel) subqlevel = blevel; } } else if (token[0] == '(') { blevel++; mylog("blevel++ -> %d\n", blevel); /* aggregate function ? */ if (stoken[0] && updatable && 0 == subqlevel) { if (stricmp(stoken, "count") == 0 || stricmp(stoken, "sum") == 0 || stricmp(stoken, "avg") == 0 || stricmp(stoken, "max") == 0 || stricmp(stoken, "min") == 0 || stricmp(stoken, "variance") == 0 || stricmp(stoken, "stddev") == 0) updatable = FALSE; } } else if (token[0] == ')') { blevel--; mylog("blevel-- = %d\n", blevel); if (blevel < subqlevel) subqlevel = 0; } if (blevel >= old_blevel && ',' != delim) strcpy(stoken, token); else stoken[0] = '\0'; } if (in_select) { mylog("blevel=%d btoken=%s in_dot=%d in_field=%d tbname=%s\n", blevel, btoken, in_dot, in_field, wfi ? SAFE_NAME(wfi->column_alias) : ""); if (0 == blevel && sqlsvr_check && dquote && '\0' != btoken[0] && !in_dot && in_field && (!column_has_alias)) { if (include_alias_wo_as(token, btoken)) { char *news; column_has_alias = TRUE; if (NULL != wfi) STRX_TO_NAME(wfi->column_alias, token); news = insert_as_to_the_statement(stmt->statement, &pptr, &ptr); if (news != stmt->statement) { free(stmt->statement); stmt->statement = news; } } } if (in_expr || in_func) { /* just eat the expression */ mylog("in_expr=%d or func=%d\n", in_expr, in_func); if (blevel == 0) { if (delim == ',') { mylog("**** Got comma in_expr/func\n"); in_func = FALSE; in_expr = FALSE; in_field = FALSE; } else if (unquoted && !stricmp(token, "as")) { mylog("got AS in_expr\n"); in_func = FALSE; in_expr = FALSE; in_as = TRUE; in_field = TRUE; } } continue; } /* (in_expr || in_func) && in_select */ if (in_distinct) { mylog("in distinct\n"); if (unquoted && !stricmp(token, "on")) { in_on = TRUE; mylog("got on\n"); continue; } if (in_on) { in_distinct = FALSE; in_on = FALSE; continue; /* just skip the unique on field */ } mylog("done distinct\n"); in_distinct = FALSE; } /* in_distinct */ if (!in_field) { BOOL fi_reuse = FALSE; if (!token[0]) continue; column_has_alias = FALSE; if (!sqlsvr_check) { /* if (!(irdflds->nfields % FLD_INCR)) */ if (irdflds->nfields >= allocated_size) { mylog("reallocing at nfld=%d\n", irdflds->nfields); new_size = irdflds->nfields + 1; if (!allocateFields(irdflds, new_size)) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in parse_statement for FIELD_INFO.", func); goto cleanup; } fi = irdflds->fi; allocated_size = irdflds->allocated; } wfi = fi[irdflds->nfields]; if (NULL != wfi) fi_reuse = TRUE; else wfi = fi[irdflds->nfields] = (FIELD_INFO *) malloc(sizeof(FIELD_INFO)); if (NULL == wfi) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in parse_statement for FIELD_INFO(2).", func); goto cleanup; } /* Initialize the field info */ FI_Constructor(wfi, fi_reuse); wfi->flag = FIELD_PARSING; } /* double quotes are for qualifiers */ if (dquote && NULL != wfi) wfi->dquote = TRUE; if (quote) { if (NULL != wfi) { wfi->quote = TRUE; wfi->column_size = (int) strlen(token); } } else if (numeric) { mylog("**** got numeric: nfld = %d\n", nfields); if (NULL != wfi) wfi->numeric = TRUE; } else if (0 == old_blevel && blevel > 0) { /* expression */ mylog("got EXPRESSION\n"); if (NULL != wfi) wfi->expr = TRUE; in_expr = TRUE; /* continue; */ } else if (NULL != wfi) { STRX_TO_NAME(wfi->column_name, token); NULL_THE_NAME(wfi->before_dot); } if (NULL != wfi) mylog("got field='%s', dot='%s'\n", PRINT_NAME(wfi->column_name), PRINT_NAME(wfi->before_dot)); if (delim == ',') mylog("comma (1)\n"); else in_field = TRUE; nfields++; if (NULL != irdflds) irdflds->nfields++; continue; } /* !in_field */ /* * We are in a field now */ if (!sqlsvr_check) wfi = fi[irdflds->nfields - 1]; if (in_dot) { if (NULL != wfi) { if (NAME_IS_VALID(wfi->before_dot)) { MOVE_NAME(wfi->schema_name, wfi->before_dot); } MOVE_NAME(wfi->before_dot, wfi->column_name); STRX_TO_NAME(wfi->column_name, token); } if (delim == ',') { mylog("in_dot: got comma\n"); in_field = FALSE; } in_dot = FALSE; continue; } if (in_as) { column_has_alias = TRUE; if (NULL != wfi) { STRX_TO_NAME(wfi->column_alias, token); mylog("alias for field '%s' is '%s'\n", PRINT_NAME(wfi->column_name), PRINT_NAME(wfi->column_alias)); } in_as = FALSE; in_field = FALSE; if (delim == ',') mylog("comma(2)\n"); continue; } /* Function */ if (0 == old_blevel && blevel > 0) { in_dot = FALSE; in_func = TRUE; if (NULL != wfi) { wfi->func = TRUE; /* * name will have the function name -- maybe useful some * day */ mylog("**** got function = '%s'\n", PRINT_NAME(wfi->column_name)); } continue; } if (token[0] == '.') { in_dot = TRUE; mylog("got dot\n"); continue; } in_dot = FALSE; if (!stricmp(token, "as")) { in_as = TRUE; mylog("got AS\n"); continue; } /* otherwise, it's probably an expression */ if (!column_has_alias) { in_expr = TRUE; if (NULL != wfi) { wfi->expr = TRUE; NULL_THE_NAME(wfi->column_name); wfi->column_size = 0; } mylog("*** setting expression\n"); } else mylog("*** may be an alias for a field\n"); if (0 == blevel && ',' == delim) { in_expr = in_func = in_field = FALSE; } } /* in_select end */ if (in_from || in_where) { if (token[0] == ';') /* end of the first command */ { in_select = in_from = in_where = in_table = FALSE; break; } } if (in_from) { switch (token[0]) { case '\0': continue; case ',': out_table = TRUE; continue; } if (out_table && !in_table) /* new table */ { BOOL is_table_name, is_subquery; in_dot = FALSE; maybe_join = 0; if (!dquote) { if (token[0] == '(' || token[0] == ')') continue; } if (sqlsvr_check) wti = NULL; else { if (!increaseNtab(stmt, func)) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); goto cleanup; } ti = stmt->ti; wti = ti[stmt->ntab - 1]; } is_table_name = TRUE; is_subquery = FALSE; if (dquote) ; else if (0 == stricmp(token, "select")) { mylog("got subquery lvl=%d\n", blevel); is_table_name = FALSE; is_subquery = TRUE; } else if ('(' == ptr[0]) { mylog("got srf? = '%s'\n", token); is_table_name = FALSE; } if (NULL != wti) { if (is_table_name) { STRX_TO_NAME(wti->table_name, token); lower_the_name(GET_NAME(wti->table_name), conn, dquote); mylog("got table = '%s'\n", PRINT_NAME(wti->table_name)); } else { NULL_THE_NAME(wti->table_name); TI_no_updatable(wti); } } if (0 == blevel && delim == ',') { out_table = TRUE; mylog("more than 1 tables\n"); } else { out_table = FALSE; in_table = TRUE; if (is_subquery) tbl_blevel = blevel - 1; else tbl_blevel = blevel; } continue; } if (blevel > tbl_blevel) continue; /* out_table is FALSE here */ if (!dquote && !in_dot) { if (')' == token[0]) continue; if (stricmp(token, "LEFT") == 0 || stricmp(token, "RIGHT") == 0 || stricmp(token, "OUTER") == 0 || stricmp(token, "FULL") == 0) { maybe_join = 1; in_table = FALSE; continue; } else if (stricmp(token, "INNER") == 0 || stricmp(token, "CROSS") == 0) { maybe_join = 2; in_table = FALSE; continue; } else if (stricmp(token, "JOIN") == 0) { in_table = FALSE; out_table = TRUE; switch (maybe_join) { case 1: SC_set_outer_join(stmt); break; case 2: SC_set_inner_join(stmt); break; } maybe_join = 0; continue; } } maybe_join = 0; if (in_table) { if (!sqlsvr_check) wti = ti[stmt->ntab - 1]; if (in_dot) { if (NULL != wfi) { MOVE_NAME(wti->schema_name, wti->table_name); STRX_TO_NAME(wti->table_name, token); lower_the_name(GET_NAME(wti->table_name), conn, dquote); } in_dot = FALSE; continue; } if (strcmp(token, ".") == 0) { in_dot = TRUE; continue; } if (dquote || stricmp(token, "as")) { if (!dquote) { if (stricmp(token, "ON") == 0) { in_table = FALSE; continue; } } if (NULL != wti) { STRX_TO_NAME(wti->table_alias, token); mylog("alias for table '%s' is '%s'\n", PRINT_NAME(wti->table_name), PRINT_NAME(wti->table_alias)); } in_table = FALSE; if (delim == ',') { out_table = TRUE; mylog("more than 1 tables\n"); } } } } /* in_from */ } /* * Resolve any possible field names with tables */ parse = TRUE; if (sqlsvr_check) goto cleanup; /* Resolve field names with tables */ for (i = 0; i < (int) irdflds->nfields; i++) { wfi = fi[i]; if (wfi->func || wfi->expr || wfi->numeric) { wfi->ti = NULL; wfi->columntype = wfi->basetype = (OID) 0; parse = FALSE; continue; } else if (wfi->quote) { /* handle as text */ wfi->ti = NULL; /* * wfi->type = PG_TYPE_TEXT; wfi->column_size = 0; the * following may be better */ wfi->basetype = PG_TYPE_UNKNOWN; if (wfi->column_size == 0) { wfi->basetype = PG_TYPE_VARCHAR; wfi->column_size = 254; } wfi->length = wfi->column_size; continue; } /* field name contains the schema name */ else if (NAME_IS_VALID(wfi->schema_name)) { int matchidx = -1; for (k = 0; k < stmt->ntab; k++) { wti = ti[k]; if (!NAMEICMP(wti->table_name, wfi->before_dot)) { if (!NAMEICMP(wti->schema_name, wfi->schema_name)) { wfi->ti = wti; break; } else if (NAME_IS_NULL(wti->schema_name)) { if (matchidx < 0) matchidx = k; else { SC_set_parse_status(stmt, STMT_PARSE_FATAL); SC_set_error(stmt, STMT_EXEC_ERROR, "duplicated Table name", func); SC_reset_updatable(stmt); goto cleanup; } } } } if (matchidx >= 0) wfi->ti = ti[matchidx]; } /* it's a dot, resolve to table or alias */ else if (NAME_IS_VALID(wfi->before_dot)) { for (k = 0; k < stmt->ntab; k++) { wti = ti[k]; if (!NAMEICMP(wti->table_alias, wfi->before_dot)) { wfi->ti = wti; break; } else if (!NAMEICMP(wti->table_name, wfi->before_dot)) { wfi->ti = wti; break; } } } else if (stmt->ntab == 1) wfi->ti = ti[0]; } mylog("--------------------------------------------\n"); mylog("nfld=%d, ntab=%d\n", irdflds->nfields, stmt->ntab); if (0 == stmt->ntab) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); goto cleanup; } for (i = 0; i < (int) irdflds->nfields; i++) { wfi = fi[i]; mylog("Field %d: expr=%d, func=%d, quote=%d, dquote=%d, numeric=%d, name='%s', alias='%s', dot='%s'\n", i, wfi->expr, wfi->func, wfi->quote, wfi->dquote, wfi->numeric, PRINT_NAME(wfi->column_name), PRINT_NAME(wfi->column_alias), PRINT_NAME(wfi->before_dot)); if (wfi->ti) mylog(" ----> table_name='%s', table_alias='%s'\n", PRINT_NAME(wfi->ti->table_name), PRINT_NAME(wfi->ti->table_alias)); } for (i = 0; i < stmt->ntab; i++) { wti = ti[i]; mylog("Table %d: name='%s', alias='%s'\n", i, PRINT_NAME(wti->table_name), PRINT_NAME(wti->table_alias)); } /* * Now save the SQLColumns Info for the parse tables */ /* Call SQLColumns for each table and store the result */ if (stmt->ntab > 1) updatable = FALSE; else if (stmt->from_pos < 0) updatable = FALSE; for (i = 0; i < stmt->ntab; i++) { /* See if already got it */ wti = ti[i]; if (!getCOLIfromTI(func, NULL, stmt, 0, &wti)) break; } if (STMT_PARSE_FATAL == SC_parsed_status(stmt)) { goto cleanup; } mylog("Done PG_Columns\n"); /* * Now resolve the fields to point to column info */ if (updatable && 1 == stmt->ntab) updatable = TI_is_updatable(stmt->ti[0]); for (i = 0; i < (int) irdflds->nfields;) { wfi = fi[i]; wfi->updatable = updatable; /* Dont worry about functions or quotes */ if (wfi->func || wfi->quote || wfi->numeric) { wfi->updatable = FALSE; i++; continue; } /* Stars get expanded to all fields in the table */ else if (SAFE_NAME(wfi->column_name)[0] == '*') { char do_all_tables; Int2 total_cols, cols, increased_cols; mylog("expanding field %d\n", i); total_cols = 0; if (wfi->ti) /* The star represents only the qualified * table */ total_cols = (Int2) QR_get_num_cached_tuples(wfi->ti->col_info->result); else { /* The star represents all tables */ /* Calculate the total number of columns after expansion */ for (k = 0; k < stmt->ntab; k++) total_cols += (Int2) QR_get_num_cached_tuples(ti[k]->col_info->result); } increased_cols = total_cols - 1; /* Allocate some more field pointers if necessary */ new_size = irdflds->nfields + increased_cols; mylog("k=%d, increased_cols=%d, allocated_size=%d, new_size=%d\n", k, increased_cols, allocated_size, new_size); if (new_size > allocated_size) { int new_alloc = new_size; mylog("need more cols: new_alloc = %d\n", new_alloc); if (!allocateFields(irdflds, new_alloc)) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); goto cleanup; } fi = irdflds->fi; allocated_size = irdflds->allocated; } /* * copy any other fields (if there are any) up past the * expansion */ for (j = irdflds->nfields - 1; j > i; j--) { mylog("copying field %d to %d\n", j, increased_cols + j); fi[increased_cols + j] = fi[j]; } mylog("done copying fields\n"); /* Set the new number of fields */ irdflds->nfields += increased_cols; mylog("irdflds->nfields now at %d\n", irdflds->nfields); /* copy the new field info */ do_all_tables = (wfi->ti ? FALSE : TRUE); wfi = NULL; for (k = 0; k < (do_all_tables ? stmt->ntab : 1); k++) { TABLE_INFO *the_ti = do_all_tables ? ti[k] : fi[i]->ti; cols = (Int2) QR_get_num_cached_tuples(the_ti->col_info->result); for (n = 0; n < cols; n++) { FIELD_INFO *afi; BOOL reuse = TRUE; mylog("creating field info: n=%d\n", n); /* skip malloc (already did it for the Star) */ if (k > 0 || n > 0) { mylog("allocating field info at %d\n", n + i); fi[n + i] = (FIELD_INFO *) malloc(sizeof(FIELD_INFO)); if (fi[n + i] == NULL) { SC_set_parse_status(stmt, STMT_PARSE_FATAL); goto cleanup; } reuse = FALSE; } afi = fi[n + i]; /* Initialize the new space (or the * field) */ FI_Constructor(afi, reuse); afi->ti = the_ti; mylog("about to copy at %d\n", n + i); getColInfo(the_ti->col_info, afi, n); afi->updatable = updatable; mylog("done copying\n"); } i += cols; mylog("i now at %d\n", i); } } /* * We either know which table the field was in because it was * qualified with a table name or alias -OR- there was only 1 * table. */ else if (wfi->ti) { if (!searchColInfo(fi[i]->ti->col_info, wfi)) { parse = FALSE; wfi->updatable = FALSE; } i++; } /* Don't know the table -- search all tables in "from" list */ else { for (k = 0; k < stmt->ntab; k++) { if (searchColInfo(ti[k]->col_info, wfi)) { wfi->ti = ti[k]; /* now know the table */ break; } } if (k >= stmt->ntab) { parse = FALSE; wfi->updatable = FALSE; } i++; } } if (check_hasoids && updatable) CheckHasOids(stmt); SC_set_parse_status(stmt, parse ? STMT_PARSE_COMPLETE : STMT_PARSE_INCOMPLETE); for (i = 0; i < (int) irdflds->nfields; i++) { wfi = fi[i]; wfi->flag &= ~FIELD_PARSING; if (0 != wfi->columntype || 0 != wfi->basetype) wfi->flag |= FIELD_PARSED_OK; } SC_set_updatable(stmt, updatable); cleanup: #undef return if (!sqlsvr_check && STMT_PARSE_FATAL == SC_parsed_status(stmt)) { SC_initialize_cols_info(stmt, FALSE, FALSE); parse = FALSE; } mylog("done %s: parse=%d, parse_status=%d\n", func, parse, SC_parsed_status(stmt)); return parse; } char parse_statement(StatementClass *stmt, BOOL check_hasoids) { return parse_the_statement(stmt, check_hasoids, FALSE); } char parse_sqlsvr(StatementClass *stmt) { return parse_the_statement(stmt, FALSE, TRUE); } psqlodbc-09.03.0300/statement.c000644 001752 000000 00000237166 12335653444 016367 0ustar00saitowheel000000 000000 /*------- * Module: statement.c * * Description: This module contains functions related to creating * and manipulating a statement. * * Classes: StatementClass (Functions prefix: "SC_") * * API functions: SQLAllocStmt, SQLFreeStmt * * Comments: See "readme.txt" for copyright and license information. *------- */ #ifdef WIN_MULTITHREAD_SUPPORT #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif /* _WIN32_WINNT */ #endif /* WIN_MULTITHREAD_SUPPORT */ #include "statement.h" #include "misc.h" // strncpy_null #include "bind.h" #include "connection.h" #include "multibyte.h" #include "qresult.h" #include "convert.h" #include "environ.h" #include "loadlib.h" #include #include #include #include "pgapifunc.h" #define PRN_NULLCHECK /* Map sql commands to statement types */ static const struct { int type; char *s; } Statement_Type[] = { { STMT_TYPE_SELECT, "SELECT" } ,{ STMT_TYPE_INSERT, "INSERT" } ,{ STMT_TYPE_UPDATE, "UPDATE" } ,{ STMT_TYPE_DELETE, "DELETE" } ,{ STMT_TYPE_PROCCALL, "{" } ,{ STMT_TYPE_SET, "SET" } ,{ STMT_TYPE_RESET, "RESET" } ,{ STMT_TYPE_CREATE, "CREATE" } ,{ STMT_TYPE_DECLARE, "DECLARE" } ,{ STMT_TYPE_FETCH, "FETCH" } ,{ STMT_TYPE_MOVE, "MOVE" } ,{ STMT_TYPE_CLOSE, "CLOSE" } ,{ STMT_TYPE_PREPARE, "PREPARE" } ,{ STMT_TYPE_EXECUTE, "EXECUTE" } ,{ STMT_TYPE_DEALLOCATE, "DEALLOCATE" } ,{ STMT_TYPE_DROP, "DROP" } ,{ STMT_TYPE_START, "BEGIN" } ,{ STMT_TYPE_START, "START" } ,{ STMT_TYPE_TRANSACTION, "SAVEPOINT" } ,{ STMT_TYPE_TRANSACTION, "RELEASE" } ,{ STMT_TYPE_TRANSACTION, "COMMIT" } ,{ STMT_TYPE_TRANSACTION, "END" } ,{ STMT_TYPE_TRANSACTION, "ROLLBACK" } ,{ STMT_TYPE_TRANSACTION, "ABORT" } ,{ STMT_TYPE_LOCK, "LOCK" } ,{ STMT_TYPE_ALTER, "ALTER" } ,{ STMT_TYPE_GRANT, "GRANT" } ,{ STMT_TYPE_REVOKE, "REVOKE" } ,{ STMT_TYPE_COPY, "COPY" } ,{ STMT_TYPE_ANALYZE, "ANALYZE" } ,{ STMT_TYPE_NOTIFY, "NOTIFY" } ,{ STMT_TYPE_EXPLAIN, "EXPLAIN" } /* * Special-commands that cannot be run in a transaction block. This isn't * as granular as it could be. VACUUM can never be run in a transaction * block, but some variants of REINDEX and CLUSTER can be. CHECKPOINT * doesn't throw an error if you do, but it cannot be rolled back so * there's no point in beginning a new transaction for it. */ ,{ STMT_TYPE_SPECIAL, "VACUUM" } ,{ STMT_TYPE_SPECIAL, "REINDEX" } ,{ STMT_TYPE_SPECIAL, "CLUSTER" } ,{ STMT_TYPE_SPECIAL, "CHECKPOINT" } ,{ STMT_TYPE_WITH, "WITH" } ,{ 0, NULL } }; RETCODE SQL_API PGAPI_AllocStmt(HDBC hdbc, HSTMT FAR * phstmt, UDWORD flag) { CSTR func = "PGAPI_AllocStmt"; ConnectionClass *conn = (ConnectionClass *) hdbc; StatementClass *stmt; ARDFields *ardopts; mylog("%s: entering...\n", func); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } stmt = SC_Constructor(conn); mylog("**** PGAPI_AllocStmt: hdbc = %p, stmt = %p\n", hdbc, stmt); if (!stmt) { CC_set_error(conn, CONN_STMT_ALLOC_ERROR, "No more memory to allocate a further SQL-statement", func); *phstmt = SQL_NULL_HSTMT; return SQL_ERROR; } if (!CC_add_statement(conn, stmt)) { CC_set_error(conn, CONN_STMT_ALLOC_ERROR, "Maximum number of statements exceeded.", func); SC_Destructor(stmt); *phstmt = SQL_NULL_HSTMT; return SQL_ERROR; } *phstmt = (HSTMT) stmt; stmt->iflag = flag; /* Copy default statement options based from Connection options */ if (0 != (PODBC_INHERIT_CONNECT_OPTIONS & flag)) { stmt->options = stmt->options_orig = conn->stmtOptions; stmt->ardi.ardopts = conn->ardOptions; } else { InitializeStatementOptions(&stmt->options_orig); stmt->options = stmt->options_orig; InitializeARDFields(&stmt->ardi.ardopts); } ardopts = SC_get_ARDF(stmt); ARD_AllocBookmark(ardopts); stmt->stmt_size_limit = CC_get_max_query_len(conn); /* Save the handle for later */ stmt->phstmt = phstmt; return SQL_SUCCESS; } RETCODE SQL_API PGAPI_FreeStmt(HSTMT hstmt, SQLUSMALLINT fOption) { CSTR func = "PGAPI_FreeStmt"; StatementClass *stmt = (StatementClass *) hstmt; mylog("%s: entering...hstmt=%p, fOption=%hi\n", func, hstmt, fOption); if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } SC_clear_error(stmt); if (fOption == SQL_DROP) { ConnectionClass *conn = stmt->hdbc; /* Remove the statement from the connection's statement list */ if (conn) { QResultClass *res; if (STMT_EXECUTING == stmt->status) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Statement is currently executing a transaction.", func); return SQL_ERROR; /* stmt may be executing a transaction */ } /* * Before dropping the statement, sync and discard * the response from the server for the pending * extended query. */ if (NULL != conn->sock && stmt == conn->stmt_in_extquery) QR_Destructor(SendSyncAndReceive(stmt, NULL, "finish the pending query")); conn->stmt_in_extquery = NULL; /* for safety */ /* * Free any cursors and discard any result info. * Don't detach the statement from the connection * before freeing the associated cursors. Otherwise * CC_cursor_count() would get wrong results. */ res = SC_get_Result(stmt); QR_Destructor(res); SC_init_Result(stmt); if (!CC_remove_statement(conn, stmt)) { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Statement is currently executing a transaction.", func); return SQL_ERROR; /* stmt may be executing a * transaction */ } } if (stmt->execute_delegate) { PGAPI_FreeStmt(stmt->execute_delegate, SQL_DROP); stmt->execute_delegate = NULL; } if (stmt->execute_parent) stmt->execute_parent->execute_delegate = NULL; /* Destroy the statement and free any results, cursors, etc. */ SC_Destructor(stmt); } else if (fOption == SQL_UNBIND) SC_unbind_cols(stmt); else if (fOption == SQL_CLOSE) { /* * this should discard all the results, but leave the statement * itself in place (it can be executed again) */ stmt->transition_status = STMT_TRANSITION_ALLOCATED; if (stmt->execute_delegate) { PGAPI_FreeStmt(stmt->execute_delegate, SQL_DROP); stmt->execute_delegate = NULL; } if (!SC_recycle_statement(stmt)) { return SQL_ERROR; } } else if (fOption == SQL_RESET_PARAMS) SC_free_params(stmt, STMT_FREE_PARAMS_ALL); else { SC_set_error(stmt, STMT_OPTION_OUT_OF_RANGE_ERROR, "Invalid option passed to PGAPI_FreeStmt.", func); return SQL_ERROR; } return SQL_SUCCESS; } /* * StatementClass implementation */ void InitializeStatementOptions(StatementOptions *opt) { memset(opt, 0, sizeof(StatementOptions)); opt->maxRows = 0; /* driver returns all rows */ opt->maxLength = 0; /* driver returns all data for char/binary */ opt->keyset_size = 0; /* fully keyset driven is the default */ opt->scroll_concurrency = SQL_CONCUR_READ_ONLY; opt->cursor_type = SQL_CURSOR_FORWARD_ONLY; opt->retrieve_data = SQL_RD_ON; opt->use_bookmarks = SQL_UB_OFF; #if (ODBCVER >= 0x0300) opt->metadata_id = SQL_FALSE; #endif /* ODBCVER */ } static void SC_clear_parse_status(StatementClass *self, ConnectionClass *conn) { self->parse_status = STMT_PARSE_NONE; if (PG_VERSION_LT(conn, 7.2)) { SC_set_checked_hasoids(self, TRUE); self->num_key_fields = PG_NUM_NORMAL_KEYS; } } static void SC_init_discard_output_params(StatementClass *self) { ConnectionClass *conn = SC_get_conn(self); if (!conn) return; self->discard_output_params = 0; if (!conn->connInfo.use_server_side_prepare) self->discard_output_params = 1; } static void SC_init_parse_method(StatementClass *self) { ConnectionClass *conn = SC_get_conn(self); self->parse_method = 0; if (!conn) return; if (0 == (PODBC_EXTERNAL_STATEMENT & self->iflag)) return; if (self->catalog_result) return; if (conn->connInfo.drivers.parse) SC_set_parse_forced(self); if (self->multi_statement <= 0 && conn->connInfo.disallow_premature) SC_set_parse_tricky(self); } StatementClass * SC_Constructor(ConnectionClass *conn) { StatementClass *rv; rv = (StatementClass *) malloc(sizeof(StatementClass)); if (rv) { rv->hdbc = conn; rv->phstmt = NULL; rv->result = NULL; rv->curres = NULL; rv->catalog_result = FALSE; rv->prepare = NON_PREPARE_STATEMENT; rv->prepared = NOT_YET_PREPARED; rv->status = STMT_ALLOCATED; rv->internal = FALSE; rv->iflag = 0; rv->plan_name = NULL; rv->transition_status = STMT_TRANSITION_UNALLOCATED; rv->multi_statement = -1; /* unknown */ rv->num_params = -1; /* unknown */ rv->__error_message = NULL; rv->__error_number = 0; rv->pgerror = NULL; rv->statement = NULL; rv->stmt_with_params = NULL; rv->load_statement = NULL; rv->execute_statement = NULL; rv->stmt_size_limit = -1; rv->statement_type = STMT_TYPE_UNKNOWN; rv->currTuple = -1; rv->rowset_start = 0; SC_set_rowset_start(rv, -1, FALSE); rv->current_col = -1; rv->bind_row = 0; rv->from_pos = rv->where_pos = -1; rv->last_fetch_count = rv->last_fetch_count_include_ommitted = 0; rv->save_rowset_size = -1; rv->data_at_exec = -1; rv->current_exec_param = -1; rv->exec_start_row = -1; rv->exec_end_row = -1; rv->exec_current_row = -1; rv->put_data = FALSE; rv->ref_CC_error = FALSE; rv->lock_CC_for_rb = 0; rv->join_info = 0; rv->curr_param_result = 0; SC_init_parse_method(rv); rv->lobj_fd = -1; INIT_NAME(rv->cursor_name); /* Parse Stuff */ rv->ti = NULL; rv->ntab = 0; rv->num_key_fields = -1; /* unknown */ SC_clear_parse_status(rv, conn); rv->proc_return = -1; SC_init_discard_output_params(rv); rv->cancel_info = 0; /* Clear Statement Options -- defaults will be set in AllocStmt */ memset(&rv->options, 0, sizeof(StatementOptions)); InitializeEmbeddedDescriptor((DescriptorClass *)&(rv->ardi), rv, SQL_ATTR_APP_ROW_DESC); InitializeEmbeddedDescriptor((DescriptorClass *)&(rv->apdi), rv, SQL_ATTR_APP_PARAM_DESC); InitializeEmbeddedDescriptor((DescriptorClass *)&(rv->irdi), rv, SQL_ATTR_IMP_ROW_DESC); InitializeEmbeddedDescriptor((DescriptorClass *)&(rv->ipdi), rv, SQL_ATTR_IMP_PARAM_DESC); rv->pre_executing = FALSE; rv->inaccurate_result = FALSE; rv->miscinfo = 0; rv->rbonerr = 0; SC_reset_updatable(rv); rv->diag_row_count = 0; rv->stmt_time = 0; rv->execute_delegate = NULL; rv->execute_parent = NULL; rv->allocated_callbacks = 0; rv->num_callbacks = 0; rv->callbacks = NULL; GetDataInfoInitialize(SC_get_GDTI(rv)); PutDataInfoInitialize(SC_get_PDTI(rv)); INIT_STMT_CS(rv); } return rv; } char SC_Destructor(StatementClass *self) { CSTR func = "SC_Destrcutor"; QResultClass *res = SC_get_Result(self); if (!self) return FALSE; mylog("SC_Destructor: self=%p, self->result=%p, self->hdbc=%p\n", self, res, self->hdbc); SC_clear_error(self); if (STMT_EXECUTING == self->status) { SC_set_error(self, STMT_SEQUENCE_ERROR, "Statement is currently executing a transaction.", func); return FALSE; } if (res) { if (!self->hdbc) res->conn = NULL; /* prevent any dbase activity */ QR_Destructor(res); } SC_initialize_stmts(self, TRUE); /* Free the parsed table information */ SC_initialize_cols_info(self, FALSE, TRUE); NULL_THE_NAME(self->cursor_name); /* Free the parsed field information */ DC_Destructor((DescriptorClass *) SC_get_ARDi(self)); DC_Destructor((DescriptorClass *) SC_get_APDi(self)); DC_Destructor((DescriptorClass *) SC_get_IRDi(self)); DC_Destructor((DescriptorClass *) SC_get_IPDi(self)); GDATA_unbind_cols(SC_get_GDTI(self), TRUE); PDATA_free_params(SC_get_PDTI(self), STMT_FREE_PARAMS_ALL); if (self->__error_message) free(self->__error_message); if (self->pgerror) ER_Destructor(self->pgerror); cancelNeedDataState(self); if (self->callbacks) free(self->callbacks); DELETE_STMT_CS(self); free(self); mylog("SC_Destructor: EXIT\n"); return TRUE; } void SC_init_Result(StatementClass *self) { self->result = self->curres = NULL; self->curr_param_result = 0; mylog("SC_init_Result(%x)", self); } void SC_set_Result(StatementClass *self, QResultClass *res) { if (res != self->result) { mylog("SC_set_Result(%x, %x)", self, res); QR_Destructor(self->result); self->result = self->curres = res; if (NULL != res) self->curr_param_result = 1; } } void SC_forget_unnamed(StatementClass *self) { if (PREPARED_TEMPORARILY == self->prepared) { SC_set_prepared(self, ONCE_DESCRIBED); if (FALSE && !SC_IsExecuting(self)) { QResultClass *res = SC_get_Curres(self); if (NULL != res && !res->dataFilled && !QR_is_fetching_tuples(res)) SC_set_Result(self, NULL); } } } /* * Free parameters and free the memory from the * data-at-execution parameters that was allocated in SQLPutData. */ void SC_free_params(StatementClass *self, char option) { if (option != STMT_FREE_PARAMS_DATA_AT_EXEC_ONLY) { APD_free_params(SC_get_APDF(self), option); IPD_free_params(SC_get_IPDF(self), option); } PDATA_free_params(SC_get_PDTI(self), option); self->data_at_exec = -1; self->current_exec_param = -1; self->put_data = FALSE; if (option == STMT_FREE_PARAMS_ALL) { self->exec_start_row = -1; self->exec_end_row = -1; self->exec_current_row = -1; } } int statement_type(const char *statement) { int i; /* ignore leading whitespace in query string */ while (*statement && (isspace((UCHAR) *statement) || *statement == '(')) statement++; for (i = 0; Statement_Type[i].s; i++) if (!strnicmp(statement, Statement_Type[i].s, strlen(Statement_Type[i].s))) return Statement_Type[i].type; return STMT_TYPE_OTHER; } void SC_set_planname(StatementClass *stmt, const char *plan_name) { if (stmt->plan_name) free(stmt->plan_name); if (plan_name && plan_name[0]) stmt->plan_name = strdup(plan_name); else stmt->plan_name = NULL; } void SC_set_rowset_start(StatementClass *stmt, SQLLEN start, BOOL valid_base) { QResultClass *res = SC_get_Curres(stmt); SQLLEN incr = start - stmt->rowset_start; inolog("%p->SC_set_rowstart " FORMAT_LEN "->" FORMAT_LEN "(%s) ", stmt, stmt->rowset_start, start, valid_base ? "valid" : "unknown"); if (res != NULL) { BOOL valid = QR_has_valid_base(res); inolog(":(%p)QR is %s", res, QR_has_valid_base(res) ? "valid" : "unknown"); if (valid) { if (valid_base) QR_inc_rowstart_in_cache(res, incr); else QR_set_no_valid_base(res); } else if (valid_base) { QR_set_has_valid_base(res); if (start < 0) QR_set_rowstart_in_cache(res, -1); else QR_set_rowstart_in_cache(res, start); } if (!QR_get_cursor(res)) res->key_base = start; inolog(":(%p)QR result=" FORMAT_LEN "(%s)", res, QR_get_rowstart_in_cache(res), QR_has_valid_base(res) ? "valid" : "unknown"); } stmt->rowset_start = start; inolog(":stmt result=" FORMAT_LEN "\n", stmt->rowset_start); } void SC_inc_rowset_start(StatementClass *stmt, SQLLEN inc) { SQLLEN start = stmt->rowset_start + inc; SC_set_rowset_start(stmt, start, TRUE); } int SC_set_current_col(StatementClass *stmt, int col) { if (col == stmt->current_col) return col; if (col >= 0) reset_a_getdata_info(SC_get_GDTI(stmt), col + 1); stmt->current_col = col; return stmt->current_col; } void SC_set_prepared(StatementClass *stmt, int prepared) { if (prepared == stmt->prepared) ; else if (NOT_YET_PREPARED == prepared && PREPARED_PERMANENTLY == stmt->prepared) { ConnectionClass *conn = SC_get_conn(stmt); if (conn) { ENTER_CONN_CS(conn); if (CONN_CONNECTED == conn->status) { if (CC_is_in_error_trans(conn)) { CC_mark_a_object_to_discard(conn, 's', stmt->plan_name); } else { QResultClass *res; char dealloc_stmt[128]; sprintf(dealloc_stmt, "DEALLOCATE \"%s\"", stmt->plan_name); res = CC_send_query(conn, dealloc_stmt, NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL); QR_Destructor(res); } } LEAVE_CONN_CS(conn); } } if (NOT_YET_PREPARED == prepared) SC_set_planname(stmt, NULL); stmt->prepared = prepared; } /* * Initialize stmt_with_params, load_statement and execute_statement * member pointer deallocating corresponding prepared plan. * Also initialize statement member pointer if specified. */ RETCODE SC_initialize_stmts(StatementClass *self, BOOL initializeOriginal) { ConnectionClass *conn = SC_get_conn(self); if (self->lock_CC_for_rb > 0) { while (self->lock_CC_for_rb > 0) { LEAVE_CONN_CS(conn); self->lock_CC_for_rb--; } } if (initializeOriginal) { if (self->statement) { free(self->statement); self->statement = NULL; } if (self->execute_statement) { free(self->execute_statement); self->execute_statement = NULL; } self->prepare = NON_PREPARE_STATEMENT; SC_set_prepared(self, NOT_YET_PREPARED); self->statement_type = STMT_TYPE_UNKNOWN; /* unknown */ self->multi_statement = -1; /* unknown */ self->num_params = -1; /* unknown */ self->proc_return = -1; /* unknown */ self->join_info = 0; SC_init_parse_method(self); SC_init_discard_output_params(self); } if (self->stmt_with_params) { free(self->stmt_with_params); self->stmt_with_params = NULL; } if (self->load_statement) { free(self->load_statement); self->load_statement = NULL; } return 0; } BOOL SC_opencheck(StatementClass *self, const char *func) { QResultClass *res; if (!self) return FALSE; if (self->status == STMT_EXECUTING) { SC_set_error(self, STMT_SEQUENCE_ERROR, "Statement is currently executing a transaction.", func); return TRUE; } /* * We can dispose the result of PREMATURE execution any time. */ if (self->prepare && self->status == STMT_PREMATURE) { mylog("SC_opencheck: self->prepare && self->status == STMT_PREMATURE\n"); return FALSE; } if (res = SC_get_Curres(self), NULL != res) { if (QR_command_maybe_successful(res) && res->backend_tuples) { SC_set_error(self, STMT_SEQUENCE_ERROR, "The cursor is open.", func); return TRUE; } } return FALSE; } RETCODE SC_initialize_and_recycle(StatementClass *self) { SC_initialize_stmts(self, TRUE); if (!SC_recycle_statement(self)) return SQL_ERROR; return SQL_SUCCESS; } /* * Called from SQLPrepare if STMT_PREMATURE, or * from SQLExecute if STMT_FINISHED, or * from SQLFreeStmt(SQL_CLOSE) */ char SC_recycle_statement(StatementClass *self) { CSTR func = "SC_recycle_statement"; ConnectionClass *conn; QResultClass *res; mylog("%s: self= %p\n", func, self); SC_clear_error(self); /* This would not happen */ if (self->status == STMT_EXECUTING) { SC_set_error(self, STMT_SEQUENCE_ERROR, "Statement is currently executing a transaction.", func); return FALSE; } conn = SC_get_conn(self); switch (self->status) { case STMT_ALLOCATED: /* this statement does not need to be recycled */ return TRUE; case STMT_READY: break; case STMT_PREMATURE: /* * Premature execution of the statement might have caused the * start of a transaction. If so, we have to rollback that * transaction. */ if (CC_loves_visible_trans(conn) && CC_is_in_trans(conn)) { if (SC_is_pre_executable(self) && !SC_is_parse_tricky(self)) { /* CC_abort(conn); */ } } break; case STMT_FINISHED: break; default: SC_set_error(self, STMT_INTERNAL_ERROR, "An internal error occured while recycling statements", func); return FALSE; } switch (self->prepared) { case NOT_YET_PREPARED: case ONCE_DESCRIBED: /* Free the parsed table/field information */ SC_initialize_cols_info(self, TRUE, TRUE); inolog("SC_clear_parse_status\n"); SC_clear_parse_status(self, conn); break; } /* Free any cursors */ if (res = SC_get_Result(self), res) { switch (self->prepared) { case PREPARED_PERMANENTLY: case PREPARED_TEMPORARILY: QR_close_result(res, FALSE); break; default: QR_Destructor(res); SC_init_Result(self); break; } } self->inaccurate_result = FALSE; self->miscinfo = 0; /* self->rbonerr = 0; Never clear the bits here */ /* * Reset only parameters that have anything to do with results */ self->status = STMT_READY; self->catalog_result = FALSE; /* not very important */ self->currTuple = -1; SC_set_rowset_start(self, -1, FALSE); SC_set_current_col(self, -1); self->bind_row = 0; inolog("%s statement=%p ommitted=0\n", func, self); self->last_fetch_count = self->last_fetch_count_include_ommitted = 0; self->__error_message = NULL; self->__error_number = 0; self->lobj_fd = -1; /* * Free any data at exec params before the statement is executed * again. If not, then there will be a memory leak when the next * SQLParamData/SQLPutData is called. */ SC_free_params(self, STMT_FREE_PARAMS_DATA_AT_EXEC_ONLY); SC_initialize_stmts(self, FALSE); cancelNeedDataState(self); self->cancel_info = 0; /* * reset the current attr setting to the original one. */ self->options.scroll_concurrency = self->options_orig.scroll_concurrency; self->options.cursor_type = self->options_orig.cursor_type; self->options.keyset_size = self->options_orig.keyset_size; self->options.maxLength = self->options_orig.maxLength; self->options.maxRows = self->options_orig.maxRows; return TRUE; } /* * Scan the query wholly or partially (if the next_cmd param specified). * Also count the number of parameters respectviely. */ void SC_scanQueryAndCountParams(const char *query, const ConnectionClass *conn, Int4 *next_cmd, SQLSMALLINT * pcpar, po_ind_t *multi_st, po_ind_t *proc_return) { CSTR func = "SC_scanQueryAndCountParams"; char literal_quote = LITERAL_QUOTE, identifier_quote = IDENTIFIER_QUOTE, dollar_quote = DOLLAR_QUOTE; const char *sptr, *tstr, *tag = NULL; size_t taglen = 0; char tchar, bchar, escape_in_literal = '\0'; char in_literal = FALSE, in_identifier = FALSE, in_dollar_quote = FALSE, in_escape = FALSE, in_line_comment = FALSE, del_found = FALSE; int comment_level = 0; po_ind_t multi = FALSE; SQLSMALLINT num_p; encoded_str encstr; mylog("%s: entering...\n", func); num_p = 0; if (proc_return) *proc_return = 0; if (next_cmd) *next_cmd = -1; tstr = query; make_encoded_str(&encstr, conn, tstr); for (sptr = tstr, bchar = '\0'; *sptr; sptr++) { tchar = encoded_nextchar(&encstr); if (ENCODE_STATUS(encstr) != 0) /* multibyte char */ { if ((UCHAR) tchar >= 0x80) bchar = tchar; continue; } if (!multi && del_found) { if (!isspace((UCHAR) tchar)) { multi = TRUE; if (next_cmd) break; } } if (in_dollar_quote) { if (tchar == dollar_quote) { if (strncmp(sptr, tag, taglen) == 0) { in_dollar_quote = FALSE; tag = NULL; sptr += taglen; sptr--; encoded_position_shift(&encstr, taglen - 1); } } } else if (in_literal) { if (in_escape) in_escape = FALSE; else if (tchar == escape_in_literal) in_escape = TRUE; else if (tchar == literal_quote) in_literal = FALSE; } else if (in_identifier) { if (tchar == identifier_quote) in_identifier = FALSE; } else if (in_line_comment) { if (PG_LINEFEED == tchar) in_line_comment = FALSE; } else if (comment_level > 0) { if ('/' == tchar && '*' == sptr[1]) { encoded_nextchar(&encstr); sptr++; comment_level++; } else if ('*' == tchar && '/' == sptr[1]) { encoded_nextchar(&encstr); sptr++; comment_level--; } } else { if (tchar == '?') { if (0 == num_p && bchar == '{') { if (proc_return) *proc_return = 1; } num_p++; } else if (tchar == ';') { del_found = TRUE; if (next_cmd) *next_cmd = sptr - query; } else if (tchar == dollar_quote) { taglen = findTag(sptr, dollar_quote, encstr.ccsc); if (taglen > 0) { in_dollar_quote = TRUE; tag = sptr; sptr += (taglen - 1); encoded_position_shift(&encstr, taglen - 1); } else num_p++; } else if (tchar == literal_quote) { in_literal = TRUE; escape_in_literal = CC_get_escape(conn); if (!escape_in_literal) { if (LITERAL_EXT == sptr[-1]) escape_in_literal = ESCAPE_IN_LITERAL; } } else if (tchar == identifier_quote) in_identifier = TRUE; else if ('-' == tchar) { if ('-' == sptr[1]) { encoded_nextchar(&encstr); sptr++; in_line_comment = TRUE; } } else if ('/' == tchar) { if ('*' == sptr[1]) { encoded_nextchar(&encstr); sptr++; comment_level++; } } if (!isspace((UCHAR) tchar)) bchar = tchar; } } if (pcpar) *pcpar = num_p; if (multi_st) *multi_st = multi; } /* * Pre-execute a statement (for SQLPrepare/SQLDescribeCol) */ Int4 /* returns # of fields if successful */ SC_pre_execute(StatementClass *self) { Int4 num_fields = -1; QResultClass *res; mylog("SC_pre_execute: status = %d\n", self->status); res = SC_get_Curres(self); if (NULL != res) { num_fields = QR_NumResultCols(res); if (num_fields > 0 || NULL != QR_get_command(res)) return num_fields; } if (self->status == STMT_READY) { mylog(" preprocess: status = READY\n"); self->miscinfo = 0; if (SC_can_req_colinfo(self)) { char old_pre_executing = self->pre_executing; decideHowToPrepare(self, FALSE); self->inaccurate_result = FALSE; switch (SC_get_prepare_method(self)) { case NAMED_PARSE_REQUEST: case PARSE_TO_EXEC_ONCE: if (SQL_SUCCESS != prepareParameters(self)) return num_fields; break; case PARSE_REQ_FOR_INFO: if (SQL_SUCCESS != prepareParameters(self)) return num_fields; self->status = STMT_PREMATURE; self->inaccurate_result = TRUE; break; default: self->pre_executing = TRUE; PGAPI_Execute(self, 0); self->pre_executing = old_pre_executing; if (self->status == STMT_FINISHED) { mylog(" preprocess: after status = FINISHED, so set PREMATURE\n"); self->status = STMT_PREMATURE; } } if (res = SC_get_Curres(self), NULL != res) { num_fields = QR_NumResultCols(res); return num_fields; } } if (!SC_is_pre_executable(self)) { SC_set_Result(self, QR_Constructor()); QR_set_rstatus(SC_get_Result(self), PORES_TUPLES_OK); self->inaccurate_result = TRUE; self->status = STMT_PREMATURE; num_fields = 0; } } return num_fields; } /* This is only called from SQLFreeStmt(SQL_UNBIND) */ char SC_unbind_cols(StatementClass *self) { ARDFields *opts = SC_get_ARDF(self); GetDataInfo *gdata = SC_get_GDTI(self); BindInfoClass *bookmark; ARD_unbind_cols(opts, FALSE); GDATA_unbind_cols(gdata, FALSE); if (bookmark = opts->bookmark, bookmark != NULL) { bookmark->buffer = NULL; bookmark->used = NULL; } return 1; } void SC_clear_error(StatementClass *self) { QResultClass *res; self->__error_number = 0; if (self->__error_message) { free(self->__error_message); self->__error_message = NULL; } if (self->pgerror) { ER_Destructor(self->pgerror); self->pgerror = NULL; } self->diag_row_count = 0; if (res = SC_get_Curres(self), res) { QR_set_message(res, NULL); QR_set_notice(res, NULL); res->sqlstate[0] = '\0'; } self->stmt_time = 0; SC_unref_CC_error(self); } /* * This function creates an error info which is the concatenation * of the result, statement, connection, and socket messages. */ /* Map sql commands to statement types */ static const struct { int number; const char * ver3str; const char * ver2str; } Statement_sqlstate[] = { { STMT_ERROR_IN_ROW, "01S01", "01S01" }, { STMT_OPTION_VALUE_CHANGED, "01S02", "01S02" }, { STMT_ROW_VERSION_CHANGED, "01001", "01001" }, /* data changed */ { STMT_POS_BEFORE_RECORDSET, "01S06", "01S06" }, { STMT_TRUNCATED, "01004", "01004" }, /* data truncated */ { STMT_INFO_ONLY, "00000", "00000" }, /* just an information that is returned, no error */ { STMT_OK, "00000", "00000" }, /* OK */ { STMT_EXEC_ERROR, "HY000", "S1000" }, /* also a general error */ { STMT_STATUS_ERROR, "HY010", "S1010" }, { STMT_SEQUENCE_ERROR, "HY010", "S1010" }, /* Function sequence error */ { STMT_NO_MEMORY_ERROR, "HY001", "S1001" }, /* memory allocation failure */ { STMT_COLNUM_ERROR, "07009", "S1002" }, /* invalid column number */ { STMT_NO_STMTSTRING, "HY001", "S1001" }, /* having no stmtstring is also a malloc problem */ { STMT_ERROR_TAKEN_FROM_BACKEND, "HY000", "S1000" }, /* general error */ { STMT_INTERNAL_ERROR, "HY000", "S1000" }, /* general error */ { STMT_STILL_EXECUTING, "HY010", "S1010" }, { STMT_NOT_IMPLEMENTED_ERROR, "HYC00", "S1C00" }, /* == 'driver not * capable' */ { STMT_BAD_PARAMETER_NUMBER_ERROR, "07009", "S1093" }, { STMT_OPTION_OUT_OF_RANGE_ERROR, "HY092", "S1092" }, { STMT_INVALID_COLUMN_NUMBER_ERROR, "07009", "S1002" }, { STMT_RESTRICTED_DATA_TYPE_ERROR, "07006", "07006" }, { STMT_INVALID_CURSOR_STATE_ERROR, "07005", "24000" }, { STMT_CREATE_TABLE_ERROR, "42S01", "S0001" }, /* table already exists */ { STMT_NO_CURSOR_NAME, "S1015", "S1015" }, { STMT_INVALID_CURSOR_NAME, "34000", "34000" }, { STMT_INVALID_ARGUMENT_NO, "HY024", "S1009" }, /* invalid argument value */ { STMT_ROW_OUT_OF_RANGE, "HY107", "S1107" }, { STMT_OPERATION_CANCELLED, "HY008", "S1008" }, { STMT_INVALID_CURSOR_POSITION, "HY109", "S1109" }, { STMT_VALUE_OUT_OF_RANGE, "HY019", "22003" }, { STMT_OPERATION_INVALID, "HY011", "S1011" }, { STMT_PROGRAM_TYPE_OUT_OF_RANGE, "?????", "?????" }, { STMT_BAD_ERROR, "08S01", "08S01" }, /* communication link failure */ { STMT_INVALID_OPTION_IDENTIFIER, "HY092", "HY092" }, { STMT_RETURN_NULL_WITHOUT_INDICATOR, "22002", "22002" }, { STMT_INVALID_DESCRIPTOR_IDENTIFIER, "HY091", "HY091" }, { STMT_OPTION_NOT_FOR_THE_DRIVER, "HYC00", "HYC00" }, { STMT_FETCH_OUT_OF_RANGE, "HY106", "S1106" }, { STMT_COUNT_FIELD_INCORRECT, "07002", "07002" }, { STMT_INVALID_NULL_ARG, "HY009", "S1009" }, { STMT_NO_RESPONSE, "08S01", "08S01" }, { STMT_COMMUNICATION_ERROR, "08S01", "08S01" } }; static PG_ErrorInfo * SC_create_errorinfo(const StatementClass *self) { QResultClass *res = SC_get_Curres(self); ConnectionClass *conn = SC_get_conn(self); Int4 errornum; size_t pos; BOOL resmsg = FALSE, detailmsg = FALSE, msgend = FALSE; BOOL looponce, loopend; char msg[4096], *wmsg; char *ermsg = NULL, *sqlstate = NULL; PG_ErrorInfo *pgerror; if (self->pgerror) return self->pgerror; errornum = self->__error_number; if (errornum == 0) return NULL; looponce = (SC_get_Result(self) != res); msg[0] = '\0'; for (loopend = FALSE; (NULL != res) && !loopend; res = res->next) { if (looponce) loopend = TRUE; if ('\0' != res->sqlstate[0]) { if (NULL != sqlstate && strnicmp(res->sqlstate, "00", 2) == 0) continue; sqlstate = res->sqlstate; if ('0' != sqlstate[0] || '1' < sqlstate[1]) loopend = TRUE; } if (NULL != res->message) { strncpy_null(msg, res->message, sizeof(msg)); detailmsg = resmsg = TRUE; } else if (NULL != res->messageref) { strncpy_null(msg, res->messageref, sizeof(msg)); detailmsg = resmsg = TRUE; } if (msg[0]) ermsg = msg; else if (QR_get_notice(res)) { char *notice = QR_get_notice(res); size_t len = strlen(notice); if (len < sizeof(msg)) { memcpy(msg, notice, len); msg[len] = '\0'; ermsg = msg; } else { ermsg = notice; msgend = TRUE; } } } if (!msgend && (wmsg = SC_get_errormsg(self)) && wmsg[0]) { pos = strlen(msg); if (detailmsg) { msg[pos++] = ';'; msg[pos++] = '\n'; } strncpy_null(msg + pos, wmsg, sizeof(msg) - pos); ermsg = msg; detailmsg = TRUE; } if (!self->ref_CC_error) msgend = TRUE; if (conn && !msgend) { SocketClass *sock = conn->sock; const char *sockerrmsg; if (!resmsg && (wmsg = CC_get_errormsg(conn)) && wmsg[0] != '\0') { pos = strlen(msg); snprintf(&msg[pos], sizeof(msg) - pos, ";\n%s", CC_get_errormsg(conn)); } if (sock && NULL != (sockerrmsg = SOCK_get_errmsg(sock)) && '\0' != sockerrmsg[0]) { pos = strlen(msg); snprintf(&msg[pos], sizeof(msg) - pos, ";\n%s", sockerrmsg); } ermsg = msg; } pgerror = ER_Constructor(self->__error_number, ermsg); if (sqlstate) strcpy(pgerror->sqlstate, sqlstate); else if (conn) { if (!msgend && conn->sqlstate[0]) strcpy(pgerror->sqlstate, conn->sqlstate); else { EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); errornum -= LOWEST_STMT_ERROR; if (errornum < 0 || errornum >= sizeof(Statement_sqlstate) / sizeof(Statement_sqlstate[0])) { errornum = 1 - LOWEST_STMT_ERROR; } strcpy(pgerror->sqlstate, EN_is_odbc3(env) ? Statement_sqlstate[errornum].ver3str : Statement_sqlstate[errornum].ver2str); } } return pgerror; } StatementClass *SC_get_ancestor(StatementClass *stmt) { StatementClass *child = stmt, *parent; inolog("SC_get_ancestor in stmt=%p\n", stmt); for (child = stmt, parent = child->execute_parent; parent; child = parent, parent = child->execute_parent) { inolog("parent=%p\n", parent); } return child; } void SC_reset_delegate(RETCODE retcode, StatementClass *stmt) { StatementClass *delegate = stmt->execute_delegate; if (!delegate) return; PGAPI_FreeStmt(delegate, SQL_DROP); } void SC_set_error(StatementClass *self, int number, const char *message, const char *func) { if (self->__error_message) free(self->__error_message); self->__error_number = number; self->__error_message = message ? strdup(message) : NULL; if (func && number != STMT_OK && number != STMT_INFO_ONLY) SC_log_error(func, "", self); } void SC_set_errormsg(StatementClass *self, const char *message) { if (self->__error_message) free(self->__error_message); self->__error_message = message ? strdup(message) : NULL; } void SC_replace_error_with_res(StatementClass *self, int number, const char *message, const QResultClass *from_res, BOOL check) { QResultClass *self_res; BOOL repstate; inolog("SC_set_error_from_res %p->%p check=%i\n", from_res ,self, check); if (check) { if (0 == number) return; if (0 > number && /* SQL_SUCCESS_WITH_INFO */ 0 < self->__error_number) return; } self->__error_number = number; if (!check || message) { if (self->__error_message) free(self->__error_message); self->__error_message = message ? strdup(message) : NULL; } if (self->pgerror) { ER_Destructor(self->pgerror); self->pgerror = NULL; } self_res = SC_get_Curres(self); if (!self_res) return; if (self_res == from_res) return; QR_add_message(self_res, QR_get_message(from_res)); QR_add_notice(self_res, QR_get_notice(from_res)); repstate = FALSE; if (!check) repstate = TRUE; else if (from_res->sqlstate[0]) { if (!self_res->sqlstate[0] || strncmp(self_res->sqlstate, "00", 2) == 0) repstate = TRUE; else if (strncmp(from_res->sqlstate, "01", 2) >= 0) repstate = TRUE; } if (repstate) strcpy(self_res->sqlstate, from_res->sqlstate); } void SC_error_copy(StatementClass *self, const StatementClass *from, BOOL check) { QResultClass *self_res, *from_res; BOOL repstate; inolog("SC_error_copy %p->%p check=%i\n", from ,self, check); if (self == from) return; if (check) { if (0 == from->__error_number) /* SQL_SUCCESS */ return; if (0 > from->__error_number && /* SQL_SUCCESS_WITH_INFO */ 0 < self->__error_number) return; } self->__error_number = from->__error_number; if (!check || from->__error_message) { if (self->__error_message) free(self->__error_message); self->__error_message = from->__error_message ? strdup(from->__error_message) : NULL; } if (self->pgerror) { ER_Destructor(self->pgerror); self->pgerror = NULL; } self_res = SC_get_Curres(self); from_res = SC_get_Curres(from); if (!self_res || !from_res) return; QR_add_message(self_res, QR_get_message(from_res)); QR_add_notice(self_res, QR_get_notice(from_res)); repstate = FALSE; if (!check) repstate = TRUE; else if (from_res->sqlstate[0]) { if (!self_res->sqlstate[0] || strncmp(self_res->sqlstate, "00", 2) == 0) repstate = TRUE; else if (strncmp(from_res->sqlstate, "01", 2) >= 0) repstate = TRUE; } if (repstate) strcpy(self_res->sqlstate, from_res->sqlstate); } void SC_full_error_copy(StatementClass *self, const StatementClass *from, BOOL allres) { PG_ErrorInfo *pgerror; inolog("SC_full_error_copy %p->%p\n", from ,self); if (self->__error_message) { free(self->__error_message); self->__error_message = NULL; } if (from->__error_message) self->__error_message = strdup(from->__error_message); self->__error_number = from->__error_number; if (from->pgerror) { if (self->pgerror) ER_Destructor(self->pgerror); self->pgerror = ER_Dup(from->pgerror); return; } else if (!allres) return; pgerror = SC_create_errorinfo(from); if (!pgerror->__error_message[0]) { ER_Destructor(pgerror); return; } if (self->pgerror) ER_Destructor(self->pgerror); self->pgerror = pgerror; } /* Returns the next SQL error information. */ RETCODE SQL_API PGAPI_StmtError(SQLHSTMT hstmt, SQLSMALLINT RecNumber, SQLCHAR FAR * szSqlState, SQLINTEGER FAR * pfNativeError, SQLCHAR FAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT FAR * pcbErrorMsg, UWORD flag) { /* CC: return an error of a hdesc */ StatementClass *stmt = (StatementClass *) hstmt; stmt->pgerror = SC_create_errorinfo(stmt); return ER_ReturnError(&(stmt->pgerror), RecNumber, szSqlState, pfNativeError, szErrorMsg, cbErrorMsgMax, pcbErrorMsg, flag); } time_t SC_get_time(StatementClass *stmt) { if (!stmt) return time(NULL); if (0 == stmt->stmt_time) stmt->stmt_time = time(NULL); return stmt->stmt_time; } /* * Currently, the driver offers very simple bookmark support -- it is * just the current row number. But it could be more sophisticated * someday, such as mapping a key to a 32 bit value */ SQLULEN SC_get_bookmark(StatementClass *self) { return SC_make_bookmark(self->currTuple); } RETCODE SC_fetch(StatementClass *self) { CSTR func = "SC_fetch"; QResultClass *res = SC_get_Curres(self); ARDFields *opts; GetDataInfo *gdata; int retval; RETCODE result; Int2 num_cols, lf; OID type; int atttypmod; char *value; ColumnInfoClass *coli; BindInfoClass *bookmark; BOOL useCursor; /* TupleField *tupleField; */ inolog("%s statement=%p res=%x ommitted=0\n", func, self, res); self->last_fetch_count = self->last_fetch_count_include_ommitted = 0; if (!res) return SQL_ERROR; coli = QR_get_fields(res); /* the column info */ mylog("fetch_cursor=%d, %p->total_read=%d\n", SC_is_fetchcursor(self), res, res->num_total_read); useCursor = (SC_is_fetchcursor(self) && (NULL != QR_get_cursor(res))); if (!useCursor) { if (self->currTuple >= (Int4) QR_get_num_total_tuples(res) - 1 || (self->options.maxRows > 0 && self->currTuple == self->options.maxRows - 1)) { /* * if at the end of the tuples, return "no data found" and set * the cursor past the end of the result set */ self->currTuple = QR_get_num_total_tuples(res); return SQL_NO_DATA_FOUND; } mylog("**** %s: non-cursor_result\n", func); (self->currTuple)++; } else { int lastMessageType; /* read from the cache or the physical next tuple */ retval = QR_next_tuple(res, self, &lastMessageType); if (retval < 0) { mylog("**** %s: end_tuples\n", func); if (QR_get_cursor(res) && SQL_CURSOR_FORWARD_ONLY == self->options.cursor_type && QR_once_reached_eof(res)) QR_close(res); return SQL_NO_DATA_FOUND; } else if (retval > 0) (self->currTuple)++; /* all is well */ else { ConnectionClass *conn = SC_get_conn(self); mylog("%s: error\n", func); switch (conn->status) { case CONN_NOT_CONNECTED: case CONN_DOWN: SC_set_error(self, STMT_BAD_ERROR, "Error fetching next row", func); break; default: switch (QR_get_rstatus(res)) { case PORES_NO_MEMORY_ERROR: SC_set_error(self, STMT_NO_MEMORY_ERROR, "memory allocation error???", __FUNCTION__); break; case PORES_BAD_RESPONSE: SC_set_error(self, STMT_COMMUNICATION_ERROR, "communication error occured", __FUNCTION__); break; default: SC_set_error(self, STMT_EXEC_ERROR, "Error fetching next row", __FUNCTION__); break; } } return SQL_ERROR; } } if (QR_haskeyset(res)) { SQLLEN kres_ridx; kres_ridx = GIdx2KResIdx(self->currTuple, self, res); if (kres_ridx >= 0 && kres_ridx < res->num_cached_keys) { UWORD pstatus = res->keyset[kres_ridx].status; inolog("SC_ pstatus[%d]=%hx fetch_count=" FORMAT_LEN "\n", kres_ridx, pstatus, self->last_fetch_count); if (0 != (pstatus & (CURS_SELF_DELETING | CURS_SELF_DELETED))) return SQL_SUCCESS_WITH_INFO; if (SQL_ROW_DELETED != (pstatus & KEYSET_INFO_PUBLIC) && 0 != (pstatus & CURS_OTHER_DELETED)) { return SQL_SUCCESS_WITH_INFO; } if (0 != (CURS_NEEDS_REREAD & pstatus)) { UWORD qcount; result = SC_pos_reload(self, self->currTuple, &qcount, 0); if (SQL_ERROR == result) return result; pstatus &= ~CURS_NEEDS_REREAD; } } } num_cols = QR_NumPublicResultCols(res); result = SQL_SUCCESS; self->last_fetch_count++; inolog("%s: stmt=%p ommitted++\n", func, self); self->last_fetch_count_include_ommitted++; opts = SC_get_ARDF(self); /* * If the bookmark column was bound then return a bookmark. Since this * is used with SQLExtendedFetch, and the rowset size may be greater * than 1, and an application can use row or column wise binding, use * the code in copy_and_convert_field() to handle that. */ if ((bookmark = opts->bookmark) && bookmark->buffer) { char buf[32]; SQLLEN offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0; sprintf(buf, FORMAT_ULEN, SC_get_bookmark(self)); SC_set_current_col(self, -1); result = copy_and_convert_field(self, 0, PG_UNSPECIFIED, buf, SQL_C_ULONG, 0, bookmark->buffer + offset, 0, LENADDR_SHIFT(bookmark->used, offset), LENADDR_SHIFT(bookmark->used, offset)); } if (self->options.retrieve_data == SQL_RD_OFF) /* data isn't required */ return SQL_SUCCESS; /* The following adjustment would be needed after SQLMoreResults() */ if (opts->allocated < num_cols) extend_column_bindings(opts, num_cols); gdata = SC_get_GDTI(self); if (gdata->allocated != opts->allocated) extend_getdata_info(gdata, opts->allocated, TRUE); for (lf = 0; lf < num_cols; lf++) { mylog("fetch: cols=%d, lf=%d, opts = %p, opts->bindings = %p, buffer[] = %p\n", num_cols, lf, opts, opts->bindings, opts->bindings[lf].buffer); /* reset for SQLGetData */ gdata->gdata[lf].data_left = -1; if (NULL == opts->bindings) continue; if (opts->bindings[lf].buffer != NULL) { /* this column has a binding */ /* type = QR_get_field_type(res, lf); */ type = CI_get_oid(coli, lf); /* speed things up */ atttypmod = CI_get_atttypmod(coli, lf); /* speed things up */ mylog("type = %d, atttypmod = %d\n", type, atttypmod); if (useCursor) value = QR_get_value_backend(res, lf); else { SQLLEN curt = GIdx2CacheIdx(self->currTuple, self, res); inolog("%p->base=%d curr=%d st=%d valid=%d\n", res, QR_get_rowstart_in_cache(res), self->currTuple, SC_get_rowset_start(self), QR_has_valid_base(res)); inolog("curt=%d\n", curt); value = QR_get_value_backend_row(res, curt, lf); } mylog("value = '%s'\n", (value == NULL) ? "" : value); retval = copy_and_convert_field_bindinfo(self, type, atttypmod, value, lf); mylog("copy_and_convert: retval = %d\n", retval); switch (retval) { case COPY_OK: break; /* OK, do next bound column */ case COPY_UNSUPPORTED_TYPE: SC_set_error(self, STMT_RESTRICTED_DATA_TYPE_ERROR, "Received an unsupported type from Postgres.", func); result = SQL_ERROR; break; case COPY_UNSUPPORTED_CONVERSION: SC_set_error(self, STMT_RESTRICTED_DATA_TYPE_ERROR, "Couldn't handle the necessary data type conversion.", func); result = SQL_ERROR; break; case COPY_RESULT_TRUNCATED: SC_set_error(self, STMT_TRUNCATED, "Fetched item was truncated.", func); qlog("The %dth item was truncated\n", lf + 1); qlog("The buffer size = %d", opts->bindings[lf].buflen); qlog(" and the value is '%s'\n", value); result = SQL_SUCCESS_WITH_INFO; break; /* error msg already filled in */ case COPY_GENERAL_ERROR: result = SQL_ERROR; break; /* This would not be meaningful in SQLFetch. */ case COPY_NO_DATA_FOUND: break; default: SC_set_error(self, STMT_INTERNAL_ERROR, "Unrecognized return value from copy_and_convert_field.", func); result = SQL_ERROR; break; } } } return result; } #include "dlg_specific.h" RETCODE SC_execute(StatementClass *self) { CSTR func = "SC_execute"; CSTR fetch_cmd = "fetch"; ConnectionClass *conn; IPDFields *ipdopts; char was_ok, was_nonfatal; QResultClass *res = NULL; Int2 oldstatus, numcols; QueryInfo qi; ConnInfo *ci; UDWORD qflag = 0; BOOL is_in_trans, issue_begin, has_out_para; BOOL use_extended_protocol; int func_cs_count = 0, i; BOOL useCursor, isSelectType; conn = SC_get_conn(self); ci = &(conn->connInfo); /* Begin a transaction if one is not already in progress */ /* * Basically we don't have to begin a transaction in autocommit mode * because Postgres backend runs in autocomit mode. We issue "BEGIN" * in the following cases. 1) we use declare/fetch and the statement * is SELECT (because declare/fetch must be called in a transaction). * 2) we are in autocommit off state and the statement isn't of type * OTHER. */ #define return DONT_CALL_RETURN_FROM_HERE??? ENTER_INNER_CONN_CS(conn, func_cs_count); oldstatus = conn->status; if (CONN_EXECUTING == conn->status) { SC_set_error(self, STMT_SEQUENCE_ERROR, "Connection is already in use.", func); mylog("%s: problem with connection\n", func); goto cleanup; } is_in_trans = CC_is_in_trans(conn); if ((useCursor = SC_is_fetchcursor(self))) { QResultClass *curres = SC_get_Curres(self); if (NULL != curres && curres->dataFilled) useCursor = (NULL != QR_get_cursor(curres)); } /* issue BEGIN ? */ issue_begin = TRUE; if (self->internal) issue_begin = FALSE; else if (is_in_trans) { issue_begin = FALSE; if (STMT_TYPE_START == self->statement_type && CC_does_autocommit(conn)) { CC_commit(conn); is_in_trans = CC_is_in_trans(conn); } } else if (CC_does_autocommit(conn) && (!useCursor /* || SC_is_with_hold(self) thiw would lose the performance */ )) issue_begin = FALSE; else if (self->statement_type == STMT_TYPE_SPECIAL) { /* * Some utility commands like VACUUM cannot be run in a transaction * block, so don't begin one even if auto-commit mode is disabled. * * An application should never issue an explicit BEGIN when * auto-commit mode is disabled (probably not even when it's enabled, * actually). We used to also suppress the implicit BEGIN when the * statement was of STMT_TYPE_START type, ie. if the application * issued an explicit BEGIN, but that actually seems like a bad idea. * First of all, if you issue a BEGIN twice the backend will give a * warning which can be helpful to spot mistakes in the application * (because it shouldn't be doing that). */ issue_begin = FALSE; } if (issue_begin) { mylog(" about to begin a transaction on statement = %p\n", self); if (PG_VERSION_GE(conn, 7.1)) qflag |= GO_INTO_TRANSACTION; else if (!CC_begin(conn)) { SC_set_error(self, STMT_EXEC_ERROR, "Could not begin a transaction", func); goto cleanup; } } /* self->status = STMT_EXECUTING; */ if (!SC_SetExecuting(self, TRUE)) { SC_set_error(self, STMT_OPERATION_CANCELLED, "Cancel Reuest Accepted", func); goto cleanup; } conn->status = CONN_EXECUTING; /* If it's a SELECT statement, use a cursor. */ /* * Note that the declare cursor has already been prepended to the * statement */ /* in copy_statement... */ use_extended_protocol = FALSE; switch (self->prepared) { case PREPARING_PERMANENTLY: case PREPARED_PERMANENTLY: if (PROTOCOL_74(ci)) use_extended_protocol = TRUE; break; case PREPARING_TEMPORARILY: case PREPARED_TEMPORARILY: if (!issue_begin) { switch (SC_get_prepare_method(self)) { #ifndef BYPASS_ONESHOT_PLAN_EXECUTION case PARSE_TO_EXEC_ONCE: #endif /* BYPASS_ONESHOT_PLAN_EXECUTION */ case NAMED_PARSE_REQUEST: use_extended_protocol = TRUE; break; } } if (use_extended_protocol) break; /* fall through */ case ONCE_DESCRIBED: SC_forget_unnamed(self); { QResultClass *pres = SC_get_Result(self); if (NULL != pres && NULL == QR_get_command(pres)) SC_set_Result(self, NULL); /* discard the parsed information */ } break; } isSelectType = (SC_may_use_cursor(self) || self->statement_type == STMT_TYPE_PROCCALL); if (use_extended_protocol) { char *plan_name = self->plan_name; if (issue_begin) CC_begin(conn); if (!plan_name) plan_name = ""; if (!SendBindRequest(self, plan_name)) { if (SC_get_errornumber(self) <= 0) SC_set_error(self, STMT_EXEC_ERROR, "Bind request error", func); goto cleanup; } if (!SendExecuteRequest(self, plan_name, 0)) { if (SC_get_errornumber(self) <= 0) SC_set_error(self, STMT_EXEC_ERROR, "Execute request error", func); goto cleanup; } for (res = SC_get_Result(self); NULL != res && NULL != res->next; res = res->next) ; inolog("get_Result=%p %p %d\n", res, SC_get_Result(self), self->curr_param_result); if (!(res = SendSyncAndReceive(self, self->curr_param_result ? res : NULL, "bind_and_execute"))) { if (SC_get_errornumber(self) <= 0) SC_set_error(self, STMT_NO_RESPONSE, "Could not receive the response, communication down ??", func); CC_on_abort(conn, CONN_DEAD); goto cleanup; } } else if (isSelectType) { char fetch[128]; const char *appendq = NULL; QueryInfo *qryi = NULL; qflag |= (SQL_CONCUR_READ_ONLY != self->options.scroll_concurrency ? CREATE_KEYSET : 0); mylog(" Sending SELECT statement on stmt=%p, cursor_name='%s' qflag=%d,%d\n", self, SC_cursor_name(self), qflag, self->options.scroll_concurrency); /* send the declare/select */ if (useCursor) { qi.result_in = NULL; qi.cursor = SC_cursor_name(self); qi.row_size = ci->drivers.fetch_max; sprintf(fetch, "%s " FORMAT_LEN " in \"%s\"", fetch_cmd, qi.row_size, SC_cursor_name(self)); qryi = &qi; appendq = fetch; if (0 != (ci->extra_opts & BIT_IGNORE_ROUND_TRIP_TIME)) qflag |= IGNORE_ROUND_TRIP; } res = CC_send_query_append(conn, self->stmt_with_params, qryi, qflag, SC_get_ancestor(self), appendq); if (useCursor && QR_command_maybe_successful(res)) { /* * If we sent a DECLARE CURSOR + FETCH, throw away the result of * the DECLARE CURSOR statement, and only return the result of the * FETCH to the caller. However, if we received any NOTICEs as * part of the DECLARE CURSOR, carry those over. */ if (appendq) { QResultClass *qres, *nres; for (qres = res; qres;) { if (qres->command && strnicmp(qres->command, fetch_cmd, 5) == 0) { res = qres; break; } nres = qres->next; if (nres && QR_get_notice(qres) != NULL) { if (QR_command_successful(nres) && QR_command_nonfatal(qres)) { QR_set_rstatus(nres, PORES_NONFATAL_ERROR); } QR_add_notice(nres, QR_get_notice(qres)); } qres->next = NULL; QR_Destructor(qres); qres = nres; } } if (res && SC_is_with_hold(self)) QR_set_withhold(res); } mylog(" done sending the query:\n"); } else { /* not a SELECT statement so don't use a cursor */ mylog(" it's NOT a select statement: stmt=%p\n", self); res = CC_send_query(conn, self->stmt_with_params, NULL, qflag, SC_get_ancestor(self)); } if (!isSelectType) { /* * We shouldn't send COMMIT. Postgres backend does the autocommit * if neccessary. (Zoltan, 04/26/2000) */ /* * Above seems wrong. Even in case of autocommit, started * transactions must be committed. (Hiroshi, 02/11/2001) */ if (CC_is_in_trans(conn)) { if (!is_in_trans) CC_set_in_manual_trans(conn); if (!self->internal && CC_does_autocommit(conn)) CC_commit(conn); } } SC_forget_unnamed(self); if (CONN_DOWN != conn->status) conn->status = oldstatus; self->status = STMT_FINISHED; LEAVE_INNER_CONN_CS(func_cs_count, conn); /* Check the status of the result */ if (res) { was_ok = QR_command_successful(res); was_nonfatal = QR_command_nonfatal(res); if (was_ok) SC_set_errornumber(self, STMT_OK); else if (0 < SC_get_errornumber(self)) ; else if (was_nonfatal) SC_set_errornumber(self, STMT_INFO_ONLY); else { switch (QR_get_rstatus(res)) { case PORES_NO_MEMORY_ERROR: SC_set_errornumber(self, STMT_NO_MEMORY_ERROR); break; case PORES_BAD_RESPONSE: SC_set_errornumber(self, STMT_COMMUNICATION_ERROR); break; case PORES_INTERNAL_ERROR: SC_set_errornumber(self, STMT_INTERNAL_ERROR); break; default: SC_set_errornumber(self, STMT_ERROR_TAKEN_FROM_BACKEND); } } /* set cursor before the first tuple in the list */ self->currTuple = -1; SC_set_current_col(self, -1); SC_set_rowset_start(self, -1, FALSE); /* issue "ABORT" when query aborted */ if (QR_get_aborted(res)) { #ifdef _LEGACY_MODE_ if (!self->internal) CC_abort(conn); #endif /* _LEGACY_MODE */ } else { QResultClass *tres; /* see if the query did return any result columns */ for (tres = res, numcols = 0; !numcols && tres; tres = tres->next) { numcols = QR_NumResultCols(tres); } /* now allocate the array to hold the binding info */ if (numcols > 0) { ARDFields *opts = SC_get_ARDF(self); extend_column_bindings(opts, numcols); if (opts->bindings == NULL) { QR_Destructor(res); SC_set_error(self, STMT_NO_MEMORY_ERROR,"Could not get enough free memory to store the binding information", func); goto cleanup; } } inolog("!!%p->SC_is_concat_pre=%x res=%p\n", self, self->miscinfo, res); /* * special handling of result for keyset driven cursors. * Use the columns info of the 1st query and * user the keyset info of the 2nd query. */ if (SQL_CURSOR_KEYSET_DRIVEN == self->options.cursor_type && SQL_CONCUR_READ_ONLY != self->options.scroll_concurrency && !useCursor) { if (tres = res->next, tres) { QR_set_fields(tres, QR_get_fields(res)); QR_set_fields(res, NULL); tres->num_fields = res->num_fields; res->next = NULL; QR_Destructor(res); SC_init_Result(self); SC_set_Result(self, tres); res = tres; } } /* skip the result of PREPARE in 'PREPARE ..:EXECUTE ..' call */ else if (SC_is_concat_prepare_exec(self)) { tres = res->next; inolog("res->next=%p\n", tres); res->next = NULL; if (res != SC_get_Result(self)) QR_Destructor(res); SC_set_Result(self, tres); res = tres; SC_set_prepared(self, PREPARED_PERMANENTLY); SC_no_concat_prepare_exec(self); } } } else { /* Bad Error -- The error message will be in the Connection */ if (!conn->sock) SC_set_error(self, STMT_BAD_ERROR, CC_get_errormsg(conn), func); else if (self->statement_type == STMT_TYPE_CREATE) { SC_set_error(self, STMT_CREATE_TABLE_ERROR, "Error creating the table", func); /* * This would allow the table to already exists, thus * appending rows to it. BUT, if the table didn't have the * same attributes, it would fail. return * SQL_SUCCESS_WITH_INFO; */ } else { SC_set_error(self, STMT_EXEC_ERROR, CC_get_errormsg(conn), func); } #ifdef _LEGACY_MODE_ if (!self->internal) CC_abort(conn); #endif /* _LEGACY_MODE_ */ } if (!SC_get_Result(self)) SC_set_Result(self, res); else { QResultClass *last; for (last = SC_get_Result(self); NULL != last->next; last = last->next) { if (last == res) break; } if (last != res) last->next = res; self->curr_param_result = 1; } ipdopts = SC_get_IPDF(self); has_out_para = FALSE; if (self->statement_type == STMT_TYPE_PROCCALL && (SC_get_errornumber(self) == STMT_OK || SC_get_errornumber(self) == STMT_INFO_ONLY)) { Int2 io, out; has_out_para = (CountParameters(self, NULL, &io, &out) > 0); /* * I'm not sure if the following REFCUR_SUPPORT stuff is valuable * or not. */ #ifdef REFCUR_SUPPORT inolog("!!! numfield=%d field_type=%u\n", QR_NumResultCols(res), QR_get_field_type(res, 0)); if (!has_out_para && 0 < QR_NumResultCols(res) && PG_TYPE_REFCURSOR == QR_get_field_type(res, 0)) { char fetch[128]; int stmt_type = self->statement_type; STR_TO_NAME(self->cursor_name, QR_get_value_backend_text(res, 0, 0)); QR_Destructor(res); SC_init_Result(self); SC_set_fetchcursor(self); qi.result_in = NULL; qi.cursor = SC_cursor_name(self); qi.row_size = ci->drivers.fetch_max; snprintf(fetch, sizeof(fetch), "%s " FORMAT_LEN " in \"%s\"", fetch_cmd, qi.row_size, SC_cursor_name(self)); if (0 != (ci->extra_opts & BIT_IGNORE_ROUND_TRIP_TIME)) qflag |= IGNORE_ROUND_TRIP; if (res = CC_send_query_append(conn, fetch, &qi, qflag, SC_get_ancestor(self), NULL), NULL != res) SC_set_Result(self, res); } #endif /* REFCUR_SUPPORT */ } if (has_out_para) { /* get the return value of the procedure call */ RETCODE ret; HSTMT hstmt = (HSTMT) self; self->bind_row = 0; ret = SC_fetch(hstmt); inolog("!!SC_fetch return =%d\n", ret); if (SQL_SUCCEEDED(ret)) { APDFields *apdopts = SC_get_APDF(self); SQLULEN offset = apdopts->param_offset_ptr ? *apdopts->param_offset_ptr : 0; ARDFields *ardopts = SC_get_ARDF(self); const ParameterInfoClass *apara; const ParameterImplClass *ipara; int save_bind_size = ardopts->bind_size, gidx, num_p; ardopts->bind_size = apdopts->param_bind_type; num_p = self->num_params; if (ipdopts->allocated < num_p) num_p = ipdopts->allocated; for (i = 0, gidx = 0; i < num_p; i++) { ipara = ipdopts->parameters + i; if (ipara->paramType == SQL_PARAM_OUTPUT || ipara->paramType == SQL_PARAM_INPUT_OUTPUT) { apara = apdopts->parameters + i; ret = PGAPI_GetData(hstmt, gidx + 1, apara->CType, apara->buffer + offset, apara->buflen, apara->used ? LENADDR_SHIFT(apara->used, offset) : NULL); if (!SQL_SUCCEEDED(ret)) { SC_set_error(self, STMT_EXEC_ERROR, "GetData to Procedure return failed.", func); break; } gidx++; } } ardopts->bind_size = save_bind_size; /* restore */ } else { SC_set_error(self, STMT_EXEC_ERROR, "SC_fetch to get a Procedure return failed.", func); } } cleanup: #undef return SC_SetExecuting(self, FALSE); CLEANUP_FUNC_CONN_CS(func_cs_count, conn); if (CONN_DOWN != conn->status) conn->status = oldstatus; /* self->status = STMT_FINISHED; */ if (SC_get_errornumber(self) == STMT_OK) return SQL_SUCCESS; else if (SC_get_errornumber(self) < STMT_OK) return SQL_SUCCESS_WITH_INFO; else { if (!SC_get_errormsg(self) || !SC_get_errormsg(self)[0]) { if (STMT_NO_MEMORY_ERROR != SC_get_errornumber(self)) SC_set_errormsg(self, "Error while executing the query"); SC_log_error(func, NULL, self); } return SQL_ERROR; } } #define CALLBACK_ALLOC_ONCE 4 int enqueueNeedDataCallback(StatementClass *stmt, NeedDataCallfunc func, void *data) { if (stmt->num_callbacks >= stmt->allocated_callbacks) { SC_REALLOC_return_with_error(stmt->callbacks, NeedDataCallback, sizeof(NeedDataCallback) * (stmt->allocated_callbacks + CALLBACK_ALLOC_ONCE), stmt, "NeedDataCallback enqueue error", 0); stmt->allocated_callbacks += CALLBACK_ALLOC_ONCE; } stmt->callbacks[stmt->num_callbacks].func = func; stmt->callbacks[stmt->num_callbacks].data = data; stmt->num_callbacks++; inolog("enqueueNeedDataCallack stmt=%p, func=%p, count=%d\n", stmt, func, stmt->num_callbacks); return stmt->num_callbacks; } RETCODE dequeueNeedDataCallback(RETCODE retcode, StatementClass *stmt) { RETCODE ret; NeedDataCallfunc func; void *data; int i, cnt; mylog("dequeueNeedDataCallback ret=%d count=%d\n", retcode, stmt->num_callbacks); if (SQL_NEED_DATA == retcode) return retcode; if (stmt->num_callbacks <= 0) return retcode; func = stmt->callbacks[0].func; data = stmt->callbacks[0].data; for (i = 1; i < stmt->num_callbacks; i++) stmt->callbacks[i - 1] = stmt->callbacks[i]; cnt = --stmt->num_callbacks; ret = (*func)(retcode, data); free(data); if (SQL_NEED_DATA != ret && cnt > 0) ret = dequeueNeedDataCallback(ret, stmt); return ret; } void cancelNeedDataState(StatementClass *stmt) { int cnt = stmt->num_callbacks, i; stmt->num_callbacks = 0; for (i = 0; i < cnt; i++) { if (stmt->callbacks[i].data) free(stmt->callbacks[i].data); } SC_reset_delegate(SQL_ERROR, stmt); } void SC_log_error(const char *func, const char *desc, const StatementClass *self) { const char *head; #ifdef PRN_NULLCHECK #define nullcheck(a) (a ? a : "(NULL)") #endif if (self) { QResultClass *res = SC_get_Result(self); const ARDFields *opts = SC_get_ARDF(self); const APDFields *apdopts = SC_get_APDF(self); SQLLEN rowsetSize; #if (ODBCVER >= 0x0300) rowsetSize = (STMT_TRANSITION_EXTENDED_FETCH == self->transition_status ? opts->size_of_rowset_odbc2 : opts->size_of_rowset); #else rowsetSize = opts->size_of_rowset_odbc2; #endif /* ODBCVER */ if (SC_get_errornumber(self) <= 0) head = "STATEMENT WARNING"; else { head = "STATEMENT ERROR"; qlog("%s: func=%s, desc='%s', errnum=%d, errmsg='%s'\n",head, func, desc, self->__error_number, nullcheck(self->__error_message)); } mylog("%s: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", head, func, desc, self->__error_number, nullcheck(self->__error_message)); if (SC_get_errornumber(self) > 0) { qlog(" ------------------------------------------------------------\n"); qlog(" hdbc=%p, stmt=%p, result=%p\n", self->hdbc, self, res); qlog(" prepare=%d, internal=%d\n", self->prepare, self->internal); qlog(" bindings=%p, bindings_allocated=%d\n", opts->bindings, opts->allocated); qlog(" parameters=%p, parameters_allocated=%d\n", apdopts->parameters, apdopts->allocated); qlog(" statement_type=%d, statement='%s'\n", self->statement_type, nullcheck(self->statement)); qlog(" stmt_with_params='%s'\n", nullcheck(self->stmt_with_params)); qlog(" data_at_exec=%d, current_exec_param=%d, put_data=%d\n", self->data_at_exec, self->current_exec_param, self->put_data); qlog(" currTuple=%d, current_col=%d, lobj_fd=%d\n", self->currTuple, self->current_col, self->lobj_fd); qlog(" maxRows=%d, rowset_size=%d, keyset_size=%d, cursor_type=%d, scroll_concurrency=%d\n", self->options.maxRows, rowsetSize, self->options.keyset_size, self->options.cursor_type, self->options.scroll_concurrency); qlog(" cursor_name='%s'\n", SC_cursor_name(self)); qlog(" ----------------QResult Info -------------------------------\n"); if (res) { qlog(" fields=%p, backend_tuples=%p, tupleField=%d, conn=%p\n", QR_get_fields(res), res->backend_tuples, res->tupleField, res->conn); qlog(" fetch_count=%d, num_total_rows=%d, num_fields=%d, cursor='%s'\n", res->fetch_number, QR_get_num_total_tuples(res), res->num_fields, nullcheck(QR_get_cursor(res))); qlog(" message='%s', command='%s', notice='%s'\n", nullcheck(QR_get_message(res)), nullcheck(res->command), nullcheck(res->notice)); qlog(" status=%d, inTuples=%d\n", QR_get_rstatus(res), QR_is_fetching_tuples(res)); } /* Log the connection error if there is one */ CC_log_error(func, desc, self->hdbc); } } else { qlog("INVALID STATEMENT HANDLE ERROR: func=%s, desc='%s'\n", func, desc); mylog("INVALID STATEMENT HANDLE ERROR: func=%s, desc='%s'\n", func, desc); } #undef PRN_NULLCHECK } /* * Extended Query */ static BOOL RequestStart(StatementClass *stmt, ConnectionClass *conn, const char *func) { BOOL ret = TRUE; #ifdef _HANDLE_ENLIST_IN_DTC_ if (conn->asdum) CALL_IsolateDtcConn(conn, TRUE); #endif /* _HANDLE_ENLIST_IN_DTC_ */ if (SC_accessed_db(stmt)) return TRUE; if (SQL_ERROR == SetStatementSvp(stmt)) { char emsg[128]; snprintf(emsg, sizeof(emsg), "internal savepoint error in %s", func); SC_set_error(stmt, STMT_INTERNAL_ERROR, emsg, func); return FALSE; } /* * In auto-commit mode, begin a new transaction implicitly if no * transaction is in progress yet. However, some special statements like * VACUUM and CLUSTER cannot be run in a transaction block. */ if (!CC_is_in_trans(conn) && CC_loves_visible_trans(conn) && stmt->statement_type != STMT_TYPE_SPECIAL) { ret = CC_begin(conn); } return ret; } /* * Copies the column information from the first result set of 'self' to 'res'. */ static BOOL ReflectColumnsInfo(StatementClass *self, QResultClass *res) { QResultClass *pres; if (NOT_YET_PREPARED == self->prepared) return FALSE; if (res->num_fields > 0) return FALSE; pres = SC_get_Result(self); if (pres != res && pres->num_fields > 0) { QR_set_fields(res, QR_get_fields(pres)); QR_set_conn(res, SC_get_conn(self)); if (QR_haskeyset(pres)) QR_set_haskeyset(res); if (QR_is_withhold(pres)) QR_set_withhold(res); res->num_fields = pres->num_fields; return TRUE; } return FALSE; } BOOL SendBindRequest(StatementClass *stmt, const char *plan_name) { CSTR func = "SendBindRequest"; ConnectionClass *conn = SC_get_conn(stmt); mylog("%s: plan_name=%s\n", func, plan_name); if (!RequestStart(stmt, conn, func)) return FALSE; if (!BuildBindRequest(stmt, plan_name)) return FALSE; conn->stmt_in_extquery = stmt; return TRUE; } QResultClass *SendSyncAndReceive(StatementClass *stmt, QResultClass *res, const char *comment) { CSTR func = "SendSyncAndReceive"; ConnectionClass *conn = SC_get_conn(stmt); SocketClass *sock = conn->sock; char id; Int4 response_length; UInt4 oid; int num_p, num_io_params; int i, pidx; Int2 num_discard_params, paramType; BOOL rcvend = FALSE, loopend = FALSE; char msgbuffer[ERROR_MSG_LENGTH + 1]; IPDFields *ipdopts; QResultClass *newres = NULL; if (!RequestStart(stmt, conn, func)) return NULL; SOCK_put_char(sock, 'S'); /* Sync command */ SOCK_put_int(sock, 4, 4); /* length */ SOCK_flush_output(sock); if (!res) newres = res = QR_Constructor(); for (;!loopend;) { id = SOCK_get_id(sock); if ((SOCK_get_errcode(sock) != 0) || (id == EOF)) break; inolog("desc id=%c", id); response_length = SOCK_get_response_length(sock); if (0 != SOCK_get_errcode(sock)) break; inolog(" response_length=%d\n", response_length); switch (id) { case 'C': SOCK_get_string(sock, msgbuffer, sizeof(msgbuffer)); mylog("command response=%s\n", msgbuffer); QR_set_command(res, msgbuffer); if (QR_is_fetching_tuples(res)) { res->dataFilled = TRUE; QR_set_no_fetching_tuples(res); /* in case of FETCH, Portal Suspend never arrives */ if (strnicmp(msgbuffer, "SELECT", 6) == 0) { mylog("%s: reached eof now\n", func); QR_set_reached_eof(res); } else { int ret1, ret2; ret1 = ret2 = 0; if (sscanf(msgbuffer, "%*s %d %d", &ret1, &ret2) > 1) res->recent_processed_row_count = ret2; else res->recent_processed_row_count = ret1; } } break; case 'E': /* ErrorMessage */ handle_error_message(conn, msgbuffer, sizeof(msgbuffer), res->sqlstate, comment, res); break; case 'N': /* Notice */ handle_notice_message(conn, msgbuffer, sizeof(msgbuffer), res->sqlstate, comment, res); break; case '1': /* ParseComplete */ if (stmt->plan_name) SC_set_prepared(stmt, PREPARED_PERMANENTLY); else SC_set_prepared(stmt, PREPARED_TEMPORARILY); break; case '2': /* BindComplete */ QR_set_fetching_tuples(res); break; case '3': /* CloseComplete */ QR_set_no_fetching_tuples(res); break; case 'Z': /* ReadyForQuery */ loopend = rcvend = TRUE; EatReadyForQuery(conn); break; case 't': /* ParameterDesription */ num_p = SOCK_get_int(sock, 2); inolog("num_params=%d info=%d\n", stmt->num_params, num_p); num_discard_params = 0; if (stmt->discard_output_params) CountParameters(stmt, NULL, NULL, &num_discard_params); if (num_discard_params < stmt->proc_return) num_discard_params = stmt->proc_return; if (num_p + num_discard_params != (int) stmt->num_params) { mylog("ParamInfo unmatch num_params(=%d) != info(=%d)+discard(=%d)\n", stmt->num_params, num_p, num_discard_params); /* stmt->num_params = (Int2) num_p + num_discard_params; it's possible in case of multi command queries */ } ipdopts = SC_get_IPDF(stmt); extend_iparameter_bindings(ipdopts, stmt->num_params); #ifdef NOT_USED if (stmt->discard_output_params) { for (i = 0, pidx = stmt->proc_return; i < num_p && pidx < stmt->num_params; pidx++) { paramType = ipdopts->parameters[pidx].paramType; if (SQL_PARAM_OUTPUT == paramType) { i++; continue; } oid = SOCK_get_int(sock, 4); PIC_set_pgtype(ipdopts->parameters[pidx], oid); } } else { for (i = 0, pidx = stmt->proc_return; i < num_p; i++, pidx++) { paramType = ipdopts->parameters[pidx].paramType; oid = SOCK_get_int(sock, 4); if (SQL_PARAM_OUTPUT != paramType || PG_TYPE_VOID != oid) PIC_set_pgtype(ipdopts->parameters[pidx], oid); } } #endif /* NOT_USED */ pidx = stmt->current_exec_param; if (pidx >= 0) pidx--; for (i = 0; i < num_p; i++) { SC_param_next(stmt, &pidx, NULL, NULL); if (pidx >= stmt->num_params) { mylog("%dth parameter's position(%d) is out of bound[%d]\n", i, pidx, stmt->num_params); break; } oid = SOCK_get_int(sock, 4); paramType = ipdopts->parameters[pidx].paramType; if (SQL_PARAM_OUTPUT != paramType || PG_TYPE_VOID != oid) PIC_set_pgtype(ipdopts->parameters[pidx], oid); } break; case 'T': /* RowDesription */ QR_set_conn(res, conn); if (CI_read_fields(QR_get_fields(res), conn)) { Int2 dummy1, dummy2; int cidx; QR_set_rstatus(res, PORES_FIELDS_OK); res->num_fields = CI_get_num_fields(QR_get_fields(res)); if (QR_haskeyset(res)) res->num_fields -= res->num_key_fields; num_io_params = CountParameters(stmt, NULL, &dummy1, &dummy2); if (stmt->proc_return > 0 || num_io_params > 0) { ipdopts = SC_get_IPDF(stmt); extend_iparameter_bindings(ipdopts, stmt->num_params); for (i = 0, cidx = 0; i < stmt->num_params; i++) { if (i < stmt->proc_return) ipdopts->parameters[i].paramType = SQL_PARAM_OUTPUT; paramType =ipdopts->parameters[i].paramType; if (SQL_PARAM_OUTPUT == paramType || SQL_PARAM_INPUT_OUTPUT == paramType) { inolog("!![%d].PGType %u->%u\n", i, PIC_get_pgtype(ipdopts->parameters[i]), CI_get_oid(QR_get_fields(res), cidx)); PIC_set_pgtype(ipdopts->parameters[i], CI_get_oid(QR_get_fields(res), cidx)); cidx++; } } } } else { if (NULL == QR_get_fields(res)->coli_array) { QR_set_rstatus(res, PORES_NO_MEMORY_ERROR); QR_set_messageref(res, "Out of memory while reading field information"); } else { QR_set_rstatus(res, PORES_BAD_RESPONSE); QR_set_message(res, "Error reading field information"); } loopend = rcvend = TRUE; } break; case 'B': /* Binary data */ case 'D': /* ASCII data */ ReflectColumnsInfo(stmt, res); if (!QR_get_tupledata(res, id == 'B')) { loopend = TRUE; } break; case 'S': /* parameter status */ getParameterValues(conn); break; case 's': /* portal suspend */ QR_set_no_fetching_tuples(res); res->dataFilled = TRUE; break; default: break; } } if (!rcvend && 0 == SOCK_get_errcode(sock) && EOF != id) { for (;;) { id = SOCK_get_id(sock); if ((SOCK_get_errcode(sock) != 0) || (id == EOF)) break; response_length = SOCK_get_response_length(sock); if (0 != SOCK_get_errcode(sock)) break; if ('Z' == id) { EatReadyForQuery(conn); qlog("%s Discarded data until ReadyForQuery comes\n", __FUNCTION__); break; } } } if (0 != SOCK_get_errcode(sock) || EOF == id) { SC_set_error(stmt, STMT_NO_RESPONSE, "No response from the backend", func); mylog("%s: 'id' - %s\n", func, SC_get_errormsg(stmt)); CC_on_abort(conn, CONN_DEAD); res = NULL; } if (res != newres && NULL != newres) QR_Destructor(newres); conn->stmt_in_extquery = NULL; return res; } BOOL SendParseRequest(StatementClass *stmt, const char *plan_name, const char *query, Int4 qlen, Int2 num_params) { CSTR func = "SendParseRequest"; ConnectionClass *conn = SC_get_conn(stmt); SocketClass *sock = conn->sock; Int4 sta_pidx = -1, end_pidx = -1; size_t pileng, leng; mylog("%s: plan_name=%s query=%s\n", func, plan_name, query); qlog("%s: plan_name=%s query=%s\n", func, plan_name, query); if (!RequestStart(stmt, conn, func)) return FALSE; SOCK_put_char(sock, 'P'); /* Parse command */ if (SOCK_get_errcode(sock) != 0) { CC_set_error(conn, CONNECTION_COULD_NOT_SEND, "Could not send P request to backend", func); CC_on_abort(conn, CONN_DEAD); return FALSE; } pileng = sizeof(Int2); if (stmt->discard_output_params) num_params = 0; else if (num_params != 0) { #ifdef NOT_USED sta_pidx += stmt->proc_return; #endif /* NOT_USED */ int pidx; sta_pidx = stmt->current_exec_param; if (num_params < 0) end_pidx = stmt->num_params - 1; else end_pidx = sta_pidx + num_params - 1; #ifdef NOT_USED num_params = end_pidx - sta_pidx + 1; #endif /* NOT_USED */ for (num_params = 0, pidx = sta_pidx - 1;;) { SC_param_next(stmt, &pidx, NULL, NULL); if (pidx > end_pidx) break; else if (pidx < end_pidx) num_params++; else { num_params++; break; } } mylog("sta_pidx=%d end_pidx=%d num_p=%d\n", sta_pidx, end_pidx, num_params); pileng += (sizeof(UInt4) * num_params); } qlen = (SQL_NTS == qlen) ? strlen(query) : qlen; leng = strlen(plan_name) + 1 + qlen + 1 + pileng; SOCK_put_int(sock, (Int4) (leng + 4), 4); /* length */ inolog("parse leng=" FORMAT_SIZE_T "\n", leng); SOCK_put_string(sock, plan_name); SOCK_put_n_char(sock, query, qlen); SOCK_put_char(sock, '\0'); SOCK_put_int(sock, num_params, sizeof(Int2)); /* number of parameters specified */ if (num_params > 0) { int i; IPDFields *ipdopts = SC_get_IPDF(stmt); for (i = sta_pidx; i <= end_pidx; i++) { if (i < ipdopts->allocated && SQL_PARAM_OUTPUT == ipdopts->parameters[i].paramType) SOCK_put_int(sock, PG_TYPE_VOID, sizeof(UInt4)); else SOCK_put_int(sock, 0, sizeof(UInt4)); } } conn->stmt_in_extquery = stmt; return TRUE; } BOOL SyncParseRequest(ConnectionClass *conn) { StatementClass *stmt = conn->stmt_in_extquery; QResultClass *res, *last; BOOL ret = FALSE; if (!stmt) return TRUE; res = SC_get_Result(stmt); for (last = res; last && last->next; last = last->next) ; if (!(res = SendSyncAndReceive(stmt, stmt->curr_param_result ? last : NULL, __FUNCTION__))) { if (SC_get_errornumber(stmt) <= 0) SC_set_error(stmt, STMT_NO_RESPONSE, "Could not receive the response, communication down ??", __FUNCTION__); CC_on_abort(conn, CONN_DEAD); goto cleanup; } if (!last) SC_set_Result(stmt, res); else { if (res != last) last->next = res; stmt->curr_param_result = 1; } if (!QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Error while syncing parse reuest", __FUNCTION__); goto cleanup; } ret = TRUE; cleanup: return ret; } BOOL SendDescribeRequest(StatementClass *stmt, const char *plan_name, BOOL paramAlso) { CSTR func = "SendDescribeRequest"; ConnectionClass *conn = SC_get_conn(stmt); SocketClass *sock = conn->sock; size_t leng; BOOL sockerr = FALSE; mylog("%s:plan_name=%s\n", func, plan_name); if (!RequestStart(stmt, conn, func)) return FALSE; SOCK_put_char(sock, 'D'); /* Describe command */ if (SOCK_get_errcode(sock) != 0) sockerr = TRUE; if (!sockerr) { leng = 1 + strlen(plan_name) + 1; SOCK_put_int(sock, (Int4) (leng + 4), 4); /* length */ if (SOCK_get_errcode(sock) != 0) sockerr = TRUE; } if (!sockerr) { inolog("describe leng=%d\n", leng); SOCK_put_char(sock, paramAlso ? 'S' : 'P'); /* describe a prepared statement */ if (SOCK_get_errcode(sock) != 0) sockerr = TRUE; } if (!sockerr) { SOCK_put_string(sock, plan_name); if (SOCK_get_errcode(sock) != 0) sockerr = TRUE; } if (sockerr) { CC_set_error(conn, CONNECTION_COULD_NOT_SEND, "Could not send D Request to backend", func); CC_on_abort(conn, CONN_DEAD); return FALSE; } conn->stmt_in_extquery = stmt; return TRUE; } BOOL SendExecuteRequest(StatementClass *stmt, const char *plan_name, UInt4 count) { CSTR func = "SendExecuteRequest"; ConnectionClass *conn; SocketClass *sock; size_t leng; if (!stmt) return FALSE; if (conn = SC_get_conn(stmt), !conn) return FALSE; if (sock = conn->sock, !sock) return FALSE; mylog("%s: plan_name=%s count=%d\n", func, plan_name, count); qlog("%s: plan_name=%s count=%d\n", func, plan_name, count); if (!SC_is_fetchcursor(stmt)) { switch (stmt->prepared) { case NOT_YET_PREPARED: case ONCE_DESCRIBED: SC_set_error(stmt, STMT_EXEC_ERROR, "about to execute a non-prepared statement", func); return FALSE; } } if (!RequestStart(stmt, conn, func)) return FALSE; SOCK_put_char(sock, 'E'); /* Execute command */ SC_forget_unnamed(stmt); /* unnamed plans are unavailable */ if (SOCK_get_errcode(sock) != 0) { CC_set_error(conn, CONNECTION_COULD_NOT_SEND, "Could not send E Request to backend", func); CC_on_abort(conn, CONN_DEAD); return FALSE; } leng = strlen(plan_name) + 1 + 4; SOCK_put_int(sock, (Int4) (leng + 4), sizeof(Int4)); /* length */ inolog("execute leng=%d\n", leng); SOCK_put_string(sock, plan_name); /* portal name == plan name */ SOCK_put_int(sock, count, sizeof(Int4)); if (0 == count) /* will send a Close portal command */ { SOCK_put_char(sock, 'C'); /* Close command */ if (SOCK_get_errcode(sock) != 0) { CC_set_error(conn, CONNECTION_COULD_NOT_SEND, "Could not send C Request to backend", func); CC_on_abort(conn, CONN_DEAD); return FALSE; } leng = 1 + strlen(plan_name) + 1; SOCK_put_int(sock, (Int4) (leng + 4), 4); /* length */ inolog("Close leng=%d\n", leng); SOCK_put_char(sock, 'P'); /* Portal */ SOCK_put_string(sock, plan_name); } conn->stmt_in_extquery = stmt; return TRUE; } BOOL SendSyncRequest(ConnectionClass *conn) { SocketClass *sock = conn->sock; SOCK_put_char(sock, 'S'); /* Sync command */ SOCK_put_int(sock, 4, 4); SOCK_flush_output(sock); conn->stmt_in_extquery = NULL; return TRUE; } enum { CancelRequestSet = 1L ,CancelRequestAccepted = (1L << 1) ,CancelCompleted = (1L << 2) }; /* commonly used for short term lock */ #if defined(WIN_MULTITHREAD_SUPPORT) extern CRITICAL_SECTION common_cs; #elif defined(POSIX_MULTITHREAD_SUPPORT) extern pthread_mutex_t common_cs; #endif /* WIN_MULTITHREAD_SUPPORT */ BOOL SC_IsExecuting(const StatementClass *self) { BOOL ret; ENTER_COMMON_CS; /* short time blocking */ ret = (STMT_EXECUTING == self->status); LEAVE_COMMON_CS; return ret; } BOOL SC_SetExecuting(StatementClass *self, BOOL on) { BOOL exeSet = FALSE; ENTER_COMMON_CS; /* short time blocking */ if (on) { if (0 == (self->cancel_info & CancelRequestSet)) { self->status = STMT_EXECUTING; exeSet = TRUE; } } else { self->cancel_info = 0; self->status = STMT_FINISHED; exeSet = TRUE; } LEAVE_COMMON_CS; return exeSet; } #ifdef NOT_USED BOOL SC_SetCancelRequest(StatementClass *self) { BOOL enteredCS = FALSE; ENTER_COMMON_CS; if (0 != (self->cancel_info & CancelCompleted)) ; else if (STMT_EXECUTING == self->status) { self->cancel_info |= CancelRequestSet; } else { /* try to acquire */ if (TRY_ENTER_STMT_CS(self)) enteredCS = TRUE; else self->cancel_info |= CancelRequestSet; } LEAVE_COMMON_CS; return enteredCS; } #endif /* NOT_USED */ BOOL SC_AcceptedCancelRequest(const StatementClass *self) { BOOL shouldCancel = FALSE; ENTER_COMMON_CS; if (0 != (self->cancel_info & (CancelRequestSet | CancelRequestAccepted | CancelCompleted))) shouldCancel = TRUE; LEAVE_COMMON_CS; return shouldCancel; } psqlodbc-09.03.0300/tuple.c000644 001752 000000 00000002715 12335653444 015502 0ustar00saitowheel000000 000000 /*------- * Module: tuple.c * * Description: This module contains functions for setting the data * for individual fields (TupleField structure) of a * manual result set. * * Important Note: These functions are ONLY used in building manual * result sets for info functions (SQLTables, * SQLColumns, etc.) * * Classes: n/a * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "tuple.h" #include #include void set_tuplefield_null(TupleField *tuple_field) { tuple_field->len = 0; tuple_field->value = NULL; /* strdup(""); */ } void set_tuplefield_string(TupleField *tuple_field, const char *string) { if (string) { tuple_field->len = (Int4) strlen(string); /* PG restriction */ tuple_field->value = malloc(strlen(string) + 1); strcpy(tuple_field->value, string); } else set_tuplefield_null(tuple_field); } void set_tuplefield_int2(TupleField *tuple_field, Int2 value) { char buffer[10]; sprintf(buffer, "%d", value); tuple_field->len = (Int4) (strlen(buffer) + 1); /* +1 ... is this correct (better be on the save side-...) */ tuple_field->value = strdup(buffer); } void set_tuplefield_int4(TupleField *tuple_field, Int4 value) { char buffer[15]; sprintf(buffer, "%d", value); tuple_field->len = (Int4) (strlen(buffer) + 1); /* +1 ... is this correct (better be on the save side-...) */ tuple_field->value = strdup(buffer); } psqlodbc-09.03.0300/dlg_specific.c000644 001752 000000 00000145737 12335653444 017000 0ustar00saitowheel000000 000000 /*------- * Module: dlg_specific.c * * Description: This module contains any specific code for handling * dialog boxes such as driver/datasource options. Both the * ConfigDSN() and the SQLDriverConnect() functions use * functions in this module. If you were to add a new option * to any dialog box, you would most likely only have to change * things in here rather than in 2 separate places as before. * * Classes: none * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ /* Multibyte support Eiji Tokuya 2001-03-15 */ #include #include "dlg_specific.h" #include "misc.h" #include "convert.h" #include "multibyte.h" #include "pgapifunc.h" extern GLOBAL_VALUES globals; static void encode(const pgNAME, char *out, int outlen); static pgNAME decode(const char *in); static pgNAME decode_or_remove_braces(const char *in); #define OVR_EXTRA_BITS (BIT_FORCEABBREVCONNSTR | BIT_FAKE_MSS | BIT_BDE_ENVIRONMENT | BIT_CVT_NULL_DATE | BIT_ACCESSIBLE_ONLY | BIT_IGNORE_ROUND_TRIP_TIME | BIT_DISABLE_KEEPALIVE) UInt4 getExtraOptions(const ConnInfo *ci) { UInt4 flag = ci->extra_opts & (~OVR_EXTRA_BITS); if (ci->force_abbrev_connstr > 0) flag |= BIT_FORCEABBREVCONNSTR; else if (ci->force_abbrev_connstr == 0) flag &= (~BIT_FORCEABBREVCONNSTR); if (ci->fake_mss > 0) flag |= BIT_FAKE_MSS; else if (ci->fake_mss == 0) flag &= (~BIT_FAKE_MSS); if (ci->bde_environment > 0) flag |= BIT_BDE_ENVIRONMENT; else if (ci->bde_environment == 0) flag &= (~BIT_BDE_ENVIRONMENT); if (ci->cvt_null_date_string > 0) flag |= BIT_CVT_NULL_DATE; else if (ci->cvt_null_date_string == 0) flag &= (~BIT_CVT_NULL_DATE); if (ci->accessible_only > 0) flag |= BIT_ACCESSIBLE_ONLY; else if (ci->accessible_only == 0) flag &= (~BIT_ACCESSIBLE_ONLY); if (ci->ignore_round_trip_time > 0) flag |= BIT_IGNORE_ROUND_TRIP_TIME; else if (ci->ignore_round_trip_time == 0) flag &= (~BIT_IGNORE_ROUND_TRIP_TIME); if (ci->disable_keepalive > 0) flag |= BIT_DISABLE_KEEPALIVE; else if (ci->disable_keepalive == 0) flag &= (~BIT_DISABLE_KEEPALIVE); return flag; } CSTR hex_format = "%x"; CSTR dec_format = "%u"; CSTR octal_format = "%o"; static UInt4 replaceExtraOptions(ConnInfo *ci, UInt4 flag, BOOL overwrite) { if (overwrite) ci->extra_opts = flag; else ci->extra_opts |= (flag & ~(OVR_EXTRA_BITS)); if (overwrite || ci->force_abbrev_connstr < 0) ci->force_abbrev_connstr = (0 != (flag & BIT_FORCEABBREVCONNSTR)); if (overwrite || ci->fake_mss < 0) ci->fake_mss = (0 != (flag & BIT_FAKE_MSS)); if (overwrite || ci->bde_environment < 0) ci->bde_environment = (0 != (flag & BIT_BDE_ENVIRONMENT)); if (overwrite || ci->cvt_null_date_string < 0) ci->cvt_null_date_string = (0 != (flag & BIT_CVT_NULL_DATE)); if (overwrite || ci->accessible_only < 0) ci->accessible_only = (0 != (flag & BIT_ACCESSIBLE_ONLY)); if (overwrite || ci->ignore_round_trip_time < 0) ci->ignore_round_trip_time = (0 != (flag & BIT_IGNORE_ROUND_TRIP_TIME)); if (overwrite || ci->disable_keepalive < 0) ci->disable_keepalive = (0 != (flag & BIT_DISABLE_KEEPALIVE)); return (ci->extra_opts = getExtraOptions(ci)); } BOOL setExtraOptions(ConnInfo *ci, const char *optstr, const char *format) { UInt4 flag = 0; if (!format) { if ('0' == *optstr) { switch (optstr[1]) { case '\0': format = dec_format; break; case 'x': case 'X': optstr += 2; format = hex_format; break; default: format = octal_format; break; } } else format = dec_format; } if (sscanf(optstr, format, &flag) < 1) return FALSE; replaceExtraOptions(ci, flag, TRUE); return TRUE; } UInt4 add_removeExtraOptions(ConnInfo *ci, UInt4 aflag, UInt4 dflag) { ci->extra_opts |= aflag; ci->extra_opts &= (~dflag); if (0 != (aflag & BIT_FORCEABBREVCONNSTR)) ci->force_abbrev_connstr = TRUE; if (0 != (aflag & BIT_FAKE_MSS)) ci->fake_mss = TRUE; if (0 != (aflag & BIT_BDE_ENVIRONMENT)) ci->bde_environment = TRUE; if (0 != (aflag & BIT_CVT_NULL_DATE)) ci->cvt_null_date_string = TRUE; if (0 != (aflag & BIT_ACCESSIBLE_ONLY)) ci->accessible_only = TRUE; if (0 != (aflag & BIT_IGNORE_ROUND_TRIP_TIME)) ci->ignore_round_trip_time = TRUE; if (0 != (aflag & BIT_DISABLE_KEEPALIVE)) ci->disable_keepalive = TRUE; if (0 != (dflag & BIT_FORCEABBREVCONNSTR)) ci->force_abbrev_connstr = FALSE; if (0 != (dflag & BIT_FAKE_MSS)) ci->fake_mss =FALSE; if (0 != (dflag & BIT_CVT_NULL_DATE)) ci->cvt_null_date_string = FALSE; if (0 != (dflag & BIT_ACCESSIBLE_ONLY)) ci->accessible_only = FALSE; if (0 != (dflag & BIT_IGNORE_ROUND_TRIP_TIME)) ci->ignore_round_trip_time = FALSE; if (0 != (dflag & BIT_DISABLE_KEEPALIVE)) ci->disable_keepalive = FALSE; return (ci->extra_opts = getExtraOptions(ci)); } static const char * abbrev_sslmode(const char *sslmode, char *abbrevmode) { switch (sslmode[0]) { case SSLLBYTE_DISABLE: case SSLLBYTE_ALLOW: case SSLLBYTE_PREFER: case SSLLBYTE_REQUIRE: abbrevmode[0] = sslmode[0]; abbrevmode[1] = '\0'; break; case SSLLBYTE_VERIFY: abbrevmode[0] = sslmode[0]; abbrevmode[2] = '\0'; switch (sslmode[1]) { case 'f': case 'c': abbrevmode[1] = sslmode[1]; break; default: if (strnicmp(sslmode, "verify_", 7) == 0) abbrevmode[1] = sslmode[7]; else strcpy(abbrevmode, sslmode); } break; } return abbrevmode; } void makeConnectString(char *connect_string, const ConnInfo *ci, UWORD len) { char got_dsn = (ci->dsn[0] != '\0'); char encoded_item[LARGE_REGISTRY_LEN]; ssize_t hlen, nlen, olen; /*BOOL abbrev = (len <= 400);*/ BOOL abbrev = (len < 1024) || 0 < ci->force_abbrev_connstr; UInt4 flag; inolog("force_abbrev=%d abbrev=%d\n", ci->force_abbrev_connstr, abbrev); encode(ci->password, encoded_item, sizeof(encoded_item)); /* fundamental info */ nlen = MAX_CONNECT_STRING; olen = snprintf(connect_string, nlen, "%s=%s;DATABASE=%s;SERVER=%s;PORT=%s;UID=%s;PWD=%s", got_dsn ? "DSN" : "DRIVER", got_dsn ? ci->dsn : ci->drivername, ci->database, ci->server, ci->port, ci->username, encoded_item); if (olen < 0 || olen >= nlen) { connect_string[0] = '\0'; return; } encode(ci->conn_settings, encoded_item, sizeof(encoded_item)); /* extra info */ hlen = strlen(connect_string); nlen = MAX_CONNECT_STRING - hlen; inolog("hlen=%d", hlen); if (!abbrev) { char protocol_and[16]; if (ci->rollback_on_error >= 0) snprintf(protocol_and, sizeof(protocol_and), "%s-%d", ci->protocol, ci->rollback_on_error); else strncpy_null(protocol_and, ci->protocol, sizeof(protocol_and)); olen = snprintf(&connect_string[hlen], nlen, ";" INI_SSLMODE "=%s;" INI_READONLY "=%s;" INI_PROTOCOL "=%s;" INI_FAKEOIDINDEX "=%s;" INI_SHOWOIDCOLUMN "=%s;" INI_ROWVERSIONING "=%s;" INI_SHOWSYSTEMTABLES "=%s;" INI_CONNSETTINGS "=%s;" INI_FETCH "=%d;" INI_SOCKET "=%d;" INI_UNKNOWNSIZES "=%d;" INI_MAXVARCHARSIZE "=%d;" INI_MAXLONGVARCHARSIZE "=%d;" INI_DEBUG "=%d;" INI_COMMLOG "=%d;" INI_OPTIMIZER "=%d;" INI_KSQO "=%d;" INI_USEDECLAREFETCH "=%d;" INI_TEXTASLONGVARCHAR "=%d;" INI_UNKNOWNSASLONGVARCHAR "=%d;" INI_BOOLSASCHAR "=%d;" INI_PARSE "=%d;" INI_CANCELASFREESTMT "=%d;" INI_EXTRASYSTABLEPREFIXES "=%s;" INI_LFCONVERSION "=%d;" INI_UPDATABLECURSORS "=%d;" INI_DISALLOWPREMATURE "=%d;" INI_TRUEISMINUS1 "=%d;" INI_INT8AS "=%d;" INI_BYTEAASLONGVARBINARY "=%d;" INI_USESERVERSIDEPREPARE "=%d;" INI_LOWERCASEIDENTIFIER "=%d;" #ifdef WIN32 INI_GSSAUTHUSEGSSAPI "=%d;" #endif /* WIN32 */ #ifdef _HANDLE_ENLIST_IN_DTC_ INI_XAOPT "=%d" /* XAOPT */ #endif /* _HANDLE_ENLIST_IN_DTC_ */ ,ci->sslmode ,ci->onlyread ,protocol_and ,ci->fake_oid_index ,ci->show_oid_column ,ci->row_versioning ,ci->show_system_tables ,encoded_item ,ci->drivers.fetch_max ,ci->drivers.socket_buffersize ,ci->drivers.unknown_sizes ,ci->drivers.max_varchar_size ,ci->drivers.max_longvarchar_size ,ci->drivers.debug ,ci->drivers.commlog ,ci->drivers.disable_optimizer ,ci->drivers.ksqo ,ci->drivers.use_declarefetch ,ci->drivers.text_as_longvarchar ,ci->drivers.unknowns_as_longvarchar ,ci->drivers.bools_as_char ,ci->drivers.parse ,ci->drivers.cancel_as_freestmt ,ci->drivers.extra_systable_prefixes ,ci->lf_conversion ,ci->allow_keyset ,ci->disallow_premature ,ci->true_is_minus1 ,ci->int8_as ,ci->bytea_as_longvarbinary ,ci->use_server_side_prepare ,ci->lower_case_identifier #ifdef WIN32 ,ci->gssauth_use_gssapi #endif /* WIN32 */ #ifdef _HANDLE_ENLIST_IN_DTC_ ,ci->xa_opt #endif /* _HANDLE_ENLIST_IN_DTC_ */ ); } /* Abbreviation is needed ? */ if (abbrev || olen >= nlen || olen < 0) { flag = 0; if (ci->disallow_premature) flag |= BIT_DISALLOWPREMATURE; if (ci->allow_keyset) flag |= BIT_UPDATABLECURSORS; if (ci->lf_conversion) flag |= BIT_LFCONVERSION; if (ci->drivers.unique_index) flag |= BIT_UNIQUEINDEX; if (PROTOCOL_74(ci)) flag |= (BIT_PROTOCOL_64 | BIT_PROTOCOL_63); else if (PROTOCOL_64(ci)) flag |= BIT_PROTOCOL_64; else if (PROTOCOL_63(ci)) flag |= BIT_PROTOCOL_63; switch (ci->drivers.unknown_sizes) { case UNKNOWNS_AS_DONTKNOW: flag |= BIT_UNKNOWN_DONTKNOW; break; case UNKNOWNS_AS_MAX: flag |= BIT_UNKNOWN_ASMAX; break; } if (ci->drivers.disable_optimizer) flag |= BIT_OPTIMIZER; if (ci->drivers.ksqo) flag |= BIT_KSQO; if (ci->drivers.commlog) flag |= BIT_COMMLOG; if (ci->drivers.debug) flag |= BIT_DEBUG; if (ci->drivers.parse) flag |= BIT_PARSE; if (ci->drivers.cancel_as_freestmt) flag |= BIT_CANCELASFREESTMT; if (ci->drivers.use_declarefetch) flag |= BIT_USEDECLAREFETCH; if (ci->onlyread[0] == '1') flag |= BIT_READONLY; if (ci->drivers.text_as_longvarchar) flag |= BIT_TEXTASLONGVARCHAR; if (ci->drivers.unknowns_as_longvarchar) flag |= BIT_UNKNOWNSASLONGVARCHAR; if (ci->drivers.bools_as_char) flag |= BIT_BOOLSASCHAR; if (ci->row_versioning[0] == '1') flag |= BIT_ROWVERSIONING; if (ci->show_system_tables[0] == '1') flag |= BIT_SHOWSYSTEMTABLES; if (ci->show_oid_column[0] == '1') flag |= BIT_SHOWOIDCOLUMN; if (ci->fake_oid_index[0] == '1') flag |= BIT_FAKEOIDINDEX; if (ci->true_is_minus1) flag |= BIT_TRUEISMINUS1; if (ci->bytea_as_longvarbinary) flag |= BIT_BYTEAASLONGVARBINARY; if (ci->use_server_side_prepare) flag |= BIT_USESERVERSIDEPREPARE; if (ci->lower_case_identifier) flag |= BIT_LOWERCASEIDENTIFIER; if (ci->gssauth_use_gssapi) flag |= BIT_GSSAUTHUSEGSSAPI; if (ci->sslmode[0]) { char abbrevmode[sizeof(ci->sslmode)]; olen = snprintf(&connect_string[hlen], nlen, ";" ABBR_SSLMODE "=%s", abbrev_sslmode(ci->sslmode, abbrevmode)); } hlen = strlen(connect_string); nlen = MAX_CONNECT_STRING - hlen; olen = snprintf(&connect_string[hlen], nlen, ";" ABBR_CONNSETTINGS "=%s;" ABBR_FETCH "=%d;" ABBR_SOCKET "=%d;" ABBR_MAXVARCHARSIZE "=%d;" ABBR_MAXLONGVARCHARSIZE "=%d;" INI_INT8AS "=%d;" ABBR_EXTRASYSTABLEPREFIXES "=%s;" INI_ABBREVIATE "=%02x%x", encoded_item, ci->drivers.fetch_max, ci->drivers.socket_buffersize, ci->drivers.max_varchar_size, ci->drivers.max_longvarchar_size, ci->int8_as, ci->drivers.extra_systable_prefixes, EFFECTIVE_BIT_COUNT, flag); if (olen < nlen && (PROTOCOL_74(ci) || ci->rollback_on_error >= 0)) { hlen = strlen(connect_string); nlen = MAX_CONNECT_STRING - hlen; /* * The PROTOCOL setting must be placed after CX flag * so that this option can override the CX setting. */ if (ci->rollback_on_error >= 0) olen = snprintf(&connect_string[hlen], nlen, ";" ABBR_PROTOCOL "=%s-%d", ci->protocol, ci->rollback_on_error); else olen = snprintf(&connect_string[hlen], nlen, ";" ABBR_PROTOCOL "=%s", ci->protocol); } } if (olen < nlen) { flag = getExtraOptions(ci); if (0 != flag) { hlen = strlen(connect_string); nlen = MAX_CONNECT_STRING - hlen; olen = snprintf(&connect_string[hlen], nlen, ";" INI_EXTRAOPTIONS "=%x;", flag); } } if (olen < 0 || olen >= nlen) /* failed */ connect_string[0] = '\0'; } static void unfoldCXAttribute(ConnInfo *ci, const char *value) { int count; UInt4 flag; if (strlen(value) < 2) { count = 3; sscanf(value, "%x", &flag); } else { char cnt[8]; memcpy(cnt, value, 2); cnt[2] = '\0'; sscanf(cnt, "%x", &count); sscanf(value + 2, "%x", &flag); } ci->disallow_premature = (char)((flag & BIT_DISALLOWPREMATURE) != 0); ci->allow_keyset = (char)((flag & BIT_UPDATABLECURSORS) != 0); ci->lf_conversion = (char)((flag & BIT_LFCONVERSION) != 0); if (count < 4) return; ci->drivers.unique_index = (char)((flag & BIT_UNIQUEINDEX) != 0); if ((flag & BIT_PROTOCOL_64) != 0) { if ((flag & BIT_PROTOCOL_63) != 0) strcpy(ci->protocol, PG74); else strcpy(ci->protocol, PG64); } else if ((flag & BIT_PROTOCOL_63) != 0) strcpy(ci->protocol, PG63); else strcpy(ci->protocol, PG62); if ((flag & BIT_UNKNOWN_DONTKNOW) != 0) ci->drivers.unknown_sizes = UNKNOWNS_AS_DONTKNOW; else if ((flag & BIT_UNKNOWN_ASMAX) != 0) ci->drivers.unknown_sizes = UNKNOWNS_AS_MAX; else ci->drivers.unknown_sizes = UNKNOWNS_AS_LONGEST; ci->drivers.disable_optimizer = (char)((flag & BIT_OPTIMIZER) != 0); ci->drivers.ksqo = (char)((flag & BIT_KSQO) != 0); ci->drivers.commlog = (char)((flag & BIT_COMMLOG) != 0); ci->drivers.debug = (char)((flag & BIT_DEBUG) != 0); ci->drivers.parse = (char)((flag & BIT_PARSE) != 0); ci->drivers.cancel_as_freestmt = (char)((flag & BIT_CANCELASFREESTMT) != 0); ci->drivers.use_declarefetch = (char)((flag & BIT_USEDECLAREFETCH) != 0); sprintf(ci->onlyread, "%d", (char)((flag & BIT_READONLY) != 0)); ci->drivers.text_as_longvarchar = (char)((flag & BIT_TEXTASLONGVARCHAR) !=0); ci->drivers.unknowns_as_longvarchar = (char)((flag & BIT_UNKNOWNSASLONGVARCHAR) !=0); ci->drivers.bools_as_char = (char)((flag & BIT_BOOLSASCHAR) != 0); sprintf(ci->row_versioning, "%d", (char)((flag & BIT_ROWVERSIONING) != 0)); sprintf(ci->show_system_tables, "%d", (char)((flag & BIT_SHOWSYSTEMTABLES) != 0)); sprintf(ci->show_oid_column, "%d", (char)((flag & BIT_SHOWOIDCOLUMN) != 0)); sprintf(ci->fake_oid_index, "%d", (char)((flag & BIT_FAKEOIDINDEX) != 0)); ci->true_is_minus1 = (char)((flag & BIT_TRUEISMINUS1) != 0); ci->bytea_as_longvarbinary = (char)((flag & BIT_BYTEAASLONGVARBINARY) != 0); ci->use_server_side_prepare = (char)((flag & BIT_USESERVERSIDEPREPARE) != 0); ci->lower_case_identifier = (char)((flag & BIT_LOWERCASEIDENTIFIER) != 0); ci->gssauth_use_gssapi = (char)((flag & BIT_GSSAUTHUSEGSSAPI) != 0); } BOOL copyAttributes(ConnInfo *ci, const char *attribute, const char *value) { CSTR func = "copyAttributes"; BOOL found = TRUE; if (stricmp(attribute, "DSN") == 0) strcpy(ci->dsn, value); else if (stricmp(attribute, "driver") == 0) strcpy(ci->drivername, value); else if (stricmp(attribute, INI_KDESC) == 0) strcpy(ci->desc, value); else if (stricmp(attribute, INI_DATABASE) == 0) strcpy(ci->database, value); else if (stricmp(attribute, INI_SERVER) == 0 || stricmp(attribute, SPEC_SERVER) == 0) strcpy(ci->server, value); else if (stricmp(attribute, INI_USERNAME) == 0 || stricmp(attribute, INI_UID) == 0) strcpy(ci->username, value); else if (stricmp(attribute, INI_PASSWORD) == 0 || stricmp(attribute, "pwd") == 0) ci->password = decode_or_remove_braces(value); else if (stricmp(attribute, INI_PORT) == 0) strcpy(ci->port, value); else if (stricmp(attribute, INI_READONLY) == 0 || stricmp(attribute, ABBR_READONLY) == 0) strcpy(ci->onlyread, value); else if (stricmp(attribute, INI_PROTOCOL) == 0 || stricmp(attribute, ABBR_PROTOCOL) == 0) { char *ptr; ptr = strchr(value, '-'); if (ptr) { if ('-' != *value) { *ptr = '\0'; strcpy(ci->protocol, value); } ci->rollback_on_error = atoi(ptr + 1); mylog("rollback_on_error=%d\n", ci->rollback_on_error); } else strcpy(ci->protocol, value); } else if (stricmp(attribute, INI_SHOWOIDCOLUMN) == 0 || stricmp(attribute, ABBR_SHOWOIDCOLUMN) == 0) strcpy(ci->show_oid_column, value); else if (stricmp(attribute, INI_FAKEOIDINDEX) == 0 || stricmp(attribute, ABBR_FAKEOIDINDEX) == 0) strcpy(ci->fake_oid_index, value); else if (stricmp(attribute, INI_ROWVERSIONING) == 0 || stricmp(attribute, ABBR_ROWVERSIONING) == 0) strcpy(ci->row_versioning, value); else if (stricmp(attribute, INI_SHOWSYSTEMTABLES) == 0 || stricmp(attribute, ABBR_SHOWSYSTEMTABLES) == 0) strcpy(ci->show_system_tables, value); else if (stricmp(attribute, INI_CONNSETTINGS) == 0 || stricmp(attribute, ABBR_CONNSETTINGS) == 0) { /* We can use the conn_settings directly when they are enclosed with braces */ if ('{' == *value) { size_t len; len = strlen(value + 1); if (len > 0 && '}' == value[len]) len--; STRN_TO_NAME(ci->conn_settings, value + 1, len); } else ci->conn_settings = decode(value); } else if (stricmp(attribute, INI_DISALLOWPREMATURE) == 0 || stricmp(attribute, ABBR_DISALLOWPREMATURE) == 0) ci->disallow_premature = atoi(value); else if (stricmp(attribute, INI_UPDATABLECURSORS) == 0 || stricmp(attribute, ABBR_UPDATABLECURSORS) == 0) ci->allow_keyset = atoi(value); else if (stricmp(attribute, INI_LFCONVERSION) == 0 || stricmp(attribute, ABBR_LFCONVERSION) == 0) ci->lf_conversion = atoi(value); else if (stricmp(attribute, INI_TRUEISMINUS1) == 0 || stricmp(attribute, ABBR_TRUEISMINUS1) == 0) ci->true_is_minus1 = atoi(value); else if (stricmp(attribute, INI_INT8AS) == 0) ci->int8_as = atoi(value); else if (stricmp(attribute, INI_BYTEAASLONGVARBINARY) == 0 || stricmp(attribute, ABBR_BYTEAASLONGVARBINARY) == 0) ci->bytea_as_longvarbinary = atoi(value); else if (stricmp(attribute, INI_USESERVERSIDEPREPARE) == 0 || stricmp(attribute, ABBR_USESERVERSIDEPREPARE) == 0) ci->use_server_side_prepare = atoi(value); else if (stricmp(attribute, INI_LOWERCASEIDENTIFIER) == 0 || stricmp(attribute, ABBR_LOWERCASEIDENTIFIER) == 0) ci->lower_case_identifier = atoi(value); else if (stricmp(attribute, INI_GSSAUTHUSEGSSAPI) == 0 || stricmp(attribute, ABBR_GSSAUTHUSEGSSAPI) == 0) ci->gssauth_use_gssapi = atoi(value); else if (stricmp(attribute, INI_SSLMODE) == 0 || stricmp(attribute, ABBR_SSLMODE) == 0) { switch (value[0]) { case SSLLBYTE_ALLOW: strcpy(ci->sslmode, SSLMODE_ALLOW); break; case SSLLBYTE_PREFER: strcpy(ci->sslmode, SSLMODE_PREFER); break; case SSLLBYTE_REQUIRE: strcpy(ci->sslmode, SSLMODE_REQUIRE); break; case SSLLBYTE_VERIFY: switch (value[1]) { case 'f': strcpy(ci->sslmode, SSLMODE_VERIFY_FULL); break; case 'c': strcpy(ci->sslmode, SSLMODE_VERIFY_CA); break; default: strcpy(ci->sslmode, value); } break; case SSLLBYTE_DISABLE: default: strcpy(ci->sslmode, SSLMODE_DISABLE); break; } } else if (stricmp(attribute, INI_ABBREVIATE) == 0) unfoldCXAttribute(ci, value); #ifdef _HANDLE_ENLIST_IN_DTC_ else if (stricmp(attribute, INI_XAOPT) == 0) ci->xa_opt = atoi(value); #endif /* _HANDLE_ENLIST_IN_DTC_ */ else if (stricmp(attribute, INI_EXTRAOPTIONS) == 0) { UInt4 val1 = 0, val2 = 0; if ('+' == value[0]) { sscanf(value + 1, "%x-%x", &val1, &val2); add_removeExtraOptions(ci, val1, val2); } else if ('-' == value[0]) { sscanf(value + 1, "%x", &val2); add_removeExtraOptions(ci, 0, val2); } else { setExtraOptions(ci, value, hex_format); } mylog("force_abbrev=%d bde=%d cvt_null_date=%x\n", ci->force_abbrev_connstr, ci->bde_environment, ci->cvt_null_date_string); } else found = FALSE; mylog("%s: DSN='%s',server='%s',dbase='%s',user='%s',passwd='%s',port='%s',onlyread='%s',protocol='%s',conn_settings='%s',disallow_premature=%d)\n", func, ci->dsn, ci->server, ci->database, ci->username, NAME_IS_VALID(ci->password) ? "xxxxx" : "", ci->port, ci->onlyread, ci->protocol, ci->conn_settings, ci->disallow_premature); return found; } BOOL copyCommonAttributes(ConnInfo *ci, const char *attribute, const char *value) { CSTR func = "copyCommonAttributes"; BOOL found = TRUE; if (stricmp(attribute, INI_FETCH) == 0 || stricmp(attribute, ABBR_FETCH) == 0) ci->drivers.fetch_max = atoi(value); else if (stricmp(attribute, INI_SOCKET) == 0 || stricmp(attribute, ABBR_SOCKET) == 0) ci->drivers.socket_buffersize = atoi(value); else if (stricmp(attribute, INI_DEBUG) == 0 || stricmp(attribute, ABBR_DEBUG) == 0) ci->drivers.debug = atoi(value); else if (stricmp(attribute, INI_COMMLOG) == 0 || stricmp(attribute, ABBR_COMMLOG) == 0) ci->drivers.commlog = atoi(value); else if (stricmp(attribute, INI_OPTIMIZER) == 0 || stricmp(attribute, ABBR_OPTIMIZER) == 0) ci->drivers.disable_optimizer = atoi(value); else if (stricmp(attribute, INI_KSQO) == 0 || stricmp(attribute, ABBR_KSQO) == 0) ci->drivers.ksqo = atoi(value); /* * else if (stricmp(attribute, INI_UNIQUEINDEX) == 0 || * stricmp(attribute, "UIX") == 0) ci->drivers.unique_index = * atoi(value); */ else if (stricmp(attribute, INI_UNKNOWNSIZES) == 0 || stricmp(attribute, ABBR_UNKNOWNSIZES) == 0) ci->drivers.unknown_sizes = atoi(value); else if (stricmp(attribute, INI_LIE) == 0) ci->drivers.lie = atoi(value); else if (stricmp(attribute, INI_PARSE) == 0 || stricmp(attribute, ABBR_PARSE) == 0) ci->drivers.parse = atoi(value); else if (stricmp(attribute, INI_CANCELASFREESTMT) == 0 || stricmp(attribute, ABBR_CANCELASFREESTMT) == 0) ci->drivers.cancel_as_freestmt = atoi(value); else if (stricmp(attribute, INI_USEDECLAREFETCH) == 0 || stricmp(attribute, ABBR_USEDECLAREFETCH) == 0) ci->drivers.use_declarefetch = atoi(value); else if (stricmp(attribute, INI_MAXVARCHARSIZE) == 0 || stricmp(attribute, ABBR_MAXVARCHARSIZE) == 0) ci->drivers.max_varchar_size = atoi(value); else if (stricmp(attribute, INI_MAXLONGVARCHARSIZE) == 0 || stricmp(attribute, ABBR_MAXLONGVARCHARSIZE) == 0) ci->drivers.max_longvarchar_size = atoi(value); else if (stricmp(attribute, INI_TEXTASLONGVARCHAR) == 0 || stricmp(attribute, ABBR_TEXTASLONGVARCHAR) == 0) ci->drivers.text_as_longvarchar = atoi(value); else if (stricmp(attribute, INI_UNKNOWNSASLONGVARCHAR) == 0 || stricmp(attribute, ABBR_UNKNOWNSASLONGVARCHAR) == 0) ci->drivers.unknowns_as_longvarchar = atoi(value); else if (stricmp(attribute, INI_BOOLSASCHAR) == 0 || stricmp(attribute, ABBR_BOOLSASCHAR) == 0) ci->drivers.bools_as_char = atoi(value); else if (stricmp(attribute, INI_EXTRASYSTABLEPREFIXES) == 0 || stricmp(attribute, ABBR_EXTRASYSTABLEPREFIXES) == 0) strcpy(ci->drivers.extra_systable_prefixes, value); else found = FALSE; mylog("%s: A7=%d;A8=%d;A9=%d;B0=%d;B1=%d;B2=%d;B3=%d;B4=%d;B5=%d;B6=%d;B7=%d;B8=%d;B9=%d;C0=%d;C1=%d;C2=%s", func, ci->drivers.fetch_max, ci->drivers.socket_buffersize, ci->drivers.unknown_sizes, ci->drivers.max_varchar_size, ci->drivers.max_longvarchar_size, ci->drivers.debug, ci->drivers.commlog, ci->drivers.disable_optimizer, ci->drivers.ksqo, ci->drivers.use_declarefetch, ci->drivers.text_as_longvarchar, ci->drivers.unknowns_as_longvarchar, ci->drivers.bools_as_char, ci->drivers.parse, ci->drivers.cancel_as_freestmt, ci->drivers.extra_systable_prefixes); return found; } void getDSNdefaults(ConnInfo *ci) { mylog("calling getDSNdefaults\n"); if (ci->port[0] == '\0') strcpy(ci->port, DEFAULT_PORT); if (ci->onlyread[0] == '\0') sprintf(ci->onlyread, "%d", globals.onlyread); if (ci->protocol[0] == '\0') strcpy(ci->protocol, globals.protocol); if (ci->fake_oid_index[0] == '\0') sprintf(ci->fake_oid_index, "%d", DEFAULT_FAKEOIDINDEX); if (ci->show_oid_column[0] == '\0') sprintf(ci->show_oid_column, "%d", DEFAULT_SHOWOIDCOLUMN); if (ci->show_system_tables[0] == '\0') sprintf(ci->show_system_tables, "%d", DEFAULT_SHOWSYSTEMTABLES); if (ci->row_versioning[0] == '\0') sprintf(ci->row_versioning, "%d", DEFAULT_ROWVERSIONING); if (ci->disallow_premature < 0) ci->disallow_premature = DEFAULT_DISALLOWPREMATURE; if (ci->allow_keyset < 0) ci->allow_keyset = DEFAULT_UPDATABLECURSORS; if (ci->lf_conversion < 0) ci->lf_conversion = DEFAULT_LFCONVERSION; if (ci->true_is_minus1 < 0) ci->true_is_minus1 = DEFAULT_TRUEISMINUS1; if (ci->int8_as < -100) ci->int8_as = DEFAULT_INT8AS; if (ci->bytea_as_longvarbinary < 0) ci->bytea_as_longvarbinary = DEFAULT_BYTEAASLONGVARBINARY; if (ci->use_server_side_prepare < 0) ci->use_server_side_prepare = DEFAULT_USESERVERSIDEPREPARE; if (ci->lower_case_identifier < 0) ci->lower_case_identifier = DEFAULT_LOWERCASEIDENTIFIER; if (ci->gssauth_use_gssapi < 0) ci->gssauth_use_gssapi = DEFAULT_GSSAUTHUSEGSSAPI; if (ci->sslmode[0] == '\0') strcpy(ci->sslmode, DEFAULT_SSLMODE); if (ci->force_abbrev_connstr < 0) ci->force_abbrev_connstr = 0; if (ci->fake_mss < 0) ci->fake_mss = 0; if (ci->bde_environment < 0) ci->bde_environment = 0; if (ci->cvt_null_date_string < 0) ci->cvt_null_date_string = 0; if (ci->accessible_only < 0) ci->accessible_only = 0; if (ci->ignore_round_trip_time < 0) ci->ignore_round_trip_time = 0; if (ci->disable_keepalive < 0) ci->disable_keepalive = 0; #ifdef _HANDLE_ENLIST_IN_DTC_ if (ci->xa_opt < 0) ci->xa_opt = DEFAULT_XAOPT; #endif /* _HANDLE_ENLIST_IN_DTC_ */ } int getDriverNameFromDSN(const char *dsn, char *driver_name, int namelen) { return SQLGetPrivateProfileString(ODBC_DATASOURCES, dsn, "", driver_name, namelen, ODBC_INI); } int getLogDir(char *dir, int dirmax) { return SQLGetPrivateProfileString(DBMS_NAME, INI_LOGDIR, "", dir, dirmax, ODBCINST_INI); } int setLogDir(const char *dir) { return SQLWritePrivateProfileString(DBMS_NAME, INI_LOGDIR, dir, ODBCINST_INI); } void getDSNinfo(ConnInfo *ci, char overwrite) { CSTR func = "getDSNinfo"; char *DSN = ci->dsn; char encoded_item[LARGE_REGISTRY_LEN], temp[SMALL_REGISTRY_LEN]; /* * If a driver keyword was present, then dont use a DSN and return. * If DSN is null and no driver, then use the default datasource. */ mylog("%s: DSN=%s overwrite=%d\n", func, DSN, overwrite); if (DSN[0] == '\0') { if (ci->drivername[0] != '\0') return; else strncpy_null(DSN, INI_DSN, sizeof(ci->dsn)); } /* brute-force chop off trailing blanks... */ while (*(DSN + strlen(DSN) - 1) == ' ') *(DSN + strlen(DSN) - 1) = '\0'; if (ci->drivername[0] == '\0' || overwrite) { getDriverNameFromDSN(DSN, ci->drivername, sizeof(ci->drivername)); if (ci->drivername[0] && stricmp(ci->drivername, SAFE_NAME(ci->drivers.drivername))) getCommonDefaults(ci->drivername, ODBCINST_INI, ci); } /* Proceed with getting info for the given DSN. */ if (ci->desc[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_KDESC, "", ci->desc, sizeof(ci->desc), ODBC_INI); if (ci->server[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_SERVER, "", ci->server, sizeof(ci->server), ODBC_INI); if (ci->database[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_DATABASE, "", ci->database, sizeof(ci->database), ODBC_INI); if (ci->username[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_USERNAME, "", ci->username, sizeof(ci->username), ODBC_INI); if (NAME_IS_NULL(ci->password) || overwrite) { SQLGetPrivateProfileString(DSN, INI_PASSWORD, "", encoded_item, sizeof(encoded_item), ODBC_INI); ci->password = decode(encoded_item); } if (ci->port[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_PORT, "", ci->port, sizeof(ci->port), ODBC_INI); if (ci->onlyread[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_READONLY, "", ci->onlyread, sizeof(ci->onlyread), ODBC_INI); if (ci->show_oid_column[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_SHOWOIDCOLUMN, "", ci->show_oid_column, sizeof(ci->show_oid_column), ODBC_INI); if (ci->fake_oid_index[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_FAKEOIDINDEX, "", ci->fake_oid_index, sizeof(ci->fake_oid_index), ODBC_INI); if (ci->row_versioning[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_ROWVERSIONING, "", ci->row_versioning, sizeof(ci->row_versioning), ODBC_INI); if (ci->show_system_tables[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_SHOWSYSTEMTABLES, "", ci->show_system_tables, sizeof(ci->show_system_tables), ODBC_INI); if (ci->protocol[0] == '\0' || overwrite) { char *ptr; SQLGetPrivateProfileString(DSN, INI_PROTOCOL, "", ci->protocol, sizeof(ci->protocol), ODBC_INI); if (ptr = strchr(ci->protocol, '-'), NULL != ptr) { *ptr = '\0'; if (overwrite || ci->rollback_on_error < 0) { ci->rollback_on_error = atoi(ptr + 1); mylog("rollback_on_error=%d\n", ci->rollback_on_error); } } } if (NAME_IS_NULL(ci->conn_settings) || overwrite) { SQLGetPrivateProfileString(DSN, INI_CONNSETTINGS, "", encoded_item, sizeof(encoded_item), ODBC_INI); ci->conn_settings = decode(encoded_item); } if (ci->translation_dll[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_TRANSLATIONDLL, "", ci->translation_dll, sizeof(ci->translation_dll), ODBC_INI); if (ci->translation_option[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_TRANSLATIONOPTION, "", ci->translation_option, sizeof(ci->translation_option), ODBC_INI); if (ci->disallow_premature < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_DISALLOWPREMATURE, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->disallow_premature = atoi(temp); } if (ci->allow_keyset < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_UPDATABLECURSORS, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->allow_keyset = atoi(temp); } if (ci->lf_conversion < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_LFCONVERSION, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->lf_conversion = atoi(temp); } if (ci->true_is_minus1 < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_TRUEISMINUS1, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->true_is_minus1 = atoi(temp); } if (ci->int8_as < -100 || overwrite) { SQLGetPrivateProfileString(DSN, INI_INT8AS, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->int8_as = atoi(temp); } if (ci->bytea_as_longvarbinary < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_BYTEAASLONGVARBINARY, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->bytea_as_longvarbinary = atoi(temp); } if (ci->use_server_side_prepare < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_USESERVERSIDEPREPARE, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->use_server_side_prepare = atoi(temp); } if (ci->lower_case_identifier < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_LOWERCASEIDENTIFIER, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->lower_case_identifier = atoi(temp); } if (ci->gssauth_use_gssapi < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_GSSAUTHUSEGSSAPI, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->gssauth_use_gssapi = atoi(temp); } if (ci->sslmode[0] == '\0' || overwrite) SQLGetPrivateProfileString(DSN, INI_SSLMODE, "", ci->sslmode, sizeof(ci->sslmode), ODBC_INI); #ifdef _HANDLE_ENLIST_IN_DTC_ if (ci->xa_opt < 0 || overwrite) { SQLGetPrivateProfileString(DSN, INI_XAOPT, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) ci->xa_opt = atoi(temp); } #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* Force abbrev connstr or bde */ SQLGetPrivateProfileString(DSN, INI_EXTRAOPTIONS, "", temp, sizeof(temp), ODBC_INI); if (temp[0]) { UInt4 val = 0; sscanf(temp, "%x", &val); replaceExtraOptions(ci, val, overwrite); mylog("force_abbrev=%d bde=%d cvt_null_date=%d\n", ci->force_abbrev_connstr, ci->bde_environment, ci->cvt_null_date_string); } /* Allow override of odbcinst.ini parameters here */ getCommonDefaults(DSN, ODBC_INI, ci); qlog("DSN info: DSN='%s',server='%s',port='%s',dbase='%s',user='%s',passwd='%s'\n", DSN, ci->server, ci->port, ci->database, ci->username, NAME_IS_VALID(ci->password) ? "xxxxx" : ""); qlog(" onlyread='%s',protocol='%s',showoid='%s',fakeoidindex='%s',showsystable='%s'\n", ci->onlyread, ci->protocol, ci->show_oid_column, ci->fake_oid_index, ci->show_system_tables); if (get_qlog()) { char *enc = (char *) check_client_encoding(ci->conn_settings); qlog(" conn_settings='%s', conn_encoding='%s'\n", ci->conn_settings, NULL != enc ? enc : "(null)"); if (NULL != enc) free(enc); qlog(" translation_dll='%s',translation_option='%s'\n", ci->translation_dll, ci->translation_option); } } /* * This function writes any global parameters (that can be manipulated) * to the ODBCINST.INI portion of the registry */ int writeDriverCommoninfo(const char *fileName, const char *sectionName, const GLOBAL_VALUES *comval) { char tmp[128]; int errc = 0; if (stricmp(ODBCINST_INI, fileName) == 0 && NULL == sectionName) sectionName = DBMS_NAME; sprintf(tmp, "%d", comval->commlog); if (!SQLWritePrivateProfileString(sectionName, INI_COMMLOG, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->debug); if (!SQLWritePrivateProfileString(sectionName, INI_DEBUG, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->fetch_max); if (!SQLWritePrivateProfileString(sectionName, INI_FETCH, tmp, fileName)) errc--; if (stricmp(ODBCINST_INI, fileName) == 0) return errc; sprintf(tmp, "%d", comval->fetch_max); if (!SQLWritePrivateProfileString(sectionName, INI_FETCH, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->disable_optimizer); if (!SQLWritePrivateProfileString(sectionName, INI_OPTIMIZER, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->ksqo); if (!SQLWritePrivateProfileString(sectionName, INI_KSQO, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->unique_index); if (!SQLWritePrivateProfileString(sectionName, INI_UNIQUEINDEX, tmp, fileName)) errc--; /* * Never update the onlyread from this module. */ if (stricmp(ODBCINST_INI, fileName) == 0) { sprintf(tmp, "%d", comval->onlyread); SQLWritePrivateProfileString(sectionName, INI_READONLY, tmp, fileName); } sprintf(tmp, "%d", comval->use_declarefetch); if (!SQLWritePrivateProfileString(sectionName, INI_USEDECLAREFETCH, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->unknown_sizes); if (!SQLWritePrivateProfileString(sectionName, INI_UNKNOWNSIZES, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->text_as_longvarchar); if (!SQLWritePrivateProfileString(sectionName, INI_TEXTASLONGVARCHAR, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->unknowns_as_longvarchar); if (!SQLWritePrivateProfileString(sectionName, INI_UNKNOWNSASLONGVARCHAR, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->bools_as_char); if (!SQLWritePrivateProfileString(sectionName, INI_BOOLSASCHAR, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->parse); if (!SQLWritePrivateProfileString(sectionName, INI_PARSE, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->cancel_as_freestmt); if (!SQLWritePrivateProfileString(sectionName, INI_CANCELASFREESTMT, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->max_varchar_size); if (!SQLWritePrivateProfileString(sectionName, INI_MAXVARCHARSIZE, tmp, fileName)) errc--; sprintf(tmp, "%d", comval->max_longvarchar_size); if (!SQLWritePrivateProfileString(sectionName, INI_MAXLONGVARCHARSIZE, tmp, fileName)) errc--; if (!SQLWritePrivateProfileString(sectionName, INI_EXTRASYSTABLEPREFIXES, comval->extra_systable_prefixes, fileName)) errc--; /* * Never update the conn_setting from this module * SQLWritePrivateProfileString(sectionName, INI_CONNSETTINGS, * comval->conn_settings, fileName); */ return errc; } /* This is for datasource based options only */ void writeDSNinfo(const ConnInfo *ci) { const char *DSN = ci->dsn; char encoded_item[LARGE_REGISTRY_LEN], temp[SMALL_REGISTRY_LEN]; SQLWritePrivateProfileString(DSN, INI_KDESC, ci->desc, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_DATABASE, ci->database, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_SERVER, ci->server, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_PORT, ci->port, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_USERNAME, ci->username, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_UID, ci->username, ODBC_INI); encode(ci->password, encoded_item, sizeof(encoded_item)); SQLWritePrivateProfileString(DSN, INI_PASSWORD, encoded_item, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_READONLY, ci->onlyread, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_SHOWOIDCOLUMN, ci->show_oid_column, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_FAKEOIDINDEX, ci->fake_oid_index, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_ROWVERSIONING, ci->row_versioning, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_SHOWSYSTEMTABLES, ci->show_system_tables, ODBC_INI); if (ci->rollback_on_error >= 0) sprintf(temp, "%s-%d", ci->protocol, ci->rollback_on_error); else strncpy_null(temp, ci->protocol, sizeof(temp)); SQLWritePrivateProfileString(DSN, INI_PROTOCOL, temp, ODBC_INI); encode(ci->conn_settings, encoded_item, sizeof(encoded_item)); SQLWritePrivateProfileString(DSN, INI_CONNSETTINGS, encoded_item, ODBC_INI); sprintf(temp, "%d", ci->disallow_premature); SQLWritePrivateProfileString(DSN, INI_DISALLOWPREMATURE, temp, ODBC_INI); sprintf(temp, "%d", ci->allow_keyset); SQLWritePrivateProfileString(DSN, INI_UPDATABLECURSORS, temp, ODBC_INI); sprintf(temp, "%d", ci->lf_conversion); SQLWritePrivateProfileString(DSN, INI_LFCONVERSION, temp, ODBC_INI); sprintf(temp, "%d", ci->true_is_minus1); SQLWritePrivateProfileString(DSN, INI_TRUEISMINUS1, temp, ODBC_INI); sprintf(temp, "%d", ci->int8_as); SQLWritePrivateProfileString(DSN, INI_INT8AS, temp, ODBC_INI); sprintf(temp, "%x", getExtraOptions(ci)); SQLWritePrivateProfileString(DSN, INI_EXTRAOPTIONS, temp, ODBC_INI); sprintf(temp, "%d", ci->bytea_as_longvarbinary); SQLWritePrivateProfileString(DSN, INI_BYTEAASLONGVARBINARY, temp, ODBC_INI); sprintf(temp, "%d", ci->use_server_side_prepare); SQLWritePrivateProfileString(DSN, INI_USESERVERSIDEPREPARE, temp, ODBC_INI); sprintf(temp, "%d", ci->lower_case_identifier); SQLWritePrivateProfileString(DSN, INI_LOWERCASEIDENTIFIER, temp, ODBC_INI); sprintf(temp, "%d", ci->gssauth_use_gssapi); SQLWritePrivateProfileString(DSN, INI_GSSAUTHUSEGSSAPI, temp, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_SSLMODE, ci->sslmode, ODBC_INI); #ifdef _HANDLE_ENLIST_IN_DTC_ sprintf(temp, "%d", ci->xa_opt); SQLWritePrivateProfileString(DSN, INI_XAOPT, temp, ODBC_INI); #endif /* _HANDLE_ENLIST_IN_DTC_ */ } /* * This function reads the ODBCINST.INI portion of * the registry and gets any driver defaults. */ void getCommonDefaults(const char *section, const char *filename, ConnInfo *ci) { CSTR func = "getCommonDefaults"; char temp[256]; GLOBAL_VALUES *comval; BOOL inst_position = (stricmp(filename, ODBCINST_INI) == 0); const char *drivername = (inst_position ? section : ci->drivername); mylog("%s:setting %s position of %p\n", func, filename, ci); if (ci) comval = &(ci->drivers); else comval = &globals; /* Fetch Count is stored in driver section */ SQLGetPrivateProfileString(section, INI_FETCH, "", temp, sizeof(temp), filename); if (temp[0]) { comval->fetch_max = atoi(temp); /* sanity check if using cursors */ if (comval->fetch_max <= 0) comval->fetch_max = FETCH_MAX; } else if (inst_position) comval->fetch_max = FETCH_MAX; /* Socket Buffersize is stored in driver section */ SQLGetPrivateProfileString(section, INI_SOCKET, "", temp, sizeof(temp), filename); if (temp[0]) comval->socket_buffersize = atoi(temp); else if (inst_position) comval->socket_buffersize = SOCK_BUFFER_SIZE; /* Debug is stored in the driver section */ SQLGetPrivateProfileString(section, INI_DEBUG, "", temp, sizeof(temp), filename); if (temp[0]) comval->debug = atoi(temp); else if (inst_position) comval->debug = DEFAULT_DEBUG; /* CommLog is stored in the driver section */ SQLGetPrivateProfileString(section, INI_COMMLOG, "", temp, sizeof(temp), filename); if (temp[0]) comval->commlog = atoi(temp); else if (inst_position) comval->commlog = DEFAULT_COMMLOG; if (!ci) logs_on_off(0, 0, 0); /* Optimizer is stored in the driver section only */ SQLGetPrivateProfileString(section, INI_OPTIMIZER, "", temp, sizeof(temp), filename); if (temp[0]) comval->disable_optimizer = atoi(temp); else if (inst_position) comval->disable_optimizer = DEFAULT_OPTIMIZER; /* KSQO is stored in the driver section only */ SQLGetPrivateProfileString(section, INI_KSQO, "", temp, sizeof(temp), filename); if (temp[0]) comval->ksqo = atoi(temp); else if (inst_position) comval->ksqo = DEFAULT_KSQO; /* Recognize Unique Index is stored in the driver section only */ SQLGetPrivateProfileString(section, INI_UNIQUEINDEX, "", temp, sizeof(temp), filename); if (temp[0]) comval->unique_index = atoi(temp); else if (inst_position) comval->unique_index = DEFAULT_UNIQUEINDEX; /* Unknown Sizes is stored in the driver section only */ SQLGetPrivateProfileString(section, INI_UNKNOWNSIZES, "", temp, sizeof(temp), filename); if (temp[0]) comval->unknown_sizes = atoi(temp); else if (inst_position) comval->unknown_sizes = DEFAULT_UNKNOWNSIZES; /* Lie about supported functions? */ SQLGetPrivateProfileString(section, INI_LIE, "", temp, sizeof(temp), filename); if (temp[0]) comval->lie = atoi(temp); else if (inst_position) comval->lie = DEFAULT_LIE; /* Parse statements */ SQLGetPrivateProfileString(section, INI_PARSE, "", temp, sizeof(temp), filename); if (temp[0]) comval->parse = atoi(temp); else if (inst_position) comval->parse = DEFAULT_PARSE; /* SQLCancel calls SQLFreeStmt in Driver Manager */ SQLGetPrivateProfileString(section, INI_CANCELASFREESTMT, "", temp, sizeof(temp), filename); if (temp[0]) comval->cancel_as_freestmt = atoi(temp); else if (inst_position) comval->cancel_as_freestmt = DEFAULT_CANCELASFREESTMT; /* UseDeclareFetch is stored in the driver section only */ SQLGetPrivateProfileString(section, INI_USEDECLAREFETCH, "", temp, sizeof(temp), filename); if (temp[0]) comval->use_declarefetch = atoi(temp); else if (inst_position) comval->use_declarefetch = DEFAULT_USEDECLAREFETCH; /* Max Varchar Size */ SQLGetPrivateProfileString(section, INI_MAXVARCHARSIZE, "", temp, sizeof(temp), filename); if (temp[0]) comval->max_varchar_size = atoi(temp); else if (inst_position) comval->max_varchar_size = MAX_VARCHAR_SIZE; /* Max TextField Size */ SQLGetPrivateProfileString(section, INI_MAXLONGVARCHARSIZE, "", temp, sizeof(temp), filename); if (temp[0]) comval->max_longvarchar_size = atoi(temp); else if (inst_position) comval->max_longvarchar_size = TEXT_FIELD_SIZE; /* Text As LongVarchar */ SQLGetPrivateProfileString(section, INI_TEXTASLONGVARCHAR, "", temp, sizeof(temp), filename); if (temp[0]) comval->text_as_longvarchar = atoi(temp); else if (inst_position) comval->text_as_longvarchar = DEFAULT_TEXTASLONGVARCHAR; /* Unknowns As LongVarchar */ SQLGetPrivateProfileString(section, INI_UNKNOWNSASLONGVARCHAR, "", temp, sizeof(temp), filename); if (temp[0]) comval->unknowns_as_longvarchar = atoi(temp); else if (inst_position) comval->unknowns_as_longvarchar = DEFAULT_UNKNOWNSASLONGVARCHAR; /* Bools As Char */ SQLGetPrivateProfileString(section, INI_BOOLSASCHAR, "", temp, sizeof(temp), filename); if (temp[0]) comval->bools_as_char = atoi(temp); else if (inst_position) comval->bools_as_char = DEFAULT_BOOLSASCHAR; /* Extra Systable prefixes */ /* * Use @@@ to distinguish between blank extra prefixes and no key * entry */ SQLGetPrivateProfileString(section, INI_EXTRASYSTABLEPREFIXES, "@@@", temp, sizeof(temp), filename); if (strcmp(temp, "@@@")) strcpy(comval->extra_systable_prefixes, temp); else if (inst_position) strcpy(comval->extra_systable_prefixes, DEFAULT_EXTRASYSTABLEPREFIXES); mylog("ci=%p globals.extra_systable_prefixes = '%s'\n", ci, comval->extra_systable_prefixes); /* Dont allow override of an override! */ if (inst_position) { char conn_settings[LARGE_REGISTRY_LEN]; /* * ConnSettings is stored in the driver section and per datasource * for override */ SQLGetPrivateProfileString(section, INI_CONNSETTINGS, "", conn_settings, sizeof(conn_settings), filename); if ('\0' != conn_settings[0]) STRX_TO_NAME(comval->conn_settings, conn_settings); /* Default state for future DSN's Readonly attribute */ SQLGetPrivateProfileString(section, INI_READONLY, "", temp, sizeof(temp), filename); if (temp[0]) comval->onlyread = atoi(temp); else comval->onlyread = DEFAULT_READONLY; /* * Default state for future DSN's protocol attribute This isn't a * real driver option YET. This is more intended for * customization from the install. */ SQLGetPrivateProfileString(section, INI_PROTOCOL, "@@@", temp, sizeof(temp), filename); if (strcmp(temp, "@@@")) strncpy_null(comval->protocol, temp, sizeof(comval->protocol)); else strcpy(comval->protocol, DEFAULT_PROTOCOL); } STR_TO_NAME(comval->drivername, drivername); } static void encode(const pgNAME in, char *out, int outlen) { size_t i, ilen, o = 0; char inc, *ins; if (NAME_IS_NULL(in)) { out[0] = '\0'; return; } ins = GET_NAME(in); ilen = strlen(ins); for (i = 0; i < ilen && o < outlen - 1; i++) { inc = ins[i]; if (inc == '+') { if (o + 2 >= outlen) break; sprintf(&out[o], "%%2B"); o += 3; } else if (isspace((unsigned char) inc)) out[o++] = '+'; else if (!isalnum((unsigned char) inc)) { if (o + 2 >= outlen) break; sprintf(&out[o], "%%%02x", inc); o += 3; } else out[o++] = inc; } out[o++] = '\0'; } static unsigned int conv_from_hex(const char *s) { int i, y = 0, val; for (i = 1; i <= 2; i++) { if (s[i] >= 'a' && s[i] <= 'f') val = s[i] - 'a' + 10; else if (s[i] >= 'A' && s[i] <= 'F') val = s[i] - 'A' + 10; else val = s[i] - '0'; y += val << (4 * (2 - i)); } return y; } static pgNAME decode(const char *in) { size_t i, ilen = strlen(in), o = 0; char inc, *outs; pgNAME out; INIT_NAME(out); if (0 == ilen) { return out; } outs = (char *) malloc(ilen + 1); for (i = 0; i < ilen; i++) { inc = in[i]; if (inc == '+') outs[o++] = ' '; else if (inc == '%') { sprintf(&outs[o++], "%c", conv_from_hex(&in[i])); i += 2; } else outs[o++] = inc; } outs[o++] = '\0'; STR_TO_NAME(out, outs); free(outs); return out; } /* * Remove braces if the input value is enclosed by braces({}). * Othewise decode the input value. */ static pgNAME decode_or_remove_braces(const char *in) { if ('{' == in[0]) { size_t inlen = strlen(in); if ('}' == in[inlen - 1]) /* enclosed by braces */ { pgNAME out; INIT_NAME(out); STRN_TO_NAME(out, in + 1, inlen - 2); return out; } } return decode(in); } char *extract_attribute_setting(const char *str, const char *attr, BOOL ref_comment) { const char *cptr, *sptr = NULL; char *rptr; BOOL allowed_cmd = TRUE, in_quote = FALSE, in_comment = FALSE; int step = 0, skiplen; size_t len = 0, attrlen = strlen(attr); for (cptr = str; *cptr; cptr++) { if (in_quote) { if (LITERAL_QUOTE == *cptr) { if (4 == step) { len = cptr - sptr; step++; } in_quote = FALSE; } continue; } else if (in_comment) { if ('*' == *cptr && '/' == cptr[1]) { if (4 == step) { len = cptr - sptr; step++; } in_comment = FALSE; cptr++; continue; } if (!ref_comment) continue; } else if ('/' == *cptr && '*' == cptr[1]) { in_comment = TRUE; cptr++; continue; } if (';' == *cptr) { if (4 == step) { len = cptr - sptr; } allowed_cmd = TRUE; step = 0; continue; } if (!allowed_cmd) continue; if (isspace((unsigned char) *cptr)) { if (4 == step) { len = cptr - sptr; step++; } continue; } switch (step) { case 0: if (0 != strnicmp(cptr, "set", 3)) { allowed_cmd = FALSE; continue; } step++; cptr += 3; break; case 1: if (0 != strnicmp(cptr, attr, attrlen)) { allowed_cmd = FALSE; continue; } step++; cptr += (attrlen - 1); break; case 2: skiplen = 0; if (0 != strnicmp(cptr, "=", 1)) { skiplen = (int) strlen("to"); if (0 != strnicmp(cptr, "to", 2)) { allowed_cmd = FALSE; continue; } } step++; cptr += skiplen; break; case 3: if (LITERAL_QUOTE == *cptr) { cptr++; sptr = cptr; } else sptr = cptr; step++; break; } } if (!sptr) return NULL; rptr = malloc(len + 1); memcpy(rptr, sptr, len); rptr[len] = '\0'; mylog("extracted a %s '%s' from %s\n", attr, rptr, str); return rptr; } /* * extract the specified attribute from the comment part. * attribute=[']value['] */ char *extract_extra_attribute_setting(const pgNAME setting, const char *attr) { const char *str = GET_NAME(setting); const char *cptr, *sptr = NULL; char *rptr; BOOL allowed_cmd = FALSE, in_quote = FALSE, in_comment = FALSE; int step = 0, step_last = 2; size_t len = 0, attrlen = strlen(attr); for (cptr = str; *cptr; cptr++) { if (in_quote) { if (LITERAL_QUOTE == *cptr) { if (step_last == step) { len = cptr - sptr; step = 0; } in_quote = FALSE; } continue; } else if (in_comment) { if ('*' == *cptr && '/' == cptr[1]) { if (step_last == step) { len = cptr - sptr; step = 0; } in_comment = FALSE; allowed_cmd = FALSE; cptr++; continue; } } else if ('/' == *cptr && '*' == cptr[1]) { in_comment = TRUE; allowed_cmd = TRUE; cptr++; continue; } else { if (LITERAL_QUOTE == *cptr) in_quote = TRUE; continue; } /* now in comment */ if (';' == *cptr || isspace((unsigned char) *cptr)) { if (step_last == step) len = cptr - sptr; allowed_cmd = TRUE; step = 0; continue; } if (!allowed_cmd) continue; switch (step) { case 0: if (0 != strnicmp(cptr, attr, attrlen)) { allowed_cmd = FALSE; continue; } if (cptr[attrlen] != '=') { allowed_cmd = FALSE; continue; } step++; cptr += attrlen; break; case 1: if (LITERAL_QUOTE == *cptr) { in_quote = TRUE; cptr++; sptr = cptr; } else sptr = cptr; step++; break; } } if (!sptr) return NULL; rptr = malloc(len + 1); memcpy(rptr, sptr, len); rptr[len] = '\0'; mylog("extracted a %s '%s' from %s\n", attr, rptr, str); return rptr; } psqlodbc-09.03.0300/loadlib.c000644 001752 000000 00000031734 12335653444 015762 0ustar00saitowheel000000 000000 /*------ * Module: loadlib.c * * Description: This module contains routines related to * delay load import libraries. * * Comments: See "readme.txt" for copyright and license information. *------- */ #include #include #include #ifndef WIN32 #include #endif /* WIN32 */ #include "loadlib.h" #ifdef USE_LIBPQ #ifdef RESET_CRYPTO_CALLBACKS #include #endif /* RESET_CRYPTO_CALLBACKS */ #include #endif /* USE_LIBPQ */ #include "pgenlist.h" #ifdef WIN32 #ifdef _MSC_VER #pragma comment(lib, "Delayimp") #ifdef USE_LIBPQ #pragma comment(lib, "libpq") #pragma comment(lib, "ssleay32") #ifdef RESET_CRYPTO_CALLBACKS #pragma comment(lib, "libeay32") #endif /* RESET_CRYPTO_CALLBACKS */ #endif /* USE_LIBPQ */ #ifdef _HANDLE_ENLIST_IN_DTC_ #ifdef UNICODE_SUPPORT #pragma comment(lib, "pgenlist") #else #pragma comment(lib, "pgenlista") #endif /* UNICODE_SUPPORT */ #endif /* _HANDLE_ENLIST_IN_DTC_ */ // The followings works under VC++6.0 but doesn't work under VC++7.0. // Please add the equivalent linker options using command line etc. #if (_MSC_VER == 1200) && defined(DYNAMIC_LOAD) // VC6.0 #ifdef USE_LIBPQ #pragma comment(linker, "/Delayload:libpq.dll") #pragma comment(linker, "/Delayload:ssleay32.dll") #ifdef RESET_CRYPTO_CALLBACKS #pragma comment(linker, "/Delayload:libeay32.dll") #endif /* RESET_CRYPTO_CALLBACKS */ #endif /* USE_LIBPQ */ #ifdef UNICODE_SUPPORT #pragma comment(linker, "/Delayload:pgenlist.dll") #else #pragma comment(linker, "/Delayload:pgenlista.dll") #endif /* UNICODE_SUPPORT */ #pragma comment(linker, "/Delay:UNLOAD") #endif /* _MSC_VER */ #endif /* _MSC_VER */ #if defined(DYNAMIC_LOAD) #define WIN_DYN_LOAD CSTR libpqdll = "LIBPQ.dll"; #ifdef _WIN64 CSTR gssapidll = "GSSAPI64.dll"; #else CSTR gssapidll = "GSSAPI32.dll"; #endif /* _WIN64 */ #ifdef UNICODE_SUPPORT CSTR pgenlist = "pgenlist"; CSTR pgenlistdll = "PGENLIST.dll"; #else CSTR pgenlist = "pgenlista"; CSTR pgenlistdll = "PGENLISTA.dll"; #endif /* UNICODE_SUPPORT */ #if defined(_MSC_VER) && (_MSC_VER >= 1200) #define _MSC_DELAY_LOAD_IMPORT #endif /* MSC_VER */ #endif /* DYNAMIC_LOAD */ #endif /* WIN32 */ CSTR libpqlib = "libpq"; #ifdef _WIN64 CSTR gssapilib = "gssapi64"; #else CSTR gssapilib = "gssapi32"; #endif /* _WIN64 */ #ifdef USE_LIBPQ CSTR checkproc1 = "PQconnectdbParams"; static int connect_withparam_available = -1; CSTR checkproc2 = "PQconninfoParse"; static int sslverify_available = -1; #endif /* USE_LIBPQ */ #if defined(_MSC_DELAY_LOAD_IMPORT) static BOOL loaded_libpq = FALSE, loaded_ssllib = FALSE; static BOOL loaded_pgenlist = FALSE, loaded_gssapi = FALSE; /* * Load psqlodbc path based libpq dll. */ static HMODULE MODULE_load_from_psqlodbc_path(const char *module_name) { extern HINSTANCE s_hModule; HMODULE hmodule = NULL; char szFileName[MAX_PATH]; if (GetModuleFileName(s_hModule, szFileName, sizeof(szFileName)) > 0) { char drive[_MAX_DRIVE], dir[_MAX_DIR], sysdir[MAX_PATH]; _splitpath(szFileName, drive, dir, NULL, NULL); GetSystemDirectory(sysdir, MAX_PATH); snprintf(szFileName, sizeof(szFileName), "%s%s%s.dll", drive, dir, module_name); if (_strnicmp(szFileName, sysdir, strlen(sysdir)) != 0) { hmodule = LoadLibraryEx(szFileName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); mylog("psqlodbc path based %s loaded module=%p\n", module_name, hmodule); } } return hmodule; } /* * Error hook function for delay load import. * Try to load psqlodbc path based libpq. * Load alternative ssl library SSLEAY32 or LIBSSL32. */ #if (_MSC_VER < 1300) extern PfnDliHook __pfnDliFailureHook; extern PfnDliHook __pfnDliNotifyHook; #else extern PfnDliHook __pfnDliFailureHook2; extern PfnDliHook __pfnDliNotifyHook2; #endif /* _MSC_VER */ static FARPROC WINAPI DliErrorHook(unsigned dliNotify, PDelayLoadInfo pdli) { HMODULE hmodule = NULL; int i; static const char * const libarray[] = {"libssl32", "ssleay32"}; mylog("Dli%sHook %s Notify=%d\n", (dliFailLoadLib == dliNotify || dliFailGetProc == dliNotify) ? "Error" : "Notify", NULL != pdli->szDll ? pdli->szDll : pdli->dlp.szProcName, dliNotify); switch (dliNotify) { case dliNotePreLoadLibrary: case dliFailLoadLib: #if (_MSC_VER < 1300) __pfnDliNotifyHook = NULL; #else __pfnDliNotifyHook2 = NULL; #endif /* _MSC_VER */ if (_strnicmp(pdli->szDll, libpqlib, strlen(libpqlib)) == 0) { if (hmodule = MODULE_load_from_psqlodbc_path(libpqlib), NULL == hmodule) hmodule = LoadLibrary(libpqlib); #ifdef USE_LIBPQ if (NULL == hmodule) connect_withparam_available = sslverify_available = FALSE; if (connect_withparam_available < 0) { if (NULL == GetProcAddress(hmodule, checkproc1)) connect_withparam_available = FALSE; else connect_withparam_available = TRUE; inolog("connect_withparam_available=%d\n", connect_withparam_available); } if (sslverify_available < 0) { if (NULL == GetProcAddress(hmodule, checkproc2)) sslverify_available = FALSE; else sslverify_available = TRUE; } #endif /* USE_LIBPQ */ } else if (_strnicmp(pdli->szDll, pgenlist, strlen(pgenlist)) == 0) { if (hmodule = MODULE_load_from_psqlodbc_path(pgenlist), NULL == hmodule) hmodule = LoadLibrary(pgenlist); } #ifdef USE_GSS else if (_strnicmp(pdli->szDll, gssapilib, strlen(gssapilib)) == 0) { #ifdef USE_LIBPQ if (hmodule = GetModuleHandle(gssapilib), NULL == hmodule) #endif { if (hmodule = MODULE_load_from_psqlodbc_path(gssapilib), NULL == hmodule) { if (hmodule = LoadLibrary(gssapilib), NULL != hmodule) loaded_gssapi = TRUE; } else loaded_gssapi = TRUE; } } #endif /* USE_GSS */ else if (0 == _stricmp(pdli->szDll, libarray[0]) || 0 == _stricmp(pdli->szDll, libarray[1])) { mylog("getting alternative ssl library instead of %s\n", pdli->szDll); for (i = 0; i < sizeof(libarray) / sizeof(const char * const); i++) { if (hmodule = GetModuleHandle(libarray[i]), NULL != hmodule) break; } } break; } return (FARPROC) hmodule; } /* * unload delay loaded libraries. * * Openssl Library nmake defined * ssleay32.dll is vc make, libssl32.dll is mingw make. */ #ifndef SSL_DLL #define SSL_DLL "SSLEAY32.dll" #endif /* SSL_DLL */ typedef BOOL (WINAPI *UnloadFunc)(LPCSTR); void CleanupDelayLoadedDLLs(void) { BOOL success; #if (_MSC_VER < 1300) /* VC6 DELAYLOAD IMPORT */ UnloadFunc func = __FUnloadDelayLoadedDLL; #else UnloadFunc func = __FUnloadDelayLoadedDLL2; #endif /* The dll names are case sensitive for the unload helper */ if (loaded_libpq) { #ifdef RESET_CRYPTO_CALLBACKS /* * May be needed to avoid crash on exit * when libpq doesn't reset the callbacks. */ CRYPTO_set_locking_callback(NULL); CRYPTO_set_id_callback(NULL); mylog("passed RESET_CRYPTO_CALLBACKS\n"); #else mylog("not passed RESET_CRYPTO_CALLBACKS\n"); #endif /* RESET_CRYPTO_CALLBACKS */ success = (*func)(libpqdll); mylog("%s unload success=%d\n", libpqdll, success); } if (loaded_ssllib) { success = (*func)(SSL_DLL); mylog("ssldll unload success=%d\n", success); } if (loaded_pgenlist) { success = (*func)(pgenlistdll); mylog("%s unload success=%d\n", pgenlistdll, success); } if (loaded_gssapi) { success = (*func)(gssapidll); mylog("%s unload success=%d\n", gssapidll, success); } return; } #else void CleanupDelayLoadedDLLs(void) { return; } #endif /* _MSC_DELAY_LOAD_IMPORT */ #ifdef USE_LIBPQ #if defined(_MSC_DELAY_LOAD_IMPORT) static int filter_env2encoding(int level) { switch (level & 0xffff) { case ERROR_MOD_NOT_FOUND: case ERROR_PROC_NOT_FOUND: return EXCEPTION_EXECUTE_HANDLER; } return EXCEPTION_CONTINUE_SEARCH; } #endif /* _MSC_DELAY_LOAD_IMPORT */ BOOL ssl_verify_available(void) { if (sslverify_available < 0) { #if defined(_MSC_DELAY_LOAD_IMPORT) __try { #if (_MSC_VER < 1300) __pfnDliFailureHook = DliErrorHook; __pfnDliNotifyHook = DliErrorHook; #else __pfnDliFailureHook2 = DliErrorHook; __pfnDliNotifyHook2 = DliErrorHook; #endif /* _MSC_VER */ PQenv2encoding(); } __except (filter_env2encoding(GetExceptionCode())) { } if (sslverify_available < 0) sslverify_available = 0; #else sslverify_available = 1; #endif /* _MSC_DELAY_LOAD_IMPORT */ } return (0 != sslverify_available); } BOOL connect_with_param_available(void) { if (connect_withparam_available < 0) { #if defined(_MSC_DELAY_LOAD_IMPORT) __try { #if (_MSC_VER < 1300) __pfnDliFailureHook = DliErrorHook; __pfnDliNotifyHook = DliErrorHook; #else __pfnDliFailureHook2 = DliErrorHook; __pfnDliNotifyHook2 = DliErrorHook; #endif /* _MSC_VER */ PQescapeLiteral(NULL, NULL, 0); } __except (filter_env2encoding(GetExceptionCode())) { } if (connect_withparam_available < 0) { inolog("connect_withparam_available is set to false\n"); connect_withparam_available = 0; } #else #ifdef NOT_USED /* currently not yet used */ #ifdef HAVE_LIBLTDL lt_dlhandle dlhandle = lt_dlopenext(libpqlib); connect_withparam_available = 1; if (NULL != dlhandle) { if (NULL == lt_dlsym(dlhandle, checkproc1)) connect_withparam_available = 0; lt_dlclose(dlhandle); } #endif /* HAVE_LIBLTDL */ #endif /* NOT_USED */ #endif /* _MSC_DELAY_LOAD_IMPORT */ } return (0 != connect_withparam_available); } void *CALL_PQconnectdb(const char *conninfo, BOOL *libpqLoaded) { void *pqconn = NULL; *libpqLoaded = TRUE; #if defined(_MSC_DELAY_LOAD_IMPORT) __try { #if (_MSC_VER < 1300) __pfnDliFailureHook = DliErrorHook; __pfnDliNotifyHook = DliErrorHook; #else __pfnDliFailureHook2 = DliErrorHook; __pfnDliNotifyHook2 = DliErrorHook; #endif /* _MSC_VER */ inolog("calling PQconnectdb\n"); pqconn = PQconnectdb(conninfo); } __except ((GetExceptionCode() & 0xffff) == ERROR_MOD_NOT_FOUND ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { *libpqLoaded = FALSE; } #if (_MSC_VER < 1300) __pfnDliNotifyHook = NULL; #else __pfnDliNotifyHook2 = NULL; #endif /* _MSC_VER */ if (*libpqLoaded) { loaded_libpq = TRUE; /* ssllibs are already loaded by libpq if (PQgetssl(pqconn)) loaded_ssllib = TRUE; */ } #else pqconn = PQconnectdb(conninfo); #endif /* _MSC_DELAY_LOAD_IMPORT */ return pqconn; } void *CALL_PQconnectdbParams(const char *opts[], const char *vals[], BOOL *libpqLoaded) { void *pqconn = NULL; *libpqLoaded = TRUE; #if defined(_MSC_DELAY_LOAD_IMPORT) __try { #if (_MSC_VER < 1300) __pfnDliFailureHook = DliErrorHook; __pfnDliNotifyHook = DliErrorHook; #else __pfnDliFailureHook2 = DliErrorHook; __pfnDliNotifyHook2 = DliErrorHook; #endif /* _MSC_VER */ inolog("calling PQconnectdbParams\n"); pqconn = PQconnectdbParams(opts, vals, 0); } __except ((GetExceptionCode() & 0xffff) == ERROR_MOD_NOT_FOUND ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { *libpqLoaded = FALSE; } #if (_MSC_VER < 1300) __pfnDliNotifyHook = NULL; #else __pfnDliNotifyHook2 = NULL; #endif /* _MSC_VER */ if (*libpqLoaded) { loaded_libpq = TRUE; /* ssllibs are already loaded by libpq if (PQgetssl(pqconn)) loaded_ssllib = TRUE; */ } #else pqconn = PQconnectdbParams(opts, vals, 0); #endif /* _MSC_DELAY_LOAD_IMPORT */ return pqconn; } #else BOOL ssl_verify_available(void) { return FALSE; } BOOL connect_with_param_available(void) { return FALSE; } #endif /* USE_LIBPQ */ #ifdef _HANDLE_ENLIST_IN_DTC_ RETCODE CALL_EnlistInDtc(ConnectionClass *conn, void *pTra, int method) { RETCODE ret; BOOL loaded = TRUE; #if defined(_MSC_DELAY_LOAD_IMPORT) __try { #if (_MSC_VER < 1300) __pfnDliFailureHook = DliErrorHook; __pfnDliNotifyHook = DliErrorHook; #else __pfnDliFailureHook2 = DliErrorHook; __pfnDliNotifyHook2 = DliErrorHook; #endif /* _MSC_VER */ ret = EnlistInDtc(conn, pTra, method); } __except ((GetExceptionCode() & 0xffff) == ERROR_MOD_NOT_FOUND ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { loaded = FALSE; } if (loaded) loaded_pgenlist = TRUE; #if (_MSC_VER < 1300) __pfnDliNotifyHook = NULL; #else __pfnDliNotifyHook2 = NULL; #endif /* _MSC_VER */ #else ret = EnlistInDtc(conn, pTra, method); loaded_pgenlist = TRUE; #endif /* _MSC_DELAY_LOAD_IMPORT */ return ret; } RETCODE CALL_DtcOnDisconnect(ConnectionClass *conn) { if (loaded_pgenlist) return DtcOnDisconnect(conn); return FALSE; } RETCODE CALL_IsolateDtcConn(ConnectionClass *conn, BOOL continueConnection) { if (loaded_pgenlist) return IsolateDtcConn(conn, continueConnection); return FALSE; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ #if defined(WIN_DYN_LOAD) BOOL SSLLIB_check(void) { extern HINSTANCE s_hModule; HMODULE hmodule = NULL; mylog("checking libpq library\n"); /* First search the driver's folder */ #ifdef USE_LIBPQ if (NULL == (hmodule = MODULE_load_from_psqlodbc_path(libpqlib))) /* Second try the PATH ordinarily */ hmodule = LoadLibrary(libpqlib); mylog("libpq hmodule=%p\n", hmodule); #endif /* USE_LIBPQ */ #ifdef USE_SSPI if (NULL == hmodule) { hmodule = LoadLibrary("secur32.dll"); mylog("secur32 hmodule=%p\n", hmodule); } #endif /* USE_SSPI */ if (hmodule) FreeLibrary(hmodule); return (NULL != hmodule); } #else BOOL SSLLIB_check(void) { return TRUE; } #endif /* WIN_DYN_LOAD */ psqlodbc-09.03.0300/multibyte.c000644 001752 000000 00000033101 12335653444 016360 0ustar00saitowheel000000 000000 /*-------- * Module : multibyte.c * * Description: New Multibyte related additional function. * * Create 2001-03-03 Eiji Tokuya * New Create 2001-09-16 Eiji Tokuya *-------- */ #include "multibyte.h" #include "misc.h" #include "connection.h" #include "pgapifunc.h" #include #include #include #include #ifndef TRUE #define TRUE 1 #endif static pg_CS CS_Table[] = { { "SQL_ASCII", SQL_ASCII }, { "EUC_JP", EUC_JP }, { "EUC_CN", EUC_CN }, { "EUC_KR", EUC_KR }, { "EUC_TW", EUC_TW }, { "JOHAB", JOHAB }, /* since 7.3 */ { "UTF8", UTF8 }, /* since 7.2 */ { "MULE_INTERNAL",MULE_INTERNAL }, { "LATIN1", LATIN1 }, { "LATIN2", LATIN2 }, { "LATIN3", LATIN3 }, { "LATIN4", LATIN4 }, { "LATIN5", LATIN5 }, { "LATIN6", LATIN6 }, { "LATIN7", LATIN7 }, { "LATIN8", LATIN8 }, { "LATIN9", LATIN9 }, { "LATIN10", LATIN10 }, { "WIN1256", WIN1256 }, /* Arabic since 7.3 */ { "WIN1258", WIN1258 }, /* Vietnamese since 8.1 */ { "WIN866", WIN866 }, /* since 8.1 */ { "WIN874", WIN874 }, /* Thai since 7.3 */ { "KOI8", KOI8R }, { "WIN1251", WIN1251 }, /* Cyrillic */ { "WIN1252", WIN1252 }, /* Western Europe since 8.1 */ { "ISO_8859_5", ISO_8859_5 }, { "ISO_8859_6", ISO_8859_6 }, { "ISO_8859_7", ISO_8859_7 }, { "ISO_8859_8", ISO_8859_8 }, { "WIN1250", WIN1250 }, /* Central Europe */ { "WIN1253", WIN1253 }, /* Greek since 8.2 */ { "WIN1254", WIN1254 }, /* Turkish since 8.2 */ { "WIN1255", WIN1255 }, /* Hebrew since 8.2 */ { "WIN1257", WIN1257 }, /* Baltic(North Europe) since 8.2 */ { "EUC_JIS_2004", EUC_JIS_2004}, /* EUC for SHIFT-JIS-2004 Japanese, since 8.3 */ { "SJIS", SJIS }, { "BIG5", BIG5 }, { "GBK", GBK }, /* since 7.3 */ { "UHC", UHC }, /* since 7.3 */ { "GB18030", GB18030 }, /* since 7.3 */ { "SHIFT_JIS_2004", SHIFT_JIS_2004 }, /* SHIFT-JIS-2004 Japanese, standard JIS X 0213, since 8.3 */ { "OTHER", OTHER } }; static pg_CS CS_Alias[] = { { "UNICODE", UTF8 }, { "TCVN", WIN1258 }, { "ALT", WIN866 }, { "WIN", WIN1251 }, { "OTHER", OTHER } }; CSTR OTHER_STRING = "OTHER"; int pg_CS_code(const char *characterset_string) { int i, c = -1; for(i = 0; CS_Table[i].code != OTHER; i++) { if (0 == stricmp(characterset_string, CS_Table[i].name)) { c = CS_Table[i].code; break; } } if (c < 0) { for(i = 0; CS_Alias[i].code != OTHER; i++) { if (0 == stricmp(characterset_string, CS_Alias[i].name)) { c = CS_Alias[i].code; break; } } } if (c < 0) c = OTHER; return (c); } char * check_client_encoding(const pgNAME conn_settings) { const char *cptr, *sptr = NULL; char *rptr; BOOL allowed_cmd = TRUE, in_quote = FALSE; int step = 0; size_t len = 0; if (NAME_IS_NULL(conn_settings)) return NULL; for (cptr = SAFE_NAME(conn_settings); *cptr; cptr++) { if (in_quote) if (LITERAL_QUOTE == *cptr) { in_quote = FALSE; continue; } if (';' == *cptr) { allowed_cmd = TRUE; step = 0; continue; } if (!allowed_cmd) continue; if (isspace((unsigned char) *cptr)) continue; switch (step) { case 0: if (0 != strnicmp(cptr, "set", 3)) { allowed_cmd = FALSE; continue; } step++; cptr += 3; break; case 1: if (0 != strnicmp(cptr, "client_encoding", 15)) { allowed_cmd = FALSE; continue; } step++; cptr += 15; break; case 2: if (0 != strnicmp(cptr, "to", 2)) { allowed_cmd = FALSE; continue; } step++; cptr += 2; break; case 3: if (LITERAL_QUOTE == *cptr) { cptr++; for (sptr = cptr; *cptr && *cptr != LITERAL_QUOTE; cptr++) ; } else { for (sptr = cptr; *cptr && !isspace((unsigned char) *cptr); cptr++) ; } len = cptr - sptr; step++; break; } } if (!sptr) return NULL; rptr = malloc(len + 1); memcpy(rptr, sptr, len); rptr[len] = '\0'; mylog("extracted a client_encoding '%s' from conn_settings\n", rptr); return rptr; } static int pg_mb_maxlen(characterset_code) { switch (characterset_code) { case UTF8: return 6; case EUC_TW: return 4; case EUC_JIS_2004: case EUC_JP: case GB18030: return 3; case SHIFT_JIS_2004: case SJIS: case BIG5: case GBK: case UHC: case EUC_CN: case EUC_KR: case JOHAB: return 2; default: return 1; } } static int pg_CS_stat(int stat,unsigned int character,int characterset_code) { if (character == 0) stat = 0; switch (characterset_code) { case UTF8: { if (stat < 2 && character >= 0x80) { if (character >= 0xfc) stat = 6; else if (character >= 0xf8) stat = 5; else if (character >= 0xf0) stat = 4; else if (character >= 0xe0) stat = 3; else if (character >= 0xc0) stat = 2; } else if (stat >= 2 && character > 0x7f) stat--; else stat=0; } break; /* SHIFT_JIS_2004 Support. */ case SHIFT_JIS_2004: { if (stat < 2 && character >= 0x81 && character <= 0x9f) stat = 2; else if (stat < 2 && character >= 0xe0 && character <= 0xef) stat = 2; else if (stat < 2 && character >= 0xf0 && character <= 0xfc) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; /* Shift-JIS Support. */ case SJIS: { if (stat < 2 && character > 0x80 && !(character > 0x9f && character < 0xe0)) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; /* Chinese Big5 Support. */ case BIG5: { if (stat < 2 && character > 0xA0) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; /* Chinese GBK Support. */ case GBK: { if (stat < 2 && character > 0x7F) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; /* Korian UHC Support. */ case UHC: { if (stat < 2 && character > 0x7F) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; case EUC_JIS_2004: /* 0x8f is JIS X 0212 + JIS X 0213(2) 3 byte */ /* 0x8e is JIS X 0201 2 byte */ /* 0xa0-0xff is JIS X 0213(1) 2 byte */ case EUC_JP: /* 0x8f is JIS X 0212 3 byte */ /* 0x8e is JIS X 0201 2 byte */ /* 0xa0-0xff is JIS X 0208 2 byte */ { if (stat < 3 && character == 0x8f) /* JIS X 0212 */ stat = 3; else if (stat != 2 && (character == 0x8e || character > 0xa0)) /* Half Katakana HighByte & Kanji HighByte */ stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; /* EUC_CN, EUC_KR, JOHAB Support */ case EUC_CN: case EUC_KR: case JOHAB: { if (stat < 2 && character > 0xa0) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; case EUC_TW: { if (stat < 4 && character == 0x8e) stat = 4; else if (stat == 4 && character > 0xa0) stat = 3; else if ((stat == 3 || stat < 2) && character > 0xa0) stat = 2; else if (stat == 2) stat = 1; else stat = 0; } break; /*Chinese GB18030 support.Added by Bill Huang */ case GB18030: { if (stat < 2 && character > 0x80) stat = 2; else if (stat == 2) { if (character >= 0x30 && character <= 0x39) stat = 3; else stat = 1; } else if (stat == 3) { if (character >= 0x30 && character <= 0x39) stat = 1; else stat = 3; } else stat = 0; } break; default: { stat = 0; } break; } return stat; } UCHAR * pg_mbschr(int csc, const UCHAR *string, unsigned int character) { int mb_st = 0; const UCHAR *s, *rs = NULL; for(s = string; *s ; s++) { mb_st = pg_CS_stat(mb_st, (UCHAR) *s, csc); if (mb_st == 0 && (*s == character)) { rs = s; break; } } return ((UCHAR *) rs); } size_t pg_mbslen(int csc, const UCHAR *string) { UCHAR *s; size_t len; int cs_stat; for (len = 0, cs_stat = 0, s = (UCHAR *) string; *s != 0; s++) { cs_stat = pg_CS_stat(cs_stat,(unsigned int) *s, csc); if (cs_stat < 2) len++; } return len; } static char * CC_lookup_cs_new(ConnectionClass *self) { char *encstr = NULL; QResultClass *res; res = CC_send_query(self, "select pg_client_encoding()", NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL); if (QR_command_maybe_successful(res)) { const char *enc = QR_get_value_backend_text(res, 0, 0); if (enc) encstr = strdup(enc); } QR_Destructor(res); return encstr; } static char * CC_lookup_cs_old(ConnectionClass *self) { char *encstr = NULL; HSTMT hstmt; RETCODE result; result = PGAPI_AllocStmt(self, &hstmt, 0); if (!SQL_SUCCEEDED(result)) return encstr; result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) "Show Client_Encoding", SQL_NTS, 0); if (result == SQL_SUCCESS_WITH_INFO) { SQLCHAR sqlState[8]; char errormsg[128], enc[32]; if (PGAPI_Error(NULL, NULL, hstmt, sqlState, NULL, (SQLCHAR *) errormsg, sizeof(errormsg), NULL) == SQL_SUCCESS && sscanf(errormsg, "%*s %*s %*s %*s %*s %s", enc) > 0) encstr = strdup(enc); } PGAPI_FreeStmt(hstmt, SQL_DROP); return encstr; } /* * This function works under Windows or Unicode case only. * Simply returns NULL under other OSs. */ const char * get_environment_encoding(const ConnectionClass *conn, const char *setenc, const char *currenc, BOOL bStartup) { const char *wenc = NULL; #ifdef WIN32 int acp; #endif /* WIN32 */ #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) return "UTF8"; #endif /* UNICODE_SUPPORT */ if (setenc && stricmp(setenc, OTHER_STRING)) return setenc; if (wenc = getenv("PGCLIENTENCODING"), NULL != wenc) return wenc; #ifdef WIN32 acp = GetACP(); if (acp >= 1251 && acp <= 1258) { if (bStartup || stricmp(currenc, "SQL_ASCII") == 0) return wenc; } switch (acp) { case 932: wenc = "SJIS"; break; case 936: if (!bStartup && PG_VERSION_GT(conn, 7.2)) wenc = "GBK"; break; case 949: if (!bStartup && PG_VERSION_GT(conn, 7.2)) wenc = "UHC"; break; case 950: wenc = "BIG5"; break; case 1250: wenc = "WIN1250"; break; case 1251: wenc = "WIN1251"; break; case 1256: if (PG_VERSION_GE(conn, 7.3)) wenc = "WIN1256"; break; case 1252: if (strnicmp(currenc, "LATIN", 5) == 0) break; if (PG_VERSION_GE(conn, 8.1)) wenc = "WIN1252"; else wenc = "LATIN1"; break; case 1258: if (PG_VERSION_GE(conn, 8.1)) wenc = "WIN1258"; break; case 1253: if (PG_VERSION_GE(conn, 8.2)) wenc = "WIN1253"; break; case 1254: if (PG_VERSION_GE(conn, 8.2)) wenc = "WIN1254"; break; case 1255: if (PG_VERSION_GE(conn, 8.2)) wenc = "WIN1255"; break; case 1257: if (PG_VERSION_GE(conn, 8.2)) wenc = "WIN1257"; break; } #endif /* WIN32 */ return wenc; } void CC_lookup_characterset(ConnectionClass *self) { char *encspec = NULL, *currenc = NULL, *tencstr; CSTR func = "CC_lookup_characterset"; mylog("%s: entering...\n", func); if (self->original_client_encoding) encspec = strdup(self->original_client_encoding); if (self->current_client_encoding) currenc = strdup(self->current_client_encoding); else if (PG_VERSION_LT(self, 7.2)) currenc = CC_lookup_cs_old(self); else currenc = CC_lookup_cs_new(self); tencstr = encspec ? encspec : currenc; if (self->original_client_encoding) { if (stricmp(self->original_client_encoding, tencstr)) { char msg[256]; snprintf(msg, sizeof(msg), "The client_encoding '%s' was changed to '%s'", self->original_client_encoding, tencstr); CC_set_error(self, CONN_OPTION_VALUE_CHANGED, msg, func); } free(self->original_client_encoding); } #ifndef UNICODE_SUPPORT else { const char *wenc = get_environment_encoding(self, encspec, currenc, FALSE); if (wenc && (!tencstr || stricmp(tencstr, wenc))) { QResultClass *res; char query[64]; int errnum = CC_get_errornumber(self); BOOL cmd_success; sprintf(query, "set client_encoding to '%s'", wenc); res = CC_send_query(self, query, NULL, IGNORE_ABORT_ON_CONN | ROLLBACK_ON_ERROR, NULL); cmd_success = QR_command_maybe_successful(res); QR_Destructor(res); CC_set_errornumber(self, errnum); if (cmd_success) { self->original_client_encoding = strdup(wenc); self->ccsc = pg_CS_code(self->original_client_encoding); if (encspec) free(encspec); if (currenc) free(currenc); return; } } } #endif /* UNICODE_SUPPORT */ if (tencstr) { self->original_client_encoding = tencstr; if (encspec && currenc) free(currenc); self->ccsc = pg_CS_code(tencstr); qlog(" [ Client encoding = '%s' (code = %d) ]\n", self->original_client_encoding, self->ccsc); if (self->ccsc < 0) { char msg[256]; snprintf(msg, sizeof(msg), "would handle the encoding '%s' like ASCII", tencstr); CC_set_error(self, CONN_OPTION_VALUE_CHANGED, msg, func); } } else { self->ccsc = SQL_ASCII; self->original_client_encoding = NULL; } self->mb_maxbyte_per_char = pg_mb_maxlen(self->ccsc); } void encoded_str_constr(encoded_str *encstr, int ccsc, const char *str) { encstr->ccsc = ccsc; encstr->encstr = str; encstr->pos = -1; encstr->ccst = 0; } int encoded_nextchar(encoded_str *encstr) { int chr; chr = encstr->encstr[++encstr->pos]; encstr->ccst = pg_CS_stat(encstr->ccst, (unsigned int) chr, encstr->ccsc); return chr; } ssize_t encoded_position_shift(encoded_str *encstr, size_t shift) { encstr->pos += shift; return encstr->pos; } int encoded_byte_check(encoded_str *encstr, size_t abspos) { int chr; chr = encstr->encstr[encstr->pos = abspos]; encstr->ccst = pg_CS_stat(encstr->ccst, (unsigned int) chr, encstr->ccsc); return chr; } psqlodbc-09.03.0300/odbcapi.c000644 001752 000000 00000125114 12335653444 015751 0ustar00saitowheel000000 000000 /*------- * Module: odbcapi.c * * Description: This module contains routines related to * preparing and executing an SQL statement. * * Classes: n/a * * API functions: SQLAllocConnect, SQLAllocEnv, SQLAllocStmt, SQLBindCol, SQLCancel, SQLColumns, SQLConnect, SQLDataSources, SQLDescribeCol, SQLDisconnect, SQLError, SQLExecDirect, SQLExecute, SQLFetch, SQLFreeConnect, SQLFreeEnv, SQLFreeStmt, SQLGetConnectOption, SQLGetCursorName, SQLGetData, SQLGetFunctions, SQLGetInfo, SQLGetStmtOption, SQLGetTypeInfo, SQLNumResultCols, SQLParamData, SQLPrepare, SQLPutData, SQLRowCount, SQLSetConnectOption, SQLSetCursorName, SQLSetParam, SQLSetStmtOption, SQLSpecialColumns, SQLStatistics, SQLTables, SQLTransact, SQLColAttributes, SQLColumnPrivileges, SQLDescribeParam, SQLExtendedFetch, SQLForeignKeys, SQLMoreResults, SQLNativeSql, SQLNumParams, SQLParamOptions, SQLPrimaryKeys, SQLProcedureColumns, SQLProcedures, SQLSetPos, SQLTablePrivileges, SQLBindParameter *------- */ #include "psqlodbc.h" #include #include #include "misc.h" #include "pgapifunc.h" #include "environ.h" #include "connection.h" #include "statement.h" #include "qresult.h" #include "loadlib.h" #if (ODBCVER < 0x0300) RETCODE SQL_API SQLAllocConnect(HENV EnvironmentHandle, HDBC FAR * ConnectionHandle) { RETCODE ret; EnvironmentClass *env = (EnvironmentClass *) EnvironmentHandle; mylog("[SQLAllocConnect]"); ENTER_ENV_CS(env); ret = PGAPI_AllocConnect(EnvironmentHandle, ConnectionHandle); LEAVE_ENV_CS(env); return ret; } RETCODE SQL_API SQLAllocEnv(HENV FAR * EnvironmentHandle) { RETCODE ret; mylog("[SQLAllocEnv]"); ret = PGAPI_AllocEnv(EnvironmentHandle); return ret; } RETCODE SQL_API SQLAllocStmt(HDBC ConnectionHandle, HSTMT *StatementHandle) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[SQLAllocStmt]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_AllocStmt(ConnectionHandle, StatementHandle, PODBC_EXTERNAL_STATEMENT | PODBC_INHERIT_CONNECT_OPTIONS); LEAVE_CONN_CS(conn); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLBindCol(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, PTR TargetValue, SQLLEN BufferLength, SQLLEN *StrLen_or_Ind) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLBindCol]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_BindCol(StatementHandle, ColumnNumber, TargetType, TargetValue, BufferLength, StrLen_or_Ind); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLCancel(HSTMT StatementHandle) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLCancel]"); /* Not that neither ENTER_STMT_CS nor StartRollbackState is called */ /* SC_clear_error((StatementClass *) StatementHandle); maybe this neither */ ret = PGAPI_Cancel(StatementHandle); return DiscardStatementSvp(stmt, ret, FALSE); } static BOOL theResultIsEmpty(const StatementClass *stmt) { QResultClass *res = SC_get_Result(stmt); if (NULL == res) return FALSE; return (0 == QR_get_num_total_tuples(res)); } RETCODE SQL_API SQLColumns(HSTMT StatementHandle, SQLCHAR *CatalogName, SQLSMALLINT NameLength1, SQLCHAR *SchemaName, SQLSMALLINT NameLength2, SQLCHAR *TableName, SQLSMALLINT NameLength3, SQLCHAR *ColumnName, SQLSMALLINT NameLength4) { CSTR func = "SQLColumns"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; SQLCHAR *ctName = CatalogName, *scName = SchemaName, *tbName = TableName, *clName = ColumnName; UWORD flag = PODBC_SEARCH_PUBLIC_SCHEMA; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Columns(StatementHandle, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, clName, NameLength4, flag, 0, 0); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt = NULL, *newSc = NULL, *newTb = NULL, *newCl = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, CatalogName, NameLength1, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, SchemaName, NameLength2, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, TableName, NameLength3, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (newCl = make_lstring_ifneeded(conn, ColumnName, NameLength4, ifallupper), NULL != newCl) { clName = newCl; reexec = TRUE; } if (reexec) { ret = PGAPI_Columns(StatementHandle, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, clName, NameLength4, flag, 0, 0); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); if (newCl) free(newCl); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLConnect(HDBC ConnectionHandle, SQLCHAR *ServerName, SQLSMALLINT NameLength1, SQLCHAR *UserName, SQLSMALLINT NameLength2, SQLCHAR *Authentication, SQLSMALLINT NameLength3) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[SQLConnect]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_Connect(ConnectionHandle, ServerName, NameLength1, UserName, NameLength2, Authentication, NameLength3); LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLDriverConnect(HDBC hdbc, HWND hwnd, SQLCHAR FAR * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR FAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT FAR * pcbConnStrOut, SQLUSMALLINT fDriverCompletion) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[SQLDriverConnect]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_DriverConnect(hdbc, hwnd, szConnStrIn, cbConnStrIn, szConnStrOut, cbConnStrOutMax, pcbConnStrOut, fDriverCompletion); LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLBrowseConnect(HDBC hdbc, SQLCHAR *szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR *szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT *pcbConnStrOut) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[SQLBrowseConnect]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_BrowseConnect(hdbc, szConnStrIn, cbConnStrIn, szConnStrOut, cbConnStrOutMax, pcbConnStrOut); LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLDataSources(HENV EnvironmentHandle, SQLUSMALLINT Direction, SQLCHAR *ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT *NameLength1, SQLCHAR *Description, SQLSMALLINT BufferLength2, SQLSMALLINT *NameLength2) { mylog("[SQLDataSources]"); /* * return PGAPI_DataSources(EnvironmentHandle, Direction, ServerName, * BufferLength1, NameLength1, Description, BufferLength2, * NameLength2); */ return SQL_ERROR; } RETCODE SQL_API SQLDescribeCol(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLCHAR *ColumnName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength, SQLSMALLINT *DataType, SQLULEN *ColumnSize, SQLSMALLINT *DecimalDigits, SQLSMALLINT *Nullable) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLDescribeCol]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_DescribeCol(StatementHandle, ColumnNumber, ColumnName, BufferLength, NameLength, DataType, ColumnSize, DecimalDigits, Nullable); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLDisconnect(HDBC ConnectionHandle) { CSTR func = "SQLDisconnect"; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[%s for %p]", func, ConnectionHandle); #ifdef _HANDLE_ENLIST_IN_DTC_ if (CC_is_in_global_trans(conn)) CALL_DtcOnDisconnect(conn); #endif /* _HANDLE_ENLIST_IN_DTC_ */ ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_Disconnect(ConnectionHandle); LEAVE_CONN_CS(conn); return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLError(HENV EnvironmentHandle, HDBC ConnectionHandle, HSTMT StatementHandle, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength) { RETCODE ret; mylog("[SQLError]"); if (NULL != EnvironmentHandle) ENTER_ENV_CS((EnvironmentClass *) EnvironmentHandle); ret = PGAPI_Error(EnvironmentHandle, ConnectionHandle, StatementHandle, Sqlstate, NativeError, MessageText, BufferLength, TextLength); if (NULL != EnvironmentHandle) LEAVE_ENV_CS((EnvironmentClass *) EnvironmentHandle); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLExecDirect(HSTMT StatementHandle, SQLCHAR *StatementText, SQLINTEGER TextLength) { CSTR func = "SQLExecDirect"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); if (PG_VERSION_GE(SC_get_conn(stmt), 7.4)) flag |= PODBC_WITH_HOLD; if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else { StartRollbackState(stmt); ret = PGAPI_ExecDirect(StatementHandle, StatementText, TextLength, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); } LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLExecute(HSTMT StatementHandle) { CSTR func = "SQLExecute"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); if (PG_VERSION_GE(SC_get_conn(stmt), 7.4)) flag |= PODBC_WITH_HOLD; if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else { StartRollbackState(stmt); ret = PGAPI_Execute(StatementHandle, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); } LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLFetch(HSTMT StatementHandle) { CSTR func = "SQLFetch"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (SC_get_conn(stmt)->driver_version >= 0x0300) { IRDFields *irdopts = SC_get_IRDF(stmt); ARDFields *ardopts = SC_get_ARDF(stmt); SQLUSMALLINT *rowStatusArray = irdopts->rowStatusArray; SQLULEN *pcRow = irdopts->rowsFetched; mylog("[[%s]]", func); ret = PGAPI_ExtendedFetch(StatementHandle, SQL_FETCH_NEXT, 0, pcRow, rowStatusArray, 0, ardopts->size_of_rowset); stmt->transition_status = STMT_TRANSITION_FETCH_SCROLL; } else #endif { mylog("[%s]", func); ret = PGAPI_Fetch(StatementHandle); } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLFreeConnect(HDBC ConnectionHandle) { RETCODE ret; mylog("[SQLFreeConnect]"); ret = PGAPI_FreeConnect(ConnectionHandle); return ret; } RETCODE SQL_API SQLFreeEnv(HENV EnvironmentHandle) { RETCODE ret; mylog("[SQLFreeEnv]"); ret = PGAPI_FreeEnv(EnvironmentHandle); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLFreeStmt(HSTMT StatementHandle, SQLUSMALLINT Option) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; ConnectionClass *conn = NULL; mylog("[SQLFreeStmt]"); if (stmt) { if (Option == SQL_DROP) { conn = stmt->hdbc; if (conn) ENTER_CONN_CS(conn); } else ENTER_STMT_CS(stmt); } ret = PGAPI_FreeStmt(StatementHandle, Option); if (stmt) { if (Option == SQL_DROP) { if (conn) LEAVE_CONN_CS(conn); } else LEAVE_STMT_CS(stmt); } return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLGetConnectOption(HDBC ConnectionHandle, SQLUSMALLINT Option, PTR Value) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[SQLGetConnectOption]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_GetConnectOption(ConnectionHandle, Option, Value, NULL, 64); LEAVE_CONN_CS(conn); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLGetCursorName(HSTMT StatementHandle, SQLCHAR *CursorName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLGetCursorName]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_GetCursorName(StatementHandle, CursorName, BufferLength, NameLength); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLGetData(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, PTR TargetValue, SQLLEN BufferLength, SQLLEN *StrLen_or_Ind) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLGetData]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_GetData(StatementHandle, ColumnNumber, TargetType, TargetValue, BufferLength, StrLen_or_Ind); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLGetFunctions(HDBC ConnectionHandle, SQLUSMALLINT FunctionId, SQLUSMALLINT *Supported) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[SQLGetFunctions]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); #if (ODBCVER >= 0x0300) if (FunctionId == SQL_API_ODBC3_ALL_FUNCTIONS) ret = PGAPI_GetFunctions30(ConnectionHandle, FunctionId, Supported); else #endif { ret = PGAPI_GetFunctions(ConnectionHandle, FunctionId, Supported); } LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLGetInfo(HDBC ConnectionHandle, SQLUSMALLINT InfoType, PTR InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength) { CSTR func = "SQLGetInfo"; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); #if (ODBCVER >= 0x0300) mylog("[%s(30)]", func); if ((ret = PGAPI_GetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength)) == SQL_ERROR) { if (conn->driver_version >= 0x0300) { CC_clear_error(conn); ret = PGAPI_GetInfo30(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength); goto cleanup; } } if (SQL_ERROR == ret) CC_log_error("SQLGetInfo(30)", "", conn); #else mylog("[%s]", func); if (ret = PGAPI_GetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength), SQL_ERROR == ret) CC_log_error(func, "", conn); #endif cleanup: LEAVE_CONN_CS(conn); return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLGetStmtOption(HSTMT StatementHandle, SQLUSMALLINT Option, PTR Value) { CSTR func = "SQLGetStmtOption"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_GetStmtOption(StatementHandle, Option, Value, NULL, 64); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLGetTypeInfo(HSTMT StatementHandle, SQLSMALLINT DataType) { CSTR func = "SQLGetTypeInfo"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else { StartRollbackState(stmt); ret = PGAPI_GetTypeInfo(StatementHandle, DataType); ret = DiscardStatementSvp(stmt, ret, FALSE); } LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLNumResultCols(HSTMT StatementHandle, SQLSMALLINT *ColumnCount) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLNumResultCols]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_NumResultCols(StatementHandle, ColumnCount); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLParamData(HSTMT StatementHandle, PTR *Value) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLParamData]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); ret = PGAPI_ParamData(StatementHandle, Value); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLPrepare(HSTMT StatementHandle, SQLCHAR *StatementText, SQLINTEGER TextLength) { CSTR func = "SQLPrepare"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLPrepare]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else { StartRollbackState(stmt); ret = PGAPI_Prepare(StatementHandle, StatementText, TextLength); ret = DiscardStatementSvp(stmt, ret, FALSE); } LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLPutData(HSTMT StatementHandle, PTR Data, SQLLEN StrLen_or_Ind) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLPutData]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); ret = PGAPI_PutData(StatementHandle, Data, StrLen_or_Ind); ret = DiscardStatementSvp(stmt, ret, TRUE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLRowCount(HSTMT StatementHandle, SQLLEN *RowCount) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLRowCount]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_RowCount(StatementHandle, RowCount); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLSetConnectOption(HDBC ConnectionHandle, SQLUSMALLINT Option, SQLULEN Value) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[SQLSetConnectionOption]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_SetConnectOption(ConnectionHandle, Option, Value); LEAVE_CONN_CS(conn); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLSetCursorName(HSTMT StatementHandle, SQLCHAR *CursorName, SQLSMALLINT NameLength) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLSetCursorName]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_SetCursorName(StatementHandle, CursorName, NameLength); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLSetParam(HSTMT StatementHandle, SQLUSMALLINT ParameterNumber, SQLSMALLINT ValueType, SQLSMALLINT ParameterType, SQLULEN LengthPrecision, SQLSMALLINT ParameterScale, PTR ParameterValue, SQLLEN *StrLen_or_Ind) { mylog("[SQLSetParam]"); SC_clear_error((StatementClass *) StatementHandle); /* * return PGAPI_SetParam(StatementHandle, ParameterNumber, ValueType, * ParameterType, LengthPrecision, ParameterScale, ParameterValue, * StrLen_or_Ind); */ return SQL_ERROR; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLSetStmtOption(HSTMT StatementHandle, SQLUSMALLINT Option, SQLULEN Value) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[SQLSetStmtOption]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_SetStmtOption(StatementHandle, Option, Value); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLSpecialColumns(HSTMT StatementHandle, SQLUSMALLINT IdentifierType, SQLCHAR *CatalogName, SQLSMALLINT NameLength1, SQLCHAR *SchemaName, SQLSMALLINT NameLength2, SQLCHAR *TableName, SQLSMALLINT NameLength3, SQLUSMALLINT Scope, SQLUSMALLINT Nullable) { CSTR func = "SQLSpecialColumns"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; SQLCHAR *ctName = CatalogName, *scName = SchemaName, *tbName = TableName; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_SpecialColumns(StatementHandle, IdentifierType, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, Scope, Nullable); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt =NULL, *newSc = NULL, *newTb = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, CatalogName, NameLength1, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, SchemaName, NameLength2, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, TableName, NameLength3, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (reexec) { ret = PGAPI_SpecialColumns(StatementHandle, IdentifierType, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, Scope, Nullable); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLStatistics(HSTMT StatementHandle, SQLCHAR *CatalogName, SQLSMALLINT NameLength1, SQLCHAR *SchemaName, SQLSMALLINT NameLength2, SQLCHAR *TableName, SQLSMALLINT NameLength3, SQLUSMALLINT Unique, SQLUSMALLINT Reserved) { CSTR func = "SQLStatistics"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; SQLCHAR *ctName = CatalogName, *scName = SchemaName, *tbName = TableName; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Statistics(StatementHandle, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, Unique, Reserved); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt =NULL, *newSc = NULL, *newTb = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, CatalogName, NameLength1, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, SchemaName, NameLength2, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, TableName, NameLength3, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (reexec) { ret = PGAPI_Statistics(StatementHandle, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, Unique, Reserved); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLTables(HSTMT StatementHandle, SQLCHAR *CatalogName, SQLSMALLINT NameLength1, SQLCHAR *SchemaName, SQLSMALLINT NameLength2, SQLCHAR *TableName, SQLSMALLINT NameLength3, SQLCHAR *TableType, SQLSMALLINT NameLength4) { CSTR func = "SQLTables"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; SQLCHAR *ctName = CatalogName, *scName = SchemaName, *tbName = TableName; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Tables(StatementHandle, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, TableType, NameLength4, flag); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt =NULL, *newSc = NULL, *newTb = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, CatalogName, NameLength1, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, SchemaName, NameLength2, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, TableName, NameLength3, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (reexec) { ret = PGAPI_Tables(StatementHandle, ctName, NameLength1, scName, NameLength2, tbName, NameLength3, TableType, NameLength4, flag); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLTransact(HENV EnvironmentHandle, HDBC ConnectionHandle, SQLUSMALLINT CompletionType) { RETCODE ret; mylog("[SQLTransact]"); if (NULL != EnvironmentHandle) ENTER_ENV_CS((EnvironmentClass *) EnvironmentHandle); else ENTER_CONN_CS((ConnectionClass *) ConnectionHandle); ret = PGAPI_Transact(EnvironmentHandle, ConnectionHandle, CompletionType); if (NULL != EnvironmentHandle) LEAVE_ENV_CS((EnvironmentClass *) EnvironmentHandle); else LEAVE_CONN_CS((ConnectionClass *) ConnectionHandle); return ret; } RETCODE SQL_API SQLColAttributes(HSTMT hstmt, SQLUSMALLINT icol, SQLUSMALLINT fDescType, PTR rgbDesc, SQLSMALLINT cbDescMax, SQLSMALLINT *pcbDesc, SQLLEN *pfDesc) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLColAttributes]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_ColAttributes(hstmt, icol, fDescType, rgbDesc, cbDescMax, pcbDesc, pfDesc); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLColumnPrivileges(HSTMT hstmt, SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLCHAR *szTableName, SQLSMALLINT cbTableName, SQLCHAR *szColumnName, SQLSMALLINT cbColumnName) { CSTR func = "SQLColumnPrivileges"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLCHAR *ctName = szCatalogName, *scName = szSchemaName, *tbName = szTableName, *clName = szColumnName; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ColumnPrivileges(hstmt, ctName, cbCatalogName, scName, cbSchemaName, tbName, cbTableName, clName, cbColumnName, flag); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt = NULL, *newSc = NULL, *newTb = NULL, *newCl = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, szCatalogName, cbCatalogName, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, szSchemaName, cbSchemaName, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, szTableName, cbTableName, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (newCl = make_lstring_ifneeded(conn, szColumnName, cbColumnName, ifallupper), NULL != newCl) { clName = newCl; reexec = TRUE; } if (reexec) { ret = PGAPI_ColumnPrivileges(hstmt, ctName, cbCatalogName, scName, cbSchemaName, tbName, cbTableName, clName, cbColumnName, flag); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); if (newCl) free(newCl); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLDescribeParam(HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT *pfSqlType, SQLULEN *pcbParamDef, SQLSMALLINT *pibScale, SQLSMALLINT *pfNullable) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLDescribeParam]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_DescribeParam(hstmt, ipar, pfSqlType, pcbParamDef, pibScale, pfNullable); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLExtendedFetch(HSTMT hstmt, SQLUSMALLINT fFetchType, SQLLEN irow, #if defined(WITH_UNIXODBC) && (SIZEOF_LONG != 8) SQLROWSETSIZE *pcrow, #else SQLULEN *pcrow, #endif /* WITH_UNIXODBC */ SQLUSMALLINT *rgfRowStatus) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLExtendedFetch]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #ifdef WITH_UNIXODBC { SQLULEN retrieved; ret = PGAPI_ExtendedFetch(hstmt, fFetchType, irow, &retrieved, rgfRowStatus, 0, SC_get_ARDF(stmt)->size_of_rowset_odbc2); if (pcrow) *pcrow = retrieved; } #else ret = PGAPI_ExtendedFetch(hstmt, fFetchType, irow, pcrow, rgfRowStatus, 0, SC_get_ARDF(stmt)->size_of_rowset_odbc2); #endif /* WITH_UNIXODBC */ stmt->transition_status = STMT_TRANSITION_EXTENDED_FETCH; ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLForeignKeys(HSTMT hstmt, SQLCHAR *szPkCatalogName, SQLSMALLINT cbPkCatalogName, SQLCHAR *szPkSchemaName, SQLSMALLINT cbPkSchemaName, SQLCHAR *szPkTableName, SQLSMALLINT cbPkTableName, SQLCHAR *szFkCatalogName, SQLSMALLINT cbFkCatalogName, SQLCHAR *szFkSchemaName, SQLSMALLINT cbFkSchemaName, SQLCHAR *szFkTableName, SQLSMALLINT cbFkTableName) { CSTR func = "SQLForeignKeys"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLCHAR *pkctName = szPkCatalogName, *pkscName = szPkSchemaName, *pktbName = szPkTableName, *fkctName = szFkCatalogName, *fkscName = szFkSchemaName, *fktbName = szFkTableName; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ForeignKeys(hstmt, pkctName, cbPkCatalogName, pkscName, cbPkSchemaName, pktbName, cbPkTableName, fkctName, cbFkCatalogName, fkscName, cbFkSchemaName, fktbName, cbFkTableName); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newPkct = NULL, *newPksc = NULL, *newPktb = NULL, *newFkct = NULL, *newFksc = NULL, *newFktb = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newPkct = make_lstring_ifneeded(conn, szPkCatalogName, cbPkCatalogName, ifallupper), NULL != newPkct) { pkctName = newPkct; reexec = TRUE; } if (newPksc = make_lstring_ifneeded(conn, szPkSchemaName, cbPkSchemaName, ifallupper), NULL != newPksc) { pkscName = newPksc; reexec = TRUE; } if (newPktb = make_lstring_ifneeded(conn, szPkTableName, cbPkTableName, ifallupper), NULL != newPktb) { pktbName = newPktb; reexec = TRUE; } if (newFkct = make_lstring_ifneeded(conn, szFkCatalogName, cbFkCatalogName, ifallupper), NULL != newFkct) { fkctName = newFkct; reexec = TRUE; } if (newFksc = make_lstring_ifneeded(conn, szFkSchemaName, cbFkSchemaName, ifallupper), NULL != newFksc) { fkscName = newFksc; reexec = TRUE; } if (newFktb = make_lstring_ifneeded(conn, szFkTableName, cbFkTableName, ifallupper), NULL != newFktb) { fktbName = newFktb; reexec = TRUE; } if (reexec) { ret = PGAPI_ForeignKeys(hstmt, pkctName, cbPkCatalogName, pkscName, cbPkSchemaName, pktbName, cbPkTableName, fkctName, cbFkCatalogName, fkscName, cbFkSchemaName, fktbName, cbFkTableName); if (newPkct) free(newPkct); if (newPksc) free(newPksc); if (newPktb) free(newPktb); if (newFkct) free(newFkct); if (newFksc) free(newFksc); if (newFktb) free(newFktb); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLMoreResults(HSTMT hstmt) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLMoreResults]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_MoreResults(hstmt); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLNativeSql(HDBC hdbc, SQLCHAR *szSqlStrIn, SQLINTEGER cbSqlStrIn, SQLCHAR *szSqlStr, SQLINTEGER cbSqlStrMax, SQLINTEGER *pcbSqlStr) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[SQLNativeSql]"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_NativeSql(hdbc, szSqlStrIn, cbSqlStrIn, szSqlStr, cbSqlStrMax, pcbSqlStr); LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLNumParams(HSTMT hstmt, SQLSMALLINT *pcpar) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLNumParams]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_NumParams(hstmt, pcpar); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #if (ODBCVER < 0x0300) RETCODE SQL_API SQLParamOptions(HSTMT hstmt, SQLULEN crow, SQLULEN *pirow) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLParamOptions]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_ParamOptions(hstmt, crow, pirow); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* ODBCVER */ RETCODE SQL_API SQLPrimaryKeys(HSTMT hstmt, SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLCHAR *szTableName, SQLSMALLINT cbTableName) { CSTR func = "SQLPrimaryKeys"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLCHAR *ctName = szCatalogName, *scName = szSchemaName, *tbName = szTableName; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_PrimaryKeys(hstmt, ctName, cbCatalogName, scName, cbSchemaName, tbName, cbTableName, 0); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt = NULL, *newSc = NULL, *newTb = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, szCatalogName, cbCatalogName, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, szSchemaName, cbSchemaName, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, szTableName, cbTableName, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (reexec) { ret = PGAPI_PrimaryKeys(hstmt, ctName, cbCatalogName, scName, cbSchemaName, tbName, cbTableName, 0); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLProcedureColumns(HSTMT hstmt, SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLCHAR *szProcName, SQLSMALLINT cbProcName, SQLCHAR *szColumnName, SQLSMALLINT cbColumnName) { CSTR func = "SQLProcedureColumns"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLCHAR *ctName = szCatalogName, *scName = szSchemaName, *prName = szProcName, *clName = szColumnName; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ProcedureColumns(hstmt, ctName, cbCatalogName, scName, cbSchemaName, prName, cbProcName, clName, cbColumnName, flag); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt = NULL, *newSc = NULL, *newPr = NULL, *newCl = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, szCatalogName, cbCatalogName, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, szSchemaName, cbSchemaName, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newPr = make_lstring_ifneeded(conn, szProcName, cbProcName, ifallupper), NULL != newPr) { prName = newPr; reexec = TRUE; } if (newCl = make_lstring_ifneeded(conn, szColumnName, cbColumnName, ifallupper), NULL != newCl) { clName = newCl; reexec = TRUE; } if (reexec) { ret = PGAPI_ProcedureColumns(hstmt, ctName, cbCatalogName, scName, cbSchemaName, prName, cbProcName, clName, cbColumnName, flag); if (newCt) free(newCt); if (newSc) free(newSc); if (newPr) free(newPr); if (newCl) free(newCl); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLProcedures(HSTMT hstmt, SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLCHAR *szProcName, SQLSMALLINT cbProcName) { CSTR func = "SQLProcedures"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLCHAR *ctName = szCatalogName, *scName = szSchemaName, *prName = szProcName; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Procedures(hstmt, ctName, cbCatalogName, scName, cbSchemaName, prName, cbProcName, flag); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt = NULL, *newSc = NULL, *newPr = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, szCatalogName, cbCatalogName, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, szSchemaName, cbSchemaName, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newPr = make_lstring_ifneeded(conn, szProcName, cbProcName, ifallupper), NULL != newPr) { prName = newPr; reexec = TRUE; } if (reexec) { ret = PGAPI_Procedures(hstmt, ctName, cbCatalogName, scName, cbSchemaName, prName, cbProcName, flag); if (newCt) free(newCt); if (newSc) free(newSc); if (newPr) free(newPr); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLSetPos(HSTMT hstmt, SQLSETPOSIROW irow, SQLUSMALLINT fOption, SQLUSMALLINT fLock) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLSetPos]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_SetPos(hstmt, irow, fOption, fLock); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLTablePrivileges(HSTMT hstmt, SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLCHAR *szTableName, SQLSMALLINT cbTableName) { CSTR func = "SQLTablePrivileges"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLCHAR *ctName = szCatalogName, *scName = szSchemaName, *tbName = szTableName; UWORD flag = 0; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_TablePrivileges(hstmt, ctName, cbCatalogName, scName, cbSchemaName, tbName, cbTableName, flag); if (SQL_SUCCESS == ret && theResultIsEmpty(stmt)) { BOOL ifallupper = TRUE, reexec = FALSE; SQLCHAR *newCt = NULL, *newSc = NULL, *newTb = NULL; ConnectionClass *conn = SC_get_conn(stmt); if (SC_is_lower_case(stmt, conn)) /* case-insensitive identifier */ ifallupper = FALSE; if (newCt = make_lstring_ifneeded(conn, szCatalogName, cbCatalogName, ifallupper), NULL != newCt) { ctName = newCt; reexec = TRUE; } if (newSc = make_lstring_ifneeded(conn, szSchemaName, cbSchemaName, ifallupper), NULL != newSc) { scName = newSc; reexec = TRUE; } if (newTb = make_lstring_ifneeded(conn, szTableName, cbTableName, ifallupper), NULL != newTb) { tbName = newTb; reexec = TRUE; } if (reexec) { ret = PGAPI_TablePrivileges(hstmt, ctName, cbCatalogName, scName, cbSchemaName, tbName, cbTableName, 0); if (newCt) free(newCt); if (newSc) free(newSc); if (newTb) free(newTb); } } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLBindParameter(HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT fParamType, SQLSMALLINT fCType, SQLSMALLINT fSqlType, SQLULEN cbColDef, SQLSMALLINT ibScale, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[SQLBindParameter]"); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_BindParameter(hstmt, ipar, fParamType, fCType, fSqlType, cbColDef, ibScale, rgbValue, cbValueMax, pcbValue); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } psqlodbc-09.03.0300/descriptor.c000644 001752 000000 00000041176 12335653444 016533 0ustar00saitowheel000000 000000 /*------- * Module: descriptor.c * * Description: This module contains functions related to creating * and manipulating a statement. * * Classes: DescriptorClass (Functions prefix: "DC_") * * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "environ.h" #include "connection.h" #include "descriptor.h" #include "statement.h" #include "qresult.h" #include #include #include #include "pgapifunc.h" void TI_Constructor(TABLE_INFO *self, const ConnectionClass *conn) { memset(self, 0, sizeof(TABLE_INFO)); TI_set_updatable(self); if (PG_VERSION_LT(conn, 7.2)) { char qual[32]; STR_TO_NAME(self->bestitem, OID_NAME); sprintf(qual, "\"%s\" = %%u", OID_NAME); STRX_TO_NAME(self->bestqual, qual); TI_set_hasoids(self); TI_set_hasoids_checked(self); } } void TI_Destructor(TABLE_INFO **ti, int count) { int i; inolog("TI_Destructor count=%d\n", count); if (ti) { for (i = 0; i < count; i++) { if (ti[i]) { COL_INFO *coli = ti[i]->col_info; if (coli) { mylog("!!!refcnt %p:%d -> %d\n", coli, coli->refcnt, coli->refcnt - 1); coli->refcnt--; if (coli->refcnt <= 0 && 0 == coli->acc_time) /* acc_time == 0 means the table is dropped */ free_col_info_contents(coli); } NULL_THE_NAME(ti[i]->schema_name); NULL_THE_NAME(ti[i]->table_name); NULL_THE_NAME(ti[i]->table_alias); NULL_THE_NAME(ti[i]->bestitem); NULL_THE_NAME(ti[i]->bestqual); free(ti[i]); ti[i] = NULL; } } } } void FI_Constructor(FIELD_INFO *self, BOOL reuse) { inolog("FI_Constructor reuse=%d\n", reuse); if (reuse) FI_Destructor(&self, 1, FALSE); memset(self, 0, sizeof(FIELD_INFO)); self->nullable = TRUE; self->columnkey = -1; self->typmod = -1; } void FI_Destructor(FIELD_INFO **fi, int count, BOOL freeFI) { int i; inolog("FI_Destructor count=%d\n", count); if (fi) { for (i = 0; i < count; i++) { if (fi[i]) { NULL_THE_NAME(fi[i]->column_name); NULL_THE_NAME(fi[i]->column_alias); NULL_THE_NAME(fi[i]->schema_name); NULL_THE_NAME(fi[i]->before_dot); if (freeFI) { free(fi[i]); fi[i] = NULL; } } } if (freeFI) free(fi); } } void DC_Constructor(DescriptorClass *self, BOOL embedded, StatementClass *stmt) { memset(self, 0, sizeof(DescriptorClass)); self->embedded = embedded; } static void ARDFields_free(ARDFields * self) { inolog("ARDFields_free %p bookmark=%p", self, self->bookmark); if (self->bookmark) { free(self->bookmark); self->bookmark = NULL; } inolog(" hey"); /* * the memory pointed to by the bindings is not deallocated by the * driver but by the application that uses that driver, so we don't * have to care */ ARD_unbind_cols(self, TRUE); } static void APDFields_free(APDFields * self) { if (self->bookmark) { free(self->bookmark); self->bookmark = NULL; } /* param bindings */ APD_free_params(self, STMT_FREE_PARAMS_ALL); } static void IRDFields_free(IRDFields * self) { /* Free the parsed field information */ if (self->fi) { FI_Destructor(self->fi, self->allocated, TRUE); self->fi = NULL; } self->allocated = 0; self->nfields = 0; } static void IPDFields_free(IPDFields * self) { /* param bindings */ IPD_free_params(self, STMT_FREE_PARAMS_ALL); } void DC_Destructor(DescriptorClass *self) { if (self->__error_message) { free(self->__error_message); self->__error_message = NULL; } if (self->pgerror) { ER_Destructor(self->pgerror); self->pgerror = NULL; } if (self->type_defined) { switch (self->desc_type) { case SQL_ATTR_APP_ROW_DESC: ARDFields_free((ARDFields *) (self + 1)); break; case SQL_ATTR_APP_PARAM_DESC: APDFields_free((APDFields *) (self + 1)); break; case SQL_ATTR_IMP_ROW_DESC: IRDFields_free((IRDFields *) (self + 1)); break; case SQL_ATTR_IMP_PARAM_DESC: IPDFields_free((IPDFields *) (self + 1)); break; } } } void InitializeEmbeddedDescriptor(DescriptorClass *desc, StatementClass *stmt, UInt4 desc_type) { DC_Constructor(desc, TRUE, stmt); DC_get_conn(desc) = SC_get_conn(stmt); desc->type_defined = TRUE; desc->desc_type = desc_type; switch (desc_type) { case SQL_ATTR_APP_ROW_DESC: memset(desc + 1, 0, sizeof(ARDFields)); stmt->ard = (ARDClass *) desc; break; case SQL_ATTR_APP_PARAM_DESC: memset(desc + 1, 0, sizeof(APDFields)); stmt->apd = (APDClass *) desc; break; case SQL_ATTR_IMP_ROW_DESC: memset(desc + 1, 0, sizeof(IRDFields)); stmt->ird = (IRDClass *) desc; stmt->ird->irdopts.stmt = stmt; break; case SQL_ATTR_IMP_PARAM_DESC: memset(desc + 1, 0, sizeof(IPDFields)); stmt->ipd = (IPDClass *) desc; break; } } /* * ARDFields initialize */ void InitializeARDFields(ARDFields *opt) { memset(opt, 0, sizeof(ARDFields)); #if (ODBCVER >= 0x0300) opt->size_of_rowset = 1; #endif /* ODBCVER */ opt->bind_size = 0; /* default is to bind by column */ opt->size_of_rowset_odbc2 = 1; } /* * APDFields initialize */ void InitializeAPDFields(APDFields *opt) { memset(opt, 0, sizeof(APDFields)); opt->paramset_size = 1; opt->param_bind_type = 0; /* default is to bind by column */ opt->paramset_size_dummy = 1; /* dummy setting */ } BindInfoClass *ARD_AllocBookmark(ARDFields *ardopts) { if (!ardopts->bookmark) { ardopts->bookmark = (BindInfoClass *) malloc(sizeof(BindInfoClass)); memset(ardopts->bookmark, 0, sizeof(BindInfoClass)); } return ardopts->bookmark; } #if (ODBCVER >= 0x0300) #define DESC_INCREMENT 10 char CC_add_descriptor(ConnectionClass *self, DescriptorClass *desc) { int i; int new_num_descs; DescriptorClass **descs; mylog("CC_add_descriptor: self=%p, desc=%p\n", self, desc); for (i = 0; i < self->num_descs; i++) { if (!self->descs[i]) { DC_get_conn(desc) = self; self->descs[i] = desc; return TRUE; } } /* no more room -- allocate more memory */ new_num_descs = DESC_INCREMENT + self->num_descs; descs = (DescriptorClass **) realloc(self->descs, sizeof(DescriptorClass *) * new_num_descs); if (!descs) return FALSE; self->descs = descs; memset(&self->descs[self->num_descs], 0, sizeof(DescriptorClass *) * DESC_INCREMENT); DC_get_conn(desc) = self; self->descs[self->num_descs] = desc; self->num_descs = new_num_descs; return TRUE; } /* * This API allocates a Application descriptor. */ RETCODE SQL_API PGAPI_AllocDesc(HDBC ConnectionHandle, SQLHDESC *DescriptorHandle) { CSTR func = "PGAPI_AllocDesc"; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; RETCODE ret = SQL_SUCCESS; DescriptorClass *desc = (DescriptorClass *) malloc(sizeof(DescriptorAlloc)); mylog("%s: entering...\n", func); if (desc) { memset(desc, 0, sizeof(DescriptorAlloc)); DC_get_conn(desc) = conn; if (CC_add_descriptor(conn, desc)) *DescriptorHandle = desc; else { free(desc); CC_set_error(conn, CONN_STMT_ALLOC_ERROR, "Maximum number of descriptors exceeded", func); ret = SQL_ERROR; } } else { CC_set_error(conn, CONN_STMT_ALLOC_ERROR, "No more memory ti allocate a further descriptor", func); ret = SQL_ERROR; } return ret; } RETCODE SQL_API PGAPI_FreeDesc(SQLHDESC DescriptorHandle) { CSTR func = "PGAPI_FreeDesc"; DescriptorClass *desc = (DescriptorClass *) DescriptorHandle; RETCODE ret = SQL_SUCCESS; mylog("%s: entering...\n", func); DC_Destructor(desc); if (!desc->embedded) { int i; ConnectionClass *conn = DC_get_conn(desc); for (i = 0; i < conn->num_descs; i++) { if (conn->descs[i] == desc) { conn->descs[i] = NULL; break; } } free(desc); } return ret; } static void BindInfoClass_copy(const BindInfoClass *src, BindInfoClass *target) { memcpy(target, src, sizeof(BindInfoClass)); } static void ARDFields_copy(const ARDFields *src, ARDFields *target) { memcpy(target, src, sizeof(ARDFields)); target->bookmark = NULL; if (src->bookmark) { BindInfoClass *bookmark = ARD_AllocBookmark(target); BindInfoClass_copy(src->bookmark, bookmark); } if (src->allocated <= 0) { target->allocated = 0; target->bindings = NULL; } else { int i; target->bindings = malloc(target->allocated * sizeof(BindInfoClass)); for (i = 0; i < target->allocated; i++) BindInfoClass_copy(&src->bindings[i], &target->bindings[i]); } } static void ParameterInfoClass_copy(const ParameterInfoClass *src, ParameterInfoClass *target) { memcpy(target, src, sizeof(ParameterInfoClass)); } static void APDFields_copy(const APDFields *src, APDFields *target) { memcpy(target, src, sizeof(APDFields)); if (src->bookmark) { target->bookmark = malloc(sizeof(BindInfoClass)); ParameterInfoClass_copy(src->bookmark, target->bookmark); } if (src->allocated <= 0) { target->allocated = 0; target->parameters = NULL; } else { int i; target->parameters = malloc(target->allocated * sizeof(ParameterInfoClass)); for (i = 0; i < target->allocated; i++) ParameterInfoClass_copy(&src->parameters[i], &target->parameters[i]); } } static void ParameterImplClass_copy(const ParameterImplClass *src, ParameterImplClass *target) { memcpy(target, src, sizeof(ParameterImplClass)); } static void IPDFields_copy(const IPDFields *src, IPDFields *target) { memcpy(target, src, sizeof(IPDFields)); if (src->allocated <= 0) { target->allocated = 0; target->parameters = NULL; } else { int i; target->parameters = (ParameterImplClass *) malloc(target->allocated * sizeof(ParameterImplClass)); for (i = 0; i < target->allocated; i++) ParameterImplClass_copy(&src->parameters[i], &target->parameters[i]); } } RETCODE SQL_API PGAPI_CopyDesc(SQLHDESC SourceDescHandle, SQLHDESC TargetDescHandle) { CSTR func = "PGAPI_CopyDesc"; RETCODE ret = SQL_ERROR; DescriptorClass *src, *target; ARDFields *ard_src, *ard_tgt; APDFields *apd_src, *apd_tgt; IPDFields *ipd_src, *ipd_tgt; mylog("%s: entering...\n", func); src = (DescriptorClass *) SourceDescHandle; target = (DescriptorClass *) TargetDescHandle; if (!src->type_defined) { mylog("source type undefined\n"); DC_set_error(target, DESC_EXEC_ERROR, "source handle type undefined"); return ret; } if (target->type_defined) { inolog("source type=%d -> target type=%d\n", src->desc_type, target->desc_type); if (SQL_ATTR_IMP_ROW_DESC == target->desc_type) { mylog("can't modify IRD\n"); DC_set_error(target, DESC_EXEC_ERROR, "can't copy to IRD"); return ret; } else if (target->desc_type != src->desc_type) { mylog("src type != target type\n"); DC_set_error(target, DESC_EXEC_ERROR, "src descriptor != target type"); return ret; } DC_Destructor(target); } ret = SQL_SUCCESS; switch (src->desc_type) { case SQL_ATTR_APP_ROW_DESC: inolog("src=%p target=%p type=%d", src, target, src->desc_type); if (!target->type_defined) { target->desc_type = src->desc_type; } ard_src = (ARDFields *) (src + 1); inolog(" rowset_size=%d bind_size=%d ope_ptr=%p off_ptr=%p\n", ard_src->size_of_rowset, ard_src->bind_size, ard_src->row_operation_ptr, ard_src->row_offset_ptr); ard_tgt = (ARDFields *) (target + 1); inolog(" target=%p", ard_tgt); ARDFields_copy(ard_src, ard_tgt); inolog(" offset_ptr=%p\n", ard_tgt->row_offset_ptr); break; case SQL_ATTR_APP_PARAM_DESC: if (!target->type_defined) { target->desc_type = src->desc_type; } apd_src = (APDFields *) (src + 1); apd_tgt = (APDFields *) (target + 1); APDFields_copy(apd_src, apd_tgt); break; case SQL_ATTR_IMP_PARAM_DESC: if (!target->type_defined) { target->desc_type = src->desc_type; } ipd_src = (IPDFields *) (src + 1); ipd_tgt = (IPDFields *) (target + 1); IPDFields_copy(ipd_src, ipd_tgt); break; default: mylog("invalid descriptor handle type=%d\n", src->desc_type); DC_set_error(target, DESC_EXEC_ERROR, "invalid descriptor type"); ret = SQL_ERROR; } if (SQL_SUCCESS == ret) target->type_defined = TRUE; return ret; } void DC_clear_error(DescriptorClass *self) { if (self->__error_message) { free(self->__error_message); self->__error_message = NULL; } if (self->pgerror) { ER_Destructor(self->pgerror); self->pgerror = NULL; } self->__error_number = 0; self->error_row = 0; self->error_index = 0; } void DC_set_error(DescriptorClass *desc, int errornumber, const char *errormsg) { if (desc->__error_message) free(desc->__error_message); desc->__error_number = errornumber; desc->__error_message = errormsg ? strdup(errormsg) : NULL; } void DC_set_errormsg(DescriptorClass *desc, const char *errormsg) { if (desc->__error_message) free(desc->__error_message); desc->__error_message = errormsg ? strdup(errormsg) : NULL; } const char *DC_get_errormsg(const DescriptorClass *desc) { return desc->__error_message; } int DC_get_errornumber(const DescriptorClass *desc) { return desc->__error_number; } /* Map sql commands to statement types */ static struct { int number; const char * ver3str; const char * ver2str; } Descriptor_sqlstate[] = { { DESC_ERROR_IN_ROW, "01S01", "01S01" }, { DESC_OPTION_VALUE_CHANGED, "01S02", "01S02" }, { DESC_OK, "00000", "00000" }, /* OK */ { DESC_EXEC_ERROR, "HY000", "S1000" }, /* also a general error */ { DESC_STATUS_ERROR, "HY010", "S1010" }, { DESC_SEQUENCE_ERROR, "HY010", "S1010" }, /* Function sequence error */ { DESC_NO_MEMORY_ERROR, "HY001", "S1001" }, /* memory allocation failure */ { DESC_COLNUM_ERROR, "07009", "S1002" }, /* invalid column number */ { DESC_NO_STMTSTRING, "HY001", "S1001" }, /* having no stmtstring is also a malloc problem */ { DESC_ERROR_TAKEN_FROM_BACKEND, "HY000", "S1000" }, /* general error */ { DESC_INTERNAL_ERROR, "HY000", "S1000" }, /* general error */ { DESC_STILL_EXECUTING, "HY010", "S1010" }, { DESC_NOT_IMPLEMENTED_ERROR, "HYC00", "S1C00" }, /* == 'driver not * capable' */ { DESC_BAD_PARAMETER_NUMBER_ERROR, "07009", "S1093" }, { DESC_OPTION_OUT_OF_RANGE_ERROR, "HY092", "S1092" }, { DESC_INVALID_COLUMN_NUMBER_ERROR, "07009", "S1002" }, { DESC_RESTRICTED_DATA_TYPE_ERROR, "07006", "07006" }, { DESC_INVALID_CURSOR_STATE_ERROR, "07005", "24000" }, { DESC_CREATE_TABLE_ERROR, "42S01", "S0001" }, /* table already exists */ { DESC_NO_CURSOR_NAME, "S1015", "S1015" }, { DESC_INVALID_CURSOR_NAME, "34000", "34000" }, { DESC_INVALID_ARGUMENT_NO, "HY024", "S1009" }, /* invalid argument value */ { DESC_ROW_OUT_OF_RANGE, "HY107", "S1107" }, { DESC_OPERATION_CANCELLED, "HY008", "S1008" }, { DESC_INVALID_CURSOR_POSITION, "HY109", "S1109" }, { DESC_VALUE_OUT_OF_RANGE, "HY019", "22003" }, { DESC_OPERATION_INVALID, "HY011", "S1011" }, { DESC_PROGRAM_TYPE_OUT_OF_RANGE, "?????", "?????" }, { DESC_BAD_ERROR, "08S01", "08S01" }, /* communication link failure */ { DESC_INVALID_OPTION_IDENTIFIER, "HY092", "HY092" }, { DESC_RETURN_NULL_WITHOUT_INDICATOR, "22002", "22002" }, { DESC_INVALID_DESCRIPTOR_IDENTIFIER, "HY091", "HY091" }, { DESC_OPTION_NOT_FOR_THE_DRIVER, "HYC00", "HYC00" }, { DESC_FETCH_OUT_OF_RANGE, "HY106", "S1106" }, { DESC_COUNT_FIELD_INCORRECT, "07002", "07002" }, }; static PG_ErrorInfo *DC_create_errorinfo(const DescriptorClass *desc) { PG_ErrorInfo *error; ConnectionClass *conn; EnvironmentClass *env; Int4 errornum; BOOL env_is_odbc3 = TRUE; if (desc->pgerror) return desc->pgerror; errornum = desc->__error_number; error = ER_Constructor(errornum, desc->__error_message); if (!error) return error; conn = DC_get_conn(desc); if (conn && (env = (EnvironmentClass *) conn->henv)) env_is_odbc3 = EN_is_odbc3(env); errornum -= LOWEST_DESC_ERROR; if (errornum < 0 || errornum >= sizeof(Descriptor_sqlstate) / sizeof(Descriptor_sqlstate[0])) errornum = 1 - LOWEST_DESC_ERROR; strcpy(error->sqlstate, env_is_odbc3 ? Descriptor_sqlstate[errornum].ver3str : Descriptor_sqlstate[errornum].ver2str); return error; } void DC_log_error(const char *func, const char *desc, const DescriptorClass *self) { #define nullcheck(a) (a ? a : "(NULL)") if (self) { qlog("DESCRIPTOR ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->__error_number, nullcheck(self->__error_message)); mylog("DESCRIPTOR ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->__error_number, nullcheck(self->__error_message)); } } /* Returns the next SQL error information. */ RETCODE SQL_API PGAPI_DescError(SQLHDESC hdesc, SQLSMALLINT RecNumber, SQLCHAR FAR * szSqlState, SQLINTEGER FAR * pfNativeError, SQLCHAR FAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT FAR * pcbErrorMsg, UWORD flag) { CSTR func = "PGAPI_DescError"; /* CC: return an error of a hdesc */ DescriptorClass *desc = (DescriptorClass *) hdesc; mylog("%s RecN=%d\n", func); desc->pgerror = DC_create_errorinfo(desc); return ER_ReturnError(&(desc->pgerror), RecNumber, szSqlState, pfNativeError, szErrorMsg, cbErrorMsgMax, pcbErrorMsg, flag); } #endif /* ODBCVER */ psqlodbc-09.03.0300/odbcapi30.c000644 001752 000000 00000050527 12335653444 016121 0ustar00saitowheel000000 000000 /*------- * Module: odbcapi30.c * * Description: This module contains routines related to ODBC 3.0 * most of their implementations are temporary * and must be rewritten properly. * 2001/07/23 inoue * * Classes: n/a * * API functions: SQLAllocHandle, SQLBindParam, SQLCloseCursor, SQLColAttribute, SQLCopyDesc, SQLEndTran, SQLFetchScroll, SQLFreeHandle, SQLGetDescField, SQLGetDescRec, SQLGetDiagField, SQLGetDiagRec, SQLGetEnvAttr, SQLGetConnectAttr, SQLGetStmtAttr, SQLSetConnectAttr, SQLSetDescField, SQLSetDescRec, SQLSetEnvAttr, SQLSetStmtAttr, SQLBulkOperations *------- */ #include "psqlodbc.h" #include "misc.h" #if (ODBCVER >= 0x0300) #include #include #include "environ.h" #include "connection.h" #include "statement.h" #include "pgapifunc.h" /* SQLAllocConnect/SQLAllocEnv/SQLAllocStmt -> SQLAllocHandle */ RETCODE SQL_API SQLAllocHandle(SQLSMALLINT HandleType, SQLHANDLE InputHandle, SQLHANDLE * OutputHandle) { CSTR func = "SQLAllocHandle"; RETCODE ret; ConnectionClass *conn; mylog("[[%s]]", func); switch (HandleType) { case SQL_HANDLE_ENV: ret = PGAPI_AllocEnv(OutputHandle); break; case SQL_HANDLE_DBC: ENTER_ENV_CS((EnvironmentClass *) InputHandle); ret = PGAPI_AllocConnect(InputHandle, OutputHandle); LEAVE_ENV_CS((EnvironmentClass *) InputHandle); break; case SQL_HANDLE_STMT: conn = (ConnectionClass *) InputHandle; CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); ret = PGAPI_AllocStmt(InputHandle, OutputHandle, PODBC_EXTERNAL_STATEMENT | PODBC_INHERIT_CONNECT_OPTIONS); LEAVE_CONN_CS(conn); break; case SQL_HANDLE_DESC: conn = (ConnectionClass *) InputHandle; CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); ret = PGAPI_AllocDesc(InputHandle, OutputHandle); LEAVE_CONN_CS(conn); inolog("OutputHandle=%p\n", *OutputHandle); break; default: ret = SQL_ERROR; break; } return ret; } /* SQLBindParameter/SQLSetParam -> SQLBindParam */ RETCODE SQL_API SQLBindParam(HSTMT StatementHandle, SQLUSMALLINT ParameterNumber, SQLSMALLINT ValueType, SQLSMALLINT ParameterType, SQLULEN LengthPrecision, SQLSMALLINT ParameterScale, PTR ParameterValue, SQLLEN *StrLen_or_Ind) { CSTR func = "SQLBindParam"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; int BufferLength = 512; /* Is it OK ? */ mylog("[[%s]]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_BindParameter(StatementHandle, ParameterNumber, SQL_PARAM_INPUT, ValueType, ParameterType, LengthPrecision, ParameterScale, ParameterValue, BufferLength, StrLen_or_Ind); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } /* New function */ RETCODE SQL_API SQLCloseCursor(HSTMT StatementHandle) { CSTR func = "SQLCloseCursor"; StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret; mylog("[[%s]]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_FreeStmt(StatementHandle, SQL_CLOSE); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } /* SQLColAttributes -> SQLColAttribute */ SQLRETURN SQL_API SQLColAttribute(SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier, SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength, #if defined(_WIN64) || defined(SQLCOLATTRIBUTE_SQLLEN) SQLLEN *NumericAttribute #else SQLPOINTER NumericAttribute #endif ) { CSTR func = "SQLColAttribute"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[[%s]]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_ColAttributes(StatementHandle, ColumnNumber, FieldIdentifier, CharacterAttribute, BufferLength, StringLength, NumericAttribute); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } /* new function */ RETCODE SQL_API SQLCopyDesc(SQLHDESC SourceDescHandle, SQLHDESC TargetDescHandle) { CSTR func = "SQLCopyDesc"; RETCODE ret; mylog("[[%s]]\n", func); ret = PGAPI_CopyDesc(SourceDescHandle, TargetDescHandle); return ret; } /* SQLTransact -> SQLEndTran */ RETCODE SQL_API SQLEndTran(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT CompletionType) { CSTR func = "SQLEndTran"; RETCODE ret; mylog("[[%s]]", func); switch (HandleType) { case SQL_HANDLE_ENV: ENTER_ENV_CS((EnvironmentClass *) Handle); ret = PGAPI_Transact(Handle, SQL_NULL_HDBC, CompletionType); LEAVE_ENV_CS((EnvironmentClass *) Handle); break; case SQL_HANDLE_DBC: CC_examine_global_transaction((ConnectionClass *) Handle); ENTER_CONN_CS((ConnectionClass *) Handle); CC_clear_error((ConnectionClass *) Handle); ret = PGAPI_Transact(SQL_NULL_HENV, Handle, CompletionType); LEAVE_CONN_CS((ConnectionClass *) Handle); break; default: ret = SQL_ERROR; break; } return ret; } /* SQLExtendedFetch -> SQLFetchScroll */ RETCODE SQL_API SQLFetchScroll(HSTMT StatementHandle, SQLSMALLINT FetchOrientation, SQLLEN FetchOffset) { CSTR func = "SQLFetchScroll"; StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret = SQL_SUCCESS; IRDFields *irdopts = SC_get_IRDF(stmt); SQLUSMALLINT *rowStatusArray = irdopts->rowStatusArray; SQLULEN *pcRow = irdopts->rowsFetched; SQLLEN bkmarkoff = 0; mylog("[[%s]] %d,%d\n", func, FetchOrientation, FetchOffset); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (FetchOrientation == SQL_FETCH_BOOKMARK) { if (stmt->options.bookmark_ptr) { bkmarkoff = FetchOffset; FetchOffset = *((Int4 *) stmt->options.bookmark_ptr); mylog("bookmark=%u FetchOffset = %d\n", FetchOffset, bkmarkoff); } else { SC_set_error(stmt, STMT_SEQUENCE_ERROR, "Bookmark isn't specifed yet", func); ret = SQL_ERROR; } } if (SQL_SUCCESS == ret) { ARDFields *opts = SC_get_ARDF(stmt); ret = PGAPI_ExtendedFetch(StatementHandle, FetchOrientation, FetchOffset, pcRow, rowStatusArray, bkmarkoff, opts->size_of_rowset); stmt->transition_status = STMT_TRANSITION_FETCH_SCROLL; } ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); if (ret != SQL_SUCCESS) mylog("%s return = %d\n", func, ret); return ret; } /* SQLFree(Connect/Env/Stmt) -> SQLFreeHandle */ RETCODE SQL_API SQLFreeHandle(SQLSMALLINT HandleType, SQLHANDLE Handle) { CSTR func = "SQLFreeHandle"; RETCODE ret; StatementClass *stmt; ConnectionClass *conn = NULL; mylog("[[%s]]", func); switch (HandleType) { case SQL_HANDLE_ENV: ret = PGAPI_FreeEnv(Handle); break; case SQL_HANDLE_DBC: ret = PGAPI_FreeConnect(Handle); break; case SQL_HANDLE_STMT: stmt = (StatementClass *) Handle; if (stmt) { conn = stmt->hdbc; if (conn) ENTER_CONN_CS(conn); } ret = PGAPI_FreeStmt(Handle, SQL_DROP); if (conn) LEAVE_CONN_CS(conn); break; case SQL_HANDLE_DESC: ret = PGAPI_FreeDesc(Handle); break; default: ret = SQL_ERROR; break; } return ret; } /* new function */ RETCODE SQL_API SQLGetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret; mylog("[[SQLGetDescField]]\n"); ret = PGAPI_GetDescField(DescriptorHandle, RecNumber, FieldIdentifier, Value, BufferLength, StringLength); return ret; } /* new function */ RETCODE SQL_API SQLGetDescRec(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLCHAR *Name, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength, SQLSMALLINT *Type, SQLSMALLINT *SubType, SQLLEN *Length, SQLSMALLINT *Precision, SQLSMALLINT *Scale, SQLSMALLINT *Nullable) { mylog("[[SQLGetDescRec]]\n"); mylog("Error not implemented\n"); return SQL_ERROR; } /* new function */ RETCODE SQL_API SQLGetDiagField(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT RecNumber, SQLSMALLINT DiagIdentifier, PTR DiagInfo, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength) { CSTR func = "SQLGetDiagField"; RETCODE ret; mylog("[[%s]] Handle=(%u,%p) Rec=%d Id=%d info=(%p,%d)\n", func, HandleType, Handle, RecNumber, DiagIdentifier, DiagInfo, BufferLength); ret = PGAPI_GetDiagField(HandleType, Handle, RecNumber, DiagIdentifier, DiagInfo, BufferLength, StringLength); return ret; } /* SQLError -> SQLDiagRec */ RETCODE SQL_API SQLGetDiagRec(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength) { RETCODE ret; mylog("[[SQLGetDiagRec]]\n"); ret = PGAPI_GetDiagRec(HandleType, Handle, RecNumber, Sqlstate, NativeError, MessageText, BufferLength, TextLength); return ret; } /* new function */ RETCODE SQL_API SQLGetEnvAttr(HENV EnvironmentHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret; EnvironmentClass *env = (EnvironmentClass *) EnvironmentHandle; mylog("[[SQLGetEnvAttr]] %d\n", Attribute); ENTER_ENV_CS(env); ret = SQL_SUCCESS; switch (Attribute) { case SQL_ATTR_CONNECTION_POOLING: *((unsigned int *) Value) = EN_is_pooling(env) ? SQL_CP_ONE_PER_DRIVER : SQL_CP_OFF; break; case SQL_ATTR_CP_MATCH: *((unsigned int *) Value) = SQL_CP_RELAXED_MATCH; break; case SQL_ATTR_ODBC_VERSION: *((unsigned int *) Value) = EN_is_odbc2(env) ? SQL_OV_ODBC2 : SQL_OV_ODBC3; break; case SQL_ATTR_OUTPUT_NTS: *((unsigned int *) Value) = SQL_TRUE; break; default: env->errornumber = CONN_INVALID_ARGUMENT_NO; ret = SQL_ERROR; } LEAVE_ENV_CS(env); return ret; } #ifndef UNICODE_SUPPORTXX /* SQLGetConnectOption -> SQLGetconnectAttr */ RETCODE SQL_API SQLGetConnectAttr(HDBC ConnectionHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret; mylog("[[SQLGetConnectAttr]] %d\n", Attribute); CC_examine_global_transaction((ConnectionClass*) ConnectionHandle); ENTER_CONN_CS((ConnectionClass *) ConnectionHandle); CC_clear_error((ConnectionClass *) ConnectionHandle); ret = PGAPI_GetConnectAttr(ConnectionHandle, Attribute,Value, BufferLength, StringLength); LEAVE_CONN_CS((ConnectionClass *) ConnectionHandle); return ret; } /* SQLGetStmtOption -> SQLGetStmtAttr */ RETCODE SQL_API SQLGetStmtAttr(HSTMT StatementHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret; CSTR func = "SQLGetStmtAttr"; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("[[%s]] Handle=%u %d\n", func, StatementHandle, Attribute); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_GetStmtAttr(StatementHandle, Attribute, Value, BufferLength, StringLength); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } /* SQLSetConnectOption -> SQLSetConnectAttr */ RETCODE SQL_API SQLSetConnectAttr(HDBC ConnectionHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[[SQLSetConnectAttr]] %d\n", Attribute); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); ret = PGAPI_SetConnectAttr(ConnectionHandle, Attribute, Value, StringLength); LEAVE_CONN_CS(conn); return ret; } #endif /* UNICODE_SUPPORTXX */ /* new function */ RETCODE SQL_API SQLSetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { RETCODE ret; mylog("[[SQLSetDescField]] h=%p rec=%d field=%d val=%p\n", DescriptorHandle, RecNumber, FieldIdentifier, Value); ret = PGAPI_SetDescField(DescriptorHandle, RecNumber, FieldIdentifier, Value, BufferLength); return ret; } /* new fucntion */ RETCODE SQL_API SQLSetDescRec(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT Type, SQLSMALLINT SubType, SQLLEN Length, SQLSMALLINT Precision, SQLSMALLINT Scale, PTR Data, SQLLEN *StringLength, SQLLEN *Indicator) { CSTR func = "SQLSetDescRec"; mylog("[[%s]]\n", func); mylog("Error not implemented\n"); return SQL_ERROR; } /* new function */ RETCODE SQL_API SQLSetEnvAttr(HENV EnvironmentHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength) { RETCODE ret; EnvironmentClass *env = (EnvironmentClass *) EnvironmentHandle; mylog("[[SQLSetEnvAttr]] att=%d,%u\n", Attribute, Value); ENTER_ENV_CS(env); switch (Attribute) { case SQL_ATTR_CONNECTION_POOLING: switch ((ULONG_PTR) Value) { case SQL_CP_OFF: EN_unset_pooling(env); ret = SQL_SUCCESS; break; #if defined(WIN_MULTITHREAD_SUPPORT) || defined(POSIX_MULTITHREAD_SUPPORT) case SQL_CP_ONE_PER_DRIVER: EN_set_pooling(env); ret = SQL_SUCCESS; break; #endif /* WIN_MULTITHREAD_SUPPORT */ default: ret = SQL_SUCCESS_WITH_INFO; } break; case SQL_ATTR_CP_MATCH: /* *((unsigned int *) Value) = SQL_CP_RELAXED_MATCH; */ ret = SQL_SUCCESS; break; case SQL_ATTR_ODBC_VERSION: if (SQL_OV_ODBC2 == CAST_UPTR(SQLUINTEGER, Value)) EN_set_odbc2(env); else EN_set_odbc3(env); ret = SQL_SUCCESS; break; case SQL_ATTR_OUTPUT_NTS: if (SQL_TRUE == CAST_UPTR(SQLUINTEGER, Value)) ret = SQL_SUCCESS; else ret = SQL_SUCCESS_WITH_INFO; break; default: env->errornumber = CONN_INVALID_ARGUMENT_NO; ret = SQL_ERROR; } if (SQL_SUCCESS_WITH_INFO == ret) { env->errornumber = CONN_OPTION_VALUE_CHANGED; env->errormsg = "SetEnv changed to "; } LEAVE_ENV_CS(env); return ret; } #ifndef UNICODE_SUPPORTXX /* SQLSet(Param/Scroll/Stmt)Option -> SQLSetStmtAttr */ RETCODE SQL_API SQLSetStmtAttr(HSTMT StatementHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength) { CSTR func = "SQLSetStmtAttr"; StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret; mylog("[[%s]] Handle=%p %d,%u\n", func, StatementHandle, Attribute, Value); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_SetStmtAttr(StatementHandle, Attribute, Value, StringLength); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* UNICODE_SUPPORTXX */ #define SQL_FUNC_ESET(pfExists, uwAPI) \ (*(((UWORD*) (pfExists)) + ((uwAPI) >> 4)) \ |= (1 << ((uwAPI) & 0x000F)) \ ) RETCODE SQL_API PGAPI_GetFunctions30(HDBC hdbc, SQLUSMALLINT fFunction, SQLUSMALLINT FAR * pfExists) { ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci = &(conn->connInfo); inolog("lie=%d\n", ci->drivers.lie); CC_examine_global_transaction(conn); CC_clear_error(conn); if (fFunction != SQL_API_ODBC3_ALL_FUNCTIONS) return SQL_ERROR; memset(pfExists, 0, sizeof(UWORD) * SQL_API_ODBC3_ALL_FUNCTIONS_SIZE); /* SQL_FUNC_ESET(pfExists, SQL_API_SQLALLOCCONNECT); 1 deprecated */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLALLOCENV); 2 deprecated */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLALLOCSTMT); 3 deprecated */ /* * for (i = SQL_API_SQLBINDCOL; i <= 23; i++) SQL_FUNC_ESET(pfExists, * i); */ SQL_FUNC_ESET(pfExists, SQL_API_SQLBINDCOL); /* 4 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLCANCEL); /* 5 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLCOLATTRIBUTE); /* 6 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLCONNECT); /* 7 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLDESCRIBECOL); /* 8 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLDISCONNECT); /* 9 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLERROR); 10 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLEXECDIRECT); /* 11 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLEXECUTE); /* 12 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLFETCH); /* 13 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLFREECONNECT); 14 deprecated */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLFREEENV); 15 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLFREESTMT); /* 16 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETCURSORNAME); /* 17 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLNUMRESULTCOLS); /* 18 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLPREPARE); /* 19 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLROWCOUNT); /* 20 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSETCURSORNAME); /* 21 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLSETPARAM); 22 deprecated */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLTRANSACT); 23 deprecated */ /* * for (i = 40; i < SQL_API_SQLEXTENDEDFETCH; i++) * SQL_FUNC_ESET(pfExists, i); */ SQL_FUNC_ESET(pfExists, SQL_API_SQLCOLUMNS); /* 40 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLDRIVERCONNECT); /* 41 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLGETCONNECTOPTION); 42 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETDATA); /* 43 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETFUNCTIONS); /* 44 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETINFO); /* 45 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLGETSTMTOPTION); 46 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETTYPEINFO); /* 47 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLPARAMDATA); /* 48 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLPUTDATA); /* 49 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLSETCONNECTIONOPTION); 50 deprecated */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLSETSTMTOPTION); 51 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSPECIALCOLUMNS); /* 52 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSTATISTICS); /* 53 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLTABLES); /* 54 */ if (ci->drivers.lie) SQL_FUNC_ESET(pfExists, SQL_API_SQLBROWSECONNECT); /* 55 */ if (ci->drivers.lie) SQL_FUNC_ESET(pfExists, SQL_API_SQLCOLUMNPRIVILEGES); /* 56 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLDATASOURCES); /* 57 */ if (SUPPORT_DESCRIBE_PARAM(ci) || ci->drivers.lie) SQL_FUNC_ESET(pfExists, SQL_API_SQLDESCRIBEPARAM); /* 58 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLEXTENDEDFETCH); /* 59 deprecated ? */ /* * for (++i; i < SQL_API_SQLBINDPARAMETER; i++) * SQL_FUNC_ESET(pfExists, i); */ SQL_FUNC_ESET(pfExists, SQL_API_SQLFOREIGNKEYS); /* 60 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLMORERESULTS); /* 61 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLNATIVESQL); /* 62 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLNUMPARAMS); /* 63 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLPARAMOPTIONS); 64 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLPRIMARYKEYS); /* 65 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLPROCEDURECOLUMNS); /* 66 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLPROCEDURES); /* 67 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSETPOS); /* 68 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLSETSCROLLOPTIONS); 69 deprecated */ SQL_FUNC_ESET(pfExists, SQL_API_SQLTABLEPRIVILEGES); /* 70 */ /* SQL_FUNC_ESET(pfExists, SQL_API_SQLDRIVERS); */ /* 71 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLBINDPARAMETER); /* 72 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLALLOCHANDLE); /* 1001 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLBINDPARAM); /* 1002 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLCLOSECURSOR); /* 1003 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLCOPYDESC); /* 1004 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLENDTRAN); /* 1005 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLFREEHANDLE); /* 1006 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETCONNECTATTR); /* 1007 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETDESCFIELD); /* 1008 */ if (ci->drivers.lie) { SQL_FUNC_ESET(pfExists, SQL_API_SQLGETDESCREC); /* 1009 not implemented yet */ } SQL_FUNC_ESET(pfExists, SQL_API_SQLGETDIAGFIELD); /* 1010 minimal implementation */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETDIAGREC); /* 1011 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETENVATTR); /* 1012 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLGETSTMTATTR); /* 1014 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSETCONNECTATTR); /* 1016 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSETDESCFIELD); /* 1017 */ if (ci->drivers.lie) { SQL_FUNC_ESET(pfExists, SQL_API_SQLSETDESCREC); /* 1018 not implemented yet */ } SQL_FUNC_ESET(pfExists, SQL_API_SQLSETENVATTR); /* 1019 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLSETSTMTATTR); /* 1020 */ SQL_FUNC_ESET(pfExists, SQL_API_SQLFETCHSCROLL); /* 1021 */ if (0 != (ALLOW_BULK_OPERATIONS & ci->updatable_cursors)) SQL_FUNC_ESET(pfExists, SQL_API_SQLBULKOPERATIONS); /* 24 */ return SQL_SUCCESS; } RETCODE SQL_API SQLBulkOperations(HSTMT hstmt, SQLSMALLINT operation) { RETCODE ret; CSTR func = "SQLBulkOperations"; StatementClass *stmt = (StatementClass *) hstmt; ENTER_STMT_CS(stmt); mylog("[[%s]] Handle=%p %d\n", func, hstmt, operation); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_BulkOperations(hstmt, operation); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #endif /* ODBCVER >= 0x0300 */ psqlodbc-09.03.0300/pgapi30.c000644 001752 000000 00000161456 12335653444 015624 0ustar00saitowheel000000 000000 /*------- * Module: pgapi30.c * * Description: This module contains routines related to ODBC 3.0 * most of their implementations are temporary * and must be rewritten properly. * 2001/07/23 inoue * * Classes: n/a * * API functions: PGAPI_ColAttribute, PGAPI_GetDiagRec, PGAPI_GetConnectAttr, PGAPI_GetStmtAttr, PGAPI_SetConnectAttr, PGAPI_SetStmtAttr *------- */ #include "psqlodbc.h" #include "misc.h" #if (ODBCVER >= 0x0300) #include #include #include "environ.h" #include "connection.h" #include "statement.h" #include "descriptor.h" #include "qresult.h" #include "pgapifunc.h" #include "loadlib.h" /* SQLError -> SQLDiagRec */ RETCODE SQL_API PGAPI_GetDiagRec(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength) { RETCODE ret; CSTR func = "PGAPI_GetDiagRec"; mylog("%s entering type=%d rec=%d\n", func, HandleType, RecNumber); switch (HandleType) { case SQL_HANDLE_ENV: ret = PGAPI_EnvError(Handle, RecNumber, Sqlstate, NativeError, MessageText, BufferLength, TextLength, 0); break; case SQL_HANDLE_DBC: ret = PGAPI_ConnectError(Handle, RecNumber, Sqlstate, NativeError, MessageText, BufferLength, TextLength, 0); break; case SQL_HANDLE_STMT: ret = PGAPI_StmtError(Handle, RecNumber, Sqlstate, NativeError, MessageText, BufferLength, TextLength, 0); break; case SQL_HANDLE_DESC: ret = PGAPI_DescError(Handle, RecNumber, Sqlstate, NativeError, MessageText, BufferLength, TextLength, 0); break; default: ret = SQL_ERROR; } mylog("%s exiting %d\n", func, ret); return ret; } /* * Minimal implementation. * */ RETCODE SQL_API PGAPI_GetDiagField(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT RecNumber, SQLSMALLINT DiagIdentifier, PTR DiagInfoPtr, SQLSMALLINT BufferLength, SQLSMALLINT *StringLengthPtr) { RETCODE ret = SQL_ERROR, rtn; ConnectionClass *conn; StatementClass *stmt; SQLLEN rc; SQLSMALLINT pcbErrm; ssize_t rtnlen = -1; int rtnctype = SQL_C_CHAR; CSTR func = "PGAPI_GetDiagField"; mylog("%s entering rec=%d", func, RecNumber); switch (HandleType) { case SQL_HANDLE_ENV: switch (DiagIdentifier) { case SQL_DIAG_CLASS_ORIGIN: case SQL_DIAG_SUBCLASS_ORIGIN: case SQL_DIAG_CONNECTION_NAME: case SQL_DIAG_SERVER_NAME: rtnlen = 0; if (DiagInfoPtr && BufferLength > rtnlen) { ret = SQL_SUCCESS; *((char *) DiagInfoPtr) = '\0'; } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_MESSAGE_TEXT: ret = PGAPI_EnvError(Handle, RecNumber, NULL, NULL, DiagInfoPtr, BufferLength, StringLengthPtr, 0); break; case SQL_DIAG_NATIVE: rtnctype = SQL_C_LONG; ret = PGAPI_EnvError(Handle, RecNumber, NULL, (SQLINTEGER *) DiagInfoPtr, NULL, 0, NULL, 0); break; case SQL_DIAG_NUMBER: rtnctype = SQL_C_LONG; ret = PGAPI_EnvError(Handle, RecNumber, NULL, NULL, NULL, 0, NULL, 0); if (SQL_SUCCEEDED(ret)) { *((SQLINTEGER *) DiagInfoPtr) = 1; } break; case SQL_DIAG_SQLSTATE: rtnlen = 5; ret = PGAPI_EnvError(Handle, RecNumber, DiagInfoPtr, NULL, NULL, 0, NULL, 0); if (SQL_SUCCESS_WITH_INFO == ret) ret = SQL_SUCCESS; break; case SQL_DIAG_RETURNCODE: /* driver manager returns */ break; case SQL_DIAG_CURSOR_ROW_COUNT: case SQL_DIAG_ROW_COUNT: case SQL_DIAG_DYNAMIC_FUNCTION: case SQL_DIAG_DYNAMIC_FUNCTION_CODE: /* options for statement type only */ break; } break; case SQL_HANDLE_DBC: conn = (ConnectionClass *) Handle; switch (DiagIdentifier) { case SQL_DIAG_CLASS_ORIGIN: case SQL_DIAG_SUBCLASS_ORIGIN: case SQL_DIAG_CONNECTION_NAME: rtnlen = 0; if (DiagInfoPtr && BufferLength > rtnlen) { ret = SQL_SUCCESS; *((char *) DiagInfoPtr) = '\0'; } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_SERVER_NAME: rtnlen = strlen(CC_get_DSN(conn)); if (DiagInfoPtr) { strncpy_null(DiagInfoPtr, CC_get_DSN(conn), BufferLength); ret = (BufferLength > rtnlen ? SQL_SUCCESS : SQL_SUCCESS_WITH_INFO); } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_MESSAGE_TEXT: ret = PGAPI_ConnectError(Handle, RecNumber, NULL, NULL, DiagInfoPtr, BufferLength, StringLengthPtr, 0); break; case SQL_DIAG_NATIVE: rtnctype = SQL_C_LONG; ret = PGAPI_ConnectError(Handle, RecNumber, NULL, (SQLINTEGER *) DiagInfoPtr, NULL, 0, NULL, 0); break; case SQL_DIAG_NUMBER: rtnctype = SQL_C_LONG; ret = PGAPI_ConnectError(Handle, RecNumber, NULL, NULL, NULL, 0, NULL, 0); if (SQL_SUCCEEDED(ret)) { *((SQLINTEGER *) DiagInfoPtr) = 1; } break; case SQL_DIAG_SQLSTATE: rtnlen = 5; ret = PGAPI_ConnectError(Handle, RecNumber, DiagInfoPtr, NULL, NULL, 0, NULL, 0); if (SQL_SUCCESS_WITH_INFO == ret) ret = SQL_SUCCESS; break; case SQL_DIAG_RETURNCODE: /* driver manager returns */ break; case SQL_DIAG_CURSOR_ROW_COUNT: case SQL_DIAG_ROW_COUNT: case SQL_DIAG_DYNAMIC_FUNCTION: case SQL_DIAG_DYNAMIC_FUNCTION_CODE: /* options for statement type only */ break; } break; case SQL_HANDLE_STMT: conn = (ConnectionClass *) SC_get_conn(((StatementClass *) Handle)); switch (DiagIdentifier) { case SQL_DIAG_CLASS_ORIGIN: case SQL_DIAG_SUBCLASS_ORIGIN: case SQL_DIAG_CONNECTION_NAME: rtnlen = 0; if (DiagInfoPtr && BufferLength > rtnlen) { ret = SQL_SUCCESS; *((char *) DiagInfoPtr) = '\0'; } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_SERVER_NAME: rtnlen = strlen(CC_get_DSN(conn)); if (DiagInfoPtr) { strncpy_null(DiagInfoPtr, CC_get_DSN(conn), BufferLength); ret = (BufferLength > rtnlen ? SQL_SUCCESS : SQL_SUCCESS_WITH_INFO); } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_MESSAGE_TEXT: ret = PGAPI_StmtError(Handle, RecNumber, NULL, NULL, DiagInfoPtr, BufferLength, StringLengthPtr, 0); break; case SQL_DIAG_NATIVE: rtnctype = SQL_C_LONG; ret = PGAPI_StmtError(Handle, RecNumber, NULL, (SQLINTEGER *) DiagInfoPtr, NULL, 0, NULL, 0); break; case SQL_DIAG_NUMBER: rtnctype = SQL_C_LONG; *((SQLINTEGER *) DiagInfoPtr) = 0; ret = SQL_NO_DATA_FOUND; stmt = (StatementClass *) Handle; rtn = PGAPI_StmtError(Handle, -1, NULL, NULL, NULL, 0, &pcbErrm, 0); switch (rtn) { case SQL_SUCCESS: case SQL_SUCCESS_WITH_INFO: ret = SQL_SUCCESS; if (pcbErrm > 0 && stmt->pgerror) *((SQLINTEGER *) DiagInfoPtr) = (pcbErrm - 1)/ stmt->pgerror->recsize + 1; break; default: break; } break; case SQL_DIAG_SQLSTATE: rtnlen = 5; ret = PGAPI_StmtError(Handle, RecNumber, DiagInfoPtr, NULL, NULL, 0, NULL, 0); if (SQL_SUCCESS_WITH_INFO == ret) ret = SQL_SUCCESS; break; case SQL_DIAG_CURSOR_ROW_COUNT: rtnctype = SQL_C_LONG; stmt = (StatementClass *) Handle; rc = -1; if (stmt->status == STMT_FINISHED) { QResultClass *res = SC_get_Curres(stmt); /*if (!res) return SQL_ERROR;*/ if (stmt->proc_return > 0) rc = 0; else if (res && QR_NumResultCols(res) > 0 && !SC_is_fetchcursor(stmt)) rc = QR_get_num_total_tuples(res) - res->dl_count; } *((SQLLEN *) DiagInfoPtr) = rc; inolog("rc=%d\n", rc); ret = SQL_SUCCESS; break; case SQL_DIAG_ROW_COUNT: rtnctype = SQL_C_LONG; stmt = (StatementClass *) Handle; *((SQLLEN *) DiagInfoPtr) = stmt->diag_row_count; ret = SQL_SUCCESS; break; case SQL_DIAG_ROW_NUMBER: rtnctype = SQL_C_LONG; *((SQLLEN *) DiagInfoPtr) = SQL_ROW_NUMBER_UNKNOWN; ret = SQL_SUCCESS; break; case SQL_DIAG_COLUMN_NUMBER: rtnctype = SQL_C_LONG; *((SQLINTEGER *) DiagInfoPtr) = SQL_COLUMN_NUMBER_UNKNOWN; ret = SQL_SUCCESS; break; case SQL_DIAG_RETURNCODE: /* driver manager returns */ break; } break; case SQL_HANDLE_DESC: conn = DC_get_conn(((DescriptorClass *) Handle)); switch (DiagIdentifier) { case SQL_DIAG_CLASS_ORIGIN: case SQL_DIAG_SUBCLASS_ORIGIN: case SQL_DIAG_CONNECTION_NAME: rtnlen = 0; if (DiagInfoPtr && BufferLength > rtnlen) { ret = SQL_SUCCESS; *((char *) DiagInfoPtr) = '\0'; } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_SERVER_NAME: rtnlen = strlen(CC_get_DSN(conn)); if (DiagInfoPtr) { strncpy_null(DiagInfoPtr, CC_get_DSN(conn), BufferLength); ret = (BufferLength > rtnlen ? SQL_SUCCESS : SQL_SUCCESS_WITH_INFO); } else ret = SQL_SUCCESS_WITH_INFO; break; case SQL_DIAG_MESSAGE_TEXT: case SQL_DIAG_NATIVE: case SQL_DIAG_NUMBER: break; case SQL_DIAG_SQLSTATE: rtnlen = 5; ret = PGAPI_DescError(Handle, RecNumber, DiagInfoPtr, NULL, NULL, 0, NULL, 0); if (SQL_SUCCESS_WITH_INFO == ret) ret = SQL_SUCCESS; break; case SQL_DIAG_RETURNCODE: /* driver manager returns */ break; case SQL_DIAG_CURSOR_ROW_COUNT: case SQL_DIAG_ROW_COUNT: case SQL_DIAG_DYNAMIC_FUNCTION: case SQL_DIAG_DYNAMIC_FUNCTION_CODE: rtnctype = SQL_C_LONG; /* options for statement type only */ break; } break; default: ret = SQL_ERROR; } if (SQL_C_LONG == rtnctype) { if (SQL_SUCCESS_WITH_INFO == ret) ret = SQL_SUCCESS; if (StringLengthPtr) *StringLengthPtr = sizeof(SQLINTEGER); } else if (rtnlen >= 0) { if (rtnlen >= BufferLength) { if (SQL_SUCCESS == ret) ret = SQL_SUCCESS_WITH_INFO; if (BufferLength > 0) ((char *) DiagInfoPtr) [BufferLength - 1] = '\0'; } if (StringLengthPtr) *StringLengthPtr = (SQLSMALLINT) rtnlen; } mylog("%s exiting %d\n", func, ret); return ret; } /* SQLGetConnectOption -> SQLGetconnectAttr */ RETCODE SQL_API PGAPI_GetConnectAttr(HDBC ConnectionHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; RETCODE ret = SQL_SUCCESS; SQLINTEGER len = 4; mylog("PGAPI_GetConnectAttr %d\n", Attribute); switch (Attribute) { case SQL_ATTR_ASYNC_ENABLE: *((SQLINTEGER *) Value) = SQL_ASYNC_ENABLE_OFF; break; case SQL_ATTR_AUTO_IPD: *((SQLINTEGER *) Value) = SQL_FALSE; break; case SQL_ATTR_CONNECTION_DEAD: *((SQLUINTEGER *) Value) = (conn->status == CONN_NOT_CONNECTED || conn->status == CONN_DOWN); break; case SQL_ATTR_CONNECTION_TIMEOUT: *((SQLUINTEGER *) Value) = 0; break; case SQL_ATTR_METADATA_ID: *((SQLUINTEGER *) Value) = conn->stmtOptions.metadata_id; break; default: ret = PGAPI_GetConnectOption(ConnectionHandle, (UWORD) Attribute, Value, &len, BufferLength); } if (StringLength) *StringLength = len; return ret; } static SQLHDESC descHandleFromStatementHandle(HSTMT StatementHandle, SQLINTEGER descType) { StatementClass *stmt = (StatementClass *) StatementHandle; switch (descType) { case SQL_ATTR_APP_ROW_DESC: /* 10010 */ return (HSTMT) stmt->ard; case SQL_ATTR_APP_PARAM_DESC: /* 10011 */ return (HSTMT) stmt->apd; case SQL_ATTR_IMP_ROW_DESC: /* 10012 */ return (HSTMT) stmt->ird; case SQL_ATTR_IMP_PARAM_DESC: /* 10013 */ return (HSTMT) stmt->ipd; } return (HSTMT) 0; } static void column_bindings_set(ARDFields *opts, int cols, BOOL maxset) { int i; if (cols == opts->allocated) return; if (cols > opts->allocated) { extend_column_bindings(opts, cols); return; } if (maxset) return; for (i = opts->allocated; i > cols; i--) reset_a_column_binding(opts, i); opts->allocated = cols; if (0 == cols) { free(opts->bindings); opts->bindings = NULL; } } static RETCODE SQL_API ARDSetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { RETCODE ret = SQL_SUCCESS; ARDFields *opts = (ARDFields *) (desc + 1); SQLSMALLINT row_idx; BOOL unbind = TRUE; switch (FieldIdentifier) { case SQL_DESC_ARRAY_SIZE: opts->size_of_rowset = CAST_UPTR(SQLULEN, Value); return ret; case SQL_DESC_ARRAY_STATUS_PTR: opts->row_operation_ptr = Value; return ret; case SQL_DESC_BIND_OFFSET_PTR: opts->row_offset_ptr = Value; return ret; case SQL_DESC_BIND_TYPE: opts->bind_size = CAST_UPTR(SQLUINTEGER, Value); return ret; case SQL_DESC_COUNT: column_bindings_set(opts, CAST_PTR(SQLSMALLINT, Value), FALSE); return ret; case SQL_DESC_TYPE: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_CONCISE_TYPE: column_bindings_set(opts, RecNumber, TRUE); break; } if (RecNumber < 0 || RecNumber > opts->allocated) { DC_set_error(desc, DESC_INVALID_COLUMN_NUMBER_ERROR, "invalid column number"); return SQL_ERROR; } if (0 == RecNumber) /* bookmark column */ { BindInfoClass *bookmark = ARD_AllocBookmark(opts); switch (FieldIdentifier) { case SQL_DESC_DATA_PTR: bookmark->buffer = Value; break; case SQL_DESC_INDICATOR_PTR: bookmark->indicator = Value; break; case SQL_DESC_OCTET_LENGTH_PTR: bookmark->used = Value; break; default: DC_set_error(desc, DESC_INVALID_COLUMN_NUMBER_ERROR, "invalid column number"); ret = SQL_ERROR; } return ret; } row_idx = RecNumber - 1; switch (FieldIdentifier) { case SQL_DESC_TYPE: opts->bindings[row_idx].returntype = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_DATETIME_INTERVAL_CODE: switch (opts->bindings[row_idx].returntype) { case SQL_DATETIME: case SQL_C_TYPE_DATE: case SQL_C_TYPE_TIME: case SQL_C_TYPE_TIMESTAMP: switch ((LONG_PTR) Value) { case SQL_CODE_DATE: opts->bindings[row_idx].returntype = SQL_C_TYPE_DATE; break; case SQL_CODE_TIME: opts->bindings[row_idx].returntype = SQL_C_TYPE_TIME; break; case SQL_CODE_TIMESTAMP: opts->bindings[row_idx].returntype = SQL_C_TYPE_TIMESTAMP; break; } break; } break; case SQL_DESC_CONCISE_TYPE: opts->bindings[row_idx].returntype = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_DATA_PTR: unbind = FALSE; opts->bindings[row_idx].buffer = Value; break; case SQL_DESC_INDICATOR_PTR: unbind = FALSE; opts->bindings[row_idx].indicator = Value; break; case SQL_DESC_OCTET_LENGTH_PTR: unbind = FALSE; opts->bindings[row_idx].used = Value; break; case SQL_DESC_OCTET_LENGTH: opts->bindings[row_idx].buflen = CAST_PTR(SQLLEN, Value); break; case SQL_DESC_PRECISION: opts->bindings[row_idx].precision = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_SCALE: opts->bindings[row_idx].scale = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_ALLOC_TYPE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_LENGTH: case SQL_DESC_NUM_PREC_RADIX: default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } if (unbind) opts->bindings[row_idx].buffer = NULL; return ret; } static void parameter_bindings_set(APDFields *opts, int params, BOOL maxset) { int i; if (params == opts->allocated) return; if (params > opts->allocated) { extend_parameter_bindings(opts, params); return; } if (maxset) return; for (i = opts->allocated; i > params; i--) reset_a_parameter_binding(opts, i); opts->allocated = params; if (0 == params) { free(opts->parameters); opts->parameters = NULL; } } static void parameter_ibindings_set(IPDFields *opts, int params, BOOL maxset) { int i; if (params == opts->allocated) return; if (params > opts->allocated) { extend_iparameter_bindings(opts, params); return; } if (maxset) return; for (i = opts->allocated; i > params; i--) reset_a_iparameter_binding(opts, i); opts->allocated = params; if (0 == params) { free(opts->parameters); opts->parameters = NULL; } } static RETCODE SQL_API APDSetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { CSTR func = "APDSetField"; RETCODE ret = SQL_SUCCESS; APDFields *opts = (APDFields *) (desc + 1); SQLSMALLINT para_idx; BOOL unbind = TRUE; switch (FieldIdentifier) { case SQL_DESC_ARRAY_SIZE: opts->paramset_size = CAST_UPTR(SQLUINTEGER, Value); return ret; case SQL_DESC_ARRAY_STATUS_PTR: opts->param_operation_ptr = Value; return ret; case SQL_DESC_BIND_OFFSET_PTR: opts->param_offset_ptr = Value; return ret; case SQL_DESC_BIND_TYPE: opts->param_bind_type = CAST_UPTR(SQLUINTEGER, Value); return ret; case SQL_DESC_COUNT: parameter_bindings_set(opts, CAST_PTR(SQLSMALLINT, Value), FALSE); return ret; case SQL_DESC_TYPE: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_CONCISE_TYPE: parameter_bindings_set(opts, RecNumber, TRUE); break; } if (RecNumber <=0) { inolog("%s RecN=%d allocated=%d\n", func, RecNumber, opts->allocated); DC_set_error(desc, DESC_BAD_PARAMETER_NUMBER_ERROR, "bad parameter number"); return SQL_ERROR; } if (RecNumber > opts->allocated) { inolog("%s RecN=%d allocated=%d\n", func, RecNumber, opts->allocated); parameter_bindings_set(opts, RecNumber, TRUE); /* DC_set_error(desc, DESC_BAD_PARAMETER_NUMBER_ERROR, "bad parameter number"); return SQL_ERROR;*/ } para_idx = RecNumber - 1; switch (FieldIdentifier) { case SQL_DESC_TYPE: opts->parameters[para_idx].CType = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_DATETIME_INTERVAL_CODE: switch (opts->parameters[para_idx].CType) { case SQL_DATETIME: case SQL_C_TYPE_DATE: case SQL_C_TYPE_TIME: case SQL_C_TYPE_TIMESTAMP: switch ((LONG_PTR) Value) { case SQL_CODE_DATE: opts->parameters[para_idx].CType = SQL_C_TYPE_DATE; break; case SQL_CODE_TIME: opts->parameters[para_idx].CType = SQL_C_TYPE_TIME; break; case SQL_CODE_TIMESTAMP: opts->parameters[para_idx].CType = SQL_C_TYPE_TIMESTAMP; break; } break; } break; case SQL_DESC_CONCISE_TYPE: opts->parameters[para_idx].CType = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_DATA_PTR: unbind = FALSE; opts->parameters[para_idx].buffer = Value; break; case SQL_DESC_INDICATOR_PTR: unbind = FALSE; opts->parameters[para_idx].indicator = Value; break; case SQL_DESC_OCTET_LENGTH: opts->parameters[para_idx].buflen = CAST_PTR(Int4, Value); break; case SQL_DESC_OCTET_LENGTH_PTR: unbind = FALSE; opts->parameters[para_idx].used = Value; break; case SQL_DESC_PRECISION: opts->parameters[para_idx].precision = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_SCALE: opts->parameters[para_idx].scale = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_ALLOC_TYPE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_LENGTH: case SQL_DESC_NUM_PREC_RADIX: default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invaid descriptor identifier"); } if (unbind) opts->parameters[para_idx].buffer = NULL; return ret; } static RETCODE SQL_API IRDSetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { RETCODE ret = SQL_SUCCESS; IRDFields *opts = (IRDFields *) (desc + 1); switch (FieldIdentifier) { case SQL_DESC_ARRAY_STATUS_PTR: opts->rowStatusArray = (SQLUSMALLINT *) Value; break; case SQL_DESC_ROWS_PROCESSED_PTR: opts->rowsFetched = (SQLULEN *) Value; break; case SQL_DESC_ALLOC_TYPE: /* read-only */ case SQL_DESC_COUNT: /* read-only */ case SQL_DESC_AUTO_UNIQUE_VALUE: /* read-only */ case SQL_DESC_BASE_COLUMN_NAME: /* read-only */ case SQL_DESC_BASE_TABLE_NAME: /* read-only */ case SQL_DESC_CASE_SENSITIVE: /* read-only */ case SQL_DESC_CATALOG_NAME: /* read-only */ case SQL_DESC_CONCISE_TYPE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_CODE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_PRECISION: /* read-only */ case SQL_DESC_DISPLAY_SIZE: /* read-only */ case SQL_DESC_FIXED_PREC_SCALE: /* read-only */ case SQL_DESC_LABEL: /* read-only */ case SQL_DESC_LENGTH: /* read-only */ case SQL_DESC_LITERAL_PREFIX: /* read-only */ case SQL_DESC_LITERAL_SUFFIX: /* read-only */ case SQL_DESC_LOCAL_TYPE_NAME: /* read-only */ case SQL_DESC_NAME: /* read-only */ case SQL_DESC_NULLABLE: /* read-only */ case SQL_DESC_NUM_PREC_RADIX: /* read-only */ case SQL_DESC_OCTET_LENGTH: /* read-only */ case SQL_DESC_PRECISION: /* read-only */ #if (ODBCVER >= 0x0350) case SQL_DESC_ROWVER: /* read-only */ #endif /* ODBCVER */ case SQL_DESC_SCALE: /* read-only */ case SQL_DESC_SCHEMA_NAME: /* read-only */ case SQL_DESC_SEARCHABLE: /* read-only */ case SQL_DESC_TABLE_NAME: /* read-only */ case SQL_DESC_TYPE: /* read-only */ case SQL_DESC_TYPE_NAME: /* read-only */ case SQL_DESC_UNNAMED: /* read-only */ case SQL_DESC_UNSIGNED: /* read-only */ case SQL_DESC_UPDATABLE: /* read-only */ default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } return ret; } static RETCODE SQL_API IPDSetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { RETCODE ret = SQL_SUCCESS; IPDFields *ipdopts = (IPDFields *) (desc + 1); SQLSMALLINT para_idx; switch (FieldIdentifier) { case SQL_DESC_ARRAY_STATUS_PTR: ipdopts->param_status_ptr = (SQLUSMALLINT *) Value; return ret; case SQL_DESC_ROWS_PROCESSED_PTR: ipdopts->param_processed_ptr = (SQLULEN *) Value; return ret; case SQL_DESC_COUNT: parameter_ibindings_set(ipdopts, CAST_PTR(SQLSMALLINT, Value), FALSE); return ret; case SQL_DESC_UNNAMED: /* only SQL_UNNAMED is allowed */ if (SQL_UNNAMED != CAST_PTR(SQLSMALLINT, Value)) { ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); return ret; } case SQL_DESC_NAME: case SQL_DESC_TYPE: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_CONCISE_TYPE: parameter_ibindings_set(ipdopts, RecNumber, TRUE); break; } if (RecNumber <= 0 || RecNumber > ipdopts->allocated) { inolog("IPDSetField RecN=%d allocated=%d\n", RecNumber, ipdopts->allocated); DC_set_error(desc, DESC_BAD_PARAMETER_NUMBER_ERROR, "bad parameter number"); return SQL_ERROR; } para_idx = RecNumber - 1; switch (FieldIdentifier) { case SQL_DESC_TYPE: if (ipdopts->parameters[para_idx].SQLType != CAST_PTR(SQLSMALLINT, Value)) { reset_a_iparameter_binding(ipdopts, RecNumber); ipdopts->parameters[para_idx].SQLType = CAST_PTR(SQLSMALLINT, Value); } break; case SQL_DESC_DATETIME_INTERVAL_CODE: switch (ipdopts->parameters[para_idx].SQLType) { case SQL_DATETIME: case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: switch ((LONG_PTR) Value) { case SQL_CODE_DATE: ipdopts->parameters[para_idx].SQLType = SQL_TYPE_DATE; break; case SQL_CODE_TIME: ipdopts->parameters[para_idx].SQLType = SQL_TYPE_TIME; break; case SQL_CODE_TIMESTAMP: ipdopts->parameters[para_idx].SQLType = SQL_TYPE_TIMESTAMP; break; } break; } break; case SQL_DESC_CONCISE_TYPE: ipdopts->parameters[para_idx].SQLType = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_NAME: if (Value) STR_TO_NAME(ipdopts->parameters[para_idx].paramName, Value); else NULL_THE_NAME(ipdopts->parameters[para_idx].paramName); break; case SQL_DESC_PARAMETER_TYPE: ipdopts->parameters[para_idx].paramType = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_SCALE: ipdopts->parameters[para_idx].decimal_digits = CAST_PTR(SQLSMALLINT, Value); break; case SQL_DESC_UNNAMED: /* only SQL_UNNAMED is allowed */ if (SQL_UNNAMED != CAST_PTR(SQLSMALLINT, Value)) { ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } else NULL_THE_NAME(ipdopts->parameters[para_idx].paramName); break; case SQL_DESC_ALLOC_TYPE: /* read-only */ case SQL_DESC_CASE_SENSITIVE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_FIXED_PREC_SCALE: /* read-only */ case SQL_DESC_LENGTH: case SQL_DESC_LOCAL_TYPE_NAME: /* read-only */ case SQL_DESC_NULLABLE: /* read-only */ case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_PRECISION: #if (ODBCVER >= 0x0350) case SQL_DESC_ROWVER: /* read-only */ #endif /* ODBCVER */ case SQL_DESC_TYPE_NAME: /* read-only */ case SQL_DESC_UNSIGNED: /* read-only */ default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } return ret; } static RETCODE SQL_API ARDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret = SQL_SUCCESS; SQLLEN ival = 0; SQLINTEGER len, rettype = 0; PTR ptr = NULL; const ARDFields *opts = (ARDFields *) (desc + 1); SQLSMALLINT row_idx; len = sizeof(SQLINTEGER); if (0 == RecNumber) /* bookmark */ { BindInfoClass *bookmark = opts->bookmark; switch (FieldIdentifier) { case SQL_DESC_DATA_PTR: rettype = SQL_IS_POINTER; ptr = bookmark ? bookmark->buffer : NULL; break; case SQL_DESC_INDICATOR_PTR: rettype = SQL_IS_POINTER; ptr = bookmark ? bookmark->indicator : NULL; break; case SQL_DESC_OCTET_LENGTH_PTR: rettype = SQL_IS_POINTER; ptr = bookmark ? bookmark->used : NULL; break; } if (ptr) { *((void **) Value) = ptr; if (StringLength) *StringLength = len; return ret; } } switch (FieldIdentifier) { case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: break; default: if (RecNumber <= 0 || RecNumber > opts->allocated) { DC_set_error(desc, DESC_INVALID_COLUMN_NUMBER_ERROR, "invalid column number"); return SQL_ERROR; } } row_idx = RecNumber - 1; switch (FieldIdentifier) { case SQL_DESC_ARRAY_SIZE: ival = opts->size_of_rowset; break; case SQL_DESC_ARRAY_STATUS_PTR: rettype = SQL_IS_POINTER; ptr = opts->row_operation_ptr; break; case SQL_DESC_BIND_OFFSET_PTR: rettype = SQL_IS_POINTER; ptr = opts->row_offset_ptr; break; case SQL_DESC_BIND_TYPE: ival = opts->bind_size; break; case SQL_DESC_TYPE: rettype = SQL_IS_SMALLINT; switch (opts->bindings[row_idx].returntype) { case SQL_C_TYPE_DATE: case SQL_C_TYPE_TIME: case SQL_C_TYPE_TIMESTAMP: ival = SQL_DATETIME; break; default: ival = opts->bindings[row_idx].returntype; } break; case SQL_DESC_DATETIME_INTERVAL_CODE: rettype = SQL_IS_SMALLINT; switch (opts->bindings[row_idx].returntype) { case SQL_C_TYPE_DATE: ival = SQL_CODE_DATE; break; case SQL_C_TYPE_TIME: ival = SQL_CODE_TIME; break; case SQL_C_TYPE_TIMESTAMP: ival = SQL_CODE_TIMESTAMP; break; default: ival = 0; break; } break; case SQL_DESC_CONCISE_TYPE: rettype = SQL_IS_SMALLINT; ival = opts->bindings[row_idx].returntype; break; case SQL_DESC_DATA_PTR: rettype = SQL_IS_POINTER; ptr = opts->bindings[row_idx].buffer; break; case SQL_DESC_INDICATOR_PTR: rettype = SQL_IS_POINTER; ptr = opts->bindings[row_idx].indicator; break; case SQL_DESC_OCTET_LENGTH_PTR: rettype = SQL_IS_POINTER; ptr = opts->bindings[row_idx].used; break; case SQL_DESC_COUNT: rettype = SQL_IS_SMALLINT; ival = opts->allocated; break; case SQL_DESC_OCTET_LENGTH: ival = opts->bindings[row_idx].buflen; break; case SQL_DESC_ALLOC_TYPE: /* read-only */ rettype = SQL_IS_SMALLINT; if (desc->embedded) ival = SQL_DESC_ALLOC_AUTO; else ival = SQL_DESC_ALLOC_USER; break; case SQL_DESC_PRECISION: rettype = SQL_IS_SMALLINT; ival = opts->bindings[row_idx].precision; break; case SQL_DESC_SCALE: rettype = SQL_IS_SMALLINT; ival = opts->bindings[row_idx].scale; break; case SQL_DESC_NUM_PREC_RADIX: ival = 10; break; case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_LENGTH: default: ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } switch (rettype) { case 0: case SQL_IS_INTEGER: len = sizeof(SQLINTEGER); *((SQLINTEGER *) Value) = (SQLINTEGER) ival; break; case SQL_IS_SMALLINT: len = sizeof(SQLSMALLINT); *((SQLSMALLINT *) Value) = (SQLSMALLINT) ival; break; case SQL_IS_POINTER: len = sizeof(SQLPOINTER); *((void **) Value) = ptr; break; } if (StringLength) *StringLength = len; return ret; } static RETCODE SQL_API APDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret = SQL_SUCCESS; SQLLEN ival = 0; SQLINTEGER len, rettype = 0; PTR ptr = NULL; const APDFields *opts = (const APDFields *) (desc + 1); SQLSMALLINT para_idx; len = sizeof(SQLINTEGER); switch (FieldIdentifier) { case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: break; default:if (RecNumber <= 0 || RecNumber > opts->allocated) { inolog("APDGetField RecN=%d allocated=%d\n", RecNumber, opts->allocated); DC_set_error(desc, DESC_BAD_PARAMETER_NUMBER_ERROR, "bad parameter number"); return SQL_ERROR; } } para_idx = RecNumber - 1; switch (FieldIdentifier) { case SQL_DESC_ARRAY_SIZE: rettype = SQL_IS_LEN; ival = opts->paramset_size; break; case SQL_DESC_ARRAY_STATUS_PTR: rettype = SQL_IS_POINTER; ptr = opts->param_operation_ptr; break; case SQL_DESC_BIND_OFFSET_PTR: rettype = SQL_IS_POINTER; ptr = opts->param_offset_ptr; break; case SQL_DESC_BIND_TYPE: ival = opts->param_bind_type; break; case SQL_DESC_TYPE: rettype = SQL_IS_SMALLINT; switch (opts->parameters[para_idx].CType) { case SQL_C_TYPE_DATE: case SQL_C_TYPE_TIME: case SQL_C_TYPE_TIMESTAMP: ival = SQL_DATETIME; break; default: ival = opts->parameters[para_idx].CType; } break; case SQL_DESC_DATETIME_INTERVAL_CODE: rettype = SQL_IS_SMALLINT; switch (opts->parameters[para_idx].CType) { case SQL_C_TYPE_DATE: ival = SQL_CODE_DATE; break; case SQL_C_TYPE_TIME: ival = SQL_CODE_TIME; break; case SQL_C_TYPE_TIMESTAMP: ival = SQL_CODE_TIMESTAMP; break; default: ival = 0; break; } break; case SQL_DESC_CONCISE_TYPE: rettype = SQL_IS_SMALLINT; ival = opts->parameters[para_idx].CType; break; case SQL_DESC_DATA_PTR: rettype = SQL_IS_POINTER; ptr = opts->parameters[para_idx].buffer; break; case SQL_DESC_INDICATOR_PTR: rettype = SQL_IS_POINTER; ptr = opts->parameters[para_idx].indicator; break; case SQL_DESC_OCTET_LENGTH: ival = opts->parameters[para_idx].buflen; break; case SQL_DESC_OCTET_LENGTH_PTR: rettype = SQL_IS_POINTER; ptr = opts->parameters[para_idx].used; break; case SQL_DESC_COUNT: ret = SQL_IS_SMALLINT; ival = opts->allocated; break; case SQL_DESC_ALLOC_TYPE: /* read-only */ rettype = SQL_IS_SMALLINT; if (desc->embedded) ival = SQL_DESC_ALLOC_AUTO; else ival = SQL_DESC_ALLOC_USER; break; case SQL_DESC_NUM_PREC_RADIX: ival = 10; break; case SQL_DESC_PRECISION: rettype = SQL_IS_SMALLINT; ival = opts->parameters[para_idx].precision; break; case SQL_DESC_SCALE: rettype = SQL_IS_SMALLINT; ival = opts->parameters[para_idx].scale; break; case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_LENGTH: default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifer"); } switch (rettype) { case SQL_IS_LEN: len = sizeof(SQLLEN); *((SQLLEN *) Value) = ival; break; case 0: case SQL_IS_INTEGER: len = sizeof(SQLINTEGER); *((SQLINTEGER *) Value) = (SQLINTEGER) ival; break; case SQL_IS_SMALLINT: len = sizeof(SQLSMALLINT); *((SQLSMALLINT *) Value) = (SQLSMALLINT) ival; break; case SQL_IS_POINTER: len = sizeof(SQLPOINTER); *((void **) Value) = ptr; break; } if (StringLength) *StringLength = len; return ret; } static RETCODE SQL_API IRDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret = SQL_SUCCESS; SQLLEN ival = 0; SQLINTEGER len = 0, rettype = 0; PTR ptr = NULL; BOOL bCallColAtt = FALSE; const IRDFields *opts = (IRDFields *) (desc + 1); switch (FieldIdentifier) { case SQL_DESC_ARRAY_STATUS_PTR: rettype = SQL_IS_POINTER; ptr = opts->rowStatusArray; break; case SQL_DESC_ROWS_PROCESSED_PTR: rettype = SQL_IS_POINTER; ptr = opts->rowsFetched; break; case SQL_DESC_ALLOC_TYPE: /* read-only */ rettype = SQL_IS_SMALLINT; ival = SQL_DESC_ALLOC_AUTO; break; case SQL_DESC_COUNT: /* read-only */ case SQL_DESC_AUTO_UNIQUE_VALUE: /* read-only */ case SQL_DESC_CASE_SENSITIVE: /* read-only */ case SQL_DESC_CONCISE_TYPE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_CODE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_PRECISION: /* read-only */ case SQL_DESC_DISPLAY_SIZE: /* read-only */ case SQL_DESC_FIXED_PREC_SCALE: /* read-only */ case SQL_DESC_LENGTH: /* read-only */ case SQL_DESC_NULLABLE: /* read-only */ case SQL_DESC_NUM_PREC_RADIX: /* read-only */ case SQL_DESC_OCTET_LENGTH: /* read-only */ case SQL_DESC_PRECISION: /* read-only */ #if (ODBCVER >= 0x0350) case SQL_DESC_ROWVER: /* read-only */ #endif /* ODBCVER */ case SQL_DESC_SCALE: /* read-only */ case SQL_DESC_SEARCHABLE: /* read-only */ case SQL_DESC_TYPE: /* read-only */ case SQL_DESC_UNNAMED: /* read-only */ case SQL_DESC_UNSIGNED: /* read-only */ case SQL_DESC_UPDATABLE: /* read-only */ bCallColAtt = TRUE; break; case SQL_DESC_BASE_COLUMN_NAME: /* read-only */ case SQL_DESC_BASE_TABLE_NAME: /* read-only */ case SQL_DESC_CATALOG_NAME: /* read-only */ case SQL_DESC_LABEL: /* read-only */ case SQL_DESC_LITERAL_PREFIX: /* read-only */ case SQL_DESC_LITERAL_SUFFIX: /* read-only */ case SQL_DESC_LOCAL_TYPE_NAME: /* read-only */ case SQL_DESC_NAME: /* read-only */ case SQL_DESC_SCHEMA_NAME: /* read-only */ case SQL_DESC_TABLE_NAME: /* read-only */ case SQL_DESC_TYPE_NAME: /* read-only */ rettype = SQL_NTS; bCallColAtt = TRUE; break; default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } if (bCallColAtt) { SQLSMALLINT pcbL; StatementClass *stmt; stmt = opts->stmt; ret = PGAPI_ColAttributes(stmt, RecNumber, FieldIdentifier, Value, (SQLSMALLINT) BufferLength, &pcbL, &ival); len = pcbL; } switch (rettype) { case 0: case SQL_IS_INTEGER: len = sizeof(SQLINTEGER); *((SQLINTEGER *) Value) = (SQLINTEGER) ival; break; case SQL_IS_UINTEGER: len = sizeof(SQLUINTEGER); *((SQLUINTEGER *) Value) = (SQLUINTEGER) ival; break; case SQL_IS_SMALLINT: len = sizeof(SQLSMALLINT); *((SQLSMALLINT *) Value) = (SQLSMALLINT) ival; break; case SQL_IS_POINTER: len = sizeof(SQLPOINTER); *((void **) Value) = ptr; break; case SQL_NTS: break; } if (StringLength) *StringLength = len; return ret; } static RETCODE SQL_API IPDGetField(DescriptorClass *desc, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret = SQL_SUCCESS; SQLINTEGER ival = 0, len = 0, rettype = 0; PTR ptr = NULL; const IPDFields *ipdopts = (const IPDFields *) (desc + 1); SQLSMALLINT para_idx; switch (FieldIdentifier) { case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_COUNT: break; default:if (RecNumber <= 0 || RecNumber > ipdopts->allocated) { inolog("IPDGetField RecN=%d allocated=%d\n", RecNumber, ipdopts->allocated); DC_set_error(desc, DESC_BAD_PARAMETER_NUMBER_ERROR, "bad parameter number"); return SQL_ERROR; } } para_idx = RecNumber - 1; switch (FieldIdentifier) { case SQL_DESC_ARRAY_STATUS_PTR: rettype = SQL_IS_POINTER; ptr = ipdopts->param_status_ptr; break; case SQL_DESC_ROWS_PROCESSED_PTR: rettype = SQL_IS_POINTER; ptr = ipdopts->param_processed_ptr; break; case SQL_DESC_UNNAMED: rettype = SQL_IS_SMALLINT; ival = NAME_IS_NULL(ipdopts->parameters[para_idx].paramName) ? SQL_UNNAMED : SQL_NAMED; break; case SQL_DESC_TYPE: rettype = SQL_IS_SMALLINT; switch (ipdopts->parameters[para_idx].SQLType) { case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: ival = SQL_DATETIME; break; default: ival = ipdopts->parameters[para_idx].SQLType; } break; case SQL_DESC_DATETIME_INTERVAL_CODE: rettype = SQL_IS_SMALLINT; switch (ipdopts->parameters[para_idx].SQLType) { case SQL_TYPE_DATE: ival = SQL_CODE_DATE; break; case SQL_TYPE_TIME: ival = SQL_CODE_TIME; break; case SQL_TYPE_TIMESTAMP: ival = SQL_CODE_TIMESTAMP; break; default: ival = 0; } break; case SQL_DESC_CONCISE_TYPE: rettype = SQL_IS_SMALLINT; ival = ipdopts->parameters[para_idx].SQLType; break; case SQL_DESC_COUNT: rettype = SQL_IS_SMALLINT; ival = ipdopts->allocated; break; case SQL_DESC_PARAMETER_TYPE: rettype = SQL_IS_SMALLINT; ival = ipdopts->parameters[para_idx].paramType; break; case SQL_DESC_PRECISION: rettype = SQL_IS_SMALLINT; switch (ipdopts->parameters[para_idx].SQLType) { case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: case SQL_DATETIME: ival = ipdopts->parameters[para_idx].decimal_digits; break; } break; case SQL_DESC_SCALE: rettype = SQL_IS_SMALLINT; switch (ipdopts->parameters[para_idx].SQLType) { case SQL_NUMERIC: ival = ipdopts->parameters[para_idx].decimal_digits; break; } break; case SQL_DESC_ALLOC_TYPE: /* read-only */ rettype = SQL_IS_SMALLINT; ival = SQL_DESC_ALLOC_AUTO; break; case SQL_DESC_CASE_SENSITIVE: /* read-only */ case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_FIXED_PREC_SCALE: /* read-only */ case SQL_DESC_LENGTH: case SQL_DESC_LOCAL_TYPE_NAME: /* read-only */ case SQL_DESC_NAME: case SQL_DESC_NULLABLE: /* read-only */ case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: #if (ODBCVER >= 0x0350) case SQL_DESC_ROWVER: /* read-only */ #endif /* ODBCVER */ case SQL_DESC_TYPE_NAME: /* read-only */ case SQL_DESC_UNSIGNED: /* read-only */ default:ret = SQL_ERROR; DC_set_error(desc, DESC_INVALID_DESCRIPTOR_IDENTIFIER, "invalid descriptor identifier"); } switch (rettype) { case 0: case SQL_IS_INTEGER: len = sizeof(SQLINTEGER); *((SQLINTEGER *) Value) = ival; break; case SQL_IS_SMALLINT: len = sizeof(SQLSMALLINT); *((SQLSMALLINT *) Value) = (SQLSMALLINT) ival; break; case SQL_IS_POINTER: len = sizeof(SQLPOINTER); *((void **)Value) = ptr; break; } if (StringLength) *StringLength = len; return ret; } /* SQLGetStmtOption -> SQLGetStmtAttr */ RETCODE SQL_API PGAPI_GetStmtAttr(HSTMT StatementHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { CSTR func = "PGAPI_GetStmtAttr"; StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret = SQL_SUCCESS; SQLINTEGER len = 0; mylog("%s Handle=%p %d\n", func, StatementHandle, Attribute); switch (Attribute) { case SQL_ATTR_FETCH_BOOKMARK_PTR: /* 16 */ *((void **) Value) = stmt->options.bookmark_ptr; len = sizeof(SQLPOINTER); break; case SQL_ATTR_PARAM_BIND_OFFSET_PTR: /* 17 */ *((SQLULEN **) Value) = SC_get_APDF(stmt)->param_offset_ptr; len = sizeof(SQLPOINTER); break; case SQL_ATTR_PARAM_BIND_TYPE: /* 18 */ *((SQLUINTEGER *) Value) = SC_get_APDF(stmt)->param_bind_type; len = sizeof(SQLUINTEGER); break; case SQL_ATTR_PARAM_OPERATION_PTR: /* 19 */ *((SQLUSMALLINT **) Value) = SC_get_APDF(stmt)->param_operation_ptr; len = sizeof(SQLPOINTER); break; case SQL_ATTR_PARAM_STATUS_PTR: /* 20 */ *((SQLUSMALLINT **) Value) = SC_get_IPDF(stmt)->param_status_ptr; len = sizeof(SQLPOINTER); break; case SQL_ATTR_PARAMS_PROCESSED_PTR: /* 21 */ *((SQLULEN **) Value) = SC_get_IPDF(stmt)->param_processed_ptr; len = sizeof(SQLPOINTER); break; case SQL_ATTR_PARAMSET_SIZE: /* 22 */ *((SQLULEN *) Value) = SC_get_APDF(stmt)->paramset_size; len = sizeof(SQLUINTEGER); break; case SQL_ATTR_ROW_BIND_OFFSET_PTR: /* 23 */ *((SQLULEN **) Value) = SC_get_ARDF(stmt)->row_offset_ptr; len = 4; break; case SQL_ATTR_ROW_OPERATION_PTR: /* 24 */ *((SQLUSMALLINT **) Value) = SC_get_ARDF(stmt)->row_operation_ptr; len = 4; break; case SQL_ATTR_ROW_STATUS_PTR: /* 25 */ *((SQLUSMALLINT **) Value) = SC_get_IRDF(stmt)->rowStatusArray; len = 4; break; case SQL_ATTR_ROWS_FETCHED_PTR: /* 26 */ *((SQLULEN **) Value) = SC_get_IRDF(stmt)->rowsFetched; len = 4; break; case SQL_ATTR_ROW_ARRAY_SIZE: /* 27 */ *((SQLULEN *) Value) = SC_get_ARDF(stmt)->size_of_rowset; len = 4; break; case SQL_ATTR_APP_ROW_DESC: /* 10010 */ case SQL_ATTR_APP_PARAM_DESC: /* 10011 */ case SQL_ATTR_IMP_ROW_DESC: /* 10012 */ case SQL_ATTR_IMP_PARAM_DESC: /* 10013 */ len = 4; *((HSTMT *) Value) = descHandleFromStatementHandle(StatementHandle, Attribute); break; case SQL_ATTR_CURSOR_SCROLLABLE: /* -1 */ len = 4; if (SQL_CURSOR_FORWARD_ONLY == stmt->options.cursor_type) *((SQLUINTEGER *) Value) = SQL_NONSCROLLABLE; else *((SQLUINTEGER *) Value) = SQL_SCROLLABLE; break; case SQL_ATTR_CURSOR_SENSITIVITY: /* -2 */ len = 4; if (SQL_CONCUR_READ_ONLY == stmt->options.scroll_concurrency) *((SQLUINTEGER *) Value) = SQL_INSENSITIVE; else *((SQLUINTEGER *) Value) = SQL_UNSPECIFIED; break; case SQL_ATTR_METADATA_ID: /* 10014 */ *((SQLUINTEGER *) Value) = stmt->options.metadata_id; break; case SQL_ATTR_ENABLE_AUTO_IPD: /* 15 */ *((SQLUINTEGER *) Value) = SQL_FALSE; break; case SQL_ATTR_AUTO_IPD: /* 10001 */ /* case SQL_ATTR_ROW_BIND_TYPE: ** == SQL_BIND_TYPE(ODBC2.0) */ SC_set_error(stmt, DESC_INVALID_OPTION_IDENTIFIER, "Unsupported statement option (Get)", func); return SQL_ERROR; default: ret = PGAPI_GetStmtOption(StatementHandle, (SQLSMALLINT) Attribute, Value, &len, BufferLength); } if (ret == SQL_SUCCESS && StringLength) *StringLength = len; return ret; } /* SQLSetConnectOption -> SQLSetConnectAttr */ RETCODE SQL_API PGAPI_SetConnectAttr(HDBC ConnectionHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength) { CSTR func = "PGAPI_SetConnectAttr"; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; RETCODE ret = SQL_SUCCESS; BOOL unsupported = FALSE; int newValue; mylog("%s for %p: %d %p\n", func, ConnectionHandle, Attribute, Value); switch (Attribute) { case SQL_ATTR_METADATA_ID: conn->stmtOptions.metadata_id = CAST_UPTR(SQLUINTEGER, Value); break; #if (ODBCVER >= 0x0351) case SQL_ATTR_ANSI_APP: if (SQL_AA_FALSE != CAST_PTR(SQLINTEGER, Value)) { mylog("the application is ansi\n"); if (CC_is_in_unicode_driver(conn)) /* the driver is unicode */ CC_set_in_ansi_app(conn); /* but the app is ansi */ } else { mylog("the application is unicode\n"); } /*return SQL_ERROR;*/ return SQL_SUCCESS; #endif /* ODBCVER */ case SQL_ATTR_ENLIST_IN_DTC: #ifdef WIN32 #ifdef _HANDLE_ENLIST_IN_DTC_ mylog("SQL_ATTR_ENLIST_IN_DTC %p request received\n", Value); if (conn->connInfo.xa_opt != 0) { /* * When a new global transaction is about * to begin, isolate the existent global * transaction. */ if (NULL != Value && CC_is_in_global_trans(conn)) CALL_IsolateDtcConn(conn, TRUE); return CALL_EnlistInDtc(conn, Value, conn->connInfo.xa_opt); } #endif /* _HANDLE_ENLIST_IN_DTC_ */ #endif /* WIN32 */ unsupported = TRUE; break; case SQL_ATTR_AUTO_IPD: if (SQL_FALSE != Value) unsupported = TRUE; break; case SQL_ATTR_ASYNC_ENABLE: case SQL_ATTR_CONNECTION_DEAD: case SQL_ATTR_CONNECTION_TIMEOUT: unsupported = TRUE; break; case SQL_ATTR_PGOPT_DEBUG: newValue = CAST_UPTR(SQLCHAR, Value); if (newValue > 0 && conn->connInfo.drivers.debug <= 0) { logs_on_off(-1, 0, 0); conn->connInfo.drivers.debug = newValue; logs_on_off(1, conn->connInfo.drivers.debug, 0); mylog("debug => %d\n", conn->connInfo.drivers.debug); } else if (newValue == 0 && conn->connInfo.drivers.debug > 0) { mylog("debug => %d\n", newValue); logs_on_off(-1, conn->connInfo.drivers.debug, 0); conn->connInfo.drivers.debug = newValue; logs_on_off(1, 0, 0); } qlog("debug => %d\n", conn->connInfo.drivers.debug); break; case SQL_ATTR_PGOPT_COMMLOG: newValue = CAST_UPTR(SQLCHAR, Value); if (newValue > 0 && conn->connInfo.drivers.commlog <= 0) { logs_on_off(-1, 0, 0); conn->connInfo.drivers.commlog = newValue; logs_on_off(1, 0, conn->connInfo.drivers.commlog); qlog("commlog => %d\n", conn->connInfo.drivers.commlog); } else if (newValue == 0 && conn->connInfo.drivers.commlog > 0) { qlog("commlog => %d\n", newValue); logs_on_off(-1, 0, conn->connInfo.drivers.commlog); conn->connInfo.drivers.debug = newValue; logs_on_off(1, 0, 0); } mylog("commlog => %d\n", conn->connInfo.drivers.commlog); break; case SQL_ATTR_PGOPT_PARSE: conn->connInfo.drivers.parse = CAST_UPTR(SQLCHAR, Value); qlog("parse => %d\n", conn->connInfo.drivers.parse); mylog("parse => %d\n", conn->connInfo.drivers.parse); break; case SQL_ATTR_PGOPT_USE_DECLAREFETCH: conn->connInfo.drivers.use_declarefetch = CAST_UPTR(SQLCHAR, Value); qlog("declarefetch => %d\n", conn->connInfo.drivers.use_declarefetch); mylog("declarefetch => %d\n", conn->connInfo.drivers.use_declarefetch); break; case SQL_ATTR_PGOPT_SERVER_SIDE_PREPARE: conn->connInfo.use_server_side_prepare = CAST_UPTR(SQLCHAR, Value); qlog("server_side_prepare => %d\n", conn->connInfo.use_server_side_prepare); mylog("server_side_prepare => %d\n", conn->connInfo.use_server_side_prepare); break; case SQL_ATTR_PGOPT_FETCH: conn->connInfo.drivers.fetch_max = CAST_PTR(int, Value); qlog("fetch => %d\n", conn->connInfo.drivers.fetch_max); mylog("fetch => %d\n", conn->connInfo.drivers.fetch_max); break; default: ret = PGAPI_SetConnectOption(ConnectionHandle, (SQLUSMALLINT) Attribute, (SQLLEN) Value); } if (unsupported) { char msg[64]; snprintf(msg, sizeof(msg), "Couldn't set unsupported connect attribute " FORMAT_INTEGER, Attribute); CC_set_error(conn, CONN_OPTION_NOT_FOR_THE_DRIVER, msg, func); return SQL_ERROR; } return ret; } /* new function */ RETCODE SQL_API PGAPI_GetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { CSTR func = "PGAPI_GetDescField"; RETCODE ret = SQL_SUCCESS; DescriptorClass *desc = (DescriptorClass *) DescriptorHandle; mylog("%s h=%p rec=%d field=%d blen=%d\n", func, DescriptorHandle, RecNumber, FieldIdentifier, BufferLength); switch (desc->desc_type) { case SQL_ATTR_APP_ROW_DESC: ret = ARDGetField(desc, RecNumber, FieldIdentifier, Value, BufferLength, StringLength); break; case SQL_ATTR_APP_PARAM_DESC: ret = APDGetField(desc, RecNumber, FieldIdentifier, Value, BufferLength, StringLength); break; case SQL_ATTR_IMP_ROW_DESC: ret = IRDGetField(desc, RecNumber, FieldIdentifier, Value, BufferLength, StringLength); break; case SQL_ATTR_IMP_PARAM_DESC: ret = IPDGetField(desc, RecNumber, FieldIdentifier, Value, BufferLength, StringLength); break; default:ret = SQL_ERROR; DC_set_error(desc, DESC_INTERNAL_ERROR, "Error not implemented"); } if (ret == SQL_ERROR) { if (!DC_get_errormsg(desc)) { switch (DC_get_errornumber(desc)) { case DESC_INVALID_DESCRIPTOR_IDENTIFIER: DC_set_errormsg(desc, "can't SQLGetDescField for this descriptor identifier"); break; case DESC_INVALID_COLUMN_NUMBER_ERROR: DC_set_errormsg(desc, "can't SQLGetDescField for this column number"); break; case DESC_BAD_PARAMETER_NUMBER_ERROR: DC_set_errormsg(desc, "can't SQLGetDescField for this parameter number"); break; } } DC_log_error(func, "", desc); } return ret; } /* new function */ RETCODE SQL_API PGAPI_SetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { CSTR func = "PGAPI_SetDescField"; RETCODE ret = SQL_SUCCESS; DescriptorClass *desc = (DescriptorClass *) DescriptorHandle; mylog("%s h=%p(%d) rec=%d field=%d val=%p,%d\n", func, DescriptorHandle, desc->desc_type, RecNumber, FieldIdentifier, Value, BufferLength); switch (desc->desc_type) { case SQL_ATTR_APP_ROW_DESC: ret = ARDSetField(desc, RecNumber, FieldIdentifier, Value, BufferLength); break; case SQL_ATTR_APP_PARAM_DESC: ret = APDSetField(desc, RecNumber, FieldIdentifier, Value, BufferLength); break; case SQL_ATTR_IMP_ROW_DESC: ret = IRDSetField(desc, RecNumber, FieldIdentifier, Value, BufferLength); break; case SQL_ATTR_IMP_PARAM_DESC: ret = IPDSetField(desc, RecNumber, FieldIdentifier, Value, BufferLength); break; default:ret = SQL_ERROR; DC_set_error(desc, DESC_INTERNAL_ERROR, "Error not implemented"); } if (ret == SQL_ERROR) { if (!DC_get_errormsg(desc)) { switch (DC_get_errornumber(desc)) { case DESC_INVALID_DESCRIPTOR_IDENTIFIER: DC_set_errormsg(desc, "can't SQLSetDescField for this descriptor identifier"); case DESC_INVALID_COLUMN_NUMBER_ERROR: DC_set_errormsg(desc, "can't SQLSetDescField for this column number"); break; case DESC_BAD_PARAMETER_NUMBER_ERROR: DC_set_errormsg(desc, "can't SQLSetDescField for this parameter number"); break; break; } } DC_log_error(func, "", desc); } return ret; } /* SQLSet(Param/Scroll/Stmt)Option -> SQLSetStmtAttr */ RETCODE SQL_API PGAPI_SetStmtAttr(HSTMT StatementHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength) { RETCODE ret = SQL_SUCCESS; CSTR func = "PGAPI_SetStmtAttr"; StatementClass *stmt = (StatementClass *) StatementHandle; mylog("%s Handle=%p %d,%u(%p)\n", func, StatementHandle, Attribute, Value, Value); switch (Attribute) { case SQL_ATTR_ENABLE_AUTO_IPD: /* 15 */ if (SQL_FALSE == Value) break; case SQL_ATTR_CURSOR_SCROLLABLE: /* -1 */ case SQL_ATTR_CURSOR_SENSITIVITY: /* -2 */ case SQL_ATTR_AUTO_IPD: /* 10001 */ SC_set_error(stmt, DESC_OPTION_NOT_FOR_THE_DRIVER, "Unsupported statement option (Set)", func); return SQL_ERROR; /* case SQL_ATTR_ROW_BIND_TYPE: ** == SQL_BIND_TYPE(ODBC2.0) */ case SQL_ATTR_IMP_ROW_DESC: /* 10012 (read-only) */ case SQL_ATTR_IMP_PARAM_DESC: /* 10013 (read-only) */ /* * case SQL_ATTR_PREDICATE_PTR: case * SQL_ATTR_PREDICATE_OCTET_LENGTH_PTR: */ SC_set_error(stmt, DESC_INVALID_OPTION_IDENTIFIER, "Unsupported statement option (Set)", func); return SQL_ERROR; case SQL_ATTR_METADATA_ID: /* 10014 */ stmt->options.metadata_id = CAST_UPTR(SQLUINTEGER, Value); break; case SQL_ATTR_APP_ROW_DESC: /* 10010 */ if (SQL_NULL_HDESC == Value) { stmt->ard = &(stmt->ardi); } else { stmt->ard = (ARDClass *) Value; inolog("set ard=%p\n", stmt->ard); } break; case SQL_ATTR_APP_PARAM_DESC: /* 10011 */ if (SQL_NULL_HDESC == Value) { stmt->apd = &(stmt->apdi); } else { stmt->apd = (APDClass *) Value; } break; case SQL_ATTR_FETCH_BOOKMARK_PTR: /* 16 */ stmt->options.bookmark_ptr = Value; break; case SQL_ATTR_PARAM_BIND_OFFSET_PTR: /* 17 */ SC_get_APDF(stmt)->param_offset_ptr = (SQLULEN *) Value; break; case SQL_ATTR_PARAM_BIND_TYPE: /* 18 */ SC_get_APDF(stmt)->param_bind_type = CAST_UPTR(SQLUINTEGER, Value); break; case SQL_ATTR_PARAM_OPERATION_PTR: /* 19 */ SC_get_APDF(stmt)->param_operation_ptr = Value; break; case SQL_ATTR_PARAM_STATUS_PTR: /* 20 */ SC_get_IPDF(stmt)->param_status_ptr = (SQLUSMALLINT *) Value; break; case SQL_ATTR_PARAMS_PROCESSED_PTR: /* 21 */ SC_get_IPDF(stmt)->param_processed_ptr = (SQLULEN *) Value; break; case SQL_ATTR_PARAMSET_SIZE: /* 22 */ SC_get_APDF(stmt)->paramset_size = CAST_UPTR(SQLULEN, Value); break; case SQL_ATTR_ROW_BIND_OFFSET_PTR: /* 23 */ SC_get_ARDF(stmt)->row_offset_ptr = (SQLULEN *) Value; break; case SQL_ATTR_ROW_OPERATION_PTR: /* 24 */ SC_get_ARDF(stmt)->row_operation_ptr = Value; break; case SQL_ATTR_ROW_STATUS_PTR: /* 25 */ SC_get_IRDF(stmt)->rowStatusArray = (SQLUSMALLINT *) Value; break; case SQL_ATTR_ROWS_FETCHED_PTR: /* 26 */ SC_get_IRDF(stmt)->rowsFetched = (SQLULEN *) Value; break; case SQL_ATTR_ROW_ARRAY_SIZE: /* 27 */ SC_get_ARDF(stmt)->size_of_rowset = CAST_UPTR(SQLULEN, Value); break; default: return PGAPI_SetStmtOption(StatementHandle, (SQLUSMALLINT) Attribute, (SQLULEN) Value); } return ret; } #define CALC_BOOKMARK_ADDR(book, offset, bind_size, index) \ (book->buffer + offset + \ (bind_size > 0 ? bind_size : (SQL_C_VARBOOKMARK == book->returntype ? book->buflen : sizeof(UInt4))) * index) /* SQL_NEED_DATA callback for PGAPI_BulkOperations */ typedef struct { StatementClass *stmt; SQLSMALLINT operation; char need_data_callback; char auto_commit_needed; ARDFields *opts; int idx, processed; } bop_cdata; static RETCODE bulk_ope_callback(RETCODE retcode, void *para) { RETCODE ret = retcode; bop_cdata *s = (bop_cdata *) para; SQLULEN offset, global_idx; SQLUINTEGER bind_size; ConnectionClass *conn; QResultClass *res; IRDFields *irdflds; BindInfoClass *bookmark; if (s->need_data_callback) { mylog("bulk_ope_callback in\n"); s->processed++; s->idx++; } else { s->idx = s->processed = 0; } s->need_data_callback = FALSE; bookmark = s->opts->bookmark; offset = s->opts->row_offset_ptr ? *(s->opts->row_offset_ptr) : 0; bind_size = s->opts->bind_size; for (; SQL_ERROR != ret && s->idx < s->opts->size_of_rowset; s->idx++) { if (SQL_ADD != s->operation) { memcpy(&global_idx, CALC_BOOKMARK_ADDR(bookmark, offset, bind_size, s->idx), sizeof(UInt4)); global_idx = SC_resolve_bookmark(global_idx); } /* Note opts->row_operation_ptr is ignored */ switch (s->operation) { case SQL_ADD: ret = SC_pos_add(s->stmt, (UWORD) s->idx); break; case SQL_UPDATE_BY_BOOKMARK: ret = SC_pos_update(s->stmt, (UWORD) s->idx, global_idx); break; case SQL_DELETE_BY_BOOKMARK: ret = SC_pos_delete(s->stmt, (UWORD) s->idx, global_idx); break; case SQL_FETCH_BY_BOOKMARK: ret = SC_pos_refresh(s->stmt, (UWORD) s->idx, global_idx); break; } if (SQL_NEED_DATA == ret) { bop_cdata *cbdata = (bop_cdata *) malloc(sizeof(bop_cdata)); memcpy(cbdata, s, sizeof(bop_cdata)); cbdata->need_data_callback = TRUE; if (0 == enqueueNeedDataCallback(s->stmt, bulk_ope_callback, cbdata)) ret = SQL_ERROR; return ret; } s->processed++; } conn = SC_get_conn(s->stmt); if (s->auto_commit_needed) CC_set_autocommit(conn, TRUE); irdflds = SC_get_IRDF(s->stmt); if (irdflds->rowsFetched) *(irdflds->rowsFetched) = s->processed; if (res = SC_get_Curres(s->stmt), res) res->recent_processed_row_count = s->stmt->diag_row_count = s->processed; return ret; } RETCODE SQL_API PGAPI_BulkOperations(HSTMT hstmt, SQLSMALLINT operationX) { CSTR func = "PGAPI_BulkOperations"; bop_cdata s; RETCODE ret; ConnectionClass *conn; BindInfoClass *bookmark; mylog("%s operation = %d\n", func, operationX); s.stmt = (StatementClass *) hstmt; s.operation = operationX; SC_clear_error(s.stmt); s.opts = SC_get_ARDF(s.stmt); s.auto_commit_needed = FALSE; if (SQL_FETCH_BY_BOOKMARK != s.operation) { conn = SC_get_conn(s.stmt); if (s.auto_commit_needed = (char) CC_does_autocommit(conn), s.auto_commit_needed) CC_set_autocommit(conn, FALSE); } if (SQL_ADD != s.operation) { if (!(bookmark = s.opts->bookmark) || !(bookmark->buffer)) { SC_set_error(s.stmt, DESC_INVALID_OPTION_IDENTIFIER, "bookmark isn't specified", func); return SQL_ERROR; } } /* StartRollbackState(s.stmt); */ s.need_data_callback = FALSE; ret = bulk_ope_callback(SQL_SUCCESS, &s); if (s.stmt->internal) ret = DiscardStatementSvp(s.stmt, ret, FALSE); return ret; } #endif /* ODBCVER >= 0x0300 */ psqlodbc-09.03.0300/info30.c000644 001752 000000 00000025266 12335653444 015455 0ustar00saitowheel000000 000000 /*------- * Module: info30.c * * Description: This module contains routines related to ODBC 3.0 * SQLGetInfo(). * */ #include "psqlodbc.h" #include "misc.h" #if (ODBCVER >= 0x0300) #include "connection.h" #include "pgapifunc.h" RETCODE SQL_API PGAPI_GetInfo30(HDBC hdbc, SQLUSMALLINT fInfoType, PTR rgbInfoValue, SQLSMALLINT cbInfoValueMax, SQLSMALLINT FAR * pcbInfoValue) { CSTR func = "PGAPI_GetInfo30"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci = &(conn->connInfo); const char *p = NULL; ssize_t len = 0; SQLLEN value = 0; RETCODE result; switch (fInfoType) { case SQL_DYNAMIC_CURSOR_ATTRIBUTES1: len = 4; value = 0; break; case SQL_DYNAMIC_CURSOR_ATTRIBUTES2: len = 4; value = 0; break; case SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1: len = 4; value = SQL_CA1_NEXT; /* others aren't allowed in ODBC spec */ break; case SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2: len = 4; value = SQL_CA2_READ_ONLY_CONCURRENCY; if (!ci->drivers.use_declarefetch || ci->drivers.lie) value |= SQL_CA2_CRC_EXACT; break; case SQL_KEYSET_CURSOR_ATTRIBUTES1: len = 4; value = SQL_CA1_NEXT | SQL_CA1_ABSOLUTE | SQL_CA1_RELATIVE | SQL_CA1_BOOKMARK | SQL_CA1_LOCK_NO_CHANGE | SQL_CA1_POS_POSITION | SQL_CA1_POS_REFRESH; if (0 != (ci->updatable_cursors & ALLOW_KEYSET_DRIVEN_CURSORS)) value |= (SQL_CA1_POS_UPDATE | SQL_CA1_POS_DELETE | SQL_CA1_BULK_ADD | SQL_CA1_BULK_UPDATE_BY_BOOKMARK | SQL_CA1_BULK_DELETE_BY_BOOKMARK | SQL_CA1_BULK_FETCH_BY_BOOKMARK ); if (ci->drivers.lie) value |= (SQL_CA1_LOCK_EXCLUSIVE | SQL_CA1_LOCK_UNLOCK | SQL_CA1_POSITIONED_UPDATE | SQL_CA1_POSITIONED_DELETE | SQL_CA1_SELECT_FOR_UPDATE ); break; case SQL_KEYSET_CURSOR_ATTRIBUTES2: len = 4; value = SQL_CA2_READ_ONLY_CONCURRENCY; if (0 != (ci->updatable_cursors & ALLOW_KEYSET_DRIVEN_CURSORS)) value |= (SQL_CA2_OPT_ROWVER_CONCURRENCY /*| SQL_CA2_CRC_APPROXIMATE*/ ); if (0 != (ci->updatable_cursors & SENSE_SELF_OPERATIONS)) value |= (SQL_CA2_SENSITIVITY_DELETIONS | SQL_CA2_SENSITIVITY_UPDATES | SQL_CA2_SENSITIVITY_ADDITIONS ); if (!ci->drivers.use_declarefetch || ci->drivers.lie) value |= SQL_CA2_CRC_EXACT; if (ci->drivers.lie) value |= (SQL_CA2_LOCK_CONCURRENCY | SQL_CA2_OPT_VALUES_CONCURRENCY | SQL_CA2_MAX_ROWS_SELECT | SQL_CA2_MAX_ROWS_INSERT | SQL_CA2_MAX_ROWS_DELETE | SQL_CA2_MAX_ROWS_UPDATE | SQL_CA2_MAX_ROWS_CATALOG | SQL_CA2_MAX_ROWS_AFFECTS_ALL | SQL_CA2_SIMULATE_NON_UNIQUE | SQL_CA2_SIMULATE_TRY_UNIQUE | SQL_CA2_SIMULATE_UNIQUE ); break; case SQL_STATIC_CURSOR_ATTRIBUTES1: len = 4; value = SQL_CA1_NEXT | SQL_CA1_ABSOLUTE | SQL_CA1_RELATIVE | SQL_CA1_BOOKMARK | SQL_CA1_LOCK_NO_CHANGE | SQL_CA1_POS_POSITION | SQL_CA1_POS_REFRESH; if (0 != (ci->updatable_cursors & ALLOW_STATIC_CURSORS)) value |= (SQL_CA1_POS_UPDATE | SQL_CA1_POS_DELETE ); if (0 != (ci->updatable_cursors & ALLOW_BULK_OPERATIONS)) value |= (SQL_CA1_BULK_ADD | SQL_CA1_BULK_UPDATE_BY_BOOKMARK | SQL_CA1_BULK_DELETE_BY_BOOKMARK | SQL_CA1_BULK_FETCH_BY_BOOKMARK ); break; case SQL_STATIC_CURSOR_ATTRIBUTES2: len = 4; value = SQL_CA2_READ_ONLY_CONCURRENCY; if (0 != (ci->updatable_cursors & ALLOW_STATIC_CURSORS)) value |= (SQL_CA2_OPT_ROWVER_CONCURRENCY ); if (0 != (ci->updatable_cursors & SENSE_SELF_OPERATIONS)) value |= (SQL_CA2_SENSITIVITY_DELETIONS | SQL_CA2_SENSITIVITY_UPDATES | SQL_CA2_SENSITIVITY_ADDITIONS ); if (!ci->drivers.use_declarefetch || ci->drivers.lie) value |= (SQL_CA2_CRC_EXACT ); break; case SQL_ODBC_INTERFACE_CONFORMANCE: len = 4; value = SQL_OIC_CORE; if (ci->drivers.lie) value = SQL_OIC_LEVEL2; break; case SQL_ACTIVE_ENVIRONMENTS: len = 2; value = 0; break; case SQL_AGGREGATE_FUNCTIONS: len = 4; value = SQL_AF_ALL; break; case SQL_ALTER_DOMAIN: len = 4; value = 0; break; case SQL_ASYNC_MODE: len = 4; value = SQL_AM_NONE; break; case SQL_BATCH_ROW_COUNT: len = 4; value = SQL_BRC_EXPLICIT; break; case SQL_BATCH_SUPPORT: len = 4; value = SQL_BS_SELECT_EXPLICIT | SQL_BS_ROW_COUNT_EXPLICIT; break; case SQL_CATALOG_NAME: len = 0; if (CurrCat(conn)) p = "Y"; else p = "N"; break; case SQL_COLLATION_SEQ: len = 0; p = ""; break; case SQL_CREATE_ASSERTION: len = 4; value = 0; break; case SQL_CREATE_CHARACTER_SET: len = 4; value = 0; break; case SQL_CREATE_COLLATION: len = 4; value = 0; break; case SQL_CREATE_DOMAIN: len = 4; value = 0; break; case SQL_CREATE_SCHEMA: len = 4; if (conn->schema_support) value = SQL_CS_CREATE_SCHEMA | SQL_CS_AUTHORIZATION; else value = 0; break; case SQL_CREATE_TABLE: len = 4; value = SQL_CT_CREATE_TABLE | SQL_CT_COLUMN_CONSTRAINT | SQL_CT_COLUMN_DEFAULT; if (PG_VERSION_GE(conn, 6.5)) value |= SQL_CT_GLOBAL_TEMPORARY; if (PG_VERSION_GE(conn, 7.0)) value |= SQL_CT_TABLE_CONSTRAINT | SQL_CT_CONSTRAINT_NAME_DEFINITION | SQL_CT_CONSTRAINT_INITIALLY_DEFERRED | SQL_CT_CONSTRAINT_INITIALLY_IMMEDIATE | SQL_CT_CONSTRAINT_DEFERRABLE; break; case SQL_CREATE_TRANSLATION: len = 4; value = 0; break; case SQL_CREATE_VIEW: len = 4; value = SQL_CV_CREATE_VIEW; break; case SQL_DDL_INDEX: len = 4; value = SQL_DI_CREATE_INDEX | SQL_DI_DROP_INDEX; break; case SQL_DESCRIBE_PARAMETER: len = 0; p = "N"; break; case SQL_DROP_ASSERTION: len = 4; value = 0; break; case SQL_DROP_CHARACTER_SET: len = 4; value = 0; break; case SQL_DROP_COLLATION: len = 4; value = 0; break; case SQL_DROP_DOMAIN: len = 4; value = 0; break; case SQL_DROP_SCHEMA: len = 4; if (conn->schema_support) value = SQL_DS_DROP_SCHEMA | SQL_DS_RESTRICT | SQL_DS_CASCADE; else value = 0; break; case SQL_DROP_TABLE: len = 4; value = SQL_DT_DROP_TABLE; if (PG_VERSION_GT(conn, 7.2)) /* hopefully */ value |= (SQL_DT_RESTRICT | SQL_DT_CASCADE); break; case SQL_DROP_TRANSLATION: len = 4; value = 0; break; case SQL_DROP_VIEW: len = 4; value = SQL_DV_DROP_VIEW; if (PG_VERSION_GT(conn, 7.2)) /* hopefully */ value |= (SQL_DV_RESTRICT | SQL_DV_CASCADE); break; case SQL_INDEX_KEYWORDS: len = 4; value = SQL_IK_NONE; case SQL_INFO_SCHEMA_VIEWS: len = 4; value = 0; break; case SQL_INSERT_STATEMENT: len = 4; value = SQL_IS_INSERT_LITERALS | SQL_IS_INSERT_SEARCHED | SQL_IS_SELECT_INTO; break; case SQL_MAX_IDENTIFIER_LEN: len = 2; value = 32; if (PG_VERSION_GT(conn, 7.2)) value = 64; break; case SQL_MAX_ROW_SIZE_INCLUDES_LONG: len = 0; p = "Y"; break; case SQL_PARAM_ARRAY_ROW_COUNTS: len = 4; value = SQL_PARC_BATCH; break; case SQL_PARAM_ARRAY_SELECTS: len = 4; value = SQL_PAS_BATCH; break; case SQL_SQL_CONFORMANCE: len = 4; value = SQL_SC_SQL92_ENTRY; break; case SQL_SQL92_DATETIME_FUNCTIONS: len = 4; value = SQL_SDF_CURRENT_DATE | SQL_SDF_CURRENT_TIME | SQL_SDF_CURRENT_TIMESTAMP; break; case SQL_SQL92_FOREIGN_KEY_DELETE_RULE: len = 4; value = SQL_SFKD_CASCADE | SQL_SFKD_NO_ACTION | SQL_SFKD_SET_DEFAULT | SQL_SFKD_SET_NULL; break; case SQL_SQL92_FOREIGN_KEY_UPDATE_RULE: len = 4; value = SQL_SFKU_CASCADE | SQL_SFKU_NO_ACTION | SQL_SFKU_SET_DEFAULT | SQL_SFKU_SET_NULL; break; case SQL_SQL92_GRANT: len = 4; value = SQL_SG_DELETE_TABLE | SQL_SG_INSERT_TABLE | SQL_SG_REFERENCES_TABLE | SQL_SG_SELECT_TABLE | SQL_SG_UPDATE_TABLE; break; case SQL_SQL92_NUMERIC_VALUE_FUNCTIONS: len = 4; value = SQL_SNVF_BIT_LENGTH | SQL_SNVF_CHAR_LENGTH | SQL_SNVF_CHARACTER_LENGTH | SQL_SNVF_EXTRACT | SQL_SNVF_OCTET_LENGTH | SQL_SNVF_POSITION; break; case SQL_SQL92_PREDICATES: len = 4; value = SQL_SP_BETWEEN | SQL_SP_COMPARISON | SQL_SP_EXISTS | SQL_SP_IN | SQL_SP_ISNOTNULL | SQL_SP_ISNULL | SQL_SP_LIKE | SQL_SP_OVERLAPS | SQL_SP_QUANTIFIED_COMPARISON; break; case SQL_SQL92_RELATIONAL_JOIN_OPERATORS: len = 4; if (PG_VERSION_GE(conn, 7.1)) value = SQL_SRJO_CROSS_JOIN | SQL_SRJO_EXCEPT_JOIN | SQL_SRJO_FULL_OUTER_JOIN | SQL_SRJO_INNER_JOIN | SQL_SRJO_INTERSECT_JOIN | SQL_SRJO_LEFT_OUTER_JOIN | SQL_SRJO_NATURAL_JOIN | SQL_SRJO_RIGHT_OUTER_JOIN | SQL_SRJO_UNION_JOIN; break; case SQL_SQL92_REVOKE: len = 4; value = SQL_SR_DELETE_TABLE | SQL_SR_INSERT_TABLE | SQL_SR_REFERENCES_TABLE | SQL_SR_SELECT_TABLE | SQL_SR_UPDATE_TABLE; break; case SQL_SQL92_ROW_VALUE_CONSTRUCTOR: len = 4; value = SQL_SRVC_VALUE_EXPRESSION | SQL_SRVC_NULL; break; case SQL_SQL92_STRING_FUNCTIONS: len = 4; value = SQL_SSF_CONVERT | SQL_SSF_LOWER | SQL_SSF_UPPER | SQL_SSF_SUBSTRING | SQL_SSF_TRANSLATE | SQL_SSF_TRIM_BOTH | SQL_SSF_TRIM_LEADING | SQL_SSF_TRIM_TRAILING; break; case SQL_SQL92_VALUE_EXPRESSIONS: len = 4; value = SQL_SVE_CASE | SQL_SVE_CAST | SQL_SVE_COALESCE | SQL_SVE_NULLIF; break; #ifdef SQL_DTC_TRANSACTION_COST case SQL_DTC_TRANSACTION_COST: #else case 1750: #endif len = 4; break; /* The followings aren't implemented yet */ case SQL_DATETIME_LITERALS: len = 4; case SQL_DM_VER: len = 0; case SQL_DRIVER_HDESC: len = 4; case SQL_MAX_ASYNC_CONCURRENT_STATEMENTS: len = 4; case SQL_STANDARD_CLI_CONFORMANCE: len = 4; case SQL_XOPEN_CLI_YEAR: len = 0; default: /* unrecognized key */ CC_set_error(conn, CONN_NOT_IMPLEMENTED_ERROR, "Unrecognized key passed to SQLGetInfo30.", func); return SQL_ERROR; } result = SQL_SUCCESS; mylog("%s: p='%s', len=%d, value=%d, cbMax=%d\n", func, p ? p : "", len, value, cbInfoValueMax); if (p) { /* char/binary data */ len = strlen(p); if (rgbInfoValue) { #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(conn)) { len = utf8_to_ucs2(p, len, (SQLWCHAR *) rgbInfoValue, cbInfoValueMax / WCLEN); len *= WCLEN; } else #endif /* UNICODE_SUPPORT */ strncpy_null((char *) rgbInfoValue, p, (size_t) cbInfoValueMax); if (len >= cbInfoValueMax) { result = SQL_SUCCESS_WITH_INFO; CC_set_error(conn, CONN_TRUNCATED, "The buffer was too small for tthe InfoValue.", func); } } #ifdef UNICODE_SUPPORT else if (CC_is_in_unicode_driver(conn)) len *= WCLEN; #endif /* UNICODE_SUPPORT */ } else { /* numeric data */ if (rgbInfoValue) { if (len == 2) *((WORD *) rgbInfoValue) = (WORD) value; else if (len == 4) *((DWORD *) rgbInfoValue) = (DWORD) value; } } if (pcbInfoValue) *pcbInfoValue = (SQLSMALLINT) len; return result; } #endif /* ODBCVER >= 0x0300 */ psqlodbc-09.03.0300/mylog.c000644 001752 000000 00000021763 12335653444 015504 0ustar00saitowheel000000 000000 /*------- * Module: mylog.c * * Description: This module contains miscellaneous routines * such as for debugging/logging and string functions. * * Classes: n/a * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ #define _MYLOG_FUNCS_IMPLEMENT_ #include "psqlodbc.h" #include "dlg_specific.h" #include #include #include #include #include #ifndef WIN32 #include #include #include #include #define GENERAL_ERRNO (errno) #define GENERAL_ERRNO_SET(e) (errno = e) #else #define GENERAL_ERRNO (GetLastError()) #define GENERAL_ERRNO_SET(e) SetLastError(e) #include /* Byron: is this where Windows keeps def. * of getpid ? */ #endif #ifdef WIN32 #define DIRSEPARATOR "\\" #define PG_BINARY O_BINARY #define PG_BINARY_R "rb" #define PG_BINARY_W "wb" #define PG_BINARY_A "ab" #else #define DIRSEPARATOR "/" #define PG_BINARY 0 #define PG_BINARY_R "r" #define PG_BINARY_W "w" #define PG_BINARY_A "a" #endif /* WIN32 */ extern GLOBAL_VALUES globals; static char *logdir = NULL; void generate_filename(const char *dirname, const char *prefix, char *filename) { #ifdef WIN32 int pid; pid = _getpid(); #else pid_t pid; struct passwd *ptr; ptr = getpwuid(getuid()); pid = getpid(); #endif if (dirname == 0 || filename == 0) return; strcpy(filename, dirname); strcat(filename, DIRSEPARATOR); if (prefix != 0) strcat(filename, prefix); #ifndef WIN32 if (ptr) strcat(filename, ptr->pw_name); #endif sprintf(filename, "%s%u%s", filename, pid, ".log"); return; } static void generate_homefile(const char *prefix, char *filename) { char dir[PATH_MAX]; #ifdef WIN32 const char *ptr; dir[0] = '\0'; if (ptr=getenv("HOMEDRIVE"), NULL != ptr) strcat(dir, ptr); if (ptr=getenv("HOMEPATH"), NULL != ptr) strcat(dir, ptr); #else strcpy(dir, "~"); #endif /* WIN32 */ generate_filename(dir, prefix, filename); return; } #if defined(WIN_MULTITHREAD_SUPPORT) static CRITICAL_SECTION qlog_cs, mylog_cs; #elif defined(POSIX_MULTITHREAD_SUPPORT) static pthread_mutex_t qlog_cs, mylog_cs; #endif /* WIN_MULTITHREAD_SUPPORT */ static int force_log = 0; static int mylog_on = 0, qlog_on = 0; #if defined(WIN_MULTITHREAD_SUPPORT) #define INIT_QLOG_CS InitializeCriticalSection(&qlog_cs) #define ENTER_QLOG_CS EnterCriticalSection(&qlog_cs) #define LEAVE_QLOG_CS LeaveCriticalSection(&qlog_cs) #define DELETE_QLOG_CS DeleteCriticalSection(&qlog_cs) #define INIT_MYLOG_CS InitializeCriticalSection(&mylog_cs) #define ENTER_MYLOG_CS EnterCriticalSection(&mylog_cs) #define LEAVE_MYLOG_CS LeaveCriticalSection(&mylog_cs) #define DELETE_MYLOG_CS DeleteCriticalSection(&mylog_cs) #elif defined(POSIX_MULTITHREAD_SUPPORT) #define INIT_QLOG_CS pthread_mutex_init(&qlog_cs,0) #define ENTER_QLOG_CS pthread_mutex_lock(&qlog_cs) #define LEAVE_QLOG_CS pthread_mutex_unlock(&qlog_cs) #define DELETE_QLOG_CS pthread_mutex_destroy(&qlog_cs) #define INIT_MYLOG_CS pthread_mutex_init(&mylog_cs,0) #define ENTER_MYLOG_CS pthread_mutex_lock(&mylog_cs) #define LEAVE_MYLOG_CS pthread_mutex_unlock(&mylog_cs) #define DELETE_MYLOG_CS pthread_mutex_destroy(&mylog_cs) #else #define INIT_QLOG_CS #define ENTER_QLOG_CS #define LEAVE_QLOG_CS #define DELETE_QLOG_CS #define INIT_MYLOG_CS #define ENTER_MYLOG_CS #define LEAVE_MYLOG_CS #define DELETE_MYLOG_CS #endif /* WIN_MULTITHREAD_SUPPORT */ #ifdef MY_LOG #define MYLOGFILE "mylog_" #ifndef WIN32 #define MYLOGDIR "/tmp" #else #define MYLOGDIR "c:" #endif /* WIN32 */ #endif /* MY_LOG */ #ifdef Q_LOG #define QLOGFILE "psqlodbc_" #ifndef WIN32 #define QLOGDIR "/tmp" #else #define QLOGDIR "c:" #endif /* WIN32 */ #endif /* QLOG */ int get_mylog(void) { return mylog_on; } int get_qlog(void) { return qlog_on; } void logs_on_off(int cnopen, int mylog_onoff, int qlog_onoff) { static int mylog_on_count = 0, mylog_off_count = 0, qlog_on_count = 0, qlog_off_count = 0; ENTER_MYLOG_CS; ENTER_QLOG_CS; if (mylog_onoff) mylog_on_count += cnopen; else mylog_off_count += cnopen; if (mylog_on_count > 0) { if (mylog_onoff > mylog_on) mylog_on = mylog_onoff; else if (mylog_on < 1) mylog_on = 1; } else if (mylog_off_count > 0) mylog_on = 0; else if (globals.debug > 0) mylog_on = globals.debug; else mylog_on = force_log; if (qlog_onoff) qlog_on_count += cnopen; else qlog_off_count += cnopen; if (qlog_on_count > 0) qlog_on = 1; else if (qlog_off_count > 0) qlog_on = 0; else if (globals.commlog > 0) qlog_on = globals.commlog; else qlog_on = force_log; LEAVE_QLOG_CS; LEAVE_MYLOG_CS; } #ifdef WIN32 #define LOGGING_PROCESS_TIME #endif /* WIN32 */ #ifdef LOGGING_PROCESS_TIME #include static DWORD start_time = 0; #endif /* LOGGING_PROCESS_TIME */ #ifdef MY_LOG static FILE *MLOGFP = NULL; DLL_DECLARE void mylog(const char *fmt,...) { va_list args; char filebuf[80]; int gerrno; if (!mylog_on) return; gerrno = GENERAL_ERRNO; ENTER_MYLOG_CS; #ifdef LOGGING_PROCESS_TIME if (!start_time) start_time = timeGetTime(); #endif /* LOGGING_PROCESS_TIME */ va_start(args, fmt); if (!MLOGFP) { generate_filename(logdir ? logdir : MYLOGDIR, MYLOGFILE, filebuf); MLOGFP = fopen(filebuf, PG_BINARY_A); if (!MLOGFP) { generate_homefile(MYLOGFILE, filebuf); MLOGFP = fopen(filebuf, PG_BINARY_A); if (!MLOGFP) { generate_filename("C:\\podbclog", MYLOGFILE, filebuf); MLOGFP = fopen(filebuf, PG_BINARY_A); } } if (MLOGFP) setbuf(MLOGFP, NULL); else mylog_on = 0; } if (MLOGFP) { #ifdef WIN_MULTITHREAD_SUPPORT #ifdef LOGGING_PROCESS_TIME DWORD proc_time = timeGetTime() - start_time; fprintf(MLOGFP, "[%u-%d.%03d]", GetCurrentThreadId(), proc_time / 1000, proc_time % 1000); #else fprintf(MLOGFP, "[%u]", GetCurrentThreadId()); #endif /* LOGGING_PROCESS_TIME */ #endif /* WIN_MULTITHREAD_SUPPORT */ #if defined(POSIX_MULTITHREAD_SUPPORT) fprintf(MLOGFP, "[%lu]", pthread_self()); #endif /* POSIX_MULTITHREAD_SUPPORT */ vfprintf(MLOGFP, fmt, args); } va_end(args); LEAVE_MYLOG_CS; GENERAL_ERRNO_SET(gerrno); } DLL_DECLARE void forcelog(const char *fmt,...) { static BOOL force_on = TRUE; va_list args; char filebuf[80]; int gerrno = GENERAL_ERRNO; if (!force_on) return; ENTER_MYLOG_CS; va_start(args, fmt); if (!MLOGFP) { generate_filename(logdir ? logdir : MYLOGDIR, MYLOGFILE, filebuf); MLOGFP = fopen(filebuf, PG_BINARY_A); if (MLOGFP) setbuf(MLOGFP, NULL); if (!MLOGFP) { generate_homefile(MYLOGFILE, filebuf); MLOGFP = fopen(filebuf, PG_BINARY_A); } if (!MLOGFP) { generate_filename("C:\\podbclog", MYLOGFILE, filebuf); MLOGFP = fopen(filebuf, PG_BINARY_A); } if (MLOGFP) setbuf(MLOGFP, NULL); else force_on = FALSE; } if (MLOGFP) { #ifdef WIN_MULTITHREAD_SUPPORT #ifdef WIN32 time_t ntime; char ctim[128]; time(&ntime); strcpy(ctim, ctime(&ntime)); ctim[strlen(ctim) - 1] = '\0'; fprintf(MLOGFP, "[%d.%d(%s)]", GetCurrentProcessId(), GetCurrentThreadId(), ctim); #endif /* WIN32 */ #endif /* WIN_MULTITHREAD_SUPPORT */ #if defined(POSIX_MULTITHREAD_SUPPORT) fprintf(MLOGFP, "[%lu]", pthread_self()); #endif /* POSIX_MULTITHREAD_SUPPORT */ vfprintf(MLOGFP, fmt, args); } va_end(args); LEAVE_MYLOG_CS; GENERAL_ERRNO_SET(gerrno); } static void mylog_initialize(void) { INIT_MYLOG_CS; mylog_on = force_log; } static void mylog_finalize(void) { mylog_on = 0; if (MLOGFP) { fclose(MLOGFP); MLOGFP = NULL; } DELETE_MYLOG_CS; } #else static void mylog_initialize(void) {} static void mylog_finalize(void) {} #endif /* MY_LOG */ #ifdef Q_LOG static FILE *QLOGFP = NULL; void qlog(char *fmt,...) { va_list args; char filebuf[80]; int gerrno; if (!qlog_on) return; gerrno = GENERAL_ERRNO; ENTER_QLOG_CS; #ifdef LOGGING_PROCESS_TIME if (!start_time) start_time = timeGetTime(); #endif /* LOGGING_PROCESS_TIME */ va_start(args, fmt); if (!QLOGFP) { generate_filename(logdir ? logdir : QLOGDIR, QLOGFILE, filebuf); QLOGFP = fopen(filebuf, PG_BINARY_A); if (!QLOGFP) { generate_homefile(QLOGFILE, filebuf); QLOGFP = fopen(filebuf, PG_BINARY_A); } if (QLOGFP) setbuf(QLOGFP, NULL); else qlog_on = 0; } if (QLOGFP) { #ifdef LOGGING_PROCESS_TIME DWORD proc_time = timeGetTime() - start_time; fprintf(QLOGFP, "[%d.%03d]", proc_time / 1000, proc_time % 1000); #endif /* LOGGING_PROCESS_TIME */ vfprintf(QLOGFP, fmt, args); } va_end(args); LEAVE_QLOG_CS; GENERAL_ERRNO_SET(gerrno); } static void qlog_initialize(void) { INIT_QLOG_CS; qlog_on = force_log; } static void qlog_finalize(void) { qlog_on = 0; if (QLOGFP) { fclose(QLOGFP); QLOGFP = NULL; } DELETE_QLOG_CS; } #else static void qlog_initialize(void) {} static void qlog_finalize(void) {} #endif /* Q_LOG */ void InitializeLogging(void) { char dir[PATH_MAX]; getLogDir(dir, sizeof(dir)); if (dir[0]) logdir = strdup(dir); mylog_initialize(); qlog_initialize(); } void FinalizeLogging(void) { mylog_finalize(); qlog_finalize(); if (logdir) { free(logdir); logdir = NULL; } } psqlodbc-09.03.0300/bind.h000644 001752 000000 00000007162 12335653444 015273 0ustar00saitowheel000000 000000 /* File: bind.h * * Description: See "bind.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __BIND_H__ #define __BIND_H__ #include "psqlodbc.h" #include "descriptor.h" /* * BindInfoClass -- stores information about a bound column */ struct BindInfoClass_ { SQLLEN buflen; /* size of buffer */ char *buffer; /* pointer to the buffer */ SQLLEN *used; /* used space in the buffer (for strings * not counting the '\0') */ SQLLEN *indicator; /* indicator == used in many cases ? */ SQLSMALLINT returntype; /* kind of conversion to be applied when * returning (SQL_C_DEFAULT, * SQL_C_CHAR... etc) */ SQLSMALLINT precision; /* the precision for numeric or timestamp type */ SQLSMALLINT scale; /* the scale for numeric type */ /* area for work variables */ char dummy_data; /* currently not used */ }; typedef struct { char *ttlbuf; /* to save the large result */ SQLLEN ttlbuflen; /* the buffer length */ SQLLEN ttlbufused; /* used length of the buffer */ SQLLEN data_left; /* amount of data left to read * (SQLGetData) */ } GetDataClass; /* * ParameterInfoClass -- stores information about a bound parameter */ struct ParameterInfoClass_ { SQLLEN buflen; char *buffer; SQLLEN *used; SQLLEN *indicator; /* indicator == used in many cases ? */ SQLSMALLINT CType; SQLSMALLINT precision; /* the precision for numeric or timestamp type */ SQLSMALLINT scale; /* the scale for numeric type */ /* area for work variables */ char data_at_exec; }; typedef struct { SQLLEN *EXEC_used; /* amount of data */ char *EXEC_buffer; /* the data */ OID lobj_oid; } PutDataClass; /* * ParameterImplClass -- stores implementation information about a parameter */ struct ParameterImplClass_ { pgNAME paramName; /* this is unavailable even in 8.1 */ SQLSMALLINT paramType; SQLSMALLINT SQLType; OID PGType; SQLULEN column_size; SQLSMALLINT decimal_digits; SQLSMALLINT precision; /* the precision for numeric or timestamp type */ SQLSMALLINT scale; /* the scale for numeric type */ }; typedef struct { GetDataClass fdata; SQLSMALLINT allocated; GetDataClass *gdata; } GetDataInfo; typedef struct { SQLSMALLINT allocated; PutDataClass *pdata; } PutDataInfo; /* Macros to handle pgtype of parameters */ #define PIC_get_pgtype(pari) ((pari).PGType) #define PIC_set_pgtype(pari, type) ((pari).PGType = (type)) #define PIC_dsp_pgtype(conn, pari) ((pari).PGType ? (pari).PGType : sqltype_to_pgtype(conn, (pari).SQLType)) void extend_column_bindings(ARDFields *opts, int num_columns); void reset_a_column_binding(ARDFields *opts, int icol); void extend_parameter_bindings(APDFields *opts, int num_params); void extend_iparameter_bindings(IPDFields *opts, int num_params); void reset_a_parameter_binding(APDFields *opts, int ipar); void reset_a_iparameter_binding(IPDFields *opts, int ipar); int CountParameters(const StatementClass *stmt, Int2 *inCount, Int2 *ioCount, Int2 *outputCount); void GetDataInfoInitialize(GetDataInfo *gdata); void extend_getdata_info(GetDataInfo *gdata, int num_columns, BOOL shrink); void reset_a_getdata_info(GetDataInfo *gdata, int icol); void GDATA_unbind_cols(GetDataInfo *gdata, BOOL freeall); void PutDataInfoInitialize(PutDataInfo *pdata); void extend_putdata_info(PutDataInfo *pdata, int num_params, BOOL shrink); void reset_a_putdata_info(PutDataInfo *pdata, int ipar); void PDATA_free_params(PutDataInfo *pdata, char option); void SC_param_next(const StatementClass*, int *param_number, ParameterInfoClass **, ParameterImplClass **); RETCODE prepareParameters(StatementClass *stmt); int decideHowToPrepare(StatementClass *stmt, BOOL force); #endif psqlodbc-09.03.0300/catfunc.h000644 001752 000000 00000006556 12335653444 016010 0ustar00saitowheel000000 000000 /* File: catfunc.h * * Description: See "info.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __CATFUNC_H__ #define __CATFUNC_H__ #include "psqlodbc.h" /* SQLTables field position */ enum { TABLES_CATALOG_NAME = 0 ,TABLES_SCHEMA_NAME ,TABLES_TABLE_NAME ,TABLES_TABLE_TYPE ,TABLES_REMARKS ,NUM_OF_TABLES_FIELDS }; /* SQLColumns field position */ enum { COLUMNS_CATALOG_NAME = 0 ,COLUMNS_SCHEMA_NAME ,COLUMNS_TABLE_NAME ,COLUMNS_COLUMN_NAME ,COLUMNS_DATA_TYPE ,COLUMNS_TYPE_NAME ,COLUMNS_PRECISION ,COLUMNS_LENGTH ,COLUMNS_SCALE ,COLUMNS_RADIX ,COLUMNS_NULLABLE ,COLUMNS_REMARKS ,COLUMNS_COLUMN_DEF /* ODBC 3.0 but always use it */ #if (ODBCVER >= 0x0300) ,COLUMNS_SQL_DATA_TYPE ,COLUMNS_SQL_DATETIME_SUB ,COLUMNS_CHAR_OCTET_LENGTH ,COLUMNS_ORDINAL_POSITION ,COLUMNS_IS_NULLABLE #endif /* ODBCVER */ ,COLUMNS_DISPLAY_SIZE ,COLUMNS_FIELD_TYPE ,COLUMNS_AUTO_INCREMENT ,COLUMNS_PHYSICAL_NUMBER ,COLUMNS_TABLE_OID ,COLUMNS_BASE_TYPEID ,COLUMNS_ATTTYPMOD ,NUM_OF_COLUMNS_FIELDS }; /* SQLPrimaryKeys field position */ enum { PKS_TABLE_CAT = 0 ,PKS_TABLE_SCHEM ,PKS_TABLE_NAME ,PKS_COLUMN_NAME ,PKS_KEY_SQ ,PKS_PK_NAME ,NUM_OF_PKS_FIELDS }; /* SQLForeignKeys field position */ enum { FKS_PKTABLE_CAT = 0 ,FKS_PKTABLE_SCHEM ,FKS_PKTABLE_NAME ,FKS_PKCOLUMN_NAME ,FKS_FKTABLE_CAT ,FKS_FKTABLE_SCHEM ,FKS_FKTABLE_NAME ,FKS_FKCOLUMN_NAME ,FKS_KEY_SEQ ,FKS_UPDATE_RULE ,FKS_DELETE_RULE ,FKS_FK_NAME ,FKS_PK_NAME #if (ODBCVER >= 0x0300) ,FKS_DEFERRABILITY #endif /* ODBCVER */ ,FKS_TRIGGER_NAME ,NUM_OF_FKS_FIELDS }; /* SQLColAttribute */ enum { COLATTR_DESC_COUNT = -1 ,COLATTR_DESC_AUTO_UNIQUE_VALUE = 0 ,COLATTR_DESC_BASE_COLUMN_NAME ,COLATTR_DESC_BASE_TABLE_NAME ,COLATTR_DESC_CASE_SENSITIVE ,COLATTR_DESC_CATALOG_NAME ,COLATTR_DESC_CONCISE_TYPE ,COLATTR_DESC_DISPLAY_SIZE ,COLATTR_DESC_FIXED_PREC_SCALE ,COLATTR_DESC_LABEL ,COLATTR_DESC_LENGTH ,COLATTR_DESC_LITERAL_PREFIX ,COLATTR_DESC_LITERAL_SUFFIX ,COLATTR_DESC_LOCAL_TYPE_NAME ,COLATTR_DESC_NAME ,COLATTR_DESC_NULLABLE ,COLATTR_DESC_NUM_PREX_RADIX ,COLATTR_DESC_OCTET_LENGTH ,COLATTR_DESC_PRECISION ,COLATTR_DESC_SCALE ,COLATTR_DESC_SCHEMA_NAME ,COLATTR_DESC_SEARCHABLE ,COLATTR_DESC_TABLE_NAME ,COLATTR_DESC_TYPE ,COLATTR_DESC_TYPE_NAME ,COLATTR_DESC_UNNAMED ,COLATTR_DESC_UNSIGNED ,COLATTR_DESC_UPDATABLE }; /* SQLStatistics field position */ enum { STATS_CATALOG_NAME = 0 ,STATS_SCHEMA_NAME ,STATS_TABLE_NAME ,STATS_NON_UNIQUE ,STATS_INDEX_QUALIFIER ,STATS_INDEX_NAME ,STATS_TYPE ,STATS_SEQ_IN_INDEX ,STATS_COLUMN_NAME ,STATS_COLLATION ,STATS_CARDINALITY ,STATS_PAGES ,STATS_FILTER_CONDITION ,NUM_OF_STATS_FIELDS }; /* SQLProcedureColumns field position */ enum { PROCOLS_PROCEDURE_CAT = 0 ,PROCOLS_PROCEDURE_SCHEM ,PROCOLS_PROCEDURE_NAME ,PROCOLS_COLUMN_NAME ,PROCOLS_COLUMN_TYPE ,PROCOLS_DATA_TYPE ,PROCOLS_TYPE_NAME ,PROCOLS_COLUMN_SIZE ,PROCOLS_BUFFER_LENGTH ,PROCOLS_DECIMAL_DIGITS ,PROCOLS_NUM_PREC_RADIX ,PROCOLS_NULLABLE ,PROCOLS_REMARKS #if (ODBCVER >= 0x0300) ,PROCOLS_COLUMN_DEF ,PROCOLS_SQL_DATA_TYPE ,PROCOLS_SQL_DATETIME_SUB ,PROCOLS_CHAR_OCTET_LENGTH ,PROCOLS_ORDINAL_POSITION ,PROCOLS_IS_NULLABLE #endif /* ODBCVER */ ,NUM_OF_PROCOLS_FIELDS }; #endif /* __CARFUNC_H__ */ psqlodbc-09.03.0300/columninfo.h000644 001752 000000 00000003327 12335653444 016527 0ustar00saitowheel000000 000000 /* File: columninfo.h * * Description: See "columninfo.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __COLUMNINFO_H__ #define __COLUMNINFO_H__ #include "psqlodbc.h" struct ColumnInfoClass_ { UInt4 refcount; /* reference count. A ColumnInfo can be shared by * several qresults. */ Int2 num_fields; struct srvr_info { char *name; /* field name */ OID adtid; /* type oid */ Int2 adtsize; /* type size */ Int4 display_size; /* the display size (longest row) */ Int4 atttypmod; /* the length of bpchar/varchar */ OID relid; /* the relation id */ Int2 attid; /* the attribute number */ } *coli_array; }; #define CI_get_num_fields(self) (self->num_fields) #define CI_get_oid(self, col) (self->coli_array[col].adtid) #define CI_get_fieldname(self, col) (self->coli_array[col].name) #define CI_get_fieldsize(self, col) (self->coli_array[col].adtsize) #define CI_get_display_size(self, col) (self->coli_array[col].display_size) #define CI_get_atttypmod(self, col) (self->coli_array[col].atttypmod) #define CI_get_relid(self, col) (self->coli_array[col].relid) #define CI_get_attid(self, col) (self->coli_array[col].attid) ColumnInfoClass *CI_Constructor(void); void CI_Destructor(ColumnInfoClass *self); void CI_free_memory(ColumnInfoClass *self); char CI_read_fields(ColumnInfoClass *self, ConnectionClass *conn); /* functions for setting up the fields from within the program, */ /* without reading from a socket */ void CI_set_num_fields(ColumnInfoClass *self, int new_num_fields, BOOL); void CI_set_field_info(ColumnInfoClass *self, int field_num, char *new_name, OID new_adtid, Int2 new_adtsize, Int4 atttypmod, OID new_relid, OID new_attid); #endif psqlodbc-09.03.0300/connection.h000644 001752 000000 00000053514 12335653444 016520 0ustar00saitowheel000000 000000 /* File: connection.h * * Description: See "connection.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __CONNECTION_H__ #define __CONNECTION_H__ #include "psqlodbc.h" #include #include #include #include "descriptor.h" #if defined (POSIX_MULTITHREAD_SUPPORT) #include #endif #ifdef __cplusplus extern "C" { #endif typedef enum { CONN_NOT_CONNECTED, /* Connection has not been established */ CONN_CONNECTED, /* Connection is up and has been established */ CONN_DOWN, /* Connection is broken */ CONN_EXECUTING /* the connection is currently executing a * statement */ } CONN_Status; enum { DISALLOW_UPDATABLE_CURSORS = 0, /* No cursors are updatable */ ALLOW_STATIC_CURSORS = 1L, /* Static cursors are updatable */ ALLOW_KEYSET_DRIVEN_CURSORS = (1L << 1), /* Keyset-driven cursors are updatable */ ALLOW_DYNAMIC_CURSORS = (1L << 2), /* Dynamic cursors are updatable */ ALLOW_BULK_OPERATIONS = (1L << 3), /* Bulk operations available */ SENSE_SELF_OPERATIONS = (1L << 4), /* Sense self update/delete/add */ }; /* These errors have general sql error state */ #define CONNECTION_SERVER_NOT_REACHED 101 #define CONNECTION_MSG_TOO_LONG 103 #define CONNECTION_COULD_NOT_SEND 104 #define CONNECTION_NO_SUCH_DATABASE 105 #define CONNECTION_BACKEND_CRAZY 106 #define CONNECTION_NO_RESPONSE 107 #define CONNECTION_SERVER_REPORTED_ERROR 108 #define CONNECTION_COULD_NOT_RECEIVE 109 #define CONNECTION_SERVER_REPORTED_WARNING 110 #define CONNECTION_NEED_PASSWORD 112 #define CONNECTION_COMMUNICATION_ERROR 113 #define CONN_TRUNCATED (-2) #define CONN_OPTION_VALUE_CHANGED (-1) /* These errors correspond to specific SQL states */ #define CONN_INIREAD_ERROR 201 #define CONN_OPENDB_ERROR 202 #define CONN_STMT_ALLOC_ERROR 203 #define CONN_IN_USE 204 #define CONN_UNSUPPORTED_OPTION 205 /* Used by SetConnectoption to indicate unsupported options */ #define CONN_INVALID_ARGUMENT_NO 206 /* SetConnectOption: corresponds to ODBC--"S1009" */ #define CONN_TRANSACT_IN_PROGRES 207 #define CONN_NO_MEMORY_ERROR 208 #define CONN_NOT_IMPLEMENTED_ERROR 209 #define CONN_INVALID_AUTHENTICATION 210 #define CONN_AUTH_TYPE_UNSUPPORTED 211 #define CONN_UNABLE_TO_LOAD_DLL 212 #define CONN_VALUE_OUT_OF_RANGE 214 #define CONN_OPTION_NOT_FOR_THE_DRIVER 216 #define CONN_EXEC_ERROR 217 /* Conn_status defines */ #define CONN_IN_AUTOCOMMIT 1L #define CONN_IN_TRANSACTION (1L<<1) #define CONN_IN_MANUAL_TRANSACTION (1L<<2) #define CONN_IN_ERROR_BEFORE_IDLE (1L<<3) /* AutoCommit functions */ #define CC_is_in_autocommit(x) (x->transact_status & CONN_IN_AUTOCOMMIT) #define CC_does_autocommit(x) (CONN_IN_AUTOCOMMIT == ((x)->transact_status & (CONN_IN_AUTOCOMMIT | CONN_IN_MANUAL_TRANSACTION))) #define CC_loves_visible_trans(x) ((0 == ((x)->transact_status & CONN_IN_AUTOCOMMIT)) || (0 != ((x)->transact_status & CONN_IN_MANUAL_TRANSACTION))) /* Transaction in/not functions */ #define CC_set_in_trans(x) (x->transact_status |= CONN_IN_TRANSACTION) #define CC_set_no_trans(x) (x->transact_status &= ~(CONN_IN_TRANSACTION | CONN_IN_ERROR_BEFORE_IDLE)) #define CC_is_in_trans(x) (0 != (x->transact_status & CONN_IN_TRANSACTION)) /* Manual transaction in/not functions */ #define CC_set_in_manual_trans(x) (x->transact_status |= CONN_IN_MANUAL_TRANSACTION) #define CC_set_no_manual_trans(x) (x->transact_status &= ~CONN_IN_MANUAL_TRANSACTION) #define CC_is_in_manual_trans(x) (0 != (x->transact_status & CONN_IN_MANUAL_TRANSACTION)) /* Error waiting for ROLLBACK */ #define CC_set_in_error_trans(x) (x->transact_status |= CONN_IN_ERROR_BEFORE_IDLE) #define CC_set_no_error_trans(x) (x->transact_status &= ~CONN_IN_ERROR_BEFORE_IDLE) #define CC_is_in_error_trans(x) (x->transact_status & CONN_IN_ERROR_BEFORE_IDLE) #define CC_get_errornumber(x) (x->__error_number) #define CC_get_errormsg(x) (x->__error_message) #define CC_set_errornumber(x, n) (x->__error_number = n) /* Unicode handling */ #define CONN_UNICODE_DRIVER (1L) #define CONN_ANSI_APP (1L << 1) #define CONN_DISALLOW_WCHAR (1L << 2) #define CC_set_in_unicode_driver(x) (x->unicode |= CONN_UNICODE_DRIVER) #define CC_set_in_ansi_app(x) (x->unicode |= CONN_ANSI_APP) #define CC_is_in_unicode_driver(x) (0 != (x->unicode & CONN_UNICODE_DRIVER)) #define CC_is_in_ansi_app(x) (0 != (x->unicode & CONN_ANSI_APP)) #define CC_is_in_global_trans(x) (NULL != (x)->asdum) #define ALLOW_WCHAR(x) (0 != (x->unicode & CONN_UNICODE_DRIVER) && 0 == (x->unicode & CONN_DISALLOW_WCHAR)) #define CC_MALLOC_return_with_error(t, tp, s, x, m, ret) \ do { \ if (t = malloc(s), NULL == t) \ { \ CC_set_error(x, CONN_NO_MEMORY_ERROR, m, ""); \ return ret; \ } \ } while (0) #define CC_REALLOC_return_with_error(t, tp, s, x, m, ret) \ do { \ tp *tmp; \ if (tmp = (tp *) realloc(t, s), NULL == tmp) \ { \ CC_set_error(x, CONN_NO_MEMORY_ERROR, m, ""); \ return ret; \ } \ t = tmp; \ } while (0) /* For Multi-thread */ #if defined(WIN_MULTITHREAD_SUPPORT) #define INIT_CONN_CS(x) InitializeCriticalSection(&((x)->cs)) #define INIT_CONNLOCK(x) InitializeCriticalSection(&((x)->slock)) #define ENTER_CONN_CS(x) EnterCriticalSection(&((x)->cs)) #define CONNLOCK_ACQUIRE(x) EnterCriticalSection(&((x)->slock)) #define TRY_ENTER_CONN_CS(x) TryEnterCriticalSection(&((x)->cs)) #define ENTER_INNER_CONN_CS(x, entered) \ do { \ EnterCriticalSection(&((x)->cs)); \ entered++; \ } while (0) #define LEAVE_CONN_CS(x) LeaveCriticalSection(&((x)->cs)) #define CONNLOCK_RELEASE(x) LeaveCriticalSection(&((x)->slock)) #define DELETE_CONN_CS(x) DeleteCriticalSection(&((x)->cs)) #define DELETE_CONNLOCK(x) DeleteCriticalSection(&((x)->slock)) #elif defined(POSIX_THREADMUTEX_SUPPORT) #define INIT_CONN_CS(x) pthread_mutex_init(&((x)->cs), getMutexAttr()) #define INIT_CONNLOCK(x) pthread_mutex_init(&((x)->slock), getMutexAttr()) #define ENTER_CONN_CS(x) pthread_mutex_lock(&((x)->cs)) #define CONNLOCK_ACQUIRE(x) pthread_mutex_lock(&((x)->slock)) #define TRY_ENTER_CONN_CS(x) (0 == pthread_mutex_trylock(&((x)->cs))) #define ENTER_INNER_CONN_CS(x, entered) \ do { \ if (getMutexAttr()) \ { \ if (pthread_mutex_lock(&((x)->cs)) == 0) \ entered++; \ } \ } while (0) #define LEAVE_CONN_CS(x) pthread_mutex_unlock(&((x)->cs)) #define CONNLOCK_RELEASE(x) pthread_mutex_unlock(&((x)->slock)) #define DELETE_CONN_CS(x) pthread_mutex_destroy(&((x)->cs)) #define DELETE_CONNLOCK(x) pthread_mutex_destroy(&((x)->slock)) #else #define INIT_CONN_CS(x) #define INIT_CONNLOCK(x) #define TRY_ENTER_CONN_CS(x) (1) #define ENTER_CONN_CS(x) #define CONNLOCK_ACQUIRE(x) #define ENTER_INNER_CONN_CS(x, entered) #define LEAVE_CONN_CS(x) #define CONNLOCK_RELEASE(x) #define DELETE_CONN_CS(x) #define DELETE_CONNLOCK(x) #endif /* WIN_MULTITHREAD_SUPPORT */ #define LEAVE_INNER_CONN_CS(entered, conn) \ do { \ if (entered > 0) \ { \ LEAVE_CONN_CS(conn); \ entered--; \ } \ } while (0) #define CLEANUP_FUNC_CONN_CS(entered, conn) \ do { \ while (entered > 0) \ { \ LEAVE_CONN_CS(conn); \ entered--; \ } \ } while (0) /* Authentication types */ #define AUTH_REQ_OK 0 #define AUTH_REQ_KRB4 1 #define AUTH_REQ_KRB5 2 #define AUTH_REQ_PASSWORD 3 #define AUTH_REQ_CRYPT 4 #define AUTH_REQ_MD5 5 #define AUTH_REQ_SCM_CREDS 6 #define AUTH_REQ_GSS 7 #define AUTH_REQ_GSS_CONT 8 #define AUTH_REQ_SSPI 9 /* Startup Packet sizes */ #define SM_DATABASE 64 #define SM_USER 32 #define SM_OPTIONS 64 #define SM_UNUSED 64 #define SM_TTY 64 /* Old 6.2 protocol defines */ #define NO_AUTHENTICATION 7 #define PATH_SIZE 64 #define ARGV_SIZE 64 #define USRNAMEDATALEN 16 typedef unsigned int ProtocolVersion; #define PG_PROTOCOL(major, minor) (((major) << 16) | (minor)) #define PG_PROTOCOL_LATEST PG_PROTOCOL(3, 0) #define PG_PROTOCOL_74 PG_PROTOCOL(3, 0) #define PG_PROTOCOL_64 PG_PROTOCOL(2, 0) #define PG_PROTOCOL_63 PG_PROTOCOL(1, 0) #define PG_PROTOCOL_62 PG_PROTOCOL(0, 0) #define PG_NEGOTIATE_SSLMODE PG_PROTOCOL(1234, 5679) /* This startup packet is to support latest Postgres protocol (6.4, 6.3) */ typedef struct _StartupPacket { ProtocolVersion protoVersion; char database[SM_DATABASE]; char user[SM_USER]; char options[SM_OPTIONS]; char unused[SM_UNUSED]; char tty[SM_TTY]; } StartupPacket; /* This startup packet is to support pre-Postgres 6.3 protocol */ typedef struct _StartupPacket6_2 { unsigned int authtype; char database[PATH_SIZE]; char user[USRNAMEDATALEN]; char options[ARGV_SIZE]; char execfile[ARGV_SIZE]; char tty[PATH_SIZE]; } StartupPacket6_2; /* Transferred from pqcomm.h: */ typedef ProtocolVersion MsgType; #define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678) typedef struct CancelRequestPacket { /* Note that each field is stored in network byte order! */ MsgType cancelRequestCode; /* code to identify a cancel request */ unsigned int backendPID; /* PID of client's backend */ unsigned int cancelAuthCode; /* secret key to authorize cancel */ } CancelRequestPacket; /* Structure to hold all the connection attributes for a specific connection (used for both registry and file, DSN and DRIVER) */ typedef struct { char dsn[MEDIUM_REGISTRY_LEN]; char desc[MEDIUM_REGISTRY_LEN]; char drivername[MEDIUM_REGISTRY_LEN]; char server[MEDIUM_REGISTRY_LEN]; char database[MEDIUM_REGISTRY_LEN]; char username[MEDIUM_REGISTRY_LEN]; pgNAME password; char protocol[SMALL_REGISTRY_LEN]; char port[SMALL_REGISTRY_LEN]; char sslmode[16]; char onlyread[SMALL_REGISTRY_LEN]; char fake_oid_index[SMALL_REGISTRY_LEN]; char show_oid_column[SMALL_REGISTRY_LEN]; char row_versioning[SMALL_REGISTRY_LEN]; char show_system_tables[SMALL_REGISTRY_LEN]; char translation_dll[MEDIUM_REGISTRY_LEN]; char translation_option[SMALL_REGISTRY_LEN]; char focus_password; pgNAME conn_settings; signed char disallow_premature; signed char allow_keyset; signed char updatable_cursors; signed char lf_conversion; signed char true_is_minus1; signed char int8_as; signed char bytea_as_longvarbinary; signed char use_server_side_prepare; signed char lower_case_identifier; signed char rollback_on_error; signed char force_abbrev_connstr; signed char bde_environment; signed char fake_mss; signed char cvt_null_date_string; signed char autocommit_public; signed char accessible_only; signed char ignore_round_trip_time; signed char disable_keepalive; signed char gssauth_use_gssapi; UInt4 extra_opts; #ifdef _HANDLE_ENLIST_IN_DTC_ signed char xa_opt; #endif /* _HANDLE_ENLIST_IN_DTC_ */ GLOBAL_VALUES drivers; /* moved from driver's option */ } ConnInfo; /* Macro to determine is the connection using 6.2 protocol? */ #define PROTOCOL_62(conninfo_) (strncmp((conninfo_)->protocol, PG62, strlen(PG62)) == 0) /* Macro to determine is the connection using 6.3 protocol? */ #define PROTOCOL_63(conninfo_) (strncmp((conninfo_)->protocol, PG63, strlen(PG63)) == 0) /* Macro to determine is the connection using 6.4 protocol? */ #define PROTOCOL_64(conninfo_) (strncmp((conninfo_)->protocol, PG64, strlen(PG64)) == 0) /* Macro to determine is the connection using 7.4 protocol? */ #define PROTOCOL_74(conninfo_) (strncmp((conninfo_)->protocol, PG74, strlen(PG74)) == 0) /* Macro to determine is the connection using 7.4 rejected? */ #define PROTOCOL_74REJECTED(conninfo_) (strncmp((conninfo_)->protocol, PG74REJECTED, strlen(PG74REJECTED)) == 0) #define SUPPORT_DESCRIBE_PARAM(conninfo_) (PROTOCOL_74(conninfo_) && conninfo_->use_server_side_prepare) /* * Macros to compare the server's version with a specified version * 1st parameter: pointer to a ConnectionClass object * 2nd parameter: major version number * 3rd parameter: minor version number */ #define SERVER_VERSION_GT(conn, major, minor) \ ((conn)->pg_version_major > major || \ ((conn)->pg_version_major == major && (conn)->pg_version_minor > minor)) #define SERVER_VERSION_GE(conn, major, minor) \ ((conn)->pg_version_major > major || \ ((conn)->pg_version_major == major && (conn)->pg_version_minor >= minor)) #define SERVER_VERSION_EQ(conn, major, minor) \ ((conn)->pg_version_major == major && (conn)->pg_version_minor == minor) #define SERVER_VERSION_LE(conn, major, minor) (! SERVER_VERSION_GT(conn, major, minor)) #define SERVER_VERSION_LT(conn, major, minor) (! SERVER_VERSION_GE(conn, major, minor)) /*#if ! defined(HAVE_CONFIG_H) || defined(HAVE_STRINGIZE)*/ #define STRING_AFTER_DOT(string) (strchr(#string, '.') + 1) /*#else #define STRING_AFTER_DOT(str) (strchr("str", '.') + 1) #endif*/ /* * Simplified macros to compare the server's version with a * specified version * Note: Never pass a variable as the second parameter. * It must be a decimal constant of the form %d.%d . */ #define PG_VERSION_GT(conn, ver) \ (SERVER_VERSION_GT(conn, (int) ver, atoi(STRING_AFTER_DOT(ver)))) #define PG_VERSION_GE(conn, ver) \ (SERVER_VERSION_GE(conn, (int) ver, atoi(STRING_AFTER_DOT(ver)))) #define PG_VERSION_EQ(conn, ver) \ (SERVER_VERSION_EQ(conn, (int) ver, atoi(STRING_AFTER_DOT(ver)))) #define PG_VERSION_LE(conn, ver) (! PG_VERSION_GT(conn, ver)) #define PG_VERSION_LT(conn, ver) (! PG_VERSION_GE(conn, ver)) /* This is used to store cached table information in the connection */ struct col_info { Int2 num_reserved_cols; Int2 refcnt; QResultClass *result; pgNAME schema_name; pgNAME table_name; OID table_oid; time_t acc_time; }; #define free_col_info_contents(coli) \ { \ if (NULL != coli->result) \ QR_Destructor(coli->result); \ coli->result = NULL; \ NULL_THE_NAME(coli->schema_name); \ NULL_THE_NAME(coli->table_name); \ coli->table_oid = 0; \ coli->refcnt = 0; \ coli->acc_time = 0; \ } #define col_info_initialize(coli) (memset(coli, 0, sizeof(COL_INFO))) /* Translation DLL entry points */ #ifdef WIN32 #define DLLHANDLE HINSTANCE #else #define WINAPI CALLBACK #define DLLHANDLE void * #define HINSTANCE void * #endif typedef BOOL (FAR WINAPI * DataSourceToDriverProc) (UDWORD, SWORD, PTR, SDWORD, PTR, SDWORD, SDWORD FAR *, UCHAR FAR *, SWORD, SWORD FAR *); typedef BOOL (FAR WINAPI * DriverToDataSourceProc) (UDWORD, SWORD, PTR, SDWORD, PTR, SDWORD, SDWORD FAR *, UCHAR FAR *, SWORD, SWORD FAR *); /******* The Connection handle ************/ struct ConnectionClass_ { HENV henv; /* environment this connection was * created on */ SQLUINTEGER login_timeout; StatementOptions stmtOptions; ARDFields ardOptions; APDFields apdOptions; char *__error_message; int __error_number; char sqlstate[8]; CONN_Status status; ConnInfo connInfo; StatementClass **stmts; Int2 num_stmts; Int2 ncursors; SocketClass *sock; Int4 lobj_type; Int2 coli_allocated; Int2 ntables; COL_INFO **col_info; long translation_option; HINSTANCE translation_handle; DataSourceToDriverProc DataSourceToDriver; DriverToDataSourceProc DriverToDataSource; Int2 driver_version; /* prepared for ODBC3.0 */ char transact_status; /* Is a transaction is currently * in progress */ char errormsg_created; /* has an informative error msg * been created ? */ char pg_version[MAX_INFO_STRING]; /* Version of PostgreSQL * we're connected to - * DJP 25-1-2001 */ float pg_version_number; Int2 pg_version_major; Int2 pg_version_minor; char ms_jet; char unicode; char result_uncommitted; char schema_support; char lo_is_domain; char escape_in_literal; char *original_client_encoding; char *current_client_encoding; char *server_encoding; Int2 ccsc; Int2 mb_maxbyte_per_char; int be_pid; /* pid returned by backend */ int be_key; /* auth code needed to send cancel */ UInt4 isolation; char *current_schema; StatementClass *stmt_in_extquery; Int2 max_identifier_length; Int2 num_discardp; char **discardp; #if (ODBCVER >= 0x0300) int num_descs; DescriptorClass **descs; #endif /* ODBCVER */ pgNAME schemaIns; pgNAME tableIns; #ifdef USE_SSPI UInt4 svcs_allowed; UInt4 auth_svcs; #endif /* USE_SSPI */ #if defined(WIN_MULTITHREAD_SUPPORT) CRITICAL_SECTION cs; CRITICAL_SECTION slock; #elif defined(POSIX_THREADMUTEX_SUPPORT) pthread_mutex_t cs; pthread_mutex_t slock; #endif /* WIN_MULTITHREAD_SUPPORT */ #ifdef _HANDLE_ENLIST_IN_DTC_ UInt4 gTranInfo; void *asdum; #endif /* _HANDLE_ENLIST_IN_DTC_ */ }; /* Accessor functions */ #define CC_get_env(x) ((x)->henv) #define CC_get_socket(x) (x->sock) #define CC_get_database(x) (x->connInfo.database) #define CC_get_server(x) (x->connInfo.server) #define CC_get_DSN(x) (x->connInfo.dsn) #define CC_get_username(x) (x->connInfo.username) #define CC_is_onlyread(x) (x->connInfo.onlyread[0] == '1') #define CC_get_escape(x) (x->escape_in_literal) #define CC_fake_mss(x) (/* 0 != (x)->ms_jet && */ 0 < (x)->connInfo.fake_mss) #define CC_accessible_only(x) (0 < (x)->connInfo.accessible_only && PG_VERSION_GE((x), 7.2)) #define CC_default_is_c(x) (CC_is_in_ansi_app(x) || x->ms_jet /* not only */ || TRUE /* but for any other ? */) /* for CC_DSN_info */ #define CONN_DONT_OVERWRITE 0 #define CONN_OVERWRITE 1 #ifdef _HANDLE_ENLIST_IN_DTC_ enum { DTC_IN_PROGRESS = 1L ,DTC_ENLISTED = (1L << 1) ,DTC_REQUEST_EXECUTING = (1L << 2) ,DTC_ISOLATED = (1L << 3) ,DTC_PREPARE_REQUESTED = (1L << 4) }; #define CC_set_dtc_clear(x) ((x)->gTranInfo = 0) #define CC_set_dtc_enlisted(x) ((x)->gTranInfo |= (DTC_IN_PROGRESS | DTC_ENLISTED)) #define CC_no_dtc_enlisted(x) ((x)->gTranInfo &= (~DTC_ENLISTED)) #define CC_is_dtc_enlisted(x) (0 != ((x)->gTranInfo & DTC_ENLISTED)) #define CC_set_dtc_executing(x) ((x)->gTranInfo |= DTC_REQUEST_EXECUTING) #define CC_no_dtc_executing(x) ((x)->gTranInfo &= (~DTC_REQUEST_EXECUTING)) #define CC_is_dtc_executing(x) (0 != ((x)->gTranInfo & DTC_REQUEST_EXECUTING)) #define CC_set_dtc_prepareRequested(x) ((x)->gTranInfo |= (DTC_PREPARE_REQUESTED)) #define CC_no_dtc_prepareRequested(x) ((x)->gTranInfo &= (~DTC_PREPARE_REQUESTED)) #define CC_is_dtc_prepareRequested(x) (0 != ((x)->gTranInfo & DTC_PREPARE_REQUESTED)) #define CC_is_dtc_executing(x) (0 != ((x)->gTranInfo & DTC_REQUEST_EXECUTING)) #define CC_set_dtc_isolated(x) ((x)->gTranInfo |= DTC_ISOLATED) #define CC_is_idle_in_global_transaction(x) (0 != ((x)->gTranInfo & DTC_PREPARE_REQUESTED) || (x)->gTranInfo == DTC_IN_PROGRESS) #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* prototypes */ ConnectionClass *CC_Constructor(void); enum { /* CC_conninfo_init option */ CLEANUP_FOR_REUSE = 1L /* reuse the info */ ,COPY_GLOBALS = (1L << 1) /* copy globals to drivers */ }; void CC_conninfo_init(ConnInfo *conninfo, UInt4 option); void CC_copy_conninfo(ConnInfo *to, const ConnInfo *from); char CC_Destructor(ConnectionClass *self); int CC_cursor_count(ConnectionClass *self); char CC_cleanup(ConnectionClass *self, BOOL keepCommunication); char CC_begin(ConnectionClass *self); char CC_commit(ConnectionClass *self); char CC_abort(ConnectionClass *self); char CC_set_autocommit(ConnectionClass *self, BOOL on); int CC_set_translation(ConnectionClass *self); char CC_connect(ConnectionClass *self, char password_req, char *salt); char CC_add_statement(ConnectionClass *self, StatementClass *stmt); char CC_remove_statement(ConnectionClass *self, StatementClass *stmt) ; #if (ODBCVER >= 0x0300) char CC_add_descriptor(ConnectionClass *self, DescriptorClass *desc); char CC_remove_descriptor(ConnectionClass *self, DescriptorClass *desc); #endif /* ODBCVER */ void CC_set_error(ConnectionClass *self, int number, const char *message, const char *func); void CC_set_errormsg(ConnectionClass *self, const char *message); char CC_get_error(ConnectionClass *self, int *number, char **message); QResultClass *CC_send_query_append(ConnectionClass *self, const char *query, QueryInfo *qi, UDWORD flag, StatementClass *stmt, const char *appendq); #define CC_send_query(self, query, qi, flag, stmt) CC_send_query_append(self, query, qi, flag, stmt, NULL) void CC_clear_error(ConnectionClass *self); int CC_send_function(ConnectionClass *conn, int fnid, void *result_buf, int *actual_result_len, int result_is_int, LO_ARG *argv, int nargs); char CC_send_settings(ConnectionClass *self); /* char *CC_create_errormsg(ConnectionClass *self); void CC_lookup_lo(ConnectionClass *conn); void CC_lookup_pg_version(ConnectionClass *conn); */ void CC_initialize_pg_version(ConnectionClass *conn); void CC_log_error(const char *func, const char *desc, const ConnectionClass *self); int CC_get_max_query_len(const ConnectionClass *self); int CC_send_cancel_request(const ConnectionClass *conn); void CC_on_commit(ConnectionClass *conn); void CC_on_abort(ConnectionClass *conn, UDWORD opt); void CC_on_abort_partial(ConnectionClass *conn); void ProcessRollback(ConnectionClass *conn, BOOL undo, BOOL partial); const char *CC_get_current_schema(ConnectionClass *conn); int CC_mark_a_object_to_discard(ConnectionClass *conn, int type, const char *plan); int CC_discard_marked_objects(ConnectionClass *conn); int handle_error_message(ConnectionClass *self, char *msgbuf, size_t buflen, char *sqlstate, const char *comment, QResultClass *res); int handle_notice_message(ConnectionClass *self, char *msgbuf, size_t buflen, char *sqlstate, const char *comment, QResultClass *res); int EatReadyForQuery(ConnectionClass *self); void getParameterValues(ConnectionClass *self); int CC_get_max_idlen(ConnectionClass *self); BOOL SendSyncRequest(ConnectionClass *self); const char *CurrCat(const ConnectionClass *self); const char *CurrCatString(const ConnectionClass *self); void CC_examine_global_transaction(ConnectionClass *self); /* CC_send_query options */ enum { IGNORE_ABORT_ON_CONN = 1L /* not set the error result even when */ ,CREATE_KEYSET = (1L << 1) /* create keyset for updatable curosrs */ ,GO_INTO_TRANSACTION = (1L << 2) /* issue begin in advance */ ,ROLLBACK_ON_ERROR = (1L << 3) /* rollback the query when an error occurs */ ,END_WITH_COMMIT = (1L << 4) /* the query ends with COMMMIT command */ ,IGNORE_ROUND_TRIP = (1L << 5) /* the commincation round trip time is considered ignorable */ }; /* CC_on_abort options */ #define NO_TRANS 1L #define CONN_DEAD (1L << 1) /* connection is no longer valid */ #ifdef __cplusplus } #endif #endif /* __CONNECTION_H__ */ psqlodbc-09.03.0300/convert.h000644 001752 000000 00000003565 12335653444 016042 0ustar00saitowheel000000 000000 /* File: convert.h * * Description: See "convert.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __CONVERT_H__ #define __CONVERT_H__ #include "psqlodbc.h" #ifdef __cplusplus extern "C" { #endif /* copy_and_convert results */ #define COPY_OK 0 #define COPY_UNSUPPORTED_TYPE 1 #define COPY_UNSUPPORTED_CONVERSION 2 #define COPY_RESULT_TRUNCATED 3 #define COPY_GENERAL_ERROR 4 #define COPY_NO_DATA_FOUND 5 /* convert_escape results */ #define CONVERT_ESCAPE_OK 0 #define CONVERT_ESCAPE_OVERFLOW 1 #define CONVERT_ESCAPE_ERROR -1 typedef struct { int infinity; int m; int d; int y; int hh; int mm; int ss; int fr; } SIMPLE_TIME; int copy_and_convert_field_bindinfo(StatementClass *stmt, OID field_type, int atttypmod, void *value, int col); int copy_and_convert_field(StatementClass *stmt, OID field_type, int atttypmod, void *value, SQLSMALLINT fCType, int precision, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue, SQLLEN *pIndicator); int copy_statement_with_parameters(StatementClass *stmt, BOOL); BOOL convert_money(const char *s, char *sout, size_t soutmax); char parse_datetime(const char *buf, SIMPLE_TIME *st); size_t convert_linefeeds(const char *s, char *dst, size_t max, BOOL convlf, BOOL *changed); size_t convert_special_chars(const char *si, char *dst, SQLLEN used, UInt4 flags,int ccsc, int escape_ch); int convert_pgbinary_to_char(const char *value, char *rgbValue, ssize_t cbValueMax); size_t convert_from_pgbinary(const char *value, char *rgbValue, SQLLEN cbValueMax); SQLLEN pg_hex2bin(const char *in, char *out, SQLLEN len); int convert_lo(StatementClass *stmt, const void *value, SQLSMALLINT fCType, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue); Int4 findTag(const char *str, char dollar_quote, int ccsc); #ifdef __cplusplus } #endif #endif psqlodbc-09.03.0300/descriptor.h000644 001752 000000 00000014764 12335653444 016543 0ustar00saitowheel000000 000000 /* File: descriptor.h * * Description: This file contains defines and declarations that are related to * the entire driver. * * Comments: See "readme.txt" for copyright and license information. */ #ifndef __DESCRIPTOR_H__ #define __DESCRIPTOR_H__ #include "psqlodbc.h" enum { TI_UPDATABLE = 1L ,TI_HASOIDS_CHECKED = (1L << 1) ,TI_HASOIDS = (1L << 2) ,TI_COLATTRIBUTE = (1L << 3) }; typedef struct { OID table_oid; COL_INFO *col_info; /* cached SQLColumns info for this table */ pgNAME schema_name; pgNAME table_name; pgNAME table_alias; pgNAME bestitem; pgNAME bestqual; UInt4 flags; } TABLE_INFO; #define TI_set_updatable(ti) (ti->flags |= TI_UPDATABLE) #define TI_is_updatable(ti) (0 != (ti->flags &= TI_UPDATABLE)) #define TI_no_updatable(ti) (ti->flags &= (~TI_UPDATABLE)) #define TI_set_hasoids_checked(ti) (ti->flags |= TI_HASOIDS_CHECKED) #define TI_checked_hasoids(ti) (0 != (ti->flags &= TI_HASOIDS)) #define TI_set_hasoids(ti) (ti->flags |= TI_HASOIDS) #define TI_has_oids(ti) (0 != (ti->flags &= TI_HASOIDS)) #define TI_set_has_no_oids(ti) (ti->flags &= (~TI_HASOIDS)) void TI_Constructor(TABLE_INFO *, const ConnectionClass *); void TI_Destructor(TABLE_INFO **, int); enum { FIELD_INITIALIZED = 0 ,FIELD_PARSING = 1L ,FIELD_TEMP_SET = (1L << 1) ,FIELD_COL_ATTRIBUTE = (1L << 2) ,FIELD_PARSED_OK = (1L << 3) ,FIELD_PARSED_INCOMPLETE = (1L << 4) }; typedef struct { char flag; char updatable; Int2 attnum; pgNAME schema_name; TABLE_INFO *ti; /* to resolve explicit table names */ pgNAME column_name; pgNAME column_alias; char nullable; char auto_increment; char func; char columnkey; int column_size; /* precision in 2.x */ int decimal_digits; /* scale in 2.x */ int display_size; SQLLEN length; OID columntype; OID basetype; /* may be the basetype when the column type is a domain */ int typmod; char expr; char quote; char dquote; char numeric; pgNAME before_dot; } FIELD_INFO; Int4 FI_precision(const FIELD_INFO *); Int4 FI_scale(const FIELD_INFO *); void FI_Constructor(FIELD_INFO *, BOOL reuse); void FI_Destructor(FIELD_INFO **, int, BOOL freeFI); #define FI_is_applicable(fi) (NULL != fi && (fi->flag & (FIELD_PARSED_OK | FIELD_COL_ATTRIBUTE)) != 0) #define FI_type(fi) (0 == (fi)->basetype ? (fi)->columntype : (fi)->basetype) typedef struct DescriptorHeader_ { ConnectionClass *conn_conn; char embedded; char type_defined; UInt4 desc_type; UInt4 error_row; /* 1-based row */ UInt4 error_index; /* 1-based index */ Int4 __error_number; char *__error_message; PG_ErrorInfo *pgerror; } DescriptorClass; /* * ARD and APD are(must be) of the same format */ struct ARDFields_ { #if (ODBCVER >= 0x0300) SQLLEN size_of_rowset; /* for ODBC3 fetch operation */ #endif /* ODBCVER */ SQLUINTEGER bind_size; /* size of each structure if using * Row-wise Binding */ SQLUSMALLINT *row_operation_ptr; SQLULEN *row_offset_ptr; BindInfoClass *bookmark; BindInfoClass *bindings; SQLSMALLINT allocated; SQLLEN size_of_rowset_odbc2; /* for SQLExtendedFetch */ }; /* * APD must be of the same format as ARD */ struct APDFields_ { SQLLEN paramset_size; /* really an SQLINTEGER type */ SQLUINTEGER param_bind_type; /* size of each structure if using * Row-wise Parameter Binding */ SQLUSMALLINT *param_operation_ptr; SQLULEN *param_offset_ptr; ParameterInfoClass *bookmark; /* dummy item to fit APD to ARD */ ParameterInfoClass *parameters; SQLSMALLINT allocated; SQLLEN paramset_size_dummy; /* dummy item to fit APD to ARD */ }; struct IRDFields_ { StatementClass *stmt; SQLULEN *rowsFetched; SQLUSMALLINT *rowStatusArray; UInt4 nfields; SQLSMALLINT allocated; FIELD_INFO **fi; }; struct IPDFields_ { SQLULEN *param_processed_ptr; SQLUSMALLINT *param_status_ptr; SQLSMALLINT allocated; ParameterImplClass *parameters; }; typedef struct { DescriptorClass deschd; union { ARDFields ard; APDFields apd; IRDFields ird; IPDFields ipd; } flds; } DescriptorAlloc; typedef struct { DescriptorClass deschd; ARDFields ardopts; } ARDClass; typedef struct { DescriptorClass deschd; APDFields apdopts; } APDClass; typedef struct { DescriptorClass deschd; IRDFields irdopts; } IRDClass; typedef struct { DescriptorClass deschd; IPDFields ipdopts; } IPDClass; #define DC_get_conn(a) (a->conn_conn) void InitializeEmbeddedDescriptor(DescriptorClass *, StatementClass *stmt, UInt4 desc_type); void DC_Destructor(DescriptorClass *desc); void InitializeARDFields(ARDFields *self); void InitializeAPDFields(APDFields *self); /* void InitializeIRDFields(IRDFields *self); void InitializeIPDFiedls(IPDFields *self); */ BindInfoClass *ARD_AllocBookmark(ARDFields *self); void ARD_unbind_cols(ARDFields *self, BOOL freeall); void APD_free_params(APDFields *self, char option); void IPD_free_params(IPDFields *self, char option); BOOL getCOLIfromTI(const char *, ConnectionClass *, StatementClass *, const OID, TABLE_INFO **); #if (ODBCVER >= 0x0300) RETCODE DC_set_stmt(DescriptorClass *desc, StatementClass *stmt); void DC_clear_error(DescriptorClass *desc); void DC_set_error(DescriptorClass *desc, int errornumber, const char * errormsg); void DC_set_errormsg(DescriptorClass *desc, const char * errormsg); PG_ErrorInfo *DC_get_error(DescriptorClass *self); int DC_get_errornumber(const DescriptorClass *self); const char *DC_get_errormsg(const DescriptorClass *self); void DC_log_error(const char *func, const char *desc, const DescriptorClass *self); #endif /* ODBCVER */ /* Error numbers about descriptor handle */ enum { LOWEST_DESC_ERROR = -2 /* minus means warning/notice message */ ,DESC_ERROR_IN_ROW = -2 ,DESC_OPTION_VALUE_CHANGED = -1 ,DESC_OK = 0 ,DESC_EXEC_ERROR ,DESC_STATUS_ERROR ,DESC_SEQUENCE_ERROR ,DESC_NO_MEMORY_ERROR ,DESC_COLNUM_ERROR ,DESC_NO_STMTSTRING ,DESC_ERROR_TAKEN_FROM_BACKEND ,DESC_INTERNAL_ERROR ,DESC_STILL_EXECUTING ,DESC_NOT_IMPLEMENTED_ERROR ,DESC_BAD_PARAMETER_NUMBER_ERROR ,DESC_OPTION_OUT_OF_RANGE_ERROR ,DESC_INVALID_COLUMN_NUMBER_ERROR ,DESC_RESTRICTED_DATA_TYPE_ERROR ,DESC_INVALID_CURSOR_STATE_ERROR ,DESC_CREATE_TABLE_ERROR ,DESC_NO_CURSOR_NAME ,DESC_INVALID_CURSOR_NAME ,DESC_INVALID_ARGUMENT_NO ,DESC_ROW_OUT_OF_RANGE ,DESC_OPERATION_CANCELLED ,DESC_INVALID_CURSOR_POSITION ,DESC_VALUE_OUT_OF_RANGE ,DESC_OPERATION_INVALID ,DESC_PROGRAM_TYPE_OUT_OF_RANGE ,DESC_BAD_ERROR ,DESC_INVALID_OPTION_IDENTIFIER ,DESC_RETURN_NULL_WITHOUT_INDICATOR ,DESC_INVALID_DESCRIPTOR_IDENTIFIER ,DESC_OPTION_NOT_FOR_THE_DRIVER ,DESC_FETCH_OUT_OF_RANGE ,DESC_COUNT_FIELD_INCORRECT }; #endif /* __DESCRIPTOR_H__ */ psqlodbc-09.03.0300/dlg_specific.h000644 001752 000000 00000023313 12335653444 016766 0ustar00saitowheel000000 000000 /* File: dlg_specific.h * * Description: See "dlg_specific.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __DLG_SPECIFIC_H__ #define __DLG_SPECIFIC_H__ #include "psqlodbc.h" #include "connection.h" #ifdef WIN32 #include #include "resource.h" #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Unknown data type sizes */ #define UNKNOWNS_AS_DEFAULT -1 #define UNKNOWNS_AS_MAX 0 #define UNKNOWNS_AS_DONTKNOW 1 #define UNKNOWNS_AS_LONGEST 2 #define UNKNOWNS_AS_CATALOG 100 /* ODBC initialization files */ #ifndef WIN32 #define ODBC_INI ".odbc.ini" #define ODBCINST_INI "odbcinst.ini" #else #define ODBC_INI "ODBC.INI" #define ODBCINST_INI "ODBCINST.INI" #endif #define ODBC_DATASOURCES "ODBC Data Sources" #if (ODBCVER >= 0x0300) #ifdef UNICODE_SUPPORT #define INI_DSN "PostgreSQL35W" #else #define INI_DSN "PostgreSQL30" #endif /* UNICODE_SUPPORT */ #else #define INI_DSN DBMS_NAME #endif /* ODBCVER */ #define INI_KDESC "Description" /* Data source * description */ #define INI_SERVER "Servername" /* Name of Server * running the Postgres * service */ #define SPEC_SERVER "server" #define INI_PORT "Port" /* Port on which the * Postmaster is listening */ #define INI_DATABASE "Database" /* Database Name */ #define INI_UID "UID" /* Default User Name */ #define INI_USERNAME "Username" /* Default User Name */ #define INI_PASSWORD "Password" /* Default Password */ #define INI_ABBREVIATE "CX" #define INI_DEBUG "Debug" /* Debug flag */ #define ABBR_DEBUG "B2" #define INI_FETCH "Fetch" /* Fetch Max Count */ #define ABBR_FETCH "A7" #define INI_SOCKET "Socket" /* Socket buffer size */ #define ABBR_SOCKET "A8" #define INI_READONLY "ReadOnly" /* Database is read only */ #define ABBR_READONLY "A0" #define INI_COMMLOG "CommLog" /* Communication to * backend logging */ #define ABBR_COMMLOG "B3" #define INI_PROTOCOL "Protocol" /* What protocol (6.2) */ #define ABBR_PROTOCOL "A1" #define INI_OPTIMIZER "Optimizer" /* Use backend genetic * optimizer */ #define ABBR_OPTIMIZER "B4" #define INI_KSQO "Ksqo" /* Keyset query * optimization */ #define ABBR_KSQO "B5" #define INI_CONNSETTINGS "ConnSettings" /* Anything to send to * backend on successful * connection */ #define ABBR_CONNSETTINGS "A6" #define INI_UNIQUEINDEX "UniqueIndex" /* Recognize unique * indexes */ #define INI_UNKNOWNSIZES "UnknownSizes" /* How to handle unknown * result set sizes */ #define ABBR_UNKNOWNSIZES "A9" #define INI_CANCELASFREESTMT "CancelAsFreeStmt" #define ABBR_CANCELASFREESTMT "C1" #define INI_USEDECLAREFETCH "UseDeclareFetch" /* Use Declare/Fetch * cursors */ #define ABBR_USEDECLAREFETCH "B6" /* More ini stuff */ #define INI_TEXTASLONGVARCHAR "TextAsLongVarchar" #define ABBR_TEXTASLONGVARCHAR "B7" #define INI_UNKNOWNSASLONGVARCHAR "UnknownsAsLongVarchar" #define ABBR_UNKNOWNSASLONGVARCHAR "B8" #define INI_BOOLSASCHAR "BoolsAsChar" #define ABBR_BOOLSASCHAR "B9" #define INI_MAXVARCHARSIZE "MaxVarcharSize" #define ABBR_MAXVARCHARSIZE "B0" #define INI_MAXLONGVARCHARSIZE "MaxLongVarcharSize" #define ABBR_MAXLONGVARCHARSIZE "B1" #define INI_FAKEOIDINDEX "FakeOidIndex" #define ABBR_FAKEOIDINDEX "A2" #define INI_SHOWOIDCOLUMN "ShowOidColumn" #define ABBR_SHOWOIDCOLUMN "A3" #define INI_ROWVERSIONING "RowVersioning" #define ABBR_ROWVERSIONING "A4" #define INI_SHOWSYSTEMTABLES "ShowSystemTables" #define ABBR_SHOWSYSTEMTABLES "A5" #define INI_LIE "Lie" #define INI_PARSE "Parse" #define ABBR_PARSE "C0" #define INI_EXTRASYSTABLEPREFIXES "ExtraSysTablePrefixes" #define ABBR_EXTRASYSTABLEPREFIXES "C2" #define INI_TRANSLATIONNAME "TranslationName" #define INI_TRANSLATIONDLL "TranslationDLL" #define INI_TRANSLATIONOPTION "TranslationOption" #define INI_DISALLOWPREMATURE "DisallowPremature" #define ABBR_DISALLOWPREMATURE "C3" #define INI_UPDATABLECURSORS "UpdatableCursors" #define ABBR_UPDATABLECURSORS "C4" #define INI_LFCONVERSION "LFConversion" #define ABBR_LFCONVERSION "C5" #define INI_TRUEISMINUS1 "TrueIsMinus1" #define ABBR_TRUEISMINUS1 "C6" #define INI_INT8AS "BI" #define INI_BYTEAASLONGVARBINARY "ByteaAsLongVarBinary" #define ABBR_BYTEAASLONGVARBINARY "C7" #define INI_USESERVERSIDEPREPARE "UseServerSidePrepare" #define ABBR_USESERVERSIDEPREPARE "C8" #define INI_LOWERCASEIDENTIFIER "LowerCaseIdentifier" #define ABBR_LOWERCASEIDENTIFIER "C9" #define INI_SSLMODE "SSLmode" #define ABBR_SSLMODE "CA" #define INI_EXTRAOPTIONS "AB" #define INI_LOGDIR "Logdir" #define INI_GSSAUTHUSEGSSAPI "GssAuthUseGSS" #define ABBR_GSSAUTHUSEGSSAPI "D0" #define SSLMODE_DISABLE "disable" #define SSLMODE_ALLOW "allow" #define SSLMODE_PREFER "prefer" #define SSLMODE_REQUIRE "require" #define SSLMODE_VERIFY_CA "verify-ca" #define SSLMODE_VERIFY_FULL "verify-full" #define SSLLBYTE_DISABLE 'd' #define SSLLBYTE_ALLOW 'a' #define SSLLBYTE_PREFER 'p' #define SSLLBYTE_REQUIRE 'r' #define SSLLBYTE_VERIFY 'v' #ifdef _HANDLE_ENLIST_IN_DTC_ #define INI_XAOPT "XaOpt" const char *GetXaLibPath(void); #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* Bit representaion for abbreviated connection strings */ #define BIT_LFCONVERSION (1L) #define BIT_UPDATABLECURSORS (1L<<1) #define BIT_DISALLOWPREMATURE (1L<<2) #define BIT_UNIQUEINDEX (1L<<3) #define BIT_PROTOCOL_63 (1L<<4) #define BIT_PROTOCOL_64 (1L<<5) #define BIT_UNKNOWN_DONTKNOW (1L<<6) #define BIT_UNKNOWN_ASMAX (1L<<7) #define BIT_OPTIMIZER (1L<<8) #define BIT_KSQO (1L<<9) #define BIT_COMMLOG (1L<<10) #define BIT_DEBUG (1L<<11) #define BIT_PARSE (1L<<12) #define BIT_CANCELASFREESTMT (1L<<13) #define BIT_USEDECLAREFETCH (1L<<14) #define BIT_READONLY (1L<<15) #define BIT_TEXTASLONGVARCHAR (1L<<16) #define BIT_UNKNOWNSASLONGVARCHAR (1L<<17) #define BIT_BOOLSASCHAR (1L<<18) #define BIT_ROWVERSIONING (1L<<19) #define BIT_SHOWSYSTEMTABLES (1L<<20) #define BIT_SHOWOIDCOLUMN (1L<<21) #define BIT_FAKEOIDINDEX (1L<<22) #define BIT_TRUEISMINUS1 (1L<<23) #define BIT_BYTEAASLONGVARBINARY (1L<<24) #define BIT_USESERVERSIDEPREPARE (1L<<25) #define BIT_LOWERCASEIDENTIFIER (1L<<26) #define BIT_GSSAUTHUSEGSSAPI (1L<<27) #define EFFECTIVE_BIT_COUNT 28 /* Mask for extra options */ #define BIT_FORCEABBREVCONNSTR 1L #define BIT_FAKE_MSS (1L << 1) #define BIT_BDE_ENVIRONMENT (1L << 2) #define BIT_CVT_NULL_DATE (1L << 3) #define BIT_ACCESSIBLE_ONLY (1L << 4) #define BIT_IGNORE_ROUND_TRIP_TIME (1L << 5) #define BIT_DISABLE_KEEPALIVE (1L << 6) /* Connection Defaults */ #define DEFAULT_PORT "5432" #define DEFAULT_READONLY 0 #define DEFAULT_PROTOCOL "7.4" /* the latest protocol is * the default */ #define DEFAULT_USEDECLAREFETCH 0 #define DEFAULT_TEXTASLONGVARCHAR 1 #define DEFAULT_UNKNOWNSASLONGVARCHAR 0 #define DEFAULT_BOOLSASCHAR 1 #define DEFAULT_OPTIMIZER 0 /* enable */ #define DEFAULT_KSQO 1 /* on */ #define DEFAULT_UNIQUEINDEX 1 /* dont recognize */ #define DEFAULT_COMMLOG 0 /* dont log */ #define DEFAULT_DEBUG 0 #define DEFAULT_UNKNOWNSIZES UNKNOWNS_AS_MAX #define DEFAULT_FAKEOIDINDEX 0 #define DEFAULT_SHOWOIDCOLUMN 0 #define DEFAULT_ROWVERSIONING 0 #define DEFAULT_SHOWSYSTEMTABLES 0 /* dont show system tables */ #define DEFAULT_LIE 0 #define DEFAULT_PARSE 0 #define DEFAULT_CANCELASFREESTMT 0 #define DEFAULT_EXTRASYSTABLEPREFIXES "dd_;" #define DEFAULT_DISALLOWPREMATURE 0 #define DEFAULT_TRUEISMINUS1 0 #define DEFAULT_UPDATABLECURSORS 1 #ifdef WIN32 #define DEFAULT_LFCONVERSION 1 #else #define DEFAULT_LFCONVERSION 0 #endif /* WIN32 */ #define DEFAULT_INT8AS 0 #define DEFAULT_BYTEAASLONGVARBINARY 0 #define DEFAULT_USESERVERSIDEPREPARE 1 #define DEFAULT_LOWERCASEIDENTIFIER 0 #define DEFAULT_SSLMODE SSLMODE_DISABLE #define DEFAULT_GSSAUTHUSEGSSAPI 0 #ifdef _HANDLE_ENLIST_IN_DTC_ #define DEFAULT_XAOPT 1 #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* prototypes */ void getCommonDefaults(const char *section, const char *filename, ConnInfo *ci); #ifdef WIN32 void SetDlgStuff(HWND hdlg, const ConnInfo *ci); void GetDlgStuff(HWND hdlg, ConnInfo *ci); LRESULT CALLBACK driver_optionsProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK global_optionsProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK ds_options1Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK ds_options2Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK manage_dsnProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); #endif /* WIN32 */ void updateGlobals(void); int writeDriverCommoninfo(const char *fileName, const char *sectionName, const GLOBAL_VALUES *); void writeDSNinfo(const ConnInfo *ci); void getDSNdefaults(ConnInfo *ci); void getDSNinfo(ConnInfo *ci, char overwrite); void makeConnectString(char *connect_string, const ConnInfo *ci, UWORD); BOOL copyAttributes(ConnInfo *ci, const char *attribute, const char *value); BOOL copyCommonAttributes(ConnInfo *ci, const char *attribute, const char *value); int getDriverNameFromDSN(const char *dsn, char *driver_name, int namelen); int getLogDir(char *dir, int dirmax); int setLogDir(const char *dir); int changeDriverNameOfaDSN(const char *dsn, const char *driver_name, DWORD *errcode); UInt4 getExtraOptions(const ConnInfo *); BOOL setExtraOptions(ConnInfo *, const char *str, const char *format); char *extract_attribute_setting(const char *str, const char *attr, BOOL ref_comment); char *extract_extra_attribute_setting(const pgNAME setting, const char *attr); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __DLG_SPECIFIC_H__ */ psqlodbc-09.03.0300/environ.h000644 001752 000000 00000006653 12335653444 016043 0ustar00saitowheel000000 000000 /* * * Description: See "environ.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __ENVIRON_H__ #define __ENVIRON_H__ #ifdef __cplusplus extern "C" { #endif #include "psqlodbc.h" #if defined (POSIX_MULTITHREAD_SUPPORT) #include #endif #define ENV_ALLOC_ERROR 1 /********** Environment Handle *************/ struct EnvironmentClass_ { char *errormsg; int errornumber; Int4 flag; #if defined(WIN_MULTITHREAD_SUPPORT) CRITICAL_SECTION cs; #elif defined(POSIX_MULTITHREAD_SUPPORT) pthread_mutex_t cs; #endif /* WIN_MULTITHREAD_SUPPORT */ }; /* Environment prototypes */ EnvironmentClass *EN_Constructor(void); char EN_Destructor(EnvironmentClass *self); char EN_get_error(EnvironmentClass *self, int *number, char **message); char EN_add_connection(EnvironmentClass *self, ConnectionClass *conn); char EN_remove_connection(EnvironmentClass *self, ConnectionClass *conn); void EN_log_error(const char *func, char *desc, EnvironmentClass *self); int getConnCount(void); ConnectionClass * const *getConnList(void); #define EN_OV_ODBC2 1L #define EN_CONN_POOLING (1L<<1) #define EN_is_odbc2(env) ((env->flag & EN_OV_ODBC2) != 0) #define EN_is_odbc3(env) (env && (env->flag & EN_OV_ODBC2) == 0) #define EN_set_odbc2(env) (env->flag |= EN_OV_ODBC2) #define EN_set_odbc3(env) (env->flag &= ~EN_OV_ODBC2) #define EN_is_pooling(env) (env && (env->flag & EN_CONN_POOLING) != 0) #define EN_set_pooling(env) (env->flag |= EN_CONN_POOLING) #define EN_unset_pooling(env) (env->flag &= ~EN_CONN_POOLING) /* For Multi-thread */ #if defined( WIN_MULTITHREAD_SUPPORT) #define INIT_CONNS_CS InitializeCriticalSection(&conns_cs) #define ENTER_CONNS_CS EnterCriticalSection(&conns_cs) #define LEAVE_CONNS_CS LeaveCriticalSection(&conns_cs) #define DELETE_CONNS_CS DeleteCriticalSection(&conns_cs) #define INIT_ENV_CS(x) InitializeCriticalSection(&((x)->cs)) #define ENTER_ENV_CS(x) EnterCriticalSection(&((x)->cs)) #define LEAVE_ENV_CS(x) LeaveCriticalSection(&((x)->cs)) #define DELETE_ENV_CS(x) DeleteCriticalSection(&((x)->cs)) #define INIT_COMMON_CS InitializeCriticalSection(&common_cs) #define ENTER_COMMON_CS EnterCriticalSection(&common_cs) #define LEAVE_COMMON_CS LeaveCriticalSection(&common_cs) #define DELETE_COMMON_CS DeleteCriticalSection(&common_cs) #elif defined(POSIX_MULTITHREAD_SUPPORT) #define INIT_CONNS_CS pthread_mutex_init(&conns_cs,0) #define ENTER_CONNS_CS pthread_mutex_lock(&conns_cs) #define LEAVE_CONNS_CS pthread_mutex_unlock(&conns_cs) #define DELETE_CONNS_CS pthread_mutex_destroy(&conns_cs) #define INIT_ENV_CS(x) pthread_mutex_init(&((x)->cs),0) #define ENTER_ENV_CS(x) pthread_mutex_lock(&((x)->cs)) #define LEAVE_ENV_CS(x) pthread_mutex_unlock(&((x)->cs)) #define DELETE_ENV_CS(x) pthread_mutex_destroy(&((x)->cs)) #define INIT_COMMON_CS pthread_mutex_init(&common_cs,0) #define ENTER_COMMON_CS pthread_mutex_lock(&common_cs) #define LEAVE_COMMON_CS pthread_mutex_unlock(&common_cs) #define DELETE_COMMON_CS pthread_mutex_destroy(&common_cs) #else #define INIT_CONNS_CS #define ENTER_CONNS_CS #define LEAVE_CONNS_CS #define DELETE_CONNS_CS #define INIT_ENV_CS(x) #define ENTER_ENV_CS(x) #define LEAVE_ENV_CS(x) #define DELETE_ENV_CS(x) #define INIT_COMMON_CS #define ENTER_COMMON_CS #define LEAVE_COMMON_CS #define DELETE_COMMON_CS #endif /* WIN_MULTITHREAD_SUPPORT */ void shortterm_common_lock(void); void shortterm_common_unlock(void); #ifdef __cplusplus } #endif #endif /* __ENVIRON_H_ */ psqlodbc-09.03.0300/lobj.h000644 001752 000000 00000002046 12335653444 015301 0ustar00saitowheel000000 000000 /* File: lobj.h * * Description: See "lobj.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __LOBJ_H__ #define __LOBJ_H__ #include "psqlodbc.h" struct lo_arg { int isint; int len; union { int integer; char *ptr; } u; }; #define LO_CREAT 957 #define LO_OPEN 952 #define LO_CLOSE 953 #define LO_READ 954 #define LO_WRITE 955 #define LO_LSEEK 956 #define LO_TELL 958 #define LO_UNLINK 964 #define INV_WRITE 0x00020000 #define INV_READ 0x00040000 OID odbc_lo_creat(ConnectionClass *conn, int mode); int odbc_lo_open(ConnectionClass *conn, int lobjId, int mode); int odbc_lo_close(ConnectionClass *conn, int fd); Int4 odbc_lo_read(ConnectionClass *conn, int fd, char *buf, Int4 len); Int4 odbc_lo_write(ConnectionClass *conn, int fd, char *buf, Int4 len); Int4 odbc_lo_lseek(ConnectionClass *conn, int fd, int offset, Int4 len); Int4 odbc_lo_tell(ConnectionClass *conn, int fd); int odbc_lo_unlink(ConnectionClass *conn, OID lobjId); #endif psqlodbc-09.03.0300/md5.h000644 001752 000000 00000001561 12335653444 015041 0ustar00saitowheel000000 000000 /* File: md5.h * * Description: See "md5.h" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __MD5_H__ #define __MD5_H__ #include "psqlodbc.h" #include #include #define MD5_PASSWD_LEN 35 /* From c.h */ #ifndef __BEOS__ #ifndef __cplusplus #ifndef bool typedef char bool; #endif #ifndef true #define true ((bool) 1) #endif #ifndef false #define false ((bool) 0) #endif #endif /* not C++ */ #endif /* __BEOS__ */ /* Also defined in include/c.h */ #ifndef HAVE_UINT8 typedef unsigned char uint8; /* == 8 bits */ typedef unsigned short uint16; /* == 16 bits */ typedef unsigned int uint32; /* == 32 bits */ #endif /* not HAVE_UINT8 */ extern bool md5_hash(const void *buff, size_t len, char *hexsum); extern bool EncryptMD5(const char *passwd, const char *salt, size_t salt_len, char *buf); #endif psqlodbc-09.03.0300/misc.h000644 001752 000000 00000002774 12335653444 015316 0ustar00saitowheel000000 000000 /* File: misc.h * * Description: See "misc.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __MISC_H__ #define __MISC_H__ #include #ifndef WIN32 #include #endif #ifdef __cplusplus extern "C" { #endif char *strncpy_null(char *dst, const char *src, ssize_t len); #ifndef HAVE_STRLCPY size_t strlcat(char *, const char *, size_t); #endif /* HAVE_STRLCPY */ char *my_trim(char *string); char *make_string(const SQLCHAR *s, SQLINTEGER len, char *buf, size_t bufsize); SQLCHAR *make_lstring_ifneeded(ConnectionClass *, const SQLCHAR *s, ssize_t len, BOOL); char *schema_strcat(char *buf, const char *fmt, const SQLCHAR *s, SQLLEN len, const SQLCHAR *, SQLLEN, ConnectionClass *conn); char *schema_strcat1(char *buf, const char *fmt, const char *s1, const char *s, ssize_t len, const SQLCHAR *, int, ConnectionClass *conn); int snprintf_add(char *buf, size_t size, const char *format, ...); size_t snprintf_len(char *buf, size_t size, const char *format, ...); /* #define GET_SCHEMA_NAME(nspname) (stricmp(nspname, "public") ? nspname : "") */ char *quote_table(const pgNAME schema, pgNAME table); #define GET_SCHEMA_NAME(nspname) (nspname) /* defines for return value of my_strcpy */ #define STRCPY_SUCCESS 1 #define STRCPY_FAIL 0 #define STRCPY_TRUNCATED (-1) #define STRCPY_NULL (-2) ssize_t my_strcpy(char *dst, ssize_t dst_len, const char *src, ssize_t src_len); #ifdef __cplusplus } #endif #endif /* __MISC_H__ */ psqlodbc-09.03.0300/multibyte.h000644 001752 000000 00000005141 12335653444 016370 0ustar00saitowheel000000 000000 #ifndef __MULTIBUYTE_H__ #define __MULTIBUYTE_H__ /* * * Multibyte library header ( psqlODBC Only ) * */ #include "psqlodbc.h" #include "qresult.h" /* PostgreSQL client encoding */ enum { SQL_ASCII = 0 /* SQL/ASCII */ ,EUC_JP /* EUC for Japanese */ ,EUC_CN /* EUC for Chinese */ ,EUC_KR /* EUC for Korean */ ,EUC_TW /* EUC for Taiwan */ ,JOHAB ,UTF8 /* Unicode UTF-8 */ ,MULE_INTERNAL /* Mule internal code */ ,LATIN1 /* ISO-8859 Latin 1 */ ,LATIN2 /* ISO-8859 Latin 2 */ ,LATIN3 /* ISO-8859 Latin 3 */ ,LATIN4 /* ISO-8859 Latin 4 */ ,LATIN5 /* ISO-8859 Latin 5 */ ,LATIN6 /* ISO-8859 Latin 6 */ ,LATIN7 /* ISO-8859 Latin 7 */ ,LATIN8 /* ISO-8859 Latin 8 */ ,LATIN9 /* ISO-8859 Latin 9 */ ,LATIN10 /* ISO-8859 Latin 10 */ ,WIN1256 /* Arabic Windows */ ,WIN1258 /* Vietnamese Windows */ ,WIN866 /* Alternativny Variant (MS-DOS CP866) */ ,WIN874 /* Thai Windows */ ,KOI8R /* KOI8-R/U */ ,WIN1251 /* Cyrillic Windows */ ,WIN1252 /* Western Europe Windows */ ,ISO_8859_5 /* ISO-8859-5 */ ,ISO_8859_6 /* ISO-8859-6 */ ,ISO_8859_7 /* ISO-8859-7 */ ,ISO_8859_8 /* ISO-8859-8 */ ,WIN1250 /* Central Europe Windows */ ,WIN1253 /* Greek Windows */ ,WIN1254 /* Turkish Windows */ ,WIN1255 /* Hebrew Windows */ ,WIN1257 /* Baltic(North Europe) Windows */ ,EUC_JIS_2004 /* EUC for SHIFT-JIS-2004 Japanese */ ,SJIS /* Shift JIS */ ,BIG5 /* Big5 */ ,GBK /* GBK */ ,UHC /* UHC */ ,GB18030 /* GB18030 */ ,SHIFT_JIS_2004 /* SHIFT-JIS-2004 Japanese, JIS X 0213 */ ,OTHER = -1 }; extern void CC_lookup_characterset(ConnectionClass *self); extern const char *get_environment_encoding(const ConnectionClass *conn, const char *setenc, const char *svrenc, BOOL bStartup); extern int pg_CS_code(const char *stat_string); typedef struct pg_CS { char *name; int code; }pg_CS; extern size_t pg_mbslen(int ccsc, const UCHAR *string); extern UCHAR *pg_mbschr(int ccsc, const UCHAR *string, unsigned int character); /* Old Type Compatible */ typedef struct { int ccsc; const char *encstr; ssize_t pos; int ccst; } encoded_str; #define ENCODE_STATUS(enc) ((enc).ccst) void encoded_str_constr(encoded_str *encstr, int ccsc, const char *str); #define make_encoded_str(encstr, conn, str) encoded_str_constr(encstr, conn->ccsc, str) extern int encoded_nextchar(encoded_str *encstr); extern ssize_t encoded_position_shift(encoded_str *encstr, size_t shift); extern int encoded_byte_check(encoded_str *encstr, size_t abspos); /* #define check_client_encoding(X) pg_CS_name(pg_CS_code(X)) */ char *check_client_encoding(const pgNAME sql_string); #endif /* __MULTIBUYTE_H__ */ psqlodbc-09.03.0300/pgapifunc.h000644 001752 000000 00000031757 12335653444 016342 0ustar00saitowheel000000 000000 /*------- * Module: pgapifunc.h * *------- */ #ifndef _PG_API_FUNC_H__ #define _PG_API_FUNC_H__ #include "psqlodbc.h" #include #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Internal flags for catalog functions */ #define PODBC_NOT_SEARCH_PATTERN 1L #define PODBC_SEARCH_PUBLIC_SCHEMA (1L << 1) #define PODBC_SEARCH_BY_IDS (1L << 2) /* Internal flags for PGAPI_AllocStmt functions */ #define PODBC_EXTERNAL_STATEMENT 1L /* visible to the driver manager */ #define PODBC_INHERIT_CONNECT_OPTIONS (1L << 1) /* Internal flags for PGAPI_Exec... functions */ #define PODBC_WITH_HOLD 1L #define PODBC_PER_STATEMENT_ROLLBACK (1L << 1) /* Flags for the error handling */ #define PODBC_ALLOW_PARTIAL_EXTRACT 1L #define PODBC_ERROR_CLEAR (1L << 1) RETCODE SQL_API PGAPI_AllocConnect(HENV EnvironmentHandle, HDBC FAR * ConnectionHandle); RETCODE SQL_API PGAPI_AllocEnv(HENV FAR * EnvironmentHandle); RETCODE SQL_API PGAPI_AllocStmt(HDBC ConnectionHandle, HSTMT *StatementHandle, UDWORD flag); RETCODE SQL_API PGAPI_BindCol(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, PTR TargetValue, SQLLEN BufferLength, SQLLEN *StrLen_or_Ind); RETCODE SQL_API PGAPI_Cancel(HSTMT StatementHandle); RETCODE SQL_API PGAPI_Columns(HSTMT StatementHandle, const SQLCHAR *CatalogName, SQLSMALLINT NameLength1, const SQLCHAR *SchemaName, SQLSMALLINT NameLength2, const SQLCHAR *TableName, SQLSMALLINT NameLength3, const SQLCHAR *ColumnName, SQLSMALLINT NameLength4, UWORD flag, OID reloid, Int2 attnum); RETCODE SQL_API PGAPI_Connect(HDBC ConnectionHandle, const SQLCHAR *ServerName, SQLSMALLINT NameLength1, const SQLCHAR *UserName, SQLSMALLINT NameLength2, const SQLCHAR *Authentication, SQLSMALLINT NameLength3); RETCODE SQL_API PGAPI_DriverConnect(HDBC hdbc, HWND hwnd, const SQLCHAR FAR * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR FAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT FAR * pcbConnStrOut, SQLUSMALLINT fDriverCompletion); RETCODE SQL_API PGAPI_BrowseConnect(HDBC hdbc, const SQLCHAR *szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR *szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT *pcbConnStrOut); RETCODE SQL_API PGAPI_DataSources(HENV EnvironmentHandle, SQLUSMALLINT Direction, const SQLCHAR *ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT *NameLength1, const SQLCHAR *Description, SQLSMALLINT BufferLength2, SQLSMALLINT *NameLength2); RETCODE SQL_API PGAPI_DescribeCol(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLCHAR *ColumnName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength, SQLSMALLINT *DataType, SQLULEN *ColumnSize, SQLSMALLINT *DecimalDigits, SQLSMALLINT *Nullable); RETCODE SQL_API PGAPI_Disconnect(HDBC ConnectionHandle); RETCODE SQL_API PGAPI_Error(HENV EnvironmentHandle, HDBC ConnectionHandle, HSTMT StatementHandle, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength); /* Helper functions for Error handling */ RETCODE SQL_API PGAPI_EnvError(HENV EnvironmentHandle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength, UWORD flag); RETCODE SQL_API PGAPI_ConnectError(HDBC ConnectionHandle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength, UWORD flag); RETCODE SQL_API PGAPI_StmtError(HSTMT StatementHandle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength, UWORD flag); RETCODE SQL_API PGAPI_ExecDirect(HSTMT StatementHandle, const SQLCHAR *StatementText, SQLINTEGER TextLength, UWORD flag); RETCODE SQL_API PGAPI_Execute(HSTMT StatementHandle, UWORD flag); RETCODE SQL_API PGAPI_Fetch(HSTMT StatementHandle); RETCODE SQL_API PGAPI_FreeConnect(HDBC ConnectionHandle); RETCODE SQL_API PGAPI_FreeEnv(HENV EnvironmentHandle); RETCODE SQL_API PGAPI_FreeStmt(HSTMT StatementHandle, SQLUSMALLINT Option); RETCODE SQL_API PGAPI_GetConnectOption(HDBC ConnectionHandle, SQLUSMALLINT Option, PTR Value, SQLINTEGER *StringLength, SQLINTEGER BufferLength); RETCODE SQL_API PGAPI_GetCursorName(HSTMT StatementHandle, SQLCHAR *CursorName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength); RETCODE SQL_API PGAPI_GetData(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLSMALLINT TargetType, PTR TargetValue, SQLLEN BufferLength, SQLLEN *StrLen_or_Ind); RETCODE SQL_API PGAPI_GetFunctions(HDBC ConnectionHandle, SQLUSMALLINT FunctionId, SQLUSMALLINT *Supported); RETCODE SQL_API PGAPI_GetFunctions30(HDBC ConnectionHandle, SQLUSMALLINT FunctionId, SQLUSMALLINT *Supported); RETCODE SQL_API PGAPI_GetInfo(HDBC ConnectionHandle, SQLUSMALLINT InfoType, PTR InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength); RETCODE SQL_API PGAPI_GetInfo30(HDBC ConnectionHandle, SQLUSMALLINT InfoType, PTR InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength); RETCODE SQL_API PGAPI_GetStmtOption(HSTMT StatementHandle, SQLUSMALLINT Option, PTR Value, SQLINTEGER *StringLength, SQLINTEGER BufferLength); RETCODE SQL_API PGAPI_GetTypeInfo(HSTMT StatementHandle, SQLSMALLINT DataType); RETCODE SQL_API PGAPI_NumResultCols(HSTMT StatementHandle, SQLSMALLINT *ColumnCount); RETCODE SQL_API PGAPI_ParamData(HSTMT StatementHandle, PTR *Value); RETCODE SQL_API PGAPI_Prepare(HSTMT StatementHandle, const SQLCHAR *StatementText, SQLINTEGER TextLength); RETCODE SQL_API PGAPI_PutData(HSTMT StatementHandle, PTR Data, SQLLEN StrLen_or_Ind); RETCODE SQL_API PGAPI_RowCount(HSTMT StatementHandle, SQLLEN *RowCount); RETCODE SQL_API PGAPI_SetConnectOption(HDBC ConnectionHandle, SQLUSMALLINT Option, SQLULEN Value); RETCODE SQL_API PGAPI_SetCursorName(HSTMT StatementHandle, const SQLCHAR *CursorName, SQLSMALLINT NameLength); RETCODE SQL_API PGAPI_SetParam(HSTMT StatementHandle, SQLUSMALLINT ParameterNumber, SQLSMALLINT ValueType, SQLSMALLINT ParameterType, SQLULEN LengthPrecision, SQLSMALLINT ParameterScale, PTR ParameterValue, SQLLEN *StrLen_or_Ind); RETCODE SQL_API PGAPI_SetStmtOption(HSTMT StatementHandle, SQLUSMALLINT Option, SQLULEN Value); RETCODE SQL_API PGAPI_SpecialColumns(HSTMT StatementHandle, SQLUSMALLINT IdentifierType, const SQLCHAR *CatalogName, SQLSMALLINT NameLength1, const SQLCHAR *SchemaName, SQLSMALLINT NameLength2, const SQLCHAR *TableName, SQLSMALLINT NameLength3, SQLUSMALLINT Scope, SQLUSMALLINT Nullable); RETCODE SQL_API PGAPI_Statistics(HSTMT StatementHandle, const SQLCHAR *CatalogName, SQLSMALLINT NameLength1, const SQLCHAR *SchemaName, SQLSMALLINT NameLength2, const SQLCHAR *TableName, SQLSMALLINT NameLength3, SQLUSMALLINT Unique, SQLUSMALLINT Reserved); RETCODE SQL_API PGAPI_Tables(HSTMT StatementHandle, const SQLCHAR *CatalogName, SQLSMALLINT NameLength1, const SQLCHAR *SchemaName, SQLSMALLINT NameLength2, const SQLCHAR *TableName, SQLSMALLINT NameLength3, const SQLCHAR *TableType, SQLSMALLINT NameLength4, UWORD flag); RETCODE SQL_API PGAPI_Transact(HENV EnvironmentHandle, HDBC ConnectionHandle, SQLUSMALLINT CompletionType); RETCODE SQL_API PGAPI_ColAttributes( HSTMT hstmt, SQLUSMALLINT icol, SQLUSMALLINT fDescType, PTR rgbDesc, SQLSMALLINT cbDescMax, SQLSMALLINT *pcbDesc, SQLLEN *pfDesc); RETCODE SQL_API PGAPI_ColumnPrivileges( HSTMT hstmt, const SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, const SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, const SQLCHAR *szTableName, SQLSMALLINT cbTableName, const SQLCHAR *szColumnName, SQLSMALLINT cbColumnName, UWORD flag); RETCODE SQL_API PGAPI_DescribeParam( HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT *pfSqlType, SQLULEN *pcbParamDef, SQLSMALLINT *pibScale, SQLSMALLINT *pfNullable); RETCODE SQL_API PGAPI_ExtendedFetch( HSTMT hstmt, SQLUSMALLINT fFetchType, SQLLEN irow, SQLULEN *pcrow, SQLUSMALLINT *rgfRowStatus, SQLLEN FetchOffset, SQLLEN rowsetSize); RETCODE SQL_API PGAPI_ForeignKeys( HSTMT hstmt, const SQLCHAR *szPkCatalogName, SQLSMALLINT cbPkCatalogName, const SQLCHAR *szPkSchemaName, SQLSMALLINT cbPkSchemaName, const SQLCHAR *szPkTableName, SQLSMALLINT cbPkTableName, const SQLCHAR *szFkCatalogName, SQLSMALLINT cbFkCatalogName, const SQLCHAR *szFkSchemaName, SQLSMALLINT cbFkSchemaName, const SQLCHAR *szFkTableName, SQLSMALLINT cbFkTableName); RETCODE SQL_API PGAPI_MoreResults( HSTMT hstmt); RETCODE SQL_API PGAPI_NativeSql( HDBC hdbc, const SQLCHAR *szSqlStrIn, SQLINTEGER cbSqlStrIn, SQLCHAR *szSqlStr, SQLINTEGER cbSqlStrMax, SQLINTEGER *pcbSqlStr); RETCODE SQL_API PGAPI_NumParams( HSTMT hstmt, SQLSMALLINT *pcpar); RETCODE SQL_API PGAPI_ParamOptions( HSTMT hstmt, SQLULEN crow, SQLULEN *pirow); RETCODE SQL_API PGAPI_PrimaryKeys( HSTMT hstmt, const SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, const SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, const SQLCHAR *szTableName, SQLSMALLINT cbTableName, OID reloid); RETCODE SQL_API PGAPI_ProcedureColumns( HSTMT hstmt, const SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, const SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, const SQLCHAR *szProcName, SQLSMALLINT cbProcName, const SQLCHAR *szColumnName, SQLSMALLINT cbColumnName, UWORD flag); RETCODE SQL_API PGAPI_Procedures( HSTMT hstmt, const SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, const SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, const SQLCHAR *szProcName, SQLSMALLINT cbProcName, UWORD flag); RETCODE SQL_API PGAPI_SetPos( HSTMT hstmt, SQLSETPOSIROW irow, SQLUSMALLINT fOption, SQLUSMALLINT fLock); RETCODE SQL_API PGAPI_TablePrivileges( HSTMT hstmt, const SQLCHAR *szCatalogName, SQLSMALLINT cbCatalogName, const SQLCHAR *szSchemaName, SQLSMALLINT cbSchemaName, const SQLCHAR *szTableName, SQLSMALLINT cbTableName, UWORD flag); RETCODE SQL_API PGAPI_BindParameter( HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT fParamType, SQLSMALLINT fCType, SQLSMALLINT fSqlType, SQLULEN cbColDef, SQLSMALLINT ibScale, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue); RETCODE SQL_API PGAPI_SetScrollOptions( HSTMT hstmt, SQLUSMALLINT fConcurrency, SQLLEN crowKeyset, SQLUSMALLINT crowRowset); #if (ODBCVER >= 0x0300) RETCODE SQL_API PGAPI_GetDiagRec(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength); RETCODE SQL_API PGAPI_GetDiagField(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT RecNumber, SQLSMALLINT DiagIdentifier, PTR DiagInfoPtr, SQLSMALLINT BufferLength, SQLSMALLINT *StringLengthPtr); RETCODE SQL_API PGAPI_GetConnectAttr(HDBC ConnectionHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength); RETCODE SQL_API PGAPI_GetStmtAttr(HSTMT StatementHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength); enum { SQL_ATTR_PGOPT_DEBUG = 65536 ,SQL_ATTR_PGOPT_COMMLOG ,SQL_ATTR_PGOPT_PARSE ,SQL_ATTR_PGOPT_USE_DECLAREFETCH ,SQL_ATTR_PGOPT_SERVER_SIDE_PREPARE ,SQL_ATTR_PGOPT_FETCH }; RETCODE SQL_API PGAPI_SetConnectAttr(HDBC ConnectionHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength); RETCODE SQL_API PGAPI_SetStmtAttr(HSTMT StatementHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength); RETCODE SQL_API PGAPI_BulkOperations(HSTMT StatementHandle, SQLSMALLINT operation); RETCODE SQL_API PGAPI_AllocDesc(HDBC ConnectionHandle, SQLHDESC *DescriptorHandle); RETCODE SQL_API PGAPI_FreeDesc(SQLHDESC DescriptorHandle); RETCODE SQL_API PGAPI_CopyDesc(SQLHDESC SourceDescHandle, SQLHDESC TargetDescHandle); RETCODE SQL_API PGAPI_SetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength); RETCODE SQL_API PGAPI_GetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength); RETCODE SQL_API PGAPI_DescError(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLCHAR *Sqlstate, SQLINTEGER *NativeError, SQLCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength, UWORD flag); #endif /* ODBCVER */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* define_PG_API_FUNC_H__ */ psqlodbc-09.03.0300/pgtypes.h000644 001752 000000 00000015323 12335653444 016050 0ustar00saitowheel000000 000000 /* File: pgtypes.h * * Description: See "pgtypes.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __PGTYPES_H__ #define __PGTYPES_H__ #include "psqlodbc.h" /* the type numbers are defined by the OID's of the types' rows */ /* in table pg_type */ #ifdef NOT_USED #define PG_TYPE_LO ???? /* waiting for permanent type */ #endif #define MS_ACCESS_SERIAL "int identity" #define PG_TYPE_BOOL 16 #define PG_TYPE_BYTEA 17 #define PG_TYPE_CHAR 18 #define PG_TYPE_NAME 19 #define PG_TYPE_INT8 20 #define PG_TYPE_INT2 21 #define PG_TYPE_INT2VECTOR 22 #define PG_TYPE_INT4 23 #define PG_TYPE_REGPROC 24 #define PG_TYPE_TEXT 25 #define PG_TYPE_OID 26 #define PG_TYPE_TID 27 #define PG_TYPE_XID 28 #define PG_TYPE_CID 29 #define PG_TYPE_OIDVECTOR 30 #define PG_TYPE_SET 32 #define PG_TYPE_XML 142 #define PG_TYPE_XMLARRAY 143 #define PG_TYPE_CHAR2 409 #define PG_TYPE_CHAR4 410 #define PG_TYPE_CHAR8 411 #define PG_TYPE_POINT 600 #define PG_TYPE_LSEG 601 #define PG_TYPE_PATH 602 #define PG_TYPE_BOX 603 #define PG_TYPE_POLYGON 604 #define PG_TYPE_FILENAME 605 #define PG_TYPE_CIDR 650 #define PG_TYPE_FLOAT4 700 #define PG_TYPE_FLOAT8 701 #define PG_TYPE_ABSTIME 702 #define PG_TYPE_RELTIME 703 #define PG_TYPE_TINTERVAL 704 #define PG_TYPE_UNKNOWN 705 #define PG_TYPE_MONEY 790 #define PG_TYPE_OIDINT2 810 #define PG_TYPE_MACADDR 829 #define PG_TYPE_INET 869 #define PG_TYPE_OIDINT4 910 #define PG_TYPE_OIDNAME 911 #define PG_TYPE_TEXTARRAY 1009 #define PG_TYPE_BPCHARARRAY 1014 #define PG_TYPE_VARCHARARRAY 1015 #define PG_TYPE_BPCHAR 1042 #define PG_TYPE_VARCHAR 1043 #define PG_TYPE_DATE 1082 #define PG_TYPE_TIME 1083 #define PG_TYPE_TIMESTAMP_NO_TMZONE 1114 /* since 7.2 */ #define PG_TYPE_DATETIME 1184 #define PG_TYPE_INTERVAL 1186 #define PG_TYPE_TIME_WITH_TMZONE 1266 /* since 7.1 */ #define PG_TYPE_TIMESTAMP 1296 /* deprecated since 7.0 */ #define PG_TYPE_BIT 1560 #define PG_TYPE_NUMERIC 1700 #define PG_TYPE_REFCURSOR 1790 #define PG_TYPE_RECORD 2249 #define PG_TYPE_VOID 2278 #define PG_TYPE_UUID 2950 #define INTERNAL_ASIS_TYPE (-9999) #define TYPE_MAY_BE_ARRAY(type) ((type) == PG_TYPE_XMLARRAY || ((type) >= 1000 && (type) <= 1041)) /* extern Int4 pgtypes_defined[]; */ extern SQLSMALLINT sqlTypes[]; /* Defines for pgtype_precision */ #define PG_STATIC (-1) #define PG_UNSPECIFIED (-1) #define PG_WIDTH_OF_BOOLS_AS_CHAR 5 #if (ODBCVER >= 0x0300) /* * SQL_INTERVAL support is disabled because I found * some applications which are unhappy with it. * #define PG_INTERVAL_AS_SQL_INTERVAL */ #endif /* ODBCVER */ OID pg_true_type(const ConnectionClass *, OID, OID); OID sqltype_to_pgtype(const ConnectionClass *conn, SQLSMALLINT fSqlType); SQLSMALLINT pgtype_to_concise_type(const StatementClass *stmt, OID type, int col); SQLSMALLINT pgtype_to_sqldesctype(const StatementClass *stmt, OID type, int col); SQLSMALLINT pgtype_to_datetime_sub(const StatementClass *stmt, OID type, int col); const char *pgtype_to_name(const StatementClass *stmt, OID type, int col, BOOL auto_increment); SQLSMALLINT pgtype_attr_to_concise_type(const ConnectionClass *conn, OID type, int typmod, int adtsize_or_longestlen); SQLSMALLINT pgtype_attr_to_sqldesctype(const ConnectionClass *conn, OID type, int typmod); SQLSMALLINT pgtype_attr_to_datetime_sub(const ConnectionClass *conn, OID type, int typmod); SQLSMALLINT pgtype_attr_to_ctype(const ConnectionClass *conn, OID type, int typmod); const char *pgtype_attr_to_name(const ConnectionClass *conn, OID type, int typmod, BOOL auto_increment); Int4 pgtype_attr_column_size(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int handle_unknown_size_as); Int4 pgtype_attr_buffer_length(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as); Int4 pgtype_attr_display_size(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as); Int2 pgtype_attr_decimal_digits(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as); Int4 pgtype_attr_transfer_octet_length(const ConnectionClass *conn, OID type, int atttypmod, int handle_unknown_size_as); SQLSMALLINT pgtype_attr_precision(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int handle_unknown_size_as); Int4 pgtype_attr_desclength(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as); Int2 pgtype_attr_scale(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as); /* These functions can use static numbers or result sets(col parameter) */ Int4 pgtype_column_size(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); /* corresponds to "precision" in ODBC 2.x */ SQLSMALLINT pgtype_precision(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); /* "precsion in ODBC 3.x */ /* the following size/length are of Int4 due to PG restriction */ Int4 pgtype_display_size(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); Int4 pgtype_buffer_length(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); Int4 pgtype_desclength(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); // Int4 pgtype_transfer_octet_length(const ConnectionClass *conn, OID type, int column_size); SQLSMALLINT pgtype_decimal_digits(const StatementClass *stmt, OID type, int col); /* corresponds to "scale" in ODBC 2.x */ SQLSMALLINT pgtype_min_decimal_digits(const ConnectionClass *conn, OID type); /* corresponds to "min_scale" in ODBC 2.x */ SQLSMALLINT pgtype_max_decimal_digits(const ConnectionClass *conn, OID type); /* corresponds to "max_scale" in ODBC 2.x */ SQLSMALLINT pgtype_scale(const StatementClass *stmt, OID type, int col); /* ODBC 3.x " */ Int2 pgtype_radix(const ConnectionClass *conn, OID type); Int2 pgtype_nullable(const ConnectionClass *conn, OID type); Int2 pgtype_auto_increment(const ConnectionClass *conn, OID type); Int2 pgtype_case_sensitive(const ConnectionClass *conn, OID type); Int2 pgtype_money(const ConnectionClass *conn, OID type); Int2 pgtype_searchable(const ConnectionClass *conn, OID type); Int2 pgtype_unsigned(const ConnectionClass *conn, OID type); const char *pgtype_literal_prefix(const ConnectionClass *conn, OID type); const char *pgtype_literal_suffix(const ConnectionClass *conn, OID type); const char *pgtype_create_params(const ConnectionClass *conn, OID type); SQLSMALLINT sqltype_to_default_ctype(const ConnectionClass *stmt, SQLSMALLINT sqltype); Int4 ctype_length(SQLSMALLINT ctype); #define USE_ZONE FALSE #endif psqlodbc-09.03.0300/psqlodbc.h000644 001752 000000 00000037672 12335653444 016177 0ustar00saitowheel000000 000000 /* File: psqlodbc.h * * Description: This file contains defines and declarations that are related to * the entire driver. * * Comments: See "readme.txt" for copyright and license information. */ #ifndef __PSQLODBC_H__ #define __PSQLODBC_H__ /* #define __MS_REPORTS_ANSI_CHAR__ */ #ifndef WIN32 #include "config.h" #else #define WIN32_LEAN_AND_MEAN #include #endif #include /* for FILE* pointers: see GLOBAL_VALUES */ #ifdef POSIX_MULTITHREAD_SUPPORT #include #endif #include "version.h" #ifdef WIN32 #ifdef _DEBUG #ifndef _MEMORY_DEBUG_ #include #if (_MSC_VER < 1400) /* in case of VC7 or under */ #include #endif /* _MSC_VER */ #define _CRTDBG_MAP_ALLOC #include #endif /* _MEMORY_DEBUG_ */ #else /* _DEBUG */ #include #endif /* _DEBUG */ #endif /* WIN32 */ #ifdef _MEMORY_DEBUG_ void *pgdebug_alloc(size_t); void *pgdebug_calloc(size_t, size_t); void *pgdebug_realloc(void *, size_t); char *pgdebug_strdup(const char *); void *pgdebug_memcpy(void *, const void *, size_t); void *pgdebug_memset(void *, int c, size_t); char *pgdebug_strcpy(char *, const char *); char *pgdebug_strncpy(char *, const char *, size_t); char *pgdebug_strncpy_null(char *, const char *, size_t); void pgdebug_free(void *); void debug_memory_check(void); #ifdef WIN32 #undef strdup #endif /* WIN32 */ #define malloc pgdebug_alloc #define realloc pgdebug_realloc #define calloc pgdebug_calloc #define strdup pgdebug_strdup #define free pgdebug_free #define strcpy pgdebug_strcpy #define strncpy pgdebug_strncpy /* #define strncpy_null pgdebug_strncpy_null */ #define memcpy pgdebug_memcpy #define memset pgdebug_memset #endif /* _MEMORY_DEBUG_ */ #ifdef WIN32 #include #endif /* WIN32 */ /* Must come before sql.h */ #ifndef ODBCVER #define ODBCVER 0x0250 #endif /* ODBCVER_REP */ #define NAMEDATALEN_V72 32 #define NAMEDATALEN_V73 64 #ifndef NAMESTORAGELEN #define NAMESTORAGELEN 64 #endif /* NAMEDATALEN */ #ifndef WIN32 #undef WIN_MULTITHREAD_SUPPORT #endif #if defined(WIN32) || defined(WITH_UNIXODBC) || defined(WITH_IODBC) #include #include #if defined(WIN32) && (_MSC_VER < 1300) /* in case of VC6 or under */ #define SQLLEN SQLINTEGER #define SQLULEN SQLUINTEGER #define SQLSETPOSIROW SQLUSMALLINT /* VC6 bypasses 64bit mode. */ #define DWLP_USER DWL_USER #define ULONG_PTR ULONG #define LONG_PTR LONG #define SetWindowLongPtr(hdlg, DWLP_USER, lParam) SetWindowLong(hdlg, DWLP_USER, lParam) #define GetWindowLongPtr(hdlg, DWLP_USER) GetWindowLong(hdlg, DWLP_USER); #endif #else #include "iodbc.h" #include "isql.h" #include "isqlext.h" #endif /* WIN32 */ #if defined(WIN32) #include #elif defined(WITH_UNIXODBC) #include #elif defined(WITH_IODBC) #include #else #include "gpps.h" #endif #ifdef __cplusplus extern "C" { #endif #define Int4 int #define UInt4 unsigned int #define Int2 short #define UInt2 unsigned short typedef UInt4 OID; #define FORMAT_INT4 "%d" /* Int4 */ #define FORMAT_UINT4 "%u" /* UInt4 */ #ifndef SQL_TRUE #define SQL_TRUE TRUE #endif /* SQL_TRUE */ #ifndef SQL_FALSE #define SQL_FALSE FALSE #endif /* SQL_FALSE */ #ifdef WIN32 #ifndef SSIZE_T_DEFINED #define ssize_t SSIZE_T #define SSIZE_T_DEFINED #endif #define FORMAT_SIZE_T "%Iu" /* size_t */ #define FORMAT_SSIZE_T "%Id" /* ssize_t */ #define FORMAT_INTEGER "%ld" /* SQLINTEGER */ #define FORMAT_UINTEGER "%lu" /* SQLUINTEGER */ #ifdef _WIN64 #define FORMAT_LEN "%I64d" /* SQLLEN */ #define FORMAT_ULEN "%I64u" /* SQLULEN */ #define FORMAT_LPTR "%I64d" /* LONG_PTR */ #define FORMAT_ULPTR "%I64u" /* ULONG_PTR */ #else #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #define FORMAT_LPTR "%ld" /* LONG_PTR */ #define FORMAT_ULPTR "%lu" /* ULONG_PTR */ #endif /* _WIN64 */ #else #define FORMAT_SIZE_T "%zu" /* size_t */ #define FORMAT_SSIZE_T "%zd" /* ssize_t */ #ifndef HAVE_SSIZE_T typedef long ssize_t #endif /* HAVE_SSIZE_T */ #if (SIZEOF_VOID_P == SIZEOF_LONG) typedef long LONG_PTR; typedef unsigned long ULONG_PTR; #define FORMAT_LPTR "%ld" /* LONG_PTR */ #define FORMAT_ULPTR "%lu" /* ULONG_PTR */ #elif defined (HAVE_LONG_LONG) typedef long long LONG_PTR; typedef unsigned long long ULONG_PTR; #define FORMAT_LPTR "%lld" /* LONG_PTR */ #define FORMAT_ULPTR "%llu" /* ULONG_PTR */ #else #error appropriate long pointer type not found #endif /* SIZEOF_VOID_P */ #if (SIZEOF_LONG == 8) #define FORMAT_INTEGER "%d" /* SQLINTEGER */ #define FORMAT_UINTEGER "%u" /* SQLUINTEGER */ #if defined(WITH_UNIXODBC) && defined(BUILD_LEGACY_64_BIT_MODE) #define FORMAT_LEN "%d" /* SQLLEN */ #define FORMAT_ULEN "%u" /* SQLULEN */ #else #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #endif /* WITH_UNIXODBC */ #else #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #define FORMAT_INTEGER "%ld" /* SQLINTEGER */ #define FORMAT_UINTEGER "%lu" /* SQLUINTEGER */ #endif /* SIZEOF_VOID_P */ #endif /* WIN32 */ #define CAST_PTR(type, ptr) (type)((LONG_PTR)(ptr)) #define CAST_UPTR(type, ptr) (type)((ULONG_PTR)(ptr)) #ifndef SQL_IS_LEN #define SQL_IS_LEN (-1000) #endif /* SQL_IS_LEN */ #ifdef HAVE_SIGNED_CHAR typedef signed char po_ind_t; #else typedef char po_ind_t; #endif /* HAVE_SIGNED_CHAR */ #ifndef WIN32 #if !defined(WITH_UNIXODBC) && !defined(WITH_IODBC) typedef float SFLOAT; typedef double SDOUBLE; #endif /* WITH_UNIXODBC */ #ifndef CALLBACK #define CALLBACK #endif /* CALLBACK */ #endif /* WIN32 */ #ifndef WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp #ifndef TRUE #define TRUE (BOOL)1 #endif /* TRUE */ #ifndef FALSE #define FALSE (BOOL)0 #endif /* FALSE */ #else #define snprintf _snprintf #ifndef strdup #define strdup _strdup #endif /* strdup */ #define strnicmp _strnicmp #define stricmp _stricmp #define vsnprintf _vsnprintf #endif /* WIN32 */ #ifndef SQL_ATTR_APP_ROW_DESC #define SQL_ATTR_APP_ROW_DESC 10010 #endif #ifndef SQL_ATTR_APP_PARAM_DESC #define SQL_ATTR_APP_PARAM_DESC 10011 #endif #ifndef SQL_ATTR_IMP_ROW_DESC #define SQL_ATTR_IMP_ROW_DESC 10012 #endif #ifndef SQL_ATTR_IMP_PARAM_DESC #define SQL_ATTR_IMP_PARAM_DESC 10013 #endif /* Driver stuff */ #define DRIVERNAME "PostgreSQL ODBC" #if (ODBCVER >= 0x0300) #if (ODBCVER >= 0x0351) #define DRIVER_ODBC_VER "03.51" #else #define DRIVER_ODBC_VER "03.00" #endif /* ODBCVER 0x0351 */ #ifndef DBMS_NAME #ifdef UNICODE_SUPPORT #define DBMS_NAME "PostgreSQL Unicode" #else #define DBMS_NAME "PostgreSQL ANSI" #endif /* UNICODE_SUPPORT */ #endif /* DBMS_NAME */ #else #define DRIVER_ODBC_VER "02.50" #ifndef DBMS_NAME #define DBMS_NAME "PostgreSQL Legacy" #endif /* DBMS_NAME */ #endif /* ODBCVER */ #ifdef WIN32 #if (ODBCVER >= 0x0300) #ifdef UNICODE_SUPPORT #if (ODBCVER >= 0x0350) #define DRIVER_FILE_NAME "PSQLODBC35W.DLL" #else #define DRIVER_FILE_NAME "PSQLODBC30W.DLL" #endif /* ODBCVER 0x0350 */ #else #define DRIVER_FILE_NAME "PSQLODBC.DLL" #endif /* UNICODE_SUPPORT */ #else #define DRIVER_FILE_NAME "PSQLODBC25.DLL" #endif /* ODBCVER 0x0300 */ #else #ifdef UNICODE_SUPPORT #define DRIVER_FILE_NAME "psqlodbcw.so" #else #define DRIVER_FILE_NAME "psqlodbca.so" #endif #endif /* WIN32 */ BOOL isMsAccess(void); BOOL isMsQuery(void); BOOL isSqlServr(void); /* ESCAPEs */ #define ESCAPE_IN_LITERAL '\\' #define BYTEA_ESCAPE_CHAR '\\' #define SEARCH_PATTERN_ESCAPE '\\' #define LITERAL_QUOTE '\'' #define IDENTIFIER_QUOTE '\"' #define ODBC_ESCAPE_START '{' #define ODBC_ESCAPE_END '}' #define DOLLAR_QUOTE '$' #define LITERAL_EXT 'E' #define PG_CARRIAGE_RETURN '\r' #define PG_LINEFEED '\n' /* Limits */ #define BLCKSZ 4096 #define MAXPGPATH 1024 #define MAX_MESSAGE_LEN 65536 /* This puts a limit on * query size but I don't */ /* see an easy way round this - DJP 24-1-2001 */ #define MAX_CONNECT_STRING 4096 #define ERROR_MSG_LENGTH 4096 #define FETCH_MAX 100 /* default number of rows to cache * for declare/fetch */ #define TUPLE_MALLOC_INC 100 #define SOCK_BUFFER_SIZE 4096 /* default socket buffer * size */ #define MAX_CONNECTIONS 128 /* conns per environment * (arbitrary) */ #define MAX_FIELDS 512 #define BYTELEN 8 #define VARHDRSZ sizeof(Int4) #ifdef NAMEDATALEN #define MAX_SCHEMA_LEN NAMEDATALEN #define MAX_TABLE_LEN NAMEDATALEN #define MAX_COLUMN_LEN NAMEDATALEN #define NAME_FIELD_SIZE NAMEDATALEN /* size of name fields */ #if (NAMEDATALEN > NAMESTORAGELEN) #undef NAMESTORAGELEN #define NAMESTORAGELEN NAMEDATALEN #endif #endif /* NAMEDATALEN */ #define MAX_CURSOR_LEN 32 #define SCHEMA_NAME_STORAGE_LEN NAMESTORAGELEN #define TABLE_NAME_STORAGE_LEN NAMESTORAGELEN #define COLUMN_NAME_STORAGE_LEN NAMESTORAGELEN #define INDEX_KEYS_STORAGE_COUNT 32 /* Registry length limits */ #define LARGE_REGISTRY_LEN 4096 /* used for special cases */ #define MEDIUM_REGISTRY_LEN 256 /* normal size for * user,database,etc. */ #define SMALL_REGISTRY_LEN 10 /* for 1/0 settings */ /* These prefixes denote system tables */ #define POSTGRES_SYS_PREFIX "pg_" /* Info limits */ #define MAX_INFO_STRING 128 /* POSIX defines a PATH_MAX.( wondows is _MAX_PATH ..) */ #ifndef PATH_MAX #ifdef _MAX_PATH #define PATH_MAX _MAX_PATH #else #define PATH_MAX 1024 #endif /* _MAX_PATH */ #endif /* PATH_MAX */ #define PG62 "6.2" /* "Protocol" key setting * to force Postgres 6.2 */ #define PG63 "6.3" /* "Protocol" key setting * to force postgres 6.3 */ #define PG64 "6.4" #define PG74REJECTED "reject7.4" #define PG74 "7.4" typedef struct ConnectionClass_ ConnectionClass; typedef struct StatementClass_ StatementClass; typedef struct QResultClass_ QResultClass; typedef struct SocketClass_ SocketClass; typedef struct BindInfoClass_ BindInfoClass; typedef struct ParameterInfoClass_ ParameterInfoClass; typedef struct ParameterImplClass_ ParameterImplClass; typedef struct ColumnInfoClass_ ColumnInfoClass; typedef struct EnvironmentClass_ EnvironmentClass; typedef struct TupleField_ TupleField; typedef struct KeySet_ KeySet; typedef struct Rollback_ Rollback; typedef struct ARDFields_ ARDFields; typedef struct APDFields_ APDFields; typedef struct IRDFields_ IRDFields; typedef struct IPDFields_ IPDFields; typedef struct col_info COL_INFO; typedef struct lo_arg LO_ARG; /* pgNAME type define */ typedef struct { char *name; } pgNAME; #define GET_NAME(the_name) ((the_name).name) #define SAFE_NAME(the_name) ((the_name).name ? (the_name).name : NULL_STRING) #define PRINT_NAME(the_name) ((the_name).name ? (the_name).name : PRINT_NULL) #define NAME_IS_NULL(the_name) (NULL == (the_name).name) #define NAME_IS_VALID(the_name) (NULL != (the_name).name) #define INIT_NAME(the_name) ((the_name).name = NULL) #define NULL_THE_NAME(the_name) \ do { \ if ((the_name).name) free((the_name).name); \ (the_name).name = NULL; \ } while (0) #define STR_TO_NAME(the_name, str) \ do { \ if ((the_name).name) \ free((the_name).name); \ (the_name).name = (str ? strdup((str)) : NULL); \ } while (0) #define STRX_TO_NAME(the_name, str) \ do { \ if ((the_name).name) \ free((the_name).name); \ (the_name).name = strdup((str)); \ } while (0) #define STRN_TO_NAME(the_name, str, n) \ do { \ if ((the_name).name) \ free((the_name).name); \ if (str) \ { \ (the_name).name = malloc((n) + 1); \ memcpy((the_name).name, str, (n)); \ (the_name).name[(n)] = '\0'; \ } \ else \ (the_name).name = NULL; \ } while (0) #define NAME_TO_STR(str, the_name) \ do {\ if ((the_name).name) strcpy(str, (the_name).name); \ else *str = '\0'; \ } while (0) #define NAME_TO_NAME(to, from) \ do { \ if ((to).name) \ free((to).name); \ if ((from).name) \ (to).name = strdup(from.name); \ else \ (to).name = NULL; \ } while (0) #define MOVE_NAME(to, from) \ do { \ if ((to).name) \ free((to).name); \ (to).name = (from).name; \ (from).name = NULL; \ } while (0) #define SET_NAME_DIRECTLY(the_name, str) ((the_name).name = (str)) #define NAMECMP(name1, name2) (strcmp(SAFE_NAME(name1), SAFE_NAME(name2))) #define NAMEICMP(name1, name2) (stricmp(SAFE_NAME(name1), SAFE_NAME(name2))) /* pgNAME define end */ typedef struct GlobalValues_ { pgNAME drivername; int fetch_max; int socket_buffersize; int unknown_sizes; int max_varchar_size; int max_longvarchar_size; char debug; char commlog; char disable_optimizer; char ksqo; char unique_index; char onlyread; /* readonly is reserved on Digital C++ * compiler */ char use_declarefetch; char text_as_longvarchar; char unknowns_as_longvarchar; char bools_as_char; char lie; char parse; char cancel_as_freestmt; char extra_systable_prefixes[MEDIUM_REGISTRY_LEN]; char protocol[SMALL_REGISTRY_LEN]; pgNAME conn_settings; } GLOBAL_VALUES; void copy_globals(GLOBAL_VALUES *to, const GLOBAL_VALUES *from); void finalize_globals(GLOBAL_VALUES *glbv); typedef struct StatementOptions_ { SQLLEN maxRows; SQLLEN maxLength; SQLLEN keyset_size; SQLUINTEGER cursor_type; SQLUINTEGER scroll_concurrency; SQLUINTEGER retrieve_data; SQLUINTEGER use_bookmarks; void *bookmark_ptr; #if (ODBCVER >= 0x0300) SQLUINTEGER metadata_id; #endif /* ODBCVER */ } StatementOptions; /* Used to pass extra query info to send_query */ typedef struct QueryInfo_ { SQLLEN row_size; QResultClass *result_in; const char *cursor; } QueryInfo; /* Used to save the error information */ typedef struct { UInt4 status; Int4 errorsize; Int2 recsize; Int2 errorpos; char sqlstate[8]; SQLLEN diag_row_count; char __error_message[1]; } PG_ErrorInfo; PG_ErrorInfo *ER_Constructor(SDWORD errornumber, const char *errormsg); PG_ErrorInfo *ER_Dup(const PG_ErrorInfo *from); void ER_Destructor(PG_ErrorInfo *); RETCODE SQL_API ER_ReturnError(PG_ErrorInfo **, SQLSMALLINT, UCHAR FAR *, SQLINTEGER FAR *, UCHAR FAR *, SQLSMALLINT, SQLSMALLINT FAR *, UWORD); void logs_on_off(int cnopen, int, int); #define PG_TYPE_LO_UNDEFINED (-999) /* hack until permanent * type available */ #define PG_TYPE_LO_NAME "lo" #define CTID_ATTNUM (-1) /* the attnum of ctid */ #define OID_ATTNUM (-2) /* the attnum of oid */ #define XMIN_ATTNUM (-3) /* the attnum of xmin */ /* sizes */ #define TEXT_FIELD_SIZE 8190 /* size of default text fields * (not including null term) */ #define MAX_VARCHAR_SIZE 255 /* default maximum size of * varchar fields (not including null term) */ #define INFO_VARCHAR_SIZE 254 /* varchar field size * used in info.c */ #define PG_NUMERIC_MAX_PRECISION 1000 #define PG_NUMERIC_MAX_SCALE 1000 #define INFO_INQUIRY_LEN 8192 /* this seems sufficiently big for * queries used in info.c inoue * 2001/05/17 */ #define LENADDR_SHIFT(x, sft) ((x) ? (SQLLEN *)((char *)(x) + (sft)) : NULL) int initialize_global_cs(void); #ifdef POSIX_MULTITHREAD_SUPPORT #if !defined(HAVE_ECO_THREAD_LOCKS) #define POSIX_THREADMUTEX_SUPPORT #endif /* HAVE_ECO_THREAD_LOCKS */ #endif /* POSIX_MULTITHREAD_SUPPORT */ #ifdef POSIX_THREADMUTEX_SUPPORT const pthread_mutexattr_t *getMutexAttr(void); #endif /* POSIX_THREADMUTEX_SUPPORT */ #ifdef UNICODE_SUPPORT #define WCLEN sizeof(SQLWCHAR) SQLULEN ucs2strlen(const SQLWCHAR *ucs2str); char *ucs2_to_utf8(const SQLWCHAR *ucs2str, SQLLEN ilen, SQLLEN *olen, BOOL tolower); SQLULEN utf8_to_ucs2_lf(const char * utf8str, SQLLEN ilen, BOOL lfconv, SQLWCHAR *ucs2str, SQLULEN buflen, BOOL errcheck); int msgtowstr(const char *, const char *, int, LPWSTR, int); int wstrtomsg(const char *, const LPWSTR, int, char *, int); #define utf8_to_ucs2(utf8str, ilen, ucs2str, buflen) utf8_to_ucs2_lf(utf8str, ilen, FALSE, ucs2str, buflen, FALSE) #endif /* UNICODE_SUPPORT */ /* Define a type for defining a constant string expression */ #ifndef CSTR #define CSTR static const char * const #endif /* CSTR */ CSTR NULL_STRING = ""; CSTR PRINT_NULL = "(null)"; CSTR OID_NAME = "oid"; #ifdef __cplusplus } #endif #include "mylog.h" #endif /* __PSQLODBC_H__ */ psqlodbc-09.03.0300/qresult.h000644 001752 000000 00000030056 12335653444 016054 0ustar00saitowheel000000 000000 /* File: qresult.h * * Description: See "qresult.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __QRESULT_H__ #define __QRESULT_H__ #include "psqlodbc.h" #include "connection.h" #include "socket.h" #include "columninfo.h" #include "tuple.h" #ifdef __cplusplus extern "C" { #endif typedef enum QueryResultCode_ { PORES_EMPTY_QUERY = 0, PORES_COMMAND_OK, /* a query command that doesn't return * anything was executed properly by the backend */ PORES_TUPLES_OK, /* a query command that returns tuples * was executed properly by the backend, PGresult * contains the resulttuples */ PORES_COPY_OUT, PORES_COPY_IN, PORES_BAD_RESPONSE, /* an unexpected response was recv'd from * the backend */ PORES_NONFATAL_ERROR, PORES_FATAL_ERROR, PORES_NO_MEMORY_ERROR, PORES_FIELDS_OK = 100, /* field information from a query was * successful */ /* PORES_END_TUPLES, */ PORES_INTERNAL_ERROR } QueryResultCode; enum { FQR_FETCHING_TUPLES = 1L /* is fetching tuples from db */ ,FQR_REACHED_EOF = (1L << 1) /* reached eof */ ,FQR_HAS_VALID_BASE = (1L << 2) ,FQR_NEEDS_SURVIVAL_CHECK = (1L << 3) /* check if the cursor is open */ }; struct QResultClass_ { ColumnInfoClass *fields; /* the Column information */ ConnectionClass *conn; /* the connection this result is using * (backend) */ QResultClass *next; /* the following result class */ /* Stuff for declare/fetch tuples */ SQLULEN num_total_read; /* the highest absolute position ever read in + 1 */ SQLULEN count_backend_allocated;/* m(re)alloced count */ SQLULEN num_cached_rows; /* count of tuples kept in backend_tuples member */ SQLLEN fetch_number; /* 0-based index to the tuple to read next */ SQLLEN cursTuple; /* absolute current position in the servr's cursor used to retrieve tuples from the DB */ SQLULEN move_offset; SQLLEN base; /* relative position of rowset start in the current data cache(backend_tuples) */ UInt2 num_fields; /* number of fields in the result */ UInt2 num_key_fields; /* number of key fields in the result */ SQLULEN cache_size; UInt4 rowset_size_include_ommitted; /* PG restriction */ SQLLEN recent_processed_row_count; QueryResultCode rstatus; /* result status */ char sqlstate[8]; char *message; const char *messageref; char *cursor_name; /* The name of the cursor for select statements */ char *command; char *notice; TupleField *backend_tuples; /* data from the backend (the tuple cache) */ TupleField *tupleField; /* current backend tuple being retrieved */ char pstatus; /* processing status */ char aborted; /* was aborted ? */ char flags; /* this result contains keyset etc ? */ char move_direction; /* must move before fetching this result set */ SQLULEN count_keyset_allocated; /* m(re)alloced count */ SQLULEN num_cached_keys; /* count of keys kept in backend_keys member */ KeySet *keyset; SQLLEN key_base; /* relative position of rowset start in the current keyset cache */ UInt2 reload_count; UInt2 rb_alloc; /* count of allocated rollback info */ UInt2 rb_count; /* count of rollback info */ char dataFilled; /* Cache is filled with data ? */ Rollback *rollback; UInt4 ad_alloc; /* count of allocated added info */ UInt4 ad_count; /* count of newly added rows */ KeySet *added_keyset; /* added keyset info */ TupleField *added_tuples; /* added data by myself */ UInt2 dl_alloc; /* count of allocated deleted info */ UInt2 dl_count; /* count of deleted info */ SQLLEN *deleted; /* deleted index info */ KeySet *deleted_keyset; /* deleted keyset info */ UInt2 up_alloc; /* count of allocated updated info */ UInt2 up_count; /* count of updated info */ SQLLEN *updated; /* updated index info */ KeySet *updated_keyset; /* uddated keyset info */ TupleField *updated_tuples; /* uddated data by myself */ }; enum { FQR_HASKEYSET = 1L ,FQR_WITHHOLD = (1L << 1) ,FQR_HOLDPERMANENT = (1L << 2) /* the cursor is alive across transactions */ ,FQR_SYNCHRONIZEKEYS = (1L<<3) /* synchronize the keyset range with that of cthe tuples cache */ }; #define QR_haskeyset(self) (0 != (self->flags & FQR_HASKEYSET)) #define QR_is_withhold(self) (0 != (self->flags & FQR_WITHHOLD)) #define QR_is_permanent(self) (0 != (self->flags & FQR_HOLDPERMANENT)) #define QR_synchronize_keys(self) (0 != (self->flags & FQR_SYNCHRONIZEKEYS)) #define QR_get_fields(self) (self->fields) /* These functions are for retrieving data from the qresult */ #define QR_get_value_backend(self, fieldno) (self->tupleField[fieldno].value) #define QR_get_value_backend_row(self, tupleno, fieldno) ((self->backend_tuples + (tupleno * self->num_fields))[fieldno].value) #define QR_get_value_backend_text(self, tupleno, fieldno) QR_get_value_backend_row(self, tupleno, fieldno) #define QR_get_value_backend_int(self, tupleno, fieldno, isNull) atoi(QR_get_value_backend_row(self, tupleno, fieldno)) /* These functions are used by both manual and backend results */ #define QR_NumResultCols(self) (CI_get_num_fields(self->fields)) #define QR_NumPublicResultCols(self) (QR_haskeyset(self) ? (CI_get_num_fields(self->fields) - self->num_key_fields) : CI_get_num_fields(self->fields)) #define QR_get_fieldname(self, fieldno_) (CI_get_fieldname(self->fields, fieldno_)) #define QR_get_fieldsize(self, fieldno_) (CI_get_fieldsize(self->fields, fieldno_)) #define QR_get_display_size(self, fieldno_) (CI_get_display_size(self->fields, fieldno_)) #define QR_get_atttypmod(self, fieldno_) (CI_get_atttypmod(self->fields, fieldno_)) #define QR_get_field_type(self, fieldno_) (CI_get_oid(self->fields, fieldno_)) #define QR_get_relid(self, fieldno_) (CI_get_relid(self->fields, fieldno_)) #define QR_get_attid(self, fieldno_) (CI_get_attid(self->fields, fieldno_)) /* These functions are used only for manual result sets */ #define QR_get_num_total_tuples(self) (QR_once_reached_eof(self) ? (self->num_total_read + self->ad_count) : self->num_total_read) #define QR_get_num_total_read(self) (self->num_total_read) #define QR_get_num_cached_tuples(self) (self->num_cached_rows) #define QR_set_field_info(self, field_num, name, adtid, adtsize, relid, attid) (CI_set_field_info(self->fields, field_num, name, adtid, adtsize, -1, relid, attid)) #define QR_set_field_info_v(self, field_num, name, adtid, adtsize) (CI_set_field_info(self->fields, field_num, name, adtid, adtsize, -1, 0, 0)) /* status macros */ #define QR_command_successful(self) (self && !(self->rstatus == PORES_BAD_RESPONSE || self->rstatus == PORES_NONFATAL_ERROR || self->rstatus == PORES_FATAL_ERROR || self->rstatus == PORES_NO_MEMORY_ERROR)) #define QR_command_maybe_successful(self) (self && !(self->rstatus == PORES_BAD_RESPONSE || self->rstatus == PORES_FATAL_ERROR || self->rstatus == PORES_NO_MEMORY_ERROR)) #define QR_command_nonfatal(self) ( self->rstatus == PORES_NONFATAL_ERROR) #define QR_set_conn(self, conn_) ( self->conn = conn_ ) #define QR_set_rstatus(self, condition) ( self->rstatus = condition ) #define QR_set_sqlstatus(self, status) strcpy(self->sqlstatus, status) #define QR_set_messageref(self, m) ((self)->messageref = m) #define QR_set_aborted(self, aborted_) ( self->aborted = aborted_) #define QR_set_haskeyset(self) (self->flags |= FQR_HASKEYSET) #define QR_set_synchronize_keys(self) (self->flags |= FQR_SYNCHRONIZEKEYS) #define QR_set_no_cursor(self) ((self)->flags &= ~(FQR_WITHHOLD | FQR_HOLDPERMANENT), (self)->pstatus &= ~FQR_NEEDS_SURVIVAL_CHECK) #define QR_set_withhold(self) (self->flags |= FQR_WITHHOLD) #define QR_set_permanent(self) (self->flags |= FQR_HOLDPERMANENT) #define QR_set_reached_eof(self) (self->pstatus |= FQR_REACHED_EOF) #define QR_set_fetching_tuples(self) (self->pstatus |= FQR_FETCHING_TUPLES) #define QR_set_no_fetching_tuples(self) (self->pstatus &= ~FQR_FETCHING_TUPLES) #define QR_set_has_valid_base(self) (self->pstatus |= FQR_HAS_VALID_BASE) #define QR_set_no_valid_base(self) (self->pstatus &= ~FQR_HAS_VALID_BASE) #define QR_set_survival_check(self) (self->pstatus |= FQR_NEEDS_SURVIVAL_CHECK) #define QR_set_no_survival_check(self) (self->pstatus &= ~FQR_NEEDS_SURVIVAL_CHECK) #define QR_inc_num_cache(self) \ do { \ self->num_cached_rows++; \ if (QR_haskeyset(self)) \ self->num_cached_keys++; \ } while (0) #define QR_set_next_in_cache(self, number) \ do { \ inolog("set the number to %d to read next\n", number); \ self->fetch_number = number; \ } while (0) #define QR_inc_next_in_cache(self) \ do { \ inolog("increased the number %d", self->fetch_number); \ self->fetch_number++; \ inolog("to %d to next read\n", self->fetch_number); \ } while (0) #define QR_get_message(self) ((self)->message ? (self)->message : (self)->messageref) #define QR_get_command(self) (self->command) #define QR_get_notice(self) (self->notice) #define QR_get_rstatus(self) (self->rstatus) #define QR_get_aborted(self) (self->aborted) #define QR_get_conn(self) (self->conn) #define QR_get_cursor(self) (self->cursor_name) #define QR_get_rowstart_in_cache(self) (self->base) #define QR_once_reached_eof(self) ((self->pstatus & FQR_REACHED_EOF) != 0) #define QR_is_fetching_tuples(self) ((self->pstatus & FQR_FETCHING_TUPLES) != 0) #define QR_has_valid_base(self) (0 != (self->pstatus & FQR_HAS_VALID_BASE)) #define QR_needs_survival_check(self) (0 != (self->pstatus & FQR_NEEDS_SURVIVAL_CHECK)) #define QR_aborted(self) (!self || self->aborted) #define QR_get_reqsize(self) (self->rowset_size_include_ommitted) #define QR_stop_movement(self) (self->move_direction = 0) #define QR_is_moving(self) (0 != self->move_direction) #define QR_is_not_moving(self) (0 == self->move_direction) #define QR_set_move_forward(self) (self->move_direction = 1) #define QR_is_moving_forward(self) (1 == self->move_direction) #define QR_set_move_backward(self) (self->move_direction = -1) #define QR_is_moving_backward(self) (-1 == self->move_direction) #define QR_set_move_from_the_last(self) (self->move_direction = 2) #define QR_is_moving_from_the_last(self) (2 == self->move_direction) #define QR_is_moving_not_backward(self) (0 < self->move_direction) /* Core Functions */ QResultClass *QR_Constructor(void); void QR_Destructor(QResultClass *self); TupleField *QR_AddNew(QResultClass *self); BOOL QR_get_tupledata(QResultClass *self, BOOL binary); int QR_next_tuple(QResultClass *self, StatementClass *, int *LastMessageType); int QR_close(QResultClass *self); void QR_on_close_cursor(QResultClass *self); void QR_close_result(QResultClass *self, BOOL destroy); char QR_fetch_tuples(QResultClass *self, ConnectionClass *conn, const char *cursor, int *LastMessageType); void QR_free_memory(QResultClass *self); void QR_set_command(QResultClass *self, const char *msg); void QR_set_message(QResultClass *self, const char *msg); void QR_add_message(QResultClass *self, const char *msg); void QR_set_notice(QResultClass *self, const char *msg); void QR_add_notice(QResultClass *self, const char *msg); void QR_set_num_fields(QResultClass *self, int new_num_fields); /* catalog functions' result only */ void QR_set_fields(QResultClass *self, ColumnInfoClass *); void QR_set_num_cached_rows(QResultClass *, SQLLEN); void QR_set_rowstart_in_cache(QResultClass *, SQLLEN); void QR_inc_rowstart_in_cache(QResultClass *self, SQLLEN base_inc); void QR_set_cache_size(QResultClass *self, SQLLEN cache_size); void QR_set_rowset_size(QResultClass *self, Int4 rowset_size); void QR_set_position(QResultClass *self, SQLLEN pos); void QR_set_cursor(QResultClass *self, const char *name); SQLLEN getNthValid(const QResultClass *self, SQLLEN sta, UWORD orientation, SQLULEN nth, SQLLEN *nearest); #define QR_MALLOC_return_with_error(t, tp, s, a, m, r) \ do { \ if (t = (tp *) malloc(s), NULL == t) \ { \ QR_set_rstatus(a, PORES_NO_MEMORY_ERROR); \ qlog("QR_MALLOC_error\n"); \ QR_free_memory(a); \ QR_set_messageref(a, m); \ return r; \ } \ } while (0) #define QR_REALLOC_return_with_error(t, tp, s, a, m, r) \ do { \ tp *tmp; \ if (tmp = (tp *) realloc(t, s), NULL == tmp) \ { \ QR_set_rstatus(a, PORES_NO_MEMORY_ERROR); \ qlog("QR_REALLOC_error\n"); \ QR_free_memory(a); \ QR_set_messageref(a, m); \ return r; \ } \ t = tmp; \ } while (0) #ifdef __cplusplus } #endif #endif /* __QRESULT_H__ */ psqlodbc-09.03.0300/resource.h000644 001752 000000 00000010374 12335653444 016205 0ustar00saitowheel000000 000000 //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by psqlodbc.rc // #define IDS_BADDSN 1 #define IDS_MSGTITLE 2 #define IDS_ADVANCE_OPTION_DEF 3 #define IDOK2 3 #define IDS_ADVANCE_SAVE 4 #define IDCANCEL2 4 #define IDS_ADVANCE_OPTION_DSN1 5 #define IDS_ADVANCE_OPTION_CON1 6 #define IDS_ADVANCE_OPTION_DSN2 7 #define IDS_ADVANCE_OPTION_CON2 8 #define IDS_ADVANCE_CONNECTION 9 #define DLG_OPTIONS_DRV 102 #define DLG_OPTIONS_DS 103 #define DLG_OPTIONS_GLOBAL 104 #define IDC_DSNAME 400 #define IDC_DSNAMETEXT 401 #define IDC_DESC 404 #define IDC_SERVER 407 #define IDC_DATABASE 408 #define IDC_SSLMODE 409 #define IDS_SSLREQUEST_PREFER 410 #define IDS_SSLREQUEST_ALLOW 411 #define IDS_SSLREQUEST_REQUIRE 412 #define IDS_SSLREQUEST_DISABLE 413 #define IDC_NOTICE_USER 414 #define IDS_SSLREQUEST_VERIFY_CA 415 #define IDS_SSLREQUEST_VERIFY_FULL 416 #define DLG_CONFIG 1001 #define IDC_PORT 1002 #define DLG_DRIVER_CHANGE 1002 #define IDC_USER 1006 #define IDC_PASSWORD 1009 #define DS_READONLY 1011 #define DS_SHOWOIDCOLUMN 1012 #define DS_FAKEOIDINDEX 1013 #define DRV_COMMLOG 1014 #define DS_PG62 1016 #define IDC_DATASOURCE 1018 #define DRV_OPTIMIZER 1019 #define DS_CONNSETTINGS 1020 #define IDC_DRIVER 1021 #define DRV_CONNSETTINGS 1031 #define DRV_UNIQUEINDEX 1032 #define DRV_UNKNOWN_MAX 1035 #define DRV_UNKNOWN_DONTKNOW 1036 #define DRV_READONLY 1037 #define IDC_DESCTEXT 1039 #define DRV_MSG_LABEL 1040 #define DRV_UNKNOWN_LONGEST 1041 #define DRV_TEXT_LONGVARCHAR 1043 #define DRV_UNKNOWNS_LONGVARCHAR 1044 #define DRV_CACHE_SIZE 1045 #define DRV_VARCHAR_SIZE 1046 #define DRV_LONGVARCHAR_SIZE 1047 #define IDDEFAULTS 1048 #define DRV_USEDECLAREFETCH 1049 #define DRV_BOOLS_CHAR 1050 #define DS_SHOWSYSTEMTABLES 1051 #define DRV_EXTRASYSTABLEPREFIXES 1051 #define DS_ROWVERSIONING 1052 #define DRV_PARSE 1052 #define DRV_CANCELASFREESTMT 1053 #define IDC_OPTIONS 1054 #define DRV_KSQO 1055 #define DS_PG64 1057 #define DS_PG63 1058 #define DRV_OR_DSN 1059 #define DRV_DEBUG 1060 #define DS_DISALLOWPREMATURE 1061 #define DS_LFCONVERSION 1062 #define DS_TRUEISMINUS1 1063 #define DS_UPDATABLECURSORS 1064 #define IDNEXTPAGE 1065 #define IDPREVPAGE 1066 #define DS_INT8_AS_DEFAULT 1067 #define DS_INT8_AS_BIGINT 1068 #define DS_INT8_AS_NUMERIC 1069 #define DS_INT8_AS_VARCHAR 1070 #define DS_INT8_AS_DOUBLE 1071 #define DS_INT8_AS_INT4 1072 #define DRV_MSG_LABEL2 1073 #define DS_BYTEAASLONGVARBINARY 1073 #define IDAPPLY 1074 #define DS_SERVERSIDEPREPARE 1075 #define IDC_DRIVERNAME 1076 #define IDC_MANAGEDSN 1077 #define IDC_DRIVER_LIST 1078 #define DS_PG74 1079 #define DS_NO_ROLLBACK 1080 #define DS_TRANSACTION_ROLLBACK 1081 #define DS_STATEMENT_ROLLBACK 1082 #define DRV_DTCLOG 1083 #define DS_EXTRA_OPTIONS 1084 #define IDC_TEST 1085 #define DS_LOGDIR 1086 #define DS_GSSAUTHUSEGSSAPI 1087 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 105 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1088 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif psqlodbc-09.03.0300/socket.h000644 001752 000000 00000014405 12335653444 015645 0ustar00saitowheel000000 000000 /* File: socket.h * * Description: See "socket.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __SOCKET_H__ #define __SOCKET_H__ #include "psqlodbc.h" #if defined (USE_GSS) #ifdef HAVE_GSSAPI_H #include #else #include #endif #endif #ifndef WIN32 #include #define WSAAPI #ifdef HAVE_POLL #include #endif /* HAVE_POLL */ #include #include #include #include #include #include #include #include #define closesocket(xxx) close(xxx) #define SOCKETFD int #ifndef INADDR_NONE #ifndef _IN_ADDR_T #define _IN_ADDR_T typedef unsigned int in_addr_t; #endif /* _IN_ADDR_T */ #define INADDR_NONE ((in_addr_t)-1) #endif /* _IN_ADDR_NONE */ #define SOCK_ERRNO errno #define SOCK_ERRNO_SET(e) (errno = e) #ifdef HAVE_SYS_UN_H #define HAVE_UNIX_SOCKETS #endif /* HAVE_SYS_UN_H */ #else #include #include #if defined(_MSC_VER) && (_MSC_VER < 1300) /* * The order of the structure elements on Win32 doesn't match the * order specified in the standard, but we have to match it for * IPv6 to work. */ #define AI_PASSIVE 0x1 // Socket address will be used in bind() call. #define AI_CANONNAME 0x2 // Return canonical name in first ai_canonname. #define AI_NUMERICHOST 0x4 // Nodename must be a numeric address string. #define NI_NUMERICHOST 1 #define _SS_MAXSIZE 128 #define _SS_ALIGNSIZE (sizeof(__int64)) #define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof (short)) #define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof (short) + _SS_PAD1SIZE + _SS_ALIGNSIZE)) typedef int socklen_t; struct sockaddr_storage { short ss_family; char __ss_pad1[_SS_PAD1SIZE]; __int64 __ss_align; char __ss_pad2[_SS_PAD2SIZE]; }; struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; size_t ai_addrlen; char *ai_canonname; struct sockaddr *ai_addr; struct addrinfo *ai_next; }; #endif /* _MSC_VER */ #define SOCKETFD SOCKET #define SOCK_ERRNO (WSAGetLastError()) #define SOCK_ERRNO_SET(e) WSASetLastError(e) #ifndef EINTR #define EINTR WSAEINTR #endif /* EINTR */ #ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK #endif /* EWOULDBLOCK */ #ifndef ECONNRESET #define ECONNRESET WSAECONNRESET #endif /* ECONNRESET */ #ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS #endif /* EINPROGRESS */ #endif /* WIN32 */ typedef void (WSAAPI *freeaddrinfo_func) (struct addrinfo *); typedef int (WSAAPI *getaddrinfo_func) (const char *, const char *, const struct addrinfo *, struct addrinfo **); typedef int (WSAAPI *getnameinfo_func) (const struct sockaddr *, socklen_t, char *, size_t, char *, size_t, int); typedef int (WSAAPI *inet_pton_func) (int, const char *, void *); #ifdef MSG_NOSIGNAL #define SEND_FLAG MSG_NOSIGNAL #define RECV_FLAG MSG_NOSIGNAL #elif defined(MSG_NOSIGPIPE) #define SEND_FLAG MSG_NOSIGPIPE #define RECV_FLAG MSG_NOSIGPIPE #else #define SEND_FLAG 0 #define RECV_FLAG 0 #endif /* MSG_NOSIGNAL */ #define SOCKET_ALREADY_CONNECTED 1 #define SOCKET_HOST_NOT_FOUND 2 #define SOCKET_COULD_NOT_CREATE_SOCKET 3 #define SOCKET_COULD_NOT_CONNECT 4 #define SOCKET_READ_ERROR 5 #define SOCKET_WRITE_ERROR 6 #define SOCKET_NULLPOINTER_PARAMETER 7 #define SOCKET_PUT_INT_WRONG_LENGTH 8 #define SOCKET_GET_INT_WRONG_LENGTH 9 #define SOCKET_CLOSED 10 #define SOCKET_READ_TIMEOUT 11 #define SOCKET_WRITE_TIMEOUT 12 struct SocketClass_ { int buffer_size; int buffer_filled_in; int buffer_filled_out; int buffer_read_in; UCHAR *buffer_in; UCHAR *buffer_out; SOCKETFD socket; unsigned int pversion; int reslen; char *_errormsg_; int errornumber; int sadr_len; struct sockaddr_storage sadr_area; /* Used for various connections */ #ifdef USE_SSPI UInt4 sspisvcs; void *ssd; #endif /* USE_SSPI */ #ifdef USE_SSL /* SSL stuff */ void *ssl; /* libpq ssl */ #endif /* USE_SSL */ #ifdef USE_LIBPQ void *pqconn; /* libpq PGConn */ BOOL via_libpq; /* using libpq library ? */ #endif /* USE_LIBPQ */ #ifdef USE_GSS gss_ctx_id_t gctx; /* GSS context */ gss_name_t gtarg_nam; /* GSS target name */ #endif /* USE_GSS */ char reverse; /* used to handle Postgres 6.2 protocol * (reverse byte order) */ char keepalive; /* TCP keepalive */ }; #define SOCK_get_char(self) (SOCK_get_next_byte(self, FALSE)) #define SOCK_put_char(self, c) (SOCK_put_next_byte(self, c)) /* error functions */ #define SOCK_get_errcode(self) (self ? self->errornumber : SOCKET_CLOSED) #define SOCK_get_errmsg(self) (self ? self->_errormsg_ : "socket closed") /* * code taken from postgres libpq et al. */ #ifndef WIN32 #define DEFAULT_PGSOCKET_DIR "/tmp" #define UNIXSOCK_PATH(sun, port, defpath) \ snprintf((sun)->sun_path, sizeof((sun)->sun_path), "%s/.s.PGSQL.%d", \ ((defpath) && *(defpath) != '\0') ? (defpath) : \ DEFAULT_PGSOCKET_DIR, \ (port)) /* * We do this because sun_len is in BSD's struct, while others don't. * We never actually set BSD's sun_len, and I can't think of a * platform-safe way of doing it, but the code still works. bjm */ #ifndef offsetof #define offsetof(type, field) ((long) &((type *)0)->field) #endif /* offsetof */ #if defined(SUN_LEN) #define UNIXSOCK_LEN(sun) SUN_LEN(sun) #else #define UNIXSOCK_LEN(sun) \ (strlen((sun)->sun_path) + offsetof(struct sockaddr_un, sun_path)) #endif /* SUN_LEN */ #endif /* WIN32 */ /* * END code taken from postgres libpq et al. */ /* Socket prototypes */ SocketClass *SOCK_Constructor(const ConnectionClass *conn); void SOCK_Destructor(SocketClass *self); char SOCK_connect_to(SocketClass *self, unsigned short port, char *hostname, long timeout); int SOCK_get_id(SocketClass *self); void SOCK_get_n_char(SocketClass *self, char *buffer, Int4 len); void SOCK_put_n_char(SocketClass *self, const char *buffer, size_t len); BOOL SOCK_get_string(SocketClass *self, char *buffer, Int4 bufsize); void SOCK_put_string(SocketClass *self, const char *string); int SOCK_get_int(SocketClass *self, short len); void SOCK_put_int(SocketClass *self, int value, short len); Int4 SOCK_flush_output(SocketClass *self); UCHAR SOCK_get_next_byte(SocketClass *self, BOOL peek); void SOCK_put_next_byte(SocketClass *self, UCHAR next_byte); Int4 SOCK_get_response_length(SocketClass *self); #endif /* __SOCKET_H__ */ psqlodbc-09.03.0300/statement.h000644 001752 000000 00000046574 12335653444 016375 0ustar00saitowheel000000 000000 /* File: statement.h * * Description: See "statement.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __STATEMENT_H__ #define __STATEMENT_H__ #include "psqlodbc.h" #include #include "pgtypes.h" #include "bind.h" #include "descriptor.h" #if defined (POSIX_MULTITHREAD_SUPPORT) #include #endif typedef enum { STMT_ALLOCATED, /* The statement handle is allocated, but * not used so far */ STMT_READY, /* the statement is waiting to be executed */ STMT_PREMATURE, /* ODBC states that it is legal to call * e.g. SQLDescribeCol before a call to * SQLExecute, but after SQLPrepare. To * get all the necessary information in * such a case, we simply execute the * query _before_ the actual call to * SQLExecute, so that statement is * considered to be "premature". */ STMT_FINISHED, /* statement execution has finished */ STMT_EXECUTING /* statement execution is still going on */ } STMT_Status; /* * ERROR status code * * The code for warnings must be minus * and LOWEST_STMT_ERROR must be set to * the least code number. * The code for STMT_OK is 0 and error * codes follow after it. */ enum { LOWEST_STMT_ERROR = (-6) /* minus values mean warning returns */ ,STMT_ERROR_IN_ROW = (-6) ,STMT_OPTION_VALUE_CHANGED = (-5) ,STMT_ROW_VERSION_CHANGED = (-4) ,STMT_POS_BEFORE_RECORDSET = (-3) ,STMT_TRUNCATED = (-2) ,STMT_INFO_ONLY = (-1) /* not an error message, * just a notification * to be returned by * SQLError */ ,STMT_OK = 0 ,STMT_EXEC_ERROR ,STMT_STATUS_ERROR ,STMT_SEQUENCE_ERROR ,STMT_NO_MEMORY_ERROR ,STMT_COLNUM_ERROR ,STMT_NO_STMTSTRING ,STMT_ERROR_TAKEN_FROM_BACKEND ,STMT_INTERNAL_ERROR ,STMT_STILL_EXECUTING ,STMT_NOT_IMPLEMENTED_ERROR ,STMT_BAD_PARAMETER_NUMBER_ERROR ,STMT_OPTION_OUT_OF_RANGE_ERROR ,STMT_INVALID_COLUMN_NUMBER_ERROR ,STMT_RESTRICTED_DATA_TYPE_ERROR ,STMT_INVALID_CURSOR_STATE_ERROR ,STMT_CREATE_TABLE_ERROR ,STMT_NO_CURSOR_NAME ,STMT_INVALID_CURSOR_NAME ,STMT_INVALID_ARGUMENT_NO ,STMT_ROW_OUT_OF_RANGE ,STMT_OPERATION_CANCELLED ,STMT_INVALID_CURSOR_POSITION ,STMT_VALUE_OUT_OF_RANGE ,STMT_OPERATION_INVALID ,STMT_PROGRAM_TYPE_OUT_OF_RANGE ,STMT_BAD_ERROR ,STMT_INVALID_OPTION_IDENTIFIER ,STMT_RETURN_NULL_WITHOUT_INDICATOR ,STMT_INVALID_DESCRIPTOR_IDENTIFIER ,STMT_OPTION_NOT_FOR_THE_DRIVER ,STMT_FETCH_OUT_OF_RANGE ,STMT_COUNT_FIELD_INCORRECT ,STMT_INVALID_NULL_ARG ,STMT_NO_RESPONSE ,STMT_COMMUNICATION_ERROR }; /* statement types */ enum { STMT_TYPE_UNKNOWN = -2 ,STMT_TYPE_OTHER = -1 ,STMT_TYPE_SELECT = 0 ,STMT_TYPE_INSERT ,STMT_TYPE_UPDATE ,STMT_TYPE_DELETE ,STMT_TYPE_WITH ,STMT_TYPE_CREATE ,STMT_TYPE_ALTER ,STMT_TYPE_DROP ,STMT_TYPE_GRANT ,STMT_TYPE_REVOKE ,STMT_TYPE_PROCCALL ,STMT_TYPE_LOCK ,STMT_TYPE_TRANSACTION ,STMT_TYPE_CLOSE ,STMT_TYPE_FETCH ,STMT_TYPE_PREPARE ,STMT_TYPE_EXECUTE ,STMT_TYPE_DEALLOCATE ,STMT_TYPE_ANALYZE ,STMT_TYPE_NOTIFY ,STMT_TYPE_EXPLAIN ,STMT_TYPE_SET ,STMT_TYPE_RESET ,STMT_TYPE_DECLARE ,STMT_TYPE_MOVE ,STMT_TYPE_COPY ,STMT_TYPE_START ,STMT_TYPE_SPECIAL }; #define STMT_UPDATE(stmt) (stmt->statement_type > STMT_TYPE_SELECT) /* Parsing status */ enum { STMT_PARSE_NONE = 0 ,STMT_PARSE_COMPLETE /* the driver parsed the statement */ ,STMT_PARSE_INCOMPLETE ,STMT_PARSE_FATAL ,STMT_PARSE_MASK = 3L ,STMT_PARSED_OIDS = (1L << 2) ,STMT_FOUND_KEY = (1L << 3) ,STMT_HAS_ROW_DESCRIPTION = (1L << 4) /* already got the col info */ ,STMT_REFLECTED_ROW_DESCRIPTION = (1L << 5) }; /* transition status */ enum { STMT_TRANSITION_UNALLOCATED = 0 ,STMT_TRANSITION_ALLOCATED = 1 ,STMT_TRANSITION_FETCH_SCROLL = 6 ,STMT_TRANSITION_EXTENDED_FETCH = 7 }; /* Result style */ enum { STMT_FETCH_NONE = 0, STMT_FETCH_NORMAL, STMT_FETCH_EXTENDED }; #define PG_NUM_NORMAL_KEYS 2 typedef RETCODE (*NeedDataCallfunc)(RETCODE, void *); typedef struct { NeedDataCallfunc func; void *data; } NeedDataCallback; /******** Statement Handle ***********/ struct StatementClass_ { ConnectionClass *hdbc; /* pointer to ConnectionClass this * statement belongs to */ QResultClass *result; /* result of the current statement */ QResultClass *curres; /* the current result in the chain */ HSTMT FAR *phstmt; StatementOptions options; StatementOptions options_orig; /* attached descriptor handles */ ARDClass *ard; APDClass *apd; IRDClass *ird; IPDClass *ipd; /* implicit descriptor handles */ ARDClass ardi; IRDClass irdi; APDClass apdi; IPDClass ipdi; STMT_Status status; char *__error_message; int __error_number; PG_ErrorInfo *pgerror; SQLLEN currTuple; /* current absolute row number (GetData, * SetPos, SQLFetch) */ GetDataInfo gdata_info; SQLLEN save_rowset_size; /* saved rowset size in case of * change/FETCH_NEXT */ SQLLEN rowset_start; /* start of rowset (an absolute row * number) */ SQLSETPOSIROW bind_row; /* current offset for Multiple row/column * binding */ Int2 current_col; /* current column for GetData -- used to * handle multiple calls */ SQLLEN last_fetch_count; /* number of rows retrieved in * last fetch/extended fetch */ int lobj_fd; /* fd of the current large object */ char *statement; /* if non--null pointer to the SQL * statement that has been executed */ TABLE_INFO **ti; Int2 ntab; Int2 num_key_fields; Int2 statement_type; /* According to the defines above */ Int2 num_params; Int2 data_at_exec; /* Number of params needing SQLPutData */ Int2 current_exec_param; /* The current parameter for * SQLPutData */ UDWORD iflag; /* PGAPI_AllocStmt parameter */ PutDataInfo pdata_info; po_ind_t parse_status; po_ind_t proc_return; po_ind_t put_data; /* Has SQLPutData been called ? */ po_ind_t catalog_result; /* Is this a result of catalog function ? */ po_ind_t prepare; /* is this a prepared statement ? */ po_ind_t prepared; /* is this statement already * prepared at the server ? */ po_ind_t internal; /* Is this statement being called * internally ? */ po_ind_t transition_status; /* Transition status */ po_ind_t multi_statement; /* -1:unknown 0:single 1:multi */ po_ind_t rbonerr; /* rollback on error */ po_ind_t discard_output_params; /* discard output parameters on parse stage */ po_ind_t cancel_info; /* cancel information */ po_ind_t ref_CC_error; /* refer to CC_error ? */ po_ind_t lock_CC_for_rb; /* lock CC for statement rollback ? */ po_ind_t join_info; /* have joins ? */ po_ind_t parse_method; /* parse_statement is forced or ? */ po_ind_t curr_param_result; /* current param result is set ? */ pgNAME cursor_name; char *plan_name; char *stmt_with_params; /* statement after parameter * substitution */ Int4 stmt_size_limit; /* PG restriction */ SQLLEN exec_start_row; SQLLEN exec_end_row; SQLLEN exec_current_row; po_ind_t pre_executing; /* This statement is prematurely executing */ po_ind_t inaccurate_result; /* Current status is PREMATURE but * result is inaccurate */ unsigned char miscinfo; po_ind_t updatable; SQLLEN diag_row_count; char *load_statement; /* to (re)load updatable individual rows */ char *execute_statement; /* to execute the prepared plans */ Int4 from_pos; Int4 where_pos; SQLLEN last_fetch_count_include_ommitted; time_t stmt_time; /* SQL_NEED_DATA Callback list */ StatementClass *execute_delegate; StatementClass *execute_parent; UInt2 allocated_callbacks; UInt2 num_callbacks; NeedDataCallback *callbacks; #if defined(WIN_MULTITHREAD_SUPPORT) CRITICAL_SECTION cs; #elif defined(POSIX_THREADMUTEX_SUPPORT) pthread_mutex_t cs; #endif /* WIN_MULTITHREAD_SUPPORT */ }; #define SC_get_conn(a) (a->hdbc) void SC_init_Result(StatementClass *self); void SC_set_Result(StatementClass *self, QResultClass *res); #define SC_get_Result(a) (a->result) #define SC_set_Curres(a, b) (a->curres = b) #define SC_get_Curres(a) (a->curres) #define SC_get_ARD(a) (a->ard) #define SC_get_APD(a) (a->apd) #define SC_get_IRD(a) (a->ird) #define SC_get_IPD(a) (a->ipd) #define SC_get_ARDF(a) (&(SC_get_ARD(a)->ardopts)) #define SC_get_APDF(a) (&(SC_get_APD(a)->apdopts)) #define SC_get_IRDF(a) (&(SC_get_IRD(a)->irdopts)) #define SC_get_IPDF(a) (&(SC_get_IPD(a)->ipdopts)) #define SC_get_ARDi(a) (&(a->ardi)) #define SC_get_APDi(a) (&(a->apdi)) #define SC_get_IRDi(a) (&(a->irdi)) #define SC_get_IPDi(a) (&(a->ipdi)) #define SC_get_GDTI(a) (&(a->gdata_info)) #define SC_get_PDTI(a) (&(a->pdata_info)) #define SC_get_errornumber(a) (a->__error_number) #define SC_set_errornumber(a, n) (a->__error_number = n) #define SC_get_errormsg(a) (a->__error_message) #define SC_get_errormsg(a) (a->__error_message) #define SC_is_prepare_statement(a) (0 != (a->prepare & PREPARE_STATEMENT)) #define SC_get_prepare_method(a) (a->prepare & (~PREPARE_STATEMENT)) #define SC_parsed_status(a) (a->parse_status & STMT_PARSE_MASK) #define SC_set_parse_status(a, s) (a->parse_status |= s) #define SC_update_not_ready(a) (SC_parsed_status(a) == STMT_PARSE_NONE || 0 == (a->parse_status & STMT_PARSED_OIDS)) #define SC_update_ready(a) (SC_parsed_status(a) == STMT_PARSE_COMPLETE && 0 != (a->parse_status & STMT_FOUND_KEY) && a->updatable) #define SC_set_checked_hasoids(a, b) (a->parse_status |= (STMT_PARSED_OIDS | (b ? STMT_FOUND_KEY : 0))) #define SC_checked_hasoids(a) (0 != (a->parse_status & STMT_PARSED_OIDS)) #define SC_set_delegate(p, c) (p->execute_delegate = c, c->execute_parent = p) #define SC_is_updatable(s) (0 < ((s)->updatable)) #define SC_reset_updatable(s) ((s)->updatable = -1) #define SC_set_updatable(s, b) ((s)->updatable = (b)) #define SC_clear_parse_method(s) ((s)->parse_method = 0) #define SC_is_parse_forced(s) (0 != ((s)->parse_method & 1L)) #define SC_set_parse_forced(s) ((s)->parse_method |= 1L) #define SC_is_parse_tricky(s) (0 != ((s)->parse_method & 2L)) #define SC_set_parse_tricky(s) ((s)->parse_method |= 2L) #define SC_no_parse_tricky(s) ((s)->parse_method &= ~2L) #define SC_cursor_is_valid(s) (NAME_IS_VALID(s->cursor_name)) #define SC_cursor_name(s) (SAFE_NAME(s->cursor_name)) void SC_reset_delegate(RETCODE, StatementClass *); StatementClass *SC_get_ancestor(StatementClass *); #if (ODBCVER >= 0x0300) #define SC_is_lower_case(a, b) (a->options.metadata_id || b->connInfo.lower_case_identifier) #else #define SC_is_lower_case(a, b) (b->connInfo.lower_case_identifier) #endif /* ODBCVER */ #define SC_MALLOC_return_with_error(t, tp, s, a, m, r) \ do { \ if (t = (tp *) malloc(s), NULL == t) \ { \ SC_set_error(a, STMT_NO_MEMORY_ERROR, m, "SC_MALLOC"); \ return r; \ } \ } while (0) #define SC_REALLOC_return_with_error(t, tp, s, a, m, r) \ do { \ tp *tmp; \ if (tmp = (tp *) realloc(t, s), NULL == tmp) \ { \ SC_set_error(a, STMT_NO_MEMORY_ERROR, m, "SC_REALLOC"); \ return r; \ } \ t = tmp; \ } while (0) /* options for SC_free_params() */ #define STMT_FREE_PARAMS_ALL 0 #define STMT_FREE_PARAMS_DATA_AT_EXEC_ONLY 1 /* prepare state */ enum { NON_PREPARE_STATEMENT = 0 , PREPARE_STATEMENT = 1 , PREPARE_BY_THE_DRIVER = (1L << 1) , USING_PREPARE_COMMAND = (2L << 1) , NAMED_PARSE_REQUEST = (3L << 1) , PARSE_TO_EXEC_ONCE = (4L << 1) , PARSE_REQ_FOR_INFO = (5L << 1) }; /* prepared state */ enum { NOT_YET_PREPARED = 0 ,PREPARING_PERMANENTLY ,PREPARING_TEMPORARILY ,PREPARED_PERMANENTLY ,PREPARED_TEMPORARILY ,ONCE_DESCRIBED }; /* misc info */ #define SC_set_pre_executable(a) (a->miscinfo |= 1L) #define SC_no_pre_executable(a) (a->miscinfo &= ~1L) #define SC_is_pre_executable(a) ((a->miscinfo & 1L) != 0) #define SC_set_fetchcursor(a) (a->miscinfo |= (1L << 1)) #define SC_no_fetchcursor(a) (a->miscinfo &= ~(1L << 1)) #define SC_is_fetchcursor(a) ((a->miscinfo & (1L << 1)) != 0) #define SC_set_concat_prepare_exec(a) (a->miscinfo |= (1L << 2)) #define SC_no_concat_prepare_exec(a) (a->miscinfo &= ~(1L << 2)) #define SC_is_concat_prepare_exec(a) ((a->miscinfo & (1L << 2)) != 0) #define SC_set_with_hold(a) (a->miscinfo |= (1L << 3)) #define SC_set_without_hold(a) (a->miscinfo &= ~(1L << 3)) #define SC_is_with_hold(a) ((a->miscinfo & (1L << 3)) != 0) #define SC_miscinfo_clear(a) (a->miscinfo &= (1L << 3)) #define STMT_HAS_OUTER_JOIN 1L #define STMT_HAS_INNER_JOIN (1L << 1) #define SC_has_join(a) (0 != (a)->join_info) #define SC_has_outer_join(a) (0 != (STMT_HAS_OUTER_JOIN & (a)->join_info)) #define SC_has_inner_join(a) (0 != (STMT_HAS_INNER_JOIN & (a)->join_info)) #define SC_set_outer_join(a) ((a)->join_info |= STMT_HAS_OUTER_JOIN) #define SC_set_inner_join(a) ((a)->join_info |= STMT_HAS_INNER_JOIN) #define SC_start_stmt(a) (a->rbonerr = 0) #define SC_start_tc_stmt(a) (a->rbonerr = (1L << 1)) #define SC_is_tc_stmt(a) ((a->rbonerr & (1L << 1)) != 0) #define SC_start_rb_stmt(a) (a->rbonerr = (1L << 2)) #define SC_is_rb_stmt(a) ((a->rbonerr & (1L << 2)) != 0) #define SC_set_accessed_db(a) (a->rbonerr |= (1L << 3)) #define SC_accessed_db(a) ((a->rbonerr & (1L << 3)) != 0) #define SC_start_rbpoint(a) (a->rbonerr |= (1L << 4)) #define SC_started_rbpoint(a) ((a->rbonerr & (1L << 4)) != 0) #define SC_unref_CC_error(a) ((a->ref_CC_error) = FALSE) #define SC_ref_CC_error(a) ((a->ref_CC_error) = TRUE) void SC_forget_unnamed(StatementClass *self); #define SC_can_parse_statement(a) (STMT_TYPE_SELECT == (a)->statement_type) /* * DECLARE CURSOR + FETCH can only be used with SELECT-type queries. And * it's not currently supported with array-bound parameters. */ #define SC_may_use_cursor(a) \ (SC_get_APDF(a)->paramset_size <= 1 && \ (STMT_TYPE_SELECT == (a)->statement_type || STMT_TYPE_WITH == (a)->statement_type) ) #define SC_may_fetch_rows(a) (STMT_TYPE_SELECT == (a)->statement_type || STMT_TYPE_WITH == (a)->statement_type) #define SC_can_req_colinfo(a) (STMT_TYPE_SELECT == (a)->statement_type || \ STMT_TYPE_WITH == (a)->statement_type || \ ((a)->prepare && \ STMT_TYPE_INSERT <= (a)->statement_type && \ STMT_TYPE_DELETE >= (a)->statement_type && \ SC_get_conn((a))->connInfo.use_server_side_prepare)) #define SC_determine_statement_type(a) (STMT_TYPE_SELECT != (a)->statement_type ? (a)->statement_type : ((a)->statement_type = || statement_type((a)->statement))) /* For Multi-thread */ #if defined(WIN_MULTITHREAD_SUPPORT) #define INIT_STMT_CS(x) InitializeCriticalSection(&((x)->cs)) #define ENTER_STMT_CS(x) EnterCriticalSection(&((x)->cs)) #define TRY_ENTER_STMT_CS(x) TryEnterCriticalSection(&((x)->cs)) #define LEAVE_STMT_CS(x) LeaveCriticalSection(&((x)->cs)) #define DELETE_STMT_CS(x) DeleteCriticalSection(&((x)->cs)) #elif defined(POSIX_THREADMUTEX_SUPPORT) #define INIT_STMT_CS(x) pthread_mutex_init(&((x)->cs),0) #define ENTER_STMT_CS(x) pthread_mutex_lock(&((x)->cs)) #define TRY_ENTER_STMT_CS(x) (0 == pthread_mutex_trylock(&((x)->cs))) #define LEAVE_STMT_CS(x) pthread_mutex_unlock(&((x)->cs)) #define DELETE_STMT_CS(x) pthread_mutex_destroy(&((x)->cs)) #else #define INIT_STMT_CS(x) #define ENTER_STMT_CS(x) #define TRY_ENTER_STMT_CS(x) (1) #define LEAVE_STMT_CS(x) #define DELETE_STMT_CS(x) #endif /* WIN_MULTITHREAD_SUPPORT */ /* Statement prototypes */ StatementClass *SC_Constructor(ConnectionClass *); void InitializeStatementOptions(StatementOptions *opt); char SC_Destructor(StatementClass *self); BOOL SC_opencheck(StatementClass *self, const char *func); RETCODE SC_initialize_and_recycle(StatementClass *self); void SC_initialize_cols_info(StatementClass *self, BOOL DCdestroy, BOOL parseReset); int statement_type(const char *statement); char parse_statement(StatementClass *stmt, BOOL); char parse_sqlsvr(StatementClass *stmt); SQLRETURN SC_set_SS_columnkey(StatementClass *stmt); Int4 SC_pre_execute(StatementClass *self); char SC_unbind_cols(StatementClass *self); char SC_recycle_statement(StatementClass *self); void SC_clear_error(StatementClass *self); void SC_set_error(StatementClass *self, int errnum, const char *msg, const char *func); void SC_set_errormsg(StatementClass *self, const char *msg); void SC_error_copy(StatementClass *self, const StatementClass *from, BOOL); void SC_full_error_copy(StatementClass *self, const StatementClass *from, BOOL); void SC_replace_error_with_res(StatementClass *self, int errnum, const char *msg, const QResultClass*, BOOL); void SC_set_prepared(StatementClass *self, int); void SC_set_planname(StatementClass *self, const char *plan_name); void SC_set_rowset_start(StatementClass *self, SQLLEN, BOOL); void SC_inc_rowset_start(StatementClass *self, SQLLEN); RETCODE SC_initialize_stmts(StatementClass *self, BOOL); RETCODE SC_execute(StatementClass *self); RETCODE SC_fetch(StatementClass *self); void SC_free_params(StatementClass *self, char option); void SC_log_error(const char *func, const char *desc, const StatementClass *self); time_t SC_get_time(StatementClass *self); SQLULEN SC_get_bookmark(StatementClass *self); RETCODE SC_pos_reload(StatementClass *self, SQLULEN index, UInt2 *, Int4); RETCODE SC_pos_update(StatementClass *self, SQLSETPOSIROW irow, SQLULEN index); RETCODE SC_pos_delete(StatementClass *self, SQLSETPOSIROW irow, SQLULEN index); RETCODE SC_pos_refresh(StatementClass *self, SQLSETPOSIROW irow, SQLULEN index); RETCODE SC_pos_add(StatementClass *self, SQLSETPOSIROW irow); int SC_set_current_col(StatementClass *self, int col); void SC_setInsertedTable(StatementClass *, RETCODE); void SC_scanQueryAndCountParams(const char *, const ConnectionClass *, Int4 *next_cmd, SQLSMALLINT *num_params, po_ind_t *multi, po_ind_t *proc_return); BOOL SC_IsExecuting(const StatementClass *self); BOOL SC_SetExecuting(StatementClass *self, BOOL on); BOOL SC_SetCancelRequest(StatementClass *self); BOOL SC_AcceptedCancelRequest(const StatementClass *self); int enqueueNeedDataCallback(StatementClass *self, NeedDataCallfunc, void *); RETCODE dequeueNeedDataCallback(RETCODE, StatementClass *self); void cancelNeedDataState(StatementClass *self); int StartRollbackState(StatementClass *self); RETCODE SetStatementSvp(StatementClass *self); RETCODE DiscardStatementSvp(StatementClass *self, RETCODE, BOOL errorOnly); BOOL SendParseRequest(StatementClass *self, const char *name, const char *query, Int4 qlen, Int2 num_params); BOOL SyncParseRequest(ConnectionClass *conn); BOOL SendDescribeRequest(StatementClass *self, const char *name, BOOL paramAlso); BOOL SendBindRequest(StatementClass *self, const char *name); BOOL BuildBindRequest(StatementClass *stmt, const char *name); BOOL SendExecuteRequest(StatementClass *stmt, const char *portal, UInt4 count); QResultClass *SendSyncAndReceive(StatementClass *stmt, QResultClass *res, const char *comment); /* * Macros to convert global index <-> relative index in resultset/rowset */ /* a global index to the relative index in a rowset */ #define SC_get_rowset_start(stmt) (stmt->rowset_start) #define GIdx2RowIdx(gidx, stmt) (gidx - stmt->rowset_start) /* a global index to the relative index in a resultset(not a rowset) */ #define GIdx2CacheIdx(gidx, s, r) (gidx - (QR_has_valid_base(r) ? (s->rowset_start - r->base) : 0)) #define GIdx2KResIdx(gidx, s, r) (gidx - (QR_has_valid_base(r) ? (s->rowset_start - r->key_base) : 0)) /* a relative index in a rowset to the global index */ #define RowIdx2GIdx(ridx, stmt) (ridx + stmt->rowset_start) /* a relative index in a resultset to the global index */ #define CacheIdx2GIdx(ridx, stmt, res) (ridx - res->base + stmt->rowset_start) #define KResIdx2GIdx(ridx, stmt, res) (ridx - res->key_base + stmt->rowset_start) #define BOOKMARK_SHIFT 1 #define SC_make_bookmark(b) ((b < 0) ? (b) : (b + BOOKMARK_SHIFT)) #define SC_resolve_bookmark(b) ((b < 0) ? (b) : (b - BOOKMARK_SHIFT)) #endif /* __STATEMENT_H__ */ psqlodbc-09.03.0300/tuple.h000644 001752 000000 00000004151 12335653444 015503 0ustar00saitowheel000000 000000 /* File: tuple.h * * Description: See "tuple.c" * * Important NOTE: The TupleField structure is used both to hold backend data and manual result set data. The "set_" functions are only used for manual result sets by info routines. * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __TUPLE_H__ #define __TUPLE_H__ #include "psqlodbc.h" /* Used by backend data AND manual result sets */ struct TupleField_ { Int4 len; /* PG length of the current Tuple */ void *value; /* an array representing the value */ }; /* keyset(TID + OID) info */ struct KeySet_ { UWORD status; UInt2 offset; UInt4 blocknum; OID oid; }; /* Rollback(index + original TID) info */ struct Rollback_ { SQLLEN index; UInt4 blocknum; UInt2 offset; UWORD option; }; #define KEYSET_INFO_PUBLIC 0x07 #define CURS_SELF_ADDING (1L << 3) #define CURS_SELF_DELETING (1L << 4) #define CURS_SELF_UPDATING (1L << 5) #define CURS_SELF_ADDED (1L << 6) #define CURS_SELF_DELETED (1L << 7) #define CURS_SELF_UPDATED (1L << 8) #define CURS_NEEDS_REREAD (1L << 9) #define CURS_IN_ROWSET (1L << 10) #define CURS_OTHER_DELETED (1L << 11) /* These macros are wrappers for the corresponding set_tuplefield functions but these handle automatic NULL determination and call set_tuplefield_null() if appropriate for the datatype (used by SQLGetTypeInfo). */ #define set_nullfield_string(FLD, VAL) ((VAL) ? set_tuplefield_string(FLD, (VAL)) : set_tuplefield_null(FLD)) #define set_nullfield_int2(FLD, VAL) ((VAL) != -1 ? set_tuplefield_int2(FLD, (VAL)) : set_tuplefield_null(FLD)) #define set_nullfield_int4(FLD, VAL) ((VAL) != -1 ? set_tuplefield_int4(FLD, (VAL)) : set_tuplefield_null(FLD)) void set_tuplefield_null(TupleField *tuple_field); void set_tuplefield_string(TupleField *tuple_field, const char *string); void set_tuplefield_int2(TupleField *tuple_field, Int2 value); void set_tuplefield_int4(TupleField *tuple_field, Int4 value); SQLLEN ClearCachedRows(TupleField *tuple, int num_fields, SQLLEN num_rows); SQLLEN ReplaceCachedRows(TupleField *otuple, const TupleField *ituple, int num_fields, SQLLEN num_rows); #endif psqlodbc-09.03.0300/version.h000644 001752 000000 00000001176 12335653444 016043 0ustar00saitowheel000000 000000 /* File: version.h * * Description: This file defines the driver version. * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __VERSION_H__ #define __VERSION_H__ /* * BuildAll may pass POSTGRESDRIVERVERSION, POSTGRES_RESOURCE_VERSION * and PG_DRVFILE_VERSION via winbuild/psqlodbc.vcxproj. */ #ifndef POSTGRESDRIVERVERSION #define POSTGRESDRIVERVERSION "09.03.0300" #endif #ifndef POSTGRES_RESOURCE_VERSION #define POSTGRES_RESOURCE_VERSION POSTGRESDRIVERVERSION #endif #ifndef PG_DRVFILE_VERSION #define PG_DRVFILE_VERSION 9,3,03,00 #endif #define PG_BUILD_VERSION "201405140001" #endif psqlodbc-09.03.0300/loadlib.h000644 001752 000000 00000002027 12335653444 015760 0ustar00saitowheel000000 000000 /* File: loadlib.h * * Description: See "loadlib.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __LOADLIB_H__ #define __LOADLIB_H__ #include "psqlodbc.h" #ifdef HAVE_LIBLTDL #include #else #ifdef HAVE_DLFCN_H #include #endif /* HAVE_DLFCN_H */ #endif /* HAVE_LIBLTDL */ #include #ifdef __cplusplus extern "C" { #endif BOOL SSLLIB_check(void); #ifdef USE_LIBPQ void *CALL_PQconnectdb(const char *conninfo, BOOL *); void *CALL_PQconnectdbParams(const char *opts[], const char *vals[], BOOL *); #endif /* USE_LIBPQ */ BOOL ssl_verify_available(void); BOOL connect_with_param_available(void); #ifdef _HANDLE_ENLIST_IN_DTC_ RETCODE CALL_EnlistInDtc(ConnectionClass *conn, void * pTra, int method); RETCODE CALL_DtcOnDisconnect(ConnectionClass *); RETCODE CALL_IsolateDtcConn(ConnectionClass *, BOOL); #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* void UnloadDelayLoadedDLLs(BOOL); */ void CleanupDelayLoadedDLLs(void); #ifdef __cplusplus } #endif #endif /* __LOADLIB_H__ */ psqlodbc-09.03.0300/pgenlist.h000644 001752 000000 00000001122 12335653444 016172 0ustar00saitowheel000000 000000 /* File: enlist.h * * Description: See "msdtc_enlist.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __PGENLIST_H__ #define __PGENLIST_H__ #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 #ifdef _HANDLE_ENLIST_IN_DTC_ RETCODE EnlistInDtc(void *conn, void *pTra, int method); RETCODE DtcOnDisconnect(void *); RETCODE IsolateDtcConn(void *, BOOL continueConnection); const char *GetXaLibName(void); const char *GetXaLibPath(void); #endif /* _HANDLE_ENLIST_IN_DTC_ */ #endif /* WIN32 */ #ifdef __cplusplus } #endif #endif /* __PGENLIST_H__ */ psqlodbc-09.03.0300/mylog.h000644 001752 000000 00000005104 12335653444 015500 0ustar00saitowheel000000 000000 /* File: mylog.h * * Description: See "mylog.c" * * Comments: See "notice.txt" for copyright and license information. * */ #ifndef __MYLOG_H__ #define __MYLOG_H__ #undef DLL_DECLARE #ifdef WIN32 #ifdef _MYLOG_FUNCS_IMPLEMENT_ #define DLL_DECLARE _declspec(dllexport) #else #ifdef _MYLOG_FUNCS_IMPORT_ #define DLL_DECLARE _declspec(dllimport) #else #define DLL_DECLARE #endif /* _MYLOG_FUNCS_IMPORT_ */ #endif /* _MYLOG_FUNCS_IMPLEMENT_ */ #else #define DLL_DECLARE #endif /* WIN32 */ #include #ifndef WIN32 #include #endif #ifdef __cplusplus extern "C" { #endif /* Uncomment MY_LOG define to compile in the mylog() statements. Then, debug logging will occur if 'Debug' is set to 1 in the ODBCINST.INI portion of the registry. You may have to manually add this key. This logfile is intended for development use, not for an end user! */ #define MY_LOG /* Uncomment Q_LOG to compile in the qlog() statements (Communications log, i.e. CommLog). This logfile contains serious log statements that are intended for an end user to be able to read and understand. It is controlled by the 'CommLog' flag in the ODBCINST.INI portion of the registry (see above), which is manipulated on the setup/connection dialog boxes. */ #define Q_LOG #ifdef MY_LOG DLL_DECLARE void mylog(const char *fmt,...); DLL_DECLARE void forcelog(const char *fmt,...); #define inolog if (get_mylog() > 1) mylog /* for really temporary debug */ #else /* MY_LOG */ #ifndef WIN32 #define mylog(args...) /* GNU convention for variable arguments */ #define forcelog(args...) /* GNU convention for variable arguments */ #define inolog(args...) /* GNU convention for variable arguments */ #else #define _DUMMY_LOG_IMPL_ static void DumLog(const char *fmt,...) {} #define mylog if (0) DumLog /* mylog */ #define forcelog if (0) DumLog /* forcelog */ #define inolog if (0) DumLog /* inolog */ #endif /* WIN32 */ #endif /* MY_LOG */ #ifdef Q_LOG extern void qlog(char *fmt,...); #define inoqlog if (get_qlog() > 1) qlog /* for really temporary debug */ #else #ifndef WIN32 #define qlog(args...) /* GNU convention for variable arguments */ #define inoqlog(args...) /* GNU convention for variable arguments */ #else #ifndef _DUMMY_LOG_IMPL_ #define _DUMMY_LOG_IMPL_ static void DumLog(const char *fmt,...) {} #endif /* _DUMMY_LOG_IMPL_ */ #define qlog if (0) DumLog /* qlog */ #define inoqlog if (0) DumLog /* inoqlog */ #endif /* WIN32 */ #endif /* QLOG */ int get_qlog(void); int get_mylog(void); void InitializeLogging(void); void FinalizeLogging(void); #ifdef __cplusplus } #endif #endif /* __MYLOG_H__ */ psqlodbc-09.03.0300/odbcapi30w.c000644 001752 000000 00000024206 12335653444 016303 0ustar00saitowheel000000 000000 /*------- * Module: odbcapi30w.c * * Description: This module contains UNICODE routines * * Classes: n/a * * API functions: SQLColAttributeW, SQLGetStmtAttrW, SQLSetStmtAttrW, SQLSetConnectAttrW, SQLGetConnectAttrW, SQLGetDescFieldW, SQLGetDescRecW, SQLGetDiagFieldW, SQLGetDiagRecW, *------- */ #include "psqlodbc.h" #if (ODBCVER >= 0x0300) #include #include #include "pgapifunc.h" #include "connection.h" #include "statement.h" RETCODE SQL_API SQLGetStmtAttrW(SQLHSTMT hstmt, SQLINTEGER fAttribute, PTR rgbValue, SQLINTEGER cbValueMax, SQLINTEGER *pcbValue) { CSTR func = "SQLGetStmtAttrW"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[%s]", func); ENTER_STMT_CS((StatementClass *) hstmt); SC_clear_error((StatementClass *) hstmt); StartRollbackState(stmt); ret = PGAPI_GetStmtAttr(hstmt, fAttribute, rgbValue, cbValueMax, pcbValue); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS((StatementClass *) hstmt); return ret; } RETCODE SQL_API SQLSetStmtAttrW(SQLHSTMT hstmt, SQLINTEGER fAttribute, PTR rgbValue, SQLINTEGER cbValueMax) { CSTR func = "SQLSetStmtAttrW"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_SetStmtAttr(hstmt, fAttribute, rgbValue, cbValueMax); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLGetConnectAttrW(HDBC hdbc, SQLINTEGER fAttribute, PTR rgbValue, SQLINTEGER cbValueMax, SQLINTEGER *pcbValue) { CSTR func = "SQLGetConnectAttrW"; RETCODE ret; mylog("[%s]", func); CC_examine_global_transaction((ConnectionClass *) hdbc); ENTER_CONN_CS((ConnectionClass *) hdbc); CC_clear_error((ConnectionClass *) hdbc); ret = PGAPI_GetConnectAttr(hdbc, fAttribute, rgbValue, cbValueMax, pcbValue); LEAVE_CONN_CS((ConnectionClass *) hdbc); return ret; } RETCODE SQL_API SQLSetConnectAttrW(HDBC hdbc, SQLINTEGER fAttribute, PTR rgbValue, SQLINTEGER cbValue) { CSTR func = "SQLSetConnectAttrW"; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[%s]", func); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); CC_set_in_unicode_driver(conn); ret = PGAPI_SetConnectAttr(hdbc, fAttribute, rgbValue, cbValue); LEAVE_CONN_CS(conn); return ret; } /* new function */ RETCODE SQL_API SQLSetDescFieldW(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { CSTR func = "SQLSetDescFieldW"; RETCODE ret; SQLLEN vallen; char *uval = NULL; BOOL val_alloced = FALSE; mylog("[%s]", func); if (BufferLength > 0 || SQL_NTS == BufferLength) { switch (FieldIdentifier) { case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: uval = ucs2_to_utf8(Value, BufferLength > 0 ? BufferLength / WCLEN : BufferLength, &vallen, FALSE); val_alloced = TRUE; break; } } if (!val_alloced) { uval = Value; vallen = BufferLength; } ret = PGAPI_SetDescField(DescriptorHandle, RecNumber, FieldIdentifier, uval, (SQLINTEGER) vallen); if (val_alloced) free(uval); return ret; } RETCODE SQL_API SQLGetDescFieldW(SQLHDESC hdesc, SQLSMALLINT iRecord, SQLSMALLINT iField, PTR rgbValue, SQLINTEGER cbValueMax, SQLINTEGER *pcbValue) { CSTR func = "SQLGetDescFieldW"; RETCODE ret; SQLINTEGER blen = 0, bMax, *pcbV; char *rgbV = NULL; mylog("[%s]", func); switch (iField) { case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: bMax = cbValueMax * 3 / WCLEN; rgbV = malloc(bMax + 1); pcbV = &blen; for (;; bMax = blen + 1, rgbV = realloc(rgbV, bMax)) { ret = PGAPI_GetDescField(hdesc, iRecord, iField, rgbV, bMax, pcbV); if (SQL_SUCCESS_WITH_INFO != ret || blen < bMax) break; } if (SQL_SUCCEEDED(ret)) { blen = (SQLINTEGER) utf8_to_ucs2(rgbV, blen, (SQLWCHAR *) rgbValue, cbValueMax / WCLEN); if (SQL_SUCCESS == ret && blen * WCLEN >= cbValueMax) { ret = SQL_SUCCESS_WITH_INFO; DC_set_error(hdesc, STMT_TRUNCATED, "The buffer was too small for the rgbDesc."); } if (pcbValue) *pcbValue = blen * WCLEN; } if (rgbV) free(rgbV); break; default: rgbV = rgbValue; bMax = cbValueMax; pcbV = pcbValue; ret = PGAPI_GetDescField(hdesc, iRecord, iField, rgbV, bMax, pcbV); break; } return ret; } RETCODE SQL_API SQLGetDiagRecW(SQLSMALLINT fHandleType, SQLHANDLE handle, SQLSMALLINT iRecord, SQLWCHAR *szSqlState, SQLINTEGER *pfNativeError, SQLWCHAR *szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT *pcbErrorMsg) { CSTR func = "SQLGetDiagRecW"; RETCODE ret; SQLSMALLINT buflen, tlen; char *qstr = NULL, *mtxt = NULL; mylog("[%s]", func); if (szSqlState) qstr = malloc(8); buflen = 0; if (szErrorMsg && cbErrorMsgMax > 0) { buflen = cbErrorMsgMax; mtxt = malloc(buflen); } ret = PGAPI_GetDiagRec(fHandleType, handle, iRecord, (SQLCHAR *) qstr, pfNativeError, (SQLCHAR *) mtxt, buflen, &tlen); if (SQL_SUCCEEDED(ret)) { if (qstr) utf8_to_ucs2(qstr, strlen(qstr), szSqlState, 6); if (mtxt && tlen <= cbErrorMsgMax) { SQLULEN ulen = utf8_to_ucs2_lf(mtxt, tlen, FALSE, szErrorMsg, cbErrorMsgMax, TRUE); if (ulen == (SQLULEN) -1) { tlen = (SQLSMALLINT) msgtowstr(NULL, mtxt, (int) tlen, (LPWSTR) szErrorMsg, (int) cbErrorMsgMax); } else tlen = (SQLSMALLINT) ulen; if (tlen >= cbErrorMsgMax) ret = SQL_SUCCESS_WITH_INFO; } if (pcbErrorMsg) *pcbErrorMsg = tlen; } if (qstr) free(qstr); if (mtxt) free(mtxt); return ret; } SQLRETURN SQL_API SQLColAttributeW(SQLHSTMT hstmt, SQLUSMALLINT iCol, SQLUSMALLINT iField, SQLPOINTER pCharAttr, SQLSMALLINT cbCharAttrMax, SQLSMALLINT *pcbCharAttr, #if defined(_WIN64) || defined(SQLCOLATTRIBUTE_SQLLEN) SQLLEN *pNumAttr #else SQLPOINTER pNumAttr #endif ) { CSTR func = "SQLColAttributeW"; RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; SQLSMALLINT *rgbL, blen = 0, bMax; char *rgbD = NULL; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); switch (iField) { case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: case SQL_COLUMN_NAME: bMax = cbCharAttrMax * 3 / WCLEN; rgbD = malloc(bMax); rgbL = &blen; for (;; bMax = blen + 1, rgbD = realloc(rgbD, bMax)) { ret = PGAPI_ColAttributes(hstmt, iCol, iField, rgbD, bMax, rgbL, pNumAttr); if (SQL_SUCCESS_WITH_INFO != ret || blen < bMax) break; } if (SQL_SUCCEEDED(ret)) { blen = (SQLSMALLINT) utf8_to_ucs2(rgbD, blen, (SQLWCHAR *) pCharAttr, cbCharAttrMax / WCLEN); if (SQL_SUCCESS == ret && blen * WCLEN >= cbCharAttrMax) { ret = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_TRUNCATED, "The buffer was too small for the pCharAttr.", func); } if (pcbCharAttr) *pcbCharAttr = blen * WCLEN; } if (rgbD) free(rgbD); break; default: rgbD = pCharAttr; bMax = cbCharAttrMax; rgbL = pcbCharAttr; ret = PGAPI_ColAttributes(hstmt, iCol, iField, rgbD, bMax, rgbL, pNumAttr); break; } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLGetDiagFieldW(SQLSMALLINT fHandleType, SQLHANDLE handle, SQLSMALLINT iRecord, SQLSMALLINT fDiagField, SQLPOINTER rgbDiagInfo, SQLSMALLINT cbDiagInfoMax, SQLSMALLINT *pcbDiagInfo) { CSTR func = "SQLGetDiagFieldW"; RETCODE ret; SQLSMALLINT *rgbL, blen = 0, bMax; char *rgbD = NULL; mylog("[[%s]] Handle=(%u,%p) Rec=%d Id=%d info=(%p,%d)\n", func, fHandleType, handle, iRecord, fDiagField, rgbDiagInfo, cbDiagInfoMax); switch (fDiagField) { case SQL_DIAG_DYNAMIC_FUNCTION: case SQL_DIAG_CLASS_ORIGIN: case SQL_DIAG_CONNECTION_NAME: case SQL_DIAG_MESSAGE_TEXT: case SQL_DIAG_SERVER_NAME: case SQL_DIAG_SQLSTATE: case SQL_DIAG_SUBCLASS_ORIGIN: bMax = cbDiagInfoMax * 3 / WCLEN + 1; if (rgbD = malloc(bMax), !rgbD) return SQL_ERROR; rgbL = &blen; for (;; bMax = blen + 1, rgbD = realloc(rgbD, bMax)) { ret = PGAPI_GetDiagField(fHandleType, handle, iRecord, fDiagField, rgbD, bMax, rgbL); if (SQL_SUCCESS_WITH_INFO != ret || blen < bMax) break; } if (SQL_SUCCEEDED(ret)) { SQLULEN ulen = (SQLSMALLINT) utf8_to_ucs2_lf(rgbD, blen, FALSE, (SQLWCHAR *) rgbDiagInfo, cbDiagInfoMax / WCLEN, TRUE); if (ulen == (SQLULEN) -1) { blen = (SQLSMALLINT) msgtowstr(NULL, rgbD, (int) blen, (LPWSTR) rgbDiagInfo, (int) cbDiagInfoMax / WCLEN); } else blen = (SQLSMALLINT) ulen; if (SQL_SUCCESS == ret && blen * WCLEN >= cbDiagInfoMax) ret = SQL_SUCCESS_WITH_INFO; if (pcbDiagInfo) { #ifdef WIN32 extern int platformId; if (VER_PLATFORM_WIN32_WINDOWS == platformId && NULL == rgbDiagInfo && 0 == cbDiagInfoMax) blen++; #endif /* WIN32 */ *pcbDiagInfo = blen * WCLEN; } } if (rgbD) free(rgbD); break; default: rgbD = rgbDiagInfo; bMax = cbDiagInfoMax; rgbL = pcbDiagInfo; ret = PGAPI_GetDiagField(fHandleType, handle, iRecord, fDiagField, rgbD, bMax, rgbL); break; } return ret; } #endif /* ODBCVER >= 0x0300 */ psqlodbc-09.03.0300/odbcapiw.c000644 001752 000000 00000065342 12335653444 016146 0ustar00saitowheel000000 000000 /*------- * Module: odbcapiw.c * * Description: This module contains UNICODE routines * * Classes: n/a * * API functions: SQLColumnPrivilegesW, SQLColumnsW, SQLConnectW, SQLDataSourcesW, SQLDescribeColW, SQLDriverConnectW, SQLExecDirectW, SQLForeignKeysW, SQLGetCursorNameW, SQLGetInfoW, SQLNativeSqlW, SQLPrepareW, SQLPrimaryKeysW, SQLProcedureColumnsW, SQLProceduresW, SQLSetCursorNameW, SQLSpecialColumnsW, SQLStatisticsW, SQLTablesW, SQLTablePrivilegesW, SQLGetTypeInfoW *------- */ #include "psqlodbc.h" #include #include #include "pgapifunc.h" #include "connection.h" #include "statement.h" RETCODE SQL_API SQLColumnsW(HSTMT StatementHandle, SQLWCHAR *CatalogName, SQLSMALLINT NameLength1, SQLWCHAR *SchemaName, SQLSMALLINT NameLength2, SQLWCHAR *TableName, SQLSMALLINT NameLength3, SQLWCHAR *ColumnName, SQLSMALLINT NameLength4) { CSTR func = "SQLColumnsW"; RETCODE ret; char *ctName, *scName, *tbName, *clName; SQLLEN nmlen1, nmlen2, nmlen3, nmlen4; StatementClass *stmt = (StatementClass *) StatementHandle; ConnectionClass *conn; BOOL lower_id; UWORD flag = PODBC_SEARCH_PUBLIC_SCHEMA; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(CatalogName, NameLength1, &nmlen1, lower_id); scName = ucs2_to_utf8(SchemaName, NameLength2, &nmlen2, lower_id); tbName = ucs2_to_utf8(TableName, NameLength3, &nmlen3, lower_id); clName = ucs2_to_utf8(ColumnName, NameLength4, &nmlen4, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Columns(StatementHandle, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, (SQLCHAR *) clName, (SQLSMALLINT) nmlen4, flag, 0, 0); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); if (clName) free(clName); return ret; } RETCODE SQL_API SQLConnectW(HDBC ConnectionHandle, SQLWCHAR *ServerName, SQLSMALLINT NameLength1, SQLWCHAR *UserName, SQLSMALLINT NameLength2, SQLWCHAR *Authentication, SQLSMALLINT NameLength3) { CSTR func = "SQLConnectW"; char *svName, *usName, *auth; SQLLEN nmlen1, nmlen2, nmlen3; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; mylog("[%s]", func); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); CC_set_in_unicode_driver(conn); svName = ucs2_to_utf8(ServerName, NameLength1, &nmlen1, FALSE); usName = ucs2_to_utf8(UserName, NameLength2, &nmlen2, FALSE); auth = ucs2_to_utf8(Authentication, NameLength3, &nmlen3, FALSE); ret = PGAPI_Connect(ConnectionHandle, (SQLCHAR *) svName, (SQLSMALLINT) nmlen1, (SQLCHAR *) usName, (SQLSMALLINT) nmlen2, (SQLCHAR *) auth, (SQLSMALLINT) nmlen3); LEAVE_CONN_CS(conn); if (svName) free(svName); if (usName) free(usName); if (auth) free(auth); return ret; } RETCODE SQL_API SQLDriverConnectW(HDBC hdbc, HWND hwnd, SQLWCHAR *szConnStrIn, SQLSMALLINT cbConnStrIn, SQLWCHAR *szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT FAR *pcbConnStrOut, SQLUSMALLINT fDriverCompletion) { CSTR func = "SQLDriverConnectW"; char *szIn, *szOut = NULL; SQLSMALLINT maxlen, obuflen = 0; SQLLEN inlen; SQLSMALLINT olen, *pCSO; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[%s]", func); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); CC_set_in_unicode_driver(conn); szIn = ucs2_to_utf8(szConnStrIn, cbConnStrIn, &inlen, FALSE); maxlen = cbConnStrOutMax; pCSO = NULL; olen = 0; if (maxlen > 0) { obuflen = maxlen + 1; szOut = malloc(obuflen); pCSO = &olen; } else if (pcbConnStrOut) pCSO = &olen; ret = PGAPI_DriverConnect(hdbc, hwnd, (SQLCHAR *) szIn, (SQLSMALLINT) inlen, (SQLCHAR *) szOut, maxlen, pCSO, fDriverCompletion); if (ret != SQL_ERROR && NULL != pCSO) { SQLLEN outlen = olen; if (olen < obuflen) outlen = utf8_to_ucs2(szOut, olen, szConnStrOut, cbConnStrOutMax); else utf8_to_ucs2(szOut, maxlen, szConnStrOut, cbConnStrOutMax); if (outlen >= cbConnStrOutMax && NULL != szConnStrOut && NULL != pcbConnStrOut) { inolog("cbConnstrOutMax=%d pcb=%p\n", cbConnStrOutMax, pcbConnStrOut); if (SQL_SUCCESS == ret) { CC_set_error(conn, CONN_TRUNCATED, "the ConnStrOut is too small", func); ret = SQL_SUCCESS_WITH_INFO; } } if (pcbConnStrOut) *pcbConnStrOut = (SQLSMALLINT) outlen; } LEAVE_CONN_CS(conn); if (szOut) free(szOut); if (szIn) free(szIn); return ret; } RETCODE SQL_API SQLBrowseConnectW(HDBC hdbc, SQLWCHAR *szConnStrIn, SQLSMALLINT cbConnStrIn, SQLWCHAR *szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT *pcbConnStrOut) { CSTR func = "SQLBrowseConnectW"; char *szIn, *szOut; SQLLEN inlen; SQLUSMALLINT obuflen; SQLSMALLINT olen; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[%s]", func); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); CC_set_in_unicode_driver(conn); szIn = ucs2_to_utf8(szConnStrIn, cbConnStrIn, &inlen, FALSE); obuflen = cbConnStrOutMax + 1; szOut = malloc(obuflen); ret = PGAPI_BrowseConnect(hdbc, (SQLCHAR *) szIn, (SQLSMALLINT) inlen, (SQLCHAR *) szOut, cbConnStrOutMax, &olen); LEAVE_CONN_CS(conn); if (ret != SQL_ERROR) { SQLLEN outlen = utf8_to_ucs2(szOut, olen, szConnStrOut, cbConnStrOutMax); if (pcbConnStrOut) *pcbConnStrOut = (SQLSMALLINT) outlen; } free(szOut); if (szIn) free(szIn); return ret; } RETCODE SQL_API SQLDataSourcesW(HENV EnvironmentHandle, SQLUSMALLINT Direction, SQLWCHAR *ServerName, SQLSMALLINT BufferLength1, SQLSMALLINT *NameLength1, SQLWCHAR *Description, SQLSMALLINT BufferLength2, SQLSMALLINT *NameLength2) { CSTR func = "SQLDataSourcesW"; mylog("[%s]", func); /* return PGAPI_DataSources(EnvironmentHandle, Direction, ServerName, BufferLength1, NameLength1, Description, BufferLength2, NameLength2); */ return SQL_ERROR; } RETCODE SQL_API SQLDescribeColW(HSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLWCHAR *ColumnName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength, SQLSMALLINT *DataType, SQLULEN *ColumnSize, SQLSMALLINT *DecimalDigits, SQLSMALLINT *Nullable) { CSTR func = "SQLDescribeColW"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; SQLSMALLINT buflen, nmlen; char *clName = NULL; mylog("[%s]", func); buflen = 0; if (BufferLength > 0) buflen = BufferLength * 3; else if (NameLength) buflen = 32; if (buflen > 0) clName = malloc(buflen); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); for (;; buflen = nmlen + 1, clName = realloc(clName, buflen)) { ret = PGAPI_DescribeCol(StatementHandle, ColumnNumber, (SQLCHAR *) clName, buflen, &nmlen, DataType, ColumnSize, DecimalDigits, Nullable); if (SQL_SUCCESS_WITH_INFO != ret || nmlen < buflen) break; } if (SQL_SUCCEEDED(ret)) { SQLLEN nmcount = nmlen; if (nmlen < buflen) nmcount = utf8_to_ucs2(clName, nmlen, ColumnName, BufferLength); if (SQL_SUCCESS == ret && BufferLength > 0 && nmcount > BufferLength) { ret = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_TRUNCATED, "Column name too large", func); } if (NameLength) *NameLength = (SQLSMALLINT) nmcount; } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (clName) free(clName); return ret; } RETCODE SQL_API SQLExecDirectW(HSTMT StatementHandle, SQLWCHAR *StatementText, SQLINTEGER TextLength) { CSTR func = "SQLExecDirectW"; RETCODE ret; char *stxt; SQLLEN slen; StatementClass *stmt = (StatementClass *) StatementHandle; UWORD flag = 0; mylog("[%s]", func); stxt = ucs2_to_utf8(StatementText, TextLength, &slen, FALSE); ENTER_STMT_CS(stmt); SC_clear_error(stmt); if (PG_VERSION_GE(SC_get_conn(stmt), 7.4)) flag |= PODBC_WITH_HOLD; StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ExecDirect(StatementHandle, (SQLCHAR *) stxt, (SQLINTEGER) slen, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (stxt) free(stxt); return ret; } RETCODE SQL_API SQLGetCursorNameW(HSTMT StatementHandle, SQLWCHAR *CursorName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength) { CSTR func = "SQLGetCursorNameW"; RETCODE ret; StatementClass * stmt = (StatementClass *) StatementHandle; char *crName; SQLSMALLINT clen, buflen; mylog("[%s]", func); if (BufferLength > 0) buflen = BufferLength * 3; else buflen = 32; crName = malloc(buflen); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); for (;; buflen = clen + 1, crName = realloc(crName, buflen)) { ret = PGAPI_GetCursorName(StatementHandle, (SQLCHAR *) crName, buflen, &clen); if (SQL_SUCCESS_WITH_INFO != ret || clen < buflen) break; } if (SQL_SUCCEEDED(ret)) { SQLLEN nmcount = clen; if (clen < buflen) nmcount = utf8_to_ucs2(crName, clen, CursorName, BufferLength); if (SQL_SUCCESS == ret && nmcount > BufferLength) { ret = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_TRUNCATED, "Cursor name too large", func); } if (NameLength) *NameLength = (SQLSMALLINT) nmcount; } ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); free(crName); return ret; } RETCODE SQL_API SQLGetInfoW(HDBC ConnectionHandle, SQLUSMALLINT InfoType, PTR InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength) { CSTR func = "SQLGetInfoW"; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; RETCODE ret; CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_set_in_unicode_driver(conn); CC_clear_error(conn); #if (ODBCVER >= 0x0300) mylog("[%s(30)]", func); if ((ret = PGAPI_GetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength)) == SQL_ERROR) { if (conn->driver_version >= 0x0300) { CC_clear_error(conn); ret = PGAPI_GetInfo30(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength); } } if (SQL_ERROR == ret) CC_log_error("SQLGetInfoW(30)", "", conn); #else mylog("[%s]", func); ret = PGAPI_GetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength); if (SQL_ERROR == ret) CC_log_error("SQLGetInfoW", "", conn); #endif LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLPrepareW(HSTMT StatementHandle, SQLWCHAR *StatementText, SQLINTEGER TextLength) { CSTR func = "SQLPrepareW"; StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret; char *stxt; SQLLEN slen; mylog("[%s]", func); stxt = ucs2_to_utf8(StatementText, TextLength, &slen, FALSE); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Prepare(StatementHandle, (SQLCHAR *) stxt, (SQLINTEGER) slen); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (stxt) free(stxt); return ret; } RETCODE SQL_API SQLSetCursorNameW(HSTMT StatementHandle, SQLWCHAR *CursorName, SQLSMALLINT NameLength) { CSTR func = "SQLSetCursorNameW"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; char *crName; SQLLEN nlen; mylog("[%s]", func); crName = ucs2_to_utf8(CursorName, NameLength, &nlen, FALSE); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_SetCursorName(StatementHandle, (SQLCHAR *) crName, (SQLSMALLINT) nlen); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (crName) free(crName); return ret; } RETCODE SQL_API SQLSpecialColumnsW(HSTMT StatementHandle, SQLUSMALLINT IdentifierType, SQLWCHAR *CatalogName, SQLSMALLINT NameLength1, SQLWCHAR *SchemaName, SQLSMALLINT NameLength2, SQLWCHAR *TableName, SQLSMALLINT NameLength3, SQLUSMALLINT Scope, SQLUSMALLINT Nullable) { CSTR func = "SQLSpecialColumnsW"; RETCODE ret; char *ctName, *scName, *tbName; SQLLEN nmlen1, nmlen2, nmlen3; StatementClass *stmt = (StatementClass *) StatementHandle; ConnectionClass *conn; BOOL lower_id; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(CatalogName, NameLength1, &nmlen1, lower_id); scName = ucs2_to_utf8(SchemaName, NameLength2, &nmlen2, lower_id); tbName = ucs2_to_utf8(TableName, NameLength3, &nmlen3, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_SpecialColumns(StatementHandle, IdentifierType, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, Scope, Nullable); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); return ret; } RETCODE SQL_API SQLStatisticsW(HSTMT StatementHandle, SQLWCHAR *CatalogName, SQLSMALLINT NameLength1, SQLWCHAR *SchemaName, SQLSMALLINT NameLength2, SQLWCHAR *TableName, SQLSMALLINT NameLength3, SQLUSMALLINT Unique, SQLUSMALLINT Reserved) { CSTR func = "SQLStatisticsW"; RETCODE ret; char *ctName, *scName, *tbName; SQLLEN nmlen1, nmlen2, nmlen3; StatementClass *stmt = (StatementClass *) StatementHandle; ConnectionClass *conn; BOOL lower_id; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(CatalogName, NameLength1, &nmlen1, lower_id); scName = ucs2_to_utf8(SchemaName, NameLength2, &nmlen2, lower_id); tbName = ucs2_to_utf8(TableName, NameLength3, &nmlen3, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Statistics(StatementHandle, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, Unique, Reserved); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); return ret; } RETCODE SQL_API SQLTablesW(HSTMT StatementHandle, SQLWCHAR *CatalogName, SQLSMALLINT NameLength1, SQLWCHAR *SchemaName, SQLSMALLINT NameLength2, SQLWCHAR *TableName, SQLSMALLINT NameLength3, SQLWCHAR *TableType, SQLSMALLINT NameLength4) { CSTR func = "SQLTablesW"; RETCODE ret; char *ctName, *scName, *tbName, *tbType; SQLLEN nmlen1, nmlen2, nmlen3, nmlen4; StatementClass *stmt = (StatementClass *) StatementHandle; ConnectionClass *conn; BOOL lower_id; UWORD flag = 0; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(CatalogName, NameLength1, &nmlen1, lower_id); scName = ucs2_to_utf8(SchemaName, NameLength2, &nmlen2, lower_id); tbName = ucs2_to_utf8(TableName, NameLength3, &nmlen3, lower_id); tbType = ucs2_to_utf8(TableType, NameLength4, &nmlen4, FALSE); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Tables(StatementHandle, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, (SQLCHAR *) tbType, (SQLSMALLINT) nmlen4, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); if (tbType) free(tbType); return ret; } RETCODE SQL_API SQLColumnPrivilegesW(HSTMT hstmt, SQLWCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLWCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLWCHAR *szTableName, SQLSMALLINT cbTableName, SQLWCHAR *szColumnName, SQLSMALLINT cbColumnName) { CSTR func = "SQLColumnPrivilegesW"; RETCODE ret; char *ctName, *scName, *tbName, *clName; SQLLEN nmlen1, nmlen2, nmlen3, nmlen4; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; BOOL lower_id; UWORD flag = 0; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(szCatalogName, cbCatalogName, &nmlen1, lower_id); scName = ucs2_to_utf8(szSchemaName, cbSchemaName, &nmlen2, lower_id); tbName = ucs2_to_utf8(szTableName, cbTableName, &nmlen3, lower_id); clName = ucs2_to_utf8(szColumnName, cbColumnName, &nmlen4, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ColumnPrivileges(hstmt, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, (SQLCHAR *) clName, (SQLSMALLINT) nmlen4, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); if (clName) free(clName); return ret; } RETCODE SQL_API SQLForeignKeysW(HSTMT hstmt, SQLWCHAR *szPkCatalogName, SQLSMALLINT cbPkCatalogName, SQLWCHAR *szPkSchemaName, SQLSMALLINT cbPkSchemaName, SQLWCHAR *szPkTableName, SQLSMALLINT cbPkTableName, SQLWCHAR *szFkCatalogName, SQLSMALLINT cbFkCatalogName, SQLWCHAR *szFkSchemaName, SQLSMALLINT cbFkSchemaName, SQLWCHAR *szFkTableName, SQLSMALLINT cbFkTableName) { CSTR func = "SQLForeignKeysW"; RETCODE ret; char *ctName, *scName, *tbName, *fkctName, *fkscName, *fktbName; SQLLEN nmlen1, nmlen2, nmlen3, nmlen4, nmlen5, nmlen6; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; BOOL lower_id; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(szPkCatalogName, cbPkCatalogName, &nmlen1, lower_id); scName = ucs2_to_utf8(szPkSchemaName, cbPkSchemaName, &nmlen2, lower_id); tbName = ucs2_to_utf8(szPkTableName, cbPkTableName, &nmlen3, lower_id); fkctName = ucs2_to_utf8(szFkCatalogName, cbFkCatalogName, &nmlen4, lower_id); fkscName = ucs2_to_utf8(szFkSchemaName, cbFkSchemaName, &nmlen5, lower_id); fktbName = ucs2_to_utf8(szFkTableName, cbFkTableName, &nmlen6, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ForeignKeys(hstmt, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, (SQLCHAR *) fkctName, (SQLSMALLINT) nmlen4, (SQLCHAR *) fkscName, (SQLSMALLINT) nmlen5, (SQLCHAR *) fktbName, (SQLSMALLINT) nmlen6); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); if (fkctName) free(fkctName); if (fkscName) free(fkscName); if (fktbName) free(fktbName); return ret; } RETCODE SQL_API SQLNativeSqlW(HDBC hdbc, SQLWCHAR *szSqlStrIn, SQLINTEGER cbSqlStrIn, SQLWCHAR *szSqlStr, SQLINTEGER cbSqlStrMax, SQLINTEGER *pcbSqlStr) { CSTR func = "SQLNativeSqlW"; RETCODE ret; char *szIn, *szOut = NULL; SQLLEN slen; SQLINTEGER buflen, olen; ConnectionClass *conn = (ConnectionClass *) hdbc; mylog("[%s}", func); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); CC_set_in_unicode_driver(conn); szIn = ucs2_to_utf8(szSqlStrIn, cbSqlStrIn, &slen, FALSE); buflen = 3 * cbSqlStrMax; if (buflen > 0) szOut = malloc(buflen); for (;; buflen = olen + 1, szOut = realloc(szOut, buflen)) { ret = PGAPI_NativeSql(hdbc, (SQLCHAR *) szIn, (SQLINTEGER) slen, (SQLCHAR *) szOut, buflen, &olen); if (SQL_SUCCESS_WITH_INFO != ret || olen < buflen) break; } if (szIn) free(szIn); if (SQL_SUCCEEDED(ret)) { SQLLEN szcount = olen; if (olen < buflen) szcount = utf8_to_ucs2(szOut, olen, szSqlStr, cbSqlStrMax); if (SQL_SUCCESS == ret && szcount > cbSqlStrMax) { ConnectionClass *conn = (ConnectionClass *) hdbc; ret = SQL_SUCCESS_WITH_INFO; CC_set_error(conn, CONN_TRUNCATED, "Sql string too large", func); } if (pcbSqlStr) *pcbSqlStr = (SQLINTEGER) szcount; } LEAVE_CONN_CS(conn); free(szOut); return ret; } RETCODE SQL_API SQLPrimaryKeysW(HSTMT hstmt, SQLWCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLWCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLWCHAR *szTableName, SQLSMALLINT cbTableName) { CSTR func = "SQLPrimaryKeysW"; RETCODE ret; char *ctName, *scName, *tbName; SQLLEN nmlen1, nmlen2, nmlen3; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; BOOL lower_id; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(szCatalogName, cbCatalogName, &nmlen1, lower_id); scName = ucs2_to_utf8(szSchemaName, cbSchemaName, &nmlen2, lower_id); tbName = ucs2_to_utf8(szTableName, cbTableName, &nmlen3, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_PrimaryKeys(hstmt, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, 0); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); return ret; } RETCODE SQL_API SQLProcedureColumnsW(HSTMT hstmt, SQLWCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLWCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLWCHAR *szProcName, SQLSMALLINT cbProcName, SQLWCHAR *szColumnName, SQLSMALLINT cbColumnName) { CSTR func = "SQLProcedureColumnsW"; RETCODE ret; char *ctName, *scName, *prName, *clName; SQLLEN nmlen1, nmlen2, nmlen3, nmlen4; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; BOOL lower_id; UWORD flag = 0; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(szCatalogName, cbCatalogName, &nmlen1, lower_id); scName = ucs2_to_utf8(szSchemaName, cbSchemaName, &nmlen2, lower_id); prName = ucs2_to_utf8(szProcName, cbProcName, &nmlen3, lower_id); clName = ucs2_to_utf8(szColumnName, cbColumnName, &nmlen4, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_ProcedureColumns(hstmt, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) prName, (SQLSMALLINT) nmlen3, (SQLCHAR *) clName, (SQLSMALLINT) nmlen4, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (prName) free(prName); if (clName) free(clName); return ret; } RETCODE SQL_API SQLProceduresW(HSTMT hstmt, SQLWCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLWCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLWCHAR *szProcName, SQLSMALLINT cbProcName) { CSTR func = "SQLProceduresW"; RETCODE ret; char *ctName, *scName, *prName; SQLLEN nmlen1, nmlen2, nmlen3; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; BOOL lower_id; UWORD flag = 0; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(szCatalogName, cbCatalogName, &nmlen1, lower_id); scName = ucs2_to_utf8(szSchemaName, cbSchemaName, &nmlen2, lower_id); prName = ucs2_to_utf8(szProcName, cbProcName, &nmlen3, lower_id); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_Procedures(hstmt, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) prName, (SQLSMALLINT) nmlen3, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); if (ctName) free(ctName); if (scName) free(scName); if (prName) free(prName); return ret; } RETCODE SQL_API SQLTablePrivilegesW(HSTMT hstmt, SQLWCHAR *szCatalogName, SQLSMALLINT cbCatalogName, SQLWCHAR *szSchemaName, SQLSMALLINT cbSchemaName, SQLWCHAR *szTableName, SQLSMALLINT cbTableName) { CSTR func = "SQLTablePrivilegesW"; RETCODE ret; char *ctName, *scName, *tbName; SQLLEN nmlen1, nmlen2, nmlen3; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; BOOL lower_id; UWORD flag = 0; mylog("[%s]", func); conn = SC_get_conn(stmt); lower_id = SC_is_lower_case(stmt, conn); ctName = ucs2_to_utf8(szCatalogName, cbCatalogName, &nmlen1, lower_id); scName = ucs2_to_utf8(szSchemaName, cbSchemaName, &nmlen2, lower_id); tbName = ucs2_to_utf8(szTableName, cbTableName, &nmlen3, lower_id); ENTER_STMT_CS((StatementClass *) hstmt); SC_clear_error(stmt); StartRollbackState(stmt); #if (ODBCVER >= 0x0300) if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; #endif if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_TablePrivileges(hstmt, (SQLCHAR *) ctName, (SQLSMALLINT) nmlen1, (SQLCHAR *) scName, (SQLSMALLINT) nmlen2, (SQLCHAR *) tbName, (SQLSMALLINT) nmlen3, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS((StatementClass *) hstmt); if (ctName) free(ctName); if (scName) free(scName); if (tbName) free(tbName); return ret; } RETCODE SQL_API SQLGetTypeInfoW(SQLHSTMT StatementHandle, SQLSMALLINT DataType) { CSTR func = "SQLGetTypeInfoW"; RETCODE ret; StatementClass * stmt = (StatementClass *) StatementHandle; mylog("[%s]", func); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else ret = PGAPI_GetTypeInfo(StatementHandle, DataType); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } psqlodbc-09.03.0300/win_unicode.c000644 001752 000000 00000017615 12335653444 016661 0ustar00saitowheel000000 000000 /*------- * Module: win_unicode.c * * Description: This module contains utf8 <-> ucs2 conversion routines * under WIndows * *------- */ #include "psqlodbc.h" #include #include #define byte3check 0xfffff800 #define byte2_base 0x80c0 #define byte2_mask1 0x07c0 #define byte2_mask2 0x003f #define byte3_base 0x8080e0 #define byte3_mask1 0xf000 #define byte3_mask2 0x0fc0 #define byte3_mask3 0x003f #define surrog_check 0xfc00 #define surrog1_bits 0xd800 #define surrog2_bits 0xdc00 #define byte4_base 0x808080f0 #define byte4_sr1_mask1 0x0700 #define byte4_sr1_mask2 0x00fc #define byte4_sr1_mask3 0x0003 #define byte4_sr2_mask1 0x03c0 #define byte4_sr2_mask2 0x003f #define surrogate_adjust (0x10000 >> 10) static int little_endian = -1; SQLULEN ucs2strlen(const SQLWCHAR *ucs2str) { SQLULEN len; for (len = 0; ucs2str[len]; len++) ; return len; } char *ucs2_to_utf8(const SQLWCHAR *ucs2str, SQLLEN ilen, SQLLEN *olen, BOOL lower_identifier) { char * utf8str; /*mylog("ucs2_to_utf8 %p ilen=%d ", ucs2str, ilen);*/ if (!ucs2str) { *olen = SQL_NULL_DATA; return NULL; } if (little_endian < 0) { int crt = 1; little_endian = (0 != ((char *) &crt)[0]); } if (SQL_NTS == ilen) ilen = ucs2strlen(ucs2str); /*mylog(" newlen=%d", ilen);*/ utf8str = (char *) malloc(ilen * 4 + 1); if (utf8str) { int i, len = 0; UInt2 byte2code; Int4 byte4code, surrd1, surrd2; const SQLWCHAR *wstr; for (i = 0, wstr = ucs2str; i < ilen; i++, wstr++) { if (!*wstr) break; else if (0 == (*wstr & 0xffffff80)) /* ASCII */ { if (lower_identifier) utf8str[len++] = (char) tolower(*wstr); else utf8str[len++] = (char) *wstr; } else if ((*wstr & byte3check) == 0) { byte2code = byte2_base | ((byte2_mask1 & *wstr) >> 6) | ((byte2_mask2 & *wstr) << 8); if (little_endian) memcpy(utf8str + len, (char *) &byte2code, sizeof(byte2code)); else { utf8str[len] = ((char *) &byte2code)[1]; utf8str[len + 1] = ((char *) &byte2code)[0]; } len += sizeof(byte2code); } /* surrogate pair check for non ucs-2 code */ else if (surrog1_bits == (*wstr & surrog_check)) { surrd1 = (*wstr & ~surrog_check) + surrogate_adjust; wstr++; i++; surrd2 = (*wstr & ~surrog_check); byte4code = byte4_base | ((byte4_sr1_mask1 & surrd1) >> 8) | ((byte4_sr1_mask2 & surrd1) << 6) | ((byte4_sr1_mask3 & surrd1) << 20) | ((byte4_sr2_mask1 & surrd2) << 10) | ((byte4_sr2_mask2 & surrd2) << 24); if (little_endian) memcpy(utf8str + len, (char *) &byte4code, sizeof(byte4code)); else { utf8str[len] = ((char *) &byte4code)[3]; utf8str[len + 1] = ((char *) &byte4code)[2]; utf8str[len + 2] = ((char *) &byte4code)[1]; utf8str[len + 3] = ((char *) &byte4code)[0]; } len += sizeof(byte4code); } else { byte4code = byte3_base | ((byte3_mask1 & *wstr) >> 12) | ((byte3_mask2 & *wstr) << 2) | ((byte3_mask3 & *wstr) << 16); if (little_endian) memcpy(utf8str + len, (char *) &byte4code, 3); else { utf8str[len] = ((char *) &byte4code)[3]; utf8str[len + 1] = ((char *) &byte4code)[2]; utf8str[len + 2] = ((char *) &byte4code)[1]; } len += 3; } } utf8str[len] = '\0'; if (olen) *olen = len; } /*mylog(" olen=%d %s\n", *olen, utf8str ? utf8str : "");*/ return utf8str; } #define byte3_m1 0x0f #define byte3_m2 0x3f #define byte3_m3 0x3f #define byte2_m1 0x1f #define byte2_m2 0x3f #define byte4_m1 0x07 #define byte4_m2 0x3f #define byte4_m31 0x30 #define byte4_m32 0x0f #define byte4_m4 0x3f /* * Convert a string from UTF-8 encoding to UCS-2. * * utf8str - input string in UTF-8 * ilen - length of input string in bytes (or SQL_NTS) * lfconv - TRUE if line feeds (LF) should be converted to CR + LF * ucs2str - output buffer * bufcount - size of output buffer * errcheck - if TRUE, check for invalidly encoded input characters * * Returns the number of SQLWCHARs copied to output buffer. If the output * buffer is too small, the output is truncated. The output string is * NULL-terminated, except when the output is truncated. */ SQLULEN utf8_to_ucs2_lf(const char *utf8str, SQLLEN ilen, BOOL lfconv, SQLWCHAR *ucs2str, SQLULEN bufcount, BOOL errcheck) { int i; SQLULEN rtn, ocount, wcode; const UCHAR *str; /*mylog("utf8_to_ucs2 ilen=%d bufcount=%d", ilen, bufcount);*/ if (!utf8str) return 0; /*mylog(" string=%s\n", utf8str);*/ if (!bufcount) ucs2str = NULL; else if (!ucs2str) bufcount = 0; if (ilen < 0) ilen = strlen(utf8str); for (i = 0, ocount = 0, str = (SQLCHAR *) utf8str; i < ilen && *str;) { if ((*str & 0x80) == 0) { if (lfconv && PG_LINEFEED == *str && (i == 0 || PG_CARRIAGE_RETURN != str[-1])) { if (ocount < bufcount) ucs2str[ocount] = PG_CARRIAGE_RETURN; ocount++; } if (ocount < bufcount) ucs2str[ocount] = *str; ocount++; i++; str++; } else if (0xf8 == (*str & 0xf8)) /* more than 5 byte code */ { ocount = (SQLULEN) -1; goto cleanup; } else if (0xf0 == (*str & 0xf8)) /* 4 byte code */ { if (errcheck) { if (i + 4 > ilen || 0 == (str[1] & 0x80) || 0 == (str[2] & 0x80) || 0 == (str[3] & 0x80)) { ocount = (SQLULEN) -1; goto cleanup; } } if (ocount < bufcount) { wcode = (surrog1_bits | ((((UInt4) *str) & byte4_m1) << 8) | ((((UInt4) str[1]) & byte4_m2) << 2) | ((((UInt4) str[2]) & byte4_m31) >> 4)) - surrogate_adjust; ucs2str[ocount] = (SQLWCHAR) wcode; } ocount++; if (ocount < bufcount) { wcode = surrog2_bits | ((((UInt4) str[2]) & byte4_m32) << 6) | (((UInt4) str[3]) & byte4_m4); ucs2str[ocount] = (SQLWCHAR) wcode; } ocount++; i += 4; str += 4; } else if (0xe0 == (*str & 0xf0)) /* 3 byte code */ { if (errcheck) { if (i + 3 > ilen || 0 == (str[1] & 0x80) || 0 == (str[2] & 0x80)) { ocount = (SQLULEN) -1; goto cleanup; } } if (ocount < bufcount) { wcode = ((((UInt4) *str) & byte3_m1) << 12) | ((((UInt4) str[1]) & byte3_m2) << 6) | (((UInt4) str[2]) & byte3_m3); ucs2str[ocount] = (SQLWCHAR) wcode; } ocount++; i += 3; str += 3; } else if (0xc0 == (*str & 0xe0)) /* 2 byte code */ { if (errcheck) { if (i + 2 > ilen || 0 == (str[1] & 0x80)) { ocount = (SQLULEN) -1; goto cleanup; } } if (ocount < bufcount) { wcode = ((((UInt4) *str) & byte2_m1) << 6) | (((UInt4) str[1]) & byte2_m2); ucs2str[ocount] = (SQLWCHAR) wcode; } ocount++; i += 2; str += 2; } else { ocount = (SQLULEN) -1; goto cleanup; } } cleanup: rtn = ocount; if (ocount == (SQLULEN) -1) { if (!errcheck) rtn = 0; ocount = 0; } if (ocount < bufcount && ucs2str) ucs2str[ocount] = 0; /*mylog(" ocount=%d\n", ocount);*/ return rtn; } int msgtowstr(const char *enc, const char *inmsg, int inlen, LPWSTR outmsg, int buflen) { int outlen; #ifdef WIN32 int wlen, cp = CP_ACP; if (NULL != enc && 0 != atoi(enc)) cp = atoi(enc); wlen = MultiByteToWideChar(cp, MB_PRECOMPOSED | MB_ERR_INVALID_CHARS, inmsg, inlen, outmsg, buflen); mylog(" out=%dchars\n", wlen); outlen = wlen; #else #ifdef HAVE_MBSTOWCS_L outlen = 0; #else outlen = 0; #endif /* HAVE_MBSTOWCS_L */ #endif /* WIN32 */ if (outlen < buflen) outmsg[outlen] = 0; return outlen; } int wstrtomsg(const char *enc, const LPWSTR wstr, int wstrlen, char * outmsg, int buflen) { int outlen; #ifdef WIN32 int len, cp = CP_ACP; if (NULL != enc && 0 != atoi(enc)) cp = atoi(enc); len = WideCharToMultiByte(cp, 0, wstr, (int) wstrlen, outmsg, buflen, NULL, NULL); outlen = len; #else #ifdef HAVE_MBSTOWCS_L outlen = 0; #else outlen = 0; #endif /* HAVE_MBSTOWCS_L */ #endif /* WIN32 */ if (outlen < buflen) outmsg[outlen] = 0; return outlen; } psqlodbc-09.03.0300/license.txt000644 001752 000000 00000062222 12335653444 016367 0ustar00saitowheel000000 000000 GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! psqlodbc-09.03.0300/readme.txt000644 001752 000000 00000002541 12335653444 016200 0ustar00saitowheel000000 000000 /******************************************************************** PSQLODBC.DLL - A library to talk to the PostgreSQL DBMS using ODBC. Copyright (C) 1998 Insight Distribution Systems Copyright (C) 1998 - 2013 The PostgreSQL Global Development Group Multibyte support was added by Sankyo Unyu Service, (C) 2001. The code contained in this library is based on code written by Christian Czezatke and Dan McGuirk, (C) 1996. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library (see "license.txt"); if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. How to contact the authors: email: pgsql-odbc@postgresql.org website: http://pgfoundry.org/projects/psqlodbc ***********************************************************************/ psqlodbc-09.03.0300/readme_winbuild.txt000644 001752 000000 00000003241 12335653444 020073 0ustar00saitowheel000000 000000 /******************************************************************** BuildAll.bat - A Windows batch script to build all dlls for psqlodbc. You can also use the same functionality using Powershell at winbuild folder. See .\winbuild\readme.txt. 1. You have to install one of the following. . Visual Studio 2013 non-Express edtion or Express 2013 for Windows Desktop . Visual Studio 2012 non-Express edtion or Express 2012 for Windows Desktop . Full Microsoft Visual C++ 2010 . Windows SDK 7.1 You have to include x64 development tools (bin, lib, include) as well as x86 ones for the installation. Please start a command prompt and 2. Set the ExecutionPolicy of Powershell to RemoteSigned or Unrestricted. You can get the ExecutionPolicy by typing powershell Get-ExecutionPolicy When the ExectionPolicy is "Restricted" or "AllSigned" then type e.g. powershell Set-ExecutionPolicy RemoteSigned To see details about ExecutionPolicy, type powershell Get-Help about_Execution_Policies 3. Please type .\editConfiguration(.bat) and edit the setting of your environment especially the folders you placed libpq/Openssl related include/lib files. 4. Please type .\BuildAll(.bat) to invoke build operations. If the automatically selected VisualStudioVersion is inappropriate and the desired version is e.g. 11.0, type .\BuildAll(.bat) -V(CVersion) 11.0 or set the value 11.0 to Configuration.vcver attribute of the configuration file. To see details about the use of BuildAll, type .\BuildAll(.bat) /? . ***********************************************************************/ psqlodbc-09.03.0300/psqlodbc.def000644 001752 000000 00000004042 12335653444 016467 0ustar00saitowheel000000 000000 LIBRARY psqlodbc35w EXPORTS ;;SQLAllocConnect @1 ;;SQLAllocEnv @2 ;;SQLAllocStmt @3 SQLBindCol @4 SQLCancel @5 ;;SQLColAttributes @6 ;SQLConnect @7 ;SQLDescribeCol @8 SQLDisconnect @9 ;;SQLError @10 ;SQLExecDirect @11 SQLExecute @12 SQLFetch @13 ;;SQLFreeConnect @14 ;;SQLFreeEnv @15 SQLFreeStmt @16 ;SQLGetCursorName @17 SQLNumResultCols @18 ;SQLPrepare @19 SQLRowCount @20 ;SQLSetCursorName @21 ;;SQLTransact @23 ;SQLColumns @40 ;SQLDriverConnect @41 SQLGetData @43 SQLGetFunctions @44 ;SQLGetInfo @45 ;;SQLGetStmtOption @46 ;SQLGetTypeInfo @47 SQLParamData @48 SQLPutData @49 ;SQLSpecialColumns @52 ;SQLStatistics @53 ;SQLTables @54 SQLBrowseConnect @55 ;SQLColumnPrivileges @56 SQLDescribeParam @58 SQLExtendedFetch @59 ;SQLForeignKeys @60 SQLMoreResults @61 ;SQLNativeSql @62 SQLNumParams @63 ;;SQLParamOptions @64 ;SQLPrimaryKeys @65 ;SQLProcedureColumns @66 ;SQLProcedures @67 SQLSetPos @68 SQLSetScrollOptions @69 ;SQLTablePrivileges @70 SQLBindParameter @72 SQLAllocHandle @80 SQLBindParam @81 SQLCloseCursor @82 ;SQLColAttribute @83 SQLCopyDesc @84 SQLEndTran @85 SQLFetchScroll @86 SQLFreeHandle @87 ;SQLGetDescField @88 SQLGetDescRec @89 ;SQLGetDiagField @90 ;SQLGetDiagRec @91 SQLGetEnvAttr @92 ;SQLGetConnectAttr @93 ;SQLGetStmtAttr @94 ;SQLSetConnectAttr @95 ;SQLSetDescField @96 SQLSetDescRec @97 SQLSetEnvAttr @98 SQLSetStmtAttr @99 SQLBulkOperations @100 SQLDummyOrdinal @199 dconn_FDriverConnectProc @200 DllMain @201 ConfigDSN @202 ConfigDriver @203 SQLColAttributeW @101 SQLColumnPrivilegesW @102 SQLColumnsW @103 SQLConnectW @104 SQLDescribeColW @106 SQLExecDirectW @107 SQLForeignKeysW @108 SQLGetConnectAttrW @109 SQLGetCursorNameW @110 SQLGetInfoW @111 SQLNativeSqlW @112 SQLPrepareW @113 SQLPrimaryKeysW @114 SQLProcedureColumnsW @115 SQLProceduresW @116 SQLSetConnectAttrW @117 SQLSetCursorNameW @118 SQLSpecialColumnsW @119 SQLStatisticsW @120 SQLTablesW @121 SQLTablePrivilegesW @122 SQLDriverConnectW @123 SQLGetDiagRecW @124 SQLGetStmtAttrW @125 SQLSetStmtAttrW @126 SQLSetDescFieldW @127 SQLGetTypeInfoW @128 SQLGetDiagFieldW @129 psqlodbc-09.03.0300/psqlodbca.def000644 001752 000000 00000002743 12335653444 016636 0ustar00saitowheel000000 000000 LIBRARY psqlodbc30a EXPORTS ;SQLAllocConnect @1 ;SQLAllocEnv @2 ;SQLAllocStmt @3 SQLBindCol @4 SQLCancel @5 ; SQLColAttributes @6 SQLConnect @7 SQLDescribeCol @8 SQLDisconnect @9 ;SQLError @10 SQLExecDirect @11 SQLExecute @12 SQLFetch @13 ;SQLFreeConnect @14 ;SQLFreeEnv @15 SQLFreeStmt @16 SQLGetCursorName @17 SQLNumResultCols @18 SQLPrepare @19 SQLRowCount @20 SQLSetCursorName @21 ;SQLTransact @23 SQLColumns @40 SQLDriverConnect @41 ;SQLGetConnectOption @42 SQLGetData @43 SQLGetFunctions @44 SQLGetInfo @45 ;SQLGetStmtOption @46 SQLGetTypeInfo @47 SQLParamData @48 SQLPutData @49 ;SQLSetConnectOption @50 ;SQLSetStmtOption @51 SQLSpecialColumns @52 SQLStatistics @53 SQLTables @54 SQLBrowseConnect @55 SQLColumnPrivileges @56 SQLDescribeParam @58 SQLExtendedFetch @59 SQLForeignKeys @60 SQLMoreResults @61 SQLNativeSql @62 SQLNumParams @63 ;SQLParamOptions @64 SQLPrimaryKeys @65 SQLProcedureColumns @66 SQLProcedures @67 SQLSetPos @68 SQLSetScrollOptions @69 SQLTablePrivileges @70 SQLBindParameter @72 SQLAllocHandle @80 SQLBindParam @81 SQLCloseCursor @82 SQLColAttribute @83 SQLCopyDesc @84 SQLEndTran @85 SQLFetchScroll @86 SQLFreeHandle @87 SQLGetDescField @88 SQLGetDescRec @89 SQLGetDiagField @90 SQLGetDiagRec @91 SQLGetEnvAttr @92 SQLGetConnectAttr @93 SQLGetStmtAttr @94 SQLSetConnectAttr @95 SQLSetDescField @96 SQLSetDescRec @97 SQLSetEnvAttr @98 SQLSetStmtAttr @99 SQLBulkOperations @100 SQLDummyOrdinal @199 dconn_FDriverConnectProc @200 DllMain @201 ConfigDSN @202 ConfigDriver @203 psqlodbc-09.03.0300/editConfiguration.bat000755 001752 000000 00000000220 12335653444 020342 0ustar00saitowheel000000 000000 :: :: Start editConfiguration with a mimimized console window :: powershell -Sta -WindowStyle Minimized %~dp0\winbuild\editConfiguration.ps1 %* psqlodbc-09.03.0300/BuildAll.bat000755 001752 000000 00000000433 12335653444 016363 0ustar00saitowheel000000 000000 :: :: Build all dlls of psqlodbc project :: @echo off if "%1" == "/?" ( powershell Get-Help %~dp0\winbuild\BuildAll.ps1 -detailed ) else if "%1" == "-?" ( powershell Get-Help %~dp0\winbuild\BuildAll.ps1 %2 %3 %4 %5 %6 %7 %8 %9 ) else ( powershell %~dp0\winbuild\BuildAll.ps1 %* ) psqlodbc-09.03.0300/pgenlist.def000644 001752 000000 00000000104 12335653444 016500 0ustar00saitowheel000000 000000 LIBRARY pgenlist EXPORTS EnlistInDtc DtcOnDisconnect IsolateDtcConn psqlodbc-09.03.0300/pgenlista.def000644 001752 000000 00000000105 12335653444 016642 0ustar00saitowheel000000 000000 LIBRARY pgenlista EXPORTS EnlistInDtc DtcOnDisconnect IsolateDtcConn psqlodbc-09.03.0300/connexp.h000644 001752 000000 00000003701 12335653444 016024 0ustar00saitowheel000000 000000 /* File: connexp.h * * Description: See "connection.c" * * Comments: See "notice.txt" for copyright and license information. * */ #ifndef __CONNEXPORT_H__ #define __CONNEXPORT_H__ /* * The psqlodbc dll exports functions below used in the pgenlist dll. * */ #undef DLL_DECLARE #ifdef _PGDTC_FUNCS_IMPLEMENT_ #define DLL_DECLARE _declspec(dllexport) #else #ifdef _PGDTC_FUNCS_IMPORT_ #define DLL_DECLARE _declspec(dllimport) #else #define DLL_DECLARE #endif /* _PGDTC_FUNC_IMPORT_ */ #endif /* _PGDTC_FUNCS_IMPLEMENT_ */ #ifdef __cplusplus extern "C" { #endif /* Property */ enum { inprogress ,enlisted ,inTrans /* read-only */ ,errorNumber /* read_only */ ,idleInGlobalTransaction /* read-only */ ,connected /* read-only */ ,prepareRequested }; /* PgDtc_isolate option */ enum { disposingConnection = 1L ,useAnotherRoom = (1L << 1) }; /* One phase commit operations */ enum { ONE_PHASE_COMMIT = 0 ,ONE_PHASE_ROLLBACK ,ABORT_GLOBAL_TRANSACTION ,SHUTDOWN_LOCAL_TRANSACTION }; /* Two phase commit operations */ enum { PREPARE_TRANSACTION = 0 ,COMMIT_PREPARED ,ROLLBACK_PREPARED }; DLL_DECLARE void PgDtc_create_connect_string(void *self, char *connstr, int strsize); DLL_DECLARE void PgDtc_set_async(void *self, void *async); DLL_DECLARE void *PgDtc_get_async(void *self); DLL_DECLARE void PgDtc_set_property(void *self, int property, void *value); DLL_DECLARE void PgDtc_set_error(void *self, const char *message, const char *func); DLL_DECLARE int PgDtc_get_property(void *self, int property); DLL_DECLARE BOOL PgDtc_connect(void *self); DLL_DECLARE void PgDtc_free_connect(void *self); DLL_DECLARE BOOL PgDtc_one_phase_operation(void *self, int operation); DLL_DECLARE BOOL PgDtc_two_phase_operation(void *self, int operation, const char *gxid); DLL_DECLARE BOOL PgDtc_lock_cntrl(void *self, BOOL acquire, BOOL bTrial); DLL_DECLARE void *PgDtc_isolate(void *self, DWORD option); #ifdef __cplusplus } #endif #endif /* __CONNEXPORT_H__ */ psqlodbc-09.03.0300/dlg_wingui.c000644 001752 000000 00000056120 12335653444 016500 0ustar00saitowheel000000 000000 #ifdef WIN32 /*------- * Module: dlg_wingui.c * * Description: This module contains any specific code for handling * dialog boxes such as driver/datasource options. Both the * ConfigDSN() and the SQLDriverConnect() functions use * functions in this module. If you were to add a new option * to any dialog box, you would most likely only have to change * things in here rather than in 2 separate places as before. * * Classes: none * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ /* Multibyte support Eiji Tokuya 2001-03-15 */ #include "dlg_specific.h" #include "misc.h" // strncpy_null #include "win_setup.h" #include "convert.h" #include "loadlib.h" #include "multibyte.h" #include "pgapifunc.h" extern GLOBAL_VALUES globals; extern HINSTANCE NEAR s_hModule; static int driver_optionsDraw(HWND, const ConnInfo *, int src, BOOL enable); static int driver_options_update(HWND hdlg, ConnInfo *ci, const char *); static struct { int ids; const char * const modestr; } modetab[] = { {IDS_SSLREQUEST_DISABLE, SSLMODE_DISABLE} , {IDS_SSLREQUEST_ALLOW, SSLMODE_ALLOW} , {IDS_SSLREQUEST_PREFER, SSLMODE_PREFER} , {IDS_SSLREQUEST_REQUIRE, SSLMODE_REQUIRE} , {IDS_SSLREQUEST_VERIFY_CA, SSLMODE_VERIFY_CA} , {IDS_SSLREQUEST_VERIFY_FULL, SSLMODE_VERIFY_FULL} }; static int dspcount_bylevel[] = {1, 4, 6}; void SetDlgStuff(HWND hdlg, const ConnInfo *ci) { char buff[MEDIUM_REGISTRY_LEN + 1]; BOOL libpq_exist = FALSE; int i, dsplevel, selidx, dspcount; /* * If driver attribute NOT present, then set the datasource name and * description */ SetDlgItemText(hdlg, IDC_DSNAME, ci->dsn); SetDlgItemText(hdlg, IDC_DESC, ci->desc); SetDlgItemText(hdlg, IDC_DATABASE, ci->database); SetDlgItemText(hdlg, IDC_SERVER, ci->server); SetDlgItemText(hdlg, IDC_USER, ci->username); SetDlgItemText(hdlg, IDC_PASSWORD, SAFE_NAME(ci->password)); SetDlgItemText(hdlg, IDC_PORT, ci->port); dsplevel = 0; #ifdef USE_LIBPQ libpq_exist = SSLLIB_check(); mylog("libpq_exist=%d\n", libpq_exist); if (libpq_exist) { ShowWindow(GetDlgItem(hdlg, IDC_NOTICE_USER), SW_HIDE); dsplevel = 2; } else #endif /* USE_LIBPQ */ { mylog("SendMessage CTL_COLOR\n"); SendMessage(GetDlgItem(hdlg, IDC_NOTICE_USER), WM_CTLCOLOR, 0, 0); #ifdef USE_SSPI ShowWindow(GetDlgItem(hdlg, IDC_NOTICE_USER), SW_HIDE); dsplevel = 2; #endif /* USE_SSPI */ } selidx = -1; for (i = 0; i < sizeof(modetab) / sizeof(modetab[0]); i++) { if (!stricmp(ci->sslmode, modetab[i].modestr)) { selidx = i; break; } } for (i = dsplevel; i < sizeof(dspcount_bylevel) / sizeof(int); i++) { if (selidx < dspcount_bylevel[i]) break; dsplevel++; } dspcount = dspcount_bylevel[dsplevel]; for (i = 0; i < dspcount; i++) { LoadString(GetWindowInstance(hdlg), modetab[i].ids, buff, MEDIUM_REGISTRY_LEN); SendDlgItemMessage(hdlg, IDC_SSLMODE, CB_ADDSTRING, 0, (WPARAM) buff); } SendDlgItemMessage(hdlg, IDC_SSLMODE, CB_SETCURSEL, selidx, (WPARAM) 0); } void GetDlgStuff(HWND hdlg, ConnInfo *ci) { int sslposition; char medium_buf[MEDIUM_REGISTRY_LEN]; GetDlgItemText(hdlg, IDC_DESC, ci->desc, sizeof(ci->desc)); GetDlgItemText(hdlg, IDC_DATABASE, ci->database, sizeof(ci->database)); GetDlgItemText(hdlg, IDC_SERVER, ci->server, sizeof(ci->server)); GetDlgItemText(hdlg, IDC_USER, ci->username, sizeof(ci->username)); GetDlgItemText(hdlg, IDC_PASSWORD, medium_buf, sizeof(medium_buf)); STR_TO_NAME(ci->password, medium_buf); GetDlgItemText(hdlg, IDC_PORT, ci->port, sizeof(ci->port)); sslposition = (int)(DWORD)SendMessage(GetDlgItem(hdlg, IDC_SSLMODE), CB_GETCURSEL, 0L, 0L); strncpy_null(ci->sslmode, modetab[sslposition].modestr, sizeof(ci->sslmode)); } static int driver_optionsDraw(HWND hdlg, const ConnInfo *ci, int src, BOOL enable) { const GLOBAL_VALUES *comval; static BOOL defset = FALSE; static GLOBAL_VALUES defval; switch (src) { case 0: /* driver common */ comval = &globals; break; case 1: /* dsn specific */ comval = &(ci->drivers); break; case 2: /* default */ if (!defset) { defval.commlog = DEFAULT_COMMLOG; defval.disable_optimizer = DEFAULT_OPTIMIZER; defval.ksqo = DEFAULT_KSQO; defval.unique_index = DEFAULT_UNIQUEINDEX; defval.onlyread = DEFAULT_READONLY; defval.use_declarefetch = DEFAULT_USEDECLAREFETCH; defval.parse = DEFAULT_PARSE; defval.cancel_as_freestmt = DEFAULT_CANCELASFREESTMT; defval.debug = DEFAULT_DEBUG; /* Unknown Sizes */ defval.unknown_sizes = DEFAULT_UNKNOWNSIZES; defval.text_as_longvarchar = DEFAULT_TEXTASLONGVARCHAR; defval.unknowns_as_longvarchar = DEFAULT_UNKNOWNSASLONGVARCHAR; defval.bools_as_char = DEFAULT_BOOLSASCHAR; } defset = TRUE; comval = &defval; break; } ShowWindow(GetDlgItem(hdlg, DRV_MSG_LABEL2), enable ? SW_SHOW : SW_HIDE); CheckDlgButton(hdlg, DRV_COMMLOG, comval->commlog); #ifndef Q_LOG EnableWindow(GetDlgItem(hdlg, DRV_COMMLOG), FALSE); #endif /* Q_LOG */ CheckDlgButton(hdlg, DRV_OPTIMIZER, comval->disable_optimizer); CheckDlgButton(hdlg, DRV_KSQO, comval->ksqo); CheckDlgButton(hdlg, DRV_UNIQUEINDEX, comval->unique_index); /* EnableWindow(GetDlgItem(hdlg, DRV_UNIQUEINDEX), enable); */ CheckDlgButton(hdlg, DRV_READONLY, comval->onlyread); EnableWindow(GetDlgItem(hdlg, DRV_READONLY), enable); CheckDlgButton(hdlg, DRV_USEDECLAREFETCH, comval->use_declarefetch); /* Unknown Sizes clear */ CheckDlgButton(hdlg, DRV_UNKNOWN_DONTKNOW, 0); CheckDlgButton(hdlg, DRV_UNKNOWN_LONGEST, 0); CheckDlgButton(hdlg, DRV_UNKNOWN_MAX, 0); /* Unknown (Default) Data Type sizes */ switch (comval->unknown_sizes) { case UNKNOWNS_AS_DONTKNOW: CheckDlgButton(hdlg, DRV_UNKNOWN_DONTKNOW, 1); break; case UNKNOWNS_AS_LONGEST: CheckDlgButton(hdlg, DRV_UNKNOWN_LONGEST, 1); break; case UNKNOWNS_AS_MAX: default: CheckDlgButton(hdlg, DRV_UNKNOWN_MAX, 1); break; } CheckDlgButton(hdlg, DRV_TEXT_LONGVARCHAR, comval->text_as_longvarchar); CheckDlgButton(hdlg, DRV_UNKNOWNS_LONGVARCHAR, comval->unknowns_as_longvarchar); CheckDlgButton(hdlg, DRV_BOOLS_CHAR, comval->bools_as_char); CheckDlgButton(hdlg, DRV_PARSE, comval->parse); CheckDlgButton(hdlg, DRV_CANCELASFREESTMT, comval->cancel_as_freestmt); CheckDlgButton(hdlg, DRV_DEBUG, comval->debug); #ifndef MY_LOG EnableWindow(GetDlgItem(hdlg, DRV_DEBUG), FALSE); #endif /* MY_LOG */ SetDlgItemInt(hdlg, DRV_CACHE_SIZE, comval->fetch_max, FALSE); SetDlgItemInt(hdlg, DRV_VARCHAR_SIZE, comval->max_varchar_size, FALSE); SetDlgItemInt(hdlg, DRV_LONGVARCHAR_SIZE, comval->max_longvarchar_size, TRUE); SetDlgItemText(hdlg, DRV_EXTRASYSTABLEPREFIXES, comval->extra_systable_prefixes); /* Driver Connection Settings */ SetDlgItemText(hdlg, DRV_CONNSETTINGS, SAFE_NAME(comval->conn_settings)); EnableWindow(GetDlgItem(hdlg, DRV_CONNSETTINGS), enable); ShowWindow(GetDlgItem(hdlg, IDPREVPAGE), enable ? SW_HIDE : SW_SHOW); ShowWindow(GetDlgItem(hdlg, IDNEXTPAGE), enable ? SW_HIDE : SW_SHOW); return 0; } static int driver_options_update(HWND hdlg, ConnInfo *ci, const char *updateDriver) { GLOBAL_VALUES *comval; if (ci) comval = &(ci->drivers); else comval = &globals; comval->commlog = IsDlgButtonChecked(hdlg, DRV_COMMLOG); comval->disable_optimizer = IsDlgButtonChecked(hdlg, DRV_OPTIMIZER); comval->ksqo = IsDlgButtonChecked(hdlg, DRV_KSQO); comval->unique_index = IsDlgButtonChecked(hdlg, DRV_UNIQUEINDEX); if (!ci) { comval->onlyread = IsDlgButtonChecked(hdlg, DRV_READONLY); } comval->use_declarefetch = IsDlgButtonChecked(hdlg, DRV_USEDECLAREFETCH); /* Unknown (Default) Data Type sizes */ if (IsDlgButtonChecked(hdlg, DRV_UNKNOWN_MAX)) comval->unknown_sizes = UNKNOWNS_AS_MAX; else if (IsDlgButtonChecked(hdlg, DRV_UNKNOWN_DONTKNOW)) comval->unknown_sizes = UNKNOWNS_AS_DONTKNOW; else if (IsDlgButtonChecked(hdlg, DRV_UNKNOWN_LONGEST)) comval->unknown_sizes = UNKNOWNS_AS_LONGEST; else comval->unknown_sizes = UNKNOWNS_AS_MAX; comval->text_as_longvarchar = IsDlgButtonChecked(hdlg, DRV_TEXT_LONGVARCHAR); comval->unknowns_as_longvarchar = IsDlgButtonChecked(hdlg, DRV_UNKNOWNS_LONGVARCHAR); comval->bools_as_char = IsDlgButtonChecked(hdlg, DRV_BOOLS_CHAR); comval->parse = IsDlgButtonChecked(hdlg, DRV_PARSE); comval->cancel_as_freestmt = IsDlgButtonChecked(hdlg, DRV_CANCELASFREESTMT); comval->debug = IsDlgButtonChecked(hdlg, DRV_DEBUG); comval->fetch_max = GetDlgItemInt(hdlg, DRV_CACHE_SIZE, NULL, FALSE); comval->max_varchar_size = GetDlgItemInt(hdlg, DRV_VARCHAR_SIZE, NULL, FALSE); comval->max_longvarchar_size = GetDlgItemInt(hdlg, DRV_LONGVARCHAR_SIZE, NULL, TRUE); /* allows for * SQL_NO_TOTAL */ GetDlgItemText(hdlg, DRV_EXTRASYSTABLEPREFIXES, comval->extra_systable_prefixes, sizeof(comval->extra_systable_prefixes)); /* Driver Connection Settings */ if (!ci) { char conn_settings[LARGE_REGISTRY_LEN]; GetDlgItemText(hdlg, DRV_CONNSETTINGS, conn_settings, sizeof(conn_settings)); if ('\0' != conn_settings[0]) STR_TO_NAME(comval->conn_settings, conn_settings); } if (updateDriver) { if (writeDriverCommoninfo(ODBCINST_INI, updateDriver, comval) < 0) MessageBox(hdlg, "impossible to update the values, sorry", "Update Error", MB_ICONEXCLAMATION | MB_OK); ; } /* fall through */ return 0; } LRESULT CALLBACK driver_optionsProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci; char strbuf[128]; switch (wMsg) { case WM_INITDIALOG: SetWindowLongPtr(hdlg, DWLP_USER, lParam); /* save for OK etc */ ci = (ConnInfo *) lParam; LoadString(s_hModule, IDS_ADVANCE_OPTION_DEF, strbuf, sizeof(strbuf)); SetWindowText(hdlg, strbuf); LoadString(s_hModule, IDS_ADVANCE_SAVE, strbuf, sizeof(strbuf)); SetWindowText(GetDlgItem(hdlg, IDOK), strbuf); ShowWindow(GetDlgItem(hdlg, IDAPPLY), SW_HIDE); driver_optionsDraw(hdlg, ci, 0, TRUE); break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); driver_options_update(hdlg, NULL, ci ? ci->drivername : NULL); case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; case IDDEFAULTS: driver_optionsDraw(hdlg, NULL, 2, TRUE); break; } } return FALSE; } #ifdef _HANDLE_ENLIST_IN_DTC_ static HMODULE DtcProc(const char *procname, FARPROC *proc) { HMODULE hmodule; *proc = NULL; if (hmodule = LoadLibrary(GetXaLibPath()), NULL != hmodule) { mylog("GetProcAddres for %s\n", procname); *proc = GetProcAddress(hmodule, procname); } return hmodule; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ LRESULT CALLBACK global_optionsProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { #ifdef _HANDLE_ENLIST_IN_DTC_ HMODULE hmodule; FARPROC proc; #endif /* _HANDLE_ENLIST_IN_DTC_ */ char logdir[PATH_MAX]; switch (wMsg) { case WM_INITDIALOG: CheckDlgButton(hdlg, DRV_COMMLOG, globals.commlog); #ifndef Q_LOG EnableWindow(GetDlgItem(hdlg, DRV_COMMLOG), FALSE); #endif /* Q_LOG */ CheckDlgButton(hdlg, DRV_DEBUG, globals.debug); #ifndef MY_LOG EnableWindow(GetDlgItem(hdlg, DRV_DEBUG), FALSE); #endif /* MY_LOG */ getLogDir(logdir, sizeof(logdir)); SetDlgItemText(hdlg, DS_LOGDIR, logdir); #ifdef _HANDLE_ENLIST_IN_DTC_ hmodule = DtcProc("GetMsdtclog", &proc); if (proc) { INT_PTR res = (*proc)(); CheckDlgButton(hdlg, DRV_DTCLOG, 0 != res); } else EnableWindow(GetDlgItem(hdlg, DRV_DTCLOG), FALSE); if (hmodule) FreeLibrary(hmodule); #else ShowWindow(GetDlgItem(hdlg, DRV_DTCLOG), SW_HIDE); #endif /* _HANDLE_ENLIST_IN_DTC_ */ break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: globals.commlog = IsDlgButtonChecked(hdlg, DRV_COMMLOG); globals.debug = IsDlgButtonChecked(hdlg, DRV_DEBUG); if (writeDriverCommoninfo(ODBCINST_INI, NULL, &globals) < 0) MessageBox(hdlg, "Sorry, impossible to update the values\nWrite permission seems to be needed", "Update Error", MB_ICONEXCLAMATION | MB_OK); GetDlgItemText(hdlg, DS_LOGDIR, logdir, sizeof(logdir)); setLogDir(logdir[0] ? logdir : NULL); #ifdef _HANDLE_ENLIST_IN_DTC_ hmodule = DtcProc("SetMsdtclog", &proc); if (proc) (*proc)(IsDlgButtonChecked(hdlg, DRV_DTCLOG)); if (hmodule) FreeLibrary(hmodule); #endif /* _HANDLE_ENLIST_IN_DTC_ */ case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; } } return FALSE; } LRESULT CALLBACK ds_options1Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci; char strbuf[128]; switch (wMsg) { case WM_INITDIALOG: SetWindowLongPtr(hdlg, DWLP_USER, lParam); /* save for OK etc */ ci = (ConnInfo *) lParam; if (ci && ci->dsn && ci->dsn[0]) { DWORD cmd; char fbuf[64]; cmd = LoadString(s_hModule, IDS_ADVANCE_OPTION_DSN1, fbuf, sizeof(fbuf)); if (cmd <= 0) strcpy(fbuf, "Advanced Options (%s) 1/2"); sprintf(strbuf, fbuf, ci->dsn); SetWindowText(hdlg, strbuf); } else { LoadString(s_hModule, IDS_ADVANCE_OPTION_CON1, strbuf, sizeof(strbuf)); SetWindowText(hdlg, strbuf); ShowWindow(GetDlgItem(hdlg, IDAPPLY), SW_HIDE); } driver_optionsDraw(hdlg, ci, 1, FALSE); break; case WM_COMMAND: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: driver_options_update(hdlg, ci, NULL); case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; case IDAPPLY: driver_options_update(hdlg, ci, NULL); SendMessage(GetWindow(hdlg, GW_OWNER), WM_COMMAND, wParam, lParam); break; case IDDEFAULTS: driver_optionsDraw(hdlg, ci, 0, FALSE); break; case IDNEXTPAGE: driver_options_update(hdlg, ci, NULL); EndDialog(hdlg, FALSE); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DS), hdlg, ds_options2Proc, (LPARAM) ci); break; } } return FALSE; } LRESULT CALLBACK ds_options2Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci; char buf[128]; DWORD cmd; BOOL enable; switch (wMsg) { case WM_INITDIALOG: ci = (ConnInfo *) lParam; SetWindowLongPtr(hdlg, DWLP_USER, lParam); /* save for OK */ /* Change window caption */ if (ci && ci->dsn && ci->dsn[0]) { char fbuf[64]; cmd = LoadString(s_hModule, IDS_ADVANCE_OPTION_DSN2, fbuf, sizeof(fbuf)); if (cmd <= 0) strcpy(fbuf, "Advanced Options (%s) 2/2"); sprintf(buf, fbuf, ci->dsn); SetWindowText(hdlg, buf); } else { LoadString(s_hModule, IDS_ADVANCE_OPTION_CON2, buf, sizeof(buf)); SetWindowText(hdlg, buf); ShowWindow(GetDlgItem(hdlg, IDAPPLY), SW_HIDE); } /* Readonly */ CheckDlgButton(hdlg, DS_READONLY, atoi(ci->onlyread)); /* Protocol */ enable = (ci->sslmode[0] == SSLLBYTE_DISABLE || ci->username[0] == '\0'); EnableWindow(GetDlgItem(hdlg, DS_PG62), enable); EnableWindow(GetDlgItem(hdlg, DS_PG63), enable); EnableWindow(GetDlgItem(hdlg, DS_PG64), enable); EnableWindow(GetDlgItem(hdlg, DS_PG74), enable); if (PROTOCOL_62(ci)) CheckDlgButton(hdlg, DS_PG62, 1); else if (PROTOCOL_63(ci)) CheckDlgButton(hdlg, DS_PG63, 1); else if (PROTOCOL_64(ci)) CheckDlgButton(hdlg, DS_PG64, 1); else /* latest */ CheckDlgButton(hdlg, DS_PG74, 1); /* How to issue Rollback */ switch (ci->rollback_on_error) { case 0: CheckDlgButton(hdlg, DS_NO_ROLLBACK, 1); break; case 1: CheckDlgButton(hdlg, DS_TRANSACTION_ROLLBACK, 1); break; case 2: CheckDlgButton(hdlg, DS_STATEMENT_ROLLBACK, 1); break; } /* Int8 As */ switch (ci->int8_as) { case SQL_BIGINT: CheckDlgButton(hdlg, DS_INT8_AS_BIGINT, 1); break; case SQL_NUMERIC: CheckDlgButton(hdlg, DS_INT8_AS_NUMERIC, 1); break; case SQL_VARCHAR: CheckDlgButton(hdlg, DS_INT8_AS_VARCHAR, 1); break; case SQL_DOUBLE: CheckDlgButton(hdlg, DS_INT8_AS_DOUBLE, 1); break; case SQL_INTEGER: CheckDlgButton(hdlg, DS_INT8_AS_INT4, 1); break; default: CheckDlgButton(hdlg, DS_INT8_AS_DEFAULT, 1); } sprintf(buf, "0x%x", getExtraOptions(ci)); SetDlgItemText(hdlg, DS_EXTRA_OPTIONS, buf); CheckDlgButton(hdlg, DS_SHOWOIDCOLUMN, atoi(ci->show_oid_column)); CheckDlgButton(hdlg, DS_FAKEOIDINDEX, atoi(ci->fake_oid_index)); CheckDlgButton(hdlg, DS_ROWVERSIONING, atoi(ci->row_versioning)); CheckDlgButton(hdlg, DS_SHOWSYSTEMTABLES, atoi(ci->show_system_tables)); CheckDlgButton(hdlg, DS_DISALLOWPREMATURE, ci->disallow_premature); CheckDlgButton(hdlg, DS_LFCONVERSION, ci->lf_conversion); CheckDlgButton(hdlg, DS_TRUEISMINUS1, ci->true_is_minus1); CheckDlgButton(hdlg, DS_UPDATABLECURSORS, ci->allow_keyset); CheckDlgButton(hdlg, DS_SERVERSIDEPREPARE, ci->use_server_side_prepare); CheckDlgButton(hdlg, DS_BYTEAASLONGVARBINARY, ci->bytea_as_longvarbinary); /*CheckDlgButton(hdlg, DS_LOWERCASEIDENTIFIER, ci->lower_case_identifier);*/ CheckDlgButton(hdlg, DS_GSSAUTHUSEGSSAPI, ci->gssauth_use_gssapi); #if !defined(USE_LIBPQ) && !defined(USE_SSPI) && !defined(USE_GSS) EnableWindow(GetDlgItem(hdlg, DS_GSSAUTHUSEGSSAPI), FALSE); #endif EnableWindow(GetDlgItem(hdlg, DS_FAKEOIDINDEX), atoi(ci->show_oid_column)); /* Datasource Connection Settings */ SetDlgItemText(hdlg, DS_CONNSETTINGS, SAFE_NAME(ci->conn_settings)); break; case WM_COMMAND: switch (cmd = GET_WM_COMMAND_ID(wParam, lParam)) { case DS_SHOWOIDCOLUMN: mylog("WM_COMMAND: DS_SHOWOIDCOLUMN\n"); EnableWindow(GetDlgItem(hdlg, DS_FAKEOIDINDEX), IsDlgButtonChecked(hdlg, DS_SHOWOIDCOLUMN)); return TRUE; case IDOK: case IDAPPLY: case IDPREVPAGE: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); mylog("IDOK: got ci = %p\n", ci); /* Readonly */ sprintf(ci->onlyread, "%d", IsDlgButtonChecked(hdlg, DS_READONLY)); /* Protocol */ if (IsDlgButtonChecked(hdlg, DS_PG62)) strcpy(ci->protocol, PG62); else if (IsDlgButtonChecked(hdlg, DS_PG63)) strcpy(ci->protocol, PG63); else if (IsDlgButtonChecked(hdlg, DS_PG64)) strcpy(ci->protocol, PG64); else /* latest */ strcpy(ci->protocol, PG74); /* Issue rollback command on error */ if (IsDlgButtonChecked(hdlg, DS_NO_ROLLBACK)) ci->rollback_on_error = 0; else if (IsDlgButtonChecked(hdlg, DS_TRANSACTION_ROLLBACK)) ci->rollback_on_error = 1; else if (IsDlgButtonChecked(hdlg, DS_STATEMENT_ROLLBACK)) ci->rollback_on_error = 2; else /* legacy */ ci->rollback_on_error = 1; /* Int8 As */ if (IsDlgButtonChecked(hdlg, DS_INT8_AS_DEFAULT)) ci->int8_as = 0; else if (IsDlgButtonChecked(hdlg, DS_INT8_AS_BIGINT)) ci->int8_as = SQL_BIGINT; else if (IsDlgButtonChecked(hdlg, DS_INT8_AS_NUMERIC)) ci->int8_as = SQL_NUMERIC; else if (IsDlgButtonChecked(hdlg, DS_INT8_AS_DOUBLE)) ci->int8_as = SQL_DOUBLE; else if (IsDlgButtonChecked(hdlg, DS_INT8_AS_INT4)) ci->int8_as = SQL_INTEGER; else ci->int8_as = SQL_VARCHAR; GetDlgItemText(hdlg, DS_EXTRA_OPTIONS, buf, sizeof(buf)); setExtraOptions(ci, buf, NULL); sprintf(ci->show_system_tables, "%d", IsDlgButtonChecked(hdlg, DS_SHOWSYSTEMTABLES)); sprintf(ci->row_versioning, "%d", IsDlgButtonChecked(hdlg, DS_ROWVERSIONING)); ci->disallow_premature = IsDlgButtonChecked(hdlg, DS_DISALLOWPREMATURE); ci->lf_conversion = IsDlgButtonChecked(hdlg, DS_LFCONVERSION); ci->true_is_minus1 = IsDlgButtonChecked(hdlg, DS_TRUEISMINUS1); ci->allow_keyset = IsDlgButtonChecked(hdlg, DS_UPDATABLECURSORS); ci->use_server_side_prepare = IsDlgButtonChecked(hdlg, DS_SERVERSIDEPREPARE); ci->bytea_as_longvarbinary = IsDlgButtonChecked(hdlg, DS_BYTEAASLONGVARBINARY); /*ci->lower_case_identifier = IsDlgButtonChecked(hdlg, DS_LOWERCASEIDENTIFIER);*/ ci->gssauth_use_gssapi = IsDlgButtonChecked(hdlg, DS_GSSAUTHUSEGSSAPI); /* OID Options */ sprintf(ci->fake_oid_index, "%d", IsDlgButtonChecked(hdlg, DS_FAKEOIDINDEX)); sprintf(ci->show_oid_column, "%d", IsDlgButtonChecked(hdlg, DS_SHOWOIDCOLUMN)); /* Datasource Connection Settings */ { char conn_settings[LARGE_REGISTRY_LEN]; GetDlgItemText(hdlg, DS_CONNSETTINGS, conn_settings, sizeof(conn_settings)); if ('\0' != conn_settings[0]) STR_TO_NAME(ci->conn_settings, conn_settings); } if (IDAPPLY == cmd) { SendMessage(GetWindow(hdlg, GW_OWNER), WM_COMMAND, wParam, lParam); break; } EndDialog(hdlg, cmd == IDOK); if (IDOK == cmd) return TRUE; DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, ds_options1Proc, (LPARAM) ci); break; case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; } } return FALSE; } typedef SQLRETURN (SQL_API *SQLAPIPROC)(); static int makeDriversList(HWND lwnd, const ConnInfo *ci) { HMODULE hmodule; SQLHENV henv; int lcount = 0; LRESULT iidx; char drvname[64], drvatt[128]; SQLUSMALLINT direction = SQL_FETCH_FIRST; SQLSMALLINT drvncount, drvacount; SQLRETURN ret; SQLAPIPROC addr; hmodule = GetModuleHandle("ODBC32"); if (!hmodule) return lcount; addr = (SQLAPIPROC) GetProcAddress(hmodule, "SQLAllocEnv"); if (!addr) return lcount; ret = (*addr)(&henv); if (SQL_SUCCESS != ret) return lcount; do { ret = SQLDrivers(henv, direction, drvname, sizeof(drvname), &drvncount, drvatt, sizeof(drvatt), &drvacount); if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret) break; if (strnicmp(drvname, "postgresql", 10) == 0) { iidx = SendMessage(lwnd, LB_ADDSTRING, 0, (LPARAM) drvname); if (LB_ERR != iidx && stricmp(drvname, ci->drivername) == 0) { SendMessage(lwnd, LB_SETCURSEL, (WPARAM) iidx, (LPARAM) 0); } lcount++; } direction = SQL_FETCH_NEXT; } while (1); addr = (SQLAPIPROC) GetProcAddress(hmodule, "SQLFreeEnv"); if (addr) (*addr)(henv); return lcount; } LRESULT CALLBACK manage_dsnProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { LPSETUPDLG lpsetupdlg; ConnInfo *ci; HWND lwnd; LRESULT sidx; char drvname[64]; switch (wMsg) { case WM_INITDIALOG: SetWindowLongPtr(hdlg, DWLP_USER, lParam); lpsetupdlg = (LPSETUPDLG) lParam; ci = &lpsetupdlg->ci; lwnd = GetDlgItem(hdlg, IDC_DRIVER_LIST); makeDriversList(lwnd, ci); break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); lwnd = GetDlgItem(hdlg, IDC_DRIVER_LIST); sidx = SendMessage(lwnd, LB_GETCURSEL, (WPARAM) 0, (LPARAM) 0); if (LB_ERR == sidx) return FALSE; sidx = SendMessage(lwnd, LB_GETTEXT, (WPARAM) sidx, (LPARAM) drvname); if (LB_ERR == sidx) return FALSE; ChangeDriverName(hdlg, lpsetupdlg, drvname); case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; } } return FALSE; } #endif /* WIN32 */ psqlodbc-09.03.0300/inouealc.c000644 001752 000000 00000012221 12335653444 016141 0ustar00saitowheel000000 000000 #undef _MEMORY_DEBUG_ #include "psqlodbc.h" #ifdef WIN32 #ifdef _DEBUG /* #include */ #define _CRTDBG_MAP_ALLOC #include #else #include #endif /* _DEBUG */ #endif /* WIN32 */ #include #include "misc.h" typedef struct { size_t len; void *aladr; } ALADR; static int alsize = 0; static int tbsize = 0; static ALADR *altbl = NULL; CSTR ALCERR = "alcerr"; void * pgdebug_alloc(size_t size) { void * alloced; alloced = malloc(size); inolog(" alloced=%p(%d)\n", alloced, size); if (alloced) { if (!alsize) { alsize = 100; altbl = (ALADR *) malloc(alsize * sizeof(ALADR)); } else if (tbsize >= alsize) { ALADR *al; alsize *= 2; if (al = (ALADR *) realloc(altbl, alsize * sizeof(ALADR)), NULL == al) return alloced; altbl = al; } altbl[tbsize].aladr = alloced; altbl[tbsize].len = size; tbsize++; } else mylog("%s:alloc %dbyte\n", ALCERR, size); return alloced; } void * pgdebug_calloc(size_t n, size_t size) { void * alloced = calloc(n, size); if (alloced) { if (!alsize) { alsize = 100; altbl = (ALADR *) malloc(alsize * sizeof(ALADR)); } else if (tbsize >= alsize) { ALADR *al; alsize *= 2; if (al = (ALADR *) realloc(altbl, alsize * sizeof(ALADR)), NULL == al) return alloced; altbl = al; } altbl[tbsize].aladr = alloced; altbl[tbsize].len = n * size; tbsize++; } else mylog("%s:calloc %dbyte\n", ALCERR, size); inolog("calloced = %p\n", alloced); return alloced; } void * pgdebug_realloc(void * ptr, size_t size) { void * alloced = realloc(ptr, size); if (!alloced) { mylog("%s:%s %p error\n", ALCERR, __FUNCTION__, ptr); } else if (!ptr) { altbl[tbsize].aladr = alloced; altbl[tbsize].len = size; tbsize++; } else /* if (alloced != ptr) */ { int i; for (i = 0; i < tbsize; i++) { if (altbl[i].aladr == ptr) { altbl[i].aladr = alloced; altbl[i].len = size; break; } } } inolog("%s %p->%p\n", __FUNCTION__, ptr, alloced); return alloced; } char * pgdebug_strdup(const char * ptr) { char * alloced = strdup(ptr); if (!alloced) { mylog("%s:%s %p error\n", ALCERR, __FUNCTION__, ptr); } else { if (!alsize) { alsize = 100; altbl = (ALADR *) malloc(alsize * sizeof(ALADR)); } else if (tbsize >= alsize) { ALADR *al; alsize *= 2; if (al = (ALADR *) realloc(altbl, alsize * sizeof(ALADR)), NULL == al) return alloced; altbl = al; } altbl[tbsize].aladr = alloced; altbl[tbsize].len = strlen(ptr) + 1; tbsize++; } inolog("%s %p->%p(%s)\n", __FUNCTION__, ptr, alloced, alloced); return alloced; } void pgdebug_free(void * ptr) { int i, j; int freed = 0; if (!ptr) { mylog("%s:%sing null ptr\n", ALCERR, __FUNCTION__); return; } for (i = 0; i < tbsize; i++) { if (altbl[i].aladr == ptr) { for (j = i; j < tbsize - 1; j++) { altbl[j].aladr = altbl[j + 1].aladr; altbl[j].len = altbl[j + 1].len; } tbsize--; freed = 1; break; } } if (! freed) { mylog("%s:%sing not found ptr %p\n", ALCERR, __FUNCTION__, ptr); return; } else inolog("%sing ptr=%p\n", __FUNCTION__, ptr); free(ptr); } static BOOL out_check(void *out, size_t len, const char *name) { BOOL ret = TRUE; int i; for (i = 0; i < tbsize; i++) { if ((UInt4)out < (UInt4)(altbl[i].aladr)) continue; if ((UInt4)out < (UInt4)(altbl[i].aladr) + altbl[i].len) { if ((UInt4)out + len > (UInt4)(altbl[i].aladr) + altbl[i].len) { ret = FALSE; mylog("%s:%s:out_check found memory buffer overrun %p(%d)>=%p(%d)\n", ALCERR, name, out, len, altbl[i].aladr, altbl[i].len); } break; } } return ret; } char *pgdebug_strcpy(char *out, const char *in) { if (!out || !in) { mylog("%s:%s null pointer out=%p,in=%p\n", ALCERR, __FUNCTION__, out, in); return NULL; } out_check(out, strlen(in) + 1, __FUNCTION__); return strcpy(out, in); } char *pgdebug_strncpy(char *out, const char *in, size_t len) { if (!out || !in) { mylog("%s:%s null pointer out=%p,in=%p\n", ALCERR, __FUNCTION__, out, in); return NULL; } out_check(out, len, __FUNCTION__); return strncpy(out, in, len); } char *pgdebug_strncpy_null(char *out, const char *in, size_t len) { if (!out || !in) { mylog("%s:%s null pointer out=%p,in=%p\n", ALCERR, __FUNCTION__, out, in); return NULL; } out_check(out, len, __FUNCTION__); return strncpy_null(out, in, len); } void *pgdebug_memcpy(void *out, const void *in, size_t len) { if (!out || !in) { mylog("%s:%s null pointer out=%p,in=%p\n", ALCERR, __FUNCTION__, out, in); return NULL; } out_check(out, len, __FUNCTION__); return memcpy(out, in, len); } void *pgdebug_memset(void *out, int c, size_t len) { if (!out) { mylog("%s:%s null pointer out=%p\n", ALCERR, __FUNCTION__, out); return NULL; } out_check(out, len, __FUNCTION__); return memset(out, c, len); } void debug_memory_check(void) { int i; if (0 == tbsize) { mylog("no memry leak found and max count allocated so far is %d\n", alsize); free(altbl); alsize = 0; } else { mylog("%s:memory leak found check count=%d alloc=%d\n", ALCERR, tbsize, alsize); for (i = 0; i < tbsize; i++) { mylog("%s:leak = %p(%d)\n", ALCERR, altbl[i].aladr, altbl[i].len); } } } psqlodbc-09.03.0300/win_setup.h000644 001752 000000 00000001702 12335653444 016366 0ustar00saitowheel000000 000000 #ifndef _WIN_SETUP_H__ #define _WIN_SETUP_H__ #ifndef INTFUNC #define INTFUNC __stdcall #endif /* INTFUNC */ #define MAXDSNAME (32+1) /* Max data source name length */ /* Globals */ /* NOTE: All these are used by the dialog procedures */ typedef struct tagSETUPDLG { HWND hwndParent; /* Parent window handle */ LPCSTR lpszDrvr; /* Driver description */ ConnInfo ci; char szDSN[MAXDSNAME]; /* Original data source name */ BOOL fNewDSN; /* New data source flag */ BOOL fDefault; /* Default data source flag */ } SETUPDLG, FAR * LPSETUPDLG; /* Prototypes */ void INTFUNC CenterDialog(HWND hdlg); LRESULT CALLBACK ConfigDlgProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); void INTFUNC ParseAttributes(LPCSTR lpszAttributes, LPSETUPDLG lpsetupdlg); BOOL INTFUNC SetDSNAttributes(HWND hwnd, LPSETUPDLG lpsetupdlg, DWORD *); BOOL INTFUNC ChangeDriverName(HWND hwnd, LPSETUPDLG lpsetupdlg, LPCSTR driver_name); #endif /* _WIN_SETUP_H__ */ psqlodbc-09.03.0300/setup.c000644 001752 000000 00000040420 12335653444 015504 0ustar00saitowheel000000 000000 /*------- * Module: setup.c * * Description: This module contains the setup functions for * adding/modifying a Data Source in the ODBC.INI portion * of the registry. * * Classes: n/a * * API functions: ConfigDSN, ConfigDriver * * Comments: See "readme.txt" for copyright and license information. *------- */ #include "psqlodbc.h" #include "misc.h" // strncpy_null #include "environ.h" #include "connection.h" #include #include #include #include "resource.h" #include "pgapifunc.h" #include "dlg_specific.h" #include "win_setup.h" #define INTFUNC __stdcall extern HINSTANCE NEAR s_hModule; /* Saved module handle. */ extern GLOBAL_VALUES globals; /* Constants */ #define MIN(x,y) ((x) < (y) ? (x) : (y)) #define MAXKEYLEN (32+1) /* Max keyword length */ #define MAXDESC (255+1) /* Max description length */ #define MAXDSNAME (32+1) /* Max data source name length */ /*-------- * ConfigDSN * * Description: ODBC Setup entry point * This entry point is called by the ODBC Installer * (see file header for more details) * Input : hwnd ----------- Parent window handle * fRequest ------- Request type (i.e., add, config, or remove) * lpszDriver ----- Driver name * lpszAttributes - data source attribute string * Output : TRUE success, FALSE otherwise *-------- */ BOOL CALLBACK ConfigDSN(HWND hwnd, WORD fRequest, LPCSTR lpszDriver, LPCSTR lpszAttributes) { BOOL fSuccess; /* Success/fail flag */ GLOBALHANDLE hglbAttr; LPSETUPDLG lpsetupdlg; /* Allocate attribute array */ hglbAttr = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof(SETUPDLG)); if (!hglbAttr) return FALSE; lpsetupdlg = (LPSETUPDLG) GlobalLock(hglbAttr); /* Parse attribute string */ if (lpszAttributes) ParseAttributes(lpszAttributes, lpsetupdlg); /* Save original data source name */ if (lpsetupdlg->ci.dsn[0]) lstrcpy(lpsetupdlg->szDSN, lpsetupdlg->ci.dsn); else lpsetupdlg->szDSN[0] = '\0'; /* Remove data source */ if (ODBC_REMOVE_DSN == fRequest) { /* Fail if no data source name was supplied */ if (!lpsetupdlg->ci.dsn[0]) fSuccess = FALSE; /* Otherwise remove data source from ODBC.INI */ else fSuccess = SQLRemoveDSNFromIni(lpsetupdlg->ci.dsn); } /* Add or Configure data source */ else { /* Save passed variables for global access (e.g., dialog access) */ lpsetupdlg->hwndParent = hwnd; lpsetupdlg->lpszDrvr = lpszDriver; lpsetupdlg->fNewDSN = (ODBC_ADD_DSN == fRequest); lpsetupdlg->fDefault = !lstrcmpi(lpsetupdlg->ci.dsn, INI_DSN); /* * Display the appropriate dialog (if parent window handle * supplied) */ if (hwnd) { /* Display dialog(s) */ fSuccess = (IDOK == DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_CONFIG), hwnd, ConfigDlgProc, (LPARAM) lpsetupdlg)); } else if (lpsetupdlg->ci.dsn[0]) fSuccess = SetDSNAttributes(hwnd, lpsetupdlg, NULL); else fSuccess = FALSE; } GlobalUnlock(hglbAttr); GlobalFree(hglbAttr); return fSuccess; } /*-------- * ConfigDriver * * Description: ODBC Setup entry point * This entry point is called by the ODBC Installer * (see file header for more details) * Arguments : hwnd ----------- Parent window handle * fRequest ------- Request type (i.e., add, config, or remove) * lpszDriver ----- Driver name * lpszArgs ------- A null-terminated string containing arguments for a driver specific fRequest * lpszMsg -------- A null-terimated string containing an output message from the driver setup * cnMsgMax ------- Length of lpszMSg * pcbMsgOut ------ Total number of bytes available to return in lpszMsg * Returns : TRUE success, FALSE otherwise *-------- */ static BOOL SetDriverAttributes(LPCSTR lpszDriver, DWORD *pErrorCode, LPSTR pErrorMessage, WORD cbMessage); BOOL CALLBACK ConfigDriver(HWND hwnd, WORD fRequest, LPCSTR lpszDriver, LPCSTR lpszArgs, LPSTR lpszMsg, WORD cbMsgMax, WORD *pcbMsgOut) { DWORD errorCode = 0; BOOL fSuccess = TRUE; /* Success/fail flag */ if (cbMsgMax > 0 && NULL != lpszMsg) *lpszMsg = '\0'; if (NULL != pcbMsgOut) *pcbMsgOut = 0; /* Add the driver */ switch (fRequest) { case ODBC_INSTALL_DRIVER: fSuccess = SetDriverAttributes(lpszDriver, &errorCode, lpszMsg, cbMsgMax); if (cbMsgMax > 0 && NULL != lpszMsg) *pcbMsgOut = (WORD) strlen(lpszMsg); break; case ODBC_REMOVE_DRIVER: break; default: errorCode = ODBC_ERROR_INVALID_REQUEST_TYPE; fSuccess = FALSE; } if (!fSuccess) SQLPostInstallerError(errorCode, lpszMsg); return fSuccess; } /*------- * CenterDialog * * Description: Center the dialog over the frame window * Input : hdlg -- Dialog window handle * Output : None *------- */ void INTFUNC CenterDialog(HWND hdlg) { HWND hwndFrame; RECT rcDlg, rcScr, rcFrame; int cx, cy; hwndFrame = GetParent(hdlg); GetWindowRect(hdlg, &rcDlg); cx = rcDlg.right - rcDlg.left; cy = rcDlg.bottom - rcDlg.top; GetClientRect(hwndFrame, &rcFrame); ClientToScreen(hwndFrame, (LPPOINT) (&rcFrame.left)); ClientToScreen(hwndFrame, (LPPOINT) (&rcFrame.right)); rcDlg.top = rcFrame.top + (((rcFrame.bottom - rcFrame.top) - cy) >> 1); rcDlg.left = rcFrame.left + (((rcFrame.right - rcFrame.left) - cx) >> 1); rcDlg.bottom = rcDlg.top + cy; rcDlg.right = rcDlg.left + cx; GetWindowRect(GetDesktopWindow(), &rcScr); if (rcDlg.bottom > rcScr.bottom) { rcDlg.bottom = rcScr.bottom; rcDlg.top = rcDlg.bottom - cy; } if (rcDlg.right > rcScr.right) { rcDlg.right = rcScr.right; rcDlg.left = rcDlg.right - cx; } if (rcDlg.left < 0) rcDlg.left = 0; if (rcDlg.top < 0) rcDlg.top = 0; MoveWindow(hdlg, rcDlg.left, rcDlg.top, cx, cy, TRUE); return; } /*------- * ConfigDlgProc * Description: Manage add data source name dialog * Input : hdlg --- Dialog window handle * wMsg --- Message * wParam - Message parameter * lParam - Message parameter * Output : TRUE if message processed, FALSE otherwise *------- */ LRESULT CALLBACK ConfigDlgProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { LPSETUPDLG lpsetupdlg; ConnInfo *ci; DWORD cmd; char strbuf[64]; switch (wMsg) { /* Initialize the dialog */ case WM_INITDIALOG: lpsetupdlg = (LPSETUPDLG) lParam; ci = &lpsetupdlg->ci; /* Hide the driver connect message */ ShowWindow(GetDlgItem(hdlg, DRV_MSG_LABEL), SW_HIDE); LoadString(s_hModule, IDS_ADVANCE_SAVE, strbuf, sizeof(strbuf)); SetWindowText(GetDlgItem(hdlg, IDOK), strbuf); SetWindowLongPtr(hdlg, DWLP_USER, lParam); CenterDialog(hdlg); /* Center dialog */ /* * NOTE: Values supplied in the attribute string will always */ /* override settings in ODBC.INI */ copy_globals(&ci->drivers, &globals); /* Get the rest of the common attributes */ getDSNinfo(ci, CONN_DONT_OVERWRITE); /* Fill in any defaults */ getDSNdefaults(ci); /* Initialize dialog fields */ SetDlgStuff(hdlg, ci); if (lpsetupdlg->fNewDSN || !ci->dsn[0]) ShowWindow(GetDlgItem(hdlg, IDC_MANAGEDSN), SW_HIDE); if (lpsetupdlg->fDefault) { EnableWindow(GetDlgItem(hdlg, IDC_DSNAME), FALSE); EnableWindow(GetDlgItem(hdlg, IDC_DSNAMETEXT), FALSE); } else SendDlgItemMessage(hdlg, IDC_DSNAME, EM_LIMITTEXT, (WPARAM) (MAXDSNAME - 1), 0L); SendDlgItemMessage(hdlg, IDC_DESC, EM_LIMITTEXT, (WPARAM) (MAXDESC - 1), 0L); return TRUE; /* Focus was not set */ /* Process buttons */ case WM_COMMAND: switch (cmd = GET_WM_COMMAND_ID(wParam, lParam)) { /* * Ensure the OK button is enabled only when a data * source name */ /* is entered */ case IDC_DSNAME: if (GET_WM_COMMAND_CMD(wParam, lParam) == EN_CHANGE) { char szItem[MAXDSNAME]; /* Edit control text */ /* Enable/disable the OK button */ EnableWindow(GetDlgItem(hdlg, IDOK), GetDlgItemText(hdlg, IDC_DSNAME, szItem, sizeof(szItem))); return TRUE; } break; /* Accept results */ case IDOK: case IDAPPLY: lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); /* Retrieve dialog values */ if (!lpsetupdlg->fDefault) GetDlgItemText(hdlg, IDC_DSNAME, lpsetupdlg->ci.dsn, sizeof(lpsetupdlg->ci.dsn)); /* Get Dialog Values */ GetDlgStuff(hdlg, &lpsetupdlg->ci); /* Update ODBC.INI */ SetDSNAttributes(hdlg, lpsetupdlg, NULL); if (IDAPPLY == cmd) break; /* Return to caller */ case IDCANCEL: EndDialog(hdlg, wParam); return TRUE; case IDC_TEST: { lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); if (NULL != lpsetupdlg) { EnvironmentClass *env = EN_Constructor(); ConnectionClass *conn = NULL; char szMsg[SQL_MAX_MESSAGE_LENGTH]; /* Get Dialog Values */ GetDlgStuff(hdlg, &lpsetupdlg->ci); if (env) conn = CC_Constructor(); if (conn) { char *emsg, *allocstr = NULL; #ifdef UNICODE_SUPPORT int tlen; SQLWCHAR *wermsg = NULL; SQLULEN ulen; #endif /* UNICODE_SUPPORT */ int errnum; EN_add_connection(env, conn); CC_copy_conninfo(&conn->connInfo, &lpsetupdlg->ci); CC_initialize_pg_version(conn); logs_on_off(1, conn->connInfo.drivers.debug, conn->connInfo.drivers.commlog); #ifdef UNICODE_SUPPORT CC_set_in_unicode_driver(conn); #endif /* UNICODE_SUPPORT */ if (CC_connect(conn, AUTH_REQ_OK, NULL) > 0) { if (CC_get_errornumber(conn) != 0) { CC_get_error(conn, &errnum, &emsg); snprintf(szMsg, sizeof(szMsg), "Warning: %s", emsg); } else strncpy_null(szMsg, "Connection successful", sizeof(szMsg)); emsg = szMsg; } else { CC_get_error(conn, &errnum, &emsg); } #ifdef UNICODE_SUPPORT tlen = strlen(emsg); wermsg = (SQLWCHAR *) malloc(sizeof(SQLWCHAR) * (tlen + 1)); ulen = utf8_to_ucs2_lf(emsg, SQL_NTS, FALSE, wermsg, tlen + 1, TRUE); if (ulen != (SQLULEN) -1) { allocstr = malloc(4 * tlen + 1); tlen = (SQLSMALLINT) wstrtomsg(NULL, wermsg, (int) tlen, allocstr, (int) 4 * tlen + 1); emsg = allocstr; } if (NULL != wermsg) free(wermsg); #endif /* UNICODE_SUPPORT */ MessageBox(lpsetupdlg->hwndParent, emsg, "Connection Test", MB_ICONEXCLAMATION | MB_OK); logs_on_off(-1, conn->connInfo.drivers.debug, conn->connInfo.drivers.commlog); EN_remove_connection(env, conn); CC_Destructor(conn); if (NULL != allocstr) free(allocstr); } if (env) EN_Destructor(env); return TRUE; } break; } case IDC_DATASOURCE: lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, ds_options1Proc, (LPARAM) &lpsetupdlg->ci); return TRUE; case IDC_DRIVER: lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_GLOBAL), hdlg, global_optionsProc, (LPARAM) &lpsetupdlg->ci); return TRUE; case IDC_MANAGEDSN: lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); if (DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_DRIVER_CHANGE), hdlg, manage_dsnProc, (LPARAM) lpsetupdlg) > 0) EndDialog(hdlg, 0); return TRUE; } break; case WM_CTLCOLORSTATIC: if (lParam == (LPARAM)GetDlgItem(hdlg, IDC_NOTICE_USER)) { HBRUSH hBrush = (HBRUSH)GetStockObject(LTGRAY_BRUSH); SetTextColor((HDC)wParam, RGB(255, 0, 0)); return (long)hBrush; } break; } /* Message not processed */ return FALSE; } /*------- * ParseAttributes * * Description: Parse attribute string moving values into the aAttr array * Input : lpszAttributes - Pointer to attribute string * Output : None (global aAttr normally updated) *------- */ void INTFUNC ParseAttributes(LPCSTR lpszAttributes, LPSETUPDLG lpsetupdlg) { LPCSTR lpsz; LPCSTR lpszStart; char aszKey[MAXKEYLEN]; int cbKey; char value[MAXPGPATH]; CC_conninfo_init(&(lpsetupdlg->ci), COPY_GLOBALS); for (lpsz = lpszAttributes; *lpsz; lpsz++) { /* * Extract key name (e.g., DSN), it must be terminated by an * equals */ lpszStart = lpsz; for (;; lpsz++) { if (!*lpsz) return; /* No key was found */ else if (*lpsz == '=') break; /* Valid key found */ } /* Determine the key's index in the key table (-1 if not found) */ cbKey = lpsz - lpszStart; if (cbKey < sizeof(aszKey)) { _fmemcpy(aszKey, lpszStart, cbKey); aszKey[cbKey] = '\0'; } /* Locate end of key value */ lpszStart = ++lpsz; for (; *lpsz; lpsz++) ; /* lpsetupdlg->aAttr[iElement].fSupplied = TRUE; */ _fmemcpy(value, lpszStart, MIN(lpsz - lpszStart + 1, MAXPGPATH)); mylog("aszKey='%s', value='%s'\n", aszKey, value); /* Copy the appropriate value to the conninfo */ if (!copyAttributes(&lpsetupdlg->ci, aszKey, value)) copyCommonAttributes(&lpsetupdlg->ci, aszKey, value); } return; } /*-------- * SetDSNAttributes * * Description: Write data source attributes to ODBC.INI * Input : hwnd - Parent window handle (plus globals) * Output : TRUE if successful, FALSE otherwise *-------- */ BOOL INTFUNC SetDSNAttributes(HWND hwndParent, LPSETUPDLG lpsetupdlg, DWORD *errcode) { LPCSTR lpszDSN; /* Pointer to data source name */ lpszDSN = lpsetupdlg->ci.dsn; if (errcode) *errcode = 0; /* Validate arguments */ if (lpsetupdlg->fNewDSN && !*lpsetupdlg->ci.dsn) return FALSE; /* Write the data source name */ if (!SQLWriteDSNToIni(lpszDSN, lpsetupdlg->lpszDrvr)) { RETCODE ret = SQL_ERROR; DWORD err = SQL_ERROR; char szMsg[SQL_MAX_MESSAGE_LENGTH]; #if (ODBCVER >= 0x0300) ret = SQLInstallerError(1, &err, szMsg, sizeof(szMsg), NULL); #endif /* ODBCVER */ if (hwndParent) { char szBuf[MAXPGPATH]; if (SQL_SUCCESS != ret) { LoadString(s_hModule, IDS_BADDSN, szBuf, sizeof(szBuf)); wsprintf(szMsg, szBuf, lpszDSN); } LoadString(s_hModule, IDS_MSGTITLE, szBuf, sizeof(szBuf)); MessageBox(hwndParent, szMsg, szBuf, MB_ICONEXCLAMATION | MB_OK); } if (errcode) *errcode = err; return FALSE; } /* Update ODBC.INI */ writeDriverCommoninfo(ODBC_INI, lpsetupdlg->ci.dsn, &(lpsetupdlg->ci.drivers)); writeDSNinfo(&lpsetupdlg->ci); /* If the data source name has changed, remove the old name */ if (lstrcmpi(lpsetupdlg->szDSN, lpsetupdlg->ci.dsn)) SQLRemoveDSNFromIni(lpsetupdlg->szDSN); return TRUE; } /*-------- * SetDriverAttributes * * Description: Write driver information attributes to ODBCINST.INI * Input : lpszDriver - The driver name * Output : TRUE if successful, FALSE otherwise *-------- */ static BOOL SetDriverAttributes(LPCSTR lpszDriver, DWORD *pErrorCode, LPSTR message, WORD cbMessage) { BOOL ret = FALSE; /* Validate arguments */ if (!lpszDriver || !lpszDriver[0]) { if (pErrorCode) *pErrorCode = ODBC_ERROR_INVALID_NAME; strncpy_null(message, "Driver name not specified", cbMessage); return FALSE; } if (!SQLWritePrivateProfileString(lpszDriver, "APILevel", "1", ODBCINST_INI)) goto cleanup; if (!SQLWritePrivateProfileString(lpszDriver, "ConnectFunctions", "YYN", ODBCINST_INI)) goto cleanup; if (!SQLWritePrivateProfileString(lpszDriver, "DriverODBCVer", #ifdef UNICODE_SUPPORT "03.51", #else "03.00", #endif ODBCINST_INI)) goto cleanup; if (!SQLWritePrivateProfileString(lpszDriver, "FileUsage", "0", ODBCINST_INI)) goto cleanup; if (!SQLWritePrivateProfileString(lpszDriver, "SQLLevel", "1", ODBCINST_INI)) goto cleanup; ret = TRUE; cleanup: if (!ret) { if (pErrorCode) *pErrorCode = ODBC_ERROR_REQUEST_FAILED; strncpy_null(message, "Failed to WritePrivateProfileString", cbMessage); } return ret; } #ifdef WIN32 BOOL INTFUNC ChangeDriverName(HWND hwndParent, LPSETUPDLG lpsetupdlg, LPCSTR driver_name) { DWORD err = 0; ConnInfo *ci = &lpsetupdlg->ci; if (!ci->dsn[0]) { err = IDS_BADDSN; } else if (!driver_name || strnicmp(driver_name, "postgresql", 10)) { err = IDS_BADDSN; } else { LPCSTR lpszDrvr = lpsetupdlg->lpszDrvr; lpsetupdlg->lpszDrvr = driver_name; if (!SetDSNAttributes(hwndParent, lpsetupdlg, &err)) { if (!err) err = IDS_BADDSN; lpsetupdlg->lpszDrvr = lpszDrvr; } } return (err == 0); } #endif /* WIN32 */ psqlodbc-09.03.0300/win_md5.c000644 001752 000000 00000000434 12335653444 015707 0ustar00saitowheel000000 000000 /* * win_md5.c * Under Windows I don't love the following /D in makefiles. - inoue */ #define MD5_ODBC #define FRONTEND /* * md5.c is the exact copy of the src/backend/libpq/md5.c. * * psqlodbc driver stuff never refer(link) to other * stuff directly. */ #include "md5.c" psqlodbc-09.03.0300/psqlodbc.rc000644 001752 000000 00000076324 12335653444 016351 0ustar00saitowheel000000 000000 //Microsoft Developer Studio generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winresrc.h" #ifndef IDC_STATIC #define IDC_STATIC (-1) #endif #include "version.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // Japanese resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_JPN) #ifdef _WIN32 LANGUAGE LANG_JAPANESE, SUBLANG_DEFAULT #pragma code_page(932) #endif //_WIN32 ///////////////////////////////////////////////////////////////////////////// // // Dialog // DLG_CONFIG DIALOGEX 65, 43, 359, 219 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU #ifdef UNICODE_SUPPORT CAPTION "PostgreSQL Unicode ODBC ƒZƒbƒgƒAƒbƒv" #else CAPTION "PostgreSQL ANSI ODBC ƒZƒbƒgƒAƒbƒv" #endif FONT 9, "‚l‚r ƒSƒVƒbƒN", 0, 0, 0x1 BEGIN RTEXT "ƒf|ƒ^ƒ\|ƒX–¼:(&N)",IDC_DSNAMETEXT,2,9,63,17,NOT WS_GROUP,WS_EX_TRANSPARENT | WS_EX_RIGHT EDITTEXT IDC_DSNAME,72,12,188,13,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT RTEXT "à–¾:(&D)",IDC_DESCTEXT,5,31,60,16,SS_CENTERIMAGE | NOT WS_GROUP,WS_EX_TRANSPARENT | WS_EX_RIGHT EDITTEXT IDC_DESC,72,32,188,13,ES_AUTOHSCROLL,WS_EX_TRANSPARENT RTEXT "SSL Mode:(&L)",IDC_STATIC,16,49,49,9,NOT WS_GROUP COMBOBOX IDC_SSLMODE,72,47,90,56,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP LTEXT "libpqƒ‰ƒCƒuƒ‰ƒŠload•s‰Â:SSLÚ‘±‚ÍŽg—p‚Å‚«‚Ü‚¹‚ñ", IDC_NOTICE_USER,165,50,190,10 RTEXT "ƒT|ƒo|–¼:(&S)",IDC_STATIC,17,68,48,15,NOT WS_GROUP EDITTEXT IDC_SERVER,72,66,203,14,ES_AUTOHSCROLL RTEXT "ƒf|ƒ^ƒx|ƒX–¼:(&b)",IDC_STATIC,5,91,60,15,NOT WS_GROUP EDITTEXT IDC_DATABASE,72,88,203,14,ES_AUTOHSCROLL RTEXT "&Port:",IDC_STATIC,281,101,22,11 EDITTEXT IDC_PORT,307,99,37,14,ES_AUTOHSCROLL RTEXT "ƒ†|ƒU|–¼:(&U)",IDC_STATIC,18,139,47,15 EDITTEXT IDC_USER,72,135,162,14,ES_AUTOHSCROLL RTEXT "ƒpƒXƒ|ƒh:(&w)",IDC_STATIC,21,159,46,15 EDITTEXT IDC_PASSWORD,72,157,162,13,ES_PASSWORD | ES_AUTOHSCROLL DEFPUSHBUTTON "OK",IDOK,295,61,52,14,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,296,80,51,14 GROUPBOX "ƒIƒvƒVƒ‡ƒ“ (‚“x‚ÈÝ’è)",IDC_OPTIONS,249,119,99,59, BS_CENTER PUSHBUTTON "‘S‘ÌÝ’è",IDC_DRIVER,269,155,53,15 PUSHBUTTON "ƒf|ƒ^ƒ\|ƒX",IDC_DATASOURCE,269,132,53,15 GROUPBOX "Šù’è‚Ì”FØ",IDC_STATIC,11,119,235,59 LTEXT "PostgreSQL Ver7.3 Copyright (C) 1998-2006; Insight Distribution Systems", IDC_STATIC,36,186,302,9 LTEXT "In the original form, Japanese patch Hiroshi-saito", IDC_STATIC,35,198,295,8 PUSHBUTTON "ŠÇ—",IDC_MANAGEDSN,295,10,50,14 PUSHBUTTON "ƒeƒXƒg",IDC_TEST,296,30,51,14 END DLG_OPTIONS_DRV DIALOG DISCARDABLE 0, 0, 350, 241 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "‚“x‚ÈÝ’è (ƒf[ƒ^ƒ\[ƒX‚P)" FONT 9, "‚l‚r ƒSƒVƒbƒN" BEGIN PUSHBUTTON "Ý’è1",IDPREVPAGE,5,5,40,15 PUSHBUTTON "Ý’è2",IDNEXTPAGE,49,5,40,15 CONTROL "ˆâ“`“IÅ“K‰»ˆ—‚𖳌ø‚É‚·‚é(&O)",DRV_OPTIMIZER,"Button", BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,15,26,140,10 CONTROL "ˆê”ʃƒOo—Í‚ð‚·‚é(&L) (C:\\psqlodbc.log)",DRV_COMMLOG, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,167,24,170,10 CONTROL "&KSQO (¸´Ø°·°¾¯ÄÅ“K‰»ƒIƒvƒVƒ‡ƒ“)",DRV_KSQO,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,41,145,10 CONTROL "ƒ†ƒj|ƒNƒCƒ“ƒfƒbƒNƒX‚ðŽg‚¤(&I)",DRV_UNIQUEINDEX,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,56,129,10 CONTROL "ƒXƒe|ƒgƒƒ“ƒg‚Ì\•¶‰ðÍ‚ðs‚È‚¤(&a)",DRV_PARSE,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,167,40,152,10 CONTROL "Declare`Fetch‚ðŽg—p‚·‚é(&U)",DRV_USEDECLAREFETCH, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,71,138,10 CONTROL "ƒLƒƒƒ“ƒZƒ‹‚ÉSQLFreeStmt‚ðŽg—p‚·‚é(Exp)", DRV_CANCELASFREESTMT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,167,54,168,10 CONTROL "Ú׃ƒOo—Í‚ð‚·‚é(C:\\mylog_xxxx.log)",DRV_DEBUG, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,167,69,164,10 GROUPBOX "–¢’m‚̃TƒCƒY“®ì",IDC_STATIC,5,85,340,31 CONTROL "Å‘å‚ð‚Æ‚é",DRV_UNKNOWN_MAX,"Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,17,98,57,10 CONTROL "“Á’肵‚È‚¢",DRV_UNKNOWN_DONTKNOW,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,99,98,59,10 CONTROL "Å’·‚ð‚Æ‚é",DRV_UNKNOWN_LONGEST,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,173,98,60,10 GROUPBOX "ƒf|ƒ^ ƒ^ƒCƒv ƒIƒvƒVƒ‡ƒ“",IDC_STATIC,5,119,340,32 CONTROL "text‚ð’·•¶Žš—ñ‚Æ‚µ‚Ĉµ‚¤",DRV_TEXT_LONGVARCHAR,"Button", BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,12,132,107,10 CONTROL "•s–¾‚ð’·•¶Žš—ñ‚Æ‚µ‚Ĉµ‚¤",DRV_UNKNOWNS_LONGVARCHAR, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,123,132,117,10 CONTROL "Char‚Æ‚µ‚ÄBools‚ðˆµ‚¤",DRV_BOOLS_CHAR,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,243,132,96,10 LTEXT "·¬¯¼­»²½Þ:",IDC_STATIC,21,189,39,8 EDITTEXT DRV_CACHE_SIZE,69,187,35,12,ES_AUTOHSCROLL LTEXT "Å‘å&Varchar:",IDC_STATIC,13,167,54,8 EDITTEXT DRV_VARCHAR_SIZE,70,166,35,12,ES_AUTOHSCROLL LTEXT "Å‘åLon&gVarChar:",IDC_STATIC,148,168,66,8 EDITTEXT DRV_LONGVARCHAR_SIZE,219,166,35,12,ES_AUTOHSCROLL LTEXT "¼½ÃÑðÌÞÙ ÌßŲ́¸½:",IDC_STATIC,140,189,74,9 EDITTEXT DRV_EXTRASYSTABLEPREFIXES,219,187,71,12,ES_AUTOHSCROLL DEFPUSHBUTTON "OK",IDOK,5,221,50,15,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,68,221,50,15 PUSHBUTTON "“K—p",IDAPPLY,132,221,50,15 PUSHBUTTON "ƒfƒtƒHƒ‹ƒg",IDDEFAULTS,295,221,50,15 GROUPBOX "‚»‚Ì‘¼",IDC_STATIC,5,155,340,54 END DLG_OPTIONS_DS DIALOG DISCARDABLE 0, 0, 306, 243 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "‚“x‚ÈÝ’è (ƒf[ƒ^ƒ\[ƒX‚Q)" FONT 9, "‚l‚r ƒSƒVƒbƒN" BEGIN PUSHBUTTON "Ý’è2",IDNEXTPAGE,49,5,40,15 PUSHBUTTON "Ý’è1",IDPREVPAGE,5,5,40,15 CONTROL "ƒŠ|ƒhƒIƒ“ƒŠƒB(&R)",DS_READONLY,"Button", BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,15,26,102,10 CONTROL "ƒo|ƒWƒ‡ƒ“—ñ•\ަ(&V)",DS_ROWVERSIONING,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,139,25,114,10 CONTROL "ƒVƒXƒeƒ€ƒe|ƒuƒ‹‚ð•\ަ(&T)",DS_SHOWSYSTEMTABLES,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,41,111,10 CONTROL "Prepareî•ñŽæ“¾‚ÉæsŽÀs‚µ‚È‚¢(&P)", DS_DISALLOWPREMATURE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,139,41,162,10 CONTROL "LF <-> CR/LF •ÏŠ·‚ðs‚¤",DS_LFCONVERSION,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,56,106,10 CONTROL "-1 ‚ð^’l(True)‚Æ‚·‚é",DS_TRUEISMINUS1,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,139,55,98,10 CONTROL "XV‰Â”\ƒJ[ƒ\ƒ‹",DS_UPDATABLECURSORS,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,71,87,10 CONTROL "ƒT[ƒo[‘¤ Prepare(7.3ˆÈŒã)",DS_SERVERSIDEPREPARE, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,139,70,122,10 GROUPBOX "Int8 ‚Ì‘ã‘Ö’è‹`",IDC_STATIC,5,98,256,25 CONTROL "default",DS_INT8_AS_DEFAULT,"Button",BS_AUTORADIOBUTTON | WS_GROUP,12,108,40,10 CONTROL "bigint",DS_INT8_AS_BIGINT,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,55,108,35,10 CONTROL "numeric",DS_INT8_AS_NUMERIC,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,98,108,40,10 CONTROL "varchar",DS_INT8_AS_VARCHAR,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,141,108,40,10 CONTROL "double",DS_INT8_AS_DOUBLE,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,184,108,40,10 CONTROL "int4",DS_INT8_AS_INT4,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,227,108,29,10 LTEXT "“Á•ʂȃIƒvƒVƒ‡ƒ“",IDC_STATIC,227,158,66,8 EDITTEXT DS_EXTRA_OPTIONS,227,168,35,14,ES_AUTOHSCROLL GROUPBOX "ƒvƒƒgƒRƒ‹ƒo|ƒWƒ‡ƒ“",IDC_STATIC,5,128,150,25 CONTROL "7.4+",DS_PG74,"Button",BS_AUTORADIOBUTTON | WS_GROUP,18, 139,30,10 CONTROL "6.4+",DS_PG64,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP, 52,139,30,10 CONTROL "6.3",DS_PG63,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP, 90,140,26,10 CONTROL "6.2",DS_PG62,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP, 118,140,26,10 GROUPBOX "ƒGƒ‰[Žž‚̃[ƒ‹ƒoƒbƒN”­s",IDC_STATIC,160,128,130,25 CONTROL "–³‚µ",DS_NO_ROLLBACK,"Button",BS_AUTORADIOBUTTON | WS_GROUP,165,139,30,10 CONTROL "‘S·¬Ý¾Ù",DS_TRANSACTION_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,195,140,50,10 CONTROL "•¶’PˆÊ",DS_STATEMENT_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,250,140,35,10 GROUPBOX "OID ƒIƒvƒVƒ‡ƒ“",IDC_STATIC,5,158,206,25 CONTROL "ƒJƒ‰ƒ€—ñ•\ަ(&C)",DS_SHOWOIDCOLUMN,"Button", BS_AUTOCHECKBOX | WS_GROUP,16,169,72,10 CONTROL "ƒCƒ“ƒfƒbƒNƒX‚ð‘•‚¤(&I)",DS_FAKEOIDINDEX,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,107,169,95,10 LTEXT "Ú‘±Žž Ý’è:(&S)",IDC_STATIC,13,192,69,10,NOT WS_GROUP EDITTEXT DS_CONNSETTINGS,90,191,211,27,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN | NOT WS_TABSTOP DEFPUSHBUTTON "OK",IDOK,5,224,50,14,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,66,224,50,14 PUSHBUTTON "“K—p",IDAPPLY,128,224,50,14 CONTROL "bytea‚ðLO‚Æ‚µ‚Ĉµ‚¤",DS_BYTEAASLONGVARBINARY,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,85,87,10 CONTROL "Kerberos‰ž“š‚ÉGSSAPI—˜—p",DS_GSSAUTHUSEGSSAPI,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,139,85,110,10 END DLG_OPTIONS_GLOBAL DIALOG DISCARDABLE 0, 0, 306, 115 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "‚“x‚ÈÝ’è(‘S‘Ì)" FONT 9, "‚l‚r ƒSƒVƒbƒN" BEGIN CONTROL "ˆê”ʃƒO(&L) (C:\\psqlodbc_xxxx.log - ƒRƒ~ƒ…ƒjƒP|ƒVƒ‡ƒ“ƒƒO)", DRV_COMMLOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,24, 249,10 CONTROL "ê—pƒƒO (C:\\mylog_xxxx.log - Ú׃fƒoƒbƒOo—̓ƒO)", DRV_DEBUG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,42, 220,10 CONTROL "MSDTCƒƒO (C:\\pgdtclog\\mylog_xxxx.log - MSDTCƒfƒoƒbƒOo—̓ƒO)", DRV_DTCLOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,60, 260,10 RTEXT "ƒƒMƒ“ƒO—pƒtƒHƒ‹ƒ_",IDC_STATIC,14,77,79,12 EDITTEXT DS_LOGDIR,98,75,188,13,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT DEFPUSHBUTTON "OK",IDOK,5,96,50,14,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,65,95,50,15 GROUPBOX "ƒRƒlƒNƒVƒ‡ƒ“‘O‚̃fƒtƒHƒ‹ƒgƒƒMƒ“ƒOƒIƒvƒVƒ‡ƒ“", IDC_STATIC,5,5,296,88 END DLG_DRIVER_CHANGE DIALOG DISCARDABLE 0, 0, 306, 87 STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "ƒhƒ‰ƒCƒo@ƒAƒbƒv/ƒ_ƒEƒ“" FONT 10, "Terminal" BEGIN DEFPUSHBUTTON "OK",IDOK,82,68,50,14,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,172,67,50,15 GROUPBOX "ƒhƒ‰ƒCƒoƒŠƒXƒg",IDC_STATIC,5,5,296,58 LTEXT "ƒhƒ‰ƒCƒo‚ð‘I‘ð‚µ‚Ä‚­‚¾‚³‚¢",IDC_STATIC,11,33,105,8 LISTBOX IDC_DRIVER_LIST,124,19,170,33,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO DISCARDABLE BEGIN DLG_CONFIG, DIALOG BEGIN VERTGUIDE, 65 VERTGUIDE, 72 VERTGUIDE, 260 BOTTOMMARGIN, 210 END DLG_OPTIONS_DRV, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 345 TOPMARGIN, 5 BOTTOMMARGIN, 236 END DLG_OPTIONS_DS, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 301 TOPMARGIN, 5 BOTTOMMARGIN, 238 END DLG_OPTIONS_GLOBAL, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 301 TOPMARGIN, 5 BOTTOMMARGIN, 82 END DLG_DRIVER_CHANGE, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 301 TOPMARGIN, 5 BOTTOMMARGIN, 82 END END #endif // APSTUDIO_INVOKED #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE DISCARDABLE BEGIN "resource.h\0" END 2 TEXTINCLUDE DISCARDABLE BEGIN "#include ""afxres.h""\r\n" "#include ""version.h""\r\n" "\0" END 3 TEXTINCLUDE DISCARDABLE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION PG_DRVFILE_VERSION PRODUCTVERSION PG_DRVFILE_VERSION FILEFLAGSMASK 0x3L #ifdef _DEBUG FILEFLAGS 0x9L #else FILEFLAGS 0x8L #endif FILEOS 0x4L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "041104e4" BEGIN #ifdef UNICODE_SUPPORT VALUE "Comments", "PostgreSQL Unicode ODBC driver Japanese\0" #else VALUE "Comments", "PostgreSQL ANSI ODBC driver Japanese\0" #endif VALUE "CompanyName", "PostgreSQL Global Development Group\0" VALUE "FileDescription", "PostgreSQL ODBC Driver (Japanese)\0" VALUE "FileVersion", POSTGRES_RESOURCE_VERSION #ifdef UNICODE_SUPPORT VALUE "InternalName", "psqlodbc35w\0" #else VALUE "InternalName", "psqlodbc30a\0" #endif VALUE "LegalCopyright", "\0" VALUE "LegalTrademarks", "ODBC(TM) is a trademark of Microsoft Corporation. Microsoftƒ‡ is a registered trademark of Microsoft Corporation. Windows(TM) is a trademark of Microsoft Corporation.\0" #ifdef UNICODE_SUPPORT VALUE "OriginalFilename", "psqlodbc35w.dll\0" #else VALUE "OriginalFilename", "psqlodbc30a.dll\0" #endif VALUE "PrivateBuild", "for Japanese by Hiroshi Inoue & Hiroshi Saito\0" VALUE "ProductName", "PostgreSQL\0" VALUE "ProductVersion", POSTGRES_RESOURCE_VERSION VALUE "SpecialBuild", "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x411, 1252 END END #endif // !_MAC ///////////////////////////////////////////////////////////////////////////// // // String Table // STRINGTABLE DISCARDABLE BEGIN IDS_BADDSN "DSNƒGƒ“ƒgƒŠ|‚ª•s³‚Å‚·BÄ“xƒ`ƒFƒbƒNݒ肵‚Ä‚­‚¾‚³‚¢B." IDS_MSGTITLE "DSN•s³" IDS_ADVANCE_OPTION_DEF "‚“x‚ÈÝ’è (ƒfƒtƒHƒ‹ƒg)" IDS_ADVANCE_SAVE "•Û‘¶" IDS_ADVANCE_OPTION_DSN1 "‚“x‚ÈÝ’è (%s Ý’è1)" IDS_ADVANCE_OPTION_CON1 "‚“x‚ÈÝ’èiƒRƒlƒNƒVƒ‡ƒ“Ý’è‚Pj" IDS_ADVANCE_OPTION_DSN2 "‚“x‚ÈÝ’è (%s Ý’è2)" IDS_ADVANCE_OPTION_CON2 "‚“x‚ÈÝ’è (ƒRƒlƒNƒVƒ‡ƒ“Ý’è2)" IDS_ADVANCE_CONNECTION "ƒRƒlƒNƒVƒ‡ƒ“" END STRINGTABLE DISCARDABLE BEGIN IDS_SSLREQUEST_PREFER "—Dæ" IDS_SSLREQUEST_ALLOW "l—¶" IDS_SSLREQUEST_REQUIRE "•K{" IDS_SSLREQUEST_DISABLE "–³Œø" IDS_SSLREQUEST_VERIFY_CA "•K{:Ø–¾‘”FØ" IDS_SSLREQUEST_VERIFY_FULL "•K{:Ø–¾‘Š®‘S”FØ" END #endif // Japanese resources ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // 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 ///////////////////////////////////////////////////////////////////////////// // // Dialog // DLG_CONFIG DIALOG DISCARDABLE 65, 43, 305, 142 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU #ifdef UNICODE_SUPPORT CAPTION "PostgreSQL Unicode ODBC Driver (psqlODBC) Setup" #else CAPTION "PostgreSQL ANSI ODBC Driver (psqlODBC) Setup" #endif FONT 8, "MS Sans Serif" BEGIN RTEXT "&Data Source",IDC_DSNAMETEXT,3,25,50,12,NOT WS_GROUP EDITTEXT IDC_DSNAME,57,24,72,12,ES_AUTOHSCROLL | WS_GROUP RTEXT "Des&cription",IDC_DESCTEXT,143,24,45,12,NOT WS_GROUP EDITTEXT IDC_DESC,192,22,104,12,ES_AUTOHSCROLL RTEXT "Data&base",IDC_STATIC,15,40,38,12,NOT WS_GROUP EDITTEXT IDC_DATABASE,57,39,72,12,ES_AUTOHSCROLL RTEXT "SS&L Mode",IDC_STATIC,143,40,45,12,NOT WS_GROUP COMBOBOX IDC_SSLMODE,192,36,104,50,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP CTEXT "Couldn't load libpq - SSL mode is unavailable", IDC_NOTICE_USER,53,87,200,11,SS_NOTIFY | SS_CENTERIMAGE | WS_BORDER RTEXT "&Server",IDC_STATIC,24,55,29,12,NOT WS_GROUP EDITTEXT IDC_SERVER,57,54,72,12,ES_AUTOHSCROLL RTEXT "&Port",IDC_STATIC,166,56,22,12 EDITTEXT IDC_PORT,192,54,37,12,ES_AUTOHSCROLL RTEXT "&User Name",IDC_STATIC,14,70,39,12 EDITTEXT IDC_USER,57,69,72,12,ES_AUTOHSCROLL RTEXT "Pass&word",IDC_STATIC,154,72,34,9 EDITTEXT IDC_PASSWORD,192,70,72,12,ES_PASSWORD | ES_AUTOHSCROLL // DEFPUSHBUTTON "OK",IDOK,12,114,44,15,WS_GROUP // PUSHBUTTON "Cancel",IDCANCEL,66,114,44,15 // GROUPBOX "Options",IDC_OPTIONS,121,101,177,35,BS_LEFT // PUSHBUTTON "Datasource",IDC_DATASOURCE,128,115,50,14 // PUSHBUTTON "Global",IDC_DRIVER,184,115,50,14 LTEXT "Please supply any missing information required to connect.", DRV_MSG_LABEL,12,5,249,10 // PUSHBUTTON "Manage DSN",IDC_MANAGEDSN,240,115,52,14 GROUPBOX "Options",IDC_OPTIONS,5,100,177,35,BS_LEFT PUSHBUTTON "Datasource",IDC_DATASOURCE,12,114,50,14 PUSHBUTTON "Global",IDC_DRIVER,67,114,50,14 PUSHBUTTON "Manage DSN",IDC_MANAGEDSN,122,114,52,14 PUSHBUTTON "Test",IDC_TEST,254,103,44,15 DEFPUSHBUTTON "OK",IDOK,203,121,44,15,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,254,121,44,15 END DLG_OPTIONS_DRV DIALOG DISCARDABLE 0, 0, 287, 231 STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Advanced Options (DataSource)" FONT 8, "MS Sans Serif" BEGIN PUSHBUTTON "Page 1",IDPREVPAGE,5,5,40,15 PUSHBUTTON "Page 2",IDNEXTPAGE,49,5,40,15 CONTROL "Disable Genetic &Optimizer",DRV_OPTIMIZER,"Button", BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,15,26,116,10 CONTROL "Comm&Log (C:\\psqlodbc_xxxx.log)",DRV_COMMLOG,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,149,26,131,10 CONTROL "&KSQO(Keyset Query Optimization)",DRV_KSQO,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,41,132,10 CONTROL "Recognize Unique &Indexes",DRV_UNIQUEINDEX,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,56,110,10 CONTROL "P&arse Statements",DRV_PARSE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,149,41,80,10 CONTROL "&Use Declare/Fetch",DRV_USEDECLAREFETCH,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,71,83,10 CONTROL "Cancel as FreeStmt (Exp)",DRV_CANCELASFREESTMT,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,149,56,114,10 CONTROL "MyLog (C:\\mylog_xxxx.log)",DRV_DEBUG,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,149,71,112,10 GROUPBOX "Unknown Sizes",IDC_STATIC,5,85,277,25 CONTROL "Maximum",DRV_UNKNOWN_MAX,"Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,15,96,45,10 CONTROL "Don't Know",DRV_UNKNOWN_DONTKNOW,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,105,96,53,10 CONTROL "Longest",DRV_UNKNOWN_LONGEST,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,215,95,50,10 GROUPBOX "Data Type Options",IDC_STATIC,5,115,277,25 CONTROL "Text as LongVarChar",DRV_TEXT_LONGVARCHAR,"Button", BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,15,125,90,10 CONTROL "Unknowns as LongVarChar",DRV_UNKNOWNS_LONGVARCHAR, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,105,125,105,10 CONTROL "Bools as Char",DRV_BOOLS_CHAR,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,215,125,67,10 LTEXT "&Cache Size:",IDC_STATIC,14,183,52,8 EDITTEXT DRV_CACHE_SIZE,69,181,35,12,ES_AUTOHSCROLL LTEXT "Max &Varchar:",IDC_STATIC,13,161,54,8 EDITTEXT DRV_VARCHAR_SIZE,70,160,35,12,ES_AUTOHSCROLL LTEXT "Max Lon&gVarChar:",IDC_STATIC,125,161,67,8 EDITTEXT DRV_LONGVARCHAR_SIZE,199,160,35,12,ES_AUTOHSCROLL LTEXT "SysTable &Prefixes:",IDC_STATIC,126,178,61,18 EDITTEXT DRV_EXTRASYSTABLEPREFIXES,199,181,71,12,ES_AUTOHSCROLL DEFPUSHBUTTON "OK",IDOK,5,212,50,14,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,81,211,50,15 PUSHBUTTON "Apply",IDAPPLY,156,212,50,14 PUSHBUTTON "Defaults",IDDEFAULTS,232,211,50,15 GROUPBOX "Miscellaneous",IDC_STATIC,5,145,277,58 END DLG_OPTIONS_DS DIALOG DISCARDABLE 0, 0, 306, 241 STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Advanced Options (DataSource)" FONT 8, "MS Sans Serif" BEGIN PUSHBUTTON "Page 2",IDNEXTPAGE,49,5,40,15 PUSHBUTTON "Page 1",IDPREVPAGE,5,5,40,15 CONTROL "&Read Only",DS_READONLY,"Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,15,26,102,10 CONTROL "Row &Versioning",DS_ROWVERSIONING,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,163,26,85,10 CONTROL "Show System &Tables",DS_SHOWSYSTEMTABLES,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,41,100,10 CONTROL "Disallow &Premature",DS_DISALLOWPREMATURE,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,163,41,85,10 CONTROL "LF <-> CR/LF conversion",DS_LFCONVERSION,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,56,106,10 CONTROL "True is -1",DS_TRUEISMINUS1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,163,56,86,10 CONTROL "Updatable Cursors",DS_UPDATABLECURSORS,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,71,87,10 CONTROL "Server side prepare",DS_SERVERSIDEPREPARE,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,163,71,90,10 CONTROL "bytea as LO",DS_BYTEAASLONGVARBINARY,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,16,84,87,10 CONTROL "use gssapi for GSS request",DS_GSSAUTHUSEGSSAPI,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,163,84,110,10 GROUPBOX "Int8 As",IDC_STATIC,5,97,256,25 CONTROL "default",DS_INT8_AS_DEFAULT,"Button",BS_AUTORADIOBUTTON | WS_GROUP,12,107,40,10 CONTROL "bigint",DS_INT8_AS_BIGINT,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,55,107,35,10 CONTROL "numeric",DS_INT8_AS_NUMERIC,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,98,107,40,10 CONTROL "varchar",DS_INT8_AS_VARCHAR,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,141,107,40,10 CONTROL "double",DS_INT8_AS_DOUBLE,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,184,107,40,10 CONTROL "int4",DS_INT8_AS_INT4,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,227,107,29,10 LTEXT "Extra Opts",IDC_STATIC,264,98,40,17 EDITTEXT DS_EXTRA_OPTIONS,264,105,40,12,ES_AUTOHSCROLL GROUPBOX "Protocol",IDC_STATIC,5,126,136,25 CONTROL "7.4+",DS_PG74,"Button",BS_AUTORADIOBUTTON | WS_GROUP,11, 138,31,10 CONTROL "6.4+",DS_PG64,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP, 45,138,27,10 CONTROL "6.3",DS_PG63,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP, 79,138,26,10 CONTROL "6.2",DS_PG62,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP, 110,138,26,10 GROUPBOX "OID Options",IDC_STATIC,5,157,296,25 CONTROL "Show &Column",DS_SHOWOIDCOLUMN,"Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,13,168,67,10 CONTROL "Fake &Index",DS_FAKEOIDINDEX,"Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,80,168,59,10 LTEXT "Connect &Settings:",IDC_STATIC,5,189,57,11 EDITTEXT DS_CONNSETTINGS,90,189,211,27,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN DEFPUSHBUTTON "OK",IDOK,5,222,50,14,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,81,222,50,14 PUSHBUTTON "Apply",IDAPPLY,156,222,50,14 GROUPBOX "Level of rollback on errors",IDC_STATIC,147,126,154,25 CONTROL "Nop",DS_NO_ROLLBACK,"Button",BS_AUTORADIOBUTTON | WS_GROUP,151,138,36,9 CONTROL "Transaction",DS_TRANSACTION_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,186,138,57,9 CONTROL "Statement",DS_STATEMENT_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,247,138,47,9 END DLG_OPTIONS_GLOBAL DIALOG DISCARDABLE 0, 0, 306, 110 STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Global settings" FONT 8, "MS Sans Serif" BEGIN CONTROL "Comm&Log (C:\\psqlodbc_xxxx.log - Communications log)", DRV_COMMLOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,24, 263,10 CONTROL "Mylog (C:\\mylog_xxxx.log - Detailed debug output)", DRV_DEBUG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,42, 264,10 CONTROL "MSDTC log (C:\\pgdtclog\\mylog_xxxx.log - MSDTC debug output)", DRV_DTCLOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,60, 264,10 RTEXT "Folder for logging",IDC_STATIC,17,77,69,12 EDITTEXT DS_LOGDIR,98,75,188,13,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT DEFPUSHBUTTON "OK",IDOK,82,92,50,14,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,172,91,50,15 GROUPBOX "Pre-connection/default logging options",IDC_STATIC,5,5, 296,85 END DLG_DRIVER_CHANGE DIALOG DISCARDABLE 0, 0, 306, 87 STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Driver up/downgrade" FONT 8, "MS Sans Serif" BEGIN DEFPUSHBUTTON "OK",IDOK,82,68,50,14,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,172,67,50,15 GROUPBOX "Drivers List",IDC_STATIC,5,5,296,58 LTEXT "Select the driver",IDC_STATIC,31,30,73,8 LISTBOX IDC_DRIVER_LIST,117,18,151,32,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO DISCARDABLE BEGIN DLG_CONFIG, DIALOG BEGIN BOTTOMMARGIN, 141 END DLG_OPTIONS_DRV, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 282 TOPMARGIN, 5 BOTTOMMARGIN, 226 END DLG_OPTIONS_DS, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 301 TOPMARGIN, 5 BOTTOMMARGIN, 238 HORZGUIDE, 136 END DLG_OPTIONS_GLOBAL, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 301 TOPMARGIN, 5 BOTTOMMARGIN, 82 END DLG_DRIVER_CHANGE, DIALOG BEGIN LEFTMARGIN, 5 RIGHTMARGIN, 301 TOPMARGIN, 5 BOTTOMMARGIN, 82 END END #endif // APSTUDIO_INVOKED #ifndef _MAC ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION PG_DRVFILE_VERSION PRODUCTVERSION PG_DRVFILE_VERSION FILEFLAGSMASK 0x3L #ifdef _DEBUG FILEFLAGS 0x9L #else FILEFLAGS 0x8L #endif FILEOS 0x4L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904e4" BEGIN #ifdef UNICODE_SUPPORT VALUE "Comments", "PostgreSQL Unicode ODBC driver\0" #else VALUE "Comments", "PostgreSQL ANSI ODBC driver\0" #endif VALUE "CompanyName", "PostgreSQL Global Development Group\0" VALUE "FileDescription", "PostgreSQL ODBC Driver (English)\0" VALUE "FileVersion", POSTGRES_RESOURCE_VERSION #ifdef UNICODE_SUPPORT VALUE "InternalName", "psqlodbc35w\0" #else VALUE "InternalName", "psqlodbc30a\0" #endif VALUE "LegalCopyright", "Copyright \0" VALUE "LegalTrademarks", "ODBC(TM) is a trademark of Microsoft Corporation. Microsoft? is a registered trademark of Microsoft Corporation. Windows(TM) is a trademark of Microsoft Corporation.\0" #ifdef UNICODE_SUPPORT VALUE "OriginalFilename", "psqlodbc35w.dll\0" #else VALUE "OriginalFilename", "psqlodbc30a.dll\0" #endif VALUE "PrivateBuild", "\0" VALUE "ProductName", "PostgreSQL\0" VALUE "ProductVersion", POSTGRES_RESOURCE_VERSION VALUE "SpecialBuild", "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END #endif // !_MAC ///////////////////////////////////////////////////////////////////////////// // // String Table // STRINGTABLE DISCARDABLE BEGIN IDS_BADDSN "Invalid DSN entry, please recheck." IDS_MSGTITLE "Invalid DSN" IDS_ADVANCE_OPTION_DEF "Advanced Options (Default)" IDS_ADVANCE_SAVE "Save" IDS_ADVANCE_OPTION_DSN1 "Advanced Options (%s) 1/2" IDS_ADVANCE_OPTION_CON1 "Advanced Options (Connection 2/2)" IDS_ADVANCE_OPTION_DSN2 "Advanced Options (%s) 2/2" IDS_ADVANCE_OPTION_CON2 "Advanced Options (Connection 2/2)" IDS_ADVANCE_CONNECTION "Connection" END STRINGTABLE DISCARDABLE BEGIN IDS_SSLREQUEST_PREFER "prefer" IDS_SSLREQUEST_ALLOW "allow" IDS_SSLREQUEST_REQUIRE "require" IDS_SSLREQUEST_DISABLE "disable" IDS_SSLREQUEST_VERIFY_CA "verify-ca" IDS_SSLREQUEST_VERIFY_FULL "verify-full" END #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED psqlodbc-09.03.0300/win64.mak000644 001752 000000 00000024063 12335653444 015646 0ustar00saitowheel000000 000000 # # File: win64.mak # # Description: psqlodbc35w Unicode 64bit version Makefile. # (can be built using platform SDK's buildfarm) # # Configurations: Debug, Release # Build Types: ALL, CLEAN # Usage: NMAKE /f win64.mak CFG=[Release | Debug] [ALL | CLEAN] # # Comments: Created by Hiroshi Inoue, 2006-10-31 # !IF "$(CPU)" == "" !MESSAGE Making 64bit DLL... !MESSAGE You should set the CPU environemt variable !MESSAGE to distinguish your OS !ENDIF !IF "$(ANSI_VERSION)" == "yes" !MESSAGE Building the PostgreSQL ANSI 3.0 Driver for $(CPU)... !ELSE !MESSAGE Building the PostgreSQL Unicode 3.5 Driver for $(CPU)... !ENDIF !MESSAGE !IF "$(CFG)" == "" CFG=Release !MESSAGE No configuration specified. Defaulting to Release. !MESSAGE !ENDIF !IF "$(CFG)" != "Release" && "$(CFG)" != "Debug" !MESSAGE Invalid configuration "$(CFG)" specified. !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f win64.mak CFG=[Release | Debug] [ALL | CLEAN] !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "Release" ($(CPU) Release DLL) !MESSAGE "Debug" ($(CPU) Debug DLL) !MESSAGE !ERROR An invalid configuration was specified. !ENDIF # # Please replace the default options from the commandline if necessary # !IFNDEF CUSTOMCLOPT CUSTOMCLOPT=/nologo /MD /W3 /wd4018 /EHsc !ELSE !MESSAGE CL option $(CUSTOMCLOPT) specified !ENDIF # # Please specify additional libraries to link from the command line. # For example specify # CUSTOMLINKLIBS=bufferoverflowu.lib # when bufferoverflowu.lib is needed in old VC environment. # CUSTOMLINKLIBS= ADD_DEFINES=/D _WIN64 # # Include libraries as well as import libraries # may be different from those of 32bit ones. # Please set PG_INC, PG_LIB, SSL_INC or PG_LIB # variables to appropriate ones. # !IFNDEF PG_INC PG_INC=$(PROGRAMFILES)\PostgreSQL\9.3\include !MESSAGE Using default PostgreSQL Include directory: $(PG_INC) !ENDIF !IFNDEF PG_LIB PG_LIB=C:\develop\lib\$(CPU) !MESSAGE Using default PostgreSQL Library directory: $(PG_LIB) !ENDIF !IF "$(USE_LIBPQ)" != "no" !IFNDEF SSL_INC SSL_INC=C:\OpenSSL\include !MESSAGE Using default OpenSSL Include directory: $(SSL_INC) !ENDIF !IFNDEF SSL_LIB SSL_LIB=C:\develop\lib\$(CPU) !MESSAGE Using default OpenSSL Library directory: $(SSL_LIB) !ENDIF SSL_DLL = "SSLEAY32.dll" RESET_CRYPTO = yes ADD_DEFINES = $(ADD_DEFINES) /D USE_LIBPQ /D "SSL_DLL=\"$(SSL_DLL)\"" /D USE_SSL !ENDIF !IF "$(USE_SSPI)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D USE_SSPI !ENDIF !IF "$(USE_GSS)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D USE_GSS !ENDIF !IF "$(ANSI_VERSION)" == "yes" DTCLIB = pgenlista !ELSE DTCLIB = pgenlist !ENDIF DTCDLL = $(DTCLIB).dll !IF "$(_NMAKE_VER)" == "6.00.9782.0" VC07_DELAY_LOAD= MSDTC=no !ELSE !IF "$(USE_LIBPQ)" != "no" VC07_DELAY_LOAD=/DelayLoad:libpq.dll /DelayLoad:$(SSL_DLL) !IF "$(RESET_CRYPTO)" == "yes" VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /DelayLoad:libeay32.dll ADD_DEFINES=$(ADD_DEFINES) /D RESET_CRYPTO_CALLBACKS !ENDIF !ENDIF !IF "$(USE_SSPI)" == "yes" VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /DelayLoad:secur32.dll /Delayload:crypt32.dll !ENDIF !IF "$(USE_GSS)" == "yes" VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /Delayload:gssapi64.dll !ENDIF VC07_DELAY_LOAD="$(VC07_DELAY_LOAD) /DelayLoad:$(DTCDLL) /DELAY:UNLOAD" !ENDIF ADD_DEFINES = $(ADD_DEFINES) /D "DYNAMIC_LOAD" !IF "$(MSDTC)" != "no" ADD_DEFINES = $(ADD_DEFINES) /D "_HANDLE_ENLIST_IN_DTC_" !ENDIF !IF "$(MEMORY_DEBUG)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D "_MEMORY_DEBUG_" /GS !ENDIF !IF "$(CPU)" == "AMD64" CPUTYPE = x64 !ELSE CPUTYPE = $(CPU) !ENDIF !IF "$(ANSI_VERSION)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D "DBMS_NAME=\"PostgreSQL ANSI($(CPUTYPE))\"" /D "ODBCVER=0x0300" !ELSE ADD_DEFINES = $(ADD_DEFINES) /D "DBMS_NAME=\"PostgreSQL Unicode($(CPUTYPE))\"" /D "ODBCVER=0x0351" /D "UNICODE_SUPPORT" RSC_DEFINES = $(RSC_DEFINES) /D "UNICODE_SUPPORT" !ENDIF !IF "$(PORT_CHECK)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /Wp64 !ENDIF !IF "$(PG_INC)" != "" INC_OPT = $(INC_OPT) /I "$(PG_INC)" !ENDIF !IF "$(SSL_INC)" != "" INC_OPT = $(INC_OPT) /I "$(SSL_INC)" !ENDIF !IF "$(GSS_INC)" != "" INC_OPT = $(INC_OPT) /I "$(GSS_INC)" !ENDIF !IF "$(ADDL_INC)" != "" INC_OPT = $(INC_OPT) /I "$(ADD_INC)" !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF !IF "$(ANSI_VERSION)" == "yes" MAINLIB = psqlodbc30a !ELSE MAINLIB = psqlodbc35w !ENDIF MAINDLL = $(MAINLIB).dll XALIB = pgxalib XADLL = $(XALIB).dll !IF "$(CFG)" == "Release" !IF "$(ANSI_VERSION)" == "yes" OUTDIR=.\$(CPU)ANSI OUTDIRBIN=.\$(CPU)ANSI INTDIR=.\$(CPU)ANSI !ELSE OUTDIR=.\$(CPU) OUTDIRBIN=.\$(CPU) INTDIR=.\$(CPU) !ENDIF !ELSEIF "$(CFG)" == "Debug" !IF "$(ANSI_VERSION)" == "yes" OUTDIR=.\$(CPU)ANSIDebug OUTDIRBIN=.\$(CPU)ANSIDebug INTDIR=.\$(CPU)ANSIDebug !ELSE OUTDIR=.\$(CPU)Debug OUTDIRBIN=.\$(CPU)Debug INTDIR=.\$(CPU)Debug !ENDIF !ENDIF ALLDLL = "$(INTDIR)" !IF "$(OUTDIR)" != "$(INTDIR)" ALLDLL = $(ALLDLL) "$(INTDIR)" !ENDIF ALLDLL = $(ALLDLL) "$(OUTDIR)\$(MAINDLL)" !IF "$(MSDTC)" != "no" ALLDLL = $(ALLDLL) "$(OUTDIR)\$(XADLL)" "$(OUTDIR)\$(DTCDLL)" !ENDIF ALL : $(ALLDLL) CLEAN : -@erase "$(INTDIR)\*.obj" -@erase "$(INTDIR)\*.res" -@erase "$(OUTDIR)\*.lib" -@erase "$(OUTDIR)\*.exp" -@erase "$(INTDIR)\*.pch" -@erase "$(OUTDIR)\$(MAINDLL)" !IF "$(MSDTC)" != "no" -@erase "$(OUTDIR)\$(DTCDLL)" -@erase "$(OUTDIR)\$(XADLL)" !ENDIF !IF "$(MSDTC)" != "no" "$(OUTDIR)\$(MAINDLL)": "$(OUTDIR)\$(DTCLIB).lib" !ENDIF "$(INTDIR)" : if not exist "$(INTDIR)/$(NULL)" mkdir "$(INTDIR)" !IF "$(OUTDIR)" != "$(INTDIR)" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" !ENDIF CPP=cl.exe CPP_PROJ=$(CUSTOMCLOPT) $(INC_OPT) /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "_CRT_SECURE_NO_DEPRECATE" /D "PSQLODBC_EXPORTS" /D "WIN_MULTITHREAD_SUPPORT" $(ADD_DEFINES) /Fp"$(INTDIR)\psqlodbc.pch" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD !IF "$(CFG)" == "Release" CPP_PROJ=$(CPP_PROJ) /O2 /D "NDEBUG" !ELSEIF "$(CFG)" == "Debug" CPP_PROJ=$(CPP_PROJ) /Gm /ZI /Od /D "_DEBUG" /GZ !ENDIF .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) /c $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) /c $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) /c $< << MTL=midl.exe RSC=rc.exe BSC32=bscmake.exe MTL_PROJ=/nologo /mktyplib203 /win32 RSC_PROJ=/l 0x809 /fo"$(INTDIR)\psqlodbc.res" /d "MULTIBUTE" BSC32_FLAGS=/nologo /o"$(OUTDIR)\psqlodbc.bsc" !IF "$(CFG)" == "Release" MTL_PROJ=$(MTL_PROJ) /D "NDEBUG" RSC_PROJ=$(RSC_PROJ) /d "NDEBUG" !ELSE MTL_PROJ=$(MTL_PROJ) /D "_DEBUG" RSC_PROJ=$(RSC_PROJ) /d "_DEBUG" !ENDIF BSC32_SBRS= \ LINK32=link.exe LIB32=lib.exe LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib advapi32.lib odbc32.lib odbccp32.lib wsock32.lib ws2_32.lib XOleHlp.lib winmm.lib "$(OUTDIR)\$(DTCLIB).lib" msvcrt.lib $(CUSTOMLINKLIBS) /nologo /dll /machine:$(CPU) /def:"$(DEF_FILE)" !IF "$(ANSI_VERSION)" == "yes" DEF_FILE= "psqlodbca.def" !ELSE DEF_FILE= "psqlodbc.def" !ENDIF !IF "$(CFG)" == "Release" LINK32_FLAGS=$(LINK32_FLAGS) /incremental:no !ELSE LINK32_FLAGS=$(LINK32_FLAGS) /incremental:yes /debug /pdbtype:sept !ENDIF LINK32_FLAGS=$(LINK32_FLAGS) "$(VC07_DELAY_LOAD)" !IF "$(PG_LIB)" != "" LINK32_FLAGS=$(LINK32_FLAGS) /libpath:"$(PG_LIB)" !ENDIF !IF "$(GSS_LIB)" != "" LINK32_FLAGS=$(LINK32_FLAGS) /libpath:"$(GSS_LIB)" !ENDIF !IF "$(SSL_LIB)" != "" LINK32_FLAGS=$(LINK32_FLAGS) /libpath:"$(SSL_LIB)" !ENDIF LINK32_OBJS= \ "$(INTDIR)\bind.obj" \ "$(INTDIR)\columninfo.obj" \ "$(INTDIR)\connection.obj" \ "$(INTDIR)\convert.obj" \ "$(INTDIR)\dlg_specific.obj" \ "$(INTDIR)\dlg_wingui.obj" \ "$(INTDIR)\drvconn.obj" \ "$(INTDIR)\environ.obj" \ "$(INTDIR)\execute.obj" \ "$(INTDIR)\info.obj" \ "$(INTDIR)\info30.obj" \ "$(INTDIR)\lobj.obj" \ "$(INTDIR)\md5.obj" \ "$(INTDIR)\misc.obj" \ "$(INTDIR)\mylog.obj" \ "$(INTDIR)\pgapi30.obj" \ "$(INTDIR)\multibyte.obj" \ "$(INTDIR)\options.obj" \ "$(INTDIR)\parse.obj" \ "$(INTDIR)\pgtypes.obj" \ "$(INTDIR)\psqlodbc.obj" \ "$(INTDIR)\qresult.obj" \ "$(INTDIR)\results.obj" \ "$(INTDIR)\setup.obj" \ !IF "$(USE_SSPI)" == "yes" "$(INTDIR)\sspisvcs.obj" \ !ENDIF !IF "$(USE_GSS)" == "yes" "$(INTDIR)\gsssvcs.obj" \ !ENDIF "$(INTDIR)\socket.obj" \ "$(INTDIR)\statement.obj" \ "$(INTDIR)\tuple.obj" \ "$(INTDIR)\odbcapi.obj" \ "$(INTDIR)\odbcapi30.obj" \ "$(INTDIR)\descriptor.obj" \ "$(INTDIR)\loadlib.obj" \ !IF "$(ANSI_VERSION)" != "yes" "$(INTDIR)\win_unicode.obj" \ "$(INTDIR)\odbcapiw.obj" \ "$(INTDIR)\odbcapi30w.obj" \ !ENDIF !IF "$(MSDTC)" != "no" "$(INTDIR)\xalibname.obj" \ !ENDIF !IF "$(MEMORY_DEBUG)" == "yes" "$(INTDIR)\inouealc.obj" \ !ENDIF "$(INTDIR)\psqlodbc.res" DTCDEF_FILE= "$(DTCLIB).def" LIB32_DTCLIBFLAGS=/nologo /machine:$(CPU) /def:"$(DTCDEF_FILE)" LINK32_DTCFLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib uuid.lib wsock32.lib XOleHlp.lib $(OUTDIR)\$(MAINLIB).lib $(CUSTOMLINKLIBS) Delayimp.lib /DelayLoad:XOLEHLP.DLL /nologo /dll /incremental:no /machine:$(CPU) LINK32_DTCOBJS= \ "$(INTDIR)\msdtc_enlist.obj" "$(INTDIR)\xalibname.obj" XADEF_FILE= "$(XALIB).def" LINK32_XAFLAGS=/nodefaultlib:libcmt.lib kernel32.lib user32.lib gdi32.lib advapi32.lib odbc32.lib odbccp32.lib wsock32.lib XOleHlp.lib winmm.lib msvcrt.lib $(CUSTOMLINKLIBS) /nologo /dll /incremental:no /machine:$(CPU) /def:"$(XADEF_FILE)" LINK32_XAOBJS= \ "$(INTDIR)\pgxalib.obj" "$(OUTDIR)\$(MAINDLL)" : $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) /pdb:$*.pdb /implib:$*.lib /out:$@ << "$(OUTDIR)\$(DTCLIB).lib" : $(DEF_FILE) $(LINK32_DTCOBJS) $(LIB32) @<< $(LIB32_DTCLIBFLAGS) $(LINK32_DTCOBJS) /out:$@ << "$(OUTDIR)\$(DTCDLL)" : $(LINK32_DTCOBJS) $(LINK32) @<< $(LINK32_DTCFLAGS) $(LINK32_DTCOBJS) $*.exp /pdb:$*.pdb /out:$@ << "$(OUTDIR)\$(XADLL)" : $(XADEF_FILE) $(LINK32_XAOBJS) $(LINK32) @<< $(LINK32_XAFLAGS) $(LINK32_XAOBJS) /pdb:$*.pdb /implib:$*.lib /out:$@ << SOURCE=psqlodbc.rc "$(INTDIR)\psqlodbc.res" : $(SOURCE) "$(INTDIR)" $(RSC) $(RSC_PROJ) $(RSC_DEFINES) $(SOURCE) psqlodbc-09.03.0300/win32.mak000644 001752 000000 00000022640 12335653444 015640 0ustar00saitowheel000000 000000 # # File: win32.mak # # Description: psqlodbc35w Unicode version Makefile for Win32. # # Configurations: Debug, Release # Build Types: ALL, CLEAN # Usage: NMAKE /f win32.mak CFG=[Release | Debug] [ALL | CLEAN] # # Comments: Created by Dave Page, 2001-02-12 # !IF "$(ANSI_VERSION)" == "yes" !MESSAGE Building the PostgreSQL ANSI 3.0 Driver for Win32... !ELSE !MESSAGE Building the PostgreSQL Unicode 3.5 Driver for Win32... !ENDIF !MESSAGE !IF "$(CFG)" == "" CFG=Release !MESSAGE No configuration specified. Defaulting to Release. !MESSAGE !ENDIF !IF "$(CFG)" != "Release" && "$(CFG)" != "Debug" !MESSAGE Invalid configuration "$(CFG)" specified. !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f win32.mak CFG=[Release | Debug] [ALL | CLEAN] !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "Release" (Win32 Release DLL) !MESSAGE "Debug" (Win32 Debug DLL) !MESSAGE !ERROR An invalid configuration was specified. !ENDIF # # Please replace the default options from the commandline if necessary # !IFNDEF CUSTOMCLOPT CUSTOMCLOPT=/nologo /W3 /wd4018 !ELSE !MESSAGE CL option $(CUSTOMCLOPT) specified !ENDIF # !IFNDEF PG_INC PG_INC=$(PROGRAMFILES)\PostgreSQL\9.3\include !MESSAGE Using default PostgreSQL Include directory: $(PG_INC) !ENDIF !IFNDEF PG_LIB PG_LIB=$(PROGRAMFILES)\PostgreSQL\9.3\lib !MESSAGE Using default PostgreSQL Library directory: $(PG_LIB) !ENDIF !IFNDEF LINKMT LINKMT=MT !ENDIF !IF "$(LINKMT)" == "MT" !MESSAGE Linking static Multithread library !ELSE !MESSAGE Linking dynamic Multithread library !ENDIF !IFNDEF SSL_INC SSL_INC=C:\OpenSSL\include !MESSAGE Using default OpenSSL Include directory: $(SSL_INC) !ENDIF !IFNDEF SSL_LIB SSL_LIB=C:\OpenSSL\lib\VC !MESSAGE Using default OpenSSL Library directory: $(SSL_LIB) !ENDIF !IF "$(USE_LIBPQ)" != "no" SSL_DLL = "SSLEAY32.dll" RESET_CRYPTO = yes ADD_DEFINES = $(ADD_DEFINES) /D USE_LIBPQ /D "SSL_DLL=\"$(SSL_DLL)\"" /D USE_SSL !ENDIF !IF "$(USE_SSPI)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D USE_SSPI !ENDIF !IF "$(ANSI_VERSION)" == "yes" DTCLIB = pgenlista !ELSE DTCLIB = pgenlist !ENDIF DTCDLL = $(DTCLIB).dll !IF "$(_NMAKE_VER)" == "6.00.9782.0" MSVC_VERSION=vc60 VC07_DELAY_LOAD= MSDTC=no VC_FLAGS=/GX /YX !ELSE MSVC_VERSION=vc70 !IF "$(USE_LIBPQ)" != "no" VC07_DELAY_LOAD=/DelayLoad:libpq.dll /DelayLoad:$(SSL_DLL) !IF "$(RESET_CRYPTO)" == "yes" VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /DelayLoad:libeay32.dll ADD_DEFINES=$(ADD_DEFINES) /D RESET_CRYPTO_CALLBACKS !ENDIF !ENDIF !IF "$(USE_SSPI)" == "yes" VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /Delayload:secur32.dll /Delayload:crypt32.dll !ENDIF VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /delayLoad:$(DTCDLL) /DELAY:UNLOAD VC_FLAGS=/EHsc !ENDIF ADD_DEFINES = $(ADD_DEFINES) /D "DYNAMIC_LOAD" !IF "$(MSDTC)" != "no" ADD_DEFINES = $(ADD_DEFINES) /D "_HANDLE_ENLIST_IN_DTC_" !ENDIF !IF "$(MEMORY_DEBUG)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D "_MEMORY_DEBUG_" /GS !ELSE ADD_DEFINES = $(ADD_DEFINES) /GS !ENDIF !IF "$(ANSI_VERSION)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D "DBMS_NAME=\"PostgreSQL ANSI\"" /D "ODBCVER=0x0350" !ELSE ADD_DEFINES = $(ADD_DEFINES) /D "UNICODE_SUPPORT" /D "ODBCVER=0x0351" RSC_DEFINES = $(RSC_DEFINES) /D "UNICODE_SUPPORT" !ENDIF !IF "$(PORTCHECK_64BIT)" == "yes" # ADD_DEFINES = $(ADD_DEFINES) /Wp64 ADD_DEFINES = $(ADD_DEFINES) /D _WIN64 !ENDIF !IF "$(PG_INC)" != "" INC_OPT=$(INC_OPT) /I "$(PG_INC)" !ENDIF !IF "$(SSL_INC)" != "" INC_OPT=$(INC_OPT) /I "$(SSL_INC)" !ENDIF !IF "$(OS)" == "Windows_NT" NULL= !ELSE NULL=nul !ENDIF !IF "$(ANSI_VERSION)" == "yes" MAINLIB = psqlodbc30a !ELSE MAINLIB = psqlodbc35w !ENDIF MAINDLL = $(MAINLIB).dll XALIB = pgxalib XADLL = $(XALIB).dll !IF "$(CFG)" == "Release" !IF "$(ANSI_VERSION)" == "yes" OUTDIR=.\MultibyteRelease OUTDIRBIN=.\MultibyteRelease INTDIR=.\MultibyteRelease !ELSE OUTDIR=.\Release OUTDIRBIN=.\Release INTDIR=.\Release !ENDIF !ELSEIF "$(CFG)" == "Debug" !IF "$(ANSI_VERSION)" == "yes" OUTDIR=.\MultibyteDebug OUTDIRBIN=.\MultibyteDebug INTDIR=.\MultibyteDebug !ELSE OUTDIR=.\Debug OUTDIRBIN=.\Debug INTDIR=.\Debug !ENDIF !ENDIF !IF "$(LINKMT)" != "MT" OUTDIR = $(OUTDIR)$(LINKMT) OUTDIRBIN = $(OUTDIRBIN)$(LINKMT) INTDIR = $(INTDIR)$(LINKMT) !ENDIF ALLDLL = "$(INTDIR)" !IF "$(OUTDIR)" != "$(INTDIR)" ALLDLL = $(ALLDLL) "$(OUTDIR)" !ENDIF ALLDLL = $(ALLDLL) "$(OUTDIR)\$(MAINDLL)" !IF "$(MSDTC)" != "no" ALLDLL = $(ALLDLL) "$(OUTDIR)\$(XADLL)" "$(OUTDIR)\$(DTCDLL)" !ENDIF ALL : $(ALLDLL) CLEAN : -@erase "$(INTDIR)\*.obj" -@erase "$(INTDIR)\*.res" -@erase "$(OUTDIR)\*.lib" -@erase "$(OUTDIR)\*.exp" -@erase "$(INTDIR)\*.pch" -@erase "$(OUTDIR)\$(MAINDLL)" !IF "$(MSDTC)" != "no" -@erase "$(OUTDIR)\$(DTCDLL)" -@erase "$(OUTDIR)\$(XADLL)" !ENDIF "$(INTDIR)" : if not exist "$(INTDIR)/$(NULL)" mkdir "$(INTDIR)" !IF "$(OUTDIR)" != "$(INTDIR)" "$(OUTDIR)" : if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)" !ENDIF !IF "$(MSDTC)" != "no" "$(OUTDIR)\$(MAINDLL)" : "$(OUTDIR)\$(DTCLIB).lib" !ENDIF $(INTDIR)\connection.obj $(INTDIR)\psqlodbc.res: version.h CPP=cl.exe !IF "$(CFG)" == "Release" CPP_PROJ=/$(LINKMT) /O2 /D "NDEBUG" !ELSEIF "$(CFG)" == "Debug" CPP_PROJ=/$(LINKMT)d /Gm /ZI /Od /RTC1 /D "_DEBUG" !ENDIF CPP_PROJ=$(CPP_PROJ) $(CUSTOMCLOPT) $(VC_FLAGS) $(INC_OPT) /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "_CRT_SECURE_NO_DEPRECATE" /D "PSQLODBC_EXPORTS" /D "WIN_MULTITHREAD_SUPPORT" $(ADD_DEFINES) /Fp"$(INTDIR)\psqlodbc.pch" /Fo"$(INTDIR)"\ /Fd"$(INTDIR)"\ /FD !MESSAGE CPP_PROJ=$(CPP_PROJ) .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .c{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) /c $< << .cpp{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) /c $< << .cxx{$(INTDIR)}.sbr:: $(CPP) @<< $(CPP_PROJ) /c $< << MTL=midl.exe RSC=rc.exe BSC32=bscmake.exe MTL_PROJ=/nologo /mktyplib203 /win32 RSC_PROJ=/l 0x809 /d "MULTIBYTE" BSC32_FLAGS=/nologo /o"$(OUTDIR)\psqlodbc.bsc" !IF "$(CFG)" == "Release" MTL_PROJ=$(MTL_PROC) /D "NDEBUG" RSC_PROJ=$(RSC_PROJ) /d "NDEBUG" !ELSE MTL_PROJ=$(MTL_PROJ) /D "_DEBUG" RSC_PROJ=$(RSC_PROJ) /d "_DEBUG" !ENDIF BSC32_SBRS= \ LINK32=link.exe LIB32=lib.exe !IF "$(MSDTC)" != "no" LINK32_FLAGS=$(OUTDIR)\$(DTCLIB).lib !ENDIF LINK32_FLAGS=$(LINK32_FLAGS) kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib wsock32.lib ws2_32.lib winmm.lib /nologo /dll /machine:I386 /def:$(DEF_FILE) !IF "$(ANSI_VERSION)" == "yes" DEF_FILE= "psqlodbca.def" !ELSE DEF_FILE= "psqlodbc.def" !ENDIF !IF "$(CFG)" == "Release" LINK32_FLAGS=$(LINK32_FLAGS) /incremental:no !ELSE LINK32_FLAGS=$(LINK32_FLAGS) /incremental:yes /debug !ENDIF LINK32_FLAGS=$(LINK32_FLAGS) $(VC07_DELAY_LOAD) !IF "$(PG_LIB)" != "" LINK32_FLAGS=$(LINK32_FLAGS) /libpath:"$(PG_LIB)" !ENDIF !IF "$(SSL_LIB)" != "" LINK32_FLAGS=$(LINK32_FLAGS) /libpath:"$(SSL_LIB)" !ENDIF LINK32_OBJS= \ "$(INTDIR)\bind.obj" \ "$(INTDIR)\columninfo.obj" \ "$(INTDIR)\connection.obj" \ "$(INTDIR)\convert.obj" \ "$(INTDIR)\dlg_specific.obj" \ "$(INTDIR)\dlg_wingui.obj" \ "$(INTDIR)\drvconn.obj" \ "$(INTDIR)\environ.obj" \ "$(INTDIR)\execute.obj" \ "$(INTDIR)\info.obj" \ "$(INTDIR)\info30.obj" \ "$(INTDIR)\lobj.obj" \ "$(INTDIR)\md5.obj" \ "$(INTDIR)\misc.obj" \ "$(INTDIR)\mylog.obj" \ "$(INTDIR)\pgapi30.obj" \ "$(INTDIR)\multibyte.obj" \ "$(INTDIR)\options.obj" \ "$(INTDIR)\parse.obj" \ "$(INTDIR)\pgtypes.obj" \ "$(INTDIR)\psqlodbc.obj" \ "$(INTDIR)\qresult.obj" \ "$(INTDIR)\results.obj" \ "$(INTDIR)\setup.obj" \ !IF "$(USE_SSPI)" == "yes" "$(INTDIR)\sspisvcs.obj" \ !ENDIF "$(INTDIR)\socket.obj" \ "$(INTDIR)\statement.obj" \ "$(INTDIR)\tuple.obj" \ "$(INTDIR)\odbcapi.obj" \ "$(INTDIR)\odbcapi30.obj" \ "$(INTDIR)\descriptor.obj" \ "$(INTDIR)\loadlib.obj" \ !IF "$(ANSI_VERSION)" != "yes" "$(INTDIR)\win_unicode.obj" \ "$(INTDIR)\odbcapiw.obj" \ "$(INTDIR)\odbcapi30w.obj" \ !ENDIF !IF "$(MSDTC)" != "no" "$(INTDIR)\xalibname.obj" \ !ENDIF !IF "$(MEMORY_DEBUG)" == "yes" "$(INTDIR)\inouealc.obj" \ !ENDIF "$(INTDIR)\psqlodbc.res" DTCDEF_FILE= "$(DTCLIB).def" LIB_DTCLIBFLAGS=/nologo /machine:I386 /def:$(DTCDEF_FILE) LINK32_DTCFLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib uuid.lib wsock32.lib XOleHlp.lib $(OUTDIR)\$(MAINLIB).lib Delayimp.lib /DelayLoad:XOLEHLP.DLL /nologo /dll /incremental:no /machine:I386 LINK32_DTCOBJS= \ "$(INTDIR)\msdtc_enlist.obj" "$(INTDIR)\xalibname.obj" XADEF_FILE= "$(XALIB).def" LINK32_XAFLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib odbc32.lib odbccp32.lib uuid.lib wsock32.lib /nologo /dll /incremental:no /machine:I386 /def:$(XADEF_FILE) LINK32_XAOBJS= \ "$(INTDIR)\pgxalib.obj" "$(OUTDIR)\$(MAINDLL)" : $(DEF_FILE) $(LINK32_OBJS) $(LINK32) @<< $(LINK32_FLAGS) $(LINK32_OBJS) /pdb:$*.pdb /implib:$*.lib /out:$@ << "$(OUTDIR)\$(DTCLIB).lib" : $(DTCDEF_FILE) $(LINK32_DTCOBJS) $(LIB32) @<< $(LIB_DTCLIBFLAGS) $(LINK32_DTCOBJS) /out:$@ << "$(OUTDIR)\$(DTCDLL)" : $(DTCDEF_FILE) $(LINK32_DTCOBJS) $(LINK32) @<< $(LINK32_DTCFLAGS) $(LINK32_DTCOBJS) $*.exp /pdb:$*.pdb /out:$@ << "$(OUTDIR)\$(XADLL)" : $(XADEF_FILE) $(LINK32_XAOBJS) $(LINK32) @<< $(LINK32_XAFLAGS) $(LINK32_XAOBJS) /pdb:$*.pdb /implib:$*.lib /out:$@ << SOURCE=psqlodbc.rc "$(INTDIR)\psqlodbc.res" : $(SOURCE) $(RSC) $(RSC_PROJ) /fo$@ $(RSC_DEFINES) $(SOURCE) psqlodbc-09.03.0300/psqlodbc.reg000644 001752 000000 00000001234 12335653444 016506 0ustar00saitowheel000000 000000 REGEDIT4 [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI] [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers] "PostgreSQL ANSI"="Installed" "PostgreSQL Unicode"="Installed" [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\PostgreSQL ANSI] "APILevel"="1" "ConnectFunctions"="YYN" "Driver"="PSQLODBC30A.DLL" "DriverODBCVer"="03.00" "FileUsage"="0" "Setup"="PSQLODBC30A.DLL" "SQLLevel"="1" "UsageCount"=dword:00000001 [HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\PostgreSQL Unicode] "APILevel"="1" "ConnectFunctions"="YYN" "Driver"="PSQLODBC35W.DLL" "DriverODBCVer"="03.51" "FileUsage"="0" "Setup"="PSQLODBC35W.DLL" "SQLLevel"="1" "UsageCount"=dword:00000001 psqlodbc-09.03.0300/psqlodbc.dsp000644 001752 000000 00000021470 12335653444 016523 0ustar00saitowheel000000 000000 # Microsoft Developer Studio Project File - Name="psqlODBC" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) Console Application" 0x0103 CFG=psqlODBC - Win32 Release !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "psqlodbc.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "psqlodbc.mak" CFG="psqlODBC - Win32 Release" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "psqlODBC - Win32 Release" ("Win32 (x86) Console Application") !MESSAGE "psqlODBC - Win32 Debug" ("Win32 (x86) Console Application") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" CPP=cl.exe RSC=rc.exe !IF "$(CFG)" == "psqlODBC - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "Release" # PROP Intermediate_Dir "Release" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "USE_LIBPQ" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /D ODBCVER=0x0351 /D "DRIVER_CURSOR_IMPLEMENT" /D "WIN_MULTITHREAD_SUPPORT" /D "DYNAMIC_LOAD" /D "MULTIBYTE" /D "UNICODE_SUPPORT" /Fp"psqlodbc.pch" /YX /FD /c # ADD CPP /nologo /W3 /GX /O2 /I "C:\Program Files\PostgreSQL\9.3\include" /I "C:\OpenSSL\include" /D "NDEBUG" /D "USE_LIBPQ" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /D ODBCVER=0x0351 /D "DRIVER_CURSOR_IMPLEMENT" /D "WIN_MULTITHREAD_SUPPORT" /D "DYNAMIC_LOAD" /D "MULTIBYTE" /D "UNICODE_SUPPORT" /D "USE_SSL" /Fp"psqlodbc.pch" /YX /FD /D SSL_DLL="\"SSLEAY32.dll\"" /c # ADD BASE RSC /l 0x411 /d "NDEBUG" # ADD RSC /l 0x411 /i "." /d "NDEBUG" # SUBTRACT RSC /x BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib wsock32.lib XOleHlp.lib winmm.lib /nologo /subsystem:windows /machine:I386 # ADD LINK32 wsock32.lib XOleHlp.lib winmm.lib libpq.lib ssleay32.lib libeay32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /pdb:"psqlodbc35w.pdb" /machine:I386 /out:"psqlodbc35w.dll" /implib:"psqlodbc35w.lib" /libpath:"C:\Program Files\PostgreSQL\9.3\lib\ms" /libpath:"C:\OpenSSL\lib\VC" # SUBTRACT LINK32 /pdb:none /nodefaultlib !ELSEIF "$(CFG)" == "psqlODBC - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "Debug" # PROP BASE Intermediate_Dir "Debug" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "Debug" # PROP Intermediate_Dir "Debug" # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MT /W3 /GX /Od /D "USE_LIBPQ" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /D ODBCVER=0x0351 /D "DRIVER_CURSOR_IMPLEMENT" /D "WIN_MULTITHREAD_SUPPORT" /D "DYNAMIC_LOAD" /D "MULTIBYTE" /D "UNICODE_SUPPORT" /YX /FD /c # ADD CPP /nologo /W3 /GX /O2 /I "C:\Program Files\PostgreSQL\9.3\include" /I "C:\OpenSSL\include" /D "_DEBUG" /D "USE_LIBPQ" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /D ODBCVER=0x0351 /D "DRIVER_CURSOR_IMPLEMENT" /D "WIN_MULTITHREAD_SUPPORT" /D "DYNAMIC_LOAD" /D "MULTIBYTE" /D "UNICODE_SUPPORT" /D "USE_SSL" /FR /YX /FD /D SSL_DLL="\"SSLEAY32.dll\"" /c # SUBTRACT CPP /X # ADD BASE RSC /l 0x411 /d "_DEBUG" # ADD RSC /l 0x411 /i "." /d "_DEBUG" # SUBTRACT RSC /x BSC32=bscmake.exe # ADD BASE BSC32 /nologo # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib wsock32.lib XOleHlp.lib winmm.lib /nologo /subsystem:windows /debug /machine:I386 # ADD LINK32 wsock32.lib XOleHlp.lib winmm.lib libpq.lib ssleay32.lib libeay32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /pdb:"psqlodbc35w.pdb" /debug /machine:I386 /out:"psqlodbc35w.dll" /implib:"psqlodbc35w.lib" /libpath:"C:\Program Files\PostgreSQL\9.3\lib\ms" /libpath:"C:\OpenSSL\lib\VC" # SUBTRACT LINK32 /pdb:none /nodefaultlib !ENDIF # Begin Target # Name "psqlODBC - Win32 Release" # Name "psqlODBC - Win32 Debug" # Begin Group "source" # PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" # Begin Source File SOURCE=bind.c # End Source File # Begin Source File SOURCE=columninfo.c # End Source File # Begin Source File SOURCE=connection.c # End Source File # Begin Source File SOURCE=convert.c # End Source File # Begin Source File SOURCE=.\descriptor.c # End Source File # Begin Source File SOURCE=dlg_specific.c # End Source File # Begin Source File SOURCE=dlg_wingui.c # End Source File # Begin Source File SOURCE=drvconn.c # End Source File # Begin Source File SOURCE=environ.c # End Source File # Begin Source File SOURCE=execute.c # End Source File # Begin Source File SOURCE=info.c # End Source File # Begin Source File SOURCE=info30.c # End Source File # Begin Source File SOURCE=.\inouealc.c # End Source File # Begin Source File SOURCE=.\loadlib.c # End Source File # Begin Source File SOURCE=lobj.c # End Source File # Begin Source File SOURCE=misc.c # End Source File # Begin Source File SOURCE=multibyte.c # End Source File # Begin Source File SOURCE=.\mylog.c # End Source File # Begin Source File SOURCE=.\odbcapi.c # End Source File # Begin Source File SOURCE=.\odbcapi30.c # End Source File # Begin Source File SOURCE=.\odbcapi30w.c # End Source File # Begin Source File SOURCE=.\odbcapiw.c # End Source File # Begin Source File SOURCE=options.c # End Source File # Begin Source File SOURCE=parse.c # End Source File # Begin Source File SOURCE=pgapi30.c # End Source File # Begin Source File SOURCE=pgtypes.c # End Source File # Begin Source File SOURCE=psqlodbc.c # End Source File # Begin Source File SOURCE=qresult.c # End Source File # Begin Source File SOURCE=results.c # End Source File # Begin Source File SOURCE=setup.c # End Source File # Begin Source File SOURCE=socket.c # End Source File # Begin Source File SOURCE=statement.c # End Source File # Begin Source File SOURCE=tuple.c # End Source File # Begin Source File SOURCE=win_md5.c # End Source File # Begin Source File SOURCE=.\win_unicode.c # End Source File # End Group # Begin Group "include" # PROP Default_Filter "" # Begin Source File SOURCE=bind.h # End Source File # Begin Source File SOURCE=columninfo.h # End Source File # Begin Source File SOURCE=connection.h # End Source File # Begin Source File SOURCE=convert.h # End Source File # Begin Source File SOURCE=descriptor.h # End Source File # Begin Source File SOURCE=dlg_specific.h # End Source File # Begin Source File SOURCE=environ.h # End Source File # Begin Source File SOURCE=iodbc.h # End Source File # Begin Source File SOURCE=isql.h # End Source File # Begin Source File SOURCE=isqlext.h # End Source File # Begin Source File SOURCE=.\loadlib.h # End Source File # Begin Source File SOURCE=lobj.h # End Source File # Begin Source File SOURCE=md5.h # End Source File # Begin Source File SOURCE=misc.h # End Source File # Begin Source File SOURCE=multibyte.h # End Source File # Begin Source File SOURCE=pgapifunc.h # End Source File # Begin Source File SOURCE=pgtypes.h # End Source File # Begin Source File SOURCE=psqlodbc.h # End Source File # Begin Source File SOURCE=qresult.h # End Source File # Begin Source File SOURCE=socket.h # End Source File # Begin Source File SOURCE=statement.h # End Source File # Begin Source File SOURCE=tuple.h # End Source File # Begin Source File SOURCE=tuplelist.h # End Source File # Begin Source File SOURCE=win_setup.h # End Source File # End Group # Begin Group "resource" # PROP Default_Filter "" # Begin Source File SOURCE=.\psqlodbc.def # End Source File # Begin Source File SOURCE=.\psqlodbc.rc # End Source File # Begin Source File SOURCE=resource.h # End Source File # End Group # End Target # End Project psqlodbc-09.03.0300/psqlodbc.vcproj000644 001752 000000 00000061326 12335653444 017244 0ustar00saitowheel000000 000000 psqlodbc-09.03.0300/psqlodbc.sln000644 001752 000000 00000001560 12335653444 016527 0ustar00saitowheel000000 000000  Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "psqlODBC", "psqlodbc.vcproj", "{C45ECB41-8473-4F11-8186-E5574CFBADCF}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C45ECB41-8473-4F11-8186-E5574CFBADCF}.Debug|Win32.ActiveCfg = Debug|Win32 {C45ECB41-8473-4F11-8186-E5574CFBADCF}.Debug|Win32.Build.0 = Debug|Win32 {C45ECB41-8473-4F11-8186-E5574CFBADCF}.Release|Win32.ActiveCfg = Release|Win32 {C45ECB41-8473-4F11-8186-E5574CFBADCF}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal psqlodbc-09.03.0300/msdtc_enlist.cpp000644 001752 000000 00000070774 12335653444 017413 0ustar00saitowheel000000 000000 /* Module: msdtc_enlist.cpp * * Description: * This module contains routines related to * the enlistment in MSDTC. * *------- */ #ifdef _HANDLE_ENLIST_IN_DTC_ #undef _MEMORY_DEBUG_ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif /* _WIN32_WINNT */ #define WIN32_LEAN_AND_MEAN #include #include /*#include */ #define _PGDTC_FUNCS_IMPORT_ #include "connexp.h" /*#define _SLEEP_FOR_TEST_*/ #include #include #include #include #include #ifndef WIN32 #include #endif /* WIN32 */ #include #define _MYLOG_FUNCS_IMPORT_ #include "mylog.h" #include "pgenlist.h" #ifdef WIN32 #ifndef snprintf #define snprintf _snprintf #endif /* snprintf */ #endif /* WIN32 */ /* Define a type for defining a constant string expression */ #ifndef CSTR #define CSTR static const char * const #endif /* CSTR */ EXTERN_C { HINSTANCE s_hModule; /* Saved module handle. */ } /* This is where the Driver Manager attaches to this Driver */ BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: s_hModule = (HINSTANCE) hInst; /* Save for dialog boxes */ break; } return TRUE; } /* * A comment About locks used in this module * * the locks should be acquired with stronger to weaker order. * * 1:ELOCK -- the strongest per IAsyncPG object lock * When the *isolated* or *dtcconn* member of an IAsyncPG object * is changed, this lock should be held. * While an IAsyncPG object accesses a psqlodbc connection, * this lock should be held. * * 2:[CONN_CS] -- per psqlodbc connection lock * This lock would be held for a pretty long time while accessing * the psqlodbc connection assigned to an IAsyncPG object. You * can use the connecion safely by holding a ELOCK for the * IAsyncPG object because the assignment is ensured to be * fixed while the ELOCK is held. * * 3:LIFELOCK -- a global lock to ensure the lives of IAsyncPG objects * While this lock is held, IAsyncPG objects would never die. * * 4:SLOCK -- the short term per IAsyncPG object lock * When any member of an IAsyncPG object is changed, this lock * should be held. */ // #define _LOCK_DEBUG_ static class INIT_CRIT { public: CRITICAL_SECTION life_cs; /* for asdum member of ConnectionClass */ INIT_CRIT() { InitializeCriticalSection(&life_cs); } ~INIT_CRIT() { DeleteCriticalSection(&life_cs); } } init_crit; #ifdef _LOCK_DEBUG_ #define LIFELOCK_ACQUIRE (forcelog("LIFELOCK_ACQUIRE\n"), EnterCriticalSection(&init_crit.life_cs), forcelog("LIFELOCK ACQUIRED\n")) #define LIFELOCK_RELEASE (forcelog("LIFELOCK_RELEASE\n"), LeaveCriticalSection(&init_crit.life_cs)) #else #define LIFELOCK_ACQUIRE EnterCriticalSection(&init_crit.life_cs) #define LIFELOCK_RELEASE LeaveCriticalSection(&init_crit.life_cs) #endif /* * Some helper macros about connection handling. */ #define CONN_CS_ACQUIRE(conn) PgDtc_lock_cntrl((conn), TRUE, FALSE) #define TRY_CONN_CS_ACQUIRE(conn) PgDtc_lock_cntrl((conn), TRUE, TRUE) #define CONN_CS_RELEASE(conn) PgDtc_lock_cntrl((conn), FALSE, FALSE) #define CONN_IS_IN_TRANS(conn) PgDtc_get_property((conn), inTrans) static const char *XidToText(const XID &xid, char *rtext) { int glen = xid.gtrid_length, blen = xid.bqual_length; int i, j; for (i = 0, j = 0; i < glen; i++, j += 2) sprintf(rtext + j, "%02x", (unsigned char) xid.data[i]); strcat(rtext, "-"); j++; for (; i < glen + blen; i++, j += 2) sprintf(rtext + j, "%02x", (unsigned char) xid.data[i]); return rtext; } static LONG g_cComponents = 0; static LONG g_cServerLocks = 0; // // ˆÈ‰º‚ÌITransactionResourceAsyncƒIƒuƒWƒFƒNƒg‚Í”CˆÓ‚̃XƒŒƒbƒh‚©‚ç // Ž©—R‚ɃAƒNƒZƒX‰Â”\‚Ȃ悤‚ÉŽÀ‘•‚·‚éBŠeRequest‚ÌŒ‹‰Ê‚ð•Ô‚·‚½‚ß‚É // Žg—p‚·‚éITransactionEnlistmentAsyncƒCƒ“ƒ^[ƒtƒFƒCƒX‚à‚»‚̂悤‚É // ŽÀ‘•‚³‚ê‚Ä‚¢‚éi‚ÆŽv‚í‚ê‚éA‰º‹LŽQÆj‚̂ŌĂÑo‚µ‚ÉCOM‚̃Aƒp[ // ƒgƒƒ“ƒg‚ðˆÓޝ‚·‚é(CoMarshalInterThreadInterfaceInStream/CoGetIn // terfaceAndReleaseStream‚ðŽg—p‚·‚éj•K—v‚͂Ȃ¢B // ‚±‚ÌDLL“à‚ÅŽg—p‚·‚éITransactionResourceAsync‚ÆITransactionEnlist // mentAsync‚̃Cƒ“ƒ^[ƒtƒFƒCƒXƒ|ƒCƒ“ƒ^[‚Í”CˆÓ‚̃XƒŒƒbƒh‚©‚ç’¼ÚŽg—p // ‚·‚邱‚Æ‚ª‚Å‚«‚éB // // OLE Transactions Standard // // OLE Transactions is the Microsoft interface standard for transaction // management. Applications use OLE Transactions-compliant interfaces to // initiate, commit, abort, and inquire about transactions. Resource // managers use OLE Transactions-compliant interfaces to enlist in // transactions, to propagate transactions to other resource managers, // to propagate transactions from process to process or from system to // system, and to participate in the two-phase commit protocol. // // The Microsoft DTC system implements most OLE Transactions-compliant // objects, interfaces, and methods. Resource managers that wish to use // OLE Transactions must implement some OLE Transactions-compliant objects, // interfaces, and methods. // // The OLE Transactions specification is based on COM but it differs in the // following respects: // // OLE Transactions objects cannot be created using the COM CoCreate APIs. // References to OLE Transactions objects are always direct. Therefore, // no proxies or stubs are created for inter-apartment, inter-process, // or inter-node calls and OLE Transactions references cannot be marshaled // using standard COM marshaling. // All references to OLE Transactions objects and their sinks are completely // free threaded and cannot rely upon COM concurrency control models. // For example, you cannot pass a reference to an IResourceManagerSink // interface on a single-threaded apartment and expect the callback to occur // only on the same single-threaded apartment. class IAsyncPG : public ITransactionResourceAsync { private: IDtcToXaHelperSinglePipe *helper; DWORD RMCookie; void *dtcconn; LONG refcnt; CRITICAL_SECTION as_spin; // to make this object Both CRITICAL_SECTION as_exec; // to make this object Both XID xid; bool isolated; bool prepared; bool done; bool abort; HANDLE eThread[3]; bool eFin[3]; bool requestAccepted; HRESULT prepare_result; HRESULT commit_result; #ifdef _LOCK_DEBUG_ int spin_cnt; int cs_cnt; #endif /* _LOCK_DEBUG_ */ public: enum { PrepareExec = 0 ,CommitExec ,AbortExec }; ITransactionEnlistmentAsync *enlist; HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void ** ppvObject); ULONG STDMETHODCALLTYPE AddRef(void); ULONG STDMETHODCALLTYPE Release(void); HRESULT STDMETHODCALLTYPE PrepareRequest(BOOL fRetaining, DWORD grfRM, BOOL fWantMoniker, BOOL fSinglePhase); HRESULT STDMETHODCALLTYPE CommitRequest(DWORD grfRM, XACTUOW * pNewUOW); HRESULT STDMETHODCALLTYPE AbortRequest(BOID * pboidReason, BOOL fRetaining, XACTUOW * pNewUOW); HRESULT STDMETHODCALLTYPE TMDown(void); IAsyncPG(); void SetHelper(IDtcToXaHelperSinglePipe *pHelper, DWORD dwRMCookie) {helper = pHelper; RMCookie = dwRMCookie;} HRESULT RequestExec(DWORD type, HRESULT res); HRESULT ReleaseConnection(void); void SetConnection(void *sconn) {SLOCK_ACQUIRE(); dtcconn = sconn; SLOCK_RELEASE();} void SetXid(const XID *ixid) {SLOCK_ACQUIRE(); xid = *ixid; SLOCK_RELEASE();} void *separateXAConn(bool spinAcquired, bool continueConnection); bool CloseThread(DWORD type); private: ~IAsyncPG(); #ifdef _LOCK_DEBUG_ void SLOCK_ACQUIRE() {forcelog("SLOCK_ACQUIRE %d\n", spin_cnt); EnterCriticalSection(&as_spin); spin_cnt++;} void SLOCK_RELEASE() {forcelog("SLOCK_RELEASE=%d\n", spin_cnt); LeaveCriticalSection(&as_spin); spin_cnt--;} void ELOCK_ACQUIRE() {forcelog("%p->ELOCK_ACQUIRE\n", this); EnterCriticalSection(&as_exec); forcelog("ELOCK ACQUIRED\n");} void ELOCK_RELEASE() {forcelog("ELOCK_RELEASE\n"); LeaveCriticalSection(&as_exec);} #else void SLOCK_ACQUIRE() {EnterCriticalSection(&as_spin);} void SLOCK_RELEASE() {LeaveCriticalSection(&as_spin);} void ELOCK_ACQUIRE() {EnterCriticalSection(&as_exec);} void ELOCK_RELEASE() {LeaveCriticalSection(&as_exec);} #endif /* _LOCK_DEBUG_ */ void *getLockedXAConn(void); void *generateXAConn(bool spinAcquired); void *isolateXAConn(bool spinAcquired, bool continueConnection); void SetPrepareResult(HRESULT res) {SLOCK_ACQUIRE(); prepared = true; prepare_result = res; SLOCK_RELEASE();} void SetDone(HRESULT); void Wait_pThread(bool slock_hold); void Wait_cThread(bool slock_hold, bool once); }; IAsyncPG::IAsyncPG(void) : helper(NULL), RMCookie(0), enlist(NULL), dtcconn(NULL), refcnt(1), isolated(false), done(false), abort(false), prepared(false), requestAccepted(false) { InterlockedIncrement(&g_cComponents); InitializeCriticalSection(&as_spin); InitializeCriticalSection(&as_exec); eThread[0] = eThread[1] = eThread[2] = NULL; eFin[0] = eFin[1] = eFin[2] = false; memset(&xid, 0, sizeof(xid)); #ifdef _LOCK_DEBUG_ spin_cnt = 0; cs_cnt = 0; #endif /* _LOCK_DEBUG_ */ } // // invoked from *delete*. // When entered ELOCK -> LIFELOCK -> SLOCK are held // and they are released. // IAsyncPG::~IAsyncPG(void) { void *fconn = NULL; if (dtcconn) { if (isolated) fconn = dtcconn; PgDtc_set_async(dtcconn, NULL); dtcconn = NULL; } SLOCK_RELEASE(); LIFELOCK_RELEASE; if (fconn) { mylog("IAsyncPG Destructor is freeing the connection\n"); PgDtc_free_connect(fconn); } DeleteCriticalSection(&as_spin); ELOCK_RELEASE(); DeleteCriticalSection(&as_exec); InterlockedDecrement(&g_cComponents); } HRESULT STDMETHODCALLTYPE IAsyncPG::QueryInterface(REFIID riid, void ** ppvObject) { forcelog("%p QueryInterface called\n", this); if (riid == IID_IUnknown || riid == IID_ITransactionResourceAsync) { *ppvObject = this; AddRef(); return S_OK; } *ppvObject = NULL; return E_NOINTERFACE; } // // acquire/releases SLOCK. // ULONG STDMETHODCALLTYPE IAsyncPG::AddRef(void) { mylog("%p->AddRef called\n", this); SLOCK_ACQUIRE(); refcnt++; SLOCK_RELEASE(); return refcnt; } // // acquire/releases [ELOCK -> LIFELOCK -> ] SLOCK. // ULONG STDMETHODCALLTYPE IAsyncPG::Release(void) { mylog("%p->Release called refcnt=%d\n", this, refcnt); SLOCK_ACQUIRE(); refcnt--; if (refcnt <= 0) { SLOCK_RELEASE(); ELOCK_ACQUIRE(); LIFELOCK_ACQUIRE; SLOCK_ACQUIRE(); if (refcnt <=0) { mylog("delete %p\n", this); delete this; } else { SLOCK_RELEASE(); LIFELOCK_RELEASE; ELOCK_RELEASE(); } } else SLOCK_RELEASE(); return refcnt; } // // Acquire/release SLOCK. // void IAsyncPG::Wait_pThread(bool slock_hold) { mylog("Wait_pThread %d in\n", slock_hold); HANDLE wThread; int wait_idx = PrepareExec; DWORD ret; if (!slock_hold) SLOCK_ACQUIRE(); while (NULL != (wThread = eThread[wait_idx]) && !eFin[wait_idx]) { SLOCK_RELEASE(); ret = WaitForSingleObject(wThread, 2000); SLOCK_ACQUIRE(); if (WAIT_TIMEOUT != ret) eFin[wait_idx] = true; } if (!slock_hold) SLOCK_RELEASE(); mylog("Wait_pThread out\n"); } // // Acquire/releases SLOCK. // void IAsyncPG::Wait_cThread(bool slock_hold, bool once) { HANDLE wThread; int wait_idx; DWORD ret; mylog("Wait_cThread %d,%d in\n", slock_hold, once); if (!slock_hold) SLOCK_ACQUIRE(); if (NULL != eThread[CommitExec]) wait_idx = CommitExec; else wait_idx = AbortExec; while (NULL != (wThread = eThread[wait_idx]) && !eFin[wait_idx]) { SLOCK_RELEASE(); ret = WaitForSingleObject(wThread, 2000); SLOCK_ACQUIRE(); if (WAIT_TIMEOUT != ret) eFin[wait_idx] = true; else if (once) break; } if (!slock_hold) SLOCK_RELEASE(); mylog("Wait_cThread out\n"); } /* Processing Prepare/Commit Request */ typedef struct RequestPara { DWORD type; LPVOID lpr; HRESULT res; } RequestPara; // // Acquire/releases LIFELOCK -> SLOCK. // may acquire/release ELOCK. // void IAsyncPG::SetDone(HRESULT res) { LIFELOCK_ACQUIRE; SLOCK_ACQUIRE(); done = true; if (E_FAIL == res || E_UNEXPECTED == res) abort = true; requestAccepted = true; commit_result = res; if (dtcconn) { PgDtc_set_async(dtcconn, NULL); if (isolated) { SLOCK_RELEASE(); LIFELOCK_RELEASE; ELOCK_ACQUIRE(); if (dtcconn) { mylog("Freeing isolated connection=%p\n", dtcconn); PgDtc_free_connect(dtcconn); SetConnection(NULL); } ELOCK_RELEASE(); } else { dtcconn = NULL; SLOCK_RELEASE(); LIFELOCK_RELEASE; } } else { SLOCK_RELEASE(); LIFELOCK_RELEASE; } } // // Acquire/releases [ELOCK -> LIFELOCK -> ] SLOCK. // void *IAsyncPG::generateXAConn(bool spinAcquired) { mylog("generateXAConn isolated=%d dtcconn=%p\n", isolated, dtcconn); if (!spinAcquired) SLOCK_ACQUIRE(); if (isolated || done) { SLOCK_RELEASE(); return dtcconn; } SLOCK_RELEASE(); ELOCK_ACQUIRE(); LIFELOCK_ACQUIRE; SLOCK_ACQUIRE(); if (dtcconn && !isolated && !done && prepared) { void *sconn = dtcconn; dtcconn = PgDtc_isolate(sconn, useAnotherRoom); isolated = true; SLOCK_RELEASE(); LIFELOCK_RELEASE; // PgDtc_connect(dtcconn); may be called in getLockedXAConn } else { SLOCK_RELEASE(); LIFELOCK_RELEASE; } ELOCK_RELEASE(); return dtcconn; } // // Acquire/releases [ELOCK -> LIFELOCK -> ] SLOCK. // void *IAsyncPG::isolateXAConn(bool spinAcquired, bool continueConnection) { void *sconn; mylog("isolateXAConn isolated=%d dtcconn=%p\n", isolated, dtcconn); if (!spinAcquired) SLOCK_ACQUIRE(); if (isolated || done || NULL == dtcconn) { SLOCK_RELEASE(); return dtcconn; } SLOCK_RELEASE(); ELOCK_ACQUIRE(); LIFELOCK_ACQUIRE; SLOCK_ACQUIRE(); if (isolated || done || NULL == dtcconn) { SLOCK_RELEASE(); LIFELOCK_RELEASE; ELOCK_RELEASE(); return dtcconn; } sconn = dtcconn; dtcconn = PgDtc_isolate(sconn, continueConnection ? 0 : disposingConnection); isolated = true; SLOCK_RELEASE(); LIFELOCK_RELEASE; if (continueConnection) { PgDtc_connect(sconn); } ELOCK_RELEASE(); return dtcconn; } // // Acquire/releases [ELOCK -> LIFELOCK -> ] SLOCK. // void *IAsyncPG::separateXAConn(bool spinAcquired, bool continueConnection) { mylog("%s isolated=%d dtcconn=%p\n", __FUNCTION__, isolated, dtcconn); if (!spinAcquired) SLOCK_ACQUIRE(); if (prepared) return generateXAConn(true); else return isolateXAConn(true, continueConnection); } // // [when entered] // ELOCK is held. // // Acquire/releases SLOCK. // Try to acquire CONN_CS also. // // [on exit] // ELOCK is kept held. // If the return connection != NULL // the CONN_CS lock for the connection is held. // void *IAsyncPG::getLockedXAConn() { SLOCK_ACQUIRE(); while (!done && !isolated && NULL != dtcconn) { /* * Note that COMMIT/ROLLBACK PREPARED command should be * issued outside the transaction. */ if (!prepared || !CONN_IS_IN_TRANS(dtcconn)) { if (TRY_CONN_CS_ACQUIRE(dtcconn)) { if (prepared && CONN_IS_IN_TRANS(dtcconn)) { CONN_CS_RELEASE(dtcconn); } else break; } } separateXAConn(true, true); SLOCK_ACQUIRE(); // SLOCK was released by separateXAConn() } SLOCK_RELEASE(); if (isolated && NULL != dtcconn) { CONN_CS_ACQUIRE(dtcconn); if (!PgDtc_get_property(dtcconn, connected)) PgDtc_connect(dtcconn); } return dtcconn; } // // Acquire/release ELOCK -> SLOCK. // HRESULT IAsyncPG::RequestExec(DWORD type, HRESULT res) { HRESULT ret; bool bReleaseEnlist = false; void *econn; char pgxid[258]; mylog("%p->RequestExec type=%d conn=%p\n", this, type, dtcconn); XidToText(xid, pgxid); #ifdef _SLEEP_FOR_TEST_ /*Sleep(2000);*/ #endif /* _SLEEP_FOR_TEST_ */ ELOCK_ACQUIRE(); switch (type) { case PrepareExec: if (done || NULL == dtcconn) { res = E_UNEXPECTED; break; } if (econn = getLockedXAConn(), NULL != econn) { PgDtc_set_property(econn, inprogress, (void *) 1); if (E_FAIL == res) PgDtc_one_phase_operation(econn, ABORT_GLOBAL_TRANSACTION); else if (XACT_S_SINGLEPHASE == res) { if (!PgDtc_one_phase_operation(econn, ONE_PHASE_COMMIT)) res = E_FAIL; } else { if (!PgDtc_two_phase_operation(econn, PREPARE_TRANSACTION, pgxid)) res = E_FAIL; } PgDtc_set_property(econn, inprogress, (void *) 0); CONN_CS_RELEASE(econn); } if (S_OK != res) { SetDone(res); bReleaseEnlist = true; } PgDtc_set_property(dtcconn, prepareRequested, (void *) 0); ret = enlist->PrepareRequestDone(res, NULL, NULL); SetPrepareResult(res); break; case CommitExec: Wait_pThread(false); if (E_FAIL != res) { econn = getLockedXAConn(); if (econn) { PgDtc_set_property(econn, inprogress, (void *) 1); if (!PgDtc_two_phase_operation(econn, COMMIT_PREPARED, pgxid)) res = E_FAIL; PgDtc_set_property(econn, inprogress, (void *) 0); CONN_CS_RELEASE(econn); } } SetDone(res); ret = enlist->CommitRequestDone(res); bReleaseEnlist = true; break; case AbortExec: Wait_pThread(false); if (prepared && !done) { econn = getLockedXAConn(); if (econn) { PgDtc_set_property(econn, inprogress, (void *) 1); if (!PgDtc_two_phase_operation(econn, ROLLBACK_PREPARED, pgxid)) res = E_FAIL; PgDtc_set_property(econn, inprogress, (void *) 0); CONN_CS_RELEASE(econn); } } SetDone(res); ret = enlist->AbortRequestDone(res); bReleaseEnlist = true; break; default: ret = -1; } if (bReleaseEnlist) { helper->ReleaseRMCookie(RMCookie, TRUE); enlist->Release(); } ELOCK_RELEASE(); mylog("%p->Done ret=%d\n", this, ret); return ret; } // // Acquire/releses SLOCK // or [ELOCK -> LIFELOCK -> ] SLOCK. // HRESULT IAsyncPG::ReleaseConnection(void) { mylog("%p->ReleaseConnection\n", this); SLOCK_ACQUIRE(); if (isolated || NULL == dtcconn) { SLOCK_RELEASE(); return SQL_SUCCESS; } Wait_pThread(true); if (NULL != eThread[CommitExec] || NULL != eThread[AbortExec] || requestAccepted) { if (!done) Wait_cThread(true, true); } if (!isolated && !done && dtcconn && PgDtc_get_property(dtcconn, connected)) { isolateXAConn(true, false); } else SLOCK_RELEASE(); mylog("%p->ReleaseConnection exit\n", this); return SQL_SUCCESS; } EXTERN_C static unsigned WINAPI DtcRequestExec(LPVOID para); EXTERN_C static void __cdecl ClosePrepareThread(LPVOID para); EXTERN_C static void __cdecl CloseCommitThread(LPVOID para); EXTERN_C static void __cdecl CloseAbortThread(LPVOID para); // // Acquire/release [ELOCK -> ] SLOCK. // HRESULT STDMETHODCALLTYPE IAsyncPG::PrepareRequest(BOOL fRetaining, DWORD grfRM, BOOL fWantMoniker, BOOL fSinglePhase) { HRESULT ret, res; RequestPara *reqp; const DWORD reqtype = PrepareExec; mylog("%p PrepareRequest called grhRM=%d enl=%p\n", this, grfRM, enlist); SLOCK_ACQUIRE(); if (dtcconn && 0 != PgDtc_get_property(dtcconn, errorNumber)) res = ret = E_FAIL; else { ret = S_OK; if (fSinglePhase) { res = XACT_S_SINGLEPHASE; mylog("XACT is singlePhase\n"); } else res = S_OK; } SLOCK_RELEASE(); ELOCK_ACQUIRE(); #ifdef _SLEEP_FOR_TEST_ Sleep(2000); #endif /* _SLEEP_FOR_TEST_ */ reqp = new RequestPara; reqp->type = reqtype; reqp->lpr = (LPVOID) this; reqp->res = res; #define DONT_CALL_RETURN_FROM_HERE ??? AddRef(); HANDLE hThread = (HANDLE) _beginthreadex(NULL, 0, DtcRequestExec, reqp, 0, NULL); if (NULL == hThread) { delete(reqp); ret = E_FAIL; } else { SLOCK_ACQUIRE(); eThread[reqtype] = hThread; SLOCK_RELEASE(); /* * We call here _beginthread not _beginthreadex * so as not to call CloseHandle() to clean up * the thread. */ _beginthread(ClosePrepareThread, 0, (void *) this); } ELOCK_RELEASE(); Release(); #undef return return ret; } // // Acquire/release [ELOCK -> ] SLOCK. // HRESULT STDMETHODCALLTYPE IAsyncPG::CommitRequest(DWORD grfRM, XACTUOW * pNewUOW) { HRESULT res = S_OK, ret = S_OK; RequestPara *reqp; const DWORD reqtype = CommitExec; mylog("%p CommitRequest called grfRM=%d enl=%p\n", this, grfRM, enlist); SLOCK_ACQUIRE(); if (!prepared || done) ret = E_UNEXPECTED; else if (S_OK != prepare_result) ret = E_UNEXPECTED; SLOCK_RELEASE(); if (S_OK != ret) return ret; #define DONT_CALL_RETURN_FROM_HERE ??? AddRef(); ELOCK_ACQUIRE(); #ifdef _SLEEP_FOR_TEST_ Sleep(1000); #endif /* _SLEEP_FOR_TEST_ */ reqp = new RequestPara; reqp->type = reqtype; reqp->lpr = (LPVOID) this; reqp->res = res; enlist->AddRef(); HANDLE hThread = (HANDLE) _beginthreadex(NULL, 0, DtcRequestExec, reqp, 0, NULL); if (NULL == hThread) { delete(reqp); enlist->Release(); ret = E_FAIL; } else { SLOCK_ACQUIRE(); eThread[reqtype] = hThread; SLOCK_RELEASE(); /* * We call here _beginthread not _beginthreadex * so as not to call CloseHandle() to clean up * the thread. */ _beginthread(CloseCommitThread, 0, (void *) this); } mylog("CommitRequest ret=%d\n", ret); requestAccepted = true; ELOCK_RELEASE(); Release(); #undef return return ret; } // // Acquire/release [ELOCK -> ] SLOCK. // HRESULT STDMETHODCALLTYPE IAsyncPG::AbortRequest(BOID * pboidReason, BOOL fRetaining, XACTUOW * pNewUOW) { HRESULT res = S_OK, ret = S_OK; RequestPara *reqp; const DWORD reqtype = AbortExec; mylog("%p AbortRequest called\n", this); SLOCK_ACQUIRE(); if (done) ret = E_UNEXPECTED; else if (prepared && S_OK != prepare_result) ret = E_UNEXPECTED; SLOCK_RELEASE(); if (S_OK != ret) return ret; #define return DONT_CALL_RETURN_FROM_HERE ??? AddRef(); ELOCK_ACQUIRE(); if (!prepared && dtcconn) { PgDtc_set_property(dtcconn, inprogress, (void *) 1); PgDtc_one_phase_operation(dtcconn, ONE_PHASE_ROLLBACK); PgDtc_set_property(dtcconn, inprogress, (void *) 0); } reqp = new RequestPara; reqp->type = reqtype; reqp->lpr = (LPVOID) this; reqp->res = res; enlist->AddRef(); HANDLE hThread = (HANDLE) _beginthreadex(NULL, 0, DtcRequestExec, reqp, 0, NULL); if (NULL == hThread) { delete(reqp); enlist->Release(); ret = E_FAIL; } else { SLOCK_ACQUIRE(); eThread[reqtype] = hThread; SLOCK_RELEASE(); /* * We call here _beginthread not _beginthreadex * so as not to call CloseHandle() to clean up * the thread. */ _beginthread(CloseAbortThread, 0, (void *) this); } mylog("AbortRequest ret=%d\n", ret); requestAccepted = true; ELOCK_RELEASE(); Release(); #undef return return ret; } HRESULT STDMETHODCALLTYPE IAsyncPG::TMDown(void) { forcelog("%p TMDown called\n", this); return S_OK; } bool IAsyncPG::CloseThread(DWORD type) { CSTR func = "CloseThread"; HANDLE th; DWORD ret, excode = S_OK; bool rls_async = false; mylog("%s for %p thread=%d\n", func, this, eThread[type]); if (th = eThread[type], NULL == th || eFin[type]) return false; ret = WaitForSingleObject(th, INFINITE); if (WAIT_OBJECT_0 == ret) { switch (type) { case IAsyncPG::AbortExec: case IAsyncPG::CommitExec: rls_async = true; break; default: GetExitCodeThread(th, &excode); if (S_OK != excode) rls_async = true; } SLOCK_ACQUIRE(); eThread[type] = NULL; eFin[type] = true; SLOCK_RELEASE(); CloseHandle(th); } mylog("%s ret=%d\n", func, ret); return rls_async; } EXTERN_C static void __cdecl ClosePrepareThread(LPVOID para) { CSTR func = "ClosePrepareThread"; IAsyncPG *async = (IAsyncPG *) para; bool release; mylog("%s for %p", func, async); if (release = async->CloseThread(IAsyncPG::PrepareExec), release) async->Release(); mylog("%s release=%d\n", func, release); } EXTERN_C static void __cdecl CloseCommitThread(LPVOID para) { CSTR func = "CloseCommitThread"; IAsyncPG *async = (IAsyncPG *) para; bool release; mylog("%s for %p", func, async); if (release = async->CloseThread(IAsyncPG::CommitExec), release) async->Release(); mylog("%s release=%d\n", func, release); } EXTERN_C static void __cdecl CloseAbortThread(LPVOID para) { CSTR func = "CloseAbortThread"; IAsyncPG *async = (IAsyncPG *) para; bool release; mylog("%s for %p", func, async); if (release = async->CloseThread(IAsyncPG::AbortExec), release) async->Release(); mylog("%s release=%d\n", func, release); } EXTERN_C static unsigned WINAPI DtcRequestExec(LPVOID para) { RequestPara *reqp = (RequestPara *) para; DWORD type = reqp->type; IAsyncPG *async = (IAsyncPG *) reqp->lpr; HRESULT res = reqp->res, ret; mylog("DtcRequestExec type=%d", reqp->type); delete(reqp); ret = async->RequestExec(type, res); mylog(" Done ret=%d\n", ret); return ret; } CSTR regKey = "SOFTWARE\\Microsoft\\MSDTC\\XADLL"; RETCODE static EnlistInDtc_1pipe(void *conn, ITransaction *pTra, ITransactionDispenser *pDtc) { CSTR func = "EnlistInDtc_1pipe"; static IDtcToXaHelperSinglePipe *pHelper = NULL; ITransactionResourceAsync *pRes = NULL; IAsyncPG *asdum; HRESULT res; bool retry, errset; DWORD dwRMCookie; XID xid; if (!pHelper) { res = pDtc->QueryInterface(IID_IDtcToXaHelperSinglePipe, (void **) &pHelper); if (res != S_OK || !pHelper) { forcelog("DtcToXaHelperSingelPipe get error %d\n", res); pHelper = NULL; return SQL_ERROR; } } res = (NULL != (asdum = new IAsyncPG)) ? S_OK : E_FAIL; if (S_OK != res) { mylog("CoCreateInstance error %d\n", res); return SQL_ERROR; } /*mylog("dllname=%s dsn=%s\n", GetXaLibName(), conn->connInfo.dsn); res = 0;*/ retry = false; errset = false; char dtcname[1024]; PgDtc_create_connect_string(conn, dtcname, sizeof(dtcname)); do { res = pHelper->XARMCreate(dtcname, (char *) GetXaLibName(), &dwRMCookie); if (S_OK == res) break; mylog("XARMCreate error code=%x\n", res); if (XACT_E_XA_TX_DISABLED == res) { PgDtc_set_error(conn, "XARMcreate error:Please enable XA transaction in MSDTC security configuration", func); errset = true; } else if (!retry) { LONG ret; HKEY sKey; DWORD rSize; ret = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, regKey, 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &sKey); if (ERROR_SUCCESS != ret) ret = ::RegCreateKeyEx(HKEY_LOCAL_MACHINE, regKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &sKey, NULL); if (ERROR_SUCCESS == ret) { switch (ret = ::RegQueryValueEx(sKey, "XADLL", NULL, NULL, NULL, &rSize)) { case ERROR_SUCCESS: if (rSize > 0) break; default: ret = ::RegSetValueEx(sKey, GetXaLibName(), 0, REG_SZ, (CONST BYTE *) GetXaLibPath(), (DWORD) strlen(GetXaLibPath()) + 1); if (ERROR_SUCCESS == ret) { retry = true; continue; // retry } PgDtc_set_error(conn, "XARMCreate error:Please register HKLM\\SOFTWARE\\Microsoft\\MSDTC\\XADLL", func); break; } ::RegCloseKey(sKey); } } if (!errset) PgDtc_set_error(conn, "MSDTC XARMCreate error", func); return SQL_ERROR; } while (1); res = pHelper->ConvertTridToXID((DWORD *) pTra, dwRMCookie, &xid); if (res != S_OK) { mylog("ConvertTridToXid error %d\n", res); return SQL_ERROR; } { char pgxid[258]; XidToText(xid, pgxid); mylog("ConvertTridToXID -> %s\n", pgxid); } asdum->SetXid(&xid); /* Create an IAsyncPG instance by myself */ /* DLLGetClassObject(GUID_IAsyncPG, IID_ITransactionResourceAsync, (void **) &asdum); */ asdum->SetHelper(pHelper, dwRMCookie); res = pHelper->EnlistWithRM(dwRMCookie, pTra, asdum, &asdum->enlist); if (res != S_OK) { mylog("EnlistWithRM error %d\n", res); pHelper->ReleaseRMCookie(dwRMCookie, TRUE); return SQL_ERROR; } mylog("asdum=%p start transaction\n", asdum); asdum->SetConnection(conn); LIFELOCK_ACQUIRE; PgDtc_set_async(conn, asdum); LIFELOCK_RELEASE; return SQL_SUCCESS; } EXTERN_C RETCODE IsolateDtcConn(void *conn, BOOL continueConnection) { IAsyncPG *async; LIFELOCK_ACQUIRE; if (async = (IAsyncPG *) PgDtc_get_async(conn), NULL != async) { if (PgDtc_get_property(conn, idleInGlobalTransaction)) { async->AddRef(); LIFELOCK_RELEASE; async->separateXAConn(false, continueConnection ? true : false); async->Release(); } else LIFELOCK_RELEASE; } else LIFELOCK_RELEASE; return SQL_SUCCESS; } EXTERN_C RETCODE EnlistInDtc(void *conn, void *pTra, int method) { static ITransactionDispenser *pDtc = NULL; RETCODE ret; if (!pTra) { IAsyncPG *asdum = (IAsyncPG *) PgDtc_get_async(conn); PgDtc_set_property(conn, enlisted, (void *) 0); return SQL_SUCCESS; } if (CONN_IS_IN_TRANS(conn)) { PgDtc_one_phase_operation(conn, SHUTDOWN_LOCAL_TRANSACTION); } if (!pDtc) { HRESULT res; res = DtcGetTransactionManager(NULL, NULL, IID_ITransactionDispenser, 0, 0, NULL, (void **) &pDtc); if (res != S_OK || !pDtc) { forcelog("TransactionManager get error %d\n", res); pDtc = NULL; } } ret = EnlistInDtc_1pipe(conn, (ITransaction *) pTra, pDtc); if (SQL_SUCCEEDED(ret)) PgDtc_set_property(conn, enlisted, (void *) 1); return ret; } EXTERN_C RETCODE DtcOnDisconnect(void *conn) { mylog("DtcOnDisconnect\n"); LIFELOCK_ACQUIRE; IAsyncPG *asdum = (IAsyncPG *) PgDtc_get_async(conn); if (asdum) { asdum->AddRef(); LIFELOCK_RELEASE; asdum->ReleaseConnection(); asdum->Release(); } else LIFELOCK_RELEASE; return SQL_SUCCESS; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ psqlodbc-09.03.0300/pgxalib.cpp000644 001752 000000 00000033564 12335653444 016345 0ustar00saitowheel000000 000000 /*------ * Module: pgxalib.cpp * * Description: * This module implements XA like routines * invoked from MSDTC process. * * xa_open(), xa_close(), xa_commit(), * xa_rollback() and xa_recover() * are really invoked AFAIC. *------- */ #include /*#define _SLEEP_FOR_TEST_*/ #include #include #include #include #include #include #include #include #include #include EXTERN_C static void mylog(const char *fmt,...); using namespace std; class XAConnection { private: string connstr; HDBC xaconn; vector qvec; int pos; public: XAConnection(LPCTSTR str) : connstr(str), xaconn(NULL), pos(-1) {} ~XAConnection(); HDBC ActivateConnection(void); void SetPos(int spos) {pos = spos;} HDBC GetConnection(void) const {return xaconn;} vector &GetResultVec(void) {return qvec;} int GetPos(void) {return pos;} const string &GetConnstr(void) {return connstr;} }; static class INIT_CRIT { private: public: bool cs_init; CRITICAL_SECTION map_cs; CRITICAL_SECTION mylog_cs; map xatab; FILE *LOGFP; HENV env; INIT_CRIT() : LOGFP(NULL), env(NULL) { InitializeCriticalSection(&map_cs); InitializeCriticalSection(&mylog_cs); cs_init = true; } ~INIT_CRIT() { // mylog("Leaving INIT_CRIT\n"); if (cs_init) { xatab.clear(); FreeEnv(); if (LOGFP) fclose(LOGFP); DeleteCriticalSection(&mylog_cs); DeleteCriticalSection(&map_cs); } } void finalize() { if (cs_init) { xatab.clear(); FreeEnv(); if (LOGFP) fclose(LOGFP); LOGFP = NULL; DeleteCriticalSection(&mylog_cs); DeleteCriticalSection(&map_cs); cs_init = false; } } void FreeEnv() { if (env) { SQLFreeHandle(SQL_HANDLE_ENV, env); env = NULL; } } } init_crit; #define MLOCK_ACQUIRE EnterCriticalSection(&init_crit.map_cs) #define MLOCK_RELEASE LeaveCriticalSection(&init_crit.map_cs) static int dtclog = 0; XAConnection::~XAConnection() { qvec.clear(); if (xaconn) SQLFreeHandle(SQL_HANDLE_DBC, xaconn); } HDBC XAConnection::ActivateConnection(void) { RETCODE ret; MLOCK_ACQUIRE; if (!init_crit.env) { ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &init_crit.env); if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret) return NULL; } MLOCK_RELEASE; if (!xaconn) { ret = SQLSetEnvAttr(init_crit.env, SQL_ATTR_ODBC_VERSION, (PTR) SQL_OV_ODBC3, 0); ret = SQLAllocHandle(SQL_HANDLE_DBC, init_crit.env, &xaconn); if (SQL_SUCCESS == ret || SQL_SUCCESS_WITH_INFO == ret) { string cstr = connstr; if (dtclog) { cstr += ";B2="; cstr += dtclog; } ret = SQLDriverConnect(xaconn, NULL, (SQLCHAR *) cstr.c_str(), SQL_NTS, NULL, SQL_NULL_DATA, NULL, SQL_DRIVER_COMPLETE); if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret) { mylog("SQLDriverConnect return=%d\n", ret); SQLFreeHandle(SQL_HANDLE_DBC, xaconn); xaconn = NULL; } } } return xaconn; } #define _BUILD_DLL_ #ifdef _BUILD_DLL_ EXTERN_C { #define DIRSEPARATOR "\\" #define PG_BINARY_A "ab" #define MYLOGDIR "c:" #define MYLOGFILE "mylog_" static void generate_filename(const char *dirname, const char *prefix, char *filename) { int pid = 0; pid = _getpid(); if (dirname == 0 || filename == 0) return; strcpy(filename, dirname); strcat(filename, DIRSEPARATOR); if (prefix != 0) strcat(filename, prefix); sprintf(filename, "%s%u%s", filename, pid, ".log"); return; } static void FreeEnv() { init_crit.FreeEnv(); } #define DTCLOGDIR "c:\\pgdtclog" #include static const char * const DBMSNAME = "PostgreSQL"; static const char * const KEY_NAME = "MsdtcLog"; static const char * const ODBCINST_INI = "ODBCINST.INI"; INT_PTR FAR WINAPI GetMsdtclog() { char temp[16]; SQLGetPrivateProfileString(DBMSNAME, KEY_NAME, "", temp, sizeof(temp), ODBCINST_INI); dtclog = atoi(temp); return dtclog; } INT_PTR FAR WINAPI SetMsdtclog(int dtclog) { char temp[16]; sprintf(temp, "%d", dtclog); SQLWritePrivateProfileString(DBMSNAME, KEY_NAME, temp, ODBCINST_INI); return dtclog; } static BOOL output_mylog() { return (0 != dtclog); } static void mylog(const char *fmt,...) { va_list args; char filebuf[80]; static BOOL init = TRUE; FILE *logfp = init_crit.LOGFP; if (!output_mylog()) return; EnterCriticalSection(&init_crit.mylog_cs); va_start(args, fmt); if (init) { if (!logfp) { generate_filename(MYLOGDIR, MYLOGFILE, filebuf); logfp = fopen(filebuf, PG_BINARY_A); } if (!logfp) { generate_filename(DTCLOGDIR, MYLOGFILE, filebuf); logfp = fopen(filebuf, PG_BINARY_A); #ifdef WIN32 if (NULL == logfp) { if (0 == _mkdir(DTCLOGDIR)) logfp = fopen(filebuf, PG_BINARY_A); } #endif /* WIN32 */ } if (logfp) { setbuf(logfp, NULL); init_crit.LOGFP = logfp; } } init = FALSE; if (logfp) { time_t ntime; char ctim[128]; time(&ntime); strcpy(ctim, ctime(&ntime)); ctim[strlen(ctim) - 1] = '\0'; fprintf(logfp, "[%d.%d(%s)]", GetCurrentProcessId(), GetCurrentThreadId(), ctim); vfprintf(logfp, fmt, args); } va_end(args); LeaveCriticalSection(&init_crit.mylog_cs); } static int initialize_globals(void) { static int init = 1; if (!init) init = 0; return 0; } static void XatabClear(void); static void finalize_globals(void) { /* my(q)log is unavailable from here */ mylog("DETACHING PROCESS\n"); init_crit.finalize(); } HINSTANCE s_hModule; /* Saved module handle. */ /* This is where the Driver Manager attaches to this Driver */ BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { WORD wVersionRequested; WSADATA wsaData; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: s_hModule = (HINSTANCE) hInst; /* Save for dialog boxes */ /* Load the WinSock Library */ wVersionRequested = MAKEWORD(1, 1); if (WSAStartup(wVersionRequested, &wsaData)) return FALSE; /* Verify that this is the minimum version of WinSock */ if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1) { WSACleanup(); return FALSE; } initialize_globals(); break; case DLL_THREAD_ATTACH: break; case DLL_PROCESS_DETACH: finalize_globals(); WSACleanup(); return TRUE; case DLL_THREAD_DETACH: break; default: break; } return TRUE; } } /* end of EXTERN_C */ #endif /* _BUILD_DLL_ */ static void XatabClear(void) { init_crit.xatab.clear(); } static const char *XidToText(const XID &xid, char *rtext) { int glen = xid.gtrid_length, blen = xid.bqual_length; int i, j; for (i = 0, j = 0; i < glen; i++, j += 2) sprintf(rtext + j, "%02x", (unsigned char) xid.data[i]); strcat(rtext, "-"); j++; for (; i < glen + blen; i++, j += 2) sprintf(rtext + j, "%02x", (unsigned char) xid.data[i]); return rtext; } static int pg_hex2bin(const UCHAR *src, UCHAR *dst, int length) { UCHAR chr; const UCHAR *src_wk; UCHAR *dst_wk; int i, val; BOOL HByte = TRUE; for (i = 0, src_wk = src, dst_wk = dst; i < length; i++, src_wk++) { chr = *src_wk; if (!chr) break; if (chr >= 'a' && chr <= 'f') val = chr - 'a' + 10; else if (chr >= 'A' && chr <= 'F') val = chr - 'A' + 10; else val = chr - '0'; if (HByte) *dst_wk = (val << 4); else { *dst_wk += val; dst_wk++; } HByte = !HByte; } return length; } static int TextToXid(XID &xid, const char *rtext) { int slen, glen, blen; char *sptr; slen = (int) strlen(rtext); sptr = (char *)strchr(rtext, '-'); if (sptr) { glen = (int) (sptr - rtext); blen = slen - glen - 1; } else { glen = slen; blen = 0; } xid.gtrid_length = glen / 2; xid.bqual_length = blen / 2; pg_hex2bin((const UCHAR *) rtext, (UCHAR *) &xid.data[0], glen); pg_hex2bin((const UCHAR *) sptr + 1, (UCHAR *) &xid.data[glen / 2], blen); return (glen + blen) / 2; } EXTERN_C static int __cdecl xa_open(char *xa_info, int rmid, long flags) { mylog("xa_open %s rmid=%d flags=%ld\n", xa_info, rmid, flags); GetMsdtclog(); MLOCK_ACQUIRE; init_crit.xatab.insert(pair(rmid, XAConnection(xa_info))); MLOCK_RELEASE; return S_OK; } EXTERN_C static int __cdecl xa_close(char *xa_info, int rmid, long flags) { mylog("xa_close rmid=%d flags=%ld\n", rmid, flags); MLOCK_ACQUIRE; init_crit.xatab.erase(rmid); if (init_crit.xatab.size() == 0) FreeEnv(); GetMsdtclog(); MLOCK_RELEASE; return XA_OK; } // // Dummy implementation (not called from MSDTC). // EXTERN_C static int __cdecl xa_start(XID *xid, int rmid, long flags) { char pgxid[258]; XidToText(*xid, pgxid); mylog("xa_start %s rmid=%d flags=%ld\n", pgxid, rmid, flags); init_crit.xatab.find(rmid)->second.ActivateConnection(); return XA_OK; } // // Dummy implementation (not called from MSDTC). // EXTERN_C static int __cdecl xa_end(XID *xid, int rmid, long flags) { char pgxid[258]; XidToText(*xid, pgxid); mylog("xa_end %s rmid=%d flags=%ld\n", pgxid, rmid, flags); return XA_OK; } EXTERN_C static int __cdecl xa_rollback(XID *xid, int rmid, long flags) { int rmcode = XAER_RMERR; char pgxid[258]; XidToText(*xid, pgxid); mylog("xa_rollback %s rmid=%d flags=%ld\n", pgxid, rmid, flags); map::iterator p; p = init_crit.xatab.find(rmid); if (p != init_crit.xatab.end()) { HDBC conn = p->second.ActivateConnection(); if (conn) { SQLCHAR cmdmsg[512], sqlstate[8]; HSTMT stmt; RETCODE ret; ret = SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt); if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret) { mylog("Statement allocation error\n"); return rmcode; } _snprintf((char *) cmdmsg, sizeof(cmdmsg), "ROLLBACK PREPARED '%s'", pgxid); ret = SQLExecDirect(stmt, (SQLCHAR *) cmdmsg, SQL_NTS); switch (ret) { case SQL_SUCCESS: case SQL_SUCCESS_WITH_INFO: rmcode = XA_OK; break; case SQL_ERROR: SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, sqlstate, NULL, cmdmsg, sizeof(cmdmsg), NULL); mylog("xa_commit error %s '%s'\n", sqlstate, cmdmsg); if (_stricmp((char *) sqlstate, "42704") == 0) rmcode = XA_HEURHAZ; break; } SQLFreeHandle(SQL_HANDLE_STMT, stmt); } } return rmcode; } // // Dummy implementation (not called from MSDTC). // Anyway it's almost impossible to implement this routine properly. // EXTERN_C static int __cdecl xa_prepare(XID *xid, int rmid, long flags) { char pgxid[258]; XidToText(*xid, pgxid); mylog("xa_prepare %s rmid=%d\n", pgxid, rmid); #ifdef _SLEEP_FOR_TEST_ Sleep(2000); #endif /* _SLEEP_FOR_TEST_ */ map::iterator p; p = init_crit.xatab.find(rmid); if (p != init_crit.xatab.end()) { HDBC conn = p->second.GetConnection(); if (conn) { } } return XAER_RMERR; } EXTERN_C static int __cdecl xa_commit(XID *xid, int rmid, long flags) { int rmcode = XAER_RMERR; char pgxid[258]; XidToText(*xid, pgxid); mylog("xa_commit %s rmid=%d flags=%ld\n", pgxid, rmid, flags); #ifdef _SLEEP_FOR_TEST_ Sleep(2000); #endif /* _SLEEP_FOR_TEST_ */ map::iterator p; p = init_crit.xatab.find(rmid); if (p != init_crit.xatab.end()) { HDBC conn = p->second.ActivateConnection(); if (conn) { SQLCHAR cmdmsg[512], sqlstate[8]; HSTMT stmt; RETCODE ret; SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt); _snprintf((char *) cmdmsg, sizeof(cmdmsg), "COMMIT PREPARED '%s'", pgxid); ret = SQLExecDirect(stmt, (SQLCHAR *) cmdmsg, SQL_NTS); switch (ret) { case SQL_SUCCESS: case SQL_SUCCESS_WITH_INFO: rmcode = XA_OK; break; case SQL_ERROR: SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, sqlstate, NULL, cmdmsg, sizeof(cmdmsg), NULL); if (_stricmp((char *) sqlstate, "42704") == 0) rmcode = XA_HEURHAZ; break; } SQLFreeHandle(SQL_HANDLE_STMT, stmt); } } return rmcode; } EXTERN_C static int __cdecl xa_recover(XID *xids, long count, int rmid, long flags) { int rmcode = XAER_RMERR, rcount; mylog("xa_recover rmid=%d count=%d flags=%ld\n", rmid, count, flags); map::iterator p; p = init_crit.xatab.find(rmid); if (p == init_crit.xatab.end()) return rmcode; HDBC conn = p->second.ActivateConnection(); if (!conn) return rmcode; vector &vec = p->second.GetResultVec(); int pos = p->second.GetPos(); if ((flags & TMSTARTRSCAN) != 0) { HSTMT stmt; RETCODE ret; char buf[512]; vec.clear(); SQLAllocHandle(SQL_HANDLE_STMT, conn, &stmt); ret = SQLExecDirect(stmt, (SQLCHAR *) "select gid from pg_prepared_xacts", SQL_NTS); if (SQL_SUCCESS != ret && SQL_SUCCESS_WITH_INFO != ret) { SQLFreeHandle(SQL_HANDLE_STMT, stmt); pos = -1; goto onExit; } SQLBindCol(stmt, 1, SQL_C_CHAR, buf, sizeof(buf), NULL); ret = SQLFetch(stmt); while (SQL_NO_DATA_FOUND != ret) { vec.push_back(buf); ret = SQLFetch(stmt); } SQLFreeHandle(SQL_HANDLE_STMT, stmt); pos = 0; } rcount = (int) vec.size(); rmcode = rcount - pos; if (rmcode > count) rmcode = count; for (int i = 0; i < rmcode; i++, pos++) TextToXid(xids[i], vec[pos].c_str()); if ((flags & TMENDRSCAN) != 0) { vec.clear(); pos = -1; } mylog("return count=%d\n", rmcode); onExit: p->second.SetPos(pos); return rmcode; } // // I'm not sure if this is invoked from MSDTC // Anyway there's nothing to do with it. // EXTERN_C static int __cdecl xa_forget(XID *xid, int rmid, long flags) { char pgxid[258]; XidToText(*xid, pgxid); mylog("xa_forget %s rmid=%d\n", pgxid, rmid); return XA_OK; } // // I'm not sure if this can be invoked from MSDTC. // EXTERN_C static int __cdecl xa_complete(int *handle, int *retval, int rmid, long flags) { mylog("xa_complete rmid=%d\n", rmid); return XA_OK; } EXTERN_C static xa_switch_t xapsw = { "psotgres_xa", TMNOMIGRATE, 0, xa_open, xa_close, xa_start, xa_end, xa_rollback, xa_prepare, xa_commit, xa_recover, xa_forget, xa_complete}; EXTERN_C HRESULT __cdecl GetXaSwitch (XA_SWITCH_FLAGS XaSwitchFlags, xa_switch_t ** ppXaSwitch) { mylog("GetXaSwitch called\n"); GetMsdtclog(); *ppXaSwitch = &xapsw; return S_OK; } psqlodbc-09.03.0300/xalibname.c000644 001752 000000 00000002257 12335653444 016312 0ustar00saitowheel000000 000000 /*------ * Module: xalibname.c * * Description: * This module gets the (path) name of xalib. * *------- */ #ifdef _HANDLE_ENLIST_IN_DTC_ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif /* _WIN32_WINNT */ #define WIN32_LEAN_AND_MEAN #include #include #include extern HMODULE s_hModule; static char xalibpath[_MAX_PATH] = ""; static char xalibname[_MAX_FNAME] = ""; const char *GetXaLibName(void) { char dllpath[_MAX_PATH], drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; if (!xalibpath[0]) { GetModuleFileName(s_hModule, dllpath, sizeof(dllpath)); /* In Windows XP SP2, the dllname should be specified */ /* instead of the dll path name, because it looks up */ /* the HKLM\Microfost\MSDTC\XADLL\(dllname) registry */ /* entry for security reason. */ _splitpath(dllpath, drive, dir, fname, ext); // _snprintf(xalibname, sizeof(xalibname), "%s%s", fname, ext); strcpy(xalibname, "pgxalib.dll"); _snprintf(xalibpath, sizeof(xalibpath), "%s%s%s", drive, dir, xalibname); } return xalibname; } const char *GetXaLibPath(void) { GetXaLibName(); return xalibpath; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ psqlodbc-09.03.0300/pgxalib.def000644 001752 000000 00000000133 12335653444 016303 0ustar00saitowheel000000 000000 LIBRARY pgxalib EXPORTS DllMain @201 GetXaSwitch @203 GetMsdtclog @204 SetMsdtclog @205 psqlodbc-09.03.0300/odbc.sql000644 001752 000000 00000014502 12335653444 015632 0ustar00saitowheel000000 000000 -- PostgreSQL catalog extensions for ODBC compatibility (odbc.sql) -- ODBC scalar functions are described here: -- Microsoft ODBC Programmer's Reference, Appendix E: Scalar Functions -- http://msdn.microsoft.com/library/ms711813.aspx -- Note: If we format this file consistently we can automatically -- generate a corresponding "drop script". Start "CREATE" in the first -- column, and keep everything up to and including the argument list on -- the same line. See also the makefile rule. -- String Functions -- ++++++++++++++++ -- -- Built-in: ASCII, BIT_LENGTH, CHAR_LENGTH, CHARACTER_LENGTH, LTRIM, -- OCTET_LENGTH, POSITION, REPEAT, RTRIM, SUBSTRING -- Missing: DIFFERENCE, REPLACE, SOUNDEX, LENGTH (ODBC sense) -- Keyword problems: CHAR -- CHAR(code) CREATE OR REPLACE FUNCTION "char"(integer) RETURNS text AS ' SELECT chr($1); ' LANGUAGE SQL; -- CONCAT(string1, string2) CREATE OR REPLACE FUNCTION concat(text, text) RETURNS text AS ' SELECT $1 || $2; ' LANGUAGE SQL; -- INSERT(string1, start, len, string2) CREATE OR REPLACE FUNCTION insert(text, integer, integer, text) RETURNS text AS ' SELECT substring($1 from 1 for $2 - 1) || $4 || substring($1 from $2 + $3); ' LANGUAGE SQL; -- LCASE(string) CREATE OR REPLACE FUNCTION lcase(text) RETURNS text AS ' SELECT lower($1); ' LANGUAGE SQL; -- LEFT(string, count) CREATE OR REPLACE FUNCTION left(text, integer) RETURNS text AS ' SELECT substring($1 for $2); ' LANGUAGE SQL; -- LOCATE(substring, string[, start]) CREATE OR REPLACE FUNCTION locate(text, text) RETURNS integer AS ' SELECT position($1 in $2); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION locate(text, text, integer) RETURNS integer AS ' SELECT position($1 in substring($2 from $3)) + $3 - 1; ' LANGUAGE SQL; -- RIGHT(string, count) CREATE OR REPLACE FUNCTION right(text, integer) RETURNS text AS ' SELECT substring($1 from char_length($1) - $2 + 1); ' LANGUAGE SQL; -- SPACE(count) CREATE OR REPLACE FUNCTION space(integer) RETURNS text AS ' SELECT repeat('' '', $1); ' LANGUAGE SQL; -- UCASE(string) CREATE OR REPLACE FUNCTION ucase(text) RETURNS text AS ' SELECT upper($1); ' LANGUAGE SQL; -- Numeric Functions -- +++++++++++++++++ -- -- Built-in: ABS, ACOS, ASIN, ATAN, ATAN2, COS, COT, DEGRESS, EXP, -- FLOOR, MOD, PI, RADIANS, ROUND, SIGN, SIN, SQRT, TAN -- Missing: LOG (ODBC sense) -- CEILING(num) CREATE OR REPLACE FUNCTION ceiling(numeric) RETURNS numeric AS ' SELECT ceil($1); ' LANGUAGE SQL; -- LOG10(num) CREATE OR REPLACE FUNCTION log10(double precision) RETURNS double precision AS ' SELECT log($1); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION log10(numeric) RETURNS numeric AS ' SELECT log($1); ' LANGUAGE SQL; -- POWER(num, num) CREATE OR REPLACE FUNCTION power(double precision, double precision) RETURNS double precision AS ' SELECT pow($1, $2); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION power(numeric, numeric) RETURNS numeric AS ' SELECT pow($1, $2); ' LANGUAGE SQL; -- RAND([seed]) CREATE OR REPLACE FUNCTION rand() RETURNS double precision AS ' SELECT random(); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION rand(double precision) RETURNS double precision AS ' SELECT setseed($1); SELECT random(); ' LANGUAGE SQL; -- TRUNCATE(num, places) CREATE OR REPLACE FUNCTION truncate(numeric, integer) RETURNS numeric AS ' SELECT trunc($1, $2); ' LANGUAGE SQL; -- Time, Date, and Interval Functions -- ++++++++++++++++++++++++++++++++++ -- -- Built-in: CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, EXTRACT, NOW -- Missing: none CREATE OR REPLACE FUNCTION curdate() RETURNS date AS ' SELECT current_date; ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION curtime() RETURNS time with time zone AS ' SELECT current_time; ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION odbc_timestamp() RETURNS timestamp with time zone AS ' SELECT current_timestamp; ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION dayname(timestamp) RETURNS text AS ' SELECT to_char($1,''Day''); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION dayofmonth(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(day FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION dayofweek(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(dow FROM $1) AS integer) + 1; ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION dayofyear(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(doy FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION hour(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(hour FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION minute(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(minute FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION month(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(month FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION monthname(timestamp) RETURNS text AS ' SELECT to_char($1, ''Month''); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION quarter(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(quarter FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION second(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(second FROM $1) AS integer); ' LANGUAGE SQL; /* -- The first argument is an integer constant denoting the units -- of the second argument. Until we know the actual values, we -- cannot implement these. - thomas 2000-04-11 xCREATE OR REPLACE FUNCTION timestampadd(integer, integer, timestamp) RETURNS timestamp AS ' SELECT CAST(($3 + ($2 * $1)) AS timestamp); ' LANGUAGE SQL; xCREATE OR REPLACE FUNCTION timestampdiff(integer, integer, timestamp) RETURNS timestamp AS ' SELECT CAST(($3 + ($2 * $1)) AS timestamp); ' LANGUAGE SQL; */ CREATE OR REPLACE FUNCTION week(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(week FROM $1) AS integer); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION year(timestamp) RETURNS integer AS ' SELECT CAST(EXTRACT(year FROM $1) AS integer); ' LANGUAGE SQL; -- System Functions -- ++++++++++++++++ -- -- Built-in: USER -- Missing: DATABASE, IFNULL CREATE OR REPLACE FUNCTION odbc_user() RETURNS text AS ' SELECT CAST(current_user AS TEXT); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION odbc_current_user() RETURNS text AS ' SELECT CAST(current_user AS TEXT); ' LANGUAGE SQL; CREATE OR REPLACE FUNCTION odbc_session_user() RETURNS text AS ' SELECT CAST(session_user AS TEXT); ' LANGUAGE SQL; psqlodbc-09.03.0300/odbc-drop.sql000644 001752 000000 00000002317 12335653444 016575 0ustar00saitowheel000000 000000 DROP FUNCTION "char"(integer); DROP FUNCTION concat(text, text); DROP FUNCTION insert(text, integer, integer, text); DROP FUNCTION lcase(text); DROP FUNCTION left(text, integer); DROP FUNCTION locate(text, text); DROP FUNCTION locate(text, text, integer); DROP FUNCTION right(text, integer); DROP FUNCTION space(integer); DROP FUNCTION ucase(text); DROP FUNCTION ceiling(numeric); DROP FUNCTION log10(double precision); DROP FUNCTION log10(numeric); DROP FUNCTION power(double precision, double precision); DROP FUNCTION power(numeric, numeric); DROP FUNCTION rand(); DROP FUNCTION rand(double precision); DROP FUNCTION truncate(numeric, integer); DROP FUNCTION curdate(); DROP FUNCTION curtime(); DROP FUNCTION odbc_timestamp(); DROP FUNCTION dayname(timestamp); DROP FUNCTION dayofmonth(timestamp); DROP FUNCTION dayofweek(timestamp); DROP FUNCTION dayofyear(timestamp); DROP FUNCTION hour(timestamp); DROP FUNCTION minute(timestamp); DROP FUNCTION month(timestamp); DROP FUNCTION monthname(timestamp); DROP FUNCTION quarter(timestamp); DROP FUNCTION second(timestamp); DROP FUNCTION week(timestamp); DROP FUNCTION year(timestamp); DROP FUNCTION odbc_user(); DROP FUNCTION odbc_current_user(); DROP FUNCTION odbc_session_user(); psqlodbc-09.03.0300/odbcapi25w.c000644 001752 000000 00000004153 12335653444 016306 0ustar00saitowheel000000 000000 /*------- * Module: odbcapi25w.c * * Description: This module contains UNICODE routines * * Classes: n/a * * API functions: SQLColAttributesW, SQLErrorW, SQLGetConnectOptionW, SQLSetConnectOptionW *------- */ #include "psqlodbc.h" #include #include #include "pgapifunc.h" #include "connection.h" #include "statement.h" RETCODE SQL_API SQLErrorW(HENV EnvironmentHandle, HDBC ConnectionHandle, HSTMT StatementHandle, SQLWCHAR *Sqlstate, SQLINTEGER *NativeError, SQLWCHAR *MessageText, SQLSMALLINT BufferLength, SQLSMALLINT *TextLength) { RETCODE ret; SWORD tlen, buflen; char *qst = NULL, *mtxt = NULL; mylog("[SQLErrorW]"); if (Sqlstate) qst = malloc(8); buflen = 0; if (MessageText && BufferLength > 0) { buflen = BufferLength * 3 + 1; mtxt = malloc(buflen); } ret = PGAPI_Error(EnvironmentHandle, ConnectionHandle, StatementHandle, qst, NativeError, mtxt, buflen, &tlen); if (qst) utf8_to_ucs2(qst, strlen(qst), Sqlstate, 5); if (NULL != mtxt) { SQLULEN tulen = utf8_to_ucs2(mtxt, tlen, MessageText, BufferLength); if (NULL != TextLength) *TextLength = tulen; free(mtxt); } if (qst) free(qst); return ret; } RETCODE SQL_API SQLGetConnectOptionW(HDBC ConnectionHandle, SQLUSMALLINT Option, PTR Value) { mylog("[SQLGetConnectOptionW]"); CC_set_in_unicode_driver((ConnectionClass *) ConnectionHandle); return PGAPI_GetConnectOption(ConnectionHandle, Option, Value, NULL, 64); } RETCODE SQL_API SQLSetConnectOptionW(HDBC ConnectionHandle, SQLUSMALLINT Option, SQLUINTEGER Value) { mylog("[SQLSetConnectionOptionW]"); if (!ConnectionHandle) return SQL_ERROR; CC_set_in_unicode_driver((ConnectionClass *) ConnectionHandle); return PGAPI_SetConnectOption(ConnectionHandle, Option, Value); } RETCODE SQL_API SQLColAttributesW(HSTMT hstmt, SQLUSMALLINT icol, SQLUSMALLINT fDescType, PTR rgbDesc, SQLSMALLINT cbDescMax, SQLSMALLINT *pcbDesc, SQLINTEGER *pfDesc) { mylog("[SQLColAttributesW]"); return PGAPI_ColAttributes(hstmt, icol, fDescType, rgbDesc, cbDescMax, pcbDesc, pfDesc); } psqlodbc-09.03.0300/sspisvcs.c000644 001752 000000 00000131167 12335653444 016232 0ustar00saitowheel000000 000000 /*------- * Module: sspisvcs.c * * Description: This module contains functions for low level socket * operations (connecting/reading/writing to the backend) * * Classes: SocketClass (Functions prefix: "SOCK_") * * API functions: none * * Comments: See "readme.txt" for copyright and license information. *------- */ #ifdef USE_SSPI #define SECURITY_WIN32 #define WIN32_LEAN_AND_MEAN #include #include #include #pragma comment(lib, "secur32.lib") #include "sspisvcs.h" #include "socket.h" #include "connection.h" #include "environ.h" /* * To handle EWOULDBLOCK etc (mainly for libpq non-blocking connection). */ #define MAX_RETRY_COUNT 30 static int Socket_wait_for_ready(SOCKET socket, BOOL output, int retry_count) { int ret, gerrno; fd_set fds, except_fds; struct timeval tm; BOOL no_timeout = (retry_count < 0); do { FD_ZERO(&fds); FD_ZERO(&except_fds); FD_SET(socket, &fds); FD_SET(socket, &except_fds); if (!no_timeout) { tm.tv_sec = retry_count; tm.tv_usec = 0; } ret = select((int) socket + 1, output ? NULL : &fds, output ? &fds : NULL, &except_fds, no_timeout ? NULL : &tm); gerrno = SOCK_ERRNO; } while (ret < 0 && EINTR == gerrno); if (retry_count < 0) retry_count *= -1; if (0 == ret && retry_count > MAX_RETRY_COUNT) { ret = -1; } return ret; } static int sendall(SOCKET sock, const void *buf, int len) { CSTR func = "sendall"; int wrtlen, ttllen, reqlen, retry_count; retry_count = 0; for (ttllen = 0, reqlen = len; reqlen > 0;) { if (0 > (wrtlen = send(sock, (const char *) buf + ttllen, reqlen, SEND_FLAG))) { int gerrno = SOCK_ERRNO; mylog("%s:errno=%d\n", func, gerrno); switch (gerrno) { case EINTR: continue; case EWOULDBLOCK: retry_count++; if (Socket_wait_for_ready(sock, TRUE, retry_count) >= 0) continue; break; case ECONNRESET: return 0; } return SOCKET_ERROR; } ttllen += wrtlen; reqlen -= wrtlen; retry_count = 0; } return ttllen; } static int recvall(SOCKET sock, void *buf, int len) { CSTR func = "recvall"; int rcvlen, ttllen, reqlen, retry_count = 0; for (ttllen = 0, reqlen = len; reqlen > 0;) { if (0 > (rcvlen = recv(sock, (char *) buf + ttllen, reqlen, RECV_FLAG))) { int gerrno = SOCK_ERRNO; switch (gerrno) { case EINTR: continue; case EWOULDBLOCK: retry_count++; if (Socket_wait_for_ready(sock, FALSE, retry_count) >= 0) continue; break; case ECONNRESET: return 0; } return -1; } ttllen += rcvlen; reqlen -= rcvlen; retry_count = 0; } return ttllen; } /* * service specific data */ /* Schannel specific data */ typedef struct { CredHandle hCred; CtxtHandle hCtxt; PBYTE ioovrbuf; size_t ioovrlen; PBYTE iobuf; size_t iobuflen; size_t ioread; } SchannelSpec; /* Kerberos/Negotiate common specific data */ typedef struct { LPTSTR svcprinc; CredHandle hKerbEtcCred; BOOL ValidCtxt; CtxtHandle hKerbEtcCtxt; } KerberosEtcSpec; typedef struct { SchannelSpec sdata; KerberosEtcSpec kdata; } SspiData; static int DoSchannelNegotiation(SocketClass *, SspiData *, const void *opt, int *bReconnect); static int DoKerberosNegotiation(SocketClass *, SspiData *, const void *opt, int *bReconnect); static int DoNegotiateNegotiation(SocketClass *, SspiData *, const void *opt, int *bReconnect); static int DoKerberosEtcProcessAuthentication(SocketClass *, const void *opt); static SspiData *SspiDataAlloc(SocketClass *self) { SspiData *sspidata; if (sspidata = self->ssd, !sspidata) sspidata = calloc(sizeof(SspiData), 1); return sspidata; } int StartupSspiService(SocketClass *self, SSPI_Service svc, const void *opt, int *bReconnect) { CSTR func = "DoServicelNegotiation"; SspiData *sspidata; if (bReconnect != NULL) *bReconnect = 0; if (NULL == (sspidata = SspiDataAlloc(self))) return -1; switch (svc) { case SchannelService: return DoSchannelNegotiation(self, sspidata, opt, bReconnect); case KerberosService: return DoKerberosNegotiation(self, sspidata, opt, bReconnect); case NegotiateService: return DoNegotiateNegotiation(self, sspidata, opt, bReconnect); } free(sspidata); return -1; } int ContinueSspiService(SocketClass *self, SSPI_Service svc, const void *opt) { CSTR func = "ContinueSspiService"; switch (svc) { case KerberosService: case NegotiateService: return DoKerberosEtcProcessAuthentication(self, opt); } return -1; } static BOOL format_sspierr(char *errmsg, size_t buflen, SECURITY_STATUS r, const char *cmd, const char *cmd2) { BOOL ret = FALSE; if (!cmd2) cmd2 = ""; if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, r, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), errmsg, (DWORD)buflen, NULL)) ret = TRUE; if (ret) { size_t tlen = strlen(errmsg); errmsg += tlen; buflen -= tlen; snprintf(errmsg, buflen, " in %s:%s", cmd, cmd2); } else snprintf(errmsg, buflen, "%s:%s failed ", cmd, cmd2); return ret; } static void SSPI_set_error(SocketClass *s, SECURITY_STATUS r, const char *cmd, const char *cmd2) { int gerrno = SOCK_ERRNO; char emsg[256]; format_sspierr(emsg, sizeof(emsg), r, cmd, cmd2); s->errornumber = r; if (NULL != s->_errormsg_) free(s->_errormsg_); if (NULL != emsg) s->_errormsg_ = strdup(emsg); else s->_errormsg_ = NULL; mylog("(%d)%s ERRNO=%d\n", r, emsg, gerrno); } /* * Stuff for Schannel service */ #include #pragma comment(lib, "crypt32") #define UNI_SCHANNEL TEXT("sChannel") #define IO_BUFFER_SIZE 0x10000 static SECURITY_STATUS CreateSchannelCredentials(LPCTSTR, LPSTR, PCredHandle); static SECURITY_STATUS PerformSchannelClientHandshake(SOCKET, PCredHandle, LPSTR, CtxtHandle *, SecBuffer *); static SECURITY_STATUS SchannelClientHandshakeLoop(SOCKET, PCredHandle, CtxtHandle *, BOOL, SecBuffer *); static void GetNewSchannelClientCredentials(PCredHandle, CtxtHandle *); static BOOL bRootCALoaded = FALSE; static BOOL bMyCert = FALSE; static HCERTSTORE hMyCertStore = NULL; static HCRYPTPROV hProv = (HCRYPTPROV) 0; static PCCERT_CONTEXT pClientCertContext = NULL; static void FreeCertStores(void) { shortterm_common_lock(); if (pClientCertContext) { CertFreeCertificateContext(pClientCertContext); pClientCertContext = NULL; } if (hProv) { CryptReleaseContext(hProv, 0); hProv = (HCRYPTPROV) 0; } if (hMyCertStore) { CertCloseStore(hMyCertStore, CERT_CLOSE_STORE_FORCE_FLAG); hMyCertStore = NULL; } shortterm_common_unlock(); } void LeaveSSPIService(void) { FreeCertStores(); bMyCert = FALSE; bRootCALoaded = FALSE; } /* * This driver allows certificates of PFX form when a pair of * postgresql.crt and postgresql.key doesn't work well. */ static void CertStoreInit_pfx(void) { BOOL success = FALSE; LPCTSTR pgsslpfx = NULL; LPCTSTR appdata = NULL; TCHAR sslpfx[256]; HANDLE fd = INVALID_HANDLE_VALUE; DWORD flen, rlen; CRYPT_DATA_BLOB crypt_data; if (bMyCert) return; if (hMyCertStore != NULL) return; bMyCert = TRUE; pgsslpfx = getenv("PGSSLPFX"); if (!pgsslpfx) { if (!appdata) appdata = getenv("APPDATA"); if (!appdata) return; snprintf(sslpfx, sizeof(sslpfx), "%s\\postgresql\\postgresql.pfx", appdata); pgsslpfx = sslpfx; } fd = CreateFile(pgsslpfx, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == fd) { mylog("!!! pfxfile=%s not found\n", pgsslpfx); goto cleanup; } flen = GetFileSize(fd, NULL); if (flen <= 0) { goto cleanup; } crypt_data.cbData = flen; crypt_data.pbData = (LPBYTE) CryptMemAlloc(flen); ReadFile(fd, crypt_data.pbData, flen, &rlen, NULL); CloseHandle(fd); fd = INVALID_HANDLE_VALUE; hMyCertStore = PFXImportCertStore(&crypt_data, L"", 0); CryptMemFree(crypt_data.pbData); success = TRUE; cleanup: if (fd != INVALID_HANDLE_VALUE) CloseHandle(fd); if (!success) FreeCertStores(); } static void CertStoreInit(void) { BOOL success = FALSE; LPCTSTR pgsslkey = NULL, pgsslcert = NULL; LPCTSTR appdata = NULL; TCHAR sslkey[256], sslcert[256]; HANDLE fd = INVALID_HANDLE_VALUE; DWORD flen, rlen; char *pemdata = NULL; DWORD dwBufferLen, cbKeyBlob; LPBYTE pbBuffer = NULL, pbKeyBlob = NULL; HCRYPTKEY hKey = (HCRYPTKEY) 0; if (hMyCertStore != NULL) return; bMyCert = TRUE; pgsslkey = getenv("PGSSLKEY"); if (!pgsslkey) { if (!appdata) appdata = getenv("APPDATA"); if (!appdata) goto cleanup; snprintf(sslkey, sizeof(sslkey), "%s\\postgresql\\postgresql.key", appdata); pgsslkey = sslkey; } fd = CreateFile(pgsslkey, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == fd) { mylog("!!! keyfile=%s not found\n", pgsslkey); goto cleanup; } flen = GetFileSize(fd, NULL); if (flen <= 0) { goto cleanup; } if (pemdata = malloc(flen), NULL == pemdata) goto cleanup; ReadFile(fd, pemdata, flen, &rlen, NULL); CloseHandle(fd); fd = INVALID_HANDLE_VALUE; if (!CryptStringToBinaryA(pemdata, 0, CRYPT_STRING_BASE64HEADER, NULL, &dwBufferLen, NULL, NULL)) { mylog("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError()); goto cleanup; } if (pbBuffer = malloc(dwBufferLen), NULL == pbBuffer) goto cleanup; if (!CryptStringToBinaryA(pemdata, 0, CRYPT_STRING_BASE64HEADER, pbBuffer, &dwBufferLen, NULL, NULL)) { mylog("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError()); goto cleanup; } free(pemdata); pemdata = NULL; if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, NULL, &cbKeyBlob)) { mylog("Failed to parse private key. Error 0x%.8X\n", GetLastError()); goto cleanup; } if (pbKeyBlob = malloc(cbKeyBlob), NULL == pbKeyBlob) goto cleanup; if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, pbKeyBlob, &cbKeyBlob)) { mylog("Failed to parse private key. Error 0x%.8X\n", GetLastError()); goto cleanup; } free(pbBuffer); pbBuffer = NULL; // Create a temporary and volatile CSP context in order to import // the key if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { mylog("CryptAcquireContext failed with error 0x%.8X\n", GetLastError()); goto cleanup; } // import private key if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, (HCRYPTKEY) 0, 0, &hKey)) { mylog("CryptImportKey failed with error 0x%.8X\n", GetLastError()); goto cleanup; } CryptDestroyKey(hKey); hKey = (HCRYPTKEY) 0; free(pbKeyBlob); pbKeyBlob = NULL; pgsslcert = getenv("PGSSLCERT"); if (!pgsslcert) { appdata = getenv("APPDATA"); if (!appdata) goto cleanup; snprintf(sslcert, sizeof(sslcert), "%s\\postgresql\\postgresql.crt", appdata); pgsslcert = sslcert; } hMyCertStore = CertOpenStore( CERT_STORE_PROV_FILENAME_A , 0 , (HCRYPTPROV) NULL , CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG , pgsslcert ); mylog("!!! hMyCertStore=%p sslcert=%s sslkey=%s\n", hMyCertStore, pgsslcert, pgsslkey); if (hMyCertStore != NULL) { PCCERT_CONTEXT pContext = NULL; pContext = CertEnumCertificatesInStore(hMyCertStore, pContext); while (pContext != NULL) { CertSetCertificateContextProperty(pContext, CERT_KEY_PROV_HANDLE_PROP_ID, 0, (const void *) hProv); pContext = CertEnumCertificatesInStore(hMyCertStore, pContext); } } success = TRUE; cleanup: if (pemdata) free(pemdata); if (pbBuffer) free(pbBuffer); if (pbKeyBlob) free(pbKeyBlob); if (fd != INVALID_HANDLE_VALUE) CloseHandle(fd); if (!success) { HCERTSTORE hSv = hMyCertStore; FreeCertStores(); if (hSv == NULL) CertStoreInit_pfx(); } if (!hMyCertStore) { mylog("!!! hMyCertStore=%p %d\n", hMyCertStore, GetLastError()); } return; } static int InstallRootCA(void) { HCERTSTORE hTempCertStore = NULL, hRootCertStore = NULL; LPCTSTR pgsslroot = NULL; LPCTSTR appdata = NULL; TCHAR sslroot[256]; PCCERT_CONTEXT pContext = NULL; int installed_count = 0, reject_count = 0; shortterm_common_lock(); if (bRootCALoaded) { shortterm_common_unlock(); goto cleanup; } shortterm_common_unlock(); pgsslroot = getenv("PGSSLROOTCERT"); if (!pgsslroot) { appdata = getenv("APPDATA"); if (!appdata) goto cleanup; snprintf(sslroot, sizeof(sslroot), "%s\\postgresql\\root.crt", appdata); pgsslroot = sslroot; } hTempCertStore = CertOpenStore( CERT_STORE_PROV_FILENAME_A , 0 , (HCRYPTPROV) NULL , CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG , pgsslroot ); if (hTempCertStore == NULL) goto cleanup; hRootCertStore = CertOpenSystemStore(0, TEXT("ROOT")); mylog("hRootCertStore=%p sslroot=%s\n", hRootCertStore, pgsslroot); if (hRootCertStore == NULL) goto cleanup; pContext = CertEnumCertificatesInStore(hTempCertStore, pContext); while (pContext != NULL) { if (CertAddCertificateContextToStore(hRootCertStore, pContext, CERT_STORE_ADD_NEWER, NULL)) installed_count++; else { int lasterror = GetLastError(); switch (lasterror) { case CRYPT_E_EXISTS: mylog("Certificate already exists\n"); break; case 1223: // ERROR_CANCELED reject_count++; mylog("Certificate canceled\n"); break; default: reject_count++; mylog("Failed to install root certificate error=%08x\n", lasterror); } } pContext = CertEnumCertificatesInStore(hRootCertStore, pContext); } shortterm_common_lock(); if (!bRootCALoaded) { if (installed_count > 0 || reject_count == 0) bRootCALoaded = TRUE; } shortterm_common_unlock(); cleanup: if (hTempCertStore) CertCloseStore(hTempCertStore, CERT_CLOSE_STORE_FORCE_FLAG); if (hRootCertStore) CertCloseStore(hRootCertStore, CERT_CLOSE_STORE_FORCE_FLAG); return installed_count; } static int DoSchannelNegotiation(SocketClass *self, SspiData *sspidata, const void *opt, int *bReconnect) { CSTR func = "DoSchannelNegotiation"; SECURITY_STATUS r = SEC_E_OK; const char *cmd = NULL; SecBuffer ExtraData; BOOL ret = 0, cCreds = FALSE, cCtxt = FALSE; SchannelSpec *ssd = &(sspidata->sdata); char *server = NULL; if (SEC_E_OK != (r = CreateSchannelCredentials(opt, NULL, &ssd->hCred))) { cmd = "CreateSchannelCredentials"; mylog("%s:%s failed\n", func, cmd); goto cleanup; } cCreds = TRUE; if (opt != NULL) server = ((ConnInfo *) opt)->server; if (SEC_E_OK != (r = PerformSchannelClientHandshake(self->socket, &ssd->hCred, server, &ssd->hCtxt, &ExtraData))) { cmd = "PerformSchannelClientHandshake"; switch (r) { case SEC_E_UNTRUSTED_ROOT: mylog("Installing RootCA\n"); if (InstallRootCA() > 0) *bReconnect = 1; break; default: break; } mylog("%s:%s failed\n", func, cmd); goto cleanup; } cCtxt = TRUE; if (NULL != ExtraData.pvBuffer && 0 != ExtraData.cbBuffer) { ssd->iobuf = malloc(ExtraData.cbBuffer); ssd->iobuflen = ssd->ioread = ExtraData.cbBuffer; memcpy(ssd->iobuf, ExtraData.pvBuffer, ssd->ioread); free(ExtraData.pvBuffer); } ret = TRUE; cleanup: if (ret) { self->sspisvcs |= SchannelService; self->ssd = sspidata; } else { SSPI_set_error(self, r, __FUNCTION__, cmd); if (cCreds) FreeCredentialHandle(&ssd->hCred); if (cCtxt) DeleteSecurityContext(&ssd->hCtxt); if (ssd->iobuf) free(ssd->iobuf); if (!self->ssd) free(sspidata); } return ret; } static SECURITY_STATUS CreateSchannelCredentials( LPCTSTR opt, /* in */ LPSTR pszUserName, /* in */ PCredHandle phCreds) /* out */ { TimeStamp tsExpiry; SECURITY_STATUS Status; SCHANNEL_CRED SchannelCred; DWORD cSupportedAlgs = 0; ALG_ID rgbSupportedAlgs[16]; DWORD dwProtocol = SP_PROT_SSL3 | SP_PROT_SSL2; DWORD aiKeyExch = 0; char *sslmode = NULL; PCCERT_CONTEXT pCertContext = NULL; /* * If a user name is specified, then attempt to find a client * certificate. Otherwise, just create a NULL credential. */ if (pClientCertContext) pCertContext = pClientCertContext; else if (pszUserName) { /* Find client certificate. Note that this sample just searchs for a * certificate that contains the user name somewhere in the subject name. * A real application should be a bit less casual. */ pCertContext = CertFindCertificateInStore(hMyCertStore, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR_A, pszUserName, NULL); if (pCertContext == NULL) { mylog("**** Error 0x%p returned by CertFindCertificateInStore\n", GetLastError()); return SEC_E_NO_CREDENTIALS; } } /* * Build Schannel credential structure. Currently, this sample only * specifies the protocol to be used (and optionally the certificate, * of course). Real applications may wish to specify other parameters * as well. */ ZeroMemory(&SchannelCred, sizeof(SchannelCred)); SchannelCred.dwVersion = SCHANNEL_CRED_VERSION; if (pCertContext) { SchannelCred.cCreds = 1; SchannelCred.paCred = &pCertContext; } SchannelCred.grbitEnabledProtocols = dwProtocol; if (aiKeyExch) { rgbSupportedAlgs[cSupportedAlgs++] = aiKeyExch; } if (cSupportedAlgs) { SchannelCred.cSupportedAlgs = cSupportedAlgs; SchannelCred.palgSupportedAlgs = rgbSupportedAlgs; } SchannelCred.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS; /* The SCH_CRED_MANUAL_CRED_VALIDATION flag is specified because * this sample verifies the server certificate manually. * Applications that expect to run on WinNT, Win9x, or WinME * should specify this flag and also manually verify the server * certificate. Applications running on newer versions of Windows can * leave off this flag, in which case the InitializeSecurityContext * function will validate the server certificate automatically. */ if (opt != NULL) sslmode = ((ConnInfo *) opt)->sslmode; if (sslmode == NULL || sslmode[0] != 'v') SchannelCred.dwFlags |= SCH_CRED_MANUAL_CRED_VALIDATION; else { if (strcmp(sslmode, "verify-full")) SchannelCred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK; // InstallRootCA(); } /* * Create an SSPI credential. */ Status = AcquireCredentialsHandle( NULL, /* Name of principal */ UNI_SCHANNEL, /* Name of package */ SECPKG_CRED_OUTBOUND, /* Flags indicating use */ NULL, /* Pointer to logon ID */ &SchannelCred, /* Package specific data */ NULL, /* Pointer to GetKey() func */ NULL, /* Value to pass to GetKey() */ phCreds, /* (out) Cred Handle */ &tsExpiry); /* (out) Lifetime (optional) */ if (Status != SEC_E_OK) { mylog("**** Error 0x%p returned by AcquireCredentialsHandle\n", Status); goto cleanup; } cleanup: /* * Free the certificate context. Schannel has already made its own copy. */ if (pCertContext && pCertContext != pClientCertContext) { CertFreeCertificateContext(pCertContext); } return Status; } static SECURITY_STATUS PerformSchannelClientHandshake( SOCKET Socket, /* in */ PCredHandle phCreds, /* in */ LPSTR pszServerName, /* in */ CtxtHandle *phContext, /* out */ SecBuffer *pExtraData) /* out */ { SecBufferDesc OutBuffer; SecBuffer OutBuffers[1]; DWORD dwSSPIFlags; DWORD dwSSPIOutFlags; TimeStamp tsExpiry; SECURITY_STATUS scRet; DWORD cbData; dwSSPIFlags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; /* * Initiate a ClientHello message and generate a token. */ OutBuffers[0].pvBuffer = NULL; OutBuffers[0].BufferType = SECBUFFER_TOKEN; OutBuffers[0].cbBuffer = 0; OutBuffer.cBuffers = 1; OutBuffer.pBuffers = OutBuffers; OutBuffer.ulVersion = SECBUFFER_VERSION; scRet = InitializeSecurityContext( phCreds, NULL, pszServerName, dwSSPIFlags, 0, SECURITY_NATIVE_DREP, NULL, 0, phContext, &OutBuffer, &dwSSPIOutFlags, &tsExpiry); if (scRet != SEC_I_CONTINUE_NEEDED) { mylog("**** Error %x returned by InitializeSecurityContext (1)\n", scRet); return scRet; } /* Send response to server if there is one. */ if (OutBuffers[0].cbBuffer != 0 && OutBuffers[0].pvBuffer != NULL) { cbData = sendall(Socket, OutBuffers[0].pvBuffer, OutBuffers[0].cbBuffer); if (cbData <= 0) { mylog("**** Error %x sending data to server\n", SOCK_ERRNO); FreeContextBuffer(OutBuffers[0].pvBuffer); DeleteSecurityContext(phContext); return SEC_E_INTERNAL_ERROR; } mylog("%d bytes of handshake data sent\n", cbData); /* Free output buffer. */ FreeContextBuffer(OutBuffers[0].pvBuffer); OutBuffers[0].pvBuffer = NULL; } return SchannelClientHandshakeLoop(Socket, phCreds, phContext, TRUE, pExtraData); } static SECURITY_STATUS SchannelClientHandshakeLoop( SOCKET Socket, /* in */ PCredHandle phCreds, /* in */ CtxtHandle *phContext, /* i-o */ BOOL fDoInitialRead, /* in */ SecBuffer *pExtraData) /* out */ { SecBufferDesc InBuffer; SecBuffer InBuffers[2]; SecBufferDesc OutBuffer; SecBuffer OutBuffers[1]; DWORD dwSSPIFlags; DWORD dwSSPIOutFlags; TimeStamp tsExpiry; SECURITY_STATUS scRet; DWORD cbData; PUCHAR IoBuffer; DWORD cbIoBuffer; BOOL fDoRead; int retry_count; dwSSPIFlags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; /* * Allocate data buffer. */ IoBuffer = malloc(IO_BUFFER_SIZE); if (IoBuffer == NULL) { mylog("**** Out of memory (1)\n"); return SEC_E_INTERNAL_ERROR; } cbIoBuffer = 0; fDoRead = fDoInitialRead; /* * Loop until the handshake is finished or an error occurs. */ retry_count = 0; scRet = SEC_I_CONTINUE_NEEDED; while (scRet == SEC_I_CONTINUE_NEEDED || scRet == SEC_E_INCOMPLETE_MESSAGE || scRet == SEC_I_INCOMPLETE_CREDENTIALS) { /* * Read data from server. */ if( 0 == cbIoBuffer || scRet == SEC_E_INCOMPLETE_MESSAGE) { if (fDoRead) { cbData = recv(Socket, IoBuffer + cbIoBuffer, IO_BUFFER_SIZE - cbIoBuffer, RECV_FLAG); if (cbData == SOCKET_ERROR) { int gerrno = SOCK_ERRNO; mylog("**** Error %d reading data from server\n", gerrno); switch (gerrno) { case EINTR: continue; case ECONNRESET: break; case EWOULDBLOCK: retry_count++; if (Socket_wait_for_ready(Socket, FALSE, retry_count) >= 0) continue; default: scRet = SEC_E_INTERNAL_ERROR; SOCK_ERRNO_SET(gerrno); break; } break; } else if(cbData == 0) { mylog("**** Server unexpectedly disconnected\n"); scRet = SEC_E_INTERNAL_ERROR; break; } mylog("%d bytes of handshake data received\n", cbData); cbIoBuffer += cbData; retry_count = 0; } else { fDoRead = TRUE; } } /* * Set up the input buffers. Buffer 0 is used to pass in data * received from the server. Schannel will consume some or all * of this. Leftover data (if any) will be placed in buffer 1 and * given a buffer type of SECBUFFER_EXTRA. */ InBuffers[0].pvBuffer = IoBuffer; InBuffers[0].cbBuffer = cbIoBuffer; InBuffers[0].BufferType = SECBUFFER_TOKEN; InBuffers[1].pvBuffer = NULL; InBuffers[1].cbBuffer = 0; InBuffers[1].BufferType = SECBUFFER_EMPTY; InBuffer.cBuffers = 2; InBuffer.pBuffers = InBuffers; InBuffer.ulVersion = SECBUFFER_VERSION; /* * Set up the output buffers. These are initialized to NULL * so as to make it less likely we'll attempt to free random * garbage later. */ OutBuffers[0].pvBuffer = NULL; OutBuffers[0].BufferType= SECBUFFER_TOKEN; OutBuffers[0].cbBuffer = 0; OutBuffer.cBuffers = 1; OutBuffer.pBuffers = OutBuffers; OutBuffer.ulVersion = SECBUFFER_VERSION; /* * Call InitializeSecurityContext. */ scRet = InitializeSecurityContext(phCreds, phContext, NULL, dwSSPIFlags, 0, SECURITY_NATIVE_DREP, &InBuffer, 0, NULL, &OutBuffer, &dwSSPIOutFlags, &tsExpiry); /* * If InitializeSecurityContext was successful (or if the error was * one of the special extended ones), send the contends of the output * buffer to the server. */ if( scRet == SEC_E_OK || scRet == SEC_I_CONTINUE_NEEDED || FAILED(scRet) && (dwSSPIOutFlags & ISC_RET_EXTENDED_ERROR)) { if (OutBuffers[0].cbBuffer != 0 && OutBuffers[0].pvBuffer != NULL) { cbData = sendall(Socket, OutBuffers[0].pvBuffer, OutBuffers[0].cbBuffer); if (cbData == SOCKET_ERROR || cbData == 0) { mylog("**** Error %d sending data to server (2)\n", SOCK_ERRNO); FreeContextBuffer(OutBuffers[0].pvBuffer); DeleteSecurityContext(phContext); return SEC_E_INTERNAL_ERROR; } mylog("%d bytes of handshake data sent\n", cbData); /* Free output buffer. */ FreeContextBuffer(OutBuffers[0].pvBuffer); OutBuffers[0].pvBuffer = NULL; } } /* * If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, * then we need to read more data from the server and try again. */ if (scRet == SEC_E_INCOMPLETE_MESSAGE) { continue; } /* * If InitializeSecurityContext returned SEC_E_OK, then the * handshake completed successfully. */ if(scRet == SEC_E_OK) { /* * If the "extra" buffer contains data, this is encrypted application * protocol layer stuff. It needs to be saved. The application layer * will later decrypt it with DecryptMessage. */ mylog("Handshake was successful\n"); if (InBuffers[1].BufferType == SECBUFFER_EXTRA) { pExtraData->pvBuffer = malloc(InBuffers[1].cbBuffer); if (pExtraData->pvBuffer == NULL) { mylog("**** Out of memory (2)\n"); return SEC_E_INTERNAL_ERROR; } memmove(pExtraData->pvBuffer, IoBuffer + (cbIoBuffer - InBuffers[1].cbBuffer), InBuffers[1].cbBuffer); pExtraData->cbBuffer = InBuffers[1].cbBuffer; pExtraData->BufferType = SECBUFFER_TOKEN; mylog("%d bytes of app data was bundled with handshake data\n", pExtraData->cbBuffer); } else { pExtraData->pvBuffer = NULL; pExtraData->cbBuffer = 0; pExtraData->BufferType = SECBUFFER_EMPTY; } /* * Bail out to quit */ break; } /* * Check for fatal error. */ if(FAILED(scRet)) { mylog("**** Error 0x%p returned by InitializeSecurityContext (2)\n", scRet); break; } /* * If InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS, * then the server just requested client authentication. */ if (scRet == SEC_I_INCOMPLETE_CREDENTIALS) { /* * Busted. The server has requested client authentication and * the credential we supplied didn't contain a client certificate. * * * This function will read the list of trusted certificate * authorities ("issuers") that was received from the server * and attempt to find a suitable client certificate that * was issued by one of these. If this function is successful, * then we will connect using the new certificate. Otherwise, * we will attempt to connect anonymously (using our current * credentials). */ mylog("Server returned SEC_I_INCOMPLETE_CREDENTIALS\n"); shortterm_common_lock(); GetNewSchannelClientCredentials(phCreds, phContext); shortterm_common_unlock(); /* Go around again. */ fDoRead = FALSE; scRet = SEC_I_CONTINUE_NEEDED; continue; } /* * Copy any leftover data from the "extra" buffer, and go around * again. */ if ( InBuffers[1].BufferType == SECBUFFER_EXTRA ) { memmove(IoBuffer, IoBuffer + (cbIoBuffer - InBuffers[1].cbBuffer), InBuffers[1].cbBuffer); cbIoBuffer = InBuffers[1].cbBuffer; } else { cbIoBuffer = 0; } } /* Delete the security context in the case of a fatal error. */ if (FAILED(scRet)) { DeleteSecurityContext(phContext); } free(IoBuffer); return scRet; } static void GetNewSchannelClientCredentials( CredHandle *phCreds, CtxtHandle *phContext) { SCHANNEL_CRED SchannelCred; CredHandle hCreds; PCCERT_CONTEXT pCertContext; TimeStamp tsExpiry; SECURITY_STATUS Status; CertStoreInit(); if (hMyCertStore == NULL) return; /* * Enumerate the client certificates. */ pCertContext = NULL; while (TRUE) { pCertContext = CertEnumCertificatesInStore(hMyCertStore, pCertContext); if (pCertContext == NULL) { mylog("Error 0x%p enum cert chain\n", GetLastError()); break; } mylog("certificate context found\n"); ZeroMemory(&SchannelCred, sizeof(SchannelCred)); /* Create schannel credential. */ SchannelCred.dwVersion = SCHANNEL_CRED_VERSION; SchannelCred.cCreds = 1; SchannelCred.paCred = &pCertContext; Status = AcquireCredentialsHandle( NULL, /* Name of principal */ UNI_SCHANNEL, /* Name of package */ SECPKG_CRED_OUTBOUND, /* Flags indicating use */ NULL, /* Pointer to logon ID */ &SchannelCred, /* Package specific data */ NULL, /* Pointer to GetKey() func */ NULL, /* Value to pass to GetKey() */ &hCreds, /* (out) Cred Handle */ &tsExpiry); /* (out) Lifetime (optional) */ if (Status != SEC_E_OK) { mylog("**** Error 0x%p returned by AcquireCredentialsHandle\n", Status); continue; } mylog("new schannel client credential created\n"); /* Destroy the old credentials. */ FreeCredentialsHandle(phCreds); *phCreds = hCreds; /* * As you can see, this sample code maintains a single credential * handle, replacing it as necessary. This is a little unusual. * * Many applications maintain a global credential handle that's * anonymous (that is, it doesn't contain a client certificate), * which is used to connect to all servers. If a particular server * should require client authentication, then a new credential * is created for use when connecting to that server. The global * anonymous credential is retained for future connections to * other servers. * * Maintaining a single anonymous credential that's used whenever * possible is most efficient, since creating new credentials all * the time is rather expensive. */ if (pCertContext) pClientCertContext = pCertContext; break; } } /* * Stuff for Kerberos etc service */ #define UNI_KERBEROS TEXT("Kerberos") #define UNI_NEGOTIATE TEXT("Negotiate") #define IO_BUFFER_SIZE 0x10000 static SECURITY_STATUS CreateKerberosEtcCredentials(LPCTSTR, SEC_CHAR *, LPCTSTR, PCredHandle); static SECURITY_STATUS PerformKerberosEtcClientHandshake(SocketClass *, KerberosEtcSpec *ssd, size_t); static int DoKerberosNegotiation(SocketClass *self, SspiData *sspidata, const void *opt, int *bReconnect) { CSTR func = "DoKerberosNegotiation"; SECURITY_STATUS r = SEC_E_OK; const char * cmd = NULL; BOOL ret = 0; KerberosEtcSpec *ssd = &(sspidata->kdata); mylog("!!! %s in\n", __FUNCTION__); if (SEC_E_OK != (r = CreateKerberosEtcCredentials(NULL, UNI_KERBEROS, (LPCTSTR) opt, &ssd->hKerbEtcCred))) { cmd = "CreateKerberosCredentials"; mylog("%s:%s failed\n", func, cmd); SSPI_set_error(self, r, __FUNCTION__, cmd); return 0; } mylog("!!! CreateKerberosCredentials passed\n"); ssd->svcprinc = (LPTSTR) opt; self->sspisvcs |= KerberosService; self->ssd = sspidata; return DoKerberosEtcProcessAuthentication(self, NULL); } static int DoNegotiateNegotiation(SocketClass *self, SspiData *sspidata, const void *opt, int *bReconnect) { CSTR func = "DoNegotiateNegotiation"; SECURITY_STATUS r = SEC_E_OK; const char * cmd = NULL; BOOL ret = 0; KerberosEtcSpec *ssd = &(sspidata->kdata); mylog("!!! %s in\n", __FUNCTION__); if (SEC_E_OK != (r = CreateKerberosEtcCredentials(NULL, UNI_NEGOTIATE, (LPCTSTR) opt, &ssd->hKerbEtcCred))) { cmd = "CreateNegotiateCredentials"; mylog("%s:%s failed\n", func, cmd); SSPI_set_error(self, r, __FUNCTION__, cmd); return 0; } mylog("!!! CreateNegotiateCredentials passed\n"); ssd->svcprinc = (LPTSTR) opt; self->sspisvcs |= NegotiateService; self->ssd = sspidata; return DoKerberosEtcProcessAuthentication(self, NULL); } static int DoKerberosEtcProcessAuthentication(SocketClass *self, const void *opt) { CSTR func = "DoKerberosEtcProcessAuthentication"; SECURITY_STATUS r = SEC_E_OK; const char * cmd = NULL; BOOL ret = 0, cCtxt = FALSE; KerberosEtcSpec *ssd; mylog("!!! %s in\n", __FUNCTION__); ssd = &(((SspiData *)(self->ssd))->kdata); if (SEC_E_OK != (r = PerformKerberosEtcClientHandshake(self, ssd, (size_t) opt))) { cmd = "PerformKerberosEtcClientHandshake"; mylog("%s:%s failed\n", func, cmd); goto cleanup; } mylog("!!! PerformKerberosEtcClientHandshake passed\n"); cCtxt = TRUE; ret = TRUE; cleanup: if (!ret) { SSPI_set_error(self, r, __FUNCTION__, cmd); FreeCredentialHandle(&ssd->hKerbEtcCred); if (cCtxt) { DeleteSecurityContext(&ssd->hKerbEtcCtxt); } self->sspisvcs &= (~(KerberosService | NegotiateService)); } return ret; } static SECURITY_STATUS CreateKerberosEtcCredentials( LPCTSTR opt, /* in */ SEC_CHAR *packname, /* in */ LPCTSTR pszUserName, /* in */ PCredHandle phCreds) /* out */ { TimeStamp tsExpiry; SECURITY_STATUS Status; /* * Create an SSPI credential. */ Status = AcquireCredentialsHandle( NULL, /* Name of principal */ packname, /* Name of package */ SECPKG_CRED_OUTBOUND, /* Flags indicating use */ NULL, /* Pointer to logon ID */ NULL, /* Package specific data */ NULL, /* Pointer to GetKey() func */ NULL, /* Value to pass to GetKey() */ phCreds, /* (out) Cred Handle */ &tsExpiry); /* (out) Lifetime (optional) */ if (Status != SEC_E_OK) { mylog("**** Error 0x%p returned by AcquireCredentialsHandle\n", Status); goto cleanup; } cleanup: return Status; } static SECURITY_STATUS PerformKerberosEtcClientHandshake( SocketClass *sock, /* in */ KerberosEtcSpec *ssd, /* i-o */ size_t inlen) { SecBufferDesc InBuffer; SecBuffer InBuffers[1]; SecBufferDesc OutBuffer; SecBuffer OutBuffers[1]; DWORD dwSSPIFlags; DWORD dwSSPIOutFlags; TimeStamp tsExpiry; SECURITY_STATUS scRet; CtxtHandle hContext; PBYTE inbuf = NULL; mylog("!!! inlen=%u svcprinc=%s\n", inlen, ssd->svcprinc); if (ssd->ValidCtxt && inlen > 0) { if (NULL == (inbuf = malloc(inlen + 1))) { return SEC_E_INTERNAL_ERROR; } SOCK_get_n_char(sock, inbuf, inlen); if (SOCK_get_errcode(sock) != 0) { mylog("**** Error %d receiving data from server (1)\n", SOCK_ERRNO); free(inbuf); return SEC_E_INTERNAL_ERROR; } InBuffer.ulVersion = SECBUFFER_VERSION; InBuffer.cBuffers = 1; InBuffer.pBuffers = InBuffers; InBuffers[0].pvBuffer = inbuf; InBuffers[0].cbBuffer = inlen; InBuffers[0].BufferType = SECBUFFER_TOKEN; } dwSSPIFlags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; /* * Initiate a ClientHello message and generate a token. */ OutBuffers[0].pvBuffer = NULL; OutBuffers[0].BufferType = SECBUFFER_TOKEN; OutBuffers[0].cbBuffer = 0; OutBuffer.cBuffers = 1; OutBuffer.pBuffers = OutBuffers; OutBuffer.ulVersion = SECBUFFER_VERSION; mylog("!!! before InitializeSecurityContext\n"); scRet = InitializeSecurityContext( &ssd->hKerbEtcCred, ssd->ValidCtxt ? &ssd->hKerbEtcCtxt : NULL, ssd->svcprinc, dwSSPIFlags, 0, SECURITY_NATIVE_DREP, ssd->ValidCtxt ? &InBuffer : NULL, 0, &hContext, &OutBuffer, &dwSSPIOutFlags, &tsExpiry); mylog("!!! %s:InitializeSecurityContext ret=%x\n", __FUNCTION__, scRet); if (inbuf) free(inbuf); if (SEC_E_OK != scRet && SEC_I_CONTINUE_NEEDED != scRet) { mylog("**** Error %x returned by InitializeSecurityContext\n", scRet); return scRet; } if (!ssd->ValidCtxt) { memcpy(&ssd->hKerbEtcCtxt, &hContext, sizeof(CtxtHandle)); ssd->ValidCtxt = TRUE; } mylog("!!! cbBuffer=%d pvBuffer=%p\n", OutBuffers[0].cbBuffer, OutBuffers[0].pvBuffer); /* Send response to server if there is one. */ if (OutBuffers[0].cbBuffer != 0 && OutBuffers[0].pvBuffer != NULL) { int reslen = OutBuffers[0].cbBuffer; mylog("!!! responding 'p' + int(%d) + %dbytes of data\n", reslen + 4, reslen); SOCK_put_char(sock, 'p'); SOCK_put_int(sock, reslen + 4, 4); SOCK_put_n_char(sock, OutBuffers[0].pvBuffer, reslen); SOCK_flush_output(sock); if (SOCK_get_errcode(sock) != 0) { mylog("**** Error %d sending data to server (1)\n", SOCK_ERRNO); FreeContextBuffer(OutBuffers[0].pvBuffer); return SEC_E_INTERNAL_ERROR; } mylog("%d bytes of handshake data sent\n", OutBuffers[0].cbBuffer); /* Free output buffer. */ FreeContextBuffer(OutBuffers[0].pvBuffer); OutBuffers[0].pvBuffer = NULL; } return SEC_E_OK; // return KerberosEtcClientHandshakeLoop(Socket, ssd, TRUE, pExtraData); } int SSPI_recv(SocketClass *self, void *buffer, int len) { CSTR func = "SSPI_recv"; if (0 != (self->sspisvcs & SchannelService)) { SECURITY_STATUS scRet; SecBuffer Buffers[4]; SecBufferDesc Message; SecBuffer *pDataBuffer; SecBuffer *pExtraBuffer; SecBuffer ExtraBuffer; int i, retry_count, reqlen, rtnlen = -1; PBYTE pbIoBuffer; DWORD cbIoBuffer, cbIoBufferLength; DWORD cbData; SchannelSpec *ssd = &(((SspiData *)(self->ssd))->sdata); mylog("buflen=%d,%d ovrlen=%d\n", ssd->iobuflen, ssd->ioread, ssd->ioovrlen); if (ssd->ioovrlen > 0) { if (rtnlen = ssd->ioovrlen, rtnlen > len) rtnlen = len; memmove(buffer, ssd->ioovrbuf, rtnlen); if (rtnlen < ssd->ioovrlen) { memmove(ssd->ioovrbuf, ssd->ioovrbuf + rtnlen, ssd->ioovrlen - rtnlen); } ssd->ioovrlen -= rtnlen; return rtnlen; } /* * Read data from server until done. */ retry_count = 0; cbIoBufferLength = ((len - 1) / 16 + 1) * 16; pbIoBuffer = ssd->iobuf; cbIoBuffer = ssd->ioread; if (cbIoBuffer > 0) reqlen = 0; else reqlen = len - cbIoBuffer; while (TRUE) { /* * Read some data. */ mylog("buf=%p read=%d req=%d\n", pbIoBuffer, cbIoBuffer, reqlen); if (reqlen > 0) { if (cbIoBuffer + reqlen > ssd->iobuflen) { void *iobuf; cbIoBufferLength = cbIoBuffer + reqlen; iobuf = realloc(ssd->iobuf, cbIoBufferLength); if (NULL == iobuf) { mylog("failed to realloc ssd->iobuf\n"); if (ssd->iobuf) { free(ssd->iobuf); ssd->iobuf = NULL; } ssd->iobuflen = 0; return -1; } pbIoBuffer = ssd->iobuf = iobuf; ssd->iobuflen = cbIoBufferLength; } cbData = recv(self->socket, pbIoBuffer + cbIoBuffer, reqlen, RECV_FLAG); if (cbData == SOCKET_ERROR) { int gerrno = SOCK_ERRNO; mylog("**** Error %d reading data from server\n", gerrno); switch (gerrno) { case EINTR: continue; case EWOULDBLOCK: retry_count++; if (Socket_wait_for_ready(self->socket, FALSE, retry_count) >= 0) continue; default: SOCK_ERRNO_SET(gerrno); scRet = SEC_E_INTERNAL_ERROR; break; } break; } else if (cbData == 0) { /* Server disconnected. */ if (cbIoBuffer) { mylog("**** Server unexpectedly disconnected\n"); scRet = SEC_E_INTERNAL_ERROR; goto cleanup; } else { rtnlen = 0; break; } } else { mylog("%d bytes of (encrypted) application data received\n", cbData); cbIoBuffer += cbData; reqlen -= cbData; retry_count = 0; } } /* * Attempt to decrypt the received data. */ Buffers[0].pvBuffer = pbIoBuffer; Buffers[0].cbBuffer = cbIoBuffer; Buffers[0].BufferType = SECBUFFER_DATA; Buffers[1].BufferType = SECBUFFER_EMPTY; Buffers[2].BufferType = SECBUFFER_EMPTY; Buffers[3].BufferType = SECBUFFER_EMPTY; Message.ulVersion = SECBUFFER_VERSION; Message.cBuffers = 4; Message.pBuffers = Buffers; scRet = DecryptMessage(&ssd->hCtxt, &Message, 0, NULL); if (scRet == SEC_E_INCOMPLETE_MESSAGE) { /* The input buffer contains only a fragment of an * encrypted record. Loop around and read some more * data. */ if (reqlen <= 0) { if (cbIoBuffer < len) reqlen = len - cbIoBuffer; else reqlen = len; } continue; } /* Server signalled end of session */ if (scRet == SEC_I_CONTEXT_EXPIRED) break; if (scRet != SEC_E_OK && scRet != SEC_I_RENEGOTIATE) { mylog("**** Error 0x%p returned by DecryptMessage\n", scRet); goto cleanup; } /* Locate data and (optional) extra buffers. */ pDataBuffer = NULL; pExtraBuffer = NULL; for(i = 1; i < 4; i++) { if (pDataBuffer == NULL && Buffers[i].BufferType == SECBUFFER_DATA) { pDataBuffer = &Buffers[i]; mylog("%p Buffers[%d].BufferType = SECBUFFER_DATA\n", pDataBuffer->pvBuffer, i); } if (pExtraBuffer == NULL && Buffers[i].BufferType == SECBUFFER_EXTRA) { pExtraBuffer = &Buffers[i]; mylog("%p Buffers[%d].BufferType = SECBUFFER_EXTRA\n", pExtraBuffer->pvBuffer, i); } } /* Display or otherwise process the decrypted data. */ if (pDataBuffer) { mylog("Decrypted data: %d bytes\n", pDataBuffer->cbBuffer); if (len < pDataBuffer->cbBuffer) { rtnlen = len; memcpy(buffer, pDataBuffer->pvBuffer, rtnlen); ssd->ioovrlen = pDataBuffer->cbBuffer - len; ssd->ioovrbuf = realloc(ssd->ioovrbuf, ssd->ioovrlen); memcpy(ssd->ioovrbuf, (const char *) pDataBuffer->pvBuffer + len, ssd->ioovrlen); } else { rtnlen = pDataBuffer->cbBuffer; memcpy(buffer, pDataBuffer->pvBuffer, rtnlen); } } /* Move any "extra" data to the input buffer. */ if (pExtraBuffer) { mylog("Extra data: %d bytes\n", pExtraBuffer->cbBuffer); pbIoBuffer = ssd->iobuf; cbIoBuffer = pExtraBuffer->cbBuffer; memmove(pbIoBuffer, pExtraBuffer->pvBuffer, cbIoBuffer); } else cbIoBuffer = 0; ssd->ioread = cbIoBuffer; if (scRet == SEC_I_RENEGOTIATE) { /* The server wants to perform another handshake * sequence. */ mylog("Server requested renegotiate!\n"); scRet = SchannelClientHandshakeLoop( self->socket, &ssd->hCred, &ssd->hCtxt, FALSE, &ExtraBuffer); if (scRet != SEC_E_OK) { goto cleanup; } /* Move any "extra" data to the input buffer. */ if (ExtraBuffer.pvBuffer) { memmove(pbIoBuffer, ExtraBuffer.pvBuffer, ExtraBuffer.cbBuffer); cbIoBuffer = ExtraBuffer.cbBuffer; } } break; } cleanup: return rtnlen; } else return recv(self->socket, (char *) buffer, len, RECV_FLAG); } int SSPI_send(SocketClass *self, const void *buffer, int len) { CSTR func = "SSPI_send"; if (0 != (self->sspisvcs & SchannelService)) { SecPkgContext_StreamSizes sizes; int ttllen, wrtlen, slen; LPVOID lpHead; LPVOID lpMsg; LPVOID lpTrail; SecBuffer sb[4]; SecBufferDesc sbd; SchannelSpec *ssd = &(((SspiData *)(self->ssd))->sdata); QueryContextAttributes(&ssd->hCtxt, SECPKG_ATTR_STREAM_SIZES, &sizes); slen = len; ttllen = sizes.cbHeader + len + sizes.cbTrailer; if (ttllen > sizes.cbMaximumMessage) { ttllen = sizes.cbMaximumMessage; slen = ttllen - sizes.cbHeader - sizes.cbTrailer; } lpHead = malloc(ttllen); lpMsg = (char *) lpHead + sizes.cbHeader; memcpy(lpMsg, buffer, slen); lpTrail = (char *) lpMsg + slen; sb[0].cbBuffer = sizes.cbHeader; sb[0].pvBuffer = lpHead; sb[0].BufferType = SECBUFFER_STREAM_HEADER; sb[1].cbBuffer = slen; sb[1].pvBuffer = lpMsg; sb[1].BufferType = SECBUFFER_DATA; sb[2].cbBuffer = sizes.cbTrailer; sb[2].pvBuffer = lpTrail; sb[2].BufferType = SECBUFFER_STREAM_TRAILER; /* sb[3].cbBuffer = 16; sb[3].pvBuffer = lpPad; */ sb[3].BufferType = SECBUFFER_EMPTY; sbd.cBuffers = 4; sbd.pBuffers = sb; sbd.ulVersion = SECBUFFER_VERSION; EncryptMessage(&ssd->hCtxt, 0, &sbd, 0); mylog("EMPTY=%p %d %d\n", sb[3].pvBuffer, sb[3].cbBuffer, sb[3].BufferType); if (wrtlen = sendall(self->socket, lpHead, ttllen), wrtlen < 0) { int gerrno = SOCK_ERRNO; free(lpHead); SOCK_ERRNO_SET(gerrno); return -1; } free(lpHead); return slen; } else return send(self->socket, (char *) buffer, len, SEND_FLAG); } void ReleaseSvcSpecData(SocketClass *self, UInt4 svc) { if (!self->ssd) return; if (0 != (self->sspisvcs & (svc & SchannelService))) { SchannelSpec *ssd = &(((SspiData *)(self->ssd))->sdata); if (ssd->iobuf) { free(ssd->iobuf); ssd->iobuf = NULL; } if (ssd->ioovrbuf) { free(ssd->ioovrbuf); ssd->ioovrbuf = NULL; } FreeCredentialHandle(&ssd->hCred); DeleteSecurityContext(&ssd->hCtxt); self->sspisvcs &= (~SchannelService); } if (0 != (self->sspisvcs & (svc & (KerberosService | NegotiateService)))) { KerberosEtcSpec *ssd = &(((SspiData *)(self->ssd))->kdata); if (ssd->svcprinc) { free(ssd->svcprinc); ssd->svcprinc = NULL; } FreeCredentialHandle(&ssd->hKerbEtcCred); if (ssd->ValidCtxt) { DeleteSecurityContext(&ssd->hKerbEtcCtxt); ssd->ValidCtxt = FALSE; } self->sspisvcs &= (~(KerberosService | NegotiateService)); } } #endif /* USE_SSPI */ psqlodbc-09.03.0300/sspisvcs.h000644 001752 000000 00000001344 12335653444 016230 0ustar00saitowheel000000 000000 /* File: sspisvcs.h * * Description: See "sspisvcs.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __SSPISVCS_H__ #define __SSPISVCS_H__ #include "socket.h" /* SSPI Services */ typedef enum { SchannelService = 1L ,KerberosService = (1L << 1) ,NegotiateService = (1L << 2) } SSPI_Service; void LeaveSSPIService(void); void ReleaseSvcSpecData(SocketClass *self, UInt4); int StartupSspiService(SocketClass *self, SSPI_Service svc, const void *opt, int *bReconnect); int ContinueSspiService(SocketClass *self, SSPI_Service svc, const void *opt); int SSPI_recv(SocketClass *self, void *buf, int len); int SSPI_send(SocketClass *self, const void *buf, int len); #endif /* __SSPISVCS_H__ */ psqlodbc-09.03.0300/gsssvcs.c000644 001752 000000 00000015700 12335653444 016042 0ustar00saitowheel000000 000000 #ifndef WIN32 #include "config.h" #endif /* WIN32 */ #ifdef USE_GSS #if defined(WIN32) && defined( _MSC_VER) #ifdef _WIN64 #pragma comment(lib, "gssapi64") #else #pragma comment(lib, "gssapi32") #endif /* _WIN64 */ #endif /* WIN32 */ #include "connection.h" #ifdef _WIN64 CSTR GSSAPIDLL = "gssapi64"; #else CSTR GSSAPIDLL = "gssapi32"; #endif /* _WIN64 */ #include "socket.h" #include "environ.h" #ifndef MAXHOSTNAMELEN #include #endif #ifndef STATUS_ERROR #define STATUS_ERROR (-1) #endif #ifndef STATUS_OK #define STATUS_OK (0) #endif /* * GSSAPI authentication system. */ #if defined(WIN32) && !defined(_MSC_VER) /* * MIT Kerberos GSSAPI DLL doesn't properly export the symbols for MingW * that contain the OIDs required. Redefine here, values copied * from src/athena/auth/krb5/src/lib/gssapi/generic/gssapi_generic.c */ static const gss_OID_desc GSS_C_NT_HOSTBASED_SERVICE_desc = {10, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x01\x04"}; static GSS_DLLIMP gss_OID GSS_C_NT_HOSTBASED_SERVICE = &GSS_C_NT_HOSTBASED_SERVICE_desc; #endif /* * Fetch all errors of a specific type and append to "str". */ static void pg_GSS_error_int(ConnectionClass *conn, const char *mprefix, OM_uint32 stat, int type) { char *errmsg, *nerrmsg; size_t alclen; OM_uint32 lmaj_s, lmin_s; gss_buffer_desc lmsg; OM_uint32 msg_ctx = 0; do { lmaj_s = gss_display_status(&lmin_s, stat, type, GSS_C_NO_OID, &msg_ctx, &lmsg); errmsg = CC_get_errormsg(conn); alclen = strlen(errmsg) + strlen(mprefix) + 2 + strlen(lmsg.value) + strlen("\n") + 1; nerrmsg = malloc(alclen); snprintf(nerrmsg, alclen, "%s%s: %s\n", errmsg, mprefix, (char *) lmsg.value); CC_set_errormsg(conn, nerrmsg); free(nerrmsg); gss_release_buffer(&lmin_s, &lmsg); } while (msg_ctx); } /* * GSSAPI errors contain two parts; put both into conn->errorMessage. */ static void pg_GSS_error(const char *mprefix, ConnectionClass *conn, OM_uint32 maj_stat, OM_uint32 min_stat) { CC_set_errormsg(conn, ""); /* Fetch major error codes */ pg_GSS_error_int(conn, mprefix, maj_stat, GSS_C_GSS_CODE); /* Add the minor codes as well */ pg_GSS_error_int(conn, mprefix, min_stat, GSS_C_MECH_CODE); } /* * Continue GSS authentication with next token as needed. */ int pg_GSS_continue(ConnectionClass *conn, Int4 inlen) { SocketClass *sock = CC_get_socket(conn); OM_uint32 maj_stat, min_stat, lmin_s; gss_buffer_desc ginbuf, goutbuf; ginbuf.length = 0; mylog("!!! %s inlen=%d in\n", __FUNCTION__, inlen); if (sock->gctx != GSS_C_NO_CONTEXT) { mylog("!!! %s -1\n", __FUNCTION__); if (inlen > 0) { if (NULL == (ginbuf.value = malloc(inlen))) { CC_set_error(conn, CONN_NO_MEMORY_ERROR, "realloc error during autehntication", __FUNCTION__); return STATUS_ERROR; } mylog("!!! %s -2\n", __FUNCTION__); ginbuf.length = inlen; SOCK_get_n_char(conn->sock, ginbuf.value, inlen); if (0 != SOCK_get_errcode(conn->sock)) { CC_set_error(conn, CONN_INVALID_AUTHENTICATION, "communication error during autehntication", __FUNCTION__); free(ginbuf.value); return STATUS_ERROR; } } } mylog("!!! %s 0\n", __FUNCTION__); maj_stat = gss_init_sec_context(&min_stat, GSS_C_NO_CREDENTIAL, &sock->gctx, sock->gtarg_nam, GSS_C_NO_OID, GSS_C_MUTUAL_FLAG, 0, GSS_C_NO_CHANNEL_BINDINGS, (sock->gctx == GSS_C_NO_CONTEXT) ? GSS_C_NO_BUFFER : &ginbuf, NULL, &goutbuf, NULL, NULL); mylog("!!! %s 1\n", __FUNCTION__); if (ginbuf.length != 0) { free(ginbuf.value); ginbuf.length = 0; } mylog("!!! %s 1-1 outlen=%d\n", __FUNCTION__, goutbuf.length); if (goutbuf.length != 0) { SocketClass *sock = conn->sock; int slen; /* * GSS generated data to send to the server. We don't care if it's the * first or subsequent packet, just send the same kind of password * packet. */ mylog("!!! %s 2\n", __FUNCTION__); if (PROTOCOL_74(&(conn->connInfo))) SOCK_put_char(sock, 'p'); slen = goutbuf.length; SOCK_put_int(sock, slen + 4, 4); SOCK_put_n_char(sock, goutbuf.value, slen); SOCK_flush_output(sock); gss_release_buffer(&lmin_s, &goutbuf); goutbuf.length = 0; if (0 != SOCK_get_errcode(sock)) { mylog("!!! %s 3\n", __FUNCTION__); CC_set_error(conn, CONN_INVALID_AUTHENTICATION, "communication error during autehntication", __FUNCTION__); } } mylog("!!! %s maj_stat=%d\n", __FUNCTION__, maj_stat); if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) { mylog("!!! %s 5\n", __FUNCTION__); pg_GSS_error("GSSAPI continuation error", conn, maj_stat, min_stat); gss_release_name(&lmin_s, &sock->gtarg_nam); if (sock->gctx) gss_delete_sec_context(&lmin_s, &sock->gctx, GSS_C_NO_BUFFER); return STATUS_ERROR; } mylog("!!! %s 6\n", __FUNCTION__); if (maj_stat == GSS_S_COMPLETE) gss_release_name(&lmin_s, &sock->gtarg_nam); return STATUS_OK; } /* * This is needed to make /Delayload:gssapi32(64).dll possible * under Windows. */ static gss_OID get_c_nt_hostbased_service() { #if defined(WIN32) && defined(_MSC_VER) static FARPROC proc = NULL; shortterm_common_lock(); if (NULL == proc) { HMODULE hmodule = GetModuleHandle(GSSAPIDLL); if (NULL != hmodule) proc = GetProcAddress(hmodule, "GSS_C_NT_HOSTBASED_SERVICE"); } shortterm_common_unlock(); if (NULL != proc) return *((gss_OID *) proc); return 0; #else return GSS_C_NT_HOSTBASED_SERVICE; #endif } /* * Send initial GSS authentication token */ int pg_GSS_startup(ConnectionClass *conn, void *opt) { SocketClass *sock = CC_get_socket(conn); OM_uint32 maj_stat, min_stat; gss_buffer_desc temp_gbuf; mylog("!!! %s in\n", __FUNCTION__); if (sock->gctx) { char mesg[100]; mylog("!!! %s 0\n", __FUNCTION__); snprintf(mesg, sizeof(mesg), "duplicate GSS authentication request"); CC_set_error(conn, CONN_INVALID_AUTHENTICATION, mesg, __FUNCTION__); free(opt); return STATUS_ERROR; } mylog("!!! %s 2\n", __FUNCTION__); /* * Import service principal name so the proper ticket can be acquired by * the GSSAPI system. */ temp_gbuf.value = (char *) opt; temp_gbuf.length = strlen(temp_gbuf.value); mylog("!!! temp_gbuf.value=%s\n", temp_gbuf.value); maj_stat = gss_import_name(&min_stat, &temp_gbuf, // GSS_C_NT_HOSTBASED_SERVICE, get_c_nt_hostbased_service(), &sock->gtarg_nam); free(temp_gbuf.value); if (maj_stat != GSS_S_COMPLETE) { mylog("!!! %s 3\n", __FUNCTION__); pg_GSS_error("GSSAPI name import error", conn, maj_stat, min_stat); return STATUS_ERROR; } mylog("!!! %s 4\n", __FUNCTION__); /* * Initial packet is the same as a continuation packet with no initial * context. */ sock->gctx = GSS_C_NO_CONTEXT; return pg_GSS_continue(conn, 0); } void pg_GSS_cleanup(SocketClass *sock) { OM_uint32 min_s; if (sock->gctx) { gss_delete_sec_context(&min_s, &sock->gctx, GSS_C_NO_BUFFER); } if (sock->gtarg_nam) { gss_release_name(&min_s, &sock->gtarg_nam); } } #endif /* USE_GSS */ psqlodbc-09.03.0300/gsssvcs.h000644 001752 000000 00000000274 12335653444 016047 0ustar00saitowheel000000 000000 #ifdef USE_GSS int pg_GSS_continue(ConnectionClass *conn, Int4 inlen); int pg_GSS_startup(ConnectionClass *conn, void *opt); void pg_GSS_cleanup(SocketClass *sock); #endif /* USE_GSS */ psqlodbc-09.03.0300/buildx64.ps1000644 001752 000000 00000003104 12335653444 016264 0ustar00saitowheel000000 000000 # build 64bit dll Param( [string]$target="ALL", [string]$configPath ) $scriptPath = (Split-Path $MyInvocation.MyCommand.Path) $configInfo = & "$scriptPath\winbuild\configuration.ps1" "$configPath" $x64info = $configInfo.Configuration.x64 pushd $scriptPath if ($x64info.setvcvars -ne "") { $envcmd = [String] $x64info.setvcvars Write-Host "setvcvars :" $envcmd Invoke-Expression $envcmd } $USE_LIBPQ=$x64info.use_libpq $LIBPQVER=$x64info.libpq.version if ($LIBPQVER -eq "") { $LIBPQVER = $LIBPQ_VERSION } $USE_SSPI=$x64info.use_sspi $USE_GSS=$x64info.use_gss $PG_INC=$x64info.libpq.include $PG_LIB=$x64info.libpq.lib $SSL_INC=$x64info.ssl.include $SSL_LIB=$x64info.ssl.lib $GSS_INC=$x64info.gss.include $GSS_LIB=$x64info.gss.lib $BUILD_MACROS=$x64info.build_macros if ($USE_LIBPQ -eq "yes") { if ($env:PROCESSOR_ARCHITECTURE -eq "x86") { $pgmfs = "" } else { $pgmfs = "$env:ProgramFiles" } if ($PG_INC -eq "default") { $PG_INC = "$pgmfs\PostgreSQL\$LIBPQVER\include" } if ($PG_LIB -eq "default") { $PG_LIB = "$pgmfs\PostgreSQL\$LIBPQVER\lib" } } Write-Host "USE LIBPQ : $USE_LIBPQ ($PG_INC $PG_LIB)" Write-Host "USE GSS : $USE_GSS ($GSS_INC $GSS_LIB)" Write-Host "USE SSPI : $USE_SSPI" Write-Host "SSL DIR : ($SSL_INC $SSL_LIB)" $MACROS = "USE_LIBPQ=$USE_LIBPQ USE_SSPI=$USE_SSPI USE_GSS=$USE_GSS PG_LIB=`"$PG_LIB`" PG_INC=`"$PG_INC`" SSL_LIB=`"$SSL_LIB`" SSL_INC=`"$SSL_INC`" GSS_LIB=`"$GSS_LIB`" GSS_INC=`"$GSS_INC`" $BUILD_MACROS" invoke-expression "nmake.exe /f win64.mak $MACROS $target" invoke-expression "nmake.exe /f win64.mak ANSI_VERSION=yes $MACROS $target" popd psqlodbc-09.03.0300/buildx86.ps1000644 001752 000000 00000002664 12335653444 016302 0ustar00saitowheel000000 000000 # build 32bit dll Param( [string]$target="ALL", [string]$configPath ) $scriptPath = (Split-Path $MyInvocation.MyCommand.Path) $configInfo = & "$scriptPath\winbuild\configuration.ps1" "$configPath" $x86info = $configInfo.Configuration.x86 pushd $scriptPath if ($x86info.setvcvars -ne "") { $envcmd = [String] $x86info.setvcvars Write-Host "setvcvars :" $envcmd Invoke-Expression $envcmd } $USE_LIBPQ=$x86info.use_libpq $USE_SSPI=$x86info.use_sspi $LIBPQVER=$x86info.libpq.version if ($LIBPQVER -eq "") { $LIBPQVER=$LIBPQ_VERSION } $PG_INC=$x86info.libpq.include $PG_LIB=$x86info.libpq.lib $SSL_INC=$x86info.ssl.include $SSL_LIB=$x86info.ssl.lib $BUILD_MACROS=$x86info.build_macros if ($USE_LIBPQ -eq "yes") { if ($env:PROCESSOR_ARCHITECTURE -eq "x86") { $pgmfs = "$env:ProgramFiles" } else { $pgmfs = "${env:ProgramFiles(x86)}" } if ($PG_INC -eq "default") { $PG_INC = "$pgmfs\PostgreSQL\$LIBPQVER\include" } if ($PG_LIB -eq "default") { $PG_LIB = "$pgmfs\PostgreSQL\$LIBPQVER\lib" } } Write-Host "USE LIBPQ : $USE_LIBPQ ($PG_INC $PG_LIB)" # Write-Host "USE GSS : $USE_GSS" Write-Host "USE SSPI : $USE_SSPI" Write-Host "SSL : ($SSL_INC $SSL_LIB)" $MACROS = "USE_LIBPQ=$USE_LIBPQ USE_SSPI=$USE_SSPI PG_LIB=`"$PG_LIB`" PG_INC=`"$PG_INC`" SSL_LIB=`"$SSL_LIB`" SSL_INC=`"$SSL_INC`" $BUILD_MACROS" invoke-expression "nmake.exe /f win32.mak $MACROS $target" invoke-expression "nmake.exe /f win32.mak ANSI_VERSION=yes $MACROS $target" popd psqlodbc-09.03.0300/winbuild/BuildAll.ps1000644 001752 000000 00000021263 12335653444 020136 0ustar00saitowheel000000 000000 <# .SYNOPSIS Build all dlls of psqlodbc project using MSbuild. .DESCRIPTION Build psqlodbc35w.dll, psqlodbc30a.dll, pgenlist.dll, pgenlista.dll and pgxalib.dll for both x86 and x64 platforms. .PARAMETER Target Specify the target of MSBuild. "Build"(default), "Rebuild" or "Clean" is available. .PARAMETER VCVersion Visual Studio version is determined automatically unless this option is specified. .PARAMETER Platform Specify build platforms, "both"(default), "Wind32" or "x64" is available. .PARAMETER Toolset MSBuild PlatformToolset is determined automatically unless this option is specified. Currently "v100", "Windows7.1SDK", "v110", "v110_xp", "v120" or "v120_xp" is available. .PARAMETER MSToolsVersion MSBuild ToolsVersion is detemrined automatically unless this option is specified. Currently "4.0" or "12.0" is available. .PARAMETER Configuration Specify "Release"(default) or "Debug". .PARAMETER BuildConfigPath Specify the configuration xml file name if you want to use the configuration file other than standard one. The relative path is relative to the current directory. .EXAMPLE > .\BuildAll Build with default or automatically selected parameters. .EXAMPLE > .\BuildAll Clean Clean all generated files. .EXAMPLE > .\BuildAll -V(CVersion) 11.0 Build using Visual Studio 11.0 environment. .EXAMPLE > .\BuildAll -P(latform) x64 Build only 64bit dlls. .NOTES Author: Hiroshi Inoue Date: Febrary 1, 2014 #> # # build 32bit & 64bit dlls for VC10 or later # Param( [ValidateSet("Build", "Rebuild", "Clean", "info")] [string]$Target="Build", [string]$VCVersion, [ValidateSet("Win32", "x64", "both")] [string]$Platform="both", [string]$Toolset, [ValidateSet("", "4.0", "12.0")] [string]$MSToolsVersion, [ValidateSet("Debug", "Release")] [String]$Configuration="Release", [string]$BuildConfigPath ) function buildPlatform($platinfo, $Platform) { $USE_LIBPQ=$platinfo.use_libpq $LIBPQVER=$platinfo.libpq.version if ($LIBPQVER -eq "") { $LIBPQVER = $LIBPQ_VERSION } $USE_SSPI=$platinfo.use_sspi $USE_GSS=$platinfo.use_gss $PG_INC=$platinfo.libpq.include $PG_LIB=$platinfo.libpq.lib $SSL_INC=$platinfo.ssl.include $SSL_LIB=$platinfo.ssl.lib $GSS_INC=$platinfo.gss.include $GSS_LIB=$platinfo.gss.lib $BUILD_MACROS=$platinfo.build_macros if ($USE_LIBPQ -eq "yes") { if ($Platform -eq "x64") { if ($env:PROCESSOR_ARCHITECTURE -eq "x86") { $pgmfs = "$env:ProgramW6432" } else { $pgmfs = "$env:ProgramFiles" } } else { if ($env:PROCESSOR_ARCHITECTURE -eq "x86") { $pgmfs = "$env:ProgramFiles" } else { $pgmfs = "${env:ProgramFiles(x86)}" } } if ($PG_INC -eq "default") { if ($pgmfs -eq "") { PG_INC="" } else { $PG_INC = "$pgmfs\PostgreSQL\$LIBPQVER\include" } } if ($PG_LIB -eq "default") { if ($pgmfs -eq "") { PG_LIB="" } else { $PG_LIB = "$pgmfs\PostgreSQL\$LIBPQVER\lib" } } } Write-Host "USE LIBPQ : $USE_LIBPQ ($PG_INC $PG_LIB)" Write-Host "USE GSS : $USE_GSS ($GSS_INC $GSS_LIB)" Write-Host "USE SSPI : $USE_SSPI" Write-Host "SSL DIR : ($SSL_INC $SSL_LIB)" $MACROS=@" /p:USE_LIBPQ=$USE_LIBPQ``;USE_SSPI=$USE_SSPI``;USE_GSS=$USE_GSS``;PG_LIB="$PG_LIB"``;PG_INC="$PG_INC"``;SSL_LIB="$SSL_LIB"``;SSL_INC="$SSL_INC"``;GSS_LIB="$GSS_LIB"``;GSS_INC="$GSS_INC" "@ if ($BUILD_MACROS -ne "") { $BUILD_MACROS = $BUILD_MACROS -replace ';', '`;' $BUILD_MACROS = $BUILD_MACROS -replace '"', '`"' $MACROS="$MACROS $BUILD_MACROS" } Write-Debug "MACROS in function = $MACROS" invoke-expression -Command "& `"${msbuildexe}`" ./platformbuild.vcxproj /tv:$MSToolsVersion /p:Platform=$Platform``;Configuration=$Configuration``;PlatformToolset=${Toolset} /t:$target /p:VisualStudioVersion=${VisualStudioVersion} /p:DRIVERVERSION=$DRIVERVERSION ${MACROS}" } $scriptPath = (Split-Path $MyInvocation.MyCommand.Path) $configInfo = & "$scriptPath\configuration.ps1" "$BuildConfigPath" $DRIVERVERSION=$configInfo.Configuration.version pushd $scriptPath $path_save = ${env:PATH} $WSDK71Set="Windows7.1SDK" $refnum="" Write-Debug "VCVersion=$VCVersion $env:VisualStudioVersion" # # Determine VisualStudioVersion # if ("$VCVersion" -eq "") { $VCVersion=$configInfo.Configuration.vcversion } $VisualStudioVersion=$VCVersion if ("$VisualStudioVersion" -eq "") { $VisualStudioVersion = $env:VisualStudioVersion # VC11 or later version of C++ command prompt sets this variable } if ("$VisualStudioVersion" -eq "") { if ("${env:WindowsSDKVersionOverride}" -eq "v7.1") { # SDK7.1+ command prompt $VisualStudioVersion = "10.0" } elseif ("${env:VCInstallDir}" -ne "") { # C++ command prompt if ("${env:VCInstallDir}" -match "Visual Studio\s*(\S+)\\VC\\$") { $VisualStudioVersion = $matches[1] } } } # neither C++ nor SDK prompt if ("$VisualStudioVersion" -eq "") { if ("${env:VS100COMNTOOLS}" -ne "") { # VC10 or SDK 7.1 is installed (current official) $VisualStudioVersion = "10.0" } elseif ("${env:VS120COMNTOOLS}" -ne "") { # VC12 is installed $VisualStudioVersion = "12.0" } elseif ("${env:VS110COMNTOOLS}" -ne "") { # VC11 is installed $VisualStudioVersion = "11.0" } else { Write-Error "Visual Studio >= 10.0 not found" -Category InvalidArgument;return } } elseif ([int]::TryParse($VisualStudioVersion, [ref]$refnum)) { $VisualStudioVersion="${refnum}.0" } # Check VisualStudioVersion and prepare for ToolsVersion switch ($VisualStudioVersion) { "10.0" { $tv = "4.0" } "11.0" { $tv = "4.0" } "12.0" { $tv = "12.0" } default { Write-Error "Selected Visual Stuidio is Version ${VisualStudioVersion}. Please use VC10 or later" -Category InvalidArgument; return } } # # Determine ToolsVersion # if ("$MSToolsVersion" -eq "") { $MSToolsVersion=$env:ToolsVersion } if ("$MSToolsVersion" -eq "") { $MSToolsVersion = $tv } elseif ([int]::TryParse($MSToolsVersion, [ref]$refnum)) { $MSToolsVersion="${refnum}.0" } # # Determine MSBuild executable # Write-Debug "ToolsVersion=$MSToolsVersion VisualStudioVersion=$VisualStudioVersion" try { $msbver = invoke-expression "msbuild /ver /nologo" if ("$msbver" -match "^(\d+)\.(\d+)") { $major1 = [int] $matches[1] $minor1 = [int] $matches[2] if ($MSToolsVersion -match "^(\d+)\.(\d+)") { $bavail = $false $major2 = [int] $matches[1] $minor2 = [int] $matches[2] if ($major1 -gt $major2) { Write-Debug "$major1 > $major2" $bavail = $true } elseif ($major1 -eq $major2 -And $minor1 -ge $minor2) { Write-Debug "($major1, $minor1) >= ($major2, $minor2)" $bavail = $true } if ($bavail) { $msbuildexe = "MSBuild" } } } } catch {} if ("$msbuildexe" -eq "") { $msbindir="" $regKey="HKLM:\Software\Wow6432Node\Microsoft\MSBuild\ToolsVersions\${MSToolsVersion}" if (Test-Path -path $regkey) { $msbitem=Get-ItemProperty $regKey if ($msbitem -ne $null) { $msbindir=$msbitem.MSBuildToolsPath } } else { $regKey="HKLM:\Software\Microsoft\MSBuild\ToolsVersions\${MSToolsVersion}" if (Test-Path -path $regkey) { $msbitem=Get-ItemProperty $regKey if ($msbitem -ne $null) { $msbindir=$msbitem.MSBuildToolsPath } } else { Write-Error "MSBuild ToolsVersion $MSToolsVersion not Found" -Category NotInstalled; return } } $msbuildexe = "$msbindir\msbuild" } # # Determine PlatformToolset # if ("$Toolset" -eq "") { $Toolset=$configInfo.Configuration.toolset } if ("$Toolset" -eq "") { $Toolset=$env:PlatformToolset } if ("$Toolset" -eq "") { switch ($VisualStudioVersion) { "10.0" { if (Test-path "HKLM:\Software\Microsoft\Microsoft SDKs\Windows\v7.1") { $Toolset=$WSDK71Set } else { $Toolset="v100" } } "11.0" {$Toolset="v110_xp"} "12.0" {$Toolset="v120_xp"} } } # avoid a bug of Windows7.1SDK PlatformToolset if ($Toolset -eq $WSDK71Set) { $env:TARGET_CPU="" } $recordResult = $true try { # # build 32bit dlls # if ($Platform -ieq "Win32" -or $Platform -ieq "both") { buildPlatform $configInfo.Configuration.x86 "Win32" if ($LastExitCode -ne 0) { $recordResult = $false } } # # build 64bit dlls # if ($Platform -ieq "x64" -or $Platform -ieq "both") { buildPlatform $configInfo.Configuration.x64 "x64" if ($LastExitCode -ne 0) { $recordResult = $false } } # # Write the result to configuration xml # if ($recordResult) { $configInfo.Configuration.BuildResult.Date=[string](Get-Date) $configInfo.Configuration.BuildResult.VisualStudioVersion=$VisualStudioVersion $configInfo.Configuration.BuildResult.PlatformToolset=$Toolset $configInfo.Configuration.BuildResult.ToolsVersion=$MSToolsVersion $configInfo.Configuration.BuildResult.Platform=$Platform SaveConfiguration $configInfo } } catch { $error[0] | Format-List -Force } Write-Host "ToolsVersion=$MSToolsVersion VisualStudioVersion=$VisualStudioVersion PlatformToolset=$Toolset" $env:PATH = $path_save popd psqlodbc-09.03.0300/winbuild/configuration.ps1000644 001752 000000 00000005260 12335653444 021314 0ustar00saitowheel000000 000000 Param( [string]$configPath ) function InitConfiguration($savePath = $configurationXmlPath) { $configInfo = [xml](Get-Content "$configurationTemplatePath") if ($env:PROCESSOR_ARCHITECTURE -eq "x86") { $x64info = $configInfo.Configuration.x64 $x64info.libpq.include = "" $x64info.libpq.lib = "" $x64info.libpq.bin = "" } $configInfo.save("$savePath") return $configInfo } function global:GetConfiguration($loadPath = $configurationXmlPath) { $configInfo = [xml] (Get-Content "$loadPath") set-variable -name xmlFormatVersion -value "0.3" -option constant if ($configInfo.Configuration.formatVersion -ne $xmlFormatVersion) { $xmlDoc2 = [xml](Get-Content "$configurationTemplatePath") $root2 = $XmlDoc2.get_DocumentElement() $root1 = $configInfo.get_DocumentElement() unifyNodes $root1 $root2 $root1.formatVersion = $xmlFormatVersion $configInfo.save("$loadPath") } return $configInfo } function global:SaveConfiguration($configInfo, $savePath = $configurationXmlPath) { $configInfo.save("$savePath") } function global:unifyNodes($node1, $node2) { $attributes2 = $node2.get_Attributes() if ($attributes2.Count -gt 0) { $attributes1 = $node1.get_Attributes() foreach ($attrib in $attributes2) { $attribname = $attrib.name if (($attributes1.Count -eq 0) -or ($attributes1.GetNamedItem($attribname) -eq $null)) { Write-Debug " Adding attribute=$attribname" $addattr = $node1.OwnerDocument.ImportNode($attrib, $true) $added = $attributes1.Append($addattr) } } } if (!$node2.get_HasChildNodes()) { return; } foreach ($child2 in $node2.get_ChildNodes()) { $nodename = $child2.get_Name() if ($nodename -eq "#text"){ continue } $matchnode = $node1.SelectSingleNode($nodename) if ($matchnode -eq $null) { Write-Debug "Adding node=$nodename" $addnode = $node1.OwnerDocument.ImportNode($child2, $true) $added = $node1.AppendChild($addnode) continue } unifyNodes $matchnode $child2 } } Write-Debug "configPath=$configPath" $global:LIBPQ_VERSION="9.3" $scriptPath = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition) $global:configurationTemplatePath = "$scriptPath\configuration_template.xml" $global:configurationXmlPath = $configPath if ($configurationXmlPath -eq "") { $global:configurationXmlPath = "$scriptPath\configuration.xml" } if (!(Test-Path -path $configurationXmlPath)) { InitConfiguration } else { GetConfiguration } Return psqlodbc-09.03.0300/winbuild/configuration_template.xml000644 001752 000000 00000002252 12335653444 023302 0ustar00saitowheel000000 000000 default default default default default default psqlodbc-09.03.0300/winbuild/editConfiguration.ps1000644 001752 000000 00000046440 12335653444 022127 0ustar00saitowheel000000 000000 # Powershell needs to run in STA mode to display WPF windows Param( [string]$configPath ) if ([Threading.Thread]::CurrentThread.GetApartmentState() -eq "MTA"){ PowerShell -Sta -File $MyInvocation.MyCommand.Path return } <# Edit the configuration xnl file with WPF #> Add-Type -AssemblyName presentationframework [xml]$XAML = @'