psqlodbc-13.02.0000/000755 001751 001751 00000000000 14122576775 015102 5ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/config/000755 001751 001751 00000000000 14122576774 016346 5ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/docs/000755 001751 001751 00000000000 14122576775 016032 5ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/installer/000755 001751 001751 00000000000 14122576775 017077 5ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/test/000755 001751 001751 00000000000 14122576775 016061 5ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/winbuild/000755 001751 001751 00000000000 14122576775 016717 5ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/Makefile.am000644 001751 001751 00000006457 14122574535 017142 0ustar00hiroshihiroshi000000 000000 #------------------------------------------------------------------------- # # Makefile.am for psqlodbc30w (PostgreSQL ODBC driver) # #------------------------------------------------------------------------- AUTOMAKE_OPTIONS = 1.8 foreign ACLOCAL_AMFLAGS = -I config lib_LTLIBRARIES = psqlodbcw.la psqlodbca.la AM_LDFLAGS = -module -no-undefined -avoid-version -export-symbols-regex '^SQL' psqlodbcw_la_CFLAGS = -DUNICODE_SUPPORT # -DUNICODE_SUPPORTXX psqlodbca_la_SOURCES = \ info.c bind.c columninfo.c connection.c convert.c drvconn.c \ environ.c execute.c lobj.c misc.c options.c \ pgtypes.c psqlodbc.c qresult.c results.c parse.c \ statement.c tuple.c dlg_specific.c \ multibyte.c odbcapi.c descriptor.c \ odbcapi30.c pgapi30.c mylog.c \ \ bind.h catfunc.h columninfo.h connection.h convert.h \ descriptor.h dlg_specific.h environ.h unicode_support.h \ lobj.h misc.h multibyte.h pgapifunc.h pgtypes.h \ psqlodbc.h qresult.h resource.h statement.h tuple.h \ version.h pgenlist.h mylog.h xalibname.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 \ windows-defaults.mak buildInstallers.bat regress.bat \ pgenlist.def pgenlista.def connexp.h \ dlg_wingui.c loadlib.c loadlib.h inouealc.c win_setup.h \ psqlsetup.c setup.c win_unicode.c psqlodbc.rc win64.mak \ psqlodbc.reg psqlodbc.dsp psqlodbc.vcproj \ psqlodbc.sln msdtc_enlist.cpp pgxalib.cpp xalibname.c \ pgxalib.def psqlsetup.def psqlsetupa.def odbc.sql odbc-drop.sql \ \ 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 \ docs/msdtc_pgxalib_tracing_enable.reg \ docs/msdtc_pgxalib_tracing_disable.reg \ docs/msdtc_pgxalib_tracing_README.txt \ docs/editConfiguration.jpg \ \ installer/background.bmp \ installer/banner.bmp \ installer/buildInstallers.ps1 \ installer/installer.mak \ installer/lgpl.rtf \ installer/modify_msi.vbs \ installer/productcodes.mak \ installer/psqlodbc-setup \ installer/README.txt \ installer/psqlodbcm_cpu.wxs \ installer/psqlodbc_cpu.wxs \ installer/psqlodbc-setup/buildBootstrapper.ps1 \ installer/psqlodbc-setup/Bundle.wxs \ installer/psqlodbc-setup/Make.bat \ installer/psqlodbc-setup/psqlodbc-setup.wixproj \ installer/psqlodbc-setup/vcredist.wxs \ \ winbuild/BuildAll.ps1 \ winbuild/platformbuild.vcxproj \ winbuild/MSProgram-Get.psm1 \ winbuild/psqlodbc.Cpp.props \ winbuild/Psqlodbc-config.psm1 \ winbuild/psqlodbc.vcxproj \ winbuild/configuration_template.xml \ winbuild/psqlsetup.vcxproj \ winbuild/editConfiguration.ps1 \ winbuild/readme.txt \ winbuild/pgenlist.vcxproj \ winbuild/regress.ps1 \ winbuild/pguser.Cpp.props \ winbuild/regress_one.vcxproj \ winbuild/pgxalib.vcxproj \ winbuild/std_dbmsname.Cpp.props \ \ test/Makefile.in \ test/odbcini-gen.sh \ test/README.txt \ test/RegisterRegdsn.c \ test/reset-db.c \ test/runsuite.c \ test/sampletables.sql \ test/tests \ test/win.mak \ test/expected \ test/src 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-13.02.0000/configure000755 001751 001751 00001602026 14122576746 017016 0ustar00hiroshihiroshi000000 000000 #! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for psqlodbc 13.02.0000. # # 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 \$(( 1 + 1 )) = 2 || 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" 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='13.02.0000' PACKAGE_STRING='psqlodbc 13.02.0000' 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='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS LIBOBJS OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB ac_ct_AR AR LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP SED LIBTOOL OBJDUMP DLLTOOL AS host_os host_vendor host_cpu host build_os build_vendor build_cpu build PROVE PG_CONFIG LIBODBC ODBC_CONFIG EGREP GREP CPP GCC_FALSE GCC_TRUE am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep 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_BACKSLASH AM_DEFAULT_VERBOSITY AM_DEFAULT_V AM_V 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_silent_rules enable_maintainer_mode enable_dependency_tracking with_unixodbc with_iodbc with_libpq 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 13.02.0000 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 13.02.0000:";; 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-silent-rules less verbose build output (undo: "make V=1") --disable-silent-rules verbose build output (undo: "make V=0") --enable-maintainer-mode enable make rules and dependencies not useful (and sometimes confusing) to the casual installer --enable-dependency-tracking do not reject slow dependency extractors --disable-dependency-tracking speeds up one-time build --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] DIR is the PostgreSQL base install directory or the path to pg_config --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 13.02.0000 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_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_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 (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_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_check_type LINENO TYPE VAR INCLUDES # ------------------------------------------- # Tests whether TYPE exists after having included INCLUDES, setting cache # variable VAR accordingly. ac_fn_c_check_type () { 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 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_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_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_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 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 13.02.0000, 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.15' # 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; } # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; esac # 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 ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file 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 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 if test "$2" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done 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; } # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi rm -f conftest.file 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` if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " 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 if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # 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" { $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; } 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 # Check whether --enable-silent-rules was given. if test "${enable_silent_rules+set}" = set; then : enableval=$enable_silent_rules; fi case $enable_silent_rules in # ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=1;; esac am_make=${MAKE-make} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 $as_echo_n "checking whether $am_make supports nested variables... " >&6; } if ${am_cv_make_support_nested_variables+:} false; then : $as_echo_n "(cached) " >&6 else if $as_echo 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 $as_echo "$am_cv_make_support_nested_variables" >&6; } if test $am_cv_make_support_nested_variables = yes; then AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AM_BACKSLASH='\' 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='13.02.0000' 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"} # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # mkdir_p='$(MKDIR_P)' # We need awk for the "check" target (and possibly the TAP driver). The # system "awk" is bad on some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar pax cpio none' am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 fi fi 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 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 whether $CC understands -c and -o together" >&5 $as_echo_n "checking whether $CC understands -c and -o together... " >&6; } if ${am_cv_prog_cc_c_o+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 $as_echo "$am_cv_prog_cc_c_o" >&6; } if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" 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 this is the am__doit target .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 # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac 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='\' am__nodep='_no' 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". rm -rf conftest.dir 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 am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac 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 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # 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. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; 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 ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj 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 $am__obj 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 # All AC_CHECK_SIZEOF() or AC_CHECK_TYPES() calls were move from 4. # unixODBC wants the following to get sane behavior for ODBCINT64 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 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 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 # 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 long int" >&5 $as_echo_n "checking size of long int... " >&6; } if ${ac_cv_sizeof_long_int+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long int))" "ac_cv_sizeof_long_int" "$ac_includes_default"; then : else if test "$ac_cv_type_long_int" = 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 int) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_long_int=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_int" >&5 $as_echo "$ac_cv_sizeof_long_int" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_LONG_INT $ac_cv_sizeof_long_int _ACEOF # for unixODBC # 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 # Check if "-Wall" is valid if test -n "$GCC" && test "$ac_test_CFLAGS" != set; then { $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_SAVE="${CFLAGS}" CFLAGS="${CFLAGS} -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; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } CFLAGS="${CFLAGS_SAVE}" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext 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 ! -x "${ODBC_CONFIG}/bin/iodbc-config"; then if test ! -x "${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 wo_odbc_config=__without_odbc_config 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 "${ODBC_CONFIG}" = "${wo_odbc_config}"; then : elif test ! -x "${ODBC_CONFIG}/bin/odbc_config"; then if test ! -x "${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}" LIBODBC=`${ODBC_CONFIG} --libs` # for regression test elif test "${ODBC_CONFIG}" = "${wo_odbc_config}"; then ODBC_INCLUDE=/usr/include CPPFLAGS="$CPPFLAGS -I${ODBC_INCLUDE}" ODBC_LIBDiR="" LIBODBC="-lodbc" # for regression test else ODBC_INCLUDE=`${ODBC_CONFIG} --include-prefix` CPPFLAGS="$CPPFLAGS -I${ODBC_INCLUDE}" # Linking libodbc is rather problematic ODBC_LIBDIR=`${ODBC_CONFIG} --lib-prefix` if test "${ODBC_LIBDIR}" != ""; then LDFLAGS="$LDFLAGS -L${ODBC_LIBDIR}" fi LIBODBC=`${ODBC_CONFIG} --libs` # for regression test fi { $as_echo "$as_me:${as_lineno-$LINENO}: using $ODBC_INCLUDE $ODBC_LIBDIR" >&5 $as_echo "$as_me: using $ODBC_INCLUDE $ODBC_LIBDIR" >&6;} { $as_echo "$as_me:${as_lineno-$LINENO}: using $LIBODBC for regression test" >&5 $as_echo "$as_me: using $LIBODBC for regression test" >&6;} fi # # SQLCOLATTRIBUTE_SQLLEN check # { $as_echo "$as_me:${as_lineno-$LINENO}: checking last argument to SQLColAttribute is SQLLEN *" >&5 $as_echo_n "checking last argument to SQLColAttribute is SQLLEN *... " >&6; } 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 *NumericAttribute) { SQLLEN t = 1; *NumericAttribute = t; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : $as_echo "#define SQLCOLATTRIBUTE_SQLLEN 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_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_fn_error $? "libpq is mandatory, --without-libpq is no longer supported" "$LINENO" 5 fi if test "$with_libpq" != yes; then if test -d "$with_libpq"; then PATH="$with_libpq/bin:$PATH" CPPFLAGS="$CPPFLAGS -I$with_libpq/include -I$with_libpq/include/postgresql/internal" 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 # # 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 -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_pkg_includedir=`"$PG_CONFIG" --pkgincludedir` pg_libdir=`"$PG_CONFIG" --libdir` CPPFLAGS="$CPPFLAGS -I$pg_includedir -I$pg_pkg_includedir/internal" LDFLAGS="$LDFLAGS -L$pg_libdir" fi # 1. Programs # 'prove' is used to pretty-print regression test results, if available. for ac_prog in prove 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_PROVE+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$PROVE"; then ac_cv_prog_PROVE="$PROVE" # 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_PROVE="$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 PROVE=$ac_cv_prog_PROVE if test -n "$PROVE"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PROVE" >&5 $as_echo "$PROVE" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$PROVE" && break done # 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 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 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 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQsetSingleRowMode in -lpq" >&5 $as_echo_n "checking for PQsetSingleRowMode in -lpq... " >&6; } if ${ac_cv_lib_pq_PQsetSingleRowMode+:} 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 PQsetSingleRowMode (); int main () { return PQsetSingleRowMode (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pq_PQsetSingleRowMode=yes else ac_cv_lib_pq_PQsetSingleRowMode=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_PQsetSingleRowMode" >&5 $as_echo "$ac_cv_lib_pq_PQsetSingleRowMode" >&6; } if test "x$ac_cv_lib_pq_PQsetSingleRowMode" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPQ 1 _ACEOF LIBS="-lpq $LIBS" else as_fn_error $? "libpq library version >= 9.2 is required" "$LINENO" 5 fi # 3. Header files for ac_header in locale.h sys/time.h uchar.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 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 { $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(all members were moved to 0.) # 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 # 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 mbstowcs wcstombs mbrtoc16 c16rtomb 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 for ac_func in PQsslInUse do : ac_fn_c_check_func "$LINENO" "PQsslInUse" "ac_cv_func_PQsslInUse" if test "x$ac_cv_func_PQsslInUse" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_PQSSLINUSE 1 _ACEOF fi done 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 # 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= 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 { $as_echo "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5 $as_echo_n "checking that generated files are newer than configure... " >&6; } if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 $as_echo "done" >&6; } if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi 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 : "${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 13.02.0000, 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 13.02.0000 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"" || { # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf 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"` # 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'`; 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-13.02.0000/configure.ac000644 001751 001751 00000016714 14122576423 017367 0ustar00hiroshihiroshi000000 000000 # Process this file with autoconf to produce a configure script. AC_INIT(psqlodbc, 13.02.0000, [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"]) # All AC_CHECK_SIZEOF() or AC_CHECK_TYPES() calls were move from 4. # unixODBC wants the following to get sane behavior for ODBCINT64 AC_CHECK_SIZEOF(long) AC_CHECK_SIZEOF(long int) # for unixODBC AC_CHECK_SIZEOF(void *) AC_CHECK_TYPES([long long]) AC_CHECK_TYPES([signed char]) AC_CHECK_TYPES([ssize_t]) AC_TYPE_SIZE_T # Check if "-Wall" is valid if test -n "$GCC" && test "$ac_test_CFLAGS" != set; then AC_MSG_CHECKING(-Wall is a valid compile option) CFLAGS_SAVE="${CFLAGS}" CFLAGS="${CFLAGS} -Wall" AC_COMPILE_IFELSE([AC_LANG_PROGRAM( [[#include ]], [])], [AC_MSG_RESULT(yes)], [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 ! -x "${ODBC_CONFIG}/bin/iodbc-config"; then if test ! -x "${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 wo_odbc_config=__without_odbc_config 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 "${ODBC_CONFIG}" = "${wo_odbc_config}"; then : elif test ! -x "${ODBC_CONFIG}/bin/odbc_config"; then if test ! -x "${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}" LIBODBC=`${ODBC_CONFIG} --libs` # for regression test elif test "${ODBC_CONFIG}" = "${wo_odbc_config}"; then ODBC_INCLUDE=/usr/include CPPFLAGS="$CPPFLAGS -I${ODBC_INCLUDE}" ODBC_LIBDiR="" LIBODBC="-lodbc" # for regression test else ODBC_INCLUDE=`${ODBC_CONFIG} --include-prefix` CPPFLAGS="$CPPFLAGS -I${ODBC_INCLUDE}" # Linking libodbc is rather problematic ODBC_LIBDIR=`${ODBC_CONFIG} --lib-prefix` if test "${ODBC_LIBDIR}" != ""; then LDFLAGS="$LDFLAGS -L${ODBC_LIBDIR}" fi LIBODBC=`${ODBC_CONFIG} --libs` # for regression test fi AC_MSG_NOTICE([using $ODBC_INCLUDE $ODBC_LIBDIR]) AC_MSG_NOTICE([using $LIBODBC for regression test]) fi AC_SUBST(LIBODBC) # # SQLCOLATTRIBUTE_SQLLEN check # AC_MSG_CHECKING(last argument to SQLColAttribute is SQLLEN *) AC_COMPILE_IFELSE([AC_LANG_SOURCE([[ #include SQLRETURN SQL_API SQLColAttribute(SQLHSTMT StatementHandle, SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier, SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength, SQLLEN *NumericAttribute) { SQLLEN t = 1; *NumericAttribute = t; return 0; } ]])], [AC_DEFINE(SQLCOLATTRIBUTE_SQLLEN, 1, [Define to 1 if SQLColAttribute use SQLLEN]) AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)] ) # # Whether libpq functionalities are used # AC_ARG_WITH(libpq, [ --with-libpq[[=DIR]] DIR is the PostgreSQL base install directory or the path to pg_config], [], [with_libpq=yes]) if test "$with_libpq" = no; then AC_MSG_ERROR([libpq is mandatory, --without-libpq is no longer supported]) fi if test "$with_libpq" != yes; then if test -d "$with_libpq"; then PATH="$with_libpq/bin:$PATH" CPPFLAGS="$CPPFLAGS -I$with_libpq/include -I$with_libpq/include/postgresql/internal" 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 # # 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 -z "$PG_CONFIG"; then AC_PATH_PROGS(PG_CONFIG, pg_config) fi if test -n "$PG_CONFIG"; then pg_includedir=`"$PG_CONFIG" --includedir` pg_pkg_includedir=`"$PG_CONFIG" --pkgincludedir` pg_libdir=`"$PG_CONFIG" --libdir` CPPFLAGS="$CPPFLAGS -I$pg_includedir -I$pg_pkg_includedir/internal" LDFLAGS="$LDFLAGS -L$pg_libdir" fi # 1. Programs # 'prove' is used to pretty-print regression test results, if available. AC_CHECK_PROGS(PROVE, prove) # 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 AC_CHECK_LIB(pq, PQsetSingleRowMode, [], [AC_MSG_ERROR([libpq library version >= 9.2 is required])]) # 3. Header files AC_CHECK_HEADERS(locale.h sys/time.h uchar.h) AC_CHECK_HEADER(libpq-fe.h,,[AC_MSG_ERROR([libpq header not found])]) AC_HEADER_TIME # 4. Types(all members were moved to 0.) # 5. Structures AC_STRUCT_TM # 6. Compiler characteristics AC_C_CONST # 7. Functions, global variables AC_FUNC_STRERROR_R AC_CHECK_FUNCS(strtoul strtoll strlcat mbstowcs wcstombs mbrtoc16 c16rtomb) AC_CHECK_FUNCS(PQsslInUse) 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 # 8. Libltdl This release doesn't need libltdl # AC_CHECK_LIB(ltdl, lt_dlopen) AC_CONFIG_FILES([Makefile test/Makefile]) AC_OUTPUT psqlodbc-13.02.0000/aclocal.m4000644 001751 001751 00000127725 14122576746 016756 0ustar00hiroshihiroshi000000 000000 # generated automatically by aclocal 1.15.1 -*- Autoconf -*- # Copyright (C) 1996-2017 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_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([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-2017 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.15' 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.15.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 AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.15.1])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001-2017 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], [AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl # Expand $ac_aux_dir to an absolute path. am_aux_dir=`cd "$ac_aux_dir" && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997-2017 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_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ([2.52])dnl m4_if([$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 m4_define([_AM_COND_VALUE_$1], [$2])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-2017 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. # 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", "OBJC", "OBJCXX", "UPC", or "GJC". # 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 m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], [$1], [CXX], [depcc="$CXX" am_compiler_list=], [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], [OBJCXX], [depcc="$OBJCXX" 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". rm -rf conftest.dir 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 am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) 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 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # 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. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; 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 ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj 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 $am__obj 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], [dnl AS_HELP_STRING( [--enable-dependency-tracking], [do not reject slow dependency extractors]) AS_HELP_STRING( [--disable-dependency-tracking], [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999-2017 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_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf 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"` # 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'`; 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"]) ]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996-2017 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 macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC]) [_AM_PROG_CC_C_O ]) # 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.65])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], [AC_DIAGNOSE([obsolete], [$0: two- and three-arguments forms are deprecated.]) 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], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]), [ok:ok],, [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]) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # AC_SUBST([mkdir_p], ['$(MKDIR_P)']) # We need awk for the "check" target (and possibly the TAP driver). 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])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) AC_REQUIRE([AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) fi fi dnl The trailing newline in this macro's definition is deliberate, for dnl backward compatibility and to allow trailing 'dnl'-style comments dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. ]) dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # 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-2017 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 if test x"${install_sh+set}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST([install_sh])]) # Copyright (C) 2003-2017 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. # 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-2017 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_MAINTAINER_MODE([DEFAULT-MODE]) # ---------------------------------- # Control maintainer-specific portions of Makefiles. # Default is to disable them, unless 'enable' is passed literally. # For symmetry, 'disable' may be passed as well. Anyway, the user # can override the default with the --enable/--disable switch. AC_DEFUN([AM_MAINTAINER_MODE], [m4_case(m4_default([$1], [disable]), [enable], [m4_define([am_maintainer_other], [disable])], [disable], [m4_define([am_maintainer_other], [enable])], [m4_define([am_maintainer_other], [enable]) m4_warn([syntax], [unexpected argument to AM@&t@_MAINTAINER_MODE: $1])]) AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) dnl maintainer-mode's default is 'disable' unless 'enable' is passed AC_ARG_ENABLE([maintainer-mode], [AS_HELP_STRING([--]am_maintainer_other[-maintainer-mode], am_maintainer_other[ make rules and dependencies not useful (and sometimes confusing) to the casual installer])], [USE_MAINTAINER_MODE=$enableval], [USE_MAINTAINER_MODE=]m4_if(am_maintainer_other, [enable], [no], [yes])) AC_MSG_RESULT([$USE_MAINTAINER_MODE]) AM_CONDITIONAL([MAINTAINER_MODE], [test $USE_MAINTAINER_MODE = yes]) MAINT=$MAINTAINER_MODE_TRUE AC_SUBST([MAINT])dnl ] ) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001-2017 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_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .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 # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac 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-2017 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_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 is modern enough. # If it is, 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 if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= AC_MSG_WARN(['missing' script is too old or missing]) fi ]) # -*- Autoconf -*- # Obsolete and "removed" macros, that must however still report explicit # error messages when used, to smooth transition. # # Copyright (C) 1996-2017 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. AC_DEFUN([AM_CONFIG_HEADER], [AC_DIAGNOSE([obsolete], ['$0': this macro is obsolete. You should use the 'AC][_CONFIG_HEADERS' macro instead.])dnl AC_CONFIG_HEADERS($@)]) AC_DEFUN([AM_PROG_CC_STDC], [AC_PROG_CC am_cv_prog_cc_stdc=$ac_cv_prog_cc_stdc AC_DIAGNOSE([obsolete], ['$0': this macro is obsolete. You should simply use the 'AC][_PROG_CC' macro instead. Also, your code should no longer depend upon 'am_cv_prog_cc_stdc', but upon 'ac_cv_prog_cc_stdc'.])]) AC_DEFUN([AM_C_PROTOTYPES], [AC_FATAL([automatic de-ANSI-fication support has been removed])]) AU_DEFUN([fp_C_PROTOTYPES], [AM_C_PROTOTYPES]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001-2017 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_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], [m4_foreach_w([_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])]) # Copyright (C) 1999-2017 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_CC_C_O # --------------- # Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC # to automatically call this. AC_DEFUN([_AM_PROG_CC_C_O], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([compile])dnl AC_LANG_PUSH([C])dnl AC_CACHE_CHECK( [whether $CC understands -c and -o together], [am_cv_prog_cc_c_o], [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi AC_LANG_POP([C])]) # For backward compatibility. AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) # Copyright (C) 2001-2017 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_RUN_LOG(COMMAND) # ------------------- # Run COMMAND, save the exit status in ac_status, and log it. # (This has been adapted from Autoconf's _AC_RUN_LOG macro.) AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996-2017 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_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac # 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 ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file 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 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 if test "$[2]" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done 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]) # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi AC_MSG_RESULT([done])]) rm -f conftest.file ]) # Copyright (C) 2009-2017 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_SILENT_RULES([DEFAULT]) # -------------------------- # Enable less verbose build rules; with the default set to DEFAULT # ("yes" being less verbose, "no" or empty being verbose). AC_DEFUN([AM_SILENT_RULES], [AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) case $enable_silent_rules in @%:@ ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. dnl See automake bug#9928 and bug#10237. am_make=${MAKE-make} AC_CACHE_CHECK([whether $am_make supports nested variables], [am_cv_make_support_nested_variables], [if AS_ECHO([['TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi]) if test $am_cv_make_support_nested_variables = yes; then dnl Using '$V' instead of '$(V)' breaks IRIX make. AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl ]) # Copyright (C) 2001-2017 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-2017 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]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004-2017 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_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. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar], [# The POSIX 1988 'ustar' format is defined with fixed-size fields. # There is notably a 21 bits limit for the UID and the GID. In fact, # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 # and bug#13588). am_max_uid=2097151 # 2^21 - 1 am_max_gid=$am_max_uid # The $UID and $GID variables are not portable, so we need to resort # to the POSIX-mandated id(1) utility. Errors in the 'id' calls # below are definitely unexpected, so allow the users to see them # (that is, avoid stderr redirection). am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) if test $am_uid -le $am_max_uid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) if test $am_gid -le $am_max_gid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi], [pax], [], [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Go ahead even if we have the value already cached. We do so because we # need to set the values for the 'am__tar' and 'am__untar' variables. _am_tools=${am_cv_prog_tar_$1-$_am_tools} 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/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-13.02.0000/Makefile.in000644 001751 001751 00000200765 14122576747 017160 0ustar00hiroshihiroshi000000 000000 # Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 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@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@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 = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(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) DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ $(am__configure_deps) $(am__DIST_COMMON) 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 CONFIG_CLEAN_VPATH_FILES = 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 = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" 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 misc.lo \ options.lo pgtypes.lo psqlodbc.lo qresult.lo results.lo \ parse.lo statement.lo tuple.lo dlg_specific.lo multibyte.lo \ odbcapi.lo descriptor.lo odbcapi30.lo pgapi30.lo mylog.lo psqlodbca_la_OBJECTS = $(am_psqlodbca_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = psqlodbcw_la_LIBADD = am__objects_1 = psqlodbcw_la-info.lo psqlodbcw_la-bind.lo \ psqlodbcw_la-columninfo.lo psqlodbcw_la-connection.lo \ psqlodbcw_la-convert.lo psqlodbcw_la-drvconn.lo \ psqlodbcw_la-environ.lo psqlodbcw_la-execute.lo \ psqlodbcw_la-lobj.lo psqlodbcw_la-misc.lo \ psqlodbcw_la-options.lo psqlodbcw_la-pgtypes.lo \ psqlodbcw_la-psqlodbc.lo psqlodbcw_la-qresult.lo \ psqlodbcw_la-results.lo psqlodbcw_la-parse.lo \ psqlodbcw_la-statement.lo psqlodbcw_la-tuple.lo \ psqlodbcw_la-dlg_specific.lo psqlodbcw_la-multibyte.lo \ psqlodbcw_la-odbcapi.lo psqlodbcw_la-descriptor.lo \ psqlodbcw_la-odbcapi30.lo psqlodbcw_la-pgapi30.lo \ psqlodbcw_la-mylog.lo am_psqlodbcw_la_OBJECTS = $(am__objects_1) psqlodbcw_la-odbcapi30w.lo \ psqlodbcw_la-odbcapiw.lo psqlodbcw_la-win_unicode.lo psqlodbcw_la_OBJECTS = $(am_psqlodbcw_la_OBJECTS) psqlodbcw_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(psqlodbcw_la_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ depcomp = $(SHELL) $(top_srcdir)/config/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(psqlodbca_la_SOURCES) $(psqlodbcw_la_SOURCES) DIST_SOURCES = $(psqlodbca_la_SOURCES) $(psqlodbcw_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ $(LISP)config.h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags CSCOPE = cscope AM_RECURSIVE_TARGETS = cscope am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(top_srcdir)/config/compile $(top_srcdir)/config/config.guess \ $(top_srcdir)/config/config.sub $(top_srcdir)/config/depcomp \ $(top_srcdir)/config/install-sh $(top_srcdir)/config/ltmain.sh \ $(top_srcdir)/config/missing $(top_srcdir)/test/Makefile.in \ config/compile config/config.guess config/config.sub \ config/depcomp config/install-sh config/ltmain.sh \ config/missing DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best DIST_TARGETS = dist-gzip distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ 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@ LIBODBC = @LIBODBC@ 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@ PROVE = @PROVE@ 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 lib_LTLIBRARIES = psqlodbcw.la psqlodbca.la AM_LDFLAGS = -module -no-undefined -avoid-version -export-symbols-regex '^SQL' psqlodbcw_la_CFLAGS = -DUNICODE_SUPPORT # -DUNICODE_SUPPORTXX psqlodbca_la_SOURCES = \ info.c bind.c columninfo.c connection.c convert.c drvconn.c \ environ.c execute.c lobj.c misc.c options.c \ pgtypes.c psqlodbc.c qresult.c results.c parse.c \ statement.c tuple.c dlg_specific.c \ multibyte.c odbcapi.c descriptor.c \ odbcapi30.c pgapi30.c mylog.c \ \ bind.h catfunc.h columninfo.h connection.h convert.h \ descriptor.h dlg_specific.h environ.h unicode_support.h \ lobj.h misc.h multibyte.h pgapifunc.h pgtypes.h \ psqlodbc.h qresult.h resource.h statement.h tuple.h \ version.h pgenlist.h mylog.h xalibname.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 \ windows-defaults.mak buildInstallers.bat regress.bat \ pgenlist.def pgenlista.def connexp.h \ dlg_wingui.c loadlib.c loadlib.h inouealc.c win_setup.h \ psqlsetup.c setup.c win_unicode.c psqlodbc.rc win64.mak \ psqlodbc.reg psqlodbc.dsp psqlodbc.vcproj \ psqlodbc.sln msdtc_enlist.cpp pgxalib.cpp xalibname.c \ pgxalib.def psqlsetup.def psqlsetupa.def odbc.sql odbc-drop.sql \ \ 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 \ docs/msdtc_pgxalib_tracing_enable.reg \ docs/msdtc_pgxalib_tracing_disable.reg \ docs/msdtc_pgxalib_tracing_README.txt \ docs/editConfiguration.jpg \ \ installer/background.bmp \ installer/banner.bmp \ installer/buildInstallers.ps1 \ installer/installer.mak \ installer/lgpl.rtf \ installer/modify_msi.vbs \ installer/productcodes.mak \ installer/psqlodbc-setup \ installer/README.txt \ installer/psqlodbcm_cpu.wxs \ installer/psqlodbc_cpu.wxs \ installer/psqlodbc-setup/buildBootstrapper.ps1 \ installer/psqlodbc-setup/Bundle.wxs \ installer/psqlodbc-setup/Make.bat \ installer/psqlodbc-setup/psqlodbc-setup.wixproj \ installer/psqlodbc-setup/vcredist.wxs \ \ winbuild/BuildAll.ps1 \ winbuild/platformbuild.vcxproj \ winbuild/MSProgram-Get.psm1 \ winbuild/psqlodbc.Cpp.props \ winbuild/Psqlodbc-config.psm1 \ winbuild/psqlodbc.vcxproj \ winbuild/configuration_template.xml \ winbuild/psqlsetup.vcxproj \ winbuild/editConfiguration.ps1 \ winbuild/readme.txt \ winbuild/pgenlist.vcxproj \ winbuild/regress.ps1 \ winbuild/pguser.Cpp.props \ winbuild/regress_one.vcxproj \ winbuild/pgxalib.vcxproj \ winbuild/std_dbmsname.Cpp.props \ \ test/Makefile.in \ test/odbcini-gen.sh \ test/README.txt \ test/RegisterRegdsn.c \ test/reset-db.c \ test/runsuite.c \ test/sampletables.sql \ test/tests \ test/win.mak \ test/expected \ test/src 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: Makefile @: $(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'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign 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) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @test -f $@ || rm -f stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 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) ($(am__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) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } psqlodbca.la: $(psqlodbca_la_OBJECTS) $(psqlodbca_la_DEPENDENCIES) $(EXTRA_psqlodbca_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) -rpath $(libdir) $(psqlodbca_la_OBJECTS) $(psqlodbca_la_LIBADD) $(LIBS) psqlodbcw.la: $(psqlodbcw_la_OBJECTS) $(psqlodbcw_la_DEPENDENCIES) $(EXTRA_psqlodbcw_la_DEPENDENCIES) $(AM_V_CCLD)$(psqlodbcw_la_LINK) -rpath $(libdir) $(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)/lobj.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)/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)/psqlodbcw_la-bind.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-columninfo.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-connection.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-convert.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-descriptor.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-dlg_specific.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-drvconn.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-environ.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-execute.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-info.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-lobj.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-misc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-multibyte.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-mylog.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-odbcapi.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-odbcapi30.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-odbcapi30w.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-odbcapiw.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-options.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-parse.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-pgapi30.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-pgtypes.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-psqlodbc.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-qresult.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-results.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-statement.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-tuple.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psqlodbcw_la-win_unicode.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)/statement.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tuple.Plo@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< psqlodbcw_la-info.lo: info.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-info.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-info.Tpo -c -o psqlodbcw_la-info.lo `test -f 'info.c' || echo '$(srcdir)/'`info.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-info.Tpo $(DEPDIR)/psqlodbcw_la-info.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='info.c' object='psqlodbcw_la-info.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-info.lo `test -f 'info.c' || echo '$(srcdir)/'`info.c psqlodbcw_la-bind.lo: bind.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-bind.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-bind.Tpo -c -o psqlodbcw_la-bind.lo `test -f 'bind.c' || echo '$(srcdir)/'`bind.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-bind.Tpo $(DEPDIR)/psqlodbcw_la-bind.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='bind.c' object='psqlodbcw_la-bind.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-bind.lo `test -f 'bind.c' || echo '$(srcdir)/'`bind.c psqlodbcw_la-columninfo.lo: columninfo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-columninfo.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-columninfo.Tpo -c -o psqlodbcw_la-columninfo.lo `test -f 'columninfo.c' || echo '$(srcdir)/'`columninfo.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-columninfo.Tpo $(DEPDIR)/psqlodbcw_la-columninfo.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='columninfo.c' object='psqlodbcw_la-columninfo.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-columninfo.lo `test -f 'columninfo.c' || echo '$(srcdir)/'`columninfo.c psqlodbcw_la-connection.lo: connection.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-connection.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-connection.Tpo -c -o psqlodbcw_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-connection.Tpo $(DEPDIR)/psqlodbcw_la-connection.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connection.c' object='psqlodbcw_la-connection.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c psqlodbcw_la-convert.lo: convert.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-convert.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-convert.Tpo -c -o psqlodbcw_la-convert.lo `test -f 'convert.c' || echo '$(srcdir)/'`convert.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-convert.Tpo $(DEPDIR)/psqlodbcw_la-convert.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='convert.c' object='psqlodbcw_la-convert.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-convert.lo `test -f 'convert.c' || echo '$(srcdir)/'`convert.c psqlodbcw_la-drvconn.lo: drvconn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-drvconn.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-drvconn.Tpo -c -o psqlodbcw_la-drvconn.lo `test -f 'drvconn.c' || echo '$(srcdir)/'`drvconn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-drvconn.Tpo $(DEPDIR)/psqlodbcw_la-drvconn.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='drvconn.c' object='psqlodbcw_la-drvconn.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-drvconn.lo `test -f 'drvconn.c' || echo '$(srcdir)/'`drvconn.c psqlodbcw_la-environ.lo: environ.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-environ.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-environ.Tpo -c -o psqlodbcw_la-environ.lo `test -f 'environ.c' || echo '$(srcdir)/'`environ.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-environ.Tpo $(DEPDIR)/psqlodbcw_la-environ.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='environ.c' object='psqlodbcw_la-environ.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-environ.lo `test -f 'environ.c' || echo '$(srcdir)/'`environ.c psqlodbcw_la-execute.lo: execute.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-execute.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-execute.Tpo -c -o psqlodbcw_la-execute.lo `test -f 'execute.c' || echo '$(srcdir)/'`execute.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-execute.Tpo $(DEPDIR)/psqlodbcw_la-execute.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='execute.c' object='psqlodbcw_la-execute.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-execute.lo `test -f 'execute.c' || echo '$(srcdir)/'`execute.c psqlodbcw_la-lobj.lo: lobj.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-lobj.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-lobj.Tpo -c -o psqlodbcw_la-lobj.lo `test -f 'lobj.c' || echo '$(srcdir)/'`lobj.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-lobj.Tpo $(DEPDIR)/psqlodbcw_la-lobj.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='lobj.c' object='psqlodbcw_la-lobj.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-lobj.lo `test -f 'lobj.c' || echo '$(srcdir)/'`lobj.c psqlodbcw_la-misc.lo: misc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-misc.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-misc.Tpo -c -o psqlodbcw_la-misc.lo `test -f 'misc.c' || echo '$(srcdir)/'`misc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-misc.Tpo $(DEPDIR)/psqlodbcw_la-misc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='misc.c' object='psqlodbcw_la-misc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-misc.lo `test -f 'misc.c' || echo '$(srcdir)/'`misc.c psqlodbcw_la-options.lo: options.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-options.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-options.Tpo -c -o psqlodbcw_la-options.lo `test -f 'options.c' || echo '$(srcdir)/'`options.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-options.Tpo $(DEPDIR)/psqlodbcw_la-options.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='options.c' object='psqlodbcw_la-options.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-options.lo `test -f 'options.c' || echo '$(srcdir)/'`options.c psqlodbcw_la-pgtypes.lo: pgtypes.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-pgtypes.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-pgtypes.Tpo -c -o psqlodbcw_la-pgtypes.lo `test -f 'pgtypes.c' || echo '$(srcdir)/'`pgtypes.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-pgtypes.Tpo $(DEPDIR)/psqlodbcw_la-pgtypes.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pgtypes.c' object='psqlodbcw_la-pgtypes.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-pgtypes.lo `test -f 'pgtypes.c' || echo '$(srcdir)/'`pgtypes.c psqlodbcw_la-psqlodbc.lo: psqlodbc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-psqlodbc.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-psqlodbc.Tpo -c -o psqlodbcw_la-psqlodbc.lo `test -f 'psqlodbc.c' || echo '$(srcdir)/'`psqlodbc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-psqlodbc.Tpo $(DEPDIR)/psqlodbcw_la-psqlodbc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='psqlodbc.c' object='psqlodbcw_la-psqlodbc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-psqlodbc.lo `test -f 'psqlodbc.c' || echo '$(srcdir)/'`psqlodbc.c psqlodbcw_la-qresult.lo: qresult.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-qresult.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-qresult.Tpo -c -o psqlodbcw_la-qresult.lo `test -f 'qresult.c' || echo '$(srcdir)/'`qresult.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-qresult.Tpo $(DEPDIR)/psqlodbcw_la-qresult.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='qresult.c' object='psqlodbcw_la-qresult.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-qresult.lo `test -f 'qresult.c' || echo '$(srcdir)/'`qresult.c psqlodbcw_la-results.lo: results.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-results.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-results.Tpo -c -o psqlodbcw_la-results.lo `test -f 'results.c' || echo '$(srcdir)/'`results.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-results.Tpo $(DEPDIR)/psqlodbcw_la-results.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='results.c' object='psqlodbcw_la-results.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-results.lo `test -f 'results.c' || echo '$(srcdir)/'`results.c psqlodbcw_la-parse.lo: parse.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-parse.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-parse.Tpo -c -o psqlodbcw_la-parse.lo `test -f 'parse.c' || echo '$(srcdir)/'`parse.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-parse.Tpo $(DEPDIR)/psqlodbcw_la-parse.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='parse.c' object='psqlodbcw_la-parse.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-parse.lo `test -f 'parse.c' || echo '$(srcdir)/'`parse.c psqlodbcw_la-statement.lo: statement.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-statement.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-statement.Tpo -c -o psqlodbcw_la-statement.lo `test -f 'statement.c' || echo '$(srcdir)/'`statement.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-statement.Tpo $(DEPDIR)/psqlodbcw_la-statement.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='statement.c' object='psqlodbcw_la-statement.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-statement.lo `test -f 'statement.c' || echo '$(srcdir)/'`statement.c psqlodbcw_la-tuple.lo: tuple.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-tuple.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-tuple.Tpo -c -o psqlodbcw_la-tuple.lo `test -f 'tuple.c' || echo '$(srcdir)/'`tuple.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-tuple.Tpo $(DEPDIR)/psqlodbcw_la-tuple.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tuple.c' object='psqlodbcw_la-tuple.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-tuple.lo `test -f 'tuple.c' || echo '$(srcdir)/'`tuple.c psqlodbcw_la-dlg_specific.lo: dlg_specific.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-dlg_specific.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-dlg_specific.Tpo -c -o psqlodbcw_la-dlg_specific.lo `test -f 'dlg_specific.c' || echo '$(srcdir)/'`dlg_specific.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-dlg_specific.Tpo $(DEPDIR)/psqlodbcw_la-dlg_specific.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='dlg_specific.c' object='psqlodbcw_la-dlg_specific.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-dlg_specific.lo `test -f 'dlg_specific.c' || echo '$(srcdir)/'`dlg_specific.c psqlodbcw_la-multibyte.lo: multibyte.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-multibyte.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-multibyte.Tpo -c -o psqlodbcw_la-multibyte.lo `test -f 'multibyte.c' || echo '$(srcdir)/'`multibyte.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-multibyte.Tpo $(DEPDIR)/psqlodbcw_la-multibyte.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='multibyte.c' object='psqlodbcw_la-multibyte.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-multibyte.lo `test -f 'multibyte.c' || echo '$(srcdir)/'`multibyte.c psqlodbcw_la-odbcapi.lo: odbcapi.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-odbcapi.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-odbcapi.Tpo -c -o psqlodbcw_la-odbcapi.lo `test -f 'odbcapi.c' || echo '$(srcdir)/'`odbcapi.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-odbcapi.Tpo $(DEPDIR)/psqlodbcw_la-odbcapi.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='odbcapi.c' object='psqlodbcw_la-odbcapi.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-odbcapi.lo `test -f 'odbcapi.c' || echo '$(srcdir)/'`odbcapi.c psqlodbcw_la-descriptor.lo: descriptor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-descriptor.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-descriptor.Tpo -c -o psqlodbcw_la-descriptor.lo `test -f 'descriptor.c' || echo '$(srcdir)/'`descriptor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-descriptor.Tpo $(DEPDIR)/psqlodbcw_la-descriptor.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='descriptor.c' object='psqlodbcw_la-descriptor.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-descriptor.lo `test -f 'descriptor.c' || echo '$(srcdir)/'`descriptor.c psqlodbcw_la-odbcapi30.lo: odbcapi30.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-odbcapi30.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-odbcapi30.Tpo -c -o psqlodbcw_la-odbcapi30.lo `test -f 'odbcapi30.c' || echo '$(srcdir)/'`odbcapi30.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-odbcapi30.Tpo $(DEPDIR)/psqlodbcw_la-odbcapi30.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='odbcapi30.c' object='psqlodbcw_la-odbcapi30.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-odbcapi30.lo `test -f 'odbcapi30.c' || echo '$(srcdir)/'`odbcapi30.c psqlodbcw_la-pgapi30.lo: pgapi30.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-pgapi30.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-pgapi30.Tpo -c -o psqlodbcw_la-pgapi30.lo `test -f 'pgapi30.c' || echo '$(srcdir)/'`pgapi30.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-pgapi30.Tpo $(DEPDIR)/psqlodbcw_la-pgapi30.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='pgapi30.c' object='psqlodbcw_la-pgapi30.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-pgapi30.lo `test -f 'pgapi30.c' || echo '$(srcdir)/'`pgapi30.c psqlodbcw_la-mylog.lo: mylog.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-mylog.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-mylog.Tpo -c -o psqlodbcw_la-mylog.lo `test -f 'mylog.c' || echo '$(srcdir)/'`mylog.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-mylog.Tpo $(DEPDIR)/psqlodbcw_la-mylog.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mylog.c' object='psqlodbcw_la-mylog.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-mylog.lo `test -f 'mylog.c' || echo '$(srcdir)/'`mylog.c psqlodbcw_la-odbcapi30w.lo: odbcapi30w.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-odbcapi30w.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-odbcapi30w.Tpo -c -o psqlodbcw_la-odbcapi30w.lo `test -f 'odbcapi30w.c' || echo '$(srcdir)/'`odbcapi30w.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-odbcapi30w.Tpo $(DEPDIR)/psqlodbcw_la-odbcapi30w.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='odbcapi30w.c' object='psqlodbcw_la-odbcapi30w.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-odbcapi30w.lo `test -f 'odbcapi30w.c' || echo '$(srcdir)/'`odbcapi30w.c psqlodbcw_la-odbcapiw.lo: odbcapiw.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-odbcapiw.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-odbcapiw.Tpo -c -o psqlodbcw_la-odbcapiw.lo `test -f 'odbcapiw.c' || echo '$(srcdir)/'`odbcapiw.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-odbcapiw.Tpo $(DEPDIR)/psqlodbcw_la-odbcapiw.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='odbcapiw.c' object='psqlodbcw_la-odbcapiw.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-odbcapiw.lo `test -f 'odbcapiw.c' || echo '$(srcdir)/'`odbcapiw.c psqlodbcw_la-win_unicode.lo: win_unicode.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -MT psqlodbcw_la-win_unicode.lo -MD -MP -MF $(DEPDIR)/psqlodbcw_la-win_unicode.Tpo -c -o psqlodbcw_la-win_unicode.lo `test -f 'win_unicode.c' || echo '$(srcdir)/'`win_unicode.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/psqlodbcw_la-win_unicode.Tpo $(DEPDIR)/psqlodbcw_la-win_unicode.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='win_unicode.c' object='psqlodbcw_la-win_unicode.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(psqlodbcw_la_CFLAGS) $(CFLAGS) -c -o psqlodbcw_la-win_unicode.lo `test -f 'win_unicode.c' || echo '$(srcdir)/'`win_unicode.c mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscope: cscope.files test ! -s cscope.files \ || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) clean-cscope: -rm -f cscope.files cscope.files: clean-cscope cscopelist cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files 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 "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -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) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz $(am__post_remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__post_remove_distdir) dist-tarZ: distdir @echo WARNING: "Support for distribution archives compressed with" \ "legacy program 'compress' is deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__post_remove_distdir) dist-shar: distdir @echo WARNING: "Support for shar distribution archives is" \ "deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__post_remove_distdir) dist dist-all: $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' $(am__post_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*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir) chmod u+w $(distdir) mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build/sub \ && ../../configure \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ --srcdir=../.. --prefix="$$dc_install_base" \ && $(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 \ && cd "$$am__cwd" \ || exit 1 $(am__post_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: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { 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: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_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 html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am 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: all install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--refresh check check-am clean \ clean-cscope clean-generic clean-libLTLIBRARIES clean-libtool \ cscope cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \ dist-gzip dist-lzip dist-shar dist-tarZ dist-xz 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 tags-am uninstall uninstall-am uninstall-libLTLIBRARIES .PRECIOUS: Makefile # 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-13.02.0000/config.h.in000644 001751 001751 00000010675 14122576747 017135 0ustar00hiroshihiroshi000000 000000 /* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the `c16rtomb' function. */ #undef HAVE_C16RTOMB /* 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_INTTYPES_H /* 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 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 `mbrtoc16' function. */ #undef HAVE_MBRTOC16 /* Define to 1 if you have the `mbstowcs' function. */ #undef HAVE_MBSTOWCS /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the `PQsslInUse' function. */ #undef HAVE_PQSSLINUSE /* 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 `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 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_UCHAR_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the `wcstombs' function. */ #undef HAVE_WCSTOMBS /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* 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 `long int', as computed by sizeof. */ #undef SIZEOF_LONG_INT /* 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 /* 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-13.02.0000/info.c000644 001751 001751 00000553616 14122574536 016212 0ustar00hiroshihiroshi000000 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 "unicode_support.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 static const SQLCHAR *pubstr = (SQLCHAR *) "public"; static const char *likeop = "like"; static const char *eqop = "="; /* group of SQL_CVT_(chars) */ #define PG_CONVERT_CH SQL_CVT_CHAR | SQL_CVT_VARCHAR | SQL_CVT_LONGVARCHAR /* group of SQL_CVT_(numbers) */ #define PG_CONVERT_NUM SQL_CVT_SMALLINT | SQL_CVT_INTEGER | SQL_CVT_BIGINT | SQL_CVT_REAL | SQL_CVT_FLOAT | SQL_CVT_DOUBLE | SQL_CVT_NUMERIC | SQL_CVT_DECIMAL /* group of SQL_CVT_(date time) */ #define PG_CONVERT_DT SQL_CVT_DATE | SQL_CVT_TIME | SQL_CVT_TIMESTAMP /* group of SQL_CVT_(wchars) */ #ifdef UNICODE_SUPPORT #define PG_CONVERT_WCH SQL_CVT_WCHAR | SQL_CVT_WVARCHAR | SQL_CVT_WLONGVARCHAR #else #define PG_CONVERT_WCH 0 #endif /* UNICODE_SUPPORT */ #define QR_set_field_info_EN(self, field_num, adtid, adtsize) (CI_set_field_info(self->fields, field_num, catcn[field_num][is_ODBC2], adtid, adtsize, -1, 0, 0)) const SQLLEN mask_longvarbinary = SQL_CVT_LONGVARBINARY; RETCODE SQL_API PGAPI_GetInfo(HDBC hdbc, SQLUSMALLINT fInfoType, PTR rgbInfoValue, SQLSMALLINT cbInfoValueMax, SQLSMALLINT * 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 ret = SQL_ERROR; char odbcver[16]; MYLOG(0, "entering...fInfoType=%d\n", 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 | SQL_AT_DROP_COLUMN | SQL_AT_ADD_COLUMN_SINGLE | SQL_AT_ADD_CONSTRAINT | SQL_AT_ADD_TABLE_CONSTRAINT | SQL_AT_CONSTRAINT_INITIALLY_DEFERRED | SQL_AT_CONSTRAINT_INITIALLY_IMMEDIATE | SQL_AT_CONSTRAINT_DEFERRABLE | SQL_AT_DROP_TABLE_CONSTRAINT_RESTRICT | SQL_AT_DROP_TABLE_CONSTRAINT_CASCADE | SQL_AT_DROP_COLUMN_RESTRICT | SQL_AT_DROP_COLUMN_CASCADE; break; case SQL_BOOKMARK_PERSISTENCE: /* ODBC 2.0 */ /* very simple bookmark support */ len = 4; value = 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_BIT: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : SQL_CVT_BIT | SQL_CVT_INTEGER | PG_CONVERT_CH | PG_CONVERT_WCH; MYLOG(0, "SQL_CONVERT_ mask=" FORMAT_ULEN "\n", value); break; case SQL_CONVERT_INTEGER: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : SQL_CVT_BIT | PG_CONVERT_NUM | PG_CONVERT_CH | PG_CONVERT_WCH; break; case SQL_CONVERT_SMALLINT: case SQL_CONVERT_BIGINT: case SQL_CONVERT_DECIMAL: case SQL_CONVERT_DOUBLE: case SQL_CONVERT_FLOAT: case SQL_CONVERT_NUMERIC: case SQL_CONVERT_REAL: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : PG_CONVERT_NUM | PG_CONVERT_CH | PG_CONVERT_WCH; break; case SQL_CONVERT_CHAR: case SQL_CONVERT_VARCHAR: /* ODBC 1.0 */ case SQL_CONVERT_LONGVARCHAR: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : SQL_CVT_BIT | PG_CONVERT_NUM | PG_CONVERT_CH | PG_CONVERT_WCH; break; case SQL_CONVERT_DATE: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : PG_CONVERT_CH | SQL_CVT_DATE | SQL_CVT_TIMESTAMP | PG_CONVERT_WCH; break; case SQL_CONVERT_TIME: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : PG_CONVERT_CH | SQL_CVT_TIME | PG_CONVERT_WCH; break; case SQL_CONVERT_TIMESTAMP: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : PG_CONVERT_CH | PG_CONVERT_DT | PG_CONVERT_WCH; break; case SQL_CONVERT_LONGVARBINARY: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : SQL_CVT_LONGVARBINARY; break; #ifdef UNICODE_SUPPORT case SQL_CONVERT_WCHAR: case SQL_CONVERT_WLONGVARCHAR: case SQL_CONVERT_WVARCHAR: len = sizeof(SQLUINTEGER); value = ci->disable_convert_func ? 0 : SQL_CVT_BIT | PG_CONVERT_NUM | PG_CONVERT_DT | PG_CONVERT_WCH; break; #endif /* UNICODE_SUPPORT */ case SQL_CONVERT_TINYINT: case SQL_CONVERT_BINARY: case SQL_CONVERT_VARBINARY: /* ODBC 1.0 */ 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(0, "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_PRESERVE; break; case SQL_CURSOR_ROLLBACK_BEHAVIOR: /* ODBC 1.0 */ len = 2; if (!ci->drivers.use_declarefetch) value = SQL_CB_PRESERVE; else value = SQL_CB_CLOSE; 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 */ /* SPRINTF_FIXED(tmp, "%s %s", POSTGRESDRIVERVERSION, conn->pg_version); tmp[sizeof(tmp) - 1] = '\0'; */ if (CC_fake_mss(conn)) p = "09.00.1399"; else { STRCPY_FIXED(tmp, conn->pg_version); p = tmp; } break; case SQL_DEFAULT_TXN_ISOLATION: /* ODBC 1.0 */ len = 4; if (0 == conn->default_isolation) conn->isolation = CC_get_isolation(conn); value = conn->default_isolation; break; case SQL_DRIVER_NAME: /* ODBC 1.0 */ p = DRIVER_FILE_NAME; break; case SQL_DRIVER_ODBC_VER: SPRINTF_FIXED(odbcver, "%02x.%02x", ODBCVER / 256, 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 = "Y"; 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 = "\""; break; case SQL_KEYWORDS: /* ODBC 2.0 */ p = NULL_STRING; break; case SQL_LIKE_ESCAPE_CLAUSE: /* ODBC 2.0 */ p = "Y"; 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; value = CC_get_max_idlen(conn); if (0 == value) value = NAMEDATALEN_V73 - 1; 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 value = MAX_SCHEMA_LEN; #endif /* MAX_SCHEMA_LEN */ if (0 == value) value = NAMEDATALEN_V73 - 1; 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; /* No limit with tuptoaster in 7.1+ */ value = 0; break; case SQL_MAX_STATEMENT_LEN: /* ODBC 2.0 */ len = 4; value = 0; 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) value = NAMEDATALEN_V73 - 1; 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; value = SQL_NC_HIGH; break; case SQL_NUMERIC_FUNCTIONS: /* ODBC 1.0 */ len = 4; value = SQL_FN_NUM_ABS | SQL_FN_NUM_ACOS | SQL_FN_NUM_ASIN | SQL_FN_NUM_ATAN | SQL_FN_NUM_ATAN2 | SQL_FN_NUM_CEILING | SQL_FN_NUM_COS | SQL_FN_NUM_COT | SQL_FN_NUM_DEGREES | SQL_FN_NUM_EXP | SQL_FN_NUM_FLOOR | SQL_FN_NUM_LOG | SQL_FN_NUM_LOG10 | SQL_FN_NUM_MOD | SQL_FN_NUM_PI | SQL_FN_NUM_POWER | SQL_FN_NUM_RADIANS | SQL_FN_NUM_RAND | SQL_FN_NUM_ROUND | SQL_FN_NUM_SIGN | SQL_FN_NUM_SIN | SQL_FN_NUM_SQRT | SQL_FN_NUM_TAN | SQL_FN_NUM_TRUNCATE; 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; 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); break; case SQL_ORDER_BY_COLUMNS_IN_SELECT: /* ODBC 2.0 */ p = "Y"; break; case SQL_OUTER_JOINS: /* ODBC 1.0 */ p = "Y"; break; case SQL_OWNER_TERM: /* ODBC 1.0 */ p = "schema"; break; case SQL_OWNER_USAGE: /* ODBC 2.0 */ len = 4; 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 (CurrCat(conn)) value = SQL_CU_DML_STATEMENTS; else 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 */ p = "\\"; 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_ASCII | SQL_FN_STR_CHAR | SQL_FN_STR_CONCAT | SQL_FN_STR_INSERT | SQL_FN_STR_LCASE | SQL_FN_STR_LEFT | SQL_FN_STR_LENGTH | SQL_FN_STR_LOCATE | SQL_FN_STR_LOCATE_2 | SQL_FN_STR_LTRIM | SQL_FN_STR_REPEAT | SQL_FN_STR_RIGHT | SQL_FN_STR_RTRIM | SQL_FN_STR_SPACE | 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 = SQL_FN_SYS_IFNULL | SQL_FN_SYS_USERNAME; break; case SQL_TABLE_TERM: /* ODBC 1.0 */ p = "table"; break; case SQL_TIMEDATE_ADD_INTERVALS: /* ODBC 2.0 */ len = 4; value = SQL_FN_TSI_DAY | SQL_FN_TSI_HOUR | SQL_FN_TSI_MINUTE | SQL_FN_TSI_SECOND | SQL_FN_TSI_FRAC_SECOND | SQL_FN_TSI_YEAR | SQL_FN_TSI_MONTH | SQL_FN_TSI_WEEK; break; case SQL_TIMEDATE_DIFF_INTERVALS: /* ODBC 2.0 */ len = 4; value = SQL_FN_TSI_DAY | SQL_FN_TSI_HOUR | SQL_FN_TSI_MINUTE | SQL_FN_TSI_SECOND | SQL_FN_TSI_SECOND; break; case SQL_TIMEDATE_FUNCTIONS: /* ODBC 1.0 */ len = 4; value = SQL_FN_TD_NOW | SQL_FN_TD_CURRENT_DATE | SQL_FN_TD_CURRENT_TIME | SQL_FN_TD_CURRENT_TIMESTAMP | SQL_FN_TD_CURDATE | SQL_FN_TD_CURTIME | SQL_FN_TD_DAYNAME | SQL_FN_TD_DAYOFMONTH | SQL_FN_TD_DAYOFWEEK | SQL_FN_TD_DAYOFYEAR | SQL_FN_TD_HOUR | SQL_FN_TD_MINUTE | SQL_FN_TD_MONTH | SQL_FN_TD_MONTHNAME | SQL_FN_TD_NOW | SQL_FN_TD_QUARTER | SQL_FN_TD_SECOND | SQL_FN_TD_WEEK | SQL_FN_TD_YEAR | SQL_FN_TD_TIMESTAMPADD | SQL_FN_TD_TIMESTAMPDIFF | SQL_FN_TD_EXTRACT; 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; value = SQL_TXN_READ_UNCOMMITTED | SQL_TXN_READ_COMMITTED | SQL_TXN_REPEATABLE_READ | SQL_TXN_SERIALIZABLE; 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; /* Keys for ODBC 3.0 */ 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: if (CurrCat(conn)) p = "Y"; else p = "N"; break; case SQL_COLLATION_SEQ: 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; value = SQL_CS_CREATE_SCHEMA | SQL_CS_AUTHORIZATION; break; case SQL_CREATE_TABLE: len = 4; value = SQL_CT_CREATE_TABLE | SQL_CT_COLUMN_CONSTRAINT | SQL_CT_COLUMN_DEFAULT | SQL_CT_GLOBAL_TEMPORARY | 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: 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; value = SQL_DS_DROP_SCHEMA | SQL_DS_RESTRICT | SQL_DS_CASCADE; break; case SQL_DROP_TABLE: len = 4; value = SQL_DT_DROP_TABLE; 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; value |= (SQL_DV_RESTRICT | SQL_DV_CASCADE); break; case SQL_INDEX_KEYWORDS: len = 4; value = SQL_IK_NONE; break; 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 = CC_get_max_idlen(conn); if (0 == value) value = NAMEDATALEN_V73 - 1; break; case SQL_MAX_ROW_SIZE_INCLUDES_LONG: 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; 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 PGAPI_GetInfo.", NULL); goto cleanup; } ret = SQL_SUCCESS; MYLOG(0, "p='%s', len=" FORMAT_ULEN ", value=" FORMAT_ULEN ", cbMax=%d\n", 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) { ret = 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 ret; } /* * macros for pgtype_xxxx() calls which have PG_ATP_UNSET parameters */ #define PGTYPE_COLUMN_SIZE(conn, pgType) pgtype_attr_column_size(conn, pgType, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_TO_CONCISE_TYPE(conn, pgType) pgtype_attr_to_concise_type(conn, pgType, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_TO_SQLDESCTYPE(conn, pgType) pgtype_attr_to_sqldesctype(conn, pgType, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_BUFFER_LENGTH(conn, pgType) pgtype_attr_buffer_length(conn, pgType, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_DECIMAL_DIGITS(conn, pgType) pgtype_attr_decimal_digits(conn, pgType, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_TRANSFER_OCTET_LENGTH(conn, pgType) pgtype_attr_transfer_octet_length(conn, pgType, PG_ATP_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_TO_NAME(conn, pgType, auto_increment) pgtype_attr_to_name(conn, pgType, PG_ATP_UNSET, auto_increment) #define PGTYPE_TO_DATETIME_SUB(conn, pgtype) pgtype_attr_to_datetime_sub(conn, pgtype, PG_ATP_UNSET) 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 ret = SQL_ERROR, result; static const char *catcn[][2] = { {"TYPE_NAME", "TYPE_NAME"}, {"DATA_TYPE", "DATA_TYPE"}, {"COLUMN_SIZE", "RECISION"}, {"LITERAL_PREFIX", "LITERAL_PREFIX"}, {"LITERAL_SUFFIX", "LITERAL_SUFFIX"}, {"CREATE_PARAMS", "CREATE_PARAMS"}, {"NULLABLE", "NULLABLE"}, {"CASE_SENSITIVE", "CASE_SENSITIVE"}, {"SEARCHABLE", "SEARCHABLE"}, {"UNSIGNED_ATTRIBUTE", "UNSIGNED_ATTRIBUTE"}, {"FIXED_PREC_SCALE", "MONEY"}, {"AUTO_UNIQUE_VALUE", "AUTO_INCREMENT"}, {"LOCAL_TYPE_NAME", "LOCAL_TYPE_NAME"}, {"MINIMUM_SCALE", "MINIMUM_SCALE"}, {"MAXIMUM_SCALE", "MAXIMUM_SCALE"}, {"SQL_DATA_TYPE", "SQL_DATA_TYPE"}, {"SQL_DATETIME_SUB", "SQL_DATETIME_SUB"}, {"NUM_PREC_RADIX", "NUM_PREC_RADIX"}, {"INTERVAL_PRECISION", "INTERVAL_PRECISION"} }; EnvironmentClass *env; BOOL is_ODBC2; MYLOG(0, "entering...fSqlType=%d\n", fSqlType); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); env = CC_get_env(conn); is_ODBC2 = EN_is_odbc2(env); 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??? result_cols = NUM_OF_GETTYPE_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; QR_set_num_fields(res, result_cols); QR_set_field_info_EN(res, 0, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 1, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 2, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, 3, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 4, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 5, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 6, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 7, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 8, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 9, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 10, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 11, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 12, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 13, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 14, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 15, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 16, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 17, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, 18, PG_TYPE_INT2, 2); for (i = 0, sqlType = sqlTypes[0]; sqlType; sqlType = sqlTypes[++i]) { /* Filter unsupported data types when fSqlType = SQL_ALL_TYPES */ if (SQL_ALL_TYPES == fSqlType && EN_is_odbc2(env)) { switch (sqlType) { case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: continue; } } pgType = sqltype_to_pgtype(conn, sqlType); if (sqlType == SQL_LONGVARBINARY) { ConnInfo *ci = &(conn->connInfo); MYLOG(DETAIL_LOG_LEVEL, "%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(0, "sqlType=%d ms_jet=%d\n", sqlType, conn->ms_jet); if (conn->ms_jet) { aunq_match = 1; pgtcount = 2; } MYLOG(0, "aunq_match=%d pgtcount=%d\n", aunq_match, pgtcount); } for (cnt = 0; cnt < pgtcount; cnt ++) { if (tuple = QR_AddNew(res), NULL == tuple) { 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[GETTYPE_TYPE_NAME], PGTYPE_TO_NAME(conn, pgType, TRUE)); set_tuplefield_int2(&tuple[GETTYPE_NULLABLE], SQL_NO_NULLS); MYLOG(DETAIL_LOG_LEVEL, "serial in\n"); } else { set_tuplefield_string(&tuple[GETTYPE_TYPE_NAME], PGTYPE_TO_NAME(conn, pgType, FALSE)); set_tuplefield_int2(&tuple[GETTYPE_NULLABLE], pgtype_nullable(conn, pgType)); } set_tuplefield_int2(&tuple[GETTYPE_DATA_TYPE], (Int2) sqlType); set_tuplefield_int2(&tuple[GETTYPE_CASE_SENSITIVE], pgtype_case_sensitive(conn, pgType)); set_tuplefield_int2(&tuple[GETTYPE_SEARCHABLE], pgtype_searchable(conn, pgType)); set_tuplefield_int2(&tuple[GETTYPE_FIXED_PREC_SCALE], pgtype_money(conn, pgType)); /* * Localized data-source dependent data type name (always * NULL) */ set_tuplefield_null(&tuple[GETTYPE_LOCAL_TYPE_NAME]); /* These values can be NULL */ set_nullfield_int4(&tuple[GETTYPE_COLUMN_SIZE], PGTYPE_COLUMN_SIZE(conn, pgType)); set_nullfield_string(&tuple[GETTYPE_LITERAL_PREFIX], pgtype_literal_prefix(conn, pgType)); set_nullfield_string(&tuple[GETTYPE_LITERAL_SUFFIX], pgtype_literal_suffix(conn, pgType)); set_nullfield_string(&tuple[GETTYPE_CREATE_PARAMS], pgtype_create_params(conn, pgType)); if (1 < pgtcount) set_tuplefield_int2(&tuple[GETTYPE_UNSIGNED_ATTRIBUTE], SQL_TRUE); else set_nullfield_int2(&tuple[GETTYPE_UNSIGNED_ATTRIBUTE], pgtype_unsigned(conn, pgType)); if (aunq_match == cnt) set_tuplefield_int2(&tuple[GETTYPE_AUTO_UNIQUE_VALUE], SQL_TRUE); else set_nullfield_int2(&tuple[GETTYPE_AUTO_UNIQUE_VALUE], pgtype_auto_increment(conn, pgType)); set_nullfield_int2(&tuple[GETTYPE_MINIMUM_SCALE], pgtype_min_decimal_digits(conn, pgType)); set_nullfield_int2(&tuple[GETTYPE_MAXIMUM_SCALE], pgtype_max_decimal_digits(conn, pgType)); set_tuplefield_int2(&tuple[GETTYPE_SQL_DATA_TYPE], PGTYPE_TO_SQLDESCTYPE(conn, pgType)); set_nullfield_int2(&tuple[GETTYPE_SQL_DATETIME_SUB], PGTYPE_TO_DATETIME_SUB(conn, pgType)); set_nullfield_int4(&tuple[GETTYPE_NUM_PREC_RADIX], pgtype_radix(conn, pgType)); set_nullfield_int4(&tuple[GETTYPE_INTERVAL_PRECISION], 0); } } } 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; stmt->currTuple = -1; if (SQL_SUCCEEDED(ret)) SC_set_rowset_start(stmt, -1, FALSE); else SC_set_Result(stmt, NULL); SC_set_current_col(stmt, -1); return ret; } RETCODE SQL_API PGAPI_GetFunctions(HDBC hdbc, SQLUSMALLINT fFunction, SQLUSMALLINT * pfExists) { ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci = &(conn->connInfo); MYLOG(0, "entering...%u\n", fFunction); if (fFunction == SQL_API_ALL_FUNCTIONS) { 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; 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; pfExists[SQL_API_SQLPROCEDURECOLUMNS] = TRUE; pfExists[SQL_API_SQLPROCEDURES] = TRUE; pfExists[SQL_API_SQLSETPOS] = TRUE; pfExists[SQL_API_SQLSETSCROLLOPTIONS] = TRUE; /* odbc 1.0 */ pfExists[SQL_API_SQLTABLEPRIVILEGES] = TRUE; if (0 == ci->updatable_cursors) pfExists[SQL_API_SQLBULKOPERATIONS] = FALSE; else pfExists[SQL_API_SQLBULKOPERATIONS] = TRUE; } else { if (ci->drivers.lie) *pfExists = TRUE; else { switch (fFunction) { case SQL_API_SQLBINDCOL: *pfExists = TRUE; break; case SQL_API_SQLCANCEL: *pfExists = TRUE; break; case SQL_API_SQLCOLATTRIBUTE: *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; case SQL_API_SQLEXECDIRECT: *pfExists = TRUE; break; case SQL_API_SQLEXECUTE: *pfExists = TRUE; break; case SQL_API_SQLFETCH: *pfExists = TRUE; break; 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; /* 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; case SQL_API_SQLGETDATA: *pfExists = TRUE; break; case SQL_API_SQLGETFUNCTIONS: *pfExists = TRUE; break; case SQL_API_SQLGETINFO: *pfExists = TRUE; break; case SQL_API_SQLGETTYPEINFO: *pfExists = TRUE; break; case SQL_API_SQLPARAMDATA: *pfExists = TRUE; break; case SQL_API_SQLPUTDATA: *pfExists = TRUE; break; 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; case SQL_API_SQLPRIMARYKEYS: *pfExists = TRUE; break; case SQL_API_SQLPROCEDURECOLUMNS: *pfExists = TRUE; break; case SQL_API_SQLPROCEDURES: *pfExists = TRUE; break; case SQL_API_SQLSETPOS: *pfExists = TRUE; break; case SQL_API_SQLTABLEPRIVILEGES: *pfExists = TRUE; break; 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; default: *pfExists = FALSE; break; } } } return SQL_SUCCESS; } char * identifierEscape(const SQLCHAR *src, SQLLEN srclen, const ConnectionClass *conn, char *buf, size_t bufsize, BOOL double_quote) { int i, outlen; UCHAR tchar; char *dest = NULL, escape_ch = CC_get_escape(conn); encoded_str encstr; if (!src || srclen == SQL_NULL_DATA) return dest; else if (srclen == SQL_NTS) srclen = (SQLLEN) strlen((char *) src); if (srclen <= 0) return dest; MYLOG(0, "entering in=%s(" FORMAT_LEN ")\n", src, srclen); if (NULL != buf && bufsize > 0) dest = buf; else { bufsize = 2 * srclen + 1; dest = malloc(bufsize); } if (!dest) return NULL; encoded_str_constr(&encstr, conn->ccsc, (char *) src); outlen = 0; if (double_quote) dest[outlen++] = IDENTIFIER_QUOTE; for (i = 0, tchar = encoded_nextchar(&encstr); i < srclen && outlen < bufsize - 1; i++, tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) { dest[outlen++] = tchar; continue; } if (LITERAL_QUOTE == tchar || escape_ch == tchar) dest[outlen++] = tchar; else if (double_quote && IDENTIFIER_QUOTE == tchar) dest[outlen++] = tchar; dest[outlen++] = tchar; } if (double_quote) dest[outlen++] = IDENTIFIER_QUOTE; dest[outlen] = '\0'; MYLOG(0, "leaving output=%s(%d)\n", dest, outlen); return dest; } static char * simpleCatalogEscape(const SQLCHAR *src, SQLLEN srclen, const ConnectionClass *conn) { return identifierEscape(src, srclen, conn, NULL, -1, FALSE); } /* * PostgreSQL needs 2 '\\' to escape '_' and '%'. */ static char * adjustLikePattern(const SQLCHAR *src, int srclen, const ConnectionClass *conn) { int i, outlen; UCHAR tchar; char *dest = NULL, escape_in_literal = CC_get_escape(conn); BOOL escape_in = FALSE; encoded_str encstr; 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(0, "entering in=%.*s(%d)\n", srclen, src, srclen); encoded_str_constr(&encstr, conn->ccsc, (char *) src); dest = malloc(4 * srclen + 1); if (!dest) return NULL; for (i = 0, outlen = 0; i < srclen; i++) { tchar = encoded_nextchar(&encstr); if (MBCS_NON_ASCII(encstr)) { dest[outlen++] = tchar; continue; } if (escape_in) { switch (tchar) { case '%': case '_': break; default: if (SEARCH_PATTERN_ESCAPE == escape_in_literal) dest[outlen++] = escape_in_literal; dest[outlen++] = SEARCH_PATTERN_ESCAPE; break; } } if (tchar == SEARCH_PATTERN_ESCAPE) { escape_in = TRUE; if (SEARCH_PATTERN_ESCAPE == escape_in_literal) dest[outlen++] = escape_in_literal; /* insert 1 more LEXER escape */ } else { escape_in = FALSE; if (LITERAL_QUOTE == tchar) dest[outlen++] = tchar; } dest[outlen++] = tchar; } if (escape_in) { if (SEARCH_PATTERN_ESCAPE == escape_in_literal) dest[outlen++] = escape_in_literal; dest[outlen++] = SEARCH_PATTERN_ESCAPE; } dest[outlen] = '\0'; MYLOG(0, "leaving output=%s(%d)\n", dest, outlen); return dest; } #define CSTR_SYS_TABLE "SYSTEM TABLE" #define CSTR_TABLE "TABLE" #define CSTR_VIEW "VIEW" #define CSTR_FOREIGN_TABLE "FOREIGN TABLE" #define CSTR_MATVIEW "MATVIEW" 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); const char *curschema; size_t userlen = strlen(user); size_t schemalen; if (NULL == szSchemaName) return FALSE; if (SQL_NTS == cbSchemaName) schemalen = strlen((char *) szSchemaName); else schemalen = cbSchemaName; if (schemalen != userlen) return FALSE; if (strnicmp((char *) szSchemaName, user, userlen) != 0) return FALSE; curschema = CC_get_current_schema(conn); if (curschema == NULL) return FALSE; return stricmp(curschema, (const char *) pubstr) == 0; } #define TABLE_IN_RELKIND "('r', 'v', 'm', 'f', 'p')" RETCODE SQL_API PGAPI_Tables(HSTMT hstmt, const SQLCHAR * szTableQualifier, /* PV X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* PV E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * szTableName, /* PV E*/ SQLSMALLINT cbTableName, const SQLCHAR * szTableType, SQLSMALLINT cbTableType, UWORD flag) { CSTR func = "PGAPI_Tables"; StatementClass *stmt = (StatementClass *) hstmt; StatementClass *tbl_stmt = NULL; QResultClass *res; TupleField *tuple; RETCODE ret = SQL_ERROR, result; int result_cols; char *tableType = NULL; PQExpBufferData tables_query = {0}; 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, show_matviews, show_foreign_tables; char regular_table, view, matview, foreign_table, 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; EnvironmentClass *env; BOOL is_ODBC2; static const char *catcn[][2] = { {"TABLE_CAT", "TABLE_QUALIFIER"}, {"TABLE_SCHEM", "TABLE_OWNER"}, {"TABLE_NAME", "TABLE_NAME"}, {"TABLE_TYPE", "TABLE_TYPE"}, {"REMARKS", "REMARKS"}}; MYLOG(0, "entering...stmt=%p scnm=%p len=%d\n", stmt, szTableOwner, cbTableOwner); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); ci = &(conn->connInfo); env = CC_get_env(conn); is_ODBC2 = EN_is_odbc2(env); result = PGAPI_AllocStmt(conn, (HSTMT *) &tbl_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; } 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, conn); escTableName = adjustLikePattern(szTableName, cbTableName, conn); } else { like_or_eq = eqop; escCatName = simpleCatalogEscape(szTableQualifier, cbTableQualifier, conn); escTableName = simpleCatalogEscape(szTableName, cbTableName, conn); } retry_public_schema: if (escSchemaName) free(escSchemaName); if (search_pattern) escSchemaName = adjustLikePattern(szSchemaName, cbSchemaName, conn); else escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, conn); /* * Create the query to find out the tables */ /* make_string mallocs memory */ tableType = make_string(szTableType, cbTableType, NULL, 0); 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; } list_some = (list_cat || list_schemas || list_table_types); initPQExpBuffer(&tables_query); #define return DONT_CALL_RETURN_FROM_HERE??? if (list_cat) appendPQExpBufferStr(&tables_query, "select NULL, NULL, NULL"); else if (list_table_types) { /* * Query relations depending on what is available: * - 10 and newer versions have partition tables * - 9.3 and newer versions have materialized views * - 9.1 and newer versions have foreign tables */ appendPQExpBufferStr(&tables_query, "select NULL, NULL, relkind from (select 'r' as relkind " "union select 'v' " "union select 'm' " "union select 'f' " "union select 'p') as a"); } else if (list_schemas) { appendPQExpBufferStr(&tables_query, "select NULL, nspname, NULL" " from pg_catalog.pg_namespace n where true"); } else { /* * View is represented by its relkind since 7.1, * Materialized views are added in 9.3, and foreign * tables in 9.1. */ appendPQExpBufferStr(&tables_query, "select relname, nspname, relkind " "from pg_catalog.pg_class c, pg_catalog.pg_namespace n " "where relkind in " TABLE_IN_RELKIND); } op_string = gen_opestr(like_or_eq, conn); if (!list_some) { schema_appendPQExpBuffer1(&tables_query, " and nspname %s'%.*s'", op_string, escSchemaName, TABLE_IS_VALID(szTableName, cbTableName), conn); if (IS_VALID_NAME(escTableName)) appendPQExpBuffer(&tables_query, " and relname %s'%s'", op_string, escTableName); } /* * Parse the extra systable prefix configuration variable into an array * of prefixes. */ STRCPY_FIXED(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; show_foreign_tables = FALSE; show_matviews = FALSE; /* TABLE_TYPE */ if (!tableType) { show_regular_tables = TRUE; show_views = TRUE; show_foreign_tables = TRUE; show_matviews = TRUE; } else if (list_some || stricmp(tableType, SQL_ALL_TABLE_TYPES) == 0) { show_regular_tables = TRUE; show_views = TRUE; show_foreign_tables = TRUE; show_matviews = TRUE; } 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; else if (strnicmp(typestr, CSTR_FOREIGN_TABLE, strlen(CSTR_FOREIGN_TABLE)) == 0) show_foreign_tables = TRUE; else if (strnicmp(typestr, CSTR_MATVIEW, strlen(CSTR_MATVIEW)) == 0) show_matviews = 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) appendPQExpBufferStr(&tables_query, " and nspname not in ('pg_catalog', 'information_schema', 'pg_toast', 'pg_temp_1')"); if (!list_some) { if (CC_accessible_only(conn)) appendPQExpBufferStr(&tables_query, " and has_table_privilege(c.oid, 'select')"); } if (list_schemas) appendPQExpBufferStr(&tables_query, " order by nspname"); else if (list_some) ; else appendPQExpBufferStr(&tables_query, " and n.oid = relnamespace order by nspname, relname"); if (PQExpBufferDataBroken(tables_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_Tables()", func); goto cleanup; } result = PGAPI_ExecDirect(tbl_stmt, (SQLCHAR *) tables_query.data, SQL_NTS, PODBC_RDONLY); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, tbl_stmt, FALSE); goto cleanup; } /* If not found */ if ((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(tbl_stmt, 1, internal_asis_type, table_name, MAX_INFO_STRING, &cbRelname); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 2, internal_asis_type, table_owner, MAX_INFO_STRING, &cbSchName); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 3, internal_asis_type, relkind_or_hasrules, MAX_INFO_STRING, &cbRelkind); if (!SQL_SUCCEEDED(result)) { 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_EN(res, TABLES_CATALOG_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, TABLES_SCHEMA_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, TABLES_TABLE_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, TABLES_TABLE_TYPE, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, TABLES_REMARKS, PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); /* add the tuples */ table_name[0] = '\0'; table_owner[0] = '\0'; result = PGAPI_Fetch(tbl_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 (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 { /* Check extra system table prefixes */ for (i = 0; i < nprefixes; i++) { MYLOG(0, "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 */ view = (relkind_or_hasrules[0] == 'v'); /* Check for foreign tables and materialized views ... */ foreign_table = (relkind_or_hasrules[0] == 'f'); matview = (relkind_or_hasrules[0] == 'm'); /* 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) || (foreign_table && show_foreign_tables) || (matview && show_matviews) || (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(0, "table_name = '%s'\n", table_name); if (list_schemas || !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) { if (systable) set_tuplefield_string(&tuple[TABLES_TABLE_TYPE], CSTR_SYS_TABLE); else if (view) set_tuplefield_string(&tuple[TABLES_TABLE_TYPE], CSTR_VIEW); else if (matview) set_tuplefield_string(&tuple[TABLES_TABLE_TYPE], CSTR_MATVIEW); else if (foreign_table) set_tuplefield_string(&tuple[TABLES_TABLE_TYPE], CSTR_FOREIGN_TABLE); else set_tuplefield_string(&tuple[TABLES_TABLE_TYPE], CSTR_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(tbl_stmt); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, tbl_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 (!SQL_SUCCEEDED(ret) && 0 >= SC_get_errornumber(stmt)) SC_error_copy(stmt, tbl_stmt, TRUE); if (!PQExpBufferDataBroken(tables_query)) termPQExpBuffer(&tables_query); 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 (tbl_stmt) PGAPI_FreeStmt(tbl_stmt, SQL_DROP); MYLOG(0, "leaving stmt=%p, ret=%d\n", stmt, ret); return ret; } /* * macros for pgtype_attr_xxxx() calls which have * PG_ADT_UNSET or PG_UNKNOWNS_UNSET parameters */ #define PGTYPE_ATTR_COLUMN_SIZE(conn, pgType, atttypmod) pgtype_attr_column_size(conn, pgType, atttypmod, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_ATTR_TO_CONCISE_TYPE(conn, pgType, atttypmod) pgtype_attr_to_concise_type(conn, pgType, atttypmod, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_ATTR_TO_SQLDESCTYPE(conn, pgType, atttypmod) pgtype_attr_to_sqldesctype(conn, pgType, atttypmod, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_ATTR_DISPLAY_SIZE(conn, pgType, atttypmod) pgtype_attr_display_size(conn, pgType, atttypmod, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_ATTR_BUFFER_LENGTH(conn, pgType, atttypmod) pgtype_attr_buffer_length(conn, pgType, atttypmod, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_ATTR_DECIMAL_DIGITS(conn, pgType, atttypmod) pgtype_attr_decimal_digits(conn, pgType, atttypmod, PG_ADT_UNSET, PG_UNKNOWNS_UNSET) #define PGTYPE_ATTR_TRANSFER_OCTET_LENGTH(conn, pgType, atttypmod) pgtype_attr_transfer_octet_length(conn, pgType, atttypmod, PG_UNKNOWNS_UNSET) /* * for oid or xmin */ static void add_tuple_for_oid_or_xmin(TupleField *tuple, int ordinal, const char *colname, OID the_type, const char *typname, const ConnectionClass *conn, const char *table_owner, const char *table_name, OID greloid, int attnum, BOOL auto_increment, int table_info) { int sqltype; const int atttypmod = -1; set_tuplefield_string(&tuple[COLUMNS_CATALOG_NAME], CurrCat(conn)); /* see note in SQLTables() */ set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], GET_SCHEMA_NAME(table_owner)); set_tuplefield_string(&tuple[COLUMNS_TABLE_NAME], table_name); set_tuplefield_string(&tuple[COLUMNS_COLUMN_NAME], colname); sqltype = PGTYPE_ATTR_TO_CONCISE_TYPE(conn, the_type, atttypmod); set_tuplefield_int2(&tuple[COLUMNS_DATA_TYPE], sqltype); set_tuplefield_string(&tuple[COLUMNS_TYPE_NAME], typname); set_tuplefield_int4(&tuple[COLUMNS_PRECISION], PGTYPE_ATTR_COLUMN_SIZE(conn, the_type, atttypmod)); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], PGTYPE_ATTR_BUFFER_LENGTH(conn, the_type, atttypmod)); set_nullfield_int2(&tuple[COLUMNS_SCALE], PGTYPE_ATTR_DECIMAL_DIGITS(conn, the_type, atttypmod)); 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); 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"); set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], PGTYPE_ATTR_DISPLAY_SIZE(conn, the_type, atttypmod)); set_tuplefield_int4(&tuple[COLUMNS_FIELD_TYPE], the_type); set_tuplefield_int4(&tuple[COLUMNS_AUTO_INCREMENT], auto_increment); set_tuplefield_int2(&tuple[COLUMNS_PHYSICAL_NUMBER], attnum); set_tuplefield_int4(&tuple[COLUMNS_TABLE_OID], greloid); set_tuplefield_int4(&tuple[COLUMNS_BASE_TYPEID], 0); set_tuplefield_int4(&tuple[COLUMNS_ATTTYPMOD], -1); set_tuplefield_int4(&tuple[COLUMNS_TABLE_INFO], table_info); } RETCODE SQL_API PGAPI_Columns(HSTMT hstmt, const SQLCHAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* PV E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * szTableName, /* PV E*/ SQLSMALLINT cbTableName, const SQLCHAR * szColumnName, /* PV E*/ SQLSMALLINT cbColumnName, UWORD flag, OID reloid, Int2 attnum) { CSTR func = "PGAPI_Columns"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; TupleField *tuple; StatementClass *col_stmt = NULL; PQExpBufferData columns_query = {0}; RETCODE ret = SQL_ERROR, 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, relhassubclass; OID field_type, greloid, basetype; char not_null[MAX_INFO_STRING], relhasrules[MAX_INFO_STRING], relkind[8], attidentity[2]; char *escSchemaName = NULL, *escTableName = NULL, *escColumnName = NULL; BOOL search_pattern = TRUE, search_by_ids, relisaview, show_oid_column, row_versioning; 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; int table_info = 0; static const char *catcn[][2] = { {"TABLE_CAT", "TABLE_QUALIFIER"}, {"TABLE_SCHEM", "TABLE_OWNER"}, {"TABLE_NAME", "TABLE_NAME"}, {"COLUMN_NAME", "COLUMN_NAME"}, {"DATA_TYPE", "DATA_TYPE"}, {"TYPE_NAME", "TYPE_NAME"}, {"COLUMN_SIZE", "PRECISION"}, {"BUFFER_LENGTH", "LENGTH"}, {"DECIMAL_DIGITS", "SCALE"}, {"NUM_PREC_RADIX", "RADIX"}, {"NULLABLE", "NULLABLE"}, {"REMARKS", "REMARKS"}, {"COLUMN_DEF", "COLUMN_DEF"}, {"SQL_DATA_TYPE", "SQL_DATA_TYPE"}, {"SQL_DATETIME_SUB", "SQL_DATETIME_SUB"}, {"CHAR_OCTET_LENGTH", "CHAR_OCTET_LENGTH"}, {"ORDINAL_POSITION", "ORDINAL_POSITION"}, {"IS_NULLABLE", "IS_NULLABLE"}, /* User defined fields */ {"DISPLAY_SIZE", "DISPLAY_SIZE"}, {"FIELD_TYPE", "FIELD_TYPE"}, {"AUTO_INCREMENT", "AUTO_INCREMENT"}, {"PHYSICAL NUMBER", "PHYSICAL NUMBER"}, {"TABLE OID", "TABLE OID"}, {"BASE TYPEID", "BASE TYPEID"}, {"TYPMOD", "TYPMOD"}, {"TABLE INFO", "TABLE INFO"} }; EnvironmentClass *env; BOOL is_ODBC2; MYLOG(0, "entering...stmt=%p scnm=%p len=%d columnOpt=%x\n", stmt, szTableOwner, cbTableOwner, flag); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); ci = &(conn->connInfo); env = CC_get_env(conn); is_ODBC2 = EN_is_odbc2(env); #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??? show_oid_column = ((flag & PODBC_SHOW_OID_COLUMN) != 0); row_versioning = ((flag & PODBC_ROW_VERSIONING) != 0); 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, conn); escColumnName = adjustLikePattern(szColumnName, cbColumnName, conn); } else { like_or_eq = eqop; escTableName = simpleCatalogEscape(szTableName, cbTableName, conn); escColumnName = simpleCatalogEscape(szColumnName, cbColumnName, conn); } } retry_public_schema: if (!search_by_ids) { if (escSchemaName) free(escSchemaName); if (search_pattern) escSchemaName = adjustLikePattern(szSchemaName, cbSchemaName, conn); else escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, conn); } initPQExpBuffer(&columns_query); #define return DONT_CALL_RETURN_FROM_HERE??? /* * 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); printfPQExpBuffer(&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, pg_get_expr(d.adbin, d.adrelid), " "case t.typtype when 'd' then t.typbasetype else 0 end, t.typtypmod, " "%s, %s, c.relhassubclass " "from (((pg_catalog.pg_class c " "inner join pg_catalog.pg_namespace n on n.oid = c.relnamespace", PG_VERSION_GE(conn, 12.0) ? "0" : "c.relhasoids", PG_VERSION_GE(conn, 10.0) ? "attidentity" : "''"); if (search_by_ids) appendPQExpBuffer(&columns_query, " and c.oid = %u", reloid); else { if (escTableName) appendPQExpBuffer(&columns_query, " and c.relname %s'%s'", op_string, escTableName); schema_appendPQExpBuffer1(&columns_query, " and n.nspname %s'%.*s'", op_string, escSchemaName, TABLE_IS_VALID(szTableName, cbTableName), conn); } appendPQExpBufferStr(&columns_query, ") inner join pg_catalog.pg_attribute a" " on (not a.attisdropped)"); if (0 == attnum && (NULL == escColumnName || like_or_eq != eqop)) appendPQExpBufferStr(&columns_query, " and a.attnum > 0"); if (search_by_ids) { if (attnum != 0) appendPQExpBuffer(&columns_query, " and a.attnum = %d", attnum); } else if (escColumnName) appendPQExpBuffer(&columns_query, " and a.attname %s'%s'", op_string, escColumnName); appendPQExpBufferStr(&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"); appendPQExpBufferStr(&columns_query, " order by n.nspname, c.relname, attnum"); if (PQExpBufferDataBroken(columns_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_Columns()", func); goto cleanup; } result = PGAPI_AllocStmt(conn, (HSTMT *) &col_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for PGAPI_Columns result.", func); goto cleanup; } MYLOG(0, "col_stmt = %p\n", col_stmt); result = PGAPI_ExecDirect(col_stmt, (SQLCHAR *) columns_query.data, SQL_NTS, PODBC_RDONLY); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, col_stmt, FALSE); goto cleanup; } /* If not found */ if ((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(col_stmt, SQL_DROP); col_stmt = NULL; szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } } result = PGAPI_BindCol(col_stmt, 1, internal_asis_type, table_owner, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 2, internal_asis_type, table_name, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 3, internal_asis_type, field_name, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 4, SQL_C_ULONG, &field_type, 4, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 5, internal_asis_type, field_type_name, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 6, SQL_C_SHORT, &field_number, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } #ifdef NOT_USED result = PGAPI_BindCol(col_stmt, 7, SQL_C_LONG, &field_length, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } #endif /* NOT_USED */ result = PGAPI_BindCol(col_stmt, 8, SQL_C_LONG, &mod_length, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 9, internal_asis_type, not_null, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 10, internal_asis_type, relhasrules, MAX_INFO_STRING, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 11, internal_asis_type, relkind, sizeof(relkind), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 12, SQL_C_LONG, &greloid, sizeof(greloid), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 14, SQL_C_ULONG, &basetype, sizeof(basetype), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 15, SQL_C_LONG, &typmod, sizeof(typmod), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 16, SQL_C_LONG, &relhasoids, sizeof(relhasoids), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 17, SQL_C_CHAR, attidentity, sizeof(attidentity), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 18, SQL_C_LONG, &relhassubclass, sizeof(relhassubclass), NULL); if (!SQL_SUCCEEDED(result)) { 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_EN(res, COLUMNS_CATALOG_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, COLUMNS_SCHEMA_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, COLUMNS_TABLE_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, COLUMNS_COLUMN_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, COLUMNS_DATA_TYPE, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, COLUMNS_TYPE_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, COLUMNS_PRECISION, PG_TYPE_INT4, 4); /* COLUMN_SIZE */ QR_set_field_info_EN(res, COLUMNS_LENGTH, PG_TYPE_INT4, 4); /* BUFFER_LENGTH */ QR_set_field_info_EN(res, COLUMNS_SCALE, PG_TYPE_INT2, 2); /* DECIMAL_DIGITS ***/ QR_set_field_info_EN(res, COLUMNS_RADIX, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, COLUMNS_NULLABLE, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, COLUMNS_REMARKS, PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); QR_set_field_info_EN(res, COLUMNS_COLUMN_DEF, PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); QR_set_field_info_EN(res, COLUMNS_SQL_DATA_TYPE, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, COLUMNS_SQL_DATETIME_SUB, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, COLUMNS_CHAR_OCTET_LENGTH, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, COLUMNS_ORDINAL_POSITION, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, COLUMNS_IS_NULLABLE, PG_TYPE_VARCHAR, INFO_VARCHAR_SIZE); /* User defined fields */ QR_set_field_info_EN(res, COLUMNS_DISPLAY_SIZE, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, COLUMNS_FIELD_TYPE, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, COLUMNS_AUTO_INCREMENT, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, COLUMNS_PHYSICAL_NUMBER, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, COLUMNS_TABLE_OID, PG_TYPE_OID, 4); QR_set_field_info_EN(res, COLUMNS_BASE_TYPEID, PG_TYPE_OID, 4); QR_set_field_info_EN(res, COLUMNS_ATTTYPMOD, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, COLUMNS_TABLE_INFO, PG_TYPE_INT4, 4); ordinal = 1; result = PGAPI_Fetch(col_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 */ relisaview = (relkind[0] == 'v'); if (SQL_SUCCEEDED(result)) { if (relhasoids) table_info |= TBINFO_HASOIDS; if (relhassubclass) table_info |= TBINFO_HASSUBCLASS; if (!relisaview && relhasoids && (show_oid_column || strncmp(table_name, POSTGRES_SYS_PREFIX, strlen(POSTGRES_SYS_PREFIX)) == 0) && (NULL == escColumnName || 0 == strcmp(escColumnName, OID_NAME))) { const char *typname; /* For OID fields */ tuple = QR_AddNew(res); if (CC_fake_mss(conn)) { typname = "OID identity"; setIdentity = TRUE; } else typname = OID_NAME; add_tuple_for_oid_or_xmin(tuple, ordinal, OID_NAME, PG_TYPE_OID, typname, conn, table_owner, table_name, greloid, OID_ATTNUM, TRUE, table_info); ordinal++; } } while (SQL_SUCCEEDED(result)) { int auto_unique; SQLLEN len_needed; char *attdef; attdef = NULL; PGAPI_SetPos(col_stmt, 1, SQL_POSITION, 0); PGAPI_GetData(col_stmt, 13, internal_asis_type, NULL, 0, &len_needed); if (len_needed > 0) { MYLOG(0, "len_needed=" FORMAT_LEN "\n", len_needed); attdef = malloc(len_needed + 1); if (!attdef) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for attdef.", func); goto cleanup; } PGAPI_GetData(col_stmt, 13, internal_asis_type, attdef, len_needed + 1, &len_needed); MYLOG(0, " 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() */ set_tuplefield_string(&tuple[COLUMNS_SCHEMA_NAME], GET_SCHEMA_NAME(table_owner)); 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 (attidentity[0] != 0 || (attdef && strnicmp(attdef, "nextval(", 8) == 0 && not_null[0] != '0')) { auto_unique = SQL_TRUE; if (!setIdentity && CC_fake_mss(conn)) { char tmp[256]; SPRINTF_FIXED(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 * *---------- */ MYLOG(0, "table='%s',field_name='%s',type=%d,name='%s'\n", table_name, field_name, field_type, field_type_name); /* 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)); set_tuplefield_int4(&tuple[COLUMNS_LENGTH], PGTYPE_ATTR_BUFFER_LENGTH(conn, field_type, mod_length)); set_tuplefield_int4(&tuple[COLUMNS_DISPLAY_SIZE], PGTYPE_ATTR_DISPLAY_SIZE(conn, field_type, mod_length)); set_nullfield_int2(&tuple[COLUMNS_SCALE], PGTYPE_ATTR_DECIMAL_DIGITS(conn, field_type, mod_length)); sqltype = PGTYPE_ATTR_TO_CONCISE_TYPE(conn, field_type, mod_length); concise_type = PGTYPE_ATTR_TO_SQLDESCTYPE(conn, field_type, mod_length); 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 (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)); set_tuplefield_int4(&tuple[COLUMNS_ORDINAL_POSITION], ordinal); set_tuplefield_null(&tuple[COLUMNS_IS_NULLABLE]); 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); set_tuplefield_int4(&tuple[COLUMNS_TABLE_INFO], table_info); ordinal++; result = PGAPI_Fetch(col_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 && row_versioning && (NULL == escColumnName || 0 == strcmp(escColumnName, XMIN_NAME))) { /* For Row Versioning fields */ tuple = QR_AddNew(res); add_tuple_for_oid_or_xmin(tuple, ordinal, XMIN_NAME, PG_TYPE_XID, "xid", conn, table_owner, table_name, greloid, XMIN_ATTNUM, FALSE, table_info); ordinal++; } 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; stmt->catalog_result = TRUE; if (!SQL_SUCCEEDED(ret) && 0 >= SC_get_errornumber(stmt)) SC_error_copy(stmt, col_stmt, 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 (!PQExpBufferDataBroken(columns_query)) termPQExpBuffer(&columns_query); if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (escColumnName) free(escColumnName); if (col_stmt) PGAPI_FreeStmt(col_stmt, SQL_DROP); MYLOG(0, "leaving stmt=%p\n", stmt); return ret; } RETCODE SQL_API PGAPI_SpecialColumns(HSTMT hstmt, SQLUSMALLINT fColType, const SQLCHAR * szTableQualifier, SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, SQLUSMALLINT fScope, SQLUSMALLINT fNullable) { CSTR func = "PGAPI_SpecialColumns"; TupleField *tuple; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; QResultClass *res; StatementClass *col_stmt = NULL; PQExpBufferData columns_query = {0}; char *escSchemaName = NULL, *escTableName = NULL; RETCODE ret = SQL_ERROR, result; 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; int result_cols; static const char *catcn[][2] = { {"SCOPE", "SCOPE"}, {"COLUMN_NAME", "COLUMN_NAME"}, {"DATA_TYPE", "DATA_TYPE"}, {"TYPE_NAME", "TYPE_NAME"}, {"COLUMN_SIZE", "PRECISION"}, {"BUFFER_LENGTH", "LENGTH"}, {"DECIMAL_DIGITS", "SCALE"}, {"PSEUDO_COLUMN", "PSEUDO_COLUMN"}}; EnvironmentClass *env; BOOL is_ODBC2; MYLOG(0, "entering...stmt=%p scnm=%p len=%d colType=%d scope=%d\n", stmt, szTableOwner, cbTableOwner, fColType, fScope); if (result = SC_initialize_and_recycle(stmt), SQL_SUCCESS != result) return result; conn = SC_get_conn(stmt); env = CC_get_env(conn); is_ODBC2 = EN_is_odbc2(env); #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, 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, conn); eq_string = gen_opestr(eqop, conn); initPQExpBuffer(&columns_query); #define return DONT_CALL_RETURN_FROM_HERE??? /* * Create the query to find out if this is a view or not... */ appendPQExpBufferStr(&columns_query, "select c.relhasrules, c.relkind"); if (PG_VERSION_LT(conn, 12.0)) appendPQExpBufferStr(&columns_query, ", c.relhasoids"); else appendPQExpBufferStr(&columns_query, ", 0 as relhasoids"); appendPQExpBufferStr(&columns_query, " from pg_catalog.pg_namespace u," " pg_catalog.pg_class c where " "u.oid = c.relnamespace"); /* TableName cannot contain a string search pattern */ if (escTableName) appendPQExpBuffer(&columns_query, " and c.relname %s'%s'", eq_string, escTableName); /* SchemaName cannot contain a string search pattern */ schema_appendPQExpBuffer1(&columns_query, " and u.nspname %s'%.*s'", eq_string, escSchemaName, TABLE_IS_VALID(szTableName, cbTableName), conn); result = PGAPI_AllocStmt(conn, (HSTMT *) &col_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for SQLSpecialColumns result.", func); goto cleanup; } MYLOG(0, "col_stmt = %p\n", col_stmt); if (PQExpBufferDataBroken(columns_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_SpecialColumns()", func); goto cleanup; } result = PGAPI_ExecDirect(col_stmt, (SQLCHAR *) columns_query.data, SQL_NTS, PODBC_RDONLY); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, col_stmt, FALSE); goto cleanup; } /* If not found */ if ((res = SC_get_Result(col_stmt)) && 0 == QR_get_num_total_tuples(res)) { if (allow_public_schema(conn, szSchemaName, cbSchemaName)) { PGAPI_FreeStmt(col_stmt, SQL_DROP); col_stmt = NULL; szSchemaName = pubstr; cbSchemaName = SQL_NTS; goto retry_public_schema; } SC_set_error(stmt, DESC_BAD_PARAMETER_NUMBER_ERROR, "The specified table does not exist", func); goto cleanup; } result = PGAPI_BindCol(col_stmt, 1, internal_asis_type, relhasrules, sizeof(relhasrules), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, 2, internal_asis_type, relkind, sizeof(relkind), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } relhasoids[0] = '1'; result = PGAPI_BindCol(col_stmt, 3, internal_asis_type, relhasoids, sizeof(relhasoids), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_Fetch(col_stmt); relisaview = (relkind[0] == 'v'); PGAPI_FreeStmt(col_stmt, SQL_DROP); col_stmt = NULL; res = QR_Constructor(); if (!res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for query.", func); goto cleanup; } SC_set_Result(stmt, res); extend_column_bindings(SC_get_ARDF(stmt), 8); stmt->catalog_result = TRUE; result_cols = NUM_OF_SPECOLS_FIELDS; QR_set_num_fields(res, result_cols); QR_set_field_info_EN(res, 0, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 1, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 2, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 3, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, 4, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, 5, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, 6, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, 7, PG_TYPE_INT2, 2); if (relisaview) { /* there's no oid for views */ if (fColType == SQL_BEST_ROWID) { ret = SQL_SUCCESS; goto cleanup; } else if (fColType == SQL_ROWVER) { Int2 the_type = PG_TYPE_TID; int atttypmod = -1; tuple = QR_AddNew(res); set_tuplefield_null(&tuple[SPECOLS_SCOPE]); set_tuplefield_string(&tuple[SPECOLS_COLUMN_NAME], "ctid"); set_tuplefield_int2(&tuple[SPECOLS_DATA_TYPE], PGTYPE_ATTR_TO_CONCISE_TYPE(conn, the_type, atttypmod)); set_tuplefield_string(&tuple[SPECOLS_TYPE_NAME], pgtype_attr_to_name(conn, the_type, atttypmod, FALSE)); set_tuplefield_int4(&tuple[SPECOLS_COLUMN_SIZE], PGTYPE_ATTR_COLUMN_SIZE(conn, the_type, atttypmod)); set_tuplefield_int4(&tuple[SPECOLS_BUFFER_LENGTH], PGTYPE_ATTR_BUFFER_LENGTH(conn, the_type, atttypmod)); set_tuplefield_int2(&tuple[SPECOLS_DECIMAL_DIGITS], PGTYPE_ATTR_DECIMAL_DIGITS(conn, the_type, atttypmod)); set_tuplefield_int2(&tuple[SPECOLS_PSEUDO_COLUMN], SQL_PC_NOT_PSEUDO); MYLOG(DETAIL_LOG_LEVEL, "Add ctid\n"); } } else { /* use the oid value for the rowid */ if (fColType == SQL_BEST_ROWID) { Int2 the_type = PG_TYPE_OID; int atttypmod = -1; if (relhasoids[0] != '1') { ret = SQL_SUCCESS; goto cleanup; } tuple = QR_AddNew(res); set_tuplefield_int2(&tuple[SPECOLS_SCOPE], SQL_SCOPE_SESSION); set_tuplefield_string(&tuple[SPECOLS_COLUMN_NAME], OID_NAME); set_tuplefield_int2(&tuple[SPECOLS_DATA_TYPE], PGTYPE_ATTR_TO_CONCISE_TYPE(conn, the_type, atttypmod)); set_tuplefield_string(&tuple[SPECOLS_TYPE_NAME], pgtype_attr_to_name(conn, the_type, atttypmod, TRUE)); set_tuplefield_int4(&tuple[SPECOLS_COLUMN_SIZE], PGTYPE_ATTR_COLUMN_SIZE(conn, the_type, atttypmod)); set_tuplefield_int4(&tuple[SPECOLS_BUFFER_LENGTH], PGTYPE_ATTR_BUFFER_LENGTH(conn, the_type, atttypmod)); set_tuplefield_int2(&tuple[SPECOLS_DECIMAL_DIGITS], PGTYPE_ATTR_DECIMAL_DIGITS(conn, the_type, atttypmod)); set_tuplefield_int2(&tuple[SPECOLS_PSEUDO_COLUMN], SQL_PC_PSEUDO); } else if (fColType == SQL_ROWVER) { Int2 the_type = PG_TYPE_XID; int atttypmod = -1; tuple = QR_AddNew(res); set_tuplefield_null(&tuple[SPECOLS_SCOPE]); set_tuplefield_string(&tuple[SPECOLS_COLUMN_NAME], XMIN_NAME); set_tuplefield_int2(&tuple[SPECOLS_DATA_TYPE], PGTYPE_ATTR_TO_CONCISE_TYPE(conn, the_type, atttypmod)); set_tuplefield_string(&tuple[SPECOLS_TYPE_NAME], pgtype_attr_to_name(conn, the_type, atttypmod, FALSE)); set_tuplefield_int4(&tuple[SPECOLS_COLUMN_SIZE], PGTYPE_ATTR_COLUMN_SIZE(conn, the_type, atttypmod)); set_tuplefield_int4(&tuple[SPECOLS_BUFFER_LENGTH], PGTYPE_ATTR_BUFFER_LENGTH(conn, the_type, atttypmod)); set_tuplefield_int2(&tuple[SPECOLS_DECIMAL_DIGITS], PGTYPE_ATTR_DECIMAL_DIGITS(conn, the_type, atttypmod)); set_tuplefield_int2(&tuple[SPECOLS_PSEUDO_COLUMN], SQL_PC_PSEUDO); } } ret = SQL_SUCCESS; cleanup: #undef return if (!SQL_SUCCEEDED(ret) && 0 >= SC_get_errornumber(stmt)) SC_error_copy(stmt, col_stmt, TRUE); if (!PQExpBufferDataBroken(columns_query)) termPQExpBuffer(&columns_query); 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 (col_stmt) PGAPI_FreeStmt(col_stmt, SQL_DROP); MYLOG(0, "leaving stmt=%p\n", stmt); return ret; } #define INDOPTION_DESC 0x0001 /* values are in reverse order */ RETCODE SQL_API PGAPI_Statistics(HSTMT hstmt, const SQLCHAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, SQLUSMALLINT fUnique, SQLUSMALLINT fAccuracy) { CSTR func = "PGAPI_Statistics"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn; QResultClass *res; PQExpBufferData index_query = {0}; 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 = NULL, *indx_stmt = NULL; 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; static const char *catcn[][2] = { {"TABLE_CAT", "TABLE_QUALIFIER"}, {"TABLE_SCHEM", "TABLE_OWNER"}, {"TABLE_NAME", "TABLE_NAME"}, {"NON_UNIQUE" , "NON_UNIQUE"}, {"INDEX_QUALIFIER", "INDEX_QUALIFIER"}, {"INDEX_NAME", "INDEX_NAME"}, {"TYPE", "TYPE"}, {"ORDINAL_POSITION", "SEQ_IN_INDEX"}, {"COLUMN_NAME", "COLUMN_NAME"}, {"ASC_OR_DESC", "COLLATION"}, {"CARDINALITY", "CARDINALITY"}, {"PAGES", "PAGES"}, {"FILTER_CONDITION", "FILTER_CONDITION"}}; EnvironmentClass *env; BOOL is_ODBC2; MYLOG(0, "entering...stmt=%p scnm=%p len=%d\n", 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); env = CC_get_env(conn); is_ODBC2 = EN_is_odbc2(env); #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); free(table_name); 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_EN(res, STATS_CATALOG_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, STATS_SCHEMA_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, STATS_TABLE_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, STATS_NON_UNIQUE, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, STATS_INDEX_QUALIFIER, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, STATS_INDEX_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, STATS_TYPE, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, STATS_SEQ_IN_INDEX, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, STATS_COLUMN_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, STATS_COLLATION, PG_TYPE_CHAR, 1); QR_set_field_info_EN(res, STATS_CARDINALITY, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, STATS_PAGES, PG_TYPE_INT4, 4); QR_set_field_info_EN(res, STATS_FILTER_CONDITION, PG_TYPE_VARCHAR, MAX_INFO_STRING); #define return DONT_CALL_RETURN_FROM_HERE??? szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; table_schemaname[0] = '\0'; schema_str(table_schemaname, sizeof(table_schemaname), szSchemaName, cbSchemaName, TABLE_IS_VALID(szTableName, cbTableName), conn); /* * we need to get a list of the field names first, so we can return * them later. */ result = PGAPI_AllocStmt(conn, (HSTMT *) &col_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; } /* * table_name parameter cannot contain a string search pattern. */ result = PGAPI_Columns(col_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); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, COLUMNS_COLUMN_NAME + 1, internal_asis_type, column_name, sizeof(column_name), &column_name_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(col_stmt, COLUMNS_PHYSICAL_NUMBER + 1, SQL_C_SHORT, &field_number, sizeof(field_number), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } alcount = 0; result = PGAPI_Fetch(col_stmt); while (SQL_SUCCEEDED(result)) { if (0 == total_columns) PGAPI_GetData(col_stmt, 2, internal_asis_type, table_schemaname, sizeof(table_schemaname), NULL); if (total_columns >= alcount) { if (0 == alcount) alcount = 4; else alcount *= 2; SC_REALLOC_gexit_with_error(column_names, struct columns_idx, alcount * sizeof(struct columns_idx), stmt, "Couldn't allocate memory for column names.", (result = SQL_ERROR)); } column_names[total_columns].col_name = strdup(column_name); if (!column_names[total_columns].col_name) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for column name.", func); goto cleanup; } column_names[total_columns].pnum = field_number; total_columns++; MYLOG(0, "column_name = '%s'\n", column_name); result = PGAPI_Fetch(col_stmt); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, col_stmt, FALSE); goto cleanup; } PGAPI_FreeStmt(col_stmt, SQL_DROP); col_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, (HSTMT *) &indx_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "PGAPI_AllocStmt failed in SQLStatistics for indices.", func); goto cleanup; } /* TableName cannot contain a string search pattern */ escTableName = simpleCatalogEscape((SQLCHAR *) table_name, SQL_NTS, conn); eq_string = gen_opestr(eqop, conn); escSchemaName = simpleCatalogEscape((SQLCHAR *) table_schemaname, SQL_NTS, conn); initPQExpBuffer(&index_query); printfPQExpBuffer(&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_LT(conn, 12.0) ? "d.relhasoids" : "0" , PG_VERSION_GE(conn, 8.3) ? "i.indoption" : "0" , eq_string, escTableName, eq_string, escSchemaName); appendPQExpBufferStr(&index_query, " i.indisprimary desc,"); appendPQExpBufferStr(&index_query, " i.indisunique, n.nspname, c.relname"); if (PQExpBufferDataBroken(index_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_Columns()", func); goto cleanup; } result = PGAPI_ExecDirect(indx_stmt, (SQLCHAR *) index_query.data, SQL_NTS, PODBC_RDONLY); 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(indx_stmt, 1, internal_asis_type, index_name, MAX_INFO_STRING, &index_name_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } /* bind the vector column */ result = PGAPI_BindCol(indx_stmt, 2, SQL_C_DEFAULT, fields_vector, sizeof(fields_vector), &fields_vector_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } /* bind the "is unique" column */ result = PGAPI_BindCol(indx_stmt, 3, internal_asis_type, isunique, sizeof(isunique), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } /* bind the "is clustered" column */ result = PGAPI_BindCol(indx_stmt, 4, internal_asis_type, isclustered, sizeof(isclustered), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } /* bind the "is hash" column */ result = PGAPI_BindCol(indx_stmt, 5, internal_asis_type, ishash, sizeof(ishash), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(indx_stmt, 6, internal_asis_type, relhasrules, sizeof(relhasrules), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(indx_stmt, 8, SQL_C_ULONG, &ioid, sizeof(ioid), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(indx_stmt, 9, SQL_C_ULONG, &relhasoids, sizeof(relhasoids), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } /* bind the vector column */ result = PGAPI_BindCol(indx_stmt, 10, SQL_C_DEFAULT, indopt_vector, sizeof(fields_vector), &fields_vector_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } relhasrules[0] = '0'; result = PGAPI_Fetch(indx_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)); SPRINTF_FIXED(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(0, "column name = oid\n"); } else if (0 == attnum) { char cmd[64]; QResultClass *res; SPRINTF_FIXED(cmd, "select pg_get_indexdef(%u, %d, true)", ioid, i); res = CC_send_query(conn, cmd, NULL, READ_ONLY_QUERY, 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(0, "column name = UNKNOWN\n"); } else { set_tuplefield_string(&tuple[STATS_COLUMN_NAME], column_names[matchidx].col_name); MYLOG(0, "column name = '%s'\n", 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(indx_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 (!SQL_SUCCEEDED(ret) && 0 >= SC_get_errornumber(stmt)) { SC_error_copy(stmt, col_stmt, TRUE); if (0 >= SC_get_errornumber(stmt)) SC_error_copy(stmt, indx_stmt, TRUE); } if (col_stmt) PGAPI_FreeStmt(col_stmt, SQL_DROP); if (indx_stmt) PGAPI_FreeStmt(indx_stmt, SQL_DROP); /* These things should be freed on any error ALSO! */ if (!PQExpBufferDataBroken(index_query)) termPQExpBuffer(&index_query); 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); MYLOG(0, "leaving stmt=%p, ret=%d\n", stmt, ret); return ret; } RETCODE SQL_API PGAPI_ColumnPrivileges(HSTMT hstmt, const SQLCHAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * szTableName, /* OA(R) E*/ SQLSMALLINT cbTableName, const SQLCHAR * szColumnName, /* PV E*/ SQLSMALLINT cbColumnName, UWORD flag) { CSTR func = "PGAPI_ColumnPrivileges"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn = SC_get_conn(stmt); RETCODE ret = SQL_ERROR; char *escSchemaName = NULL, *escTableName = NULL, *escColumnName = NULL; const char *like_or_eq, *op_string, *eq_string; PQExpBufferData column_query = {0}; BOOL search_pattern; QResultClass *res = NULL; MYLOG(0, "entering...\n"); /* Neither Access or Borland care about this. */ if (SC_initialize_and_recycle(stmt) != SQL_SUCCESS) return SQL_ERROR; escSchemaName = simpleCatalogEscape(szTableOwner, cbTableOwner, conn); escTableName = simpleCatalogEscape(szTableName, cbTableName, conn); search_pattern = (0 == (flag & PODBC_NOT_SEARCH_PATTERN)); if (search_pattern) { like_or_eq = likeop; escColumnName = adjustLikePattern(szColumnName, cbColumnName, conn); } else { like_or_eq = eqop; escColumnName = simpleCatalogEscape(szColumnName, cbColumnName, conn); } initPQExpBuffer(&column_query); #define return DONT_CALL_RETURN_FROM_HERE??? appendPQExpBufferStr(&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) appendPQExpBuffer(&column_query, " and table_schem %s'%s'", eq_string, escSchemaName); if (escTableName) appendPQExpBuffer(&column_query, " and table_name %s'%s'", eq_string, escTableName); if (escColumnName) appendPQExpBuffer(&column_query, " and column_name %s'%s'", op_string, escColumnName); if (PQExpBufferDataBroken(column_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_ColumnPriviles()", func); goto cleanup; } if (res = CC_send_query(conn, column_query.data, NULL, READ_ONLY_QUERY, 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 */ ret = SQL_SUCCESS; cleanup: #undef return if (!SQL_SUCCEEDED(ret)) 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 (!PQExpBufferDataBroken(column_query)) termPQExpBuffer(&column_query); if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (escColumnName) free(escColumnName); return ret; } /* * SQLPrimaryKeys() * * Retrieve the primary key columns for the specified table. */ RETCODE SQL_API PGAPI_PrimaryKeys(HSTMT hstmt, const SQLCHAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* OA E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * 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_ERROR, result; int seq = 0; StatementClass *tbl_stmt = NULL; PQExpBufferData tables_query = {0}; 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; static const char *catcn[][2] = { {"TABLE_CAT", "TABLE_QUALIFIER"}, {"TABLE_SCHEM", "TABLE_OWNER"}, {"TABLE_NAME", "TABLE_NAME"}, {"COLUMN_NAME", "COLUMN_NAME"}, {"KEY_SEQ", "KEY_SEQ"}, {"PK_NAME", "PK_NAME"}}; EnvironmentClass *env; BOOL is_ODBC2; MYLOG(0, "entering...stmt=%p scnm=%p len=%d\n", 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; conn = SC_get_conn(stmt); env = CC_get_env(conn); is_ODBC2 = EN_is_odbc2(env); /* set the field names */ QR_set_num_fields(res, result_cols); QR_set_field_info_EN(res, PKS_TABLE_CAT, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, PKS_TABLE_SCHEM, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, PKS_TABLE_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, PKS_COLUMN_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); QR_set_field_info_EN(res, PKS_KEY_SQ, PG_TYPE_INT2, 2); QR_set_field_info_EN(res, PKS_PK_NAME, PG_TYPE_VARCHAR, MAX_INFO_STRING); result = PGAPI_AllocStmt(conn, (HSTMT *) &tbl_stmt, 0); if (!SQL_SUCCEEDED(result)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate statement for Primary Key result.", func); goto cleanup; } #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); goto cleanup; } szSchemaName = szTableOwner; cbSchemaName = cbTableOwner; escTableName = simpleCatalogEscape(szTableName, cbTableName, conn); } eq_string = gen_opestr(eqop, conn); retry_public_schema: pkscm[0] = '\0'; if (0 == reloid) { if (escSchemaName) free(escSchemaName); escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, conn); schema_str(pkscm, sizeof(pkscm), (SQLCHAR *) escSchemaName, SQL_NTS, TABLE_IS_VALID(szTableName, cbTableName), conn); } result = PGAPI_BindCol(tbl_stmt, 1, internal_asis_type, attname, MAX_INFO_STRING, &attname_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 3, internal_asis_type, pkname, TABLE_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 4, internal_asis_type, pkscm, SCHEMA_NAME_STORAGE_LEN, &pkscm_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 5, internal_asis_type, tabname, TABLE_NAME_STORAGE_LEN, &tabname_len); if (!SQL_SUCCEEDED(result)) { goto cleanup; } initPQExpBuffer(&tables_query); qstart = 1; if (0 == reloid) qend = 2; else qend = 1; for (qno = qstart; qno <= qend; qno++) { resetPQExpBuffer(&tables_query); switch (qno) { case 1: /* * Simplified query to remove assumptions about number of * possible index columns. Courtesy of Tom Lane - thomas * 2000-03-21 */ appendPQExpBufferStr(&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"); if (0 == reloid) appendPQExpBuffer(&tables_query, " where tc.relname %s'%s'" " AND n.nspname %s'%s'" , eq_string, escTableName, eq_string, pkscm); else appendPQExpBuffer(&tables_query, " where tc.oid = %u", reloid); appendPQExpBufferStr(&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"); break; case 2: /* * Simplified query to search old fashoned primary key */ appendPQExpBuffer(&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); break; } if (PQExpBufferDataBroken(tables_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_PrimaryKeys()", func); goto cleanup; } MYLOG(0, "tables_query='%s'\n", tables_query.data); result = PGAPI_ExecDirect(tbl_stmt, (SQLCHAR *) tables_query.data, SQL_NTS, PODBC_RDONLY); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, tbl_stmt, FALSE); goto cleanup; } result = PGAPI_Fetch(tbl_stmt); if (result != SQL_NO_DATA_FOUND) break; } /* If not found */ if (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(0, ">> primaryKeys: schema ='%s', pktab = '%s', attname = '%s', seq = %d\n", pkscm, pktbname, attname, seq); result = PGAPI_Fetch(tbl_stmt); } if (result != SQL_NO_DATA_FOUND) { SC_full_error_copy(stmt, tbl_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 (!SQL_SUCCEEDED(ret) && 0 >= SC_get_errornumber(stmt)) SC_error_copy(stmt, tbl_stmt, TRUE); if (tbl_stmt) PGAPI_FreeStmt(tbl_stmt, SQL_DROP); if (!PQExpBufferDataBroken(tables_query)) termPQExpBuffer(&tables_query); 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); MYLOG(0, "leaving stmt=%p, ret=%d\n", 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 = READ_ONLY_QUERY; *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; SPRINTF_FIXED(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) { SPRINTF_FIXED(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_FIXED(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 */ SPRINTF_FIXED(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; SPRINTF_FIXED(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) { char *tmp; tmp = strdup(QR_get_value_backend_text(res, 0, 0)); if (tmp) { ret = tmp; *nameAlloced = TRUE; } } } QR_Destructor(res); return ret; } static RETCODE SQL_API PGAPI_ForeignKeys_new(HSTMT hstmt, const SQLCHAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName); static RETCODE SQL_API PGAPI_ForeignKeys_old(HSTMT hstmt, const SQLCHAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName) { CSTR func = "PGAPI_ForeignKeys"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; TupleField *tuple; HSTMT hpkey_stmt = NULL; StatementClass *tbl_stmt = NULL; RETCODE ret = SQL_ERROR, result, keyresult; PQExpBufferData tables_query = {0}; 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; SQLSMALLINT defer_type; char pkey[MAX_INFO_STRING]; Int2 result_cols; UInt4 relid1, relid2; const char *eq_string; MYLOG(0, "entering...stmt=%p\n", 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); QR_set_field_info_v(res, FKS_DEFERRABILITY, "DEFERRABILITY", PG_TYPE_INT2, 2); 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, (HSTMT *) &tbl_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??? 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); initPQExpBuffer(&tables_query); /* * 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') { char *escSchemaName; MYLOG(0, " Foreign Key Case #2\n"); escFkTableName = simpleCatalogEscape((SQLCHAR *) fk_table_needed, SQL_NTS, conn); schema_str(schema_needed, sizeof(schema_needed), szFkTableOwner, cbFkTableOwner, TABLE_IS_VALID(szFkTableName, cbFkTableName), conn); escSchemaName = simpleCatalogEscape((SQLCHAR *) schema_needed, SQL_NTS, conn); printfPQExpBuffer(&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); if (PQExpBufferDataBroken(tables_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_ForeignKeys()", func); goto cleanup; } result = PGAPI_ExecDirect(tbl_stmt, (SQLCHAR *) tables_query.data, SQL_NTS, PODBC_RDONLY); if (!SQL_SUCCEEDED(result)) { SC_full_error_copy(stmt, tbl_stmt, FALSE); goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 1, SQL_C_BINARY, trig_args, sizeof(trig_args), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 2, SQL_C_SHORT, &trig_nargs, 0, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 3, internal_asis_type, trig_deferrable, sizeof(trig_deferrable), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 4, internal_asis_type, trig_initdeferred, sizeof(trig_initdeferred), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 5, internal_asis_type, upd_rule, sizeof(upd_rule), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 6, internal_asis_type, del_rule, sizeof(del_rule), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 7, SQL_C_ULONG, &relid1, sizeof(relid1), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 8, SQL_C_ULONG, &relid2, sizeof(relid2), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 9, internal_asis_type, pk_table_fetched, TABLE_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 10, internal_asis_type, constrname, NAMESTORAGELEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 11, internal_asis_type, schema_fetched, SCHEMA_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_Fetch(tbl_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(0, "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(tbl_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(0, "pkey_ptr='%s', pkey='%s'\n", 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; /* 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; /* 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(0, "pk_table = '%s', pkey_ptr = '%s'\n", 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(0, "fk_table_needed = '%s', fkey_ptr = '%s'\n", 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(0, "upd_rule_type = '%i', del_rule_type = '%i'\n, trig_name = '%s'", 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); set_tuplefield_int2(&tuple[FKS_DEFERRABILITY], defer_type); 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(tbl_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') { char *escSchemaName; escPkTableName = simpleCatalogEscape((SQLCHAR *) pk_table_needed, SQL_NTS, conn); schema_str(schema_needed, sizeof(schema_needed), szPkTableOwner, cbPkTableOwner, TABLE_IS_VALID(szPkTableName, cbPkTableName), conn); escSchemaName = simpleCatalogEscape((SQLCHAR *) schema_needed, SQL_NTS, conn); printfPQExpBuffer(&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); if (PQExpBufferDataBroken(tables_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_ForeignKeys()", func); goto cleanup; } result = PGAPI_ExecDirect(tbl_stmt, (SQLCHAR *) tables_query.data, SQL_NTS, PODBC_RDONLY); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 1, SQL_C_BINARY, trig_args, sizeof(trig_args), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 2, SQL_C_SHORT, &trig_nargs, 0, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 3, internal_asis_type, trig_deferrable, sizeof(trig_deferrable), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 4, internal_asis_type, trig_initdeferred, sizeof(trig_initdeferred), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 5, internal_asis_type, upd_rule, sizeof(upd_rule), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 6, internal_asis_type, del_rule, sizeof(del_rule), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 7, SQL_C_ULONG, &relid1, sizeof(relid1), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 8, SQL_C_ULONG, &relid2, sizeof(relid2), NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 9, internal_asis_type, fk_table_fetched, TABLE_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 10, internal_asis_type, constrname, NAMESTORAGELEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_BindCol(tbl_stmt, 11, internal_asis_type, schema_fetched, SCHEMA_NAME_STORAGE_LEN, NULL); if (!SQL_SUCCEEDED(result)) { goto cleanup; } result = PGAPI_Fetch(tbl_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; /* 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; MYLOG(0, "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(0, "pkey_ptr = '%s', fk_table = '%s', fkey_ptr = '%s'\n", pkey_text, fk_table_fetched, fkey_text); tuple = QR_AddNew(res); MYLOG(0, "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(0, "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(0, "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); MYPRINTF(0, " defer_type = %d\n", defer_type); set_tuplefield_int2(&tuple[FKS_DEFERRABILITY], defer_type); 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(tbl_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 (!SQL_SUCCEEDED(ret) && 0 >= SC_get_errornumber(stmt)) SC_error_copy(stmt, tbl_stmt, TRUE); if (!PQExpBufferDataBroken(tables_query)) termPQExpBuffer(&tables_query); 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 (tbl_stmt) PGAPI_FreeStmt(tbl_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); MYLOG(0, "leaving stmt=%p, ret=%d\n", stmt, ret); return ret; } RETCODE SQL_API PGAPI_ForeignKeys(HSTMT hstmt, const SQLCHAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR * 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 static BOOL has_outparam(const char *proargmodes) { const char *ptr; if (!proargmodes) return FALSE; for (ptr = proargmodes; *ptr; ptr++) { switch (*ptr) { case 'o': case 'b': case 't': return TRUE; } } return FALSE; } RETCODE SQL_API PGAPI_ProcedureColumns(HSTMT hstmt, const SQLCHAR * szProcQualifier, /* OA X*/ SQLSMALLINT cbProcQualifier, const SQLCHAR * szProcOwner, /* PV E*/ SQLSMALLINT cbProcOwner, const SQLCHAR * szProcName, /* PV E*/ SQLSMALLINT cbProcName, const SQLCHAR * szColumnName, /* PV X*/ SQLSMALLINT cbColumnName, UWORD flag) { CSTR func = "PGAPI_ProcedureColumns"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn = SC_get_conn(stmt); PQExpBufferData proc_query = {0}; 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 = NULL; SQLLEN tcount; OID pgtype; Int4 paramcount, column_size, i, j; RETCODE ret = SQL_ERROR, result; BOOL search_pattern, bRetset, outpara_exist; 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(0, "entering...\n"); 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, conn); escProcName = adjustLikePattern(szProcName, cbProcName, conn); } else { like_or_eq = eqop; escSchemaName = simpleCatalogEscape(szProcOwner, cbProcOwner, conn); escProcName = simpleCatalogEscape(szProcName, cbProcName, conn); } op_string = gen_opestr(like_or_eq, conn); initPQExpBuffer(&proc_query); #define return DONT_CALL_RETURN_FROM_HERE??? appendPQExpBufferStr(&proc_query, "select proname, proretset, prorettype, " "pronargs, proargtypes, nspname, p.oid"); ret_col = ext_pos = 7; poid_pos = 6; #ifdef PRORET_COUNT appendPQExpBufferStr(&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)) { appendPQExpBufferStr(&proc_query, ", proargnames"); ret_col++; } if (PG_VERSION_GE(conn, 8.1)) { appendPQExpBufferStr(&proc_query, ", proargmodes, proallargtypes"); ret_col += 2; } #ifdef PRORET_COUNT appendPQExpBufferStr(&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 appendPQExpBufferStr(&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 */ appendPQExpBuffer(&proc_query, " has_function_privilege(p.oid, 'EXECUTE')"); if (IS_VALID_NAME(escSchemaName)) appendPQExpBuffer(&proc_query, " and nspname %s'%s'", op_string, escSchemaName); if (escProcName) appendPQExpBuffer(&proc_query, " and proname %s'%s'", op_string, escProcName); appendPQExpBuffer(&proc_query, " order by nspname, proname, p.oid, attnum"); if (escSchemaName) free(escSchemaName); if (escProcName) free(escProcName); if (PQExpBufferDataBroken(proc_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_ProcedureColumns()", func); goto cleanup; } tres = CC_send_query(conn, proc_query.data, NULL, READ_ONLY_QUERY, stmt); if (!QR_command_maybe_successful(tres)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_ProcedureColumns query error", func); QR_Destructor(tres); goto cleanup; } if (res = QR_Constructor(), !res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for PGAPI_ProcedureColumns 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_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); 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); 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++) { schema_name = GET_SCHEMA_NAME(QR_get_value_backend_text(tres, i, 5)); 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'); outpara_exist = FALSE; newpoid = 0; if (poid_pos >= 0) newpoid = QR_get_value_backend_int(tres, i, poid_pos, NULL); MYLOG(0, "newpoid=%d\n", newpoid); atttypid = NULL; if (attid_pos >= 0) { atttypid = QR_get_value_backend_text(tres, i, attid_pos); MYLOG(0, "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); } outpara_exist = has_outparam(proargmodes); /* RETURN_VALUE info */ if (0 != pgtype && PG_TYPE_VOID != pgtype && !bRetset && !atttypid && !outpara_exist) { 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(conn, pgtype)); set_tuplefield_string(&tuple[PROCOLS_TYPE_NAME], PGTYPE_TO_NAME(conn, pgtype, FALSE)); column_size = PGTYPE_COLUMN_SIZE(conn, pgtype); set_nullfield_int4(&tuple[PROCOLS_COLUMN_SIZE], column_size); set_tuplefield_int4(&tuple[PROCOLS_BUFFER_LENGTH], PGTYPE_BUFFER_LENGTH(conn, pgtype)); set_nullfield_int2(&tuple[PROCOLS_DECIMAL_DIGITS], PGTYPE_DECIMAL_DIGITS(conn, pgtype)); 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]); set_tuplefield_null(&tuple[PROCOLS_COLUMN_DEF]); set_tuplefield_int2(&tuple[PROCOLS_SQL_DATA_TYPE], PGTYPE_TO_SQLDESCTYPE(conn, pgtype)); set_nullfield_int2(&tuple[PROCOLS_SQL_DATETIME_SUB], PGTYPE_TO_DATETIME_SUB(conn, pgtype)); set_nullfield_int4(&tuple[PROCOLS_CHAR_OCTET_LENGTH], PGTYPE_TRANSFER_OCTET_LENGTH(conn, pgtype)); set_tuplefield_int4(&tuple[PROCOLS_ORDINAL_POSITION], 0); set_tuplefield_string(&tuple[PROCOLS_IS_NULLABLE], NULL_STRING); } paramcount = 0; params = NULL; if (proargmodes) { const char *p; for (p = proargmodes; *p; p++) { if (',' == (*p)) paramcount++; } paramcount++; params = QR_get_value_backend_text(tres, i, ext_pos + 2); // proallargtypes - oidarray if ('{' == *proargmodes) proargmodes++; } if (0 == paramcount) paramcount = QR_get_value_backend_int(tres, i, 3, NULL); if (0 < paramcount && NULL == params) params = QR_get_value_backend_text(tres, i, 4); // proargtypes - oidvector if (proargnames) { if ('{' == *proargnames) proargnames++; } if (params && '{' == *params) params++; /* 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; IS_NOT_SPACE(*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': case 't': ptype = bRetset ? SQL_RESULT_COL : 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(conn, pgtype)); set_tuplefield_string(&tuple[PROCOLS_TYPE_NAME], PGTYPE_TO_NAME(conn, pgtype, FALSE)); column_size = PGTYPE_COLUMN_SIZE(conn, pgtype); set_nullfield_int4(&tuple[PROCOLS_COLUMN_SIZE], column_size); set_tuplefield_int4(&tuple[PROCOLS_BUFFER_LENGTH], PGTYPE_BUFFER_LENGTH(conn, pgtype)); set_nullfield_int2(&tuple[PROCOLS_DECIMAL_DIGITS], PGTYPE_DECIMAL_DIGITS(conn, pgtype)); 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]); set_tuplefield_null(&tuple[PROCOLS_COLUMN_DEF]); set_tuplefield_int2(&tuple[PROCOLS_SQL_DATA_TYPE], PGTYPE_TO_SQLDESCTYPE(conn, pgtype)); set_nullfield_int2(&tuple[PROCOLS_SQL_DATETIME_SUB], PGTYPE_TO_DATETIME_SUB(conn, pgtype)); set_nullfield_int4(&tuple[PROCOLS_CHAR_OCTET_LENGTH], PGTYPE_TRANSFER_OCTET_LENGTH(conn, pgtype)); set_tuplefield_int4(&tuple[PROCOLS_ORDINAL_POSITION], j + 1); set_tuplefield_string(&tuple[PROCOLS_IS_NULLABLE], NULL_STRING); } } /* RESULT Columns info */ if (!outpara_exist && (NULL != atttypid || bRetset)) { int typid; if (!atttypid) { 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], bRetset ? SQL_RESULT_COL : SQL_PARAM_OUTPUT); set_tuplefield_int2(&tuple[PROCOLS_DATA_TYPE], PGTYPE_TO_CONCISE_TYPE(conn, typid)); set_tuplefield_string(&tuple[PROCOLS_TYPE_NAME], PGTYPE_TO_NAME(conn, typid, FALSE)); column_size = PGTYPE_COLUMN_SIZE(conn, typid); set_nullfield_int4(&tuple[PROCOLS_COLUMN_SIZE], column_size); set_tuplefield_int4(&tuple[PROCOLS_BUFFER_LENGTH], PGTYPE_BUFFER_LENGTH(conn, typid)); set_nullfield_int2(&tuple[PROCOLS_DECIMAL_DIGITS], PGTYPE_DECIMAL_DIGITS(conn, typid)); 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]); set_tuplefield_null(&tuple[PROCOLS_COLUMN_DEF]); set_tuplefield_int2(&tuple[PROCOLS_SQL_DATA_TYPE], PGTYPE_TO_SQLDESCTYPE(conn, typid)); set_nullfield_int2(&tuple[PROCOLS_SQL_DATETIME_SUB], PGTYPE_TO_DATETIME_SUB(conn, typid)); set_nullfield_int4(&tuple[PROCOLS_CHAR_OCTET_LENGTH], PGTYPE_TRANSFER_OCTET_LENGTH(conn, typid)); set_tuplefield_int4(&tuple[PROCOLS_ORDINAL_POSITION], 0); set_tuplefield_string(&tuple[PROCOLS_IS_NULLABLE], NULL_STRING); } } ret = SQL_SUCCESS; cleanup: #undef return if (tres) QR_Destructor(tres); if (!PQExpBufferDataBroken(proc_query)) termPQExpBuffer(&proc_query); /* * 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); return ret; } RETCODE SQL_API PGAPI_Procedures(HSTMT hstmt, const SQLCHAR * szProcQualifier, /* OA X*/ SQLSMALLINT cbProcQualifier, const SQLCHAR * szProcOwner, /* PV E*/ SQLSMALLINT cbProcOwner, const SQLCHAR * szProcName, /* PV E*/ SQLSMALLINT cbProcName, UWORD flag) { CSTR func = "PGAPI_Procedures"; StatementClass *stmt = (StatementClass *) hstmt; ConnectionClass *conn = SC_get_conn(stmt); PQExpBufferData proc_query = {0}; char *escSchemaName = NULL, *escProcName = NULL; QResultClass *res; RETCODE ret = SQL_ERROR, result; const char *like_or_eq, *op_string; BOOL search_pattern; MYLOG(0, "entering... scnm=%p len=%d\n", szProcOwner, cbProcOwner); 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, conn); escProcName = adjustLikePattern(szProcName, cbProcName, conn); } else { like_or_eq = eqop; escSchemaName = simpleCatalogEscape(szProcOwner, cbProcOwner, conn); escProcName = simpleCatalogEscape(szProcName, cbProcName, conn); } /* * The following seems the simplest implementation */ op_string = gen_opestr(like_or_eq, conn); initPQExpBuffer(&proc_query); #define return DONT_CALL_RETURN_FROM_HERE??? appendPQExpBufferStr(&proc_query, "select ''::varchar as " "PROCEDURE_CAT" ", nspname as " "PROCEDURE_SCHEM" "," " proname as " "PROCEDURE_NAME" ", ''::varchar as " "NUM_INPUT_PARAMS" "," " ''::varchar as " "NUM_OUTPUT_PARAMS" ", ''::varchar as " "NUM_RESULT_SETS" "," " ''::varchar 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_appendPQExpBuffer1(&proc_query, " and nspname %s'%.*s'", op_string, escSchemaName, TABLE_IS_VALID(szProcName, cbProcName), conn); if (IS_VALID_NAME(escProcName)) appendPQExpBuffer(&proc_query, " and proname %s'%s'", op_string, escProcName); if (PQExpBufferDataBroken(proc_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_Procedures()", func); goto cleanup; } res = CC_send_query(conn, proc_query.data, NULL, READ_ONLY_QUERY, stmt); if (!QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_Procedures query error", func); QR_Destructor(res); goto cleanup; } SC_set_Result(stmt, res); ret = SQL_SUCCESS; /* * also, things need to think that this statement is finished so the * results can be retrieved. */ cleanup: #undef return stmt->status = STMT_FINISHED; extend_column_bindings(SC_get_ARDF(stmt), 8); if (escSchemaName) free(escSchemaName); if (escProcName) free(escProcName); if (!PQExpBufferDataBroken(proc_query)) termPQExpBuffer(&proc_query); /* 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 ret; } #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(0, "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(0, "addcnt=%d\n", addcnt); } RETCODE SQL_API PGAPI_TablePrivileges(HSTMT hstmt, const SQLCHAR * szTableQualifier, /* OA X*/ SQLSMALLINT cbTableQualifier, const SQLCHAR * szTableOwner, /* PV E*/ SQLSMALLINT cbTableOwner, const SQLCHAR * szTableName, /* PV E*/ SQLSMALLINT cbTableName, UWORD flag) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_TablePrivileges"; ConnectionClass *conn = SC_get_conn(stmt); Int2 result_cols; PQExpBufferData proc_query = {0}; 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_ERROR; const char *like_or_eq, *op_string; const SQLCHAR *szSchemaName; SQLSMALLINT cbSchemaName; char *escSchemaName = NULL, *escTableName = NULL; BOOL search_pattern; MYLOG(0, "entering... scnm=%p len-%d\n", 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 = NUM_OF_TABPRIV_FIELDS; extend_column_bindings(SC_get_ARDF(stmt), result_cols); stmt->catalog_result = TRUE; /* set the field names */ res = QR_Constructor(); if (!res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for query.", func); return SQL_ERROR; } 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, conn); } else { like_or_eq = eqop; escTableName = simpleCatalogEscape(szTableName, cbTableName, conn); } retry_public_schema: if (escSchemaName) free(escSchemaName); if (search_pattern) escSchemaName = adjustLikePattern(szSchemaName, cbSchemaName, conn); else escSchemaName = simpleCatalogEscape(szSchemaName, cbSchemaName, conn); op_string = gen_opestr(like_or_eq, conn); initPQExpBuffer(&proc_query); appendPQExpBufferStr(&proc_query, "select relname, usename, relacl, nspname" " from pg_catalog.pg_namespace, pg_catalog.pg_class ," " pg_catalog.pg_user where"); if (escSchemaName) schema_appendPQExpBuffer1(&proc_query, " nspname %s'%.*s' and", op_string, escSchemaName, TABLE_IS_VALID(szTableName, cbTableName), conn); if (escTableName) appendPQExpBuffer(&proc_query, " relname %s'%s' and", op_string, escTableName); appendPQExpBufferStr(&proc_query, " pg_namespace.oid = relnamespace and relkind in " TABLE_IN_RELKIND " and"); if ((!escTableName) && (!escSchemaName)) appendPQExpBufferStr(&proc_query, " nspname not in ('pg_catalog', 'information_schema') and"); appendPQExpBufferStr(&proc_query, " pg_user.usesysid = relowner"); if (PQExpBufferDataBroken(proc_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_TablePrivileges()", func); goto cleanup; } if (wres = CC_send_query(conn, proc_query.data, NULL, READ_ONLY_QUERY, stmt), !QR_command_maybe_successful(wres)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_TablePrivileges query error", func); goto cleanup; } tablecount = (Int4) QR_get_num_cached_tuples(wres); /* If not found */ if ((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; } } resetPQExpBuffer(&proc_query); appendPQExpBufferStr(&proc_query, "select usename, usesysid, usesuper from pg_user"); if (PQExpBufferDataBroken(proc_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_TablePrivileges()", func); goto cleanup; } if (allures = CC_send_query(conn, proc_query.data, NULL, READ_ONLY_QUERY, stmt), !QR_command_maybe_successful(allures)) { SC_set_error(stmt, STMT_EXEC_ERROR, "PGAPI_TablePrivileges query error", func); goto cleanup; } usercount = (Int4) QR_get_num_cached_tuples(allures); useracl = (char (*)[ACLMAX]) malloc(usercount * sizeof(char [ACLMAX])); if (!useracl) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for user acl.", func); goto cleanup; } 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; resetPQExpBuffer(&proc_query); appendPQExpBuffer(&proc_query, "select grolist from pg_group where groname = '%s'", user); if (PQExpBufferDataBroken(proc_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_TablePrivileges()", func); goto cleanup; } if (gres = CC_send_query(conn, proc_query.data, NULL, READ_ONLY_QUERY, 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(0, "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); 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[TABPRIV_TABLE_CAT], CurrCat(conn)); set_tuplefield_string(&tuple[TABPRIV_TABLE_SCHEM], GET_SCHEMA_NAME(schnm)); set_tuplefield_string(&tuple[TABPRIV_TABLE_NAME], reln); if (su || sys) set_tuplefield_string(&tuple[TABPRIV_GRANTOR], "_SYSTEM"); else set_tuplefield_string(&tuple[TABPRIV_GRANTOR], owner); MYLOG(0, "user=%s\n", user); set_tuplefield_string(&tuple[TABPRIV_GRANTEE], 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[TABPRIV_PRIVILEGE], priv); /* The owner and the super user are grantable */ if (sys || su) set_tuplefield_string(&tuple[TABPRIV_IS_GRANTABLE], "YES"); else set_tuplefield_string(&tuple[TABPRIV_IS_GRANTABLE], "NO"); } } } ret = SQL_SUCCESS; cleanup: #undef return if (escSchemaName) free(escSchemaName); if (escTableName) free(escTableName); if (useracl) free(useracl); if (!PQExpBufferDataBroken(proc_query)) termPQExpBuffer(&proc_query); if (wres) QR_Destructor(wres); if (allures) QR_Destructor(allures); return ret; } static RETCODE SQL_API PGAPI_ForeignKeys_new(HSTMT hstmt, const SQLCHAR * szPkTableQualifier, /* OA X*/ SQLSMALLINT cbPkTableQualifier, const SQLCHAR * szPkTableOwner, /* OA E*/ SQLSMALLINT cbPkTableOwner, const SQLCHAR * szPkTableName, /* OA(R) E*/ SQLSMALLINT cbPkTableName, const SQLCHAR * szFkTableQualifier, /* OA X*/ SQLSMALLINT cbFkTableQualifier, const SQLCHAR * szFkTableOwner, /* OA E*/ SQLSMALLINT cbFkTableOwner, const SQLCHAR * szFkTableName, /* OA(R) E*/ SQLSMALLINT cbFkTableName) { CSTR func = "PGAPI_ForeignKeys"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res = NULL; RETCODE ret = SQL_ERROR, result; PQExpBufferData tables_query = {0}; char *pk_table_needed = NULL, *escTableName = NULL; char *fk_table_needed = NULL; char schema_needed[SCHEMA_NAME_STORAGE_LEN + 1]; char *escSchemaName; 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(0, "entering...stmt=%p\n", 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(0, " Foreign Key Case #2\n"); escTableName = simpleCatalogEscape((SQLCHAR *) fk_table_needed, SQL_NTS, conn); schema_str(schema_needed, sizeof(schema_needed), szFkTableOwner, cbFkTableOwner, TABLE_IS_VALID(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, conn); schema_str(schema_needed, sizeof(schema_needed), szPkTableOwner, cbPkTableOwner, TABLE_IS_VALID(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 (NULL != CurrCat(conn)) SPRINTF_FIXED(catName, "'%s'::name", CurrCat(conn)); else STRCPY_FIXED(catName, "NULL::name"); STRCPY_FIXED(scmName1, "n2.nspname"); STRCPY_FIXED(scmName2, "n1.nspname"); escSchemaName = simpleCatalogEscape((SQLCHAR *) schema_needed, SQL_NTS, conn); initPQExpBuffer(&tables_query); #define return DONT_CALL_RETURN_FROM_HERE??? printfPQExpBuffer(&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\"" ",\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 \"DEFERRABILITY\"" "\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 , SQL_INITIALLY_DEFERRED , SQL_INITIALLY_IMMEDIATE , SQL_NOT_DEFERRABLE , 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, conn); appendPQExpBuffer(&tables_query, "\n where c2.relname %s'%s'", eq_string, escTableName); } appendPQExpBufferStr(&tables_query, "\n order by ref.oid, ref.i"); if (PQExpBufferDataBroken(tables_query)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in PGAPI_SpecialColumns()", func); goto cleanup; } if (res = CC_send_query(conn, tables_query.data, NULL, READ_ONLY_QUERY, 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); if (!PQExpBufferDataBroken(tables_query)) termPQExpBuffer(&tables_query); /* set up the current tuple pointer for SQLFetch */ stmt->currTuple = -1; SC_set_rowset_start(stmt, -1, FALSE); SC_set_current_col(stmt, -1); MYLOG(0, "leaving stmt=%p, ret=%d\n", stmt, ret); return ret; } psqlodbc-13.02.0000/bind.c000644 001751 001751 00000062650 14122574535 016163 0ustar00hiroshihiroshi000000 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 * pcbValue) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_BindParameter"; APDFields *apdopts; IPDFields *ipdopts; PutDataInfo *pdata_info; MYLOG(0, "entering...\n"); 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; 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; /* * 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_DESCRIBED) SC_recycle_statement(stmt); MYLOG(0, "ipar=%d, paramType=%d, fCType=%d, fSqlType=%d, cbColDef=" FORMAT_ULEN ", ibScale=%d,", ipar, fParamType, fCType, fSqlType, cbColDef, ibScale); MYPRINTF(0, "rgbValue=%p(" FORMAT_LEN "), 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 * pcbValue) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_BindCol"; ARDFields *opts; GetDataInfo *gdata_info; BindInfoClass *bookmark; RETCODE ret = SQL_SUCCESS; MYLOG(0, "entering...\n"); MYLOG(0, "**** : stmt = %p, icol = %d\n", stmt, icol); MYLOG(0, "**** : fCType=%d rgb=%p valusMax=" FORMAT_LEN " 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: case SQL_C_VARBOOKMARK: break; default: SC_set_error(stmt, STMT_PROGRAM_TYPE_OUT_OF_RANGE, "Bind column 0 is not of type SQL_C_BOOKMARK", func); MYLOG(DETAIL_LOG_LEVEL, "Bind column 0 is type %d not of type SQL_C_BOOKMARK\n", 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 || !gdata_info->gdata) { 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 */ GETDATA_RESET(gdata_info->gdata[icol]); 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; 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; } opts->bindings[icol].scale = 0; MYLOG(0, " bound buffer[%d] = %p\n", icol, opts->bindings[icol].buffer); } cleanup: #undef return 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 * pfSqlType, SQLULEN * pcbParamDef, SQLSMALLINT * pibScale, SQLSMALLINT * pfNullable) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_DescribeParam"; IPDFields *ipdopts; RETCODE ret = SQL_SUCCESS; int num_params; OID pgtype; ConnectionClass *conn; MYLOG(0, "entering...%d\n", ipar); if (!stmt) { SC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } conn = SC_get_conn(stmt); 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)) { MYLOG(DETAIL_LOG_LEVEL, "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); MYLOG(DETAIL_LOG_LEVEL, "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, FALSE), 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) { MYLOG(DETAIL_LOG_LEVEL, "[%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_attr_to_concise_type(conn, pgtype, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET); 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_attr_column_size(conn, pgtype, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET); } 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 return ret; } /* * 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 * pcpar) { StatementClass *stmt = (StatementClass *) hstmt; CSTR func = "PGAPI_NumParams"; MYLOG(0, "entering...\n"); 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; } MYLOG(DETAIL_LOG_LEVEL, "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; } MYLOG(DETAIL_LOG_LEVEL, "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) { ParameterInfoClass *new_bindings; MYLOG(0, "entering ... self=%p, parameters_allocated=%d, num_params=%d,%p\n", 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(0, "unable to create %d new bindings from %d old bindings\n", num_params, self->allocated); if (self->parameters) free(self->parameters); 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(0, "leaving %p\n", self->parameters); } void extend_iparameter_bindings(IPDFields *self, int num_params) { ParameterImplClass *new_bindings; MYLOG(0, "entering ... self=%p, parameters_allocated=%d, num_params=%d\n", 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(0, "unable to create %d new bindings from %d old bindings\n", num_params, self->allocated); if (self->parameters) free(self->parameters); 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(0, "leaving %p\n", self->parameters); } void reset_a_parameter_binding(APDFields *self, int ipar) { MYLOG(0, "entering ... self=%p, parameters_allocated=%d, ipar=%d\n", 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) { MYLOG(0, "entering ... self=%p, parameters_allocated=%d, ipar=%d\n", 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) { MYLOG(0, "entering self=%p\n", apdopts); if (!apdopts->parameters) return; if (option == STMT_FREE_PARAMS_ALL) { free(apdopts->parameters); apdopts->parameters = NULL; apdopts->allocated = 0; } MYLOG(0, "leaving\n"); } void PDATA_free_params(PutDataInfo *pdata, char option) { int i; MYLOG(0, "entering self=%p\n", 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(0, "leaving\n"); } /* * Free parameters and free the memory. */ void IPD_free_params(IPDFields *ipdopts, char option) { MYLOG(0, "entering self=%p\n", ipdopts); if (!ipdopts->parameters) return; if (option == STMT_FREE_PARAMS_ALL) { free(ipdopts->parameters); ipdopts->parameters = NULL; ipdopts->allocated = 0; } MYLOG(0, "leaving\n"); } void extend_column_bindings(ARDFields *self, int num_columns) { BindInfoClass *new_bindings; int i; MYLOG(0, "entering ... self=%p, bindings_allocated=%d, num_columns=%d\n", 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(0, "unable to create %d new bindings from %d old bindings\n", 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(0, "leaving %p\n", self->bindings); } void reset_a_column_binding(ARDFields *self, int icol) { BindInfoClass *bookmark; MYLOG(0, "entering ... self=%p, bindings_allocated=%d, icol=%d\n", 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; MYLOG(DETAIL_LOG_LEVEL, "freeall=%d allocated=%d bindings=%p\n", 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; MYLOG(DETAIL_LOG_LEVEL, "freeall=%d allocated=%d gdata=%p\n", freeall, self->allocated, self->gdata); if (self->fdata.ttlbuf) { free(self->fdata.ttlbuf); self->fdata.ttlbuf = NULL; } self->fdata.ttlbuflen = self->fdata.ttlbufused = 0; GETDATA_RESET(self->fdata); 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) { GETDATA_RESET(gdata_info->fdata); 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++) { GETDATA_RESET(new_gdata[i]); 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) { GetDataClass *new_gdata; MYLOG(0, "entering ... self=%p, gdata_allocated=%d, num_columns=%d\n", 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(0, "unable to create %d new gdata from %d old gdata\n", 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(0, "leaving %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; GETDATA_RESET(gdata_info->gdata[icol]); } void PutDataInfoInitialize(PutDataInfo *pdata_info) { pdata_info->allocated = 0; pdata_info->pdata = NULL; } void extend_putdata_info(PutDataInfo *self, int num_params, BOOL shrink) { PutDataClass *new_pdata; MYLOG(0, "entering ... self=%p, parameters_allocated=%d, num_params=%d\n", 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(0, "??? 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(0, "unable to create %d new pdata from %d old pdata\n", 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(0, "leaving %p\n", 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-13.02.0000/columninfo.c000644 001751 001751 00000007247 14122574535 017421 0ustar00hiroshihiroshi000000 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 #include #include "pgapifunc.h" #include 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 from a libpq result set. * If self is not null, then also store the information. * If self is null, then just read, don't store. */ BOOL CI_read_fields_from_pgres(ColumnInfoClass *self, PGresult *pgres) { Int2 lf; int new_num_fields; OID new_adtid, new_relid = 0, new_attid = 0; Int2 new_adtsize; Int4 new_atttypmod = -1; char *new_field_name; /* at first read in the number of fields that are in the query */ new_num_fields = PQnfields(pgres); QLOG(0, "\tnFields: %d\n", new_num_fields); if (self) { /* according to that allocate memory */ CI_set_num_fields(self, new_num_fields); if (new_num_fields > 0 && NULL == self->coli_array) return FALSE; } /* now read in the descriptions */ for (lf = 0; lf < new_num_fields; lf++) { new_field_name = PQfname(pgres, lf); new_relid = PQftable(pgres, lf); new_attid = PQftablecol(pgres, lf); new_adtid = PQftype(pgres, lf); new_adtsize = PQfsize(pgres, lf); MYLOG(0, "READING ATTTYPMOD\n"); new_atttypmod = PQfmod(pgres, lf); /* 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; QLOG(0, "\tfieldname='%s', adtid=%d, adtsize=%d, atttypmod=%d (rel,att)=(%d,%d)\n", 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 TRUE; } 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) { 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, const 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 = PG_ADT_UNSET; self->coli_array[field_num].relid = new_relid; self->coli_array[field_num].attid = new_attid; } psqlodbc-13.02.0000/connection.c000644 001751 001751 00000253466 14122574535 017415 0ustar00hiroshihiroshi000000 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" #include "misc.h" #include #include #include /* for htonl */ #ifdef WIN32 #include #else #include #endif #include "environ.h" #include "statement.h" #include "qresult.h" #include "lobj.h" #include "dlg_specific.h" #include "loadlib.h" #include "multibyte.h" #include "pgapifunc.h" #define SAFE_STR(s) (NULL != (s) ? (s) : "(null)") #define STMT_INCREMENT 16 /* how many statement holders to allocate * at a time */ static SQLRETURN CC_lookup_lo(ConnectionClass *self); static int CC_close_eof_cursors(ConnectionClass *self); static void LIBPQ_update_transaction_status(ConnectionClass *self); static void CC_set_error_if_not_set(ConnectionClass *self, int errornumber, const char *errormsg, const char *func) { int errornum = CC_get_errornumber(self); const char *errmsg = CC_get_errormsg(self); if (errornumber == 0) return; if (errornumber > 0) { if (errornum <= 0) CC_set_error(self, errornumber, errormsg, func); else if (!errmsg) CC_set_errormsg(self, errormsg); } else if (errornum == 0) CC_set_error(self, errornumber, errormsg, func); else if (errornum < 0 && !errmsg) CC_set_errormsg(self, errormsg); } RETCODE SQL_API PGAPI_AllocConnect(HENV henv, HDBC * phdbc) { EnvironmentClass *env = (EnvironmentClass *) henv; ConnectionClass *conn; CSTR func = "PGAPI_AllocConnect"; MYLOG(0, "entering...\n"); conn = CC_Constructor(); MYLOG(0, "**** henv = %p, conn = %p\n", 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 * szDSN, SQLSMALLINT cbDSN, const SQLCHAR * szUID, SQLSMALLINT cbUID, const SQLCHAR * szAuthStr, SQLSMALLINT cbAuthStr) { ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci; CSTR func = "PGAPI_Connect"; RETCODE ret = SQL_SUCCESS; char fchar, *tmpstr; MYLOG(0, "entering..cbDSN=%hi.\n", cbDSN); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } ci = &conn->connInfo; CC_conninfo_init(ci, INIT_GLOBALS); make_string(szDSN, cbDSN, ci->dsn, sizeof(ci->dsn)); /* get the values for the DSN from the registry */ getDSNinfo(ci, NULL); 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); } MYLOG(0, "conn = %p (DSN='%s', UID='%s', PWD='%s')\n", conn, ci->dsn, ci->username, NAME_IS_VALID(ci->password) ? "xxxxx" : ""); if ((fchar = CC_connect(conn, 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(0, "leaving..%d.\n", ret); return ret; } RETCODE SQL_API PGAPI_BrowseConnect(HDBC hdbc, const SQLCHAR * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT * pcbConnStrOut) { CSTR func = "PGAPI_BrowseConnect"; ConnectionClass *conn = (ConnectionClass *) hdbc; MYLOG(0, "entering...\n"); 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(0, "entering...\n"); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } 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(0, "about to CC_cleanup\n"); /* Close the connection and free statements */ CC_cleanup(conn, FALSE); MYLOG(0, "done CC_cleanup\n"); MYLOG(0, "leaving...\n"); return SQL_SUCCESS; } RETCODE SQL_API PGAPI_FreeConnect(HDBC hdbc) { ConnectionClass *conn = (ConnectionClass *) hdbc; CSTR func = "PGAPI_FreeConnect"; EnvironmentClass *env; MYLOG(0, "entering...hdbc=%p\n", 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(0, "leaving...\n"); return SQL_SUCCESS; } /* * IMPLEMENTATION CONNECTION CLASS */ static void reset_current_schema(ConnectionClass *self) { if (self->current_schema) { free(self->current_schema); self->current_schema = NULL; } self->current_schema_valid = FALSE; } 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) { 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->unnamed_prepared_stmt = 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; 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; rv->lobj_type = PG_TYPE_LO_UNDEFINED; if (isMsAccess()) rv->ms_jet = 1; rv->isolation = 0; // means initially unknown server's default isolation rv->mb_maxbyte_per_char = 1; rv->max_identifier_length = -1; rv->autocommit_public = SQL_AUTOCOMMIT_ON; /* 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); return rv; cleanup: CC_Destructor(rv); return NULL; } 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(0, "entering self=%p\n", self); if (self->status == CONN_EXECUTING) return 0; CC_cleanup(self, FALSE); /* cleanup socket and statements */ MYLOG(0, "after CC_Cleanup\n"); /* Free up statement holders */ if (self->stmts) { free(self->stmts); self->stmts = NULL; } if (self->descs) { free(self->descs); self->descs = NULL; } MYLOG(0, "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(0, "leaving\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(0, "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(0, "leaving %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'; 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_ */ } CSTR bgncmd = "BEGIN"; CSTR cmtcmd = "COMMIT"; CSTR rbkcmd = "ROLLBACK"; CSTR svpcmd = "SAVEPOINT"; CSTR per_query_svp = "_per_query_svp_"; CSTR rlscmd = "RELEASE"; /* * 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(0, " 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(0, " 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(0, " 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) { BOOL currsts = CC_is_in_autocommit(self); if ((on && currsts) || (!on && !currsts)) return on; MYLOG(0, " %d->%d\n", 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; } } } static void CC_set_locale_encoding(ConnectionClass *self, const char * encoding) { char *currenc = self->locale_encoding; if (encoding) self->locale_encoding = strdup(encoding); else self->locale_encoding = NULL; if (currenc) free(currenc); } static void CC_determine_locale_encoding(ConnectionClass *self) { const char *dbencoding = PQparameterStatus(self->pqconn, "client_encoding"); const char *encoding; QLOG(0, "PQparameterStatus(%p, \"client_encoding\")=%s\n", self->pqconn, SAFE_STR(dbencoding)); if (self->locale_encoding) /* already set */ return; encoding = derive_locale_encoding(dbencoding); if (!encoding) encoding = "SQL_ASCII"; CC_set_locale_encoding(self, encoding); } static void CC_set_client_encoding(ConnectionClass *self, const char * encoding) { char *currenc = self->original_client_encoding; if (encoding) { self->original_client_encoding = strdup(encoding); self->ccsc = pg_CS_code(encoding); } else { self->original_client_encoding = NULL; self->ccsc = SQL_ASCII; } self->mb_maxbyte_per_char = pg_mb_maxlen(self->ccsc); if (currenc) free(currenc); } int CC_send_client_encoding(ConnectionClass *self, const char * encoding) { const char *dbencoding = PQparameterStatus(self->pqconn, "client_encoding"); if (encoding && (!dbencoding || stricmp(encoding, dbencoding))) { char query[64]; QResultClass *res; BOOL cmd_success; SPRINTF_FIXED(query, "set client_encoding to '%s'", encoding); res = CC_send_query(self, query, NULL, 0, NULL); cmd_success = QR_command_maybe_successful(res); QR_Destructor(res); if (!cmd_success) return SQL_ERROR; } CC_set_client_encoding(self, encoding); return SQL_SUCCESS; } /* 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(0, "entering 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->pqconn) { QLOG(0, "PQfinish: %p\n", self->pqconn); PQfinish(self->pqconn); self->pqconn = NULL; } MYLOG(0, "after PQfinish\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; } } /* 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; } } /* 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->unnamed_prepared_stmt = 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->locale_encoding) { free(self->locale_encoding); self->locale_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(0, "leaving\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; } #ifndef PG_DIAG_SEVERITY_NONLOCALIZED #define PG_DIAG_SEVERITY_NONLOCALIZED 'V' #endif void handle_pgres_error(ConnectionClass *self, const PGresult *pgres, const char *comment, QResultClass *res, BOOL error_not_a_notice) { char *errseverity; char *errseverity_nonloc = NULL; char *errprimary = NULL; char *errdetail = NULL; char *errhint = NULL; char *errstatementposition = NULL; char *errinternalquery = NULL; char *errcontext = NULL; char *errschemaname = NULL; char *errtablename = NULL; char *errcolumnname = NULL; char *errdatatypename = NULL; char *errmsg = NULL; char *sqlstate = NULL; int level = MIN_LOG_LEVEL; int display_error_level = (self->connInfo).optional_errors ? 3 : 1; PQExpBufferData errbuf = {0}; MYLOG(DETAIL_LOG_LEVEL, "entering\n"); sqlstate = PQresultErrorField(pgres, PG_DIAG_SQLSTATE); if (res && pgres) { if (sqlstate) STRCPY_FIXED(res->sqlstate, sqlstate); } if (NULL == pgres && NULL == self->pqconn) { const char *errmsg = "The connection has been lost"; MYLOG(0, "setting error message=%s\n", errmsg); QLOG(0, "\t%ssetting error message=%s\n", __FUNCTION__, errmsg); if (CC_get_errornumber(self) <= 0) CC_set_error(self, CONNECTION_COMMUNICATION_ERROR, errmsg, comment); if (res) { QR_set_rstatus(res, PORES_FATAL_ERROR); QR_set_message(res, errmsg); } goto cleanup; } /* * The full message with details and context and everything could * be obtained with PQresultErrorMessage(). I think that would be * more user-friendly, but for now, construct a message with * severity and primary message, which is backwards compatible. */ errseverity = PQresultErrorField(pgres, PG_DIAG_SEVERITY); if (PG_VERSION_GE(self, 9.6)) { errseverity_nonloc = PQresultErrorField(pgres, PG_DIAG_SEVERITY_NONLOCALIZED); MYLOG(0, "PG_DIAG_SEVERITY_NONLOCALIZED=%s\n", SAFE_STR(errseverity_nonloc)); } if (!error_not_a_notice) { if (errseverity_nonloc) { if (stricmp(errseverity_nonloc, "NOTICE") != 0) level = 1; } else if (errseverity) { if (stricmp(errseverity, "NOTICE") != 0) level = 1; } } errprimary = PQresultErrorField(pgres, PG_DIAG_MESSAGE_PRIMARY); if (errseverity_nonloc) QLOG(level, "\t%s(%s) %s '%s'\n", errseverity_nonloc, SAFE_STR(errseverity), SAFE_STR(sqlstate), SAFE_STR(errprimary)); else QLOG(level, "\t(%s) %s '%s'\n", SAFE_STR(errseverity), SAFE_STR(sqlstate), SAFE_STR(errprimary)); if (errprimary == NULL) { /* Hmm. got no primary message. Check if there's a connection error */ if (self->pqconn) errprimary = PQerrorMessage(self->pqconn); if (errprimary == NULL) errprimary = "no error information"; } else if (display_error_level > 0) { errdetail = PQresultErrorField(pgres, PG_DIAG_MESSAGE_DETAIL); errhint = PQresultErrorField(pgres, PG_DIAG_MESSAGE_HINT); errstatementposition = PQresultErrorField(pgres, PG_DIAG_STATEMENT_POSITION); errinternalquery = PQresultErrorField(pgres, PG_DIAG_INTERNAL_POSITION); errcontext = PQresultErrorField(pgres, PG_DIAG_CONTEXT); errschemaname = PQresultErrorField(pgres, PG_DIAG_SCHEMA_NAME); errtablename = PQresultErrorField(pgres, PG_DIAG_TABLE_NAME); errcolumnname = PQresultErrorField(pgres, PG_DIAG_COLUMN_NAME); errdatatypename = PQresultErrorField(pgres, PG_DIAG_DATATYPE_NAME); } initPQExpBuffer(&errbuf); if (errseverity && errprimary) { printfPQExpBuffer(&errbuf, "%s: %s", errseverity, errprimary); if (display_error_level > 0 && errdetail) appendPQExpBuffer(&errbuf, "\nDETAIL: %s", errdetail); if (display_error_level > 1) { if (errhint) appendPQExpBuffer(&errbuf, "\nHINT: %s", errhint); } if (display_error_level > 2) { if (errstatementposition) appendPQExpBuffer(&errbuf, "\nSTATEMENT_POSITION: %s", errstatementposition); if (errinternalquery) appendPQExpBuffer(&errbuf, "\nINTERNAL_QUERY: %s", errinternalquery); if (errcontext) appendPQExpBuffer(&errbuf, "\nCONTEXT: %s", errcontext); if (errschemaname) appendPQExpBuffer(&errbuf, "\nSCHEMA_NAME: %s", errschemaname); if (errtablename) appendPQExpBuffer(&errbuf, "\nTABLE_NAME: %s", errtablename); if (errcolumnname) appendPQExpBuffer(&errbuf, "\nCOLUMN_NAME: %s", errcolumnname); if (errdatatypename) appendPQExpBuffer(&errbuf, "\nDATATYPE_NAME :%s", errdatatypename); } errmsg = errbuf.data; } if (errmsg == NULL) errmsg = errprimary; if (!error_not_a_notice) /* warning, notice, log etc */ { MYLOG(0, "notice message %s\n", errmsg); if (res) { if (QR_command_successful(res)) QR_set_rstatus(res, PORES_NONFATAL_ERROR); /* notice or warning */ QR_add_notice(res, errmsg); /* will dup this string */ } goto cleanup; } MYLOG(0, "error message=%s(" FORMAT_SIZE_T ")\n", errmsg, strlen(errmsg)); if (res) { QR_set_rstatus(res, PORES_FATAL_ERROR); /* error or fatal */ if (errmsg[0]) QR_set_message(res, errmsg); QR_set_aborted(res, TRUE); } /* * If the error is continuable after rollback? */ if (PQstatus(self->pqconn) == CONNECTION_BAD) { CC_set_errornumber(self, CONNECTION_COMMUNICATION_ERROR); CC_on_abort(self, CONN_DEAD); /* give up the connection */ } else if ((errseverity_nonloc && strcmp(errseverity_nonloc, "FATAL") == 0) || (NULL == errseverity_nonloc && errseverity && strcmp(errseverity, "FATAL") == 0)) /* no */ { CC_set_errornumber(self, CONNECTION_SERVER_REPORTED_SEVERITY_FATAL); CC_on_abort(self, CONN_DEAD); /* give up the connection */ } else /* yes */ { CC_set_errornumber(self, CONNECTION_SERVER_REPORTED_SEVERITY_ERROR); if (CC_is_in_trans(self)) CC_set_in_error_trans(self); } cleanup: if (!PQExpBufferDataBroken(errbuf)) termPQExpBuffer(&errbuf); LIBPQ_update_transaction_status(self); } void receive_libpq_notice(void *arg, const PGresult *pgres) { if (arg != NULL) { notice_receiver_arg *nrarg = (notice_receiver_arg *) arg; if (NULL != nrarg->stmt) nrarg->stmt->has_notice = 1; handle_pgres_error(nrarg->conn, pgres, nrarg->comment, nrarg->res, FALSE); } } 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, __DATE__ #ifdef _MSC_VER , _MSC_VER #endif /* _MSC_VER */ ); QLOG(0, "%s", vermsg); MYLOG(DETAIL_LOG_LEVEL, "Global Options: fetch=%d, unknown_sizes=%d, max_varchar_size=%d, max_longvarchar_size=%d\n", ci->drivers.fetch_max, ci->drivers.unknown_sizes, ci->drivers.max_varchar_size, ci->drivers.max_longvarchar_size); MYLOG(DETAIL_LOG_LEVEL, " unique_index=%d, use_declarefetch=%d\n", ci->drivers.unique_index, ci->drivers.use_declarefetch); MYLOG(DETAIL_LOG_LEVEL, " 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); if (NULL == self->locale_encoding) { encoding = check_client_encoding(ci->conn_settings); CC_set_locale_encoding(self, encoding); MYLOG(DETAIL_LOG_LEVEL, " extra_systable_prefixes='%s', conn_settings='%s' conn_encoding='%s'\n", ci->drivers.extra_systable_prefixes, PRINT_NAME(ci->conn_settings), encoding ? encoding : ""); } if (self->status == CONN_DOWN) { CC_set_error_if_not_set(self, CONN_OPENDB_ERROR, "Connection broken.", func); return 0; } else if (self->status != CONN_NOT_CONNECTED) { CC_set_error_if_not_set(self, CONN_OPENDB_ERROR, "Already connected.", func); return 0; } MYLOG(0, "DSN = '%s', server = '%s', port = '%s', database = '%s', username = '%s', password='%s'\n", ci->dsn, ci->server, ci->port, ci->database, ci->username, NAME_IS_VALID(ci->password) ? "xxxxx" : ""); return 1; } static int handle_show_results(const QResultClass *res); #define TRANSACTION_ISOLATION "transaction_isolation" #define ISOLATION_SHOW_QUERY "show " TRANSACTION_ISOLATION static int LIBPQ_connect(ConnectionClass *self); static char LIBPQ_CC_connect(ConnectionClass *self, char *salt_para) { int ret; CSTR func = "LIBPQ_CC_connect"; QResultClass *res; MYLOG(0, "entering...\n"); if (0 == CC_initial_log(self, func)) return 0; if (ret = LIBPQ_connect(self), ret <= 0) return ret; res = CC_send_query(self, "SET DateStyle = 'ISO';SET extra_float_digits = 2;" ISOLATION_SHOW_QUERY, NULL, READ_ONLY_QUERY, NULL); if (QR_command_maybe_successful(res)) { handle_show_results(res); ret = 1; } else ret = 0; QR_Destructor(res); return ret; } char CC_connect(ConnectionClass *self, char *salt_para) { ConnInfo *ci = &(self->connInfo); CSTR func = "CC_connect"; char ret, *saverr = NULL, retsend; const char *errmsg = NULL; MYLOG(0, "entering...sslmode=%s\n", self->connInfo.sslmode); ret = LIBPQ_CC_connect(self, salt_para); 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. */ /* Per Datasource settings */ retsend = CC_send_settings(self, GET_NAME(self->connInfo.conn_settings)); if (CONN_DOWN == self->status) { ret = 0; goto cleanup; } if (CC_get_errornumber(self) > 0 && NULL != (errmsg = CC_get_errormsg(self))) saverr = strdup(errmsg); CC_clear_error(self); /* clear any error */ if (!SQL_SUCCEEDED(CC_lookup_lo(self))) /* a hack to get the oid of our large object oid type */ { ret = 0; goto cleanup; } /* * Multibyte handling * * Send 'UTF8' when required Unicode behavior, otherwise send * locale encodings. */ CC_clear_error(self); CC_determine_locale_encoding(self); /* determine the locale_encoding */ #ifdef UNICODE_SUPPORT if (CC_is_in_unicode_driver(self)) { if (!SQL_SUCCEEDED(CC_send_client_encoding(self, "UTF8"))) { ret = 0; goto cleanup; } } else /* for unicode drivers require ANSI behavior */ #endif /* UNICODE_SUPPORT */ { if (!SQL_SUCCEEDED(CC_send_client_encoding(self, self->locale_encoding))) { ret = 0; goto cleanup; } } CC_clear_error(self); if (self->server_isolation != self->isolation) if (!CC_set_transact(self, self->isolation)) { ret = 0; goto cleanup; } ci_updatable_cursors_set(ci); 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) && (CC_is_in_ansi_app(self) || 0 < ci->bde_environment)) self->unicode |= CONN_DISALLOW_WCHAR; MYLOG(0, "conn->unicode=%d Client Encoding='%s' (Code %d)\n", self->unicode, self->original_client_encoding, self->ccsc); ret = 1; cleanup: MYLOG(0, "leaving...%d\n", ret); if (NULL != saverr) { if (ret > 0 && CC_get_errornumber(self) <= 0) CC_set_error(self, -1, saverr, func); free(saverr); } if (1 == ret && FALSE == retsend) ret = 2; return ret; } char CC_add_statement(ConnectionClass *self, StatementClass *stmt) { int i; char ret = TRUE; MYLOG(0, "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(0, "entering 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; } char CC_get_escape(const ConnectionClass *self) { const char *scf; static const ConnectionClass *conn = NULL; scf = PQparameterStatus(self->pqconn, "standard_conforming_strings"); if (self != conn) { QLOG(0, "PQparameterStatus(%p, \"standard_conforming_strings\")=%s\n", self->pqconn, SAFE_STR(scf)); conn = self; } if (scf == NULL) { /* we're connected to a pre-8.1 server, and E'' is not supported */ return '\0'; } if (strcmp(scf, "on") != 0) return ESCAPE_IN_LITERAL; else return '\0'; } 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, READ_ONLY_QUERY, NULL); if (QR_command_maybe_successful(res)) len = self->max_identifier_length = QR_get_value_backend_int(res, 0, 0, FALSE); QR_Destructor(res); } MYLOG(0, "max_identifier_length=%d\n", len); return len < 0 ? 0 : len; } static SQLINTEGER isolation_str_to_enum(const char *str_isolation) { SQLINTEGER isolation = 0; if (strnicmp(str_isolation, "seri", 4) == 0) isolation = SQL_TXN_SERIALIZABLE; else if (strnicmp(str_isolation, "repe", 4) == 0) isolation = SQL_TXN_REPEATABLE_READ; else if (strnicmp(str_isolation, "read com", 8) == 0) isolation = SQL_TXN_READ_COMMITTED; else if (strnicmp(str_isolation, "read unc", 8) == 0) isolation = SQL_TXN_READ_UNCOMMITTED; return isolation; } static int handle_show_results(const QResultClass *res) { int count = 0; const QResultClass *qres; ConnectionClass *conn = QR_get_conn(res); for (qres = res; qres; qres = QR_nextr(qres)) { if (!qres->command || stricmp(qres->command, "SHOW") != 0) continue; if (strcmp(QR_get_fieldname(qres, 0), TRANSACTION_ISOLATION) == 0) { conn->server_isolation = isolation_str_to_enum(QR_get_value_backend_text(qres, 0, 0)); MYLOG(0, "isolation " FORMAT_UINTEGER " to be " FORMAT_UINTEGER "\n", conn->server_isolation, conn->isolation); if (0 == conn->isolation) conn->isolation = conn->server_isolation; if (0 == conn->default_isolation) conn->default_isolation = conn->server_isolation; count++; } } return count; } /* * This function may not be called as long as ISOLATION_SHOW_QUERY is * issued in LIBPQ_CC_connect. */ SQLUINTEGER CC_get_isolation(ConnectionClass *self) { SQLUINTEGER isolation = 0; QResultClass *res; res = CC_send_query(self, ISOLATION_SHOW_QUERY, NULL, READ_ONLY_QUERY, NULL); if (QR_command_maybe_successful(res)) { handle_show_results(res); isolation = self->server_isolation; } QR_Destructor(res); MYLOG(0, "isolation=" FORMAT_UINTEGER "\n", isolation); return isolation; } 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; MYLOG(0, "entering\n"); CONNLOCK_ACQUIRE(self); 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(0, "leaving\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)) { SPRINTF_FIXED(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 | READ_ONLY_QUERY, NULL); QR_set_no_survival_check(res); if (QR_command_maybe_successful(wres) && CONN_ERROR_IGNORED != CC_get_errornumber(self)) QR_set_permanent(res); else QR_set_cursor(res, NULL); QR_Destructor(wres); CONNLOCK_ACQUIRE(self); MYLOG(DETAIL_LOG_LEVEL, "%p->permanent -> %d %p\n", res, QR_is_permanent(res), QR_get_cursor(res)); } 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) { if (conn->on_commit_in_progress) return; conn->on_commit_in_progress = 1; CONNLOCK_ACQUIRE(conn); if (CC_is_in_trans(conn)) { CC_set_no_trans(conn); CC_set_no_manual_trans(conn); } CC_svp_init(conn); CC_start_stmt(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); conn->on_commit_in_progress = 0; } void CC_on_abort(ConnectionClass *conn, unsigned int opt) { BOOL set_no_trans = FALSE; MYLOG(0, "entering opt=%x\n", opt); 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_svp_init(conn); CC_start_stmt(conn); CC_clear_cursors(conn, TRUE); if (0 != (opt & CONN_DEAD)) { conn->status = CONN_DOWN; if (conn->pqconn) { CONNLOCK_RELEASE(conn); QLOG(0, "PQfinish: %p\n", conn->pqconn); PQfinish(conn->pqconn); CONNLOCK_ACQUIRE(conn); conn->pqconn = 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(0, "entering\n"); CONNLOCK_ACQUIRE(conn); ProcessRollback(conn, TRUE, TRUE); CC_discard_marked_objects(conn); CONNLOCK_RELEASE(conn); } static BOOL is_setting_search_path(const char *query) { const char *q = query; if (strnicmp(q, "set", 3) != 0) return FALSE; q += 3; while (isspace(*q)) q++; for (; *q;) { if (IS_NOT_SPACE(*q)) { if (strnicmp(q, "search_path", 11) == 0) return TRUE; q++; while (IS_NOT_SPACE(*q)) q++; } else q++; } return FALSE; } static BOOL CC_from_PGresult(QResultClass *res, StatementClass *stmt, ConnectionClass *conn, const char *cursor, PGresult **pgres) { BOOL success = TRUE; if (!QR_from_PGresult(res, stmt, conn, cursor, pgres)) { QLOG(0, "\tGetting result from PGresult failed\n"); 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; } } } return success; } int CC_internal_rollback(ConnectionClass *self, int rollback_type, BOOL ignore_abort) { int ret = 0; char cmd[128]; PGresult *pgres = NULL; if (!CC_is_in_error_trans(self)) return 1; switch (rollback_type) { case PER_STATEMENT_ROLLBACK: GenerateSvpCommand(self, INTERNAL_ROLLBACK_OPERATION, cmd, sizeof(cmd)); QLOG(0, "PQexec: %p '%s'\n", self->pqconn, cmd); pgres = PQexec(self->pqconn, cmd); switch (PQresultStatus(pgres)) { case PGRES_COMMAND_OK: QLOG(0, "\tok: - 'C' - %s\n", PQcmdStatus(pgres)); case PGRES_NONFATAL_ERROR: ret = 1; if (ignore_abort) CC_set_no_error_trans(self); LIBPQ_update_transaction_status(self); break; default: handle_pgres_error(self, pgres, __FUNCTION__, NULL, TRUE); break; } break; case PER_QUERY_ROLLBACK: SPRINTF_FIXED(cmd, "%s TO %s;%s %s" , rbkcmd, per_query_svp , rlscmd, per_query_svp); QLOG(0, "PQsendQuery: %p '%s'\n", self->pqconn, cmd); PQsendQuery(self->pqconn, cmd); ret = 0; while (self->pqconn && (pgres = PQgetResult(self->pqconn)) != NULL) { switch (PQresultStatus(pgres)) { case PGRES_COMMAND_OK: QLOG(0, "\tok: - 'C' - %s\n", PQcmdTuples(pgres)); ret = 1; break; case PGRES_NONFATAL_ERROR: ret = 1; default: handle_pgres_error(self, pgres, __FUNCTION__, NULL, !ret); } } if (!ret) { if (ignore_abort) CC_set_no_error_trans(self); else MYLOG(0, " return error\n"); } LIBPQ_update_transaction_status(self); break; } if (pgres) PQclear(pgres); return ret; } /* * 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. * * * If issue_begin, send "BEGIN" * * if needed, send "SAVEPOINT ..." * * Send "query", read result * * Send appendq, read result. * */ QResultHold CC_send_query_append(ConnectionClass *self, const char *query, QueryInfo *qi, UDWORD flag, StatementClass *stmt, const char *appendq) { CSTR func = "CC_send_query"; QResultHold rhold = {0}; 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, read_only, prepend_savepoint = FALSE, ignore_roundtrip_time = ((self->connInfo.extra_opts & BIT_IGNORE_ROUND_TRIP_TIME) != 0); char *ptr; BOOL ReadyToReturn = FALSE, query_completed = FALSE, aborted = FALSE, used_passed_result_object = FALSE, discard_next_begin = FALSE, discard_next_savepoint = FALSE, discard_next_release = FALSE, consider_rollback; BOOL discardTheRest = FALSE; int func_cs_count = 0; PQExpBufferData query_buf = {0}; size_t query_len; /* QR_set_command() dups this string so doesn't need static */ char *cmdbuffer; PGresult *pgres = NULL; notice_receiver_arg nrarg; if (appendq) { MYLOG(0, "conn=%p, query='%s'+'%s'\n", self, query, appendq); } else { MYLOG(0, "conn=%p, query='%s'\n", self, query); } if (!self->pqconn) { PQExpBufferData pbuf = {0}; initPQExpBuffer(&pbuf); appendPQExpBuffer(&pbuf, "The connection is down\nFailed to send '%s'", query); CC_set_error(self, CONNECTION_COULD_NOT_SEND, pbuf.data, func); termPQExpBuffer(&pbuf); return rhold; } ENTER_INNER_CONN_CS(self, func_cs_count); /* Indicate that we are sending a query to the backend */ if ((NULL == query) || (query[0] == '\0')) { CLEANUP_FUNC_CONN_CS(func_cs_count, self); return rhold; } /* * 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 && ignore_roundtrip_time) { QResultHold rholda; rhold = CC_send_query_append(self, query, qi, flag, stmt, NULL); if (QR_command_maybe_successful(rhold.first)) { rholda = CC_send_query_append(self, appendq, qi, flag & (~(GO_INTO_TRANSACTION)), stmt, NULL); if (QR_command_maybe_successful(rholda.first)) QR_concat(rhold.last, rholda.first); else { QR_Destructor(rhold.first); rhold = rholda; } } CLEANUP_FUNC_CONN_CS(func_cs_count, self); return rhold; } rollback_on_error = (flag & ROLLBACK_ON_ERROR) != 0; end_with_commit = (flag & END_WITH_COMMIT) != 0; read_only = (flag & READ_ONLY_QUERY) != 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); unsigned int svpopt = 0; if (read_only) svpopt |= SVPOPT_RDONLY; if (!ignore_roundtrip_time) svpopt |= SVPOPT_REDUCE_ROUNDTRIP; if (!CC_started_rbpoint(self)) { if (SQL_ERROR == SetStatementSvp(astmt, svpopt)) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal savepoint error", func); goto cleanup; } } } } /* prepend internal savepoint command ? */ if (PREPEND_IN_PROGRESS == self->internal_op) prepend_savepoint = TRUE; /* append all these together, to avoid round-trips */ query_len = strlen(query); MYLOG(0, "query_len=" FORMAT_SIZE_T "\n", query_len); initPQExpBuffer(&query_buf); /* issue_begin, query_rollback and prepend_savepoint are exclusive */ if (issue_begin) { appendPQExpBuffer(&query_buf, "%s;", bgncmd); discard_next_begin = TRUE; } else if (query_rollback) { appendPQExpBuffer(&query_buf, "%s %s;", svpcmd, per_query_svp); discard_next_savepoint = TRUE; } else if (prepend_savepoint) { char prepend_cmd[128]; GenerateSvpCommand(self, INTERNAL_SAVEPOINT_OPERATION, prepend_cmd, sizeof(prepend_cmd)); appendPQExpBuffer(&query_buf, "%s;", prepend_cmd); self->internal_op = SAVEPOINT_IN_PROGRESS; } appendPQExpBufferStr(&query_buf, query); if (appendq) { appendPQExpBuffer(&query_buf, ";%s", appendq); } if (query_rollback) { appendPQExpBuffer(&query_buf, ";%s %s", rlscmd, per_query_svp); } if (PQExpBufferDataBroken(query_buf)) { CC_set_error(self, CONN_NO_MEMORY_ERROR, "Couldn't alloc buffer for query.", ""); goto cleanup; } /* Set up notice receiver */ nrarg.conn = self; nrarg.comment = func; nrarg.res = NULL; nrarg.stmt = stmt; PQsetNoticeReceiver(self->pqconn, receive_libpq_notice, &nrarg); QLOG(0, "PQsendQuery: %p '%s'\n", self->pqconn, query_buf.data); if (!PQsendQuery(self->pqconn, query_buf.data)) { char *errmsg = PQerrorMessage(self->pqconn); QLOG(0, "\nCommunication Error: %s\n", SAFE_STR(errmsg)); CC_set_error(self, CONNECTION_COMMUNICATION_ERROR, errmsg, func); goto cleanup; } PQsetSingleRowMode(self->pqconn); 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; if (qi) { res->cmd_fetch_size = qi->fetch_size; res->cache_size = qi->row_size; } nrarg.res = res; while (self->pqconn && (pgres = PQgetResult(self->pqconn)) != NULL) { int status = PQresultStatus(pgres); if (discardTheRest) continue; switch (status) { case PGRES_COMMAND_OK: /* portal query command, no tuples returned */ /* read in the return message from the backend */ cmdbuffer = PQcmdStatus(pgres); QLOG(0, "\tok: - 'C' - %s\n", cmdbuffer); if (query_completed) /* allow for "show" style notices */ { QR_concat(res, QR_Constructor()); if (!QR_nextr(res)) { CC_set_error(self, CONNECTION_COULD_NOT_RECEIVE, "Could not create result info in send_query.", func); ReadyToReturn = TRUE; retres = NULL; break; } res = QR_nextr(res); nrarg.res = res; } MYLOG(0, " setting cmdbuffer = '%s'\n", cmdbuffer); my_trim(cmdbuffer); /* get rid of trailing space */ if (strnicmp(cmdbuffer, bgncmd, strlen(bgncmd)) == 0) { CC_set_in_trans(self); if (discard_next_begin) /* discard the automatically issued BEGIN */ { discard_next_begin = FALSE; break; /* discard the result */ } } /* * There are 2 risks to RELEASE an internal savepoint. * One is to RELEASE the savepoint invalitated * due to manually issued ROLLBACK or RELEASE. * Another is to invalitate manual SAVEPOINTs unexpectedly * by RELEASing the internal savepoint. */ else if (strnicmp(cmdbuffer, svpcmd, strlen(svpcmd)) == 0) { if (discard_next_savepoint) { discard_next_savepoint = FALSE; discard_next_release = TRUE; MYLOG(DETAIL_LOG_LEVEL, "Discarded a SAVEPOINT result\n"); break; /* discard the result */ } if (SAVEPOINT_IN_PROGRESS == self->internal_op) { CC_start_rbpoint(self); self->internal_op = 0; break; /* discard the result */ } /* Don't release the internal savepoint */ self->internal_svp = 0; } else if (strnicmp(cmdbuffer, rbkcmd, strlen(rbkcmd)) == 0) { CC_mark_cursors_doubtful(self); CC_set_in_error_trans(self); /* mark the transaction error in case of manual rollback */ self->internal_svp = 0; /* possibly an internal savepoint is invalid */ self->opt_previous = 0; /* unknown */ CC_init_opt_in_progress(self); } else if (strnicmp(cmdbuffer, rlscmd, strlen(rlscmd)) == 0) { if (discard_next_release) { MYLOG(DETAIL_LOG_LEVEL, "Discarded a RELEASE result\n"); discard_next_release = FALSE; break; /* discard the result */ } self->internal_svp = 0; if (SAVEPOINT_IN_PROGRESS == self->internal_op) break; /* discard the result */ } /* * 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 (self->current_schema_valid && strnicmp(cmdbuffer, "SET", 3) == 0) { if (is_setting_search_path(query)) reset_current_schema(self); } } if (QR_command_successful(res)) QR_set_rstatus(res, PORES_COMMAND_OK); QR_set_command(res, cmdbuffer); query_completed = TRUE; MYLOG(0, " returning res = %p\n", res); break; case PGRES_EMPTY_QUERY: /* We return the empty query */ QR_set_rstatus(res, PORES_EMPTY_QUERY); break; case PGRES_NONFATAL_ERROR: handle_pgres_error(self, pgres, "send_query", res, FALSE); if (stmt) stmt->has_notice = 1; break; case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: handle_pgres_error(self, pgres, "send_query", res, TRUE); /* We should report that an error occured. Zoltan */ aborted = TRUE; query_completed = TRUE; break; case PGRES_TUPLES_OK: QLOG(0, "\tok: - 'T' - %s\n", PQcmdStatus(pgres)); case PGRES_SINGLE_TUPLE: if (query_completed) { QR_concat(res, QR_Constructor()); if (!QR_nextr(res)) { 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(QR_nextr(res)); if (stmt) { if (stmt->num_key_fields < 0) /* for safety */ CheckPgClassInfo(stmt); QR_nextr(res)->num_key_fields = stmt->num_key_fields; } } MYLOG(0, " 'T' no result_in: res = %p\n", QR_nextr(res)); res = QR_nextr(res); nrarg.res = res; if (qi) { QR_set_cache_size(res, qi->row_size); res->cmd_fetch_size = qi->fetch_size; } } if (!used_passed_result_object) { const char *cursor = qi ? qi->cursor : NULL; if (create_keyset) { QR_set_haskeyset(res); if (stmt) { if (stmt->num_key_fields < 0) /* for safety */ CheckPgClassInfo(stmt); res->num_key_fields = stmt->num_key_fields; } if (cursor && cursor[0]) QR_set_synchronize_keys(res); } if (CC_from_PGresult(res, stmt, self, cursor, &pgres)) query_completed = TRUE; else { aborted = TRUE; if (QR_command_maybe_successful(res)) retres = NULL; else retres = cmdres; } } else { /* next fetch, so reuse an existing result */ const char *cursor = res->cursor_name; /* * called from QR_next_tuple and must return * immediately. */ if (!CC_from_PGresult(res, stmt, NULL, cursor, &pgres)) { retres = NULL; break; } retres = cmdres; } if (res->rstatus == PORES_TUPLES_OK && res->notice) { QR_set_rstatus(res, PORES_NONFATAL_ERROR); } else if (PORES_NO_MEMORY_ERROR == QR_get_rstatus(res)) { PGcancel *cancel; char dummy[8]; discardTheRest = TRUE; if (NULL != (cancel = PQgetCancel(self->pqconn))) { PQcancel(cancel, dummy, sizeof(dummy)); PQfreeCancel(cancel); } else goto cleanup; } break; case PGRES_COPY_OUT: /* XXX: We used to read from stdin here. Does that make any sense? */ case PGRES_COPY_IN: if (query_completed) { QR_concat(res, QR_Constructor()); if (!QR_nextr(res)) { CC_set_error(self, CONNECTION_COULD_NOT_RECEIVE, "Could not create result info in send_query.", func); ReadyToReturn = TRUE; retres = NULL; break; } res = QR_nextr(res); nrarg.res = res; } QR_set_rstatus(res, PORES_COPY_IN); ReadyToReturn = TRUE; retres = cmdres; break; case PGRES_COPY_BOTH: default: /* skip the unexpected response if possible */ CC_set_error(self, CONNECTION_BACKEND_CRAZY, "Unexpected result status (send_query)", func); handle_pgres_error(self, pgres, "send_query", res, TRUE); CC_on_abort(self, CONN_DEAD); MYLOG(0, " error - %s\n", CC_get_errormsg(self)); ReadyToReturn = TRUE; retres = NULL; break; } if (pgres) { PQclear(pgres); pgres = NULL; } } cleanup: if (self->pqconn) PQsetNoticeReceiver(self->pqconn, receive_libpq_notice, NULL); if (pgres != NULL) { PQclear(pgres); pgres = NULL; } MYLOG(DETAIL_LOG_LEVEL, " rollback_on_error=%d CC_is_in_trans=%d discard_next_savepoint=%d query_rollback=%d\n", rollback_on_error, CC_is_in_trans(self), discard_next_savepoint, query_rollback); if (rollback_on_error && CC_is_in_trans(self) && !discard_next_savepoint) { if (query_rollback) { if (!CC_internal_rollback(self, PER_QUERY_ROLLBACK, ignore_abort_on_conn)) ignore_abort_on_conn = FALSE; } else if (CC_is_in_error_trans(self)) { QLOG(0, "PQexec: %p '%s'\n", self->pqconn, rbkcmd); pgres = PQexec(self->pqconn, rbkcmd); } /* * XXX: we don't check the result here. Should we? We're rolling back, * so it's not clear what else we can do on error. Giving an error * message to the application would be nice though. */ if (pgres != NULL) { PQclear(pgres); pgres = NULL; } } CLEANUP_FUNC_CONN_CS(func_cs_count, self); #undef return /* * Break before being ready to return. */ if (!ReadyToReturn) retres = cmdres; if (!PQExpBufferDataBroken(query_buf)) termPQExpBuffer(&query_buf); /* * 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; QR_nextr(qres); qres = retres) { if (QR_get_aborted(qres)) break; retres = QR_nextr(qres); QR_detach(qres); QR_Destructor(qres); } /* * If error message isn't set */ if (ignore_abort_on_conn) { CC_set_errornumber(self, CONN_ERROR_IGNORED); if (retres) QR_set_rstatus(retres, PORES_NONFATAL_ERROR); MYLOG(DETAIL_LOG_LEVEL, " ignored abort_on_conn\n"); } 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_FIXED(self->sqlstate, retres->sqlstate); } } } } /* * Update our copy of the transaction status. * * XXX: Once we stop using the socket directly, and do everything with * libpq, we can get rid of the transaction_status field altogether * and always ask libpq for it. */ LIBPQ_update_transaction_status(self); if (retres) QR_set_conn(retres, self); rhold.first = retres; rhold.last = res; return rhold; } #define MAX_SEND_FUNC_ARGS 3 static const char *func_param_str[MAX_SEND_FUNC_ARGS + 1] = { "()", "($1)", "($1, $2)", "($1, $2, $3)" }; static Int8 odbc_hton64(Int8 h64) { union { Int8 n64; UInt4 i32[2]; } u; u.i32[0] = htonl((UInt4) (h64 >> 32)); u.i32[1] = htonl((UInt4) h64); return u.n64; } static Int8 odbc_ntoh64(Int8 n64) { union { Int8 h64; UInt4 i32[2]; } u; Int8 result; u.h64 = n64; result = ntohl(u.i32[0]); result <<= 32; result |= ntohl(u.i32[1]); return result; } int CC_send_function(ConnectionClass *self, const char *fn_name, void *result_buf, int *actual_result_len, int result_is_int, LO_ARG *args, int nargs) { int i; int ret = FALSE; int func_cs_count = 0; char sqlbuffer[1000]; PGresult *pgres = NULL; Oid paramTypes[MAX_SEND_FUNC_ARGS]; char *paramValues[MAX_SEND_FUNC_ARGS]; int paramLengths[MAX_SEND_FUNC_ARGS]; int paramFormats[MAX_SEND_FUNC_ARGS]; Int4 intParamBufs[MAX_SEND_FUNC_ARGS]; Int8 int8ParamBufs[MAX_SEND_FUNC_ARGS]; MYLOG(0, "conn=%p, fn_name=%s, result_is_int=%d, nargs=%d\n", self, fn_name, result_is_int, nargs); /* Finish the pending extended query first */ #define return DONT_CALL_RETURN_FROM_HERE??? ENTER_INNER_CONN_CS(self, func_cs_count); SPRINTF_FIXED(sqlbuffer, "SELECT pg_catalog.%s%s", fn_name, func_param_str[nargs]); for (i = 0; i < nargs; ++i) { MYLOG(0, " arg[%d]: len = %d, isint = %d, integer = " FORMATI64 ", ptr = %p\n", i, args[i].len, args[i].isint, args[i].isint == 2 ? args[i].u.integer64 : args[i].u.integer, args[i].u.ptr); /* integers are sent as binary, others as text */ if (args[i].isint == 2) { paramTypes[i] = PG_TYPE_INT8; int8ParamBufs[i] = odbc_hton64(args[i].u.integer64); paramValues[i] = (char *) &int8ParamBufs[i]; paramLengths[i] = 8; paramFormats[i] = 1; } else if (args[i].isint) { paramTypes[i] = PG_TYPE_INT4; intParamBufs[i] = htonl(args[i].u.integer); paramValues[i] = (char *) &intParamBufs[i]; paramLengths[i] = 4; paramFormats[i] = 1; } else { paramTypes[i] = 0; paramValues[i] = args[i].u.ptr; paramLengths[i] = args[i].len; paramFormats[i] = 1; } } QLOG(0, "PQexecParams: %p '%s' nargs=%d\n", self->pqconn, sqlbuffer, nargs); pgres = PQexecParams(self->pqconn, sqlbuffer, nargs, paramTypes, (const char * const *) paramValues, paramLengths, paramFormats, 1); MYLOG(0, "done sending function\n"); if (PQresultStatus(pgres) == PGRES_TUPLES_OK) QLOG(0, "\tok: - 'T' - %s\n", PQcmdStatus(pgres)); else { handle_pgres_error(self, pgres, "send_query", NULL, TRUE); goto cleanup; } if (PQnfields(pgres) != 1 || PQntuples(pgres) != 1) { CC_set_errormsg(self, "unexpected result set from large_object function"); goto cleanup; } *actual_result_len = PQgetlength(pgres, 0, 0); QLOG(0, "\tgot result with length: %d\n", *actual_result_len); if (*actual_result_len > 0) { char *value = PQgetvalue(pgres, 0, 0); if (result_is_int == 2) { Int8 int8val; memcpy(&int8val, value, sizeof(Int8)); int8val = odbc_ntoh64(int8val); memcpy(result_buf, &int8val, sizeof(Int8)); MYLOG(0, "int8 result=" FORMATI64 "\n", int8val); } else if (result_is_int) { Int4 int4val; memcpy(&int4val, value, sizeof(Int4)); int4val = ntohl(int4val); memcpy(result_buf, &int4val, sizeof(Int4)); } else memcpy(result_buf, value, *actual_result_len); } ret = TRUE; cleanup: #undef return CLEANUP_FUNC_CONN_CS(func_cs_count, self); if (pgres) PQclear(pgres); return ret; } char CC_send_settings(ConnectionClass *self, const char *set_query) { HSTMT hstmt; RETCODE result; char status = TRUE; char *cs, *ptr; #ifdef HAVE_STRTOK_R char *last; #endif /* HAVE_STRTOK_R */ CSTR func = "CC_send_settings"; MYLOG(0, "entering...\n"); if (set_query == NULL) return TRUE; /* * 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; /* non-external handle ensures no BEGIN/COMMIT/ABORT stuff */ cs = strdup(set_query); if (cs == NULL) { CC_set_error(self, CONN_NO_MEMORY_ERROR, "Couldn't alloc buffer for query.", func); return FALSE; } #ifdef HAVE_STRTOK_R ptr = strtok_r(cs, ";", &last); #else ptr = strtok(cs, ";"); #endif /* HAVE_STRTOK_R */ while (ptr) { result = PGAPI_ExecDirect(hstmt, (SQLCHAR *) ptr, SQL_NTS, 0); if (!SQL_SUCCEEDED(result)) status = FALSE; MYLOG(0, "result %d, status %d from '%s'\n", result, status, ptr); #ifdef HAVE_STRTOK_R ptr = strtok_r(NULL, ";", &last); #else ptr = strtok(NULL, ";"); #endif /* HAVE_STRTOK_R */ } free(cs); 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 SQLRETURN CC_lookup_lo(ConnectionClass *self) { SQLRETURN ret = SQL_SUCCESS; QResultClass *res; MYLOG(0, "entering...\n"); res = CC_send_query(self, "select oid, typbasetype from pg_type where typname = '" PG_TYPE_LO_NAME "'", NULL, READ_ONLY_QUERY, NULL); if (!QR_command_maybe_successful(res)) ret = SQL_ERROR; else 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(0, "Got the large object oid: %d\n", self->lobj_type); return ret; } /* * 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_FIXED(self->pg_version, "7.4"); self->pg_version_major = 7; self->pg_version_minor = 4; } void CC_log_error(const char *func, const char *desc, const ConnectionClass *self) { #define NULLCHECK(a) (a ? a : "(NULL)") if (self) { MYLOG(0, "CONN ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->__error_number, NULLCHECK(self->__error_message)); MYLOG(DETAIL_LOG_LEVEL, " ------------------------------------------------------------\n"); MYLOG(DETAIL_LOG_LEVEL, " henv=%p, conn=%p, status=%u, num_stmts=%d\n", self->henv, self, self->status, self->num_stmts); MYLOG(DETAIL_LOG_LEVEL, " pqconn=%p, stmts=%p, lobj_type=%d\n", self->pqconn, self->stmts, self->lobj_type); } else { MYLOG(0, "INVALID CONNECTION HANDLE ERROR: func=%s, desc='%s'\n", func, desc); } } /* * 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_valid) { QResultClass *res; if (res = CC_send_query(conn, "select current_schema()", NULL, READ_ONLY_QUERY, NULL), QR_command_maybe_successful(res)) { if (QR_get_num_total_tuples(res) == 1) { char *curschema = QR_get_value_backend_text(res, 0, 0); if (curschema) conn->current_schema = strdup(curschema); } if (conn->current_schema) conn->current_schema_valid = TRUE; } QR_Destructor(res); } return (const char *) conn->current_schema; } int CC_mark_a_object_to_discard(ConnectionClass *conn, int type, const char *plan) { int cnt = conn->num_discardp + 1, plansize; char *pname; CC_REALLOC_return_with_error(conn->discardp, char *, (cnt * sizeof(char *)), conn, "Couldn't alloc discardp.", -1); plansize = strlen(plan) + 2; CC_MALLOC_return_with_error(pname, char, plansize, conn, "Couldn't alloc discardp mem.", -1); pname[0] = (char) type; /* 's':prepared statement 'p':cursor */ strncpy_null(pname + 1, plan, plansize - 1); 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]) SPRINTF_FIXED(cmd, "DEALLOCATE \"%s\"", pname + 1); else SPRINTF_FIXED(cmd, "CLOSE \"%s\"", pname + 1); res = CC_send_query(conn, cmd, NULL, ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN | READ_ONLY_QUERY, NULL); QR_Destructor(res); free(conn->discardp[i]); conn->num_discardp--; } return 1; } static void LIBPQ_update_transaction_status(ConnectionClass *self) { if (!self->pqconn) return; MYLOG(DETAIL_LOG_LEVEL, "transactionStatus=%d\n", PQtransactionStatus(self->pqconn)); switch (PQtransactionStatus(self->pqconn)) { case PQTRANS_IDLE: // correspond to 'I' in ReadyForQuery message if (CC_is_in_trans(self)) { if (CC_is_in_error_trans(self)) CC_on_abort(self, NO_TRANS); else CC_on_commit(self); } break; case PQTRANS_INTRANS: // correspond to 'T' in ReadyForQuery message CC_set_in_trans(self); if (CC_is_in_error_trans(self)) { CC_set_no_error_trans(self); CC_on_abort_partial(self); } break; case PQTRANS_INERROR: // correspond to 'E' in ReadyForQuery message CC_set_in_trans(self); CC_set_in_error_trans(self); break; case PQTRANS_ACTIVE: // no correspondence in ReadyForQuery message /* * A query is still executing. It's not necessary to consider this status. */ // CC_set_in_trans(self); break; default: /* unknown status */ break; } } #define PROTOCOL3_OPTS_MAX 30 static int LIBPQ_connect(ConnectionClass *self) { CSTR func = "LIBPQ_connect"; ConnInfo *ci = &(self->connInfo); char ret = 0; void *pqconn = NULL; int pqret; int pversion; const char *opts[PROTOCOL3_OPTS_MAX], *vals[PROTOCOL3_OPTS_MAX]; PQconninfoOption *conninfoOption = NULL, *pqopt; int i, cnt; char login_timeout_str[20]; char keepalive_idle_str[20]; char keepalive_interval_str[20]; char *errmsg = NULL; MYLOG(0, "connecting to the database using %s as the server and pqopt={%s}\n", self->connInfo.server, SAFE_NAME(ci->pqopt)); if (NULL == (conninfoOption = PQconninfoParse(SAFE_NAME(ci->pqopt), &errmsg))) { char emsg[200]; if (errmsg != NULL) SPRINTF_FIXED(emsg, "libpq connection parameter error:%s", errmsg); else STRCPY_FIXED(emsg, "memory error? in PQconninfoParse"); CC_set_error(self, CONN_OPENDB_ERROR, emsg, func); goto cleanup; } /* Build arrays of keywords & values, for PQconnectDBParams */ cnt = 0; if (ci->server[0]) { opts[cnt] = "host"; vals[cnt++] = ci->server; } if (ci->port[0]) { opts[cnt] = "port"; vals[cnt++] = ci->port; } if (ci->database[0]) { opts[cnt] = "dbname"; vals[cnt++] = ci->database; } if (ci->username[0]) { opts[cnt] = "user"; vals[cnt++] = ci->username; } 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->disable_keepalive) { opts[cnt] = "keepalives"; vals[cnt++] = "0"; } if (self->login_timeout > 0) { SPRINTF_FIXED(login_timeout_str, "%u", (unsigned int) self->login_timeout); opts[cnt] = "connect_timeout"; vals[cnt++] = login_timeout_str; } if (self->connInfo.keepalive_idle > 0) { ITOA_FIXED(keepalive_idle_str, self->connInfo.keepalive_idle); opts[cnt] = "keepalives_idle"; vals[cnt++] = keepalive_idle_str; } if (self->connInfo.keepalive_interval > 0) { ITOA_FIXED(keepalive_interval_str, self->connInfo.keepalive_interval); opts[cnt] = "keepalives_interval"; vals[cnt++] = keepalive_interval_str; } if (conninfoOption != NULL) { const char *keyword, *val; int j; for (i = 0, pqopt = conninfoOption; (keyword = pqopt->keyword) != NULL; i++, pqopt++) { if ((val = pqopt->val) != NULL) { for (j = 0; j < cnt; j++) { if (stricmp(opts[j], keyword) == 0) { char emsg[100]; if (vals[j] != NULL && strcmp(vals[j], val) == 0) continue; SPRINTF_FIXED(emsg, "%s parameter in pqopt option conflicts with other ordinary option", keyword); CC_set_error(self, CONN_OPENDB_ERROR, emsg, func); goto cleanup; } } if (j >= cnt && cnt < PROTOCOL3_OPTS_MAX - 1) { opts[cnt] = keyword; vals[cnt++] = val; } } } } opts[cnt] = vals[cnt] = NULL; /* Ok, we're all set to connect */ if (get_qlog() > 0 || get_mylog() > 0) { const char **popt, **pval; QLOG(0, "PQconnectdbParams:"); for (popt = opts, pval = vals; *popt; popt++, pval++) QPRINTF(0, " %s='%s'", *popt, *pval); QPRINTF(0, "\n"); } pqconn = PQconnectdbParams(opts, vals, FALSE); if (!pqconn) { CC_set_error(self, CONN_OPENDB_ERROR, "PQconnectdb error", func); goto cleanup; } self->pqconn = pqconn; pqret = PQstatus(pqconn); if (pqret == CONNECTION_BAD && PQconnectionNeedsPassword(pqconn)) { const char *errmsg; MYLOG(0, "password retry\n"); errmsg = PQerrorMessage(pqconn); CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, errmsg, func); QLOG(0, "PQfinish: %p\n", pqconn); PQfinish(pqconn); self->pqconn = NULL; self->connInfo.password_required = TRUE; ret = -1; goto cleanup; } if (CONNECTION_OK != pqret) { const char *errmsg; MYLOG(DETAIL_LOG_LEVEL, "status=%d\n", pqret); errmsg = PQerrorMessage(pqconn); CC_set_error(self, CONNECTION_SERVER_NOT_REACHED, errmsg, func); MYLOG(0, "Could not establish connection to the database; LIBPQ returned -> %s\n", errmsg); goto cleanup; } MYLOG(0, "libpq connection to the database established.\n"); pversion = PQprotocolVersion(pqconn); if (pversion < 3) { MYLOG(0, "Protocol version %d is not supported\n", pversion); goto cleanup; } MYLOG(0, "protocol=%d\n", pversion); pversion = PQserverVersion(pqconn); self->pg_version_major = pversion / 10000; self->pg_version_minor = (pversion % 10000) / 100; SPRINTF_FIXED(self->pg_version, "%d.%d.%d", self->pg_version_major, self->pg_version_minor, pversion % 100); MYLOG(0, "Server version=%s\n", self->pg_version); if (!CC_get_username(self)[0]) { MYLOG(0, "PQuser=%s\n", PQuser(pqconn)); STRCPY_FIXED(self->connInfo.username, PQuser(pqconn)); } ret = 1; cleanup: if (errmsg != NULL) free(errmsg); PQconninfoFree(conninfoOption); if (ret != 1) { if (self->pqconn) { QLOG(0, "PQfinish: %p\n", self->pqconn); PQfinish(self->pqconn); } self->pqconn = NULL; } MYLOG(0, "leaving %d\n", ret); return ret; } int CC_send_cancel_request(const ConnectionClass *conn) { int ret = 0; char errbuf[256]; void *cancel; /* Check we have an open connection */ if (!conn || !conn->pqconn) return FALSE; cancel = PQgetCancel(conn->pqconn); if (!cancel) return FALSE; ret = PQcancel(cancel, errbuf, sizeof(errbuf)); PQfreeCancel(cancel); if (1 == ret) return TRUE; else return FALSE; } 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; return conn->connInfo.database; } const char *CurrCatString(const ConnectionClass *conn) { const char *cat = CurrCat(conn); if (!cat) cat = NULL_STRING; return cat; } /*------ * 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; UCHAR tchar; encoded_str encstr; make_encoded_str(&encstr, conn, ccs); for (i = 0; i < length; i++) { tchar = encoded_nextchar(&encstr); if (MBCS_NON_ASCII(encstr)) continue; if (ifallupper && islower(tchar)) { if (str) { free(str); str = NULL; } break; } if (tolower(tchar) != tchar) { if (!str) { str = malloc(length + 1); if (!str) return NULL; memcpy(str, s, length); str[length] = '\0'; } str[i] = tolower(tchar); } } } 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 int my_str(char *buf, int buflen, const char *fmt, const char *s, ssize_t len) { if (s && (len > 0 || (len == SQL_NTS && *s != 0))) { size_t length = (len > 0) ? len : strlen(s); return snprintf(buf, buflen, fmt, length, s); } buf[0] = '\0'; return 0; } int schema_str(char *buf, int buflen, const SQLCHAR *s, SQLLEN len, BOOL table_is_valid, ConnectionClass *conn) { CSTR fmt = "%.*s"; buf[0] = '\0'; if (!s || 0 == len) { /* * Note that this driver assumes the implicit schema is * the CURRENT_SCHEMA() though it doesn't worth the * naming. */ if (table_is_valid) return my_str(buf, buflen, fmt, CC_get_current_schema(conn), SQL_NTS); return 0; } return my_str(buf, buflen, fmt, (char *) s, len); } static void my_appendPQExpBuffer(PQExpBufferData *buf, const char *fmt, const char *s, ssize_t len) { if (s && (len > 0 || (len == SQL_NTS && *s != 0))) { size_t length = (len > 0) ? len : strlen(s); appendPQExpBuffer(buf, fmt, length, s); } } /* * my_appendPQExpBuffer1 is a extension of my_appendPQExpBuffer. * It can have 1 more parameter than my_appendPQExpBuffer. */ static void my_appendPQExpBuffer1(PQExpBufferData *buf, const char *fmt, const char *s1, const char *s) { if (s && s[0] != '\0') { ssize_t length = strlen(s); if (s1) appendPQExpBuffer(buf, fmt, s1, length, s); else appendPQExpBuffer(buf, fmt, length, s); } } void schema_appendPQExpBuffer(PQExpBufferData *buf, const char *fmt, const SQLCHAR *s, SQLLEN len, BOOL table_is_valid, 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 (table_is_valid) my_appendPQExpBuffer(buf, fmt, CC_get_current_schema(conn), SQL_NTS); return; } my_appendPQExpBuffer(buf, fmt, (char *) s, len); } void schema_appendPQExpBuffer1(PQExpBufferData *buf, const char *fmt, const char *s1, const char *s, BOOL table_is_valid, ConnectionClass *conn) { if (!s || s[0] == '\0') { if (table_is_valid) my_appendPQExpBuffer1(buf, fmt, s1, CC_get_current_schema(conn)); return; } my_appendPQExpBuffer1(buf, fmt, s1, s); } #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->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); const char *drivername = ci->drivername; char xaOptStr[32]; #if defined(_WIN32) && !defined(_WIN64) /* * If this is an x86 driver running on an x64 host then the driver name * passed to MSDTC must be the (x64) driver but the client app will be * using the 32-bit driver name. So MSDTC.exe will fail to find the driver * and we'll fail to recover XA transactions. * * IsWow64Process(...) would be the ideal function for this, but is only * available on Windows 6+ (Vista/2k8). We'd use GetNativeSystemInfo, which * is supported on XP and 2k3, instead, but that won't link with older * SDKs. * * It's impler to just test the PROCESSOR_ARCHITEW6432 environment * variable. * * See http://www.postgresql.org/message-id/53A45B59.70303@2ndquadrant.com * for details on this issue. */ const char * const procenv = getenv("PROCESSOR_ARCHITEW6432"); if (procenv != NULL && strcmp(procenv, "AMD64") == 0) { /* * We're a 32-bit binary running under SysWow64 on a 64-bit host and need * to pass a different driver name. * * To avoid playing memory management games, just return a different * string constant depending on the unicode-ness of the driver. * * It probably doesn't matter whether we use the Unicode or ANSI driver * for the XA transaction manager, but pick the same as the client driver * to keep things as similar as possible. */ if (strcmp(drivername, DBMS_NAME) == 0) #ifdef UNICODE_SUPPORT drivername = DBMS_NAME_UNICODE"(x64)"; #else drivername = DBMS_NAME_ANSI"(x64)"; #endif } #endif // _WIN32 && !_WIN64 if (0 >= ci->xa_opt) return; switch (ci->xa_opt) { case DTC_CHECK_LINK_ONLY: case DTC_CHECK_BEFORE_LINK: SPRINTF_FIXED(xaOptStr, KEYWORD_DTC_CHECK "=0;"); break; case DTC_CHECK_RM_CONNECTION: SPRINTF_FIXED(xaOptStr, KEYWORD_DTC_CHECK "=1;"); break; default: *xaOptStr = '\0'; break; } snprintf(connstr, strsize, "DRIVER={%s};%s" "SERVER=%s;PORT=%s;DATABASE=%s;" "UID=%s;PWD=%s;" ABBR_SSLMODE "=%s", drivername, xaOptStr, ci->server, ci->port, ci->database, ci->username, SAFE_NAME(ci->password), ci->sslmode ); return; } #define SECURITY_WIN32 #include DLL_DECLARE int PgDtc_is_recovery_available(void *self, char *reason, int rsize) { ConnectionClass *conn = (ConnectionClass *) self; ConnInfo *ci = &(conn->connInfo); int ret = -1; // inknown LONG nameSize; char loginUser[256]; BOOL outReason = FALSE; BOOL doubtRootCert = TRUE, doubtCert = TRUE; const char *delim; /* * Root certificate is used? */ if (NULL != reason && rsize > 0) outReason = TRUE; /* * Root certificate is used? */ doubtRootCert = FALSE; if (0 == stricmp(ci->sslmode, SSLMODE_VERIFY_CA) || 0 == stricmp(ci->sslmode, SSLMODE_VERIFY_FULL)) { if (outReason) strncpy_null(reason, "sslmode verify-[ca|full]", rsize); return 0; } /* * Did we use SSL client certificate, SSPI, Kerberos or similar * authentication methods? */ doubtCert = FALSE; #ifdef HAVE_PQSSLINUSE if (PQsslInUse(conn->pqconn)) #else if (PQgetssl(conn->pqconn) != NULL) #endif doubtCert = TRUE; nameSize = sizeof(loginUser); if (GetUserNameEx(NameUserPrincipal, loginUser, &nameSize)) { MYLOG(0, "loginUser=%s\n", loginUser); } else { int err = GetLastError(); switch (err) { case ERROR_NONE_MAPPED: MYLOG(0, "The user name is unavailable in the specified format\n"); break; case ERROR_NO_SUCH_DOMAIN: MYLOG(0, "The domain controller is unavailable to perform the lookup\n"); break; case ERROR_MORE_DATA: MYLOG(0, "The buffer is too small\n"); break; default: MYLOG(0, "GetUserNameEx error=%d\n", err); break; } } ret = 1; if (outReason) *reason = '\0'; delim = ""; if (doubtRootCert) { if (outReason) snprintf(reason, rsize, "%s%ssslmode verify-[ca|full]", reason, delim); delim = ", "; ret = -1; } if (doubtCert) { if (outReason) snprintf(reason, rsize, "%s%scertificate", reason, delim); delim = ", "; ret = -1; } return ret; } 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, 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: SPRINTF_FIXED(cmd, "PREPARE TRANSACTION '%s'", gxid); break; case COMMIT_PREPARED: SPRINTF_FIXED(cmd, "COMMIT PREPARED '%s'", gxid); break; case ROLLBACK_PREPARED: SPRINTF_FIXED(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; } DLL_DECLARE void * PgDtc_isolate(void *self, DWORD option) { BOOL disposingConn = (0 != (disposingConnection & option)); ConnectionClass *sconn = (ConnectionClass *) self, *newconn = NULL; if (0 == (useAnotherRoom & option)) { HENV henv = sconn->henv; CC_cleanup(sconn, TRUE); if (newconn = CC_Copy(sconn), NULL == newconn) return newconn; MYLOG(0, "newconn=%p from %p\n", newconn, sconn); CC_initialize(sconn, FALSE); if (!disposingConn) CC_copy_conninfo(&sconn->connInfo, &newconn->connInfo); CC_initialize_pg_version(sconn); sconn->henv = henv; newconn->henv = NULL; SYNC_AUTOCOMMIT(sconn); return newconn; } newconn = CC_Constructor(); if (!newconn) return NULL; CC_copy_conninfo(&newconn->connInfo, &sconn->connInfo); CC_initialize_pg_version(newconn); newconn->asdum = sconn->asdum; newconn->gTranInfo = sconn->gTranInfo; CC_set_dtc_isolated(newconn); sconn->asdum = NULL; SYNC_AUTOCOMMIT(sconn); CC_set_dtc_clear(sconn); MYLOG(0, "generated connection=%p with %p\n", newconn, newconn->asdum); return newconn; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ BOOL CC_set_transact(ConnectionClass *self, UInt4 isolation) { char *query; QResultClass *res; BOOL bShow = FALSE; if (PG_VERSION_LT(self, 8.0) && (isolation == SQL_TXN_READ_UNCOMMITTED || isolation == SQL_TXN_REPEATABLE_READ)) { CC_set_error(self, CONN_NOT_IMPLEMENTED_ERROR, "READ_UNCOMMITTED or REPEATABLE_READ is not supported by the server", __FUNCTION__); return FALSE; } switch (isolation) { 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; } if (self->default_isolation == 0) bShow = TRUE; if (bShow) res = CC_send_query_append(self, ISOLATION_SHOW_QUERY, NULL, READ_ONLY_QUERY, NULL, query).first; else res = CC_send_query(self, query, NULL, READ_ONLY_QUERY, NULL); if (!QR_command_maybe_successful(res)) { CC_set_error(self, CONN_EXEC_ERROR, "ISOLATION change request to the server error", __FUNCTION__); QR_Destructor(res); return FALSE; } if (bShow) handle_show_results(res); QR_Destructor(res); self->server_isolation = isolation; return TRUE; } psqlodbc-13.02.0000/convert.c000644 001751 001751 00000477056 14122574535 016741 0ustar00hiroshihiroshi000000 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 "unicode_support.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 #include "statement.h" #include "qresult.h" #include "bind.h" #include "pgtypes.h" #include "lobj.h" #include "connection.h" #include "catfunc.h" #include "pgapifunc.h" CSTR NAN_STRING = "NaN"; CSTR INFINITY_STRING = "Infinity"; CSTR MINFINITY_STRING = "-Infinity"; #if defined(WIN32) || defined(__CYGWIN__) #define TIMEZONE_GLOBAL _timezone #define TZNAME_GLOBAL _tzname #define DAYLIGHT_GLOBAL _daylight #elif defined(HAVE_INT_TIMEZONE) #define TIMEZONE_GLOBAL timezone #define TZNAME_GLOBAL tzname #define DAYLIGHT_GLOBAL daylight #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 */ static const struct { /* * There's a horrible hack in odbc_name field: if it begins with a %, * the digit after the % indicates the number of arguments. Otherwise, * the entry matches any number of args. */ char *odbc_name; char *pgsql_name; } mapFuncs[] = { /* { "ASCII", "ascii" }, built_in */ {"CHAR", "chr($*)" }, {"CONCAT", "concat($1::text, $2::text)" }, /* { "DIFFERENCE", "difference" }, how to ? */ {"INSERT", "substring($1 from 1 for $2 - 1) || $4 || substring($1 from $2 + $3)" }, {"LCASE", "lower($*)" }, /* {"LEFT", "left" }, built_in */ {"%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", "right" }, built_in */ {"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" }, built_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", "power" }, built_in */ /* { "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)" }, // TIMESTAMPADD() {"TIMESTAMPADD(SQL_TSI_YEAR", "($3+make_interval(years := $2))" }, {"TIMESTAMPADD(SQL_TSI_MONTH", "($3+make_interval(months := $2))" }, {"TIMESTAMPADD(SQL_TSI_WEEK", "($3+make_interval(weeks := $2))" }, {"TIMESTAMPADD(SQL_TSI_DAY", "($3+make_interval(days := $2))" }, {"TIMESTAMPADD(SQL_TSI_HOUR", "($3+make_interval(hours := $2))" }, {"TIMESTAMPADD(SQL_TSI_MINUTE", "($3+make_interval(mins := $2))" }, {"TIMESTAMPADD(SQL_TSI_SECOND", "($3+make_interval(secs := $2))" }, {"TIMESTAMPADD(SQL_TSI_FRAC_SECOND", "($3+make_interval(secs := $2::float / 1000000))" }, // TIMESTAMPDIFF() /* doesn't work properly? {"TIMESTAMPDIFF(SQL_TSI_YEAR", "cast(extract(year from ($3 - $2)) as integer)" }, {"TIMESTAMPDIFF(SQL_TSI_MONTH", "cast(extract(month from ($3 - $2)) as integer)" }, {"TIMESTAMPDIFF(SQL_TSI_QUARTER", "cast(extract(quarter from ($3 - $2)) as integer)" }, {"TIMESTAMPDIFF(SQL_TSI_WEEK", "cast(extract(week from ($3 - $2)) as integer)" }, */ /* {"TIMESTAMPDIFF(SQL_TSI_DAY", "cast(extract(day from ($3 - $2)) as integer)" }, {"TIMESTAMPDIFF(SQL_TSI_HOUR", "cast(extract(hour from ($3 - $2)) as integer)" }, {"TIMESTAMPDIFF(SQL_TSI_HOUR", "(extract(epoch from $3) - extract(epoch from $2)) / 3600" }, {"TIMESTAMPDIFF(SQL_TSI_MINUTE", "cast(extract(minute from ($3 - $2)) as integer)" }, {"TIMESTAMPDIFF(SQL_TSI_SECOND", "cast(extract(second from ($3 - $2)) as integer)" }, */ {"TIMESTAMPDIFF(SQL_TSI_DAY", "cast((extract(epoch from $3) - extract(epoch from $2)) / (24*60*60) as int)" }, {"TIMESTAMPDIFF(SQL_TSI_HOUR", "cast((extract(epoch from $3) - extract(epoch from $2)) / 3600 as int)" }, {"TIMESTAMPDIFF(SQL_TSI_MINUTE", "cast((extract(epoch from $3) - extract(epoch from $2)) / 60 as int)" }, {"TIMESTAMPDIFF(SQL_TSI_SECOND", "cast((extract(epoch from $3) - extract(epoch from $2)) as int)" }, {"TIMESTAMPDIFF(SQL_TSI_FRAC_SECOND", "mod(cast(extract(second from ($3 - $2)) as numeric), 1.0) * 1000000" }, /* { "EXTRACT", "extract" }, built_in */ /* { "DATABASE", "database" }, */ {"IFNULL", "coalesce($*)" }, {"USER", "cast(current_user as text)" }, {0, 0} }; typedef struct { int infinity; int m; int d; int y; int hh; int mm; int ss; int fr; } SIMPLE_TIME; static const char *mapFunction(const char *func, int param_count, const char * keyword); static BOOL convert_money(const char *s, char *sout, size_t soutmax); static 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); static size_t convert_from_pgbinary(const char *value, char *rgbValue, SQLLEN cbValueMax); static int convert_lo(StatementClass *stmt, const void *value, SQLSMALLINT fCType, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue); 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) #elif (SIZEOF_LONG == 8) #define ATOI64(val) strtol(val, NULL, 10) #define ATOI64U(val) strtoul(val, NULL, 10) #else #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 */ static void ResolveNumericParam(const SQL_NUMERIC_STRUCT *ns, char *chrform); static void parse_to_numeric_struct(const char *wv, SQL_NUMERIC_STRUCT *ns, BOOL *overflow); /* * 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; int y, m, d, hh, mm, ss; #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", &y, &m, &d, &hh, &mm, &ss, rest, bc)) < 6) { if (scnt == 3) /* date */ { st->y = y; st->m = m; st->d = d; st->hh = 0; st->mm = 0; st->ss = 0; return TRUE; } if ((scnt = sscanf(str, "%2d:%2d:%2d%31s %15s", &hh, &mm, &ss, rest, bc)) < 3) return FALSE; else { st->hh = hh; st->mm = mm; st->ss = ss; if (scnt == 3) /* time */ return TRUE; } } else { st->y = y; st->m = m; st->d = d; st->hh = hh; st->mm = mm; st->ss = ss; 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_GLOBAL[0] || !TZNAME_GLOBAL[0][0]) { *bZone = FALSE; return TRUE; } timediff = TIMEZONE_GLOBAL + (*zone) * 3600; if (!DAYLIGHT_GLOBAL && 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 int stime2timestamp(const SIMPLE_TIME *st, char *str, size_t bufsize, BOOL bZone, int precision) { char precstr[16], zonestr[16]; int i; precstr[0] = '\0'; if (st->infinity > 0) { return snprintf(str, bufsize, "%s", INFINITY_STRING); } else if (st->infinity < 0) { return snprintf(str, bufsize, "%s", MINFINITY_STRING); } if (precision > 0 && st->fr) { SPRINTF_FIXED(precstr, ".%09d", st->fr); if (precision < 9) precstr[precision + 1] = '\0'; else if (precision > 9) precision = 9; 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_GLOBAL[0] && TZNAME_GLOBAL[0][0] && st->y >= 1970) { long zoneint; struct tm tm; time_t time0; zoneint = TIMEZONE_GLOBAL; if (DAYLIGHT_GLOBAL && 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_FIXED(zonestr, "-%02d", (int) zoneint / 3600); else SPRINTF_FIXED(zonestr, "+%02d", -(int) zoneint / 3600); } #endif /* TIMEZONE_GLOBAL */ if (st->y < 0) return snprintf(str, bufsize, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s BC", -st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr); else return snprintf(str, bufsize, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d%s%s", st->y, st->m, st->d, st->hh, st->mm, st->ss, precstr, zonestr); } 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 (scnt == 5 || scnt == 6) { if (strnicmp(lit1, "day", 3) != 0) return FALSE; 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 = 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); if (scnt == 3 || scnt == 4) { sign = hours < 0 ? SQL_TRUE : SQL_FALSE; 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; } #ifdef HAVE_LOCALE_H /* * Get the decimal point of the current locale. * * XXX: This isn't thread-safe, if another thread changes the locale with * setlocale() concurrently. There are two problems with that: * * 1. The pointer returned by localeconv(), or the lc->decimal_point string, * might be invalidated by calls in other threads. Until someone comes up * with a thread-safe version of localeconv(), there isn't much we can do * about that. (libc implementations that return a static buffer (like glibc) * happen to be safe from the lconv struct being invalidated, but the * decimal_point string might still not point to a static buffer). * * 2. The between the call to sprintf() and get_current_decimal_point(), the * decimal point might change. That would cause set_server_decimal_point() * to fail to recognize a decimal separator, and we might send a numeric * string to the server that the server won't recognize. This would cause * the query to fail in the server. * * XXX: we only take into account the first byte of the decimal separator. */ static char get_current_decimal_point(void) { struct lconv *lc = localeconv(); return lc->decimal_point[0]; } /* * Modify the string representation of a numeric/float value, converting the * decimal point from '.' to the correct decimal separator of the current * locale. */ static void set_server_decimal_point(char *num, SQLLEN len) { char current_decimal_point = get_current_decimal_point(); char *str; SQLLEN i; if ('.' == current_decimal_point) return; i = 0; for (str = num; '\0' != *str; str++) { if (*str == current_decimal_point) { *str = '.'; break; } if (len != SQL_NTS && i++ >= len) break; } } /* * Inverse of set_server_decimal_point. */ static void set_client_decimal_point(char *num) { char current_decimal_point = get_current_decimal_point(); char *str; 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)); } /* * Is 'str' a valid integer literal, consisting only of ASCII characters * 0-9 ? * * Also, *negative is set to TRUE if the value was negative. * * We don't check for overflow here. This is just to decide if we need to * quote the value. */ static BOOL valid_int_literal(const char *str, SQLLEN len, BOOL *negative) { SQLLEN i = 0; /* Check there is a minus sign in front */ if ((len == SQL_NTS || len > 0) && str[0] == '-') { i++; *negative = TRUE; } else *negative = FALSE; /* * Must begin with a digit. This also rejects empty strings and '-'. */ if (i == len || !(str[i] >= '0' && str[i] <= '9')) return FALSE; for (; str[i] && (len == SQL_NTS || i < len); i++) { if (!(str[i] >= '0' && str[i] <= '9')) return FALSE; } return TRUE; } 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); } 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; } static int effective_fraction(int fraction, int *width) { for (*width = 9; fraction % 10 == 0; (*width)--, fraction /= 10) ; return fraction; } static int get_terminator_len(SQLSMALLINT fCType) { switch (fCType) { #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: return WCLEN; #endif /* UNICODE_SUPPORT */ case SQL_C_BINARY: return 0; } /* SQL_C_CHAR or INTERNAL_ASIS_TYPE */ return 1; } static SQLLEN get_adjust_len(SQLSMALLINT fCType, SQLLEN len) { switch (fCType) { #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: return (len / WCLEN) * WCLEN; #endif /* UNICODE_SUPPORT */ } return len; } #define BYTEA_PROCESS_ESCAPE 1 #define BYTEA_PROCESS_BINARY 2 static int setup_getdataclass(SQLLEN * const length_return, const char ** const ptr_return, int *needbuflen_return, GetDataClass * const pgdc, const char *neut_str, const OID field_type, const SQLSMALLINT fCType, const SQLLEN cbValueMax, const ConnectionClass * const conn) { SQLLEN len = (-2); const char *ptr = NULL; int needbuflen = 0; int result = COPY_OK; BOOL lf_conv = conn->connInfo.lf_conversion; int bytea_process_kind = 0; BOOL already_processed = FALSE; BOOL changed = FALSE; int len_for_wcs_term = 0; #ifdef UNICODE_SUPPORT char *allocbuf = NULL; int unicode_count = -1; BOOL localize_needed = FALSE; BOOL hybrid = FALSE; #endif /* UNICODE_SUPPORT */ if (PG_TYPE_BYTEA == field_type) { if (SQL_C_BINARY == fCType) bytea_process_kind = BYTEA_PROCESS_BINARY; else if (0 == strnicmp(neut_str, "\\x", 2)) /* hex format */ neut_str += 2; else bytea_process_kind = BYTEA_PROCESS_ESCAPE; } #ifdef UNICODE_SUPPORT if (0 == bytea_process_kind) { if (get_convtype() > 0) /* coversion between the current locale is available */ { BOOL wcs_debug = conn->connInfo.wcs_debug; BOOL same_encoding = (conn->ccsc == pg_CS_code(conn->locale_encoding)); BOOL is_utf8 = (UTF8 == conn->ccsc); switch (field_type) { case PG_TYPE_UNKNOWN: case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: case PG_TYPE_TEXT: case PG_TYPE_BPCHARARRAY: case PG_TYPE_VARCHARARRAY: case PG_TYPE_TEXTARRAY: if (SQL_C_CHAR == fCType || SQL_C_BINARY == fCType) localize_needed = (!same_encoding || wcs_debug); if (SQL_C_WCHAR == fCType) hybrid = (!is_utf8 || (same_encoding && wcs_debug)); } MYLOG(0, "localize=%d hybrid=%d is_utf8=%d same_encoding=%d wcs_debug=%d\n", localize_needed, hybrid, is_utf8, same_encoding, wcs_debug); } } if (fCType == SQL_C_WCHAR) { if (BYTEA_PROCESS_ESCAPE == bytea_process_kind) unicode_count = convert_from_pgbinary(neut_str, NULL, 0) * 2; else if (hybrid) { MYLOG(0, "hybrid estimate\n"); if ((unicode_count = bindcol_hybrid_estimate(neut_str, lf_conv, &allocbuf)) < 0) { result = COPY_INVALID_STRING_CONVERSION; goto cleanup; } } else /* normally */ { unicode_count = utf8_to_ucs2_lf(neut_str, SQL_NTS, lf_conv, NULL, 0, FALSE); } len = WCLEN * unicode_count; already_processed = changed = TRUE; } else if (localize_needed) { if ((len = bindcol_localize_estimate(neut_str, lf_conv, &allocbuf)) < 0) { result = COPY_INVALID_STRING_CONVERSION; goto cleanup; } already_processed = changed = TRUE; } #endif /* UNICODE_SUPPORT */ if (already_processed) /* skip */ ; else if (0 != bytea_process_kind) { len = convert_from_pgbinary(neut_str, NULL, 0); if (BYTEA_PROCESS_BINARY != bytea_process_kind) len *= 2; changed = TRUE; } else /* convert linefeeds to carriage-return/linefeed */ len = convert_linefeeds(neut_str, NULL, 0, lf_conv, &changed); /* just returns length info */ if (cbValueMax == 0) { result = COPY_RESULT_TRUNCATED; goto cleanup; } if (!pgdc->ttlbuf) pgdc->ttlbuflen = 0; needbuflen = len + get_terminator_len(fCType); if (SQL_C_BINARY == fCType) { /* * Though Binary doesn't have NULL terminator, * bindcol_localize_exec() needs output buffer * for NULL terminator. */ len_for_wcs_term = 1; } if (changed || needbuflen > cbValueMax) { if (needbuflen > (SQLLEN) pgdc->ttlbuflen) { pgdc->ttlbuf = realloc(pgdc->ttlbuf, needbuflen + len_for_wcs_term); pgdc->ttlbuflen = needbuflen; } already_processed = FALSE; #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR) { if (BYTEA_PROCESS_ESCAPE == bytea_process_kind) { len = convert_from_pgbinary(neut_str, pgdc->ttlbuf, pgdc->ttlbuflen); len = pg_bin2whex(pgdc->ttlbuf, (SQLWCHAR *) pgdc->ttlbuf, len); } else { if (!hybrid) /* normally */ utf8_to_ucs2_lf(neut_str, SQL_NTS, lf_conv, (SQLWCHAR *) pgdc->ttlbuf, unicode_count, FALSE); else /* hybrid */ { MYLOG(0, "hybrid convert\n"); if (bindcol_hybrid_exec((SQLWCHAR *) pgdc->ttlbuf, neut_str, unicode_count + 1, lf_conv, &allocbuf) < 0) { result = COPY_INVALID_STRING_CONVERSION; goto cleanup; } } } already_processed = TRUE; } else if (localize_needed) { if (bindcol_localize_exec(pgdc->ttlbuf, len + 1, lf_conv, &allocbuf) < 0) { result = COPY_INVALID_STRING_CONVERSION; goto cleanup; } already_processed = TRUE; } #endif /* UNICODE_SUPPORT */ if (already_processed) ; else if (0 != bytea_process_kind) { len = convert_from_pgbinary(neut_str, pgdc->ttlbuf, pgdc->ttlbuflen); if (BYTEA_PROCESS_ESCAPE == bytea_process_kind) len = pg_bin2hex(pgdc->ttlbuf, pgdc->ttlbuf, len); } else 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; } cleanup: #ifdef UNICODE_SUPPORT if (allocbuf) free(allocbuf); #endif /* UNICODE_SUPPORT */ *length_return = len; *ptr_return = ptr; *needbuflen_return = needbuflen; return result; } /* gdata SC_get_GDTI(stmt) current_col stmt->current_col */ /* * fCType treated in the following function is * * SQL_C_CHAR, SQL_C_BINARY, SQL_C_WCHAR or INTERNAL_ASIS_TYPE */ static int convert_text_field_to_sql_c(GetDataInfo * const gdata, const int current_col, const char * const neut_str, const OID field_type, const SQLSMALLINT fCType, char * const rgbValueBindRow, const SQLLEN cbValueMax, const ConnectionClass * const conn, SQLLEN * const length_return) { int result = COPY_OK; SQLLEN len = (-2); GetDataClass *pgdc; int copy_len = 0, needbuflen = 0, i; const char *ptr; MYLOG(0, "field_type=%u type=%d\n", field_type, fCType); switch (field_type) { case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_NUMERIC: set_client_decimal_point((char *) neut_str); break; } if (current_col < 0) { pgdc = &(gdata->fdata); pgdc->data_left = -1; } else pgdc = &gdata->gdata[current_col]; if (pgdc->data_left < 0) { if (COPY_OK != (result = setup_getdataclass(&len, &ptr, &needbuflen, pgdc, neut_str, field_type, fCType, cbValueMax, conn))) goto cleanup; } else { ptr = pgdc->ttlbuf; len = pgdc->ttlbufused; } MYLOG(0, "DEFAULT: len = " FORMAT_LEN ", ptr = '%.*s'\n", len, (int) len, ptr); if (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; int terminatorlen; terminatorlen = get_terminator_len(fCType); if (terminatorlen >= cbValueMax) copy_len = 0; else if (len + terminatorlen > cbValueMax) copy_len = get_adjust_len(fCType, cbValueMax - terminatorlen); else copy_len = len; if (!already_copied) { /* Copy the data */ if (copy_len > 0) memcpy(rgbValueBindRow, ptr, copy_len); /* Add null terminator */ for (i = 0; i < terminatorlen && copy_len + i < cbValueMax; i++) rgbValueBindRow[copy_len + i] = '\0'; } /* Adjust data_left for next time */ if (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; } } #ifdef UNICODE_SUPPORT if (SQL_C_WCHAR == fCType) MYLOG(0, " SQL_C_WCHAR, default: len = " FORMAT_LEN ", cbValueMax = " FORMAT_LEN ", rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow); else #endif /* UNICODE_SUPPORT */ if (SQL_C_BINARY == fCType) MYLOG(0, " SQL_C_BINARY, default: len = " FORMAT_LEN ", cbValueMax = " FORMAT_LEN ", rgbValueBindRow = '%.*s'\n", len, cbValueMax, copy_len, rgbValueBindRow); else MYLOG(0, " SQL_C_CHAR, default: len = " FORMAT_LEN ", cbValueMax = " FORMAT_LEN ", rgbValueBindRow = '%s'\n", len, cbValueMax, rgbValueBindRow); cleanup: *length_return = len; return result; } /* 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; SIMPLE_TIME std_time; #ifdef HAVE_LOCALTIME_R struct tm tm; #endif /* HAVE_LOCALTIME_R */ SQLLEN pcbValueOffset, rgbValueOffset; char *rgbValueBindRow = NULL; SQLLEN *pcbValueBindRow = NULL, *pIndicatorBindRow = NULL; SQLSETPOSIROW bind_row = stmt->bind_row; int bind_size = opts->bind_size; int result = COPY_OK; const ConnectionClass *conn = SC_get_conn(stmt); BOOL text_bin_handling; const char *neut_str = value; char booltemp[3]; char midtemp[64]; GetDataClass *pgdc; 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)); MYLOG(0, "field_type = %d, fctype = %d, value = '%s', cbValueMax=" FORMAT_LEN "\n", field_type, fCType, (value == NULL) ? "" : value, cbValueMax); if (!value) { MYLOG(0, "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 || SQL_C_TYPE_DATE == fCType || 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: case SQL_C_TYPE_DATE: 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: { BOOL bZone = FALSE; /* time zone stuff is unreliable */ int zone; timestamp2stime(value, &std_time, &bZone, &zone); } 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; 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); MYLOG(DETAIL_LOG_LEVEL, "2stime fr=%d\n", std_time.fr); } else { /* * The timestamp is invalid so set something conspicuous, * like the epoch */ struct tm *tim; 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 */ const ConnInfo *ci = &(conn->connInfo); switch (((char *)value)[0]) { case 'f': case 'F': case 'n': case 'N': case '0': STRCPY_FIXED(booltemp, "0"); break; default: if (ci->true_is_minus1) STRCPY_FIXED(booltemp, "-1"); else STRCPY_FIXED(booltemp, "1"); } neut_str = booltemp; } 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(0, "index=("); for (i = 0;; i++) { if (sscanf(vp, "%hi", &shortv) != 1) break; MYPRINTF(0, " %hi", shortv); nval++; if (nval < maxc) short_array[i + 1] = shortv; /* skip the current token */ while (IS_NOT_SPACE(*vp)) vp++; /* and skip the space to the next token */ while ((*vp != '\0') && (isspace(*vp))) vp++; if (*vp == '\0') break; } MYPRINTF(0, ") 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); #ifdef UNICODE_SUPPORT if (fCType == SQL_C_WCHAR && CC_default_is_c(conn)) fCType = SQL_C_CHAR; #endif MYLOG(0, ", SQL_C_DEFAULT: fCType = %d\n", fCType); } text_bin_handling = FALSE; switch (fCType) { case INTERNAL_ASIS_TYPE: #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: #endif /* UNICODE_SUPPORT */ case SQL_C_CHAR: text_bin_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: case PG_TYPE_BYTEA: text_bin_handling = TRUE; break; } break; } if (text_bin_handling) { BOOL pre_convert = TRUE; int midsize = sizeof(midtemp); int i; /* Special character formatting as required */ /* * These really should return error if cbValueMax is not big * enough. */ switch (field_type) { case PG_TYPE_DATE: len = SPRINTF_FIXED(midtemp, "%.4d-%.2d-%.2d", std_time.y, std_time.m, std_time.d); break; case PG_TYPE_TIME: len = SPRINTF_FIXED(midtemp, "%.2d:%.2d:%.2d", std_time.hh, std_time.mm, std_time.ss); if (std_time.fr > 0) { int wdt; int fr = effective_fraction(std_time.fr, &wdt); len = SPRINTFCAT_FIXED(midtemp, ".%0*d", wdt, fr); } break; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: len = stime2timestamp(&std_time, midtemp, midsize, FALSE, (int) (midsize - 19 - 2) ); break; case PG_TYPE_UUID: len = strlen(neut_str); for (i = 0; i < len && i < midsize - 2; i++) midtemp[i] = toupper((UCHAR) neut_str[i]); midtemp[i] = '\0'; MYLOG(0, "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: pre_convert = FALSE; } if (pre_convert) neut_str = midtemp; result = convert_text_field_to_sql_c(gdata, stmt->current_col, neut_str, field_type, fCType, rgbValueBindRow, cbValueMax, conn, &len); } else { SQLGUID g; /* * 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, sizeof(midtemp))) neut_str = midtemp; else { MYLOG(0, "couldn't convert money type to %d\n", fCType); return COPY_UNSUPPORTED_TYPE; } } switch (fCType) { case SQL_C_DATE: case SQL_C_TYPE_DATE: /* 91 */ len = 6; { DATE_STRUCT *ds; struct tm *tim; if (bind_size > 0) ds = (DATE_STRUCT *) rgbValueBindRow; else ds = (DATE_STRUCT *) rgbValue + bind_row; /* * Initialize date in case conversion destination * expects date part from this source time data. * A value may be partially set here, so do some * sanity checks on the existing values before * setting them. */ tim = SC_get_localtime(stmt); if (std_time.m == 0) std_time.m = tim->tm_mon + 1; if (std_time.d == 0) std_time.d = tim->tm_mday; if (std_time.y == 0) std_time.y = tim->tm_year + 1900; ds->year = std_time.y; ds->month = std_time.m; ds->day = std_time.d; } break; case SQL_C_TIME: case SQL_C_TYPE_TIME: /* 92 */ 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: case SQL_C_TYPE_TIMESTAMP: /* 93 */ len = 16; { struct tm *tim; TIMESTAMP_STRUCT *ts; if (bind_size > 0) ts = (TIMESTAMP_STRUCT *) rgbValueBindRow; else ts = (TIMESTAMP_STRUCT *) rgbValue + bind_row; /* * Initialize date in case conversion destination * expects date part from this source time data. * A value may be partially set here, so do some * sanity checks on the existing values before * setting them. */ tim = SC_get_localtime(stmt); if (std_time.m == 0) std_time.m = tim->tm_mon + 1; if (std_time.d == 0) std_time.d = tim->tm_mday; if (std_time.y == 0) std_time.y = tim->tm_year + 1900; 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(99, "SQL_C_BIT: bind_row = " FORMAT_POSIROW " val = %d, cb = " FORMAT_LEN ", 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; case SQL_C_NUMERIC: { SQL_NUMERIC_STRUCT *ns; BOOL overflowed; if (bind_size > 0) ns = (SQL_NUMERIC_STRUCT *) rgbValueBindRow; else ns = (SQL_NUMERIC_STRUCT *) rgbValue + bind_row; parse_to_numeric_struct(neut_str, ns, &overflowed); if (overflowed) result = COPY_RESULT_TRUNCATED; } break; 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; #ifdef 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: /* The following is for SQL_C_VARBOOKMARK */ if (PG_TYPE_INT4 == field_type) { UInt4 ival = ATOI32U(neut_str); MYLOG(DETAIL_LOG_LEVEL, "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; } 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; } else { MYLOG(0, "couldn't convert the type %d to SQL_C_BINARY\n", field_type); return COPY_UNSUPPORTED_TYPE; } break; case SQL_C_GUID: result = char2guid(neut_str, &g); if (COPY_OK != result) { MYLOG(0, "Could not convert to SQL_C_GUID\n"); return COPY_UNSUPPORTED_TYPE; } len = sizeof(g); if (bind_size > 0) *((SQLGUID *) rgbValueBindRow) = g; else *((SQLGUID *) rgbValue + bind_row) = g; break; 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; default: MYLOG(0, "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_USING_CURSOR (1L << 1) #define FLGP_SELECT_INTO (1L << 2) #define FLGP_SELECT_FOR_UPDATE_OR_SHARE (1L << 3) #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; ssize_t from_pos; ssize_t where_pos; ssize_t stmt_len; int in_status; char escape_in_literal, prev_token_end; const char *dollar_tag; ssize_t taglen; char token_curr[64]; int token_len; size_t declare_pos; UInt4 flags, comment_level; encoded_str encstr; } QueryParse; static void QP_initialize(QueryParse *q, const StatementClass *stmt) { q->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_status = 0; q->escape_in_literal = '\0'; q->dollar_tag = NULL; q->taglen = -1; q->token_curr[0] = '\0'; q->token_len = 0; q->prev_token_end = TRUE; q->declare_pos = 0; q->flags = 0; q->comment_level = 0; make_encoded_str(&q->encstr, SC_get_conn(stmt), q->statement); } enum { QP_IN_IDENT_KEYWORD = 1L /* identifier or keyword */ , QP_IN_DQUOTE_IDENTIFIER = (1L << 1) /* "" */ , QP_IN_LITERAL = (1L << 2) /* '' */ , QP_IN_ESCAPE = (1L << 3) /* \ in literal */ , QP_IN_DOLLAR_QUOTE = (1L << 4) /* $...$ $...$ */ , QP_IN_COMMENT_BLOCK = (1L << 5) /* slash asterisk */ , QP_IN_LINE_COMMENT = (1L << 6) /* -- */ }; #define QP_in_idle_status(qp) ((qp)->in_status == 0) #define QP_is_in(qp, status) (((qp)->in_status & status) != 0) #define QP_enter(qp, status) ((qp)->in_status |= status) #define QP_exit(qp, status) ((qp)->in_status &= (~status)) /* * ResolveOneParam can be work in these four modes: * * RPM_REPLACE_PARAMS * Replace parameter markers with their values. * * RPM_FAKE_PARAMS * The query is going to be sent to the server only to be able to * Describe the result set. Parameter markers are replaced with NULL * literals if we don't know their real values yet. * * RPM_BUILDING_PREPARE_STATEMENT * Building a query suitable for PREPARE statement, or server-side Parse. * Parameter markers are replaced with $n-style parameter markers. * * RPM_BUILDING_BIND_REQUEST * Building the actual parameter values to send to the server in a Bind * request. Return an unescaped value that will be accepted by the * server's input function. */ typedef enum { RPM_REPLACE_PARAMS, RPM_FAKE_PARAMS, RPM_BUILDING_PREPARE_STATEMENT, RPM_BUILDING_BIND_REQUEST } ResolveParamMode; #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) #define FLGB_PARAM_CAST (1L << 12) typedef struct _QueryBuild { char *query_statement; 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; size_t load_from_pos; ResolveParamMode param_mode; 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, ResolveParamMode param_mode) { size_t newsize = 0; qb->param_mode = param_mode; qb->flags = 0; qb->load_stmt_len = 0; qb->load_from_pos = 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; /* Copy options from statement */ 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->discard_output_params) qb->flags |= FLGB_DISCARD_OUTPUT; qb->num_io_params = CountParameters(stmt, NULL, NULL, &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; /* Copy options from connection */ 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; 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->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, BOOL *isnull, BOOL *usebinary, Oid *pgType); 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 BOOL convert_special_chars(QueryBuild *qb, const char *si, size_t used); /* * Enlarge qb->query_statement buffer so that it is at least newsize + 1 * in size. */ static ssize_t enlarge_query_statement(QueryBuild *qb, size_t newsize) { size_t newalsize = INIT_MIN_ALLOC; CSTR func = "enlarge_statement"; 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) \ do { \ if ((newpos) >= (qb)->str_alsize) \ { \ if (enlarge_query_statement(qb, newpos) <= 0) \ { \ retval = SQL_ERROR; \ goto cleanup; \ } \ } \ } while(0) /*---------- * 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; \ \ newlimit = (qb)->npos; \ if (qb->flags & FLGB_HEX_BIN_FORMAT) \ newlimit += 2 * used + 4; \ else \ newlimit += 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 { \ if (!convert_special_chars(qb, buf, used)) \ { \ retval = SQL_ERROR; \ goto cleanup; \ } \ } while (0) 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 (MBCS_NON_ASCII(encstr)) 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; while (isspace((UCHAR) *stmt)) stmt++; switch (*stmt) { case '\0': case ',': case LITERAL_QUOTE: case DOLLAR_QUOTE: return FALSE; case '-': case '/': return TRUE; case IDENTIFIER_QUOTE: /* double quoted table name ? */ do { do { ++stmt; } while (*stmt != IDENTIFIER_QUOTE && *stmt); if (*stmt) stmt++; } while (*stmt == IDENTIFIER_QUOTE); break; default: while (IS_NOT_SPACE(*stmt)) stmt++; break; } if (!*stmt) return FALSE; while (isspace((UCHAR) *stmt)) stmt++; if ('/' == *stmt || '-' == *stmt) return TRUE; if (strnicmp(stmt, "from", 4)) return FALSE; return TRUE; } /*---------- * 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, zeroflag = 0; while (isspace((UCHAR) *wstmt)) 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 { flag |= FLGP_SELECT_FOR_UPDATE_OR_SHARE; /* maybe */ return flag; } zeroflag = flag; /* returns flag anyway */ wstmt += advance; if (IS_NOT_SPACE(wstmt[0])) return zeroflag; else if (0 != (flag & FLGP_SELECT_FOR_READONLY)) { if (IS_NOT_SPACE(wstmt[0])) return zeroflag; while (isspace((UCHAR) *wstmt)) wstmt++; if (!*wstmt) return zeroflag; if (0 != strnicmp(wstmt, "only", advance = 4)) return zeroflag; wstmt += advance; } if (IS_NOT_SPACE(wstmt[0])) return zeroflag; *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 && IS_NOT_SPACE(*wstmt); stapos--, wstmt--) ; if (stapos < 0 || 0 == *wstmt) 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)) wstmt++; if (!*wstmt) return FALSE; if (strnicmp(wstmt, "VALUES", 6)) return FALSE; wstmt += 6; if (!wstmt[0] || IS_NOT_SPACE(wstmt[0])) return FALSE; while (isspace((UCHAR) *wstmt)) wstmt++; if (*wstmt != '(' || *(++wstmt) != ')') return FALSE; wstmt++; *endpos = wstmt - stmt; return !wstmt[0] || isspace((UCHAR) wstmt[0]) || ';' == wstmt[0]; } static ProcessedStmt * buildProcessedStmt(const char *srvquery, ssize_t endp, int num_params) { ProcessedStmt *pstmt; size_t qlen; qlen = (endp == SQL_NTS) ? strlen(srvquery) : endp; pstmt = malloc(sizeof(ProcessedStmt)); if (!pstmt) return NULL; pstmt->next = NULL; pstmt->query = malloc(qlen + 1); if (!pstmt->query) { free(pstmt); return NULL; } memcpy(pstmt->query, srvquery, qlen); pstmt->query[qlen] = '\0'; pstmt->num_params = num_params; return pstmt; } /* * Process the original SQL query for execution using server-side prepared * statements. * * Split a possible multi-statement query into parts, and replace ?-style * parameter markers with $n. The resulting queries are stored in a linked * list in stmt->processed_statements. * * If 'fake_params' is true, we will replace ?-style parameter markers with * fake parameter values instead. This is used when a query's result columns * have to be described (SQLPrepare+SQLDescribeCol) before executing the * query, in UseServerSidePrepare=0 mode. */ RETCODE prepareParametersNoDesc(StatementClass *stmt, BOOL fake_params, BOOL param_cast) { CSTR func = "process_statements"; RETCODE retval; ConnectionClass *conn = SC_get_conn(stmt); char plan_name[32]; po_ind_t multi; const char *orgquery = NULL, *srvquery = NULL; ssize_t endp1, endp2; SQLSMALLINT num_pa = 0, num_p1, num_p2; ProcessedStmt *pstmt; ProcessedStmt *last_pstmt; QueryParse query_org, *qp; QueryBuild query_crt, *qb; MYLOG(DETAIL_LOG_LEVEL, "entering\n"); qp = &query_org; QP_initialize(qp, stmt); qb = &query_crt; if (QB_initialize(qb, qp->stmt_len, stmt, fake_params ? RPM_FAKE_PARAMS : RPM_BUILDING_PREPARE_STATEMENT) < 0) { SC_set_errornumber(stmt, STMT_NO_MEMORY_ERROR); return SQL_ERROR; } if (param_cast) qb->flags |= FLGB_PARAM_CAST; 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??? if (NAMED_PARSE_REQUEST == SC_get_prepare_method(stmt)) SPRINTF_FIXED(plan_name, "_PLAN%p", stmt); else plan_name[0] = '\0'; stmt->current_exec_param = 0; multi = stmt->multi_statement; orgquery = stmt->statement; srvquery = qb->query_statement; SC_scanQueryAndCountParams(orgquery, conn, &endp1, &num_p1, &multi, NULL); SC_scanQueryAndCountParams(srvquery, conn, &endp2, NULL, NULL, NULL); MYLOG(0, "parsed for the first command length=" FORMAT_SSIZE_T "(" FORMAT_SSIZE_T ") num_p=%d\n", endp2, endp1, num_p1); pstmt = buildProcessedStmt(srvquery, endp2 < 0 ? SQL_NTS : endp2, fake_params ? 0 : num_p1); if (!pstmt) { SC_set_errornumber(stmt, STMT_NO_MEMORY_ERROR); goto cleanup; } stmt->processed_statements = last_pstmt = pstmt; 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(0, "parsed for the subsequent command length=" FORMAT_SSIZE_T "(" FORMAT_SSIZE_T ") num_p=%d\n", endp2, endp1, num_p1); pstmt = buildProcessedStmt(srvquery, endp2 < 0 ? SQL_NTS : endp2, fake_params ? 0 : num_p1); if (!pstmt) { SC_set_errornumber(stmt, STMT_NO_MEMORY_ERROR); goto cleanup; } last_pstmt->next = pstmt; last_pstmt = pstmt; } SC_set_planname(stmt, plan_name); SC_set_prepared(stmt, plan_name[0] ? PREPARING_PERMANENTLY : PREPARING_TEMPORARILY); retval = SQL_SUCCESS; cleanup: #undef return stmt->current_exec_param = -1; QB_Destructor(qb); return retval; } /* * Describe the parameters and portal for given query. */ static RETCODE desc_params_and_sync(StatementClass *stmt) { CSTR func = "desc_params_and_sync"; RETCODE retval; ConnectionClass *conn = SC_get_conn(stmt); QResultClass *res; char *plan_name; int func_cs_count = 0; SQLSMALLINT num_pa = 0; ProcessedStmt *pstmt; MYLOG(DETAIL_LOG_LEVEL, "entering\n"); retval = SQL_ERROR; #define return DONT_CALL_RETURN_FROM_HERE??? ENTER_INNER_CONN_CS(conn, func_cs_count); plan_name = stmt->plan_name ? stmt->plan_name : ""; pstmt = stmt->processed_statements; stmt->current_exec_param = 0; res = ParseAndDescribeWithLibpq(stmt, plan_name, pstmt->query, pstmt->num_params, "prepare_and_describe", NULL); if (res == NULL) goto cleanup; // SC_set_Result(stmt, res); QR_Destructor(stmt->parsed); stmt->parsed = res; if (!QR_command_maybe_successful(res)) { SC_set_error(stmt, STMT_EXEC_ERROR, "Error while preparing parameters", func); goto cleanup; } num_pa = pstmt->num_params; for (pstmt = pstmt->next; pstmt; pstmt = pstmt->next) { if (pstmt->num_params > 0) { stmt->current_exec_param = num_pa; res = ParseAndDescribeWithLibpq(stmt, plan_name, pstmt->query, pstmt->num_params, "prepare_and_describe", NULL); if (res == NULL) goto cleanup; QR_Destructor(res); num_pa += pstmt->num_params; } } retval = SQL_SUCCESS; cleanup: #undef return CLEANUP_FUNC_CONN_CS(func_cs_count, conn); stmt->current_exec_param = -1; return retval; } /* * Process the original SQL query, and and ask the server describe the * parameters. */ RETCODE prepareParameters(StatementClass *stmt, BOOL fake_params) { ConnectionClass *conn = SC_get_conn(stmt); switch (stmt->prepared) { case PREPARED_TEMPORARILY: if (conn->unnamed_prepared_stmt == stmt) return SQL_SUCCESS; else break; case NOT_YET_PREPARED: case PREPARING_PERMANENTLY: case PREPARING_TEMPORARILY: break; default: return SQL_SUCCESS; } MYLOG(DETAIL_LOG_LEVEL, "calling prepareParameters\n"); if (prepareParametersNoDesc(stmt, fake_params, PARSE_PARAM_CAST) == SQL_ERROR) return SQL_ERROR; return desc_params_and_sync(stmt); } /* * 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; ConnectionClass *conn = SC_get_conn(stmt); ConnInfo *ci = &(conn->connInfo); const char *bestitem = NULL; MYLOG(DETAIL_LOG_LEVEL, "entering prepared=%d\n", 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; } MYLOG(DETAIL_LOG_LEVEL, "type=" FORMAT_UINTEGER " concur=" FORMAT_UINTEGER "\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_FIXED(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); qb = &query_crt; qb->query_statement = NULL; if (PREPARED_PERMANENTLY == stmt->prepared) { /* already prepared */ retval = SQL_SUCCESS; goto cleanup; } /* * If it's a simple read-only cursor, we use extended query protocol to * Parse it. */ if (buildPrepareStatement && SQL_CONCUR_READ_ONLY == stmt->options.scroll_concurrency) { /* Nothing to do here. It will be prepared before execution. */ char plan_name[32]; if (NAMED_PARSE_REQUEST == SC_get_prepare_method(stmt)) SPRINTF_FIXED(plan_name, "_PLAN%p", stmt); else plan_name[0] = '\0'; SC_set_planname(stmt, plan_name); SC_set_prepared(stmt, plan_name[0] ? PREPARING_PERMANENTLY : PREPARING_TEMPORARILY); retval = SQL_SUCCESS; goto cleanup; } /* Otherwise... */ if (QB_initialize(qb, qp->stmt_len, stmt, RPM_REPLACE_PARAMS) < 0) { retval = SQL_ERROR; goto cleanup; } if (SIMPLE_PARAM_CAST) qb->flags |= FLGB_PARAM_CAST; new_statement = qb->query_statement; /* For selects, prepend a declare cursor to the statement */ if (SC_may_use_cursor(stmt) && stmt->external) { const char *opt_scroll = NULL_STRING, *opt_hold = NULL_STRING; 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 (SQL_CURSOR_FORWARD_ONLY != stmt->options.cursor_type) opt_scroll = " scroll"; } if (SC_is_fetchcursor(stmt)) { snprintfcat(new_statement, qb->str_alsize, "declare \"%s\"%s cursor%s for ", 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; 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)) { 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); if (!stmt->load_statement) { retval = SQL_ERROR; goto cleanup; } memcpy(stmt->load_statement, qb->query_statement + qp->declare_pos, npos); stmt->load_from_pos = qb->load_from_pos - qp->declare_pos; stmt->load_statement[npos] = '\0'; } 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; } /* * When 'tag' starts with dollar-quoted tag, e.g. "$foo$...", return * the length of the tag (e.g. 5, with the previous example). If there * is no end-dollar in the string, returns 0. The caller should've checked * that the string begins with a dollar. */ size_t findTag(const char *tag, int ccsc) { size_t taglen = 0; encoded_str encstr; UCHAR tchar; encoded_str_constr(&encstr, ccsc, tag + 1); for (tchar = encoded_nextchar(&encstr); tchar; tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) continue; if (DOLLAR_QUOTE == tchar) { taglen = encstr.pos + 2; break; } if (!isalnum(tchar)) break; } return taglen; } int findIdentifier(const UCHAR *str, int ccsc, const UCHAR **next_token) { int slen = -1; encoded_str encstr; UCHAR tchar; BOOL dquote = FALSE; *next_token = NULL; encoded_str_constr(&encstr, ccsc, (const char *) str); for (tchar = encoded_nextchar(&encstr); tchar; tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) continue; if (encstr.pos == 0) /* the first character */ { if (dquote = (IDENTIFIER_QUOTE == tchar), dquote) continue; if (!isalpha(tchar)) { slen = 0; if (IS_NOT_SPACE(tchar)) *next_token = ENCODE_PTR(encstr); break; } } if (dquote) { if (IDENTIFIER_QUOTE == tchar) { tchar = encoded_nextchar(&encstr); if (IDENTIFIER_QUOTE == tchar) continue; slen = encstr.pos; break; } } else { if (isalnum(tchar)) continue; switch (tchar) { case '_': case DOLLAR_QUOTE: continue; } slen = encstr.pos; if (IS_NOT_SPACE(tchar)) *next_token = ENCODE_PTR(encstr); break; } } if (slen < 0 && !dquote) slen = encstr.pos; if (NULL == *next_token) { for (; tchar; tchar = encoded_nextchar(&encstr)) { if (IS_NOT_SPACE((UCHAR) tchar)) { *next_token = ENCODE_PTR(encstr); break; } } } return slen; } static pgNAME lower_or_remove_dquote(pgNAME nm, const UCHAR *src, int srclen, int ccsc) { int i, outlen; char *tc; UCHAR tchar; BOOL idQuote; encoded_str encstr; if (nm.name) tc = realloc(nm.name, srclen + 1); else tc = malloc(srclen + 1); if (!tc) { NULL_THE_NAME(nm); return nm; } nm.name = tc; idQuote = (src[0] == IDENTIFIER_QUOTE); encoded_str_constr(&encstr, ccsc, (const char *) src); for (i = 0, tchar = encoded_nextchar(&encstr), outlen = 0; i < srclen; i++, tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) { tc[outlen++] = tchar; continue; } if (idQuote) { if (IDENTIFIER_QUOTE == tchar) { if (0 == i) continue; if (i == srclen - 1) continue; i++; tchar = encoded_nextchar(&encstr); } tc[outlen++] = tchar; } else { tc[outlen++] = tolower(tchar); } } tc[outlen] = '\0'; return nm; } int eatTableIdentifiers(const UCHAR *str, int ccsc, pgNAME *table, pgNAME *schema) { int len; const UCHAR *next_token; const UCHAR *tstr = str; while (isspace(*tstr)) tstr++; if ((len = findIdentifier(tstr, ccsc, &next_token)) <= 0) return len; /* table name doesn't exist */ if (table) { if (IDENTIFIER_QUOTE == *tstr) *table = lower_or_remove_dquote(*table, tstr, len, ccsc); else STRN_TO_NAME(*table, tstr, len); } if (!next_token || '.' != *next_token || (int) (next_token - tstr) != len) return (int) (next_token - str); /* table only */ tstr = next_token + 1; if ((len = findIdentifier(tstr, ccsc, &next_token)) <= 0) return -1; if (table) { if (schema) MOVE_NAME(*schema, *table); *table = lower_or_remove_dquote(*table, tstr, len, ccsc); } if (!next_token || '.' != *next_token || (int) (next_token - tstr) != len) return (int) (next_token - str); /* schema.table */ tstr = next_token + 1; if ((len = findIdentifier(tstr, ccsc, &next_token)) <= 0) return -1; if (table) { if (schema) MOVE_NAME(*schema, *table); *table = lower_or_remove_dquote(*table, tstr, len, ccsc); } return (int) (next_token - str); /* catalog.schema.table */ } static void token_start(QueryParse *qp, char oldchar) { qp->prev_token_end = FALSE; qp->token_curr[0] = oldchar; qp->token_len = 1; } static int token_finish(QueryParse *qp, char oldchar, char *finished_token) { int ret = -1; if (!qp->prev_token_end) { if (oldchar && qp->token_len + 1 < sizeof(qp->token_curr)) qp->token_curr[qp->token_len++] = oldchar; qp->prev_token_end = TRUE; qp->token_curr[qp->token_len] = '\0'; strncpy_null(finished_token, qp->token_curr, sizeof(qp->token_curr)); MYLOG(DETAIL_LOG_LEVEL, "finished token=%s\n", finished_token); ret = qp->token_len; } return ret; } static int token_restart(QueryParse *qp, char oldchar, char *finished_token) { int ret = token_finish(qp, 0, finished_token); if (IS_NOT_SPACE(oldchar)) token_start(qp, oldchar); return ret; } static int token_continue(QueryParse *qp, char oldchar) { if (qp->prev_token_end) token_start(qp, oldchar); else if (qp->token_len + 1 < sizeof(qp->token_curr)) qp->token_curr[qp->token_len++] = oldchar; return qp->token_len; } /* * ParseToken functions */ typedef struct { QueryParse *qp; int token_len; BOOL curchar_processed; unsigned int in_status; char finished_token[sizeof(((QueryParse *) NULL)->token_curr)]; } ParseToken; static void PT_initialize(ParseToken *pt, QueryParse *qp) { pt->qp = qp; pt->token_len = -1; pt->curchar_processed = FALSE; pt->in_status = 0; pt->finished_token[0] = '\0'; } static int PT_token_finish(ParseToken *pt, char oldchar) { int token_len_tmp; if (pt->curchar_processed) return pt->token_len; if ((token_len_tmp = token_finish(pt->qp, oldchar, pt->finished_token)) > 0) { pt->token_len = token_len_tmp; pt->in_status = pt->qp->in_status; } if (oldchar) pt->curchar_processed = TRUE; return pt->token_len; } static int PT_token_restart(ParseToken *pt, char oldchar) { int token_len_tmp; unsigned int in_status_save; if (pt->curchar_processed) return pt->token_len; in_status_save = pt->qp->in_status; if ((token_len_tmp = token_restart(pt->qp, oldchar, pt->finished_token)) > 0) { pt->token_len = token_len_tmp; pt->in_status = in_status_save; } pt->curchar_processed = TRUE; return pt->token_len; } static int PT_token_continue(ParseToken *pt, char oldchar) { if (pt->curchar_processed) return pt->token_len; token_continue(pt->qp, oldchar); pt->curchar_processed = TRUE; return pt->token_len; } #define PT_TOKEN_IGNORE(pt) ((pt)->curchar_processed = TRUE) 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; BOOL isnull; BOOL isbinary; Oid dummy; ParseToken pts, *pt = &pts; PT_initialize(pt, qp); if (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, "\" "); qb->load_from_pos = qb->npos; } 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 (MBCS_NON_ASCII(qp->encstr)) { if (QP_in_idle_status(qp)) { PT_token_restart(pt, oldchar); /* placed before QP_enter() */ QP_enter(qp, QP_IN_IDENT_KEYWORD); /* identifier */ } else if (qp->token_len > 0) PT_token_continue(pt, oldchar); CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } /* * From here we are guaranteed to handle a 1-byte character. */ if (QP_is_in(qp, QP_IN_IDENT_KEYWORD)) /* identifier or keyword */ { if (isalnum((UCHAR)oldchar) || DOLLAR_QUOTE == oldchar || '_' == oldchar) { CVT_APPEND_CHAR(qb, oldchar); PT_token_continue(pt, oldchar); return SQL_SUCCESS; } PT_token_finish(pt, 0); /* placed before QP_exit() */ QP_exit(qp, QP_IN_IDENT_KEYWORD); } if (QP_is_in(qp, QP_IN_ESCAPE)) /* escape in literal check */ { QP_exit(qp, QP_IN_ESCAPE); CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (QP_is_in(qp, 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_exit(qp, QP_IN_DOLLAR_QUOTE); qp->dollar_tag = NULL; qp->taglen = -1; return SQL_SUCCESS; } } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (QP_is_in(qp, QP_IN_LITERAL)) /* quote check */ { if (oldchar == LITERAL_QUOTE) { PT_token_finish(pt, oldchar); /* placed before QP_exit() */ QP_exit(qp, QP_IN_LITERAL); } else { PT_token_continue(pt, oldchar); if (oldchar == qp->escape_in_literal) QP_enter(qp, QP_IN_ESCAPE); /* escape in literal */ } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (QP_is_in(qp, QP_IN_DQUOTE_IDENTIFIER)) /* double quote check */ { if (oldchar == IDENTIFIER_QUOTE) { PT_token_finish(pt, oldchar); /* placed before QP_exit() */ QP_exit(qp, QP_IN_DQUOTE_IDENTIFIER); } else PT_token_continue(pt, oldchar); CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (QP_is_in(qp, QP_IN_COMMENT_BLOCK)) /* comment_level check */ { if ('/' == oldchar && '*' == F_OldPtr(qp)[1]) { qp->comment_level++; QP_enter(qp, QP_IN_COMMENT_BLOCK); CVT_APPEND_CHAR(qb, oldchar); F_OldNext(qp); oldchar = F_OldChar(qp); } else if ('*' == oldchar && '/' == F_OldPtr(qp)[1]) { if (--qp->comment_level <= 0) QP_exit(qp, QP_IN_COMMENT_BLOCK); CVT_APPEND_CHAR(qb, oldchar); F_OldNext(qp); oldchar = F_OldChar(qp); } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else if (QP_is_in(qp, QP_IN_LINE_COMMENT)) /* line comment check */ { if (PG_LINEFEED == oldchar) QP_exit(qp, QP_IN_LINE_COMMENT); CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } if (!QP_in_idle_status(qp)) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "logic error? not in QP_in_idle_status"; return SQL_ERROR; } /* * From here we are guaranteed to be in neither a literal_escape, * a LITREAL_QUOTE nor an IDENTIFIER_QUOTE. */ /* Squeeze carriage-return/linefeed pairs to linefeed only */ 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 */ if (oldchar == ODBC_ESCAPE_START) { PT_token_finish(pt, 0); if (SQL_ERROR == convert_escape(qp, qb)) { if (0 == qb->errornumber) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "ODBC escape convert error"; } MYLOG(0, "convert_escape error\n"); return SQL_ERROR; } PT_TOKEN_IGNORE(pt); return SQL_SUCCESS; } /* End of an escape sequence */ else if (oldchar == ODBC_ESCAPE_END) { PT_token_finish(pt, 0); PT_TOKEN_IGNORE(pt); 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); const char *auto_increment; for (i = 0; i < num_fields; i++) { auto_increment = (const char *) QR_get_value_backend_text(coli->result, i, COLUMNS_AUTO_INCREMENT); if (auto_increment && auto_increment[0] == '1') { converted = TRUE; break; } } if (converted) { const char *column_def = (const char *) QR_get_value_backend_text(coli->result, i, COLUMNS_COLUMN_DEF); if (NULL != column_def && strncmp(column_def, "nextval", 7) == 0) { CVT_APPEND_STR(qb, "curr"); CVT_APPEND_STR(qb, column_def + 4); } else { char relcnv[128]; const char *column_name = (const char *) QR_get_value_backend_text(coli->result, i, COLUMNS_COLUMN_NAME); CVT_APPEND_STR(qb, "currval(pg_get_serial_sequence('"); if (NAME_IS_VALID(conn->schemaIns)) { CVT_APPEND_STR(qb, identifierEscape((const SQLCHAR *) SAFE_NAME(conn->schemaIns), SQL_NTS, conn, relcnv, sizeof(relcnv), TRUE)); CVT_APPEND_STR(qb, "."); } CVT_APPEND_STR(qb, identifierEscape((const SQLCHAR *) SAFE_NAME(conn->tableIns), SQL_NTS, conn, relcnv, sizeof(relcnv), TRUE)); CVT_APPEND_STR(qb, "','"); if (NULL != column_name) CVT_APPEND_STR(qb, identifierEscape((const SQLCHAR *) column_name, SQL_NTS, conn, relcnv, sizeof(relcnv), FALSE)); CVT_APPEND_STR(qb, "')::regclass)"); } } } } 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) { PT_token_finish(pt, 0); qp->taglen = findTag(F_OldPtr(qp), qp->encstr.ccsc); if (qp->taglen > 0) { QP_enter(qp, QP_IN_DOLLAR_QUOTE); 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) { PT_token_restart(pt, oldchar); /* placed before QP_enter() */ QP_enter(qp, QP_IN_LITERAL); qp->escape_in_literal = CC_get_escape(qb->conn); if (!qp->escape_in_literal) { if (LITERAL_EXT == F_OldPtr(qp)[-1]) qp->escape_in_literal = ESCAPE_IN_LITERAL; } } else if (oldchar == IDENTIFIER_QUOTE) { PT_token_restart(pt, oldchar); /* placed before QP_enter() */ QP_enter(qp, QP_IN_DQUOTE_IDENTIFIER); } else if ('/' == oldchar && '*' == F_OldPtr(qp)[1]) { qp->comment_level++; PT_token_finish(pt, 0); /* comments are excluded */ QP_enter(qp, QP_IN_COMMENT_BLOCK); PT_TOKEN_IGNORE(pt); } else if ('-' == oldchar && '-' == F_OldPtr(qp)[1]) { PT_token_finish(pt, 0); /* comments are excluded */ QP_enter(qp, QP_IN_LINE_COMMENT); PT_TOKEN_IGNORE(pt); } else if (oldchar == ';') { PT_token_restart(pt, 0); /* * 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 (isalnum(oldchar)) { PT_token_restart(pt, oldchar); /* placed before QP_enter() */ QP_enter(qp, QP_IN_IDENT_KEYWORD); /* identifier or keyword */ } else { /* * a hack to handle boolean items in VBA * with MS Access. * VBA seems to transform the where condition * a_boolean_item=True * into * ("a_boolean_item" = 1) * which causes an ERROR:Operator does not exist boolean = integer . * So transforms it into * ("a_boolean_item"='1') * here. */ if (')' == oldchar && qb->conn->ms_jet && 1 == qp->token_len && '1' == qp->token_curr[0] && 8 <= F_OldPos(qp)) { const char *oldptr = F_OldPtr(qp); int oldpos = F_OldPos(qp); if (strncmp(oldptr - 5, "\" =", 3) == 0) { int i; for (i = 6; i < oldpos - 1; i++) { if (oldptr[-i] == '"') { if (oldptr[-(i+1)] == '(') { F_NewPtr(qb)[-4] = '='; F_NewPtr(qb)[-3] = '\''; F_NewPtr(qb)[-2] = '1'; F_NewPtr(qb)[-1] = '\''; } break; } } } } if (!isalnum((UCHAR) oldchar)) { PT_token_restart(pt, oldchar); } else PT_token_continue(pt, oldchar); } if (pt->token_len > 0) MYLOG(0, "token_len=%d status=%x token=%s\n", pt->token_len, pt->in_status, pt->finished_token); if (!pt->curchar_processed) { MYLOG(0, "Forgot to process ParseToken char=%c status=%u\n", oldchar, qp->in_status); #ifdef NOT_USED /* strict check for debugging */ qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "Forget to process ParseToken"; return SQL_ERROR; #endif /* NOT_USED */ } switch (pt->token_len) { case 4: if (0 != (qp->flags & FLGP_USING_CURSOR) && into_table_from(&qp->statement[qp->opos - pt->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(pt->finished_token, "join") == 0) check_join(stmt, F_OldPtr(qp), F_OldPos(qp)); break; case 3: if (0 != (qp->flags & FLGP_USING_CURSOR) && strnicmp(pt->finished_token, "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)) { qp->flags |= flg; remove_declare_cursor(qb, qp); } else qp->flags |= flg; } break; case 2: { size_t endpos; if (STMT_TYPE_INSERT == qp->statement_type && strnicmp(pt->finished_token, "()", 2) == 0 && insert_without_target(F_OldPtr(qp), &endpos)) { qb->npos -= 2; CVT_APPEND_STR(qb, "DEFAULT VALUES"); qp->opos += endpos; return SQL_SUCCESS; } break; } case 1: { size_t endpos; if (STMT_TYPE_INSERT == qp->statement_type && pt->finished_token[0] == '(' && oldchar == ')' && insert_without_target(F_OldPtr(qp)+1, &endpos)) { qb->npos --; CVT_APPEND_STR(qb, " DEFAULT VALUES"); qp->opos += endpos; return SQL_SUCCESS; } break; } } CVT_APPEND_CHAR(qb, oldchar); return SQL_SUCCESS; } else PT_token_restart(pt, oldchar); /* * It's a '?' parameter alright */ retval = ResolveOneParam(qb, qp, &isnull, &isbinary, &dummy); if (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 /* * Build an array of parameters to pass to libpq's PQexecPrepared * function. */ BOOL build_libpq_bind_params(StatementClass *stmt, int *nParams, OID **paramTypes, char ***paramValues, int **paramLengths, int **paramFormats, int *resultFormat) { CSTR func = "build_libpq_bind_params"; QueryBuild qb; SQLSMALLINT num_p; int i, num_params; ConnectionClass *conn = SC_get_conn(stmt); BOOL ret = FALSE, discard_output; RETCODE retval; const IPDFields *ipdopts = SC_get_IPDF(stmt); *paramTypes = NULL; *paramValues = NULL; *paramLengths = NULL; *paramFormats = NULL; num_params = stmt->num_params; if (num_params < 0) { PGAPI_NumParams(stmt, &num_p); num_params = num_p; } if (ipdopts->allocated < num_params) { char tmp[100]; if (0 == ipdopts->allocated) STRCPY_FIXED(tmp, "Parameters exist but IPD isn't set. Please call SQLDescribeParam()"); else SPRINTF_FIXED(tmp, "The # of IPD parameters %d < %d the # of parameter markers", ipdopts->allocated, num_params); MYLOG(0, "%s\n", tmp); SC_set_error(stmt, STMT_COUNT_FIELD_INCORRECT, tmp, func); return FALSE; } if (QB_initialize(&qb, MIN_ALC_SIZE, stmt, RPM_BUILDING_BIND_REQUEST) < 0) return FALSE; if (num_params > 0) { *paramTypes = malloc(sizeof(OID) * num_params); if (*paramTypes == NULL) goto cleanup; *paramValues = malloc(sizeof(char *) * num_params); if (*paramValues == NULL) goto cleanup; memset(*paramValues, 0, sizeof(char *) * num_params); *paramLengths = malloc(sizeof(int) * num_params); if (*paramLengths == NULL) goto cleanup; *paramFormats = malloc(sizeof(int) * num_params); if (*paramFormats == NULL) goto cleanup; } qb.flags |= FLGB_BINARY_AS_POSSIBLE; MYLOG(DETAIL_LOG_LEVEL, "num_params=%d proc_return=%d\n", num_params, stmt->proc_return); num_p = num_params - qb.num_discard_params; MYLOG(DETAIL_LOG_LEVEL, "num_p=%d\n", num_p); discard_output = (0 != (qb.flags & FLGB_DISCARD_OUTPUT)); *nParams = 0; if (num_p > 0) { ParameterImplClass *parameters = ipdopts->parameters; int pno; BOOL isnull; BOOL isbinary; char *val_copy; OID pgType; /* * Now build the parameter values. */ for (i = 0, pno = 0; i < stmt->num_params; i++) { qb.npos = 0; retval = ResolveOneParam(&qb, NULL, &isnull, &isbinary, &pgType); if (SQL_ERROR == retval) { QB_replace_SC_error(stmt, &qb, func); ret = FALSE; goto cleanup; } MYLOG(DETAIL_LOG_LEVEL, "%dth parameter type oid is %u\n", i, PIC_dsp_pgtype(conn, parameters[i])); if (i < qb.proc_return) continue; if (SQL_PARAM_OUTPUT == parameters[i].paramType) { if (discard_output) continue; (*paramTypes)[pno] = PG_TYPE_VOID; (*paramValues)[pno] = NULL; (*paramLengths)[pno] = 0; (*paramFormats)[pno] = 0; pno++; continue; } if (!isnull) { val_copy = malloc(qb.npos + 1); if (!val_copy) goto cleanup; memcpy(val_copy, qb.query_statement, qb.npos); val_copy[qb.npos] = '\0'; (*paramTypes)[pno] = pgType; (*paramValues)[pno] = val_copy; if (qb.npos > INT_MAX) goto cleanup; (*paramLengths)[pno] = (int) qb.npos; } else { (*paramTypes)[pno] = pgType; (*paramValues)[pno] = NULL; (*paramLengths)[pno] = 0; } if (isbinary) MYLOG(0, "%dth parameter is of binary format\n", pno); (*paramFormats)[pno] = isbinary ? 1 : 0; pno++; } *nParams = pno; } /* result format is text */ *resultFormat = 0; ret = TRUE; cleanup: QB_Destructor(&qb); return ret; } /* * With SQL_MAX_NUMERIC_LEN = 16, the highest representable number is * 2^128 - 1, which fits in 39 digits. */ #define MAX_NUMERIC_DIGITS 39 /* * Convert a SQL_NUMERIC_STRUCT into string representation. */ static void ResolveNumericParam(const SQL_NUMERIC_STRUCT *ns, char *chrform) { Int4 i, vlen, len, newlen; const UCHAR *val = (const UCHAR *) ns->val; UCHAR vals[SQL_MAX_NUMERIC_LEN]; int lastnonzero; UCHAR calv[MAX_NUMERIC_DIGITS]; int precision; MYLOG(DETAIL_LOG_LEVEL, "C_NUMERIC [prec=%d scale=%d]", ns->precision, ns->scale); if (0 == ns->precision) { if (chrform) strncpy_null(chrform, "0", 2); return; } precision = ns->precision; if (precision > MAX_NUMERIC_DIGITS) precision = MAX_NUMERIC_DIGITS; /* * The representation in SQL_NUMERIC_STRUCT is 16 bytes with most * significant byte first. Make a working copy. */ memcpy(vals, val, SQL_MAX_NUMERIC_LEN); vlen = SQL_MAX_NUMERIC_LEN; len = 0; do { UInt2 d, r; /* * Divide the number by 10, and output the reminder as the next digit. * * Begin from the most-significant byte (last in the array), and at * each step, carry the remainder to the prev byte. */ r = 0; lastnonzero = -1; for (i = vlen - 1; i >= 0; i--) { UInt2 v; v = ((UInt2) vals[i]) + (r << 8); d = v / 10; r = v % 10; vals[i] = (UCHAR) d; if (d != 0 && lastnonzero == -1) lastnonzero = i; } /* output the remainder */ calv[len++] = (UCHAR) r; vlen = lastnonzero + 1; } while(lastnonzero >= 0 && len < precision); /* * calv now contains the digits in reverse order, i.e. least significant * digit is at calv[0] */ MYPRINTF(DETAIL_LOG_LEVEL, " len2=%d", len); /* build the final output string. */ newlen = 0; if (0 == ns->sign) chrform[newlen++] = '-'; i = len - 1; if (i < ns->scale) i = ns->scale; for (; i >= ns->scale; i--) { if (i >= len) chrform[newlen++] = '0'; else chrform[newlen++] = calv[i] + '0'; } if (ns->scale > 0) { chrform[newlen++] = '.'; for (; i >= 0; i--) { if (i >= len) chrform[newlen++] = '0'; else chrform[newlen++] = calv[i] + '0'; } } if (0 == len) chrform[newlen++] = '0'; chrform[newlen] = '\0'; MYLOG(DETAIL_LOG_LEVEL, " convval(2) len=%d %s\n", newlen, chrform); } /* * Convert a string representation of a numeric into SQL_NUMERIC_STRUCT. */ static void parse_to_numeric_struct(const char *wv, SQL_NUMERIC_STRUCT *ns, BOOL *overflow) { int i, nlen, dig; char calv[SQL_MAX_NUMERIC_LEN * 3]; BOOL dot_exist; *overflow = FALSE; /* skip leading space */ while (*wv && isspace((unsigned char) *wv)) wv++; /* sign */ ns->sign = 1; if (*wv == '-') { ns->sign = 0; wv++; } else if (*wv == '+') wv++; /* skip leading zeros */ while (*wv == '0') wv++; /* read the digits into calv */ ns->precision = 0; ns->scale = 0; for (nlen = 0, dot_exist = FALSE;; wv++) { if (*wv == '.') { if (dot_exist) break; dot_exist = TRUE; } else if (*wv == '\0' || !isdigit((unsigned char) *wv)) break; else { if (nlen >= sizeof(calv)) { if (dot_exist) break; else { ns->scale--; *overflow = TRUE; continue; } } if (dot_exist) ns->scale++; calv[nlen++] = *wv; } } ns->precision = nlen; /* Convert the decimal digits to binary */ memset(ns->val, 0, sizeof(ns->val)); for (dig = 0; dig < nlen; dig++) { UInt4 carry; /* multiply the current value by 10, and add the next digit */ carry = calv[dig] - '0'; for (i = 0; i < sizeof(ns->val); i++) { UInt4 t; t = ((UInt4) ns->val[i]) * 10 + carry; ns->val[i] = (unsigned char) (t & 0xFF); carry = (t >> 8); } if (carry != 0) *overflow = TRUE; } } static BOOL parameter_is_with_cast(const QueryParse *qp) { const char *str = F_OldPtr(qp); if ('?' != *str) return FALSE; while (isspace(*(++str))) ; if (strncmp(str, "::", 2) == 0) return TRUE; if (strnicmp(str, "as", 2) != 0) return FALSE; if (isspace(str[2])) return TRUE; return FALSE; } #ifdef UNICODE_SUPPORT enum { ErrorOutConversionErrors /* error out conversion errors */ , ReturnZeroLengthString /* simply returns zero length strings */ }; static int convert_err_flag = #ifdef WIN32 ReturnZeroLengthString; #else ErrorOutConversionErrors; #endif /* WIN32 */ static BOOL handle_lu_onvert_error(QueryBuild *qb, int flag, char *buffer, SQLLEN paralen) { int blen = paralen; if (!buffer) return FALSE; if (get_mylog() > 0 || ReturnZeroLengthString != flag) { const UCHAR *buf = (UCHAR *) buffer; int i; PQExpBufferData pbuf = {0}; if (SQL_NTS == blen) blen = strlen(buffer); initPQExpBuffer(&pbuf); appendPQExpBuffer(&pbuf, "Could not convert the current data '"); for (i = 0; i < blen; i++) { if (buf[i] >= 0x80) appendPQExpBuffer(&pbuf, "\\%03o", buf[i]); else if ('\\' == buf[i]) appendPQExpBuffer(&pbuf, "\\\\"); else appendPQExpBuffer(&pbuf, "%c", buf[i]); } appendPQExpBuffer(&pbuf, "' to wide chars"); MYLOG(0, "%s\n", pbuf.data); if (ReturnZeroLengthString != flag) { if (qb->stmt) SC_set_error(qb->stmt, STMT_EXEC_ERROR, pbuf.data, __FUNCTION__); else qb->errormsg = "could not convert the current data to wide chars"; } termPQExpBuffer(&pbuf); } switch (flag) { case ReturnZeroLengthString: if (qb->stmt) SC_set_error(qb->stmt, STMT_ERROR_IN_ROW, "conversion error to wide chars occured", __FUNCTION__); return TRUE; default: qb->errornumber = STMT_EXEC_ERROR; return FALSE; } } #endif /* UNICODE_SUPPORT */ /* * Resolve one parameter. * * *isnull is set to TRUE if it was NULL. * *isbinary is set to TRUE, if the binary output format was used. (binary * output is only produced if the FLGB_BINARY_AS_POSSIBLE flag is set) * *pgType is set to the PostgreSQL type OID that should be used when binding * (or 0, to let the server decide) */ static int ResolveOneParam(QueryBuild *qb, QueryParse *qp, BOOL *isnull, BOOL *isbinary, OID *pgType) { ConnectionClass *conn = qb->conn; const APDFields *apdopts = qb->apdopts; const IPDFields *ipdopts = qb->ipdopts; PutDataInfo *pdata = qb->pdata; int param_number; char param_string[150], tmp[256]; char 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; struct tm *tim; SQLLEN used; const char *send_buf; char *buffer, *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; BOOL handling_large_object = FALSE, req_bind; BOOL need_quotes = TRUE; BOOL add_parens = FALSE; BOOL negative; ParameterInfoClass *apara; ParameterImplClass *ipara; BOOL outputDiscard, valueOutput; SDOUBLE dbv; SFLOAT flv; SQL_INTERVAL_STRUCT *ivstruct; const char *ivsign; BOOL final_binary_convert = FALSE; RETCODE retval = SQL_ERROR; *isnull = FALSE; *isbinary = FALSE; *pgType = 0; outputDiscard = (0 != (qb->flags & FLGB_DISCARD_OUTPUT)); valueOutput = (qb->param_mode != RPM_FAKE_PARAMS && qb->param_mode != RPM_BUILDING_PREPARE_STATEMENT); req_bind = (qb->param_mode == RPM_BUILDING_BIND_REQUEST); if (qb->proc_return < 0 && qb->stmt) qb->proc_return = qb->stmt->proc_return; /* * It's a '?' parameter alright */ param_number = ++qb->param_number; MYLOG(DETAIL_LOG_LEVEL, "para:%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(0, "The # of (A|I)PD parameters (%d, %d) < %d the # of parameter markers\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; } MYLOG(DETAIL_LOG_LEVEL, "ipara=%p paramName=%s paramType=%d %d proc_return=%d\n", ipara, ipara ? PRINT_NAME(ipara->paramName) : PRINT_NULL, 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) { ssize_t npos = 0; 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; } } else { /* For procedures, use named notation if a parameter name is specified */ if (!req_bind && ipara && NAME_IS_VALID(ipara->paramName) && qp && qp->statement_type == STMT_TYPE_PROCCALL) { char named_notation[COLUMN_NAME_STORAGE_LEN + 7]; SPRINTF_FIXED(named_notation, "\"%s\" := ", GET_NAME(ipara->paramName)); CVT_APPEND_STR(qb, named_notation); } } if ((!apara || !ipara) && qb->param_mode == RPM_FAKE_PARAMS) { CVT_APPEND_STR(qb, "NULL"); qb->flags |= FLGB_INACCURATE_RESULT; return SQL_SUCCESS; } if (qb->param_mode == RPM_BUILDING_PREPARE_STATEMENT) { char pnum[16]; qb->dollar_number++; if (ipara && SQL_PARAM_OUTPUT != ipara->paramType && (qb->flags & FLGB_PARAM_CAST) != 0 && !parameter_is_with_cast(qp)) SPRINTF_FIXED(pnum, "$%d%s", qb->dollar_number, sqltype_to_pgcast(conn, ipara->SQLType)); else SPRINTF_FIXED(pnum, "$%d", qb->dollar_number); CVT_APPEND_STR(qb, pnum); return SQL_SUCCESS; } /* * After this point, we can assume apara and ipara to be set. The only * cases where we allow them to be NULL is when param_mode is * RPM_FAKE_PARAMS or RPM_BUILDING_PREPARE_STATEMENT, and we've now handled * those cases. */ /* 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; 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; } /* Handle DEFAULT_PARAM parameter data. Should be NULL ? if (used == SQL_DEFAULT_PARAM) { return SQL_SUCCESS; } */ param_ctype = apara->CType; param_sqltype = ipara->SQLType; param_pgtype = PIC_dsp_pgtype(qb->conn, *ipara); /* XXX: should we use param_pgtype here instead? */ *pgType = sqltype_to_bind_pgtype(conn, param_sqltype); if (0 == param_sqltype) /* calling SQLSetStmtAttr(.., SQL_ATTR_APP_PARAM_DES, an ARD of another statement) may cause this */ { if (0 != param_pgtype) { param_sqltype = pgtype_attr_to_concise_type(conn, param_pgtype, PG_ATP_UNSET, PG_ADT_UNSET, PG_UNKNOWNS_UNSET); MYLOG(0, "convert from pgtype(%u) to sqltype(%d)\n", param_pgtype, param_sqltype); } } MYLOG(0, "from(fcType)=%d, to(fSqlType)=%d(%u), *pgType=%u\n", param_ctype, param_sqltype, param_pgtype, *pgType); /* Handle NULL parameter data */ if (SQL_PARAM_OUTPUT == ipara->paramType || used == SQL_NULL_DATA || used == SQL_DEFAULT_PARAM) { *isnull = TRUE; if (!req_bind) 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 (qb->param_mode == RPM_FAKE_PARAMS) { CVT_APPEND_STR(qb, "NULL"); qb->flags |= FLGB_INACCURATE_RESULT; return SQL_SUCCESS; } else if (!handling_large_object) { /* shouldn't happen */ qb->errormsg = "unexpected NULL parameter value"; qb->errornumber = STMT_EXEC_ERROR; return SQL_ERROR; } } /* replace DEFAULT with something we can use */ if (param_ctype == SQL_C_DEFAULT) { param_ctype = sqltype_to_default_ctype(conn, param_sqltype); #ifdef UNICODE_SUPPORT if (param_ctype == SQL_C_WCHAR && CC_default_is_c(conn)) param_ctype =SQL_C_CHAR; #endif } allocbuf = NULL; send_buf = NULL; param_string[0] = '\0'; cbuf[0] = '\0'; memset(&st, 0, sizeof(st)); ivstruct = (SQL_INTERVAL_STRUCT *) buffer; /* Convert input C type to a neutral format */ #ifdef UNICODE_SUPPORT if (get_convtype() > 0) /* coversion between the current locale is available */ { BOOL wcs_debug = conn->connInfo.wcs_debug; BOOL is_utf8 = (UTF8 == conn->ccsc); BOOL same_encoding = (conn->ccsc == pg_CS_code(conn->locale_encoding)); switch (param_ctype) { case SQL_C_CHAR: if (!same_encoding || wcs_debug) { SQLLEN paralen = used; MYLOG(0, "locale param convert\n"); if ((used = bindpara_msg_to_utf8(buffer, &allocbuf, used)) < 0) { if (!handle_lu_onvert_error(qb, convert_err_flag, buffer, paralen)) goto cleanup; send_buf = NULL_STRING; used = 0; } else send_buf = allocbuf; } break; case SQL_C_WCHAR: if (!is_utf8 || (same_encoding && wcs_debug)) { MYLOG(0, "hybrid param convert\n"); if ((used = bindpara_wchar_to_msg((SQLWCHAR *) buffer, &allocbuf, used)) < 0) { qb->errormsg = "Could not convert from wide characters to the current locale"; qb->errornumber = STMT_EXEC_ERROR; goto cleanup; } send_buf = allocbuf; } break; } } #endif /* UNICODE_SUPPORT */ switch (param_ctype) { case SQL_C_BINARY: send_buf = buffer; break; case SQL_C_CHAR: if (NULL == send_buf) send_buf = buffer; break; #ifdef UNICODE_SUPPORT case SQL_C_WCHAR: MYLOG(0, " C_WCHAR=%d contents=%s(" FORMAT_LEN ")\n", param_ctype, buffer, used); if (NULL == send_buf) { allocbuf = ucs2_to_utf8((SQLWCHAR *) buffer, used > 0 ? used / WCLEN : used, &used, FALSE); send_buf = allocbuf; } break; #endif /* UNICODE_SUPPORT */ case SQL_C_DOUBLE: dbv = *((SDOUBLE *) buffer); #ifdef WIN32 if (_finite(dbv)) #endif /* WIN32 */ { SPRINTF_FIXED(param_string, "%.*g", PG_DOUBLE_DIGITS, dbv); set_server_decimal_point(param_string, SQL_NTS); } #ifdef WIN32 else if (_isnan(dbv)) STRCPY_FIXED(param_string, NAN_STRING); else if (dbv < .0) STRCPY_FIXED(param_string, MINFINITY_STRING); else STRCPY_FIXED(param_string, INFINITY_STRING); #endif /* WIN32 */ break; case SQL_C_FLOAT: flv = *((SFLOAT *) buffer); #ifdef WIN32 if (_finite(flv)) #endif /* WIN32 */ { SPRINTF_FIXED(param_string, "%.*g", PG_REAL_DIGITS, flv); set_server_decimal_point(param_string, SQL_NTS); } #ifdef WIN32 else if (_isnan(flv)) STRCPY_FIXED(param_string, NAN_STRING); else if (flv < .0) STRCPY_FIXED(param_string, MINFINITY_STRING); else STRCPY_FIXED(param_string, INFINITY_STRING); #endif /* WIN32 */ break; case SQL_C_SLONG: case SQL_C_LONG: SPRINTF_FIXED(param_string, FORMAT_INTEGER, *((SQLINTEGER *) buffer)); break; #ifdef ODBCINT64 case SQL_C_SBIGINT: case SQL_BIGINT: /* Is this needed ? */ SPRINTF_FIXED(param_string, FORMATI64, *((SQLBIGINT *) buffer)); break; case SQL_C_UBIGINT: SPRINTF_FIXED(param_string, FORMATI64U, *((SQLUBIGINT *) buffer)); break; #endif /* ODBCINT64 */ case SQL_C_SSHORT: case SQL_C_SHORT: ITOA_FIXED(param_string, *((SQLSMALLINT *) buffer)); break; case SQL_C_STINYINT: case SQL_C_TINYINT: ITOA_FIXED(param_string, *((SCHAR *) buffer)); break; case SQL_C_ULONG: SPRINTF_FIXED(param_string, FORMAT_UINTEGER, *((SQLUINTEGER *) buffer)); break; case SQL_C_USHORT: SPRINTF_FIXED(param_string, "%u", *((SQLUSMALLINT *) buffer)); break; case SQL_C_UTINYINT: SPRINTF_FIXED(param_string, "%u", *((UCHAR *) buffer)); break; case SQL_C_BIT: { int i = *((UCHAR *) buffer); ITOA_FIXED(param_string, i ? 1 : 0); break; } case SQL_C_DATE: case SQL_C_TYPE_DATE: /* 91 */ { DATE_STRUCT *ds = (DATE_STRUCT *) buffer; st.m = ds->month; st.d = ds->day; st.y = ds->year; break; } case SQL_C_TIME: case SQL_C_TYPE_TIME: /* 92 */ { TIME_STRUCT *ts = (TIME_STRUCT *) buffer; st.hh = ts->hour; st.mm = ts->minute; st.ss = ts->second; /* * Initialize date in case conversion destination * expects date part from this source time data. */ tim = SC_get_localtime(qb->stmt); st.m = tim->tm_mon + 1; st.d = tim->tm_mday; st.y = tim->tm_year + 1900; break; } case SQL_C_TIMESTAMP: case SQL_C_TYPE_TIMESTAMP: /* 93 */ { 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(0, "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; } case SQL_C_NUMERIC: { ResolveNumericParam((SQL_NUMERIC_STRUCT *) buffer, param_string); break; } case SQL_C_INTERVAL_YEAR: ivsign = ivstruct->interval_sign ? "-" : ""; SPRINTF_FIXED(param_string, "%s%u years", ivsign, (unsigned int) ivstruct->intval.year_month.year); break; case SQL_C_INTERVAL_MONTH: case SQL_C_INTERVAL_YEAR_TO_MONTH: ivsign = ivstruct->interval_sign ? "-" : ""; SPRINTF_FIXED(param_string, "%s%u years %s%u mons", ivsign, (unsigned int) ivstruct->intval.year_month.year, ivsign, (unsigned int) ivstruct->intval.year_month.month); break; case SQL_C_INTERVAL_DAY: ivsign = ivstruct->interval_sign ? "-" : ""; SPRINTF_FIXED(param_string, "%s%u days", ivsign, (unsigned int) ivstruct->intval.day_second.day); break; case SQL_C_INTERVAL_HOUR: case SQL_C_INTERVAL_DAY_TO_HOUR: ivsign = ivstruct->interval_sign ? "-" : ""; SPRINTF_FIXED(param_string, "%s%u days %s%02u:00:00", ivsign, (unsigned int) ivstruct->intval.day_second.day, ivsign, (unsigned int) 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_FIXED(param_string, "%s%u days %s%02u:%02u:00", ivsign, (unsigned int) ivstruct->intval.day_second.day, ivsign, (unsigned int) ivstruct->intval.day_second.hour, (unsigned int) 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_FIXED(param_string, "%s%u days %s%02u:%02u:%02u", ivsign, (unsigned int) ivstruct->intval.day_second.day, ivsign, (unsigned int) ivstruct->intval.day_second.hour, (unsigned int) ivstruct->intval.day_second.minute, (unsigned int) 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--; } SPRINTFCAT_FIXED(param_string, ".%0*d", prec, fraction); } break; case SQL_C_GUID: { /* * SQLGUID.Data1 is an "unsigned long" on some platforms, and * "unsigned int" on others. */ SQLGUID *g = (SQLGUID *) buffer; SPRINTF_FIXED (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; 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 */ 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(0, "cvt_null_date_string=%d pgtype=%d send_buf=%p\n", conn->connInfo.cvt_null_date_string, param_pgtype, send_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 != send_buf && ( (SQL_C_CHAR == param_ctype && '\0' == send_buf[0]) #ifdef UNICODE_SUPPORT || (SQL_C_WCHAR ==param_ctype && '\0' == send_buf[0] && '\0' == send_buf[1]) #endif /* UNICODE_SUPPORT */ )) { *isnull = TRUE; if (!req_bind) CVT_APPEND_STR(qb, "NULL"); retval = SQL_SUCCESS; goto cleanup; } /* * We now have the value we want to print in one of these three canonical * formats: * * 1. As a string in 'send_buf', with length indicated by 'used' (can be * SQL_NTS). * 2. As a null-terminated string in 'param_string'. * 3. Time-related fields in 'st'. */ /* * For simplicity, fold the param_string representation into 'send_buf'. */ if (!send_buf && param_string[0]) { send_buf = param_string; used = SQL_NTS; } /* * Do some further processing to create the final string we want to output. * This will use the fields in 'st' to create a string if it's a time/date * value, and do some other conversions. */ 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 */ case SQL_BIT: /* Special handling for some column types */ switch (param_pgtype) { case PG_TYPE_BOOL: /* * consider True is -1 case. * * FIXME: This actually matches anything that begins * with -1, like "-1234" or "-1foobar". Is that * intentional? */ if (NULL != send_buf && '-' == send_buf[0] && '1' == send_buf[1]) { send_buf = "1"; used = 1; } break; case PG_TYPE_FLOAT4: case PG_TYPE_FLOAT8: case PG_TYPE_NUMERIC: if (NULL != send_buf) set_server_decimal_point((char *) send_buf, used); break; } if (!send_buf) { /* it was date,time,timestamp -- use m,d,y,hh,mm,ss */ SPRINTF_FIXED(tmp, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d", st.y, st.m, st.d, st.hh, st.mm, st.ss); send_buf = tmp; used = SQL_NTS; } break; case SQL_DATE: case SQL_TYPE_DATE: /* 91 */ if (send_buf) { /* copy char data to time */ my_strcpy(cbuf, sizeof(cbuf), send_buf, used); parse_datetime(cbuf, &st); } if (st.y < 0) SPRINTF_FIXED(tmp, "%.4d-%.2d-%.2d BC", -st.y, st.m, st.d); else SPRINTF_FIXED(tmp, "%.4d-%.2d-%.2d", st.y, st.m, st.d); lastadd = "::date"; send_buf = tmp; used = SQL_NTS; break; case SQL_TIME: case SQL_TYPE_TIME: /* 92 */ if (send_buf) { /* copy char data to time */ my_strcpy(cbuf, sizeof(cbuf), send_buf, used); parse_datetime(cbuf, &st); } if (st.fr > 0) { int wdt; int fr = effective_fraction(st.fr, &wdt); SPRINTF_FIXED(tmp, "%.2d:%.2d:%.2d.%0*d", st.hh, st.mm, st.ss, wdt, fr); } else SPRINTF_FIXED(tmp, "%.2d:%.2d:%.2d", st.hh, st.mm, st.ss); lastadd = "::time"; send_buf = tmp; used = SQL_NTS; break; case SQL_TIMESTAMP: case SQL_TYPE_TIMESTAMP: /* 93 */ if (send_buf) { my_strcpy(cbuf, sizeof(cbuf), send_buf, used); parse_datetime(cbuf, &st); } /* * SPRINTF_FIXED(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, sizeof(tmp), USE_ZONE, 6); lastadd = "::timestamp"; send_buf = tmp; used = SQL_NTS; 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(send_buf); break; } allocbuf = malloc(used / 2 + 1); if (allocbuf) { pg_hex2bin(send_buf, allocbuf, used); send_buf = allocbuf; used /= 2; } break; default: qb->errormsg = "Could not convert the ctype to binary type"; qb->errornumber = STMT_EXEC_ERROR; goto cleanup; } if (param_pgtype == PG_TYPE_BYTEA) { if (0 != (qb->flags & FLGB_BINARY_AS_POSSIBLE)) { MYLOG(0, "sending binary data leng=" FORMAT_LEN "\n", used); *isbinary = TRUE; } else { /* non-ascii characters should be * converted to octal */ MYLOG(0, "SQL_VARBINARY: about to call convert_to_pgbinary, used = " FORMAT_LEN "\n", used); final_binary_convert = TRUE; } 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; 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); int write_result; /* 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; 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 = "Couldn't create (in-line) large object."; 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 = "Couldn't open (in-line) large object for writing."; goto cleanup; } write_result = odbc_lo_write(conn, lobj_fd, buffer, (Int4) used); if (write_result < 0) { qb->errornumber = STMT_EXEC_ERROR; qb->errormsg = "Couldn't write to (in-line) large object."; goto cleanup; } 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; 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_FIXED(param_string, "%u", lobj_oid); lastadd = "::lo"; send_buf = param_string; used = SQL_NTS; 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: set_server_decimal_point((char *) send_buf, used); lastadd = "::float4"; break; case SQL_FLOAT: case SQL_DOUBLE: set_server_decimal_point((char *) send_buf, used); lastadd = "::float8"; break; case SQL_NUMERIC: break; /* * If it looks like a valid integer, we can pass it without quotes * and let the server interpret it. Arguably, it would always be * better to explicitly pass it as 'xxx'::integer or 'xxx'::smallint, * but historically we haven't done that, so let's avoid changing the * behaviour. * * If it's a negative number, we have to wrap it in parens. Otherwise * a query like "SELECT 0-?" would turn into "SELECT 0--123". */ case SQL_INTEGER: if (valid_int_literal(send_buf, used, &negative)) { need_quotes = FALSE; add_parens = negative; } else { /* * Doesn't look like a valid integer. The server will most * likely throw an error, unless it's in some format we don't * recognize but the server does. */ lastadd = "::int4"; } break; case SQL_SMALLINT: if (valid_int_literal(send_buf, used, &negative)) { need_quotes = FALSE; add_parens = negative; } else lastadd = "::smallint"; break; default: /* a numeric type or SQL_BIT */ break; } if (!send_buf) { qb->errormsg = "Could not convert parameter ctype to sqltype"; qb->errornumber = STMT_EXEC_ERROR; goto cleanup; } if (used == SQL_NTS) used = strlen(send_buf); /* * Ok, we now have the final string representation in 'send_buf', length 'used'. * We're ready to output the final string, with quotes and other * embellishments if necessary. * * In bind-mode, we don't need to do any quoting. */ if (req_bind) CVT_APPEND_DATA(qb, send_buf, used); else { if (add_parens) CVT_APPEND_CHAR(qb, '('); if (need_quotes) { if ((qb->flags & FLGB_LITERAL_EXTENSION) != 0) CVT_APPEND_CHAR(qb, LITERAL_EXT); CVT_APPEND_CHAR(qb, LITERAL_QUOTE); if (final_binary_convert) CVT_APPEND_BINARY(qb, send_buf, used); else CVT_SPECIAL_CHARS(qb, send_buf, used); CVT_APPEND_CHAR(qb, LITERAL_QUOTE); } else CVT_APPEND_DATA(qb, send_buf, used); if (add_parens) CVT_APPEND_CHAR(qb, ')'); if (lastadd && (FLGB_PARAM_CAST & qb->flags) != 0) CVT_APPEND_STR(qb, lastadd); } retval = SQL_SUCCESS; cleanup: if (allocbuf) free(allocbuf); return retval; } static const char * mapFunction(const char *func, int param_count, const char *keyword) { int i; const char *p1, *p2; for (i = 0; (p1 = mapFuncs[i].odbc_name) != NULL; i++) { if (p1[0] == '%') { if (p1[1] - '0' == param_count && !stricmp(p1 + 2, func)) return mapFuncs[i].pgsql_name; } else if (!stricmp(p1, func)) return mapFuncs[i].pgsql_name; else if (p2 = strchr(p1, (int) '('), NULL != p2) { int len = (int) (p2 - mapFuncs[i].odbc_name); if (strlen(func) == len && !strnicmp(p1, func, len) && !stricmp(p2 + 1, keyword)) return mapFuncs[i].pgsql_name; } } 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]) { 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 (MBCS_NON_ASCII(qp->encstr)) continue; if (!QP_in_idle_status(qp)) 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(0, "closing ) not found %d\n", 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 (IS_NOT_SPACE(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) { 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])); } sscanf(F_OldPtr(qp), "%32s", key); while ((ucv = F_OldChar(qp)) != '\0' && (IS_NOT_SPACE(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) { size_t funclen; const UCHAR *next_token; if (SQL_ERROR == QB_start_brace(qb)) { retval = SQL_ERROR; goto cleanup; } if (qb->num_io_params > 1 || (0 == qb->proc_return)) CVT_APPEND_STR(qb, "SELECT * FROM "); else CVT_APPEND_STR(qb, "SELECT "); funclen = findIdentifier((const UCHAR *) F_OldPtr(qp), qb->ccsc, &next_token); if (next_token && ODBC_ESCAPE_END == *next_token) { 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 += ((const char *) next_token - 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)); prtlen = SPRINTF_FIXED(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 = SPRINTF_FIXED(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)); prtlen = SPRINTF_FIXED(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 = SPRINTF_FIXED(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 != '(' && (IS_NOT_SPACE(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 { char keyword[64] = ""; if (param_count > 0) { int i, from, to; const char * p; for (i = param_pos[0][0], p = nqb.query_statement + i; i <= param_pos[0][1] && isspace(*p); i++, p++) ; from = i; for (; i <= param_pos[0][1] && IS_NOT_SPACE(*p); i++, p++) ; to = i - 1; if (to >= from) { int len = to - from + 1; if (len < sizeof(keyword)) { memcpy(keyword, nqb.query_statement + from, len); keyword[len] = '\0'; } } } mapExpr = mapFunction(key, param_count, keyword); } 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; char sqltype[32]; int typel; CVT_APPEND_CHAR(qb, ')'); from = param_pos[1][0]; to = param_pos[1][1]; typel = to - from + 1; if (typel < sizeof(sqltype)) { const char *type; memcpy(sqltype, nqb.query_statement + from, typel); sqltype[typel] = '\0'; MYLOG(0, FORMAT_LEN "-" FORMAT_LEN " SQLtype=%s SQL_BIT=%d\n", to, from, sqltype, SQL_BIT); for (type = sqltype; *type && isspace(*type); type++) ; if (strncmp(type, "SQL_", 4) == 0) { type += 4; if (strcmp(type, "INTEGER") == 0) cast_form = "int4"; else if (strcmp(type, "CHAR") == 0) cast_form = "varchar"; else if (strcmp(type, "VARCHAR") == 0) cast_form = "varchar"; else if (strcmp(type, "LONGVARCHAR") == 0) cast_form = "text"; else if (strcmp(type, "WCHAR") == 0) cast_form = "varchar"; else if (strcmp(type, "WVARCHAR") == 0) cast_form = "varchar"; else if (strcmp(type, "WLONGVARCHAR") == 0) cast_form = "text"; else if (strcmp(type, "NUMERIC") == 0) cast_form = "numeric"; else if (strcmp(type, "DOUBLE") == 0) cast_form = "float8"; else if (strcmp(type, "FLOAT") == 0) cast_form = "float8"; else if (strcmp(type, "REAL") == 0) cast_form = "float4"; else if (strcmp(type, "BIGINT") == 0) cast_form = "int8"; else if (strcmp(type, "DECIMAL") == 0) cast_form = "numeric"; else if (strcmp(type, "SMALLINT") == 0) cast_form = "int2"; else if (strcmp(type, "TYPE_DATE") == 0) cast_form = "date"; else if (strcmp(type, "TYPE_TIME") == 0) cast_form = "time"; else if (strcmp(type, "TYPE_TIMESTAMP") == 0) cast_form = "timestamp"; else if (strcmp(type, "BIT") == 0) cast_form = "bit"; } } 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 (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"; MYLOG(0, "%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"; MYLOG(0, "internal expression error %s\n", 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->dollar_number = nqb.dollar_number; qb->flags = nqb.flags; } } else { /* Bogus key, leave untranslated */ retval = SQL_ERROR; } cleanup: if (nqb_is_valid) QB_Destructor(&nqb); return retval; } static BOOL convert_money(const char *s, char *sout, size_t soutmax) { char in, decp = 0; size_t i = 0, out = 0; int num_in = -1, period_in = -1, comma_in = -1; for (i = 0; s[i]; i++) { switch (in = s[i]) { case '.': if (period_in < 0) period_in = i; break; case ',': if (comma_in < 0) comma_in = i; break; default: if ('0' <= in && '9' >= in) num_in = i; break; } } if (period_in > comma_in) { if ( period_in >= num_in - 2) decp = '.'; } else if (comma_in >= 0 && comma_in >= num_in - 2) decp = ','; for (i = 0; s[i] && out + 1 < soutmax; i++) { switch (in = s[i]) { case '(': case '-': sout[out++] = '-'; break; default: if (in >= '0' && in <= '9') sout[out++] = in; else if (in == decp) sout[out++] = '.'; } } 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 */ static char parse_datetime(const char *buf, SIMPLE_TIME *st) { int y, m, d, hh, mm, ss; int nf; BOOL bZone; int zone; y = m = d = hh = mm = ss = 0; st->fr = 0; st->infinity = 0; /* * Handle ODBC time/date/timestamp literals, e.g. * { d '2011-04-22' } * { t '12:34:56' } * { ts '2011-04-22 12:34:56' } */ if (buf[0] == ODBC_ESCAPE_START) { while (*(++buf) && *buf != LITERAL_QUOTE); if (!(*buf)) return FALSE; buf++; } bZone = FALSE; if (timestamp2stime(buf, st, &bZone, &zone)) return TRUE; 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. */ static BOOL convert_special_chars(QueryBuild *qb, const char *si, size_t used) { size_t i = 0, max; char tchar; encoded_str encstr; BOOL convlf = (0 != (qb->flags & FLGB_CONVERT_LF)); BOOL double_special = (qb->param_mode != RPM_BUILDING_BIND_REQUEST); int ccsc = qb->ccsc; char escape_in_literal = CC_get_escape(qb->conn); if (used == SQL_NTS) max = strlen(si); else max = used; /* * Make sure there's room for the null-terminator, if the input is an * empty string. XXX: I don't think the null-termination is actually * even required, but better safe than sorry. */ if (!enlarge_query_statement(qb, qb->npos + 1)) return FALSE; encoded_str_constr(&encstr, ccsc, si); for (i = 0; i < max && si[i]; i++) { tchar = encoded_nextchar(&encstr); /* * Make sure there is room for three more bytes in the buffer. We * expand quotes to two bytes, plus null-terminate the end. */ if (qb->npos + 3 >= qb->str_alsize) { if (!enlarge_query_statement(qb, qb->npos + 3)) return FALSE; } if (MBCS_NON_ASCII(encstr)) { qb->query_statement[qb->npos++] = tchar; 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)) { qb->query_statement[qb->npos++] = tchar; } qb->query_statement[qb->npos++] = tchar; } qb->query_statement[qb->npos] = '\0'; return TRUE; } 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 */ static 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(0, "i=%d, rgbValue[%d] = %d, %c\n", i, o, rgbValue[o], rgbValue[o]); ***/ } if (rgbValue) rgbValue[o] = '\0'; /* extra protection */ MYLOG(0, "in=" FORMAT_SIZE_T ", out = " FORMAT_SIZE_T "\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) { UCHAR inc; size_t i, o = 0; char escape_in_literal = CC_get_escape(qb->conn); BOOL esc_double = (qb->param_mode != RPM_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]; MYLOG(DETAIL_LOG_LEVEL, "in[" FORMAT_SIZE_T "] = %d, %c\n", 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(0, "leaving " FORMAT_SIZE_T ", out='%.*s'\n", o, (int) 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. *------- */ static int convert_lo(StatementClass *stmt, const void *value, SQLSMALLINT fCType, PTR rgbValue, SQLLEN cbValueMax, SQLLEN *pcbValue) { CSTR func = "convert_lo"; OID oid; int result; Int8 retval; Int8 left64 = -1; struct GetBlobDataClass *gdata_blob = 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_blob = &(gdata_info->gdata[stmt->current_col].blob); left64 = gdata_blob->data_left64; } /* * if this is the first call for this column, open the large object * for reading */ if (!gdata_blob || gdata_blob->data_left64 == -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_lseek64(conn, stmt->lobj_fd, 0L, SEEK_END); if (retval >= 0) { left64 = odbc_lo_tell64(conn, stmt->lobj_fd); if (gdata_blob) gdata_blob->data_left64 = left64; /* return to beginning */ odbc_lo_lseek64(conn, stmt->lobj_fd, 0L, SEEK_SET); } } else if (left64 == 0) return COPY_NO_DATA_FOUND; MYLOG(0, "lo data left = " FORMATI64 "\n", left64); 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 = (Int8) 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 < left64) result = COPY_RESULT_TRUNCATED; else result = COPY_OK; if (pcbValue) { Int8 leftbytes = left64 * factor; *pcbValue = left64 < 0 ? SQL_NO_TOTAL : (leftbytes == (SQLLEN) leftbytes ? leftbytes : /* exceeds SQLLEN limit */ SQL_NO_TOTAL); } if (gdata_blob && gdata_blob->data_left64 > 0) gdata_blob->data_left64 -= retval; if (!gdata_blob || gdata_blob->data_left64 == 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-13.02.0000/drvconn.c000644 001751 001751 00000034277 14122574535 016724 0ustar00hiroshihiroshi000000 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 #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 (!outstr) return NULL; 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 BOOL dconn_get_DSN_or_Driver(const char *connect_string, ConnInfo *ci); static BOOL dconn_get_connect_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 s_hModule; /* Saved module handle. */ #endif #define PASSWORD_IS_REQUIRED 1 static int paramRequired(const ConnInfo *ci, int reqs) { int required = 0; const char *pw = SAFE_NAME(ci->password); /* Password is not necessarily a required parameter. */ if ((reqs & PASSWORD_IS_REQUIRED) != 0) if ('\0' == pw[0]) required |= PASSWORD_IS_REQUIRED; return required; } RETCODE SQL_API PGAPI_DriverConnect(HDBC hdbc, HWND hwnd, const SQLCHAR * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT * pcbConnStrOut, SQLUSMALLINT fDriverCompletion) { CSTR func = "PGAPI_DriverConnect"; ConnectionClass *conn = (ConnectionClass *) hdbc; ConnInfo *ci; #ifdef WIN32 RETCODE dialog_result; BOOL didUI = FALSE; #endif const char *lackMessage = NULL; RETCODE result; char *connStrIn = NULL; char connStrOut[MAX_CONNECT_STRING]; int retval; char salt[5]; ssize_t len = 0; SQLSMALLINT lenStrout; int reqs = 0; MYLOG(0, "entering...\n"); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } connStrIn = make_string(szConnStrIn, cbConnStrIn, NULL, 0); #ifdef FORCE_PASSWORD_DISPLAY MYLOG(0, "**** fDriverCompletion=%d, connStrIn='%s'\n", fDriverCompletion, connStrIn); #else if (get_mylog()) { char *hide_str = hide_password(connStrIn); MYLOG(0, "**** fDriverCompletion=%d, connStrIn='%s'\n", fDriverCompletion, NULL_IF_NULL(hide_str)); if (hide_str) free(hide_str); } #endif /* FORCE_PASSWORD_DISPLAY */ ci = &(conn->connInfo); /* First parse the connect string and get the name of DSN or Driver */ if (!dconn_get_DSN_or_Driver(connStrIn, ci)) { CC_set_error(conn, CONN_OPENDB_ERROR, "Connection string parse error", func); return SQL_ERROR; } /* * 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, NULL); /* Parse the connect string and fill in conninfo for this hdbc. */ if (!dconn_get_connect_attributes(connStrIn, ci)) { CC_set_error(conn, CONN_OPENDB_ERROR, "Connection string parse error", func); return SQL_ERROR; } logs_on_off(1, ci->drivers.debug, ci->drivers.commlog); if (connStrIn) { free(connStrIn); connStrIn = NULL; } /* initialize pg_version */ CC_initialize_pg_version(conn); memset(salt, 0, sizeof(salt)); #ifdef WIN32 dialog: #endif MYLOG(DETAIL_LOG_LEVEL, "DriverCompletion=%d\n", fDriverCompletion); switch (fDriverCompletion) { #ifdef WIN32 case SQL_DRIVER_PROMPT: if (NULL == hwnd) break; 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: if (NULL == hwnd) break; if (paramRequired(ci, reqs)) { 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) */ if (paramRequired(ci, reqs)) { /* if (didUI) return SQL_NO_DATA_FOUND; */ if (!lackMessage) lackMessage = "Please supply password"; CC_set_error(conn, CONN_OPENDB_ERROR, lackMessage, func); return SQL_ERROR; } reqs = 0; MYLOG(DETAIL_LOG_LEVEL, "before CC_connect\n"); /* do the actual connect */ retval = CC_connect(conn, 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 if (ci->password_required) reqs |= PASSWORD_IS_REQUIRED; if (hwnd && paramRequired(ci, reqs)) goto dialog; #endif /* WIN32 */ /* Prompting for missing options is only supported on Windows. */ return SQL_ERROR; } } 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(0, "szConnStrOut = '%s' len=" FORMAT_SSIZE_T ",%d\n", NULL_IF_NULL((char *) szConnStrOut), len, cbConnStrOutMax); } #else if (get_mylog()) { char *hide_str = NULL; if (cbConnStrOutMax > 0) hide_str = hide_password(szConnStrOut); MYLOG(0, "szConnStrOut = '%s' len=%d,%d\n", NULL_IF_NULL(hide_str), len, cbConnStrOutMax); if (hide_str) free(hide_str); } #endif /* FORCE_PASSWORD_DISPLAY */ MYLOG(0, "leaving %d\n", result); return result; } #ifdef WIN32 RETCODE dconn_DoDialog(HWND hwnd, ConnInfo *ci) { LRESULT dialog_result; MYLOG(0, "entering ci = %p\n", ci); if (hwnd) { dialog_result = DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_CONFIG), hwnd, dconn_FDriverConnectProc, (LPARAM) ci); if (-1 == dialog_result) { int errc = GetLastError(); MYLOG(0, " LastError=%d\n", errc); } if (!dialog_result || (dialog_result == -1)) return SQL_NO_DATA_FOUND; else return SQL_SUCCESS; } MYLOG(0, " No window specified\n"); 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); ShowWindow(GetDlgItem(hdlg, IDC_MANAGEDSN), SW_HIDE); // ShowWindow(GetDlgItem(hdlg, IDC_DATASOURCE), 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->password_required) { HWND notu = GetDlgItem(hdlg, IDC_NOTICE_USER); SetWindowText(notu, " Supply password "); ShowWindow(notu, SW_SHOW); SendMessage(notu, WM_CTLCOLOR, 0, 0); } if (ci->database[0] == '\0') SetFocus(GetDlgItem(hdlg, IDC_DATABASE)); 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 (SAFE_NAME(ci->password)[0] == '\0' && ci->password_required) 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; } break; case WM_CTLCOLORSTATIC: if (lParam == (LPARAM)GetDlgItem(hdlg, IDC_NOTICE_USER)) { HBRUSH hBrush = (HBRUSH)GetStockObject(WHITE_BRUSH); SetTextColor((HDC)wParam, RGB(255, 0, 0)); return (LRESULT)hBrush; } 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 BOOL dconn_get_attributes(copyfunc func, const char *connect_string, ConnInfo *ci) { BOOL ret = TRUE; char *our_connect_string; const char *pair, *attribute, *value, *termp; BOOL eoftok; char *equals, *delp; char *strtok_arg; #ifdef HAVE_STRTOK_R char *last = NULL; #endif /* HAVE_STRTOK_R */ if (our_connect_string = strdup(connect_string), NULL == our_connect_string) return FALSE; strtok_arg = our_connect_string; #ifdef FORCE_PASSWORD_DISPLAY MYLOG(0, "our_connect_string = '%s'\n", our_connect_string); #else if (get_mylog()) { char *hide_str = hide_password(our_connect_string); MYLOG(0, "our_connect_string = '%s'\n", hide_str); free(hide_str); } #endif /* FORCE_PASSWORD_DISPLAY */ termp = strchr(our_connect_string, '\0'); eoftok = FALSE; while (!eoftok) { if (strtok_arg != NULL && strtok_arg >= termp) /* for safety */ break; #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(;). */ switch (*value) { const char *valuen, *closep; case OPENING_BRACKET: delp = strchr(value, '\0'); if (delp >= termp) { eoftok = TRUE; break; } /* Where's a corresponding closing bracket? */ closep = strchr(value, CLOSING_BRACKET); if (NULL != closep && closep[1] == '\0') break; for (valuen = value; valuen < termp; closep = strchr(valuen, CLOSING_BRACKET)) { if (NULL == closep) { if (!delp) /* error */ { MYLOG(0, "closing bracket doesn't exist 1\n"); ret = FALSE; goto cleanup; } closep = strchr(delp + 1, CLOSING_BRACKET); if (!closep) /* error */ { MYLOG(0, "closing bracket doesn't exist 2\n"); ret = FALSE; goto cleanup; } *delp = ATTRIBUTE_DELIMITER; /* restore delimiter */ delp = NULL; } if (CLOSING_BRACKET == closep[1]) { valuen = closep + 2; if (valuen >= termp) break; else if (valuen == delp) { *delp = ATTRIBUTE_DELIMITER; delp = NULL; } continue; } else if (ATTRIBUTE_DELIMITER == closep[1] || '\0' == closep[1] || delp == closep + 1) { delp = (char *) (closep + 1); *delp = '\0'; strtok_arg = delp + 1; if (strtok_arg + 1 >= termp) eoftok = TRUE; break; } MYLOG(0, "subsequent char to the closing bracket is %c value=%s\n", closep[1], value); ret = FALSE; goto cleanup; } } /* Copy the appropriate value to the conninfo */ (*func)(ci, attribute, value); } cleanup: free(our_connect_string); return ret; } static BOOL dconn_get_DSN_or_Driver(const char *connect_string, ConnInfo *ci) { CC_conninfo_init(ci, INIT_GLOBALS); return dconn_get_attributes(get_DSN_or_Driver, connect_string, ci); } static BOOL dconn_get_connect_attributes(const char *connect_string, ConnInfo *ci) { return dconn_get_attributes(copyConnAttributes, connect_string, ci); } psqlodbc-13.02.0000/environ.c000644 001751 001751 00000035164 14122574536 016730 0ustar00hiroshihiroshi000000 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" /* 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 * phenv) { CSTR func = "PGAPI_AllocEnv"; SQLRETURN ret = SQL_SUCCESS; MYLOG(0, "entering\n"); /* * For systems on which none of the constructor-making * techniques in psqlodbc.c work: * It's ok to call initialize_global_cs() twice. */ { initialize_global_cs(); } *phenv = (HENV) EN_Constructor(); if (!*phenv) { *phenv = SQL_NULL_HENV; EN_log_error(func, "Error allocating environment", NULL); ret = SQL_ERROR; } MYLOG(0, "leaving phenv=%p\n", *phenv); return ret; } RETCODE SQL_API PGAPI_FreeEnv(HENV henv) { CSTR func = "PGAPI_FreeEnv"; SQLRETURN ret = SQL_SUCCESS; EnvironmentClass *env = (EnvironmentClass *) henv; MYLOG(0, "entering env=%p\n", env); if (env && EN_Destructor(env)) { MYLOG(0, " ok\n"); goto cleanup; } ret = SQL_ERROR; EN_log_error(func, "Error freeing environment", NULL); cleanup: return ret; } #define SIZEOF_SQLSTATE 6 static void pg_sqlstate_set(const EnvironmentClass *env, UCHAR *szSqlState, const char *ver3str, const char *ver2str) { strncpy_null((char *) szSqlState, EN_is_odbc3(env) ? ver3str : ver2str, SIZEOF_SQLSTATE); } 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 - sizeof(error->__error_message) + 1; if (aladd < 0) aladd = 0; } 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 = (Int2) errsize; if (errsize > 0) memcpy(error->__error_message, msg, errsize); error->__error_message[errsize] = '\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); if (new) 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 * szSqlState, SQLINTEGER * pfNativeError, SQLCHAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT * pcbErrorMsg, UWORD flag) { /* CC: return an error of a hstmt */ PG_ErrorInfo *error; BOOL partial_ok = ((flag & PODBC_ALLOW_PARTIAL_EXTRACT) != 0); const char *msg; SWORD msglen, stapos, wrtlen, pcblen; if (!pgerror) return SQL_NO_DATA_FOUND; error = pgerror; msg = error->__error_message; MYLOG(0, "entering status = %d, msg = #%s#\n", 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; } else if (1 == RecNumber && cbErrorMsgMax > 0) error->recsize = cbErrorMsgMax - 1; 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 = cbErrorMsgMax - 1; 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(0, " szSqlState = '%s',len=%d, szError='%s'\n", szSqlState, pcblen, szErrorMsg); if (wrtlen < pcblen) return SQL_SUCCESS_WITH_INFO; else return SQL_SUCCESS; } RETCODE SQL_API PGAPI_ConnectError(HDBC hdbc, SQLSMALLINT RecNumber, SQLCHAR * szSqlState, SQLINTEGER * pfNativeError, SQLCHAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT * pcbErrorMsg, UWORD flag) { ConnectionClass *conn = (ConnectionClass *) hdbc; EnvironmentClass *env = (EnvironmentClass *) conn->henv; char *msg; int status; BOOL once_again = FALSE; ssize_t msglen; MYLOG(0, "entering 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(0, "CC_Get_error returned nothing.\n"); if (NULL != szSqlState) strncpy_null((char *) szSqlState, "00000", SIZEOF_SQLSTATE); if (NULL != pcbErrorMsg) *pcbErrorMsg = 0; if ((NULL != szErrorMsg) && (cbErrorMsgMax > 0)) szErrorMsg[0] = '\0'; return SQL_NO_DATA_FOUND; } MYLOG(0, "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]) strncpy_null((char *) szSqlState, conn->sqlstate, SIZEOF_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, "HY011", "S1011"); 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_ILLEGAL_TRANSACT_STATE: pg_sqlstate_set(env, szSqlState, "25000", "S1010"); 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(0, " szSqlState = '%s',len=" FORMAT_SSIZE_T ", 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 * szSqlState, SQLINTEGER * pfNativeError, SQLCHAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT * pcbErrorMsg, UWORD flag) { EnvironmentClass *env = (EnvironmentClass *) henv; char *msg = NULL; int status; MYLOG(0, "entering 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(0, "EN_get_error: msg = #%s#\n", 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(0, "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; } /* * 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(0, " WSAStartup error\n"); 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(0, " WSAStartup version=(%d,%d)\n", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion)); goto cleanup; } #endif /* WIN32 */ rv = (EnvironmentClass *) malloc(sizeof(EnvironmentClass)); if (NULL == rv) { MYLOG(0, " malloc error\n"); 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(0, "entering 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(0, "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(0, "leaving 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(0, "entering 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(0, " 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(0, " 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) MYLOG(0, "ENVIRON ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->errornumber, self->errormsg); else MYLOG(0, "INVALID ENVIRON HANDLE ERROR: func=%s, desc='%s'\n", func, desc); } psqlodbc-13.02.0000/execute.c000644 001751 001751 00000131075 14122574536 016710 0ustar00hiroshihiroshi000000 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" /* Perform a Prepare on the SQL statement */ RETCODE SQL_API PGAPI_Prepare(HSTMT hstmt, const SQLCHAR * szSqlStr, SQLINTEGER cbSqlStr) { CSTR func = "PGAPI_Prepare"; StatementClass *self = (StatementClass *) hstmt; RETCODE retval = SQL_SUCCESS; BOOL prepared; MYLOG(0, "entering...\n"); #define return DONT_CALL_RETURN_FROM_HERE??? /* StartRollbackState(self); */ /* * 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_DESCRIBED: MYLOG(0, "**** STMT_DESCRIBED, recycle\n"); SC_recycle_statement(self); /* recycle the statement, but do * not remove parameter bindings */ break; case STMT_FINISHED: MYLOG(0, "**** STMT_FINISHED, recycle\n"); SC_recycle_statement(self); /* recycle the statement, but do * not remove parameter bindings */ break; case STMT_ALLOCATED: MYLOG(0, "**** STMT_ALLOCATED, copy\n"); self->status = STMT_READY; break; case STMT_READY: MYLOG(0, "**** STMT_READY, change SQL\n"); if (NOT_YET_PREPARED != prepared) SC_recycle_statement(self); /* recycle the statement */ break; case STMT_EXECUTING: MYLOG(0, "**** 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 MYLOG(DETAIL_LOG_LEVEL, "leaving %d\n", retval); return retval; } /* Performs the equivalent of SQLPrepare, followed by SQLExecute. */ RETCODE SQL_API PGAPI_ExecDirect(HSTMT hstmt, const SQLCHAR * szSqlStr, SQLINTEGER cbSqlStr, UWORD flag) { StatementClass *stmt = (StatementClass *) hstmt; RETCODE result; CSTR func = "PGAPI_ExecDirect"; const ConnectionClass *conn = SC_get_conn(stmt); MYLOG(0, "entering...%x\n", 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); MYLOG(DETAIL_LOG_LEVEL, "a2\n"); if (!stmt->statement) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "No memory available to store statement", func); return SQL_ERROR; } MYLOG(0, "**** hstmt=%p, statement='%s'\n", hstmt, stmt->statement); if (0 != (flag & PODBC_WITH_HOLD)) SC_set_with_hold(stmt); if (0 != (flag & PODBC_RDONLY)) SC_set_readonly(stmt); /* * If an SQLPrepare was performed prior to this, but was left in the * described state because an error occurred prior to SQLExecute then * set the statement to finished so it can be recycled. */ if (stmt->status == STMT_DESCRIBED) 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(0, "calling PGAPI_Execute...\n"); result = PGAPI_Execute(hstmt, flag); MYLOG(0, "leaving %hd\n", 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 (!stmt->use_server_side_prepare) { /* 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) { /* * divide the query into multiple commands and apply V3 parse * requests for each of them */ ret = PARSE_REQ_FOR_INFO; } else { 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; } } 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; 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 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 (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; } static const char *GetSvpName(const ConnectionClass *conn, char *wrk, int wrksize) { snprintf(wrk, wrksize, "_EXEC_SVP_%p", conn); return wrk; } /* * The execution after all parameters were resolved. */ #define INVALID_EXPBUFFER PQExpBufferDataBroken(stmt->stmt_deffered) #define VALID_EXPBUFFER (!PQExpBufferDataBroken(stmt->stmt_deffered)) static void param_status_batch_update(IPDFields *ipdopts, RETCODE retval, SQLLEN target_row, int count_of_deffered) { int i, j; if (NULL != ipdopts->param_status_ptr) { for (i = target_row, j = 0; i >= 0 && j <= count_of_deffered; i--) { if (SQL_PARAM_UNUSED != ipdopts->param_status_ptr[i]) { ipdopts->param_status_ptr[i] = retval; j++; } } } } static RETCODE Exec_with_parameters_resolved(StatementClass *stmt, EXEC_TYPE exec_type, BOOL *exec_end) { CSTR func = "Exec_with_parameters_resolved"; RETCODE retval; SQLLEN start_row, end_row; SQLINTEGER cursor_type, scroll_concurrency; ConnectionClass *conn; QResultClass *res; APDFields *apdopts; IPDFields *ipdopts; BOOL prepare_before_exec = FALSE; char *stmt_with_params; SQLLEN status_row = stmt->exec_current_row; int count_of_deffered; *exec_end = FALSE; conn = SC_get_conn(stmt); MYLOG(0, "copying statement params: trans_status=%d, len=" FORMAT_SIZE_T ", stmt='%s'\n", 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 (HowToPrepareBeforeExec(stmt, FALSE) >= allowParse) prepare_before_exec = TRUE; MYLOG(DETAIL_LOG_LEVEL, "prepare_before_exec=%d srv=%d\n", prepare_before_exec, stmt->use_server_side_prepare); /* Create the statement with parameters substituted. */ stmt_with_params = stmt->stmt_with_params; if (LAST_EXEC == exec_type) { if (NULL != stmt_with_params) { free(stmt_with_params); stmt_with_params = stmt->stmt_with_params = NULL; } if (INVALID_EXPBUFFER || !stmt->stmt_deffered.data[0]) RETURN(SQL_SUCCESS); } else { 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 */ } stmt_with_params = stmt->stmt_with_params; if (!stmt_with_params) // Extended Protocol exec_type = DIRECT_EXEC; } MYLOG(0, " stmt_with_params = '%s'\n", stmt->stmt_with_params); /* * The real execution. */ MYLOG(0, "about to begin SC_execute exec_type=%d\n", exec_type); ipdopts = SC_get_IPDF(stmt); apdopts = SC_get_APDF(stmt); 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 (end_row < 0) end_row = 0; } if (LAST_EXEC == exec_type && NULL != ipdopts->param_status_ptr) { int i; for (i = end_row; i >= start_row; i--) { if (SQL_PARAM_UNUSED != ipdopts->param_status_ptr[i]) { status_row = i; break; } } } count_of_deffered = stmt->count_of_deffered; if (DIRECT_EXEC == exec_type) { retval = SC_execute(stmt); stmt->count_of_deffered = 0; } else if (DEFFERED_EXEC == exec_type && stmt->exec_current_row < end_row && stmt->count_of_deffered + 1 < stmt->batch_size) { if (INVALID_EXPBUFFER) initPQExpBuffer(&stmt->stmt_deffered); if (INVALID_EXPBUFFER) { retval = SQL_ERROR; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory", __FUNCTION__); } else { if (NULL != stmt_with_params) { if (stmt->stmt_deffered.data[0]) appendPQExpBuffer(&stmt->stmt_deffered, ";%s", stmt_with_params); else printfPQExpBuffer(&stmt->stmt_deffered, "%s", stmt_with_params); } if (NULL != ipdopts->param_status_ptr) ipdopts->param_status_ptr[stmt->exec_current_row] = SQL_PARAM_SUCCESS; // set without exec stmt->count_of_deffered++; stmt->exec_current_row++; RETURN(SQL_SUCCESS); } } else { if (VALID_EXPBUFFER) { if (NULL != stmt_with_params) appendPQExpBuffer(&stmt->stmt_deffered, ";%s", stmt_with_params); stmt->stmt_with_params = stmt->stmt_deffered.data; } retval = SC_execute(stmt); stmt->stmt_with_params = stmt_with_params; stmt->count_of_deffered = 0; if (VALID_EXPBUFFER) resetPQExpBuffer(&stmt->stmt_deffered); } if (retval == SQL_ERROR) { MYLOG(0, "count_of_deffered=%d\n", count_of_deffered); param_status_batch_update(ipdopts, SQL_PARAM_ERROR, stmt->exec_current_row, count_of_deffered); 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 = QR_nextr(res), kres) { QR_set_fields(kres, QR_get_fields(res)); QR_set_fields(res, NULL); kres->num_fields = res->num_fields; QR_detach(res); SC_set_Result(stmt, kres); res = kres; } } ipdopts = SC_get_IPDF(stmt); if (ipdopts->param_status_ptr) { switch (retval) { case SQL_SUCCESS: ipdopts->param_status_ptr[status_row] = SQL_PARAM_SUCCESS; break; case SQL_SUCCESS_WITH_INFO: MYLOG(0, "count_of_deffered=%d has_notice=%d\n", count_of_deffered, stmt->has_notice); param_status_batch_update(ipdopts, (count_of_deffered > 0 && !stmt->has_notice) ? SQL_PARAM_SUCCESS : SQL_PARAM_SUCCESS_WITH_INFO, status_row, count_of_deffered); break; default: param_status_batch_update(ipdopts, SQL_PARAM_ERROR, status_row, count_of_deffered); break; } } stmt->has_notice = 0; if (stmt->exec_current_row >= end_row) { *exec_end = TRUE; stmt->exec_current_row = -1; } else stmt->exec_current_row++; if (res) { EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); const char *cmd = QR_get_command(res); 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; } 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) { int ret; ConnectionClass *conn; ConnInfo *ci = NULL; MYLOG(DETAIL_LOG_LEVEL, "entering %p->external=%d\n", stmt, stmt->external); conn = SC_get_conn(stmt); if (conn) ci = &conn->connInfo; 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; } int GenerateSvpCommand(ConnectionClass *conn, int type, char *cmd, int buflen) { char esavepoint[50]; int rtn = -1; cmd[0] = '\0'; switch (type) { case INTERNAL_SAVEPOINT_OPERATION: /* savepoint */ #ifdef _RELEASE_INTERNAL_SAVEPOINT if (conn->internal_svp) rtn = snprintf(cmd, buflen, "RELEASE %s;", GetSvpName(conn, esavepoint, sizeof(esavepoint))); #endif /* _RELEASE_INTERNAL_SAVEPOINT */ rtn = snprintfcat(cmd, buflen, "SAVEPOINT %s", GetSvpName(conn, esavepoint, sizeof(esavepoint))); break; case INTERNAL_ROLLBACK_OPERATION: /* rollback */ if (conn->internal_svp) rtn = snprintf(cmd, buflen, "ROLLBACK TO %s", GetSvpName(conn, esavepoint, sizeof(esavepoint))); else rtn = snprintf(cmd, buflen, "ROLLBACK"); break; } return rtn; } /* * Must be in a transaction or the subsequent execution * invokes a transaction. */ RETCODE SetStatementSvp(StatementClass *stmt, unsigned int option) { CSTR func = "SetStatementSvp"; char cmd[128]; ConnectionClass *conn = SC_get_conn(stmt); QResultClass *res; RETCODE ret = SQL_SUCCESS_WITH_INFO; if (NULL == conn->pqconn) { SC_set_error(stmt, STMT_COMMUNICATION_ERROR, "The connection has been lost", __FUNCTION__); return SQL_ERROR; } if (CC_is_in_error_trans(conn)) return ret; if (!stmt->lock_CC_for_rb) { ENTER_CONN_CS(conn); stmt->lock_CC_for_rb = TRUE; } MYLOG(DETAIL_LOG_LEVEL, " %p->accessed=%d opt=%u in_progress=%u prev=%u\n", conn, CC_accessed_db(conn), option, conn->opt_in_progress, conn->opt_previous); conn->opt_in_progress &= option; switch (stmt->statement_type) { case STMT_TYPE_SPECIAL: case STMT_TYPE_TRANSACTION: return ret; } /* If rbpoint is not yet started and the previous statement was not read-only */ if (!CC_started_rbpoint(conn) && 0 == (conn->opt_previous & SVPOPT_RDONLY)) { BOOL need_savep = FALSE; if (SC_is_rb_stmt(stmt)) { if (CC_is_in_trans(conn)) /* needless to issue SAVEPOINT before the 1st command */ { need_savep = TRUE; } } if (need_savep) { if (0 != (option & SVPOPT_REDUCE_ROUNDTRIP)) { conn->internal_op = PREPEND_IN_PROGRESS; CC_set_accessed_db(conn); return ret; } GenerateSvpCommand(conn, INTERNAL_SAVEPOINT_OPERATION, cmd, sizeof(cmd)); conn->internal_op = SAVEPOINT_IN_PROGRESS; res = CC_send_query(conn, cmd, NULL, 0, NULL); conn->internal_op = 0; if (QR_command_maybe_successful(res)) ret = SQL_SUCCESS; else { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal SAVEPOINT failed", func); ret = SQL_ERROR; } QR_Destructor(res); } } CC_set_accessed_db(conn); MYLOG(DETAIL_LOG_LEVEL, "leaving %p->accessed=%d\n", conn, CC_accessed_db(conn)); return ret; } RETCODE DiscardStatementSvp(StatementClass *stmt, RETCODE ret, BOOL errorOnly) { CSTR func = "DiscardStatementSvp"; ConnectionClass *conn = SC_get_conn(stmt); BOOL start_stmt = FALSE; MYLOG(DETAIL_LOG_LEVEL, "entering %p->accessed=%d is_in=%d is_rb=%d is_tc=%d\n", conn, CC_accessed_db(conn), CC_is_in_trans(conn), SC_is_rb_stmt(stmt), SC_is_tc_stmt(stmt)); if (stmt->lock_CC_for_rb) MYLOG(0, "in_progress=%u previous=%d\n", conn->opt_in_progress, conn->opt_previous); switch (ret) { case SQL_NEED_DATA: break; case SQL_ERROR: start_stmt = TRUE; break; default: if (!errorOnly) start_stmt = TRUE; break; } if (!CC_accessed_db(conn) || !CC_is_in_trans(conn)) goto cleanup; if (!SC_is_rb_stmt(stmt) && !SC_is_tc_stmt(stmt)) goto cleanup; if (SQL_ERROR == ret) { if (CC_started_rbpoint(conn) && conn->internal_svp) { int cmd_success = CC_internal_rollback(conn, PER_STATEMENT_ROLLBACK, FALSE); if (!cmd_success) { SC_set_error(stmt, STMT_INTERNAL_ERROR, "internal ROLLBACK failed", func); goto cleanup; } } else { CC_abort(conn); goto cleanup; } } else if (errorOnly) return ret; MYLOG(DETAIL_LOG_LEVEL, "\tret=%d\n", ret); cleanup: #ifdef NOT_USED if (!SC_is_prepare_statement(stmt) && ONCE_DESCRIBED == stmt->prepared) SC_set_prepared(stmt, NOT_YET_PREPARED); #endif if (start_stmt || SQL_ERROR == ret) { stmt->execinfo = 0; if (SQL_ERROR != ret && CC_accessed_db(conn)) { conn->opt_previous = conn->opt_in_progress; CC_init_opt_in_progress(conn); } if (stmt->lock_CC_for_rb) { stmt->lock_CC_for_rb = FALSE; LEAVE_CONN_CS(conn); MYLOG(DETAIL_LOG_LEVEL, " release conn_lock\n"); } CC_start_stmt(conn); } MYLOG(DETAIL_LOG_LEVEL, "leaving %d\n", ret); return ret; } /* * Given a SQL statement, see if it is an INSERT INTO statement and extract * the name of the table (with schema) of the table that was inserted to. * (It is needed to resolve any @@identity references in the future.) */ void SC_setInsertedTable(StatementClass *stmt, RETCODE retval) { const char *cmd = stmt->statement; ConnectionClass *conn; size_t len; if (STMT_TYPE_INSERT != stmt->statement_type) return; if (!SQL_SUCCEEDED(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;*/ /* * Parse a statement that was just executed. If it looks like an INSERT INTO * statement, try to extract the table name (and schema) of the table that * we inserted into. * * This is by no means fool-proof, we don't implement the whole backend * lexer and grammar here, but should handle most simple INSERT statements. */ 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)) cmd++; if (!*cmd) return; NULL_THE_NAME(conn->schemaIns); NULL_THE_NAME(conn->tableIns); eatTableIdentifiers((const UCHAR *) cmd, conn->ccsc, &conn->tableIns, &conn->schemaIns); if (!NAME_IS_VALID(conn->tableIns)) NULL_THE_NAME(conn->schemaIns); } /* 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 = FALSE, recycled = FALSE, recycle = TRUE; SQLSMALLINT num_params; MYLOG(0, "entering...%x %p status=%d\n", flag, stmt, stmt->status); stmt->has_notice = 0; conn = SC_get_conn(stmt); apdopts = SC_get_APDF(stmt); /* * If the statement was previously described, just recycle the old result * set that contained just the column information. */ if ((stmt->prepare && stmt->status == STMT_DESCRIBED) || (stmt->status == STMT_FINISHED && 0 != (flag & PODBC_RECYCLE_STATEMENT))) { stmt->exec_current_row = -1; SC_recycle_statement(stmt); } MYLOG(0, "clear errors...\n"); 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(0, "problem with handle\n"); 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) { /* * re-executing an prepared statement. * Don't recycle the statement but * discard the old result. */ recycle = FALSE; SC_reset_result_for_rerun(stmt); } /* * 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(0, "recycling statement (should have been done by app)...\n"); /******** 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(0, "problem with statement\n"); 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 (end_row < 0) end_row = 0; } 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; BOOL maybeBatch = FALSE; if (end_row > start_row && SQL_CURSOR_FORWARD_ONLY == stmt->options.cursor_type && SQL_CONCUR_READ_ONLY == stmt->options.scroll_concurrency && stmt->batch_size > 1) maybeBatch = TRUE; MYLOG(0, "prepare=%d prepared=%d batch_size=%d start_row=" FORMAT_LEN "end_row=" FORMAT_LEN " => maybeBatch=%d\n", stmt->prepare, stmt->prepared, stmt->batch_size, start_row, end_row, maybeBatch); if (NOT_YET_PREPARED == stmt->prepared) { if (maybeBatch) stmt->use_server_side_prepare = 0; switch (nCallParse = HowToPrepareBeforeExec(stmt, TRUE)) { case shouldParse: if (retval = prepareParameters(stmt, FALSE), SQL_ERROR == retval) goto cleanup; break; } } MYLOG(0, "prepareParameters was %s called, prepare state:%d\n", shouldParse == nCallParse ? "" : "not", stmt->prepare); if (shouldParse == nCallParse && PREPARE_BY_THE_DRIVER == stmt->prepare) { SC_set_Result(stmt, NULL); } if (0 != (PREPARE_BY_THE_DRIVER & stmt->prepare) && maybeBatch) stmt->exec_type = DEFFERED_EXEC; else stmt->exec_type = DIRECT_EXEC; MYLOG(0, "prepare=%d maybeBatch=%d exec_type=%d\n", stmt->prepare, maybeBatch, stmt->exec_type); if (ipdopts->param_processed_ptr) *ipdopts->param_processed_ptr = 0; /* * Initialize param_status_ptr */ if (ipdopts->param_status_ptr) { for (i = 0; i <= end_row; i++) ipdopts->param_status_ptr[i] = SQL_PARAM_UNUSED; } if (recycle && !recycled) SC_recycle_statement(stmt); if (isSqlServr() && stmt->external && 0 != stmt->prepare && PG_VERSION_LT(conn, 8.4) && SC_can_parse_statement(stmt)) parse_sqlsvr(stmt); } next_param_row: if (stmt->exec_current_row > end_row) exec_end = TRUE; else if (apdopts->param_operation_ptr) { while (apdopts->param_operation_ptr[stmt->exec_current_row] == SQL_PARAM_IGNORE) { if (stmt->exec_current_row >= end_row) { exec_end = TRUE; break; } ++stmt->exec_current_row; } } if (exec_end) { if (DEFFERED_EXEC == stmt->exec_type ) retval = Exec_with_parameters_resolved(stmt, LAST_EXEC, &exec_end); stmt->exec_current_row = -1; goto cleanup; } /* * Initialize the current row status */ if (ipdopts->param_status_ptr) ipdopts->param_status_ptr[stmt->exec_current_row] = SQL_PARAM_ERROR; /* * Free any data at exec params before the statement is * executed again or the next set of parameters is processed. * If not, then there will be a memory leak when the next * SQLParamData/SQLPutData is called. */ SC_free_params(stmt, STMT_FREE_PARAMS_DATA_AT_EXEC_ONLY); /* * Check if statement has any data-at-execute parameters when it is * not in SC_pre_execute. */ { /* * 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(0, "The " FORMAT_LEN "th parameter of " FORMAT_LEN "-row is data at exec(" FORMAT_LEN ")\n", i, current_row, pcVal ? (*pcVal) : -1); 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, stmt->exec_type, &exec_end); if (!exec_end) { goto next_param_row; } cleanup: MYLOG(0, "leaving %p retval=%d status=%d\n", stmt, retval, stmt->status); SC_setInsertedTable(stmt, retval); #undef return if (SQL_SUCCESS == retval && STMT_OK > SC_get_errornumber(stmt)) retval = SQL_SUCCESS_WITH_INFO; return retval; } RETCODE SQL_API PGAPI_Transact(HENV henv, HDBC hdbc, SQLUSMALLINT fType) { CSTR func = "PGAPI_Transact"; ConnectionClass *conn; char ok; int lf; MYLOG(0, "entering hdbc=%p, henv=%p\n", 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(0, "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; MYLOG(0, "entering...\n"); /* 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); if (stmt->execute_delegate) estmt = stmt->execute_delegate; else estmt = stmt; /* * SQLCancel works differently depending on what the statement is * currently doing: * * 1. In the middle of SQLParamData / SQLPutData * -> cancel the statement * * 2. Running a query asynchronously. (asynchronous mode is not supported * by psqlODBC) * * 3. Busy running a function in another thread. * -> Send a query cancel request to the server * * 4. Not doing anything. * -> in ODBC version 2.0, same as SQLFreeStmt(SQL_CLOSE). In version * 3.5, it has no effect. * * XXX: Checking for these conditions is racy. For example, we might * see that the statement is waiting for SQLParamdata/SQLPutData, but * before we acquire the lock on the statement, another thread has * supplied the data and started executing. In that case, we'll block * on the lock until the execution finishes. */ if (estmt->data_at_exec >= 0) { /* Waiting for more data from SQLParamData/SQLPutData. Cancel that. */ /* * Note, any previous data-at-exec buffers will be freed * if they call SQLExecDirect or SQLExecute again. */ ENTER_STMT_CS(stmt); SC_clear_error(stmt); estmt->data_at_exec = -1; estmt->current_exec_param = -1; estmt->put_data = FALSE; cancelNeedDataState(estmt); LEAVE_STMT_CS(stmt); return ret; } else if (estmt->status == STMT_EXECUTING) { /* * Busy executing in a different thread. Send a cancel request to * the server. */ if (!CC_send_cancel_request(conn)) return SQL_ERROR; else return SQL_SUCCESS; } else { /* * The statement is not executing, and it's not waiting for params * either. Looks like it's not doing anything. */ return SQL_SUCCESS; } } /* * 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 * szSqlStrIn, SQLINTEGER cbSqlStrIn, SQLCHAR * szSqlStr, SQLINTEGER cbSqlStrMax, SQLINTEGER * pcbSqlStr) { CSTR func = "PGAPI_NativeSql"; size_t len = 0; char *ptr; ConnectionClass *conn = (ConnectionClass *) hdbc; RETCODE result; MYLOG(0, "entering...cbSqlStrIn=" FORMAT_INTEGER "\n", 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 * 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(0, "entering...\n"); conn = SC_get_conn(stmt); estmt = stmt->execute_delegate ? stmt->execute_delegate : stmt; apdopts = SC_get_APDF(estmt); MYLOG(0, "\tdata_at_exec=%d, params_alloc=%d\n", 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); MYLOG(DETAIL_LOG_LEVEL, "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, stmt->exec_type, &exec_end); if (exec_end) { /**SC_reset_delegate(retval, stmt);**/ retval = dequeueNeedDataCallback(retval, stmt); goto cleanup; } 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); MYLOG(DETAIL_LOG_LEVEL, "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++) { MYLOG(DETAIL_LOG_LEVEL, "i=%d", i); if (apdopts->parameters[i].data_at_exec) { MYPRINTF(DETAIL_LOG_LEVEL, " 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; MYPRINTF(DETAIL_LOG_LEVEL, " offset=" FORMAT_LEN " perrow=" FORMAT_LEN, offset, perrow); *prgbValue = apdopts->parameters[i].buffer + offset + estmt->exec_current_row * perrow; } else *prgbValue = apdopts->parameters[i].buffer; } break; } MYPRINTF(DETAIL_LOG_LEVEL, "\n"); } retval = SQL_NEED_DATA; MYLOG(DETAIL_LOG_LEVEL, "return SQL_NEED_DATA\n"); cleanup: #undef return SC_setInsertedTable(stmt, retval); MYLOG(0, "leaving %d\n", 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 *putbuf, *allocbuf = NULL; Int2 ctype; SQLLEN putlen; BOOL lenset = FALSE, handling_lo = FALSE; MYLOG(0, "entering...\n"); #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; } 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); #ifdef UNICODE_SUPPORT if (SQL_C_WCHAR == ctype && CC_default_is_c(conn)) ctype = SQL_C_CHAR; #endif } 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(0, "(1) cbValue = " FORMAT_LEN "\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(0, "lo_write: cbValue=" FORMAT_LEN ", 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(0, "(>1) cbValue = " FORMAT_LEN "\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(0, "lo_write(2): cbValue = " FORMAT_LEN ", wrote %d bytes\n", putlen, retval); *current_pdata->EXEC_used += putlen; } else { old_pos = *current_pdata->EXEC_used; if (putlen > 0) { SQLLEN used = *current_pdata->EXEC_used + putlen; SQLLEN allocsize; char *buffer; for (allocsize = (1 << 4); allocsize <= used; allocsize <<= 1) ; MYLOG(0, " cbValue = " FORMAT_LEN ", old_pos = " FORMAT_LEN ", *used = " FORMAT_LEN "\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); return retval; } psqlodbc-13.02.0000/lobj.c000644 001751 001751 00000007623 14122574536 016175 0ustar00hiroshihiroshi000000 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_lseek64(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, "loread", (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, "lowrite", &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; /* We use lo_lseek64 */ 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; /* We use lo_tell64 */ if (!CC_send_function(conn, "lo_tell", &retval, &result_len, 1, argv, 1)) return -1; else return retval; } Int8 odbc_lo_lseek64(ConnectionClass *conn, int fd, Int8 offset, Int4 whence) { LO_ARG argv[3]; Int8 retval; Int4 result_len; if (PG_VERSION_LT(conn, 9.3)) { Int4 offset32; offset32 = (Int4) offset; if (offset != (Int8) offset32) { CC_set_error(conn, CONN_VALUE_OUT_OF_RANGE, "large object lseek64 is unavailable for the server", __FUNCTION__); return -1; } return (Int8) odbc_lo_lseek(conn, fd, offset32, whence); } argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; argv[1].isint = 2; argv[1].len = sizeof(offset); argv[1].u.integer64 = offset; argv[2].isint = 1; argv[2].len = 4; argv[2].u.integer = whence; if (!CC_send_function(conn, "lo_lseek64", &retval, &result_len, 2, argv, 3)) return -1; else return retval; } Int8 odbc_lo_tell64(ConnectionClass *conn, int fd) { LO_ARG argv[1]; Int8 retval; Int4 result_len; if (PG_VERSION_LT(conn, 9.3)) return (Int8) odbc_lo_tell(conn, fd); argv[0].isint = 1; argv[0].len = 4; argv[0].u.integer = fd; if (!CC_send_function(conn, "lo_tell64", &retval, &result_len, 2, argv, 1)) return -1; else return retval; } psqlodbc-13.02.0000/misc.c000644 001751 001751 00000013730 14122574536 016176 0ustar00hiroshihiroshi000000 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 /* * 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. */ size_t strncpy_null(char *dst, const char *src, ssize_t len) { int i; if (NULL != dst && len > 0) { for (i = 0; src[i] && i < len - 1; i++) dst[i] = src[i]; dst[i] = '\0'; } else return 0; if (src[i]) return strlen(src); return i; } /*------ * 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(0, "invalid length=" FORMAT_INTEGER "\n", len); return NULL; } if (buf) { strncpy_null(buf, (char *) s, bufsize > length ? length + 1 : bufsize); return buf; } MYLOG(DETAIL_LOG_LEVEL, "malloc size=" FORMAT_SIZE_T "\n", length); str = malloc(length + 1); MYLOG(DETAIL_LOG_LEVEL, "str=%p\n", str); if (!str) return NULL; strncpy_null(str, (char *) s, length + 1); return str; } char * my_trim(char *s) { char *last; for (last = s + strlen(s) - 1; last >= s; last--) { if (*last == ' ') *last = '\0'; else break; } return s; } /* * snprintfcat is a extension to snprintf * It add format to buf at given pos */ #ifdef POSIX_SNPRINTF_REQUIRED static posix_vsnprintf(char *str, size_t size, const char *format, va_list ap); #define vsnprintf posix_vsnprintf #endif /* POSIX_SNPRINTF_REQUIRED */ int snprintfcat(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 + pos; } /* * snprintf_len 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; } /* * Windows doesn't have snprintf(). It has _snprintf() which is similar, * but it behaves differently wrt. truncation. This is a compatibility * function that uses _snprintf() to provide POSIX snprintf() behavior. * * Our strategy, if the output doesn't fit, is to create a temporary buffer * and call _snprintf() on that. If it still doesn't fit, enlarge the buffer * and repeat. */ #ifdef POSIX_SNPRINTF_REQUIRED static int posix_vsnprintf(char *str, size_t size, const char *format, va_list ap) { int len; char *tmp; size_t newsize; len = _vsnprintf(str, size, format, ap); if (len < 0) { if (size == 0) newsize = 100; else newsize = size; do { newsize *= 2; tmp = malloc(newsize); if (!tmp) return -1; len = _vsnprintf(tmp, newsize, format, ap); if (len >= 0) memcpy(str, tmp, size); free(tmp); } while (len < 0); } if (len >= size && size > 0) { /* Ensure the buffer is NULL-terminated */ str[size - 1] = '\0'; } return len; } int posix_snprintf(char *buf, size_t size, const char *format, ...) { int len; va_list arglist; va_start(arglist, format); len = posix_vsnprintf(buf, size, format, arglist); va_end(arglist); return len; } #endif /* POSIX_SNPRINTF_REQUIRED */ #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. */ char * quote_table(const pgNAME schema, const pgNAME table, char *buf, int buf_size) { const char *ptr; int i; i = 0; if (NAME_IS_VALID(schema)) { buf[i++] = '"'; for (ptr = SAFE_NAME(schema); *ptr != '\0' && i < buf_size - 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 < buf_size - 3; ptr++) { buf[i++] = *ptr; if (*ptr == '"') buf[i++] = '"'; /* escape quotes by doubling them */ } buf[i++] = '"'; buf[i] = '\0'; return buf; } psqlodbc-13.02.0000/options.c000644 001751 001751 00000047276 14122574536 016752 0ustar00hiroshihiroshi000000 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 "unicode_support.h" #include #include "misc.h" #include "environ.h" #include "connection.h" #include "statement.h" #include "qresult.h" #include "pgapifunc.h" static 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 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(0, "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; MYPRINTF(0, "-> " 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(0, "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; MYPRINTF(0, "-> " FORMAT_LEN "\n", setval); break; case SQL_KEYSET_SIZE: /* ignored, but saved and returned */ MYLOG(0, "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(0, "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(0, "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(0, "SQL_NOSCAN, vParam = " FORMAT_LEN "\n", vParam); break; case SQL_QUERY_TIMEOUT: /* ignored */ MYLOG(0, "SQL_QUERY_TIMEOUT, vParam = " FORMAT_LEN "\n", vParam); if (conn) conn->stmtOptions.stmt_timeout = (SQLULEN) vParam; if (stmt) stmt->options.stmt_timeout = (SQLULEN) vParam; break; case SQL_RETRIEVE_DATA: MYLOG(0, "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(0, "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) { MYLOG(0, "USE_BOOKMARKS %s\n", (vParam == SQL_UB_OFF) ? "off" : ((vParam == SQL_UB_VARIABLE) ? "variable" : "fixed")); 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; #else SC_set_error(stmt, STMT_OPTION_NOT_FOR_THE_DRIVER, "The option may be for MS SQL Server(Set)", func); #endif /* NOT_USED */ } 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_FIXED(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_FIXED(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; char changed = FALSE; RETCODE retval; BOOL autocomm_on; MYLOG(0, "entering fOption = %d vParam = " FORMAT_LEN "\n", 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: /* * 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 != conn->autocommit_public) break; else if (!autocomm_on && SQL_AUTOCOMMIT_OFF == conn->autocommit_public) break; conn->autocommit_public = (autocomm_on ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF); MYLOG(0, "AUTOCOMMIT: transact_status=%d, vparam=" FORMAT_LEN "\n", conn->transact_status, vParam); #ifdef _HANDLE_ENLIST_IN_DTC_ if (CC_is_in_global_trans(conn)) { CC_set_error(conn, CONN_ILLEGAL_TRANSACT_STATE, "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: if (conn->isolation == vParam) break; /* * If the connection is not established, just record the setting to * reflect it upon connection. */ if (CC_not_connected(conn)) { conn->isolation = (UInt4) vParam; break; } /* The ODBC spec prohibits changing the isolation level while in manual transaction. */ 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; } } if (!CC_set_transact(conn, (UInt4) vParam)) return SQL_ERROR; conn->isolation = (UInt4) vParam; 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_FIXED(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(0, "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; const char *p = NULL; SQLLEN len = sizeof(SQLINTEGER); SQLRETURN result = SQL_SUCCESS; MYLOG(0, "entering...\n"); 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) = conn->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) = 4096; break; case SQL_QUERY_TIMEOUT: *((SQLULEN *) pvParam) = conn->stmtOptions.stmt_timeout; break; case SQL_QUIET_MODE: /* NOT SUPPORTED */ *((SQLULEN *) pvParam) = 0; break; case SQL_TXN_ISOLATION: if (conn->isolation == 0) { if (CC_not_connected(conn)) return SQL_NO_DATA; conn->isolation = CC_get_isolation(conn); } *((SQLUINTEGER *) pvParam) = conn->isolation; break; #ifdef SQL_ATTR_CONNECTION_DEAD case SQL_ATTR_CONNECTION_DEAD: #else case 1209: #endif /* SQL_ATTR_CONNECTION_DEAD */ MYLOG(0, "CONNECTION_DEAD status=%d", conn->status); *((SQLUINTEGER *) pvParam) = CC_not_connected(conn); MYPRINTF(0, " val=" FORMAT_UINTEGER "\n", *((SQLUINTEGER *) pvParam)); break; case SQL_ATTR_ANSI_APP: *((SQLUINTEGER *) pvParam) = CC_is_in_ansi_app(conn); MYLOG(0, "ANSI_APP val=" FORMAT_UINTEGER "\n", *((SQLUINTEGER *) pvParam)); 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 (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_FIXED(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(0, " entering...\n"); /* * 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); 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); Int4 bookmark; MYLOG(0, "entering...\n"); /* * 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; } bookmark = SC_make_int4_bookmark(stmt->currTuple); memcpy(pvParam, &bookmark, sizeof(UInt4)); 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(0, "SQL_CONCURRENCY " FORMAT_INTEGER "\n", stmt->options.scroll_concurrency); *((SQLINTEGER *) pvParam) = stmt->options.scroll_concurrency; break; case SQL_CURSOR_TYPE: /* PARTIAL SUPPORT */ MYLOG(0, "SQL_CURSOR_TYPE " FORMAT_INTEGER "\n", stmt->options.cursor_type); *((SQLINTEGER *) pvParam) = stmt->options.cursor_type; break; case SQL_KEYSET_SIZE: /* NOT SUPPORTED, but saved */ MYLOG(0, "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(0, "MAX_ROWS, returning " FORMAT_LEN "\n", stmt->options.maxRows); break; case SQL_NOSCAN: /* NOT SUPPORTED */ *((SQLINTEGER *) pvParam) = SQL_NOSCAN_ON; break; case SQL_QUERY_TIMEOUT: /* NOT SUPPORTED */ *((SQLULEN *) pvParam) = stmt->options.stmt_timeout; 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_FIXED(option, "fOption=%d", fOption); SC_log_error(func, option, stmt); return SQL_ERROR; } } if (StringLength) *StringLength = len; return SQL_SUCCESS; } psqlodbc-13.02.0000/pgtypes.c000644 001751 001751 00000141204 14122574536 016734 0ustar00hiroshihiroshi000000 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 SQLSMALLINT ansi_to_wtype(const ConnectionClass *self, SQLSMALLINT ansitype) { #ifndef UNICODE_SUPPORT return ansitype; #else if (!ALLOW_WCHAR(self)) return ansitype; switch (ansitype) { case SQL_CHAR: return SQL_WCHAR; case SQL_VARCHAR: return SQL_WVARCHAR; case SQL_LONGVARCHAR: return SQL_WLONGVARCHAR; } return ansitype; #endif /* UNICODE_SUPPORT */ } 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, SQL_TYPE_DATE, SQL_DATE, SQL_DECIMAL, SQL_DOUBLE, SQL_FLOAT, SQL_INTEGER, SQL_LONGVARBINARY, SQL_LONGVARCHAR, SQL_NUMERIC, SQL_REAL, SQL_SMALLINT, SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP, SQL_TIME, SQL_TIMESTAMP, SQL_TINYINT, SQL_VARBINARY, SQL_VARCHAR, #ifdef UNICODE_SUPPORT SQL_WCHAR, SQL_WVARCHAR, SQL_WLONGVARCHAR, #endif /* UNICODE_SUPPORT */ SQL_GUID, /* 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 }; #ifdef 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) static SQLSMALLINT get_interval_type(Int4 atttypmod, const char **name) { MYLOG(0, "entering atttypmod=%x\n", 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; } 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(0, "entering type=%d, atttypmod=%d, adtsize_or=%d, unknown = %d\n", 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 */ maxsize = 0; /* * Static ColumnSize (i.e., the Maximum ColumnSize of the datatype) This * has nothing to do with a result set. */ MYLOG(DETAIL_LOG_LEVEL, "!!! atttypmod < 0 ?\n"); if (atttypmod < 0 && adtsize_or_longestlen < 0) return maxsize; MYLOG(DETAIL_LOG_LEVEL, "!!! adtsize_or_logngest=%d\n", adtsize_or_longestlen); p = adtsize_or_longestlen; /* longest */ /* * Catalog Result Sets -- use assigned column width (i.e., from * set_tuplefield_string) */ MYLOG(DETAIL_LOG_LEVEL, "!!! catalog_result=%d\n", handle_unknown_size_as); if (UNKNOWNS_AS_LONGEST == handle_unknown_size_as) { MYLOG(0, "LONGEST: p = %d\n", p); if (p > 0 && (atttypmod < 0 || atttypmod > p)) return p; } if (TYPE_MAY_BE_ARRAY(type)) { if (p > 0) return p; return maxsize; } /* Size is unknown -- handle according to parameter */ if (atttypmod > 0) /* maybe the length is known */ { return atttypmod; } /* The type is really unknown */ switch (handle_unknown_size_as) { case UNKNOWNS_AS_DONTKNOW: return -1; case UNKNOWNS_AS_LONGEST: 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; } /* * Specify when handle_unknown_size_as parameter is unused */ #define UNUSED_HANDLE_UNKNOWN_SIZE_AS (-2) static SQLSMALLINT getNumericDecimalDigitsX(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longest, int UNUSED_handle_unknown_size_as) { Int4 default_decimal_digits = 6; MYLOG(0, "entering type=%d, atttypmod=%d\n", 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; const ConnInfo *ci = &(conn->connInfo); MYLOG(0, "entering type=%d, typmod=%d\n", type, atttypmod); if (atttypmod > -1) return (atttypmod >> 16) & 0xffff; switch (ci->numeric_as) { case SQL_VARCHAR: return ci->drivers.max_varchar_size; case SQL_LONGVARCHAR: return ci->drivers.max_longvarchar_size; case SQL_DOUBLE: return PG_DOUBLE_DIGITS; } 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; 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(0, "type=%d, atttypmod=%d\n", type, atttypmod); return (atttypmod > -1 ? atttypmod : 6); } static SQLSMALLINT getTimestampColumnSizeX(const ConnectionClass *conn, OID type, int atttypmod) { Int4 fixed, scale; MYLOG(0, "entering type=%d, atttypmod=%d\n", 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(0, "entering type=%d, atttypmod=%d\n", 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(0, "entering type=%d, atttypmod=%d\n", type, atttypmod); ttl = leading_precision; 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; } 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, int handle_unknown_size_as) { const ConnInfo *ci = &(conn->connInfo); EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); #ifdef PG_INTERVAL_AS_SQL_INTERVAL SQLSMALLINT sqltype; #endif /* PG_INTERVAL_AS_SQL_INTERVAL */ BOOL bLongVarchar, bFixed = FALSE; switch (type) { case PG_TYPE_CHAR: return ansi_to_wtype(conn, SQL_CHAR); case PG_TYPE_NAME: case PG_TYPE_REFCURSOR: return ansi_to_wtype(conn, SQL_VARCHAR); case PG_TYPE_BPCHAR: bFixed = TRUE; case PG_TYPE_VARCHAR: if (getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as) > ci->drivers.max_varchar_size) bLongVarchar = TRUE; else bLongVarchar = FALSE; return ansi_to_wtype(conn, bLongVarchar ? SQL_LONGVARCHAR : (bFixed ? SQL_CHAR : SQL_VARCHAR)); case PG_TYPE_TEXT: bLongVarchar = ci->drivers.text_as_longvarchar; if (bLongVarchar) { int column_size = getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); if (column_size > 0 && column_size <= ci->drivers.max_varchar_size) bLongVarchar = FALSE; } return ansi_to_wtype(conn, bLongVarchar ? SQL_LONGVARCHAR : SQL_VARCHAR); 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 */ return SQL_BIGINT; case PG_TYPE_NUMERIC: if (-1 == atttypmod && DEFAULT_NUMERIC_AS != ci->numeric_as) return ci->numeric_as; return SQL_NUMERIC; case PG_TYPE_FLOAT4: return SQL_REAL; case PG_TYPE_FLOAT8: return SQL_FLOAT; case PG_TYPE_DATE: if (EN_is_odbc3(env)) return SQL_TYPE_DATE; return SQL_DATE; case PG_TYPE_TIME: if (EN_is_odbc3(env)) return SQL_TYPE_TIME; return SQL_TIME; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: if (EN_is_odbc3(env)) return SQL_TYPE_TIMESTAMP; 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 ansi_to_wtype(conn, SQL_LONGVARCHAR); case PG_TYPE_INET: case PG_TYPE_CIDR: case PG_TYPE_MACADDR: return ansi_to_wtype(conn, SQL_VARCHAR); case PG_TYPE_UUID: return SQL_GUID; 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 ansi_to_wtype(conn, SQL_VARCHAR); case PG_TYPE_BIT: if (1 == atttypmod) return SQL_BIT; else return 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; bLongVarchar = ci->drivers.unknowns_as_longvarchar; if (bLongVarchar) { int column_size = getCharColumnSizeX(conn, type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); if (column_size > 0 && column_size <= ci->drivers.max_varchar_size) bLongVarchar = FALSE; } #ifdef EXPERIMENTAL_CURRENTLY return ansi_to_wtype(conn, bLongVarchar ? SQL_LONGVARCHAR : SQL_VARCHAR); #endif /* EXPERIMENTAL_CURRENTLY */ return bLongVarchar ? SQL_LONGVARCHAR : SQL_VARCHAR; } } SQLSMALLINT pgtype_attr_to_sqldesctype(const ConnectionClass *conn, OID type, int atttypmod, int adtsize_or_longestlen, int handle_unknown_size_as) { 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, adtsize_or_longestlen, handle_unknown_size_as)) { case SQL_TYPE_DATE: case SQL_TYPE_TIME: case SQL_TYPE_TIMESTAMP: return SQL_DATETIME; } 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_ADT_UNSET, PG_UNKNOWNS_UNSET)) { 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; } return -1; } SQLSMALLINT pgtype_attr_to_ctype(const ConnectionClass *conn, OID type, int atttypmod) { const ConnInfo *ci = &(conn->connInfo); EnvironmentClass *env = (EnvironmentClass *) CC_get_env(conn); #ifdef PG_INTERVAL_AS_SQL_INTERVAL SQLSMALLINT ctype; #endif /* PG_INTERVAL_A_SQL_INTERVAL */ switch (type) { case PG_TYPE_INT8: if (!conn->ms_jet) return ALLOWED_C_BIGINT; 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 (EN_is_odbc3(env)) return SQL_C_TYPE_DATE; return SQL_C_DATE; case PG_TYPE_TIME: if (EN_is_odbc3(env)) return SQL_C_TYPE_TIME; return SQL_C_TIME; case PG_TYPE_ABSTIME: case PG_TYPE_DATETIME: case PG_TYPE_TIMESTAMP_NO_TMZONE: case PG_TYPE_TIMESTAMP: if (EN_is_odbc3(env)) return SQL_C_TYPE_TIMESTAMP; 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; case PG_TYPE_BPCHAR: case PG_TYPE_VARCHAR: case PG_TYPE_TEXT: return ansi_to_wtype(conn, SQL_C_CHAR); case PG_TYPE_UUID: if (!conn->ms_jet) return SQL_C_GUID; return ansi_to_wtype(conn, 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 ansi_to_wtype(conn, 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 return ansi_to_wtype(conn, SQL_C_CHAR); #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_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: MYLOG(DETAIL_LOG_LEVEL, "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: return "timestamptz"; 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"; case PG_TYPE_VOID: return "void"; case PG_TYPE_INT2VECTOR: return "int2vector"; case PG_TYPE_OIDVECTOR: return "oidvector"; case PG_TYPE_ANY: return "any"; case PG_TYPE_INTERVAL: get_interval_type(atttypmod, &tname); return tname; 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); MYLOG(0, "entering type=%d, atttypmod=%d, adtsize_or=%d, unknown = %d\n", type, atttypmod, adtsize_or_longest, handle_unknown_size_as); switch (type) { case PG_TYPE_CHAR: return 1; 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) value = NAMEDATALEN_V73; 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_MONEY: return 10; case PG_TYPE_FLOAT4: return PG_REAL_DIGITS; case PG_TYPE_FLOAT8: return PG_DOUBLE_DIGITS; 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_TIME: 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: /* a sign, PG_REAL_DIGITS digits, a decimal point, the letter E, a sign, and 2 digits */ return (1 + PG_REAL_DIGITS + 1 + 1 + 3); case PG_TYPE_FLOAT8: /* a sign, PG_DOUBLE_DIGITS digits, a decimal point, the letter E, a sign, and 3 digits */ return (1 + PG_DOUBLE_DIGITS + 1 + 1 + 1 + 3); 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 36; 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: return 16; /* sizeof(SQLGUID) */ /* 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 */ 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 UNUSED_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_TIME: 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, UNUSED_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 UNUSED_handle_unknown_size_as) { switch (type) { case PG_TYPE_NUMERIC: return getNumericDecimalDigitsX(conn, type, atttypmod, adtsize_or_longestlen, UNUSED_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: case PG_TYPE_UNKNOWN: column_size = pgtype_attr_column_size(conn, type, atttypmod, PG_ADT_UNSET, 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 */ 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_ADT_UNSET, handle_unknown_size_as); default: if (type == conn->lobj_type) return pgtype_attr_column_size(conn, type, atttypmod, PG_ADT_UNSET, handle_unknown_size_as); } return -1; } /* * This was used when binding a query parameter, to decide which PostgreSQL * datatype to send to the server, depending on the SQL datatype that was * used in the SQLBindParameter call. * * However it is inflexible and rather harmful. * Now this function always returns 0. * We use cast instead to keep regression test results * in order to keep regression test results. */ OID sqltype_to_bind_pgtype(const ConnectionClass *conn, SQLSMALLINT fSqlType) { OID pgType = 0; return pgType; } /* * Casting parameters e.g. ?::timestamp is much more flexible * than specifying parameter datatype oids determined by * sqltype_to_bind_pgtype() via parse message. */ const char * sqltype_to_pgcast(const ConnectionClass *conn, SQLSMALLINT fSqlType) { const char *pgCast = NULL_STRING; switch (fSqlType) { case SQL_BINARY: case SQL_VARBINARY: pgCast = "::bytea"; break; case SQL_TYPE_DATE: case SQL_DATE: pgCast = "::date"; break; case SQL_DECIMAL: case SQL_NUMERIC: pgCast = "::numeric"; break; case SQL_BIGINT: pgCast = "::int8"; break; case SQL_INTEGER: pgCast = "::int4"; break; case SQL_REAL: pgCast = "::float4"; break; case SQL_SMALLINT: case SQL_TINYINT: pgCast = "::int2"; break; case SQL_TIME: case SQL_TYPE_TIME: pgCast = "::time"; break; case SQL_TIMESTAMP: case SQL_TYPE_TIMESTAMP: pgCast = "::timestamp"; break; case SQL_GUID: if (PG_VERSION_GE(conn, 8.3)) pgCast = "::uuid"; break; 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: pgCast = "::interval"; break; } return pgCast; } 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 = PG_TYPE_BOOL; break; case SQL_TYPE_DATE: 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: case SQL_TYPE_TIME: pgType = PG_TYPE_TIME; break; case SQL_TIMESTAMP: case SQL_TYPE_TIMESTAMP: pgType = PG_TYPE_DATETIME; break; case SQL_VARBINARY: pgType = PG_TYPE_BYTEA; break; case SQL_VARCHAR: pgType = PG_TYPE_VARCHAR; break; #ifdef UNICODE_SUPPORT case SQL_WVARCHAR: pgType = PG_TYPE_VARCHAR; break; #endif /* UNICODE_SUPPORT */ case SQL_GUID: if (PG_VERSION_GE(conn, 8.3)) pgType = PG_TYPE_UUID; break; 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 = PG_ADT_UNSET; if (col >= 0) { const QResultClass *res; if (res = SC_get_ExecdOrParsed(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) { SQLULEN i; size_t sval, maxscale = 0; const char *tval, *sptr; for (i = 0; i < res->num_cached_rows; i++) { tval = QR_get_value_backend_text(res, i, col); if (NULL != tval) { sptr = strchr(tval, '.'); if (NULL != sptr) { sval = strlen(tval) - (sptr + 1 - tval); if (sval > maxscale) maxscale = sval; } } } *adtsize_or_longestlen += (int) (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 handle_unknown_size_as) { 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, handle_unknown_size_as); } SQLSMALLINT pgtype_to_sqldesctype(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as) { int adtsize_or_longestlen; int atttypmod = getAtttypmodEtc(stmt, col, &adtsize_or_longestlen); return pgtype_attr_to_sqldesctype(SC_get_conn(stmt), type, atttypmod, adtsize_or_longestlen, handle_unknown_size_as); } 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); } /* * 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_LONGEST : 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_LONGEST : 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_LONGEST : 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_LONGEST : 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_LONGEST : 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 */ 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, UNUSED_HANDLE_UNKNOWN_SIZE_AS); 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, UNUSED_HANDLE_UNKNOWN_SIZE_AS); } /* * "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, UNUSED_HANDLE_UNKNOWN_SIZE_AS); } 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_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_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: return SQL_C_CHAR; case SQL_BIGINT: return ALLOWED_C_BIGINT; #ifdef UNICODE_SUPPORT case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: return ansi_to_wtype(conn, SQL_C_CHAR); #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; 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; case SQL_GUID: if (conn->ms_jet) return SQL_C_CHAR; else return SQL_C_GUID; 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: case SQL_C_TYPE_DATE: return sizeof(DATE_STRUCT); case SQL_C_TIME: case SQL_C_TYPE_TIME: return sizeof(TIME_STRUCT); case SQL_C_TIMESTAMP: case SQL_C_TYPE_TIMESTAMP: return sizeof(TIMESTAMP_STRUCT); case SQL_C_GUID: return sizeof(SQLGUID); 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); case SQL_C_NUMERIC: return sizeof(SQL_NUMERIC_STRUCT); case SQL_C_SBIGINT: case SQL_C_UBIGINT: return sizeof(SQLBIGINT); 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-13.02.0000/psqlodbc.c000644 001751 001751 00000010047 14122574536 017050 0ustar00hiroshihiroshi000000 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" #include "misc.h" #include #ifdef WIN32 #include "loadlib.h" #else #include #endif static int exepgm = 0; BOOL isMsAccess(void) {return 1 == exepgm;} BOOL isMsQuery(void) {return 2 == exepgm;} BOOL isSqlServr(void) {return 3 == exepgm;} 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(); INIT_CONNS_CS; INIT_COMMON_CS; return 0; } static void finalize_global_cs(void) { DELETE_COMMON_CS; DELETE_CONNS_CS; FinalizeLogging(); #ifdef _DEBUG #ifdef _MEMORY_DEBUG_ // _CrtDumpMemoryLeaks(); #endif /* _MEMORY_DEBUG_ */ #endif /* _DEBUG */ } #ifdef WIN32 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) { const char *exename = GetExeProgramName(); switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: s_hModule = hInst; /* Save for dialog boxes */ if (stricmp(exename, "msaccess") == 0) exepgm = 1; else if (strnicmp(exename, "msqry", 5) == 0) exepgm = 2; else if (strnicmp(exename, "sqlservr", 8) == 0) exepgm = 3; initialize_global_cs(); MYLOG(0, "exe name=%s\n", exename); break; case DLL_THREAD_ATTACH: break; case DLL_PROCESS_DETACH: MYLOG(0, "DETACHING %s\n", DRIVER_FILE_NAME); 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 */ #if defined(__GNUC__) || defined(__SUNPRO_C) /* Shared library initializer and destructor, using gcc's attributes */ static void __attribute__((constructor)) psqlodbc_init(void) { initialize_global_cs(); } 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(); 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-13.02.0000/qresult.c000644 001751 001751 00000112273 14122574536 016744 0ustar00hiroshihiroshi000000 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 #include "misc.h" #include #include #include static BOOL QR_prepare_for_tupledata(QResultClass *self); static BOOL QR_read_tuples_from_pgres(QResultClass *, PGresult **pgres); /* * 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) { if (!self) return; MYLOG(0, "entering\n"); CI_set_num_fields(QR_get_fields(self), new_num_fields); MYLOG(0, "leaving\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_reqsize(QResultClass *self, Int4 reqsize) { self->rowset_size_include_ommitted = reqsize; } 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); } 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 = QR_nextr(self); NULL != res; res = QR_nextr(res)) { 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(0, " 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(0, "entering\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; QR_nextr(rv) = NULL; 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->cmd_fetch_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(0, "leaving %p\n", rv); return rv; } void QR_close_result(QResultClass *self, BOOL destroy) { ConnectionClass *conn; QResultClass *next; BOOL top = TRUE; if (!self) return; MYLOG(0, "entering\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->pqconn) { 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 = QR_nextr(self); QR_detach(self); if (destroy) free(self); /* Repeat for the next result in the chain */ self = next; destroy = TRUE; /* always destroy chained results */ top = FALSE; } MYLOG(0, "leaving\n"); } void QR_reset_for_re_execute(QResultClass *self) { MYLOG(0, "entering for %p\n", self); if (!self) return; QR_close_result(self, FALSE); /* reset flags etc */ self->flags = 0; QR_set_rowstart_in_cache(self, -1); self->recent_processed_row_count = -1; /* clear error info etc */ self->rstatus = PORES_EMPTY_QUERY; self->aborted = FALSE; self->sqlstate[0] = '\0'; self->messageref = NULL; MYLOG(0, "leaving\n"); } void QR_Destructor(QResultClass *self) { MYLOG(0, "entering\n"); if (!self) return; QR_close_result(self, TRUE); MYLOG(0, "leaving\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, addlen; if (!msg || !msg[0]) return; addlen = strlen(msg); if (message) { pos = strlen(message) + 1; alsize = pos + addlen + 1; } else { pos = 0; alsize = addlen + 1; } if (message = realloc(message, alsize), NULL == message) return; if (pos > 0) message[pos - 1] = ';'; strncpy_null(message + pos, msg, addlen + 1); 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, addlen; if (!msg || !msg[0]) return; addlen = strlen(msg); if (message) { pos = strlen(message) + 1; alsize = pos + addlen + 1; } else { pos = 0; alsize = addlen + 1; } if (message = realloc(message, alsize), NULL == message) return; if (pos > 0) message[pos - 1] = ';'; strncpy_null(message + pos, msg, addlen + 1); self->notice = message; } TupleField *QR_AddNew(QResultClass *self) { size_t alloc; UInt4 num_fields; if (!self) return NULL; MYLOG(DETAIL_LOG_LEVEL, FORMAT_ULEN "th row(%d fields) alloc=" FORMAT_LEN "\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(0, "entering fcount=" FORMAT_LEN "\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; self->tupleField = NULL; } 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->pqconn) { char plannm[32]; SPRINTF_FIXED(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]; SPRINTF_FIXED(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(0, "leaving\n"); } BOOL QR_from_PGresult(QResultClass *self, StatementClass *stmt, ConnectionClass *conn, const char *cursor, PGresult **pgres) { int num_io_params, num_cached_rows; int i; Int2 paramType; IPDFields *ipdopts; Int2 lf; int new_num_fields; OID new_adtid, new_relid = 0, new_attid = 0; Int2 new_adtsize; Int4 new_atttypmod = -1; char *new_field_name; Int2 dummy1, dummy2; int cidx; BOOL reached_eof_now = FALSE; if (NULL != conn) /* First, get column information */ QR_set_conn(self, conn); /* at first read in the number of fields that are in the query */ new_num_fields = PQnfields(*pgres); QLOG(0, "\tnFields: %d\n", new_num_fields); /* according to that allocate memory */ QR_set_num_fields(self, new_num_fields); if (NULL == QR_get_fields(self)->coli_array) return FALSE; /* now read in the descriptions */ for (lf = 0; lf < new_num_fields; lf++) { new_field_name = PQfname(*pgres, lf); new_relid = PQftable(*pgres, lf); new_attid = PQftablecol(*pgres, lf); new_adtid = (OID) PQftype(*pgres, lf); new_adtsize = (Int2) PQfsize(*pgres, lf); new_atttypmod = (Int4) PQfmod(*pgres, lf); /* 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; QLOG(0, "\tfieldname='%s', adtid=%d, adtsize=%d, atttypmod=%d (rel,att)=(%d,%d)\n", new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid); CI_set_field_info(QR_get_fields(self), lf, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid); 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; if (stmt && conn) { 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) { MYLOG(DETAIL_LOG_LEVEL, "[%d].PGType %u->%u\n", i, PIC_get_pgtype(ipdopts->parameters[i]), CI_get_oid(QR_get_fields(self), cidx)); PIC_set_pgtype(ipdopts->parameters[i], CI_get_oid(QR_get_fields(self), cidx)); cidx++; } } } } } /* Then, get the data itself */ num_cached_rows = self->num_cached_rows; if (!QR_read_tuples_from_pgres(self, pgres)) return FALSE; MYLOG(DETAIL_LOG_LEVEL, "!!%p->cursTup=" FORMAT_LEN " total_read=" FORMAT_ULEN "\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; /* EOF is 'fetched < fetch requested' */ if (self->num_cached_rows - num_cached_rows < self->cmd_fetch_size) { MYLOG(0, "detect EOF " FORMAT_ULEN " - %d < " FORMAT_ULEN "\n", self->num_cached_rows, num_cached_rows, self->cmd_fetch_size); reached_eof_now = TRUE; QR_set_reached_eof(self); } if (reached_eof_now && self->cursTuple < (Int4) self->num_total_read) self->cursTuple = self->num_total_read; if (NULL != conn) { /* Force a read to occur in next_tuple */ QR_set_next_in_cache(self, (SQLLEN) 0); QR_set_rowstart_in_cache(self, 0); self->key_base = 0; } /* * Also fill in command tag. (Typically, it's SELECT, but can also be * a FETCH.) */ QR_set_command(self, PQcmdStatus(*pgres)); QR_set_cursor(self, cursor); if (NULL == cursor) QR_set_reached_eof(self); return TRUE; } /* * Procedure needed when closing cursors. */ void QR_on_close_cursor(QResultClass *self) { QR_set_cursor(self, NULL); } /* * 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; unsigned int flag = 0; char buf[64]; flag = READ_ONLY_QUERY; if (QR_needs_survival_check(self)) flag |= (ROLLBACK_ON_ERROR | IGNORE_ABORT_ON_CONN); SPRINTF_FIXED(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(0, "End transaction on conn=%p\n", conn); if ((ROLLBACK_ON_ERROR & flag) == 0) { STRCAT_FIXED(buf, ";commit"); flag |= END_WITH_COMMIT; QR_set_cursor(self, NULL); } else does_commit = TRUE; } MYLOG(DETAIL_LOG_LEVEL, " Case I CC_send_query %s flag=%x\n", buf, flag); 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(0, "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; } /* * Allocate memory for receiving next tuple. */ static BOOL QR_prepare_for_tupledata(QResultClass *self) { BOOL haskeyset = QR_haskeyset(self); SQLULEN num_total_rows = QR_get_num_total_tuples(self); MYLOG(DETAIL_LOG_LEVEL, "entering %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(0, "REALLOC: old_count = " FORMAT_LEN ", size = " FORMAT_SIZE_T "\n", tuple_size, (size_t) (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); memset(&self->keyset[self->count_keyset_allocated], 0, (tuple_size - self->count_keyset_allocated) * sizeof(KeySet)); self->count_keyset_allocated = tuple_size; } } 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; } SQLLEN QR_move_cursor_to_last(QResultClass *self, StatementClass *stmt) { char movecmd[64]; QResultClass *res; SQLLEN moved; ConnectionClass *conn = SC_get_conn(stmt); if (!QR_get_cursor(self)) return 0; if (QR_once_reached_eof(self) && self->cursTuple >= self->num_total_read) return 0; SPRINTF_FIXED(movecmd, "move all in \"%s\"", QR_get_cursor(self)); res = CC_send_query(conn, movecmd, NULL, READ_ONLY_QUERY, stmt); if (!QR_command_maybe_successful(res)) { QR_Destructor(res); SC_set_error(stmt, STMT_EXEC_ERROR, "move error occured", __FUNCTION__); return (-1); } moved = (-1); if (sscanf(res->command, "MOVE " FORMAT_ULEN, &moved) > 0) { moved++; self->cursTuple += moved; if (!QR_once_reached_eof(self)) { self->num_total_read = self->cursTuple; QR_set_reached_eof(self); } } QR_Destructor(res); return moved; } /* This function is called by fetch_tuples() AND SQLFetch() */ int QR_next_tuple(QResultClass *self, StatementClass *stmt) { CSTR func = "QR_next_tuple"; int ret = TRUE; /* 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; QResultClass *res; /* QR_set_command() dups this string so doesn't need static */ char fetch[128]; QueryInfo qi; ConnectionClass *conn; ConnInfo *ci; BOOL reached_eof_now = FALSE, curr_eof; /* detecting EOF is pretty important */ MYLOG(DETAIL_LOG_LEVEL, "Oh %p->fetch_number=" FORMAT_LEN "\n", self, self->fetch_number); MYLOG(DETAIL_LOG_LEVEL, "in total_read=" FORMAT_ULEN " cursT=" FORMAT_LEN " currT=" FORMAT_LEN " ad=%d total=" FORMAT_ULEN " rowsetSize=%d\n", self->num_total_read, self->cursTuple, stmt->currTuple, self->ad_count, QR_get_num_total_tuples(self), self->rowset_size_include_ommitted); num_total_rows = QR_get_num_total_tuples(self); conn = QR_get_conn(self); curr_eof = FALSE; req_size = QR_get_reqsize(self); /* Determine the optimum cache size. */ ci = &(conn->connInfo); fetch_size = ci->drivers.fetch_max; if ((Int4)req_size > fetch_size) fetch_size = req_size; 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 = NULL; SQLULEN movement, moved; movement = self->move_offset; if (QR_is_moving_backward(self)) { if (fetch_size > req_size) { SQLLEN incr_move = fetch_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; MYLOG(DETAIL_LOG_LEVEL, "cache=" FORMAT_ULEN " rowset=%d movement=" FORMAT_ULEN "\n", self->cache_size, req_size, movement); SPRINTF_FIXED(movecmd, "move backward " FORMAT_ULEN " in \"%s\"", movement, QR_get_cursor(self)); } else if (QR_is_moving_forward(self)) SPRINTF_FIXED(movecmd, "move " FORMAT_ULEN " in \"%s\"", movement, QR_get_cursor(self)); else { SPRINTF_FIXED(movecmd, "move all in \"%s\"", QR_get_cursor(self)); movement = INT_MAX; } mres = CC_send_query(conn, movecmd, NULL, READ_ONLY_QUERY, stmt); if (!QR_command_maybe_successful(mres)) { QR_Destructor(mres); SC_set_error(stmt, STMT_EXEC_ERROR, "move error occured", func); RETURN(-1) } moved = movement; if (sscanf(mres->command, "MOVE " FORMAT_ULEN, &moved) > 0) { MYLOG(DETAIL_LOG_LEVEL, "moved=" FORMAT_ULEN " ? " 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); } } } } /* ... 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 */ { SC_set_error(stmt, STMT_EXEC_ERROR, "Hmm where are fetched data?", func); RETURN(-1) } /* return a row from cache */ MYLOG(0, "fetch_number < fcount: returning tuple " FORMAT_LEN ", fcount = " FORMAT_LEN "\n", fetch_number, num_backend_rows); self->tupleField = the_tuples + (fetch_number * num_fields); MYLOG(DETAIL_LOG_LEVEL, "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; if (stmt->currTuple + 1 >= num_total_rows) reached_eod = TRUE; if (reached_eod) { MYLOG(0, "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; if (!QR_get_cursor(self)) { MYLOG(0, "ALL_ROWS: done, fcount = " FORMAT_ULEN ", fetch_number = " FORMAT_LEN "\n", 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 */ self->cache_size = fetch_size; /* clear obsolete tuples */ MYLOG(DETAIL_LOG_LEVEL, "clear obsolete " FORMAT_LEN " 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(0, "corrupted fetch_size end_tuple=" FORMAT_LEN " <= cached_rows=" FORMAT_LEN "\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) /* Send a FETCH command to get more rows */ SPRINTF_FIXED(fetch, "fetch %d in \"%s\"", fetch_size, QR_get_cursor(self)); MYLOG(0, "sending actual fetch (%d) query '%s'\n", fetch_size, fetch); if (!boundary_adjusted) { QR_set_num_cached_rows(self, 0); QR_set_rowstart_in_cache(self, offset); } num_rows_in = self->num_cached_rows; /* don't read ahead for the next tuple (self) ! */ qi.row_size = self->cache_size; qi.fetch_size = fetch_size; qi.result_in = self; qi.cursor = NULL; res = CC_send_query(conn, fetch, &qi, READ_ONLY_QUERY, stmt); if (!QR_command_maybe_successful(res)) { if (!QR_get_message(self)) QR_set_message(self, "Error fetching next group."); RETURN(FALSE) } cur_fetch = 0; self->tupleField = NULL; curr_eof = reached_eof_now = (QR_once_reached_eof(self) && self->cursTuple >= (Int4)self->num_total_read); MYLOG(DETAIL_LOG_LEVEL, "reached_eof_now=%d\n", reached_eof_now); MYLOG(0, ": PGresult: fetch_total = " FORMAT_ULEN " & this_fetch = " FORMAT_ULEN "\n", self->num_total_read, self->num_cached_rows); MYLOG(0, ": PGresult: cursTuple = " FORMAT_LEN ", offset = " FORMAT_LEN "\n", self->cursTuple, offset); cur_fetch = self->num_cached_rows - num_rows_in; if (!ret) RETURN(ret) { SQLLEN start_idx = 0; num_backend_rows = self->num_cached_rows; if (reached_eof_now) { MYLOG(0, "reached eof now\n"); QR_set_reached_eof(self); 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; start_idx = CacheIdx2GIdx(offset, stmt, self) - self->num_total_read; if (curr_eof && start_idx >= 0) { 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; else if (add_size < 0) add_size = 0; MYLOG(DETAIL_LOG_LEVEL, "will add " FORMAT_LEN " added_tuples from " FORMAT_LEN " and select the " FORMAT_LEN "th added tuple " FORMAT_LEN "\n", add_size, start_idx, offset - num_backend_rows + start_idx, cur_fetch); 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(0, " 'C': DONE (fcount == " FORMAT_LEN ")\n", 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 (self->keyset && (self->dl_count > 0 || self->up_count > 0)) { SQLLEN i, lf; SQLLEN lidx, hidx, lkidx, hkidx; SQLLEN *deleted = self->deleted, *updated = self->updated; num_backend_rows = QR_get_num_cached_tuples(self); lidx = CacheIdx2GIdx(num_rows_in, stmt, self); hidx = CacheIdx2GIdx(num_backend_rows, stmt, self); lkidx = GIdx2KResIdx(lidx, stmt, self); hkidx = GIdx2KResIdx(hidx, stmt, self); /* For simplicty, use CURS_NEEDS_REREAD bit to mark the row */ for (i = lkidx; i < hkidx; i++) self->keyset[i].status |= CURS_NEEDS_REREAD; /* deleted info */ for (i = 0; i < self->dl_count && hidx > deleted[i]; i++) { if (lidx <= deleted[i]) { lf = GIdx2KResIdx(deleted[i], stmt, self); if (lf >= 0 && lf < self->num_cached_keys) { 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 = GIdx2KResIdx(updated[i], stmt, self); /* 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); /*MYLOG(DETAIL_LOG_LEVEL, "keyset[%d].status=%x\n", i, self->keyset[i].status);*/ } } cleanup: LEAVE_CONN_CS(conn); #undef RETURN #undef return MYLOG(DETAIL_LOG_LEVEL, "returning %d offset=" FORMAT_LEN "\n", ret, offset); return ret; } /* * Read tuples from a libpq PGresult object into QResultClass. * * The result status of the passed-in PGresult should be either * PGRES_TUPLES_OK, or PGRES_SINGLE_TUPLE. If it's PGRES_SINGLE_TUPLE, * this function will call PQgetResult() to read all the available tuples. */ static BOOL QR_read_tuples_from_pgres(QResultClass *self, PGresult **pgres) { Int2 field_lf; int len; char *value; char *buffer; int ci_num_fields = QR_NumResultCols(self); /* speed up access */ int num_fields = self->num_fields; /* speed up access */ ColumnInfoClass *flds; int effective_cols; char tidoidbuf[32]; int rowno; int nrows; int resStatus; int numTotalRows = 0; /* set the current row to read the fields into */ effective_cols = QR_NumPublicResultCols(self); flds = QR_get_fields(self); nextrow: resStatus = PQresultStatus(*pgres); switch (resStatus) { case PGRES_TUPLES_OK: QLOG(0, "\tok: - 'T' - %s\n", PQcmdStatus(*pgres)); break; case PGRES_SINGLE_TUPLE: break; case PGRES_NONFATAL_ERROR: case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: default: handle_pgres_error(self->conn, *pgres, "read_tuples", self, TRUE); QR_set_rstatus(self, PORES_FATAL_ERROR); return FALSE; } nrows = PQntuples(*pgres); numTotalRows += nrows; for (rowno = 0; rowno < nrows; rowno++) { TupleField *this_tuplefield; KeySet *this_keyset = NULL; if (!QR_prepare_for_tupledata(self)) return FALSE; 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; } QLOG(TUPLE_LOG_LEVEL, "\t"); for (field_lf = 0; field_lf < ci_num_fields; field_lf++) { BOOL isnull = FALSE; isnull = PQgetisnull(*pgres, rowno, field_lf); if (isnull) { this_tuplefield[field_lf].len = 0; this_tuplefield[field_lf].value = 0; QPRINTF(TUPLE_LOG_LEVEL, " (null)"); continue; } else { len = PQgetlength(*pgres, rowno, field_lf); value = PQgetvalue(*pgres, rowno, field_lf); 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); } memcpy(buffer, value, len); buffer[len] = '\0'; QPRINTF(TUPLE_LOG_LEVEL, " '%s'(%d)", buffer, len); if (field_lf >= effective_cols) { if (NULL == this_keyset) { char emsg[128]; QR_set_rstatus(self, PORES_INTERNAL_ERROR); SPRINTF_FIXED(emsg, "Internal Error -- this_keyset == NULL ci_num_fields=%d effective_cols=%d", ci_num_fields, effective_cols); QR_set_message(self, emsg); return FALSE; } 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; } } } QPRINTF(TUPLE_LOG_LEVEL, "\n"); self->cursTuple++; if (self->num_fields > 0) { QR_inc_num_cache(self); } else if (QR_haskeyset(self)) self->num_cached_keys++; if (self->cursTuple >= self->num_total_read) self->num_total_read = self->cursTuple + 1; } if (resStatus == PGRES_SINGLE_TUPLE) { /* Process next row */ PQclear(*pgres); *pgres = PQgetResult(self->conn->pqconn); goto nextrow; } self->dataFilled = TRUE; self->tupleField = self->backend_tuples + (self->fetch_number * self->num_fields); MYLOG(DETAIL_LOG_LEVEL, "tupleField=%p\n", self->tupleField); QR_set_rstatus(self, PORES_TUPLES_OK); return TRUE; } int QR_search_by_fieldname(const QResultClass *self, const char *name) { int i; char *col_name; for (i = 0; i < QR_NumResultCols(self); i++) { col_name = QR_get_fieldname(self, i); if (strcmp(col_name, name) == 0) return i; } return -1; } psqlodbc-13.02.0000/results.c000644 001751 001751 00000416552 14122574536 016755 0ustar00hiroshihiroshi000000 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 * pcrow) { CSTR func = "PGAPI_RowCount"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; MYLOG(0, "entering...\n"); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } if (stmt->proc_return > 0) { *pcrow = 0; MYLOG(DETAIL_LOG_LEVEL, "returning RowCount=" FORMAT_LEN "\n", *pcrow); return SQL_SUCCESS; } res = SC_get_Curres(stmt); if (res) { 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(0, "**** THE ROWS: *pcrow = " FORMAT_LEN "\n", *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(0, "RowCount=" FORMAT_LEN "\n", *pcrow); return SQL_SUCCESS; } } return SQL_SUCCESS; } static BOOL SC_describe_ok(StatementClass *stmt, BOOL build_fi, int col_idx, const char *func) { Int2 num_fields; QResultClass *result; BOOL exec_ok = TRUE; num_fields = SC_describe(stmt); result = SC_get_ExecdOrParsed(stmt); MYLOG(0, "entering result = %p, status = %d, numcols = %d\n", 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; MYLOG(DETAIL_LOG_LEVEL, "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); MYLOG(DETAIL_LOG_LEVEL, "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 * pccol) { CSTR func = "PGAPI_NumResultCols"; StatementClass *stmt = (StatementClass *) hstmt; QResultClass *result; char parse_ok; RETCODE ret = SQL_SUCCESS; MYLOG(0, "entering...\n"); 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(0, "calling parse_statement on stmt=%p\n", stmt); parse_statement(stmt, FALSE); } if (SC_parsed_status(stmt) != STMT_PARSE_FATAL) { parse_ok = TRUE; *pccol = SC_get_IRDF(stmt)->nfields; MYLOG(0, "PARSE: *pccol = %d\n", *pccol); } } if (!parse_ok) { if (!SC_describe_ok(stmt, FALSE, -1, func)) { ret = SQL_ERROR; goto cleanup; } result = SC_get_ExecdOrParsed(stmt); *pccol = QR_NumPublicResultCols(result); } cleanup: #undef return return ret; } #define USE_FI(fi, unknown) (fi && UNKNOWNS_AS_LONGEST != unknown) /* * Return information about the database column the user wants * information about. */ RETCODE SQL_API PGAPI_DescribeCol(HSTMT hstmt, SQLUSMALLINT icol, SQLCHAR * szColName, SQLSMALLINT cbColNameMax, SQLSMALLINT * pcbColName, SQLSMALLINT * pfSqlType, SQLULEN * pcbColDef, SQLSMALLINT * pibScale, SQLSMALLINT * 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; int unknown_sizes; SQLINTEGER decimal_digits = 0; ConnInfo *ci; FIELD_INFO *fi; char buf[255]; int len = 0; RETCODE result = SQL_SUCCESS; MYLOG(0, "entering.%d..\n", icol); if (!stmt) { SC_log_error(func, NULL_STRING, NULL); return SQL_INVALID_HANDLE; } conn = SC_get_conn(stmt); ci = &(conn->connInfo); unknown_sizes = ci->drivers.unknown_sizes; SC_clear_error(stmt); #define return DONT_CALL_RETURN_FROM_HERE??? irdflds = SC_get_IRDF(stmt); if (0 == icol) /* bookmark column */ { SQLSMALLINT fType = stmt->options.use_bookmarks == SQL_UB_VARIABLE ? SQL_BINARY : SQL_INTEGER; MYLOG(DETAIL_LOG_LEVEL, "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; } /* * 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(0, "calling parse_statement on stmt=%p\n", stmt); parse_statement(stmt, FALSE); } MYLOG(0, "PARSE: 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(0, "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 = (NULL != pfNullable || NULL != pfSqlType); fi = NULL; if (!SC_describe_ok(stmt, build_fi, icol, func)) { result = SQL_ERROR; goto cleanup; } res = SC_get_ExecdOrParsed(stmt); if (icol >= QR_NumPublicResultCols(res)) { SC_set_error(stmt, STMT_INVALID_COLUMN_NUMBER_ERROR, "Invalid column number in DescribeCol.", func); SPRINTF_FIXED(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]; } res = SC_get_ExecdOrParsed(stmt); #ifdef SUPPRESS_LONGEST_ON_CURSORS if (UNKNOWNS_AS_LONGEST == unknown_sizes) { if (QR_once_reached_eof(res)) unknown_sizes = UNKNOWNS_AS_LONGEST; else unknown_sizes = UNKNOWNS_AS_MAX; } #endif /* SUPPRESS_LONGEST_ON_CURSORS */ /* handle constants */ if (res && -2 == QR_get_fieldsize(res, icol)) unknown_sizes = UNKNOWNS_AS_LONGEST; 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); if (USE_FI(fi, unknown_sizes)) { column_size = fi->column_size; decimal_digits = fi->decimal_digits; } else { column_size = pgtype_column_size(stmt, fieldtype, icol, unknown_sizes); decimal_digits = pgtype_decimal_digits(stmt, fieldtype, icol); } MYLOG(0, "PARSE: fieldtype=%u, col_name='%s', column_size=" FORMAT_LEN "\n", fieldtype, NULL_IF_NULL(col_name), column_size); } else { col_name = QR_get_fieldname(res, icol); fieldtype = QR_get_field_type(res, icol); column_size = pgtype_column_size(stmt, fieldtype, icol, unknown_sizes); decimal_digits = pgtype_decimal_digits(stmt, fieldtype, icol); } MYLOG(0, "col %d fieldname = '%s'\n", icol, NULL_IF_NULL(col_name)); MYLOG(0, "col %d fieldtype = %d\n", icol, fieldtype); MYLOG(0, "col %d column_size = " FORMAT_LEN "\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, unknown_sizes); MYLOG(0, "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(0, "Col: col %d *pcbColDef = " FORMAT_ULEN "\n", icol, *pcbColDef); } /* * DECIMAL DIGITS(SCALE in 2.x) */ if (pibScale) { if (decimal_digits < 0) decimal_digits = 0; *pibScale = (SQLSMALLINT) decimal_digits; MYLOG(0, "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(0, "col %d *pfNullable = %d\n", icol, *pfNullable); } cleanup: #undef return 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 * pcbDesc, SQLLEN * 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(0, "entering..col=%d %d len=%d.\n", 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_ExecdOrParsed(stmt); if (0 == icol && SQL_DESC_COUNT != fDescType) /* bookmark column */ { MYLOG(DETAIL_LOG_LEVEL, "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; } col_idx = icol - 1; unknown_sizes = ci->drivers.unknown_sizes; /* not appropriate for SQLColAttributes() */ if (stmt->catalog_result) unknown_sizes = UNKNOWNS_AS_LONGEST; 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(0, "calling parse_statement\n"); parse_statement(stmt, FALSE); } cols = irdflds->nfields; /* * Column Count is a special case. The Column number is ignored * in this case. */ if (fDescType == SQL_DESC_COUNT) { 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; 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: case SQL_DESC_NULLABLE: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_BASE_COLUMN_NAME: case SQL_COLUMN_UPDATABLE: case 1212: /* SQL_CA_SS_COLUMN_KEY ? */ build_fi = TRUE; break; } if (!SC_describe_ok(stmt, build_fi, col_idx, func)) return SQL_ERROR; res = SC_get_ExecdOrParsed(stmt); cols = QR_NumPublicResultCols(res); /* * Column Count is a special case. The Column number is ignored * in this case. */ if (fDescType == SQL_DESC_COUNT) { 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(0, "col %d field_type=%d fi,ti=%p,%p\n", col_idx, field_type, fi, ti); #ifdef SUPPRESS_LONGEST_ON_CURSORS if (UNKNOWNS_AS_LONGEST == unknown_sizes) { if (QR_once_reached_eof(res)) unknown_sizes = UNKNOWNS_AS_LONGEST; else unknown_sizes = UNKNOWNS_AS_MAX; } #endif /* SUPPRESS_LONGEST_ON_CURSORS */ /* handle constants */ if (res && -2 == QR_get_fieldsize(res, col_idx)) unknown_sizes = UNKNOWNS_AS_LONGEST; column_size = (USE_FI(fi, unknown_sizes) && 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(0, "AUTO_INCREMENT=" FORMAT_LEN "\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 = (USE_FI(fi, unknown_sizes) && 0 != fi->display_size) ? fi->display_size : pgtype_display_size(stmt, field_type, col_idx, unknown_sizes); MYLOG(0, "col %d, display_size= " FORMAT_LEN "\n", 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(0, "COLUMN_LABEL = '%s'\n", p); break; } /* otherwise same as column name -- FALL THROUGH!!! */ case SQL_DESC_NAME: MYLOG(DETAIL_LOG_LEVEL, "fi=%p (alias, name)=", fi); if (fi) MYPRINTF(DETAIL_LOG_LEVEL, "(%s,%s)\n", PRINT_NAME(fi->column_alias), PRINT_NAME(fi->column_name)); else MYPRINTF(DETAIL_LOG_LEVEL, "NULL\n"); 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(0, "COLUMN_NAME = '%s'\n", p); break; case SQL_COLUMN_LENGTH: value = (USE_FI(fi, unknown_sizes) && 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(0, "col %d, column_length = " FORMAT_LEN "\n", col_idx, value); break; case SQL_COLUMN_MONEY: /* == SQL_DESC_FIXED_PREC_SCALE */ value = pgtype_money(conn, field_type); MYLOG(DETAIL_LOG_LEVEL, "COLUMN_MONEY=" FORMAT_LEN "\n", value); break; case SQL_DESC_NULLABLE: if (SC_has_outer_join(stmt)) value = TRUE; else value = fi ? fi->nullable : pgtype_nullable(conn, field_type); MYLOG(DETAIL_LOG_LEVEL, "COLUMN_NULLABLE=" FORMAT_LEN "\n", value); break; case SQL_COLUMN_OWNER_NAME: /* == SQL_DESC_SCHEMA_NAME */ p = ti ? SAFE_NAME(ti->schema_name) : NULL_STRING; MYLOG(0, "SCHEMA_NAME = '%s'\n", p); break; case SQL_COLUMN_PRECISION: /* in 2.x */ value = column_size; if (value < 0) value = 0; MYLOG(0, "col %d, column_size = " FORMAT_LEN "\n", 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); MYLOG(DETAIL_LOG_LEVEL, "COLUMN_SCALE=" FORMAT_LEN "\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(0, "TABLE_NAME = '%s'\n", p); break; case SQL_COLUMN_TYPE: /* == SQL_DESC_CONCISE_TYPE */ value = pgtype_to_concise_type(stmt, field_type, col_idx, unknown_sizes); MYLOG(0, "COLUMN_TYPE=" FORMAT_LEN "\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 : SQL_ATTR_READONLY); 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_NAME) == 0) value = SQL_ATTR_READONLY; else if (conn->ms_jet && fi && fi->auto_increment) value = SQL_ATTR_READONLY; } MYLOG(0, "%s: UPDATEABLE = " FORMAT_LEN "\n", func, value); break; case SQL_DESC_BASE_COLUMN_NAME: p = fi ? SAFE_NAME(fi->column_name) : QR_get_fieldname(res, col_idx); MYLOG(0, "BASE_COLUMN_NAME = '%s'\n", p); break; case SQL_DESC_BASE_TABLE_NAME: /* the same as TABLE_NAME ok ? */ p = ti ? SAFE_NAME(ti->table_name) : NULL_STRING; MYLOG(0, "BASE_TABLE_NAME = '%s'\n", 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(0, "col %d, desc_length = " FORMAT_LEN "\n", col_idx, value); break; case SQL_DESC_OCTET_LENGTH: value = (USE_FI(fi, unknown_sizes) && fi->length > 0) ? fi->length : pgtype_attr_transfer_octet_length(conn, field_type, column_size, unknown_sizes); if (-1 == value) value = 0; MYLOG(0, "col %d, octet_length = " FORMAT_LEN "\n", 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(0, "col %d, desc_precision = " FORMAT_LEN "\n", 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, unknown_sizes); 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; 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(0, "SS_COLUMN_KEY=" FORMAT_LEN "\n", 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 * 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; #ifdef WITH_UNIXODBC SQLCHAR dum_rgb[2] = "\0\0"; #endif /* WITH_UNIXODBC */ MYLOG(0, "entering stmt=%p icol=%d\n", 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; } #ifdef WITH_UNIXODBC if (NULL == rgbValue) /* unixODBC allows rgbValue is NULL? */ { cbValueMax = 0; rgbValue = dum_rgb; /* to avoid a crash */ } #endif /* WITH_UNIXODBC */ 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(0, "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 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: case SQL_C_VARBOOKMARK: break; default: MYLOG(DETAIL_LOG_LEVEL, "GetData Column 0 is type %d not of type SQL_C_BOOKMARK\n", 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(0, " num_rows = " FORMAT_LEN "\n", num_rows); if (!get_bookmark) { SQLLEN curt = GIdx2CacheIdx(stmt->currTuple, stmt, res); value = QR_get_value_backend_row(res, curt, icol); MYLOG(DETAIL_LOG_LEVEL, "currT=" FORMAT_LEN " base=" FORMAT_LEN " rowset=" FORMAT_LEN "\n", stmt->currTuple, QR_get_rowstart_in_cache(res), SC_get_rowset_start(stmt)); MYLOG(0, " 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(0, " socket: value = '%s'\n", NULL_IF_NULL(value)); } if (get_bookmark) { BOOL contents_get = FALSE; if (rgbValue) { if (SQL_C_BOOKMARK == target_type || sizeof(UInt4) <= cbValueMax) { Int4 bookmark = SC_make_int4_bookmark(stmt->currTuple); contents_get = TRUE; memcpy(rgbValue, &bookmark, sizeof(bookmark)); } } if (pcbValue) *pcbValue = sizeof(Int4); 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(0, "**** icol = %d, target_type = %d, field_type = %d, value = '%s'\n", 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_INVALID_STRING_CONVERSION: /* invalid string */ SC_set_error(stmt, STMT_STRING_CONVERSION_ERROR, "invalid string conversion occured.", func); result = SQL_ERROR; 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 MYLOG(DETAIL_LOG_LEVEL, "leaving %d\n", 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(0, "entering stmt = %p, stmt->result= %p\n", 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_reqsize(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 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 */ MYLOG(DETAIL_LOG_LEVEL, "get " FORMAT_ULEN "th Valid data from " FORMAT_LEN " to %s [dlt=%d]", nth, sta, orientation == SQL_FETCH_PRIOR ? "backward" : "forward", res->dl_count); if (0 == res->dl_count) { MYPRINTF(DETAIL_LOG_LEVEL, "\n"); 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; SQLLEN delsta; if (SQL_FETCH_PRIOR == orientation) { *nearest = sta + 1 - nth; delsta = (-1); MYPRINTF(DETAIL_LOG_LEVEL, "deleted "); for (i = res->dl_count - 1; i >=0 && *nearest <= deleted[i]; i--) { MYPRINTF(DETAIL_LOG_LEVEL, "[" FORMAT_LEN "]=" FORMAT_LEN " ", i, deleted[i]); if (sta >= deleted[i]) { (*nearest)--; if (i > delsta) delsta = i; } } MYPRINTF(DETAIL_LOG_LEVEL, "nearest=" FORMAT_LEN "\n", *nearest); if (*nearest < 0) { *nearest = -1; count = sta - delsta; } else return nth; } else { MYPRINTF(DETAIL_LOG_LEVEL, "\n"); *nearest = sta - 1 + nth; delsta = res->dl_count; 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 (i < delsta) delsta = i; } } if (*nearest >= num_tuples) { *nearest = num_tuples; count = *nearest - sta + delsta - res->dl_count; } 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; MYPRINTF(DETAIL_LOG_LEVEL, " nearest=" FORMAT_LEN "\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; MYPRINTF(DETAIL_LOG_LEVEL, " nearest=" FORMAT_LEN "\n", *nearest); if (++count == nth) return count; } } *nearest = num_tuples; } MYPRINTF(DETAIL_LOG_LEVEL, " 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; } MYLOG(DETAIL_LOG_LEVEL, "BASE=" FORMAT_LEN " numb=" FORMAT_LEN " curr=" FORMAT_LEN " cursT=" FORMAT_LEN "\n", QR_get_rowstart_in_cache(res), res->num_cached_rows, self->currTuple, res->cursTuple); /* 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) \ { \ MYLOG(DETAIL_LOG_LEVEL, "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) \ { \ MYLOG(DETAIL_LOG_LEVEL, "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 * pcrow, SQLUSMALLINT * 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, rowset_end = (-1); RETCODE result = SQL_SUCCESS; char truncated, error, should_set_rowset_start = FALSE; SQLLEN currp; UWORD pstatus; BOOL currp_is_valid, reached_eof, useCursor; SQLLEN reqsize = rowsetSize; MYLOG(0, "entering stmt=%p rowsetSize=" FORMAT_LEN "\n", 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; MYLOG(DETAIL_LOG_LEVEL, "num_tuples=" FORMAT_LEN "\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) { int min_nth; SQLLEN bidx; 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(0, "SQL_FETCH_NEXT: num_tuples=" FORMAT_LEN ", currtuple=" FORMAT_LEN ", rowst=" FORMAT_LEN "\n", num_tuples, stmt->currTuple, rowset_start); break; case SQL_FETCH_PRIOR: MYLOG(0, "SQL_FETCH_PRIOR: num_tuples=" FORMAT_LEN ", currtuple=" FORMAT_LEN "\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 (rowset_start <= 0) { EXTFETCH_RETURN_BOF(stmt, res) } if (rowset_start >= num_tuples && 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, 0, TRUE); } else if (QR_haskeyset(res)) { rowset_end = rowset_start - 1; if (min_nth = getNthValid(res, rowset_end, SQL_FETCH_PRIOR, rowsetSize, &rowset_start), min_nth <= 0) { if (min_nth == 0) { EXTFETCH_RETURN_BOF(stmt, res) } else { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch prior and before the beginning", func); rowset_end = (-1); SC_set_rowset_start(stmt, 0, TRUE); } } else { should_set_rowset_start = TRUE; reqsize = rowset_end - rowset_start + 1; } } else if (rowset_start < rowsetSize) { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch prior from eof and before the beginning", func); SC_set_rowset_start(stmt, 0, TRUE); } else SC_inc_rowset_start(stmt, -rowsetSize); break; case SQL_FETCH_FIRST: MYLOG(0, "SQL_FETCH_FIRST: num_tuples=" FORMAT_LEN ", currtuple=" FORMAT_LEN "\n", num_tuples, stmt->currTuple); SC_set_rowset_start(stmt, 0, TRUE); break; case SQL_FETCH_LAST: MYLOG(0, "SQL_FETCH_LAST: num_tuples=" FORMAT_LEN ", currtuple=" FORMAT_LEN "\n", num_tuples, stmt->currTuple); if (!reached_eof) { QR_move_cursor_to_last(res, stmt); num_tuples = QR_get_num_total_tuples(res); } rowset_end = num_tuples - 1; if (min_nth = getNthValid(res, rowset_end, SQL_FETCH_PRIOR, rowsetSize, &rowset_start), min_nth <= 0) { if (min_nth == 0) { EXTFETCH_RETURN_BOF(stmt, res) } else { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch last and before the beginning", func); rowset_end = (-1); SC_set_rowset_start(stmt, 0, TRUE); } } else { should_set_rowset_start = TRUE; reqsize = rowset_end - rowset_start + 1; } break; case SQL_FETCH_ABSOLUTE: MYLOG(0, "SQL_FETCH_ABSOLUTE: num_tuples=" FORMAT_LEN ", currtuple=" FORMAT_LEN ", irow=" FORMAT_LEN "\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 (!reached_eof) { QR_move_cursor_to_last(res, stmt); num_tuples = QR_get_num_total_tuples(res); } if (min_nth = getNthValid(res, num_tuples - 1, SQL_FETCH_PRIOR, -irow, &rowset_start), min_nth <= 0) { if (min_nth == 0) { EXTFETCH_RETURN_BOF(stmt, res) } else { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch absolute and before the beginning", func); rowset_end = (-1); SC_set_rowset_start(stmt, 0, TRUE); } } else 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 (min_nth = getNthValid(res, SC_get_rowset_start(stmt) - 1, SQL_FETCH_PRIOR, -irow, &rowset_start), min_nth <= 0) { if (min_nth == 0) EXTFETCH_RETURN_BOF(stmt, res) else { SC_set_error(stmt, STMT_POS_BEFORE_RECORDSET, "fetch relative and before the beginning", func); rowset_end = (-1); SC_set_rowset_start(stmt, 0, TRUE); } } else should_set_rowset_start = TRUE; } break; case SQL_FETCH_BOOKMARK: bidx = SC_resolve_int4_bookmark(irow); if (bidx < 0) { if (!reached_eof) { QR_move_cursor_to_last(res, stmt); num_tuples = QR_get_num_total_tuples(res); } 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??? /* set the rowset_start if needed */ if (should_set_rowset_start) SC_set_rowset_start(stmt, rowset_start, TRUE); if (rowset_end < 0 && QR_haskeyset(res)) { getNthValid(res, rowset_start, SQL_FETCH_NEXT, rowsetSize, &rowset_end); reqsize = rowset_end - rowset_start + 1; } QR_set_reqsize(res, (Int4) reqsize); /* 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; if (SQL_CURSOR_KEYSET_DRIVEN == stmt->options.cursor_type) { if (fFetchType != SQL_FETCH_NEXT || QR_get_rowstart_in_cache(res) + reqsize > QR_get_num_cached_tuples(res)) { flag = 1; } } if (SQL_RD_ON == stmt->options.retrieve_data || flag != 0) { RETCODE ret = SC_pos_reload_needed(stmt, reqsize, flag); if (!SQL_SUCCEEDED(ret)) { result = ret; goto cleanup; } } } /* Physical Row advancement occurs for each row fetched below */ MYLOG(0, "new currTuple = " FORMAT_LEN "\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); MYLOG(DETAIL_LOG_LEVEL, "currp=" FORMAT_LEN "\n", currp); if (currp < 0) { result = SQL_ERROR; MYLOG(0, "rowset_start=" FORMAT_LEN " but currp=" FORMAT_LEN "\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(0, "Umm current row is out of keyset\n"); break; } } MYLOG(DETAIL_LOG_LEVEL, "ExtFetch result=%d\n", result); if (currp_is_valid && SQL_SUCCESS_WITH_INFO == result && 0 == stmt->last_fetch_count) { MYLOG(DETAIL_LOG_LEVEL, "just skipping deleted row " FORMAT_LEN "\n", currp); if (rowsetSize - i + fc_io > reqsize) QR_set_reqsize(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; MYLOG(DETAIL_LOG_LEVEL, "pcrow=" FORMAT_LEN "\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 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) { StatementClass *stmt = (StatementClass *) hstmt; QResultClass *res; RETCODE ret = SQL_SUCCESS; MYLOG(0, "entering...\n"); res = SC_get_Curres(stmt); if (res) { res = QR_nextr(res); SC_set_Curres(stmt, res); } if (res) { SQLSMALLINT num_p; int errnum = 0, curerr; 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; if (!QR_command_maybe_successful(res)) { ret = SQL_ERROR; errnum = STMT_EXEC_ERROR; } else if (NULL != QR_get_notice(res)) { ret = SQL_SUCCESS_WITH_INFO; errnum = STMT_INFO_ONLY; } if (0 != errnum) { curerr = SC_get_errornumber(stmt); if (0 == curerr || (0 > curerr && errnum > 0)) SC_set_errornumber(stmt, errnum); } } else { PGAPI_FreeStmt(hstmt, SQL_CLOSE); ret = SQL_NO_DATA_FOUND; } MYLOG(0, "leaving %d\n", 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, BOOL statusInit) { if (statusInit) keyset->status = 0; sscanf(tuple[num_fields - num_key_fields].value, "(%u,%hu)", &keyset->blocknum, &keyset->offset); if (num_key_fields > 1) { const char *oval = tuple[num_fields - 1].value; if ('-' == oval[0]) sscanf(oval, "%d", &keyset->oid); else sscanf(oval, "%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; MYLOG(DETAIL_LOG_LEVEL, "entering " FORMAT_LEN "(%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); if (!rollback) { res->rb_alloc = res->rb_count = 0; return; } } 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; rollback->oid = 0; if (keyset) { rollback->blocknum = keyset->blocknum; rollback->offset = keyset->offset; rollback->oid = keyset->oid; } 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) { MYLOG(DETAIL_LOG_LEVEL, "freeing tuple[" FORMAT_LEN "][" FORMAT_LEN "].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; MYLOG(DETAIL_LOG_LEVEL, "entering %p num_fields=%d num_rows=" FORMAT_LEN "\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); MYLOG(DETAIL_LOG_LEVEL, "[" FORMAT_LEN "," FORMAT_LEN "] %s copied\n", i / num_fields, i % num_fields, (const char *) otuple->value); } if (otuple->value) otuple->len = ituple->len; else otuple->len = -1; } return i; } static int MoveCachedRows(TupleField *otuple, TupleField *ituple, Int2 num_fields, SQLLEN num_rows) { int i; MYLOG(DETAIL_LOG_LEVEL, "entering %p num_fields=%d num_rows=" FORMAT_LEN "\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; MYLOG(DETAIL_LOG_LEVEL, "[%d,%d] %s copied\n", i / num_fields, i % num_fields, (const char *) otuple->value); } otuple->len = ituple->len; ituple->len = -1; } return i; } static const char * ti_quote(StatementClass *stmt, OID tableoid, char *buf, int buf_size) { TABLE_INFO *ti = stmt->ti[0]; pgNAME rNAME; if (0 == tableoid || !TI_has_subclass(ti)) return quote_table(ti->schema_name, ti->table_name, buf, buf_size); else if (NAME_IS_VALID(rNAME = TI_From_IH(ti, tableoid))) return SAFE_NAME(rNAME); else { char query[200]; QResultClass *res; char *ret = ""; SPRINTF_FIXED(query, "select relname, nspname from pg_class c, pg_namespace n where c.oid=%u and c.relnamespace=n.oid", tableoid); res = CC_send_query(SC_get_conn(stmt), query, NULL, READ_ONLY_QUERY, stmt); if (QR_command_maybe_successful(res) && QR_get_num_cached_tuples(res) == 1) { pgNAME schema_name, table_name; SET_NAME_DIRECTLY(schema_name, QR_get_value_backend_text(res, 0, 1)); SET_NAME_DIRECTLY(table_name, QR_get_value_backend_text(res, 0, 0)); ret = quote_table(schema_name, table_name, buf, buf_size); TI_Ins_IH(ti, tableoid, ret); } QR_Destructor(res); return ret; } } static BOOL tupleExists(StatementClass *stmt, const KeySet *keyset) { PQExpBufferData selstr = {0}; const TABLE_INFO *ti = stmt->ti[0]; QResultClass *res; RETCODE ret = FALSE; const char *bestqual = GET_NAME(ti->bestqual); char table_fqn[256]; initPQExpBuffer(&selstr); printfPQExpBuffer(&selstr, "select 1 from %s where ctid = '(%u,%u)'", ti_quote(stmt, keyset->oid, table_fqn, sizeof(table_fqn)), keyset->blocknum, keyset->offset); if (NULL != bestqual && 0 != keyset->oid && !TI_has_subclass(ti)) { appendPQExpBuffer(&selstr, " and "); appendPQExpBuffer(&selstr, bestqual, keyset->oid); } if (PQExpBufferDataBroken(selstr)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in tupleExists()", __FUNCTION__); goto cleanup; } res = CC_send_query(SC_get_conn(stmt), selstr.data, NULL, READ_ONLY_QUERY, NULL); if (QR_command_maybe_successful(res) && 1 == res->num_cached_rows) ret = TRUE; QR_Destructor(res); cleanup: if (!PQExpBufferDataBroken(selstr)) termPQExpBuffer(&selstr); 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; MYLOG(DETAIL_LOG_LEVEL, "entering index=" FORMAT_LEN ", 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, TRUE); 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(0, "entering index=" FORMAT_LEN "\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(0, "removed=1 count=%d\n", res->ad_count); } static void CommitAdded(QResultClass *res) { KeySet *added_keyset; int i; UWORD status; MYLOG(0, "entering 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) { MYLOG(DETAIL_LOG_LEVEL, "!!Commit Added=" FORMAT_ULEN "(%d)\n", QR_get_num_total_read(res) + i, i); added_keyset[i].status = status; } } } static int AddDeleted(QResultClass *res, SQLULEN index, const KeySet *keyset) { int i; Int2 dl_count, new_alloc; SQLLEN *deleted; KeySet *deleted_keyset; UWORD status; MYLOG(DETAIL_LOG_LEVEL, "entering " FORMAT_ULEN "\n", index); 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++) { 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(0, "entering index=" FORMAT_LEN "\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(0, "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) { MYLOG(DETAIL_LOG_LEVEL, "Deleted=" FORMAT_LEN "(%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, const KeySet *keyset, const TupleField *tuple_updated) { QResultClass *res; SQLLEN *updated; KeySet *updated_keyset; TupleField *updated_tuples = NULL, *tuple; /* SQLLEN res_ridx; */ UInt2 up_count; BOOL is_in_trans; SQLLEN upd_idx, upd_add_idx; Int2 num_fields; int i; UWORD status; MYLOG(DETAIL_LOG_LEVEL, "entering index=" FORMAT_LEN "\n", index); if (!stmt) return; if (res = SC_get_Curres(stmt), !res) return; if (!keyset) return; 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; /* res_ridx = GIdx2CacheIdx(index, stmt, res); if (res_ridx >= 0 && res_ridx < QR_get_num_cached_tuples(res)) tuple_updated = res->backend_tuples + res_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(0, "up_count=%d\n", res->up_count); } static void RemoveUpdated(QResultClass *res, SQLLEN index) { MYLOG(0, "entering index=" FORMAT_LEN "\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(0, "entering " FORMAT_LEN ",(%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(0, "removed count=%d,%d\n", rm_count, res->up_count); } static void CommitUpdated(QResultClass *res) { KeySet *updated_keyset; int i; UWORD status; MYLOG(0, "entering 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) { MYLOG(DETAIL_LOG_LEVEL, "!!Commit Updated=" FORMAT_LEN "(%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; MYLOG(DETAIL_LOG_LEVEL, "entering\n"); 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; int rollbps; int doubtp; int j; MYLOG(DETAIL_LOG_LEVEL, " "); for (i = 0, doubtp = 0; i < res->rb_count; i++) { keys.status = 0; keys.blocknum = rollback[i].blocknum; keys.offset = rollback[i].offset; keys.oid = rollback[i].oid; texist = tupleExists(stmt, &keys); MYPRINTF(DETAIL_LOG_LEVEL, "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; } MYPRINTF(DETAIL_LOG_LEVEL, " (doubtp=%d)", doubtp); } rollbp = i; MYPRINTF(DETAIL_LOG_LEVEL, " doubtp=%d,rollbp=%d\n", doubtp, rollbp); do { rollbps = rollbp; for (i = doubtp; i < rollbp; i++) { index = rollback[i].index; if (SQL_ADD == rollback[i].option) { MYLOG(DETAIL_LOG_LEVEL, "index[%d]=" FORMAT_LEN "\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; } MYLOG(DETAIL_LOG_LEVEL, "pidx=" FORMAT_LEN ",midx=" FORMAT_LEN "\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) { MYLOG(DETAIL_LOG_LEVEL, "delete[%d].index=" FORMAT_LEN "\n", j, rollback[j].index); break; } /*else if (SQL_UPDATE == rollback[j].option) { MYLOG(DETAIL_LOG_LEVEL, "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); } MYLOG(DETAIL_LOG_LEVEL, "rollbp=%d\n", rollbp); for (i = res->rb_count - 1; i >= rollbp; i--) { MYLOG(DETAIL_LOG_LEVEL, "do %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.status = 0; keys.blocknum = rollback[i].blocknum; keys.offset = rollback[i].offset; keys.oid = rollback[i].oid; /* RemoveUpdatedAfterTheKey(res, index, &keys); is no longer needed? */ RemoveUpdated(res, 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; wkey = keyset + kres_ridx; status = wkey->status; } } MYLOG(DETAIL_LOG_LEVEL, " index=" FORMAT_LEN " 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 { MYPRINTF(DETAIL_LOG_LEVEL, " (%u, %u)", wkey->blocknum, wkey->offset); wkey->blocknum = rollback[i].blocknum; wkey->offset = rollback[i].offset; wkey->oid = rollback[i].oid; MYPRINTF(DETAIL_LOG_LEVEL, "->(%u, %u)", 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]; Oid oid = wkey->oid; SPRINTF_FIXED(tidval, "(%u,%u)", wkey->blocknum, wkey->offset); qres = positioned_load(stmt, 0, &oid, 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); } } } } MYPRINTF(DETAIL_LOG_LEVEL, "\n"); 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 = QR_nextr(res)) { 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"; QResultClass *qres = NULL; PQExpBufferData selstr = {0}; BOOL latest = ((flag & LATEST_TUPLE_LOAD) != 0); TABLE_INFO *ti = stmt->ti[0]; const char *bestqual = GET_NAME(ti->bestqual); const ssize_t from_pos = stmt->load_from_pos; const char *load_stmt = stmt->load_statement; MYLOG(DETAIL_LOG_LEVEL, "entering bestitem=%s bestqual=%s\n", SAFE_NAME(ti->bestitem), SAFE_NAME(ti->bestqual)); initPQExpBuffer(&selstr); #define return DONT_CALL_RETURN_FROM_HERE??? if (TI_has_subclass(ti)) { OID tableoid = *oidint; char table_fqn[256]; const char *quoted_table; quoted_table = ti_quote(stmt, tableoid, table_fqn, sizeof(table_fqn)); if (tidval) { if (latest) { printfPQExpBuffer(&selstr, "%.*sfrom %s where ctid = (select currtid2('%s', '%s'))", (int) from_pos, load_stmt, quoted_table, quoted_table, tidval); } else printfPQExpBuffer(&selstr, "%.*sfrom %s where ctid = '%s'", (int) from_pos, load_stmt, quoted_table, tidval); } else if ((flag & USE_INSERTED_TID) != 0) printfPQExpBuffer(&selstr, "%.*sfrom %s where ctid = (select currtid(0, '(0,0)'))", (int) from_pos, load_stmt, quoted_table); /* else if (bestitem && oidint) { } */ else { SC_set_error(stmt,STMT_INTERNAL_ERROR, "can't find added and updating row because of the lack of oid", func); goto cleanup; } } else { CSTR andqual = " and "; BOOL andExist = TRUE; if (tidval) { if (latest) { char table_fqn[256]; printfPQExpBuffer(&selstr, "%s where ctid = (select currtid2('%s', '%s'))", load_stmt, ti_quote(stmt, 0, table_fqn, sizeof(table_fqn)), tidval); } else printfPQExpBuffer(&selstr, "%s where ctid = '%s'", load_stmt, tidval); } else if ((flag & USE_INSERTED_TID) != 0) printfPQExpBuffer(&selstr, "%s where ctid = (select currtid(0, '(0,0)'))", load_stmt); else if (bestqual) { andExist = FALSE; printfPQExpBuffer(&selstr, "%s where ", load_stmt); } else { SC_set_error(stmt,STMT_INTERNAL_ERROR, "can't find added and updating row because of the lack of oid", func); goto cleanup; } if (bestqual && oidint) { if (andExist) appendPQExpBufferStr(&selstr, andqual); appendPQExpBuffer(&selstr, bestqual, *oidint); } } if (PQExpBufferDataBroken(selstr)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory positioned_load()", func); goto cleanup; } MYLOG(0, "selstr=%s\n", selstr.data); qres = CC_send_query(SC_get_conn(stmt), selstr.data, NULL, READ_ONLY_QUERY, stmt); cleanup: #undef return if (!PQExpBufferDataBroken(selstr)) termPQExpBuffer(&selstr); return qres; } BOOL QR_get_last_bookmark(const QResultClass *res, Int4 index, KeySet *keyset) { int i; if (res->dl_count > 0 && res->deleted) { for (i = 0; i < res->dl_count; i++) { if (res->deleted[i] == index) { *keyset = res->deleted_keyset[i]; return TRUE; } if (res->deleted[i] > index) break; } } if (res->up_count > 0 && res->updated) { for (i = res->up_count - 1; i >= 0; i--) { if (res->updated[i] == index) { *keyset = res->updated_keyset[i]; return TRUE; } } } return FALSE; } static RETCODE SC_pos_reload_with_key(StatementClass *stmt, SQLULEN global_ridx, UInt2 *count, Int4 logKind, const KeySet *keyset) { CSTR func = "SC_pos_reload_with_key"; int res_cols; UInt2 rcnt; SQLLEN kres_ridx; OID oidint; QResultClass *res, *qres; IRDFields *irdflds = SC_get_IRDF(stmt); RETCODE ret = SQL_ERROR; char tidval[32]; BOOL use_ctid = TRUE; BOOL idx_exist = TRUE; MYLOG(0, "entering 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; } kres_ridx = GIdx2KResIdx(global_ridx, stmt, res); if (kres_ridx < 0 || kres_ridx >= res->num_cached_keys) { if (NULL == keyset || keyset->offset == 0) { SC_set_error(stmt, STMT_ROW_OUT_OF_RANGE, "the target keys are out of the rowset", func); return SQL_ERROR; } idx_exist = FALSE; } else if (0 != (res->keyset[kres_ridx].status & CURS_SELF_ADDING)) { if (NULL == keyset || keyset->offset == 0) { use_ctid = FALSE; MYLOG(0, "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; } /* old oid & tid */ if (idx_exist) { UInt4 blocknum; UInt2 offset; 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); SPRINTF_FIXED(tidval, "(%u, %u)", blocknum, offset); } res_cols = getNumResultCols(res); if (keyset) /* after or update */ { char tid[32]; oidint = keyset->oid; SPRINTF_FIXED(tid, "(%u,%hu)", keyset->blocknum, keyset->offset); qres = positioned_load(stmt, 0, &oidint, tid); } else { if (use_ctid) qres = positioned_load(stmt, LATEST_TUPLE_LOAD, &oidint, tidval); else qres = positioned_load(stmt, 0, &oidint, NULL); keyset = res->keyset + kres_ridx; } 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 if (rcnt = (UInt2) QR_get_num_cached_tuples(qres), rcnt == 1) { SQLLEN res_ridx; switch (logKind) { case 0: case SQL_FETCH_BY_BOOKMARK: break; case SQL_UPDATE: AddUpdated(stmt, global_ridx, keyset, qres->tupleField); break; default: AddRollback(stmt, res, global_ridx, keyset, logKind); } res_ridx = GIdx2CacheIdx(global_ridx, stmt, res); if (res_ridx >= 0 && res_ridx < QR_get_num_cached_tuples(res)) { TupleField *tuple_old, *tuple_new; int effective_fields = res_cols; tuple_old = res->backend_tuples + res->num_fields * res_ridx; QR_set_position(qres, 0); tuple_new = qres->tupleField; 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, FALSE); MoveCachedRows(tuple_old, tuple_new, effective_fields, 1); } if (rcnt > 1) { ret = SQL_SUCCESS_WITH_INFO; SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "more than one row were update/deleted?", func); } else 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; AddRollback(stmt, res, global_ridx, keyset, logKind); if (idx_exist) { 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_key(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; OID oid; UInt4 blocknum; SQLLEN kres_ridx; UInt2 offset; PQExpBufferData qval = {0}; int keys_per_fetch = 10; #define return DONT_CALL_RETURN_FROM_HERE??? for (i = SC_get_rowset_start(stmt), kres_ridx = GIdx2KResIdx(i, stmt, res), rowc = 0;; i++, kres_ridx++) { if (i >= limitrow) { if (!rowc) break; if (res->reload_count > 0) { for (j = rowc; j < keys_per_fetch; j++) { appendPQExpBufferStr(&qval, j ? ",NULL" : "NULL"); } } rowc = -1; /* end of loop */ } if (rowc < 0 || rowc >= keys_per_fetch) { QResultClass *qres; appendPQExpBufferStr(&qval, ")"); if (PQExpBufferDataBroken(qval)) { rcnt = -1; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in LoadFromKeyset()", func); goto cleanup; } qres = CC_send_query(conn, qval.data, NULL, CREATE_KEYSET | READ_ONLY_QUERY, stmt); if (QR_command_maybe_successful(qres)) { SQLLEN j, k, l; Int2 m; TupleField *tuple, *tuplew; UInt4 bln; UInt2 off; 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++) { getTid(res, k, &bln, &off); if (oid == getOid(res, k) && bln == blocknum && off == offset) { 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) { if (PQExpBufferDataBroken(qval)) { initPQExpBuffer(&qval); 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; SPRINTF_FIXED(planname, "_KEYSET_%p", res); printfPQExpBuffer(&qval, "PREPARE \"%s\"", planname); for (j = 0; j < keys_per_fetch; j++) { appendPQExpBufferStr(&qval, j ? ",tid" : "(tid"); } appendPQExpBuffer(&qval, ") as %s where ctid in ", stmt->load_statement); for (j = 0; j < keys_per_fetch; j++) { if (j == 0) appendPQExpBufferStr(&qval, "($1"); else appendPQExpBuffer(&qval, ",$%d", j + 1); } appendPQExpBufferStr(&qval, ")"); if (PQExpBufferDataBroken(qval)) { rcnt = -1; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in LoadFromKeyset()", func); goto cleanup; } qres = CC_send_query(conn, qval.data, NULL, READ_ONLY_QUERY, 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; SC_set_Result(stmt, qres); break; } QR_Destructor(qres); } } if (res->reload_count > 0) { printfPQExpBuffer(&qval, "EXECUTE \"_KEYSET_%p\"(", res); } else { printfPQExpBuffer(&qval, "%s where ctid in (", stmt->load_statement); } } if (rcnt >= 0 && 0 != (res->keyset[kres_ridx].status & CURS_NEEDS_REREAD)) { getTid(res, kres_ridx, &blocknum, &offset); if (rowc) appendPQExpBuffer(&qval, ",'(%u,%u)'", blocknum, offset); else appendPQExpBuffer(&qval, "'(%u,%u)'", blocknum, offset); rowc++; rcnt++; } } cleanup: #undef return if (!PQExpBufferDataBroken(qval)) termPQExpBuffer(&qval); return rcnt; } static SQLLEN LoadFromKeyset_inh(StatementClass *stmt, QResultClass * res, int rows_per_fetch, SQLLEN limitrow) { ConnectionClass *conn = SC_get_conn(stmt); SQLLEN i; int j, rowc, rcnt = 0; OID oid, new_oid; UInt4 blocknum; SQLLEN kres_ridx; UInt2 offset; PQExpBufferData qval = {0}; int keys_per_fetch = 10; const char *load_stmt = stmt->load_statement; const ssize_t from_pos = stmt->load_from_pos; MYLOG(0, "entering in rows_per_fetch=%d limitrow=" FORMAT_LEN "\n", rows_per_fetch, limitrow); new_oid = 0; #define return DONT_CALL_RETURN_FROM_HERE??? for (i = SC_get_rowset_start(stmt), kres_ridx = GIdx2KResIdx(i, stmt, res), rowc = 0, oid = 0;; i++, kres_ridx++) { if (i >= limitrow) { if (!rowc) break; rowc = -1; /* end of loop */ } else if (0 == (res->keyset[kres_ridx].status & CURS_NEEDS_REREAD)) continue; else new_oid = getOid(res, kres_ridx); if (rowc < 0 || rowc >= keys_per_fetch || (oid != 0 && new_oid != oid)) { QResultClass *qres; appendPQExpBufferStr(&qval, ")"); if (PQExpBufferDataBroken(qval)) { rcnt = -1; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in LoadFromKeyset_inh()", __FUNCTION__); goto cleanup; } qres = CC_send_query(conn, qval.data, NULL, CREATE_KEYSET | READ_ONLY_QUERY, stmt); if (QR_command_maybe_successful(qres)) { SQLLEN k, l; Int2 m; TupleField *tuple, *tuplew; UInt4 bln; UInt2 off; OID tbloid; for (j = 0; j < QR_get_num_total_read(qres); j++) { tbloid = getOid(qres, j); getTid(qres, j, &blocknum, &offset); for (k = SC_get_rowset_start(stmt); k < limitrow; k++) { getTid(res, k, &bln, &off); if (tbloid == getOid(res, k) && bln == blocknum && off == offset) { 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", __FUNCTION__); rcnt = -1; SC_set_Result(stmt, qres); break; } QR_Destructor(qres); if (rowc < 0) break; rowc = 0; } if (!rowc) { char table_fqn[256]; if (PQExpBufferDataBroken(qval)) { 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; initPQExpBuffer(&qval); } printfPQExpBuffer(&qval, "%.*sfrom %s where ctid in (", (int) from_pos, load_stmt, ti_quote(stmt, new_oid, table_fqn, sizeof(table_fqn))); } if (new_oid != oid) oid = new_oid; getTid(res, kres_ridx, &blocknum, &offset); if (rowc) appendPQExpBuffer(&qval, ",'(%u,%u)'", blocknum, offset); else appendPQExpBuffer(&qval, "'(%u,%u)'", blocknum, offset); rowc++; rcnt++; } cleanup: #undef return if (!PQExpBufferDataBroken(qval)) termPQExpBuffer(&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(0, "entering\n"); #define return DONT_CALL_RETURN_FROM_HERE??? if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_pos_reload_needed.", func); goto cleanup; } 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); goto cleanup; } 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_gexit_with_error(res->backend_tuples, TupleField, sizeof(TupleField) * res->num_fields * brows, res, "pos_reload_needed failed", ret = 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) { ret = SQL_SUCCESS; goto cleanup; } 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 (TI_has_subclass(stmt->ti[0])) { if (rowc = LoadFromKeyset_inh(stmt, res, rows_per_fetch, limitrow), rowc < 0) { goto cleanup; } } else if (rowc = LoadFromKeyset(stmt, res, rows_per_fetch, limitrow), rowc < 0) { goto cleanup; } 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) { goto cleanup; } 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; } } ret = SQL_SUCCESS; res->dataFilled = TRUE; cleanup: #undef return 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(0, "entering 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 { MYLOG(DETAIL_LOG_LEVEL, "total " FORMAT_LEN " <> backend " FORMAT_LEN " - base " FORMAT_LEN " + start " FORMAT_LEN " cursor_type=" FORMAT_UINTEGER "\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, TRUE); res->num_cached_keys++; } if (appendData) { MYLOG(DETAIL_LOG_LEVEL, "total " FORMAT_LEN " == backend " FORMAT_LEN " - base " FORMAT_LEN " + start " FORMAT_LEN " cursor_type=" FORMAT_UINTEGER "\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->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, SQLULEN global_ridx, const KeySet *old_keyset) { 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) { KeySet keys; if (NULL != tres->backend_tuples && 1 == QR_get_num_cached_tuples(tres)) { KeySetSet(tres->backend_tuples, QR_NumResultCols(tres), QR_NumResultCols(tres), &keys, TRUE); if (SQL_SUCCEEDED(ret = SC_pos_reload_with_key(stmt, global_ridx, (UInt2 *) 0, SQL_UPDATE, &keys))) AddRollback(stmt, SC_get_Curres(stmt), global_ridx, old_keyset, SQL_UPDATE); } else ret = SQL_ERROR; } else if (updcnt == 0) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the content was changed before updates", func); ret = SQL_SUCCESS_WITH_INFO; 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; KeySet old_keyset; } pup_cdata; static RETCODE pos_update_callback(RETCODE retcode, void *para) { RETCODE ret = retcode; pup_cdata *s = (pup_cdata *) para; SQLLEN kres_ridx; BOOL idx_exist = TRUE; if (s->updyes) { MYLOG(0, "entering\n"); ret = irow_update(ret, s->stmt, s->qstmt, s->global_ridx, &s->old_keyset); MYLOG(DETAIL_LOG_LEVEL, "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) { idx_exist = FALSE; } if (SQL_SUCCESS == ret && s->res->keyset && idx_exist) { 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 (s->irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_UPDATED; break; case SQL_NO_DATA_FOUND: case SQL_SUCCESS_WITH_INFO: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_SUCCESS_WITH_INFO; ret = SQL_SUCCESS_WITH_INFO; break; case SQL_ERROR: default: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_ERROR; } } return ret; } RETCODE SC_pos_update(StatementClass *stmt, SQLSETPOSIROW irow, SQLULEN global_ridx, const KeySet *keyset) { 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; PQExpBufferData updstr = {0}; RETCODE ret = SQL_ERROR; OID oid; UInt4 blocknum; UInt2 pgoffset; SQLLEN offset; SQLLEN *used, kres_ridx; Int4 bind_size = opts->bind_size; BOOL idx_exist = TRUE; char table_fqn[256]; 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(0, "entering " FORMAT_POSIROW "+" FORMAT_LEN " 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) { if (NULL == keyset || keyset->offset == 0) { SC_set_error(s.stmt, STMT_ROW_OUT_OF_RANGE, "the target keys are out of the rowset", func); return SQL_ERROR; } idx_exist = FALSE; } if (idx_exist) { 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); s.old_keyset = s.res->keyset[kres_ridx]; } else { oid = keyset->oid; blocknum = keyset->blocknum; pgoffset = keyset->offset; s.old_keyset = *keyset; } ti = s.stmt->ti[0]; initPQExpBuffer(&updstr); #define return DONT_CALL_RETURN_FROM_HERE??? printfPQExpBuffer(&updstr, "update %s set", ti_quote(stmt, oid, table_fqn, sizeof(table_fqn))); 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(0, "%d used=" FORMAT_LEN ",%p\n", i, *used, used); if (*used != SQL_IGNORE && fi[i]->updatable) { if (upd_cols) appendPQExpBuffer(&updstr, ", \"%s\" = ?", GET_NAME(fi[i]->column_name)); else appendPQExpBuffer(&updstr, " \"%s\" = ?", GET_NAME(fi[i]->column_name)); upd_cols++; } } else MYLOG(0, "%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); int unknown_sizes = ci->drivers.unknown_sizes; appendPQExpBuffer(&updstr, " where ctid = '(%u, %u)'", blocknum, pgoffset); if (bestqual) { appendPQExpBuffer(&updstr, " and "); appendPQExpBuffer(&updstr, bestqual, oid); } if (PG_VERSION_GE(conn, 8.2)) { appendPQExpBuffer(&updstr, " returning ctid"); if (bestitem) { appendPQExpBuffer(&updstr, ", "); appendPQExpBuffer(&updstr, "\"%s\"", bestitem); } } MYLOG(0, "updstr=%s\n", updstr.data); if (PGAPI_AllocStmt(conn, &hstmt, 0) != SQL_SUCCESS) { SC_set_error(s.stmt, STMT_NO_MEMORY_ERROR, "internal AllocStmt error", func); goto cleanup; } 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(0, "%d used=" FORMAT_LEN "\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, unknown_sizes), fi[i]->column_size > 0 ? fi[i]->column_size : pgtype_column_size(s.stmt, fieldtype, i, 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; if (PQExpBufferDataBroken(updstr)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in SC_pos_updatet()", func); goto cleanup; } ret = PGAPI_ExecDirect(hstmt, (SQLCHAR *) updstr.data, SQL_NTS, 0); if (ret == SQL_NEED_DATA) { pup_cdata *cbdata = (pup_cdata *) malloc(sizeof(pup_cdata)); if (!cbdata) { SC_set_error(s.stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for cbdata", func); ret = SQL_ERROR; goto cleanup; } memcpy(cbdata, &s, sizeof(pup_cdata)); if (0 == enqueueNeedDataCallback(s.stmt, pos_update_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, "update list null", func); } ret = pos_update_callback(ret, &s); cleanup: #undef return if (!PQExpBufferDataBroken(updstr)) termPQExpBuffer(&updstr); return ret; } RETCODE SC_pos_delete(StatementClass *stmt, SQLSETPOSIROW irow, SQLULEN global_ridx, const KeySet *keyset) { CSTR func = "SC_pos_update"; UWORD offset; QResultClass *res, *qres; ConnectionClass *conn = SC_get_conn(stmt); IRDFields *irdflds = SC_get_IRDF(stmt); PQExpBufferData dltstr = {0}; RETCODE ret; SQLLEN kres_ridx; OID oid; UInt4 blocknum, qflag; TABLE_INFO *ti; const char *bestitem; const char *bestqual; BOOL idx_exist = TRUE; char table_fqn[256]; MYLOG(0, "entering 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) { if (NULL == keyset || keyset->offset == 0) { SC_set_error(stmt, STMT_ROW_OUT_OF_RANGE, "the target keys are out of the rowset", func); return SQL_ERROR; } idx_exist = FALSE; } ti = stmt->ti[0]; bestitem = GET_NAME(ti->bestitem); bestqual = GET_NAME(ti->bestqual); if (idx_exist) { 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; } } getTid(res, kres_ridx, &blocknum, &offset); keyset = res->keyset + kres_ridx; } else { oid = keyset->oid; blocknum = keyset->blocknum; offset = keyset->offset; } initPQExpBuffer(&dltstr); #define return DONT_CALL_RETURN_FROM_HERE??? printfPQExpBuffer(&dltstr, "delete from %s where ctid = '(%u, %u)'", ti_quote(stmt, oid, table_fqn, sizeof(table_fqn)), blocknum, offset); if (bestqual && !TI_has_subclass(ti)) { appendPQExpBuffer(&dltstr, " and "); appendPQExpBuffer(&dltstr, bestqual, oid); } if (PQExpBufferDataBroken(dltstr)) { ret = SQL_ERROR; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in SC_pos_delete()", func); goto cleanup; } MYLOG(0, "dltstr=%s\n", dltstr.data); qflag = 0; if (stmt->external && !CC_is_in_trans(conn) && (!CC_does_autocommit(conn))) qflag |= GO_INTO_TRANSACTION; qres = CC_send_query(conn, dltstr.data, 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_with_key(stmt, global_ridx, (UInt2 *) 0, SQL_DELETE, keyset); if (!SQL_SUCCEEDED(tret)) ret = tret; } else if (dltcnt == 0) { SC_set_error(stmt, STMT_ROW_VERSION_CHANGED, "the content was changed before deletes", func); ret = SQL_SUCCESS_WITH_INFO; if (idx_exist && 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; if (qres) { STRCPY_FIXED(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 && keyset) AddDeleted(res, global_ridx, keyset); if (SQL_SUCCESS == ret && keyset && idx_exist) { 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); MYLOG(DETAIL_LOG_LEVEL, ".status[" FORMAT_ULEN "]=%x\n", global_ridx, res->keyset[kres_ridx].status); } if (irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: irdflds->rowStatusArray[irow] = SQL_ROW_DELETED; break; case SQL_NO_DATA_FOUND: case SQL_SUCCESS_WITH_INFO: irdflds->rowStatusArray[irow] = SQL_ROW_DELETED; // SQL_ROW_SUCCESS_WITH_INFO; ret = SQL_SUCCESS_WITH_INFO; break; case SQL_ERROR: default: irdflds->rowStatusArray[irow] = SQL_ROW_ERROR; break; } } cleanup: #undef return if (!PQExpBufferDataBroken(dltstr)) termPQExpBuffer(&dltstr); 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 = (QR_nextr(ires) ? QR_nextr(ires) : ires); cmdstr = QR_get_command(tres); if (cmdstr && sscanf(cmdstr, "INSERT %u %d", &oid, &addcnt) == 2 && addcnt == 1) { RETCODE qret; const char * tidval = NULL; char tidv[32]; KeySet keys; if (NULL != tres->backend_tuples && 1 == QR_get_num_cached_tuples(tres)) { KeySetSet(tres->backend_tuples, QR_NumResultCols(tres), QR_NumResultCols(tres), &keys, TRUE); oid = keys.oid; SPRINTF_FIXED(tidv, "(%u,%hu)", keys.blocknum, keys.offset); tidval = tidv; } if (0 != oid) poid = &oid; 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) { SC_set_current_col(stmt, -1); SC_Create_bookmark(stmt, bookmark, stmt->bind_row, addpos, &keys); } } 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(0, "entering 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 (s->irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_ADDED; break; case SQL_NO_DATA_FOUND: case SQL_SUCCESS_WITH_INFO: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_SUCCESS_WITH_INFO; break; default: s->irdflds->rowStatusArray[s->irow] = SQL_ROW_ERROR; } } 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; PQExpBufferData addstr = {0}; RETCODE ret; SQLULEN offset; SQLLEN *used; Int4 bind_size = opts->bind_size; OID fieldtype; int unknown_sizes; int func_cs_count = 0; char table_fqn[256]; MYLOG(0, "entering 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); if (PGAPI_AllocStmt(conn, &hstmt, 0) != SQL_SUCCESS) { SC_set_error(s.stmt, STMT_NO_MEMORY_ERROR, "internal AllocStmt error", func); return SQL_ERROR; } initPQExpBuffer(&addstr); #define return DONT_CALL_RETURN_FROM_HERE??? printfPQExpBuffer(&addstr, "insert into %s (", ti_quote(s.stmt, 0, table_fqn, sizeof(table_fqn))); 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); unknown_sizes = ci->drivers.unknown_sizes; 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(0, "%d used=" FORMAT_LEN "\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) appendPQExpBuffer(&addstr, ", \"%s\"", GET_NAME(fi[i]->column_name)); else appendPQExpBuffer(&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, unknown_sizes), fi[i]->column_size > 0 ? fi[i]->column_size : pgtype_column_size(s.stmt, fieldtype, i, unknown_sizes), (SQLSMALLINT) fi[i]->decimal_digits, bindings[i].buffer, bindings[i].buflen, bindings[i].used); } } else MYLOG(0, "%d null bind\n", i); } s.updyes = FALSE; ENTER_INNER_CONN_CS(conn, func_cs_count); if (add_cols > 0) { appendPQExpBuffer(&addstr, ") values ("); for (i = 0; i < add_cols; i++) { if (i) appendPQExpBuffer(&addstr, ", ?"); else appendPQExpBuffer(&addstr, "?"); } appendPQExpBuffer(&addstr, ")"); if (PG_VERSION_GE(conn, 8.2)) { TABLE_INFO *ti = stmt->ti[0]; const char *bestitem = GET_NAME(ti->bestitem); appendPQExpBuffer(&addstr, " returning ctid"); if (bestitem) { appendPQExpBuffer(&addstr, ", "); appendPQExpBuffer(&addstr, "\"%s\"", bestitem); } } if (PQExpBufferDataBroken(addstr)) { ret = SQL_ERROR; SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory in SC_pos_add()", func); goto cleanup; } MYLOG(0, "addstr=%s\n", addstr.data); s.qstmt->exec_start_row = s.qstmt->exec_end_row = s.irow; s.updyes = TRUE; ret = PGAPI_ExecDirect(hstmt, (SQLCHAR *) addstr.data, SQL_NTS, 0); if (ret == SQL_NEED_DATA) { padd_cdata *cbdata = (padd_cdata *) malloc(sizeof(padd_cdata)); if (!cbdata) { SC_set_error(s.stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for cbdata", func); ret = SQL_ERROR; goto cleanup; } 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); if (!PQExpBufferDataBroken(addstr)) termPQExpBuffer(&addstr); return ret; } /* * Stuff for updatable cursors end. */ RETCODE SC_pos_refresh(StatementClass *stmt, SQLSETPOSIROW irow , SQLULEN global_ridx) { RETCODE ret; IRDFields *irdflds = SC_get_IRDF(stmt); /* 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) { if (!SQL_SUCCEEDED(ret = SC_pos_reload(stmt, global_ridx, (UInt2 *) 0, 0))) return ret; } 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 (irdflds->rowStatusArray) { switch (ret) { case SQL_SUCCESS: irdflds->rowStatusArray[irow] = SQL_ROW_SUCCESS; break; case SQL_SUCCESS_WITH_INFO: irdflds->rowStatusArray[irow] = SQL_ROW_SUCCESS_WITH_INFO; break; case SQL_ERROR: default: irdflds->rowStatusArray[irow] = SQL_ROW_ERROR; break; } } 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(0, "entering %d in\n", 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 (0 != s->irow || !opts->row_operation_ptr || opts->row_operation_ptr[s->nrow] == SQL_ROW_PROCEED) { switch (s->fOption) { case SQL_UPDATE: ret = SC_pos_update(s->stmt, s->nrow, global_ridx, NULL); break; case SQL_DELETE: ret = SC_pos_delete(s->stmt, s->nrow, global_ridx, NULL); 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)); if (!cbdata) { SC_set_error(s->stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for cbdata", func); return SQL_ERROR; } 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 (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) /* logging */ { MYLOG(DETAIL_LOG_LEVEL, "processed=" FORMAT_POSIROW " ret=%d rowset=" FORMAT_LEN, s->processed, ret, opts->size_of_rowset_odbc2); MYPRINTF(DETAIL_LOG_LEVEL, "," FORMAT_LEN "\n", opts->size_of_rowset); } 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(0, "entering fOption=%d irow=" FORMAT_POSIROW " lock=%hu currt=" FORMAT_LEN "\n", 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; } rowsetSize = (s.stmt->transition_status == STMT_TRANSITION_EXTENDED_FETCH ? s.opts->size_of_rowset_odbc2 : s.opts->size_of_rowset); 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(0, "num_cols=%d gdatainfo=%d\n", QR_NumPublicResultCols(s.res), gdata_allocated); /* Reset for SQLGetData */ if (gdata) { for (i = 0; i < gdata_allocated; i++) GETDATA_RESET(gdata[i]); } 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 (SQL_SUCCEEDED(ret) && 0 == s.processed) { SC_set_error(s.stmt, STMT_ROW_OUT_OF_RANGE, "the row was deleted?", func); ret = SQL_ERROR; } MYLOG(0, "leaving %d\n", 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(0, "entering fConcurrency=%d crowKeyset=" FORMAT_LEN " crowRowset=%d\n", 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 * szCursor, SQLSMALLINT cbCursor) { CSTR func = "PGAPI_SetCursorName"; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "entering hstmt=%p, szCursor=%p, cbCursorMax=%d\n", 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 * szCursor, SQLSMALLINT cbCursorMax, SQLSMALLINT * pcbCursor) { CSTR func = "PGAPI_GetCursorName"; StatementClass *stmt = (StatementClass *) hstmt; size_t len = 0; RETCODE result; MYLOG(0, "entering hstmt=%p, szCursor=%p, cbCursorMax=%d, pcbCursor=%p\n", 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; } RETCODE SC_fetch_by_bookmark(StatementClass *stmt) { UInt2 offset; SQLLEN kres_ridx; OID oidint; UInt4 blocknum; QResultClass *res, *qres; RETCODE ret = SQL_ERROR; HSTMT hstmt = NULL; StatementClass *fstmt; SQLLEN size_of_rowset, cached_rows; SQLULEN cRow; UInt2 num_fields; ARDFields *opts = SC_get_ARDF(stmt); SQLHDESC hdesc; APDFields *apdf; const int tidbuflen = 20; char *tidbuf = NULL, *query = NULL; int i, lodlen; BindInfoClass *bookmark_orig = opts->bookmark; TupleField *otuple, *ituple; SQLUSMALLINT *rowStatusArray; MYLOG(0, "entering\n"); if (!(res = SC_get_Curres(stmt))) { SC_set_error(stmt, STMT_INVALID_CURSOR_STATE_ERROR, "Null statement result in SC_fetch_by_bookmark.", __FUNCTION__); 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", __FUNCTION__); return SQL_ERROR; } if (ret = PGAPI_AllocStmt(SC_get_conn(stmt), &hstmt, 0), !SQL_SUCCEEDED(ret)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "internal AllocStmt error", __FUNCTION__); return ret; } size_of_rowset = opts->size_of_rowset; SC_MALLOC_gexit_with_error(tidbuf, char, size_of_rowset * tidbuflen, stmt, "Couldn't allocate memory for tidbuf bind.", (ret = SQL_ERROR)); for (i = 0; i < size_of_rowset; i++) { PG_BM pg_bm; SQLLEN bidx; pg_bm = SC_Resolve_bookmark(opts, i); bidx = pg_bm.index; MYLOG(0, "i=%d bidx=" FORMAT_LEN " cached=" FORMAT_ULEN "\n", i, bidx, res->num_cached_keys); kres_ridx = GIdx2KResIdx(bidx, stmt, res); if (kres_ridx < 0 || kres_ridx >= res->num_cached_keys) { if (pg_bm.keys.offset > 0) { QR_get_last_bookmark(res, bidx, &pg_bm.keys); blocknum = pg_bm.keys.blocknum; offset = pg_bm.keys.offset; oidint = pg_bm.keys.oid; } else { SC_set_error(stmt, STMT_ROW_OUT_OF_RANGE, "the target rows is out of the rowset", __FUNCTION__); goto cleanup; } } else { 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 ?", __FUNCTION__); } } getTid(res, kres_ridx, &blocknum, &offset); } snprintf(tidbuf + i * tidbuflen, tidbuflen, "(%u,%u)", blocknum, offset); MYLOG(0, "!!!! tidbuf=%s\n", tidbuf + i * tidbuflen); } if (!SQL_SUCCEEDED(PGAPI_BindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, tidbuflen, 0, tidbuf, tidbuflen, NULL))) goto cleanup; apdf = SC_get_APDF((StatementClass *) hstmt); apdf->paramset_size = size_of_rowset; if (!SQL_SUCCEEDED(PGAPI_GetStmtAttr(stmt, SQL_ATTR_APP_ROW_DESC, (SQLPOINTER) &hdesc, SQL_IS_POINTER, NULL))) goto cleanup; if (!SQL_SUCCEEDED(PGAPI_SetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, (SQLPOINTER) hdesc, SQL_IS_POINTER))) goto cleanup; lodlen = strlen(stmt->load_statement) + 15; SC_MALLOC_gexit_with_error(query, char, lodlen, stmt, "Couldn't allocate memory for query buf.", (ret = SQL_ERROR)); snprintf(query, lodlen, "%s where ctid=?", stmt->load_statement); if (!SQL_SUCCEEDED(ret = PGAPI_ExecDirect(hstmt, (SQLCHAR *) query, SQL_NTS, PODBC_RDONLY))) goto cleanup; /* * Combine multiple results into one */ fstmt = (StatementClass *) hstmt; res = SC_get_Result(fstmt); num_fields = QR_NumResultCols(res); cached_rows = QR_get_num_cached_tuples(res); if (size_of_rowset > res->count_backend_allocated) { SC_REALLOC_gexit_with_error(res->backend_tuples, TupleField, size_of_rowset * sizeof(TupleField) * num_fields, hstmt, "Couldn't realloc memory for backend.", (ret = SQL_ERROR)); res->count_backend_allocated = size_of_rowset; } memset(res->backend_tuples + num_fields * cached_rows, 0, (size_of_rowset - cached_rows) * num_fields * sizeof(TupleField)); QR_set_num_cached_rows(res, size_of_rowset); res->num_total_read = size_of_rowset; rowStatusArray = (SC_get_IRDF(stmt))->rowStatusArray; for (i = 0, qres = res; i < size_of_rowset && NULL != qres; i++, qres = QR_nextr(qres)) { if (1 == QR_get_num_cached_tuples(qres)) { otuple = res->backend_tuples + i * num_fields; ituple = qres->backend_tuples; if (otuple != ituple) MoveCachedRows(otuple, ituple, num_fields, 1); if (NULL != rowStatusArray) rowStatusArray[i] = SQL_ROW_SUCCESS; } else if (NULL != rowStatusArray) rowStatusArray[i] = SQL_ROW_DELETED; } /* Fetch and fill bind info */ cRow = 0; opts->bookmark = NULL; ret = PGAPI_ExtendedFetch(fstmt, SQL_FETCH_NEXT, 0, &cRow, NULL, 0, size_of_rowset); MYLOG(0, "cRow=" FORMAT_ULEN "\n", cRow); cleanup: if (NULL != hstmt) { PGAPI_SetStmtAttr(hstmt, SQL_ATTR_APP_ROW_DESC, (SQLPOINTER) NULL, SQL_IS_POINTER); PGAPI_FreeStmt(hstmt, SQL_DROP); } opts->bookmark = bookmark_orig; if (NULL != tidbuf) free(tidbuf); if (NULL != query) free(query); return ret; } psqlodbc-13.02.0000/parse.c000644 001751 001751 00000145366 14122574536 016370 0ustar00hiroshihiroshi000000 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" #include "misc.h" #define FLD_INCR 32 #define TAB_INCR 8 #define COLI_INCR 16 #define COLI_RECYCLE 128 static const char *getNextToken(int ccsc, char escape_in_literal, const 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 const char * getNextToken( int ccsc, /* client encoding */ char escape_ch, const char *s, char *token, int smax, char *delim, char *quote, char *dquote, char *numeric) { size_t out = 0; size_t taglen; char in_quote, in_dollar_quote, in_escape; const UCHAR *tag, *tagend; encoded_str encstr; char escape_in_literal; const UCHAR *tstr = (const UCHAR *) s; UCHAR tchar, qc; if (smax <= 1) return NULL; smax--; /* skip leading delimiters */ while (isspace(*tstr) || *tstr == ',') { /* MYLOG(0, "skipping '%c'\n", *tstr); */ tstr++; } if (*tstr == '\0') { token[0] = '\0'; return NULL; } if (quote) *quote = FALSE; if (dquote) *dquote = FALSE; if (numeric) *numeric = FALSE; encoded_str_constr(&encstr, ccsc, (const char *) tstr); /* get the next token */ for (tchar = encoded_nextchar(&encstr); tchar && out < smax; tstr++, tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) { token[out++] = tchar; continue; } if (isspace(tchar) || tchar == ',') break; /* Handle quoted stuff */ in_quote = in_dollar_quote = FALSE; taglen = 0; tag = NULL; escape_in_literal = '\0'; if (out == 0) { qc = tchar; if (qc == DOLLAR_QUOTE) { in_quote = in_dollar_quote = TRUE; tag = tstr; taglen = 1; if (tagend = (const UCHAR *) strchr((const char *) tstr + 1, DOLLAR_QUOTE), NULL != tagend) taglen = tagend - tstr + 1; tstr += (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 == tstr[-1]) escape_in_literal = ESCAPE_IN_LITERAL; } } else if (qc == IDENTIFIER_QUOTE) { in_quote = TRUE; if (dquote) *dquote = TRUE; } } /* out == 0 */ if (in_quote) /* dquote, dollar_quote */ { in_escape = FALSE; for (tstr++, tchar = encoded_nextchar(&encstr); tchar != '\0' && out != smax; tstr++, tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) { token[out++] = tchar; continue; } if (in_escape) in_escape = FALSE; else if (tchar == qc) { if (!in_dollar_quote) { /* * Peek at the next byte to see if this is a '' or * "", i.e a quote character that has been escaped * by doubling it. */ if (tstr[1] == qc) { tstr++; tchar = encoded_nextchar(&encstr); } else break; } else if (strncmp((const char *) tstr, (const char *) tag, taglen) == 0) { tstr += (taglen - 1); tchar = encoded_position_shift(&encstr, taglen - 1); break; } token[out++] = tchar; } else if (LITERAL_QUOTE == qc && tchar == escape_in_literal) { in_escape = TRUE; } else { token[out++] = tchar; } } /* for */ if (tchar == qc) tstr++; break; } /* in_quote */ /* Check for numeric literals */ if (out == 0 && isdigit(tchar)) { if (numeric) *numeric = TRUE; token[out++] = tchar; tstr++; while ((isalnum(*tstr) || *tstr == '.') && out < smax) { token[out++] = *tstr; tstr++; } break; } if (ispunct(tchar) && tchar != '_') { MYLOG(0, "got ispunct: s[] = '%c'\n", tchar); if (out == 0) { token[out++] = tchar; tstr++; } break; } if (out < smax) token[out++] = tchar; } /* for */ /* MYLOG(0, "done -- s[] = '%c'\n", *tstr); */ token[out] = '\0'; /* find the delimiter */ while (isspace(*tstr)) tstr++; /* return the most priority delimiter */ if (*tstr == ',') { if (delim) *delim = *tstr; } else if (*tstr == '\0') { if (delim) *delim = '\0'; } else { if (delim) *delim = ' '; } /* skip trailing blanks */ while (isspace(*tstr)) tstr++; return (const char *) tstr; } static void getColInfo(COL_INFO *col_info, FIELD_INFO *fi, int k) { char *str; MYLOG(DETAIL_LOG_LEVEL, "entering 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; MYLOG(DETAIL_LOG_LEVEL, "entering num_cols=" FORMAT_ULEN " 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); MYLOG(DETAIL_LOG_LEVEL, "%d attnum=%d\n", k, attnum); if (attnum == fi->attnum && basetype == fi->basetype && atttypmod == fi->typmod) { getColInfo(col_info, fi, k); MYLOG(0, "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); MYLOG(DETAIL_LOG_LEVEL, "%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(0, "PARSE: \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 (!MBCS_NON_ASCII(encstr)) *ptr = tolower((UCHAR) *ptr); } } } /* * Check relhasoids(before PG12), relhssubclass and get some relevant information. */ BOOL CheckPgClassInfo(StatementClass *stmt) { const COL_INFO *coli; int table_info; TABLE_INFO *ti; BOOL hasoids = FALSE, hassubclass =FALSE, keyFound = FALSE; MYLOG(0, "Entering\n"); if (0 != SC_checked_hasoids(stmt)) return TRUE; if (!stmt->ti || !stmt->ti[0]) return FALSE; ti = stmt->ti[0]; MYLOG(DETAIL_LOG_LEVEL, "ti->col_info=%p\n", ti->col_info); if (TI_checked_hasoids(ti)) ; else if (coli = ti->col_info, NULL != coli) { table_info = coli->table_info; if (0 == (table_info & TBINFO_HASSUBCLASS)) { TI_set_has_no_subclass(ti); } else { hassubclass = TRUE; TI_set_hassubclass(ti); STR_TO_NAME(ti->bestitem, TABLEOID_NAME); STRX_TO_NAME(ti->bestqual, "\"" TABLEOID_NAME "\" = %u"); } if (!hassubclass) { if (0 == (table_info & TBINFO_HASOIDS)) { TI_set_has_no_oids(ti); } else { hasoids = TRUE; TI_set_hasoids(ti); STR_TO_NAME(ti->bestitem, OID_NAME); STRX_TO_NAME(ti->bestqual, "\"" OID_NAME "\" = %u"); } } ti->table_oid = coli->table_oid; if (!hasoids && !hassubclass) { QResultClass *res = coli->result; int num_tuples = res ? QR_get_num_cached_tuples(res) : -1; if (num_tuples > 0) { int i; for (i = 0; i < num_tuples; i++) { if (QR_get_value_backend_int(res, i, COLUMNS_AUTO_INCREMENT, NULL) != 0&& QR_get_value_backend_int(res, i, COLUMNS_FIELD_TYPE, NULL) == PG_TYPE_INT4) { char query[512]; STR_TO_NAME(ti->bestitem, QR_get_value_backend_text(res, i, COLUMNS_COLUMN_NAME)); SPRINTF_FIXED(query, "\"%s\" = %%d", SAFE_NAME(ti->bestitem)); STRX_TO_NAME(ti->bestqual, query); break; } } } } TI_set_hasoids_checked(ti); } else return FALSE; stmt->num_key_fields = PG_NUM_NORMAL_KEYS; if (TI_has_subclass(ti)) keyFound = FALSE; else if (TI_has_oids(ti)) keyFound = TRUE; else if (NAME_IS_NULL(ti->bestqual)) { keyFound = TRUE; stmt->num_key_fields--; } else keyFound = TRUE; MYLOG(DETAIL_LOG_LEVEL, "subclass=%d oids=%d bestqual=%s keyFound=%d num_key_fields=%d\n", TI_has_subclass(ti), TI_has_oids(ti), PRINT_NAME(ti->bestqual), keyFound, stmt->num_key_fields); SC_set_checked_hasoids(stmt, keyFound); 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_NAME); break; } } } /* * SQLColAttribute tries to set the FIELD_INFO (using protocol 3). */ static BOOL ColAttSet(StatementClass *stmt, TABLE_INFO *rti) { CSTR func = "ColAttSet"; QResultClass *res = SC_get_ExecdOrParsed(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(0, "entering\n"); 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 = TI_is_updatable(rti); MYLOG(0, "updatable=%d tab=%d fields=%d", updatable, stmt->ntab, num_fields); if (updatable) { if (1 > stmt->ntab) updatable = FALSE; } MYPRINTF(0, "->%d\n", 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)); if (wfi == NULL) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for field info.", func); return FALSE; } 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 (stmt->updatable < 0) { if (stmt->ntab > 1) updatable = FALSE; SC_set_updatable(stmt, updatable); } 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 (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. */ if (curschema) { 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(0, "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], relcnv[128]; BOOL tblFound = FALSE; /* * We also have to check as follows. */ SPRINTF_FIXED(token, "select nspname from pg_namespace n, pg_class c" " where c.relnamespace=n.oid and c.oid='%s'::regclass", identifierEscape((const SQLCHAR *) SAFE_NAME(table_name), SQL_NTS, conn, relcnv, sizeof(relcnv), TRUE)); res = CC_send_query(conn, token, NULL, READ_ONLY_QUERY, 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(0, "FOUND col_info table='%s' schema='%s'\n", PRINT_NAME(table_name), PRINT_NAME(*schema_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(0, "entering 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; 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(0, " Past PG_Columns\n"); res = SC_get_ExecdOrParsed(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(0, " 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(0, "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(0, "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) { int num_tuples = QR_get_num_cached_tuples(res); int i; 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)); for (i = 0; i < num_tuples; i++) { if (NULL != QR_get_value_backend_text(res, 0, COLUMNS_TABLE_INFO)) { coli->table_info = QR_get_value_backend_int(res, 0, COLUMNS_TABLE_INFO, NULL); break; } } } MYLOG(DETAIL_LOG_LEVEL, "#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) MYLOG(DETAIL_LOG_LEVEL, "oid item == %s\n", (const char *) QR_get_value_backend_text(res, 0, 3)); MYLOG(0, "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; MYLOG(DETAIL_LOG_LEVEL, "entering 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) { MYLOG(DETAIL_LOG_LEVEL, "before increaseNtab\n"); if (!increaseNtab(stmt, func)) return FALSE; wti = stmt->ti[stmt->ntab - 1]; wti->table_oid = greloid; } *pti = wti; } MYLOG(DETAIL_LOG_LEVEL, "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(0, "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)); } MYLOG(DETAIL_LOG_LEVEL, "#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); MYLOG(DETAIL_LOG_LEVEL, "leaving returns %d\n", found); return found; } SQLRETURN SC_set_SS_columnkey(StatementClass *stmt) { 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; MYLOG(DETAIL_LOG_LEVEL, "entering fields=" FORMAT_SIZE_T " ntab=%d\n", nfields, stmt->ntab); if (!fi) return ret; if (0 >= nfields) return ret; for (i = 0; i < stmt->ntab; i++) { 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[i]; 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)) { int i; // different from i of outer loop 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) { MYLOG(DETAIL_LOG_LEVEL, "key %s found at %p\n", keycolnam, fi + i); tfi->columnkey = TRUE; break; } } if (i >= nfields) { MYLOG(0, "%s not found\n", 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; } MYLOG(DETAIL_LOG_LEVEL, "contains_key=%d\n", 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(0, "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, const char **pptr, const 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; const char *ptr; const char *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; po_ind_t join_info = STMT_HAS_NO_JOIN; ConnectionClass *conn = SC_get_conn(stmt); IRDFields *irdflds; BOOL updatable = TRUE, column_has_alias = FALSE, fupdatable; MYLOG(0, "entering...\n"); if (SC_parsed_status(stmt) != STMT_PARSE_NONE) { if (check_hasoids) CheckPgClassInfo(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 = (const char *) ptr, (delim != ',') ? STRCPY_FIXED(btoken, token) : (btoken[0] = '\0', 0), (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(0, "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(0, "DISTINCT\n"); continue; } else if (!stricmp(token, "into")) { in_select = FALSE; MYLOG(0, "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(0, "First From\n"); stmt->from_pos = pptr - stmt->statement; } else MYLOG(0, "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(0, "%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(0, "SELECT\n"); continue; } else { MYLOG(0, "SUBSELECT\n"); if (0 == subqlevel) subqlevel = blevel; } } else if (token[0] == '(') { blevel++; MYLOG(0, "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(0, "blevel-- = %d\n", blevel); if (blevel < subqlevel) subqlevel = 0; } if (blevel >= old_blevel && ',' != delim) STRCPY_FIXED(stoken, token); else stoken[0] = '\0'; } if (in_select) { MYLOG(0, "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(0, "in_expr=%d or func=%d\n", in_expr, in_func); if (blevel == 0) { if (delim == ',') { MYLOG(0, "**** Got comma in_expr/func\n"); in_func = FALSE; in_expr = FALSE; in_field = FALSE; } else if (unquoted && !stricmp(token, "as")) { MYLOG(0, "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(0, "in distinct\n"); if (unquoted && !stricmp(token, "on")) { in_on = TRUE; MYLOG(0, "got on\n"); continue; } if (in_on) { in_distinct = FALSE; in_on = FALSE; continue; /* just skip the unique on field */ } MYLOG(0, "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(0, "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(0, "**** got numeric: nfld = %d\n", nfields); if (NULL != wfi) wfi->numeric = TRUE; } else if (0 == old_blevel && blevel > 0) { /* expression */ MYLOG(0, "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(0, "got field='%s', dot='%s'\n", PRINT_NAME(wfi->column_name), PRINT_NAME(wfi->before_dot)); if (delim == ',') MYLOG(0, "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(0, "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(0, "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(0, "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(0, "**** got function = '%s'\n", PRINT_NAME(wfi->column_name)); } continue; } if (token[0] == '.') { in_dot = TRUE; MYLOG(0, "got dot\n"); continue; } in_dot = FALSE; if (!stricmp(token, "as")) { in_as = TRUE; MYLOG(0, "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(0, "*** setting expression\n"); } else MYLOG(0, "*** 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; join_info = STMT_HAS_NO_JOIN; 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(0, "got subquery lvl=%d\n", blevel); is_table_name = FALSE; is_subquery = TRUE; } else if ('(' == ptr[0]) { MYLOG(0, "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(0, "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(0, "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) { join_info = STMT_HAS_OUTER_JOIN; in_table = FALSE; continue; } else if (stricmp(token, "INNER") == 0 || stricmp(token, "CROSS") == 0) { join_info = STMT_HAS_INNER_JOIN; in_table = FALSE; continue; } else if (stricmp(token, "JOIN") == 0) { in_table = FALSE; out_table = TRUE; if (join_info == STMT_HAS_OUTER_JOIN) { SC_set_outer_join(stmt); } else { SC_set_inner_join(stmt); } join_info = STMT_HAS_NO_JOIN; continue; } } join_info = STMT_HAS_NO_JOIN; 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(0, "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(0, "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(0, "--------------------------------------------\n"); MYLOG(0, "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(0, "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(0, " ----> 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(0, "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(0, "Done PG_Columns\n"); /* * Now resolve the fields to point to column info */ for (i = 0; i < (int) irdflds->nfields;) { wfi = fi[i]; if (wfi->ti) fupdatable = updatable && TI_is_updatable(wfi->ti); else fupdatable = FALSE; wfi->updatable = fupdatable; /* 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(0, "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(0, "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(0, "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(0, "copying field %d to %d\n", j, increased_cols + j); fi[increased_cols + j] = fi[j]; } MYLOG(0, "done copying fields\n"); /* Set the new number of fields */ irdflds->nfields += increased_cols; MYLOG(0, "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(0, "creating field info: n=%d\n", n); /* skip malloc (already did it for the Star) */ if (k > 0 || n > 0) { MYLOG(0, "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(0, "about to copy at %d\n", n + i); getColInfo(the_ti->col_info, afi, n); afi->updatable = fupdatable; MYLOG(0, "done copying\n"); } i += cols; MYLOG(0, "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) CheckPgClassInfo(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; } if (updatable) { if (stmt->ntab > 1) updatable = FALSE; } 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(0, "laving parse=%d, parse_status=%d\n", 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-13.02.0000/statement.c000644 001751 001751 00000251431 14122574536 017251 0ustar00hiroshihiroshi000000 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" /* 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, "CALL" } ,{ 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 } }; static QResultClass *libpq_bind_and_exec(StatementClass *stmt); static void SC_set_errorinfo(StatementClass *self, QResultClass *res, int errkind); static void SC_set_error_if_not_set(StatementClass *self, int errornumber, const char *errmsg, const char *func); RETCODE SQL_API PGAPI_AllocStmt(HDBC hdbc, HSTMT * phstmt, UDWORD flag) { CSTR func = "PGAPI_AllocStmt"; ConnectionClass *conn = (ConnectionClass *) hdbc; StatementClass *stmt; ARDFields *ardopts; MYLOG(0, "entering...\n"); if (!conn) { CC_log_error(func, "", NULL); return SQL_INVALID_HANDLE; } stmt = SC_Constructor(conn); MYLOG(0, "**** : 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.ardf = conn->ardOptions; } else { InitializeStatementOptions(&stmt->options_orig); stmt->options = stmt->options_orig; InitializeARDFields(&stmt->ardi.ardf); } ardopts = SC_get_ARDF(stmt); ARD_AllocBookmark(ardopts); /* 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(0, "entering...hstmt=%p, fOption=%hi\n", 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 */ } if (conn->unnamed_prepared_stmt == stmt) conn->unnamed_prepared_stmt = NULL; /* * 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; } SC_set_Curres(stmt, NULL); } 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->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; opt->metadata_id = SQL_FALSE; } static void SC_clear_parse_status(StatementClass *self, ConnectionClass *conn) { self->parse_status = STMT_PARSE_NONE; } 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); } StatementClass * SC_Constructor(ConnectionClass *conn) { StatementClass *rv; rv = (StatementClass *) malloc(sizeof(StatementClass)); if (rv) { rv->hdbc = conn; rv->phstmt = NULL; rv->rhold.first = rv->rhold.last = NULL; rv->curres = NULL; rv->parsed = NULL; rv->catalog_result = FALSE; rv->prepare = NON_PREPARE_STATEMENT; rv->prepared = NOT_YET_PREPARED; rv->status = STMT_ALLOCATED; rv->external = 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->processed_statements = NULL; rv->__error_message = NULL; rv->__error_number = 0; rv->pgerror = NULL; rv->statement = NULL; rv->stmt_with_params = NULL; rv->load_statement = NULL; 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->load_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->join_info = 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->miscinfo = 0; rv->execinfo = 0; rv->rb_or_tc = 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)); rv->use_server_side_prepare = conn->connInfo.use_server_side_prepare; rv->lock_CC_for_rb = FALSE; // for batch execution memset(&rv->stmt_deffered, 0, sizeof(rv->stmt_deffered)); if ((rv->batch_size = conn->connInfo.batch_size) < 1) rv->batch_size = 1; rv->exec_type = DIRECT_EXEC; rv->count_of_deffered = 0; rv->has_notice = 0; INIT_STMT_CS(rv); } return rv; } char SC_Destructor(StatementClass *self) { CSTR func = "SC_Destructor"; QResultClass *res = SC_get_Result(self); MYLOG(0, "entering 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); if (!PQExpBufferDataBroken(self->stmt_deffered)) termPQExpBuffer(&self->stmt_deffered); DELETE_STMT_CS(self); free(self); MYLOG(0, "leaving\n"); return TRUE; } void SC_init_Result(StatementClass *self) { self->rhold.first = self->rhold.last = NULL; self->curres = NULL; MYLOG(0, "leaving(%p)\n", self); } void SC_set_Result(StatementClass *self, QResultClass *first) { if (first != self->rhold.first) { QResultClass *last = NULL, *res; MYLOG(0, "(%p, %p)\n", self, first); QR_Destructor(self->parsed); self->parsed = NULL; QR_Destructor(self->rhold.first); for (res = first; res; res = QR_nextr(res)) last = res; self->curres = first; self->rhold.first = first; self->rhold.last = last; } } void SC_set_ResultHold(StatementClass *self, QResultHold rhold) { if (rhold.first != self->rhold.first) { MYLOG(0, "(%p, {%p, %p})\n", self, rhold.first, rhold.last); QR_Destructor(self->parsed); self->parsed = NULL; QR_Destructor(self->rhold.first); self->curres = rhold.first; self->rhold = rhold; } else if (rhold.last != self->rhold.last) { self->rhold.last = rhold.last; if (QR_nextr(rhold.last) != NULL) SC_set_error(self, STMT_INTERNAL_ERROR, "last Result is not the last result", __FUNCTION__); } } /* * 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; MYLOG(DETAIL_LOG_LEVEL, "%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); MYPRINTF(DETAIL_LOG_LEVEL, ":(%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; MYPRINTF(DETAIL_LOG_LEVEL, ":(%p)QR result=" FORMAT_LEN "(%s)", res, QR_get_rowstart_in_cache(res), QR_has_valid_base(res) ? "valid" : "unknown"); } stmt->rowset_start = start; MYPRINTF(DETAIL_LOG_LEVEL, ":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_FIXED(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 and load_statement member pointer * deallocating corresponding prepared plan. Also initialize * statement member pointer if specified. */ RETCODE SC_initialize_stmts(StatementClass *self, BOOL initializeOriginal) { ProcessedStmt *pstmt; ProcessedStmt *next_pstmt; ConnectionClass *conn = SC_get_conn(self); if (self->lock_CC_for_rb) { if (conn) LEAVE_CONN_CS(conn); self->lock_CC_for_rb = FALSE; } if (initializeOriginal) { if (self->statement) { free(self->statement); self->statement = NULL; } pstmt = self->processed_statements; while (pstmt) { if (pstmt->query) free(pstmt->query); next_pstmt = pstmt->next; free(pstmt); pstmt = next_pstmt; } self->processed_statements = 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 (conn) self->use_server_side_prepare = conn->connInfo.use_server_side_prepare; } 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; } self->has_notice = 0; 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 Describe-only any time. */ if (self->prepare && self->status == STMT_DESCRIBED) { MYLOG(0, "self->prepare && self->status == STMT_DESCRIBED\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; } void SC_reset_result_for_rerun(StatementClass *self) { QResultClass *res; ColumnInfoClass *flds; if (!self) return; if (res = SC_get_Result(self), NULL == res) return; flds = QR_get_fields(res); if (NULL == flds || 0 == CI_get_num_fields(flds)) SC_set_Result(self, NULL); else { QR_reset_for_re_execute(res); SC_set_Curres(self, NULL); } } /* * 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; MYLOG(0, "entering self=%p\n", 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; } if (SC_get_conn(self)->unnamed_prepared_stmt == self) SC_get_conn(self)->unnamed_prepared_stmt = NULL; 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_DESCRIBED: 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 PREPARED_TEMPORARILY: /* Free the parsed table/field information */ SC_initialize_cols_info(self, TRUE, TRUE); MYLOG(DETAIL_LOG_LEVEL, "SC_clear_parse_status\n"); SC_clear_parse_status(self, conn); break; } /* Free any cursors */ if (SC_get_Result(self)) SC_set_Result(self, NULL); QR_Destructor(self->parsed); self->parsed = NULL; self->miscinfo = 0; self->execinfo = 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; MYLOG(DETAIL_LOG_LEVEL, "statement=%p ommitted=0\n", self); self->last_fetch_count = self->last_fetch_count_include_ommitted = 0; self->__error_message = NULL; self->__error_number = 0; self->lobj_fd = -1; 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, ssize_t *next_cmd, SQLSMALLINT * pcpar, po_ind_t *multi_st, po_ind_t *proc_return) { const char *tstr, *tag = NULL; size_t taglen = 0; char tchar, bchar, escape_in_literal = '\0'; char in_literal = FALSE, in_ident_keyword = FALSE, in_dquote_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(0, "entering...\n"); num_p = 0; if (proc_return) *proc_return = 0; if (next_cmd) *next_cmd = -1; tstr = query; make_encoded_str(&encstr, conn, tstr); for (bchar = '\0', tchar = encoded_nextchar(&encstr); tchar; tchar = encoded_nextchar(&encstr)) { if (MBCS_NON_ASCII(encstr)) /* multibyte char */ { if ((UCHAR) tchar >= 0x80) bchar = tchar; if (in_dquote_identifier || in_literal || in_dollar_quote || in_escape || in_line_comment || comment_level > 0) ; else in_ident_keyword = TRUE; continue; } if (!multi && del_found) { if (IS_NOT_SPACE(tchar)) { multi = TRUE; if (next_cmd) break; } } if (in_ident_keyword) { if (isalnum(tchar) || DOLLAR_QUOTE == tchar || '_' == tchar) { bchar = tchar; continue; } in_ident_keyword = FALSE; } if (in_dollar_quote) { if (tchar == DOLLAR_QUOTE) { if (strncmp((const char *) ENCODE_PTR(encstr), tag, taglen) == 0) { in_dollar_quote = FALSE; tag = NULL; 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_dquote_identifier) { if (tchar == IDENTIFIER_QUOTE) in_dquote_identifier = FALSE; } else if (in_line_comment) { if (PG_LINEFEED == tchar) in_line_comment = FALSE; } else if (comment_level > 0) { if ('/' == tchar && '*' == ENCODE_PTR(encstr)[1]) { tchar = encoded_nextchar(&encstr); comment_level++; } else if ('*' == tchar && '/' == ENCODE_PTR(encstr)[1]) { tchar = encoded_nextchar(&encstr); comment_level--; } } else if (isalnum(tchar)) in_ident_keyword = TRUE; 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 = encstr.pos; } else if (tchar == DOLLAR_QUOTE) { const char *ptr = (const char *) ENCODE_PTR(encstr); taglen = findTag(ptr, encstr.ccsc); if (taglen > 0) { in_dollar_quote = TRUE; tag = ptr; encoded_position_shift(&encstr, taglen - 1); } } else if (tchar == LITERAL_QUOTE) { in_literal = TRUE; escape_in_literal = CC_get_escape(conn); if (!escape_in_literal) { if (LITERAL_EXT == ENCODE_PTR(encstr)[-1]) escape_in_literal = ESCAPE_IN_LITERAL; } } else if (tchar == IDENTIFIER_QUOTE) in_dquote_identifier = TRUE; else if ('-' == tchar) { if ('-' == ENCODE_PTR(encstr)[1]) { tchar = encoded_nextchar(&encstr); in_line_comment = TRUE; } } else if ('/' == tchar) { if ('*' == ENCODE_PTR(encstr)[1]) { tchar = encoded_nextchar(&encstr); comment_level++; } } if (IS_NOT_SPACE(tchar)) bchar = tchar; } } if (pcpar) *pcpar = num_p; if (multi_st) *multi_st = multi; MYLOG(0, "leaving...num_p=%d multi=%d\n", num_p, multi); } /* * Describe the result set a statement will produce (for * SQLPrepare/SQLDescribeCol) * * returns # of fields if successful, -1 on error. */ Int4 SC_describe(StatementClass *self) { Int4 num_fields = -1; QResultClass *res; MYLOG(0, "entering status = %d\n", self->status); res = SC_get_ExecdOrParsed(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(0, " preprocess: status = READY\n"); self->miscinfo = 0; self->execinfo = 0; decideHowToPrepare(self, FALSE); switch (SC_get_prepare_method(self)) { case NAMED_PARSE_REQUEST: case PARSE_TO_EXEC_ONCE: if (SQL_SUCCESS != prepareParameters(self, FALSE)) return num_fields; break; case PARSE_REQ_FOR_INFO: if (SQL_SUCCESS != prepareParameters(self, FALSE)) return num_fields; self->status = STMT_DESCRIBED; break; default: if (SQL_SUCCESS != prepareParameters(self, TRUE)) return num_fields; self->status = STMT_DESCRIBED; break; } if (res = SC_get_ExecdOrParsed(self), NULL != res) { num_fields = QR_NumResultCols(res); return num_fields; } } 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_ExecdOrParsed(self), res) { QR_set_message(res, NULL); QR_set_notice(res, NULL); res->sqlstate[0] = '\0'; } self->stmt_time = 0; memset(&self->localtime, 0, sizeof(self->localtime)); self->localtime.tm_sec = -1; 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[6]; const char ver2str[6]; } 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, PG_ErrorInfo *pgerror_fail_safe) { QResultClass *res = SC_get_ExecdOrParsed(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 = QR_nextr(res)) { if (looponce) loopend = TRUE; if ('\0' != res->sqlstate[0]) { if (NULL != sqlstate && strnicmp(res->sqlstate, "00", 2) == 0) continue; sqlstate = res->sqlstate; if (!QR_command_maybe_successful(res)) loopend = TRUE; /* if ('0' != sqlstate[0] || '1' < sqlstate[1]) loopend = TRUE; */ } if (NULL != res->message) { STRCPY_FIXED(msg, res->message); detailmsg = resmsg = TRUE; } else if (NULL != res->messageref) { STRCPY_FIXED(msg, res->messageref); 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); snprintf(&msg[pos], sizeof(msg) - pos, "%s%s", detailmsg ? ";\n" : "", wmsg); ermsg = msg; detailmsg = TRUE; } if (!self->ref_CC_error) msgend = TRUE; if (conn && !msgend) { 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)); } ermsg = msg; } pgerror = ER_Constructor(self->__error_number, ermsg); if (!pgerror) { if (pgerror_fail_safe) { memset(pgerror_fail_safe, 0, sizeof(*pgerror_fail_safe)); pgerror = pgerror_fail_safe; pgerror->status = self->__error_number; pgerror->errorsize = sizeof(pgerror->__error_message); STRCPY_FIXED(pgerror->__error_message, ermsg); pgerror->recsize = -1; } else return NULL; } if (sqlstate) STRCPY_FIXED(pgerror->sqlstate, sqlstate); else if (conn) { if (!msgend && conn->sqlstate[0]) STRCPY_FIXED(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_FIXED(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; MYLOG(DETAIL_LOG_LEVEL, "entering stmt=%p\n", stmt); for (child = stmt, parent = child->execute_parent; parent; child = parent, parent = child->execute_parent) { MYLOG(DETAIL_LOG_LEVEL, "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; MYLOG(DETAIL_LOG_LEVEL, "entering %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; } if (!from_res) 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_ExecdOrParsed(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_FIXED(self_res->sqlstate, from_res->sqlstate); } void SC_error_copy(StatementClass *self, const StatementClass *from, BOOL check) { QResultClass *self_res, *from_res; BOOL repstate; MYLOG(DETAIL_LOG_LEVEL, "entering %p->%p check=%i\n", from ,self, check); if (!from) return; /* for safety */ if (self == from) return; /* for safety */ 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_ExecdOrParsed(self); from_res = SC_get_ExecdOrParsed(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_FIXED(self_res->sqlstate, from_res->sqlstate); } void SC_full_error_copy(StatementClass *self, const StatementClass *from, BOOL allres) { PG_ErrorInfo *pgerror; MYLOG(DETAIL_LOG_LEVEL, "entering %p->%p\n", from ,self); if (!from) return; /* for safety */ if (self == from) return; /* for safety */ 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, NULL); if (!pgerror || !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 * szSqlState, SQLINTEGER * pfNativeError, SQLCHAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT * pcbErrorMsg, UWORD flag) { /* CC: return an error of a hdesc */ PG_ErrorInfo *pgerror, error; StatementClass *stmt = (StatementClass *) hstmt; int errnum = SC_get_errornumber(stmt); if (pgerror = SC_create_errorinfo(stmt, &error), NULL == pgerror) return SQL_NO_DATA_FOUND; if (pgerror != &error) stmt->pgerror = pgerror; if (STMT_NO_MEMORY_ERROR == errnum && !pgerror->__error_message[0]) STRCPY_FIXED(pgerror->__error_message, "Memory Allocation Error??"); return ER_ReturnError(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; } struct tm * SC_get_localtime(StatementClass *stmt) { #ifndef HAVE_LOCALTIME_R struct tm * tim; #endif /* HAVE_LOCALTIME_R */ if (stmt->localtime.tm_sec < 0) { SC_get_time(stmt); #ifdef HAVE_LOCALTIME_R localtime_r(&stmt->stmt_time, &(stmt->localtime)); #else tim = localtime(&stmt->stmt_time); stmt->localtime = *tim; #endif /* HAVE_LOCALTIME_R */ } return &(stmt->localtime); } 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; KeySet *keyset = NULL; /* TupleField *tupleField; */ MYLOG(DETAIL_LOG_LEVEL, "entering statement=%p res=%p ommitted=0\n", 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(0, "fetch_cursor=%d, %p->total_read=" FORMAT_LEN "\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(0, "**** : non-cursor_result\n"); (self->currTuple)++; } else { /* read from the cache or the physical next tuple */ retval = QR_next_tuple(res, self); if (retval < 0) { MYLOG(0, "**** : end_tuples\n"); 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 { SC_set_errorinfo(self, res, 1); 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; MYLOG(DETAIL_LOG_LEVEL, "SC_ pstatus[" FORMAT_LEN "]=%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; } keyset = res->keyset + kres_ridx; } } num_cols = QR_NumPublicResultCols(res); result = SQL_SUCCESS; self->last_fetch_count++; MYLOG(DETAIL_LOG_LEVEL, "stmt=%p ommitted++\n", 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) { SC_set_current_col(self, -1); SC_Create_bookmark(self, bookmark, self->bind_row, self->currTuple, keyset); } 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(0, "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 */ GETDATA_RESET(gdata->gdata[lf]); 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(0, "type = %d, atttypmod = %d\n", type, atttypmod); if (useCursor) value = QR_get_value_backend(res, lf); else { SQLLEN curt = GIdx2CacheIdx(self->currTuple, self, res); MYLOG(DETAIL_LOG_LEVEL, "%p->base=" FORMAT_LEN " curr=" FORMAT_LEN " st=" FORMAT_LEN " valid=%d\n", res, QR_get_rowstart_in_cache(res), self->currTuple, SC_get_rowset_start(self), QR_has_valid_base(res)); MYLOG(DETAIL_LOG_LEVEL, "curt=" FORMAT_LEN "\n", curt); value = QR_get_value_backend_row(res, curt, lf); } MYLOG(0, "value = '%s'\n", (value == NULL) ? "" : value); retval = copy_and_convert_field_bindinfo(self, type, atttypmod, value, lf); MYLOG(0, "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); MYLOG(DETAIL_LOG_LEVEL, "The %dth item was truncated\n", lf + 1); MYLOG(DETAIL_LOG_LEVEL, "The buffer size = " FORMAT_LEN, opts->bindings[lf].buflen); MYLOG(DETAIL_LOG_LEVEL, " and the value is '%s'\n", value); result = SQL_SUCCESS_WITH_INFO; break; case COPY_INVALID_STRING_CONVERSION: /* invalid string */ SC_set_error(self, STMT_STRING_CONVERSION_ERROR, "invalid string conversion occured.", func); result = SQL_ERROR; 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"; ConnectionClass *conn; IPDFields *ipdopts; char was_ok, was_nonfatal; Int2 oldstatus, numcols; QueryInfo qi; ConnInfo *ci; unsigned int qflag = 0; BOOL is_in_trans, issue_begin, has_out_para; BOOL use_extended_protocol; int func_cs_count = 0, i; BOOL useCursor, isSelectType; int errnum_sav = STMT_OK, errnum; char *errmsg_sav = NULL; SQLULEN stmt_timeout; QResultHold rhold = {0}; conn = SC_get_conn(self); ci = &(conn->connInfo); errnum_sav = SC_get_errornumber(self); errmsg_sav = SC_get_errormsg(self); if (NULL != errmsg_sav) errmsg_sav = strdup(errmsg_sav); SC_set_error(self, STMT_OK, NULL, __FUNCTION__); /* 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(0, "problem with connection\n"); 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->external) 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(0, " about to begin a transaction on statement = %p\n", self); qflag |= GO_INTO_TRANSACTION; } /* * If the session query timeout setting differs from the statement one, * change it. */ stmt_timeout = conn->connInfo.ignore_timeout ? 0 : self->options.stmt_timeout; if (conn->stmt_timeout_in_effect != stmt_timeout) { char query[64]; QResultClass *res; SPRINTF_FIXED(query, "SET statement_timeout = %d", (int) stmt_timeout * 1000); res = CC_send_query(conn, query, NULL, 0, NULL); if (QR_command_maybe_successful(res)) conn->stmt_timeout_in_effect = stmt_timeout; QR_Destructor(res); } 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... */ if (self->stmt_with_params) use_extended_protocol = FALSE; else { use_extended_protocol = TRUE; } isSelectType = (SC_may_use_cursor(self) || self->statement_type == STMT_TYPE_PROCCALL); if (use_extended_protocol) { QResultClass *first; if (issue_begin) CC_begin(conn); first = libpq_bind_and_exec(self); if (!first) { if (SC_get_errornumber(self) <= 0) { SC_set_error(self, STMT_NO_RESPONSE, "Could not receive the response, communication down ??", func); } goto cleanup; } rhold.first = rhold.last = first; } else if (isSelectType) { char fetch[128]; const char *appendq = NULL; QueryInfo *qryi = NULL; QResultClass *first; qflag |= (SQL_CONCUR_READ_ONLY != self->options.scroll_concurrency ? CREATE_KEYSET : 0); MYLOG(0, " Sending SELECT statement on stmt=%p, cursor_name='%s' qflag=%d," FORMAT_UINTEGER "\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.fetch_size = qi.row_size = ci->drivers.fetch_max; SPRINTF_FIXED(fetch, "fetch " FORMAT_LEN " in \"%s\"", qi.fetch_size, SC_cursor_name(self)); qryi = &qi; appendq = fetch; qflag &= (~READ_ONLY_QUERY); /* must be a SAVEPOINT after DECLARE */ } rhold = CC_send_query_append(conn, self->stmt_with_params, qryi, qflag, SC_get_ancestor(self), appendq); first = rhold.first; if (useCursor && QR_command_maybe_successful(first)) { /* * 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 = first; qres;) { if (qres->command && strnicmp(qres->command, "fetch", 5) == 0) { break; } nres = QR_nextr(qres); 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)); } QR_detach(qres); QR_Destructor(qres); qres = nres; /* * If we received fewer rows than requested, there are no * more rows to fetch. */ if (qres && qres->num_cached_rows < qi.row_size) /* check qres != NULL for safety */ QR_set_reached_eof(qres); } first = qres; rhold.first = first; } if (first && SC_is_with_hold(self)) QR_set_withhold(first); } MYLOG(0, " done sending the query:\n"); } else { /* not a SELECT statement so don't use a cursor */ MYLOG(0, " it's NOT a select statement: stmt=%p\n", self); rhold = CC_send_query_append(conn, self->stmt_with_params, NULL, qflag, SC_get_ancestor(self), NULL); } 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->external && CC_does_autocommit(conn)) CC_commit(conn); } } if (CONN_DOWN != conn->status) conn->status = oldstatus; self->status = STMT_FINISHED; MYLOG(0, "set %p STMT_FINISHED\n", self); LEAVE_INNER_CONN_CS(func_cs_count, conn); /* Check the status of the result */ if (rhold.first) { QResultClass *first = rhold.first; was_ok = QR_command_successful(first); was_nonfatal = QR_command_nonfatal(first); if (0 < SC_get_errornumber(self)) ; else if (was_ok) { if (self->has_notice && 0 == SC_get_errornumber(self)) SC_set_errornumber(self, STMT_INFO_ONLY); } else if (was_nonfatal) { self->has_notice = 1; if (0 == SC_get_errornumber(self)) SC_set_errornumber(self, STMT_INFO_ONLY); } else SC_set_errorinfo(self, first, 0); /* 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(first)) { } else { QResultClass *tres; /* see if the query did return any result columns */ for (tres = first, numcols = 0; !numcols && tres; tres = QR_nextr(tres)) { 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(first); SC_set_error(self, STMT_NO_MEMORY_ERROR,"Could not get enough free memory to store the binding information", func); goto cleanup; } } MYLOG(DETAIL_LOG_LEVEL, "!!%p->miscinfo=%x res=%p\n", self, self->miscinfo, first); /* * 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 = QR_nextr(first), tres) { QR_set_fields(tres, QR_get_fields(first)); QR_set_fields(first, NULL); tres->num_fields = first->num_fields; QR_detach(first); SC_set_Result(self, tres); rhold = self->rhold; } } } } else { /* Bad Error -- The error message will be in the Connection */ if (!conn->pqconn) 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); } } if (!SC_get_Result(self)) SC_set_ResultHold(self, rhold); else { if (self->rhold.last != rhold.first) QR_concat(self->rhold.last, rhold.first); self->rhold.last = rhold.last; } if (NULL == SC_get_Curres(self)) SC_set_Curres(self, SC_get_Result(self)); 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); if (has_out_para) { /* get the return value of the procedure call */ RETCODE ret; HSTMT hstmt = (HSTMT) self; ipdopts = SC_get_IPDF(self); self->bind_row = 0; ret = SC_fetch(hstmt); MYLOG(DETAIL_LOG_LEVEL, "!!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++) { int icol = gidx; ipara = ipdopts->parameters + i; if (ipara->paramType == SQL_PARAM_OUTPUT || ipara->paramType == SQL_PARAM_INPUT_OUTPUT) { if (NAME_IS_VALID(ipara->paramName)) { icol = QR_search_by_fieldname(rhold.first, GET_NAME(ipara->paramName)); if (icol < 0) { SC_set_error(self, STMT_EXEC_ERROR, "Named output parameter does not exist.", func); break; } } apara = apdopts->parameters + i; ret = PGAPI_GetData(hstmt, icol + 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); } } if (ci->fetch_refcursors) { char fetch[128]; QResultClass *last = NULL, *res; /* Iterate the columns in the result to look for refcursors */ numcols = QR_NumResultCols(rhold.first); for (i = 0; i < numcols; i++) { MYLOG(DETAIL_LOG_LEVEL, "!!! numfield=%d field_type=%u\n", numcols, QR_get_field_type(rhold.first, i)); if (PG_TYPE_REFCURSOR == QR_get_field_type(rhold.first, i)) { if (!CC_is_in_trans(conn)) { SC_set_error(self, STMT_EXEC_ERROR, "Query must be executed in a transaction when FetchRefcursors setting is enabled.", func); break; } STR_TO_NAME(self->cursor_name, QR_get_value_backend_text(rhold.first, 0, i)); SC_set_fetchcursor(self); qi.result_in = NULL; qi.cursor = SC_cursor_name(self); qi.fetch_size = qi.row_size = ci->drivers.fetch_max; SPRINTF_FIXED(fetch, "fetch " FORMAT_LEN " in \"%s\"", qi.fetch_size, SC_cursor_name(self)); res = CC_send_query(conn, fetch, &qi, qflag | READ_ONLY_QUERY, SC_get_ancestor(self)); if (NULL != res) { if (NULL == last) { /* Reinitialise with result fetched from first refcursor */ SC_init_Result(self); SC_set_Result(self, res); } else { /* Add another result fetched from the next refcursor */ QR_concat(last, res); self->multi_statement = TRUE; } if (!QR_command_maybe_successful(res)) { SC_set_errorinfo(self, res, 0); QR_Destructor(rhold.first); break; } last = res; } } } if (last) QR_Destructor(rhold.first); } } 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; */ errnum = SC_get_errornumber(self); if (errnum_sav > STMT_OK) SC_set_error(self, errnum_sav, errmsg_sav, NULL); else if (errnum > STMT_OK) ; else if (errnum_sav < STMT_OK) SC_set_error(self, errnum_sav, errmsg_sav, NULL); if (NULL != errmsg_sav) free(errmsg_sav); if (errnum == STMT_OK) return SQL_SUCCESS; else if (errnum < STMT_OK) return SQL_SUCCESS_WITH_INFO; else { char *errmsg = SC_get_errormsg(self); if (!errmsg || !errmsg[0]) { if (STMT_NO_MEMORY_ERROR != errnum) 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++; MYLOG(DETAIL_LOG_LEVEL, "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(0, "entering 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; #define NULLCHECK(a) (a ? a : "(NULL)") if (self) { QResultClass *res = SC_get_Result(self); const ARDFields *opts = SC_get_ARDF(self); const APDFields *apdopts = SC_get_APDF(self); SQLLEN rowsetSize; const int level = 9; rowsetSize = (STMT_TRANSITION_EXTENDED_FETCH == self->transition_status ? opts->size_of_rowset_odbc2 : opts->size_of_rowset); if (SC_get_errornumber(self) <= 0) head = "STATEMENT WARNING"; else { head = "STATEMENT ERROR"; QLOG(level, "%s: func=%s, desc='%s', errnum=%d, errmsg='%s'\n",head, func, desc, self->__error_number, NULLCHECK(self->__error_message)); } MYLOG(0, "%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(level, " ------------------------------------------------------------\n"); QLOG(level, " hdbc=%p, stmt=%p, result=%p\n", self->hdbc, self, res); QLOG(level, " prepare=%d, external=%d\n", self->prepare, self->external); QLOG(level, " bindings=%p, bindings_allocated=%d\n", opts->bindings, opts->allocated); QLOG(level, " parameters=%p, parameters_allocated=%d\n", apdopts->parameters, apdopts->allocated); QLOG(level, " statement_type=%d, statement='%s'\n", self->statement_type, NULLCHECK(self->statement)); QLOG(level, " stmt_with_params='%s'\n", NULLCHECK(self->stmt_with_params)); QLOG(level, " data_at_exec=%d, current_exec_param=%d, put_data=%d\n", self->data_at_exec, self->current_exec_param, self->put_data); QLOG(level, " currTuple=" FORMAT_LEN ", current_col=%d, lobj_fd=%d\n", self->currTuple, self->current_col, self->lobj_fd); QLOG(level, " maxRows=" FORMAT_LEN ", rowset_size=" FORMAT_LEN ", keyset_size=" FORMAT_LEN ", cursor_type=" FORMAT_UINTEGER ", scroll_concurrency=" FORMAT_UINTEGER "\n", self->options.maxRows, rowsetSize, self->options.keyset_size, self->options.cursor_type, self->options.scroll_concurrency); QLOG(level, " cursor_name='%s'\n", SC_cursor_name(self)); QLOG(level, " ----------------QResult Info -------------------------------\n"); if (res) { QLOG(level, " fields=%p, backend_tuples=%p, tupleField=%p, conn=%p\n", QR_get_fields(res), res->backend_tuples, res->tupleField, res->conn); QLOG(level, " fetch_count=" FORMAT_LEN ", num_total_rows=" FORMAT_ULEN ", num_fields=%d, cursor='%s'\n", res->fetch_number, QR_get_num_total_tuples(res), res->num_fields, NULLCHECK(QR_get_cursor(res))); QLOG(level, " message='%s', command='%s', notice='%s'\n", NULLCHECK(QR_get_message(res)), NULLCHECK(res->command), NULLCHECK(res->notice)); QLOG(level, " status=%d\n", QR_get_rstatus(res)); } /* Log the connection error if there is one */ CC_log_error(func, desc, self->hdbc); } } else { MYLOG(0, "INVALID STATEMENT HANDLE ERROR: func=%s, desc='%s'\n", func, desc); } } /* * Extended Query */ static BOOL RequestStart(StatementClass *stmt, ConnectionClass *conn, const char *func) { BOOL ret = TRUE; unsigned int svpopt = 0; #ifdef _HANDLE_ENLIST_IN_DTC_ if (conn->asdum) CALL_IsolateDtcConn(conn, TRUE); #endif /* _HANDLE_ENLIST_IN_DTC_ */ if (NULL == conn->pqconn) { SC_set_error(stmt, STMT_COMMUNICATION_ERROR, "The connection has been lost", __FUNCTION__); return SQL_ERROR; } if (CC_started_rbpoint(conn)) return TRUE; if (SC_is_readonly(stmt)) svpopt |= SVPOPT_RDONLY; if (SQL_ERROR == SetStatementSvp(stmt, svpopt)) { char emsg[128]; SPRINTF_FIXED(emsg, "internal savepoint error in %s", func); SC_set_error_if_not_set(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; } static void log_params(int nParams, const Oid *paramTypes, const UCHAR * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat) { int i, j; BOOL isBinary; for (i = 0; i < nParams; i++) { isBinary = paramFormats ? paramFormats[i] : FALSE; if (!paramValues[i]) QLOG(TUPLE_LOG_LEVEL, "\t%c (null) OID=%u\n", isBinary ? 'b' : 't', paramTypes ? paramTypes[i] : 0); else if (isBinary) { QLOG(TUPLE_LOG_LEVEL, "\tb '"); for (j = 0; j < paramLengths[i]; j++) QPRINTF(TUPLE_LOG_LEVEL, "%02x", paramValues[i][j]); QPRINTF(TUPLE_LOG_LEVEL, " OID=%u\n", paramTypes ? paramTypes[i] : 0); } else QLOG(TUPLE_LOG_LEVEL, "\tt '%s' OID=%u\n", paramValues[i], paramTypes ? paramTypes[i] : 0); } } static QResultClass *add_libpq_notice_receiver(StatementClass *stmt, notice_receiver_arg *nrarg) { QResultClass *res = NULL, *newres = NULL; newres = res = QR_Constructor(); nrarg->conn = SC_get_conn(stmt); nrarg->comment = __FUNCTION__; nrarg->res = res; nrarg->stmt = stmt; PQsetNoticeReceiver(nrarg->conn->pqconn, receive_libpq_notice, nrarg); return newres; } static QResultClass * libpq_bind_and_exec(StatementClass *stmt) { CSTR func = "libpq_bind_and_exec"; ConnectionClass *conn = SC_get_conn(stmt); int nParams; Oid *paramTypes = NULL; char **paramValues = NULL; int *paramLengths = NULL; int *paramFormats = NULL; int resultFormat; PGresult *pgres = NULL; int pgresstatus; QResultClass *newres = NULL; QResultClass *res = NULL; char *cmdtag; char *rowcount; notice_receiver_arg nrarg; if (!RequestStart(stmt, conn, func)) return NULL; #ifdef NOT_USED if (CC_is_in_trans(conn) && !CC_started_rbpoint(conn)) { if (SQL_ERROR == SetStatementSvp(stmt, 0)) { SC_set_error_if_not_set(stmt, STMT_INTERNAL_ERROR, "internal savepoint error in build_libpq_bind_params", func); return NULL; } } #endif /* NOT_USED */ /* 1. Bind */ MYLOG(0, "bind stmt=%p\n", stmt); if (!build_libpq_bind_params(stmt, &nParams, ¶mTypes, ¶mValues, ¶mLengths, ¶mFormats, &resultFormat)) { if (SC_get_errornumber(stmt) <= 0) SC_set_errornumber(stmt, STMT_NO_MEMORY_ERROR); goto cleanup; } /* 2. Execute */ MYLOG(0, "execute stmt=%p\n", stmt); if (!SC_is_fetchcursor(stmt)) { if (stmt->prepared == NOT_YET_PREPARED || (stmt->prepared == PREPARED_TEMPORARILY && conn->unnamed_prepared_stmt != stmt)) { SC_set_error(stmt, STMT_EXEC_ERROR, "about to execute a non-prepared statement", func); goto cleanup; } } /* 2.5 Prepare and Describe if needed */ if (stmt->prepared == PREPARING_TEMPORARILY || (stmt->prepared == PREPARED_TEMPORARILY && conn->unnamed_prepared_stmt != stmt)) { ProcessedStmt *pstmt; if (!stmt->processed_statements) { if (prepareParametersNoDesc(stmt, FALSE, EXEC_PARAM_CAST) == SQL_ERROR) goto cleanup; } pstmt = stmt->processed_statements; QLOG(0, "PQexecParams: %p '%s' nParams=%d\n", conn->pqconn, pstmt->query, nParams); log_params(nParams, paramTypes, (const UCHAR * const *) paramValues, paramLengths, paramFormats, resultFormat); /* set notice receiver */ newres = add_libpq_notice_receiver(stmt, &nrarg); pgres = PQexecParams(conn->pqconn, pstmt->query, nParams, paramTypes, (const char **) paramValues, paramLengths, paramFormats, resultFormat); } else { const char *plan_name; if (stmt->prepared == PREPARING_PERMANENTLY) { if (prepareParameters(stmt, FALSE) == SQL_ERROR) goto cleanup; } /* prepareParameters() set plan name, so don't fetch this earlier */ plan_name = stmt->plan_name ? stmt->plan_name : NULL_STRING; /* already prepared */ QLOG(0, "PQexecPrepared: %p plan=%s nParams=%d\n", conn->pqconn, plan_name, nParams); log_params(nParams, paramTypes, (const UCHAR * const *) paramValues, paramLengths, paramFormats, resultFormat); /* set notice receiver */ newres = add_libpq_notice_receiver(stmt, &nrarg); pgres = PQexecPrepared(conn->pqconn, plan_name, /* portal name == plan name */ nParams, (const char **) paramValues, paramLengths, paramFormats, resultFormat); } /* reset notice receiver */ PQsetNoticeReceiver(conn->pqconn, receive_libpq_notice, NULL); if (!(res = nrarg.res)) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Out of memory while allocating result set", func); goto cleanup; } /* 3. Receive results */ MYLOG(DETAIL_LOG_LEVEL, "get_Result=%p %p\n", res, SC_get_Result(stmt)); pgresstatus = PQresultStatus(pgres); switch (pgresstatus) { case PGRES_COMMAND_OK: /* portal query command, no tuples returned */ /* read in the return message from the backend */ cmdtag = PQcmdStatus(pgres); QLOG(0, "\tok: - 'C' - %s\n", cmdtag); QR_set_command(res, cmdtag); if (QR_command_successful(res)) QR_set_rstatus(res, PORES_COMMAND_OK); /* get rowcount */ rowcount = PQcmdTuples(pgres); if (rowcount && rowcount[0]) res->recent_processed_row_count = atoi(rowcount); else res->recent_processed_row_count = -1; break; case PGRES_EMPTY_QUERY: /* We return the empty query */ QR_set_rstatus(res, PORES_EMPTY_QUERY); break; case PGRES_NONFATAL_ERROR: handle_pgres_error(conn, pgres, "libpq_bind_and_exec", res, FALSE); break; case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: handle_pgres_error(conn, pgres, "libpq_bind_and_exec", res, TRUE); break; case PGRES_TUPLES_OK: if (!QR_from_PGresult(res, stmt, conn, NULL, &pgres)) goto cleanup; if (res->rstatus == PORES_TUPLES_OK && res->notice) QR_set_rstatus(res, PORES_NONFATAL_ERROR); break; case PGRES_COPY_OUT: case PGRES_COPY_IN: case PGRES_COPY_BOTH: default: /* skip the unexpected response if possible */ QR_set_rstatus(res, PORES_BAD_RESPONSE); CC_set_error(conn, CONNECTION_BACKEND_CRAZY, "Unexpected protocol character from backend (send_query)", func); CC_on_abort(conn, CONN_DEAD); QLOG(0, "PQexecXxxx error: - (%d) - %s\n", pgresstatus, CC_get_errormsg(conn)); break; } if (res != newres && NULL != newres) QR_Destructor(newres); cleanup: if (pgres) PQclear(pgres); if (paramValues) { int i; for (i = 0; i < nParams; i++) { if (paramValues[i] != NULL) free(paramValues[i]); } free(paramValues); } if (paramTypes) free(paramTypes); if (paramLengths) free(paramLengths); if (paramFormats) free(paramFormats); return res; } /* * Parse a query using libpq. * * 'res' is only passed here for error reporting purposes. If an error is * encountered, it is set in 'res', and the function returns FALSE. */ static BOOL ParseWithLibpq(StatementClass *stmt, const char *plan_name, const char *query, Int2 num_params, const char *comment, QResultClass *res) { CSTR func = "ParseWithLibpq"; ConnectionClass *conn = SC_get_conn(stmt); Int4 sta_pidx = -1, end_pidx = -1; const char *cstatus; Oid *paramTypes = NULL; BOOL retval = FALSE; PGresult *pgres = NULL; MYLOG(0, "entering plan_name=%s query=%s\n", plan_name, query); if (!RequestStart(stmt, conn, func)) return FALSE; 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) { if (0 == num_params) sta_pidx = pidx; num_params++; } else { num_params++; break; } } MYLOG(0, "sta_pidx=%d end_pidx=%d num_p=%d\n", sta_pidx, end_pidx, num_params); } /* * We let the server deduce the right datatype for the parameters, except * for out parameters, which are sent as VOID. */ if (num_params > 0) { int i; int j; IPDFields *ipdopts = SC_get_IPDF(stmt); paramTypes = malloc(sizeof(Oid) * num_params); if (paramTypes == NULL) { SC_set_errornumber(stmt, STMT_NO_MEMORY_ERROR); goto cleanup; } MYLOG(0, "ipdopts->allocated: %d\n", ipdopts->allocated); j = 0; for (i = sta_pidx; i <= end_pidx; i++) { if (i < ipdopts->allocated) { if (SQL_PARAM_OUTPUT == ipdopts->parameters[i].paramType) paramTypes[j++] = PG_TYPE_VOID; else paramTypes[j++] = sqltype_to_bind_pgtype(conn, ipdopts->parameters[i].SQLType); } else { /* Unknown type of parameter. Let the server decide */ paramTypes[j++] = 0; } } } if (plan_name == NULL || plan_name[0] == '\0') conn->unnamed_prepared_stmt = NULL; /* Prepare */ QLOG(0, "PQprepare: %p '%s' plan=%s nParams=%d\n", conn->pqconn, query, plan_name, num_params); pgres = PQprepare(conn->pqconn, plan_name, query, num_params, paramTypes); if (PQresultStatus(pgres) != PGRES_COMMAND_OK) { handle_pgres_error(conn, pgres, "ParseWithlibpq", res, TRUE); goto cleanup; } cstatus = PQcmdStatus(pgres); QLOG(0, "\tok: - 'C' - %s\n", cstatus); if (stmt->plan_name) SC_set_prepared(stmt, PREPARED_PERMANENTLY); else SC_set_prepared(stmt, PREPARED_TEMPORARILY); if (plan_name == NULL || plan_name[0] == '\0') conn->unnamed_prepared_stmt = stmt; retval = TRUE; cleanup: if (paramTypes) free(paramTypes); if (pgres) PQclear(pgres); return retval; } /* * Parse and describe a query using libpq. * * Returns an empty result set that has the column information, or error code * and message, filled in. If 'res' is not NULL, it is the result set * returned, otherwise a new one is allocated. * * NB: The caller must set stmt->current_exec_param before calling this * function! */ QResultClass * ParseAndDescribeWithLibpq(StatementClass *stmt, const char *plan_name, const char *query_param, Int2 num_params, const char *comment, QResultClass *res) { CSTR func = "ParseAndDescribeWithLibpq"; ConnectionClass *conn = SC_get_conn(stmt); PGresult *pgres = NULL; int num_p; Int2 num_discard_params; IPDFields *ipdopts; int pidx; int i; Oid oid; SQLSMALLINT paramType; MYLOG(0, "entering plan_name=%s query=%s\n", plan_name, query_param); if (!RequestStart(stmt, conn, func)) return NULL; if (!res) res = QR_Constructor(); if (!res) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for query", func); return NULL; } /* * We need to do Prepare + Describe as two different round-trips to the * server, while before we switched to use libpq, we used to send a Parse * and Describe message followed by a single Sync. */ if (!ParseWithLibpq(stmt, plan_name, query_param, num_params, comment, res)) goto cleanup; /* Describe */ QLOG(0, "\tPQdescribePrepared: %p plan_name=%s\n", conn->pqconn, plan_name); pgres = PQdescribePrepared(conn->pqconn, plan_name); switch (PQresultStatus(pgres)) { case PGRES_COMMAND_OK: QLOG(0, "\tok: - 'C' - %s\n", PQcmdStatus(pgres)); /* expected */ break; case PGRES_NONFATAL_ERROR: handle_pgres_error(conn, pgres, "ParseAndDescribeWithLibpq", res, FALSE); goto cleanup; case PGRES_FATAL_ERROR: handle_pgres_error(conn, pgres, "ParseAndDescribeWithLibpq", res, TRUE); goto cleanup; default: /* skip the unexpected response if possible */ CC_set_error(conn, CONNECTION_BACKEND_CRAZY, "Unexpected result from PQdescribePrepared", func); CC_on_abort(conn, CONN_DEAD); MYLOG(0, "PQdescribePrepared: error - %s\n", CC_get_errormsg(conn)); goto cleanup; } /* Extract parameter information from the result set */ num_p = PQnparams(pgres); MYLOG(DETAIL_LOG_LEVEL, "num_params=%d info=%d\n", stmt->num_params, num_p); if (get_qlog() > 0 || get_mylog() > 0) { int i; QLOG(0, "\tnParams=%d", num_p); for (i = 0; i < num_p; i++) QPRINTF(0, " %u", PQparamtype(pgres, i)); QPRINTF(0, "\n"); } 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(0, "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); 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(0, "%dth parameter's position(%d) is out of bound[%d]\n", i, pidx, stmt->num_params); break; } oid = PQparamtype(pgres, i); paramType = ipdopts->parameters[pidx].paramType; if (SQL_PARAM_OUTPUT != paramType || PG_TYPE_VOID != oid) PIC_set_pgtype(ipdopts->parameters[pidx], oid); } /* Extract Portal information */ QR_set_conn(res, conn); if (CI_read_fields_from_pgres(QR_get_fields(res), pgres)) { Int2 dummy1, dummy2; int cidx; int num_io_params; 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) { MYLOG(DETAIL_LOG_LEVEL, "!![%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"); } } cleanup: if (pgres) PQclear(pgres); return res; } 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; MYLOG(0, "set %p STMT_FINISHED\n", self); 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; } static void SC_set_error_if_not_set(StatementClass *self, int errornumber, const char *errmsg, const char *func) { int errnum = SC_get_errornumber(self); if (errnum <= 0) { const char *emsg = SC_get_errormsg(self); if (emsg && 0 == errnum) SC_set_errornumber(self, errornumber); else SC_set_error(self, errornumber, errmsg, func); } } static void SC_set_errorinfo(StatementClass *self, QResultClass *res, int errkind) { ConnectionClass *conn = SC_get_conn(self); if (CC_not_connected(conn)) { SC_set_error_if_not_set(self, STMT_COMMUNICATION_ERROR, "The connection has been lost", __FUNCTION__); return; } switch (QR_get_rstatus(res)) { case PORES_NO_MEMORY_ERROR: SC_set_error_if_not_set(self, STMT_NO_MEMORY_ERROR, "memory allocation error???", __FUNCTION__); break; case PORES_BAD_RESPONSE: SC_set_error_if_not_set(self, STMT_COMMUNICATION_ERROR, "communication error occured", __FUNCTION__); break; case PORES_INTERNAL_ERROR: SC_set_error_if_not_set(self, STMT_INTERNAL_ERROR, "Internal error fetching next row", __FUNCTION__); break; default: switch (errkind) { case 1: SC_set_error_if_not_set(self, STMT_EXEC_ERROR, "Error while fetching the next result", __FUNCTION__); break; default: SC_set_error_if_not_set(self, STMT_EXEC_ERROR, "Error while executing the query", __FUNCTION__); break; } break; } } /* * Before 9.6, the driver offered very simple bookmark support -- it is just * the current row number. * Now the driver offers more verbose bookmarks which contain KeySet informations * (CTID (+ OID)). Though they consume 12bytes(row number + CTID) or 16bytes * (row number + CTID + OID), they are useful in declare/fetch mode. */ PG_BM SC_Resolve_bookmark(const ARDFields *opts, Int4 idx) { BindInfoClass *bookmark; SQLLEN *used; SQLULEN offset; SQLUINTEGER bind_size; size_t cpylen = sizeof(Int4); PG_BM pg_bm; bookmark = opts->bookmark; offset = opts->row_offset_ptr ? *(opts->row_offset_ptr) : 0; bind_size = opts->bind_size; memset(&pg_bm, 0, sizeof(pg_bm)); if (used = bookmark->used, used != NULL) { used = LENADDR_SHIFT(used, offset); if (bind_size > 0) used = LENADDR_SHIFT(used, idx * bind_size); else used = LENADDR_SHIFT(used, idx * sizeof(SQLLEN)); if (*used >= sizeof(pg_bm)) cpylen = sizeof(pg_bm); else if (*used >= 12) cpylen = 12; MYLOG(0, "used=" FORMAT_LEN " cpylen=" FORMAT_SIZE_T "\n", *used, cpylen); } memcpy(&pg_bm, CALC_BOOKMARK_ADDR(bookmark, offset, bind_size, idx), cpylen); MYLOG(0, "index=%d block=%d off=%d\n", pg_bm.index, pg_bm.keys.blocknum, pg_bm.keys.offset); pg_bm.index = SC_resolve_int4_bookmark(pg_bm.index); return pg_bm; } int SC_Create_bookmark(StatementClass *self, BindInfoClass *bookmark, Int4 bind_row, Int4 currTuple, const KeySet *keyset) { ARDFields *opts = SC_get_ARDF(self); SQLUINTEGER bind_size = opts->bind_size; SQLULEN offset = opts->row_offset_ptr ? *opts->row_offset_ptr : 0; size_t cvtlen = sizeof(Int4); PG_BM pg_bm; MYLOG(0, "entering type=%d buflen=" FORMAT_LEN " buf=%p\n", bookmark->returntype, bookmark->buflen, bookmark->buffer); memset(&pg_bm, 0, sizeof(pg_bm)); if (SQL_C_BOOKMARK == bookmark->returntype) ; else if (bookmark->buflen >= sizeof(pg_bm)) cvtlen = sizeof(pg_bm); else if (bookmark->buflen >= 12) cvtlen = 12; pg_bm.index = SC_make_int4_bookmark(currTuple); if (keyset) pg_bm.keys = *keyset; memcpy(CALC_BOOKMARK_ADDR(bookmark, offset, bind_size, bind_row), &pg_bm, cvtlen); if (bookmark->used) { SQLLEN *used = LENADDR_SHIFT(bookmark->used, offset); if (bind_size > 0) used = LENADDR_SHIFT(used, bind_row * bind_size); else used = LENADDR_SHIFT(used, bind_row * sizeof(SQLLEN)); *used = cvtlen; } MYLOG(0, "leaving cvtlen=" FORMAT_SIZE_T " ix(bl,of)=%d(%d,%d)\n", cvtlen, pg_bm.index, pg_bm.keys.blocknum, pg_bm.keys.offset); return COPY_OK; } psqlodbc-13.02.0000/tuple.c000644 001751 001751 00000002673 14122574536 016400 0ustar00hiroshihiroshi000000 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 "misc.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 = strdup(string); } if (!tuple_field->value) set_tuplefield_null(tuple_field); } void set_tuplefield_int2(TupleField *tuple_field, Int2 value) { char buffer[10]; ITOA_FIXED(buffer, 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]; ITOA_FIXED(buffer, value); tuple_field->len = (Int4) (strlen(buffer) + 1); /* +1 ... is this correct (better be on the save side-...) */ tuple_field->value = strdup(buffer); } psqlodbc-13.02.0000/dlg_specific.c000644 001751 001751 00000156747 14122574535 017675 0ustar00hiroshihiroshi000000 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 "pgapifunc.h" #define NULL_IF_NULL(a) ((a) ? ((const char *)(a)) : "(null)") CSTR ENTRY_TEST = " @@@ "; 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 | BIT_DISABLE_CONVERT_FUNC) 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); if (ci->disable_convert_func > 0) flag |= BIT_DISABLE_CONVERT_FUNC; else if (ci->disable_convert_func == 0) flag &= (~BIT_DISABLE_CONVERT_FUNC); return flag; } CSTR hex_format = "%x%1s"; CSTR dec_format = "%u%1s"; CSTR octal_format = "%o%1s"; 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)); if (overwrite || ci->disable_convert_func < 0) ci->disable_convert_func = (0 != (flag & BIT_DISABLE_CONVERT_FUNC)); return (ci->extra_opts = getExtraOptions(ci)); } BOOL setExtraOptions(ConnInfo *ci, const char *optstr, const char *format) { UInt4 flag = 0, cnt; char dummy[2]; 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 (cnt = sscanf(optstr, format, &flag, dummy), cnt < 1) // format error return FALSE; else if (cnt > 1) // format error 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 != (aflag & BIT_DISABLE_CONVERT_FUNC)) ci->disable_convert_func = 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; if (0 != (dflag & BIT_DISABLE_CONVERT_FUNC)) ci->disable_convert_func = FALSE; return (ci->extra_opts = getExtraOptions(ci)); } static const char * abbrev_sslmode(const char *sslmode, char *abbrevmode, size_t abbrevsize) { 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 strncpy_null(abbrevmode, sslmode, abbrevsize); } break; } return abbrevmode; } static char * makeKeepaliveConnectString(char *target, int buflen, const ConnInfo *ci, BOOL abbrev) { char *buf = target; *buf = '\0'; if (ci->disable_keepalive) return target; if (ci->keepalive_idle >= 0) { if (abbrev) snprintf(buf, buflen, ABBR_KEEPALIVETIME "=%u;", ci->keepalive_idle); else snprintf(buf, buflen, INI_KEEPALIVETIME "=%u;", ci->keepalive_idle); } if (ci->keepalive_interval >= 0) { if (abbrev) snprintfcat(buf, buflen, ABBR_KEEPALIVEINTERVAL "=%u;", ci->keepalive_interval); else snprintfcat(buf, buflen, INI_KEEPALIVEINTERVAL "=%u;", ci->keepalive_interval); } return target; } #define OPENING_BRACKET '{' #define CLOSING_BRACKET '}' static const char * makeBracketConnectString(BOOL in_str, char **target, pgNAME item, const char *optname) { const char *istr, *iptr; char *buf, *optr; int len; if (!in_str) return NULL_STRING; istr = SAFE_NAME(item); for (iptr = istr, len = 0; *iptr; iptr++) { if (CLOSING_BRACKET == *iptr) len++; len++; } len += 30; if (buf = (char *) malloc(len), buf == NULL) return NULL_STRING; snprintf(buf, len, "%s=%c", optname, OPENING_BRACKET); optr = strchr(buf, '\0'); for (iptr = istr; *iptr; iptr++) { if (CLOSING_BRACKET == *iptr) *(optr++) = *iptr; *(optr++) = *iptr; } *(optr++) = CLOSING_BRACKET; *(optr++) = ';'; *optr = '\0'; *target = buf; return buf; } #ifdef _HANDLE_ENLIST_IN_DTC_ char * makeXaOptConnectString(char *target, int buflen, const ConnInfo *ci, BOOL abbrev) { char *buf = target; *buf = '\0'; if (ci->xa_opt < 0) return target; if (abbrev) { if (DEFAULT_XAOPT != ci->xa_opt) snprintf(buf, buflen, ABBR_XAOPT "=%u;", ci->xa_opt); } else snprintf(buf, buflen, INI_XAOPT "=%u;", ci->xa_opt); return target; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ void makeConnectString(char *connect_string, const ConnInfo *ci, UWORD len) { char got_dsn = (ci->dsn[0] != '\0'); char encoded_item[LARGE_REGISTRY_LEN]; char *connsetStr = NULL; char *pqoptStr = NULL; char keepaliveStr[64]; #ifdef _HANDLE_ENLIST_IN_DTC_ char xaOptStr[16]; #endif ssize_t hlen, nlen, olen; /*BOOL abbrev = (len <= 400);*/ BOOL abbrev = (len < 1024) || 0 < ci->force_abbrev_connstr; UInt4 flag; MYLOG(0, "%s row_versioning=%s\n", __FUNCTION__, ci->row_versioning); MYLOG(DETAIL_LOG_LEVEL, "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; } /* extra info */ hlen = strlen(connect_string); nlen = MAX_CONNECT_STRING - hlen; MYLOG(DETAIL_LOG_LEVEL, "hlen=" FORMAT_SSIZE_T "\n", hlen); if (!abbrev) { char protocol_and[16]; if (ci->rollback_on_error >= 0) SPRINTF_FIXED(protocol_and, "7.4-%d", ci->rollback_on_error); else STRCPY_FIXED(protocol_and, "7.4"); 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;" "%s" /* INI_CONNSETTINGS */ INI_FETCH "=%d;" INI_UNKNOWNSIZES "=%d;" INI_MAXVARCHARSIZE "=%d;" INI_MAXLONGVARCHARSIZE "=%d;" INI_DEBUG "=%d;" INI_COMMLOG "=%d;" INI_USEDECLAREFETCH "=%d;" INI_TEXTASLONGVARCHAR "=%d;" INI_UNKNOWNSASLONGVARCHAR "=%d;" INI_BOOLSASCHAR "=%d;" INI_PARSE "=%d;" INI_EXTRASYSTABLEPREFIXES "=%s;" INI_LFCONVERSION "=%d;" INI_UPDATABLECURSORS "=%d;" INI_TRUEISMINUS1 "=%d;" INI_INT8AS "=%d;" INI_BYTEAASLONGVARBINARY "=%d;" INI_USESERVERSIDEPREPARE "=%d;" INI_LOWERCASEIDENTIFIER "=%d;" "%s" /* INI_PQOPT */ "%s" /* INIKEEPALIVE TIME/INTERVAL */ ABBR_NUMERIC_AS "=%d;" INI_OPTIONAL_ERRORS "=%d;" INI_FETCHREFCURSORS "=%d;" #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 ,makeBracketConnectString(ci->conn_settings_in_str, &connsetStr, ci->conn_settings, INI_CONNSETTINGS) ,ci->drivers.fetch_max ,ci->drivers.unknown_sizes ,ci->drivers.max_varchar_size ,ci->drivers.max_longvarchar_size ,ci->drivers.debug ,ci->drivers.commlog ,ci->drivers.use_declarefetch ,ci->drivers.text_as_longvarchar ,ci->drivers.unknowns_as_longvarchar ,ci->drivers.bools_as_char ,ci->drivers.parse ,ci->drivers.extra_systable_prefixes ,ci->lf_conversion ,ci->allow_keyset ,ci->true_is_minus1 ,ci->int8_as ,ci->bytea_as_longvarbinary ,ci->use_server_side_prepare ,ci->lower_case_identifier ,makeBracketConnectString(ci->pqopt_in_str, &pqoptStr, ci->pqopt, INI_PQOPT) ,makeKeepaliveConnectString(keepaliveStr, sizeof(keepaliveStr), ci, FALSE) ,ci->numeric_as ,ci->optional_errors ,ci->fetch_refcursors #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->allow_keyset) flag |= BIT_UPDATABLECURSORS; if (ci->lf_conversion) flag |= BIT_LFCONVERSION; if (ci->drivers.unique_index) flag |= BIT_UNIQUEINDEX; 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.commlog) flag |= BIT_COMMLOG; if (ci->drivers.debug) flag |= BIT_DEBUG; if (ci->drivers.parse) flag |= BIT_PARSE; 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->optional_errors) flag |= BIT_OPTIONALERRORS; if (ci->fetch_refcursors) flag |= BIT_FETCHREFCURSORS; if (ci->sslmode[0]) { char abbrevmode[sizeof(ci->sslmode)]; (void) snprintf(&connect_string[hlen], nlen, ";" ABBR_SSLMODE "=%s", abbrev_sslmode(ci->sslmode, abbrevmode, sizeof(abbrevmode))); } hlen = strlen(connect_string); nlen = MAX_CONNECT_STRING - hlen; olen = snprintf(&connect_string[hlen], nlen, ";" "%s" /* ABBR_CONNSETTINGS */ ABBR_FETCH "=%d;" ABBR_MAXVARCHARSIZE "=%d;" ABBR_MAXLONGVARCHARSIZE "=%d;" INI_INT8AS "=%d;" ABBR_EXTRASYSTABLEPREFIXES "=%s;" "%s" /* ABBR_PQOPT */ "%s" /* ABBRKEEPALIVE TIME/INTERVAL */ ABBR_NUMERIC_AS "=%d;" #ifdef _HANDLE_ENLIST_IN_DTC_ "%s" #endif /* _HANDLE_ENLIST_IN_DTC_ */ INI_ABBREVIATE "=%02x%x", makeBracketConnectString(ci->conn_settings_in_str, &connsetStr, ci->conn_settings, ABBR_CONNSETTINGS), ci->drivers.fetch_max, ci->drivers.max_varchar_size, ci->drivers.max_longvarchar_size, ci->int8_as, ci->drivers.extra_systable_prefixes, makeBracketConnectString(ci->pqopt_in_str, &pqoptStr, ci->pqopt, ABBR_PQOPT), makeKeepaliveConnectString(keepaliveStr, sizeof(keepaliveStr), ci, TRUE), ci->numeric_as, #ifdef _HANDLE_ENLIST_IN_DTC_ makeXaOptConnectString(xaOptStr, sizeof(xaOptStr), ci, TRUE), #endif /* _HANDLE_ENLIST_IN_DTC_ */ EFFECTIVE_BIT_COUNT, flag); if (olen < nlen || 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 "=7.4-%d", ci->rollback_on_error); else olen = snprintf(&connect_string[hlen], nlen, ";" ABBR_PROTOCOL "=7.4"); } } 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'; if (NULL != connsetStr) free(connsetStr); if (NULL != pqoptStr) free(pqoptStr); } 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->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_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.commlog = (char)((flag & BIT_COMMLOG) != 0); ci->drivers.debug = (char)((flag & BIT_DEBUG) != 0); ci->drivers.parse = (char)((flag & BIT_PARSE) != 0); ci->drivers.use_declarefetch = (char)((flag & BIT_USEDECLAREFETCH) != 0); ITOA_FIXED(ci->onlyread, (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); ITOA_FIXED(ci->row_versioning, (char)((flag & BIT_ROWVERSIONING) != 0)); ITOA_FIXED(ci->show_system_tables, (char)((flag & BIT_SHOWSYSTEMTABLES) != 0)); ITOA_FIXED(ci->show_oid_column, (char)((flag & BIT_SHOWOIDCOLUMN) != 0)); ITOA_FIXED(ci->fake_oid_index, (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->optional_errors = (char)((flag & BIT_OPTIONALERRORS) != 0); ci->fetch_refcursors = (char)((flag & BIT_FETCHREFCURSORS) != 0); } BOOL get_DSN_or_Driver(ConnInfo *ci, const char *attribute, const char *value) { BOOL found = TRUE; if (stricmp(attribute, "DSN") == 0) STRCPY_FIXED(ci->dsn, value); else if (stricmp(attribute, "driver") == 0) STRCPY_FIXED(ci->drivername, value); else found = FALSE; return found; } BOOL copyConnAttributes(ConnInfo *ci, const char *attribute, const char *value) { BOOL found = TRUE, printed = FALSE; if (stricmp(attribute, "DSN") == 0) STRCPY_FIXED(ci->dsn, value); else if (stricmp(attribute, "driver") == 0) STRCPY_FIXED(ci->drivername, value); else if (stricmp(attribute, INI_KDESC) == 0) STRCPY_FIXED(ci->desc, value); else if (stricmp(attribute, INI_DATABASE) == 0 || stricmp(attribute, ABBR_DATABASE) == 0) STRCPY_FIXED(ci->database, value); else if (stricmp(attribute, INI_SERVER) == 0 || stricmp(attribute, SPEC_SERVER) == 0) STRCPY_FIXED(ci->server, value); else if (stricmp(attribute, INI_USERNAME) == 0 || stricmp(attribute, INI_UID) == 0) STRCPY_FIXED(ci->username, value); else if (stricmp(attribute, INI_PASSWORD) == 0 || stricmp(attribute, "pwd") == 0) { ci->password = decode_or_remove_braces(value); #ifndef FORCE_PASSWORDE_DISPLAY MYLOG(0, "key='%s' value='xxxxxxxx'\n", attribute); printed = TRUE; #endif } else if (stricmp(attribute, INI_PORT) == 0) STRCPY_FIXED(ci->port, value); else if (stricmp(attribute, INI_READONLY) == 0 || stricmp(attribute, ABBR_READONLY) == 0) STRCPY_FIXED(ci->onlyread, value); else if (stricmp(attribute, INI_PROTOCOL) == 0 || stricmp(attribute, ABBR_PROTOCOL) == 0) { char *ptr; /* * The first part of the Protocol used to be "6.2", "6.3" or * "7.4" to denote which protocol version to use. Nowadays we * only support the 7.4 protocol, also known as the protocol * version 3. So just ignore the first part of the string, * parsing only the rollback_on_error value. */ ptr = strchr(value, '-'); if (ptr) { if ('-' != *value) { *ptr = '\0'; /* ignore first part */ } ci->rollback_on_error = atoi(ptr + 1); MYLOG(0, "key='%s' value='%s' rollback_on_error=%d\n", attribute, value, ci->rollback_on_error); printed = TRUE; } } else if (stricmp(attribute, INI_SHOWOIDCOLUMN) == 0 || stricmp(attribute, ABBR_SHOWOIDCOLUMN) == 0) STRCPY_FIXED(ci->show_oid_column, value); else if (stricmp(attribute, INI_FAKEOIDINDEX) == 0 || stricmp(attribute, ABBR_FAKEOIDINDEX) == 0) STRCPY_FIXED(ci->fake_oid_index, value); else if (stricmp(attribute, INI_ROWVERSIONING) == 0 || stricmp(attribute, ABBR_ROWVERSIONING) == 0) STRCPY_FIXED(ci->row_versioning, value); else if (stricmp(attribute, INI_SHOWSYSTEMTABLES) == 0 || stricmp(attribute, ABBR_SHOWSYSTEMTABLES) == 0) STRCPY_FIXED(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 */ ci->conn_settings_in_str = TRUE; ci->conn_settings = decode_or_remove_braces(value); } else if (stricmp(attribute, INI_PQOPT) == 0 || stricmp(attribute, ABBR_PQOPT) == 0) { ci->pqopt_in_str = TRUE; ci->pqopt = decode_or_remove_braces(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_NUMERIC_AS) == 0 || stricmp(attribute, ABBR_NUMERIC_AS) == 0) ci->numeric_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_KEEPALIVETIME) == 0 || stricmp(attribute, ABBR_KEEPALIVETIME) == 0) ci->keepalive_idle = atoi(value); else if (stricmp(attribute, INI_KEEPALIVEINTERVAL) == 0 || stricmp(attribute, ABBR_KEEPALIVEINTERVAL) == 0) ci->keepalive_interval = atoi(value); else if (stricmp(attribute, INI_BATCHSIZE) == 0 || stricmp(attribute, ABBR_BATCHSIZE) == 0) ci->batch_size = atoi(value); else if (stricmp(attribute, INI_OPTIONAL_ERRORS) == 0 || stricmp(attribute, ABBR_OPTIONAL_ERRORS) == 0) ci->optional_errors = atoi(value); else if (stricmp(attribute, INI_IGNORETIMEOUT) == 0 || stricmp(attribute, ABBR_IGNORETIMEOUT) == 0) ci->ignore_timeout = atoi(value); else if (stricmp(attribute, INI_SSLMODE) == 0 || stricmp(attribute, ABBR_SSLMODE) == 0) { switch (value[0]) { case SSLLBYTE_ALLOW: STRCPY_FIXED(ci->sslmode, SSLMODE_ALLOW); break; case SSLLBYTE_PREFER: STRCPY_FIXED(ci->sslmode, SSLMODE_PREFER); break; case SSLLBYTE_REQUIRE: STRCPY_FIXED(ci->sslmode, SSLMODE_REQUIRE); break; case SSLLBYTE_VERIFY: switch (value[1]) { case 'f': STRCPY_FIXED(ci->sslmode, SSLMODE_VERIFY_FULL); break; case 'c': STRCPY_FIXED(ci->sslmode, SSLMODE_VERIFY_CA); break; default: STRCPY_FIXED(ci->sslmode, value); } break; case SSLLBYTE_DISABLE: default: STRCPY_FIXED(ci->sslmode, SSLMODE_DISABLE); break; } MYLOG(0, "key='%s' value='%s' set to '%s'\n", attribute, value, ci->sslmode); printed = TRUE; } 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(0, "key='%s' value='%s'(force_abbrev=%d bde=%d cvt_null_date=%x)\n", attribute, value, ci->force_abbrev_connstr, ci->bde_environment, ci->cvt_null_date_string); printed = TRUE; } else if (stricmp(attribute, INI_FETCH) == 0 || stricmp(attribute, ABBR_FETCH) == 0) ci->drivers.fetch_max = 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_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_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_FIXED(ci->drivers.extra_systable_prefixes, value); else if (stricmp(attribute, INI_FETCHREFCURSORS) == 0 || stricmp(attribute, ABBR_FETCHREFCURSORS) == 0) ci->fetch_refcursors = atoi(value); else found = FALSE; if (!printed) MYLOG(0, "key='%s' value='%s'%s\n", attribute, value, found ? NULL_STRING : " not found"); return found; } static void getCiDefaults(ConnInfo *ci) { MYLOG(0, "entering\n"); ci->drivers.debug = DEFAULT_DEBUG; ci->drivers.commlog = DEFAULT_COMMLOG; ITOA_FIXED(ci->onlyread, DEFAULT_READONLY); ITOA_FIXED(ci->fake_oid_index, DEFAULT_FAKEOIDINDEX); ITOA_FIXED(ci->show_oid_column, DEFAULT_SHOWOIDCOLUMN); ITOA_FIXED(ci->show_system_tables, DEFAULT_SHOWSYSTEMTABLES); ITOA_FIXED(ci->row_versioning, DEFAULT_ROWVERSIONING); ci->allow_keyset = DEFAULT_UPDATABLECURSORS; ci->lf_conversion = DEFAULT_LFCONVERSION; ci->true_is_minus1 = DEFAULT_TRUEISMINUS1; ci->int8_as = DEFAULT_INT8AS; ci->numeric_as = DEFAULT_NUMERIC_AS; ci->optional_errors = DEFAULT_OPTIONAL_ERRORS; ci->bytea_as_longvarbinary = DEFAULT_BYTEAASLONGVARBINARY; ci->use_server_side_prepare = DEFAULT_USESERVERSIDEPREPARE; ci->lower_case_identifier = DEFAULT_LOWERCASEIDENTIFIER; STRCPY_FIXED(ci->sslmode, DEFAULT_SSLMODE); ci->force_abbrev_connstr = 0; ci->fake_mss = 0; ci->bde_environment = 0; ci->cvt_null_date_string = 0; ci->accessible_only = 0; ci->ignore_round_trip_time = 0; ci->disable_keepalive = 0; { const char *p; ci->wcs_debug = 0; if (NULL != (p = getenv("PSQLODBC_WCS_DEBUG"))) if (strcmp(p, "1") == 0) ci->wcs_debug = 1; } ci->disable_convert_func = 0; ci->fetch_refcursors = DEFAULT_FETCHREFCURSORS; #ifdef _HANDLE_ENLIST_IN_DTC_ ci->xa_opt = DEFAULT_XAOPT; #endif /* _HANDLE_ENLIST_IN_DTC_ */ } int getDriverNameFromDSN(const char *dsn, char *driver_name, int namelen) { #ifdef WIN32 return SQLGetPrivateProfileString(ODBC_DATASOURCES, dsn, NULL_STRING, driver_name, namelen, ODBC_INI); #else /* WIN32 */ int cnt; cnt = SQLGetPrivateProfileString(dsn, "Driver", NULL_STRING, driver_name, namelen, ODBC_INI); if (!driver_name[0]) return cnt; if (strchr(driver_name, '/') || /* path to the driver */ strchr(driver_name, '.')) { driver_name[0] = '\0'; return 0; } return cnt; #endif /* WIN32 */ } static void Global_defset(GLOBAL_VALUES *comval) { comval->fetch_max = FETCH_MAX; comval->unique_index = DEFAULT_UNIQUEINDEX; comval->unknown_sizes = DEFAULT_UNKNOWNSIZES; comval->lie = DEFAULT_LIE; comval->parse = DEFAULT_PARSE; comval->use_declarefetch = DEFAULT_USEDECLAREFETCH; comval->max_varchar_size = MAX_VARCHAR_SIZE; comval->max_longvarchar_size = TEXT_FIELD_SIZE; comval->text_as_longvarchar = DEFAULT_TEXTASLONGVARCHAR; comval->unknowns_as_longvarchar = DEFAULT_UNKNOWNSASLONGVARCHAR; comval->bools_as_char = DEFAULT_BOOLSASCHAR; STRCPY_FIXED(comval->extra_systable_prefixes, DEFAULT_EXTRASYSTABLEPREFIXES); STRCPY_FIXED(comval->protocol, DEFAULT_PROTOCOL); } static void get_Ci_Drivers(const char *section, const char *filename, GLOBAL_VALUES *comval); void getDriversDefaults(const char *drivername, GLOBAL_VALUES *comval) { MYLOG(0, "%p of the driver %s\n", comval, NULL_IF_NULL(drivername)); get_Ci_Drivers(drivername, ODBCINST_INI, comval); if (NULL != drivername) STR_TO_NAME(comval->drivername, drivername); } void getCiAllDefaults(ConnInfo *ci) { Global_defset(&(ci->drivers)); getCiDefaults(ci); } void getDSNinfo(ConnInfo *ci, const char *configDrvrname) { char *DSN = ci->dsn; char temp[LARGE_REGISTRY_LEN]; const char *drivername; /* * 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(0, "entering DSN=%s driver=%s&%s\n", DSN, ci->drivername, NULL_IF_NULL(configDrvrname)); getCiDefaults(ci); drivername = ci->drivername; if (DSN[0] == '\0') { if (drivername[0] == '\0') /* adding new DSN via configDSN */ { if (configDrvrname) drivername = configDrvrname; strncpy_null(DSN, INI_DSN, sizeof(ci->dsn)); } /* else dns-less connections */ } /* brute-force chop off trailing blanks... */ while (*(DSN + strlen(DSN) - 1) == ' ') *(DSN + strlen(DSN) - 1) = '\0'; if (!drivername[0] && DSN[0]) getDriverNameFromDSN(DSN, (char *) drivername, sizeof(ci->drivername)); MYLOG(0, "drivername=%s\n", drivername); if (!drivername[0]) drivername = INVALID_DRIVER; getDriversDefaults(drivername, &(ci->drivers)); if (DSN[0] == '\0') return; /* Proceed with getting info for the given DSN. */ SQLGetPrivateProfileString(DSN, INI_KDESC, NULL_STRING, ci->desc, sizeof(ci->desc), ODBC_INI); if (SQLGetPrivateProfileString(DSN, INI_SERVER, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->server, temp); if (SQLGetPrivateProfileString(DSN, INI_DATABASE, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->database, temp); if (SQLGetPrivateProfileString(DSN, INI_USERNAME, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->username, temp); if (SQLGetPrivateProfileString(DSN, INI_PASSWORD, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->password = decode(temp); if (SQLGetPrivateProfileString(DSN, INI_PORT, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->port, temp); /* It's appropriate to handle debug and commlog here */ if (SQLGetPrivateProfileString(DSN, INI_DEBUG, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->drivers.debug = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_COMMLOG, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->drivers.commlog = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_READONLY, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->onlyread, temp); if (SQLGetPrivateProfileString(DSN, INI_SHOWOIDCOLUMN, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->show_oid_column, temp); if (SQLGetPrivateProfileString(DSN, INI_FAKEOIDINDEX, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->fake_oid_index, temp); if (SQLGetPrivateProfileString(DSN, INI_ROWVERSIONING, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->row_versioning, temp); if (SQLGetPrivateProfileString(DSN, INI_SHOWSYSTEMTABLES, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->show_system_tables, temp); SQLGetPrivateProfileString(DSN, INI_PROTOCOL, ENTRY_TEST, temp, sizeof(temp), ODBC_INI); if (strcmp(temp, ENTRY_TEST)) /* entry exists */ { char *ptr; if (ptr = strchr(temp, '-'), NULL != ptr) { *ptr = '\0'; ci->rollback_on_error = atoi(ptr + 1); MYLOG(0, "rollback_on_error=%d\n", ci->rollback_on_error); } } SQLGetPrivateProfileString(DSN, INI_CONNSETTINGS, ENTRY_TEST, temp, sizeof(temp), ODBC_INI); if (strcmp(temp, ENTRY_TEST)) /* entry exists */ { const UCHAR *ptr; BOOL percent_encoded = TRUE, pspace; int nspcnt; /* * percent-encoding was used before. * Note that there's no space in percent-encoding. */ for (ptr = (UCHAR *) temp, pspace = TRUE, nspcnt = 0; *ptr; ptr++) { if (isspace(*ptr)) pspace = TRUE; else { if (pspace) { if (nspcnt++ > 1) { percent_encoded = FALSE; break; } } pspace = FALSE; } } if (percent_encoded) ci->conn_settings = decode(temp); else STRX_TO_NAME(ci->conn_settings, temp); } SQLGetPrivateProfileString(DSN, INI_PQOPT, ENTRY_TEST, temp, sizeof(temp), ODBC_INI); if (strcmp(temp, ENTRY_TEST)) /* entry exists */ STRX_TO_NAME(ci->pqopt, temp); if (SQLGetPrivateProfileString(DSN, INI_TRANSLATIONDLL, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->translation_dll, temp); if (SQLGetPrivateProfileString(DSN, INI_TRANSLATIONOPTION, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->translation_option, temp); if (SQLGetPrivateProfileString(DSN, INI_UPDATABLECURSORS, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->allow_keyset = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_LFCONVERSION, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->lf_conversion = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_TRUEISMINUS1, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->true_is_minus1 = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_INT8AS, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->int8_as = atoi(temp); if (SQLGetPrivateProfileString(DSN, ABBR_NUMERIC_AS, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->numeric_as = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_OPTIONAL_ERRORS, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->optional_errors = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_BYTEAASLONGVARBINARY, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->bytea_as_longvarbinary = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_USESERVERSIDEPREPARE, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->use_server_side_prepare = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_LOWERCASEIDENTIFIER, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->lower_case_identifier = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_KEEPALIVETIME, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) if (0 == (ci->keepalive_idle = atoi(temp))) ci->keepalive_idle = -1; if (SQLGetPrivateProfileString(DSN, INI_KEEPALIVEINTERVAL, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) if (0 == (ci->keepalive_interval = atoi(temp))) ci->keepalive_interval = -1; if (SQLGetPrivateProfileString(DSN, INI_BATCHSIZE, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) if (0 == (ci->batch_size = atoi(temp))) ci->batch_size = DEFAULT_BATCH_SIZE; if (SQLGetPrivateProfileString(DSN, INI_IGNORETIMEOUT, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->ignore_timeout = atoi(temp); if (SQLGetPrivateProfileString(DSN, INI_SSLMODE, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) STRCPY_FIXED(ci->sslmode, temp); if (SQLGetPrivateProfileString(DSN, INI_FETCHREFCURSORS, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->fetch_refcursors = atoi(temp); #ifdef _HANDLE_ENLIST_IN_DTC_ if (SQLGetPrivateProfileString(DSN, INI_XAOPT, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) ci->xa_opt = atoi(temp); #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* Force abbrev connstr or bde */ if (SQLGetPrivateProfileString(DSN, INI_EXTRAOPTIONS, NULL_STRING, temp, sizeof(temp), ODBC_INI) > 0) { UInt4 val = 0; sscanf(temp, "%x", &val); replaceExtraOptions(ci, val, TRUE); MYLOG(0, "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 */ get_Ci_Drivers(DSN, ODBC_INI, &(ci->drivers)); STR_TO_NAME(ci->drivers.drivername, drivername); MYLOG(DETAIL_LOG_LEVEL, "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" : ""); MYLOG(DETAIL_LOG_LEVEL, " onlyread='%s',showoid='%s',fakeoidindex='%s',showsystable='%s'\n", ci->onlyread, ci->show_oid_column, ci->fake_oid_index, ci->show_system_tables); { #ifdef NOT_USED char *enc = (char *) check_client_encoding(ci->conn_settings); MYLOG(DETAIL_LOG_LEVEL, " conn_settings='%s', conn_encoding='%s'\n", ci->conn_settings, NULL != enc ? enc : "(null)"); if (NULL != enc) free(enc); #endif /* NOT_USED */ MYLOG(DETAIL_LOG_LEVEL, " 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 write_Ci_Drivers(const char *fileName, const char *sectionName, const GLOBAL_VALUES *comval) { char tmp[128]; int errc = 0; if (stricmp(ODBCINST_INI, fileName) == 0) { if (NULL == sectionName) sectionName = DBMS_NAME; } if (stricmp(ODBCINST_INI, fileName) == 0) return errc; ITOA_FIXED(tmp, comval->commlog); if (!SQLWritePrivateProfileString(sectionName, INI_COMMLOG, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->debug); if (!SQLWritePrivateProfileString(sectionName, INI_DEBUG, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->fetch_max); if (!SQLWritePrivateProfileString(sectionName, INI_FETCH, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->unique_index); if (!SQLWritePrivateProfileString(sectionName, INI_UNIQUEINDEX, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->use_declarefetch); if (!SQLWritePrivateProfileString(sectionName, INI_USEDECLAREFETCH, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->unknown_sizes); if (!SQLWritePrivateProfileString(sectionName, INI_UNKNOWNSIZES, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->text_as_longvarchar); if (!SQLWritePrivateProfileString(sectionName, INI_TEXTASLONGVARCHAR, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->unknowns_as_longvarchar); if (!SQLWritePrivateProfileString(sectionName, INI_UNKNOWNSASLONGVARCHAR, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->bools_as_char); if (!SQLWritePrivateProfileString(sectionName, INI_BOOLSASCHAR, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->parse); if (!SQLWritePrivateProfileString(sectionName, INI_PARSE, tmp, fileName)) errc--; ITOA_FIXED(tmp, comval->max_varchar_size); if (!SQLWritePrivateProfileString(sectionName, INI_MAXVARCHARSIZE, tmp, fileName)) errc--; ITOA_FIXED(tmp, 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; } int writeDriversDefaults(const char *drivername, const GLOBAL_VALUES *comval) { return write_Ci_Drivers(ODBCINST_INI, drivername, comval); } /* This is for datasource based options only */ void writeDSNinfo(const ConnInfo *ci) { const char *DSN = ci->dsn; char encoded_item[MEDIUM_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_FIXED(temp, "7.4-%d", ci->rollback_on_error); else STRCPY_FIXED(temp, NULL_STRING); SQLWritePrivateProfileString(DSN, INI_PROTOCOL, temp, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_CONNSETTINGS, SAFE_NAME(ci->conn_settings), ODBC_INI); SQLWritePrivateProfileString(DSN, INI_PQOPT, SAFE_NAME(ci->pqopt), ODBC_INI); ITOA_FIXED(temp, ci->allow_keyset); SQLWritePrivateProfileString(DSN, INI_UPDATABLECURSORS, temp, ODBC_INI); ITOA_FIXED(temp, ci->lf_conversion); SQLWritePrivateProfileString(DSN, INI_LFCONVERSION, temp, ODBC_INI); ITOA_FIXED(temp, ci->true_is_minus1); SQLWritePrivateProfileString(DSN, INI_TRUEISMINUS1, temp, ODBC_INI); ITOA_FIXED(temp, ci->int8_as); SQLWritePrivateProfileString(DSN, INI_INT8AS, temp, ODBC_INI); ITOA_FIXED(temp, ci->numeric_as); SQLWritePrivateProfileString(DSN, ABBR_NUMERIC_AS, temp, ODBC_INI); ITOA_FIXED(temp, ci->optional_errors); SQLWritePrivateProfileString(DSN, INI_OPTIONAL_ERRORS, temp, ODBC_INI); SPRINTF_FIXED(temp, "%x", getExtraOptions(ci)); SQLWritePrivateProfileString(DSN, INI_EXTRAOPTIONS, temp, ODBC_INI); ITOA_FIXED(temp, ci->bytea_as_longvarbinary); SQLWritePrivateProfileString(DSN, INI_BYTEAASLONGVARBINARY, temp, ODBC_INI); ITOA_FIXED(temp, ci->use_server_side_prepare); SQLWritePrivateProfileString(DSN, INI_USESERVERSIDEPREPARE, temp, ODBC_INI); ITOA_FIXED(temp, ci->lower_case_identifier); SQLWritePrivateProfileString(DSN, INI_LOWERCASEIDENTIFIER, temp, ODBC_INI); SQLWritePrivateProfileString(DSN, INI_SSLMODE, ci->sslmode, ODBC_INI); ITOA_FIXED(temp, ci->keepalive_idle); SQLWritePrivateProfileString(DSN, INI_KEEPALIVETIME, temp, ODBC_INI); ITOA_FIXED(temp, ci->keepalive_interval); SQLWritePrivateProfileString(DSN, INI_KEEPALIVEINTERVAL, temp, ODBC_INI); ITOA_FIXED(temp, ci->batch_size); SQLWritePrivateProfileString(DSN, INI_BATCHSIZE, temp, ODBC_INI); ITOA_FIXED(temp, ci->ignore_timeout); SQLWritePrivateProfileString(DSN, INI_IGNORETIMEOUT, temp, ODBC_INI); ITOA_FIXED(temp, ci->fetch_refcursors); SQLWritePrivateProfileString(DSN, INI_FETCHREFCURSORS, temp, ODBC_INI); #ifdef _HANDLE_ENLIST_IN_DTC_ ITOA_FIXED(temp, 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. */ static void get_Ci_Drivers(const char *section, const char *filename, GLOBAL_VALUES *comval) { char temp[256]; BOOL inst_position = (stricmp(filename, ODBCINST_INI) == 0); if (0 != strcmp(ODBCINST_INI, filename)) MYLOG(0, "setting %s position of %s(%p)\n", filename, section, comval); /* * It's not appropriate to handle debug or commlog here. * Now they are handled in getDSNinfo(). */ if (inst_position) Global_defset(comval); if (NULL == section || strcmp(section, INVALID_DRIVER) == 0) return; /* * If inst_position of xxxxxx is present(usually not present), * it is the default of ci->drivers.xxxxxx . */ /* Fetch Count is stored in driver section */ if (SQLGetPrivateProfileString(section, INI_FETCH, NULL_STRING, temp, sizeof(temp), filename) > 0) { if (atoi(temp) > 0) comval->fetch_max = atoi(temp); } /* Recognize Unique Index is stored in the driver section only */ if (SQLGetPrivateProfileString(section, INI_UNIQUEINDEX, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->unique_index = atoi(temp); /* Unknown Sizes is stored in the driver section only */ if (SQLGetPrivateProfileString(section, INI_UNKNOWNSIZES, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->unknown_sizes = atoi(temp); /* Lie about supported functions? */ if (SQLGetPrivateProfileString(section, INI_LIE, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->lie = atoi(temp); /* Parse statements */ if (SQLGetPrivateProfileString(section, INI_PARSE, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->parse = atoi(temp); /* UseDeclareFetch is stored in the driver section only */ if (SQLGetPrivateProfileString(section, INI_USEDECLAREFETCH, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->use_declarefetch = atoi(temp); /* Max Varchar Size */ if (SQLGetPrivateProfileString(section, INI_MAXVARCHARSIZE, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->max_varchar_size = atoi(temp); /* Max TextField Size */ if (SQLGetPrivateProfileString(section, INI_MAXLONGVARCHARSIZE, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->max_longvarchar_size = atoi(temp); /* Text As LongVarchar */ if (SQLGetPrivateProfileString(section, INI_TEXTASLONGVARCHAR, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->text_as_longvarchar = atoi(temp); /* Unknowns As LongVarchar */ if (SQLGetPrivateProfileString(section, INI_UNKNOWNSASLONGVARCHAR, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->unknowns_as_longvarchar = atoi(temp); /* Bools As Char */ if (SQLGetPrivateProfileString(section, INI_BOOLSASCHAR, NULL_STRING, temp, sizeof(temp), filename) > 0) comval->bools_as_char = atoi(temp); /* Extra Systable prefixes */ /* * Use ENTRY_TEST to distinguish between blank extra prefixes and no key * entry */ SQLGetPrivateProfileString(section, INI_EXTRASYSTABLEPREFIXES, ENTRY_TEST, temp, sizeof(temp), filename); if (strcmp(temp, ENTRY_TEST)) STRCPY_FIXED(comval->extra_systable_prefixes, temp); MYLOG(0, "comval=%p comval->extra_systable_prefixes = '%s'\n", comval, comval->extra_systable_prefixes); /* Dont allow override of an override! */ if (inst_position) { /* * 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, ENTRY_TEST, temp, sizeof(temp), filename); if (strcmp(temp, ENTRY_TEST)) STRCPY_FIXED(comval->protocol, temp); } } 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; snprintf(&out[o], outlen - o, "%%2B"); o += 3; } else if (isspace((unsigned char) inc)) out[o++] = '+'; else if (!isalnum((unsigned char) inc)) { if (o + 2 >= outlen) break; snprintf(&out[o], outlen - 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); if (!outs) return out; for (i = 0; i < ilen; i++) { inc = in[i]; if (inc == '+') outs[o++] = ' '; else if (inc == '%') { snprintf(&outs[o], ilen + 1 - o, "%c", conv_from_hex(&in[i])); o++; 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 (OPENING_BRACKET == in[0]) { size_t inlen = strlen(in); if (CLOSING_BRACKET == in[inlen - 1]) /* enclosed with braces */ { int i; const char *istr, *eptr; char *ostr; pgNAME out; INIT_NAME(out); if (NULL == (ostr = (char *) malloc(inlen))) return out; eptr = in + inlen - 1; for (istr = in + 1, i = 0; *istr && istr < eptr; i++) { if (CLOSING_BRACKET == istr[0] && CLOSING_BRACKET == istr[1]) istr++; ostr[i] = *(istr++); } ostr[i] = '\0'; SET_NAME_DIRECTLY(out, ostr); return out; } } return decode(in); } /* * extract the specified attribute from the comment part. * attribute=[']value['] */ char *extract_extra_attribute_setting(const pgNAME setting, const char *attr) { const char *str = SAFE_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); if (!rptr) return NULL; memcpy(rptr, sptr, len); rptr[len] = '\0'; MYLOG(0, "extracted a %s '%s' from %s\n", attr, rptr, str); return rptr; } signed char ci_updatable_cursors_set(ConnInfo *ci) { ci->updatable_cursors = DISALLOW_UPDATABLE_CURSORS; if (ci->allow_keyset) { 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 ci->updatable_cursors |= (ALLOW_STATIC_CURSORS | ALLOW_BULK_OPERATIONS | SENSE_SELF_OPERATIONS); } return ci->updatable_cursors; } void CC_conninfo_release(ConnInfo *conninfo) { NULL_THE_NAME(conninfo->password); NULL_THE_NAME(conninfo->conn_settings); NULL_THE_NAME(conninfo->pqopt); finalize_globals(&conninfo->drivers); } void CC_conninfo_init(ConnInfo *conninfo, UInt4 option) { MYLOG(0, "entering opt=%d\n", option); if (0 != (CLEANUP_FOR_REUSE & option)) CC_conninfo_release(conninfo); memset(conninfo, 0, sizeof(ConnInfo)); conninfo->allow_keyset = -1; conninfo->lf_conversion = -1; conninfo->true_is_minus1 = -1; conninfo->int8_as = -101; conninfo->numeric_as = DEFAULT_NUMERIC_AS; conninfo->optional_errors = -1; 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->accessible_only = -1; conninfo->ignore_round_trip_time = -1; conninfo->disable_keepalive = -1; conninfo->keepalive_idle = -1; conninfo->keepalive_interval = -1; conninfo->disable_convert_func = -1; conninfo->batch_size = DEFAULT_BATCH_SIZE; conninfo->ignore_timeout = DEFAULT_IGNORETIMEOUT; conninfo->wcs_debug = -1; conninfo->fetch_refcursors = -1; #ifdef _HANDLE_ENLIST_IN_DTC_ conninfo->xa_opt = -1; #endif /* _HANDLE_ENLIST_IN_DTC_ */ if (0 != (INIT_GLOBALS & option)) init_globals(&(conninfo->drivers)); } void init_globals(GLOBAL_VALUES *glbv) { memset(glbv, 0, sizeof(*glbv)); glbv->debug = -1; glbv->commlog = -1; } #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); ***/ NAME_TO_NAME(to->drivername, from->drivername); CORR_VALCPY(fetch_max); CORR_VALCPY(unknown_sizes); CORR_VALCPY(max_varchar_size); CORR_VALCPY(max_longvarchar_size); CORR_VALCPY(debug); CORR_VALCPY(commlog); CORR_VALCPY(unique_index); 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_STRCPY(extra_systable_prefixes); CORR_STRCPY(protocol); MYLOG(0, "driver=%s\n", SAFE_NAME(to->drivername)); } void finalize_globals(GLOBAL_VALUES *glbv) { NULL_THE_NAME(glbv->drivername); } #undef CORR_STRCPY #undef CORR_VALCPY #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(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(password_required); NAME_TO_NAME(ci->conn_settings, sci->conn_settings); CORR_VALCPY(allow_keyset); CORR_VALCPY(updatable_cursors); CORR_VALCPY(lf_conversion); CORR_VALCPY(true_is_minus1); CORR_VALCPY(int8_as); CORR_VALCPY(numeric_as); CORR_VALCPY(optional_errors); 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(accessible_only); CORR_VALCPY(ignore_round_trip_time); CORR_VALCPY(disable_keepalive); CORR_VALCPY(disable_convert_func); CORR_VALCPY(extra_opts); CORR_VALCPY(keepalive_idle); CORR_VALCPY(keepalive_interval); CORR_VALCPY(batch_size); CORR_VALCPY(ignore_timeout); CORR_VALCPY(fetch_refcursors); #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 psqlodbc-13.02.0000/multibyte.c000644 001751 001751 00000023677 14122574536 017274 0ustar00hiroshihiroshi000000 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 WIN32 #include #endif #ifndef TRUE #define TRUE 1 #endif typedef struct pg_CS { char *name; int code; } pg_CS; 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 }, { "KOI8R", KOI8R }, { "OTHER", 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; if ('=' == *cptr) cptr--; break; case 2: if (0 == strnicmp(cptr, "to", 2)) cptr += 2; else if (0 == strnicmp(cptr, "=", 1)) ; else { allowed_cmd = FALSE; continue; } step++; break; case 3: if (LITERAL_QUOTE == *cptr) { cptr++; for (sptr = cptr; *cptr && *cptr != LITERAL_QUOTE; cptr++) ; } else { for (sptr = cptr; ';' != *cptr && IS_NOT_SPACE(*cptr); cptr++) ; } len = cptr - sptr; if (';' == *cptr) cptr--; step++; break; } } if (!sptr) return NULL; rptr = malloc(len + 1); if (!rptr) return NULL; memcpy(rptr, sptr, len); rptr[len] = '\0'; MYLOG(0, "extracted a client_encoding '%s' from conn_settings\n", rptr); return rptr; } int pg_mb_maxlen(int characterset_code) { switch (characterset_code) { case UTF8: return 4; 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; } /* * This function is used to know the encoding corresponding to * the current locale. */ const char * derive_locale_encoding(const char *dbencoding) { const char *wenc = NULL; #ifdef WIN32 int acp; #else const char *loc, *ptr; #endif /* WIN32 */ if (wenc = getenv("PGCLIENTENCODING"), NULL != wenc) /* environmnt variable */ return wenc; #ifdef WIN32 acp = GetACP(); if (acp >= 1251 && acp <= 1258) { if (stricmp(dbencoding, "SQL_ASCII") == 0) return wenc; } switch (acp) { case 932: wenc = "SJIS"; break; case 936: wenc = "GBK"; break; case 949: wenc = "UHC"; break; case 950: wenc = "BIG5"; break; case 1250: wenc = "WIN1250"; break; case 1251: wenc = "WIN1251"; break; case 1256: wenc = "WIN1256"; break; case 1252: if (strnicmp(dbencoding, "LATIN", 5) == 0) break; wenc = "WIN1252"; break; case 1258: wenc = "WIN1258"; break; case 1253: wenc = "WIN1253"; break; case 1254: wenc = "WIN1254"; break; case 1255: wenc = "WIN1255"; break; case 1257: wenc = "WIN1257"; break; } #else /* * Derive the encoding from the codeset part of the current locale. */ loc = setlocale(LC_CTYPE, ""); if (loc && (ptr = strchr(loc, '.'))) { int enc_no; ptr++; if ((enc_no= pg_char_to_encoding(ptr)) >= 0) wenc = pg_encoding_to_char(enc_no); MYLOG(0, "locale=%s enc=%s\n", loc, wenc ? wenc : "(null)"); } #endif /* WIN32 */ return wenc; } void encoded_str_constr(encoded_str *encstr, int ccsc, const char *str) { encstr->ccsc = ccsc; encstr->encstr = (const UCHAR *) str; encstr->pos = -1; encstr->ccst = 0; } int encoded_nextchar(encoded_str *encstr) { int chr; if (encstr->pos >= 0 && !encstr->encstr[encstr->pos]) return 0; 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-13.02.0000/odbcapi.c000644 001751 001751 00000116613 14122574536 016650 0ustar00hiroshihiroshi000000 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" BOOL SC_connection_lost_check(StatementClass *stmt, const char *funcname) { ConnectionClass *conn = SC_get_conn(stmt); char message[64]; if (NULL != conn->pqconn) return FALSE; SC_clear_error(stmt); SPRINTF_FIXED(message, "%s unable due to the connection lost", funcname); SC_set_error(stmt, STMT_COMMUNICATION_ERROR, message, funcname); return TRUE; } 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(0, "Entering\n"); 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) { MYLOG(0, "Entering\n"); /* Not that neither ENTER_STMT_CS nor StartRollbackState is called */ /* SC_clear_error((StatementClass *) StatementHandle); maybe this neither */ if (SC_connection_lost_check((StatementClass *) StatementHandle, __FUNCTION__)) return SQL_ERROR; return PGAPI_Cancel(StatementHandle); } 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)); } #ifndef UNICODE_SUPPORTXX 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; ConnInfo *ci = &(SC_get_conn(stmt)->connInfo); UWORD flag = PODBC_SEARCH_PUBLIC_SCHEMA; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; if (atoi(ci->show_oid_column)) flag |= PODBC_SHOW_OID_COLUMN; if (atoi(ci->row_versioning)) flag |= PODBC_ROW_VERSIONING; 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; } 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(0, "Entering\n"); 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 * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT * pcbConnStrOut, SQLUSMALLINT fDriverCompletion) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; MYLOG(0, "Entering\n"); 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(0, "Entering\n"); 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(0, "Entering\n"); /* * 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; MYLOG(0, "Entering for %p\n", 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; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLExecDirect(HSTMT StatementHandle, SQLCHAR *StatementText, SQLINTEGER TextLength) { CSTR func = "SQLExecDirect"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; UWORD flag = 0; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLExecute(HSTMT StatementHandle) { CSTR func = "SQLExecute"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; UWORD flag = 0; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); flag |= (PODBC_RECYCLE_STATEMENT | PODBC_WITH_HOLD); if (SC_opencheck(stmt, func)) ret = SQL_ERROR; else { StartRollbackState(stmt); stmt->exec_current_row = -1; //// SC_set_Result(StatementHandle, NULL); ret = PGAPI_Execute(StatementHandle, flag); ret = DiscardStatementSvp(stmt, ret, FALSE); } LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLFetch(HSTMT StatementHandle) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; IRDFields *irdopts = SC_get_IRDF(stmt); ARDFields *ardopts = SC_get_ARDF(stmt); SQLUSMALLINT *rowStatusArray = irdopts->rowStatusArray; SQLULEN *pcRow = irdopts->rowsFetched; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_ExtendedFetch(StatementHandle, SQL_FETCH_NEXT, 0, pcRow, rowStatusArray, 0, ardopts->size_of_rowset); stmt->transition_status = STMT_TRANSITION_FETCH_SCROLL; ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } RETCODE SQL_API SQLFreeStmt(HSTMT StatementHandle, SQLUSMALLINT Option) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; ConnectionClass *conn = NULL; MYLOG(0, "Entering\n"); 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; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLGetCursorName(HSTMT StatementHandle, SQLCHAR *CursorName, SQLSMALLINT BufferLength, SQLSMALLINT *NameLength) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); 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; } #endif /* UNICODE_SUPPORTXX */ 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); if (FunctionId == SQL_API_ODBC3_ALL_FUNCTIONS) ret = PGAPI_GetFunctions30(ConnectionHandle, FunctionId, Supported); else ret = PGAPI_GetFunctions(ConnectionHandle, FunctionId, Supported); LEAVE_CONN_CS(conn); return ret; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLGetInfo(HDBC ConnectionHandle, SQLUSMALLINT InfoType, PTR InfoValue, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; CC_examine_global_transaction(conn); ENTER_CONN_CS(conn); CC_clear_error(conn); MYLOG(0, "Entering\n"); if ((ret = PGAPI_GetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength)) == SQL_ERROR) CC_log_error("SQLGetInfo(30)", "", conn); LEAVE_CONN_CS(conn); return ret; } RETCODE SQL_API SQLGetTypeInfo(HSTMT StatementHandle, SQLSMALLINT DataType) { CSTR func = "SQLGetTypeInfo"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); if (SC_connection_lost_check((StatementClass *) StatementHandle, __FUNCTION__)) return SQL_ERROR; 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLNumResultCols(HSTMT StatementHandle, SQLSMALLINT *ColumnCount) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); ret = PGAPI_ParamData(StatementHandle, Value); ret = DiscardStatementSvp(stmt, ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLPrepare(HSTMT StatementHandle, SQLCHAR *StatementText, SQLINTEGER TextLength) { CSTR func = "SQLPrepare"; RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLPutData(HSTMT StatementHandle, PTR Data, SQLLEN StrLen_or_Ind) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLSetCursorName(HSTMT StatementHandle, SQLCHAR *CursorName, SQLSMALLINT NameLength) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLSetParam(HSTMT StatementHandle, SQLUSMALLINT ParameterNumber, SQLSMALLINT ValueType, SQLSMALLINT ParameterType, SQLULEN LengthPrecision, SQLSMALLINT ParameterScale, PTR ParameterValue, SQLLEN *StrLen_or_Ind) { MYLOG(0, "Entering\n"); SC_clear_error((StatementClass *) StatementHandle); /* * return PGAPI_SetParam(StatementHandle, ParameterNumber, ValueType, * ParameterType, LengthPrecision, ParameterScale, ParameterValue, * StrLen_or_Ind); */ return SQL_ERROR; } #ifndef UNICODE_SUPPORTXX 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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; } 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLDescribeParam(HSTMT hstmt, SQLUSMALLINT ipar, SQLSMALLINT *pfSqlType, SQLULEN *pcbParamDef, SQLSMALLINT *pibScale, SQLSMALLINT *pfNullable) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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_INT != 8) SQLROWSETSIZE *pcrow, #else SQLULEN *pcrow, #endif /* WITH_UNIXODBC */ SQLUSMALLINT *rgfRowStatus) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #ifndef UNICODE_SUPPORTXX 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLMoreResults(HSTMT hstmt) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #ifndef UNICODE_SUPPORTXX RETCODE SQL_API SQLNativeSql(HDBC hdbc, SQLCHAR *szSqlStrIn, SQLINTEGER cbSqlStrIn, SQLCHAR *szSqlStr, SQLINTEGER cbSqlStrMax, SQLINTEGER *pcbSqlStr) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; MYLOG(0, "Entering\n"); 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLNumParams(HSTMT hstmt, SQLSMALLINT *pcpar) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #ifndef UNICODE_SUPPORTXX 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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; } #endif /* UNICODE_SUPPORTXX */ RETCODE SQL_API SQLSetPos(HSTMT hstmt, SQLSETPOSIROW irow, SQLUSMALLINT fOption, SQLUSMALLINT fLock) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #ifndef UNICODE_SUPPORTXX 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); if (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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; } #endif /* UNICODE_SUPPORTXX */ 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(0, "Entering\n"); 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-13.02.0000/descriptor.c000644 001751 001751 00000045341 14122574535 017423 0ustar00hiroshihiroshi000000 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 "misc.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); } void TI_Destructor(TABLE_INFO **ti, int count) { int i; MYLOG(DETAIL_LOG_LEVEL, "entering 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(0, "!!!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); TI_Destroy_IH(ti[i]); free(ti[i]); ti[i] = NULL; } } } } void FI_Constructor(FIELD_INFO *self, BOOL reuse) { MYLOG(DETAIL_LOG_LEVEL, "entering 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; MYLOG(DETAIL_LOG_LEVEL, "entering 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); } } static const pgNAME invNAME = {NULL}; #define INIT_IH 32 void TI_Create_IH(TABLE_INFO *ti) { int alloc = INIT_IH; InheritanceClass *ih; ih = (InheritanceClass *) malloc(sizeof(InheritanceClass) + (alloc - 1) * sizeof(ih->inf[0])); memset(ih, 0, sizeof(InheritanceClass)); ih->allocated = alloc; ti->ih = ih; } void TI_Destroy_IH(TABLE_INFO *ti) { InheritanceClass *ih; int i; if (NULL == (ih = ti->ih)) return; for (i = 0; i < ih->count; i++) { NULL_THE_NAME(ih->inf[i].fullTable); } free(ih); ti->ih = NULL; } const pgNAME TI_From_IH(TABLE_INFO *ti, OID tableoid) { InheritanceClass *ih; int i; if (NULL == (ih = ti->ih)) return invNAME; if (tableoid == ih->cur_tableoid) return ih->cur_fullTable; for (i = 0; i < ih->count; i++) { if (ih->inf[i].tableoid == tableoid) { ih->cur_tableoid = tableoid; ih->cur_fullTable = ih->inf[i].fullTable; return ih->cur_fullTable; } } return invNAME; } const pgNAME TI_Ins_IH(TABLE_INFO *ti, OID tableoid, const char *fullName) { InheritanceClass *ih; int count; if (NULL == (ih = ti->ih)) { TI_Create_IH(ti); if (ih = ti->ih, NULL == ih) return invNAME; } if ((count = ih->count) >= ih->allocated) { int alloc = ih->allocated * 2; InheritanceClass *nih; if (nih = (InheritanceClass *) realloc(ih, sizeof(InheritanceClass) + (alloc - 1) * sizeof(ih->inf[0])), NULL == nih) { TI_Destroy_IH(ti); return invNAME; } ti->ih = ih = nih; ih->allocated = alloc; } ih->inf[count].tableoid = tableoid; INIT_NAME(ih->inf[count].fullTable); STR_TO_NAME(ih->inf[count].fullTable, fullName); ih->cur_tableoid = tableoid; ih->cur_fullTable = ih->inf[count].fullTable; ih->count++; return ih->inf[count].fullTable; } void DC_Constructor(DescriptorClass *self, BOOL embedded, StatementClass *stmt) { memset(self, 0, sizeof(DescriptorClass)); self->deschd.embedded = embedded; } static void ARDFields_free(ARDFields * self) { MYLOG(DETAIL_LOG_LEVEL, "entering %p bookmark=%p\n", self, self->bookmark); if (self->bookmark) { free(self->bookmark); self->bookmark = NULL; } /* * 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) { DescriptorHeader *deschd = &(self->deschd); if (deschd->__error_message) { free(deschd->__error_message); deschd->__error_message = NULL; } if (deschd->pgerror) { ER_Destructor(deschd->pgerror); deschd->pgerror = NULL; } if (deschd->type_defined) { switch (deschd->desc_type) { case SQL_ATTR_APP_ROW_DESC: ARDFields_free(&(self->ardf)); break; case SQL_ATTR_APP_PARAM_DESC: APDFields_free(&(self->apdf)); break; case SQL_ATTR_IMP_ROW_DESC: IRDFields_free(&(self->irdf)); break; case SQL_ATTR_IMP_PARAM_DESC: IPDFields_free(&(self->ipdf)); break; } } } void InitializeEmbeddedDescriptor(DescriptorClass *self, StatementClass *stmt, UInt4 desc_type) { DescriptorHeader *deschd = &(self->deschd); DC_Constructor(self, TRUE, stmt); DC_get_conn(self) = SC_get_conn(stmt); deschd->type_defined = TRUE; deschd->desc_type = desc_type; switch (desc_type) { case SQL_ATTR_APP_ROW_DESC: memset(&(self->ardf), 0, sizeof(ARDFields)); InitializeARDFields(&(self->ardf)); stmt->ard = self; break; case SQL_ATTR_APP_PARAM_DESC: memset(&(self->apdf), 0, sizeof(APDFields)); InitializeAPDFields(&(self->apdf)); stmt->apd = self; break; case SQL_ATTR_IMP_ROW_DESC: memset(&(self->irdf), 0, sizeof(IRDFields)); stmt->ird = self; stmt->ird->irdf.stmt = stmt; break; case SQL_ATTR_IMP_PARAM_DESC: memset(&(self->ipdf), 0, sizeof(IPDFields)); stmt->ipd = self; break; } } /* * ARDFields initialize */ void InitializeARDFields(ARDFields *opt) { memset(opt, 0, sizeof(ARDFields)); opt->size_of_rowset = 1; 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; } #define DESC_INCREMENT 10 char CC_add_descriptor(ConnectionClass *self, DescriptorClass *desc) { int i; int new_num_descs; DescriptorClass **descs; MYLOG(0, "entering 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; MYLOG(0, "entering...\n"); desc = (DescriptorClass *) malloc(sizeof(DescriptorClass)); if (desc) { memset(desc, 0, sizeof(DescriptorClass)); 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) { DescriptorClass *desc = (DescriptorClass *) DescriptorHandle; RETCODE ret = SQL_SUCCESS; MYLOG(0, "entering...\n"); DC_Destructor(desc); if (!desc->deschd.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); if (bookmark) 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)); if (!target->bindings) target->allocated = 0; 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(ParameterInfoClass)); if (target->bookmark) 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)); if (!target->parameters) target->allocated = 0; 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)); if (!target->parameters) target->allocated = 0; for (i = 0; i < target->allocated; i++) ParameterImplClass_copy(&src->parameters[i], &target->parameters[i]); } } RETCODE SQL_API PGAPI_CopyDesc(SQLHDESC SourceDescHandle, SQLHDESC TargetDescHandle) { RETCODE ret = SQL_ERROR; DescriptorClass *src, *target; DescriptorHeader *srchd, *targethd; ARDFields *ard_src, *ard_tgt; APDFields *apd_src, *apd_tgt; IPDFields *ipd_src, *ipd_tgt; MYLOG(0, "entering...\n"); src = (DescriptorClass *) SourceDescHandle; target = (DescriptorClass *) TargetDescHandle; srchd = &(src->deschd); targethd = &(target->deschd); if (!srchd->type_defined) { MYLOG(0, "source type undefined\n"); DC_set_error(target, DESC_EXEC_ERROR, "source handle type undefined"); return ret; } if (targethd->type_defined) { MYLOG(DETAIL_LOG_LEVEL, "source type=%d -> target type=%d\n", srchd->desc_type, targethd->desc_type); if (SQL_ATTR_IMP_ROW_DESC == targethd->desc_type) { MYLOG(0, "can't modify IRD\n"); DC_set_error(target, DESC_EXEC_ERROR, "can't copy to IRD"); return ret; } else if (targethd->desc_type != srchd->desc_type) { if (targethd->embedded) { MYLOG(0, "src type != target type\n"); DC_set_error(target, DESC_EXEC_ERROR, "copying different type descriptor to embedded one"); return ret; } } DC_Destructor(target); } ret = SQL_SUCCESS; switch (srchd->desc_type) { case SQL_ATTR_APP_ROW_DESC: MYLOG(DETAIL_LOG_LEVEL, "src=%p target=%p type=%d", src, target, srchd->desc_type); if (!targethd->type_defined) { targethd->desc_type = srchd->desc_type; } ard_src = &(src->ardf); MYPRINTF(DETAIL_LOG_LEVEL, " rowset_size=" FORMAT_LEN " bind_size=" FORMAT_UINTEGER " 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 = &(target->ardf); MYPRINTF(DETAIL_LOG_LEVEL, " target=%p", ard_tgt); ARDFields_copy(ard_src, ard_tgt); MYPRINTF(DETAIL_LOG_LEVEL, " offset_ptr=%p\n", ard_tgt->row_offset_ptr); break; case SQL_ATTR_APP_PARAM_DESC: if (!targethd->type_defined) { targethd->desc_type = srchd->desc_type; } apd_src = &(src->apdf); apd_tgt = &(target->apdf); APDFields_copy(apd_src, apd_tgt); break; case SQL_ATTR_IMP_PARAM_DESC: if (!targethd->type_defined) { targethd->desc_type = srchd->desc_type; } ipd_src = &(src->ipdf); ipd_tgt = &(target->ipdf); IPDFields_copy(ipd_src, ipd_tgt); break; default: MYLOG(0, "invalid descriptor handle type=%d\n", srchd->desc_type); DC_set_error(target, DESC_EXEC_ERROR, "invalid descriptor type"); ret = SQL_ERROR; } if (SQL_SUCCESS == ret) targethd->type_defined = TRUE; return ret; } void DC_clear_error(DescriptorClass *self) { DescriptorHeader *deschd = &(self->deschd); if (deschd->__error_message) { free(deschd->__error_message); deschd->__error_message = NULL; } if (deschd->pgerror) { ER_Destructor(deschd->pgerror); deschd->pgerror = NULL; } deschd->__error_number = 0; deschd->error_row = 0; deschd->error_index = 0; } void DC_set_error(DescriptorClass *self, int errornumber, const char *errormsg) { DescriptorHeader *deschd = &(self->deschd); if (deschd->__error_message) free(deschd->__error_message); deschd->__error_number = errornumber; deschd->__error_message = errormsg ? strdup(errormsg) : NULL; } void DC_set_errormsg(DescriptorClass *self, const char *errormsg) { DescriptorHeader *deschd = &(self->deschd); if (deschd->__error_message) free(deschd->__error_message); deschd->__error_message = errormsg ? strdup(errormsg) : NULL; } const char *DC_get_errormsg(const DescriptorClass *desc) { return desc->deschd.__error_message; } int DC_get_errornumber(const DescriptorClass *desc) { return desc->deschd.__error_number; } /* Map sql commands to statement types */ static const struct { int number; const char ver3str[6]; const char ver2str[6]; } 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 *self) { const DescriptorHeader *deschd = &(self->deschd); PG_ErrorInfo *error; ConnectionClass *conn; EnvironmentClass *env; Int4 errornum; BOOL env_is_odbc3 = TRUE; if (deschd->pgerror) return deschd->pgerror; errornum = deschd->__error_number; error = ER_Constructor(errornum, deschd->__error_message); if (!error) return error; conn = DC_get_conn(self); 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_FIXED(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) { MYLOG(0, "DESCRIPTOR ERROR: func=%s, desc='%s', errnum=%d, errmsg='%s'\n", func, desc, self->deschd.__error_number, nullcheck(self->deschd.__error_message)); } } /* Returns the next SQL error information. */ RETCODE SQL_API PGAPI_DescError(SQLHDESC hdesc, SQLSMALLINT RecNumber, SQLCHAR * szSqlState, SQLINTEGER * pfNativeError, SQLCHAR * szErrorMsg, SQLSMALLINT cbErrorMsgMax, SQLSMALLINT * pcbErrorMsg, UWORD flag) { /* CC: return an error of a hdesc */ DescriptorClass *desc = (DescriptorClass *) hdesc; DescriptorHeader *deschd = &(desc->deschd); MYLOG(0, "entering RecN=%hd\n", RecNumber); deschd->pgerror = DC_create_errorinfo(desc); return ER_ReturnError(deschd->pgerror, RecNumber, szSqlState, pfNativeError, szErrorMsg, cbErrorMsgMax, pcbErrorMsg, flag); } psqlodbc-13.02.0000/odbcapi30.c000644 001751 001751 00000051066 14122574536 017013 0ustar00hiroshihiroshi000000 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" #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) { RETCODE ret; ConnectionClass *conn; MYLOG(0, "Entering\n"); 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); if (*OutputHandle) ((StatementClass *) (*OutputHandle))->external = 1; 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); MYLOG(DETAIL_LOG_LEVEL, "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) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; int BufferLength = 512; /* Is it OK ? */ MYLOG(0, "Entering\n"); 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) { StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #ifndef UNICODE_SUPPORTXX /* 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 ) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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; } #endif /* UNICODE_SUPPORTXX */ /* new function */ RETCODE SQL_API SQLCopyDesc(SQLHDESC SourceDescHandle, SQLHDESC TargetDescHandle) { RETCODE ret; MYLOG(0, "Entering\n"); ret = PGAPI_CopyDesc(SourceDescHandle, TargetDescHandle); return ret; } /* SQLTransact -> SQLEndTran */ RETCODE SQL_API SQLEndTran(SQLSMALLINT HandleType, SQLHANDLE Handle, SQLSMALLINT CompletionType) { RETCODE ret; MYLOG(0, "Entering\n"); 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(0, "Entering %d," FORMAT_LEN "\n", FetchOrientation, FetchOffset); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "bookmark=" FORMAT_LEN " FetchOffset = " FORMAT_LEN "\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(0, "leaving return = %d\n", ret); return ret; } /* SQLFree(Connect/Env/Stmt) -> SQLFreeHandle */ RETCODE SQL_API SQLFreeHandle(SQLSMALLINT HandleType, SQLHANDLE Handle) { RETCODE ret; StatementClass *stmt; ConnectionClass *conn = NULL; MYLOG(0, "Entering\n"); 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; } #ifndef UNICODE_SUPPORTXX /* new function */ RETCODE SQL_API SQLGetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret; MYLOG(0, "Entering\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(0, "Entering\n"); MYLOG(0, "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) { RETCODE ret; MYLOG(0, "Entering Handle=(%u,%p) Rec=%d Id=%d info=(%p,%d)\n", 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(0, "Entering\n"); ret = PGAPI_GetDiagRec(HandleType, Handle, RecNumber, Sqlstate, NativeError, MessageText, BufferLength, TextLength); return ret; } #endif /* UNICODE_SUPPORTXX */ /* new function */ RETCODE SQL_API SQLGetEnvAttr(HENV EnvironmentHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER BufferLength, SQLINTEGER *StringLength) { RETCODE ret; EnvironmentClass *env = (EnvironmentClass *) EnvironmentHandle; MYLOG(0, "Entering " FORMAT_INTEGER "\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(0, "Entering " FORMAT_UINTEGER "\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; StatementClass *stmt = (StatementClass *) StatementHandle; MYLOG(0, "Entering Handle=%p " FORMAT_INTEGER "\n", 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(0, "Entering " FORMAT_INTEGER "\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; } /* new function */ RETCODE SQL_API SQLSetDescField(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT FieldIdentifier, PTR Value, SQLINTEGER BufferLength) { RETCODE ret; MYLOG(0, "Entering 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) { MYLOG(0, "Entering\n"); MYLOG(0, "Error not implemented\n"); return SQL_ERROR; } #endif /* UNICODE_SUPPORTXX */ /* new function */ RETCODE SQL_API SQLSetEnvAttr(HENV EnvironmentHandle, SQLINTEGER Attribute, PTR Value, SQLINTEGER StringLength) { RETCODE ret; EnvironmentClass *env = (EnvironmentClass *) EnvironmentHandle; MYLOG(0, "Entering att=" FORMAT_INTEGER "," FORMAT_ULEN "\n", Attribute, (SQLULEN) 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) { StatementClass *stmt = (StatementClass *) StatementHandle; RETCODE ret; MYLOG(0, "Entering Handle=%p " FORMAT_INTEGER "," FORMAT_ULEN "\n", StatementHandle, Attribute, (SQLULEN) 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); MYLOG(DETAIL_LOG_LEVEL, "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; StatementClass *stmt = (StatementClass *) hstmt; if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; ENTER_STMT_CS(stmt); MYLOG(0, "Entering Handle=%p %d\n", hstmt, operation); SC_clear_error(stmt); StartRollbackState(stmt); ret = PGAPI_BulkOperations(hstmt, operation); ret = DiscardStatementSvp(stmt,ret, FALSE); LEAVE_STMT_CS(stmt); return ret; } psqlodbc-13.02.0000/pgapi30.c000644 001751 001751 00000167134 14122574536 016516 0ustar00hiroshihiroshi000000 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" #include #include #include "environ.h" #include "connection.h" #include "statement.h" #include "descriptor.h" #include "qresult.h" #include "pgapifunc.h" #include "loadlib.h" #include "dlg_specific.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; MYLOG(0, "entering type=%d rec=%d\n", 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(0, "leaving %d\n", 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; MYLOG(0, "entering rec=%d\n", 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; MYLOG(DETAIL_LOG_LEVEL, "rc=" FORMAT_LEN "\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(0, "leaving %d\n", 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(0, "entering " FORMAT_INTEGER "\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) = CC_not_connected(conn); break; case SQL_ATTR_CONNECTION_TIMEOUT: *((SQLUINTEGER *) Value) = 0; break; case SQL_ATTR_METADATA_ID: *((SQLUINTEGER *) Value) = conn->stmtOptions.metadata_id; break; case SQL_ATTR_PGOPT_DEBUG: *((SQLINTEGER *) Value) = conn->connInfo.drivers.debug; break; case SQL_ATTR_PGOPT_COMMLOG: *((SQLINTEGER *) Value) = conn->connInfo.drivers.commlog; break; case SQL_ATTR_PGOPT_PARSE: *((SQLINTEGER *) Value) = conn->connInfo.drivers.parse; break; case SQL_ATTR_PGOPT_USE_DECLAREFETCH: *((SQLINTEGER *) Value) = conn->connInfo.drivers.use_declarefetch; break; case SQL_ATTR_PGOPT_SERVER_SIDE_PREPARE: *((SQLINTEGER *) Value) = conn->connInfo.use_server_side_prepare; break; case SQL_ATTR_PGOPT_FETCH: *((SQLINTEGER *) Value) = conn->connInfo.drivers.fetch_max; break; case SQL_ATTR_PGOPT_UNKNOWNSIZES: *((SQLINTEGER *) Value) = conn->connInfo.drivers.unknown_sizes; break; case SQL_ATTR_PGOPT_TEXTASLONGVARCHAR: *((SQLINTEGER *) Value) = conn->connInfo.drivers.text_as_longvarchar; break; case SQL_ATTR_PGOPT_UNKNOWNSASLONGVARCHAR: *((SQLINTEGER *) Value) = conn->connInfo.drivers.unknowns_as_longvarchar; break; case SQL_ATTR_PGOPT_BOOLSASCHAR: *((SQLINTEGER *) Value) = conn->connInfo.drivers.bools_as_char; break; case SQL_ATTR_PGOPT_MAXVARCHARSIZE: *((SQLINTEGER *) Value) = conn->connInfo.drivers.max_varchar_size; break; case SQL_ATTR_PGOPT_MAXLONGVARCHARSIZE: *((SQLINTEGER *) Value) = conn->connInfo.drivers.max_longvarchar_size; break; case SQL_ATTR_PGOPT_MSJET: *((SQLINTEGER *) Value) = conn->ms_jet; break; case SQL_ATTR_PGOPT_BATCHSIZE: *((SQLINTEGER *) Value) = conn->connInfo.batch_size; break; case SQL_ATTR_PGOPT_IGNORETIMEOUT: *((SQLINTEGER *) Value) = conn->connInfo.ignore_timeout; 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 = &(desc->ardf); 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) { RETCODE ret = SQL_SUCCESS; APDFields *opts = &(desc->apdf); 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) { MYLOG(DETAIL_LOG_LEVEL, "RecN=%d allocated=%d\n", RecNumber, opts->allocated); DC_set_error(desc, DESC_BAD_PARAMETER_NUMBER_ERROR, "bad parameter number"); return SQL_ERROR; } if (RecNumber > opts->allocated) { MYLOG(DETAIL_LOG_LEVEL, "RecN=%d allocated=%d\n", 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 = &(desc->irdf); 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 */ case SQL_DESC_ROWVER: /* read-only */ 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 = &(desc->ipdf); 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) { MYLOG(DETAIL_LOG_LEVEL, "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: case SQL_DESC_ROWVER: /* read-only */ 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 = &(desc->ardf); 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 (DC_get_embedded(desc)) 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->apdf); 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) { MYLOG(DETAIL_LOG_LEVEL, "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: rettype = SQL_IS_SMALLINT; ival = opts->allocated; break; case SQL_DESC_ALLOC_TYPE: /* read-only */ rettype = SQL_IS_SMALLINT; if (DC_get_embedded(desc)) 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 = &(desc->irdf); 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 */ case SQL_DESC_ROWVER: /* read-only */ 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->ipdf); 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) { MYLOG(DETAIL_LOG_LEVEL, "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: case SQL_DESC_ROWVER: /* read-only */ 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(0, "entering Handle=%p " FORMAT_INTEGER "\n", 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(0, "entering for %p: " FORMAT_INTEGER " %p\n", ConnectionHandle, Attribute, Value); switch (Attribute) { case SQL_ATTR_METADATA_ID: conn->stmtOptions.metadata_id = CAST_UPTR(SQLUINTEGER, Value); break; case SQL_ATTR_ANSI_APP: if (SQL_AA_FALSE != CAST_PTR(SQLINTEGER, Value)) { MYLOG(0, "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(0, "the application is unicode\n"); } /*return SQL_ERROR;*/ return SQL_SUCCESS; case SQL_ATTR_ENLIST_IN_DTC: #ifdef WIN32 #ifdef _HANDLE_ENLIST_IN_DTC_ MYLOG(0, "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) { logs_on_off(-1, conn->connInfo.drivers.debug, 0); conn->connInfo.drivers.debug = newValue; logs_on_off(1, conn->connInfo.drivers.debug, 0); MYLOG(0, "debug => %d\n", conn->connInfo.drivers.debug); } else if (newValue == 0 && conn->connInfo.drivers.debug > 0) { MYLOG(0, "debug => %d\n", newValue); logs_on_off(-1, conn->connInfo.drivers.debug, 0); conn->connInfo.drivers.debug = newValue; logs_on_off(1, 0, 0); } break; case SQL_ATTR_PGOPT_COMMLOG: newValue = CAST_UPTR(SQLCHAR, Value); if (newValue > 0) { logs_on_off(-1, 0, conn->connInfo.drivers.commlog); conn->connInfo.drivers.commlog = newValue; logs_on_off(1, 0, conn->connInfo.drivers.commlog); MYLOG(0, "commlog => %d\n", conn->connInfo.drivers.commlog); } else if (newValue == 0 && conn->connInfo.drivers.commlog > 0) { MYLOG(0, "commlog => %d\n", newValue); logs_on_off(-1, 0, conn->connInfo.drivers.commlog); conn->connInfo.drivers.debug = newValue; logs_on_off(1, 0, 0); } break; case SQL_ATTR_PGOPT_PARSE: conn->connInfo.drivers.parse = CAST_UPTR(SQLCHAR, Value); MYLOG(0, "parse => %d\n", conn->connInfo.drivers.parse); break; case SQL_ATTR_PGOPT_USE_DECLAREFETCH: conn->connInfo.drivers.use_declarefetch = CAST_UPTR(SQLCHAR, Value); ci_updatable_cursors_set(&conn->connInfo); MYLOG(0, "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); MYLOG(0, "server_side_prepare => %d\n", conn->connInfo.use_server_side_prepare); break; case SQL_ATTR_PGOPT_FETCH: conn->connInfo.drivers.fetch_max = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "fetch => %d\n", conn->connInfo.drivers.fetch_max); break; case SQL_ATTR_PGOPT_UNKNOWNSIZES: conn->connInfo.drivers.unknown_sizes = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "unknown_sizes => %d\n", conn->connInfo.drivers.unknown_sizes); break; case SQL_ATTR_PGOPT_TEXTASLONGVARCHAR: conn->connInfo.drivers.text_as_longvarchar = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "text_as_longvarchar => %d\n", conn->connInfo.drivers.text_as_longvarchar); break; case SQL_ATTR_PGOPT_UNKNOWNSASLONGVARCHAR: conn->connInfo.drivers.unknowns_as_longvarchar = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "unknowns_as_long_varchar => %d\n", conn->connInfo.drivers.unknowns_as_longvarchar); break; case SQL_ATTR_PGOPT_BOOLSASCHAR: conn->connInfo.drivers.bools_as_char = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "bools_as_char => %d\n", conn->connInfo.drivers.bools_as_char); break; case SQL_ATTR_PGOPT_MAXVARCHARSIZE: conn->connInfo.drivers.max_varchar_size = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "max_varchar_size => %d\n", conn->connInfo.drivers.max_varchar_size); break; case SQL_ATTR_PGOPT_MAXLONGVARCHARSIZE: conn->connInfo.drivers.max_longvarchar_size = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "max_longvarchar_size => %d\n", conn->connInfo.drivers.max_longvarchar_size); break; case SQL_ATTR_PGOPT_WCSDEBUG: conn->connInfo.wcs_debug = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "wcs_debug => %d\n", conn->connInfo.wcs_debug); break; case SQL_ATTR_PGOPT_MSJET: conn->ms_jet = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "ms_jet => %d\n", conn->ms_jet); break; case SQL_ATTR_PGOPT_BATCHSIZE: conn->connInfo.batch_size = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "batch size => %d\n", conn->connInfo.batch_size); break; case SQL_ATTR_PGOPT_IGNORETIMEOUT: conn->connInfo.ignore_timeout = CAST_PTR(SQLINTEGER, Value); MYLOG(0, "ignore_timeout => %d\n", conn->connInfo.ignore_timeout); break; default: if (Attribute < 65536) ret = PGAPI_SetConnectOption(ConnectionHandle, (SQLUSMALLINT) Attribute, (SQLLEN) Value); else unsupported = TRUE; } if (unsupported) { char msg[64]; SPRINTF_FIXED(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(0, "entering h=%p rec=" FORMAT_SMALLI " field=" FORMAT_SMALLI " blen=" FORMAT_INTEGER "\n", DescriptorHandle, RecNumber, FieldIdentifier, BufferLength); switch (DC_get_desc_type(desc)) { 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(0, "entering h=%p(%d) rec=" FORMAT_SMALLI " field=" FORMAT_SMALLI " val=%p," FORMAT_INTEGER "\n", DescriptorHandle, DC_get_desc_type(desc), RecNumber, FieldIdentifier, Value, BufferLength); switch (DC_get_desc_type(desc)) { 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"); break; 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(0, "entering Handle=%p " FORMAT_INTEGER "," FORMAT_ULEN "(%p)\n", StatementHandle, Attribute, (SQLULEN) 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 = (DescriptorClass *) Value; MYLOG(DETAIL_LOG_LEVEL, "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 = (DescriptorClass *) 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; } /* 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) { CSTR func = "bulk_ope_callback"; RETCODE ret = retcode; bop_cdata *s = (bop_cdata *) para; SQLULEN global_idx; ConnectionClass *conn; QResultClass *res; IRDFields *irdflds; PG_BM pg_bm; if (s->need_data_callback) { MYLOG(0, "entering in\n"); s->processed++; s->idx++; } else { s->idx = s->processed = 0; } s->need_data_callback = FALSE; res = SC_get_Curres(s->stmt); for (; SQL_ERROR != ret && s->idx < s->opts->size_of_rowset; s->idx++) { if (SQL_ADD != s->operation) { pg_bm = SC_Resolve_bookmark(s->opts, s->idx); QR_get_last_bookmark(res, s->idx, &pg_bm.keys); global_idx = pg_bm.index; } /* 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, &(pg_bm.keys)); break; case SQL_DELETE_BY_BOOKMARK: ret = SC_pos_delete(s->stmt, (UWORD) s->idx, global_idx, &(pg_bm.keys)); break; } if (SQL_NEED_DATA == ret) { bop_cdata *cbdata = (bop_cdata *) malloc(sizeof(bop_cdata)); if (!cbdata) { SC_set_error(s->stmt, STMT_NO_MEMORY_ERROR, "Couldn't allocate memory for cbdata.", func); return SQL_ERROR; } 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) 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(0, "entering operation = %d\n", 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); */ if (SQL_FETCH_BY_BOOKMARK == operationX) ret = SC_fetch_by_bookmark(s.stmt); else { s.need_data_callback = FALSE; ret = bulk_ope_callback(SQL_SUCCESS, &s); } return ret; } psqlodbc-13.02.0000/mylog.c000644 001751 001751 00000027522 14122574536 016376 0ustar00hiroshihiroshi000000 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 "misc.h" #include #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 */ static char *logdir = NULL; void generate_filename(const char *dirname, const char *prefix, char *filename, size_t filenamelen) { const char *exename = GetExeProgramName(); #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; snprintf(filename, filenamelen, "%s%s", dirname, DIRSEPARATOR); if (prefix != 0) strlcat(filename, prefix, filenamelen); if (exename[0]) snprintfcat(filename, filenamelen, "%s_", exename); #ifndef WIN32 if (ptr) strlcat(filename, ptr->pw_name, filenamelen); #endif snprintfcat(filename, filenamelen, "%u%s", pid, ".log"); return; } static void generate_homefile(const char *prefix, char *filename, size_t filenamelen) { char dir[PATH_MAX]; #ifdef WIN32 const char *ptr; dir[0] = '\0'; if (ptr=getenv("HOMEDRIVE"), NULL != ptr) strlcat(dir, ptr, filenamelen); if (ptr=getenv("HOMEPATH"), NULL != ptr) strlcat(dir, ptr, filenamelen); #else STRCPY_FIXED(dir, "~"); #endif /* WIN32 */ generate_filename(dir, prefix, filename, filenamelen); return; } #ifdef WIN32 static char exename[_MAX_FNAME]; #elif defined MAXNAMELEN static char exename[MAXNAMELEN]; #else static char exename[256]; #endif const char *GetExeProgramName() { static int init = 1; if (init) { UCHAR *p; #ifdef WIN32 char pathname[_MAX_PATH]; if (GetModuleFileName(NULL, pathname, sizeof(pathname)) > 0) _splitpath(pathname, NULL, NULL, exename, NULL); #else CSTR flist[] = {"/proc/self/exe", "/proc/curproc/file", "/proc/curproc/exe" }; int i; char path_name[256]; for (i = 0; i < sizeof(flist) / sizeof(flist[0]); i++) { if (readlink(flist[i], path_name, sizeof(path_name)) > 0) { /* fprintf(stderr, "i=%d pathname=%s\n", i, path_name); */ STRCPY_FIXED(exename, po_basename(path_name)); break; } } #endif /* WIN32 */ for (p = (UCHAR *) exename; '\0' != *p; p++) { if (isalnum(*p)) continue; switch (*p) { case '_': case '-': continue; } *p = '\0'; /* avoid multi bytes for safety */ break; } init = 0; } return exename; } #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 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 */ #define MYLOGFILE "mylog_" #ifndef WIN32 #define MYLOGDIR "/tmp" #else #define MYLOGDIR "c:" #endif /* WIN32 */ #define QLOGFILE "psqlodbc_" #ifndef WIN32 #define QLOGDIR "/tmp" #else #define QLOGDIR "c:" #endif /* WIN32 */ int get_mylog(void) { return mylog_on; } int get_qlog(void) { return qlog_on; } const char *po_basename(const char *path) { char *p; if (p = strrchr(path, DIRSEPARATOR[0]), NULL != p) return p + 1; return path; } 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; 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 (getGlobalDebug() > 0) mylog_on = getGlobalDebug(); LEAVE_MYLOG_CS; ENTER_QLOG_CS; if (qlog_onoff) qlog_on_count += cnopen; else qlog_off_count += cnopen; if (qlog_on_count > 0) { if (qlog_onoff > qlog_on) qlog_on = qlog_onoff; else if (qlog_on < 1) qlog_on = 1; } else if (qlog_off_count > 0) qlog_on = 0; else if (getGlobalCommlog() > 0) qlog_on = getGlobalCommlog(); LEAVE_QLOG_CS; MYLOG(0, "mylog_on=%d qlog_on=%d\n", mylog_on, qlog_on); } #ifdef WIN32 #define LOGGING_PROCESS_TIME #include #endif /* WIN32 */ #ifdef LOGGING_PROCESS_TIME #include static DWORD start_time = 0; #endif /* LOGGING_PROCESS_TIME */ static FILE *MLOGFP = NULL; static void MLOG_open() { char filebuf[80], errbuf[160]; BOOL open_error = FALSE; if (MLOGFP) return; generate_filename(logdir ? logdir : MYLOGDIR, MYLOGFILE, filebuf, sizeof(filebuf)); MLOGFP = fopen(filebuf, PG_BINARY_A); if (!MLOGFP) { int lasterror = GENERAL_ERRNO; open_error = TRUE; SPRINTF_FIXED(errbuf, "%s open error %d\n", filebuf, lasterror); generate_homefile(MYLOGFILE, filebuf, sizeof(filebuf)); MLOGFP = fopen(filebuf, PG_BINARY_A); } if (MLOGFP) { if (open_error) fputs(errbuf, MLOGFP); } } static int mylog_misc(unsigned int option, const char *fmt, va_list args) { // va_list args; int gerrno; BOOL log_threadid = option; 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) { MLOG_open(); if (!MLOGFP) mylog_on = 0; } if (MLOGFP) { if (log_threadid) { #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, "[%lx]", (unsigned long int) pthread_self()); #endif /* POSIX_MULTITHREAD_SUPPORT */ } vfprintf(MLOGFP, fmt, args); fflush(MLOGFP); } // va_end(args); LEAVE_MYLOG_CS; GENERAL_ERRNO_SET(gerrno); return 1; } DLL_DECLARE int mylog(const char *fmt,...) { int ret = 0; unsigned int option = 1; va_list args; if (!mylog_on) return ret; va_start(args, fmt); ret = mylog_misc(option, fmt, args); va_end(args); return ret; } DLL_DECLARE int myprintf(const char *fmt,...) { int ret = 0; va_list args; va_start(args, fmt); ret = mylog_misc(0, fmt, args); va_end(args); return ret; } static void mylog_initialize(void) { INIT_MYLOG_CS; } static void mylog_finalize(void) { mylog_on = 0; if (MLOGFP) { fclose(MLOGFP); MLOGFP = NULL; } DELETE_MYLOG_CS; } static FILE *QLOGFP = NULL; static int qlog_misc(unsigned int option, const char *fmt, va_list args) { char filebuf[80]; int gerrno; if (!qlog_on) return 0; gerrno = GENERAL_ERRNO; ENTER_QLOG_CS; #ifdef LOGGING_PROCESS_TIME if (!start_time) start_time = timeGetTime(); #endif /* LOGGING_PROCESS_TIME */ if (!QLOGFP) { generate_filename(logdir ? logdir : QLOGDIR, QLOGFILE, filebuf, sizeof(filebuf)); QLOGFP = fopen(filebuf, PG_BINARY_A); if (!QLOGFP) { generate_homefile(QLOGFILE, filebuf, sizeof(filebuf)); QLOGFP = fopen(filebuf, PG_BINARY_A); } if (!QLOGFP) qlog_on = 0; } if (QLOGFP) { if (option) { #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); fflush(QLOGFP); } LEAVE_QLOG_CS; GENERAL_ERRNO_SET(gerrno); return 1; } int qlog(char *fmt,...) { int ret = 0; unsigned int option = 1; va_list args; if (!qlog_on) return ret; va_start(args, fmt); ret = qlog_misc(option, fmt, args); va_end(args); return ret; } int qprintf(char *fmt,...) { int ret = 0; va_list args; va_start(args, fmt); ret = qlog_misc(0, fmt, args); va_end(args); return ret; } static void qlog_initialize(void) { INIT_QLOG_CS; } static void qlog_finalize(void) { qlog_on = 0; if (QLOGFP) { fclose(QLOGFP); QLOGFP = NULL; } DELETE_QLOG_CS; } static int globalDebug = -1; int getGlobalDebug() { char temp[16]; if (globalDebug >=0) return globalDebug; /* Debug is stored in the driver section */ SQLGetPrivateProfileString(DBMS_NAME, INI_DEBUG, "", temp, sizeof(temp), ODBCINST_INI); if (temp[0]) globalDebug = atoi(temp); else globalDebug = DEFAULT_DEBUG; return globalDebug; } int setGlobalDebug(int val) { return (globalDebug = val); } static int globalCommlog = -1; int getGlobalCommlog() { char temp[16]; if (globalCommlog >= 0) return globalCommlog; /* Commlog is stored in the driver section */ SQLGetPrivateProfileString(DBMS_NAME, INI_COMMLOG, "", temp, sizeof(temp), ODBCINST_INI); if (temp[0]) globalCommlog = atoi(temp); else globalCommlog = DEFAULT_COMMLOG; return globalCommlog; } int setGlobalCommlog(int val) { return (globalCommlog = val); } int writeGlobalLogs() { char temp[10]; ITOA_FIXED(temp, globalDebug); SQLWritePrivateProfileString(DBMS_NAME, INI_DEBUG, temp, ODBCINST_INI); ITOA_FIXED(temp, globalCommlog); SQLWritePrivateProfileString(DBMS_NAME, INI_COMMLOG, temp, ODBCINST_INI); return 0; } 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); } /* * This function starts a logging out of connections according the ODBCINST.INI * portion of the DBMS_NAME registry. */ static void start_logging() { /* * GlobalDebug or GlobalCommlog means whether take mylog or commlog * out of the connection time or not but doesn't mean the default of * ci->drivers.debug(commlog). */ logs_on_off(0, 0, 0); mylog("\t%s:Global.debug&commlog=%d&%d\n", __FUNCTION__, getGlobalDebug(), getGlobalCommlog()); } void InitializeLogging(void) { char dir[PATH_MAX]; getLogDir(dir, sizeof(dir)); if (dir[0]) logdir = strdup(dir); mylog_initialize(); qlog_initialize(); start_logging(); } void FinalizeLogging(void) { mylog_finalize(); qlog_finalize(); if (logdir) { free(logdir); logdir = NULL; } } psqlodbc-13.02.0000/bind.h000644 001751 001751 00000010515 14122574535 016161 0ustar00hiroshihiroshi000000 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 */ }; /* struct for SQLGetData */ typedef struct { /* for BLOBs which don't hold the data */ struct GetBlobDataClass { Int8 data_left64; /* amount of large object data left to read before conversion */ } blob; /* for non-BLOBs which hold the data in ttlbuf after conversion */ 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 */ } GetDataClass; #define GETDATA_RESET(gdc) ((gdc).blob.data_left64 = (gdc).data_left = -1) /* * 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; #define PARSE_PARAM_CAST FALSE #define EXEC_PARAM_CAST TRUE #define SIMPLE_PARAM_CAST TRUE #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) /* 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, BOOL fake_params); RETCODE prepareParametersNoDesc(StatementClass *stmt, BOOL fake_params, BOOL param_cast); int decideHowToPrepare(StatementClass *stmt, BOOL force); #endif psqlodbc-13.02.0000/catfunc.h000644 001751 001751 00000010727 14122574535 016675 0ustar00hiroshihiroshi000000 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 */ ,COLUMNS_SQL_DATA_TYPE ,COLUMNS_SQL_DATETIME_SUB ,COLUMNS_CHAR_OCTET_LENGTH ,COLUMNS_ORDINAL_POSITION ,COLUMNS_IS_NULLABLE ,COLUMNS_DISPLAY_SIZE ,COLUMNS_FIELD_TYPE ,COLUMNS_AUTO_INCREMENT ,COLUMNS_PHYSICAL_NUMBER ,COLUMNS_TABLE_OID ,COLUMNS_BASE_TYPEID ,COLUMNS_ATTTYPMOD ,COLUMNS_TABLE_INFO ,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 ,FKS_DEFERRABILITY ,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 ,PROCOLS_COLUMN_DEF ,PROCOLS_SQL_DATA_TYPE ,PROCOLS_SQL_DATETIME_SUB ,PROCOLS_CHAR_OCTET_LENGTH ,PROCOLS_ORDINAL_POSITION ,PROCOLS_IS_NULLABLE ,NUM_OF_PROCOLS_FIELDS }; /* SQLGetTypeInfo field position */ enum { GETTYPE_TYPE_NAME = 0 ,GETTYPE_DATA_TYPE ,GETTYPE_COLUMN_SIZE ,GETTYPE_LITERAL_PREFIX ,GETTYPE_LITERAL_SUFFIX ,GETTYPE_CREATE_PARAMS ,GETTYPE_NULLABLE ,GETTYPE_CASE_SENSITIVE ,GETTYPE_SEARCHABLE ,GETTYPE_UNSIGNED_ATTRIBUTE ,GETTYPE_FIXED_PREC_SCALE ,GETTYPE_AUTO_UNIQUE_VALUE ,GETTYPE_LOCAL_TYPE_NAME ,GETTYPE_MINIMUM_SCALE ,GETTYPE_MAXIMUM_SCALE ,GETTYPE_SQL_DATA_TYPE ,GETTYPE_SQL_DATETIME_SUB ,GETTYPE_NUM_PREC_RADIX ,GETTYPE_INTERVAL_PRECISION ,NUM_OF_GETTYPE_FIELDS }; /* SQLSpecialColumns field position */ enum { SPECOLS_SCOPE = 0 ,SPECOLS_COLUMN_NAME ,SPECOLS_DATA_TYPE ,SPECOLS_TYPE_NAME ,SPECOLS_COLUMN_SIZE ,SPECOLS_BUFFER_LENGTH ,SPECOLS_DECIMAL_DIGITS ,SPECOLS_PSEUDO_COLUMN ,NUM_OF_SPECOLS_FIELDS }; /* SQLTablePrivileges field position */ enum { TABPRIV_TABLE_CAT = 0 ,TABPRIV_TABLE_SCHEM ,TABPRIV_TABLE_NAME ,TABPRIV_GRANTOR ,TABPRIV_GRANTEE ,TABPRIV_PRIVILEGE ,TABPRIV_IS_GRANTABLE ,NUM_OF_TABPRIV_FIELDS }; #endif /* __CARFUNC_H__ */ psqlodbc-13.02.0000/columninfo.h000644 001751 001751 00000003363 14122574535 017421 0ustar00hiroshihiroshi000000 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" #include 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); BOOL CI_read_fields_from_pgres(ColumnInfoClass *self, PGresult *pgres); /* 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); void CI_set_field_info(ColumnInfoClass *self, int field_num, const char *new_name, OID new_adtid, Int2 new_adtsize, Int4 atttypmod, OID new_relid, OID new_attid); #endif psqlodbc-13.02.0000/connection.h000644 001751 001751 00000047142 14122574535 017412 0ustar00hiroshihiroshi000000 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 "pqexpbuffer.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; /* 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_SEVERITY_FATAL 108 #define CONNECTION_COULD_NOT_RECEIVE 109 #define CONNECTION_SERVER_REPORTED_SEVERITY_ERROR 110 #define CONNECTION_NEED_PASSWORD 112 #define CONNECTION_COMMUNICATION_ERROR 113 #define CONN_ERROR_IGNORED (-3) #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_ILLEGAL_TRANSACT_STATE 213 #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) /* not connected yet || already disconnected */ #define CC_not_connected(x) (!(x) || CONN_DOWN == (x)->status || CONN_NOT_CONNECTED == (x)->status) /* 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) /* * 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 STRING_AFTER_DOT(string) (strchr(#string, '.') + 1) /* * 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 refcnt; QResultClass *result; pgNAME schema_name; pgNAME table_name; OID table_oid; int table_info; time_t acc_time; }; enum { TBINFO_HASOIDS = 1L ,TBINFO_HASSUBCLASS = (1L << 1) }; #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 (WINAPI * DataSourceToDriverProc) (UDWORD, SWORD, PTR, SDWORD, PTR, SDWORD, SDWORD *, UCHAR *, SWORD, SWORD *); typedef BOOL (WINAPI * DriverToDataSourceProc) (UDWORD, SWORD, PTR, SDWORD, PTR, SDWORD, SDWORD *, UCHAR *, SWORD, SWORD *); /******* The Connection handle ************/ struct ConnectionClass_ { HENV henv; /* environment this connection was * created on */ SQLUINTEGER login_timeout; signed char autocommit_public; 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; PGconn *pqconn; Int4 lobj_type; Int2 coli_allocated; Int2 ntables; COL_INFO **col_info; long translation_option; HINSTANCE translation_handle; DataSourceToDriverProc DataSourceToDriver; DriverToDataSourceProc DriverToDataSource; char transact_status; /* Is a transaction is currently * in progress */ char pg_version[MAX_INFO_STRING]; /* Version of PostgreSQL * we're connected to - * DJP 25-1-2001 */ Int2 pg_version_major; Int2 pg_version_minor; char ms_jet; char unicode; char result_uncommitted; char lo_is_domain; char current_schema_valid; /* is current_schema valid? TRUE when * current_schema == NULL means it's * really NULL, while FALSE means it's * unknown */ unsigned char on_commit_in_progress; /* for per statement rollback */ char internal_svp; /* is set? */ char internal_op; /* operation being executed as to internal savepoint */ unsigned char rbonerr; unsigned char opt_in_progress; unsigned char opt_previous; char *original_client_encoding; char *locale_encoding; char *server_encoding; Int2 ccsc; Int2 mb_maxbyte_per_char; SQLUINTEGER isolation; /* isolation level initially unknown */ SQLUINTEGER server_isolation; /* isolation at server initially unknown */ char *current_schema; StatementClass *unnamed_prepared_stmt; Int2 max_identifier_length; Int2 num_discardp; char **discardp; int num_descs; SQLUINTEGER default_isolation; /* server's default isolation initially unkown */ DescriptorClass **descs; pgNAME schemaIns; pgNAME tableIns; SQLULEN stmt_timeout_in_effect; #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_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_fake_mss(x) (/* 0 != (x)->ms_jet && */ 0 < (x)->connInfo.fake_mss) #define CC_accessible_only(x) (0 < (x)->connInfo.accessible_only) #define CC_default_is_c(x) (CC_is_in_ansi_app(x) || x->ms_jet /* not only */ || TRUE /* but for any other ? */) #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_ */ /* statement callback */ #define CC_start_stmt(a) ((a)->rbonerr = 0) #define CC_start_tc_stmt(a) ((a)->rbonerr = (1L << 1)) #define CC_is_tc_stmt(a) (((a)->rbonerr & (1L << 1)) != 0) #define CC_start_rb_stmt(a) ((a)->rbonerr = (1L << 2)) #define CC_is_rb_stmt(a) (((a)->rbonerr & (1L << 2)) != 0) #define CC_set_accessed_db(a) ((a)->rbonerr |= (1L << 3)) #define CC_accessed_db(a) (((a)->rbonerr & (1L << 3)) != 0) #define CC_start_rbpoint(a) ((a)->rbonerr |= (1L << 4), (a)->internal_svp = 1) #define CC_started_rbpoint(a) (((a)->rbonerr & (1L << 4)) != 0) /* prototypes */ ConnectionClass *CC_Constructor(void); 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 *salt); char CC_add_statement(ConnectionClass *self, StatementClass *stmt); char CC_remove_statement(ConnectionClass *self, StatementClass *stmt) ; char CC_add_descriptor(ConnectionClass *self, DescriptorClass *desc); char CC_remove_descriptor(ConnectionClass *self, DescriptorClass *desc); 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); QResultHold 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).first void handle_pgres_error(ConnectionClass *self, const PGresult *pgres, const char *comment, QResultClass *res, BOOL error_not_a_notice); void CC_clear_error(ConnectionClass *self); int CC_send_function(ConnectionClass *conn, const char *fn_name, void *result_buf, int *actual_result_len, int result_is_int, LO_ARG *argv, int nargs); char CC_send_settings(ConnectionClass *self, const char *set_query); void CC_initialize_pg_version(ConnectionClass *conn); void CC_log_error(const char *func, const char *desc, const ConnectionClass *self); int CC_send_cancel_request(const ConnectionClass *conn); void CC_on_commit(ConnectionClass *conn); void CC_on_abort(ConnectionClass *conn, unsigned int 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 CC_get_max_idlen(ConnectionClass *self); char CC_get_escape(const ConnectionClass *self); char * identifierEscape(const SQLCHAR *src, SQLLEN srclen, const ConnectionClass *conn, char *buf, size_t bufsize, BOOL double_quote); int findIdentifier(const UCHAR *str, int ccsc, const UCHAR **next_token); int eatTableIdentifiers(const UCHAR *str, int ccsc, pgNAME *table, pgNAME *schema); const char *CurrCat(const ConnectionClass *self); const char *CurrCatString(const ConnectionClass *self); SQLUINTEGER CC_get_isolation(ConnectionClass *self); SQLCHAR *make_lstring_ifneeded(ConnectionClass *, const SQLCHAR *s, ssize_t len, BOOL); #define TABLE_IS_VALID(tbname, tblen) ((tbname) && (tblen > 0 || SQL_NTS == tblen)) int schema_str(char *buf, int buflen, const SQLCHAR *s, SQLLEN len, BOOL table_is_valid, ConnectionClass *conn); char *schema_strcat(char *buf, int buflen, const char *fmt, const SQLCHAR *s, SQLLEN len, BOOL table_is_valid, ConnectionClass *conn); char *schema_strcat1(char *buf, int buflen, const char *fmt, const char *s1, const char *s, const SQLCHAR *, int, ConnectionClass *conn); void schema_appendPQExpBuffer(PQExpBufferData *buf, const char *fmt, const SQLCHAR *s, SQLLEN len, BOOL table_is_valid, ConnectionClass *conn); void schema_appendPQExpBuffer1(PQExpBufferData *buf, const char *fmt, const char *s1, const char *s, BOOL table_is_valid, ConnectionClass *conn); void CC_examine_global_transaction(ConnectionClass *self); BOOL CC_set_transact(ConnectionClass *self, UInt4 isolation); int CC_send_client_encoding(ConnectionClass *self, const char *encoding); /* 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 cursors */ ,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 COMMIT command */ ,READ_ONLY_QUERY = (1L << 5) /* the query is read-only */ }; /* CC_on_abort options */ #define NO_TRANS 1L #define CONN_DEAD (1L << 1) /* connection is no longer valid */ /* * This is a libpq notice receiver callback, for handling incoming NOTICE * messages while processing a query. */ typedef struct { ConnectionClass *conn; const char *comment; QResultClass *res; StatementClass *stmt; } notice_receiver_arg; void receive_libpq_notice(void *arg, const PGresult *pgres); /* * internal savepoint related */ #define _RELEASE_INTERNAL_SAVEPOINT /* Internal rollback */ enum { PER_STATEMENT_ROLLBACK = 1 ,PER_QUERY_ROLLBACK }; int CC_internal_rollback(ConnectionClass *, int rollback_type, BOOL ignore_abort); /* Commands generated */ enum { INTERNAL_SAVEPOINT_OPERATION = 1 ,INTERNAL_ROLLBACK_OPERATION }; int GenerateSvpCommand(ConnectionClass *conn, int type, char *cmd, int bufsize); /* Operations in progress */ enum { SAVEPOINT_IN_PROGRESS = 1 ,PREPEND_IN_PROGRESS }; /* StatementSvp entry option */ enum { SVPOPT_RDONLY = 1L ,SVPOPT_REDUCE_ROUNDTRIP = (1L << 1) }; #define INIT_SVPOPT (SVPOPT_RDONLY) #define CC_svp_init(a) ((a)->internal_svp = (a)->internal_op = 0, (a)->opt_in_progress = (a)->opt_previous = INIT_SVPOPT) #define CC_init_opt_in_progress(a) ((a)->opt_in_progress = INIT_SVPOPT) #define CC_init_opt_previous(a) ((a)->opt_previous = INIT_SVPOPT) #ifdef __cplusplus } #endif #endif /* __CONNECTION_H__ */ psqlodbc-13.02.0000/convert.h000644 001751 001751 00000002341 14122574535 016723 0ustar00hiroshihiroshi000000 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 #define COPY_INVALID_STRING_CONVERSION 6 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); SQLLEN pg_hex2bin(const char *in, char *out, SQLLEN len); size_t findTag(const char *str, int ccsc); BOOL build_libpq_bind_params(StatementClass *stmt, int *nParams, OID **paramTypes, char ***paramValues, int **paramLengths, int **paramFormats, int *resultFormat); #ifdef __cplusplus } #endif #endif psqlodbc-13.02.0000/descriptor.h000644 001751 001751 00000016222 14122574535 017424 0ustar00hiroshihiroshi000000 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" typedef struct InheritanceClass { UInt4 allocated; UInt4 count; OID cur_tableoid; pgNAME cur_fullTable; struct { OID tableoid; pgNAME fullTable; } inf[1]; } InheritanceClass; enum { TI_UPDATABLE = 1L ,TI_HASOIDS_CHECKED = (1L << 1) ,TI_HASOIDS = (1L << 2) ,TI_COLATTRIBUTE = (1L << 3) ,TI_HASSUBCLASS = (1L << 4) }; 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; InheritanceClass *ih; } 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)) #define TI_set_hassubclass(ti) (ti->flags |= TI_HASSUBCLASS) #define TI_has_subclass(ti) (0 != (ti->flags & TI_HASSUBCLASS)) #define TI_set_has_no_subclass(ti) (ti->flags &= (~TI_HASSUBCLASS)) void TI_Constructor(TABLE_INFO *, const ConnectionClass *); void TI_Destructor(TABLE_INFO **, int); void TI_Create_IH(TABLE_INFO *ti); void TI_Destroy_IH(TABLE_INFO *ti); const pgNAME TI_From_IH(TABLE_INFO *ti, OID tableoid); const pgNAME TI_Ins_IH(TABLE_INFO *ti, OID tableoid, const char *fullName); 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; } DescriptorHeader; /* * ARD and APD are(must be) of the same format */ struct ARDFields_ { SQLLEN size_of_rowset; /* for ODBC3 fetch operation */ 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 { DescriptorHeader deschd; ARDFields ardopts; } ARDClass; typedef struct { DescriptorHeader deschd; APDFields apdopts; } APDClass; typedef struct { DescriptorHeader deschd; IRDFields irdopts; } IRDClass; typedef struct { DescriptorHeader deschd; IPDFields ipdopts; } IPDClass; ***/ typedef struct { DescriptorHeader deschd; union { ARDFields ardf; APDFields apdf; IRDFields irdf; IPDFields ipdf; }; } DescriptorClass; #define DC_get_conn(a) ((a)->deschd.conn_conn) #define DC_get_desc_type(a) ((a)->deschd.desc_type) #define DC_get_embedded(a) ((a)->deschd.embedded) 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 **); 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); /* 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-13.02.0000/dlg_specific.h000644 001751 001751 00000026116 14122574535 017664 0ustar00hiroshihiroshi000000 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" #ifdef WIN32 #include #include "resource.h" #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Unknown data type sizes */ #define UNKNOWNS_AS_MAX 0 #define UNKNOWNS_AS_DONTKNOW 1 #define UNKNOWNS_AS_LONGEST 2 /* 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" #define INVALID_DRIVER " @@driver not exist@@ " #ifdef UNICODE_SUPPORT #define INI_DSN "PostgreSQL35W" #else #define INI_DSN "PostgreSQL30" #endif /* UNICODE_SUPPORT */ #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 ABBR_DATABASE "DX" /* 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" /* * "Socket", abbreviated as "A8" was used for socket buffer. Now that we do * everything through libpq, it's not used */ #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" /* Controls rollback-on-error * behavior. Called "Protocol" * for historical reasons */ #define ABBR_PROTOCOL "A1" /* "Optimizer", abbreviated to B4 used to stand for "disable genetic query * optimizer". No longer supported, you can use generic ConnSettings instead. #define INI_OPTIMIZER "Optimizer" #define ABBR_OPTIMIZER "B4" */ /* "Ksqo", abbreviated to B5 was used with pre-7.1 server versions for * "keyset query optimization". No longer used. #define INI_KSQO "Ksqo" #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" /* "CancelAsFreeStmt", abbreviated to "C1" was used with ODBC versions older * than 3.51. It was a hack that made SQLCancel to imply * SQLFreeStmt(SQL_CLOSE). It never had an effect in > 3.51 mode. #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" /* * "DisallowPremature", abbreviated "C3", used to mean that we should not * execute a statement prematurely, before SQLExecute() when e.g. * SQLPrepare+SQLDescribeCol is called. We never do that anymore. * #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_NUMERIC_AS "NumericAs" #define ABBR_NUMERIC_AS "D6" #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_KEEPALIVETIME "KeepaliveTime" #define ABBR_KEEPALIVETIME "D1" #define INI_KEEPALIVEINTERVAL "KeepaliveInterval" #define ABBR_KEEPALIVEINTERVAL "D2" #define INI_PQOPT "pqopt" #define ABBR_PQOPT "D5" #define INI_OPTIONAL_ERRORS "OptionalErrors" #define ABBR_OPTIONAL_ERRORS "D7" #define INI_BATCHSIZE "BatchSize" #define ABBR_BATCHSIZE "D8" #define INI_IGNORETIMEOUT "IgnoreTimeout" #define ABBR_IGNORETIMEOUT "D9" #define INI_DTCLOG "Dtclog" #define INI_FETCHREFCURSORS "FetchRefcursors" #define ABBR_FETCHREFCURSORS "DA" /* "PreferLibpq", abbreviated "D4", used to mean whether to prefer libpq. * libpq is now required #define INI_PREFERLIBPQ "PreferLibpq" #define ABBR_PREFERLIBPQ "D3" */ #define ABBR_XAOPT "D4" #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" #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* Bit representation 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_UNKNOWN_DONTKNOW (1L<<6) #define BIT_UNKNOWN_ASMAX (1L<<7) #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_OPTIONALERRORS (1L<<27) #define BIT_FETCHREFCURSORS (1L<<28) #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) #define BIT_DISABLE_CONVERT_FUNC (1L << 7) /* Connection Defaults */ #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_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 "" #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 1 #define DEFAULT_USESERVERSIDEPREPARE 1 #define DEFAULT_LOWERCASEIDENTIFIER 0 #define DEFAULT_SSLMODE SSLMODE_DISABLE #define DEFAULT_NUMERIC_AS (-101) #define DEFAULT_OPTIONAL_ERRORS 0 #define DEFAULT_BATCH_SIZE 100 #define DEFAULT_IGNORETIMEOUT 0 #define DEFAULT_FETCHREFCURSORS 0 #ifdef _HANDLE_ENLIST_IN_DTC_ #define DEFAULT_XAOPT 1 #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* for CC_DSN_info */ #define CONN_DONT_OVERWRITE 0 #define CONN_OVERWRITE 1 /* prototypes */ #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 ds_options3Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK manage_dsnProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); #endif /* WIN32 */ int write_Ci_Drivers(const char *fileName, const char *sectionName, const GLOBAL_VALUES *); int writeDriversDefaults(const char *drivername, const GLOBAL_VALUES *); void writeDSNinfo(const ConnInfo *ci); void getDriversDefaults(const char *drivername, GLOBAL_VALUES *); void getDSNinfo(ConnInfo *ci, const char *configDrvrname); void makeConnectString(char *connect_string, const ConnInfo *ci, UWORD); BOOL get_DSN_or_Driver(ConnInfo *ci, const char *attribute, const char *value); BOOL copyConnAttributes(ConnInfo *ci, const char *attribute, const char *value); int getDriverNameFromDSN(const char *dsn, char *driver_name, int namelen); UInt4 getExtraOptions(const ConnInfo *); BOOL setExtraOptions(ConnInfo *, const char *str, const char *format); char *extract_extra_attribute_setting(const pgNAME setting, const char *attr); signed char ci_updatable_cursors_set(ConnInfo *ci); void getCiAllDefaults(ConnInfo *ci); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __DLG_SPECIFIC_H__ */ psqlodbc-13.02.0000/environ.h000644 001751 001751 00000006675 14122574536 016742 0ustar00hiroshihiroshi000000 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-13.02.0000/unicode_support.h000644 001751 001751 00000002746 14122574536 020477 0ustar00hiroshihiroshi000000 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 __UNICODE_SUPPORT_H__ #define __UNICODE_SUPPORT_H__ #include "psqlodbc.h" #ifdef UNICODE_SUPPORT #define WCLEN sizeof(SQLWCHAR) enum { CONVTYPE_UNKNOWN ,WCSTYPE_UTF16_LE ,WCSTYPE_UTF32_LE ,C16TYPE_UTF16_LE }; 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 get_convtype(void); #define utf8_to_ucs2(utf8str, ilen, ucs2str, buflen) utf8_to_ucs2_lf(utf8str, ilen, FALSE, ucs2str, buflen, FALSE) SQLLEN bindcol_hybrid_estimate(const char *ldt, BOOL lf_conv, char **wcsbuf); SQLLEN bindcol_hybrid_exec(SQLWCHAR *utf16, const char *ldt, size_t n, BOOL lf_conv, char **wcsbuf); SQLLEN bindcol_localize_estimate(const char *utf8dt, BOOL lf_conv, char **wcsbuf); SQLLEN bindcol_localize_exec(char *ldt, size_t n, BOOL lf_conv, char **wcsbuf); SQLLEN bindpara_msg_to_utf8(const char *ldt, char **wcsbuf, SQLLEN used); SQLLEN bindpara_wchar_to_msg(const SQLWCHAR *utf16, char **wcsbuf, SQLLEN used); SQLLEN locale_to_sqlwchar(SQLWCHAR *utf16, const char *ldt, size_t n, BOOL lf_conv); SQLLEN utf8_to_locale(char *ldt, const char * utf8dt, size_t n, BOOL lf_conv); #endif /* UNICODE_SUPPORT */ #endif /* __UNICODE_SUPPORT_H__ */ psqlodbc-13.02.0000/lobj.h000644 001751 001751 00000001670 14122574536 016176 0ustar00hiroshihiroshi000000 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; Int8 integer64; } u; }; #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); Int8 odbc_lo_lseek64(ConnectionClass *conn, int fd, Int8 offset, Int4 len); Int8 odbc_lo_tell64(ConnectionClass *conn, int fd); #endif psqlodbc-13.02.0000/misc.h000644 001751 001751 00000005312 14122574536 016200 0ustar00hiroshihiroshi000000 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 size_t strncpy_null(char *dst, const char *src, ssize_t len); #ifndef HAVE_STRLCAT size_t strlcat(char *, const char *, size_t); #endif /* HAVE_STRLCAT */ int snprintfcat(char *buf, size_t size, const char *format, ...) __attribute__((format(PG_PRINTF_ATTRIBUTE,3,4))); size_t snprintf_len(char *buf, size_t size, const char *format, ...); char *my_trim(char *string); char *make_string(const SQLCHAR *s, SQLINTEGER len, char *buf, size_t bufsize); /* #define GET_SCHEMA_NAME(nspname) (stricmp(nspname, "public") ? nspname : "") */ char *quote_table(const pgNAME schema, const pgNAME table, char *buf, int nuf_size); #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); /* * Macros to safely strcpy, strcat or sprintf to fixed arrays. * */ /* * With GCC, the macro CHECK_NOT_CHAR_P() causes a compilation error * when the target is pointer not a fixed array. */ #if ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406 #define FUNCTION_BEGIN_MACRO ({ #define FUNCTION_END_MACRO ;}) #define CHECK_NOT_CHAR_P(t) \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wunused-variable\"") \ if (0) { typeof(t) dummy_for_check = {};} \ _Pragma ("GCC diagnostic pop") #else #define FUNCTION_BEGIN_MACRO #define FUNCTION_END_MACRO #define CHECK_NOT_CHAR_P(t) #endif /* macro to safely strcpy() to fixed arrays. */ #define STRCPY_FIXED(to, from) \ FUNCTION_BEGIN_MACRO \ CHECK_NOT_CHAR_P(to) \ strncpy_null((to), (from), sizeof(to)) \ FUNCTION_END_MACRO /* macro to safely strcat() to fixed arrays. */ #define STRCAT_FIXED(to, from) \ FUNCTION_BEGIN_MACRO \ CHECK_NOT_CHAR_P(to) \ strlcat((to), (from), sizeof(to)) \ FUNCTION_END_MACRO /* macro to safely sprintf() to fixed arrays. */ #define SPRINTF_FIXED(to, ...) \ FUNCTION_BEGIN_MACRO \ CHECK_NOT_CHAR_P(to) \ snprintf((to), sizeof(to), __VA_ARGS__) \ FUNCTION_END_MACRO /* macro to safely sprintf() & cat to fixed arrays. */ #define SPRINTFCAT_FIXED(to, ...) \ FUNCTION_BEGIN_MACRO \ CHECK_NOT_CHAR_P(to) \ snprintfcat((to), sizeof(to), __VA_ARGS__) \ FUNCTION_END_MACRO #define ITOA_FIXED(to, from) \ FUNCTION_BEGIN_MACRO \ CHECK_NOT_CHAR_P(to) \ snprintf((to), sizeof(to), "%d", from) \ FUNCTION_END_MACRO #ifdef __cplusplus } #endif #endif /* __MISC_H__ */ psqlodbc-13.02.0000/multibyte.h000644 001751 001751 00000004716 14122574536 017272 0ustar00hiroshihiroshi000000 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 int pg_CS_code(const char *stat_string); /* Old Type Compatible */ typedef struct { int ccsc; const UCHAR *encstr; ssize_t pos; int ccst; } encoded_str; #define ENCODE_STATUS(enc) ((enc).ccst) #define ENCODE_PTR(enc) ((enc).encstr + (enc).pos) #define MBCS_NON_ASCII(enc) (0 != (enc).ccst || (enc).encstr[(enc).pos] >= 0x80) 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); const char *derive_locale_encoding(const char *dbencoding); int pg_mb_maxlen(int characterset_code); #endif /* __MULTIBUYTE_H__ */ psqlodbc-13.02.0000/pgapifunc.h000644 001751 001751 00000032614 14122574536 017226 0ustar00hiroshihiroshi000000 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) #define PODBC_SHOW_OID_COLUMN (1L << 3) #define PODBC_ROW_VERSIONING (1L << 4) /* 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_RDONLY (1L << 1) #define PODBC_RECYCLE_STATEMENT (1L << 2) /* Flags for the error handling */ #define PODBC_ALLOW_PARTIAL_EXTRACT 1L /* #define PODBC_ERROR_CLEAR (1L << 1) no longer used */ RETCODE SQL_API PGAPI_AllocConnect(HENV EnvironmentHandle, HDBC * ConnectionHandle); RETCODE SQL_API PGAPI_AllocEnv(HENV * 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 * szConnStrIn, SQLSMALLINT cbConnStrIn, SQLCHAR * szConnStrOut, SQLSMALLINT cbConnStrOutMax, SQLSMALLINT * 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_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); 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); /* Driver-specific connection attributes, for SQLSet/GetConnectAttr() */ enum { SQL_ATTR_PGOPT_DEBUG = 65536 ,SQL_ATTR_PGOPT_COMMLOG = 65537 ,SQL_ATTR_PGOPT_PARSE = 65538 ,SQL_ATTR_PGOPT_USE_DECLAREFETCH = 65539 ,SQL_ATTR_PGOPT_SERVER_SIDE_PREPARE = 65540 ,SQL_ATTR_PGOPT_FETCH = 65541 ,SQL_ATTR_PGOPT_UNKNOWNSIZES = 65542 ,SQL_ATTR_PGOPT_TEXTASLONGVARCHAR = 65543 ,SQL_ATTR_PGOPT_UNKNOWNSASLONGVARCHAR = 65544 ,SQL_ATTR_PGOPT_BOOLSASCHAR = 65545 ,SQL_ATTR_PGOPT_MAXVARCHARSIZE = 65546 ,SQL_ATTR_PGOPT_MAXLONGVARCHARSIZE = 65547 ,SQL_ATTR_PGOPT_WCSDEBUG = 65548 ,SQL_ATTR_PGOPT_MSJET = 65549 ,SQL_ATTR_PGOPT_BATCHSIZE = 65550 ,SQL_ATTR_PGOPT_IGNORETIMEOUT = 65551 }; 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); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* define_PG_API_FUNC_H__ */ psqlodbc-13.02.0000/pgtypes.h000644 001751 001751 00000015401 14122574536 016740 0ustar00hiroshihiroshi000000 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_XML 142 #define PG_TYPE_XMLARRAY 143 #define PG_TYPE_CIDR 650 #define PG_TYPE_FLOAT4 700 #define PG_TYPE_FLOAT8 701 #define PG_TYPE_ABSTIME 702 #define PG_TYPE_UNKNOWN 705 #define PG_TYPE_MONEY 790 #define PG_TYPE_MACADDR 829 #define PG_TYPE_INET 869 #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 /* timestamptz */ #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_ANY 2276 #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_ATP_UNSET (-3) /* atttypmod */ #define PG_ADT_UNSET (-3) /* adtsize_or_longestlen */ #define PG_UNKNOWNS_UNSET 0 /* UNKNOWNS_AS_MAX */ #define PG_WIDTH_OF_BOOLS_AS_CHAR 5 /* * SQL_INTERVAL support is disabled because I found * some applications which are unhappy with it. * #define PG_INTERVAL_AS_SQL_INTERVAL */ OID pg_true_type(const ConnectionClass *, OID, OID); OID sqltype_to_pgtype(const ConnectionClass *conn, SQLSMALLINT fSqlType); OID sqltype_to_bind_pgtype(const ConnectionClass *conn, SQLSMALLINT fSqlType); const char *sqltype_to_pgcast(const ConnectionClass *conn, SQLSMALLINT fSqlType); SQLSMALLINT pgtype_to_concise_type(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); SQLSMALLINT pgtype_to_sqldesctype(const StatementClass *stmt, OID type, int col, int handle_unknown_size_as); 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,int handle_unknown_size_as); SQLSMALLINT pgtype_attr_to_sqldesctype(const ConnectionClass *conn, OID type, int typmod, int adtsize_or_longestlen, int handle_unknown_size_as); 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); SQLSMALLINT ansi_to_wtype(const ConnectionClass *self, SQLSMALLINT ansitype); #define USE_ZONE FALSE #endif psqlodbc-13.02.0000/psqlodbc.h000644 001751 001751 00000046054 14122574536 017064 0ustar00hiroshihiroshi000000 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 */ #else /* WIN32 */ #include #endif /* WIN32 */ #ifdef __INCLUDE_POSTGRES_FE_H__ /* currently not defined */ /* * Unfortunately #including postgres_fe.h causes various trobles. */ #include "postgres_fe.h" #else /* currently */ #if defined(__GNUC__) || defined(__IBMC__) #if ((__GNUC__ * 100) + __GNUC_MINOR__) >= 404 #define PG_PRINTF_ATTRIBUTE gnu_printf #else #define PG_PRINTF_ATTRIBUTE printf #endif #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a))) #else #define __attribute__(x) #define pg_attribute_printf(f,a) #endif /* __GNUC__ || __IBMC__ */ #endif /* __INCLUDE_POSTGRES_FE_H__ */ #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 */ #define ODBCVER 0x0351 /* * Default NAMEDATALEN value in the server. The server can be compiled with * a different value, but this will do. */ #define NAMEDATALEN_V73 64 #ifndef NAMESTORAGELEN #define NAMESTORAGELEN 64 #endif /* NAMESTORAGELEN */ #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 #endif #ifdef __cplusplus extern "C" { #endif #define Int4 int #define UInt4 unsigned int #define Int2 short #define UInt2 unsigned short typedef SQLBIGINT Int8; typedef UInt4 OID; #ifndef SQL_TRUE #define SQL_TRUE TRUE #endif /* SQL_TRUE */ #ifndef SQL_FALSE #define SQL_FALSE FALSE #endif /* SQL_FALSE */ #define FORMAT_SMALLI "%d" /* SQLSMALLINT */ #define FORMAT_USMALLI "%u" /* SQLUSMALLINT */ #ifdef WIN32 #ifndef SSIZE_T_DEFINED #define ssize_t SSIZE_T #define SSIZE_T_DEFINED #endif /* SSIZE_T */ #define FORMAT_SIZE_T "%Iu" /* size_t */ #define FORMAT_SSIZE_T "%Id" /* ssize_t */ #define FORMAT_INTEGER "%ld" /* SQLINTEGER */ #define FORMAT_UINTEGER "%lu" /* SQLUINTEGER */ #define FORMATI64 "%I64d" /* SQLBIGINT */ #define FORMATI64U "%I64u" /* SQLUBIGINT */ #ifdef _WIN64 #define FORMAT_LEN "%I64d" /* SQLLEN */ #define FORMAT_ULEN "%I64u" /* SQLULEN */ #define FORMAT_POSIROW "%I64u" #else /* _WIN64 */ #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #define FORMAT_POSIROW "%hu" #endif /* _WIN64 */ #else /* WIN32 */ #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) /* ILP32 or LP64 */ typedef long LONG_PTR; typedef unsigned long ULONG_PTR; #elif defined (HAVE_LONG_LONG) /* LLP64 */ typedef long long LONG_PTR; typedef unsigned long long ULONG_PTR; #else /* SIZEOF_VOID_P */ #error appropriate long pointer type not found #endif /* SIZEOF_VOID_P */ #if (SIZEOF_LONG == 8) /* LP64 */ #define FORMAT_INTEGER "%d" /* SQLINTEGER */ #define FORMAT_UINTEGER "%u" /* SQLUINTEGER */ #define FORMATI64 "%ld" /* SQLBIGINT */ #define FORMATI64U "%lu" /* SQLUBIGINT */ #if defined(WITH_UNIXODBC) && defined(BUILD_LEGACY_64_BIT_MODE) #define FORMAT_LEN "%d" /* SQLLEN */ #define FORMAT_ULEN "%u" /* SQLULEN */ #else /* WITH_UNIXODBC */ #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #endif /* WITH_UNIXODBC */ #else /* SIZEOF_LONG */ #define FORMAT_INTEGER "%ld" /* SQLINTEGER */ #define FORMAT_UINTEGER "%lu" /* SQLUINTEGER */ #if defined(HAVE_LONG_LONG) #define FORMATI64 "%lld" /* SQLBIGINT */ #define FORMATI64U "%llu" /* SQLUBIGINT */ #if (SIZEOF_VOID_P == 8) /* LLP64 */ #define FORMAT_LEN "%lld" /* SQLLEN */ #define FORMAT_ULEN "%llu" /* SQLULEN */ #else /* SIZEOF_VOID_P ILP32 */ #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #endif /* SIZEOF_VOID_P */ #else /* HAVE_LONG_LONG */ #define FORMAT_LEN "%ld" /* SQLLEN */ #define FORMAT_ULEN "%lu" /* SQLULEN */ #endif /* HAVE_LONG_LONG */ #endif /* SIZEOF_LONG */ #if (SIZEOF_VOID_P == 8) && !defined(WITH_IODBC) #define FORMAT_POSIROW FORMAT_ULEN #else #define FORMAT_POSIROW "%u" #endif #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 #if (_MSC_VER < 1900) /* vc12 or under */ #define POSIX_SNPRINTF_REQUIRED #define snprintf posix_snprintf extern int posix_snprintf(char *buf, size_t size, const char *format, ...); #endif /* _MSC_VER */ #ifndef strdup #define strdup _strdup #endif /* strdup */ #define strnicmp _strnicmp #define stricmp _stricmp #endif /* WIN32 */ #define IS_NOT_SPACE(c) ((c) && !isspace((UCHAR) c)) #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" #define DBMS_NAME_UNICODE "PostgreSQL Unicode" #define DBMS_NAME_ANSI "PostgreSQL ANSI" #define DRIVER_ODBC_VER "03.51" #ifdef UNICODE_SUPPORT #define WCLEN sizeof(SQLWCHAR) SQLULEN ucs2strlen(const SQLWCHAR *); #else #undef SQL_WCHAR #undef SQL_WVARCHAR #undef SQL_WLONGVARCHAR #undef SQL_C_WCHAR #define SQL_WCHAR SQL_WCHAR_IS_INHIBITED #define SQL_WVARCHAR SQL_WVARCHAR_IS_INHIBITED #define SQL_WLONGVARCHAR SQL_WLONGVARCHAR_IS_INHIBITED #define SQL_C_WCHAR SQL_C_WCHAR_IS_INHIBITED #endif #ifndef DBMS_NAME #ifdef _WIN64 #ifdef UNICODE_SUPPORT #define DBMS_NAME DBMS_NAME_UNICODE"(x64)" #else #define DBMS_NAME DBMS_NAME_ANSI"(x64)" #endif /* UNICODE_SUPPORT */ #else /* _WIN64 */ #ifdef UNICODE_SUPPORT #define DBMS_NAME DBMS_NAME_UNICODE #else #define DBMS_NAME DBMS_NAME_ANSI #endif /* UNICODE_SUPPORT */ #endif /* _WIN64 */ #endif /* DBMS_NAME */ #ifndef DBMS_NAME #define DBMS_NAME "PostgreSQL Legacy" #endif /* DBMS_NAME */ #ifdef WIN32 #ifdef UNICODE_SUPPORT #define DRIVER_FILE_NAME "PSQLODBC35W.DLL" #else #define DRIVER_FILE_NAME "PSQLODBC30A.DLL" #endif /* UNICODE_SUPPORT */ #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 MAXPGPATH 1024 /* see an easy way round this - DJP 24-1-2001 */ #define MAX_CONNECT_STRING 4096 #define FETCH_MAX 100 /* default number of rows to cache * for declare/fetch */ #define TUPLE_MALLOC_INC 100 #define MAX_CONNECTIONS 128 /* conns per environment * (arbitrary) */ #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 */ typedef struct ConnectionClass_ ConnectionClass; typedef struct StatementClass_ StatementClass; typedef struct QResultClass_ QResultClass; 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; typedef struct QResultHold_struct { QResultClass *first; QResultClass *last; } QResultHold; /* 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); \ if ((the_name).name) \ { \ memcpy((the_name).name, str, (n)); \ (the_name).name[(n)] = '\0'; \ } \ } \ else \ (the_name).name = NULL; \ } 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 unknown_sizes; int max_varchar_size; int max_longvarchar_size; char debug; char commlog; char unique_index; char use_declarefetch; char text_as_longvarchar; char unknowns_as_longvarchar; char bools_as_char; char lie; char parse; char extra_systable_prefixes[MEDIUM_REGISTRY_LEN]; char protocol[SMALL_REGISTRY_LEN]; } GLOBAL_VALUES; void copy_globals(GLOBAL_VALUES *to, const GLOBAL_VALUES *from); void init_globals(GLOBAL_VALUES *glbv); 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; SQLUINTEGER metadata_id; SQLULEN stmt_timeout; } StatementOptions; /* Used to pass extra query info to send_query */ typedef struct QueryInfo_ { SQLLEN row_size; SQLLEN fetch_size; QResultClass *result_in; const char *cursor; } QueryInfo; /* Used to save the error information */ typedef struct { UInt4 status; Int2 errorsize; Int2 recsize; Int2 errorpos; char sqlstate[6]; SQLLEN diag_row_count; char __error_message[40]; } 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 *, SQLINTEGER *, UCHAR *, SQLSMALLINT, SQLSMALLINT *, 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 /* Sufficient digits to recover original float values */ #define PG_REAL_DIGITS 9 #define PG_DOUBLE_DIGITS 17 #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) /* 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 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 password_required; char conn_settings_in_str; char pqopt_in_str; pgNAME conn_settings; pgNAME pqopt; 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 accessible_only; signed char ignore_round_trip_time; signed char disable_keepalive; signed char disable_convert_func; signed char wcs_debug; signed char numeric_as; signed char optional_errors; signed char ignore_timeout; signed char fetch_refcursors; UInt4 extra_opts; Int4 keepalive_idle; Int4 keepalive_interval; Int4 batch_size; #ifdef _HANDLE_ENLIST_IN_DTC_ signed char xa_opt; #endif /* _HANDLE_ENLIST_IN_DTC_ */ GLOBAL_VALUES drivers; /* moved from driver's option */ } ConnInfo; #define SUPPORT_DESCRIBE_PARAM(conninfo_) (conninfo_->use_server_side_prepare) int initialize_global_cs(void); enum { /* CC_conninfo_init option */ CLEANUP_FOR_REUSE = 1L /* reuse the info */ ,INIT_GLOBALS = (1L << 1) /* init globals memebers */ }; void CC_conninfo_init(ConnInfo *conninfo, UInt4 option); void CC_conninfo_release(ConnInfo *conninfo); void CC_copy_conninfo(ConnInfo *ci, const ConnInfo *sci); const char *GetExeProgramName(); #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 */ /* 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)"; #define OID_NAME "oid" #define XMIN_NAME "xmin" #define TABLEOID_NAME "tableoid" 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 */ }; #ifdef __cplusplus } #endif #include "mylog.h" #endif /* __PSQLODBC_H__ */ psqlodbc-13.02.0000/qresult.h000644 001751 001751 00000030677 14122574536 016760 0ustar00hiroshihiroshi000000 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 "libpq-fe.h" #include "connection.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_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 *lnext; /* 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 */ UInt4 rowset_size_include_ommitted; /* PG restriction */ SQLLEN recent_processed_row_count; SQLULEN cache_size; SQLULEN cmd_fetch_size; 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 ? */ po_ind_t 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_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 { \ MYLOG(1, "set the number to " FORMAT_LEN " to read next\n", number); \ self->fetch_number = number; \ } while (0) #define QR_inc_next_in_cache(self) \ do { \ MYLOG(1, "increased the number " FORMAT_LEN, self->fetch_number); \ self->fetch_number++; \ MYLOG(1, "to " FORMAT_LEN " to next read\n", self->fetch_number); \ } while (0) #define QR_concat(self, a) ((self)->lnext=(a)) #define QR_detach(self) ((self)->lnext=NULL) #define QR_nextr(self) ((self)->lnext) #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_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); int QR_next_tuple(QResultClass *self, StatementClass *); int QR_close(QResultClass *self); void QR_on_close_cursor(QResultClass *self); void QR_close_result(QResultClass *self, BOOL destroy); void QR_reset_for_re_execute(QResultClass *self); BOOL QR_from_PGresult(QResultClass *self, StatementClass *stmt, ConnectionClass *conn, const char *cursor, PGresult **pgres); 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_reqsize(QResultClass *self, Int4 reqsize); 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); SQLLEN QR_move_cursor_to_last(QResultClass *self, StatementClass *stmt); BOOL QR_get_last_bookmark(const QResultClass *self, Int4 index, KeySet *keyset); int QR_search_by_fieldname(const QResultClass *self, const char *name); #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) #define QR_REALLOC_gexit_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); \ QR_free_memory(a); \ QR_set_messageref(a, m); \ r; \ goto cleanup; \ } \ t = tmp; \ } while (0) #ifdef __cplusplus } #endif #endif /* __QRESULT_H__ */ psqlodbc-13.02.0000/resource.h000644 001751 001751 00000011577 14122574536 017106 0ustar00hiroshihiroshi000000 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 IDS_ADVANCE_OPTION_DSN3 10 #define IDS_ADVANCE_OPTION_CON3 11 #define DLG_OPTIONS_DRV 102 #define DLG_OPTIONS_DS 103 #define DLG_OPTIONS_GLOBAL 104 #define DLG_OPTIONS_DS3 105 #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 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_OR_DSN 1059 #define DRV_DEBUG 1060 #define DS_OPTIONALERRORS 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_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 #define DS_DISABLE_KEEPALIVE 1088 #define DS_KEEPALIVETIME 1089 #define DS_KEEPALIVEINTERVAL 1090 #define DS_DEFAULT_DTCLOG 1091 #define DS_DTCLOG 1092 #define DS_NO_DTCLOG 1093 #define DS_DTC_NO_USE 1097 #define DS_DTC_LINK_ONLY 1098 #define DS_DTC_SIMPLE_PRECHECK 1099 #define DS_DTC_CONFIRM_RM_CONNECTION 1100 #define ID1STPAGE 1101 #define ID2NDPAGE 1102 #define ID3RDPAGE 1103 #define DS_LIBPQOPT 1104 #define DS_COMMLOG 1105 #define DS_DEBUG 1106 #define DS_NUMERIC_AS_DEFAULT 1107 #define DS_NUMERIC_AS_NUMERIC 1108 #define DS_NUMERIC_AS_VARCHAR 1109 #define DS_NUMERIC_AS_DOUBLE 1110 #define DS_NUMERIC_AS_LONGVARCHAR 1111 #define DS_BATCH_SIZE 1112 #define DS_IGNORETIMEOUT 1113 #define DS_FETCH_REFCURSORS 1114 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 106 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1115 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif psqlodbc-13.02.0000/statement.h000644 001751 001751 00000050235 14122574536 017255 0ustar00hiroshihiroshi000000 000000 /* File: statement.hPD * * Description: See "statement.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __STATEMENT_H__ #define __STATEMENT_H__ #include "psqlodbc.h" #include #include "pqexpbuffer.h" #include "pgtypes.h" #include "bind.h" #include "descriptor.h" #include "tuple.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_DESCRIBED, /* 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 parse the query _before_ * the actual call to SQLExecute, and the * result set contains only column information, * but no actual data. */ 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 ,STMT_STRING_CONVERSION_ERROR }; /* statement types */ enum { STMT_TYPE_UNKNOWN = -2 ,STMT_TYPE_OTHER = -1 ,STMT_TYPE_SELECT = 0 ,STMT_TYPE_WITH ,STMT_TYPE_PROCCALL ,STMT_TYPE_TRANSACTION ,STMT_TYPE_DECLARE ,STMT_TYPE_FETCH ,STMT_TYPE_CLOSE ,STMT_TYPE_INSERT ,STMT_TYPE_UPDATE ,STMT_TYPE_DELETE ,STMT_TYPE_CREATE ,STMT_TYPE_ALTER ,STMT_TYPE_DROP ,STMT_TYPE_GRANT ,STMT_TYPE_REVOKE ,STMT_TYPE_LOCK ,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_MOVE ,STMT_TYPE_COPY ,STMT_TYPE_START ,STMT_TYPE_SPECIAL }; #define STMT_UPDATE(stmt) ((stmt)->statement_type > STMT_TYPE_PROCCALL) /* 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 }; /* Type of the 3rd parameter of Exec_with_parameters_resolved() */ typedef enum { DIRECT_EXEC, DEFFERED_EXEC, LAST_EXEC } EXEC_TYPE; #define PG_NUM_NORMAL_KEYS 2 typedef RETCODE (*NeedDataCallfunc)(RETCODE, void *); typedef struct { NeedDataCallfunc func; void *data; } NeedDataCallback; /* * ProcessedStmt represents a fragment of the original SQL query, after * converting ? markers to $n style, processing ODBC escapes, and splitting * a multi-statement into individual statements. Each individual statement * is represented by one ProcessedStmt struct. */ struct ProcessedStmt { struct ProcessedStmt *next; char *query; int num_params; /* number of parameter markers in this, * fragment or -1 if not known */ }; typedef struct ProcessedStmt ProcessedStmt; /******** Statement Handle ***********/ struct StatementClass_ { ConnectionClass *hdbc; /* pointer to ConnectionClass this * statement belongs to */ QResultHold rhold; QResultClass *curres; /* the current result in the chain */ QResultClass *parsed; /* parsed result before exec */ HSTMT *phstmt; StatementOptions options; StatementOptions options_orig; /* attached descriptor handles */ DescriptorClass *ard; DescriptorClass *apd; DescriptorClass *ird; DescriptorClass *ipd; /* implicit descriptor handles */ DescriptorClass ardi; DescriptorClass irdi; DescriptorClass apdi; DescriptorClass 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 */ /* * processed_statements is the SQL after splitting multi-statement into * parts, and replacing ? markers with $n style markers, or injecting the * values in UseServerSidePrepare=0 mode. */ ProcessedStmt *processed_statements; 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 external; /* Allocated via SQLAllocHandle() */ po_ind_t transition_status; /* Transition status */ po_ind_t multi_statement; /* -1:unknown 0:single 1:multi */ po_ind_t rb_or_tc; /* 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 has_notice; /* exec result contains notice messages ? */ pgNAME cursor_name; char *plan_name; char *stmt_with_params; /* statement after parameter * substitution */ SQLLEN exec_start_row; SQLLEN exec_end_row; SQLLEN exec_current_row; unsigned char miscinfo; unsigned char execinfo; po_ind_t updatable; SQLLEN diag_row_count; char *load_statement; /* to (re)load updatable individual rows */ ssize_t from_pos; ssize_t load_from_pos; ssize_t where_pos; SQLLEN last_fetch_count_include_ommitted; time_t stmt_time; struct tm localtime; // for batch execution signed char use_server_side_prepare; int batch_size; EXEC_TYPE exec_type; int count_of_deffered; PQExpBufferData stmt_deffered; /* 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); void SC_set_ResultHold(StatementClass *self, QResultHold rhold); QResultClass *SC_get_lastres(StatementClass *stmt); #define SC_get_Result(a) ((a)->rhold).first #define SC_set_Curres(a, b) ((a)->curres = b) #define SC_get_Curres(a) ((a)->curres) #define SC_get_ExecdOrParsed(a) ((a)->curres ? (a)->curres : (a)->parsed) #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)->ardf)) #define SC_get_APDF(a) (&(SC_get_APD(a)->apdf)) #define SC_get_IRDF(a) (&(SC_get_IRD(a)->irdf)) #define SC_get_IPDF(a) (&(SC_get_IPD(a)->ipdf)) #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_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_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 *); #define SC_is_lower_case(a, b) ((a)->options.metadata_id || (b)->connInfo.lower_case_identifier) #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_MALLOC_gexit_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"); \ r; \ goto cleanup; \ } \ } 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) #define SC_REALLOC_gexit_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, __FUNCTION__); \ r; \ goto cleanup; \ } \ 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) , 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 /* Is currently, or once was, prepared as unnamed * statement. You must check * connection->unnamed_prepared_stmt to see if it * still is */ }; /* misc info */ #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_miscinfo_clear(a) ((a)->miscinfo = 0) #define SC_set_with_hold(a) ((a)->execinfo |= 1L) #define SC_set_without_hold(a) ((a)->execinfo &= (~1L)) #define SC_is_with_hold(a) (((a)->execinfo & 1L) != 0) #define SC_set_readonly(a) ((a)->execinfo |= (1L << 1)) #define SC_set_no_readonly(a) ((a)->execinfo &= ~(1L << 1)) #define SC_is_readonly(a) (((a)->execinfo & (1L << 1)) != 0) #define SC_execinfo_clear(a) (((a)->execinfo = 0) #define STMT_HAS_NO_JOIN 0L #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_tc_stmt(a) ((a)->rb_or_tc = (1L << 1)) #define SC_is_tc_stmt(a) (((a)->rb_or_tc & (1L << 1)) != 0) #define SC_start_rb_stmt(a) ((a)->rb_or_tc = (1L << 2)) #define SC_is_rb_stmt(a) (((a)->rb_or_tc & (1L << 2)) != 0) #define SC_unref_CC_error(a) (((a)->ref_CC_error) = FALSE) #define SC_ref_CC_error(a) (((a)->ref_CC_error) = TRUE) #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) /* 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); void SC_reset_result_for_rerun(StatementClass *self); 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_describe(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); struct tm *SC_get_localtime(StatementClass *self); SQLLEN SC_get_int4_bookmark(StatementClass *self); RETCODE SC_pos_reload(StatementClass *self, SQLULEN index, UInt2 *, Int4); RETCODE SC_pos_update(StatementClass *self, SQLSETPOSIROW irow, SQLULEN index, const KeySet *keyset); RETCODE SC_pos_delete(StatementClass *self, SQLSETPOSIROW irow, SQLULEN index, const KeySet *keyset); RETCODE SC_pos_refresh(StatementClass *self, SQLSETPOSIROW irow, SQLULEN index); RETCODE SC_pos_fetch(StatementClass *self, const PG_BM *pg_bm); RETCODE SC_pos_add(StatementClass *self, SQLSETPOSIROW irow); RETCODE SC_fetch_by_bookmark(StatementClass *self); int SC_Create_bookmark(StatementClass *stmt, BindInfoClass *bookmark, Int4 row_pos, Int4 currTuple, const KeySet *keyset); PG_BM SC_Resolve_bookmark(const ARDFields *opts, Int4 idx); int SC_set_current_col(StatementClass *self, int col); void SC_setInsertedTable(StatementClass *, RETCODE); void SC_scanQueryAndCountParams(const char *, const ConnectionClass *, ssize_t *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); BOOL SC_connection_lost_check(StatementClass *stmt, const char *funcname); int enqueueNeedDataCallback(StatementClass *self, NeedDataCallfunc, void *); RETCODE dequeueNeedDataCallback(RETCODE, StatementClass *self); void cancelNeedDataState(StatementClass *self); int StartRollbackState(StatementClass *self); RETCODE SetStatementSvp(StatementClass *self, unsigned int option); RETCODE DiscardStatementSvp(StatementClass *self, RETCODE, BOOL errorOnly); QResultClass *ParseAndDescribeWithLibpq(StatementClass *stmt, const char *plan_name, const char *query_p, Int2 num_params, const char *comment, QResultClass *res); BOOL CheckPgClassInfo(StatementClass *); /* * 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_int4_bookmark(b) ((b < 0) ? (b) : (b + BOOKMARK_SHIFT)) #define SC_resolve_int4_bookmark(b) ((b < 0) ? (b) : (b - BOOKMARK_SHIFT)) #endif /* __STATEMENT_H__ */ psqlodbc-13.02.0000/tuple.h000644 001751 001751 00000004261 14122574536 016400 0ustar00hiroshihiroshi000000 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; OID oid; 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); typedef struct _PG_BM_ { Int4 index; KeySet keys; } PG_BM; #endif psqlodbc-13.02.0000/version.h000644 001751 001751 00000001126 14122576377 016736 0ustar00hiroshihiroshi000000 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 "13.02.0000" #endif #ifndef POSTGRES_RESOURCE_VERSION #define POSTGRES_RESOURCE_VERSION POSTGRESDRIVERVERSION #endif #ifndef PG_DRVFILE_VERSION #define PG_DRVFILE_VERSION 13,2,00,00 #endif #endif psqlodbc-13.02.0000/pgenlist.h000644 001751 001751 00000001641 14122574536 017073 0ustar00hiroshihiroshi000000 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_ #undef DLL_DECLARE #ifdef _PGENLIST_FUNCS_IMPLEMENT_ #define DLL_DECLARE _declspec(dllexport) #else #ifdef _PGENLIST_FUNCS_IMPORT_ #define DLL_DECLARE _declspec(dllimport) #else #define DLL_DECLARE #endif /* _PGENLIST_FUNCS_IMPORT_ */ #endif /* _PGENLIST_FUNCS_IMPLEMENT_ */ RETCODE EnlistInDtc(void *conn, void *pTra, int method); RETCODE DtcOnDisconnect(void *); RETCODE IsolateDtcConn(void *, BOOL continueConnection); // for testing DLL_DECLARE void *GetTransactionObject(HRESULT *hres); DLL_DECLARE void ReleaseTransactionObject(void *); #endif /* _HANDLE_ENLIST_IN_DTC_ */ #endif /* WIN32 */ #ifdef __cplusplus } #endif #endif /* __PGENLIST_H__ */ psqlodbc-13.02.0000/mylog.h000644 001751 001751 00000006200 14122574536 016371 0ustar00hiroshihiroshi000000 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 #ifndef __GNUC__ #define __attribute__(x) #endif DLL_DECLARE int mylog(const char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2))); DLL_DECLARE int myprintf(const char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2))); extern int qlog(char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2))); extern int qprintf(char *fmt,...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2))); const char *po_basename(const char *path); #define PREPEND_FMT "%10.10s[%s]%d: " #define PREPEND_ITEMS ,po_basename(__FILE__), __FUNCTION__, __LINE__ #define QLOG_MARK "[QLOG]" #ifdef __GNUC__ #define MYLOG(level, fmt, ...) (level < get_mylog() ? mylog(PREPEND_FMT fmt PREPEND_ITEMS, ##__VA_ARGS__) : 0) #define MYPRINTF(level, fmt, ...) (level < get_mylog() ? myprintf((fmt), ##__VA_ARGS__) : 0) #define QLOG(level, fmt, ...) ((level < get_qlog() ? qlog((fmt), ##__VA_ARGS__) : 0), MYLOG(level, QLOG_MARK fmt, ##__VA_ARGS__)) #define QPRINTF(level, fmt, ...) ((level < get_qlog() ? qprintf((fmt), ##__VA_ARGS__) : 0), MYPRINTF(level, (fmt), ##__VA_ARGS__)) #elif defined WIN32 /* && _MSC_VER > 1800 */ #define MYLOG(level, fmt, ...) (level < get_mylog() ? mylog(PREPEND_FMT fmt PREPEND_ITEMS, __VA_ARGS__) : (printf || printf((fmt), __VA_ARGS__))) #define MYPRINTF(level, fmt, ...) (level < get_mylog() ? myprintf(fmt, __VA_ARGS__) : (printf || printf((fmt), __VA_ARGS__))) #define QLOG(level, fmt, ...) ((level < get_qlog() ? qlog((fmt), __VA_ARGS__) : (printf || printf(fmt, __VA_ARGS__))), MYLOG(level, QLOG_MARK fmt, __VA_ARGS__)) #define QPRINTF(level, fmt, ...) ((level < get_qlog() ? qprintf(fmt, __VA_ARGS__) : (printf || printf((fmt), __VA_ARGS__))), MYPRINTF(level, (fmt), __VA_ARGS__)) #else #define MYLOG(level, ...) (level < get_mylog() ? (mylog(PREPEND_FMT PREPEND_ITEMS), myprintf(__VA_ARGS__)) : 0) #define MYPRINTF(level, ...) (level < get_mylog() ? myprintf(__VA_ARGS__) : 0) #define QLOG(level, ...) ((level < get_qlog() ? qlog(__VA_ARGS__) : 0), MYLOG(level, QLOG_MARK), MYPRINTF(level, __VA_ARGS__)) #define QPRINTF(level, ...) ((level < get_qlog() ? qprintf(__VA_ARGS__) : 0), MYPRINTF(level, __VA_ARGS__)) #endif /* __GNUC__ */ #define MIN_LOG_LEVEL 0 #define TUPLE_LOG_LEVEL 1 #define DETAIL_LOG_LEVEL 2 int get_qlog(void); int get_mylog(void); int getGlobalDebug(); int setGlobalDebug(int val); int getGlobalCommlog(); int setGlobalCommlog(int val); int writeGlobalLogs(); int getLogDir(char *dir, int dirmax); int setLogDir(const char *dir); void InitializeLogging(void); void FinalizeLogging(void); #ifdef __cplusplus } #endif #endif /* __MYLOG_H__ */ psqlodbc-13.02.0000/xalibname.h000644 001751 001751 00000000730 14122574536 017204 0ustar00hiroshihiroshi000000 000000 /* File: xalibname.h * * Description: See "xalibname.c" * * Comments: See "readme.txt" for copyright and license information. * */ #ifndef __XALIBNAME_H__ #define __XALIBNAME_H__ #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 #ifdef _HANDLE_ENLIST_IN_DTC_ BOOL IsWow64(void); const char *GetXaLibName(void); const char *GetXaLibPath(void); #endif /* _HANDLE_ENLIST_IN_DTC_ */ #endif /* WIN32 */ #ifdef __cplusplus } #endif #endif /* __XALIBNAME_H__ */ psqlodbc-13.02.0000/odbcapi30w.c000644 001751 001751 00000025620 14122574536 017177 0ustar00hiroshihiroshi000000 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" #include "unicode_support.h" #include #include #include "pgapifunc.h" #include "connection.h" #include "statement.h" #include "misc.h" RETCODE SQL_API SQLGetStmtAttrW(SQLHSTMT hstmt, SQLINTEGER fAttribute, PTR rgbValue, SQLINTEGER cbValueMax, SQLINTEGER *pcbValue) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); 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) { RETCODE ret; StatementClass *stmt = (StatementClass *) hstmt; MYLOG(0, "Entering\n"); 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) { RETCODE ret; MYLOG(0, "Entering\n"); 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) { RETCODE ret; ConnectionClass *conn = (ConnectionClass *) hdbc; MYLOG(0, "Entering\n"); 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) { RETCODE ret; SQLLEN vallen; char *uval = NULL; BOOL val_alloced = FALSE; MYLOG(0, "Entering\n"); 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) { RETCODE ret; SQLINTEGER blen = 0, bMax, *pcbV; char *rgbV = NULL, *rgbVt; MYLOG(0, "Entering\n"); 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 (rgbVt = rgbV;; bMax = blen + 1, rgbVt = realloc(rgbV, bMax)) { if (!rgbVt) { ret = SQL_ERROR; break; } rgbV = rgbVt; 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) { RETCODE ret; SQLSMALLINT buflen, tlen; char qstr_ansi[8], *mtxt = NULL; MYLOG(0, "Entering\n"); buflen = 0; if (szErrorMsg && cbErrorMsgMax > 0) { buflen = cbErrorMsgMax; mtxt = malloc(buflen); } ret = PGAPI_GetDiagRec(fHandleType, handle, iRecord, (SQLCHAR *) qstr_ansi, pfNativeError, (SQLCHAR *) mtxt, buflen, &tlen); if (SQL_SUCCEEDED(ret)) { if (szSqlState) utf8_to_ucs2(qstr_ansi, -1, szSqlState, 6); if (mtxt && tlen <= cbErrorMsgMax) { SQLULEN ulen = utf8_to_ucs2_lf(mtxt, tlen, FALSE, szErrorMsg, cbErrorMsgMax, TRUE); if (ulen == (SQLULEN) -1) tlen = (SQLSMALLINT) locale_to_sqlwchar((SQLWCHAR *) szErrorMsg, mtxt, cbErrorMsgMax, FALSE); else tlen = (SQLSMALLINT) ulen; if (tlen >= cbErrorMsgMax) ret = SQL_SUCCESS_WITH_INFO; else if (tlen < 0) { char errc[32]; SPRINTF_FIXED(errc, "Error: SqlState=%s", qstr_ansi); tlen = utf8_to_ucs2(errc, -1, szErrorMsg, cbErrorMsgMax); } } if (pcbErrorMsg) *pcbErrorMsg = tlen; } 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, *rgbDt; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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 (rgbDt = rgbD;; bMax = blen + 1, rgbDt = realloc(rgbD, bMax)) { if (!rgbDt) { ret = SQL_ERROR; break; } rgbD = rgbDt; 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) { RETCODE ret; SQLSMALLINT *rgbL, blen = 0, bMax; char *rgbD = NULL, *rgbDt; MYLOG(0, "Entering Handle=(%u,%p) Rec=%d Id=%d info=(%p,%d)\n", 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 (rgbDt = rgbD;; bMax = blen + 1, rgbDt = realloc(rgbD, bMax)) { if (!rgbDt) { free(rgbD); return SQL_ERROR; } rgbD = rgbDt; 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) locale_to_sqlwchar((SQLWCHAR *) rgbDiagInfo, rgbD, cbDiagInfoMax / WCLEN, FALSE); else blen = (SQLSMALLINT) ulen; if (SQL_SUCCESS == ret && blen * WCLEN >= cbDiagInfoMax) ret = SQL_SUCCESS_WITH_INFO; if (pcbDiagInfo) { *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; } /* new function */ RETCODE SQL_API SQLGetDescRecW(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLWCHAR *Name, SQLSMALLINT BufferLength, SQLSMALLINT *StringLength, SQLSMALLINT *Type, SQLSMALLINT *SubType, SQLLEN *Length, SQLSMALLINT *Precision, SQLSMALLINT *Scale, SQLSMALLINT *Nullable) { MYLOG(0, "Entering\n"); MYLOG(0, "Error not implemented\n"); return SQL_ERROR; } /* new fucntion */ RETCODE SQL_API SQLSetDescRecW(SQLHDESC DescriptorHandle, SQLSMALLINT RecNumber, SQLSMALLINT Type, SQLSMALLINT SubType, SQLLEN Length, SQLSMALLINT Precision, SQLSMALLINT Scale, PTR Data, SQLLEN *StringLength, SQLLEN *Indicator) { MYLOG(0, "Entering\n"); MYLOG(0, "Error not implemented\n"); return SQL_ERROR; } psqlodbc-13.02.0000/odbcapiw.c000644 001751 001751 00000067771 14122574536 017051 0ustar00hiroshihiroshi000000 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 "unicode_support.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; ConnInfo *ci; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; conn = SC_get_conn(stmt); ci = &(conn->connInfo); 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 (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; if (atoi(ci->show_oid_column)) flag |= PODBC_SHOW_OID_COLUMN; if (atoi(ci->row_versioning)) flag |= PODBC_ROW_VERSIONING; 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) { char *svName, *usName, *auth; SQLLEN nmlen1, nmlen2, nmlen3; RETCODE ret; ConnectionClass *conn = (ConnectionClass *) ConnectionHandle; MYLOG(0, "Entering\n"); 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 *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(0, "Entering\n"); 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); if (!szOut) { CC_set_error(conn, CONN_NO_MEMORY_ERROR, "Could not allocate memory for output buffer", func); ret = SQL_ERROR; goto cleanup; } 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) { MYLOG(DETAIL_LOG_LEVEL, "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; } cleanup: 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(0, "Entering\n"); 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); if (szOut) ret = PGAPI_BrowseConnect(hdbc, (SQLCHAR *) szIn, (SQLSMALLINT) inlen, (SQLCHAR *) szOut, cbConnStrOutMax, &olen); else { CC_set_error(conn, CONN_NO_MEMORY_ERROR, "Could not allocate memory for output buffer", func); ret = SQL_ERROR; } 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) { MYLOG(0, "Entering\n"); /* 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, *clNamet = NULL; MYLOG(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; buflen = 0; if (BufferLength > 0) buflen = BufferLength * 3; else if (NameLength) buflen = 32; if (buflen > 0) clNamet = malloc(buflen); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); for (;; buflen = nmlen + 1, clNamet = realloc(clName, buflen)) { if (!clNamet) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for column name", func); ret = SQL_ERROR; break; } clName = clNamet; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; stxt = ucs2_to_utf8(StatementText, TextLength, &slen, FALSE); ENTER_STMT_CS(stmt); SC_clear_error(stmt); 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 = NULL, *crNamet; SQLSMALLINT clen, buflen; MYLOG(0, "Entering\n"); if (BufferLength > 0) buflen = BufferLength * 3; else buflen = 32; crNamet = malloc(buflen); ENTER_STMT_CS(stmt); SC_clear_error(stmt); StartRollbackState(stmt); for (;; buflen = clen + 1, crNamet = realloc(crName, buflen)) { if (!crNamet) { SC_set_error(stmt, STMT_NO_MEMORY_ERROR, "Could not allocate memory for cursor name", func); ret = SQL_ERROR; break; } crName = crNamet; 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) { 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); MYLOG(0, "Entering\n"); if ((ret = PGAPI_GetInfo(ConnectionHandle, InfoType, InfoValue, BufferLength, StringLength)) == SQL_ERROR) CC_log_error("SQLGetInfoW", "", conn); 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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) { RETCODE ret; StatementClass *stmt = (StatementClass *) StatementHandle; char *crName; SQLLEN nlen; MYLOG(0, "Entering\n"); 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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 (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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 (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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, *szOutt = NULL; SQLLEN slen; SQLINTEGER buflen, olen; ConnectionClass *conn = (ConnectionClass *) hdbc; MYLOG(0, "Entering\n"); 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) szOutt = malloc(buflen); for (;; buflen = olen + 1, szOutt = realloc(szOut, buflen)) { if (!szOutt) { CC_set_error(conn, CONN_NO_MEMORY_ERROR, "Could not allocate memory for output buffer", func); ret = SQL_ERROR; break; } szOut = szOutt; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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(0, "Entering\n"); 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 (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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 (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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 (stmt->options.metadata_id) flag |= PODBC_NOT_SEARCH_PATTERN; 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(0, "Entering\n"); if (SC_connection_lost_check(stmt, __FUNCTION__)) return SQL_ERROR; 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-13.02.0000/win_unicode.c000644 001751 001751 00000072217 14122574536 017553 0ustar00hiroshihiroshi000000 000000 /*------- * Module: win_unicode.c * * Description: This module contains utf8 <-> ucs2 conversion routines * under WIndows * *------- */ #ifdef UNICODE_SUPPORT #include "unicode_support.h" #include #include #include #ifdef WIN32 #define FORMAT_SIZE_T "%Iu" #else #define FORMAT_SIZE_T "%zu" #endif #if (defined(__STDC_ISO_10646__) && defined(HAVE_MBSTOWCS) && defined(HAVE_WCSTOMBS)) || defined(WIN32) #define __WCS_ISO10646__ static BOOL use_wcs = FALSE; #endif #if (defined(__STDC_UTF_16__) && defined(HAVE_UCHAR_H) && defined(HAVE_MBRTOC16) && defined(HAVE_C16RTOMB)) #define __CHAR16_UTF_16__ #include static BOOL use_c16 = FALSE; #endif static int convtype = -1; int get_convtype(void) { const UCHAR *cdt; #if defined(__WCS_ISO10646__) if (convtype < 0) { wchar_t *wdt = L"a"; int sizeof_w = sizeof(wchar_t); cdt = (UCHAR *) wdt; switch (sizeof_w) { case 2: if ('a' == cdt[0] && '\0' == cdt[1] && '\0' == cdt[2] && '\0' == cdt[3]) { MYLOG(0, " UTF-16LE detected\n"); convtype = WCSTYPE_UTF16_LE; use_wcs = TRUE; } break; case 4: if ('a' == cdt[0] && '\0' == cdt[1] && '\0' == cdt[2] && '\0' == cdt[3] && '\0' == cdt[4] && '\0' == cdt[5] && '\0' == cdt[6] && '\0' == cdt[7]) { MYLOG(0, " UTF32-LE detected\n"); convtype = WCSTYPE_UTF32_LE; use_wcs = TRUE; } break; } } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (convtype < 0) { char16_t *c16dt = u"a"; cdt = (UCHAR *) c16dt; if ('a' == cdt[0] && '\0' == cdt[1] && '\0' == cdt[2] && '\0' == cdt[3]) { MYLOG(0, " C16_UTF-16LE detected\n"); convtype = C16TYPE_UTF16_LE; use_c16 = TRUE; } } #endif /* __CHAR16_UTF_16__ */ if (convtype < 0) convtype = CONVTYPE_UNKNOWN; /* unknown */ return convtype; } #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; int len = 0; MYLOG(0, "%p ilen=" FORMAT_LEN " ", ucs2str, ilen); if (!ucs2str) { if (olen) *olen = SQL_NULL_DATA; return NULL; } if (little_endian < 0) { int crt = 1; little_endian = (0 != ((char *) &crt)[0]); } if (ilen < 0) ilen = ucs2strlen(ucs2str); MYPRINTF(0, " newlen=" FORMAT_LEN, ilen); utf8str = (char *) malloc(ilen * 4 + 1); if (utf8str) { int i = 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; } MYPRINTF(0, " olen=%d utf8str=%s\n", len, 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 minus) * 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(DETAIL_LOG_LEVEL, "ilen=" FORMAT_LEN " bufcount=" FORMAT_ULEN, ilen, bufcount); if (!utf8str) return 0; MYPRINTF(DETAIL_LOG_LEVEL, " string=%s", 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; MYPRINTF(DETAIL_LOG_LEVEL, " ocount=" FORMAT_ULEN "\n", ocount); return rtn; } #ifdef __WCS_ISO10646__ /* UCS4 => utf8 */ #define byte4check 0xffff0000 #define byte4_check 0x10000 #define byte4_mask1 0x1c0000 #define byte4_mask2 0x3f000 #define byte4_mask3 0x0fc0 #define byte4_mask4 0x003f #define byte4_m3 0x3f static SQLULEN ucs4strlen(const UInt4 *ucs4str) { SQLULEN len; for (len = 0; ucs4str[len]; len++) ; return len; } static char *ucs4_to_utf8(const UInt4 *ucs4str, SQLLEN ilen, SQLLEN *olen, BOOL lower_identifier) { char * utf8str; int len = 0; MYLOG(0, " %p ilen=" FORMAT_LEN "\n", ucs4str, ilen); if (!ucs4str) { if (olen) *olen = SQL_NULL_DATA; return NULL; } if (little_endian < 0) { int crt = 1; little_endian = (0 != ((char *) &crt)[0]); } if (ilen < 0) ilen = ucs4strlen(ucs4str); MYLOG(0, " newlen=" FORMAT_LEN "\n", ilen); utf8str = (char *) malloc(ilen * 4 + 1); if (utf8str) { int i; UInt2 byte2code; Int4 byte4code; const UInt4 *wstr; for (i = 0, wstr = ucs4str; 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); } else if ((*wstr & byte4check) == 0) { 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; } else { byte4code = byte4_base | ((byte4_mask1 & *wstr) >> 18) | ((byte4_mask2 & *wstr) >> 4) | ((byte4_mask3 & *wstr) << 10) | ((byte4_mask4 & *wstr) << 24); /* MYLOG(0, " %08x->%08x\n", *wstr, byte4code); */ 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); } } utf8str[len] = '\0'; if (olen) *olen = len; } MYLOG(0, " olen=%d %s\n", len, utf8str ? utf8str : ""); return utf8str; } /* * Convert a string from UTF-8 encoding to UTF-32. * * utf8str - input string in UTF-8 * ilen - length of input string in bytes (or minus) * lfconv - TRUE if line feeds (LF) should be converted to CR + LF * ucs4str - output buffer * bufcount - size of output buffer * errcheck - if TRUE, check for invalidly encoded input characters * * Returns the number of UInt4s 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. */ static SQLULEN utf8_to_ucs4_lf(const char *utf8str, SQLLEN ilen, BOOL lfconv, UInt4 *ucs4str, SQLULEN bufcount, BOOL errcheck) { int i; SQLULEN rtn, ocount, wcode; const UCHAR *str; MYLOG(0, " ilen=" FORMAT_LEN " bufcount=" FORMAT_ULEN "\n", ilen, bufcount); if (!utf8str) return 0; MYLOG(99, " string=%s\n", utf8str); if (!bufcount) ucs4str = NULL; else if (!ucs4str) 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) ucs4str[ocount] = PG_CARRIAGE_RETURN; ocount++; } if (ocount < bufcount) ucs4str[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 = (((((UInt4) *str) & byte4_m1) << 18) | ((((UInt4) str[1]) & byte4_m2) << 12) | ((((UInt4) str[2]) & byte4_m3) << 6)) | (((UInt4) str[3]) & byte4_m4); ucs4str[ocount] = 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); ucs4str[ocount] = 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); ucs4str[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 && ucs4str) ucs4str[ocount] = 0; MYLOG(0, " ocount=" FORMAT_ULEN "\n", ocount); return rtn; } #define SURROGATE_CHECK 0xfc #define SURROG1_BYTE 0xd8 #define SURROG2_BYTE 0xdc static int ucs4_to_ucs2_lf(const unsigned int *ucs4str, SQLLEN ilen, SQLWCHAR *ucs2str, int bufcount, BOOL lfconv) { int outlen = 0, i; UCHAR *ucdt; SQLWCHAR *sqlwdt, dmy_wchar; UCHAR * const udt = (UCHAR *) &dmy_wchar; unsigned int uintdt; MYLOG(0, " ilen=" FORMAT_LEN " bufcount=%d\n", ilen, bufcount); if (ilen < 0) ilen = ucs4strlen(ucs4str); for (i = 0; i < ilen && (uintdt = ucs4str[i]); i++) { sqlwdt = (SQLWCHAR *)&uintdt; ucdt = (UCHAR *)&uintdt; if (0 == sqlwdt[1]) { if (lfconv && PG_LINEFEED == ucdt[0] && (i == 0 || PG_CARRIAGE_RETURN != *((UCHAR *)&ucs4str[i - 1])) ) { if (outlen < bufcount) { udt[0] = PG_CARRIAGE_RETURN; udt[1] = 0; ucs2str[outlen] = *((SQLWCHAR *) udt); } outlen++; } if (outlen < bufcount) ucs2str[outlen] = sqlwdt[0]; outlen++; continue; } sqlwdt[1]--; udt[0] = ((0xfc & ucdt[1]) >> 2) | ((0x3 & ucdt[2]) << 6); // printf("%02x", udt[0]); udt[1] = SURROG1_BYTE | ((0xc & ucdt[2]) >> 2); // printf("%02x", udt[1]); if (outlen < bufcount) ucs2str[outlen] = *((SQLWCHAR *)udt); outlen++; udt[0] = ucdt[0]; // printf("%02x", udt[0]); udt[1] = SURROG2_BYTE | (0x3 & ucdt[1]); // printf("%02x\n", udt[1]); if (outlen < bufcount) ucs2str[outlen] = *((SQLWCHAR *)udt); outlen++; } if (outlen < bufcount) ucs2str[outlen] = 0; return outlen; } static int ucs2_to_ucs4(const SQLWCHAR *ucs2str, SQLLEN ilen, unsigned int *ucs4str, int bufcount) { int outlen = 0, i; UCHAR *ucdt; SQLWCHAR sqlwdt; unsigned int dmy_uint; UCHAR * const udt = (UCHAR *) &dmy_uint; MYLOG(0, " ilen=" FORMAT_LEN " bufcount=%d\n", ilen, bufcount); if (ilen < 0) ilen = ucs2strlen(ucs2str); udt[3] = 0; /* always */ for (i = 0; i < ilen && (sqlwdt = ucs2str[i]); i++) { ucdt = (UCHAR *)(ucs2str + i); // printf("IN=%x\n", sqlwdt); if ((ucdt[1] & SURROGATE_CHECK) != SURROG1_BYTE) { // printf("SURROG1=%2x\n", ucdt[1] & SURROG1_BYTE); if (outlen < bufcount) { udt[0] = ucdt[0]; udt[1] = ucdt[1]; udt[2] = 0; ucs4str[outlen] = *((unsigned int *)udt); } outlen++; continue; } /* surrogate pair */ udt[0] = ucdt[2]; udt[1] = (ucdt[3] & 0x3) | ((ucdt[0] & 0x3f) << 2); udt[2] = (((ucdt[0] & 0xc0) >> 6) | ((ucdt[1] & 0x3) << 2)) + 1; // udt[3] = 0; needless if (outlen < bufcount) ucs4str[outlen] = *((unsigned int *)udt); outlen++; i++; } if (outlen < bufcount) ucs4str[outlen] = 0; return outlen; } #endif /* __WCS_ISO10646__ */ #if defined(__WCS_ISO10646__) static SQLULEN utf8_to_wcs_lf(const char *utf8str, SQLLEN ilen, BOOL lfconv, wchar_t *wcsstr, SQLULEN bufcount, BOOL errcheck) { switch (get_convtype()) { case WCSTYPE_UTF16_LE: return utf8_to_ucs2_lf(utf8str, ilen, lfconv, (SQLWCHAR *) wcsstr, bufcount, errcheck); case WCSTYPE_UTF32_LE: return utf8_to_ucs4_lf(utf8str, ilen, lfconv, (UInt4 *) wcsstr, bufcount, errcheck); } return -1; } static char *wcs_to_utf8(const wchar_t *wcsstr, SQLLEN ilen, SQLLEN *olen, BOOL lower_identifier) { switch (get_convtype()) { case WCSTYPE_UTF16_LE: return ucs2_to_utf8((const SQLWCHAR *) wcsstr, ilen, olen, lower_identifier); case WCSTYPE_UTF32_LE: return ucs4_to_utf8((const UInt4 *) wcsstr, ilen, olen, lower_identifier); } return NULL; } /* * Input strings must be NULL terminated. * Output wide character strings would be NULL terminated. The result * outmsg would be truncated when the buflen is small. * * The output NULL terminator is counted as buflen. * if outmsg is NULL or buflen is 0, only output length is returned. * As for return values, NULL terminators aren't counted. */ static int msgtowstr(const char *inmsg, wchar_t *outmsg, int buflen) { int outlen = -1; MYLOG(0, " inmsg=%p buflen=%d\n", inmsg, buflen); #ifdef WIN32 if (NULL == outmsg) buflen = 0; if ((outlen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED | MB_ERR_INVALID_CHARS, inmsg, -1, outmsg, buflen)) > 0) outlen--; else if (ERROR_INSUFFICIENT_BUFFER == GetLastError()) outlen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED | MB_ERR_INVALID_CHARS, inmsg, -1, NULL, 0) - 1; else outlen = -1; #else if (0 == buflen) outmsg = NULL; outlen = mbstowcs((wchar_t *) outmsg, inmsg, buflen); #endif /* WIN32 */ if (outmsg && outlen >= buflen) { outmsg[buflen - 1] = 0; MYLOG(0, " out=%dchars truncated to %d\n", outlen, buflen - 1); } MYLOG(0, " buf=%dchars out=%dchars\n", buflen, outlen); return outlen; } /* * Input wide character strings must be NULL terminated. * Output strings would be NULL terminated. The result outmsg would be * truncated when the buflen is small. * * The output NULL terminator is counted as buflen. * if outmsg is NULL or buflen is 0, only output length is returned. * As for return values, NULL terminators aren't counted. */ static int wstrtomsg(const wchar_t *wstr, char *outmsg, int buflen) { int outlen = -1; MYLOG(0, " wstr=%p buflen=%d\n", wstr, buflen); #ifdef WIN32 if (NULL == outmsg) buflen = 0; if ((outlen = WideCharToMultiByte(CP_ACP, 0, wstr, -1, outmsg, buflen, NULL, NULL)) > 0) outlen--; else if (ERROR_INSUFFICIENT_BUFFER == GetLastError()) outlen = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL) - 1; else outlen = -1; #else if (0 == buflen) outmsg = NULL; outlen = wcstombs(outmsg, wstr, buflen); #endif /* WIN32 */ if (outmsg && outlen >= buflen) { outmsg[buflen - 1] = 0; MYLOG(0, " out=%dbytes truncated to %d\n", outlen, buflen - 1); } MYLOG(0, " buf=%dbytes outlen=%dbytes\n", buflen, outlen); return outlen; } #endif /* __WCS_ISO10646__ */ #if defined(__CHAR16_UTF_16__) static mbstate_t initial_state; static SQLLEN mbstoc16_lf(char16_t *c16dt, const char *c8dt, size_t n, BOOL lf_conv) { int i; size_t brtn; const char *cdt; mbstate_t mbst = initial_state; MYLOG(0, " c16dt=%p size=" FORMAT_SIZE_T "\n", c16dt, n); for (i = 0, cdt = c8dt; i < n || (!c16dt); i++) { if (lf_conv && PG_LINEFEED == *cdt && i > 0 && PG_CARRIAGE_RETURN != cdt[-1]) { if (c16dt) c16dt[i] = PG_CARRIAGE_RETURN; i++; } brtn = mbrtoc16(c16dt ? c16dt + i : NULL, cdt, 4, &mbst); if (0 == brtn) break; if (brtn == (size_t) -1 || brtn == (size_t) -2) return -1; if (brtn == (size_t) -3) continue; cdt += brtn; } if (c16dt && i >= n) c16dt[n - 1] = 0; return i; } static SQLLEN c16tombs(char *c8dt, const char16_t *c16dt, size_t n) { int i; SQLLEN result = 0; size_t brtn; char *cdt, c4byte[4]; mbstate_t mbst = initial_state; MYLOG(0, " c8dt=%p size=" FORMAT_SIZE_T "u\n", c8dt, n); if (!c8dt) n = 0; for (i = 0, cdt = c8dt; c16dt[i] && (result < n || (!cdt)); i++) { if (NULL != cdt && result + 4 < n) brtn = c16rtomb(cdt, c16dt[i], &mbst); else { brtn = c16rtomb(c4byte, c16dt[i], &mbst); if (brtn < 5) { SQLLEN result_n = result + brtn; if (result_n < n) memcpy(cdt, c4byte, brtn); else { if (cdt && n > 0) { c8dt[result] = '\0'; /* truncate */ return result_n; } } } } /* printf("c16dt=%04X brtn=%lu result=%ld cdt=%02X%02X%02X%02X\n", c16dt[i], brtn, result, (UCHAR) cdt[0], (UCHAR) cdt[1], (UCHAR) cdt[2], (UCHAR) cdt[3]); */ if (brtn == (size_t) -1) { if (n > 0) c8dt[n - 1] = '\0'; return -1; } if (cdt) cdt += brtn; result += brtn; } if (cdt) *cdt = '\0'; return result; } #endif /* __CHAR16_UTF_16__ */ // // SQLBindParameter SQL_C_CHAR to UTF-8 case // the current locale => UTF-8 // SQLLEN bindpara_msg_to_utf8(const char *ldt, char **wcsbuf, SQLLEN used) { SQLLEN l = (-2); char *utf8 = NULL, *ldt_nts, *alloc_nts = NULL, ntsbuf[128]; int count; if (SQL_NTS == used) { count = strlen(ldt); ldt_nts = (char *) ldt; } else if (used < 0) { return -1; } else { count = used; if (used < sizeof(ntsbuf)) ldt_nts = ntsbuf; else { if (NULL == (alloc_nts = malloc(used + 1))) return l; ldt_nts = alloc_nts; } memcpy(ldt_nts, ldt, used); ldt_nts[used] = '\0'; } get_convtype(); MYLOG(0, " \n"); #if defined(__WCS_ISO10646__) if (use_wcs) { wchar_t *wcsdt = (wchar_t *) malloc((count + 1) * sizeof(wchar_t)); if ((l = msgtowstr(ldt_nts, (wchar_t *) wcsdt, count + 1)) >= 0) utf8 = wcs_to_utf8(wcsdt, -1, &l, FALSE); free(wcsdt); } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (use_c16) { SQLWCHAR *utf16 = (SQLWCHAR *) malloc((count + 1) * sizeof(SQLWCHAR)); if ((l = mbstoc16_lf((char16_t *) utf16, ldt_nts, count + 1, FALSE)) >= 0) utf8 = ucs2_to_utf8(utf16, -1, &l, FALSE); free(utf16); } #endif /* __CHAR16_UTF_16__ */ if (l < 0 && NULL != utf8) free(utf8); else *wcsbuf = (char *) utf8; if (NULL != alloc_nts) free(alloc_nts); return l; } // // SQLBindParameter hybrid case // SQLWCHAR(UTF-16) => the current locale // SQLLEN bindpara_wchar_to_msg(const SQLWCHAR *utf16, char **wcsbuf, SQLLEN used) { SQLLEN l = (-2); char *ldt = NULL; SQLWCHAR *utf16_nts, *alloc_nts = NULL, ntsbuf[128]; int count; if (SQL_NTS == used) { count = ucs2strlen(utf16); utf16_nts = (SQLWCHAR *) utf16; } else if (used < 0) return -1; else { count = used / WCLEN; if (used + WCLEN <= sizeof(ntsbuf)) utf16_nts = ntsbuf; else { if (NULL == (alloc_nts = (SQLWCHAR *) malloc(used + WCLEN))) return l; utf16_nts = alloc_nts; } memcpy(utf16_nts, utf16, used); utf16_nts[count] = 0; } get_convtype(); MYLOG(0, "\n"); #if defined(__WCS_ISO10646__) if (use_wcs) { if (sizeof(SQLWCHAR) == sizeof(wchar_t)) { ldt = (char *) malloc(2 * count + 1); l = wstrtomsg((wchar_t *) utf16_nts, ldt, 2 * count + 1); } else { unsigned int *utf32 = (unsigned int *) malloc((count + 1) * sizeof(unsigned int)); l = ucs2_to_ucs4(utf16_nts, -1, utf32, count + 1); if ((l = wstrtomsg((wchar_t *)utf32, NULL, 0)) >= 0) { ldt = (char *) malloc(l + 1); l = wstrtomsg((wchar_t *)utf32, ldt, l + 1); } free(utf32); } } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (use_c16) { ldt = (char *) malloc(4 * count + 1); l = c16tombs(ldt, (const char16_t *) utf16_nts, 4 * count + 1); } #endif /* __CHAR16_UTF_16__ */ if (l < 0 && NULL != ldt) free(ldt); else *wcsbuf = ldt; if (NULL != alloc_nts) free(alloc_nts); return l; } size_t convert_linefeeds(const char *s, char *dst, size_t max, BOOL convlf, BOOL *changed); // // SQLBindCol hybrid case // the current locale => SQLWCHAR(UTF-16) // SQLLEN bindcol_hybrid_estimate(const char *ldt, BOOL lf_conv, char **wcsbuf) { SQLLEN l = (-2); get_convtype(); MYLOG(0, " lf_conv=%d\n", lf_conv); #if defined(__WCS_ISO10646__) if (use_wcs) { unsigned int *utf32 = NULL; if (sizeof(SQLWCHAR) == sizeof(wchar_t)) { l = msgtowstr(ldt, (wchar_t *) NULL, 0); if (l >= 0 && lf_conv) { BOOL changed; size_t len; len = convert_linefeeds(ldt, NULL, 0, TRUE, &changed); if (changed) { l += (len - strlen(ldt)); *wcsbuf = (char *) malloc(len + 1); convert_linefeeds(ldt, *wcsbuf, len + 1, TRUE, NULL); } } } else { int count = strlen(ldt); utf32 = (unsigned int *) malloc((count + 1) * sizeof(unsigned int)); if ((l = msgtowstr(ldt, (wchar_t *) utf32, count + 1)) >= 0) { l = ucs4_to_ucs2_lf(utf32, -1, NULL, 0, lf_conv); *wcsbuf = (char *) utf32; } } if (l < 0 && NULL != utf32) free(utf32); } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (use_c16) l = mbstoc16_lf((char16_t *) NULL, ldt, 0, lf_conv); #endif /* __CHAR16_UTF_16__ */ return l; } SQLLEN bindcol_hybrid_exec(SQLWCHAR *utf16, const char *ldt, size_t n, BOOL lf_conv, char **wcsbuf) { SQLLEN l = (-2); get_convtype(); MYLOG(0, " size=" FORMAT_SIZE_T " lf_conv=%d\n", n, lf_conv); #if defined(__WCS_ISO10646__) if (use_wcs) { unsigned int *utf32 = NULL; BOOL midbuf = (wcsbuf && *wcsbuf); if (sizeof(SQLWCHAR) == sizeof(wchar_t)) { if (midbuf) l = msgtowstr(*wcsbuf, (wchar_t *) utf16, n); else l = msgtowstr(ldt, (wchar_t *) utf16, n); } else if (midbuf) { utf32 = (unsigned int *) *wcsbuf; l = ucs4_to_ucs2_lf(utf32, -1, utf16, n, lf_conv); } else { int count = strlen(ldt); utf32 = (unsigned int *) malloc((count + 1) * sizeof(unsigned int)); if ((l = msgtowstr(ldt, (wchar_t *) utf32, count + 1)) >= 0) { l = ucs4_to_ucs2_lf(utf32, -1, utf16, n, lf_conv); } free(utf32); } if (midbuf) { free(*wcsbuf); *wcsbuf = NULL; } } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (use_c16) { l = mbstoc16_lf((char16_t *) utf16, ldt, n, lf_conv); } #endif /* __CHAR16_UTF_16__ */ return l; } SQLLEN locale_to_sqlwchar(SQLWCHAR *utf16, const char *ldt, size_t n, BOOL lf_conv) { return bindcol_hybrid_exec(utf16, ldt, n, lf_conv, NULL); } // // SQLBindCol localize case // UTF-8 => the current locale // SQLLEN bindcol_localize_estimate(const char *utf8dt, BOOL lf_conv, char **wcsbuf) { SQLLEN l = (-2); char *convalc = NULL; get_convtype(); MYLOG(0, " lf_conv=%d\n", lf_conv); #if defined(__WCS_ISO10646__) if (use_wcs) { wchar_t *wcsalc = NULL; l = utf8_to_wcs_lf(utf8dt, -1, lf_conv, NULL, 0, FALSE); wcsalc = (wchar_t *) malloc(sizeof(wchar_t) * (l + 1)); convalc = (char *) wcsalc; l = utf8_to_wcs_lf(utf8dt, -1, lf_conv, wcsalc, l + 1, FALSE); l = wstrtomsg(wcsalc, NULL, 0); } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (use_c16) { SQLWCHAR *wcsalc = NULL; l = utf8_to_ucs2_lf(utf8dt, -1, lf_conv, (SQLWCHAR *) NULL, 0, FALSE); wcsalc = (SQLWCHAR *) malloc(sizeof(SQLWCHAR) * (l + 1)); convalc = (char *) wcsalc; l = utf8_to_ucs2_lf(utf8dt, -1, lf_conv, wcsalc, l + 1, FALSE); l = c16tombs(NULL, (char16_t *) wcsalc, 0); } #endif /* __CHAR16_UTF_16__ */ if (l < 0 && NULL != convalc) free(convalc); else if (NULL != convalc) *wcsbuf = (char *) convalc; MYLOG(0, " return=" FORMAT_LEN "\n", l); return l; } SQLLEN bindcol_localize_exec(char *ldt, size_t n, BOOL lf_conv, char **wcsbuf) { SQLLEN l = (-2); get_convtype(); MYLOG(0, " size=" FORMAT_SIZE_T "\n", n); #if defined(__WCS_ISO10646__) if (use_wcs) { wchar_t *wcsalc = (wchar_t *) *wcsbuf; l = wstrtomsg(wcsalc, ldt, n); } #endif /* __WCS_ISO10646__ */ #ifdef __CHAR16_UTF_16__ if (use_c16) { char16_t *wcsalc = (char16_t *) *wcsbuf; l = c16tombs(ldt, (char16_t *) wcsalc, n); } #endif /* __CHAR16_UTF_16__ */ free(*wcsbuf); *wcsbuf = NULL; MYLOG(0, " return=" FORMAT_LEN "\n", l); return l; } SQLLEN utf8_to_locale(char *ldt, const char *utf8dt, size_t n, BOOL lf_conv) { SQLLEN l; char * tmpbuf; if ((l = bindcol_localize_estimate(utf8dt, lf_conv, &tmpbuf)) >= 0) l = bindcol_localize_exec(ldt, n, lf_conv, &tmpbuf); return l; } #endif /* UNICODE_SUPPORT */ psqlodbc-13.02.0000/license.txt000644 001751 001751 00000062222 14122574536 017262 0ustar00hiroshihiroshi000000 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-13.02.0000/readme.txt000644 001751 001751 00000002527 14122576462 017077 0ustar00hiroshihiroshi000000 000000 /******************************************************************** PSQLODBC.DLL - A library to talk to the PostgreSQL DBMS using ODBC. Copyright (C) 1998 Insight Distribution Systems Copyright (C) 1998 - 2021 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: https://odbc.postgresql.org/ ***********************************************************************/ psqlodbc-13.02.0000/readme_winbuild.txt000644 001751 001751 00000000542 14122574536 020767 0ustar00hiroshihiroshi000000 000000 This folder contains 4 batch scripts BuildAll.bat editConfiguration.bat regress.bat buildInstallers.bat which have the same functionalities as corresponding powershell scripts in winbuild folder. See docs\win32-compilation.html and winbuild\readme.txt for Windows compilation instructions. For info on building installers, see installer\README.txt psqlodbc-13.02.0000/psqlodbc.def000644 001751 001751 00000004145 14122574536 017366 0ustar00hiroshihiroshi000000 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 SQLGetDescFieldW @130 SQLGetDescRecW @131 SQLSetDescRecW @132 psqlodbc-13.02.0000/psqlodbca.def000644 001751 001751 00000002743 14122574536 017531 0ustar00hiroshihiroshi000000 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-13.02.0000/editConfiguration.bat000644 001751 001751 00000000226 14122574535 021237 0ustar00hiroshihiroshi000000 000000 :: :: Start editConfiguration with a mimimized console window :: powershell -Sta -WindowStyle Minimized "& '%~dp0\winbuild\editConfiguration.ps1' %*" psqlodbc-13.02.0000/BuildAll.bat000644 001751 001751 00000000445 14122574535 017255 0ustar00hiroshihiroshi000000 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-13.02.0000/windows-defaults.mak000644 001751 001751 00000001106 14122574536 021062 0ustar00hiroshihiroshi000000 000000 # # This file includes default configuration options used to build the driver # on Windows using "nmake /f win64.mak". You can override these by creating a # file in the same directory called "windows-local.mak". It will be processed #after these defaults. (You can copy this file as a template, and modify) # !IF "$(TARGET_CPU)" == "x86" PG_INC=C:\Program Files (x86)\PostgreSQL\9.6\include PG_LIB=C:\Program Files (x86)\PostgreSQL\9.6\lib !ELSE PG_INC=$(PROGRAMFILES)\PostgreSQL\9.6\include PG_LIB=$(PROGRAMFILES)\PostgreSQL\9.6\lib !ENDIF # Enable/disable features MSDTC = yes psqlodbc-13.02.0000/buildInstallers.bat000644 001751 001751 00000000477 14122574535 020732 0ustar00hiroshihiroshi000000 000000 :: :: Build installers of psqlodbc project :: @echo off if "%1" == "/?" ( powershell Get-Help '%~dp0\installer\buildInstallers.ps1' -detailed ) else if "%1" == "-?" ( powershell Get-Help '%~dp0\installer\buildInstallers.ps1' %2 %3 %4 %5 %6 %7 %8 %9 ) else ( powershell "& '%~dp0\installer\buildInstallers.ps1' %*" ) psqlodbc-13.02.0000/regress.bat000644 001751 001751 00000000453 14122574536 017237 0ustar00hiroshihiroshi000000 000000 :: :: regression test using MSBuild :: @echo off if "%1" == "/?" ( powershell Get-Help '%~dp0\winbuild\regress.ps1' -detailed ) else if "%1" == "-?" ( powershell Get-Help '%~dp0\winbuild\regress.ps1' %2 %3 %4 %5 %6 %7 %8 %9 ) else ( start powershell -noexit "& '%~dp0\winbuild\regress.ps1' %*" ) psqlodbc-13.02.0000/connexp.h000644 001751 001751 00000004227 14122574535 016722 0ustar00hiroshihiroshi000000 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 #define KEYWORD_DTC_CHECK "dtchk" #define DTC_CHECK_LINK_ONLY 1 #define DTC_CHECK_BEFORE_LINK 2 #define DTC_CHECK_RM_CONNECTION 3 /* 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 int PgDtc_is_recovery_available(void *self, char *reason, int rsize); 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-13.02.0000/pgenlist.def000644 001751 001751 00000000104 14122574536 017373 0ustar00hiroshihiroshi000000 000000 LIBRARY pgenlist EXPORTS EnlistInDtc DtcOnDisconnect IsolateDtcConn psqlodbc-13.02.0000/pgenlista.def000644 001751 001751 00000000105 14122574536 017535 0ustar00hiroshihiroshi000000 000000 LIBRARY pgenlista EXPORTS EnlistInDtc DtcOnDisconnect IsolateDtcConn psqlodbc-13.02.0000/dlg_wingui.c000644 001751 001751 00000072714 14122574535 017401 0ustar00hiroshihiroshi000000 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 "loadlib.h" #include "pgapifunc.h" #ifdef _HANDLE_ENLIST_IN_DTC_ #include "xalibname.h" #include "connexp.h" #endif /* _HANDLE_ENLIST_IN_DTC_ */ extern HINSTANCE s_hModule; static int driver_optionsDraw(HWND, const ConnInfo *, int src, BOOL enable); static int driver_options_update(HWND hdlg, ConnInfo *ci); static int ds_options_update(HWND hdlg, ConnInfo *ci); static int ds_options3Draw(HWND, const ConnInfo *); static int ds_options3_update(HWND hdlg, ConnInfo *ci); 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]; 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; /* * XXX: We used to hide or show this depending whether libpq was loaded, * but we depend on libpq directly nowadays, so it's always loaded. */ ShowWindow(GetDlgItem(hdlg, IDC_NOTICE_USER), SW_HIDE); dsplevel = 2; 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); STRCPY_FIXED(ci->sslmode, modetab[sslposition].modestr); } static void getDriversDefaultsOfCi(const ConnInfo *ci, GLOBAL_VALUES *glbv) { const char *drivername = NULL; if (ci->drivername[0]) drivername = ci->drivername; else if (NAME_IS_VALID(ci->drivers.drivername)) drivername = SAFE_NAME(ci->drivers.drivername); if (drivername && drivername[0]) getDriversDefaults(drivername, glbv); else getDriversDefaults(INVALID_DRIVER, glbv); } static int driver_optionsDraw(HWND hdlg, const ConnInfo *ci, int src, BOOL enable) { const GLOBAL_VALUES *comval = NULL; const char * drivername = NULL; GLOBAL_VALUES defval; MYLOG(0, "entering src=%d\n", src); init_globals(&defval); switch (src) { case 0: /* default */ getDriversDefaultsOfCi(ci, &defval); defval.debug = DEFAULT_DEBUG; defval.commlog = DEFAULT_COMMLOG; comval = &defval; break; case 1: /* dsn specific */ comval = &(ci->drivers); break; default: return 0; } ShowWindow(GetDlgItem(hdlg, DRV_MSG_LABEL2), enable ? SW_SHOW : SW_HIDE); CheckDlgButton(hdlg, DRV_COMMLOG, comval->commlog > 0); SetDlgItemInt(hdlg, DS_COMMLOG, comval->commlog, FALSE); ShowWindow(GetDlgItem(hdlg, DS_COMMLOG), comval->commlog > 0 ? SW_SHOW : SW_HIDE); CheckDlgButton(hdlg, DRV_UNIQUEINDEX, comval->unique_index); /* EnableWindow(GetDlgItem(hdlg, DRV_UNIQUEINDEX), enable); */ EnableWindow(GetDlgItem(hdlg, DRV_READONLY), FALSE); 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_DEBUG, comval->debug > 0); SetDlgItemInt(hdlg, DS_DEBUG, comval->debug, FALSE); ShowWindow(GetDlgItem(hdlg, DS_DEBUG), comval->debug > 0 ? SW_SHOW : SW_HIDE); 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); switch (src) { case 1: ShowWindow(GetDlgItem(hdlg, DS_BATCH_SIZE), SW_SHOW); ShowWindow(GetDlgItem(hdlg, DS_IGNORETIMEOUT), SW_SHOW); SetDlgItemInt(hdlg, DS_BATCH_SIZE, ci->batch_size, FALSE); CheckDlgButton(hdlg, DS_IGNORETIMEOUT, ci->ignore_timeout); break; default: ShowWindow(GetDlgItem(hdlg, DS_BATCH_SIZE), SW_HIDE); ShowWindow(GetDlgItem(hdlg, DS_IGNORETIMEOUT), SW_HIDE); break; } /* Driver Connection Settings */ EnableWindow(GetDlgItem(hdlg, DRV_CONNSETTINGS), FALSE); ShowWindow(GetDlgItem(hdlg, ID2NDPAGE), enable ? SW_HIDE : SW_SHOW); ShowWindow(GetDlgItem(hdlg, ID3RDPAGE), enable ? SW_HIDE : SW_SHOW); finalize_globals(&defval); return 0; } #define INIT_DISP_LOGVAL 2 static int driver_options_update(HWND hdlg, ConnInfo *ci) { GLOBAL_VALUES *comval; BOOL bTranslated; MYLOG(3, "entering\n"); comval = &(ci->drivers); (comval->commlog = GetDlgItemInt(hdlg, DS_COMMLOG, &bTranslated, FALSE)) || bTranslated || (comval->commlog = INIT_DISP_LOGVAL); comval->unique_index = IsDlgButtonChecked(hdlg, DRV_UNIQUEINDEX); 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->debug = GetDlgItemInt(hdlg, DS_DEBUG, &bTranslated, FALSE)) || bTranslated || (comval->debug = INIT_DISP_LOGVAL); 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)); ci->batch_size = GetDlgItemInt(hdlg, DS_BATCH_SIZE, NULL, FALSE); ci->ignore_timeout = IsDlgButtonChecked(hdlg, DS_IGNORETIMEOUT); /* fall through */ return 0; } #ifdef _HANDLE_ENLIST_IN_DTC_ static HMODULE DtcProc(const char *procname, FARPROC *proc) { HMODULE hmodule; *proc = NULL; if (hmodule = LoadLibraryEx(GetXaLibPath(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH), NULL != hmodule) { MYLOG(0, "GetProcAddres for %s\n", procname); *proc = GetProcAddress(hmodule, procname); } return hmodule; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ #include static const char *IsAnExistingDirectory(const char *path) { struct stat st; if (stat(path, &st) < 0) { CSTR errmsg_doesnt_exist = "doesn't exist"; return errmsg_doesnt_exist; } if ((st.st_mode & S_IFDIR) == 0) { CSTR errmsg_isnt_a_dir = "isn't a directory"; return errmsg_isnt_a_dir; } return NULL; } 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_ */ ConnInfo *ci; char logdir[PATH_MAX]; const char *logmsg; GLOBAL_VALUES defval; // if (WM_INITDIALOG == wMsg || WM_COMMAND == wMsg) // MYLOG(0, "entering wMsg=%d\n", wMsg); init_globals(&defval); switch (wMsg) { case WM_INITDIALOG: SetWindowLongPtr(hdlg, DWLP_USER, lParam); /* save for test etc */ ci = (ConnInfo *) lParam; getDriversDefaultsOfCi(ci, &defval); CheckDlgButton(hdlg, DRV_COMMLOG, getGlobalCommlog()); CheckDlgButton(hdlg, DRV_DEBUG, getGlobalDebug()); 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: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: getDriversDefaultsOfCi(ci, &defval); GetDlgItemText(hdlg, DS_LOGDIR, logdir, sizeof(logdir)); if (logdir[0] && (logmsg = IsAnExistingDirectory(logdir)) != NULL) { MessageBox(hdlg, "Folder for logging error", logmsg, MB_ICONEXCLAMATION | MB_OK); break; } setGlobalCommlog(IsDlgButtonChecked(hdlg, DRV_COMMLOG)); setGlobalDebug(IsDlgButtonChecked(hdlg, DRV_DEBUG)); writeGlobalLogs(); if (writeDriversDefaults(ci->drivername, &defval) < 0) MessageBox(hdlg, "Sorry, impossible to update the values\nWrite permission seems to be needed", "Update Error", MB_ICONEXCLAMATION | MB_OK); 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; } } finalize_globals(&defval); return FALSE; } static void CtrlCheckButton(HWND hdlg, int nIDcheck, int nIDint) { BOOL bTranslated; switch (Button_GetCheck(GetDlgItem(hdlg, nIDcheck))) { case BST_CHECKED: if (!GetDlgItemInt(hdlg, nIDint, &bTranslated, FALSE)) { ShowWindow(GetDlgItem(hdlg, nIDint), SW_SHOW); if (bTranslated) SetDlgItemInt(hdlg, nIDint, INIT_DISP_LOGVAL, FALSE); } break; case BST_UNCHECKED: if (GetDlgItemInt(hdlg, nIDint, &bTranslated, FALSE)) { ShowWindow(GetDlgItem(hdlg, nIDint), SW_HIDE); SetDlgItemInt(hdlg, nIDint, 0, FALSE); } break; } } LRESULT CALLBACK ds_options1Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci; char strbuf[128]; // if (WM_INITDIALOG == wMsg || WM_COMMAND == wMsg) // MYLOG(0, "entering wMsg=%d in\n", wMsg); 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_FIXED(fbuf, "Advanced Options (%s) 1/3"); SPRINTF_FIXED(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); case IDCANCEL: EndDialog(hdlg, GET_WM_COMMAND_ID(wParam, lParam) == IDOK); return TRUE; case IDAPPLY: driver_options_update(hdlg, ci); SendMessage(GetWindow(hdlg, GW_OWNER), WM_COMMAND, wParam, lParam); break; case IDDEFAULTS: driver_optionsDraw(hdlg, ci, 0, FALSE); break; case ID2NDPAGE: driver_options_update(hdlg, ci); EndDialog(hdlg, FALSE); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DS), hdlg, ds_options2Proc, (LPARAM) ci); break; case ID3RDPAGE: driver_options_update(hdlg, ci); EndDialog(hdlg, FALSE); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DS3), hdlg, ds_options3Proc, (LPARAM) ci); break; case DRV_COMMLOG: case DS_COMMLOG: CtrlCheckButton(hdlg, DRV_COMMLOG, DS_COMMLOG); break; case DRV_DEBUG: case DS_DEBUG: CtrlCheckButton(hdlg, DRV_DEBUG, DS_DEBUG); break; } } return FALSE; } static int ds_options_update(HWND hdlg, ConnInfo *ci) { char buf[128]; MYLOG(0, "entering got ci=%p\n", ci); /* ExtraOptions */ GetDlgItemText(hdlg, DS_EXTRA_OPTIONS, buf, sizeof(buf)); if (!setExtraOptions(ci, buf, NULL)) { MessageBox(hdlg, "ExtraOptions must be hex, decimal or octal", "Format error", MB_ICONEXCLAMATION | MB_OK); return 1; } /* Readonly */ ITOA_FIXED(ci->onlyread, IsDlgButtonChecked(hdlg, DS_READONLY)); /* 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 /* no button is checked */ 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; /* Numeric without precision As */ if (IsDlgButtonChecked(hdlg, DS_NUMERIC_AS_NUMERIC)) ci->numeric_as = SQL_NUMERIC; else if (IsDlgButtonChecked(hdlg, DS_NUMERIC_AS_DOUBLE)) ci->numeric_as = SQL_DOUBLE; else if (IsDlgButtonChecked(hdlg, DS_NUMERIC_AS_VARCHAR)) ci->numeric_as = SQL_VARCHAR; else if (IsDlgButtonChecked(hdlg, DS_NUMERIC_AS_LONGVARCHAR)) ci->numeric_as = SQL_LONGVARCHAR; else ci->numeric_as = DEFAULT_NUMERIC_AS; ITOA_FIXED(ci->show_system_tables, IsDlgButtonChecked(hdlg, DS_SHOWSYSTEMTABLES)); ITOA_FIXED(ci->row_versioning, IsDlgButtonChecked(hdlg, DS_ROWVERSIONING)); ci->lf_conversion = IsDlgButtonChecked(hdlg, DS_LFCONVERSION); ci->optional_errors = IsDlgButtonChecked(hdlg, DS_OPTIONALERRORS); 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->fetch_refcursors = IsDlgButtonChecked(hdlg, DS_FETCH_REFCURSORS); /*ci->lower_case_identifier = IsDlgButtonChecked(hdlg, DS_LOWERCASEIDENTIFIER);*/ /* OID Options */ ITOA_FIXED(ci->fake_oid_index, IsDlgButtonChecked(hdlg, DS_FAKEOIDINDEX)); ITOA_FIXED(ci->show_oid_column, 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); } /* TCP KEEPALIVE */ ci->disable_keepalive = IsDlgButtonChecked(hdlg, DS_DISABLE_KEEPALIVE); ci->extra_opts = getExtraOptions(ci); if (ci->disable_keepalive) { ci->keepalive_idle = -1; ci->keepalive_interval = -1; } else { char temp[64]; int val; GetDlgItemText(hdlg, DS_KEEPALIVETIME, temp, sizeof(temp)); if (val = atoi(temp), 0 == val) val = -1; ci->keepalive_idle = val; GetDlgItemText(hdlg, DS_KEEPALIVEINTERVAL, temp, sizeof(temp)); if (val = atoi(temp), 0 == val) val = -1; ci->keepalive_interval = val; } return 0; } LRESULT CALLBACK ds_options2Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci; char buf[128]; DWORD cmd; BOOL enable; // if (WM_INITDIALOG == wMsg || WM_COMMAND == wMsg) // MYLOG(0, "entering wMsg=%d in\n", wMsg); 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_FIXED(fbuf, "Advanced Options (%s) 2/3"); SPRINTF_FIXED(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'); /* 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); } /* Numeric As */ switch (ci->numeric_as) { case SQL_NUMERIC: CheckDlgButton(hdlg, DS_NUMERIC_AS_NUMERIC, 1); break; case SQL_VARCHAR: CheckDlgButton(hdlg, DS_NUMERIC_AS_VARCHAR, 1); break; case SQL_DOUBLE: CheckDlgButton(hdlg, DS_NUMERIC_AS_DOUBLE, 1); break; case SQL_LONGVARCHAR: CheckDlgButton(hdlg, DS_NUMERIC_AS_LONGVARCHAR, 1); break; default: CheckDlgButton(hdlg, DS_NUMERIC_AS_DEFAULT, 1); } SPRINTF_FIXED(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_LFCONVERSION, ci->lf_conversion); CheckDlgButton(hdlg, DS_OPTIONALERRORS, ci->optional_errors); 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_FETCH_REFCURSORS, ci->fetch_refcursors); /*CheckDlgButton(hdlg, DS_LOWERCASEIDENTIFIER, ci->lower_case_identifier);*/ EnableWindow(GetDlgItem(hdlg, DS_FAKEOIDINDEX), atoi(ci->show_oid_column)); /* Datasource Connection Settings */ SetDlgItemText(hdlg, DS_CONNSETTINGS, SAFE_NAME(ci->conn_settings)); /* KEEPALIVE */ enable = (0 == (ci->extra_opts & BIT_DISABLE_KEEPALIVE)); CheckDlgButton(hdlg, DS_DISABLE_KEEPALIVE, !enable); if (enable) { if (ci->keepalive_idle > 0) { ITOA_FIXED(buf, ci->keepalive_idle); SetDlgItemText(hdlg, DS_KEEPALIVETIME, buf); } if (ci->keepalive_interval > 0) { ITOA_FIXED(buf, ci->keepalive_interval); SetDlgItemText(hdlg, DS_KEEPALIVEINTERVAL, buf); } } break; case WM_COMMAND: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); switch (cmd = GET_WM_COMMAND_ID(wParam, lParam)) { case DS_SHOWOIDCOLUMN: MYLOG(0, "WM_COMMAND: DS_SHOWOIDCOLUMN\n"); EnableWindow(GetDlgItem(hdlg, DS_FAKEOIDINDEX), IsDlgButtonChecked(hdlg, DS_SHOWOIDCOLUMN)); return TRUE; case DS_DISABLE_KEEPALIVE: MYLOG(0, "WM_COMMAND: DS_SHOWOIDCOLUMN\n"); EnableWindow(GetDlgItem(hdlg, DS_KEEPALIVETIME), !IsDlgButtonChecked(hdlg, cmd)); EnableWindow(GetDlgItem(hdlg, DS_KEEPALIVEINTERVAL), !IsDlgButtonChecked(hdlg, cmd)); return TRUE; case IDOK: ds_options_update(hdlg, ci); case IDCANCEL: EndDialog(hdlg, IDOK == cmd); return TRUE; case IDAPPLY: ds_options_update(hdlg, ci); SendMessage(GetWindow(hdlg, GW_OWNER), WM_COMMAND, wParam, lParam); break; case ID1STPAGE: ds_options_update(hdlg, ci); EndDialog(hdlg, cmd == IDOK); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, ds_options1Proc, (LPARAM) ci); break; case ID3RDPAGE: ds_options_update(hdlg, ci); EndDialog(hdlg, cmd == IDOK); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DS3), hdlg, ds_options3Proc, (LPARAM) ci); break; } } return FALSE; } static int ds_options3Draw(HWND hdlg, const ConnInfo *ci) { BOOL enable = TRUE; static BOOL defset = FALSE; MYLOG(0, "entering\n"); #ifdef _HANDLE_ENLIST_IN_DTC_ switch (ci->xa_opt) { case 0: enable = FALSE; break; case DTC_CHECK_LINK_ONLY: CheckDlgButton(hdlg, DS_DTC_LINK_ONLY, 1); break; case DTC_CHECK_BEFORE_LINK: CheckDlgButton(hdlg, DS_DTC_SIMPLE_PRECHECK, 1); break; case DTC_CHECK_RM_CONNECTION: CheckDlgButton(hdlg, DS_DTC_CONFIRM_RM_CONNECTION, 1); break; } #else enable = FALSE; #endif /* _HANDLE_ENLIST_IN_DTC_ */ if (!enable) { EnableWindow(GetDlgItem(hdlg, DS_DTC_LINK_ONLY), enable); EnableWindow(GetDlgItem(hdlg, DS_DTC_SIMPLE_PRECHECK), enable); EnableWindow(GetDlgItem(hdlg, DS_DTC_CONFIRM_RM_CONNECTION), enable); } /* Datasource libpq parameters */ SetDlgItemText(hdlg, DS_LIBPQOPT, SAFE_NAME(ci->pqopt)); return 0; } void *PQconninfoParse(const char *, char **); void PQconninfoFree(void *); typedef void *(*PQCONNINFOPARSEPROC)(const char *, char **); typedef void (*PQCONNINFOFREEPROC)(void *); static int ds_options3_update(HWND hdlg, ConnInfo *ci) { void *connOpt = NULL; char *ermsg = NULL; char pqopt[LARGE_REGISTRY_LEN]; HMODULE hmodule; PQCONNINFOPARSEPROC pproc = NULL; PQCONNINFOFREEPROC fproc = NULL; MYLOG(0, "entering got ci=%p\n", ci); /* Datasource libpq parameters */ GetDlgItemText(hdlg, DS_LIBPQOPT, pqopt, sizeof(pqopt)); if (hmodule = LoadLibraryEx("libpq.dll", NULL, LOAD_WITH_ALTERED_SEARCH_PATH), NULL != hmodule) { pproc = (PQCONNINFOPARSEPROC) GetProcAddress(hmodule, "PQconninfoParse"); if (NULL != pproc && NULL == (connOpt= (*pproc)(pqopt, &ermsg))) { const char *logmsg = "libpq parameter error"; MessageBox(hdlg, ermsg ? ermsg : "memory over?", logmsg, MB_ICONEXCLAMATION | MB_OK); if (NULL != ermsg) free(ermsg); FreeLibrary(hmodule); return 1; } fproc = (PQCONNINFOFREEPROC) GetProcAddress(hmodule, "PQconninfoFree"); if (fproc) (*fproc)(connOpt); FreeLibrary(hmodule); } STR_TO_NAME(ci->pqopt, pqopt); #ifdef _HANDLE_ENLIST_IN_DTC_ if (IsDlgButtonChecked(hdlg, DS_DTC_LINK_ONLY)) ci->xa_opt = DTC_CHECK_LINK_ONLY; else if (IsDlgButtonChecked(hdlg, DS_DTC_SIMPLE_PRECHECK)) ci->xa_opt = DTC_CHECK_BEFORE_LINK; else if (IsDlgButtonChecked(hdlg, DS_DTC_CONFIRM_RM_CONNECTION)) ci->xa_opt = DTC_CHECK_RM_CONNECTION; else ci->xa_opt = 0; #endif /* _HANDLE_ENLIST_IN_DTC_ */ return 0; } LRESULT CALLBACK ds_options3Proc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam) { ConnInfo *ci, tmpInfo; char buf[128]; DWORD cmd; if (WM_INITDIALOG == wMsg || WM_COMMAND == wMsg) MYLOG(0, "entering wMsg=%d\n", wMsg); 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_DSN3, fbuf, sizeof(fbuf)); if (cmd <= 0) STRCPY_FIXED(fbuf, "Advanced Options (%s) 3/3"); SPRINTF_FIXED(buf, fbuf, ci->dsn); SetWindowText(hdlg, buf); } else { LoadString(s_hModule, IDS_ADVANCE_OPTION_CON3, buf, sizeof(buf)); SetWindowText(hdlg, buf); ShowWindow(GetDlgItem(hdlg, IDAPPLY), SW_HIDE); } ds_options3Draw(hdlg, ci); break; case WM_COMMAND: ci = (ConnInfo *) GetWindowLongPtr(hdlg, DWLP_USER); switch (cmd = GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: ds_options3_update(hdlg, ci); case IDCANCEL: EndDialog(hdlg, IDOK == cmd); return TRUE; case IDAPPLY: ds_options3_update(hdlg, ci); SendMessage(GetWindow(hdlg, GW_OWNER), WM_COMMAND, wParam, lParam); break; case IDC_TEST: CC_copy_conninfo(&tmpInfo, ci); ds_options3_update(hdlg, &tmpInfo); test_connection(hdlg, &tmpInfo, TRUE); CC_conninfo_release(&tmpInfo); break; case ID1STPAGE: ds_options3_update(hdlg, ci); EndDialog(hdlg, cmd == IDOK); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, ds_options1Proc, (LPARAM) ci); break; case ID2NDPAGE: ds_options3_update(hdlg, ci); EndDialog(hdlg, cmd == IDOK); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DS), hdlg, ds_options2Proc, (LPARAM) ci); break; } } 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-13.02.0000/loadlib.c000644 001751 001751 00000016274 14122574536 016657 0ustar00hiroshihiroshi000000 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" #include "pgenlist.h" #include "misc.h" #ifdef WIN32 #ifdef _MSC_VER #pragma comment(lib, "Delayimp") #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 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 #ifdef UNICODE_SUPPORT CSTR pgenlist = "pgenlist"; CSTR pgenlistdll = "pgenlist.dll"; CSTR psqlodbc = "psqlodbc35w"; CSTR psqlodbcdll = "psqlodbc35w.dll"; #else CSTR pgenlist = "pgenlista"; CSTR pgenlistdll = "pgenlista.dll"; CSTR psqlodbc = "psqlodbc30a"; CSTR psqlodbcdll = "psqlodbc30a.dll"; #endif /* UNICODE_SUPPORT */ #if defined(_MSC_VER) && (_MSC_VER >= 1200) #define _MSC_DELAY_LOAD_IMPORT #endif /* MSC_VER */ #endif /* DYNAMIC_LOAD */ #endif /* WIN32 */ #if defined(_MSC_DELAY_LOAD_IMPORT) /* * Error hook function for delay load import. * Try to load a DLL based on psqlodbc path. */ #if (_MSC_VER >= 1900) /* vc14 or later */ #define TRY_DLI_HOOK \ __try { #define RELEASE_NOTIFY_HOOK #elif (_MSC_VER < 1300) /* vc6 */ extern PfnDliHook __pfnDliFailureHook; extern PfnDliHook __pfnDliNotifyHook; #define TRY_DLI_HOOK \ __try { \ __pfnDliFailureHook = DliErrorHook; \ __pfnDliNotifyHook = DliErrorHook; #define RELEASE_NOTIFY_HOOK \ __pfnDliNotifyHook = NULL; #else /* vc7 ~ 12 */ extern PfnDliHook __pfnDliFailureHook2; extern PfnDliHook __pfnDliNotifyHook2; #define TRY_DLI_HOOK \ __try { \ __pfnDliFailureHook2 = DliErrorHook; \ __pfnDliNotifyHook2 = DliErrorHook; #define RELEASE_NOTIFY_HOOK \ __pfnDliNotifyHook2 = NULL; #endif /* _MSC_VER */ #else #define TRY_DLI_HOOK \ __try { #define RELEASE_NOTIFY_HOOK #endif /* _MSC_DELAY_LOAD_IMPORT */ #if defined(_MSC_DELAY_LOAD_IMPORT) static BOOL loaded_pgenlist = FALSE; static HMODULE enlist_module = NULL; static BOOL loaded_psqlodbc = FALSE; /* * Load a DLL based on psqlodbc path. */ 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); SPRINTF_FIXED(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(0, "psqlodbc path based %s loaded module=%p\n", module_name, hmodule); } } return hmodule; } static FARPROC WINAPI DliErrorHook(unsigned dliNotify, PDelayLoadInfo pdli) { HMODULE hmodule = NULL; const char* call_module = NULL; MYLOG(0, "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: RELEASE_NOTIFY_HOOK if (_strnicmp(pdli->szDll, pgenlist, strlen(pgenlist)) == 0) call_module = pgenlist; else if (_strnicmp(pdli->szDll, psqlodbc, strlen(psqlodbc)) == 0) call_module = psqlodbc; if (call_module) { if (hmodule = MODULE_load_from_psqlodbc_path(call_module), NULL == hmodule) hmodule = LoadLibrary(call_module); if (NULL != hmodule) { if (pgenlist == call_module) loaded_pgenlist = TRUE; else if (psqlodbc == call_module) loaded_psqlodbc = TRUE; } } break; } return (FARPROC) hmodule; } void AlreadyLoadedPsqlodbc(void) { loaded_psqlodbc = TRUE; } /* * unload delay loaded libraries. */ 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_pgenlist) { if (enlist_module != NULL) { MYLOG(0, "Freeing Library %s\n", pgenlistdll); FreeLibrary(enlist_module); } MYLOG(0, "%s unloading\n", pgenlistdll); success = (*func)(pgenlistdll); MYLOG(0, "%s unloaded success=%d\n", pgenlistdll, success); loaded_pgenlist = FALSE; } if (loaded_psqlodbc) { MYLOG(0, "%s unloading\n", psqlodbcdll); success = (*func)(psqlodbcdll); MYLOG(0, "%s unloaded success=%d\n", psqlodbcdll, success); loaded_psqlodbc = FALSE; } return; } #else void CleanupDelayLoadedDLLs(void) { return; } #endif /* _MSC_DELAY_LOAD_IMPORT */ #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) if (!loaded_pgenlist) { TRY_DLI_HOOK ret = EnlistInDtc(conn, pTra, method); } __except ((GetExceptionCode() & 0xffff) == ERROR_MOD_NOT_FOUND ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { if (enlist_module = MODULE_load_from_psqlodbc_path(pgenlist), NULL == enlist_module) loaded = FALSE; else ret = EnlistInDtc(conn, pTra, method); } if (loaded) loaded_pgenlist = TRUE; RELEASE_NOTIFY_HOOK } else ret = EnlistInDtc(conn, pTra, method); #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; } void *CALL_GetTransactionObject(HRESULT *hres) { void *ret = NULL; BOOL loaded = TRUE; #if defined(_MSC_DELAY_LOAD_IMPORT) if (!loaded_pgenlist) { TRY_DLI_HOOK ret = GetTransactionObject(hres); } __except ((GetExceptionCode() & 0xffff) == ERROR_MOD_NOT_FOUND ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { if (enlist_module = MODULE_load_from_psqlodbc_path(pgenlist), NULL == enlist_module) loaded = FALSE; else ret = GetTransactionObject(hres); } if (loaded) loaded_pgenlist = TRUE; RELEASE_NOTIFY_HOOK } else ret = GetTransactionObject(hres); #else ret = GetTransactionObject(hres); loaded_pgenlist = TRUE; #endif /* _MSC_DELAY_LOAD_IMPORT */ return ret; } void CALL_ReleaseTransactionObject(void *pObj) { if (loaded_pgenlist) ReleaseTransactionObject(pObj); return; } #endif /* _HANDLE_ENLIST_IN_DTC_ */ psqlodbc-13.02.0000/loadlib.h000644 001751 001751 00000001743 14122574536 016657 0ustar00hiroshihiroshi000000 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 #ifdef _HANDLE_ENLIST_IN_DTC_ RETCODE CALL_EnlistInDtc(ConnectionClass *conn, void * pTra, int method); RETCODE CALL_DtcOnDisconnect(ConnectionClass *); RETCODE CALL_IsolateDtcConn(ConnectionClass *, BOOL); void *CALL_GetTransactionObject(HRESULT *); void CALL_ReleaseTransactionObject(void *); #endif /* _HANDLE_ENLIST_IN_DTC_ */ /* void UnloadDelayLoadedDLLs(BOOL); */ void CleanupDelayLoadedDLLs(void); #ifdef WIN32 HMODULE MODULE_load_from_psqlodbc_path(const char *module_name); void AlreadyLoadedPsqlodbc(void); #endif /* WIN32 */ #ifdef __cplusplus } #endif #endif /* __LOADLIB_H__ */ psqlodbc-13.02.0000/inouealc.c000644 001751 001751 00000012100 14122574536 017030 0ustar00hiroshihiroshi000000 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); MYLOG(2, " alloced=%p(" FORMAT_SIZE_T ")\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(0, "%s:alloc " FORMAT_SIZE_T "byte\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(0, "%s:calloc " FORMAT_SIZE_T "byte\n", ALCERR, size); MYLOG(2, "calloced = %p\n", alloced); return alloced; } void * pgdebug_realloc(void * ptr, size_t size) { void * alloced; if (!ptr) return pgdebug_alloc(size); alloced = realloc(ptr, size); if (!alloced) { MYLOG(0, "%s %p error\n", ALCERR, ptr); } 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; } } } MYLOG(2, "%p->%p\n", ptr, alloced); return alloced; } char * pgdebug_strdup(const char * ptr) { char * alloced = strdup(ptr); if (!alloced) { MYLOG(0, "%s %p error\n", ALCERR, 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++; } MYLOG(2, "%p->%p(%s)\n", ptr, alloced, alloced); return alloced; } void pgdebug_free(void * ptr) { int i, j; int freed = 0; if (!ptr) { MYLOG(0, "%s null ptr\n", ALCERR); 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(0, "%s not found ptr %p\n", ALCERR, ptr); return; } else MYLOG(2, "ptr=%p\n", 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 ((ULONG_PTR)out < (ULONG_PTR)(altbl[i].aladr)) continue; if ((ULONG_PTR)out < (ULONG_PTR)(altbl[i].aladr) + altbl[i].len) { if ((ULONG_PTR)out + len > (ULONG_PTR)(altbl[i].aladr) + altbl[i].len) { ret = FALSE; MYLOG(0, "%s:%s:out_check found memory buffer overrun %p(" FORMAT_SIZE_T ")>=%p(" FORMAT_SIZE_T ")\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(0, "%s null pointer out=%p,in=%p\n", ALCERR, 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(0, "%s null pointer out=%p,in=%p\n", ALCERR, 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(0, "%s null pointer out=%p,in=%p\n", ALCERR, out, in); return NULL; } out_check(out, len, __FUNCTION__); strncpy_null(out, in, len); return out; } void *pgdebug_memcpy(void *out, const void *in, size_t len) { if (!out || !in) { MYLOG(0, "%s null pointer out=%p,in=%p\n", ALCERR, 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(0, "%s null pointer out=%p\n", ALCERR, out); return NULL; } out_check(out, len, __FUNCTION__); return memset(out, c, len); } void debug_memory_check(void) { int i; if (0 == tbsize) { MYLOG(0, "no memry leak found and max count allocated so far is %d\n", alsize); free(altbl); alsize = 0; } else { MYLOG(0, "%s:memory leak found check count=%d alloc=%d\n", ALCERR, tbsize, alsize); for (i = 0; i < tbsize; i++) { MYLOG(0, "%s:leak = %p(" FORMAT_SIZE_T ")\n", ALCERR, altbl[i].aladr, altbl[i].len); } } } psqlodbc-13.02.0000/win_setup.h000644 001751 001751 00000001502 14122574536 017257 0ustar00hiroshihiroshi000000 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, * LPSETUPDLG; /* Prototypes */ LRESULT CALLBACK ConfigDlgProc(HWND hdlg, UINT wMsg, WPARAM wParam, LPARAM lParam); BOOL INTFUNC ChangeDriverName(HWND hwnd, LPSETUPDLG lpsetupdlg, LPCSTR driver_name); void test_connection(HANDLE hwnd, ConnInfo *ci, BOOL withDTC); #endif /* _WIN_SETUP_H__ */ psqlodbc-13.02.0000/psqlsetup.c000644 001751 001751 00000006247 14122574536 017310 0ustar00hiroshihiroshi000000 000000 #include #include "psqlodbc.h" #include "dlg_specific.h" #include "loadlib.h" #include "misc.h" HINSTANCE s_hModule; /* Saved module handle. */ #include #include #include RETCODE SQL_API SQLDummyOrdinal(void); /* * 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; } static HINSTANCE s_hLModule = NULL; /* for libpq */ static HINSTANCE s_hLModule2 = NULL; /* This is where the Driver Manager attaches to this Driver */ int initialize_global_cs(void) { static int init = 1; if (!init) return 0; init = 0; InitializeLogging(); return 0; } static void finalize_global_cs(void) { FinalizeLogging(); #ifdef _DEBUG #ifdef _MEMORY_DEBUG_ // _CrtDumpMemoryLeaks(); #endif /* _MEMORY_DEBUG_ */ #endif /* _DEBUG */ } #ifdef UNICODE_SUPPORT CSTR psqlodbc = "psqlodbc35w"; #else CSTR psqlodbc = "psqlodbc30a"; #endif BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) { char dllPath[MAX_PATH] = ""; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: s_hModule = hInst; /* Save for dialog boxes */ initialize_global_cs(); #ifdef PG_BIN if (s_hLModule = LoadLibraryEx(PG_BIN "\\libpq.dll", NULL, LOAD_WITH_ALTERED_SEARCH_PATH), s_hLModule == NULL) MYLOG(0, "libpq in the folder %s couldn't be loaded\n", PG_BIN); #endif /* PG_BIN */ if (NULL == s_hLModule) { char message[MAX_PATH] = ""; SQLGetPrivateProfileString(DBMS_NAME, "Driver", "", dllPath, sizeof(dllPath), ODBCINST_INI); if (dllPath[0]) { char drive[_MAX_DRIVE], dir[_MAX_DIR]; _splitpath(dllPath, drive, dir, NULL, NULL); SPRINTF_FIXED(dllPath, "%s%slibpq.dll", drive, dir); if (s_hLModule = LoadLibraryEx(dllPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH), s_hLModule == NULL) { MYLOG(0, "libpq in the folder %s%s couldn't be loaded\n", drive, dir); SPRINTF_FIXED(message, "libpq in neither %s nor %s%s could be loaded", PG_BIN, drive, dir); } } #ifdef PG_BIN else SPRINTF_FIXED(message, "libpq in the folder %s couldn't be loaded", PG_BIN); #endif /* PG_BIN */ if (message[0]) MessageBox(NULL, message, "psqlsetup", MB_OK); } if (s_hLModule2 = MODULE_load_from_psqlodbc_path(psqlodbc), s_hLModule2 == NULL) { MessageBox(NULL, "psqlodbc load error", "psqlsetup", MB_OK); return TRUE; } else AlreadyLoadedPsqlodbc(); break; case DLL_THREAD_ATTACH: break; case DLL_PROCESS_DETACH: MYLOG(0, "DETACHING psqlsetup\n"); CleanupDelayLoadedDLLs(); if (NULL != s_hLModule) { MYLOG(0, "Freeing Library libpq\n"); FreeLibrary(s_hLModule); } if (NULL != s_hLModule2) { MYLOG(0, "Freeing Library %s\n", psqlodbc); FreeLibrary(s_hLModule2); } finalize_global_cs(); return TRUE; case DLL_THREAD_DETACH: break; default: break; } return TRUE; UNREFERENCED_PARAMETER(lpReserved); } psqlodbc-13.02.0000/setup.c000644 001751 001751 00000047063 14122574536 016411 0ustar00hiroshihiroshi000000 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 "pgenlist.h" #include "loadlib.h" #include "misc.h" // strncpy_null //#include "environ.h" #include #include #include #include "resource.h" #include "pgapifunc.h" #include "dlg_specific.h" #include "win_setup.h" #define INTFUNC __stdcall extern HINSTANCE s_hModule; /* Saved module handle. */ /* 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 */ static void ParseAttributes(LPCSTR lpszAttributes, LPSETUPDLG lpsetupdlg); static BOOL SetDSNAttributes(HWND hwndParent, LPSETUPDLG lpsetupdlg, DWORD *errcode); static BOOL SetDriverAttributes(LPCSTR lpszDriver, DWORD *pErrorCode, LPSTR pErrorMessage, WORD cbMessage); static void CenterDialog(HWND hdlg); /*-------- * 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); /* First of all, parse attribute string only for DSN entry */ CC_conninfo_init(&(lpsetupdlg->ci), INIT_GLOBALS); if (lpszAttributes) ParseAttributes(lpszAttributes, lpsetupdlg); /* Save original data source name */ if (lpsetupdlg->ci.dsn[0]) STRCPY_FIXED(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); /* Cleanup conninfo and restore data source name */ CC_conninfo_init(&(lpsetupdlg->ci), CLEANUP_FOR_REUSE | INIT_GLOBALS); STRCPY_FIXED(lpsetupdlg->ci.dsn, lpsetupdlg->szDSN); /* Get common attributes of Data Source */ getDSNinfo(&(lpsetupdlg->ci), lpsetupdlg->lpszDrvr); /* * Parse attribute string again * * NOTE: Values supplied in the attribute string will always * override settings in ODBC.INI */ if (lpszAttributes) ParseAttributes(lpszAttributes, lpsetupdlg); /* * 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]) { MYLOG(0, "SetDSNAttributes\n"); fSuccess = SetDSNAttributes(hwnd, lpsetupdlg, NULL); } else fSuccess = FALSE; } CC_conninfo_release(&(lpsetupdlg->ci)); 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 *-------- */ 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 *------- */ static void 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 */ /* Initialize dialog fields */ SetDlgStuff(hdlg, ci); /* Save drivername */ if (!(lpsetupdlg->ci.drivername[0])) STRCPY_FIXED(lpsetupdlg->ci.drivername, lpsetupdlg->lpszDrvr); 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: lpsetupdlg = (LPSETUPDLG) GetWindowLongPtr(hdlg, DWLP_USER); 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: /* 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: { if (NULL != lpsetupdlg) { /* Get Dialog Values */ GetDlgStuff(hdlg, &lpsetupdlg->ci); test_connection(lpsetupdlg->hwndParent, &lpsetupdlg->ci, FALSE); return TRUE; } break; } case IDC_DATASOURCE: /* Get Dialog Values */ GetDlgStuff(hdlg, &lpsetupdlg->ci); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_DRV), hdlg, ds_options1Proc, (LPARAM) &lpsetupdlg->ci); return TRUE; case IDC_DRIVER: /* Get Dialog Values */ GetDlgStuff(hdlg, &lpsetupdlg->ci); DialogBoxParam(s_hModule, MAKEINTRESOURCE(DLG_OPTIONS_GLOBAL), hdlg, global_optionsProc, (LPARAM) &lpsetupdlg->ci); return TRUE; case IDC_MANAGEDSN: 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 (LRESULT)hBrush; } break; } /* Message not processed */ return FALSE; } #ifdef USE_PROC_ADDRESS #define SQLALLOCHANDLEFUNC sqlallochandle #define SQLSETENVATTRFUNC sqlsetenvattr #define SQLDISCONNECTFUNC sqldisconnect #define SQLFREEHANDLEFUNC sqlfreehandle #ifdef UNICODE_SUPPORT #define SQLGETDIAGRECFUNC sqlgetdiagrecw #define SQLDRIVERCONNECTFUNC sqldriverconnectw #define SQLSETCONNECTATTRFUNC sqlsetconnectattrw #else #define SQLGETDIAGRECFUNC sqlgetdiagrec #define SQLDRIVERCONNECTFUNC sqldriverconnect #define SQLSETCONNECTATTRFUNC sqlsetconnectAttr #endif /* UNICODE_SUPPORT */ #else #define SQLALLOCHANDLEFUNC SQLAllocHandle #define SQLSETENVATTRFUNC SQLSetEnvAttr #define SQLDISCONNECTFUNC SQLDisconnect #define SQLFREEHANDLEFUNC SQLFreeHandle #ifdef UNICODE_SUPPORT #define SQLGETDIAGRECFUNC SQLGetDiagRecW #define SQLDRIVERCONNECTFUNC SQLDriverConnectW #define SQLSETCONNECTATTRFUNC SQLSetConnectAttrW #else #define SQLGETDIAGRECFUNC SQLGetDiagRec #define SQLDRIVERCONNECTFUNC SQLDriverConnect #define SQLSETCONNECTATTRFUNC SQLSetConnectAttr #endif /* UNICODE_SUPPORT */ #endif /* USE_PROC_ADDRESS */ #define MAX_CONNECT_STRING_LEN 2048 #ifdef UNICODE_SUPPORT #define MESSAGEBOXFUNC MessageBoxW #define _T(str) L ## str #define SNTPRINTF _snwprintf #else #define MESSAGEBOXFUNC MessageBoxA #define _T(str) str #define SNTPRINTF snprintf #endif /* UNICODE_SUPPORT */ void test_connection(HANDLE hwnd, ConnInfo *ci, BOOL withDTC) { int errnum; char out_conn[MAX_CONNECT_STRING_LEN]; SQLRETURN ret; SQLHENV env = SQL_NULL_HANDLE; SQLHDBC conn = SQL_NULL_HANDLE; SQLSMALLINT str_len; char dsn_1st; BOOL connected = FALSE; #ifdef UNICODE_SUPPORT SQLWCHAR wout_conn[MAX_CONNECT_STRING_LEN]; SQLWCHAR szMsg[SQL_MAX_MESSAGE_LENGTH]; const SQLWCHAR *ermsg = NULL; SQLWCHAR *conn_str; #else SQLCHAR szMsg[SQL_MAX_MESSAGE_LENGTH]; const SQLCHAR *ermsg = NULL; SQLCHAR *conn_str; #endif /* UNICODE_SUPPORT */ dsn_1st = ci->dsn[0]; ci->dsn[0] = '\0'; if (NAME_IS_VALID(ci->conn_settings)) ci->conn_settings_in_str = TRUE; if (NAME_IS_VALID(ci->pqopt)) ci->pqopt_in_str = TRUE; makeConnectString(out_conn, ci, sizeof(out_conn)); MYLOG(0, "conn_string=%s\n", out_conn); #ifdef UNICODE_SUPPORT MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, out_conn, -1, wout_conn, sizeof(wout_conn) / sizeof(wout_conn[0])); conn_str = wout_conn; #else conn_str = out_conn; #endif /* UNICODE_SUPPORT */ ci->dsn[0] = dsn_1st; if (!SQL_SUCCEEDED(ret = SQLALLOCHANDLEFUNC(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env))) { ermsg = _T("SQLAllocHandle for env error"); goto cleanup; } if (!SQL_SUCCEEDED(ret = SQLSETENVATTRFUNC(env, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, 0))) { SNTPRINTF(szMsg, _countof(szMsg), _T("SQLAllocHandle for env error=%d"), ret); goto cleanup; } if (!SQL_SUCCEEDED(ret = SQLALLOCHANDLEFUNC(SQL_HANDLE_DBC, env, &conn))) { SQLGETDIAGRECFUNC(SQL_HANDLE_ENV, env, 1, NULL, &errnum, szMsg, _countof(szMsg), &str_len); ermsg = szMsg; goto cleanup; } if (!SQL_SUCCEEDED(ret = SQLDRIVERCONNECTFUNC(conn, hwnd, conn_str, SQL_NTS, NULL, MAX_CONNECT_STRING_LEN, &str_len, SQL_DRIVER_NOPROMPT))) { SQLGETDIAGRECFUNC(SQL_HANDLE_DBC, conn, 1, NULL, &errnum, szMsg, _countof(szMsg), &str_len); ermsg = szMsg; goto cleanup; } connected = TRUE; ermsg = _T("Connection successful"); if (withDTC) { #ifdef _HANDLE_ENLIST_IN_DTC_ HRESULT res; void *pObj = NULL; pObj = CALL_GetTransactionObject(&res); if (NULL != pObj) { SQLRETURN ret = SQLSETCONNECTATTRFUNC(conn, SQL_ATTR_ENLIST_IN_DTC, (SQLPOINTER) pObj, 0); if (SQL_SUCCEEDED(ret)) { SQLSETCONNECTATTRFUNC(conn, SQL_ATTR_ENLIST_IN_DTC, SQL_DTC_DONE, 0); SNTPRINTF(szMsg, _countof(szMsg), _T("%s\nenlistment was successful\n"), ermsg); ermsg = szMsg; } else { int strl; SNTPRINTF(szMsg, _countof(szMsg), _T("%s\nMSDTC error:"), ermsg); for (strl = 0; strl < SQL_MAX_MESSAGE_LENGTH; strl++) { if (!szMsg[strl]) break; } SQLGETDIAGRECFUNC(SQL_HANDLE_DBC, conn, 1, NULL, &errnum, szMsg + strl, _countof(szMsg) - strl, &str_len); ermsg = szMsg; } CALL_ReleaseTransactionObject(pObj); } else if (FAILED(res)) { SNTPRINTF(szMsg, _countof(szMsg), _T("%s\nDistibuted Transaction enlistment error %x"), ermsg, res); ermsg = szMsg; } #else /* _HANDLE_ENLIST_IN_DTC_ */ SNTPRINTF(szMsg, _countof(szMsg), _T("%s\nDistibuted Transaction enlistment not supported by this driver"), ermsg); ermsg = szMsg; #endif } cleanup: if (NULL != ermsg && NULL != hwnd) { MESSAGEBOXFUNC(hwnd, ermsg, _T("Connection Test"), MB_ICONEXCLAMATION | MB_OK); } #undef _T if (NULL != conn) { if (connected) SQLDISCONNECTFUNC(conn); SQLFREEHANDLEFUNC(SQL_HANDLE_DBC, conn); } if (env) SQLFREEHANDLEFUNC(SQL_HANDLE_ENV, env); return; } /*------- * ParseAttributes * * Description: Parse attribute string moving values into the aAttr array * Input : lpszAttributes - Pointer to attribute string * Output : None (global aAttr normally updated) *------- */ static void ParseAttributes(LPCSTR lpszAttributes, LPSETUPDLG lpsetupdlg) { LPCSTR lpsz; LPCSTR lpszStart; char aszKey[MAXKEYLEN]; size_t cbKey; char value[MAXPGPATH]; 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)) { memcpy(aszKey, lpszStart, cbKey); aszKey[cbKey] = '\0'; } /* Locate end of key value */ lpszStart = ++lpsz; for (; *lpsz; lpsz++) ; /* lpsetupdlg->aAttr[iElement].fSupplied = TRUE; */ memcpy(value, lpszStart, MIN(lpsz - lpszStart + 1, MAXPGPATH)); MYLOG(0, "aszKey='%s', value='%s'\n", aszKey, value); /* Copy the appropriate value to the conninfo */ copyConnAttributes(&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 *-------- */ static BOOL 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]; ret = SQLInstallerError(1, &err, szMsg, sizeof(szMsg), NULL); if (hwndParent) { char szBuf[MAXPGPATH]; if (SQL_SUCCESS != ret) { LoadString(s_hModule, IDS_BADDSN, szBuf, sizeof(szBuf)); SPRINTF_FIXED(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 */ write_Ci_Drivers(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; char ver_string[8]; /* 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; SPRINTF_FIXED(ver_string, "%02x.%02x", ODBCVER / 256, ODBCVER % 256); if (!SQLWritePrivateProfileString(lpszDriver, "DriverODBCVer", ver_string, 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-13.02.0000/psqlodbc.rc000644 001751 001751 00000113336 14122574536 017237 0ustar00hiroshihiroshi000000 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 #define MISC_X #define MISC_Y 155 #define MISC_Y1 (MISC_Y+11) #define MISC_Y2 (MISC_Y+28) #define MISC_Y3 (MISC_Y+45) 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 "Ý’è2",ID2NDPAGE,5,5,40,15 PUSHBUTTON "Ý’è3",ID3RDPAGE,49,5,40,15 CONTROL "ˆê”ʃƒOo—Í‚ð‚·‚é(&L) (C:\\psqlodbc.log)",DRV_COMMLOG, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,167,24,167,10 EDITTEXT DS_COMMLOG,337,24,13,12,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT CONTROL "ƒ†ƒj|ƒNƒCƒ“ƒfƒbƒNƒX‚ðŽg‚¤(&I)",DRV_UNIQUEINDEX,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,56,129,10 CONTROL "ƒ^ƒCƒ€ƒAƒEƒg–³Ž‹",DS_IGNORETIMEOUT,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,167,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 "Ú׃ƒOo—Í‚ð‚·‚é(C:\\mylog_xxxx.log)",DRV_DEBUG, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,167,69,164,10 EDITTEXT DS_DEBUG,337,69,13,12,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT 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 GROUPBOX "‚»‚Ì‘¼",IDC_STATIC,5,MISC_Y,340,57 LTEXT "Å‘å&Varchar:",IDC_STATIC,13,MISC_Y1+1,54,8 EDITTEXT DRV_VARCHAR_SIZE,70,MISC_Y1,35,12,ES_AUTOHSCROLL LTEXT "Å‘åLon&gVarChar:",IDC_STATIC,148,MISC_Y1+2,66,8 EDITTEXT DRV_LONGVARCHAR_SIZE,219,MISC_Y1,35,12,ES_AUTOHSCROLL LTEXT "·¬¯¼­»²½Þ:",IDC_STATIC,21,MISC_Y2+1,39,8 EDITTEXT DRV_CACHE_SIZE,69,MISC_Y2-1,35,12,ES_AUTOHSCROLL LTEXT "¼½ÃÑðÌÞÙ ÌßŲ́¸½:",IDC_STATIC,140,MISC_Y2+1,74,9 EDITTEXT DRV_EXTRASYSTABLEPREFIXES,219,MISC_Y2-1,71,12,ES_AUTOHSCROLL LTEXT "ƒoƒbƒ`ƒTƒCƒY:",IDC_STATIC,13,MISC_Y3+1,74,9 EDITTEXT DS_BATCH_SIZE,69,MISC_Y3-1,35,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 END #define CONNSETTINGS_Y 185 // 191 #define KEEPALIVE_X 5 #define KEEPALIVE_Y 225 #define ENDLINE_Y 245 // 224 DLG_OPTIONS_DS DIALOG DISCARDABLE 0, 0, 306, 260 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 "Ý’è3",ID3RDPAGE,49,5,40,15 PUSHBUTTON "Ý’è1",ID1STPAGE,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 "•â•“IƒGƒ‰[ƒƒbƒZ[ƒW‚ð•\ަ",DS_OPTIONALERRORS,"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 "Numeric(¸“xŽw’è‚È‚µ) ‚Ì‘ã‘Ö’è‹`",IDC_STATIC,5,128,160,25 CONTROL "default",DS_NUMERIC_AS_DEFAULT,"Button",BS_AUTORADIOBUTTON | WS_GROUP,12,140,40,10 // CONTROL "numeric",DS_NUMERIC_AS_NUMERIC,"Button",BS_AUTORADIOBUTTON | // WS_TABSTOP,50,140,40,10 CONTROL "memo",DS_NUMERIC_AS_LONGVARCHAR,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,126,140,40,10 CONTROL "varchar",DS_NUMERIC_AS_VARCHAR,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,50,140,40,10 CONTROL "double",DS_NUMERIC_AS_DOUBLE,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,90,140,36,10 GROUPBOX "ƒGƒ‰[Žž‚̃[ƒ‹ƒoƒbƒN”­s",IDC_STATIC,170,128,130,25 CONTROL "–³‚µ",DS_NO_ROLLBACK,"Button",BS_AUTORADIOBUTTON | WS_GROUP,175,139,30,10 CONTROL "‘S·¬Ý¾Ù",DS_TRANSACTION_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,205,140,50,10 CONTROL "•¶’PˆÊ",DS_STATEMENT_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,260,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,CONNSETTINGS_Y+3,69,10,NOT WS_GROUP EDITTEXT DS_CONNSETTINGS,90,CONNSETTINGS_Y,211,27,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN | NOT WS_TABSTOP GROUPBOX "TCP KEEPALIVE(•b’PˆÊ)",IDC_STATIC,KEEPALIVE_X,KEEPALIVE_Y-10,210,25 CONTROL "—˜—p‚µ‚È‚¢",DS_DISABLE_KEEPALIVE,"Button",BS_AUTOCHECKBOX | WS_GROUP, KEEPALIVE_X+5,KEEPALIVE_Y,50,10 LTEXT "‘Ò‚¿ŽžŠÔ",IDC_STATIC,KEEPALIVE_X+62,KEEPALIVE_Y,35,10,NOT WS_GROUP EDITTEXT DS_KEEPALIVETIME,KEEPALIVE_X+100,KEEPALIVE_Y,30,10, ES_AUTOHSCROLL | WS_TABSTOP LTEXT "‰ž“š‘ÒŽžŠÔ",IDC_STATIC,KEEPALIVE_X+137,KEEPALIVE_Y,40,10,NOT WS_GROUP EDITTEXT DS_KEEPALIVEINTERVAL,KEEPALIVE_X+180,KEEPALIVE_Y,30,10, ES_AUTOHSCROLL | WS_TABSTOP DEFPUSHBUTTON "OK",IDOK,5,ENDLINE_Y,50,14,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,66,ENDLINE_Y,50,14 PUSHBUTTON "“K—p",IDAPPLY,128,ENDLINE_Y,50,14 CONTROL "bytea‚ðLO‚Æ‚µ‚Ĉµ‚¤",DS_BYTEAASLONGVARBINARY,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,85,87,10 CONTROL "Šerefcursor‚©‚猋‰Ê‚ðŽæ“¾‚µ‚Ü‚·",DS_FETCH_REFCURSORS, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,139,85,140,10 END #define DTC_GRP_X 10 #define DTC_GRP_Y 60 #define DTC_GRP_WIDTH 200 #define DTC_GRP_HEIGHT 100 #define DTC_OPT_X (DTC_GRP_X) #define DTC_OPT_Y (DTC_GRP_Y+10) #define DTC_OPT_WIDTH 180 #define DTC_OPT_HEIGHT 45 #define DTC_LOG_X (DTC_GRP_X) #define DTC_LOG_Y (DTC_OPT_Y+60) #define LIBPQOPT_Y 185 DLG_OPTIONS_DS3 DIALOG DISCARDABLE 0, 0, 306, 243 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "‚“x‚ÈÝ’è (ƒf[ƒ^ƒ\[ƒX‚R)" FONT 9, "‚l‚r ƒSƒVƒbƒN" BEGIN PUSHBUTTON "Ý’è2",ID2NDPAGE,49,5,40,15 PUSHBUTTON "Ý’è1",ID1STPAGE,5,5,40,15 GROUPBOX "•ªŽUƒgƒ‰ƒ“ƒUƒNƒVƒ‡ƒ“ŠÖ˜AÝ’è",IDC_STATIC,DTC_GRP_X,DTC_GRP_Y,DTC_GRP_WIDTH,DTC_GRP_HEIGHT GROUPBOX "MSDTCƒŠƒJƒoƒŠ[•s‰ÂÚ‘±‚ð‹–‰Â?",IDC_STATIC,DTC_OPT_X,DTC_OPT_Y,DTC_OPT_WIDTH,DTC_OPT_HEIGHT CONTROL "‚·‚é",DS_DTC_LINK_ONLY,"Button",BS_AUTORADIOBUTTON | WS_GROUP,DTC_OPT_X+5,DTC_OPT_Y+10,140,10 CONTROL "sslmode verify-[ca|full]‚ð‹‘â",DS_DTC_SIMPLE_PRECHECK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,DTC_OPT_X+5,DTC_OPT_Y+20,140,10 CONTROL "‚µ‚È‚¢(ʼn‚ÉMSDTC‚©‚ç‚ÌÚ‘±«‚ðŠm”F)",DS_DTC_CONFIRM_RM_CONNECTION,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,DTC_OPT_X+5,DTC_OPT_Y+30,170,10 PUSHBUTTON "Ú‘±ƒeƒXƒg",IDC_TEST,DTC_OPT_X+60,DTC_OPT_Y+75,51,14 LTEXT "libpqƒpƒ‰ƒ[ƒ^:(&l)",IDC_STATIC,11,LIBPQOPT_Y+3,76,10,NOT WS_GROUP EDITTEXT DS_LIBPQOPT,90,LIBPQOPT_Y,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 END #undef ENDLINE_Y #define ENDLINE_Y 110 DLG_OPTIONS_GLOBAL DIALOG DISCARDABLE 0, 0, 306, 130 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 GROUPBOX "ƒRƒlƒNƒVƒ‡ƒ“‘O‚̃fƒtƒHƒ‹ƒgƒƒMƒ“ƒOƒIƒvƒVƒ‡ƒ“", IDC_STATIC,5,5,296,68 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 RTEXT "ƒƒMƒ“ƒO—pƒtƒHƒ‹ƒ_",IDC_STATIC,14,57,79,12 EDITTEXT DS_LOGDIR,98,55,188,13,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT GROUPBOX "MSDTCƒTƒ|[ƒg", IDC_STATIC,5,75,296,27 CONTROL "ê—pƒƒO(C:\\pgdtclog\\mylog_xxxx.log - ƒfƒoƒbƒOo—̓ƒO)", DRV_DTCLOG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,22,87,260,10 DEFPUSHBUTTON "•Û‘¶",IDOK,5,ENDLINE_Y,50,14,WS_GROUP PUSHBUTTON "ƒLƒƒƒ“ƒZƒ‹",IDCANCEL,65,ENDLINE_Y,50,15 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_OPTION_DSN3 "‚“x‚ÈÝ’è (%s Ý’è3)" IDS_ADVANCE_OPTION_CON3 "‚“x‚ÈÝ’è (ƒRƒlƒNƒVƒ‡ƒ“Ý’è3)" 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 #undef MISC_Y #undef MISC_Y1 #undef MISC_Y2 #undef MISC_Y3 #define MISC_Y 145 #define MISC_Y1 (MISC_Y+15) #define MISC_Y2 (MISC_Y+32) #define MISC_Y3 (MISC_Y+49) 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 2",ID2NDPAGE,5,5,40,15 PUSHBUTTON "Page 3",ID3RDPAGE,49,5,40,15 CONTROL "Comm&Log (C:\\psqlodbc_xxxx.log)",DRV_COMMLOG,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,149,26,121,10 EDITTEXT DS_COMMLOG,275,26,100,13,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT CONTROL "Recognize Unique &Indexes",DRV_UNIQUEINDEX,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,15,56,110,10 CONTROL "Ignore Timeout",DS_IGNORETIMEOUT,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,149,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 "MyLog (C:\\mylog_xxxx.log)",DRV_DEBUG,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,149,71,112,10 EDITTEXT DS_DEBUG,275,71,15,12,ES_AUTOHSCROLL | WS_GROUP, WS_EX_TRANSPARENT 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 GROUPBOX "Miscellaneous",IDC_STATIC,5,MISC_Y,277,62 LTEXT "Max &Varchar:",IDC_STATIC,13,MISC_Y1+1,54,8 EDITTEXT DRV_VARCHAR_SIZE,70,MISC_Y1,35,12,ES_AUTOHSCROLL LTEXT "Max Lon&gVarChar:",IDC_STATIC,125,MISC_Y1+1,67,8 EDITTEXT DRV_LONGVARCHAR_SIZE,199,MISC_Y1,35,12,ES_AUTOHSCROLL LTEXT "&Cache Size:",IDC_STATIC,14,MISC_Y2+1,52,8 EDITTEXT DRV_CACHE_SIZE,69,MISC_Y2-1,35,12,ES_AUTOHSCROLL LTEXT "SysTable &Prefixes:",IDC_STATIC,126,MISC_Y2+1,61,18 EDITTEXT DRV_EXTRASYSTABLEPREFIXES,199,MISC_Y2-1,71,12,ES_AUTOHSCROLL LTEXT "&Batch &Size:",IDC_STATIC,14,MISC_Y3+1,61,18 EDITTEXT DS_BATCH_SIZE,69,MISC_Y3-1,35,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 END #undef CONNSETTINGS_Y #undef KEEPALIVE_X #undef KEEPALIVE_Y #undef ENDLINE_Y #define CONNSETTINGS_Y 185 // 189 #define KEEPALIVE_X 10 #define KEEPALIVE_Y 225 #define ENDLINE_Y 245 // 222 DLG_OPTIONS_DS DIALOG DISCARDABLE 0, 0, 306, 260 STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Advanced Options (DataSource)" FONT 8, "MS Sans Serif" BEGIN PUSHBUTTON "Page 3",ID3RDPAGE,49,5,40,15 PUSHBUTTON "Page 1",ID1STPAGE,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 "Display Optional Error Message",DS_OPTIONALERRORS,"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 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 "Fetch result from each refcursor",DS_FETCH_REFCURSORS, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,163,84,122,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 "Numeric(without precision) As",IDC_STATIC,5,126,160,25 CONTROL "default",DS_NUMERIC_AS_DEFAULT,"Button",BS_AUTORADIOBUTTON | WS_GROUP,12,138,40,10 // CONTROL "numeric",DS_NUMERIC_AS_NUMERIC,"Button",BS_AUTORADIOBUTTON | // WS_TABSTOP,50,138,40,10 CONTROL "memo",DS_NUMERIC_AS_LONGVARCHAR,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,126,138,40,10 CONTROL "varchar",DS_NUMERIC_AS_VARCHAR,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,50,138,40,10 CONTROL "double",DS_NUMERIC_AS_DOUBLE,"Button",BS_AUTORADIOBUTTON | WS_TABSTOP,90,138,36,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,CONNSETTINGS_Y,57,11 EDITTEXT DS_CONNSETTINGS,90,CONNSETTINGS_Y,211,27,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN GROUPBOX "TCP KEEPALIVE setting (by sec)",IDC_STATIC,KEEPALIVE_X,KEEPALIVE_Y-10,210,25 CONTROL "disable",DS_DISABLE_KEEPALIVE,"Button",BS_AUTOCHECKBOX | WS_GROUP, KEEPALIVE_X+5,KEEPALIVE_Y,50,10 LTEXT "idle time",IDC_STATIC,KEEPALIVE_X+62,KEEPALIVE_Y,25,10,NOT WS_GROUP EDITTEXT DS_KEEPALIVETIME,KEEPALIVE_X+90,KEEPALIVE_Y,20,10, ES_AUTOHSCROLL | WS_TABSTOP LTEXT "interval",IDC_STATIC,KEEPALIVE_X+117,KEEPALIVE_Y,25,10,NOT WS_GROUP EDITTEXT DS_KEEPALIVEINTERVAL,KEEPALIVE_X+145,KEEPALIVE_Y,30,10, ES_AUTOHSCROLL | WS_TABSTOP DEFPUSHBUTTON "OK",IDOK,5,ENDLINE_Y,50,14,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,81,ENDLINE_Y,50,14 PUSHBUTTON "Apply",IDAPPLY,156,ENDLINE_Y,50,14 GROUPBOX "Level of rollback on errors",IDC_STATIC,172,126,134,25 CONTROL "Nop",DS_NO_ROLLBACK,"Button",BS_AUTORADIOBUTTON | WS_GROUP,176,138,36,9 CONTROL "Transaction",DS_TRANSACTION_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,206,138,57,9 CONTROL "Statement",DS_STATEMENT_ROLLBACK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,257,138,47,9 END #undef DTC_GRP_X #undef DTC_GRP_Y #undef DTC_GRP_WIDTH #undef DTC_GRP_HEIGHT #undef DTC_OPT_X #undef DTC_OPT_Y #undef DTC_OPT_WIDTH #undef DTC_OPT_HEIGHT #undef DTC_LOG_X #undef DTC_LOG_Y #undef LIBPQOPT_Y #define DTC_GRP_X 10 #define DTC_GRP_Y 60 #define DTC_GRP_WIDTH 200 #define DTC_GRP_HEIGHT 100 #define DTC_OPT_X (DTC_GRP_X) #define DTC_OPT_Y (DTC_GRP_Y+10) #define DTC_OPT_WIDTH 180 #define DTC_OPT_HEIGHT 45 #define DTC_LOG_X (DTC_GRP_X) #define DTC_LOG_Y (DTC_OPT_Y+60) #define LIBPQOPT_Y 185 DLG_OPTIONS_DS3 DIALOG DISCARDABLE 0, 0, 306, 243 STYLE DS_MODALFRAME | DS_3DLOOK | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Adavanced Options(Datasource 3)" FONT 8, "MS Sans Serif" BEGIN PUSHBUTTON "Page 2",ID2NDPAGE,49,5,40,15 PUSHBUTTON "Page 1",ID1STPAGE,5,5,40,15 GROUPBOX "Distributed Transaction related settings",IDC_STATIC,DTC_GRP_X,DTC_GRP_Y,DTC_GRP_WIDTH,DTC_GRP_HEIGHT GROUPBOX "Allow connections unrecoverable by MSDTC?",IDC_STATIC,DTC_OPT_X,DTC_OPT_Y,DTC_OPT_WIDTH,DTC_OPT_HEIGHT CONTROL "yes",DS_DTC_LINK_ONLY,"Button",BS_AUTORADIOBUTTON | WS_GROUP,DTC_OPT_X+5,DTC_OPT_Y+10,40,10 CONTROL "rejects sslmode verify-[ca|full]",DS_DTC_SIMPLE_PRECHECK,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,DTC_OPT_X+5,DTC_OPT_Y+20,120,10 CONTROL "no (confirm the connectivity from MSDTC first)",DS_DTC_CONFIRM_RM_CONNECTION,"Button", BS_AUTORADIOBUTTON | WS_TABSTOP,DTC_OPT_X+5,DTC_OPT_Y+30,170,10 PUSHBUTTON "connection test",IDC_TEST,DTC_OPT_X+60,DTC_OPT_Y+75,55,14 LTEXT "libpq parameters:(&l)",IDC_STATIC,13,LIBPQOPT_Y+3,69,10,NOT WS_GROUP EDITTEXT DS_LIBPQOPT,85,LIBPQOPT_Y,215,27,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN | NOT WS_TABSTOP DEFPUSHBUTTON "OK",IDOK,5,224,50,14,WS_GROUP PUSHBUTTON "Cancel",IDCANCEL,66,224,50,14 PUSHBUTTON "Apply",IDAPPLY,128,224,50,14 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 "Save",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/3" IDS_ADVANCE_OPTION_CON1 "Advanced Options (Connection 1/3)" IDS_ADVANCE_OPTION_DSN2 "Advanced Options (%s) 2/3" IDS_ADVANCE_OPTION_DSN3 "Advanced Options (%s) 3/3" IDS_ADVANCE_OPTION_CON2 "Advanced Options (Connection 2/3)" IDS_ADVANCE_OPTION_CON3 "Advanced Options (Connection 3/3)" 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 P psqlodbc-13.02.0000/win64.mak000644 001751 001751 00000022100 14122574536 016527 0ustar00hiroshihiroshi000000 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 # # Include default configuration options, followed by any local overrides !INCLUDE windows-defaults.mak !IF EXISTS(windows-local.mak) !INCLUDE windows-local.mak !ENDIF !IF "$(ANSI_VERSION)" == "yes" !MESSAGE Building the PostgreSQL ANSI 3.0 Driver for $(TARGET_CPU)... !ELSE !MESSAGE Building the PostgreSQL Unicode 3.5 Driver for $(TARGET_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" ($(TARGET_CPU) Release DLL) !MESSAGE "Debug" ($(TARGET_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 /W3 /wd4018 /EHsc !IF "$(CFG)" == "Release" CUSTOMCLOPT=$(CUSTOMCLOPT) /MD !ELSE CUSTOMCLOPT=$(CUSTOMCLOPT) /MDd !ENDIF !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= # Print the paths that will be used in the build !MESSAGE Using PostgreSQL Include directory: $(PG_INC) !MESSAGE Using PostgreSQL Library directory: $(PG_LIB) !IF "$(ANSI_VERSION)" == "yes" DTCLIB = pgenlista !ELSE DTCLIB = pgenlist !ENDIF DTCDLL = $(DTCLIB).dll !IF "$(TARGET_CPU)" == "x64" ADD_DEFINES=$(ADD_DEFINES) /D _WIN64 !ENDIF !IF "$(MSDTC)" != "no" VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /DelayLoad:$(DTCDLL) !ENDIF VC07_DELAY_LOAD=$(VC07_DELAY_LOAD) /DELAY:UNLOAD 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 "$(ANSI_VERSION)" == "yes" ADD_DEFINES = $(ADD_DEFINES) /D "DBMS_NAME=\"PostgreSQL ANSI($(TARGET_CPU))\"" !ELSE ADD_DEFINES = $(ADD_DEFINES) /D "DBMS_NAME=\"PostgreSQL Unicode($(TARGET_CPU))\"" /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)" /I "$(PG_INC)\internal" !ENDIF !IF "$(ADD_INC)" != "" INC_OPT = $(INC_OPT) /I "$(ADD_INC)" !ENDIF !IF "$(ANSI_VERSION)" == "yes" MAINLIB = psqlodbc30a !ELSE MAINLIB = psqlodbc35w !ENDIF MAINDLL = $(MAINLIB).dll XALIB = pgxalib XADLL = $(XALIB).dll # Construct output directory name. The name consists of three parts, # target CPU, ANSI/Unicode, and Debug/Release. For example,the output # directory debug-enabled 32-bit ANSI-version is: # # .\x86_ANSI_Debug # OUTDIR=.\$(TARGET_CPU) !IF "$(ANSI_VERSION)" == "yes" OUTDIR=$(OUTDIR)_ANSI !ELSE OUTDIR=$(OUTDIR)_Unicode !ENDIF !IF "$(CFG)" == "Debug" OUTDIR=$(OUTDIR)_Debug !ELSE OUTDIR=$(OUTDIR)_Release !ENDIF # Location for intermediary build targets (e.g. *.obj files). INTDIR=$(OUTDIR) 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 "$(INTDIR)\*.dll" -@erase "$(INTDIR)\*.pdb" "$(INTDIR)" : !IF !EXISTS($(INTDIR)) mkdir "$(INTDIR)" !ENDIF !IF !EXISTS($(OUTDIR)) && "$(OUTDIR)" != "$(INTDIR)" mkdir "$(OUTDIR)" !ENDIF !IF "$(MSDTC)" != "no" "$(OUTDIR)\$(MAINDLL)": "$(OUTDIR)\$(DTCLIB).lib" !ENDIF CPP=cl.exe CPP_PROJ=$(CUSTOMCLOPT) $(INC_OPT) /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "_CRT_SECURE_NO_DEPRECATE" /D "WIN_MULTITHREAD_SUPPORT" $(ADD_DEFINES) /Fp"$(INTDIR)\psqlodbc.pch" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD !IF "$(CFG)" == "Release" CPP_PROJ=$(CPP_PROJ) /O2 !ELSEIF "$(CFG)" == "Debug" CPP_PROJ=$(CPP_PROJ) /Gm /ZI /Od /D "_DEBUG" /RTC1 !ENDIF .c{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .cpp{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << .cxx{$(INTDIR)}.obj:: $(CPP) @<< $(CPP_PROJ) /c $< << RSC=rc.exe RSC_PROJ=/l 0x809 /fo"$(INTDIR)\psqlodbc.res" !IF "$(CFG)" == "Debug" RSC_PROJ=$(RSC_PROJ) /d "_DEBUG" !ENDIF LINK32=link.exe LIB32=lib.exe LINK32_FLAGS=libpq.lib kernel32.lib user32.lib gdi32.lib advapi32.lib odbc32.lib odbccp32.lib wsock32.lib ws2_32.lib secur32.lib XOleHlp.lib winmm.lib msvcrt.lib $(CUSTOMLINKLIBS) /nologo /dll /def:"$(DEF_FILE)" !IF "$(MSDTC)" != "no" LINK32_FLAGS=$(LINK32_FLAGS) "$(OUTDIR)\$(DTCLIB).lib" !ENDIF !IF "$(ANSI_VERSION)" == "yes" DEF_FILE= "psqlodbca.def" !ELSE DEF_FILE= "psqlodbc.def" !ENDIF !IF "$(CFG)" == "Release" LINK32_FLAGS=$(LINK32_FLAGS) !ELSE LINK32_FLAGS=$(LINK32_FLAGS) /debug /pdbtype:sept !ENDIF LINK32_FLAGS=$(LINK32_FLAGS) $(VC07_DELAY_LOAD) !IF "$(PG_LIB)" != "" LINK32_FLAGS=$(LINK32_FLAGS) /libpath:"$(PG_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)\lobj.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" \ "$(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 /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 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 /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) @<< $(LIB32_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) $(RSC_DEFINES) $(SOURCE) #### # Umbrella targets, for building the driver in multiple configurations unicode-driver: $(MAKE) -f win64.mak ANSI_VERSION=no ansi-driver: $(MAKE) -f win64.mak ANSI_VERSION=yes installer: unicode-driver ansi-driver cd installer && $(MAKE) -f installer.mak CFG=$(CFG) # world target builds both 32-bit and 64-bit installers in one command. # # The "setenv" command, from Microsoft SDK, is used to switch the build # target. However, it only changes the environment for the current shell; # it is reset for the next command. So we cannot just call "setenv /x64" # here one one line and nmake one the next one. I also tried creating a .bat # file with the commands, but setenv contains a "EXIT /B" which stops the # script from executing. But we can launch a new cmd.exe and pass the # commands to it in stdin. world: cmd < << setenv /x64 $(MAKE) -f win64.mak installer CFG=$(CFG) setenv /x86 $(MAKE) -f win64.mak installer CFG=$(CFG) << clean-world: -rd /Q /S x64_ANSI_Release x64_ANSI_Debug -rd /Q /S x64_Unicode_Release x64_Unicode_Debug -rd /Q /S x86_ANSI_Release x86_ANSI_Debug -rd /Q /S x86_Unicode_Release x86_Unicode_Debug cd installer && $(MAKE) /f installer.mak CFG=$(CFG) clean psqlodbc-13.02.0000/psqlodbc.reg000644 001751 001751 00000001234 14122574536 017401 0ustar00hiroshihiroshi000000 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-13.02.0000/psqlodbc.dsp000644 001751 001751 00000020327 14122574536 017416 0ustar00hiroshihiroshi000000 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 "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /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" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /D "DRIVER_CURSOR_IMPLEMENT" /D "WIN_MULTITHREAD_SUPPORT" /D "DYNAMIC_LOAD" /D "MULTIBYTE" /D "UNICODE_SUPPORT" /Fp"psqlodbc.pch" /YX /FD" /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 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" # 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 "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /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" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "PSQLODBC_EXPORTS" /D "DRIVER_CURSOR_IMPLEMENT" /D "WIN_MULTITHREAD_SUPPORT" /D "DYNAMIC_LOAD" /D "MULTIBYTE" /D "UNICODE_SUPPORT" /FR /YX /FD /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 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" # 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=.\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=statement.c # End Source File # Begin Source File SOURCE=tuple.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=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-13.02.0000/psqlodbc.vcproj000644 001751 001751 00000055071 14122574536 020137 0ustar00hiroshihiroshi000000 000000 psqlodbc-13.02.0000/psqlodbc.sln000644 001751 001751 00000001560 14122574536 017422 0ustar00hiroshihiroshi000000 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-13.02.0000/msdtc_enlist.cpp000644 001751 001751 00000077422 14122574536 020303 0ustar00hiroshihiroshi000000 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" #define _PGENLIST_FUNCS_IMPLEMENT_ #include "pgenlist.h" #include "xalibname.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; case DLL_PROCESS_DETACH: mylog("DETACHING pgenlist\n"); 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; #define LIFELOCK_ACQUIRE EnterCriticalSection(&init_crit.life_cs) #define LIFELOCK_RELEASE LeaveCriticalSection(&init_crit.life_cs) /* * 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(); void SLOCK_ACQUIRE() {EnterCriticalSection(&as_spin);} void SLOCK_RELEASE() {LeaveCriticalSection(&as_spin);} void ELOCK_ACQUIRE() {EnterCriticalSection(&as_exec);} void ELOCK_RELEASE() {LeaveCriticalSection(&as_exec);} 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) { mylog("%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) { const int refcnt_copy = refcnt; mylog("delete %p\n", this); delete this; return refcnt_copy; } 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; } 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) { mylog("%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"; static int regkeyCheck(const char *xalibname, const char *xalibpath) { int retcode = 0; LONG ret; HKEY sKey; DWORD rSize; ret = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, regKey, 0, KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_64KEY, &sKey); switch (ret) { case ERROR_SUCCESS: break; case ERROR_FILE_NOT_FOUND: ret = ::RegCreateKeyEx(HKEY_LOCAL_MACHINE, regKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &sKey, NULL); mylog("%s:CreateKeyEx ret=%d\n", __FUNCTION__, ret); break; default: mylog("%s:OpenKeyEx ret=%d\n", __FUNCTION__, ret); } if (ERROR_SUCCESS != ret) return -1; else { char keyval[1024]; rSize = sizeof(keyval); switch (ret = ::RegQueryValueEx(sKey, xalibname, NULL, NULL, (LPBYTE) keyval, &rSize)) { case ERROR_SUCCESS: if (rSize > 0) { if (0 == _stricmp(keyval, xalibpath)) break; mylog("%s:XADLL value %s is different from %s\n", __FUNCTION__, keyval, xalibpath); if (IsWow64()) { mylog("%s:avoid RegSetValue operation from wow64 process\n", __FUNCTION__); break; } } case ERROR_FILE_NOT_FOUND: mylog("%s:Setting value %s\n", __FUNCTION__, xalibpath); ret = ::RegSetValueEx(sKey, xalibname, 0, REG_SZ, (CONST BYTE *) xalibpath, (DWORD) strlen(xalibpath) + 1); if (ERROR_SUCCESS == ret) retcode = 1; else { retcode = -1; mylog("%s:SetValuEx ret=%d\n", __FUNCTION__, ret); } break; default: retcode = -1; mylog("%s:QueryValuEx ret=%d\n", __FUNCTION__, ret); break; } ::RegCloseKey(sKey); } return retcode; } RETCODE static EnlistInDtc_1pipe(void *conn, ITransaction *pTra, ITransactionDispenser *pDtc, int method) { CSTR func = "EnlistInDtc_1pipe"; static IDtcToXaHelperSinglePipe *pHelper = NULL; ITransactionResourceAsync *pRes = NULL; IAsyncPG *asdum; HRESULT res; DWORD dwRMCookie; XID xid; const char *xalibname = GetXaLibName(); const char *xalibpath = GetXaLibPath(); int recovLvl; char errmsg[256]; char reason[128]; if (!pHelper) { res = pDtc->QueryInterface(IID_IDtcToXaHelperSinglePipe, (void **) &pHelper); if (res != S_OK || !pHelper) { mylog("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; } recovLvl = PgDtc_is_recovery_available(conn, reason, sizeof(reason)); switch (method) { case DTC_CHECK_BEFORE_LINK: if (0 == recovLvl) { snprintf(errmsg, sizeof(errmsg), "%s is unavailable in distributed transactions", reason); PgDtc_set_error(conn, errmsg, func); return SQL_ERROR; } } /*mylog("dllname=%s dsn=%s\n", xalibname, conn->connInfo.dsn); res = 0;*/ char dtcname[1024]; PgDtc_create_connect_string(conn, dtcname, sizeof(dtcname)); bool confirmedRegkey = false, confirmingLink = false, xarmerr = false; char error_header[64]; while (true) { res = pHelper->XARMCreate(dtcname, (char *) xalibname, &dwRMCookie); mylog("XARMcreate error code=%x (%d %d)\n", res, confirmedRegkey, confirmingLink); xarmerr = true; if (!confirmingLink) snprintf(error_header, sizeof(error_header), "XARMcreate error code=%x", res); switch (res) { case S_OK: if (confirmingLink) { switch (recovLvl) { case 0: snprintf(errmsg, sizeof(errmsg), "%s:%s is currently unavailable in distributed transactions", error_header, reason); break; case -1: snprintf(errmsg, sizeof(errmsg), "%s:Possibly you connect to the database whose authentication method is %s or ident", error_header, reason); break; case 1: snprintf(errmsg, sizeof(errmsg), "%s:Are you trying to connect to the database whose authentication method is ident?", error_header); break; } } else xarmerr = false; break; case XACT_E_XA_TX_DISABLED: snprintf(errmsg, sizeof(errmsg), "%s:Please enable XA transaction in MSDTC security configuration", error_header); break; case XACT_E_TMNOTAVAILABLE: snprintf(errmsg, sizeof(errmsg), "%s:Please start Distributed Transaction Coordinator service", error_header); break; case E_FAIL: if (!confirmedRegkey) { int retcode = regkeyCheck(xalibname, xalibpath); confirmedRegkey = true; if (retcode > 0) continue; } switch (method) { case DTC_CHECK_RM_CONNECTION: if (!confirmingLink) { confirmingLink = true; strcat(dtcname, ";" KEYWORD_DTC_CHECK "=0"); continue; } default: snprintf(errmsg, sizeof(errmsg), "%s:Failed to link with DTC service. Please look at the log of Event Viewer etc.", error_header); } break; case XACT_E_CONNECTION_DOWN: snprintf(errmsg, sizeof(errmsg), "%s:Lost connection with DTC transaction manager\nMSDTC has some trouble?", error_header); break; default: snprintf(errmsg, sizeof(errmsg), "%s\n", error_header); break; } break; } if (xarmerr) { PgDtc_set_error(conn, errmsg, func); return SQL_ERROR; } 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; } static ITransactionDispenser *getITransactionDispenser(DWORD grfOptions, HRESULT *hres) { static ITransactionDispenser *pDtc = NULL; HRESULT res = S_OK; if (!pDtc) { res = DtcGetTransactionManagerEx(NULL, NULL, IID_ITransactionDispenser, grfOptions, NULL, (void **) &pDtc); if (FAILED(res)) { mylog("DtcGetTransactionManager error %x\n", res); pDtc = NULL; } } if (hres) *hres = res; return pDtc; } EXTERN_C void *GetTransactionObject(HRESULT *hres) { ITransaction *pTra = NULL; ITransactionDispenser *pDtc = NULL; if (pDtc = getITransactionDispenser(OLE_TM_FLAG_NONE, hres), NULL == pDtc) return pTra; HRESULT res = pDtc->BeginTransaction(NULL, ISOLATIONLEVEL_READCOMMITTED, 0, NULL, &pTra); switch (res) { case S_OK: break; default: pTra = NULL; } if (hres) *hres = res; return pTra; } EXTERN_C void ReleaseTransactionObject(void *pObj) { ITransaction *pTra = (ITransaction *) pObj; if (!pTra) return; pTra->Release(); } EXTERN_C RETCODE EnlistInDtc(void *conn, void *pTra, int method) { 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); } HRESULT hres; pDtc = getITransactionDispenser(OLE_TM_FLAG_NODEMANDSTART, &hres); if (!pDtc) { char errmsg[128]; snprintf(errmsg, sizeof(errmsg), "enlistment error:DtcGetTransactionManager error code=%x", hres); PgDtc_set_error(conn, errmsg, __FUNCTION__); return SQL_ERROR; } ret = EnlistInDtc_1pipe(conn, (ITransaction *) pTra, pDtc, method); 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-13.02.0000/pgxalib.cpp000644 001751 001751 00000044023 14122574536 017230 0ustar00hiroshihiroshi000000 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; string dsnstr; HDBC xaconn; vector qvec; int pos; bool immediateConnection; string sqlState; string errMsg; void parse_xa_info(); public: XAConnection(LPCTSTR str) : connstr(str), xaconn(NULL), pos(-1), immediateConnection(false) {parse_xa_info();} ~XAConnection(); void Reset(void); 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;} const string &GetDsnstr(void) {return dsnstr;} bool GetImmediateConnection(void) {return immediateConnection;} bool AuthenticationError(void) {return sqlState == "08001" && errMsg.find("could not connect") == std::string::npos;} }; 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"); leave(); } void leave() { if (cs_init) { mylog("leaving pgxadll\n"); xatab.clear(); FreeEnv(); if (LOGFP) fclose(LOGFP); LOGFP = NULL; DeleteCriticalSection(&mylog_cs); DeleteCriticalSection(&map_cs); cs_init = false; } } void finalize() { leave(); } void FreeEnv() { if (env) { mylog("Freeing env\n"); 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() { } void XAConnection::Reset() { qvec.clear(); if (xaconn) { mylog("about to Disconnect\n"); SQLDisconnect(xaconn); mylog("Freeing HANDLE_DBC\n"); 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_SUCCEEDED(ret)) { MLOCK_RELEASE; return NULL; } } MLOCK_RELEASE; if (xaconn) return 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_SUCCEEDED(ret)) return NULL; ret = SQLDriverConnect(xaconn, NULL, (SQLCHAR *) dsnstr.c_str(), SQL_NTS, NULL, SQL_NULL_DATA, NULL, SQL_DRIVER_COMPLETE); if (SQL_SUCCEEDED(ret)) return xaconn; SQLCHAR sqlstate[8], errmsg[256]; SQLGetDiagRec(SQL_HANDLE_DBC, xaconn, 1, sqlstate, NULL, errmsg, sizeof(errmsg), NULL); mylog("first SQLDriverConnect return=%d sqlstate=%s error=%s\n", ret, sqlstate, errmsg); sqlState = (char *) sqlstate; errMsg = (char *) errmsg; if (!AuthenticationError()) { SQLFreeHandle(SQL_HANDLE_DBC, xaconn); return NULL; } sqlState.empty(); errMsg.empty(); ret = SQLDriverConnect(xaconn, NULL, (SQLCHAR *) (dsnstr + ";Username=postgres;Password=postgres;sslmode=allow").c_str(), SQL_NTS, NULL, SQL_NULL_DATA, NULL, SQL_DRIVER_COMPLETE); if (SQL_SUCCEEDED(ret)) { mylog("second SQLDriverConnect success\n"); return xaconn; } SQLGetDiagRec(SQL_HANDLE_DBC, xaconn, 1, sqlstate, NULL, errmsg, sizeof(errmsg), NULL); mylog("second SQLDriverConnect return=%d sqlstate=%s error=%s\n", ret, sqlstate, errmsg); sqlState = (char *) sqlstate; errMsg = (char *) errmsg; return NULL; } #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 From MSDTC 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; } static bool bImmediateConnectDefault = false; #define CHAR_OPENING_BRACE '{' #define CHAR_CLOSING_BRACE '}' #define CHAR_SEMI_COLON ';' #define CHAR_EQUAL '=' #define STR_OPENING_BRACE "{" #define STR_CLOSING_BRACE "}" #define STR_SEMI_COLON ";" #define STR_EQUAL "=" #define KEYWORD_DTC_CHECK "dtchk" #define KEYWORD_DEBUG "debug" #define KEYWORD_ABDEBUG "B2" void XAConnection::parse_xa_info() { const char *cstr, *pstr, *pnstr; char keyword[64], value[64]; bool keyhasbr, valhasbr; int debugv = -1; cstr = connstr.c_str(); immediateConnection = bImmediateConnectDefault; GetMsdtclog(); for (pstr = cstr; *pstr;) { keyhasbr = valhasbr = false; if (CHAR_OPENING_BRACE == *pstr) { keyhasbr = true; if (pnstr = strchr(pstr, (int) CHAR_CLOSING_BRACE), NULL != pnstr) strncpy_s(keyword, sizeof(keyword), pstr + 1, pnstr - pstr - 1); else break; pstr = pnstr + 1; if (CHAR_EQUAL != *pstr) break; } else { if (pnstr = strchr(pstr, (int) CHAR_EQUAL), NULL != pnstr) strncpy_s(keyword, sizeof(keyword), pstr, pnstr - pstr); else break; pstr = pnstr; } pstr++; if (CHAR_OPENING_BRACE == *pstr) { valhasbr = true; if (pnstr = strchr(pstr, (int) CHAR_CLOSING_BRACE), NULL != pnstr) strncpy_s(value, sizeof(value), pstr + 1, pnstr - pstr - 1); else break; pstr = pnstr + 1; } else { if (pnstr = strchr(pstr, (int) CHAR_SEMI_COLON), NULL != pnstr) { strncpy_s(value, sizeof(value), pstr, pnstr - pstr); pstr = pnstr; } else { strcpy(value, pstr); pstr = strchr(pstr, '\0'); } } if (0 == _stricmp(keyword, KEYWORD_DTC_CHECK)) immediateConnection = (0 != atoi(value)); else if (0 == _stricmp(keyword, KEYWORD_DEBUG) || 0 == _stricmp(keyword, KEYWORD_ABDEBUG)) debugv = atoi(value); else { if (keyhasbr) dsnstr += STR_OPENING_BRACE; dsnstr += keyword; if (keyhasbr) dsnstr += STR_CLOSING_BRACE; dsnstr += STR_EQUAL; if (valhasbr) dsnstr += STR_OPENING_BRACE; dsnstr += value; if (valhasbr) dsnstr += STR_CLOSING_BRACE; dsnstr += STR_SEMI_COLON; } if (NULL == pstr || CHAR_SEMI_COLON != *pstr) break; pstr++; } if (0 != dtclog) { char dbgopt[16]; if (debugv <= 0) debugv = 1; _snprintf(dbgopt, sizeof(dbgopt), KEYWORD_ABDEBUG "=%d;", debugv); dsnstr += dbgopt; } } EXTERN_C static int __cdecl xa_open(char *xa_info, int rmid, long flags) { int xartn = XA_OK; bool bActivateConnection = bImmediateConnectDefault; mylog("xa_open %s rmid=%d flags=%ld\n", xa_info, rmid, flags); MLOCK_ACQUIRE; init_crit.xatab.insert(pair(rmid, XAConnection(xa_info))); MLOCK_RELEASE; map::iterator p; p = init_crit.xatab.find(rmid); if (p == init_crit.xatab.end()) xartn = XAER_RMERR; else if (p->second.GetImmediateConnection()) { mylog("xa_open calls ActivateConnection %s\n", p->second.GetDsnstr().c_str()); if (p->second.ActivateConnection()) xartn = XA_OK; else xartn = XAER_RMERR; } mylog("xa_open %s rmid=%d returning %d\n", xa_info, rmid, xartn); return xartn; } EXTERN_C static int __cdecl xa_close(char *xa_info, int rmid, long flags) { mylog("xa_close rmid=%d flags=%ld\n", rmid, flags); map::iterator p; MLOCK_ACQUIRE; p = init_crit.xatab.find(rmid); if (p != init_crit.xatab.end()) p->second.Reset(); 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) { if (p->second.AuthenticationError()) rmcode = 0; mylog("%s returns %d\n", __FUNCTION__, rmcode); 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-13.02.0000/xalibname.c000644 001751 001751 00000004133 14122574536 017200 0ustar00hiroshihiroshi000000 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] = ""; static const char * const PGMFILES = "Program Files"; static const char * const PGMFILESX86 = "Program Files (x86)"; typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process; BOOL IsWow64() { static BOOL bCalled = FALSE; static BOOL bIsWow64 = FALSE; if (bCalled) return bIsWow64; fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress( GetModuleHandle("kernel32"), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) { //handle error } } bCalled = TRUE; return bIsWow64; } const char *GetXaLibName(void) { char dllpath[_MAX_PATH], drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; if (!xalibpath[0]) { size_t pgmflen = strlen(PGMFILESX86); char *ptr; 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); strncpy(xalibname, "pgxalib.dll", sizeof(xalibname)); if (IsWow64()) { if ('\\' == *dir && 0 == _strnicmp(dir + 1, PGMFILESX86, pgmflen)) { ptr = dir + 1 + pgmflen; if ('\\' == *ptr) _snprintf(xalibpath, sizeof(xalibpath), "%s\\%s%s%s", drive, PGMFILES, ptr, xalibname); } } else _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-13.02.0000/pgxalib.def000644 001751 001751 00000000133 14122574536 017176 0ustar00hiroshihiroshi000000 000000 LIBRARY pgxalib EXPORTS DllMain @201 GetXaSwitch @203 GetMsdtclog @204 SetMsdtclog @205 psqlodbc-13.02.0000/psqlsetup.def000644 001751 001751 00000002352 14122574536 017615 0ustar00hiroshihiroshi000000 000000 LIBRARY psqlsetup EXPORTS DllMain @201 ConfigDSN @202 ConfigDriver @203 SQLBindCol @4 SQLCancel @5 SQLDisconnect @9 SQLExecute @12 SQLFetch @13 SQLFreeStmt @16 SQLNumResultCols @18 SQLRowCount @20 SQLGetData @43 SQLGetFunctions @44 SQLParamData @48 SQLPutData @49 SQLDescribeParam @58 SQLExtendedFetch @59 SQLMoreResults @61 SQLNumParams @63 SQLSetPos @68 SQLBindParameter @72 SQLAllocHandle @80 SQLBindParam @81 SQLCloseCursor @82 SQLCopyDesc @84 SQLEndTran @85 SQLFetchScroll @86 SQLFreeHandle @87 SQLGetEnvAttr @92 SQLSetEnvAttr @98 SQLBulkOperations @100 SQLDummyOrdinal @199 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 SQLGetDescFieldW @130 SQLGetDescRecW @131 SQLSetDescRecW @132 psqlodbc-13.02.0000/psqlsetupa.def000644 001751 001751 00000002230 14122574536 017751 0ustar00hiroshihiroshi000000 000000 LIBRARY psqlsetupa EXPORTS DllMain @201 ConfigDSN @202 ConfigDriver @203 SQLBindCol @4 SQLCancel @5 SQLConnect @7 SQLDescribeCol @8 SQLDisconnect @9 SQLExecDirect @11 SQLExecute @12 SQLFetch @13 SQLFreeStmt @16 SQLGetCursorName @17 SQLNumResultCols @18 SQLPrepare @19 SQLRowCount @20 SQLSetCursorName @21 SQLColumns @40 SQLDriverConnect @41 SQLGetData @43 SQLGetFunctions @44 SQLGetInfo @45 SQLGetTypeInfo @47 SQLParamData @48 SQLPutData @49 SQLSpecialColumns @52 SQLStatistics @53 SQLTables @54 SQLColumnPrivileges @56 SQLDescribeParam @58 SQLExtendedFetch @59 SQLForeignKeys @60 SQLMoreResults @61 SQLNativeSql @62 SQLNumParams @63 SQLPrimaryKeys @65 SQLProcedureColumns @66 SQLProcedures @67 SQLSetPos @68 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 psqlodbc-13.02.0000/odbc.sql000644 001751 001751 00000014502 14122574536 016525 0ustar00hiroshihiroshi000000 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-13.02.0000/odbc-drop.sql000644 001751 001751 00000002317 14122574536 017470 0ustar00hiroshihiroshi000000 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-13.02.0000/winbuild/BuildAll.ps1000644 001751 001751 00000014440 14122574536 021030 0ustar00hiroshihiroshi000000 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), "Win32" or "x64" is available. .PARAMETER AlongWithInstallers Specify when you'd like to build installers after building drivers. .PARAMETER Toolset MSBuild PlatformToolset is determined automatically unless this option is specified. Currently "v90", "v100", "Windows7.1SDK", "v110", "v110_xp", "v120", "v120_xp", "v140" , "v140_xp", "v141", "v141_xp" or "v142" is available. .PARAMETER MSToolsVersion This option is deprecated. MSBuild ToolsVersion is detemrined automatically unless this option is specified. Currently "4.0", "12.0" or "14.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. .EXAMPLE > .\BuildAll -A(longWithInstallers) Build installers as well after building drivers. .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", "14.0")] [string]$MSToolsVersion, [ValidateSet("Debug", "Release")] [String]$Configuration="Release", [string]$BuildConfigPath, [switch]$AlongWithInstallers ) function buildPlatform([xml]$configInfo, [string]$Platform) { if ($Platform -ieq "x64") { $platinfo=$configInfo.Configuration.x64 } else { $platinfo=$configInfo.Configuration.x86 } $BUILD_MACROS=$platinfo.build_macros $PG_INC=getPGDir $configInfo $Platform "include" $PG_LIB=getPGDir $configInfo $Platform "lib" $PG_BIN=getPGDir $configInfo $Platform "bin" Write-Host "USE LIBPQ : ($PG_INC $PG_LIB $PG_BIN)" if (-not (Test-Path $PG_INC)) { throw("`n!!!! include directory $PG_INC does not exist`nplease specify the correct folder name using editConfiguration") } if (-not (Test-Path $PG_LIB)) { throw("`n!!!! lib directory $PG_LIB does not exist`nplease specify the correct folder name using editConfiguration") } if (-not (Test-Path $PG_BIN)) { throw("`n!!!! bin directory $PG_BIN does not exist`nplease specify the correct folder name using editConfiguration") } $useSplit=$true if ($useSplit) { $macroList = -split $BUILD_MACROS } else { $BUILD_MACROS = $BUILD_MACROS -replace ';', '`;' $BUILD_MACROS = $BUILD_MACROS -replace '"', '`"' $macroList = iex "write-output $BUILD_MACROS" } & ${msbuildexe} ./platformbuild.vcxproj /tv:$MSToolsV "/p:Platform=$Platform;Configuration=$Configuration;PlatformToolset=${Toolset}" /t:$target /p:VisualStudioVersion=${VCVersion} /p:DRIVERVERSION=$DRIVERVERSION /p:PG_INC=$PG_INC /p:PG_LIB=$PG_LIB /p:PG_BIN=$PG_BIN $macroList } $scriptPath = (Split-Path $MyInvocation.MyCommand.Path) Import-Module ${scriptPath}\Psqlodbc-config.psm1 $configInfo = LoadConfiguration $BuildConfigPath $scriptPath $DRIVERVERSION=$configInfo.Configuration.version pushd $scriptPath $path_save = ${env:PATH} Import-Module ${scriptPath}\MSProgram-Get.psm1 try { $rtnArray=Find-MSBuild ([ref]$VCVersion) ($MSToolsVersion) ([ref]$Toolset) $configInfo $msbuildexe=$rtnArray[0] $MSToolsV=$rtnArray[1] } catch [Exception] { if ("$_.Exception.Message" -ne "") { Write-Host $_.Exception.Message -ForegroundColor Red } else { echo $_.Exception | Format-List -Force } popd Remove-Module Psqlodbc-config return } finally { Remove-Module MSProgram-Get } $recordResult = $true if ($Target -ne "info") { $configInfo.Configuration.BuildResult.Date="" $configInfo.Configuration.BuildResult.VisualStudioVersion="" $configInfo.Configuration.BuildResult.PlatformToolset="" $configInfo.Configuration.BuildResult.ToolsVersion="" $configInfo.Configuration.BuildResult.Platform="" } try { # # build 32bit dlls # if ($Platform -ieq "Win32" -or $Platform -ieq "both") { buildPlatform $configInfo "Win32" if ($LastExitCode -ne 0) { $recordResult = $false } } # # build 64bit dlls # if ($recordResult -and ($Platform -ieq "x64" -or $Platform -ieq "both")) { buildPlatform $configInfo "x64" if ($LastExitCode -ne 0) { $recordResult = $false } } # # Write the result to configuration xml # $resultText="successful" if ($recordResult) { if ($Target -ne "Clean") { $configInfo.Configuration.BuildResult.Date=[string](Get-Date) $configInfo.Configuration.BuildResult.VisualStudioVersion=$VCVersion $configInfo.Configuration.BuildResult.PlatformToolset=$Toolset $configInfo.Configuration.BuildResult.ToolsVersion=$MSToolsV $configInfo.Configuration.BuildResult.Platform=$Platform } } else { $resultText="failed" } SaveConfiguration $configInfo Write-Host "VisualStudioVersion=$VCVersion(ToolsVersion=$MSToolsV) PlatformToolset=$Toolset Platform=$Platform $resultText`n" # # build installers as well # if ($AlongWithInstallers) { if (-not $recordResult) { throw("compilation failed") } $cpu = $Platform if ($Platform -eq "win32") { $cpu = "x86" } ..\installer\buildInstallers.ps1 -cpu $cpu -BuildConfigPath $BuildConfigPath if ($LASTEXITCODE -ne 0) { throw "Failed to build installers" } } } catch [Exception] { if ("$_.Exception.Message" -ne "") { Write-Host $_.Exception.Message -ForegroundColor Red } else { echo $_.Exception | Format-List -Force } } finally { $env:PATH = $path_save popd Remove-Module Psqlodbc-config } psqlodbc-13.02.0000/winbuild/platformbuild.vcxproj000644 001751 001751 00000011577 14122574536 023204 0ustar00hiroshihiroshi000000 000000 true false Release ..\ ANSI_VERSION=yes ANSI_VERSION=yes ANSI_VERSION=yes psqlodbc-13.02.0000/winbuild/MSProgram-Get.psm1000644 001751 001751 00000026172 14122574536 022106 0ustar00hiroshihiroshi000000 000000 function Find-MSBuild { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [ref]$VCVersion, [Parameter(Mandatory=$true)] $MSToolsVersion, [Parameter(Mandatory=$true)] [ref]$Toolset, [Parameter(Mandatory=$true)] [xml]$configInfo) $msbuildexe="" $VisualStudioVersion=$VCVersion.Value $Toolsetv=$Toolset.Value $WSDK71Set="Windows7.1SDK" Write-Debug "VCVersion=$VCVersionv $env:VisualStudioVersion" [int]$toolsnum=0 # # Determine VisualStudioVersion # if (("$VisualStudioVersion" -eq "") -And ($configInfo -ne $null)) { $VisualStudioVersion=$configInfo.Configuration.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] } } } $refnum="" # neither C++ nor SDK prompt if ("$VisualStudioVersion" -eq "") { if ((Find-VSDir 15) -ne "") { # VC15 is installed (current official) $VisualStudioVersion = "15.0" } elseif ((Find-VSDir 16) -ne "") { # VC16 is installed $VisualStudioVersion = "16.0" } elseif ("${env:VS140COMNTOOLS}" -ne "") { # VC14 is installed $VisualStudioVersion = "14.0" } elseif ("${env:VS120COMNTOOLS}" -ne "") { # VC12 is installed $VisualStudioVersion = "12.0" } elseif ("${env:VS100COMNTOOLS}" -ne "") { # VC10 is installed $VisualStudioVersion = "10.0" } elseif ("${env:VS110COMNTOOLS}" -ne "") { # VC11 is installed $VisualStudioVersion = "11.0" } else { throw "Visual Studio >= 10.0 not found" } } if ([int]::TryParse($VisualStudioVersion, [ref]$refnum)) { $VisualStudioVersion="${refnum}.0" } # Check VisualStudioVersion and prepare for ToolsVersion switch ($VisualStudioVersion) { "10.0" { $toolsout = 4 } "11.0" { $toolsout = 4 } "12.0" { $toolsout = 12 } "14.0" { $toolsout = 14 } "15.0" { $toolsout = 15 } "16.0" { $toolsout = 16 } default { throw "Selected Visual Stuidio is Version ${VisualStudioVersion}. Please use VC10 or later"} } # # Determine ToolsVersion # [int]$toolsnum=$toolsout if ("$MSToolsVersion" -eq "") { $MSToolsVersion=$env:ToolsVersion } if ("$MSToolsVersion" -ne "") { if ([int]::TryParse($MSToolsVersion, [ref]$refnum)) { $toolsout=[int]$refnum } } if ($toolsnum -lt 12) { $toolsnum=$toolsout } # # Determine MSBuild executable # Write-Debug "ToolsVersion=$MSToolsVersion VisualStudioVersion=$VisualStudioVersion" try { $msbver = msbuild.exe /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 "") { if ($toolsnum -gt 14) { # VC15 ~ VC16 $msbuildexe = msbfind_15_xx $toolsnum } else { # VC10 ~ VC14 $msbuildexe = msbfind_10_14 "${toolsnum}.0" if ($toolsnum -eq 4) { if ((Find-VSDir $VisualStudioVersion) -eq "") { throw "MSBuild ${toolsnum}.0 found but VisualStudioVersion $VisualStudioVersion not Found" } } } if ("$msbuildexe" -eq "") { throw "MSBuild ToolsVersion ${toolsnum}.0 not Found" } } # # Determine PlatformToolset # if (("$Toolsetv" -eq "") -And ($configInfo -ne $null)) { $Toolsetv=$configInfo.Configuration.toolset } if ("$Toolsetv" -eq "") { $Toolsetv=$env:PlatformToolset } if ("$Toolsetv" -eq "") { switch ($VisualStudioVersion) { "10.0" { if (Test-path "HKLM:\Software\Microsoft\Microsoft SDKs\Windows\v7.1") { $Toolsetv=$WSDK71Set } else { $Toolsetv="v100" } } "11.0" {$Toolsetv="v110_xp"} "12.0" {$Toolsetv="v120_xp"} "14.0" {$Toolsetv="v140_xp"} "15.0" {$Toolsetv="v141_xp"} "16.0" {$Toolsetv="v142"} } } # avoid a bug of Windows7.1SDK PlatformToolset if ($Toolsetv -eq $WSDK71Set) { $env:TARGET_CPU="" } # $VCVersion.value=$VisualStudioVersion $Toolset.value=$Toolsetv if ("$MSToolsVersion" -eq "") { if ([int]$toolsout -gt 15) { $MSToolsVersion="Current" } else { $MSToolsVersion="${toolsout}.0" } } return $msbuildexe, $MSToolsVersion } # find msbuild.exe for VC10 ~ VC14 function msbfind_10_14 { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$toolsver) $msbindir="" $regKey="HKLM:\Software\Wow6432Node\Microsoft\MSBuild\ToolsVersions\${toolsver}" if (Test-Path -path $regkey) { $msbitem=Get-ItemProperty $regKey if ($msbitem -ne $null) { $msbindir=$msbitem.MSBuildToolsPath } } else { $regKey="HKLM:\Software\Microsoft\MSBuild\ToolsVersions\${toolsver}" if (Test-Path -path $regkey) { $msbitem=Get-ItemProperty $regKey if ($msbitem -ne $null) { $msbindir=$msbitem.MSBuildToolsPath } } else { return "" } } return "${msbindir}msbuild" } # find msbuild.exe for VC15 ~ VC16 function msbfind_15_xx { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$toolsver) # via vssetup module $vsdir = find_vs_installation $toolsver # vssetup module is unavailable return find_default_msbuild_path $toolsver $vsdir } $dumpbinexe = "" $addPath="" function Find-Dumpbin { [CmdletBinding()] Param([int]$CurMaxVC = 16) if ("$dumpbinexe" -ne "") { if ("$addPath" -ne "") { if (${env:PATH}.indexof($addPath) -lt 0) { $env:PATH = "${addPath};" + $env:PATH } } return $dumpbinexe } $addPath="" $vsdir="" try { $dum = dumpbin.exe /NOLOGO $dumpbinexe="dumpbin" } catch [Exception] { # $dumpbinexe="$env:DUMPBINEXE" if ($dumpbinexe -eq "") { $searching = $true for ($i = $CurMaxVc; $searching -and ($i -ge 14); $i--) # VC15 ~ VC16 { $vsdir = Find-VSDir $i if ("$vsdir" -ne "") { $lslist = @(Get-ChildItem "${vsdir}VC\Tools\MSVC\*\bin\HostX86\x86\dumpbin.exe" -ErrorAction SilentlyContinue) if ($lslist.Count -gt 0) { $dumpbinexe=$lslist[0].FullName $searching = $false break } } } for (; $searching -and ($i -ge 10); $i--) # VC10 ~ VC14 { $vsdir = Find-VSDir $i if ("$vsdir" -ne "") { $dumpbinexe="${vsdir}VC\bin\dumpbin.exe" if (Test-Path -Path $dumpbinexe) { $searching = $false break } } } if ($searching) { throw "dumpbin doesn't exist" } elseif ($i -eq 10) { $addPath = "${vsdir}Common7\ide" } } } Write-Host "Dumpbin=$dumpbinexe" Set-Variable -Name dumpbinexe -Value $dumpbinexe -Scope 1 Set-Variable -Name addPath -Value $addPath -Scope 1 if ("$addPath" -ne "") { if (${env:PATH}.indexof($addPath) -lt 0) { $env:PATH = "${addPath};" + $env:PATH } } return $dumpbinexe } function dumpbinRecurs { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$dllname, [Parameter(Mandatory=$true)] [string]$dllfolder, [array]$instarray) $tmem=& ${dumpbinexe} /imports "$dllfolder\${dllname}" | select-string -pattern "^\s*(\S*\.dll)" | foreach-object {$_.Matches.Groups[1].Value} | where-object {test-path ("${dllfolder}\" + $_)} if ($LASTEXITCODE -ne 0) { throw "Failed to dumpbin ${dllfolder}\${dllname}" } if ($tmem -eq $Null) { return $instarray } if ($tmem.GetType().Name -eq "String") { [String []]$tarray = @($tmem) } else { $tarray = $tmem } $iarray=@() for ($i=0; $i -lt $tarray.length; $i++) { if (-not($instarray -contains $tarray[$i])) { $iarray += $tarray[$i] } } if ($iarray.length -eq 0) { return $instarray } $instarray += $iarray for ($i=0; $i -lt $iarray.length; $i++) { $instarray=dumpbinRecurs $iarray[$i] $dllfolder $instarray } return $instarray } function Get-RelatedDlls { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$dllname, [Parameter(Mandatory=$true)] [string]$dllfolder) Find-Dumpbin | Out-Null $libpqmem=@() $libpqmem=dumpbinRecurs $dllname $dllfolder $libpqmem return $libpqmem } function env_vcversion_no() { $viver = $env:VisualStudioVersion if ("$viver" -ne "") { if ("$viver" -match "(\d+)\.0") { return [int]$matches[1] } } return 0 } function Find-VSDir { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$vcversion) [int]$vcversion_no = [int]$vcversion if ("${vcversion}" -match "^(\d+)") { $vcversion_no = $matches[1] } if ((env_vcversion_no) -eq $vcversion_no) { return $env:VSINSTALLDIR } if ($vcversion_no -gt 14) { # VC15 ~ VC16 return find_vsdir_15_xx ${vcversion_no} } else { # VC10 ~ VC14 $comntools = [environment]::getenvironmentvariable("VS${vcversion_no}0COMNTOOLS") if ("$comntools" -eq "") { return "" } return (Split-Path (Split-Path $comntools -Parent) -Parent) + "\" } } [bool]$vssetup_available = $true $vssetup = $null # find vs installation path for VC15 ~ VC16 function find_vs_installation { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$toolsver) $vsdir = "" # vssetup module is available? if ($vssetup_available -and ($vsseup -eq $null)) { try { $vssetup = @(Get-VssetupInstance) } catch [Exception] { $vssetup_available = $false } } $toolsnum = [int]$toolsver if ($vssetup -ne $null) { $lslist = @($vssetup | where-object { $_.InstallationVersion.Major -eq $toolsnum } | foreach-object { $_.InstallationPath }) if ($lslist.Count -gt 0) { $vsdir = $lslist[0] } } return $vsdir } $vsarray = @{VC15 = "2017"; VC16 = "2019"} # find VS dir for VC15 ~ VC16 function find_default_msbuild_path { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$toolsver, [string]$vsdir) if ($vsdir -eq "") { $toolsnum = [int]$toolsver if ($env:PROCESSOR_ARCHITECTURE -eq "x86") { $pgmfs = "$env:ProgramFiles" } else { $pgmfs = "${env:ProgramFiles(x86)}" } $vsverdir = $vsarray["VC$toolsnum"] $lslist = @(Get-ChildItem "$pgmfs\Microsoft Visual Studio\$vsverdir\*\MSBuild\*\Bin\MSBuild.exe" -ErrorAction SilentlyContinue) } else { $lslist = @(Get-ChildItem "$vsdir\MSBuild\*\Bin\MSBuild.exe" -ErrorAction SilentlyContinue) } if ($lslist.Count -gt 0) { return $lslist[0].FullName } return "" } # find VS dir for VC15 ~ VC16 function find_vsdir_15_xx { [CmdletBinding()] Param([Parameter(Mandatory=$true)] [string]$toolsver) # via vssetup module $vsdir = find_vs_installation $toolsver if ($vsdir -ne "") { return $vsdir } # vssetup module is unavailable $msbpath = find_default_msbuild_path $toolsver $vsdir if ($msbpath -ne "") { return (Split-Path (Split-Path (Split-Path (Split-Path $msbpath -Parent) -Parent) -Parent) -Parent) + "\" } return "" } Export-ModuleMember -function Find-MSBuild, Find-Dumpbin, Get-RelatedDlls, Find-VSDir psqlodbc-13.02.0000/winbuild/psqlodbc.Cpp.props000644 001751 001751 00000010150 14122574536 022322 0ustar00hiroshihiroshi000000 000000 Level3 4018 Level3 4018 $(ADD_DEFINES);POSTGRESDRIVERVERSION="$(DRIVERVERSION)" $(RSC_DEFINES);PG_DRVFILE_VERSION=$(DRIVERVERSION.substring(0, 2)),$(DRIVERVERSION.substring(3,2)),$(DRIVERVERSION.substring(6, 2)),$(DRIVERVERSION.substring(8, 2));POSTGRES_RESOURCE_VERSION=\"$(DRIVERVERSION)\" NotUsing $(WarnLvl) Disabled true $(DSpcWarn) Windows true $(srcPath)$(TargetName).def $(OutDir)$(TargetName)$(TargetExt) NotUsing $(WarnLvl) Disabled true $(DSpcWarn) Windows true $(srcPath)$(TargetName).def $(OutDir)$(TargetName)$(TargetExt) $(WarnLvl) NotUsing MaxSpeed true true true $(DSpcWarn) Windows true true true $(srcPath)$(TargetName).def $(OutDir)$(TargetName)$(TargetExt) $(WarnLvl) NotUsing MaxSpeed true true true $(DSpcWarn) Windows true true true $(srcPath)$(TargetName).def $(OutDir)$(TargetName)$(TargetExt) psqlodbc-13.02.0000/winbuild/Psqlodbc-config.psm1000644 001751 001751 00000012073 14122574536 022527 0ustar00hiroshihiroshi000000 000000 $configurationXmlPath="" $configurationTemplatePath="" function InitConfiguration([string]$savePath) { $configInfo = [xml](Get-Content $configurationTemplatePath) if ($env:PROCESSOR_ARCHITECTURE -ieq "x86") { $x64info = $configInfo.Configuration.x64 $x64info.libpq.include = "" $x64info.libpq.lib = "" $x64info.libpq.bin = "" } $configInfo.save($savePath) return $configInfo } function GetConfiguration([string]$loadPath) { $configInfo = [xml] (Get-Content $loadPath) set-variable -name xmlFormatVersion -value "0.4" -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 LoadConfiguration([string]$configPath, [string]$configDir) { Write-Debug "configPath=$configPath" set-variable -name configurationTemplatePath -scope 1 -value "$configDir\configuration_template.xml" if ("$configPath" -eq "") { if ("$env:PSQLODBC_WCONFIG" -eq "") { $configPath = "$configDir\configuration.xml" } else { $configPath = $env:PSQLODBC_WCONFIG } } set-variable -name configurationXmlPath -scope 1 -value $configPath if (!(Test-Path -path $configPath)) { return InitConFiguration $configPath } else { return GetConfiguration $configPath } } function SaveConfiguration([xml]$configInfo, [string]$savePath) { if ("$savePath" -eq "") { $savePath = $configurationXmlPath } $configInfo.save($savePath) } function 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 } } function getPGDir([xml]$configInfo, [string]$Platform, [string]$kind) { if ($Platform -ieq "x64") { $platinfo=$configInfo.Configuration.x64 } else { $platinfo=$configInfo.Configuration.x86 } $LIBPQVER=$platinfo.libpq.version if ($kind -eq "include") { $result=$platinfo.libpq.include } elseif ($kind -eq "lib") { $result=$platinfo.libpq.lib } else { $result=$platinfo.libpq.bin } if ($result -ne "default") { return $result } if ($Platform -ieq "x64") { if ($env:PROCESSOR_ARCHITECTURE -ieq "x86") { $pgmfs = $env:ProgramW6432 } else { $pgmfs = $env:ProgramFiles } } else { if ($env:PROCESSOR_ARCHITECTURE -ieq "x86") { $pgmfs = $env:ProgramFiles } else { $pgmfs = ${env:ProgramFiles(x86)} } } if ("$pgmfs" -eq "") { $result = $null } else { $lslist = $null $result = $null if (-not (Test-Path "$pgmfs\PostgreSQL")) { throw("default Postgres Directory not found`nPlease specify the directories other than default") } $lslist = @(Get-ChildItem "$pgmfs\PostgreSQL") if ($null -eq $lslist) { throw("default Postgres Directory not found") } else { [decimal]$vernum = 0 if ("$LIBPQVER" -eq "") { foreach ($l in $lslist) { $ver = [decimal]$l.Name if ($ver -gt $vernum) { $result = $l.FullName + "\$kind" $vernum = $ver } } } else { foreach ($l in $lslist) { if ($LIBPQVER -eq $l.Name) { $result = $l.FullName + "\$kind" break } } } } } return $result } function GetPackageVersion([xml]$configInfo, [string]$srcpath) { $version_no = $configInfo.Configuration.version if ("$version_no" -eq "") { pushd "$srcpath" $splitItem = Get-Content ".\version.h" | Where-Object {($_.IndexOf("#define") -ge 0) -and ($_.IndexOf("POSTGRESDRIVERVERSION") -ge 0) -and ($_.IndexOF("`"") -ge 0)} | ForEach-Object {$_.split("`"")} $version_no = $splitItem[1] popd } return $version_no } function GetObjbase([string] $stdDir, [string] $addPath = "") { if ("$env:PSQLODBC_OBJBASE" -eq "") { return $stdDir } else { if ("$addPath" -eq "") { return $env:PSQLODBC_OBJBASE } else { return $env:PSQLODBC_OBJBASE + "\" + $addPath } } } Export-ModuleMember -function LoadConfiguration, SaveConfiguration, unifyNodes, getPGDir, getPackageVersion, GetObjbase -variable LIBPQ_VERSION psqlodbc-13.02.0000/winbuild/psqlodbc.vcxproj000644 001751 001751 00000033732 14122574536 022144 0ustar00hiroshihiroshi000000 000000 Debug Win32 Debug x64 Release Win32 Release x64 {79F872B5-9FAF-43DF-B441-9C860EAE52CF} Win32Proj psqlodbc psqlodbc DynamicLibrary true v120_xp MultiByte DynamicLibrary true v120_xp MultiByte DynamicLibrary false v120_xp true MultiByte DynamicLibrary false v120_xp true MultiByte no yes no secur32.dll $(ADD_INC);$(PG_INC);$(PG_INC)/internal;$(PG_INC)/server;$(PG_INC)/server/port/win32 $(ADD_LIBPATH);$(PG_LIB) $(ADD_DEFINES) psqlodbc30a ANSI $(srcPath)psqlodbca.def pgenlista psqlodbc35w Unicode $(srcPath)psqlodbc.def pgenlist UNICODE_SUPPORT;UNICODE_SUPPORTXX UNICODE_SUPPORT x86 x64 $(srcPath) $(ObjbaseDir)$(TARGET_CPU)_$(TargetType)_$(Configuration)\ $(ObjbaseDir)$(TARGET_CPU)_$(TargetType)_$(Configuration)\ $(ADD_DEFINES);_HANDLE_ENLIST_IN_DTC_ $(DELAY_LOAD_DLLS);$(DTCDLL).dll false $(ADD_DEFINES);_MEMORY_DEBUG_ true true false false _CRT_SECURE_NO_DEPRECATE;$(ADD_DEFINES);DYNAMIC_LOAD;WIN_MULTITHREAD_SUPPORT;WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) $(ADD_INC);%(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(ADD_LIBPATH);$(OutDir);%(AdditionalLibraryDirectories) libpq.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;wsock32.lib;ws2_32.lib;secur32.lib;winmm.lib;%(AdditionalDependencies) $(MAINDEF) true lib /def:$(srcPath)$(DTCDLL).def /machine:x86 /out:"$(outDir)\$(DTCLDLL).lib" _CRT_SECURE_NO_DEPRECATE;$(ADD_DEFINES);DYNAMIC_LOAD;WIN_MULTITHREAD_SUPPORT;WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) $(ADD_INC);%(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(ADD_LIBPATH);$(OutDir);%(AdditionalLibraryDirectories) libpq.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;wsock32.lib;ws2_32.lib;secur32.lib;winmm.lib;%(AdditionalDependencies) $(MAINDEF) true lib /def:$(srcPath)$(DTCDLL).def /machine:x64 /out:"$(outDir)\$(DTCLDLL).lib" _CRT_SECURE_NO_DEPRECATE;$(ADD_DEFINES);DYNAMIC_LOAD;WIN_MULTITHREAD_SUPPORT;WIN32;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) $(ADD_INC);%(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(ADD_LIBPATH);$(OutDir);%(AdditionalLibraryDirectories) libpq.lib;winmm.lib;wsock32.lib;ws2_32.lib;secur32.lib;%(AdditionalDependencies) $(MAINDEF) true lib /def:$(srcPath)$(DTCDLL).def /machine:x86 /out:"$(outDir)\$(DTCDLL).lib" _CRT_SECURE_NO_DEPRECATE;$(ADD_DEFINES);DYNAMIC_LOAD;WIN_MULTITHREAD_SUPPORT;WIN32;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) $(ADD_INC);%(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(ADD_LIBPATH);$(OutDir);%(AdditionalLibraryDirectories) libpq.lib;winmm.lib;wsock32.lib;ws2_32.lib;secur32.lib;%(AdditionalDependencies) $(MAINDEF) true lib /def:$(srcPath)$(DTCDLL).def /machine:x64 /out:"$(outDir)\$(DTCDLL).lib" psqlodbc-13.02.0000/winbuild/configuration_template.xml000644 001751 001751 00000001535 14122574536 024200 0ustar00hiroshihiroshi000000 000000 default default default default default default psqlodbc-13.02.0000/winbuild/psqlsetup.vcxproj000644 001751 001751 00000032422 14122574536 022370 0ustar00hiroshihiroshi000000 000000 Debug Win32 Debug x64 Release Win32 Release x64 {DFD90C9A-E9BA-4CA3-812B-E820EE9A3F5B} Win32Proj psqlsetup true DynamicLibrary true v120_xp MultiByte DynamicLibrary true v120_xp MultiByte DynamicLibrary false v120_xp true MultiByte DynamicLibrary false v120_xp true MultiByte no psqlsetupa ANSI psqlodbc30a.lib psqlodbc30a.dll;pgenlista.dll psqlsetup Unicode psqlodbc35w.lib psqlodbc35w.dll;pgenlist.dll UNICODE_SUPPORT UNICODE_SUPPORT x86 x64 false $(srcPath) $(ObjbaseDir)$(TARGET_CPU)_$(TargetType)_$(Configuration)\psqlsetup\ $(ObjbaseDir)$(TARGET_CPU)_$(TargetType)_$(Configuration)\ true true false false $(ADD_DEFINES);PG_BIN="$(PG_BIN.Replace('\','\\'))" DYNAMIC_LOAD;_HANDLE_ENLIST_IN_DTC_;$(ADD_DEFINES);_CRT_SECURE_NO_DEPRECATE;WIN32;_DEBUG;_WINDOWS;_USRDLL;PSQLSETUP_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) MachineX86 $(srcPath)$(targetName).def true $(OutDir);%(AdditionalLibraryDirectories) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(CALL_LIB);winmm.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true DYNAMIC_LOAD;_HANDLE_ENLIST_IN_DTC_;WIN_MULTITHREAD_SUPPORT;$(ADD_DEFINES);_CRT_SECURE_NO_DEPRECATE;WIN32;_DEBUG;_WINDOWS;_USRDLL;PSQLSETUP_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) MachineX64 $(srcPath)$(targetName).def true $(OutDir);%(AdditionalLibraryDirectories) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(CALL_LIB);winmm.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true DYNAMIC_LOAD;_HANDLE_ENLIST_IN_DTC_;WIN_MULTITHREAD_SUPPORT;$(ADD_DEFINES);_CRT_SECURE_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;PSQLSETUP_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) MachineX86 $(srcPath)$(targetName).def true $(OutDir);%(AdditionalLibraryDirectories) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(CALL_LIB);winmm.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true DYNAMIC_LOAD;_HANDLE_ENLIST_IN_DTC_;WIN_MULTITHREAD_SUPPORT;$(ADD_DEFINES);_CRT_SECURE_NO_DEPRECATE;WIN32;NDEBUG;_WINDOWS;_USRDLL;PSQLSETUP_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories) $(RSC_DEFINES);%(PreprocessorDefinitions) MachineX64 $(srcPath)$(targetName).def true $(OutDir);%(AdditionalLibraryDirectories) $(DELAY_LOAD_DLLS);%(DelayLoadDLLs) $(CALL_LIB);winmm.lib;%(AdditionalDependencies) $(OutDir);%(AdditionalLibraryDirectories) true $(TargetName).exp;%(AdditionalDependencies) psqlodbc-13.02.0000/winbuild/editConfiguration.ps1000644 001751 001751 00000026025 14122574536 023017 0ustar00hiroshihiroshi000000 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 } <# configuration XAML with WPF #> Add-Type -AssemblyName presentationframework [xml]$XAML = @'