pax_global_header00006660000000000000000000000064122242177650014522gustar00rootroot0000000000000052 comment=d4687c8905f70d8e7ee784a0076f434d6b05085c ruby-pg-0.17.0/000077500000000000000000000000001222421776500131745ustar00rootroot00000000000000ruby-pg-0.17.0/.gemtest000066400000000000000000000000001222421776500146330ustar00rootroot00000000000000ruby-pg-0.17.0/.hg_archival.txt000066400000000000000000000001731222421776500162630ustar00rootroot00000000000000repo: 7716d24a143b0c085767f8329ff98bcb882b68c2 node: 30da9c169efc3985ad0464936483c229faba0e33 branch: default tag: v0.17.0 ruby-pg-0.17.0/.hgignore000066400000000000000000000003651222421776500150030ustar00rootroot00000000000000ChangeLog$ commit-msg\.txt$ lowrite\.txt \.(diff|patch)$ \.(s?o|log|bundle)$ \.DS_Store \.orig$ ^doc/ ^ext/conftest\.dSYM ^ext/extconf\.h ^ext/Makefile ^pkg/ ^tmp/ ^tmp_test_specs/ ~$ build/ misc/ruby-pg/pkg misc/postgres/pkg ext/errorcodes.def ruby-pg-0.17.0/.hgsigs000066400000000000000000000047301222421776500144650ustar00rootroot00000000000000872063e42b129af10539f73b3c083ad8a031f961 0 iEYEABECAAYFAkuKoCoACgkQ+zlz4UKpE6QzewCgrFcSsAwju/KpZ8myuWexlcSbe04AmwWCbf4HM95tDXdFvsvzeegPg8AS 3993015a841e43c9cd9d1321819cbf5e74264f1d 0 iEYEABECAAYFAkz2ycMACgkQ+zlz4UKpE6SYjQCgi/1Ik2rntK2dU93Hb91wYh0Yv4sAoKxEXVuXaEIAiwB4vSQ/7JQGIBzM 230ea3e68db2360548097542c4856dec4c3cd97a 0 iEYEABECAAYFAk03CpAACgkQ+zlz4UKpE6SPAgCfbRwKmAgHTmrudSoC09c37Tuyff0AnRHrSaqKhiCO7KlX5UJq6x0ttoKH 24aa7899c6966ce349c8e4f2a87b17c3e943ff56 0 iEYEABECAAYFAk2s1wQACgkQ+zlz4UKpE6SkLQCdHOS5yxoUFguEo885HkDyOZg4Y7wAoMVofhwOUHVQ6djXr0hgAmahI1lW 19b551f972e27dcfa281b92914e2a98661243206 0 iEYEABECAAYFAk7f51sACgkQ+zlz4UKpE6RkYACg0WZjt1crbi72DQYs3kYKSYRflNYAnA80+VVwmMUQiWuFuQ+7gbiUPCyY f72b14d349bf385c769aacfddbea7a0e60ff5e9e 0 iEYEABECAAYFAk8CFCIACgkQ+zlz4UKpE6QbYACgyLQwHPQH50sGVgzTD3y13XKwi38AoIrF5zSOiMXAeL+sk++iwDYV4ddW f3dfdb6929b70ddd3bb952757bdfb199e6916245 0 iEYEABECAAYFAk8Di+MACgkQ+zlz4UKpE6TVvwCg+ibuW22lRdnOIrRF2V4am7b4YxYAn0bDEnP93JX6qKAaU8kcoCrTKDXp b67309d3ccf2f9de56535e01f58c7af994426827 0 iEYEABECAAYFAk8iJKkACgkQ+zlz4UKpE6SjUQCgpItY5hW5NyVkfL5+nkRhJqaetQMAoJQQkNPL2jQLgJREfj3PtMBbn2VG 0e7f0c2451e55855b4a90efce8db0cafbf04b26f 0 iEYEABECAAYFAk8kb0cACgkQ+zlz4UKpE6RpxgCfQDV3zq2N+zle1XLKoXGMr7EK19IAnR3llz7WPf2j9lqXdZjw4xtl0XBk 9c262b875047f9acfedb63396a262ab5a5b101ca 0 iEYEABECAAYFAk80EvkACgkQ+zlz4UKpE6SUHQCeJuJMb8+k8ynIDPSmcKHL/a5gD6AAoPXMns9HF2c3XwtS1CMRf6rcZp3e 1ba641824000abbf1b22000772815c24e9b5f6d9 0 iEYEABECAAYFAk84LSUACgkQ+zlz4UKpE6RlPQCgiGZbYJFbeWEAdehVUrIZdU7sRe4AoOgESbvEWynP4X0OKbvdC9rLchYl 41e071bdd6ed970887d4ed4da59fdfa62003c39e 0 iEYEABECAAYFAk9FXikACgkQ+zlz4UKpE6TB8ACgt/VSo/kJMg9UVLKd5UUPBPjbgOIAn0DJuOla9GF85mW74sEkCOqE6Ada a45710f8db303c400200017242589562936fcf1b 0 iEYEABECAAYFAk/l/kgACgkQ+zlz4UKpE6QCkwCg049BpW4kSvaKuICyvKokeoXbNiAAoPWAaiDuK6xjZhqGSuuGVWMmCRwk 52d22b060501ab90a89b3a758aca8ce70ad05231 0 iEYEABECAAYFAlBDfn8ACgkQ+zlz4UKpE6R3GACgzLiZ+fyM4Hx8/Qp9fyWF+mHk4FQAn3P3Y06AHadVvKwyksrAgKk/33LV 384fcbc92366ca0108b6c0984d861ffef2d38570 0 iEYEABECAAYFAlFRsM4ACgkQ+zlz4UKpE6TYXgCgksacYvWJ5dhx9oYFRR+oSH6wPgwAoJ3QO01zfiDbBz6Z9Mxy7tNi3jx6 0bfb6ff650be2d003af3d0fc6c75be16369605e1 0 iEYEABECAAYFAlFjCYkACgkQ+zlz4UKpE6RldACg77Rp2I4vYUXpFakUrYq6uSfPLLQAn266JL6CiQG44cSroW+Mgz4CZgJn 4e0606f5f5aab87855860a3eeaf4c9eaaea77f09 0 iEYEABECAAYFAlHuizwACgkQ+zlz4UKpE6QphACg4FNFwvVju9wk6PC6vwkY8cZRtvkAn1nDR0pbto9xMdMUqhJxOc5Dqisr eed93df350a6cc657d5151bd3aa29ab427fba7cc 0 iEYEABECAAYFAlI3Sy4ACgkQ+zlz4UKpE6ShLQCffDunkSEo5TCnzCx8PjVF9jetDxYAn02ZCfDJ2UPgojF+gjhHCGk9haFq ruby-pg-0.17.0/.hgtags000066400000000000000000000017741222421776500144630ustar00rootroot000000000000007fbe4187e9e53e58baf6cd7c1c21e3a3c5b920e5 0.8.0 da726282493c57b4ef8e5be1a21e98cc028fda4c 0.9.0 1822a169c4fecac402335a64a484b5dc053994a3 0.10.0 1822a169c4fecac402335a64a484b5dc053994a3 v0.10.0 1822a169c4fecac402335a64a484b5dc053994a3 0.10.0 0000000000000000000000000000000000000000 0.10.0 de10b5d8e4429d22790976ec4de89f209e882906 v0.10.1 3cb8e57c6c80737c714dd7607a144ef12074c4fe v0.11.0 da726282493c57b4ef8e5be1a21e98cc028fda4c v0.9.0 7fbe4187e9e53e58baf6cd7c1c21e3a3c5b920e5 v0.8.0 b767401684d8a4051230874b0686a54537b10e2f v0.12.0 21f84883e5c206a3f2890905af68e08a0046ba1c v0.12.1 88bd78632f86f696dd3fa8904c1d3180216378cc v0.12.2 7b2da7e0815cce834cd60f9747209923952876ec v0.13.0 9e60b2c477cde450a088161ca8f3d72b52531aaf v0.13.1 c79cd308363d614f7ba32fd86294c9aa3117c361 v0.13.2 634e0a42a1010fc1dcd279fb28506873a47090c1 v0.14.0 2d83ce956f971c3aeb145c9ad68f426e78b852dd v0.14.1 065fd1f0e9dda58557de0efb2deb138e93ba7632 v0.15.0 4692c20bcbdeadd8a31283e234464c6e1c43765d v0.15.1 def8f41a76726cf7239ff6dbaa2828a881f93451 v0.16.0 ruby-pg-0.17.0/.hoerc000066400000000000000000000001501222421776500142710ustar00rootroot00000000000000--- exclude: !ruby/regexp /(?:\.(hg|hoe|bundle|irb|pry|rvm|tm|DS_Store|travis\.yml)|tmp|misc|Gemfile)/ ruby-pg-0.17.0/.irbrc000066400000000000000000000006731222421776500143040ustar00rootroot00000000000000#!/usr/bin/ruby -*- ruby -*- BEGIN { require 'pathname' require 'rbconfig' basedir = Pathname.new( __FILE__ ).dirname.expand_path libdir = basedir + "lib" puts ">>> Adding #{libdir} to load path..." $LOAD_PATH.unshift( libdir.to_s ) } # Try to require the 'pg' library begin $stderr.puts "Loading pg..." require 'pg' rescue => e $stderr.puts "Ack! pg library failed to load: #{e.message}\n\t" + e.backtrace.join( "\n\t" ) end ruby-pg-0.17.0/.pryrc000066400000000000000000000006731222421776500143420ustar00rootroot00000000000000#!/usr/bin/ruby -*- ruby -*- BEGIN { require 'pathname' require 'rbconfig' basedir = Pathname.new( __FILE__ ).dirname.expand_path libdir = basedir + "lib" puts ">>> Adding #{libdir} to load path..." $LOAD_PATH.unshift( libdir.to_s ) } # Try to require the 'pg' library begin $stderr.puts "Loading pg..." require 'pg' rescue => e $stderr.puts "Ack! pg library failed to load: #{e.message}\n\t" + e.backtrace.join( "\n\t" ) end ruby-pg-0.17.0/.rvm.gems000066400000000000000000000002631222421776500147340ustar00rootroot00000000000000# .gems generated gem export file. Note that any env variable settings will be missing. Append these after using a ';' field separator rake-compiler -v0.8.3 hoe-deveiate -v0.2.0 ruby-pg-0.17.0/.rvmrc000066400000000000000000000013751222421776500143340ustar00rootroot00000000000000#!/usr/bin/env bash # This is an RVM Project .rvmrc file, used to automatically load the ruby # development environment upon cd'ing into the directory environment_id="ruby-2.0.0@pg" rvmdir=${rvm_path:-$HOME/.rvm} gemset_file=".rvm.gems" if [[ -d "${rvmdir}/environments" && -s "${rvmdir}/environments/$environment_id" ]]; then echo "Using ${environment_id}" . "${rvmdir}/environments/$environment_id" if [[ -s "${rvmdir}/hooks/after_use" ]]; then . "${rvmdir}/hooks/after_use" fi else # If the environment file has not yet been created, use the RVM CLI to select. if ! rvm --create use "$environment_id"; then echo "Failed to create RVM environment '${environment_id}'." fi fi if [[ -s "$gemset_file" ]]; then rvm gemset import "$gemset_file" fi ruby-pg-0.17.0/.tm_properties000066400000000000000000000006211222421776500160700ustar00rootroot00000000000000# Settings projectDirectory = "$CWD" windowTitle = "${CWD/^.*\///} «$TM_DISPLAYNAME»" excludeInFileChooser = "{$exclude,.hg}" TM_MAKE = 'rake' TM_MAKE_FILE = '${projectDirectory}/Rakefile' [ source ] softTabs = false tabSize = 4 [ source.ruby ] softTabs = false tabSize = 4 [ source.ruby.rspec ] softTabs = false tabSize = 4 ruby-pg-0.17.0/.travis.yml000066400000000000000000000035731222421776500153150ustar00rootroot00000000000000language: ruby rvm: - "1.8.7" # - "1.9.2" - "1.9.3" - "2.0.0" # - jruby-18mode # JRuby in 1.8 mode # - jruby-19mode # JRuby in 1.9 mode - rbx-18mode - rbx-19mode env: - "PGVERSION=9.2.4-1-linux-x64 PATH=\"/opt/PostgreSQL/9.2/bin:$PATH\"" - "PGVERSION=8.4.17-1-linux-x64 PATH=\"/opt/PostgreSQL/8.4/bin:$PATH\"" - "PGCROSS=true" matrix: # Test cross compilation only with 1.8.7 exclude: - rvm: 1.9.2 env: "PGCROSS=true" - rvm: 1.9.3 env: "PGCROSS=true" - rvm: 2.0.0 env: "PGCROSS=true" - rvm: jruby-18mode env: "PGCROSS=true" - rvm: jruby-19mode env: "PGCROSS=true" - rvm: rbx-18mode env: "PGCROSS=true" - rvm: rbx-19mode env: "PGCROSS=true" allow_failures: - rvm: rbx-18mode # one test fails because GVL unblocking function is not called by Rubinius core - rvm: rbx-19mode # one test fails because GVL unblocking function is not called by Rubinius core before_install: - gem install hoe rspec; - gem install rake-compiler --pre; # Download and install postgresql version to test against in /opt (for non-cross compile only) - "if [ -z \"$PGCROSS\" ]; then wget http://get.enterprisedb.com/postgresql/postgresql-$PGVERSION.run && chmod +x postgresql-$PGVERSION.run && sudo ./postgresql-$PGVERSION.run --mode unattended --unattendedmodeui minimal; fi" # Install compiler and ruby versions for cross compile (as seperate tasks to not exceed timeout limits) - "if [ -n \"$PGCROSS\" ]; then sudo apt-get install gcc-mingw-w64-i686 binutils-mingw-w64-i686 gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64; fi" - "if [ -n \"$PGCROSS\" ]; then rake-compiler cross-ruby VERSION=1.8.7-p371; fi" - "if [ -n \"$PGCROSS\" ]; then rake-compiler cross-ruby VERSION=2.0.0-p0 HOST=x86_64-w64-mingw32; fi" script: "if [ -z \"$PGCROSS\" ]; then rake compile test; else rake cross compile; fi" ruby-pg-0.17.0/BSDL000066400000000000000000000024021222421776500136410ustar00rootroot00000000000000Copyright (C) 1993-2010 Yukihiro Matsumoto. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ruby-pg-0.17.0/Contributors.rdoc000066400000000000000000000032611222421776500165440ustar00rootroot00000000000000 Thanks to all the great people that have contributed code, suggestions, and patches through the years. If you contribute a patch, please include a patch for this file that adds your name to the list. * Dennis Vshivkov * Gabriel Emerson * Noboru Saitou * Akinori MUSHA * Andy Yu * Ceri Storey * Gavin Kistner * Henry T. So Jr. * Jeremy Henty * * Leon Brooks * Martin Hedenfalk * Yukihiro Matsumoto * Eiji Matsumoto * MoonWolf * * Nate Haggard * Neil Conway * Noboru Matui * Okada Jun * Shirai,Kaoru * Riley * shibata * * ts * Yuta TSUBOI * Lugovoi Nikolai * Jeff Davis * Bertram Scharpf * Michael Granger * Mahlon E. Smith * Lars Kanis * Jason Yanowitz * Charlie Savage * Rafał Bigaj * Jason Yanowitz * Greg Hazel * Chris White * Aaron Patterson * Tim Felgentreff ruby-pg-0.17.0/Gemfile000066400000000000000000000006711222421776500144730ustar00rootroot00000000000000# -*- ruby -*- # DO NOT EDIT THIS FILE. Instead, edit Rakefile, and run `rake bundler:gemfile`. source "https://rubygems.org/" gem "rdoc", "~>4.0", :group => [:development, :test] gem "rake-compiler", "~>0.9", :group => [:development, :test] gem "hoe", "~>3.5.1", :group => [:development, :test] gem "hoe-deveiate", "~>0.2", :group => [:development, :test] gem "hoe-bundler", "~>1.0", :group => [:development, :test] # vim: syntax=ruby ruby-pg-0.17.0/History.rdoc000066400000000000000000000201721222421776500155100ustar00rootroot00000000000000== v0.17.0 [2013-09-15] Michael Granger Bugfixes: - Fix crash by calling PQsend* and PQisBusy without GVL (#171). Enhancements: - Add method PG::Connection#copy_data. - Add a Gemfile to allow installation of dependencies with bundler. - Add compatibility with rake-compiler-dev-box. - Return self from PG::Result#check instead of nil. This allows to stack method calls. == v0.16.0 [2013-07-22] Michael Granger Bugfixes: - Avoid warnings about uninitialized instance variables. - Use a more standard method of adding library and include directories. This fixes build on AIX (Github #7) and Solaris (#164). - Cancel the running query, if a thread is about to be killed (e.g. by CTRL-C). - Fix GVL issue with wait_for_notify/notifies and notice callbacks. - Set proper encoding on the string returned by quote_ident, escape_literal and escape_identifier (#163). - Use nil as PG::Error#result in case of a NULL-result from libpq (#166). - Recalculate the timeout of conn#wait_for_notify and conn#block in case of socket events that require re-runs of select(). Documentation fixes: - Fix non working example for PGresult#error_field. Enhancements: - Add unique exception classes for each PostgreSQL error type (#5). - Return result of the block in conn#transaction instead of nil (#158). - Allow 'rake compile' and 'rake gem' on non mercurial repos. - Add support for PG_DIAG_*_NAME error fields of PostgreSQL-9.3 (#161). == v0.15.1 [2013-04-08] Michael Granger Bugfixes: - Shorten application_name to avoid warnings about truncated identifier. == v0.15.0 [2013-03-03] Michael Granger Bugfixes: - Fix segfault in PG::Result#field_values when called with non String value. - Fix encoding of messages delivered by notice callbacks. - Fix text encoding for Connection#wait_for_notify and Connection#notifies. - Fix 'Bad file descriptor' problems under Windows: wrong behaviour of #wait_for_notify() and timeout handling of #block on Ruby 1.9. Documentation fixes: - conn#socket() can not be used with IO.for_fd() on Windows. Enhancements: - Tested under Ruby 2.0.0p0. - Add single row mode of PostgreSQL 9.2. - Set fallback_application_name to programm name $0. Thanks to Will Leinweber for the patch. - Release Ruby's GVL while calls to blocking libpq functions to allow better concurrency in threaded applications. - Refactor different variants of waiting for the connection socket. - Make use of rb_thread_fd_select() on Ruby 1.9 and avoid deprecated rb_thread_select(). - Add an example of how to insert array data using a prepared statement (#145). - Add continous integration tests on travis-ci.org. - Add PG::Result#each_row for iterative over result sets by row. Thanks to Aaron Patterson for the patch. - Add a PG::Connection#socket_io method for fetching a (non-autoclosing) IO object for the connection's socket. Specs: - Fix various specs to run on older PostgreSQL and Ruby versions. - Avoid fork() in specs to allow usage on Windows and JRuby. == v0.14.1 [2012-09-02] Michael Granger Important bugfix: - Fix stack overflow bug in PG::Result#values and #column_values (#135). Thanks to everyone who reported the bug, and Lars Kanis especially for figuring out the problem. PostgreSQL 9.2 beta fixes: - Recognize PGRES_SINGLE_TUPLE as OK when checking PGresult (Jeremy Evans) Documentation fixes: - Add note about the usage scope of the result object received by the #set_notice_receiver block. (Lars Kanis) - Add PGRES_COPY_BOTH to documentation of PG::Result#result_status. (Lars Kanis) - Add some documentation to PG::Result#fnumber (fix for #139) == v0.14.0 [2012-06-17] Michael Granger Bugfixes: #47, #104 New Methods for PostgreSQL 9 and async API support: PG - ::library_version PG::Connection - ::ping - #escape_literal - #escape_identifier - #set_default_encoding PG::Result - #check New Samples: This release also comes with a collection of contributed sample scripts for doing resource-utilization reports, graphing database statistics, monitoring for replication lag, shipping WAL files for replication, automated tablespace partitioning, etc. See the samples/ directory. == v0.13.2 [2012-02-22] Michael Granger - Make builds against PostgreSQL earlier than 8.3 fail with a descriptive message instead of a compile failure. == v0.13.1 [2012-02-12] Michael Granger - Made use of a finished PG::Connection raise a PG::Error instead of a fatal error (#110). - Added missing BSDL license file (#108) == v0.13.0 [2012-02-09] Michael Granger Reorganization of modules/classes to be better Ruby citizens (with backward-compatible aliases): - Created toplevel namespace 'PG' to correspond with the gem name. - Renamed PGconn to PG::Connection (with ::PGconn alias) - Renamed PGresult to PG::Result (with ::PGresult alias) - Renamed PGError to PG::Error (with ::PGError alias) - Declare all constants inside PG::Constants, then include them in PG::Connection and PG::Result for backward-compatibility, and in PG for convenience. - Split the extension source up by class/module. - Removed old compatibility code for PostgreSQL versions < 8.3 Documentation: - Clarified licensing, updated to Ruby 1.9's license. - Merged authors list, added some missing people to the Contributor's list. - Cleaned up the sample/ directory - Making contact info a bit clearer, link to the Google+ page and the mailing list Enhancements: - Added a convenience method: PG.connect -> PG::Connection.new Bugfixes: - Fixed LATIN5-LATIN10 Postgres<->Ruby encoding conversions == v0.12.2 [2012-01-03] Michael Granger - Fix for the 1.8.7 breakage introduced by the st.h fix for alternative Ruby implementations (#97 and #98). Thanks to Lars Kanis for the patch. - Encode error messages with the connection's encoding under 1.9 (#96) == v0.12.1 [2011-12-14] Michael Granger - Made rake-compiler a dev dependency, as Rubygems doesn't use the Rakefile for compiling the extension. Thanks to eolamey@bitbucket and Jeremy Evans for pointing this out. - Added an explicit include for ruby/st.h for implementations that need it (fixes #95). == v0.12.0 [2011-12-07] Michael Granger - PGconn#wait_for_notify * send nil as the payload argument if the NOTIFY didn't have one. * accept a nil argument for no timeout (Sequel support) * Fixed API docs * Taint and encode event name and payload - Handle errors while rb_thread_select()ing in PGconn#block. (Brian Weaver). - Fixes for Win32 async queries (Rafał Bigaj) - Memory leak fixed: Closing opened WSA event. (rafal) - Fixes for #66 Win32 asynchronous queries hang on connection error. (rafal) - Fixed a typo in PGconn#error_message's documentation - fixing unused variable warnings for ruby 1.9.3 (Aaron Patterson) - Build system bugfixes - Converted to Hoe - Updates for the Win32 binary gem builds (Lars Kanis) == v0.11.0 [2011-02-09] Michael Granger Enhancements: * Added a PGresult#values method to fetch all result rows as an Array of Arrays. Thanks to Jason Yanowitz (JYanowitz at enovafinancial dot com) for the patch. == v0.10.1 [2011-01-19] Michael Granger Bugfixes: * Add an include guard for pg.h * Simplify the common case require of the ext * Include the extconf header * Fix compatibility with versions of PostgreSQL without PQgetCancel. (fixes #36) * Fix require for natively-compiled extension under Windows. (fixes #55) * Change rb_yield_splat() to rb_yield_values() for compatibility with Rubinius. (fixes #54) == v0.10.0 [2010-12-01] Michael Granger Enhancements: * Added support for the payload of NOTIFY events (w/Mahlon E. Smith) * Updated the build system with Rubygems suggestions from RubyConf 2010 Bugfixes: * Fixed issue with PGconn#wait_for_notify that caused it to miss notifications that happened after the LISTEN but before the wait_for_notify. == v0.9.0 [2010-02-28] Michael Granger Bugfixes. == v0.8.0 [2009-03-28] Jeff Davis Bugfixes, better Windows support. ruby-pg-0.17.0/LICENSE000066400000000000000000000047101222421776500142030ustar00rootroot00000000000000Ruby is copyrighted free software by Yukihiro Matsumoto . You can redistribute it and/or modify it under either the terms of the 2-clause BSDL (see the file BSDL), or the conditions below: 1. You may make and give away verbatim copies of the source form of the software without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may modify your copy of the software in any way, provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or by allowing the author to include your modifications in the software. b) use the modified software only within your corporation or organization. c) give non-standard binaries non-standard names, with instructions on where to get the original software distribution. d) make other distribution arrangements with the author. 3. You may distribute the software in object code or binary form, provided that you do at least ONE of the following: a) distribute the binaries and library files of the software, together with instructions (in the manual page or equivalent) on where to get the original distribution. b) accompany the distribution with the machine-readable source of the software. c) give non-standard binaries non-standard names, with instructions on where to get the original software distribution. d) make other distribution arrangements with the author. 4. You may modify and include the part of the software into any other software (possibly commercial). But some files in the distribution are not written by the author, so that they are not under these terms. For the list of those files and their copying conditions, see the file LEGAL. 5. The scripts and library files supplied as input to or produced as output from the software do not automatically fall under the copyright of the software, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this software. 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ruby-pg-0.17.0/Manifest.txt000066400000000000000000000020461222421776500155050ustar00rootroot00000000000000.gemtest BSDL ChangeLog Contributors.rdoc History.rdoc LICENSE Manifest.txt POSTGRES README-OS_X.rdoc README-Windows.rdoc README.ja.rdoc README.rdoc Rakefile Rakefile.cross ext/errorcodes.def ext/errorcodes.rb ext/errorcodes.txt ext/extconf.rb ext/gvl_wrappers.c ext/gvl_wrappers.h ext/pg.c ext/pg.h ext/pg_connection.c ext/pg_errors.c ext/pg_result.c ext/vc/pg.sln ext/vc/pg_18/pg.vcproj ext/vc/pg_19/pg_19.vcproj lib/pg.rb lib/pg/connection.rb lib/pg/constants.rb lib/pg/exceptions.rb lib/pg/result.rb sample/array_insert.rb sample/async_api.rb sample/async_copyto.rb sample/async_mixed.rb sample/check_conn.rb sample/copyfrom.rb sample/copyto.rb sample/cursor.rb sample/disk_usage_report.rb sample/issue-119.rb sample/losample.rb sample/minimal-testcase.rb sample/notify_wait.rb sample/pg_statistics.rb sample/replication_monitor.rb sample/test_binary_values.rb sample/wal_shipper.rb sample/warehouse_partitions.rb spec/data/expected_trace.out spec/data/random_binary_data spec/lib/helpers.rb spec/pg/connection_spec.rb spec/pg/result_spec.rb spec/pg_spec.rb ruby-pg-0.17.0/POSTGRES000066400000000000000000000022501222421776500143640ustar00rootroot00000000000000PostgreSQL Database Management System (formerly known as Postgres, then as Postgres95) Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group Portions Copyright (c) 1994, The Regents of the University of California Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. ruby-pg-0.17.0/README-OS_X.rdoc000066400000000000000000000055021222421776500156120ustar00rootroot00000000000000= Compiling on MacOS X The EnterpriseDB packages are the recommended PostgreSQL installations to use with MacOS X. They eliminate most or all of the issues with getting 'pg' installed, linked correctly, and running. == Segfaults and SSL Support If you need a custom installation of PostgreSQL, you should ensure that you either compile it against the same version of OpenSSL as the OpenSSL extension of the Ruby you'll be using, or compile it without SSL support. If you fail to do this, you will likely see segfaults when you use 'pg' and the 'openssl' extension at the same time. You can see what library it's linked against using 'otool -L'; for example, on my 10.7 machine I use for 'pg' development: $ otool -L /System/Library/Frameworks/Ruby.framework/Versions\ /1.8/usr/lib/ruby/1.8/universal-darwin11.0/openssl.bundle /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/\ lib/ruby/1.8/universal-darwin11.0/openssl.bundle: /System/Library/Frameworks/Ruby.framework/Versions/1.8/\ usr/lib/libruby.1.dylib (compatibility version 1.8.0, \ current version 1.8.7) /usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, \ current version 0.9.8) /usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, \ current version 0.9.8) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, \ current version 159.0.0) == Dealing with Installation Problems If you are building/installing pg on MacOS X, and the installation doesn't work at first, here are a few things you can try. === pg_config The first thing you should do is ensure that the 'pg_config' tool that comes with Postgres is in your path. If it isn't, or the one that's first in your path isn't the one that was installed with the Postgres you want to build against, you can specify the path to it with the --with-pg-config option. For example, if you're using the Ruby binary that comes with OSX, and PostgreSQL 9.0.x installed from MacPorts, do: gem install -- --with-pg-config=/opt/local/lib/postgresql90/bin/pg_config === ARCHFLAGS and Universal Binaries OS X supports both architecture-specific binaries (e.g. i386), as well as universal binaries (i.e. i386 & ppc). If Ruby is built as a universal binary and PostgreSQL is not, you need to specify the path to the appropriate pg_config binary or set the environment variable ARCHFLAGS appropriately. Alternatively, if the build system can't figure out which architectures it should include, you may need to set the 'ARCHFLAGS' environment variable explicitly: sudo env ARCHFLAGS='-arch x86_64' gem install pg or, if you're building from source: rake compile ARCHFLAGS="-arch x86_64" Note that the recommended EnterpriseDB packages are correctly compiled as universal binaries, and don't need any of these workarounds. ruby-pg-0.17.0/README-Windows.rdoc000066400000000000000000000046621222421776500164420ustar00rootroot00000000000000= Compiling 'pg' on MS Windows In order to build this extension on MS Windows you will need a couple things. First, a compiler. For the one click installer this means you should either use VC++ 6.0 or the compiler that comes with cygwin or mingw if you're building on that platform. If you've built Ruby yourself, you should use the same compiler to build this library that you used to build Ruby. Second, PostgreSQL. Be sure you installed it with the development header files if you installed it using the standard PostgreSQL installer for Windows. If you didn't, you can run the installer again, select "modify", and then select the 'development headers' option to install them. I recommend making sure that 'pg_config.exe' is in your PATH. The PostgreSQL installer for Windows does not necessarily update your PATH when it installs itself, so you may need to do this manually. This isn't strictly necessary, however. In order to build ruby-pg, just run 'rake'. If the pg_config.exe executable is not in your PATH, you'll need to explicitly point ruby-pg to where your PostgreSQL headers and libraries are with something like this: rake --with-pg-dir=c:/progra~1/postgr~1/8.3 Adjust your path accordingly. BE SURE TO USE THE SHORT PATH NAMES! If you try to use a path with spaces in it, the nmake.exe program will choke. == Cross compiling for mswin32 Using rake-compiler a cross compiled pg gem can be build on a Linux or MacOS X host for the win32 platform. The generated gem is statically linked against libpq and libssl. OpenSSL and PostgreSQL are downloaded and compiled from the sources. There are no runtime dependencies to any but the standard Windows DLLs. Install mingw32 using the instructions in rake-compiler's README. For Debian/Ubuntu it is apt-get install gcc-mingw32 . Use ruby-1.8.7 for the following commands. Download and cross compile ruby 1.8 and 1.9 for win32 with: rake-compiler cross-ruby VERSION=1.8.7-p352 rake-compiler cross-ruby VERSION=1.9.2-p290 Download and cross compile pg for win32: rake cross native gem or with custom versions: rake cross native gem RUBY_CC_VERSION=1.8.7:1.9.2 \ OPENSSL_VERSION=1.0.0e POSTGRESQL_VERSION=9.1.1 If everything works, there should be pg-VERSION-x86-mingw32.gem in the pkg directory. == Reporting Problems If you have any problems you can submit them via [the project's issue-tracker][bitbucket]. And submit questions, problems, or solutions, so that it can be improved. ruby-pg-0.17.0/README.ja.rdoc000066400000000000000000000005131222421776500153720ustar00rootroot00000000000000= pg home :: https://bitbucket.org/ged/ruby-pg mirror :: https://github.com/ged/ruby-pg docs :: http://deveiate.org/code/pg == Description This file needs a translation of the English README. Pull requests, patches, or volunteers gladly accepted. Until such time, please accept my sincere apologies for not knowing Japanese. ruby-pg-0.17.0/README.rdoc000066400000000000000000000061421222421776500150050ustar00rootroot00000000000000= pg home :: https://bitbucket.org/ged/ruby-pg mirror :: https://github.com/ged/ruby-pg docs :: http://deveiate.org/code/pg == Description Pg is the Ruby interface to the {PostgreSQL RDBMS}[http://www.postgresql.org/]. It works with {PostgreSQL 8.4 and later}[http://www.postgresql.org/support/versioning/]. A small example usage: #!/usr/bin/env ruby require 'pg' # Output a table of current connections to the DB conn = PG.connect( dbname: 'sales' ) conn.exec( "SELECT * FROM pg_stat_activity" ) do |result| puts " PID | User | Query" result.each do |row| puts " %7d | %-16s | %s " % row.values_at('procpid', 'usename', 'current_query') end end == Build Status {Build Status}[https://travis-ci.org/ged/ruby-pg] == Requirements * Ruby 1.9.3-p392, or 2.0.0-p0. * PostgreSQL 8.4.x or later (with headers, -dev packages, etc). It may work with earlier versions of Ruby/PostgreSQL as well, but those are not regularly tested. == How To Install Install via RubyGems: gem install pg You may need to specify the path to the 'pg_config' program installed with Postgres: gem install pg -- --with-pg-config= If you're installing via Bundler, you can provide compile hints like so: bundle config build.pg --with-pg-config= See README-OS_X.rdoc for more information about installing under MacOS X, and README-Windows.rdoc for Windows build/installation instructions. There's also {a Google+ group}[http://goo.gl/TFy1U] and a {mailing list}[http://groups.google.com/group/ruby-pg] if you get stuck, or just want to chat about something. == Contributing To report bugs, suggest features, or check out the source with Mercurial, {check out the project page}[http://bitbucket.org/ged/ruby-pg]. If you prefer Git, there's also a {Github mirror}[https://github.com/ged/ruby-pg]. After checking out the source, run: $ rake newb This task will install any missing dependencies, run the tests/specs, and generate the API documentation. The current maintainers are Michael Granger and Lars Kanis . == Copying Copyright (c) 1997-2013 by the authors. * Jeff Davis * Guy Decoux (ts) * Michael Granger * Lars Kanis * Dave Lee * Eiji Matsumoto * Yukihiro Matsumoto * Noboru Saitou You may redistribute this software under the same terms as Ruby itself; see http://www.ruby-lang.org/en/LICENSE.txt or the LICENSE file in the source for details. Portions of the code are from the PostgreSQL project, and are distributed under the terms of the PostgreSQL license, included in the file POSTGRES. Portions copyright LAIKA, Inc. == Acknowledgments See Contributors.rdoc for the many additional fine people that have contributed to this library over the years. We are thankful to the people at the ruby-list and ruby-dev mailing lists. And to the people who developed PostgreSQL. ruby-pg-0.17.0/Rakefile000066400000000000000000000117121222421776500146430ustar00rootroot00000000000000#!/usr/bin/env rake require 'rbconfig' require 'pathname' require 'tmpdir' begin require 'rake/extensiontask' rescue LoadError abort "This Rakefile requires rake-compiler (gem install rake-compiler)" end begin require 'hoe' rescue LoadError abort "This Rakefile requires hoe (gem install hoe)" end require 'rake/clean' # Build directory constants BASEDIR = Pathname( __FILE__ ).dirname SPECDIR = BASEDIR + 'spec' LIBDIR = BASEDIR + 'lib' EXTDIR = BASEDIR + 'ext' PKGDIR = BASEDIR + 'pkg' TMPDIR = BASEDIR + 'tmp' DLEXT = RbConfig::CONFIG['DLEXT'] EXT = LIBDIR + "pg_ext.#{DLEXT}" TEST_DIRECTORY = BASEDIR + "tmp_test_specs" CLOBBER.include( TEST_DIRECTORY.to_s ) CLEAN.include( PKGDIR.to_s, TMPDIR.to_s ) # Set up Hoe plugins Hoe.plugin :mercurial Hoe.plugin :signing Hoe.plugin :deveiate Hoe.plugin :bundler Hoe.plugins.delete :rubyforge Hoe.plugins.delete :compiler load 'Rakefile.cross' # Hoe specification $hoespec = Hoe.spec 'pg' do self.readme_file = 'README.rdoc' self.history_file = 'History.rdoc' self.extra_rdoc_files = Rake::FileList[ '*.rdoc' ] self.extra_rdoc_files.include( 'POSTGRES', 'LICENSE' ) self.extra_rdoc_files.include( 'ext/*.c' ) self.developer 'Michael Granger', 'ged@FaerieMUD.org' self.developer 'Lars Kanis', 'lars@greiz-reinsdorf.de' self.dependency 'rake-compiler', '~> 0.9', :developer self.dependency 'hoe', '~> 3.5.1', :developer self.dependency 'hoe-deveiate', '~> 0.2', :developer self.dependency 'hoe-bundler', '~> 1.0', :developer self.spec_extras[:licenses] = ['BSD', 'Ruby', 'GPL'] self.spec_extras[:extensions] = [ 'ext/extconf.rb' ] self.require_ruby_version( '>= 1.8.7' ) self.hg_sign_tags = true if self.respond_to?( :hg_sign_tags= ) self.check_history_on_release = true if self.respond_to?( :check_history_on_release= ) self.spec_extras[:rdoc_options] = [ '-f', 'fivefish', '-t', 'pg: The Ruby Interface to PostgreSQL', '-m', 'README.rdoc', ] self.rdoc_locations << "deveiate:/usr/local/www/public/code/#{remote_rdoc_dir}" end ENV['VERSION'] ||= $hoespec.spec.version.to_s # Tests should pass before checking in task 'hg:precheckin' => [ :check_history, :check_manifest, :spec ] # Support for 'rvm specs' task :specs => :spec # Compile before testing task :spec => :compile # gem-testers support task :test do # rake-compiler always wants to copy the compiled extension into lib/, but # we don't want testers to have to re-compile, especially since that # often fails because they can't (and shouldn't have to) write to tmp/ in # the installed gem dir. So we clear the task rake-compiler set up # to break the dependency between :spec and :compile when running under # rubygems-test, and then run :spec. Rake::Task[ EXT.to_s ].clear Rake::Task[ :spec ].execute end desc "Turn on warnings and debugging in the build." task :maint do ENV['MAINTAINER_MODE'] = 'yes' end ENV['RUBY_CC_VERSION'] ||= '1.8.7:1.9.2:2.0.0' # Rake-compiler task Rake::ExtensionTask.new do |ext| ext.name = 'pg_ext' ext.gem_spec = $hoespec.spec ext.ext_dir = 'ext' ext.lib_dir = 'lib' ext.source_pattern = "*.{c,h}" ext.cross_compile = true ext.cross_platform = CrossLibraries.map &:for_platform ext.cross_config_options += CrossLibraries.map do |lib| { lib.for_platform => [ "--with-pg-include=#{lib.static_postgresql_libdir}", "--with-opt-include=#{lib.static_postgresql_incdir}", "--with-pg-lib=#{lib.static_postgresql_libdir}", "--with-opt-lib=#{lib.static_openssl_builddir}", ] } end end # Make the ChangeLog update if the repo has changed since it was last built file '.hg/branch' do warn "WARNING: You need the Mercurial repo to update the ChangeLog" end file 'ChangeLog' do |task| if File.exist?('.hg/branch') $stderr.puts "Updating the changelog..." begin content = make_changelog() rescue NameError abort "Packaging tasks require the hoe-mercurial plugin (gem install hoe-mercurial)" end File.open( task.name, 'w', 0644 ) do |fh| fh.print( content ) end else touch 'ChangeLog' end end # Rebuild the ChangeLog immediately before release task :prerelease => 'ChangeLog' desc "Stop any Postmaster instances that remain after testing." task :cleanup_testing_dbs do require 'spec/lib/helpers' PgTestingHelpers.stop_existing_postmasters() Rake::Task[:clean].invoke end desc "Update list of server error codes" task :update_error_codes do URL_ERRORCODES_TXT = "http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob_plain;f=src/backend/utils/errcodes.txt;hb=HEAD" ERRORCODES_TXT = "ext/errorcodes.txt" sh "wget #{URL_ERRORCODES_TXT.inspect} -O #{ERRORCODES_TXT.inspect} || curl #{URL_ERRORCODES_TXT.inspect} -o #{ERRORCODES_TXT.inspect}" end file 'ext/errorcodes.def' => ['ext/errorcodes.rb', 'ext/errorcodes.txt'] do ruby 'ext/errorcodes.rb', 'ext/errorcodes.txt', 'ext/errorcodes.def' end file 'ext/pg_errors.c' => ['ext/errorcodes.def'] do # trigger compilation of changed errorcodes.def touch 'ext/pg_errors.c' end ruby-pg-0.17.0/Rakefile.cross000066400000000000000000000211161222421776500157720ustar00rootroot00000000000000#!/usr/bin/env rake require 'uri' require 'tempfile' require 'rbconfig' require 'rake/clean' require 'rake/extensiontask' require 'rake/extensioncompiler' require 'ostruct' MISCDIR = BASEDIR + 'misc' NUM_CPUS = if File.exist?('/proc/cpuinfo') File.read('/proc/cpuinfo').scan('processor').length elsif RUBY_PLATFORM.include?( 'darwin' ) `system_profiler SPHardwareDataType | grep 'Cores' | awk '{print $5}'`.chomp else 1 end class CrossLibrary < OpenStruct include Rake::DSL def initialize(for_platform, openssl_config) super() self.for_platform = for_platform self.openssl_config = openssl_config # Cross-compilation constants self.openssl_version = ENV['OPENSSL_VERSION'] || '1.0.1e' self.postgresql_version = ENV['POSTGRESQL_VERSION'] || '9.2.3' self.compile_home = Pathname( "./build" ).expand_path self.static_sourcesdir = compile_home + 'sources' self.static_builddir = compile_home + 'builds' + for_platform # Static OpenSSL build vars self.static_openssl_builddir = static_builddir + "openssl-#{openssl_version}" self.openssl_source_uri = URI( "http://www.openssl.org/source/openssl-#{openssl_version}.tar.gz" ) self.openssl_tarball = static_sourcesdir + File.basename( openssl_source_uri.path ) self.openssl_makefile = static_openssl_builddir + 'Makefile' self.libssleay32 = static_openssl_builddir + 'libssleay32.a' self.libeay32 = static_openssl_builddir + 'libeay32.a' self.openssl_patches = Rake::FileList[ (MISCDIR + "openssl-#{openssl_version}.*.patch").to_s ] # Static PostgreSQL build vars self.static_postgresql_builddir = static_builddir + "postgresql-#{postgresql_version}" self.postgresql_source_uri = begin uristring = "http://ftp.postgresql.org/pub/source/v%s/postgresql-%s.tar.bz2" % [ postgresql_version, postgresql_version ] URI( uristring ) end self.postgresql_tarball = static_sourcesdir + File.basename( postgresql_source_uri.path ) self.static_postgresql_srcdir = static_postgresql_builddir + 'src' self.static_postgresql_libdir = static_postgresql_srcdir + 'interfaces/libpq' self.static_postgresql_incdir = static_postgresql_srcdir + 'include' self.postgresql_global_makefile = static_postgresql_srcdir + 'Makefile.global' self.postgresql_shlib_makefile = static_postgresql_srcdir + 'Makefile.shlib' self.postgresql_shlib_mf_orig = static_postgresql_srcdir + 'Makefile.shlib.orig' self.postgresql_lib = static_postgresql_libdir + 'libpq.a' self.postgresql_patches = Rake::FileList[ (MISCDIR + "postgresql-#{postgresql_version}.*.patch").to_s ] # Use rake-compilers config.yml to determine the toolchain that was used # to build Ruby for this platform. self.host_platform = begin config_file = YAML.load_file(File.expand_path("~/.rake-compiler/config.yml")) _, rbfile = config_file.find{|key, fname| key.start_with?("rbconfig-#{for_platform}-") } IO.read(rbfile).match(/CONFIG\["CC"\] = "(.*)"/)[1].sub(/\-gcc/, '') rescue nil end # clean intermediate files and folders CLEAN.include( static_builddir.to_s ) ENV['RUBY_CC_VERSION'] ||= '1.8.7:1.9.3:2.0.0' def download(url, save_to) part = save_to+".part" sh "wget #{url.to_s.inspect} -O #{part.inspect} || curl #{url.to_s.inspect} -o #{part.inspect}" FileUtils.mv part, save_to end def run(*args) sh *args end ##################################################################### ### C R O S S - C O M P I L A T I O N - T A S K S ##################################################################### directory static_sourcesdir.to_s # # Static OpenSSL build tasks # directory static_openssl_builddir.to_s # openssl source file should be stored there file openssl_tarball => static_sourcesdir do |t| download( openssl_source_uri, t.name ) end # Extract the openssl builds file static_openssl_builddir => openssl_tarball do |t| puts "extracting %s to %s" % [ openssl_tarball, static_openssl_builddir.parent ] static_openssl_builddir.mkpath run 'tar', '-xzf', openssl_tarball.to_s, '-C', static_openssl_builddir.parent.to_s openssl_makefile.unlink if openssl_makefile.exist? openssl_patches.each do |patchfile| puts " applying patch #{patchfile}..." run 'patch', '-Np1', '-d', static_openssl_builddir.to_s, '-i', File.expand_path( patchfile, BASEDIR ) end end self.cmd_prelude = [ 'env', "CC=#{host_platform}-gcc", "CFLAGS=-DDSO_WIN32", "AR=#{host_platform}-ar", "RANLIB=#{host_platform}-ranlib" ] # generate the makefile in a clean build location file openssl_makefile => static_openssl_builddir do |t| Dir.chdir( static_openssl_builddir ) do cmd = cmd_prelude.dup cmd << "./Configure" << openssl_config run( *cmd ) end end desc "compile static openssl libraries" task :openssl_libs => [ libssleay32, libeay32 ] task :compile_static_openssl => openssl_makefile do |t| Dir.chdir( static_openssl_builddir ) do cmd = cmd_prelude.dup cmd << 'make' << "-j#{NUM_CPUS}" << 'build_libs' run( *cmd ) end end desc "compile static #{libeay32}" file libeay32 => :compile_static_openssl do |t| FileUtils.cp( static_openssl_builddir + 'libcrypto.a', libeay32.to_s ) end desc "compile static #{libssleay32}" file libssleay32 => :compile_static_openssl do |t| FileUtils.cp( static_openssl_builddir + 'libssl.a', libssleay32.to_s ) end # # Static PostgreSQL build tasks # directory static_postgresql_builddir.to_s # postgresql source file should be stored there file postgresql_tarball => static_sourcesdir do |t| download( postgresql_source_uri, t.name ) end # Extract the postgresql sources file static_postgresql_builddir => postgresql_tarball do |t| puts "extracting %s to %s" % [ postgresql_tarball, static_postgresql_builddir.parent ] static_postgresql_builddir.mkpath run 'tar', '-xjf', postgresql_tarball.to_s, '-C', static_postgresql_builddir.parent.to_s mv postgresql_shlib_makefile, postgresql_shlib_mf_orig postgresql_patches.each do |patchfile| puts " applying patch #{patchfile}..." run 'patch', '-Np1', '-d', static_postgresql_builddir.to_s, '-i', File.expand_path( patchfile, BASEDIR ) end end # generate the makefile in a clean build location file postgresql_global_makefile => [ static_postgresql_builddir, :openssl_libs ] do |t| options = [ "--target=#{host_platform}", "--host=#{host_platform}", '--with-openssl', '--without-zlib', '--disable-shared', ] Dir.chdir( static_postgresql_builddir ) do configure_path = static_postgresql_builddir + 'configure' cmd = [ configure_path.to_s, *options ] cmd << "CFLAGS=-L#{static_openssl_builddir}" cmd << "LDFLAGS=-L#{static_openssl_builddir}" cmd << "LDFLAGS_SL=-L#{static_openssl_builddir}" cmd << "LIBS=-lwsock32 -lgdi32" cmd << "CPPFLAGS=-I#{static_openssl_builddir}/include" run( *cmd ) end end # patch the Makefile.shlib -- depend on the build dir so it's only # rewritten if the tarball is re-extracted. file postgresql_shlib_makefile => postgresql_shlib_mf_orig do |t| tf = Tempfile.new( postgresql_shlib_makefile.basename.to_s ) postgresql_shlib_mf_orig.open( File::RDONLY ) do |ifh| ifh.each_line do |line| tf.print( line.sub(/^(\s*haslibarule\s*=\s*yes)/, "# \\1 ") ) end end tf.close FileUtils.mv( tf.path, t.name, :verbose => $puts ) end # make libpq.a task postgresql_lib => [ postgresql_global_makefile, postgresql_shlib_makefile ] do |t| Dir.chdir( postgresql_lib.dirname ) do sh 'make', "-j#{NUM_CPUS}", postgresql_lib.basename.to_s, 'PORTNAME=win32' end end #desc 'compile static libpg.a' task :static_libpq => postgresql_lib end end if File.exist?(File.expand_path("~/.rake-compiler/config.yml")) CrossLibraries = [ ['i386-mingw32', 'mingw'], ['x64-mingw32', 'mingw64'], ].map do |platform, openssl_config| CrossLibrary.new platform, openssl_config end else $stderr.puts "Cross-compilation disabled -- rake-compiler not properly installed" CrossLibraries = [] end desc 'cross compile pg for win32' task :cross do ENV['CROSS_COMPILING'] = 'yes' end task :cross => [ :mingw32, :static_libpq ] task :mingw32 do # Use Rake::ExtensionCompiler helpers to find the proper host unless Rake::ExtensionCompiler.mingw_host then warn "You need to install mingw32 cross compile functionality to be able to continue." warn "Please refer to your distribution/package manager documentation about installation." fail end end ruby-pg-0.17.0/ext/000077500000000000000000000000001222421776500137745ustar00rootroot00000000000000ruby-pg-0.17.0/ext/errorcodes.rb000077500000000000000000000023541222421776500164770ustar00rootroot00000000000000#!/usr/bin/env ruby def camelize(lower_case_and_underscored_word) lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } end ec_txt, ec_def = *ARGV File.open(ec_def, 'w') do |fd_def| fd_def.puts <params.name, #define DEFINE_PARAM_LIST3(type, name) \ type name, #define DEFINE_PARAM_DECL(type, name) \ type name; #define DEFINE_GVL_WRAPPER_STRUCT(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ struct gvl_wrapper_##name##_params { \ struct { \ FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_DECL) \ lastparamtype lastparamname; \ } params; \ when_non_void( rettype retval; ) \ }; #define DEFINE_GVL_SKELETON(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ static void * gvl_##name##_skeleton( void *data ){ \ struct gvl_wrapper_##name##_params *p = (struct gvl_wrapper_##name##_params*)data; \ when_non_void( p->retval = ) \ name( FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST2) p->params.lastparamname ); \ return NULL; \ } #if defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL) #define DEFINE_GVL_STUB(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ rettype gvl_##name(FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST3) lastparamtype lastparamname){ \ struct gvl_wrapper_##name##_params params = { \ {FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST1) lastparamname}, when_non_void((rettype)0) \ }; \ rb_thread_call_without_gvl(gvl_##name##_skeleton, ¶ms, cancel_params); \ when_non_void( return params.retval; ) \ } #else #define DEFINE_GVL_STUB(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ rettype gvl_##name(FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST3) lastparamtype lastparamname){ \ return name( FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST1) lastparamname ); \ } #endif #define DEFINE_GVL_STUB_DECL(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ rettype gvl_##name(FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST3) lastparamtype lastparamname); #define DEFINE_GVLCB_SKELETON(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ static void * gvl_##name##_skeleton( void *data ){ \ struct gvl_wrapper_##name##_params *p = (struct gvl_wrapper_##name##_params*)data; \ when_non_void( p->retval = ) \ name( FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST2) p->params.lastparamname ); \ return NULL; \ } #if defined(HAVE_RB_THREAD_CALL_WITH_GVL) #define DEFINE_GVLCB_STUB(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ rettype gvl_##name(FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST3) lastparamtype lastparamname){ \ struct gvl_wrapper_##name##_params params = { \ {FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST1) lastparamname}, when_non_void((rettype)0) \ }; \ rb_thread_call_with_gvl(gvl_##name##_skeleton, ¶ms); \ when_non_void( return params.retval; ) \ } #else #define DEFINE_GVLCB_STUB(name, cancel_params, when_non_void, rettype, lastparamtype, lastparamname) \ rettype gvl_##name(FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST3) lastparamtype lastparamname){ \ return name( FOR_EACH_PARAM_OF_##name(DEFINE_PARAM_LIST1) lastparamname ); \ } #endif #define GVL_TYPE_VOID(string) #define GVL_TYPE_NONVOID(string) string #define GVL_CANCELABLE ubf_cancel_running_command, conn #define GVL_NONCANCELABLE RUBY_UBF_IO, 0 /* * Definitions of blocking functions and their parameters */ #define FOR_EACH_PARAM_OF_PQconnectdb(param) #define FOR_EACH_PARAM_OF_PQconnectStart(param) #define FOR_EACH_PARAM_OF_PQconnectPoll(param) #define FOR_EACH_PARAM_OF_PQreset(param) #define FOR_EACH_PARAM_OF_PQresetStart(param) #define FOR_EACH_PARAM_OF_PQresetPoll(param) #define FOR_EACH_PARAM_OF_PQexec(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQexecParams(param) \ param(PGconn *, conn) \ param(const char *, command) \ param(int, nParams) \ param(const Oid *, paramTypes) \ param(const char * const *, paramValues) \ param(const int *, paramLengths) \ param(const int *, paramFormats) #define FOR_EACH_PARAM_OF_PQexecPrepared(param) \ param(PGconn *, conn) \ param(const char *, stmtName) \ param(int, nParams) \ param(const char * const *, paramValues) \ param(const int *, paramLengths) \ param(const int *, paramFormats) #define FOR_EACH_PARAM_OF_PQprepare(param) \ param(PGconn *, conn) \ param(const char *, stmtName) \ param(const char *, query) \ param(int, nParams) #define FOR_EACH_PARAM_OF_PQdescribePrepared(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQdescribePortal(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQgetResult(param) #define FOR_EACH_PARAM_OF_PQputCopyData(param) \ param(PGconn *, conn) \ param(const char *, buffer) #define FOR_EACH_PARAM_OF_PQputCopyEnd(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQgetCopyData(param) \ param(PGconn *, conn) \ param(char **, buffer) #define FOR_EACH_PARAM_OF_PQnotifies(param) #define FOR_EACH_PARAM_OF_PQsendQuery(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQsendQueryParams(param) \ param(PGconn *, conn) \ param(const char *, command) \ param(int, nParams) \ param(const Oid *, paramTypes) \ param(const char *const *, paramValues) \ param(const int *, paramLengths) \ param(const int *, paramFormats) #define FOR_EACH_PARAM_OF_PQsendPrepare(param) \ param(PGconn *, conn) \ param(const char *, stmtName) \ param(const char *, query) \ param(int, nParams) #define FOR_EACH_PARAM_OF_PQsendQueryPrepared(param) \ param(PGconn *, conn) \ param(const char *, stmtName) \ param(int, nParams) \ param(const char *const *, paramValues) \ param(const int *, paramLengths) \ param(const int *, paramFormats) #define FOR_EACH_PARAM_OF_PQsendDescribePrepared(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQsendDescribePortal(param) \ param(PGconn *, conn) #define FOR_EACH_PARAM_OF_PQisBusy(param) /* function( name, cancel, void_or_nonvoid, returntype, lastparamtype, lastparamname ) */ #define FOR_EACH_BLOCKING_FUNCTION(function) \ function(PQconnectdb, GVL_NONCANCELABLE, GVL_TYPE_NONVOID, PGconn *, const char *, conninfo) \ function(PQconnectStart, GVL_NONCANCELABLE, GVL_TYPE_NONVOID, PGconn *, const char *, conninfo) \ function(PQconnectPoll, GVL_CANCELABLE, GVL_TYPE_NONVOID, PostgresPollingStatusType, PGconn *, conn) \ function(PQreset, GVL_CANCELABLE, GVL_TYPE_VOID, void, PGconn *, conn) \ function(PQresetStart, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, PGconn *, conn) \ function(PQresetPoll, GVL_CANCELABLE, GVL_TYPE_NONVOID, PostgresPollingStatusType, PGconn *, conn) \ function(PQexec, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, const char *, command) \ function(PQexecParams, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, int, resultFormat) \ function(PQexecPrepared, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, int, resultFormat) \ function(PQprepare, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, const Oid *, paramTypes) \ function(PQdescribePrepared, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, const char *, stmtName) \ function(PQdescribePortal, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, const char *, portalName) \ function(PQgetResult, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGresult *, PGconn *, conn) \ function(PQputCopyData, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, int, nbytes) \ function(PQputCopyEnd, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, const char *, errormsg) \ function(PQgetCopyData, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, int, async) \ function(PQnotifies, GVL_CANCELABLE, GVL_TYPE_NONVOID, PGnotify *, PGconn *, conn) \ function(PQsendQuery, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, const char *, query) \ function(PQsendQueryParams, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, int, resultFormat) \ function(PQsendPrepare, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, const Oid *, paramTypes) \ function(PQsendQueryPrepared, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, int, resultFormat) \ function(PQsendDescribePrepared, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, const char *, stmt) \ function(PQsendDescribePortal, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, const char *, portal) \ function(PQisBusy, GVL_CANCELABLE, GVL_TYPE_NONVOID, int, PGconn *, conn); FOR_EACH_BLOCKING_FUNCTION( DEFINE_GVL_STUB_DECL ); /* * Definitions of callback functions and their parameters */ #define FOR_EACH_PARAM_OF_notice_processor_proxy(param) \ param(void *, arg) #define FOR_EACH_PARAM_OF_notice_receiver_proxy(param) \ param(void *, arg) /* function( name, cancel, void_or_nonvoid, returntype, lastparamtype, lastparamname ) */ #define FOR_EACH_CALLBACK_FUNCTION(function) \ function(notice_processor_proxy,, GVL_TYPE_VOID, void, const char *, message) \ function(notice_receiver_proxy,, GVL_TYPE_VOID, void, const PGresult *, result) \ FOR_EACH_CALLBACK_FUNCTION( DEFINE_GVL_STUB_DECL ); #endif /* end __gvl_wrappers_h */ ruby-pg-0.17.0/ext/pg.c000066400000000000000000000511511222421776500145510ustar00rootroot00000000000000/* * pg.c - Toplevel extension * $Id$ * * Author/s: * * - Jeff Davis * - Guy Decoux (ts) * - Michael Granger * - Dave Lee * - Eiji Matsumoto * - Yukihiro Matsumoto * - Noboru Saitou * * See Contributors.rdoc for the many additional fine people that have contributed * to this library over the years. * * Copyright (c) 1997-2012 by the authors. * * You may redistribute this software under the same terms as Ruby itself; see * http://www.ruby-lang.org/en/LICENSE.txt or the LICENSE file in the source * for details. * * Portions of the code are from the PostgreSQL project, and are distributed * under the terms of the PostgreSQL license, included in the file "POSTGRES". * * Portions copyright LAIKA, Inc. * * * The following functions are part of libpq, but not available from ruby-pg, * because they are deprecated, obsolete, or generally not useful: * * - PQfreemem -- unnecessary: copied to ruby object, then freed. Ruby object's * memory is freed when it is garbage collected. * - PQbinaryTuples -- better to use PQfformat * - PQprint -- not very useful * - PQsetdb -- not very useful * - PQoidStatus -- deprecated, use PQoidValue * - PQrequestCancel -- deprecated, use PQcancel * - PQfn -- use a prepared statement instead * - PQgetline -- deprecated, use PQgetCopyData * - PQgetlineAsync -- deprecated, use PQgetCopyData * - PQputline -- deprecated, use PQputCopyData * - PQputnbytes -- deprecated, use PQputCopyData * - PQendcopy -- deprecated, use PQputCopyEnd */ #include "pg.h" VALUE rb_mPG; VALUE rb_mPGconstants; /* * Document-class: PG::Error * * This is the exception class raised when an error is returned from * a libpq API call. * * The attributes +connection+ and +result+ are set to the connection * object and result set object, respectively. * * If the connection object or result set object is not available from * the context in which the error was encountered, it is +nil+. */ /* * M17n functions */ #ifdef M17N_SUPPORTED /** * The mapping from canonical encoding names in PostgreSQL to ones in Ruby. */ const char * const (pg_enc_pg2ruby_mapping[][2]) = { {"BIG5", "Big5" }, {"EUC_CN", "GB2312" }, {"EUC_JP", "EUC-JP" }, {"EUC_JIS_2004", "EUC-JP" }, {"EUC_KR", "EUC-KR" }, {"EUC_TW", "EUC-TW" }, {"GB18030", "GB18030" }, {"GBK", "GBK" }, {"ISO_8859_5", "ISO-8859-5" }, {"ISO_8859_6", "ISO-8859-6" }, {"ISO_8859_7", "ISO-8859-7" }, {"ISO_8859_8", "ISO-8859-8" }, /* {"JOHAB", "JOHAB" }, dummy */ {"KOI8", "KOI8-R" }, {"KOI8R", "KOI8-R" }, {"KOI8U", "KOI8-U" }, {"LATIN1", "ISO-8859-1" }, {"LATIN2", "ISO-8859-2" }, {"LATIN3", "ISO-8859-3" }, {"LATIN4", "ISO-8859-4" }, {"LATIN5", "ISO-8859-9" }, {"LATIN6", "ISO-8859-10" }, {"LATIN7", "ISO-8859-13" }, {"LATIN8", "ISO-8859-14" }, {"LATIN9", "ISO-8859-15" }, {"LATIN10", "ISO-8859-16" }, {"MULE_INTERNAL", "Emacs-Mule" }, {"SJIS", "Windows-31J" }, {"SHIFT_JIS_2004","Windows-31J" }, /* {"SQL_ASCII", NULL }, special case*/ {"UHC", "CP949" }, {"UTF8", "UTF-8" }, {"WIN866", "IBM866" }, {"WIN874", "Windows-874" }, {"WIN1250", "Windows-1250"}, {"WIN1251", "Windows-1251"}, {"WIN1252", "Windows-1252"}, {"WIN1253", "Windows-1253"}, {"WIN1254", "Windows-1254"}, {"WIN1255", "Windows-1255"}, {"WIN1256", "Windows-1256"}, {"WIN1257", "Windows-1257"}, {"WIN1258", "Windows-1258"} }; /* * A cache of mapping from PostgreSQL's encoding indices to Ruby's rb_encoding*s. */ static struct st_table *enc_pg2ruby; static ID s_id_index; /* * Get the index of encoding +val+. * :FIXME: Look into replacing this with rb_enc_get_index() since 1.9.1 isn't really * used anymore. */ int pg_enc_get_index(VALUE val) { int i = ENCODING_GET_INLINED(val); if (i == ENCODING_INLINE_MAX) { VALUE iv = rb_ivar_get(val, s_id_index); i = NUM2INT(iv); } return i; } /* * Look up the JOHAB encoding, creating it as a dummy encoding if it's not * already defined. */ static rb_encoding * pg_find_or_create_johab(void) { static const char * const aliases[] = { "JOHAB", "Windows-1361", "CP1361" }; int enc_index; size_t i; for (i = 0; i < sizeof(aliases)/sizeof(aliases[0]); ++i) { enc_index = rb_enc_find_index(aliases[i]); if (enc_index > 0) return rb_enc_from_index(enc_index); } enc_index = rb_define_dummy_encoding(aliases[0]); for (i = 1; i < sizeof(aliases)/sizeof(aliases[0]); ++i) { ENC_ALIAS(aliases[i], aliases[0]); } return rb_enc_from_index(enc_index); } /* * Return the given PostgreSQL encoding ID as an rb_encoding. * * - returns NULL if the client encoding is 'SQL_ASCII'. * - returns ASCII-8BIT if the client encoding is unknown. */ rb_encoding * pg_get_pg_encoding_as_rb_encoding( int enc_id ) { rb_encoding *enc; /* Use the cached value if it exists */ if ( st_lookup(enc_pg2ruby, (st_data_t)enc_id, (st_data_t*)&enc) ) { return enc; } else { const char *name = pg_encoding_to_char( enc_id ); enc = pg_get_pg_encname_as_rb_encoding( name ); st_insert( enc_pg2ruby, (st_data_t)enc_id, (st_data_t)enc ); return enc; } } /* * Return the given PostgreSQL encoding name as an rb_encoding. */ rb_encoding * pg_get_pg_encname_as_rb_encoding( const char *pg_encname ) { size_t i; /* Trying looking it up in the conversion table */ for ( i = 0; i < sizeof(pg_enc_pg2ruby_mapping)/sizeof(pg_enc_pg2ruby_mapping[0]); ++i ) { if ( strcmp(pg_encname, pg_enc_pg2ruby_mapping[i][0]) == 0 ) return rb_enc_find( pg_enc_pg2ruby_mapping[i][1] ); } /* JOHAB isn't a builtin encoding, so make up a dummy encoding if it's seen */ if ( strncmp(pg_encname, "JOHAB", 5) == 0 ) return pg_find_or_create_johab(); /* Fallthrough to ASCII-8BIT */ return rb_ascii8bit_encoding(); } /* * Get the client encoding of the specified connection handle and return it as a rb_encoding. */ rb_encoding * pg_conn_enc_get( PGconn *conn ) { int enc_id = PQclientEncoding( conn ); return pg_get_pg_encoding_as_rb_encoding( enc_id ); } /* * Returns the given rb_encoding as the equivalent PostgreSQL encoding string. */ const char * pg_get_rb_encoding_as_pg_encoding( rb_encoding *enc ) { const char *rb_encname = rb_enc_name( enc ); const char *encname = NULL; size_t i; for (i = 0; i < sizeof(pg_enc_pg2ruby_mapping)/sizeof(pg_enc_pg2ruby_mapping[0]); ++i) { if (strcmp(rb_encname, pg_enc_pg2ruby_mapping[i][1]) == 0) { encname = pg_enc_pg2ruby_mapping[i][0]; } } if ( !encname ) encname = "SQL_ASCII"; return encname; } #endif /* M17N_SUPPORTED */ /************************************************************************** * Module Methods **************************************************************************/ #ifdef HAVE_PQLIBVERSION /* * call-seq: * PG.library_version -> Integer * * Get the version of the libpq library in use. The number is formed by * converting the major, minor, and revision numbers into two-decimal- * digit numbers and appending them together. * For example, version 7.4.2 will be returned as 70402, and version * 8.1 will be returned as 80100 (leading zeroes are not shown). Zero * is returned if the connection is bad. */ static VALUE pg_s_library_version(VALUE self) { UNUSED( self ); return INT2NUM(PQlibVersion()); } #endif /* * call-seq: * PG.isthreadsafe -> Boolean * PG.is_threadsafe? -> Boolean * PG.threadsafe? -> Boolean * * Returns +true+ if libpq is thread-safe, +false+ otherwise. */ static VALUE pg_s_threadsafe_p(VALUE self) { UNUSED( self ); return PQisthreadsafe() ? Qtrue : Qfalse; } /************************************************************************** * Initializer **************************************************************************/ void Init_pg_ext() { rb_mPG = rb_define_module( "PG" ); rb_mPGconstants = rb_define_module_under( rb_mPG, "Constants" ); /************************* * PG module methods *************************/ #ifdef HAVE_PQLIBVERSION rb_define_singleton_method( rb_mPG, "library_version", pg_s_library_version, 0 ); #endif rb_define_singleton_method( rb_mPG, "isthreadsafe", pg_s_threadsafe_p, 0 ); SINGLETON_ALIAS( rb_mPG, "is_threadsafe?", "isthreadsafe" ); SINGLETON_ALIAS( rb_mPG, "threadsafe?", "isthreadsafe" ); /****** PG::Connection CLASS CONSTANTS: Connection Status ******/ /* Connection succeeded */ rb_define_const(rb_mPGconstants, "CONNECTION_OK", INT2FIX(CONNECTION_OK)); /* Connection failed */ rb_define_const(rb_mPGconstants, "CONNECTION_BAD", INT2FIX(CONNECTION_BAD)); /****** PG::Connection CLASS CONSTANTS: Nonblocking connection status ******/ /* Waiting for connection to be made. */ rb_define_const(rb_mPGconstants, "CONNECTION_STARTED", INT2FIX(CONNECTION_STARTED)); /* Connection OK; waiting to send. */ rb_define_const(rb_mPGconstants, "CONNECTION_MADE", INT2FIX(CONNECTION_MADE)); /* Waiting for a response from the server. */ rb_define_const(rb_mPGconstants, "CONNECTION_AWAITING_RESPONSE", INT2FIX(CONNECTION_AWAITING_RESPONSE)); /* Received authentication; waiting for backend start-up to finish. */ rb_define_const(rb_mPGconstants, "CONNECTION_AUTH_OK", INT2FIX(CONNECTION_AUTH_OK)); /* Negotiating SSL encryption. */ rb_define_const(rb_mPGconstants, "CONNECTION_SSL_STARTUP", INT2FIX(CONNECTION_SSL_STARTUP)); /* Negotiating environment-driven parameter settings. */ rb_define_const(rb_mPGconstants, "CONNECTION_SETENV", INT2FIX(CONNECTION_SETENV)); /* Internal state: connect() needed. */ rb_define_const(rb_mPGconstants, "CONNECTION_NEEDED", INT2FIX(CONNECTION_NEEDED)); /****** PG::Connection CLASS CONSTANTS: Nonblocking connection polling status ******/ /* Async connection is waiting to read */ rb_define_const(rb_mPGconstants, "PGRES_POLLING_READING", INT2FIX(PGRES_POLLING_READING)); /* Async connection is waiting to write */ rb_define_const(rb_mPGconstants, "PGRES_POLLING_WRITING", INT2FIX(PGRES_POLLING_WRITING)); /* Async connection failed or was reset */ rb_define_const(rb_mPGconstants, "PGRES_POLLING_FAILED", INT2FIX(PGRES_POLLING_FAILED)); /* Async connection succeeded */ rb_define_const(rb_mPGconstants, "PGRES_POLLING_OK", INT2FIX(PGRES_POLLING_OK)); /****** PG::Connection CLASS CONSTANTS: Transaction Status ******/ /* Transaction is currently idle (#transaction_status) */ rb_define_const(rb_mPGconstants, "PQTRANS_IDLE", INT2FIX(PQTRANS_IDLE)); /* Transaction is currently active; query has been sent to the server, but not yet completed. (#transaction_status) */ rb_define_const(rb_mPGconstants, "PQTRANS_ACTIVE", INT2FIX(PQTRANS_ACTIVE)); /* Transaction is currently idle, in a valid transaction block (#transaction_status) */ rb_define_const(rb_mPGconstants, "PQTRANS_INTRANS", INT2FIX(PQTRANS_INTRANS)); /* Transaction is currently idle, in a failed transaction block (#transaction_status) */ rb_define_const(rb_mPGconstants, "PQTRANS_INERROR", INT2FIX(PQTRANS_INERROR)); /* Transaction's connection is bad (#transaction_status) */ rb_define_const(rb_mPGconstants, "PQTRANS_UNKNOWN", INT2FIX(PQTRANS_UNKNOWN)); /****** PG::Connection CLASS CONSTANTS: Error Verbosity ******/ /* Terse error verbosity level (#set_error_verbosity) */ rb_define_const(rb_mPGconstants, "PQERRORS_TERSE", INT2FIX(PQERRORS_TERSE)); /* Default error verbosity level (#set_error_verbosity) */ rb_define_const(rb_mPGconstants, "PQERRORS_DEFAULT", INT2FIX(PQERRORS_DEFAULT)); /* Verbose error verbosity level (#set_error_verbosity) */ rb_define_const(rb_mPGconstants, "PQERRORS_VERBOSE", INT2FIX(PQERRORS_VERBOSE)); #ifdef HAVE_PQPING /****** PG::Connection CLASS CONSTANTS: Check Server Status ******/ /* Server is accepting connections. */ rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK)); /* Server is alive but rejecting connections. */ rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT)); /* Could not establish connection. */ rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE)); /* Connection not attempted (bad params). */ rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT)); #endif /****** PG::Connection CLASS CONSTANTS: Large Objects ******/ /* Flag for #lo_creat, #lo_open -- open for writing */ rb_define_const(rb_mPGconstants, "INV_WRITE", INT2FIX(INV_WRITE)); /* Flag for #lo_creat, #lo_open -- open for reading */ rb_define_const(rb_mPGconstants, "INV_READ", INT2FIX(INV_READ)); /* Flag for #lo_lseek -- seek from object start */ rb_define_const(rb_mPGconstants, "SEEK_SET", INT2FIX(SEEK_SET)); /* Flag for #lo_lseek -- seek from current position */ rb_define_const(rb_mPGconstants, "SEEK_CUR", INT2FIX(SEEK_CUR)); /* Flag for #lo_lseek -- seek from object end */ rb_define_const(rb_mPGconstants, "SEEK_END", INT2FIX(SEEK_END)); /****** PG::Result CONSTANTS: result status ******/ /* #result_status constant: The string sent to the server was empty. */ rb_define_const(rb_mPGconstants, "PGRES_EMPTY_QUERY", INT2FIX(PGRES_EMPTY_QUERY)); /* #result_status constant: Successful completion of a command returning no data. */ rb_define_const(rb_mPGconstants, "PGRES_COMMAND_OK", INT2FIX(PGRES_COMMAND_OK)); /* #result_status constant: Successful completion of a command returning data (such as a SELECT or SHOW). */ rb_define_const(rb_mPGconstants, "PGRES_TUPLES_OK", INT2FIX(PGRES_TUPLES_OK)); /* #result_status constant: Copy Out (from server) data transfer started. */ rb_define_const(rb_mPGconstants, "PGRES_COPY_OUT", INT2FIX(PGRES_COPY_OUT)); /* #result_status constant: Copy In (to server) data transfer started. */ rb_define_const(rb_mPGconstants, "PGRES_COPY_IN", INT2FIX(PGRES_COPY_IN)); /* #result_status constant: The server’s response was not understood. */ rb_define_const(rb_mPGconstants, "PGRES_BAD_RESPONSE", INT2FIX(PGRES_BAD_RESPONSE)); /* #result_status constant: A nonfatal error (a notice or warning) occurred. */ rb_define_const(rb_mPGconstants, "PGRES_NONFATAL_ERROR",INT2FIX(PGRES_NONFATAL_ERROR)); /* #result_status constant: A fatal error occurred. */ rb_define_const(rb_mPGconstants, "PGRES_FATAL_ERROR", INT2FIX(PGRES_FATAL_ERROR)); /* #result_status constant: Copy In/Out data transfer in progress. */ #ifdef HAVE_CONST_PGRES_COPY_BOTH rb_define_const(rb_mPGconstants, "PGRES_COPY_BOTH", INT2FIX(PGRES_COPY_BOTH)); #endif /* #result_status constant: Single tuple from larger resultset. */ #ifdef HAVE_CONST_PGRES_SINGLE_TUPLE rb_define_const(rb_mPGconstants, "PGRES_SINGLE_TUPLE", INT2FIX(PGRES_SINGLE_TUPLE)); #endif /****** Result CONSTANTS: result error field codes ******/ /* #result_error_field argument constant: The severity; the field contents * are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, * DEBUG, INFO, or LOG (in a notice message), or a localized translation * of one of these. Always present. */ rb_define_const(rb_mPGconstants, "PG_DIAG_SEVERITY", INT2FIX(PG_DIAG_SEVERITY)); /* #result_error_field argument constant: The SQLSTATE code for the * error. The SQLSTATE code identies the type of error that has occurred; * it can be used by front-end applications to perform specic operations * (such as er- ror handling) in response to a particular database * error. For a list of the possible SQLSTATE codes, see Appendix A. * This eld is not localizable, and is always present. */ rb_define_const(rb_mPGconstants, "PG_DIAG_SQLSTATE", INT2FIX(PG_DIAG_SQLSTATE)); /* #result_error_field argument constant: The primary human-readable * error message (typically one line). Always present. */ rb_define_const(rb_mPGconstants, "PG_DIAG_MESSAGE_PRIMARY", INT2FIX(PG_DIAG_MESSAGE_PRIMARY)); /* #result_error_field argument constant: Detail: an optional secondary * error message carrying more detail about the problem. Might run to * multiple lines. */ rb_define_const(rb_mPGconstants, "PG_DIAG_MESSAGE_DETAIL", INT2FIX(PG_DIAG_MESSAGE_DETAIL)); /* #result_error_field argument constant: Hint: an optional suggestion * what to do about the problem. This is intended to differ from detail * in that it offers advice (potentially inappropriate) rather than * hard facts. Might run to multiple lines. */ rb_define_const(rb_mPGconstants, "PG_DIAG_MESSAGE_HINT", INT2FIX(PG_DIAG_MESSAGE_HINT)); /* #result_error_field argument constant: A string containing a decimal * integer indicating an error cursor position as an index into the * original statement string. The rst character has index 1, and * positions are measured in characters not bytes. */ rb_define_const(rb_mPGconstants, "PG_DIAG_STATEMENT_POSITION", INT2FIX(PG_DIAG_STATEMENT_POSITION)); /* #result_error_field argument constant: This is dened the same as * the PG_DIAG_STATEMENT_POSITION eld, but it is used when the cursor * position refers to an internally generated command rather than the * one submitted by the client. The PG_DIAG_INTERNAL_QUERY eld will * always appear when this eld appears. */ rb_define_const(rb_mPGconstants, "PG_DIAG_INTERNAL_POSITION", INT2FIX(PG_DIAG_INTERNAL_POSITION)); /* #result_error_field argument constant: The text of a failed * internally-generated command. This could be, for example, a SQL * query issued by a PL/pgSQL function. */ rb_define_const(rb_mPGconstants, "PG_DIAG_INTERNAL_QUERY", INT2FIX(PG_DIAG_INTERNAL_QUERY)); /* #result_error_field argument constant: An indication of the context * in which the error occurred. Presently this includes a call stack * traceback of active procedural language functions and internally-generated * queries. The trace is one entry per line, most recent rst. */ rb_define_const(rb_mPGconstants, "PG_DIAG_CONTEXT", INT2FIX(PG_DIAG_CONTEXT)); /* #result_error_field argument constant: The le name of the source-code * location where the error was reported. */ rb_define_const(rb_mPGconstants, "PG_DIAG_SOURCE_FILE", INT2FIX(PG_DIAG_SOURCE_FILE)); /* #result_error_field argument constant: The line number of the * source-code location where the error was reported. */ rb_define_const(rb_mPGconstants, "PG_DIAG_SOURCE_LINE", INT2FIX(PG_DIAG_SOURCE_LINE)); /* #result_error_field argument constant: The name of the source-code * function reporting the error. */ rb_define_const(rb_mPGconstants, "PG_DIAG_SOURCE_FUNCTION", INT2FIX(PG_DIAG_SOURCE_FUNCTION)); #ifdef HAVE_CONST_PG_DIAG_TABLE_NAME /* #result_error_field argument constant: If the error was associated with a * specific database object, the name of the schema containing that object, if any. */ rb_define_const(rb_mPGconstants, "PG_DIAG_SCHEMA_NAME", INT2FIX(PG_DIAG_SCHEMA_NAME)); /* #result_error_field argument constant: If the error was associated with a *specific table, the name of the table. (When this field is present, the schema name * field provides the name of the table's schema.) */ rb_define_const(rb_mPGconstants, "PG_DIAG_TABLE_NAME", INT2FIX(PG_DIAG_TABLE_NAME)); /* #result_error_field argument constant: If the error was associated with a * specific table column, the name of the column. (When this field is present, the * schema and table name fields identify the table.) */ rb_define_const(rb_mPGconstants, "PG_DIAG_COLUMN_NAME", INT2FIX(PG_DIAG_COLUMN_NAME)); /* #result_error_field argument constant: If the error was associated with a * specific datatype, the name of the datatype. (When this field is present, the * schema name field provides the name of the datatype's schema.) */ rb_define_const(rb_mPGconstants, "PG_DIAG_DATATYPE_NAME", INT2FIX(PG_DIAG_DATATYPE_NAME)); /* #result_error_field argument constant: If the error was associated with a * specific constraint, the name of the constraint. The table or domain that the * constraint belongs to is reported using the fields listed above. (For this * purpose, indexes are treated as constraints, even if they weren't created with * constraint syntax.) */ rb_define_const(rb_mPGconstants, "PG_DIAG_CONSTRAINT_NAME", INT2FIX(PG_DIAG_CONSTRAINT_NAME)); #endif /* Invalid OID constant */ rb_define_const(rb_mPGconstants, "INVALID_OID", INT2FIX(InvalidOid)); rb_define_const(rb_mPGconstants, "InvalidOid", INT2FIX(InvalidOid)); /* Add the constants to the toplevel namespace */ rb_include_module( rb_mPG, rb_mPGconstants ); #ifdef M17N_SUPPORTED enc_pg2ruby = st_init_numtable(); s_id_index = rb_intern("@encoding"); #endif /* Initialize the main extension classes */ init_pg_connection(); init_pg_result(); init_pg_errors(); } ruby-pg-0.17.0/ext/pg.h000066400000000000000000000107621222421776500145610ustar00rootroot00000000000000#ifndef __pg_h #define __pg_h #ifdef RUBY_EXTCONF_H # include RUBY_EXTCONF_H #endif /* System headers */ #include #include #include #if defined(HAVE_UNISTD_H) && !defined(_WIN32) # include #endif /* HAVE_UNISTD_H */ /* Ruby headers */ #include "ruby.h" #ifdef HAVE_RUBY_ST_H # include "ruby/st.h" #elif HAVE_ST_H # include "st.h" #endif #if defined(HAVE_RUBY_ENCODING_H) && HAVE_RUBY_ENCODING_H # include "ruby/encoding.h" # define M17N_SUPPORTED # define ASSOCIATE_INDEX( obj, index_holder ) rb_enc_associate_index((obj), pg_enc_get_index((index_holder))) # ifdef HAVE_RB_ENCDB_ALIAS extern int rb_encdb_alias(const char *, const char *); # define ENC_ALIAS(name, orig) rb_encdb_alias((name), (orig)) # elif HAVE_RB_ENC_ALIAS extern int rb_enc_alias(const char *, const char *); # define ENC_ALIAS(name, orig) rb_enc_alias((name), (orig)) # else extern int rb_enc_alias(const char *alias, const char *orig); /* declaration missing in Ruby 1.9.1 */ # define ENC_ALIAS(name, orig) rb_enc_alias((name), (orig)) # endif #else # define ASSOCIATE_INDEX( obj, index_holder ) /* nothing */ #endif #if RUBY_VM != 1 # define RUBY_18_COMPAT #endif #ifndef RARRAY_LEN # define RARRAY_LEN(x) RARRAY((x))->len #endif /* RARRAY_LEN */ #ifndef RSTRING_LEN # define RSTRING_LEN(x) RSTRING((x))->len #endif /* RSTRING_LEN */ #ifndef RSTRING_PTR # define RSTRING_PTR(x) RSTRING((x))->ptr #endif /* RSTRING_PTR */ #ifndef StringValuePtr # define StringValuePtr(x) STR2CSTR(x) #endif /* StringValuePtr */ #ifdef RUBY_18_COMPAT # define rb_io_stdio_file GetWriteFile # include "rubyio.h" #else # include "ruby/io.h" #endif #ifndef timeradd #define timeradd(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((result)->tv_usec >= 1000000L) { \ ++(result)->tv_sec; \ (result)->tv_usec -= 1000000L; \ } \ } while (0) #endif #ifndef timersub #define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000L; \ } \ } while (0) #endif /* PostgreSQL headers */ #include "libpq-fe.h" #include "libpq/libpq-fs.h" /* large-object interface */ #include "pg_config_manual.h" #if defined(_WIN32) # include __declspec(dllexport) typedef long suseconds_t; #endif #include "gvl_wrappers.h" /*************************************************************************** * Globals **************************************************************************/ extern VALUE rb_mPG; extern VALUE rb_ePGerror; extern VALUE rb_eServerError; extern VALUE rb_eUnableToSend; extern VALUE rb_eConnectionBad; extern VALUE rb_mPGconstants; extern VALUE rb_cPGconn; extern VALUE rb_cPGresult; extern VALUE rb_hErrors; /*************************************************************************** * MACROS **************************************************************************/ #define UNUSED(x) ((void)(x)) #define SINGLETON_ALIAS(klass,new,old) rb_define_alias(rb_singleton_class((klass)),(new),(old)) /*************************************************************************** * PROTOTYPES **************************************************************************/ void Init_pg_ext _(( void )); void init_pg_connection _(( void )); void init_pg_result _(( void )); void init_pg_errors _(( void )); VALUE lookup_error_class _(( const char *sqlstate )); PGconn *pg_get_pgconn _(( VALUE )); VALUE pg_new_result _(( PGresult *, VALUE )); VALUE pg_result_check _(( VALUE )); VALUE pg_result_clear _(( VALUE )); #ifdef M17N_SUPPORTED rb_encoding * pg_get_pg_encoding_as_rb_encoding _(( int )); rb_encoding * pg_get_pg_encname_as_rb_encoding _(( const char * )); const char * pg_get_rb_encoding_as_pg_encoding _(( rb_encoding * )); int pg_enc_get_index _(( VALUE )); rb_encoding *pg_conn_enc_get _(( PGconn * )); #endif /* M17N_SUPPORTED */ void notice_receiver_proxy(void *arg, const PGresult *result); void notice_processor_proxy(void *arg, const char *message); #endif /* end __pg_h */ ruby-pg-0.17.0/ext/pg_connection.c000066400000000000000000003011221222421776500167640ustar00rootroot00000000000000/* * pg_connection.c - PG::Connection class extension * $Id$ * */ #include "pg.h" VALUE rb_cPGconn; static PQnoticeReceiver default_notice_receiver = NULL; static PQnoticeProcessor default_notice_processor = NULL; static PGconn *pgconn_check( VALUE ); static VALUE pgconn_finish( VALUE ); #ifdef M17N_SUPPORTED static VALUE pgconn_set_default_encoding( VALUE self ); #endif #ifndef HAVE_RB_THREAD_FD_SELECT #define rb_fdset_t fd_set #define rb_fd_init(f) #define rb_fd_zero(f) FD_ZERO(f) #define rb_fd_set(n, f) FD_SET(n, f) #define rb_fd_term(f) #define rb_thread_fd_select rb_thread_select #endif /* * Global functions */ /* * Fetch the data pointer and check it for sanity. */ PGconn * pg_get_pgconn( VALUE self ) { PGconn *conn = pgconn_check( self ); if ( !conn ) rb_raise( rb_eConnectionBad, "connection is closed" ); return conn; } /* * Close the associated socket IO object if there is one. */ void pgconn_close_socket_io( VALUE self ) { VALUE socket_io = rb_iv_get( self, "@socket_io" ); if ( RTEST(socket_io) ) { #if defined(_WIN32) && defined(HAVE_RB_W32_WRAP_IO_HANDLE) int ruby_sd = NUM2INT(rb_funcall( socket_io, rb_intern("fileno"), 0 )); if( rb_w32_unwrap_io_handle(ruby_sd) ){ rb_raise(rb_eConnectionBad, "Could not unwrap win32 socket handle"); } #endif rb_funcall( socket_io, rb_intern("close"), 0 ); } rb_iv_set( self, "@socket_io", Qnil ); } /* * Allocation/ */ /* * Object validity checker. Returns the data pointer. */ static PGconn * pgconn_check( VALUE self ) { Check_Type( self, T_DATA ); if ( !rb_obj_is_kind_of(self, rb_cPGconn) ) { rb_raise( rb_eTypeError, "wrong argument type %s (expected PG::Connection)", rb_obj_classname( self ) ); } return DATA_PTR( self ); } /* * GC Free function */ static void pgconn_gc_free( PGconn *conn ) { if (conn != NULL) PQfinish( conn ); } /************************************************************************** * Class Methods **************************************************************************/ /* * Document-method: allocate * * call-seq: * PG::Connection.allocate -> conn */ static VALUE pgconn_s_allocate( VALUE klass ) { VALUE self = Data_Wrap_Struct( klass, NULL, pgconn_gc_free, NULL ); rb_iv_set( self, "@socket_io", Qnil ); rb_iv_set( self, "@notice_receiver", Qnil); rb_iv_set( self, "@notice_processor", Qnil); return self; } /* * Document-method: new * * call-seq: * PG::Connection.new -> conn * PG::Connection.new(connection_hash) -> conn * PG::Connection.new(connection_string) -> conn * PG::Connection.new(host, port, options, tty, dbname, user, password) -> conn * * Create a connection to the specified server. * * [+host+] * server hostname * [+hostaddr+] * server address (avoids hostname lookup, overrides +host+) * [+port+] * server port number * [+dbname+] * connecting database name * [+user+] * login user name * [+password+] * login password * [+connect_timeout+] * maximum time to wait for connection to succeed * [+options+] * backend options * [+tty+] * (ignored in newer versions of PostgreSQL) * [+sslmode+] * (disable|allow|prefer|require) * [+krbsrvname+] * kerberos service name * [+gsslib+] * GSS library to use for GSSAPI authentication * [+service+] * service name to use for additional parameters * * Examples: * * # Connect using all defaults * PG::Connection.new * * # As a Hash * PG::Connection.new( :dbname => 'test', :port => 5432 ) * * # As a String * PG::Connection.new( "dbname=test port=5432" ) * * # As an Array * PG::Connection.new( nil, 5432, nil, nil, 'test', nil, nil ) * * If the Ruby default internal encoding is set (i.e., Encoding.default_internal != nil), the * connection will have its +client_encoding+ set accordingly. * * Raises a PG::Error if the connection fails. */ static VALUE pgconn_init(int argc, VALUE *argv, VALUE self) { PGconn *conn = NULL; VALUE conninfo; VALUE error; conninfo = rb_funcall2( rb_cPGconn, rb_intern("parse_connect_args"), argc, argv ); conn = gvl_PQconnectdb(StringValuePtr(conninfo)); if(conn == NULL) rb_raise(rb_ePGerror, "PQconnectdb() unable to allocate structure"); Check_Type(self, T_DATA); DATA_PTR(self) = conn; if (PQstatus(conn) == CONNECTION_BAD) { error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } #ifdef M17N_SUPPORTED pgconn_set_default_encoding( self ); #endif if (rb_block_given_p()) { return rb_ensure(rb_yield, self, pgconn_finish, self); } return self; } /* * call-seq: * PG::Connection.connect_start(connection_hash) -> conn * PG::Connection.connect_start(connection_string) -> conn * PG::Connection.connect_start(host, port, options, tty, dbname, login, password) -> conn * * This is an asynchronous version of PG::Connection.connect(). * * Use #connect_poll to poll the status of the connection. * * NOTE: this does *not* set the connection's +client_encoding+ for you if * Encoding.default_internal is set. To set it after the connection is established, * call #internal_encoding=. You can also set it automatically by setting * ENV['PGCLIENTENCODING'], or include the 'options' connection parameter. * */ static VALUE pgconn_s_connect_start( int argc, VALUE *argv, VALUE klass ) { PGconn *conn = NULL; VALUE rb_conn; VALUE conninfo; VALUE error; /* * PG::Connection.connect_start must act as both alloc() and initialize() * because it is not invoked by calling new(). */ rb_conn = pgconn_s_allocate( klass ); conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv ); conn = gvl_PQconnectStart( StringValuePtr(conninfo) ); if( conn == NULL ) rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate structure"); Check_Type(rb_conn, T_DATA); DATA_PTR(rb_conn) = conn; if ( PQstatus(conn) == CONNECTION_BAD ) { error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn)); rb_iv_set(error, "@connection", rb_conn); rb_exc_raise(error); } if ( rb_block_given_p() ) { return rb_ensure( rb_yield, rb_conn, pgconn_finish, rb_conn ); } return rb_conn; } #ifdef HAVE_PQPING /* * call-seq: * PG::Connection.ping(connection_hash) -> Fixnum * PG::Connection.ping(connection_string) -> Fixnum * PG::Connection.ping(host, port, options, tty, dbname, login, password) -> Fixnum * * Check server status. * * Returns one of: * [+PQPING_OK+] * server is accepting connections * [+PQPING_REJECT+] * server is alive but rejecting connections * [+PQPING_NO_RESPONSE+] * could not establish connection * [+PQPING_NO_ATTEMPT+] * connection not attempted (bad params) */ static VALUE pgconn_s_ping( int argc, VALUE *argv, VALUE klass ) { PGPing ping; VALUE conninfo; conninfo = rb_funcall2( klass, rb_intern("parse_connect_args"), argc, argv ); ping = PQping( StringValuePtr(conninfo) ); return INT2FIX((int)ping); } #endif /* * call-seq: * PG::Connection.conndefaults() -> Array * * Returns an array of hashes. Each hash has the keys: * [+:keyword+] * the name of the option * [+:envvar+] * the environment variable to fall back to * [+:compiled+] * the compiled in option as a secondary fallback * [+:val+] * the option's current value, or +nil+ if not known * [+:label+] * the label for the field * [+:dispchar+] * "" for normal, "D" for debug, and "*" for password * [+:dispsize+] * field size */ static VALUE pgconn_s_conndefaults(VALUE self) { PQconninfoOption *options = PQconndefaults(); VALUE ary = rb_ary_new(); VALUE hash; int i = 0; UNUSED( self ); for(i = 0; options[i].keyword != NULL; i++) { hash = rb_hash_new(); if(options[i].keyword) rb_hash_aset(hash, ID2SYM(rb_intern("keyword")), rb_str_new2(options[i].keyword)); if(options[i].envvar) rb_hash_aset(hash, ID2SYM(rb_intern("envvar")), rb_str_new2(options[i].envvar)); if(options[i].compiled) rb_hash_aset(hash, ID2SYM(rb_intern("compiled")), rb_str_new2(options[i].compiled)); if(options[i].val) rb_hash_aset(hash, ID2SYM(rb_intern("val")), rb_str_new2(options[i].val)); if(options[i].label) rb_hash_aset(hash, ID2SYM(rb_intern("label")), rb_str_new2(options[i].label)); if(options[i].dispchar) rb_hash_aset(hash, ID2SYM(rb_intern("dispchar")), rb_str_new2(options[i].dispchar)); rb_hash_aset(hash, ID2SYM(rb_intern("dispsize")), INT2NUM(options[i].dispsize)); rb_ary_push(ary, hash); } PQconninfoFree(options); return ary; } /* * call-seq: * PG::Connection.encrypt_password( password, username ) -> String * * This function is intended to be used by client applications that * send commands like: +ALTER USER joe PASSWORD 'pwd'+. * The arguments are the cleartext password, and the SQL name * of the user it is for. * * Return value is the encrypted password. */ static VALUE pgconn_s_encrypt_password(VALUE self, VALUE password, VALUE username) { char *encrypted = NULL; VALUE rval = Qnil; UNUSED( self ); Check_Type(password, T_STRING); Check_Type(username, T_STRING); encrypted = PQencryptPassword(StringValuePtr(password), StringValuePtr(username)); rval = rb_str_new2( encrypted ); PQfreemem( encrypted ); OBJ_INFECT( rval, password ); OBJ_INFECT( rval, username ); return rval; } /************************************************************************** * PG::Connection INSTANCE METHODS **************************************************************************/ /* * call-seq: * conn.connect_poll() -> Fixnum * * Returns one of: * [+PGRES_POLLING_READING+] * wait until the socket is ready to read * [+PGRES_POLLING_WRITING+] * wait until the socket is ready to write * [+PGRES_POLLING_FAILED+] * the asynchronous connection has failed * [+PGRES_POLLING_OK+] * the asynchronous connection is ready * * Example: * conn = PG::Connection.connect_start("dbname=mydatabase") * socket = conn.socket_io * status = conn.connect_poll * while(status != PG::PGRES_POLLING_OK) do * # do some work while waiting for the connection to complete * if(status == PG::PGRES_POLLING_READING) * if(not select([socket], [], [], 10.0)) * raise "Asynchronous connection timed out!" * end * elsif(status == PG::PGRES_POLLING_WRITING) * if(not select([], [socket], [], 10.0)) * raise "Asynchronous connection timed out!" * end * end * status = conn.connect_poll * end * # now conn.status == CONNECTION_OK, and connection * # is ready. */ static VALUE pgconn_connect_poll(VALUE self) { PostgresPollingStatusType status; status = gvl_PQconnectPoll(pg_get_pgconn(self)); return INT2FIX((int)status); } /* * call-seq: * conn.finish * * Closes the backend connection. */ static VALUE pgconn_finish( VALUE self ) { pgconn_close_socket_io( self ); PQfinish( pg_get_pgconn(self) ); DATA_PTR( self ) = NULL; return Qnil; } /* * call-seq: * conn.finished? -> boolean * * Returns +true+ if the backend connection has been closed. */ static VALUE pgconn_finished_p( VALUE self ) { if ( DATA_PTR(self) ) return Qfalse; return Qtrue; } /* * call-seq: * conn.reset() * * Resets the backend connection. This method closes the * backend connection and tries to re-connect. */ static VALUE pgconn_reset( VALUE self ) { pgconn_close_socket_io( self ); gvl_PQreset( pg_get_pgconn(self) ); return self; } /* * call-seq: * conn.reset_start() -> nil * * Initiate a connection reset in a nonblocking manner. * This will close the current connection and attempt to * reconnect using the same connection parameters. * Use #reset_poll to check the status of the * connection reset. */ static VALUE pgconn_reset_start(VALUE self) { pgconn_close_socket_io( self ); if(gvl_PQresetStart(pg_get_pgconn(self)) == 0) rb_raise(rb_eUnableToSend, "reset has failed"); return Qnil; } /* * call-seq: * conn.reset_poll -> Fixnum * * Checks the status of a connection reset operation. * See #connect_start and #connect_poll for * usage information and return values. */ static VALUE pgconn_reset_poll(VALUE self) { PostgresPollingStatusType status; status = gvl_PQresetPoll(pg_get_pgconn(self)); return INT2FIX((int)status); } /* * call-seq: * conn.db() * * Returns the connected database name. */ static VALUE pgconn_db(VALUE self) { char *db = PQdb(pg_get_pgconn(self)); if (!db) return Qnil; return rb_tainted_str_new2(db); } /* * call-seq: * conn.user() * * Returns the authenticated user name. */ static VALUE pgconn_user(VALUE self) { char *user = PQuser(pg_get_pgconn(self)); if (!user) return Qnil; return rb_tainted_str_new2(user); } /* * call-seq: * conn.pass() * * Returns the authenticated user name. */ static VALUE pgconn_pass(VALUE self) { char *user = PQpass(pg_get_pgconn(self)); if (!user) return Qnil; return rb_tainted_str_new2(user); } /* * call-seq: * conn.host() * * Returns the connected server name. */ static VALUE pgconn_host(VALUE self) { char *host = PQhost(pg_get_pgconn(self)); if (!host) return Qnil; return rb_tainted_str_new2(host); } /* * call-seq: * conn.port() * * Returns the connected server port number. */ static VALUE pgconn_port(VALUE self) { char* port = PQport(pg_get_pgconn(self)); return INT2NUM(atol(port)); } /* * call-seq: * conn.tty() * * Returns the connected pgtty. (Obsolete) */ static VALUE pgconn_tty(VALUE self) { char *tty = PQtty(pg_get_pgconn(self)); if (!tty) return Qnil; return rb_tainted_str_new2(tty); } /* * call-seq: * conn.options() * * Returns backend option string. */ static VALUE pgconn_options(VALUE self) { char *options = PQoptions(pg_get_pgconn(self)); if (!options) return Qnil; return rb_tainted_str_new2(options); } /* * call-seq: * conn.status() * * Returns status of connection : CONNECTION_OK or CONNECTION_BAD */ static VALUE pgconn_status(VALUE self) { return INT2NUM(PQstatus(pg_get_pgconn(self))); } /* * call-seq: * conn.transaction_status() * * returns one of the following statuses: * PQTRANS_IDLE = 0 (connection idle) * PQTRANS_ACTIVE = 1 (command in progress) * PQTRANS_INTRANS = 2 (idle, within transaction block) * PQTRANS_INERROR = 3 (idle, within failed transaction) * PQTRANS_UNKNOWN = 4 (cannot determine status) */ static VALUE pgconn_transaction_status(VALUE self) { return INT2NUM(PQtransactionStatus(pg_get_pgconn(self))); } /* * call-seq: * conn.parameter_status( param_name ) -> String * * Returns the setting of parameter _param_name_, where * _param_name_ is one of * * +server_version+ * * +server_encoding+ * * +client_encoding+ * * +is_superuser+ * * +session_authorization+ * * +DateStyle+ * * +TimeZone+ * * +integer_datetimes+ * * +standard_conforming_strings+ * * Returns nil if the value of the parameter is not known. */ static VALUE pgconn_parameter_status(VALUE self, VALUE param_name) { const char *ret = PQparameterStatus(pg_get_pgconn(self), StringValuePtr(param_name)); if(ret == NULL) return Qnil; else return rb_tainted_str_new2(ret); } /* * call-seq: * conn.protocol_version -> Integer * * The 3.0 protocol will normally be used when communicating with PostgreSQL 7.4 * or later servers; pre-7.4 servers support only protocol 2.0. (Protocol 1.0 is * obsolete and not supported by libpq.) */ static VALUE pgconn_protocol_version(VALUE self) { return INT2NUM(PQprotocolVersion(pg_get_pgconn(self))); } /* * call-seq: * conn.server_version -> Integer * * The number is formed by converting the major, minor, and revision * numbers into two-decimal-digit numbers and appending them together. * For example, version 7.4.2 will be returned as 70402, and version * 8.1 will be returned as 80100 (leading zeroes are not shown). Zero * is returned if the connection is bad. * */ static VALUE pgconn_server_version(VALUE self) { return INT2NUM(PQserverVersion(pg_get_pgconn(self))); } /* * call-seq: * conn.error_message -> String * * Returns the error message about connection. */ static VALUE pgconn_error_message(VALUE self) { char *error = PQerrorMessage(pg_get_pgconn(self)); if (!error) return Qnil; return rb_tainted_str_new2(error); } /* * call-seq: * conn.socket() -> Fixnum * * Returns the socket's file descriptor for this connection. * IO.for_fd() can be used to build a proper IO object to the socket. * If you do so, you will likely also want to set autoclose=false * on it to prevent Ruby from closing the socket to PostgreSQL if it * goes out of scope. Alternatively, you can use #socket_io, which * creates an IO that's associated with the connection object itself, * and so won't go out of scope until the connection does. * * *Note:* On Windows the file descriptor is not really usable, * since it can not be used to build a Ruby IO object. */ static VALUE pgconn_socket(VALUE self) { int sd; if( (sd = PQsocket(pg_get_pgconn(self))) < 0) rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor"); return INT2NUM(sd); } #if !defined(_WIN32) || defined(HAVE_RB_W32_WRAP_IO_HANDLE) /* * call-seq: * conn.socket_io() -> IO * * Fetch a memoized IO object created from the Connection's underlying socket. * This object can be used for IO.select to wait for events while running * asynchronous API calls. * * Using this instead of #socket avoids the problem of the underlying connection * being closed by Ruby when an IO created using IO.for_fd(conn.socket) * goes out of scope. * * This method can also be used on Windows but requires Ruby-2.0+. */ static VALUE pgconn_socket_io(VALUE self) { int sd; int ruby_sd; ID id_autoclose = rb_intern("autoclose="); VALUE socket_io = rb_iv_get( self, "@socket_io" ); if ( !RTEST(socket_io) ) { if( (sd = PQsocket(pg_get_pgconn(self))) < 0) rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor"); #ifdef _WIN32 ruby_sd = rb_w32_wrap_io_handle((HANDLE)(intptr_t)sd, O_RDWR|O_BINARY|O_NOINHERIT); #else ruby_sd = sd; #endif socket_io = rb_funcall( rb_cIO, rb_intern("for_fd"), 1, INT2NUM(ruby_sd) ); /* Disable autoclose feature, when supported */ if( rb_respond_to(socket_io, id_autoclose) ){ rb_funcall( socket_io, id_autoclose, 1, Qfalse ); } rb_iv_set( self, "@socket_io", socket_io ); } return socket_io; } #endif /* * call-seq: * conn.backend_pid() -> Fixnum * * Returns the process ID of the backend server * process for this connection. * Note that this is a PID on database server host. */ static VALUE pgconn_backend_pid(VALUE self) { return INT2NUM(PQbackendPID(pg_get_pgconn(self))); } /* * call-seq: * conn.connection_needs_password() -> Boolean * * Returns +true+ if the authentication method required a * password, but none was available. +false+ otherwise. */ static VALUE pgconn_connection_needs_password(VALUE self) { return PQconnectionNeedsPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse; } /* * call-seq: * conn.connection_used_password() -> Boolean * * Returns +true+ if the authentication method used * a caller-supplied password, +false+ otherwise. */ static VALUE pgconn_connection_used_password(VALUE self) { return PQconnectionUsedPassword(pg_get_pgconn(self)) ? Qtrue : Qfalse; } /* :TODO: get_ssl */ static VALUE pgconn_exec_params( int, VALUE *, VALUE ); /* * call-seq: * conn.exec(sql) -> PG::Result * conn.exec(sql) {|pg_result| block } * * Sends SQL query request specified by _sql_ to PostgreSQL. * Returns a PG::Result instance on success. * On failure, it raises a PG::Error. * * For backward compatibility, if you pass more than one parameter to this method, * it will call #exec_params for you. New code should explicitly use #exec_params if * argument placeholders are used. * * If the optional code block is given, it will be passed result as an argument, * and the PG::Result object will automatically be cleared when the block terminates. * In this instance, conn.exec returns the value of the block. */ static VALUE pgconn_exec(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn(self); PGresult *result = NULL; VALUE rb_pgresult; /* If called with no parameters, use PQexec */ if ( argc == 1 ) { Check_Type(argv[0], T_STRING); result = gvl_PQexec(conn, StringValuePtr(argv[0])); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); if (rb_block_given_p()) { return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult); } return rb_pgresult; } /* Otherwise, just call #exec_params instead for backward-compatibility */ else { return pgconn_exec_params( argc, argv, self ); } } /* * call-seq: * conn.exec_params(sql, params[, result_format ] ) -> PG::Result * conn.exec_params(sql, params[, result_format ] ) {|pg_result| block } * * Sends SQL query request specified by +sql+ to PostgreSQL using placeholders * for parameters. * * Returns a PG::Result instance on success. On failure, it raises a PG::Error. * * +params+ is an array of the bind parameters for the SQL query. * Each element of the +params+ array may be either: * a hash of the form: * {:value => String (value of bind parameter) * :type => Fixnum (oid of type of bind parameter) * :format => Fixnum (0 for text, 1 for binary) * } * or, it may be a String. If it is a string, that is equivalent to the hash: * { :value => , :type => 0, :format => 0 } * * PostgreSQL bind parameters are represented as $1, $1, $2, etc., * inside the SQL query. The 0th element of the +params+ array is bound * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+. * * If the types are not specified, they will be inferred by PostgreSQL. * Instead of specifying type oids, it's recommended to simply add * explicit casts in the query to ensure that the right type is used. * * For example: "SELECT $1::int" * * The optional +result_format+ should be 0 for text results, 1 * for binary. * * If the optional code block is given, it will be passed result as an argument, * and the PG::Result object will automatically be cleared when the block terminates. * In this instance, conn.exec returns the value of the block. */ static VALUE pgconn_exec_params( int argc, VALUE *argv, VALUE self ) { PGconn *conn = pg_get_pgconn(self); PGresult *result = NULL; VALUE rb_pgresult; VALUE command, params, in_res_fmt; VALUE param, param_type, param_value, param_format; VALUE param_value_tmp; VALUE sym_type, sym_value, sym_format; VALUE gc_array; int i=0; int nParams; Oid *paramTypes; char ** paramValues; int *paramLengths; int *paramFormats; int resultFormat; rb_scan_args(argc, argv, "12", &command, ¶ms, &in_res_fmt); /* * Handle the edge-case where the caller is coming from #exec, but passed an explict +nil+ * for the second parameter. */ if ( NIL_P(params) ) { return pgconn_exec( 1, argv, self ); } Check_Type(params, T_ARRAY); if ( NIL_P(in_res_fmt) ) { resultFormat = 0; } else { resultFormat = NUM2INT(in_res_fmt); } gc_array = rb_ary_new(); rb_gc_register_address(&gc_array); sym_type = ID2SYM(rb_intern("type")); sym_value = ID2SYM(rb_intern("value")); sym_format = ID2SYM(rb_intern("format")); nParams = (int)RARRAY_LEN(params); paramTypes = ALLOC_N(Oid, nParams); paramValues = ALLOC_N(char *, nParams); paramLengths = ALLOC_N(int, nParams); paramFormats = ALLOC_N(int, nParams); for ( i = 0; i < nParams; i++ ) { param = rb_ary_entry(params, i); if (TYPE(param) == T_HASH) { param_type = rb_hash_aref(param, sym_type); param_value_tmp = rb_hash_aref(param, sym_value); if(param_value_tmp == Qnil) param_value = param_value_tmp; else param_value = rb_obj_as_string(param_value_tmp); param_format = rb_hash_aref(param, sym_format); } else { param_type = Qnil; if(param == Qnil) param_value = param; else param_value = rb_obj_as_string(param); param_format = Qnil; } if(param_type == Qnil) paramTypes[i] = 0; else paramTypes[i] = NUM2INT(param_type); if(param_value == Qnil) { paramValues[i] = NULL; paramLengths[i] = 0; } else { Check_Type(param_value, T_STRING); /* make sure param_value doesn't get freed by the GC */ rb_ary_push(gc_array, param_value); paramValues[i] = StringValuePtr(param_value); paramLengths[i] = (int)RSTRING_LEN(param_value); } if(param_format == Qnil) paramFormats[i] = 0; else paramFormats[i] = NUM2INT(param_format); } result = gvl_PQexecParams(conn, StringValuePtr(command), nParams, paramTypes, (const char * const *)paramValues, paramLengths, paramFormats, resultFormat); rb_gc_unregister_address(&gc_array); xfree(paramTypes); xfree(paramValues); xfree(paramLengths); xfree(paramFormats); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); if (rb_block_given_p()) { return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult); } return rb_pgresult; } /* * call-seq: * conn.prepare(stmt_name, sql [, param_types ] ) -> PG::Result * * Prepares statement _sql_ with name _name_ to be executed later. * Returns a PG::Result instance on success. * On failure, it raises a PG::Error. * * +param_types+ is an optional parameter to specify the Oids of the * types of the parameters. * * If the types are not specified, they will be inferred by PostgreSQL. * Instead of specifying type oids, it's recommended to simply add * explicit casts in the query to ensure that the right type is used. * * For example: "SELECT $1::int" * * PostgreSQL bind parameters are represented as $1, $1, $2, etc., * inside the SQL query. */ static VALUE pgconn_prepare(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn(self); PGresult *result = NULL; VALUE rb_pgresult; VALUE name, command, in_paramtypes; VALUE param; int i = 0; int nParams = 0; Oid *paramTypes = NULL; rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes); Check_Type(name, T_STRING); Check_Type(command, T_STRING); if(! NIL_P(in_paramtypes)) { Check_Type(in_paramtypes, T_ARRAY); nParams = (int)RARRAY_LEN(in_paramtypes); paramTypes = ALLOC_N(Oid, nParams); for(i = 0; i < nParams; i++) { param = rb_ary_entry(in_paramtypes, i); Check_Type(param, T_FIXNUM); if(param == Qnil) paramTypes[i] = 0; else paramTypes[i] = NUM2INT(param); } } result = gvl_PQprepare(conn, StringValuePtr(name), StringValuePtr(command), nParams, paramTypes); xfree(paramTypes); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); return rb_pgresult; } /* * call-seq: * conn.exec_prepared(statement_name [, params, result_format ] ) -> PG::Result * conn.exec_prepared(statement_name [, params, result_format ] ) {|pg_result| block } * * Execute prepared named statement specified by _statement_name_. * Returns a PG::Result instance on success. * On failure, it raises a PG::Error. * * +params+ is an array of the optional bind parameters for the * SQL query. Each element of the +params+ array may be either: * a hash of the form: * {:value => String (value of bind parameter) * :format => Fixnum (0 for text, 1 for binary) * } * or, it may be a String. If it is a string, that is equivalent to the hash: * { :value => , :format => 0 } * * PostgreSQL bind parameters are represented as $1, $1, $2, etc., * inside the SQL query. The 0th element of the +params+ array is bound * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+. * * The optional +result_format+ should be 0 for text results, 1 * for binary. * * If the optional code block is given, it will be passed result as an argument, * and the PG::Result object will automatically be cleared when the block terminates. * In this instance, conn.exec_prepared returns the value of the block. */ static VALUE pgconn_exec_prepared(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn(self); PGresult *result = NULL; VALUE rb_pgresult; VALUE name, params, in_res_fmt; VALUE param, param_value, param_format; VALUE param_value_tmp; VALUE sym_value, sym_format; VALUE gc_array; int i = 0; int nParams; char ** paramValues; int *paramLengths; int *paramFormats; int resultFormat; rb_scan_args(argc, argv, "12", &name, ¶ms, &in_res_fmt); Check_Type(name, T_STRING); if(NIL_P(params)) { params = rb_ary_new2(0); resultFormat = 0; } else { Check_Type(params, T_ARRAY); } if(NIL_P(in_res_fmt)) { resultFormat = 0; } else { resultFormat = NUM2INT(in_res_fmt); } gc_array = rb_ary_new(); rb_gc_register_address(&gc_array); sym_value = ID2SYM(rb_intern("value")); sym_format = ID2SYM(rb_intern("format")); nParams = (int)RARRAY_LEN(params); paramValues = ALLOC_N(char *, nParams); paramLengths = ALLOC_N(int, nParams); paramFormats = ALLOC_N(int, nParams); for(i = 0; i < nParams; i++) { param = rb_ary_entry(params, i); if (TYPE(param) == T_HASH) { param_value_tmp = rb_hash_aref(param, sym_value); if(param_value_tmp == Qnil) param_value = param_value_tmp; else param_value = rb_obj_as_string(param_value_tmp); param_format = rb_hash_aref(param, sym_format); } else { if(param == Qnil) param_value = param; else param_value = rb_obj_as_string(param); param_format = INT2NUM(0); } if(param_value == Qnil) { paramValues[i] = NULL; paramLengths[i] = 0; } else { Check_Type(param_value, T_STRING); /* make sure param_value doesn't get freed by the GC */ rb_ary_push(gc_array, param_value); paramValues[i] = StringValuePtr(param_value); paramLengths[i] = (int)RSTRING_LEN(param_value); } if(param_format == Qnil) paramFormats[i] = 0; else paramFormats[i] = NUM2INT(param_format); } result = gvl_PQexecPrepared(conn, StringValuePtr(name), nParams, (const char * const *)paramValues, paramLengths, paramFormats, resultFormat); rb_gc_unregister_address(&gc_array); xfree(paramValues); xfree(paramLengths); xfree(paramFormats); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); if (rb_block_given_p()) { return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult); } return rb_pgresult; } /* * call-seq: * conn.describe_prepared( statement_name ) -> PG::Result * * Retrieve information about the prepared statement * _statement_name_. */ static VALUE pgconn_describe_prepared(VALUE self, VALUE stmt_name) { PGresult *result; VALUE rb_pgresult; PGconn *conn = pg_get_pgconn(self); char *stmt; if(stmt_name == Qnil) { stmt = NULL; } else { Check_Type(stmt_name, T_STRING); stmt = StringValuePtr(stmt_name); } result = gvl_PQdescribePrepared(conn, stmt); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); return rb_pgresult; } /* * call-seq: * conn.describe_portal( portal_name ) -> PG::Result * * Retrieve information about the portal _portal_name_. */ static VALUE pgconn_describe_portal(self, stmt_name) VALUE self, stmt_name; { PGresult *result; VALUE rb_pgresult; PGconn *conn = pg_get_pgconn(self); char *stmt; if(stmt_name == Qnil) { stmt = NULL; } else { Check_Type(stmt_name, T_STRING); stmt = StringValuePtr(stmt_name); } result = gvl_PQdescribePortal(conn, stmt); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); return rb_pgresult; } /* * call-seq: * conn.make_empty_pgresult( status ) -> PG::Result * * Constructs and empty PG::Result with status _status_. * _status_ may be one of: * * +PGRES_EMPTY_QUERY+ * * +PGRES_COMMAND_OK+ * * +PGRES_TUPLES_OK+ * * +PGRES_COPY_OUT+ * * +PGRES_COPY_IN+ * * +PGRES_BAD_RESPONSE+ * * +PGRES_NONFATAL_ERROR+ * * +PGRES_FATAL_ERROR+ * * +PGRES_COPY_BOTH+ */ static VALUE pgconn_make_empty_pgresult(VALUE self, VALUE status) { PGresult *result; VALUE rb_pgresult; PGconn *conn = pg_get_pgconn(self); result = PQmakeEmptyPGresult(conn, NUM2INT(status)); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); return rb_pgresult; } /* * call-seq: * conn.escape_string( str ) -> String * * Connection instance method for versions of 8.1 and higher of libpq * uses PQescapeStringConn, which is safer. Avoid calling as a class method, * the class method uses the deprecated PQescapeString() API function. * * Returns a SQL-safe version of the String _str_. * This is the preferred way to make strings safe for inclusion in * SQL queries. * * Consider using exec_params, which avoids the need for passing values * inside of SQL commands. * * Encoding of escaped string will be equal to client encoding of connection. */ static VALUE pgconn_s_escape(VALUE self, VALUE string) { char *escaped; size_t size; int error; VALUE result; #ifdef M17N_SUPPORTED rb_encoding* enc; #endif Check_Type(string, T_STRING); escaped = ALLOC_N(char, RSTRING_LEN(string) * 2 + 1); if(rb_obj_class(self) == rb_cPGconn) { size = PQescapeStringConn(pg_get_pgconn(self), escaped, RSTRING_PTR(string), RSTRING_LEN(string), &error); if(error) { xfree(escaped); rb_raise(rb_ePGerror, "%s", PQerrorMessage(pg_get_pgconn(self))); } } else { size = PQescapeString(escaped, RSTRING_PTR(string), (int)RSTRING_LEN(string)); } result = rb_str_new(escaped, size); xfree(escaped); OBJ_INFECT(result, string); #ifdef M17N_SUPPORTED if ( rb_obj_class(self) == rb_cPGconn ) { enc = pg_conn_enc_get( pg_get_pgconn(self) ); } else { enc = rb_enc_get(string); } rb_enc_associate(result, enc); #endif return result; } /* * call-seq: * conn.escape_bytea( string ) -> String * * Connection instance method for versions of 8.1 and higher of libpq * uses PQescapeByteaConn, which is safer. Avoid calling as a class method, * the class method uses the deprecated PQescapeBytea() API function. * * Use the instance method version of this function, it is safer than the * class method. * * Escapes binary data for use within an SQL command with the type +bytea+. * * Certain byte values must be escaped (but all byte values may be escaped) * when used as part of a +bytea+ literal in an SQL statement. In general, to * escape a byte, it is converted into the three digit octal number equal to * the octet value, and preceded by two backslashes. The single quote (') and * backslash (\) characters have special alternative escape sequences. * #escape_bytea performs this operation, escaping only the minimally required * bytes. * * Consider using exec_params, which avoids the need for passing values inside of * SQL commands. */ static VALUE pgconn_s_escape_bytea(VALUE self, VALUE str) { unsigned char *from, *to; size_t from_len, to_len; VALUE ret; Check_Type(str, T_STRING); from = (unsigned char*)RSTRING_PTR(str); from_len = RSTRING_LEN(str); if(rb_obj_class(self) == rb_cPGconn) { to = PQescapeByteaConn(pg_get_pgconn(self), from, from_len, &to_len); } else { to = PQescapeBytea( from, from_len, &to_len); } ret = rb_str_new((char*)to, to_len - 1); OBJ_INFECT(ret, str); PQfreemem(to); return ret; } /* * call-seq: * PG::Connection.unescape_bytea( string ) * * Converts an escaped string representation of binary data into binary data --- the * reverse of #escape_bytea. This is needed when retrieving +bytea+ data in text format, * but not when retrieving it in binary format. * */ static VALUE pgconn_s_unescape_bytea(VALUE self, VALUE str) { unsigned char *from, *to; size_t to_len; VALUE ret; UNUSED( self ); Check_Type(str, T_STRING); from = (unsigned char*)StringValuePtr(str); to = PQunescapeBytea(from, &to_len); ret = rb_str_new((char*)to, to_len); OBJ_INFECT(ret, str); PQfreemem(to); return ret; } #ifdef HAVE_PQESCAPELITERAL /* * call-seq: * conn.escape_literal( str ) -> String * * Escape an arbitrary String +str+ as a literal. */ static VALUE pgconn_escape_literal(VALUE self, VALUE string) { PGconn *conn = pg_get_pgconn(self); char *escaped = NULL; VALUE error; VALUE result = Qnil; Check_Type(string, T_STRING); escaped = PQescapeLiteral(conn, RSTRING_PTR(string), RSTRING_LEN(string)); if (escaped == NULL) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); return Qnil; } result = rb_str_new2(escaped); PQfreemem(escaped); OBJ_INFECT(result, string); #ifdef M17N_SUPPORTED rb_enc_associate(result, pg_conn_enc_get( pg_get_pgconn(self) )); #endif return result; } #endif #ifdef HAVE_PQESCAPEIDENTIFIER /* * call-seq: * conn.escape_identifier( str ) -> String * * Escape an arbitrary String +str+ as an identifier. * * This method does the same as #quote_ident, but uses libpq to * process the string. */ static VALUE pgconn_escape_identifier(VALUE self, VALUE string) { PGconn *conn = pg_get_pgconn(self); char *escaped = NULL; VALUE error; VALUE result = Qnil; Check_Type(string, T_STRING); escaped = PQescapeIdentifier(conn, RSTRING_PTR(string), RSTRING_LEN(string)); if (escaped == NULL) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); return Qnil; } result = rb_str_new2(escaped); PQfreemem(escaped); OBJ_INFECT(result, string); #ifdef M17N_SUPPORTED rb_enc_associate(result, pg_conn_enc_get( pg_get_pgconn(self) )); #endif return result; } #endif #ifdef HAVE_PQSETSINGLEROWMODE /* * call-seq: * conn.set_single_row_mode -> self * * To enter single-row mode, call this method immediately after a successful * call of send_query (or a sibling function). This mode selection is effective * only for the currently executing query. * Then call Connection#get_result repeatedly, until it returns nil. * * Each (but the last) received Result has exactly one row and a * Result#result_status of PGRES_SINGLE_TUPLE. The last row has * zero rows and is used to indicate a successful execution of the query. * All of these Result objects will contain the same row description data * (column names, types, etc) that an ordinary Result object for the query * would have. * * *Caution:* While processing a query, the server may return some rows and * then encounter an error, causing the query to be aborted. Ordinarily, pg * discards any such rows and reports only the error. But in single-row mode, * those rows will have already been returned to the application. Hence, the * application will see some Result objects followed by an Error raised in get_result. * For proper transactional behavior, the application must be designed to discard * or undo whatever has been done with the previously-processed rows, if the query * ultimately fails. * * Example: * conn.send_query( "your SQL command" ) * conn.set_single_row_mode * loop do * res = conn.get_result or break * res.check * res.each do |row| * # do something with the received row * end * end * */ static VALUE pgconn_set_single_row_mode(VALUE self) { PGconn *conn = pg_get_pgconn(self); VALUE error; if( PQsetSingleRowMode(conn) == 0 ) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return self; } #endif /* * call-seq: * conn.send_query(sql [, params, result_format ] ) -> nil * * Sends SQL query request specified by _sql_ to PostgreSQL for * asynchronous processing, and immediately returns. * On failure, it raises a PG::Error. * * +params+ is an optional array of the bind parameters for the SQL query. * Each element of the +params+ array may be either: * a hash of the form: * {:value => String (value of bind parameter) * :type => Fixnum (oid of type of bind parameter) * :format => Fixnum (0 for text, 1 for binary) * } * or, it may be a String. If it is a string, that is equivalent to the hash: * { :value => , :type => 0, :format => 0 } * * PostgreSQL bind parameters are represented as $1, $1, $2, etc., * inside the SQL query. The 0th element of the +params+ array is bound * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+. * * If the types are not specified, they will be inferred by PostgreSQL. * Instead of specifying type oids, it's recommended to simply add * explicit casts in the query to ensure that the right type is used. * * For example: "SELECT $1::int" * * The optional +result_format+ should be 0 for text results, 1 * for binary. */ static VALUE pgconn_send_query(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn(self); int result; VALUE command, params, in_res_fmt; VALUE param, param_type, param_value, param_format; VALUE param_value_tmp; VALUE sym_type, sym_value, sym_format; VALUE gc_array; VALUE error; int i=0; int nParams; Oid *paramTypes; char ** paramValues; int *paramLengths; int *paramFormats; int resultFormat; rb_scan_args(argc, argv, "12", &command, ¶ms, &in_res_fmt); Check_Type(command, T_STRING); /* If called with no parameters, use PQsendQuery */ if(NIL_P(params)) { if(gvl_PQsendQuery(conn,StringValuePtr(command)) == 0) { error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* If called with parameters, and optionally result_format, * use PQsendQueryParams */ Check_Type(params, T_ARRAY); if(NIL_P(in_res_fmt)) { resultFormat = 0; } else { resultFormat = NUM2INT(in_res_fmt); } gc_array = rb_ary_new(); rb_gc_register_address(&gc_array); sym_type = ID2SYM(rb_intern("type")); sym_value = ID2SYM(rb_intern("value")); sym_format = ID2SYM(rb_intern("format")); nParams = (int)RARRAY_LEN(params); paramTypes = ALLOC_N(Oid, nParams); paramValues = ALLOC_N(char *, nParams); paramLengths = ALLOC_N(int, nParams); paramFormats = ALLOC_N(int, nParams); for(i = 0; i < nParams; i++) { param = rb_ary_entry(params, i); if (TYPE(param) == T_HASH) { param_type = rb_hash_aref(param, sym_type); param_value_tmp = rb_hash_aref(param, sym_value); if(param_value_tmp == Qnil) param_value = param_value_tmp; else param_value = rb_obj_as_string(param_value_tmp); param_format = rb_hash_aref(param, sym_format); } else { param_type = INT2NUM(0); if(param == Qnil) param_value = param; else param_value = rb_obj_as_string(param); param_format = INT2NUM(0); } if(param_type == Qnil) paramTypes[i] = 0; else paramTypes[i] = NUM2INT(param_type); if(param_value == Qnil) { paramValues[i] = NULL; paramLengths[i] = 0; } else { Check_Type(param_value, T_STRING); /* make sure param_value doesn't get freed by the GC */ rb_ary_push(gc_array, param_value); paramValues[i] = StringValuePtr(param_value); paramLengths[i] = (int)RSTRING_LEN(param_value); } if(param_format == Qnil) paramFormats[i] = 0; else paramFormats[i] = NUM2INT(param_format); } result = gvl_PQsendQueryParams(conn, StringValuePtr(command), nParams, paramTypes, (const char * const *)paramValues, paramLengths, paramFormats, resultFormat); rb_gc_unregister_address(&gc_array); xfree(paramTypes); xfree(paramValues); xfree(paramLengths); xfree(paramFormats); if(result == 0) { error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.send_prepare( stmt_name, sql [, param_types ] ) -> nil * * Prepares statement _sql_ with name _name_ to be executed later. * Sends prepare command asynchronously, and returns immediately. * On failure, it raises a PG::Error. * * +param_types+ is an optional parameter to specify the Oids of the * types of the parameters. * * If the types are not specified, they will be inferred by PostgreSQL. * Instead of specifying type oids, it's recommended to simply add * explicit casts in the query to ensure that the right type is used. * * For example: "SELECT $1::int" * * PostgreSQL bind parameters are represented as $1, $1, $2, etc., * inside the SQL query. */ static VALUE pgconn_send_prepare(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn(self); int result; VALUE name, command, in_paramtypes; VALUE param; VALUE error; int i = 0; int nParams = 0; Oid *paramTypes = NULL; rb_scan_args(argc, argv, "21", &name, &command, &in_paramtypes); Check_Type(name, T_STRING); Check_Type(command, T_STRING); if(! NIL_P(in_paramtypes)) { Check_Type(in_paramtypes, T_ARRAY); nParams = (int)RARRAY_LEN(in_paramtypes); paramTypes = ALLOC_N(Oid, nParams); for(i = 0; i < nParams; i++) { param = rb_ary_entry(in_paramtypes, i); Check_Type(param, T_FIXNUM); if(param == Qnil) paramTypes[i] = 0; else paramTypes[i] = NUM2INT(param); } } result = gvl_PQsendPrepare(conn, StringValuePtr(name), StringValuePtr(command), nParams, paramTypes); xfree(paramTypes); if(result == 0) { error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.send_query_prepared( statement_name [, params, result_format ] ) * -> nil * * Execute prepared named statement specified by _statement_name_ * asynchronously, and returns immediately. * On failure, it raises a PG::Error. * * +params+ is an array of the optional bind parameters for the * SQL query. Each element of the +params+ array may be either: * a hash of the form: * {:value => String (value of bind parameter) * :format => Fixnum (0 for text, 1 for binary) * } * or, it may be a String. If it is a string, that is equivalent to the hash: * { :value => , :format => 0 } * * PostgreSQL bind parameters are represented as $1, $1, $2, etc., * inside the SQL query. The 0th element of the +params+ array is bound * to $1, the 1st element is bound to $2, etc. +nil+ is treated as +NULL+. * * The optional +result_format+ should be 0 for text results, 1 * for binary. */ static VALUE pgconn_send_query_prepared(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn(self); int result; VALUE name, params, in_res_fmt; VALUE param, param_value, param_format; VALUE param_value_tmp; VALUE sym_value, sym_format; VALUE gc_array; VALUE error; int i = 0; int nParams; char ** paramValues; int *paramLengths; int *paramFormats; int resultFormat; rb_scan_args(argc, argv, "12", &name, ¶ms, &in_res_fmt); Check_Type(name, T_STRING); if(NIL_P(params)) { params = rb_ary_new2(0); resultFormat = 0; } else { Check_Type(params, T_ARRAY); } if(NIL_P(in_res_fmt)) { resultFormat = 0; } else { resultFormat = NUM2INT(in_res_fmt); } gc_array = rb_ary_new(); rb_gc_register_address(&gc_array); sym_value = ID2SYM(rb_intern("value")); sym_format = ID2SYM(rb_intern("format")); nParams = (int)RARRAY_LEN(params); paramValues = ALLOC_N(char *, nParams); paramLengths = ALLOC_N(int, nParams); paramFormats = ALLOC_N(int, nParams); for(i = 0; i < nParams; i++) { param = rb_ary_entry(params, i); if (TYPE(param) == T_HASH) { param_value_tmp = rb_hash_aref(param, sym_value); if(param_value_tmp == Qnil) param_value = param_value_tmp; else param_value = rb_obj_as_string(param_value_tmp); param_format = rb_hash_aref(param, sym_format); } else { if(param == Qnil) param_value = param; else param_value = rb_obj_as_string(param); param_format = INT2NUM(0); } if(param_value == Qnil) { paramValues[i] = NULL; paramLengths[i] = 0; } else { Check_Type(param_value, T_STRING); /* make sure param_value doesn't get freed by the GC */ rb_ary_push(gc_array, param_value); paramValues[i] = StringValuePtr(param_value); paramLengths[i] = (int)RSTRING_LEN(param_value); } if(param_format == Qnil) paramFormats[i] = 0; else paramFormats[i] = NUM2INT(param_format); } result = gvl_PQsendQueryPrepared(conn, StringValuePtr(name), nParams, (const char * const *)paramValues, paramLengths, paramFormats, resultFormat); rb_gc_unregister_address(&gc_array); xfree(paramValues); xfree(paramLengths); xfree(paramFormats); if(result == 0) { error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.send_describe_prepared( statement_name ) -> nil * * Asynchronously send _command_ to the server. Does not block. * Use in combination with +conn.get_result+. */ static VALUE pgconn_send_describe_prepared(VALUE self, VALUE stmt_name) { VALUE error; PGconn *conn = pg_get_pgconn(self); /* returns 0 on failure */ if(gvl_PQsendDescribePrepared(conn,StringValuePtr(stmt_name)) == 0) { error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.send_describe_portal( portal_name ) -> nil * * Asynchronously send _command_ to the server. Does not block. * Use in combination with +conn.get_result+. */ static VALUE pgconn_send_describe_portal(VALUE self, VALUE portal) { VALUE error; PGconn *conn = pg_get_pgconn(self); /* returns 0 on failure */ if(gvl_PQsendDescribePortal(conn,StringValuePtr(portal)) == 0) { error = rb_exc_new2(rb_eUnableToSend, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.get_result() -> PG::Result * conn.get_result() {|pg_result| block } * * Blocks waiting for the next result from a call to * #send_query (or another asynchronous command), and returns * it. Returns +nil+ if no more results are available. * * Note: call this function repeatedly until it returns +nil+, or else * you will not be able to issue further commands. * * If the optional code block is given, it will be passed result as an argument, * and the PG::Result object will automatically be cleared when the block terminates. * In this instance, conn.exec returns the value of the block. */ static VALUE pgconn_get_result(VALUE self) { PGconn *conn = pg_get_pgconn(self); PGresult *result; VALUE rb_pgresult; result = gvl_PQgetResult(conn); if(result == NULL) return Qnil; rb_pgresult = pg_new_result(result, self); if (rb_block_given_p()) { return rb_ensure(rb_yield, rb_pgresult, pg_result_clear, rb_pgresult); } return rb_pgresult; } /* * call-seq: * conn.consume_input() * * If input is available from the server, consume it. * After calling +consume_input+, you can check +is_busy+ * or *notifies* to see if the state has changed. */ static VALUE pgconn_consume_input(self) VALUE self; { VALUE error; PGconn *conn = pg_get_pgconn(self); /* returns 0 on error */ if(PQconsumeInput(conn) == 0) { error = rb_exc_new2(rb_eConnectionBad, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.is_busy() -> Boolean * * Returns +true+ if a command is busy, that is, if * PQgetResult would block. Otherwise returns +false+. */ static VALUE pgconn_is_busy(self) VALUE self; { return gvl_PQisBusy(pg_get_pgconn(self)) ? Qtrue : Qfalse; } /* * call-seq: * conn.setnonblocking(Boolean) -> nil * * Sets the nonblocking status of the connection. * In the blocking state, calls to #send_query * will block until the message is sent to the server, * but will not wait for the query results. * In the nonblocking state, calls to #send_query * will return an error if the socket is not ready for * writing. * Note: This function does not affect #exec, because * that function doesn't return until the server has * processed the query and returned the results. * Returns +nil+. */ static VALUE pgconn_setnonblocking(self, state) VALUE self, state; { int arg; VALUE error; PGconn *conn = pg_get_pgconn(self); if(state == Qtrue) arg = 1; else if (state == Qfalse) arg = 0; else rb_raise(rb_eArgError, "Boolean value expected"); if(PQsetnonblocking(conn, arg) == -1) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return Qnil; } /* * call-seq: * conn.isnonblocking() -> Boolean * * Returns +true+ if a command is busy, that is, if * PQgetResult would block. Otherwise returns +false+. */ static VALUE pgconn_isnonblocking(self) VALUE self; { return PQisnonblocking(pg_get_pgconn(self)) ? Qtrue : Qfalse; } /* * call-seq: * conn.flush() -> Boolean * * Attempts to flush any queued output data to the server. * Returns +true+ if data is successfully flushed, +false+ * if not (can only return +false+ if connection is * nonblocking. * Raises PG::Error if some other failure occurred. */ static VALUE pgconn_flush(self) VALUE self; { PGconn *conn = pg_get_pgconn(self); int ret; VALUE error; ret = PQflush(conn); if(ret == -1) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return (ret) ? Qfalse : Qtrue; } /* * call-seq: * conn.cancel() -> String * * Requests cancellation of the command currently being * processed. (Only implemented in PostgreSQL >= 8.0) * * Returns +nil+ on success, or a string containing the * error message if a failure occurs. */ static VALUE pgconn_cancel(VALUE self) { #ifdef HAVE_PQGETCANCEL char errbuf[256]; PGcancel *cancel; VALUE retval; int ret; cancel = PQgetCancel(pg_get_pgconn(self)); if(cancel == NULL) rb_raise(rb_ePGerror,"Invalid connection!"); ret = PQcancel(cancel, errbuf, 256); if(ret == 1) retval = Qnil; else retval = rb_str_new2(errbuf); PQfreeCancel(cancel); return retval; #else rb_notimplement(); #endif } /* * call-seq: * conn.notifies() * * Returns a hash of the unprocessed notifications. * If there is no unprocessed notifier, it returns +nil+. */ static VALUE pgconn_notifies(VALUE self) { PGconn* conn = pg_get_pgconn(self); PGnotify *notification; VALUE hash; VALUE sym_relname, sym_be_pid, sym_extra; VALUE relname, be_pid, extra; sym_relname = ID2SYM(rb_intern("relname")); sym_be_pid = ID2SYM(rb_intern("be_pid")); sym_extra = ID2SYM(rb_intern("extra")); notification = gvl_PQnotifies(conn); if (notification == NULL) { return Qnil; } hash = rb_hash_new(); relname = rb_tainted_str_new2(notification->relname); be_pid = INT2NUM(notification->be_pid); extra = rb_tainted_str_new2(notification->extra); #ifdef M17N_SUPPORTED ENCODING_SET( relname, rb_enc_to_index(pg_conn_enc_get( conn )) ); ENCODING_SET( extra, rb_enc_to_index(pg_conn_enc_get( conn )) ); #endif rb_hash_aset(hash, sym_relname, relname); rb_hash_aset(hash, sym_be_pid, be_pid); rb_hash_aset(hash, sym_extra, extra); PQfreemem(notification); return hash; } /* Win32 + Ruby 1.8 */ #if !defined( HAVE_RUBY_VM_H ) && defined( _WIN32 ) /* * Duplicate the sockets from libpq and create temporary CRT FDs */ void create_crt_fd(fd_set *os_set, fd_set *crt_set) { int i; crt_set->fd_count = os_set->fd_count; for (i = 0; i < os_set->fd_count; i++) { WSAPROTOCOL_INFO wsa_pi; /* dupicate the SOCKET */ int r = WSADuplicateSocket(os_set->fd_array[i], GetCurrentProcessId(), &wsa_pi); SOCKET s = WSASocket(wsa_pi.iAddressFamily, wsa_pi.iSocketType, wsa_pi.iProtocol, &wsa_pi, 0, 0); /* create the CRT fd so ruby can get back to the SOCKET */ int fd = _open_osfhandle(s, O_RDWR|O_BINARY); os_set->fd_array[i] = s; crt_set->fd_array[i] = fd; } } /* * Clean up the CRT FDs from create_crt_fd() */ void cleanup_crt_fd(fd_set *os_set, fd_set *crt_set) { int i; for (i = 0; i < os_set->fd_count; i++) { /* cleanup the CRT fd */ _close(crt_set->fd_array[i]); /* cleanup the duplicated SOCKET */ closesocket(os_set->fd_array[i]); } } #endif /* Win32 + Ruby 1.9+ */ #if defined( HAVE_RUBY_VM_H ) && defined( _WIN32 ) /* * On Windows, use platform-specific strategies to wait for the socket * instead of rb_thread_select(). */ int rb_w32_wait_events( HANDLE *events, int num, DWORD timeout ); /* If WIN32 and Ruby 1.9 do not use rb_thread_select() which sometimes hangs * and does not wait (nor sleep) any time even if timeout is given. * Instead use the Winsock events and rb_w32_wait_events(). */ static void * wait_socket_readable( PGconn *conn, struct timeval *ptimeout, void *(*is_readable)(PGconn *) ) { int sd = PQsocket( conn ); void *retval; struct timeval aborttime={0,0}, currtime, waittime; DWORD timeout_milisec = INFINITE; DWORD wait_ret; WSAEVENT hEvent; if ( sd < 0 ) rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor"); hEvent = WSACreateEvent(); /* Check for connection errors (PQisBusy is true on connection errors) */ if( PQconsumeInput(conn) == 0 ) { WSACloseEvent( hEvent ); rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) ); } if ( ptimeout ) { gettimeofday(&currtime, NULL); timeradd(&currtime, ptimeout, &aborttime); } while ( !(retval=is_readable(conn)) ) { if ( WSAEventSelect(sd, hEvent, FD_READ|FD_CLOSE) == SOCKET_ERROR ) { WSACloseEvent( hEvent ); rb_raise( rb_eConnectionBad, "WSAEventSelect socket error: %d", WSAGetLastError() ); } if ( ptimeout ) { gettimeofday(&currtime, NULL); timersub(&aborttime, &currtime, &waittime); timeout_milisec = (DWORD)( waittime.tv_sec * 1e3 + waittime.tv_usec / 1e3 ); } /* Is the given timeout valid? */ if( !ptimeout || (waittime.tv_sec >= 0 && waittime.tv_usec >= 0) ){ /* Wait for the socket to become readable before checking again */ wait_ret = rb_w32_wait_events( &hEvent, 1, timeout_milisec ); } else { wait_ret = WAIT_TIMEOUT; } if ( wait_ret == WAIT_TIMEOUT ) { WSACloseEvent( hEvent ); return NULL; } else if ( wait_ret == WAIT_OBJECT_0 ) { /* The event we were waiting for. */ } else if ( wait_ret == WAIT_OBJECT_0 + 1) { /* This indicates interruption from timer thread, GC, exception * from other threads etc... */ rb_thread_check_ints(); } else if ( wait_ret == WAIT_FAILED ) { WSACloseEvent( hEvent ); rb_raise( rb_eConnectionBad, "Wait on socket error (WaitForMultipleObjects): %lu", GetLastError() ); } else { WSACloseEvent( hEvent ); rb_raise( rb_eConnectionBad, "Wait on socket abandoned (WaitForMultipleObjects)" ); } /* Check for connection errors (PQisBusy is true on connection errors) */ if ( PQconsumeInput(conn) == 0 ) { WSACloseEvent( hEvent ); rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) ); } } WSACloseEvent( hEvent ); return retval; } #else /* non Win32 or Win32+Ruby-1.8 */ static void * wait_socket_readable( PGconn *conn, struct timeval *ptimeout, void *(*is_readable)(PGconn *)) { int sd = PQsocket( conn ); int ret; void *retval; rb_fdset_t sd_rset; struct timeval aborttime={0,0}, currtime, waittime; #ifdef _WIN32 rb_fdset_t crt_sd_rset; #endif if ( sd < 0 ) rb_raise(rb_eConnectionBad, "PQsocket() can't get socket descriptor"); /* Check for connection errors (PQisBusy is true on connection errors) */ if ( PQconsumeInput(conn) == 0 ) rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) ); rb_fd_init( &sd_rset ); if ( ptimeout ) { gettimeofday(&currtime, NULL); timeradd(&currtime, ptimeout, &aborttime); } while ( !(retval=is_readable(conn)) ) { rb_fd_zero( &sd_rset ); rb_fd_set( sd, &sd_rset ); #ifdef _WIN32 /* Ruby's FD_SET is modified on win32 to convert a file descriptor * to osfhandle, but we already get a osfhandle from PQsocket(). * Therefore it's overwritten here. */ sd_rset.fd_array[0] = sd; create_crt_fd(&sd_rset, &crt_sd_rset); #endif if ( ptimeout ) { gettimeofday(&currtime, NULL); timersub(&aborttime, &currtime, &waittime); } /* Is the given timeout valid? */ if( !ptimeout || (waittime.tv_sec >= 0 && waittime.tv_usec >= 0) ){ /* Wait for the socket to become readable before checking again */ ret = rb_thread_fd_select( sd+1, &sd_rset, NULL, NULL, ptimeout ? &waittime : NULL ); } else { ret = 0; } #ifdef _WIN32 cleanup_crt_fd(&sd_rset, &crt_sd_rset); #endif if ( ret < 0 ){ rb_fd_term( &sd_rset ); rb_sys_fail( "rb_thread_select()" ); } /* Return false if the select() timed out */ if ( ret == 0 ){ rb_fd_term( &sd_rset ); return NULL; } /* Check for connection errors (PQisBusy is true on connection errors) */ if ( PQconsumeInput(conn) == 0 ){ rb_fd_term( &sd_rset ); rb_raise( rb_eConnectionBad, "PQconsumeInput() %s", PQerrorMessage(conn) ); } } rb_fd_term( &sd_rset ); return retval; } #endif static void * notify_readable(PGconn *conn) { return (void*)gvl_PQnotifies(conn); } /* * call-seq: * conn.wait_for_notify( [ timeout ] ) -> String * conn.wait_for_notify( [ timeout ] ) { |event, pid| block } * conn.wait_for_notify( [ timeout ] ) { |event, pid, payload| block } # PostgreSQL 9.0 * * Blocks while waiting for notification(s), or until the optional * _timeout_ is reached, whichever comes first. _timeout_ is * measured in seconds and can be fractional. * * Returns +nil+ if _timeout_ is reached, the name of the NOTIFY * event otherwise. If used in block form, passes the name of the * NOTIFY +event+ and the generating +pid+ into the block. * * Under PostgreSQL 9.0 and later, if the notification is sent with * the optional +payload+ string, it will be given to the block as the * third argument. * */ static VALUE pgconn_wait_for_notify(int argc, VALUE *argv, VALUE self) { PGconn *conn = pg_get_pgconn( self ); PGnotify *pnotification; struct timeval timeout; struct timeval *ptimeout = NULL; VALUE timeout_in = Qnil, relname = Qnil, be_pid = Qnil, extra = Qnil; double timeout_sec; rb_scan_args( argc, argv, "01", &timeout_in ); if ( RTEST(timeout_in) ) { timeout_sec = NUM2DBL( timeout_in ); timeout.tv_sec = (time_t)timeout_sec; timeout.tv_usec = (suseconds_t)( (timeout_sec - (long)timeout_sec) * 1e6 ); ptimeout = &timeout; } pnotification = (PGnotify*) wait_socket_readable( conn, ptimeout, notify_readable); /* Return nil if the select timed out */ if ( !pnotification ) return Qnil; relname = rb_tainted_str_new2( pnotification->relname ); #ifdef M17N_SUPPORTED ENCODING_SET( relname, rb_enc_to_index(pg_conn_enc_get( conn )) ); #endif be_pid = INT2NUM( pnotification->be_pid ); #ifdef HAVE_ST_NOTIFY_EXTRA if ( *pnotification->extra ) { extra = rb_tainted_str_new2( pnotification->extra ); #ifdef M17N_SUPPORTED ENCODING_SET( extra, rb_enc_to_index(pg_conn_enc_get( conn )) ); #endif } #endif PQfreemem( pnotification ); if ( rb_block_given_p() ) rb_yield_values( 3, relname, be_pid, extra ); return relname; } /* * call-seq: * conn.put_copy_data( buffer ) -> Boolean * * Transmits _buffer_ as copy data to the server. * Returns true if the data was sent, false if it was * not sent (false is only possible if the connection * is in nonblocking mode, and this command would block). * * Raises an exception if an error occurs. * * See also #copy_data. * */ static VALUE pgconn_put_copy_data(self, buffer) VALUE self, buffer; { int ret; VALUE error; PGconn *conn = pg_get_pgconn(self); Check_Type(buffer, T_STRING); ret = gvl_PQputCopyData(conn, RSTRING_PTR(buffer), (int)RSTRING_LEN(buffer)); if(ret == -1) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return (ret) ? Qtrue : Qfalse; } /* * call-seq: * conn.put_copy_end( [ error_message ] ) -> Boolean * * Sends end-of-data indication to the server. * * _error_message_ is an optional parameter, and if set, * forces the COPY command to fail with the string * _error_message_. * * Returns true if the end-of-data was sent, false if it was * not sent (false is only possible if the connection * is in nonblocking mode, and this command would block). */ static VALUE pgconn_put_copy_end(int argc, VALUE *argv, VALUE self) { VALUE str; VALUE error; int ret; char *error_message = NULL; PGconn *conn = pg_get_pgconn(self); if (rb_scan_args(argc, argv, "01", &str) == 0) error_message = NULL; else error_message = StringValuePtr(str); ret = gvl_PQputCopyEnd(conn, error_message); if(ret == -1) { error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } return (ret) ? Qtrue : Qfalse; } /* * call-seq: * conn.get_copy_data( [ async = false ] ) -> String * * Return a string containing one row of data, +nil+ * if the copy is done, or +false+ if the call would * block (only possible if _async_ is true). * * See also #copy_data. * */ static VALUE pgconn_get_copy_data(int argc, VALUE *argv, VALUE self ) { VALUE async_in; VALUE error; VALUE result_str; int ret; int async; char *buffer; PGconn *conn = pg_get_pgconn(self); if (rb_scan_args(argc, argv, "01", &async_in) == 0) async = 0; else async = (async_in == Qfalse || async_in == Qnil) ? 0 : 1; ret = gvl_PQgetCopyData(conn, &buffer, async); if(ret == -2) { /* error */ error = rb_exc_new2(rb_ePGerror, PQerrorMessage(conn)); rb_iv_set(error, "@connection", self); rb_exc_raise(error); } if(ret == -1) { /* No data left */ return Qnil; } if(ret == 0) { /* would block */ return Qfalse; } result_str = rb_tainted_str_new(buffer, ret); PQfreemem(buffer); return result_str; } /* * call-seq: * conn.set_error_verbosity( verbosity ) -> Fixnum * * Sets connection's verbosity to _verbosity_ and returns * the previous setting. Available settings are: * * PQERRORS_TERSE * * PQERRORS_DEFAULT * * PQERRORS_VERBOSE */ static VALUE pgconn_set_error_verbosity(VALUE self, VALUE in_verbosity) { PGconn *conn = pg_get_pgconn(self); PGVerbosity verbosity = NUM2INT(in_verbosity); return INT2FIX(PQsetErrorVerbosity(conn, verbosity)); } /* * call-seq: * conn.trace( stream ) -> nil * * Enables tracing message passing between backend. The * trace message will be written to the stream _stream_, * which must implement a method +fileno+ that returns * a writable file descriptor. */ static VALUE pgconn_trace(VALUE self, VALUE stream) { VALUE fileno; FILE *new_fp; int old_fd, new_fd; VALUE new_file; if(rb_respond_to(stream,rb_intern("fileno")) == Qfalse) rb_raise(rb_eArgError, "stream does not respond to method: fileno"); fileno = rb_funcall(stream, rb_intern("fileno"), 0); if(fileno == Qnil) rb_raise(rb_eArgError, "can't get file descriptor from stream"); /* Duplicate the file descriptor and re-open * it. Then, make it into a ruby File object * and assign it to an instance variable. * This prevents a problem when the File * object passed to this function is closed * before the connection object is. */ old_fd = NUM2INT(fileno); new_fd = dup(old_fd); new_fp = fdopen(new_fd, "w"); if(new_fp == NULL) rb_raise(rb_eArgError, "stream is not writable"); new_file = rb_funcall(rb_cIO, rb_intern("new"), 1, INT2NUM(new_fd)); rb_iv_set(self, "@trace_stream", new_file); PQtrace(pg_get_pgconn(self), new_fp); return Qnil; } /* * call-seq: * conn.untrace() -> nil * * Disables the message tracing. */ static VALUE pgconn_untrace(VALUE self) { VALUE trace_stream; PQuntrace(pg_get_pgconn(self)); trace_stream = rb_iv_get(self, "@trace_stream"); rb_funcall(trace_stream, rb_intern("close"), 0); rb_iv_set(self, "@trace_stream", Qnil); return Qnil; } /* * Notice callback proxy function -- delegate the callback to the * currently-registered Ruby notice_receiver object. */ void notice_receiver_proxy(void *arg, const PGresult *result) { VALUE proc; VALUE self = (VALUE)arg; if ((proc = rb_iv_get(self, "@notice_receiver")) != Qnil) { VALUE val = Data_Wrap_Struct(rb_cPGresult, NULL, NULL, (PGresult*)result); #ifdef M17N_SUPPORTED PGconn *conn = pg_get_pgconn( self ); rb_encoding *enc = pg_conn_enc_get( conn ); ENCODING_SET( val, rb_enc_to_index(enc) ); #endif rb_funcall(proc, rb_intern("call"), 1, val); } return; } /* * call-seq: * conn.set_notice_receiver {|result| ... } -> Proc * * Notice and warning messages generated by the server are not returned * by the query execution functions, since they do not imply failure of * the query. Instead they are passed to a notice handling function, and * execution continues normally after the handler returns. The default * notice handling function prints the message on stderr, but the * application can override this behavior by supplying its own handling * function. * * For historical reasons, there are two levels of notice handling, called the * notice receiver and notice processor. The default behavior is for the notice * receiver to format the notice and pass a string to the notice processor for * printing. However, an application that chooses to provide its own notice * receiver will typically ignore the notice processor layer and just do all * the work in the notice receiver. * * This function takes a new block to act as the handler, which should * accept a single parameter that will be a PG::Result object, and returns * the Proc object previously set, or +nil+ if it was previously the default. * * If you pass no arguments, it will reset the handler to the default. * * *Note:* The +result+ passed to the block should not be used outside * of the block, since the corresponding C object could be freed after the * block finishes. */ static VALUE pgconn_set_notice_receiver(VALUE self) { VALUE proc, old_proc; PGconn *conn = pg_get_pgconn(self); /* If default_notice_receiver is unset, assume that the current * notice receiver is the default, and save it to a global variable. * This should not be a problem because the default receiver is * always the same, so won't vary among connections. */ if(default_notice_receiver == NULL) default_notice_receiver = PQsetNoticeReceiver(conn, NULL, NULL); old_proc = rb_iv_get(self, "@notice_receiver"); if( rb_block_given_p() ) { proc = rb_block_proc(); PQsetNoticeReceiver(conn, gvl_notice_receiver_proxy, (void *)self); } else { /* if no block is given, set back to default */ proc = Qnil; PQsetNoticeReceiver(conn, default_notice_receiver, NULL); } rb_iv_set(self, "@notice_receiver", proc); return old_proc; } /* * Notice callback proxy function -- delegate the callback to the * currently-registered Ruby notice_processor object. */ void notice_processor_proxy(void *arg, const char *message) { VALUE proc; VALUE self = (VALUE)arg; if ((proc = rb_iv_get(self, "@notice_processor")) != Qnil) { VALUE message_str = rb_tainted_str_new2(message); #ifdef M17N_SUPPORTED PGconn *conn = pg_get_pgconn( self ); rb_encoding *enc = pg_conn_enc_get( conn ); ENCODING_SET( message_str, rb_enc_to_index(enc) ); #endif rb_funcall(proc, rb_intern("call"), 1, message_str); } return; } /* * call-seq: * conn.set_notice_processor {|message| ... } -> Proc * * See #set_notice_receiver for the desription of what this and the * notice_processor methods do. * * This function takes a new block to act as the notice processor and returns * the Proc object previously set, or +nil+ if it was previously the default. * The block should accept a single String object. * * If you pass no arguments, it will reset the handler to the default. */ static VALUE pgconn_set_notice_processor(VALUE self) { VALUE proc, old_proc; PGconn *conn = pg_get_pgconn(self); /* If default_notice_processor is unset, assume that the current * notice processor is the default, and save it to a global variable. * This should not be a problem because the default processor is * always the same, so won't vary among connections. */ if(default_notice_processor == NULL) default_notice_processor = PQsetNoticeProcessor(conn, NULL, NULL); old_proc = rb_iv_get(self, "@notice_processor"); if( rb_block_given_p() ) { proc = rb_block_proc(); PQsetNoticeProcessor(conn, gvl_notice_processor_proxy, (void *)self); } else { /* if no block is given, set back to default */ proc = Qnil; PQsetNoticeProcessor(conn, default_notice_processor, NULL); } rb_iv_set(self, "@notice_processor", proc); return old_proc; } /* * call-seq: * conn.get_client_encoding() -> String * * Returns the client encoding as a String. */ static VALUE pgconn_get_client_encoding(VALUE self) { char *encoding = (char *)pg_encoding_to_char(PQclientEncoding(pg_get_pgconn(self))); return rb_tainted_str_new2(encoding); } /* * call-seq: * conn.set_client_encoding( encoding ) * * Sets the client encoding to the _encoding_ String. */ static VALUE pgconn_set_client_encoding(VALUE self, VALUE str) { PGconn *conn = pg_get_pgconn( self ); Check_Type(str, T_STRING); if ( (PQsetClientEncoding(conn, StringValuePtr(str))) == -1 ) { rb_raise(rb_ePGerror, "invalid encoding name: %s",StringValuePtr(str)); } return Qnil; } /* * call-seq: * conn.transaction { |conn| ... } -> result of the block * * Executes a +BEGIN+ at the start of the block, * and a +COMMIT+ at the end of the block, or * +ROLLBACK+ if any exception occurs. */ static VALUE pgconn_transaction(VALUE self) { PGconn *conn = pg_get_pgconn(self); PGresult *result; VALUE rb_pgresult; VALUE block_result = Qnil; int status; if (rb_block_given_p()) { result = gvl_PQexec(conn, "BEGIN"); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); block_result = rb_protect(rb_yield, self, &status); if(status == 0) { result = gvl_PQexec(conn, "COMMIT"); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); } else { /* exception occurred, ROLLBACK and re-raise */ result = gvl_PQexec(conn, "ROLLBACK"); rb_pgresult = pg_new_result(result, self); pg_result_check(rb_pgresult); rb_jump_tag(status); } } else { /* no block supplied? */ rb_raise(rb_eArgError, "Must supply block for PG::Connection#transaction"); } return block_result; } /* * call-seq: * PG::Connection.quote_ident( str ) -> String * conn.quote_ident( str ) -> String * * Returns a string that is safe for inclusion in a SQL query as an * identifier. Note: this is not a quote function for values, but for * identifiers. * * For example, in a typical SQL query: SELECT FOO FROM MYTABLE * The identifier FOO is folded to lower case, so it actually * means foo. If you really want to access the case-sensitive * field name FOO, use this function like * PG::Connection.quote_ident('FOO'), which will return "FOO" * (with double-quotes). PostgreSQL will see the double-quotes, and * it will not fold to lower case. * * Similarly, this function also protects against special characters, * and other things that might allow SQL injection if the identifier * comes from an untrusted source. */ static VALUE pgconn_s_quote_ident(VALUE self, VALUE in_str) { VALUE ret; char *str = StringValuePtr(in_str); /* result size at most NAMEDATALEN*2 plus surrounding * double-quotes. */ char buffer[NAMEDATALEN*2+2]; unsigned int i=0,j=0; #ifdef M17N_SUPPORTED rb_encoding* enc; #endif UNUSED( self ); if(strlen(str) >= NAMEDATALEN) { rb_raise(rb_eArgError, "Input string is longer than NAMEDATALEN-1 (%d)", NAMEDATALEN-1); } buffer[j++] = '"'; for(i = 0; i < strlen(str) && str[i]; i++) { if(str[i] == '"') buffer[j++] = '"'; buffer[j++] = str[i]; } buffer[j++] = '"'; ret = rb_str_new(buffer,j); OBJ_INFECT(ret, in_str); #ifdef M17N_SUPPORTED if ( rb_obj_class(self) == rb_cPGconn ) { enc = pg_conn_enc_get( pg_get_pgconn(self) ); } else { enc = rb_enc_get(in_str); } rb_enc_associate(ret, enc); #endif return ret; } static void * get_result_readable(PGconn *conn) { return gvl_PQisBusy(conn) ? NULL : (void*)1; } /* * call-seq: * conn.block( [ timeout ] ) -> Boolean * * Blocks until the server is no longer busy, or until the * optional _timeout_ is reached, whichever comes first. * _timeout_ is measured in seconds and can be fractional. * * Returns +false+ if _timeout_ is reached, +true+ otherwise. * * If +true+ is returned, +conn.is_busy+ will return +false+ * and +conn.get_result+ will not block. */ static VALUE pgconn_block( int argc, VALUE *argv, VALUE self ) { PGconn *conn = pg_get_pgconn( self ); /* If WIN32 and Ruby 1.9 do not use rb_thread_select() which sometimes hangs * and does not wait (nor sleep) any time even if timeout is given. * Instead use the Winsock events and rb_w32_wait_events(). */ struct timeval timeout; struct timeval *ptimeout = NULL; VALUE timeout_in; double timeout_sec; void *ret; if ( rb_scan_args(argc, argv, "01", &timeout_in) == 1 ) { timeout_sec = NUM2DBL( timeout_in ); timeout.tv_sec = (time_t)timeout_sec; timeout.tv_usec = (suseconds_t)((timeout_sec - (long)timeout_sec) * 1e6); ptimeout = &timeout; } ret = wait_socket_readable( conn, ptimeout, get_result_readable); if( !ret ) return Qfalse; return Qtrue; } /* * call-seq: * conn.get_last_result( ) -> PG::Result * * This function retrieves all available results * on the current connection (from previously issued * asynchronous commands like +send_query()+) and * returns the last non-NULL result, or +nil+ if no * results are available. * * This function is similar to #get_result * except that it is designed to get one and only * one result. */ static VALUE pgconn_get_last_result(VALUE self) { PGconn *conn = pg_get_pgconn(self); VALUE rb_pgresult = Qnil; PGresult *cur, *prev; cur = prev = NULL; while ((cur = gvl_PQgetResult(conn)) != NULL) { int status; if (prev) PQclear(prev); prev = cur; status = PQresultStatus(cur); if (status == PGRES_COPY_OUT || status == PGRES_COPY_IN) break; } if (prev) { rb_pgresult = pg_new_result( prev, self ); pg_result_check(rb_pgresult); } return rb_pgresult; } #if !defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL) /* * call-seq: * conn.async_exec(sql [, params, result_format ] ) -> PG::Result * conn.async_exec(sql [, params, result_format ] ) {|pg_result| block } * * This function has the same behavior as #exec, * but ensures that other threads can process while * waiting for the server to complete the request. * * On Ruby platforms with native threads (MRI-1.9+ and all others) * this method is an alias to #exec. * * On MRI-1.8 it's implemented using asynchronous command * processing and ruby's +rb_thread_select+ . */ static VALUE pgconn_async_exec(int argc, VALUE *argv, VALUE self) { VALUE rb_pgresult = Qnil; /* remove any remaining results from the queue */ pgconn_block( 0, NULL, self ); /* wait for input (without blocking) before reading the last result */ pgconn_get_last_result( self ); pgconn_send_query( argc, argv, self ); pgconn_block( 0, NULL, self ); rb_pgresult = pgconn_get_last_result( self ); if ( rb_block_given_p() ) { return rb_ensure( rb_yield, rb_pgresult, pg_result_clear, rb_pgresult ); } return rb_pgresult; } #endif /************************************************************************** * LARGE OBJECT SUPPORT **************************************************************************/ /* * call-seq: * conn.lo_creat( [mode] ) -> Fixnum * * Creates a large object with mode _mode_. Returns a large object Oid. * On failure, it raises PG::Error. */ static VALUE pgconn_locreat(int argc, VALUE *argv, VALUE self) { Oid lo_oid; int mode; VALUE nmode; PGconn *conn = pg_get_pgconn(self); if (rb_scan_args(argc, argv, "01", &nmode) == 0) mode = INV_READ; else mode = NUM2INT(nmode); lo_oid = lo_creat(conn, mode); if (lo_oid == 0) rb_raise(rb_ePGerror, "lo_creat failed"); return INT2FIX(lo_oid); } /* * call-seq: * conn.lo_create( oid ) -> Fixnum * * Creates a large object with oid _oid_. Returns the large object Oid. * On failure, it raises PG::Error. */ static VALUE pgconn_locreate(VALUE self, VALUE in_lo_oid) { Oid ret, lo_oid; PGconn *conn = pg_get_pgconn(self); lo_oid = NUM2INT(in_lo_oid); ret = lo_create(conn, lo_oid); if (ret == InvalidOid) rb_raise(rb_ePGerror, "lo_create failed"); return INT2FIX(ret); } /* * call-seq: * conn.lo_import(file) -> Fixnum * * Import a file to a large object. Returns a large object Oid. * * On failure, it raises a PG::Error. */ static VALUE pgconn_loimport(VALUE self, VALUE filename) { Oid lo_oid; PGconn *conn = pg_get_pgconn(self); Check_Type(filename, T_STRING); lo_oid = lo_import(conn, StringValuePtr(filename)); if (lo_oid == 0) { rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn)); } return INT2FIX(lo_oid); } /* * call-seq: * conn.lo_export( oid, file ) -> nil * * Saves a large object of _oid_ to a _file_. */ static VALUE pgconn_loexport(VALUE self, VALUE lo_oid, VALUE filename) { PGconn *conn = pg_get_pgconn(self); int oid; Check_Type(filename, T_STRING); oid = NUM2INT(lo_oid); if (oid < 0) { rb_raise(rb_ePGerror, "invalid large object oid %d",oid); } if (lo_export(conn, oid, StringValuePtr(filename)) < 0) { rb_raise(rb_ePGerror, "%s", PQerrorMessage(conn)); } return Qnil; } /* * call-seq: * conn.lo_open( oid, [mode] ) -> Fixnum * * Open a large object of _oid_. Returns a large object descriptor * instance on success. The _mode_ argument specifies the mode for * the opened large object,which is either +INV_READ+, or +INV_WRITE+. * * If _mode_ is omitted, the default is +INV_READ+. */ static VALUE pgconn_loopen(int argc, VALUE *argv, VALUE self) { Oid lo_oid; int fd, mode; VALUE nmode, selfid; PGconn *conn = pg_get_pgconn(self); rb_scan_args(argc, argv, "11", &selfid, &nmode); lo_oid = NUM2INT(selfid); if(NIL_P(nmode)) mode = INV_READ; else mode = NUM2INT(nmode); if((fd = lo_open(conn, lo_oid, mode)) < 0) { rb_raise(rb_ePGerror, "can't open large object: %s", PQerrorMessage(conn)); } return INT2FIX(fd); } /* * call-seq: * conn.lo_write( lo_desc, buffer ) -> Fixnum * * Writes the string _buffer_ to the large object _lo_desc_. * Returns the number of bytes written. */ static VALUE pgconn_lowrite(VALUE self, VALUE in_lo_desc, VALUE buffer) { int n; PGconn *conn = pg_get_pgconn(self); int fd = NUM2INT(in_lo_desc); Check_Type(buffer, T_STRING); if( RSTRING_LEN(buffer) < 0) { rb_raise(rb_ePGerror, "write buffer zero string"); } if((n = lo_write(conn, fd, StringValuePtr(buffer), RSTRING_LEN(buffer))) < 0) { rb_raise(rb_ePGerror, "lo_write failed: %s", PQerrorMessage(conn)); } return INT2FIX(n); } /* * call-seq: * conn.lo_read( lo_desc, len ) -> String * * Attempts to read _len_ bytes from large object _lo_desc_, * returns resulting data. */ static VALUE pgconn_loread(VALUE self, VALUE in_lo_desc, VALUE in_len) { int ret; PGconn *conn = pg_get_pgconn(self); int len = NUM2INT(in_len); int lo_desc = NUM2INT(in_lo_desc); VALUE str; char *buffer; buffer = ALLOC_N(char, len); if(buffer == NULL) rb_raise(rb_eNoMemError, "ALLOC failed!"); if (len < 0){ rb_raise(rb_ePGerror,"nagative length %d given", len); } if((ret = lo_read(conn, lo_desc, buffer, len)) < 0) rb_raise(rb_ePGerror, "lo_read failed"); if(ret == 0) { xfree(buffer); return Qnil; } str = rb_tainted_str_new(buffer, ret); xfree(buffer); return str; } /* * call-seq: * conn.lo_lseek( lo_desc, offset, whence ) -> Fixnum * * Move the large object pointer _lo_desc_ to offset _offset_. * Valid values for _whence_ are +SEEK_SET+, +SEEK_CUR+, and +SEEK_END+. * (Or 0, 1, or 2.) */ static VALUE pgconn_lolseek(VALUE self, VALUE in_lo_desc, VALUE offset, VALUE whence) { PGconn *conn = pg_get_pgconn(self); int lo_desc = NUM2INT(in_lo_desc); int ret; if((ret = lo_lseek(conn, lo_desc, NUM2INT(offset), NUM2INT(whence))) < 0) { rb_raise(rb_ePGerror, "lo_lseek failed"); } return INT2FIX(ret); } /* * call-seq: * conn.lo_tell( lo_desc ) -> Fixnum * * Returns the current position of the large object _lo_desc_. */ static VALUE pgconn_lotell(VALUE self, VALUE in_lo_desc) { int position; PGconn *conn = pg_get_pgconn(self); int lo_desc = NUM2INT(in_lo_desc); if((position = lo_tell(conn, lo_desc)) < 0) rb_raise(rb_ePGerror,"lo_tell failed"); return INT2FIX(position); } /* * call-seq: * conn.lo_truncate( lo_desc, len ) -> nil * * Truncates the large object _lo_desc_ to size _len_. */ static VALUE pgconn_lotruncate(VALUE self, VALUE in_lo_desc, VALUE in_len) { PGconn *conn = pg_get_pgconn(self); int lo_desc = NUM2INT(in_lo_desc); size_t len = NUM2INT(in_len); if(lo_truncate(conn,lo_desc,len) < 0) rb_raise(rb_ePGerror,"lo_truncate failed"); return Qnil; } /* * call-seq: * conn.lo_close( lo_desc ) -> nil * * Closes the postgres large object of _lo_desc_. */ static VALUE pgconn_loclose(VALUE self, VALUE in_lo_desc) { PGconn *conn = pg_get_pgconn(self); int lo_desc = NUM2INT(in_lo_desc); if(lo_close(conn,lo_desc) < 0) rb_raise(rb_ePGerror,"lo_close failed"); return Qnil; } /* * call-seq: * conn.lo_unlink( oid ) -> nil * * Unlinks (deletes) the postgres large object of _oid_. */ static VALUE pgconn_lounlink(VALUE self, VALUE in_oid) { PGconn *conn = pg_get_pgconn(self); int oid = NUM2INT(in_oid); if (oid < 0) rb_raise(rb_ePGerror, "invalid oid %d",oid); if(lo_unlink(conn,oid) < 0) rb_raise(rb_ePGerror,"lo_unlink failed"); return Qnil; } #ifdef M17N_SUPPORTED /* * call-seq: * conn.internal_encoding -> Encoding * * defined in Ruby 1.9 or later. * * Returns: * * an Encoding - client_encoding of the connection as a Ruby Encoding object. * * nil - the client_encoding is 'SQL_ASCII' */ static VALUE pgconn_internal_encoding(VALUE self) { PGconn *conn = pg_get_pgconn( self ); rb_encoding *enc = pg_conn_enc_get( conn ); if ( enc ) { return rb_enc_from_encoding( enc ); } else { return Qnil; } } static VALUE pgconn_external_encoding(VALUE self); /* * call-seq: * conn.internal_encoding = value * * A wrapper of #set_client_encoding. * defined in Ruby 1.9 or later. * * +value+ can be one of: * * an Encoding * * a String - a name of Encoding * * +nil+ - sets the client_encoding to SQL_ASCII. */ static VALUE pgconn_internal_encoding_set(VALUE self, VALUE enc) { if (NIL_P(enc)) { pgconn_set_client_encoding( self, rb_usascii_str_new_cstr("SQL_ASCII") ); return enc; } else if ( TYPE(enc) == T_STRING && strcasecmp("JOHAB", RSTRING_PTR(enc)) == 0 ) { pgconn_set_client_encoding(self, rb_usascii_str_new_cstr("JOHAB")); return enc; } else { rb_encoding *rbenc = rb_to_encoding( enc ); const char *name = pg_get_rb_encoding_as_pg_encoding( rbenc ); if ( PQsetClientEncoding(pg_get_pgconn( self ), name) == -1 ) { VALUE server_encoding = pgconn_external_encoding( self ); rb_raise( rb_eEncCompatError, "incompatible character encodings: %s and %s", rb_enc_name(rb_to_encoding(server_encoding)), name ); } return enc; } rb_raise( rb_ePGerror, "unknown encoding: %s", RSTRING_PTR(rb_inspect(enc)) ); return Qnil; } /* * call-seq: * conn.external_encoding() -> Encoding * * Return the +server_encoding+ of the connected database as a Ruby Encoding object. * The SQL_ASCII encoding is mapped to to ASCII_8BIT. */ static VALUE pgconn_external_encoding(VALUE self) { PGconn *conn = pg_get_pgconn( self ); VALUE encoding = rb_iv_get( self, "@external_encoding" ); rb_encoding *enc = NULL; const char *pg_encname = NULL; /* Use cached value if found */ if ( RTEST(encoding) ) return encoding; pg_encname = PQparameterStatus( conn, "server_encoding" ); enc = pg_get_pg_encname_as_rb_encoding( pg_encname ); encoding = rb_enc_from_encoding( enc ); rb_iv_set( self, "@external_encoding", encoding ); return encoding; } /* * call-seq: * conn.set_default_encoding() -> Encoding * * If Ruby has its Encoding.default_internal set, set PostgreSQL's client_encoding * to match. Returns the new Encoding, or +nil+ if the default internal encoding * wasn't set. */ static VALUE pgconn_set_default_encoding( VALUE self ) { PGconn *conn = pg_get_pgconn( self ); rb_encoding *enc; const char *encname; if (( enc = rb_default_internal_encoding() )) { encname = pg_get_rb_encoding_as_pg_encoding( enc ); if ( PQsetClientEncoding(conn, encname) != 0 ) rb_warn( "Failed to set the default_internal encoding to %s: '%s'", encname, PQerrorMessage(conn) ); return rb_enc_from_encoding( enc ); } else { return Qnil; } } #endif /* M17N_SUPPORTED */ void init_pg_connection() { rb_cPGconn = rb_define_class_under( rb_mPG, "Connection", rb_cObject ); rb_include_module(rb_cPGconn, rb_mPGconstants); /****** PG::Connection CLASS METHODS ******/ rb_define_alloc_func( rb_cPGconn, pgconn_s_allocate ); SINGLETON_ALIAS(rb_cPGconn, "connect", "new"); SINGLETON_ALIAS(rb_cPGconn, "open", "new"); SINGLETON_ALIAS(rb_cPGconn, "setdb", "new"); SINGLETON_ALIAS(rb_cPGconn, "setdblogin", "new"); rb_define_singleton_method(rb_cPGconn, "escape_string", pgconn_s_escape, 1); SINGLETON_ALIAS(rb_cPGconn, "escape", "escape_string"); rb_define_singleton_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1); rb_define_singleton_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1); rb_define_singleton_method(rb_cPGconn, "encrypt_password", pgconn_s_encrypt_password, 2); rb_define_singleton_method(rb_cPGconn, "quote_ident", pgconn_s_quote_ident, 1); rb_define_singleton_method(rb_cPGconn, "connect_start", pgconn_s_connect_start, -1); rb_define_singleton_method(rb_cPGconn, "conndefaults", pgconn_s_conndefaults, 0); #ifdef HAVE_PQPING rb_define_singleton_method(rb_cPGconn, "ping", pgconn_s_ping, -1); #endif /****** PG::Connection INSTANCE METHODS: Connection Control ******/ rb_define_method(rb_cPGconn, "initialize", pgconn_init, -1); rb_define_method(rb_cPGconn, "connect_poll", pgconn_connect_poll, 0); rb_define_method(rb_cPGconn, "finish", pgconn_finish, 0); rb_define_method(rb_cPGconn, "finished?", pgconn_finished_p, 0); rb_define_method(rb_cPGconn, "reset", pgconn_reset, 0); rb_define_method(rb_cPGconn, "reset_start", pgconn_reset_start, 0); rb_define_method(rb_cPGconn, "reset_poll", pgconn_reset_poll, 0); rb_define_method(rb_cPGconn, "conndefaults", pgconn_s_conndefaults, 0); rb_define_alias(rb_cPGconn, "close", "finish"); /****** PG::Connection INSTANCE METHODS: Connection Status ******/ rb_define_method(rb_cPGconn, "db", pgconn_db, 0); rb_define_method(rb_cPGconn, "user", pgconn_user, 0); rb_define_method(rb_cPGconn, "pass", pgconn_pass, 0); rb_define_method(rb_cPGconn, "host", pgconn_host, 0); rb_define_method(rb_cPGconn, "port", pgconn_port, 0); rb_define_method(rb_cPGconn, "tty", pgconn_tty, 0); rb_define_method(rb_cPGconn, "options", pgconn_options, 0); rb_define_method(rb_cPGconn, "status", pgconn_status, 0); rb_define_method(rb_cPGconn, "transaction_status", pgconn_transaction_status, 0); rb_define_method(rb_cPGconn, "parameter_status", pgconn_parameter_status, 1); rb_define_method(rb_cPGconn, "protocol_version", pgconn_protocol_version, 0); rb_define_method(rb_cPGconn, "server_version", pgconn_server_version, 0); rb_define_method(rb_cPGconn, "error_message", pgconn_error_message, 0); rb_define_method(rb_cPGconn, "socket", pgconn_socket, 0); #if !defined(_WIN32) || defined(HAVE_RB_W32_WRAP_IO_HANDLE) rb_define_method(rb_cPGconn, "socket_io", pgconn_socket_io, 0); #endif rb_define_method(rb_cPGconn, "backend_pid", pgconn_backend_pid, 0); rb_define_method(rb_cPGconn, "connection_needs_password", pgconn_connection_needs_password, 0); rb_define_method(rb_cPGconn, "connection_used_password", pgconn_connection_used_password, 0); /* rb_define_method(rb_cPGconn, "getssl", pgconn_getssl, 0); */ /****** PG::Connection INSTANCE METHODS: Command Execution ******/ rb_define_method(rb_cPGconn, "exec", pgconn_exec, -1); rb_define_alias(rb_cPGconn, "query", "exec"); rb_define_method(rb_cPGconn, "exec_params", pgconn_exec_params, -1); rb_define_method(rb_cPGconn, "prepare", pgconn_prepare, -1); rb_define_method(rb_cPGconn, "exec_prepared", pgconn_exec_prepared, -1); rb_define_method(rb_cPGconn, "describe_prepared", pgconn_describe_prepared, 1); rb_define_method(rb_cPGconn, "describe_portal", pgconn_describe_portal, 1); rb_define_method(rb_cPGconn, "make_empty_pgresult", pgconn_make_empty_pgresult, 1); rb_define_method(rb_cPGconn, "escape_string", pgconn_s_escape, 1); rb_define_alias(rb_cPGconn, "escape", "escape_string"); #ifdef HAVE_PQESCAPELITERAL rb_define_method(rb_cPGconn, "escape_literal", pgconn_escape_literal, 1); #endif #ifdef HAVE_PQESCAPEIDENTIFIER rb_define_method(rb_cPGconn, "escape_identifier", pgconn_escape_identifier, 1); #endif rb_define_method(rb_cPGconn, "escape_bytea", pgconn_s_escape_bytea, 1); rb_define_method(rb_cPGconn, "unescape_bytea", pgconn_s_unescape_bytea, 1); #ifdef HAVE_PQSETSINGLEROWMODE rb_define_method(rb_cPGconn, "set_single_row_mode", pgconn_set_single_row_mode, 0); #endif /****** PG::Connection INSTANCE METHODS: Asynchronous Command Processing ******/ rb_define_method(rb_cPGconn, "send_query", pgconn_send_query, -1); rb_define_method(rb_cPGconn, "send_prepare", pgconn_send_prepare, -1); rb_define_method(rb_cPGconn, "send_query_prepared", pgconn_send_query_prepared, -1); rb_define_method(rb_cPGconn, "send_describe_prepared", pgconn_send_describe_prepared, 1); rb_define_method(rb_cPGconn, "send_describe_portal", pgconn_send_describe_portal, 1); rb_define_method(rb_cPGconn, "get_result", pgconn_get_result, 0); rb_define_method(rb_cPGconn, "consume_input", pgconn_consume_input, 0); rb_define_method(rb_cPGconn, "is_busy", pgconn_is_busy, 0); rb_define_method(rb_cPGconn, "setnonblocking", pgconn_setnonblocking, 1); rb_define_method(rb_cPGconn, "isnonblocking", pgconn_isnonblocking, 0); rb_define_alias(rb_cPGconn, "nonblocking?", "isnonblocking"); rb_define_method(rb_cPGconn, "flush", pgconn_flush, 0); /****** PG::Connection INSTANCE METHODS: Cancelling Queries in Progress ******/ rb_define_method(rb_cPGconn, "cancel", pgconn_cancel, 0); /****** PG::Connection INSTANCE METHODS: NOTIFY ******/ rb_define_method(rb_cPGconn, "notifies", pgconn_notifies, 0); /****** PG::Connection INSTANCE METHODS: COPY ******/ rb_define_method(rb_cPGconn, "put_copy_data", pgconn_put_copy_data, 1); rb_define_method(rb_cPGconn, "put_copy_end", pgconn_put_copy_end, -1); rb_define_method(rb_cPGconn, "get_copy_data", pgconn_get_copy_data, -1); /****** PG::Connection INSTANCE METHODS: Control Functions ******/ rb_define_method(rb_cPGconn, "set_error_verbosity", pgconn_set_error_verbosity, 1); rb_define_method(rb_cPGconn, "trace", pgconn_trace, 1); rb_define_method(rb_cPGconn, "untrace", pgconn_untrace, 0); /****** PG::Connection INSTANCE METHODS: Notice Processing ******/ rb_define_method(rb_cPGconn, "set_notice_receiver", pgconn_set_notice_receiver, 0); rb_define_method(rb_cPGconn, "set_notice_processor", pgconn_set_notice_processor, 0); /****** PG::Connection INSTANCE METHODS: Other ******/ rb_define_method(rb_cPGconn, "get_client_encoding", pgconn_get_client_encoding, 0); rb_define_method(rb_cPGconn, "set_client_encoding", pgconn_set_client_encoding, 1); rb_define_alias(rb_cPGconn, "client_encoding=", "set_client_encoding"); rb_define_method(rb_cPGconn, "transaction", pgconn_transaction, 0); rb_define_method(rb_cPGconn, "block", pgconn_block, -1); rb_define_method(rb_cPGconn, "wait_for_notify", pgconn_wait_for_notify, -1); rb_define_alias(rb_cPGconn, "notifies_wait", "wait_for_notify"); rb_define_method(rb_cPGconn, "quote_ident", pgconn_s_quote_ident, 1); #if defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL) rb_define_alias(rb_cPGconn, "async_exec", "exec"); #else rb_define_method(rb_cPGconn, "async_exec", pgconn_async_exec, -1); #endif rb_define_alias(rb_cPGconn, "async_query", "async_exec"); rb_define_method(rb_cPGconn, "get_last_result", pgconn_get_last_result, 0); /****** PG::Connection INSTANCE METHODS: Large Object Support ******/ rb_define_method(rb_cPGconn, "lo_creat", pgconn_locreat, -1); rb_define_alias(rb_cPGconn, "locreat", "lo_creat"); rb_define_method(rb_cPGconn, "lo_create", pgconn_locreate, 1); rb_define_alias(rb_cPGconn, "locreate", "lo_create"); rb_define_method(rb_cPGconn, "lo_import", pgconn_loimport, 1); rb_define_alias(rb_cPGconn, "loimport", "lo_import"); rb_define_method(rb_cPGconn, "lo_export", pgconn_loexport, 2); rb_define_alias(rb_cPGconn, "loexport", "lo_export"); rb_define_method(rb_cPGconn, "lo_open", pgconn_loopen, -1); rb_define_alias(rb_cPGconn, "loopen", "lo_open"); rb_define_method(rb_cPGconn, "lo_write",pgconn_lowrite, 2); rb_define_alias(rb_cPGconn, "lowrite", "lo_write"); rb_define_method(rb_cPGconn, "lo_read",pgconn_loread, 2); rb_define_alias(rb_cPGconn, "loread", "lo_read"); rb_define_method(rb_cPGconn, "lo_lseek",pgconn_lolseek, 3); rb_define_alias(rb_cPGconn, "lolseek", "lo_lseek"); rb_define_alias(rb_cPGconn, "lo_seek", "lo_lseek"); rb_define_alias(rb_cPGconn, "loseek", "lo_lseek"); rb_define_method(rb_cPGconn, "lo_tell",pgconn_lotell, 1); rb_define_alias(rb_cPGconn, "lotell", "lo_tell"); rb_define_method(rb_cPGconn, "lo_truncate", pgconn_lotruncate, 2); rb_define_alias(rb_cPGconn, "lotruncate", "lo_truncate"); rb_define_method(rb_cPGconn, "lo_close",pgconn_loclose, 1); rb_define_alias(rb_cPGconn, "loclose", "lo_close"); rb_define_method(rb_cPGconn, "lo_unlink", pgconn_lounlink, 1); rb_define_alias(rb_cPGconn, "lounlink", "lo_unlink"); #ifdef M17N_SUPPORTED rb_define_method(rb_cPGconn, "internal_encoding", pgconn_internal_encoding, 0); rb_define_method(rb_cPGconn, "internal_encoding=", pgconn_internal_encoding_set, 1); rb_define_method(rb_cPGconn, "external_encoding", pgconn_external_encoding, 0); rb_define_method(rb_cPGconn, "set_default_encoding", pgconn_set_default_encoding, 0); #endif /* M17N_SUPPORTED */ } ruby-pg-0.17.0/ext/pg_errors.c000066400000000000000000000041561222421776500161500ustar00rootroot00000000000000/* * pg_errors.c - Definition and lookup of error classes. * */ #include "pg.h" VALUE rb_hErrors; VALUE rb_ePGerror; VALUE rb_eServerError; VALUE rb_eUnableToSend; VALUE rb_eConnectionBad; static VALUE define_error_class(const char *name, const char *baseclass_code) { VALUE baseclass = rb_eServerError; if(baseclass_code) { baseclass = rb_hash_aref( rb_hErrors, rb_str_new2(baseclass_code) ); } return rb_define_class_under( rb_mPG, name, baseclass ); } static void register_error_class(const char *code, VALUE klass) { rb_hash_aset( rb_hErrors, rb_str_new2(code), klass ); } /* Find a proper error class for the given SQLSTATE string */ VALUE lookup_error_class(const char *sqlstate) { VALUE klass; if(sqlstate) { /* Find the proper error class by the 5-characters SQLSTATE. */ klass = rb_hash_aref( rb_hErrors, rb_str_new2(sqlstate) ); if(NIL_P(klass)) { /* The given SQLSTATE couldn't be found. This might happen, if * the server side uses a newer version than the client. * Try to find a error class by using the 2-characters SQLSTATE. */ klass = rb_hash_aref( rb_hErrors, rb_str_new(sqlstate, 2) ); if(NIL_P(klass)) { /* Also the 2-characters SQLSTATE is unknown. * Use the generic server error instead. */ klass = rb_eServerError; } } } else { /* Unable to retrieve the PG_DIAG_SQLSTATE. * Use the generic error instead. */ klass = rb_eUnableToSend; } return klass; } void init_pg_errors() { rb_hErrors = rb_hash_new(); rb_define_const( rb_mPG, "ERROR_CLASSES", rb_hErrors ); rb_ePGerror = rb_define_class_under( rb_mPG, "Error", rb_eStandardError ); /************************* * PG::Error *************************/ rb_define_alias( rb_ePGerror, "error", "message" ); rb_define_attr( rb_ePGerror, "connection", 1, 0 ); rb_define_attr( rb_ePGerror, "result", 1, 0 ); rb_eServerError = rb_define_class_under( rb_mPG, "ServerError", rb_ePGerror ); rb_eUnableToSend = rb_define_class_under( rb_mPG, "UnableToSend", rb_ePGerror ); rb_eConnectionBad = rb_define_class_under( rb_mPG, "ConnectionBad", rb_ePGerror ); #include "errorcodes.def" } ruby-pg-0.17.0/ext/pg_result.c000066400000000000000000000550731222421776500161560ustar00rootroot00000000000000/* * pg_result.c - PG::Result class extension * $Id$ * */ #include "pg.h" VALUE rb_cPGresult; static void pgresult_gc_free( PGresult * ); static PGresult* pgresult_get( VALUE ); /* * Global functions */ /* * Result constructor */ VALUE pg_new_result(PGresult *result, VALUE rb_pgconn) { PGconn *conn = pg_get_pgconn( rb_pgconn ); VALUE val = Data_Wrap_Struct(rb_cPGresult, NULL, pgresult_gc_free, result); #ifdef M17N_SUPPORTED rb_encoding *enc = pg_conn_enc_get( conn ); ENCODING_SET( val, rb_enc_to_index(enc) ); #endif rb_iv_set( val, "@connection", rb_pgconn ); return val; } /* * call-seq: * res.check -> nil * * Raises appropriate exception if PG::Result is in a bad state. */ VALUE pg_result_check( VALUE self ) { VALUE error, exception, klass; VALUE rb_pgconn = rb_iv_get( self, "@connection" ); PGconn *conn = pg_get_pgconn(rb_pgconn); PGresult *result; #ifdef M17N_SUPPORTED rb_encoding *enc = pg_conn_enc_get( conn ); #endif char * sqlstate; Data_Get_Struct(self, PGresult, result); if(result == NULL) { error = rb_str_new2( PQerrorMessage(conn) ); } else { switch (PQresultStatus(result)) { case PGRES_TUPLES_OK: case PGRES_COPY_OUT: case PGRES_COPY_IN: #ifdef HAVE_CONST_PGRES_COPY_BOTH case PGRES_COPY_BOTH: #endif #ifdef HAVE_CONST_PGRES_SINGLE_TUPLE case PGRES_SINGLE_TUPLE: #endif case PGRES_EMPTY_QUERY: case PGRES_COMMAND_OK: return self; case PGRES_BAD_RESPONSE: case PGRES_FATAL_ERROR: case PGRES_NONFATAL_ERROR: error = rb_str_new2( PQresultErrorMessage(result) ); break; default: error = rb_str_new2( "internal error : unknown result status." ); } } #ifdef M17N_SUPPORTED rb_enc_set_index( error, rb_enc_to_index(enc) ); #endif sqlstate = PQresultErrorField( result, PG_DIAG_SQLSTATE ); klass = lookup_error_class( sqlstate ); exception = rb_exc_new3( klass, error ); rb_iv_set( exception, "@connection", rb_pgconn ); rb_iv_set( exception, "@result", result ? self : Qnil ); rb_exc_raise( exception ); /* Not reached */ return self; } /* * :TODO: This shouldn't be a global function, but it needs to be as long as pg_new_result * doesn't handle blocks, check results, etc. Once connection and result are disentangled * a bit more, I can make this a static pgresult_clear() again. */ /* * call-seq: * res.clear() -> nil * * Clears the PG::Result object as the result of the query. */ VALUE pg_result_clear(VALUE self) { PQclear(pgresult_get(self)); DATA_PTR(self) = NULL; return Qnil; } /* * DATA pointer functions */ /* * GC Free function */ static void pgresult_gc_free( PGresult *result ) { if(result != NULL) PQclear(result); } /* * Fetch the data pointer for the result object */ static PGresult* pgresult_get(VALUE self) { PGresult *result; Data_Get_Struct(self, PGresult, result); if (result == NULL) rb_raise(rb_ePGerror, "result has been cleared"); return result; } /******************************************************************** * * Document-class: PG::Result * * The class to represent the query result tuples (rows). * An instance of this class is created as the result of every query. * You may need to invoke the #clear method of the instance when finished with * the result for better memory performance. * * Example: * require 'pg' * conn = PGconn.open(:dbname => 'test') * res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') * res.getvalue(0,0) # '1' * res[0]['b'] # '2' * res[0]['c'] # nil * */ /************************************************************************** * PG::Result INSTANCE METHODS **************************************************************************/ /* * call-seq: * res.result_status() -> Fixnum * * Returns the status of the query. The status value is one of: * * +PGRES_EMPTY_QUERY+ * * +PGRES_COMMAND_OK+ * * +PGRES_TUPLES_OK+ * * +PGRES_COPY_OUT+ * * +PGRES_COPY_IN+ * * +PGRES_BAD_RESPONSE+ * * +PGRES_NONFATAL_ERROR+ * * +PGRES_FATAL_ERROR+ * * +PGRES_COPY_BOTH+ */ static VALUE pgresult_result_status(VALUE self) { return INT2FIX(PQresultStatus(pgresult_get(self))); } /* * call-seq: * res.res_status( status ) -> String * * Returns the string representation of status +status+. * */ static VALUE pgresult_res_status(VALUE self, VALUE status) { VALUE ret = rb_tainted_str_new2(PQresStatus(NUM2INT(status))); ASSOCIATE_INDEX(ret, self); return ret; } /* * call-seq: * res.error_message() -> String * * Returns the error message of the command as a string. */ static VALUE pgresult_error_message(VALUE self) { VALUE ret = rb_tainted_str_new2(PQresultErrorMessage(pgresult_get(self))); ASSOCIATE_INDEX(ret, self); return ret; } /* * call-seq: * res.error_field(fieldcode) -> String * * Returns the individual field of an error. * * +fieldcode+ is one of: * * +PG_DIAG_SEVERITY+ * * +PG_DIAG_SQLSTATE+ * * +PG_DIAG_MESSAGE_PRIMARY+ * * +PG_DIAG_MESSAGE_DETAIL+ * * +PG_DIAG_MESSAGE_HINT+ * * +PG_DIAG_STATEMENT_POSITION+ * * +PG_DIAG_INTERNAL_POSITION+ * * +PG_DIAG_INTERNAL_QUERY+ * * +PG_DIAG_CONTEXT+ * * +PG_DIAG_SOURCE_FILE+ * * +PG_DIAG_SOURCE_LINE+ * * +PG_DIAG_SOURCE_FUNCTION+ * * An example: * * begin * conn.exec( "SELECT * FROM nonexistant_table" ) * rescue PG::Error => err * p [ * err.result.error_field( PG::Result::PG_DIAG_SEVERITY ), * err.result.error_field( PG::Result::PG_DIAG_SQLSTATE ), * err.result.error_field( PG::Result::PG_DIAG_MESSAGE_PRIMARY ), * err.result.error_field( PG::Result::PG_DIAG_MESSAGE_DETAIL ), * err.result.error_field( PG::Result::PG_DIAG_MESSAGE_HINT ), * err.result.error_field( PG::Result::PG_DIAG_STATEMENT_POSITION ), * err.result.error_field( PG::Result::PG_DIAG_INTERNAL_POSITION ), * err.result.error_field( PG::Result::PG_DIAG_INTERNAL_QUERY ), * err.result.error_field( PG::Result::PG_DIAG_CONTEXT ), * err.result.error_field( PG::Result::PG_DIAG_SOURCE_FILE ), * err.result.error_field( PG::Result::PG_DIAG_SOURCE_LINE ), * err.result.error_field( PG::Result::PG_DIAG_SOURCE_FUNCTION ), * ] * end * * Outputs: * * ["ERROR", "42P01", "relation \"nonexistant_table\" does not exist", nil, nil, * "15", nil, nil, nil, "path/to/parse_relation.c", "857", "parserOpenTable"] */ static VALUE pgresult_error_field(VALUE self, VALUE field) { PGresult *result = pgresult_get( self ); int fieldcode = NUM2INT( field ); char * fieldstr = PQresultErrorField( result, fieldcode ); VALUE ret = Qnil; if ( fieldstr ) { ret = rb_tainted_str_new2( fieldstr ); ASSOCIATE_INDEX( ret, self ); } return ret; } /* * call-seq: * res.ntuples() -> Fixnum * * Returns the number of tuples in the query result. */ static VALUE pgresult_ntuples(VALUE self) { return INT2FIX(PQntuples(pgresult_get(self))); } /* * call-seq: * res.nfields() -> Fixnum * * Returns the number of columns in the query result. */ static VALUE pgresult_nfields(VALUE self) { return INT2NUM(PQnfields(pgresult_get(self))); } /* * call-seq: * res.fname( index ) -> String * * Returns the name of the column corresponding to _index_. */ static VALUE pgresult_fname(VALUE self, VALUE index) { VALUE fname; PGresult *result; int i = NUM2INT(index); result = pgresult_get(self); if (i < 0 || i >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", i); } fname = rb_tainted_str_new2(PQfname(result, i)); ASSOCIATE_INDEX(fname, self); return fname; } /* * call-seq: * res.fnumber( name ) -> Fixnum * * Returns the index of the field specified by the string +name+. * The given +name+ is treated like an identifier in an SQL command, that is, * it is downcased unless double-quoted. For example, given a query result * generated from the SQL command: * * result = conn.exec( %{SELECT 1 AS FOO, 2 AS "BAR"} ) * * we would have the results: * * result.fname( 0 ) # => "foo" * result.fname( 1 ) # => "BAR" * result.fnumber( "FOO" ) # => 0 * result.fnumber( "foo" ) # => 0 * result.fnumber( "BAR" ) # => ArgumentError * result.fnumber( %{"BAR"} ) # => 1 * * Raises an ArgumentError if the specified +name+ isn't one of the field names; * raises a TypeError if +name+ is not a String. */ static VALUE pgresult_fnumber(VALUE self, VALUE name) { int n; Check_Type(name, T_STRING); n = PQfnumber(pgresult_get(self), StringValuePtr(name)); if (n == -1) { rb_raise(rb_eArgError,"Unknown field: %s", StringValuePtr(name)); } return INT2FIX(n); } /* * call-seq: * res.ftable( column_number ) -> Fixnum * * Returns the Oid of the table from which the column _column_number_ * was fetched. * * Raises ArgumentError if _column_number_ is out of range or if * the Oid is undefined for that column. */ static VALUE pgresult_ftable(VALUE self, VALUE column_number) { Oid n ; int col_number = NUM2INT(column_number); PGresult *pgresult = pgresult_get(self); if( col_number < 0 || col_number >= PQnfields(pgresult)) rb_raise(rb_eArgError,"Invalid column index: %d", col_number); n = PQftable(pgresult, col_number); return INT2FIX(n); } /* * call-seq: * res.ftablecol( column_number ) -> Fixnum * * Returns the column number (within its table) of the table from * which the column _column_number_ is made up. * * Raises ArgumentError if _column_number_ is out of range or if * the column number from its table is undefined for that column. */ static VALUE pgresult_ftablecol(VALUE self, VALUE column_number) { int col_number = NUM2INT(column_number); PGresult *pgresult = pgresult_get(self); int n; if( col_number < 0 || col_number >= PQnfields(pgresult)) rb_raise(rb_eArgError,"Invalid column index: %d", col_number); n = PQftablecol(pgresult, col_number); return INT2FIX(n); } /* * call-seq: * res.fformat( column_number ) -> Fixnum * * Returns the format (0 for text, 1 for binary) of column * _column_number_. * * Raises ArgumentError if _column_number_ is out of range. */ static VALUE pgresult_fformat(VALUE self, VALUE column_number) { PGresult *result = pgresult_get(self); int fnumber = NUM2INT(column_number); if (fnumber < 0 || fnumber >= PQnfields(result)) { rb_raise(rb_eArgError, "Column number is out of range: %d", fnumber); } return INT2FIX(PQfformat(result, fnumber)); } /* * call-seq: * res.ftype( column_number ) * * Returns the data type associated with _column_number_. * * The integer returned is the internal +OID+ number (in PostgreSQL) * of the type. To get a human-readable value for the type, use the * returned OID and the field's #fmod value with the format_type() SQL * function: * * # Get the type of the second column of the result 'res' * typename = conn. * exec( "SELECT format_type($1,$2)", [res.ftype(1), res.fmod(1)] ). * getvalue( 0, 0 ) * * Raises an ArgumentError if _column_number_ is out of range. */ static VALUE pgresult_ftype(VALUE self, VALUE index) { PGresult* result = pgresult_get(self); int i = NUM2INT(index); if (i < 0 || i >= PQnfields(result)) { rb_raise(rb_eArgError, "invalid field number %d", i); } return INT2NUM(PQftype(result, i)); } /* * call-seq: * res.fmod( column_number ) * * Returns the type modifier associated with column _column_number_. See * the #ftype method for an example of how to use this. * * Raises an ArgumentError if _column_number_ is out of range. */ static VALUE pgresult_fmod(VALUE self, VALUE column_number) { PGresult *result = pgresult_get(self); int fnumber = NUM2INT(column_number); int modifier; if (fnumber < 0 || fnumber >= PQnfields(result)) { rb_raise(rb_eArgError, "Column number is out of range: %d", fnumber); } modifier = PQfmod(result,fnumber); return INT2NUM(modifier); } /* * call-seq: * res.fsize( index ) * * Returns the size of the field type in bytes. Returns -1 if the field is variable sized. * * res = conn.exec("SELECT myInt, myVarChar50 FROM foo") * res.size(0) => 4 * res.size(1) => -1 */ static VALUE pgresult_fsize(VALUE self, VALUE index) { PGresult *result; int i = NUM2INT(index); result = pgresult_get(self); if (i < 0 || i >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", i); } return INT2NUM(PQfsize(result, i)); } static VALUE pgresult_value(VALUE self, PGresult *result, int tuple_num, int field_num) { VALUE val; if ( PQgetisnull(result, tuple_num, field_num) ) { return Qnil; } else { val = rb_tainted_str_new( PQgetvalue(result, tuple_num, field_num ), PQgetlength(result, tuple_num, field_num) ); #ifdef M17N_SUPPORTED /* associate client encoding for text format only */ if ( 0 == PQfformat(result, field_num) ) { ASSOCIATE_INDEX( val, self ); } else { rb_enc_associate( val, rb_ascii8bit_encoding() ); } #endif return val; } } /* * call-seq: * res.getvalue( tup_num, field_num ) * * Returns the value in tuple number _tup_num_, field _field_num_, * or +nil+ if the field is +NULL+. */ static VALUE pgresult_getvalue(VALUE self, VALUE tup_num, VALUE field_num) { PGresult *result; int i = NUM2INT(tup_num); int j = NUM2INT(field_num); result = pgresult_get(self); if(i < 0 || i >= PQntuples(result)) { rb_raise(rb_eArgError,"invalid tuple number %d", i); } if(j < 0 || j >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", j); } return pgresult_value(self, result, i, j); } /* * call-seq: * res.getisnull(tuple_position, field_position) -> boolean * * Returns +true+ if the specified value is +nil+; +false+ otherwise. */ static VALUE pgresult_getisnull(VALUE self, VALUE tup_num, VALUE field_num) { PGresult *result; int i = NUM2INT(tup_num); int j = NUM2INT(field_num); result = pgresult_get(self); if (i < 0 || i >= PQntuples(result)) { rb_raise(rb_eArgError,"invalid tuple number %d", i); } if (j < 0 || j >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", j); } return PQgetisnull(result, i, j) ? Qtrue : Qfalse; } /* * call-seq: * res.getlength( tup_num, field_num ) -> Fixnum * * Returns the (String) length of the field in bytes. * * Equivalent to res.value(tup_num,field_num).length. */ static VALUE pgresult_getlength(VALUE self, VALUE tup_num, VALUE field_num) { PGresult *result; int i = NUM2INT(tup_num); int j = NUM2INT(field_num); result = pgresult_get(self); if (i < 0 || i >= PQntuples(result)) { rb_raise(rb_eArgError,"invalid tuple number %d", i); } if (j < 0 || j >= PQnfields(result)) { rb_raise(rb_eArgError,"invalid field number %d", j); } return INT2FIX(PQgetlength(result, i, j)); } /* * call-seq: * res.nparams() -> Fixnum * * Returns the number of parameters of a prepared statement. * Only useful for the result returned by conn.describePrepared */ static VALUE pgresult_nparams(VALUE self) { PGresult *result; result = pgresult_get(self); return INT2FIX(PQnparams(result)); } /* * call-seq: * res.paramtype( param_number ) -> Oid * * Returns the Oid of the data type of parameter _param_number_. * Only useful for the result returned by conn.describePrepared */ static VALUE pgresult_paramtype(VALUE self, VALUE param_number) { PGresult *result; result = pgresult_get(self); return INT2FIX(PQparamtype(result,NUM2INT(param_number))); } /* * call-seq: * res.cmd_status() -> String * * Returns the status string of the last query command. */ static VALUE pgresult_cmd_status(VALUE self) { VALUE ret = rb_tainted_str_new2(PQcmdStatus(pgresult_get(self))); ASSOCIATE_INDEX(ret, self); return ret; } /* * call-seq: * res.cmd_tuples() -> Fixnum * * Returns the number of tuples (rows) affected by the SQL command. * * If the SQL command that generated the PG::Result was not one of: * * +INSERT+ * * +UPDATE+ * * +DELETE+ * * +MOVE+ * * +FETCH+ * or if no tuples were affected, 0 is returned. */ static VALUE pgresult_cmd_tuples(VALUE self) { long n; n = strtol(PQcmdTuples(pgresult_get(self)),NULL, 10); return INT2NUM(n); } /* * call-seq: * res.oid_value() -> Fixnum * * Returns the +oid+ of the inserted row if applicable, * otherwise +nil+. */ static VALUE pgresult_oid_value(VALUE self) { Oid n = PQoidValue(pgresult_get(self)); if (n == InvalidOid) return Qnil; else return INT2FIX(n); } /* Utility methods not in libpq */ /* * call-seq: * res[ n ] -> Hash * * Returns tuple _n_ as a hash. */ static VALUE pgresult_aref(VALUE self, VALUE index) { PGresult *result = pgresult_get(self); int tuple_num = NUM2INT(index); int field_num; VALUE fname; VALUE tuple; if ( tuple_num < 0 || tuple_num >= PQntuples(result) ) rb_raise( rb_eIndexError, "Index %d is out of range", tuple_num ); tuple = rb_hash_new(); for ( field_num = 0; field_num < PQnfields(result); field_num++ ) { fname = rb_tainted_str_new2( PQfname(result,field_num) ); ASSOCIATE_INDEX(fname, self); rb_hash_aset( tuple, fname, pgresult_value(self, result, tuple_num, field_num) ); } return tuple; } /* * call-seq: * res.each_row { |row| ... } * * Yields each row of the result. The row is a list of column values. */ static VALUE pgresult_each_row(VALUE self) { PGresult* result = (PGresult*) pgresult_get(self); int row; int field; int num_rows = PQntuples(result); int num_fields = PQnfields(result); for ( row = 0; row < num_rows; row++ ) { VALUE new_row = rb_ary_new2(num_fields); /* populate the row */ for ( field = 0; field < num_fields; field++ ) { rb_ary_store( new_row, field, pgresult_value(self, result, row, field) ); } rb_yield( new_row ); } return Qnil; } /* * Make a Ruby array out of the encoded values from the specified * column in the given result. */ static VALUE make_column_result_array( VALUE self, int col ) { PGresult *result = pgresult_get( self ); int rows = PQntuples( result ); int i; VALUE val = Qnil; VALUE results = rb_ary_new2( rows ); if ( col >= PQnfields(result) ) rb_raise( rb_eIndexError, "no column %d in result", col ); for ( i=0; i < rows; i++ ) { val = rb_tainted_str_new( PQgetvalue(result, i, col), PQgetlength(result, i, col) ); #ifdef M17N_SUPPORTED /* associate client encoding for text format only */ if ( 0 == PQfformat(result, col) ) { ASSOCIATE_INDEX( val, self ); } else { rb_enc_associate( val, rb_ascii8bit_encoding() ); } #endif rb_ary_store( results, i, val ); } return results; } /* * call-seq: * res.column_values( n ) -> array * * Returns an Array of the values from the nth column of each * tuple in the result. * */ static VALUE pgresult_column_values(VALUE self, VALUE index) { int col = NUM2INT( index ); return make_column_result_array( self, col ); } /* * call-seq: * res.field_values( field ) -> array * * Returns an Array of the values from the given _field_ of each tuple in the result. * */ static VALUE pgresult_field_values( VALUE self, VALUE field ) { PGresult *result = pgresult_get( self ); const char *fieldname = StringValuePtr( field ); int fnum = PQfnumber( result, fieldname ); if ( fnum < 0 ) rb_raise( rb_eIndexError, "no such field '%s' in result", fieldname ); return make_column_result_array( self, fnum ); } /* * call-seq: * res.each{ |tuple| ... } * * Invokes block for each tuple in the result set. */ static VALUE pgresult_each(VALUE self) { PGresult *result = pgresult_get(self); int tuple_num; for(tuple_num = 0; tuple_num < PQntuples(result); tuple_num++) { rb_yield(pgresult_aref(self, INT2NUM(tuple_num))); } return self; } /* * call-seq: * res.fields() -> Array * * Returns an array of Strings representing the names of the fields in the result. */ static VALUE pgresult_fields(VALUE self) { PGresult *result = pgresult_get( self ); int n = PQnfields( result ); VALUE fields = rb_ary_new2( n ); int i; for ( i = 0; i < n; i++ ) { VALUE val = rb_tainted_str_new2(PQfname(result, i)); ASSOCIATE_INDEX(val, self); rb_ary_store( fields, i, val ); } return fields; } void init_pg_result() { rb_cPGresult = rb_define_class_under( rb_mPG, "Result", rb_cObject ); rb_include_module(rb_cPGresult, rb_mEnumerable); rb_include_module(rb_cPGresult, rb_mPGconstants); /****** PG::Result INSTANCE METHODS: libpq ******/ rb_define_method(rb_cPGresult, "result_status", pgresult_result_status, 0); rb_define_method(rb_cPGresult, "res_status", pgresult_res_status, 1); rb_define_method(rb_cPGresult, "error_message", pgresult_error_message, 0); rb_define_alias( rb_cPGresult, "result_error_message", "error_message"); rb_define_method(rb_cPGresult, "error_field", pgresult_error_field, 1); rb_define_alias( rb_cPGresult, "result_error_field", "error_field" ); rb_define_method(rb_cPGresult, "clear", pg_result_clear, 0); rb_define_method(rb_cPGresult, "check", pg_result_check, 0); rb_define_alias (rb_cPGresult, "check_result", "check"); rb_define_method(rb_cPGresult, "ntuples", pgresult_ntuples, 0); rb_define_alias(rb_cPGresult, "num_tuples", "ntuples"); rb_define_method(rb_cPGresult, "nfields", pgresult_nfields, 0); rb_define_alias(rb_cPGresult, "num_fields", "nfields"); rb_define_method(rb_cPGresult, "fname", pgresult_fname, 1); rb_define_method(rb_cPGresult, "fnumber", pgresult_fnumber, 1); rb_define_method(rb_cPGresult, "ftable", pgresult_ftable, 1); rb_define_method(rb_cPGresult, "ftablecol", pgresult_ftablecol, 1); rb_define_method(rb_cPGresult, "fformat", pgresult_fformat, 1); rb_define_method(rb_cPGresult, "ftype", pgresult_ftype, 1); rb_define_method(rb_cPGresult, "fmod", pgresult_fmod, 1); rb_define_method(rb_cPGresult, "fsize", pgresult_fsize, 1); rb_define_method(rb_cPGresult, "getvalue", pgresult_getvalue, 2); rb_define_method(rb_cPGresult, "getisnull", pgresult_getisnull, 2); rb_define_method(rb_cPGresult, "getlength", pgresult_getlength, 2); rb_define_method(rb_cPGresult, "nparams", pgresult_nparams, 0); rb_define_method(rb_cPGresult, "paramtype", pgresult_paramtype, 1); rb_define_method(rb_cPGresult, "cmd_status", pgresult_cmd_status, 0); rb_define_method(rb_cPGresult, "cmd_tuples", pgresult_cmd_tuples, 0); rb_define_alias(rb_cPGresult, "cmdtuples", "cmd_tuples"); rb_define_method(rb_cPGresult, "oid_value", pgresult_oid_value, 0); /****** PG::Result INSTANCE METHODS: other ******/ rb_define_method(rb_cPGresult, "[]", pgresult_aref, 1); rb_define_method(rb_cPGresult, "each", pgresult_each, 0); rb_define_method(rb_cPGresult, "fields", pgresult_fields, 0); rb_define_method(rb_cPGresult, "each_row", pgresult_each_row, 0); rb_define_method(rb_cPGresult, "column_values", pgresult_column_values, 1); rb_define_method(rb_cPGresult, "field_values", pgresult_field_values, 1); } ruby-pg-0.17.0/ext/vc/000077500000000000000000000000001222421776500144045ustar00rootroot00000000000000ruby-pg-0.17.0/ext/vc/pg.sln000066400000000000000000000024601222421776500155320ustar00rootroot00000000000000 Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pg", "pg_18\pg.vcproj", "{9A8BF0C8-1D75-4DC0-8D84-BAEFD693795E}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pg_19", "pg_19\pg_19.vcproj", "{2EE30C74-074F-4611-B39B-38D5F3C9B071}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {9A8BF0C8-1D75-4DC0-8D84-BAEFD693795E}.Debug|Win32.ActiveCfg = Debug|Win32 {9A8BF0C8-1D75-4DC0-8D84-BAEFD693795E}.Debug|Win32.Build.0 = Debug|Win32 {9A8BF0C8-1D75-4DC0-8D84-BAEFD693795E}.Release|Win32.ActiveCfg = Release|Win32 {9A8BF0C8-1D75-4DC0-8D84-BAEFD693795E}.Release|Win32.Build.0 = Release|Win32 {2EE30C74-074F-4611-B39B-38D5F3C9B071}.Debug|Win32.ActiveCfg = Debug|Win32 {2EE30C74-074F-4611-B39B-38D5F3C9B071}.Debug|Win32.Build.0 = Debug|Win32 {2EE30C74-074F-4611-B39B-38D5F3C9B071}.Release|Win32.ActiveCfg = Release|Win32 {2EE30C74-074F-4611-B39B-38D5F3C9B071}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ruby-pg-0.17.0/ext/vc/pg_18/000077500000000000000000000000001222421776500153225ustar00rootroot00000000000000ruby-pg-0.17.0/ext/vc/pg_18/pg.vcproj000066400000000000000000000116731222421776500171650ustar00rootroot00000000000000 ruby-pg-0.17.0/ext/vc/pg_19/000077500000000000000000000000001222421776500153235ustar00rootroot00000000000000ruby-pg-0.17.0/ext/vc/pg_19/pg_19.vcproj000066400000000000000000000102021222421776500174620ustar00rootroot00000000000000 ruby-pg-0.17.0/lib/000077500000000000000000000000001222421776500137425ustar00rootroot00000000000000ruby-pg-0.17.0/lib/pg.rb000066400000000000000000000021341222421776500146750ustar00rootroot00000000000000#!/usr/bin/env ruby begin require 'pg_ext' rescue LoadError # If it's a Windows binary gem, try the . subdirectory if RUBY_PLATFORM =~/(mswin|mingw)/i major_minor = RUBY_VERSION[ /^(\d+\.\d+)/ ] or raise "Oops, can't extract the major/minor version from #{RUBY_VERSION.dump}" require "#{major_minor}/pg_ext" else raise end end # The top-level PG namespace. module PG # Library version VERSION = '0.17.0' # VCS revision REVISION = %q$Revision$ class NotAllCopyDataRetrieved < PG::Error end ### Get the PG library version. If +include_buildnum+ is +true+, include the build ID. def self::version_string( include_buildnum=false ) vstring = "%s %s" % [ self.name, VERSION ] vstring << " (build %s)" % [ REVISION[/: ([[:xdigit:]]+)/, 1] || '0' ] if include_buildnum return vstring end ### Convenience alias for PG::Connection.new. def self::connect( *args ) return PG::Connection.new( *args ) end require 'pg/exceptions' require 'pg/constants' require 'pg/connection' require 'pg/result' end # module PG # Backward-compatible aliase PGError = PG::Error ruby-pg-0.17.0/lib/pg/000077500000000000000000000000001222421776500143505ustar00rootroot00000000000000ruby-pg-0.17.0/lib/pg/connection.rb000077500000000000000000000123521222421776500170420ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' unless defined?( PG ) # The PostgreSQL connection class. The interface for this class is based on # {libpq}[http://www.postgresql.org/docs/9.2/interactive/libpq.html], the C # application programmer's interface to PostgreSQL. Some familiarity with libpq # is recommended, but not necessary. # # For example, to send query to the database on the localhost: # # require 'pg' # conn = PG::Connection.open(:dbname => 'test') # res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil]) # # Equivalent to: # # res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') # # See the PG::Result class for information on working with the results of a query. # class PG::Connection # The order the options are passed to the ::connect method. CONNECT_ARGUMENT_ORDER = %w[host port options tty dbname user password] ### Quote the given +value+ for use in a connection-parameter string. def self::quote_connstr( value ) return "'" + value.to_s.gsub( /[\\']/ ) {|m| '\\' + m } + "'" end ### Parse the connection +args+ into a connection-parameter string. See PG::Connection.new ### for valid arguments. def self::parse_connect_args( *args ) return '' if args.empty? # This will be swapped soon for code that makes options like those required for # PQconnectdbParams()/PQconnectStartParams(). For now, stick to an options string for # PQconnectdb()/PQconnectStart(). # Parameter 'fallback_application_name' was introduced in PostgreSQL 9.0 # together with PQescapeLiteral(). if PG::Connection.instance_methods.find{|m| m.to_sym == :escape_literal } appname = $0.sub(/^(.{30}).{4,}(.{30})$/){ $1+"..."+$2 } appname = PG::Connection.quote_connstr( appname ) connopts = ["fallback_application_name=#{appname}"] else connopts = [] end # Handle an options hash first if args.last.is_a?( Hash ) opthash = args.pop opthash.each do |key, val| connopts.push( "%s=%s" % [key, PG::Connection.quote_connstr(val)] ) end end # Option string style if args.length == 1 && args.first.to_s.index( '=' ) connopts.unshift( args.first ) # Append positional parameters else args.each_with_index do |val, i| next unless val # Skip nil placeholders key = CONNECT_ARGUMENT_ORDER[ i ] or raise ArgumentError, "Extra positional parameter %d: %p" % [ i+1, val ] connopts.push( "%s=%s" % [key, PG::Connection.quote_connstr(val.to_s)] ) end end return connopts.join(' ') end # call-seq: # conn.copy_data( sql ) {|sql_result| ... } -> PG::Result # # Execute a copy process for transfering data to or from the server. # # This issues the SQL COPY command via #exec. The response to this # (if there is no error in the command) is a PG::Result object that # is passed to the block, bearing a status code of PGRES_COPY_OUT or # PGRES_COPY_IN (depending on the specified copy direction). # The application should then use #put_copy_data or #get_copy_data # to receive or transmit data rows and should return from the block # when finished. # # #copy_data returns another PG::Result object when the data transfer # is complete. An exception is raised if some problem was encountered, # so it isn't required to make use of any of them. # At this point further SQL commands can be issued via #exec. # (It is not possible to execute other SQL commands using the same # connection while the COPY operation is in progress.) # # This method ensures, that the copy process is properly terminated # in case of client side or server side failures. Therefore, in case # of blocking mode of operation, #copy_data is preferred to raw calls # of #put_copy_data, #get_copy_data and #put_copy_end. # # Example with CSV input format: # conn.exec "create table my_table (a text,b text,c text,d text,e text)" # conn.copy_data "COPY my_table FROM STDOUT CSV" do # conn.put_copy_data "some,csv,data,to,copy\n" # conn.put_copy_data "more,csv,data,to,copy\n" # end # This creates +my_table+ and inserts two rows. # # Example with CSV output format: # conn.copy_data "COPY my_table TO STDOUT CSV" do # while row=conn.get_copy_data # p row # end # end # This prints all rows of +my_table+ to stdout: # "some,csv,data,to,copy\n" # "more,csv,data,to,copy\n" def copy_data( sql ) res = exec( sql ) case res.result_status when PGRES_COPY_IN begin yield res rescue Exception => err errmsg = "%s while copy data: %s" % [ err.class.name, err.message ] put_copy_end( errmsg ) get_result raise else put_copy_end get_last_result end when PGRES_COPY_OUT begin yield res rescue Exception => err cancel while get_copy_data end while get_result end raise else res = get_last_result if res.result_status != PGRES_COMMAND_OK while get_copy_data end while get_result end raise PG::NotAllCopyDataRetrieved, "Not all COPY data retrieved" end res end else raise ArgumentError, "SQL command is no COPY statement: #{sql}" end end # Backward-compatibility aliases for stuff that's moved into PG. class << self define_method( :isthreadsafe, &PG.method(:isthreadsafe) ) end end # class PG::Connection # Backward-compatible alias PGconn = PG::Connection ruby-pg-0.17.0/lib/pg/constants.rb000066400000000000000000000002341222421776500167100ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' unless defined?( PG ) module PG::Constants # Most of these are defined in the extension. end # module PG::Constants ruby-pg-0.17.0/lib/pg/exceptions.rb000066400000000000000000000001711222421776500170550ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' unless defined?( PG ) module PG class Error < StandardError; end end # module PG ruby-pg-0.17.0/lib/pg/result.rb000066400000000000000000000003701222421776500162130ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' unless defined?( PG ) class PG::Result ### Returns all tuples as an array of arrays def values return enum_for(:each_row).to_a end end # class PG::Result # Backward-compatible alias PGresult = PG::Result ruby-pg-0.17.0/misc/000077500000000000000000000000001222421776500141275ustar00rootroot00000000000000ruby-pg-0.17.0/misc/openssl-pg-segfault.rb000077500000000000000000000014431222421776500203600ustar00rootroot00000000000000#!/usr/bin/env ruby PGHOST = 'localhost' PGDB = 'test' #SOCKHOST = 'github.com' SOCKHOST = 'it-trac.laika.com' # Load pg first, so the libssl.so that libpq is linked against is loaded. require 'pg' $stderr.puts "connecting to postgres://#{PGHOST}/#{PGDB}" conn = PG.connect( PGHOST, :dbname => PGDB ) # Now load OpenSSL, which might be linked against a different libssl. require 'socket' require 'openssl' $stderr.puts "Connecting to #{SOCKHOST}" sock = TCPSocket.open( SOCKHOST, 443 ) ctx = OpenSSL::SSL::SSLContext.new sock = OpenSSL::SSL::SSLSocket.new( sock, ctx ) sock.sync_close = true # The moment of truth... $stderr.puts "Attempting to connect..." begin sock.connect rescue Errno $stderr.puts "Got an error connecting, but no segfault." else $stderr.puts "Nope, no segfault!" end ruby-pg-0.17.0/misc/postgres/000077500000000000000000000000001222421776500157755ustar00rootroot00000000000000ruby-pg-0.17.0/misc/postgres/History.txt000066400000000000000000000002701222421776500201760ustar00rootroot00000000000000== v0.8.0 [2012-02-09] Michael Granger This placeholder version. == v0.7.9.2008.01.28 [2008-01-28] Jeff Davis <> The last actual version. ruby-pg-0.17.0/misc/postgres/Manifest.txt000066400000000000000000000000751222421776500203060ustar00rootroot00000000000000History.txt Manifest.txt README.txt Rakefile lib/postgres.rb ruby-pg-0.17.0/misc/postgres/README.txt000066400000000000000000000011071222421776500174720ustar00rootroot00000000000000= postgres * https://bitbucket.org/ged/ruby-pg == Description This is an old, deprecated version of the Ruby PostgreSQL driver that hasn't been maintained or supported since early 2008. You should install/require 'pg' instead. If you need the 'postgres' gem for legacy code that can't be converted, you can still install it using an explicit version, like so: gem install postgres -v '0.7.9.2008.01.28' gem uninstall postgres -v '>0.7.9.2008.01.28' If you have any questions, the nice folks in the Google group can help: http://goo.gl/OjOPP / ruby-pg@googlegroups.com ruby-pg-0.17.0/misc/postgres/Rakefile000066400000000000000000000006631222421776500174470ustar00rootroot00000000000000# -*- ruby -*- require 'date' require 'rubygems' require 'hoe' require 'pp' Hoe.spec 'postgres' do self.developer 'Michael Granger', 'ged@FaerieMUD.org' self.dependency 'pg', '~> 0' self.spec_extras[:date] = Date.parse( '2008/01/30' ) line = '-' * 75 msg = paragraphs_of( 'README.txt', 3..-1 ) msg.unshift( line ) msg.push( line ) self.spec_extras[:post_install_message] = msg.join( "\n\n" ) + "\n" end # vim: syntax=ruby ruby-pg-0.17.0/misc/postgres/lib/000077500000000000000000000000001222421776500165435ustar00rootroot00000000000000ruby-pg-0.17.0/misc/postgres/lib/postgres.rb000066400000000000000000000003661222421776500207430ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pathname' module Postgres VERSION = '0.8.1' gemdir = Pathname( __FILE__ ).dirname.parent readme = gemdir + 'README.txt' header, message = readme.read.split( /^== Description/m ) abort( message.strip ) end ruby-pg-0.17.0/misc/postgresql-9.1.4.mingw-w64-support.patch000066400000000000000000000362341222421776500233020ustar00rootroot00000000000000From 1a0c76c32fe470142d3663dd84ac960d75a4e8db Mon Sep 17 00:00:00 2001 From: Andrew Dunstan Date: Sat, 10 Dec 2011 15:35:41 -0500 Subject: [PATCH] Enable compiling with the mingw-w64 32 bit compiler. Original patch by Lars Kanis, reviewed by Nishiyama Tomoaki and tweaked some by me. This compiler, or at least the latest version of it, is currently broken, and only passes the regression tests if built with -O0. --- config/ac_func_accept_argtypes.m4 | 2 +- configure | 159 +++++++++++++++++++++++++++++++++++- configure.in | 7 ++- src/include/c.h | 3 +- src/include/pg_config.h.in | 3 + src/include/port/win32.h | 26 ++++++- src/interfaces/ecpg/test/resultmap | 3 + src/interfaces/libpq/win32.h | 6 ++ src/port/getaddrinfo.c | 4 +- src/test/regress/resultmap | 3 + 10 files changed, 207 insertions(+), 9 deletions(-) diff --git a/config/ac_func_accept_argtypes.m4 b/config/ac_func_accept_argtypes.m4 index 1e77179..a82788d 100644 --- a/config/ac_func_accept_argtypes.m4 +++ b/config/ac_func_accept_argtypes.m4 @@ -46,7 +46,7 @@ AC_DEFUN([AC_FUNC_ACCEPT_ARGTYPES], [AC_CACHE_VAL(ac_cv_func_accept_arg1,dnl [AC_CACHE_VAL(ac_cv_func_accept_arg2,dnl [AC_CACHE_VAL(ac_cv_func_accept_arg3,dnl - [for ac_cv_func_accept_return in 'int' 'unsigned int PASCAL' 'SOCKET'; do + [for ac_cv_func_accept_return in 'int' 'unsigned int PASCAL' 'SOCKET WSAAPI'; do for ac_cv_func_accept_arg1 in 'int' 'unsigned int' 'SOCKET'; do for ac_cv_func_accept_arg2 in 'struct sockaddr *' 'const struct sockaddr *' 'void *'; do for ac_cv_func_accept_arg3 in 'int' 'size_t' 'socklen_t' 'unsigned int' 'void'; do diff --git a/configure b/configure index ebe69cd..67c5632 100755 --- a/configure +++ b/configure @@ -14328,6 +14328,159 @@ done fi +if test "$PORTNAME" = "win32" ; then + +for ac_header in crtdefs.h +do +as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + { $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:$LINENO: checking $ac_header usability" >&5 +$as_echo_n "checking $ac_header usability... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +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:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:$LINENO: checking $ac_header presence" >&5 +$as_echo_n "checking $ac_header presence... " >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:$LINENO: $ac_try_echo\"" +$as_echo "$ac_try_echo") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + $as_echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ $as_echo "$as_me:$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:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +$as_echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { $as_echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +$as_echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ---------------------------------------- ## +## Report this to pgsql-bugs@postgresql.org ## +## ---------------------------------------- ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ $as_echo "$as_me:$LINENO: checking for $ac_header" >&5 +$as_echo_n "checking for $ac_header... " >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + $as_echo_n "(cached) " >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +ac_res=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + { $as_echo "$as_me:$LINENO: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + +fi +as_val=`eval 'as_val=${'$as_ac_Header'} + $as_echo "$as_val"'` + if test "x$as_val" = x""yes; then + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + +fi ## ## Types, structures, compiler characteristics @@ -17997,7 +18150,8 @@ fi # compiler characteristic, but you'd be wrong. We must check this before # probing existence of related functions such as fseeko, since the largefile # defines can affect what is generated for that. -# Check whether --enable-largefile was given. +if test "$PORTNAME" != "win32"; then + # Check whether --enable-largefile was given. if test "${enable_largefile+set}" = set; then enableval=$enable_largefile; fi @@ -18353,6 +18507,7 @@ rm -rf conftest* fi fi +fi # Check for largefile support (must be after AC_SYS_LARGEFILE) # The cast to long int works around a bug in the HP C Compiler @@ -18808,7 +18963,7 @@ else if test "${ac_cv_func_accept_arg3+set}" = set; then $as_echo_n "(cached) " >&6 else - for ac_cv_func_accept_return in 'int' 'unsigned int PASCAL' 'SOCKET'; do + for ac_cv_func_accept_return in 'int' 'unsigned int PASCAL' 'SOCKET WSAAPI'; do for ac_cv_func_accept_arg1 in 'int' 'unsigned int' 'SOCKET'; do for ac_cv_func_accept_arg2 in 'struct sockaddr *' 'const struct sockaddr *' 'void *'; do for ac_cv_func_accept_arg3 in 'int' 'size_t' 'socklen_t' 'unsigned int' 'void'; do diff --git a/configure.in b/configure.in index 5591b93..9cf084d 100644 --- a/configure.in +++ b/configure.in @@ -1101,6 +1101,9 @@ if test "$with_ossp_uuid" = yes ; then [AC_MSG_ERROR([header file or is required for OSSP-UUID])])]) fi +if test "$PORTNAME" = "win32" ; then + AC_CHECK_HEADERS(crtdefs.h) +fi ## ## Types, structures, compiler characteristics @@ -1174,7 +1177,9 @@ fi # compiler characteristic, but you'd be wrong. We must check this before # probing existence of related functions such as fseeko, since the largefile # defines can affect what is generated for that. -AC_SYS_LARGEFILE +if test "$PORTNAME" != "win32"; then + AC_SYS_LARGEFILE +fi # Check for largefile support (must be after AC_SYS_LARGEFILE) AC_CHECK_SIZEOF([off_t]) diff --git a/src/include/c.h b/src/include/c.h index 0391860..cb9b150 100644 --- a/src/include/c.h +++ b/src/include/c.h @@ -58,7 +58,8 @@ #endif #include "postgres_ext.h" -#if _MSC_VER >= 1400 || defined(WIN64) +#define HAVE_CRTDEFS_H 1 +#if _MSC_VER >= 1400 || defined(HAVE_CRTDEFS_H) #define errcode __msvc_errcode #include #undef errcode diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in index 15fe0bf..b969d8c 100644 --- a/src/include/pg_config.h.in +++ b/src/include/pg_config.h.in @@ -99,6 +99,9 @@ /* Define to 1 if you have the `class' function. */ #undef HAVE_CLASS +/* Define to 1 if you have the header file. */ +#undef HAVE_CRTDEFS_H + /* Define to 1 if you have the `crypt' function. */ #undef HAVE_CRYPT diff --git a/src/include/port/win32.h b/src/include/port/win32.h index 34f4004..afc9628 100644 --- a/src/include/port/win32.h +++ b/src/include/port/win32.h @@ -31,7 +31,7 @@ * The Mingw64 headers choke if this is already defined - they * define it themselves. */ -#if !defined(WIN64) || defined(WIN32_ONLY_COMPILER) +#if !defined(__MINGW64_VERSION_MAJOR) || defined(WIN32_ONLY_COMPILER) #define _WINSOCKAPI_ #endif #include @@ -225,9 +225,13 @@ int setitimer(int which, const struct itimerval * value, struct itimerval * ov #define fseeko(stream, offset, origin) _fseeki64(stream, offset, origin) #define ftello(stream) _ftelli64(stream) #else +#ifndef fseeko #define fseeko(stream, offset, origin) fseeko64(stream, offset, origin) +#endif +#ifndef ftello #define ftello(stream) ftello64(stream) #endif +#endif /* * Supplement to . @@ -264,16 +268,36 @@ typedef int pid_t; #undef EINTR #define EINTR WSAEINTR #define EAGAIN WSAEWOULDBLOCK +#ifndef EMSGSIZE #define EMSGSIZE WSAEMSGSIZE +#endif +#ifndef EAFNOSUPPORT #define EAFNOSUPPORT WSAEAFNOSUPPORT +#endif +#ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK +#endif +#ifndef ECONNRESET #define ECONNRESET WSAECONNRESET +#endif +#ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS +#endif +#ifndef ENOBUFS #define ENOBUFS WSAENOBUFS +#endif +#ifndef EPROTONOSUPPORT #define EPROTONOSUPPORT WSAEPROTONOSUPPORT +#endif +#ifndef ECONNREFUSED #define ECONNREFUSED WSAECONNREFUSED +#endif +#ifndef EBADFD #define EBADFD WSAENOTSOCK +#endif +#ifndef EOPNOTSUPP #define EOPNOTSUPP WSAEOPNOTSUPP +#endif /* * Extended locale functions with gratuitous underscore prefixes. diff --git a/src/interfaces/ecpg/test/resultmap b/src/interfaces/ecpg/test/resultmap index 95ea583..aef7338 100644 --- a/src/interfaces/ecpg/test/resultmap +++ b/src/interfaces/ecpg/test/resultmap @@ -1,9 +1,12 @@ compat_informix/dec_test:stdout:i.86-pc-win32vc=compat_informix-dec_test-MinGW32.stdout compat_informix/dec_test:stdout:i.86-pc-mingw32=compat_informix-dec_test-MinGW32.stdout compat_informix/dec_test:stdout:x86_64-w64-mingw32=compat_informix-dec_test-MinGW32.stdout +compat_informix/dec_test:stdout:i.86-w64-mingw32=compat_informix-dec_test-MinGW32.stdout pgtypeslib/num_test:stdout:i.86-pc-win32vc=pgtypeslib-num_test-MinGW32.stdout pgtypeslib/num_test:stdout:i.86-pc-mingw32=pgtypeslib-num_test-MinGW32.stdout pgtypeslib/num_test:stdout:x86_64-w64-mingw32=pgtypeslib-num_test-MinGW32.stdout +pgtypeslib/num_test:stdout:i.86-w64-mingw32=pgtypeslib-num_test-MinGW32.stdout pgtypeslib/num_test2:stdout:i.86-pc-win32vc=pgtypeslib-num_test2-MinGW32.stdout pgtypeslib/num_test2:stdout:i.86-pc-mingw32=pgtypeslib-num_test2-MinGW32.stdout pgtypeslib/num_test2:stdout:x86_64-w64-mingw32=pgtypeslib-num_test2-MinGW32.stdout +pgtypeslib/num_test2:stdout:i.86-w64-mingw32=pgtypeslib-num_test2-MinGW32.stdout diff --git a/src/interfaces/libpq/win32.h b/src/interfaces/libpq/win32.h index b65da9a..be00ea7 100644 --- a/src/interfaces/libpq/win32.h +++ b/src/interfaces/libpq/win32.h @@ -22,9 +22,15 @@ #undef EAGAIN /* doesn't apply on sockets */ #undef EINTR #define EINTR WSAEINTR +#ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK +#endif +#ifndef ECONNRESET #define ECONNRESET WSAECONNRESET +#endif +#ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS +#endif /* * support for handling Windows Socket errors diff --git a/src/port/getaddrinfo.c b/src/port/getaddrinfo.c index db19878..b6368ae 100644 --- a/src/port/getaddrinfo.c +++ b/src/port/getaddrinfo.c @@ -328,12 +328,10 @@ gai_strerror(int errcode) case EAI_MEMORY: return "Not enough memory"; #endif -#ifdef EAI_NODATA -#if !defined(WIN64) && !defined(WIN32_ONLY_COMPILER) /* MSVC/WIN64 duplicate */ +#if defined(EAI_NODATA) && EAI_NODATA != EAI_NONAME /* MSVC/WIN64 duplicate */ case EAI_NODATA: return "No host data of that type was found"; #endif -#endif #ifdef EAI_SERVICE case EAI_SERVICE: return "Class type not found"; diff --git a/src/test/regress/resultmap b/src/test/regress/resultmap index d02d221..04ba99f 100644 --- a/src/test/regress/resultmap +++ b/src/test/regress/resultmap @@ -1,5 +1,6 @@ float4:out:i.86-pc-mingw32=float4-exp-three-digits.out float4:out:x86_64-w64-mingw32=float4-exp-three-digits.out +float4:out:i.86-w64-mingw32=float4-exp-three-digits.out float4:out:i.86-pc-win32vc=float4-exp-three-digits.out float8:out:i.86-.*-freebsd=float8-small-is-zero.out float8:out:i.86-.*-openbsd=float8-small-is-zero.out @@ -7,8 +8,10 @@ float8:out:i.86-.*-netbsd=float8-small-is-zero.out float8:out:m68k-.*-netbsd=float8-small-is-zero.out float8:out:i.86-pc-mingw32=float8-exp-three-digits-win32.out float8:out:x86_64-w64-mingw32=float8-exp-three-digits-win32.out +float8:out:i.86-w64-mingw32=float8-exp-three-digits-win32.out float8:out:i.86-pc-win32vc=float8-exp-three-digits-win32.out float8:out:i.86-pc-cygwin=float8-small-is-zero.out int8:out:i.86-pc-mingw32=int8-exp-three-digits.out int8:out:x86_64-w64-mingw32=int8-exp-three-digits.out +int8:out:i.86-w64-mingw32=int8-exp-three-digits.out int8:out:i.86-pc-win32vc=int8-exp-three-digits.out -- 1.7.2.5 ruby-pg-0.17.0/misc/ruby-pg/000077500000000000000000000000001222421776500155145ustar00rootroot00000000000000ruby-pg-0.17.0/misc/ruby-pg/History.txt000066400000000000000000000002701222421776500177150ustar00rootroot00000000000000== v0.8.0 [2012-02-09] Michael Granger This placeholder version. == v0.7.9.2008.01.28 [2008-01-28] Jeff Davis <> The last actual version. ruby-pg-0.17.0/misc/ruby-pg/Manifest.txt000066400000000000000000000000741222421776500200240ustar00rootroot00000000000000History.txt Manifest.txt README.txt Rakefile lib/ruby/pg.rb ruby-pg-0.17.0/misc/ruby-pg/README.txt000066400000000000000000000010531222421776500172110ustar00rootroot00000000000000= ruby-pg * https://bitbucket.org/ged/ruby-pg == Description This is an old, deprecated version of the 'pg' gem that hasn't been maintained or supported since early 2008. You should install/require 'pg' instead. If you need ruby-pg for legacy code that can't be converted, you can still install it using an explicit version, like so: gem install ruby-pg -v '0.7.9.2008.01.28' gem uninstall ruby-pg -v '>0.7.9.2008.01.28' If you have any questions, the nice folks in the Google group can help: http://goo.gl/OjOPP / ruby-pg@googlegroups.com ruby-pg-0.17.0/misc/ruby-pg/Rakefile000066400000000000000000000006621222421776500171650ustar00rootroot00000000000000# -*- ruby -*- require 'date' require 'rubygems' require 'hoe' require 'pp' Hoe.spec 'ruby-pg' do self.developer 'Michael Granger', 'ged@FaerieMUD.org' self.dependency 'pg', '~> 0' self.spec_extras[:date] = Date.parse( '2008/01/30' ) line = '-' * 75 msg = paragraphs_of( 'README.txt', 3..-1 ) msg.unshift( line ) msg.push( line ) self.spec_extras[:post_install_message] = msg.join( "\n\n" ) + "\n" end # vim: syntax=ruby ruby-pg-0.17.0/misc/ruby-pg/lib/000077500000000000000000000000001222421776500162625ustar00rootroot00000000000000ruby-pg-0.17.0/misc/ruby-pg/lib/ruby/000077500000000000000000000000001222421776500172435ustar00rootroot00000000000000ruby-pg-0.17.0/misc/ruby-pg/lib/ruby/pg.rb000066400000000000000000000003671222421776500202040ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pathname' module Pg VERSION = '0.8.0' gemdir = Pathname( __FILE__ ).dirname.parent.parent readme = gemdir + 'README.txt' header, message = readme.read.split( /^== Description/m ) abort( message.strip ) end ruby-pg-0.17.0/sample/000077500000000000000000000000001222421776500144555ustar00rootroot00000000000000ruby-pg-0.17.0/sample/array_insert.rb000066400000000000000000000007151222421776500175070ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' c = PG.connect( dbname: 'test' ) # this one works: c.exec( "DROP TABLE IF EXISTS foo" ) c.exec( "CREATE TABLE foo (strings character varying[]);" ) # But using a prepared statement works: c.set_error_verbosity( PG::PQERRORS_VERBOSE ) c.prepare( 'stmt', "INSERT INTO foo VALUES ($1);" ) # This won't work #c.exec_prepared( 'stmt', ["ARRAY['this','that']"] ) # but this will: c.exec_prepared( 'stmt', ["{'this','that'}"] ) ruby-pg-0.17.0/sample/async_api.rb000077500000000000000000000066011222421776500167560ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' # This is a example of how to use the asynchronous API to query the # server without blocking other threads. It's intentionally low-level; # if you hooked up the PG::Connection#socket to some kind of reactor, you # could make this much nicer. TIMEOUT = 5.0 # seconds to wait for an async operation to complete # Print 'x' continuously to demonstrate that other threads aren't # blocked while waiting for the connection, for the query to be sent, # for results, etc. You might want to sleep inside the loop or # comment this out entirely for cleaner output. progress_thread = Thread.new { loop { print 'x' } } # Output progress messages def output_progress( msg ) puts "\n>>> #{msg}\n" end # Start the connection output_progress "Starting connection..." conn = PG::Connection.connect_start( :dbname => 'test' ) or abort "Unable to create a new connection!" abort "Connection failed: %s" % [ conn.error_message ] if conn.status == PG::CONNECTION_BAD # Now grab a reference to the underlying socket so we know when the # connection is established socket = conn.socket_io # Track the progress of the connection, waiting for the socket to become readable/writable # before polling it poll_status = PG::PGRES_POLLING_WRITING until poll_status == PG::PGRES_POLLING_OK || poll_status == PG::PGRES_POLLING_FAILED # If the socket needs to read, wait 'til it becomes readable to poll again case poll_status when PG::PGRES_POLLING_READING output_progress " waiting for socket to become readable" select( [socket], nil, nil, TIMEOUT ) or raise "Asynchronous connection timed out!" # ...and the same for when the socket needs to write when PG::PGRES_POLLING_WRITING output_progress " waiting for socket to become writable" select( nil, [socket], nil, TIMEOUT ) or raise "Asynchronous connection timed out!" end # Output a status message about the progress case conn.status when PG::CONNECTION_STARTED output_progress " waiting for connection to be made." when PG::CONNECTION_MADE output_progress " connection OK; waiting to send." when PG::CONNECTION_AWAITING_RESPONSE output_progress " waiting for a response from the server." when PG::CONNECTION_AUTH_OK output_progress " received authentication; waiting for backend start-up to finish." when PG::CONNECTION_SSL_STARTUP output_progress " negotiating SSL encryption." when PG::CONNECTION_SETENV output_progress " negotiating environment-driven parameter settings." when PG::CONNECTION_NEEDED output_progress " internal state: connect() needed." end # Check to see if it's finished or failed yet poll_status = conn.connect_poll end abort "Connect failed: %s" % [ conn.error_message ] unless conn.status == PG::CONNECTION_OK output_progress "Sending query" conn.send_query( "SELECT * FROM pg_stat_activity" ) # Fetch results until there aren't any more loop do output_progress " waiting for a response" # Buffer any incoming data on the socket until a full result is ready. conn.consume_input while conn.is_busy select( [socket], nil, nil, TIMEOUT ) or raise "Timeout waiting for query response." conn.consume_input end # Fetch the next result. If there isn't one, the query is finished result = conn.get_result or break puts "\n\nQuery result:\n%p\n" % [ result.values ] end output_progress "Done." conn.finish if defined?( progress_thread ) progress_thread.kill progress_thread.join end ruby-pg-0.17.0/sample/async_copyto.rb000077500000000000000000000015011222421776500175140ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' require 'stringio' # Using COPY asynchronously $stderr.puts "Opening database connection ..." conn = PG.connect( :dbname => 'test' ) conn.setnonblocking( true ) socket = conn.socket_io $stderr.puts "Running COPY command ..." buf = '' conn.transaction do conn.send_query( "COPY logs TO STDOUT WITH csv" ) buf = nil # #get_copy_data returns a row if there's a whole one to return, false # if there isn't one but the COPY is still running, or nil when it's # finished. begin $stderr.puts "COPY loop" conn.consume_input while conn.is_busy $stderr.puts " ready loop" select( [socket], nil, nil, 5.0 ) or raise "Timeout (5s) waiting for query response." conn.consume_input end buf = conn.get_copy_data $stdout.puts( buf ) if buf end until buf.nil? end conn.finish ruby-pg-0.17.0/sample/async_mixed.rb000077500000000000000000000030001222421776500173010ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' $stdout.sync = true # This is a example of how to mix and match synchronous and async APIs. In this case, # the connection to the server is made syncrhonously, and then queries are # asynchronous. TIMEOUT = 5.0 # seconds to wait for an async operation to complete CONN_OPTS = { :host => 'localhost', :dbname => 'test', } # Output progress messages def output_progress( msg ) puts ">>> #{msg}\n" end # Start the (synchronous) connection output_progress "Starting connection..." conn = PG.connect( CONN_OPTS ) or abort "Unable to create a new connection!" abort "Connect failed: %s" % [ conn.error_message ] unless conn.status == PG::CONNECTION_OK # Now grab a reference to the underlying socket to select() on while the query is running socket = conn.socket_io # Send the (asynchronous) query output_progress "Sending query" conn.send_query( "SELECT * FROM pg_stat_activity" ) # Fetch results until there aren't any more loop do output_progress " waiting for a response" # Buffer any incoming data on the socket until a full result is ready. conn.consume_input while conn.is_busy output_progress " waiting for data to be available on %p..." % [ socket ] select( [socket], nil, nil, TIMEOUT ) or raise "Timeout waiting for query response." conn.consume_input end # Fetch the next result. If there isn't one, the query is finished result = conn.get_result or break output_progress "Query result:\n%p\n" % [ result.values ] end output_progress "Done." conn.finish ruby-pg-0.17.0/sample/check_conn.rb000066400000000000000000000007011222421776500170720ustar00rootroot00000000000000#!/usr/bin/env ruby # vim: set nosta noet ts=4 sw=4: # encoding: utf-8 require 'pg' # This is a minimal example of a function that can test an existing PG::Connection and # reset it if necessary. def check_connection( conn ) begin conn.exec( "SELECT 1" ) rescue PG::Error => err $stderr.puts "%p while testing connection: %s" % [ err.class, err.message ] conn.reset end end conn = PG.connect( dbname: 'test' ) check_connection( conn ) ruby-pg-0.17.0/sample/copyfrom.rb000077500000000000000000000070161222421776500166470ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' require 'stringio' $stderr.puts "Opening database connection ..." conn = PG.connect( :dbname => 'test' ) conn.exec( < err errmsg = "%s while reading copy data: %s" % [ err.class.name, err.message ] conn.put_copy_end( errmsg ) else conn.put_copy_end while res = conn.get_result $stderr.puts "Result of COPY is: %s" % [ res.res_status(res.result_status) ] end end end conn.finish ruby-pg-0.17.0/sample/copyto.rb000077500000000000000000000006261222421776500163260ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' require 'stringio' # An example of how to stream data to your local host from the database as CSV. $stderr.puts "Opening database connection ..." conn = PG.connect( :dbname => 'test' ) $stderr.puts "Running COPY command ..." buf = '' conn.transaction do conn.exec( "COPY logs TO STDOUT WITH csv" ) $stdout.puts( buf ) while buf = conn.get_copy_data end conn.finish ruby-pg-0.17.0/sample/cursor.rb000077500000000000000000000010761222421776500163260ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' # An example of how to use SQL cursors. This is mostly a straight port of # the cursor portion of testlibpq.c from src/test/examples. $stderr.puts "Opening database connection ..." conn = PG.connect( :dbname => 'test' ) # conn.transaction do conn.exec( "DECLARE myportal CURSOR FOR select * from pg_database" ) res = conn.exec( "FETCH ALL IN myportal" ) puts res.fields.collect {|fname| "%-15s" % [fname] }.join( '' ) res.values.collect do |row| puts row.collect {|col| "%-15s" % [col] }.join( '' ) end end ruby-pg-0.17.0/sample/disk_usage_report.rb000077500000000000000000000073141222421776500205230ustar00rootroot00000000000000#!/usr/bin/env ruby # vim: set noet nosta sw=4 ts=4 : # # Quickly dump size information for a given database. # Top twenty objects, and size per schema. # # Mahlon E. Smith # # Based on work by Jeff Davis . # begin require 'ostruct' require 'optparse' require 'etc' require 'pg' rescue LoadError # 1.8 support unless Object.const_defined?( :Gem ) require 'rubygems' retry end raise end SCRIPT_VERSION = %q$Id$ ### Gather data and output it to $stdout. ### def report( opts ) db = PG.connect( :dbname => opts.database, :host => opts.host, :port => opts.port, :user => opts.user, :password => opts.pass, :sslmode => 'prefer' ) # ----------------------------------------- db_info = db.exec %Q{ SELECT count(oid) AS num_relations, pg_size_pretty(pg_database_size('#{opts.database}')) AS dbsize FROM pg_class } puts '=' * 70 puts "Disk usage information for %s: (%d relations, %s total)" % [ opts.database, db_info[0]['num_relations'], db_info[0]['dbsize'] ] puts '=' * 70 # ----------------------------------------- top_twenty = db.exec %q{ SELECT relname AS name, relkind AS kind, pg_size_pretty(pg_relation_size(pg_class.oid)) AS size FROM pg_class ORDER BY pg_relation_size(pg_class.oid) DESC LIMIT 20 } puts 'Top twenty objects by size:' puts '-' * 70 top_twenty.each do |row| type = case row['kind'] when 'i'; 'index' when 't'; 'toast' when 'r'; 'table' when 'S'; 'sequence' else; '???' end puts "%40s %10s (%s)" % [ row['name'], row['size'], type ] end puts '-' * 70 # ----------------------------------------- schema_sizes = db.exec %q{ SELECT table_schema, pg_size_pretty( CAST( SUM(pg_total_relation_size(table_schema || '.' || table_name)) AS bigint)) AS size FROM information_schema.tables GROUP BY table_schema ORDER BY CAST( SUM(pg_total_relation_size(table_schema || '.' || table_name)) AS bigint ) DESC } puts 'Size per schema:' puts '-' * 70 schema_sizes.each do |row| puts "%20s %10s" % [ row['table_schema'], row['size'] ] end puts '-' * 70 puts db.finish end ### Parse command line arguments. Return a struct of global options. ### def parse_args( args ) options = OpenStruct.new options.database = Etc.getpwuid( Process.uid ).name options.host = '127.0.0.1' options.port = 5432 options.user = Etc.getpwuid( Process.uid ).name options.sslmode = 'prefer' options.interval = 5 opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.separator '' opts.separator 'Connection options:' opts.on( '-d', '--database DBNAME', "specify the database to connect to (default: \"#{options.database}\")" ) do |db| options.database = db end opts.on( '-h', '--host HOSTNAME', 'database server host' ) do |host| options.host = host end opts.on( '-p', '--port PORT', Integer, "database server port (default: \"#{options.port}\")" ) do |port| options.port = port end opts.on( '-U', '--user NAME', "database user name (default: \"#{options.user}\")" ) do |user| options.user = user end opts.on( '-W', 'force password prompt' ) do |pw| print 'Password: ' begin system 'stty -echo' options.pass = gets.chomp ensure system 'stty echo' puts end end opts.separator '' opts.separator 'Other options:' opts.on_tail( '--help', 'show this help, then exit' ) do $stderr.puts opts exit end opts.on_tail( '--version', 'output version information, then exit' ) do puts SCRIPT_VERSION exit end end opts.parse!( args ) return options end if __FILE__ == $0 opts = parse_args( ARGV ) report( opts ) end ruby-pg-0.17.0/sample/issue-119.rb000077500000000000000000000042561222421776500164540ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' # This is another example of how to use COPY FROM, this time as a # minimal test case used to try to figure out what was going on in # an issue submitted from a user: # # https://bitbucket.org/ged/ruby-pg/issue/119 # conn = PG.connect( dbname: 'test' ) table_name = 'issue_119' field_list = %w[name body_weight brain_weight] method = 0 options = { truncate: true } sql_parameters = '' conn.set_error_verbosity( PG::PQERRORS_VERBOSE ) conn.exec( "DROP TABLE IF EXISTS #{table_name}" ) conn.exec( "CREATE TABLE #{table_name} ( id SERIAL, name TEXT, body_weight REAL, brain_weight REAL )" ) text = <<-END_DATA Mountain beaver 1.35 465 Cow 465 423 Grey wolf 36.33 119.5 Goat 27.66 115 Guinea pig 1.04 5.5 Dipliodocus 11700 50 Asian elephant 2547 4603 Donkey 187.1 419 Horse 521 655 Potar monkey 10 115 Cat 3.3 25.6 Giraffe 529 680 Gorilla 207 406 Human 62 1320 African elephant 6654 5712 Triceratops 9400 70 Rhesus monkey 6.8 179 Kangaroo 35 56 Golden hamster 0.12 1 Mouse 0.023 0.4 Rabbit 2.5 12.1 Sheep 55.5 175 Jaguar 100 157 Chimpanzee 52.16 440 Brachiosaurus 87000 154.5 Mole 0.122 3 Pig 192 18 END_DATA #ActiveRecord::Base.connection_pool.with_connection do |conn| conn.transaction do rc = conn #.raw_connection rc.exec "TRUNCATE TABLE #{table_name};" if options[:truncate] sql = "COPY #{table_name} (#{field_list.join(',')}) FROM STDIN #{sql_parameters} " p sql rc.exec(sql) errmsg = nil # scope this outside of the rescue below so it's visible later begin if method == 1 rc.put_copy_data text + "\\.\n" else text.each_line { |line| rc.put_copy_data(line) } end rescue Errno => err errmsg = "%s while reading copy data: %s" % [err.class.name, err.message] puts "an error occured" end if errmsg rc.put_copy_end(errmsg) puts "ERROR #{errmsg}" else rc.put_copy_end end while res = rc.get_result st = res.res_status( res.result_status ) puts "Result of COPY is: %s" % [ st ] if res.result_status != PG::PGRES_COPY_IN puts res.error_message end end puts "end" end #transaction #end #connection conn.exec( "SELECT name, brain_weight FROM #{table_name}" ) do |res| p res.values end ruby-pg-0.17.0/sample/losample.rb000077500000000000000000000035301222421776500166220ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' SAMPLE_WRITE_DATA = 'some sample data' SAMPLE_EXPORT_NAME = 'lowrite.txt' conn = PG.connect( :dbname => 'test', :host => 'localhost', :port => 5432 ) puts "dbname: " + conn.db + "\thost: " + conn.host + "\tuser: " + conn.user # Start a transaction, as all large object functions require one. puts "Beginning transaction" conn.exec( 'BEGIN' ) # Test importing from a file puts "Import test:" puts " importing %s" % [ __FILE__ ] oid = conn.lo_import( __FILE__ ) puts " imported as large object %d" % [ oid ] # Read back 50 bytes of the imported data puts "Read test:" fd = conn.lo_open( oid, PG::INV_READ|PG::INV_WRITE ) conn.lo_lseek( fd, 0, PG::SEEK_SET ) buf = conn.lo_read( fd, 50 ) puts " read: %p" % [ buf ] puts " read was ok!" if buf =~ /require 'pg'/ # Append some test data onto the end of the object puts "Write test:" conn.lo_lseek( fd, 0, PG::SEEK_END ) buf = SAMPLE_WRITE_DATA.dup totalbytes = 0 until buf.empty? bytes = conn.lo_write( fd, buf ) buf.slice!( 0, bytes ) totalbytes += bytes end puts " appended %d bytes" % [ totalbytes ] # Now export it puts "Export test:" File.unlink( SAMPLE_EXPORT_NAME ) if File.exist?( SAMPLE_EXPORT_NAME ) conn.lo_export( oid, SAMPLE_EXPORT_NAME ) puts " success!" if File.exist?( SAMPLE_EXPORT_NAME ) puts " exported as %s (%d bytes)" % [ SAMPLE_EXPORT_NAME, File.size(SAMPLE_EXPORT_NAME) ] conn.exec( 'COMMIT' ) puts "End of transaction." puts 'Testing read and delete from a new transaction:' puts ' starting a new transaction' conn.exec( 'BEGIN' ) fd = conn.lo_open( oid, PG::INV_READ ) puts ' reopened okay.' conn.lo_lseek( fd, 50, PG::SEEK_END ) buf = conn.lo_read( fd, 50 ) puts ' read okay.' if buf == SAMPLE_WRITE_DATA puts 'Closing and unlinking:' conn.lo_close( fd ) puts ' closed.' conn.lo_unlink( oid ) puts ' unlinked.' conn.exec( 'COMMIT' ) puts 'Done.' ruby-pg-0.17.0/sample/minimal-testcase.rb000077500000000000000000000007121222421776500202440ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pg' conn = PG.connect( :dbname => 'test' ) $stderr.puts '---', RUBY_DESCRIPTION, PG.version_string( true ), "Server version: #{conn.server_version}", "Client version: #{PG.respond_to?( :library_version ) ? PG.library_version : 'unknown'}", '---' result = conn.exec( "SELECT * from pg_stat_activity" ) $stderr.puts %Q{Expected this to return: ["select * from pg_stat_activity"]} p result.field_values( 'current_query' ) ruby-pg-0.17.0/sample/notify_wait.rb000077500000000000000000000025771222421776500173540ustar00rootroot00000000000000#!/usr/bin/env ruby # # Test script, demonstrating a non-poll notification for a table event. # BEGIN { require 'pathname' basedir = Pathname.new( __FILE__ ).expand_path.dirname.parent libdir = basedir + 'lib' $LOAD_PATH.unshift( libdir.to_s ) unless $LOAD_PATH.include?( libdir.to_s ) } require 'pg' TRIGGER_TABLE = %{ CREATE TABLE IF NOT EXISTS test ( message text ); } TRIGGER_FUNCTION = %{ CREATE OR REPLACE FUNCTION notify_test() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN NOTIFY woo; RETURN NULL; END $$ } DROP_TRIGGER = %{ DROP TRIGGER IF EXISTS notify_trigger ON test } TRIGGER = %{ CREATE TRIGGER notify_trigger AFTER UPDATE OR INSERT OR DELETE ON test FOR EACH STATEMENT EXECUTE PROCEDURE notify_test(); } conn = PG.connect( :dbname => 'test' ) conn.exec( TRIGGER_TABLE ) conn.exec( TRIGGER_FUNCTION ) conn.exec( DROP_TRIGGER ) conn.exec( TRIGGER ) conn.exec( 'LISTEN woo' ) # register interest in the 'woo' event notifications = [] puts "Now switch to a different term and run:", '', %{ psql test -c "insert into test values ('A message.')"}, '' puts "Waiting up to 30 seconds for for an event!" conn.wait_for_notify( 30 ) do |notify, pid| notifications << [ pid, notify ] end if notifications.empty? puts "Awww, I didn't see any events." else puts "I got one from pid %d: %s" % notifications.first end ruby-pg-0.17.0/sample/pg_statistics.rb000077500000000000000000000171451222421776500176750ustar00rootroot00000000000000#!/usr/bin/env ruby # vim: set noet nosta sw=4 ts=4 : # # PostgreSQL statistic gatherer. # Mahlon E. Smith # # Based on queries by Kenny Gorman. # http://www.kennygorman.com/wordpress/?page_id=491 # # An example gnuplot input script is included in the __END__ block # of this script. Using it, you can feed the output this script # generates to gnuplot (after removing header lines) to generate # some nice performance charts. # begin require 'ostruct' require 'optparse' require 'etc' require 'pg' rescue LoadError # 1.8 support unless Object.const_defined?( :Gem ) require 'rubygems' retry end raise end ### PostgreSQL Stats. Fetch information from pg_stat_* tables. ### Optionally run in a continuous loop, displaying deltas. ### class Stats VERSION = %q$Id$ def initialize( opts ) @opts = opts @db = PG.connect( :dbname => opts.database, :host => opts.host, :port => opts.port, :user => opts.user, :password => opts.pass, :sslmode => 'prefer' ) @last = nil end ###### public ###### ### Primary loop. Gather statistics and generate deltas. ### def run run_count = 0 loop do current_stat = self.get_stats # First run, store and continue # if @last.nil? @last = current_stat sleep @opts.interval next end # headers # if run_count == 0 || run_count % 50 == 0 puts "%-20s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s" % %w[ time commits rollbks blksrd blkshit bkends seqscan seqtprd idxscn idxtrd ins upd del locks activeq ] end # calculate deltas # delta = current_stat.inject({}) do |h, pair| stat, val = *pair if %w[ activeq locks bkends ].include?( stat ) h[stat] = current_stat[stat].to_i else h[stat] = current_stat[stat].to_i - @last[stat].to_i end h end delta[ 'time' ] = Time.now.strftime('%F %T') # new values # puts "%-20s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s%12s" % [ delta['time'], delta['commits'], delta['rollbks'], delta['blksrd'], delta['blkshit'], delta['bkends'], delta['seqscan'], delta['seqtprd'], delta['idxscn'], delta['idxtrd'], delta['ins'], delta['upd'], delta['del'], delta['locks'], delta['activeq'] ] @last = current_stat run_count += 1 sleep @opts.interval end end ### Query the database for performance measurements. Returns a hash. ### def get_stats res = @db.exec %Q{ SELECT MAX(stat_db.xact_commit) AS commits, MAX(stat_db.xact_rollback) AS rollbks, MAX(stat_db.blks_read) AS blksrd, MAX(stat_db.blks_hit) AS blkshit, MAX(stat_db.numbackends) AS bkends, SUM(stat_tables.seq_scan) AS seqscan, SUM(stat_tables.seq_tup_read) AS seqtprd, SUM(stat_tables.idx_scan) AS idxscn, SUM(stat_tables.idx_tup_fetch) AS idxtrd, SUM(stat_tables.n_tup_ins) AS ins, SUM(stat_tables.n_tup_upd) AS upd, SUM(stat_tables.n_tup_del) AS del, MAX(stat_locks.locks) AS locks, MAX(activity.sess) AS activeq FROM pg_stat_database AS stat_db, pg_stat_user_tables AS stat_tables, (SELECT COUNT(*) AS locks FROM pg_locks ) AS stat_locks, (SELECT COUNT(*) AS sess FROM pg_stat_activity WHERE current_query <> '') AS activity WHERE stat_db.datname = '%s'; } % [ @opts.database ] return res[0] end end ### Parse command line arguments. Return a struct of global options. ### def parse_args( args ) options = OpenStruct.new options.database = Etc.getpwuid( Process.uid ).name options.host = '127.0.0.1' options.port = 5432 options.user = Etc.getpwuid( Process.uid ).name options.sslmode = 'disable' options.interval = 5 opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.separator '' opts.separator 'Connection options:' opts.on( '-d', '--database DBNAME', "specify the database to connect to (default: \"#{options.database}\")" ) do |db| options.database = db end opts.on( '-h', '--host HOSTNAME', 'database server host' ) do |host| options.host = host end opts.on( '-p', '--port PORT', Integer, "database server port (default: \"#{options.port}\")" ) do |port| options.port = port end opts.on( '-U', '--user NAME', "database user name (default: \"#{options.user}\")" ) do |user| options.user = user end opts.on( '-W', 'force password prompt' ) do |pw| print 'Password: ' begin system 'stty -echo' options.pass = gets.chomp ensure system 'stty echo' puts end end opts.separator '' opts.separator 'Other options:' opts.on( '-i', '--interval SECONDS', Integer, "refresh interval in seconds (default: \"#{options.interval}\")") do |seconds| options.interval = seconds end opts.on_tail( '--help', 'show this help, then exit' ) do $stderr.puts opts exit end opts.on_tail( '--version', 'output version information, then exit' ) do puts Stats::VERSION exit end end opts.parse!( args ) return options end ### Go! ### if __FILE__ == $0 $stdout.sync = true Stats.new( parse_args( ARGV ) ).run end __END__ ###################################################################### ### T E R M I N A L O P T I O N S ###################################################################### #set terminal png nocrop enhanced font arial 8 size '800x600' x000000 xffffff x444444 #set output 'graph.png' set terminal pdf linewidth 4 size 11,8 set output 'graph.pdf' #set terminal aqua ###################################################################### ### O P T I O N S F O R A L L G R A P H S ###################################################################### set multiplot layout 2,1 title "PostgreSQL Statistics\n5 second sample rate (smoothed)" set grid x y set key right vertical outside set key nobox set xdata time set timefmt "%Y-%m-%d.%H:%M:%S" set format x "%l%p" set xtic rotate by -45 input_file = "database_stats.txt" # edit to taste! set xrange ["2012-04-16.00:00:00":"2012-04-17.00:00:00"] ###################################################################### ### G R A P H 1 ###################################################################### set title "Database Operations and Connection Totals" set yrange [0:200] plot \ input_file using 1:2 title "Commits" with lines smooth bezier, \ input_file using 1:3 title "Rollbacks" with lines smooth bezier, \ input_file using 1:11 title "Inserts" with lines smooth bezier, \ input_file using 1:12 title "Updates" with lines smooth bezier, \ input_file using 1:13 title "Deletes" with lines smooth bezier, \ input_file using 1:6 title "Backends (total)" with lines, \ input_file using 1:15 title "Active queries (total)" with lines smooth bezier ###################################################################### ### G R A P H 2 ###################################################################### set title "Backend Performance" set yrange [0:10000] plot \ input_file using 1:4 title "Block (cache) reads" with lines smooth bezier, \ input_file using 1:5 title "Block (cache) hits" with lines smooth bezier, \ input_file using 1:7 title "Sequence scans" with lines smooth bezier, \ input_file using 1:8 title "Sequence tuple reads" with lines smooth bezier, \ input_file using 1:9 title "Index scans" with lines smooth bezier, \ input_file using 1:10 title "Index tuple reads" with lines smooth bezier ###################################################################### ### C L E A N U P ###################################################################### unset multiplot reset ruby-pg-0.17.0/sample/replication_monitor.rb000077500000000000000000000127361222421776500210760ustar00rootroot00000000000000#!/usr/bin/env ruby # vim: set noet nosta sw=4 ts=4 : # # Get the current WAL segment and offset from a master postgresql # server, and compare slave servers to see how far behind they # are in MB. This script should be easily modified for use with # Nagios/Mon/Monit/Zabbix/whatever, or wrapping it in a display loop, # and is suitable for both WAL shipping or streaming forms of replication. # # Mahlon E. Smith # # First argument is the master server, all other arguments are treated # as slave machines. # # db_replication.monitor db-master.example.com ... # begin require 'ostruct' require 'optparse' require 'pathname' require 'etc' require 'pg' require 'pp' rescue LoadError # 1.8 support unless Object.const_defined?( :Gem ) require 'rubygems' retry end raise end ### A class to encapsulate the PG handles. ### class PGMonitor VERSION = %q$Id$ # When to consider a slave as 'behind', measured in WAL segments. # The default WAL segment size is 16, so we'll alert after # missing two WAL files worth of data. # LAG_ALERT = 32 ### Create a new PGMonitor object. ### def initialize( opts, hosts ) @opts = opts @master = hosts.shift @slaves = hosts @current_wal = {} @failures = [] end attr_reader :opts, :current_wal, :master, :slaves, :failures ### Perform the connections and check the lag. ### def check # clear prior failures, get current xlog info @failures = [] return unless self.get_current_wal # check all slaves self.slaves.each do |slave| begin slave_db = PG.connect( :dbname => self.opts.database, :host => slave, :port => self.opts.port, :user => self.opts.user, :password => self.opts.pass, :sslmode => 'prefer' ) xlog = slave_db.exec( 'SELECT pg_last_xlog_receive_location()' ).getvalue( 0, 0 ) slave_db.close lag_in_megs = ( self.find_lag( xlog ).to_f / 1024 / 1024 ).abs if lag_in_megs >= LAG_ALERT failures << { :host => slave, :error => "%0.2fMB behind the master." % [ lag_in_megs ] } end rescue => err failures << { :host => slave, :error => err.message } end end end ######### protected ######### ### Ask the master for the current xlog information, to compare ### to slaves. Returns true on succcess. On failure, populates ### the failures array and returns false. ### def get_current_wal master_db = PG.connect( :dbname => self.opts.database, :host => self.master, :port => self.opts.port, :user => self.opts.user, :password => self.opts.pass, :sslmode => 'prefer' ) self.current_wal[ :segbytes ] = master_db.exec( 'SHOW wal_segment_size' ). getvalue( 0, 0 ).sub( /\D+/, '' ).to_i << 20 current = master_db.exec( 'SELECT pg_current_xlog_location()' ).getvalue( 0, 0 ) self.current_wal[ :segment ], self.current_wal[ :offset ] = current.split( /\// ) master_db.close return true # If we can't get any of the info from the master, then there is no # point in a comparison with slaves. # rescue => err self.failures << { :host => self.master, :error => 'Unable to retrieve required info from the master (%s)' % [ err.message ] } return false end ### Given an +xlog+ position from a slave server, return ### the number of bytes the slave needs to replay before it ### is caught up to the master. ### def find_lag( xlog ) s_segment, s_offset = xlog.split( /\// ) m_segment = self.current_wal[ :segment ] m_offset = self.current_wal[ :offset ] m_segbytes = self.current_wal[ :segbytes ] return (( m_segment.hex - s_segment.hex ) * m_segbytes) + ( m_offset.hex - s_offset.hex ) end end ### Parse command line arguments. Return a struct of global options. ### def parse_args( args ) options = OpenStruct.new options.database = 'postgres' options.port = 5432 options.user = Etc.getpwuid( Process.uid ).name options.sslmode = 'prefer' opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options] [slave2, slave3...]" opts.separator '' opts.separator 'Connection options:' opts.on( '-d', '--database DBNAME', "specify the database to connect to (default: \"#{options.database}\")" ) do |db| options.database = db end opts.on( '-h', '--host HOSTNAME', 'database server host' ) do |host| options.host = host end opts.on( '-p', '--port PORT', Integer, "database server port (default: \"#{options.port}\")" ) do |port| options.port = port end opts.on( '-U', '--user NAME', "database user name (default: \"#{options.user}\")" ) do |user| options.user = user end opts.on( '-W', 'force password prompt' ) do |pw| print 'Password: ' begin system 'stty -echo' options.pass = $stdin.gets.chomp ensure system 'stty echo' puts end end opts.separator '' opts.separator 'Other options:' opts.on_tail( '--help', 'show this help, then exit' ) do $stderr.puts opts exit end opts.on_tail( '--version', 'output version information, then exit' ) do puts PGMonitor::VERSION exit end end opts.parse!( args ) return options end if __FILE__ == $0 opts = parse_args( ARGV ) raise ArgumentError, "At least two PostgreSQL servers are required." if ARGV.length < 2 mon = PGMonitor.new( opts, ARGV ) mon.check if mon.failures.empty? puts "All is well!" exit 0 else puts "Database replication delayed or broken." mon.failures.each do |bad| puts "%s: %s" % [ bad[ :host ], bad[ :error ] ] end exit 1 end end ruby-pg-0.17.0/sample/test_binary_values.rb000077500000000000000000000014461222421776500207140ustar00rootroot00000000000000#!/usr/bin/env ruby1.9.1 require 'pg' db = PG.connect( :dbname => 'test' ) db.exec "DROP TABLE IF EXISTS test" db.exec "CREATE TABLE test (a INTEGER, b BYTEA)" a = 42 b = [1, 2, 3] db.exec "INSERT INTO test(a, b) VALUES($1::int, $2::bytea)", [a, {:value => b.pack('N*'), :format => 1}] db.exec( "SELECT a::int, b::bytea FROM test LIMIT 1", [], 1 ) do |res| res.nfields.times do |i| puts "Field %d is: %s, a %s (%s) column from table %p" % [ i, res.fname( i ), db.exec( "SELECT format_type($1,$2)", [res.ftype(i), res.fmod(1)] ).getvalue(0,0), res.fformat( i ).zero? ? "string" : "binary", res.ftable( i ), ] end res.each do |row| puts "a = #{row['a'].inspect}" puts "a (unpacked) = #{row['a'].unpack('N*').inspect}" puts "b = #{row['b'].unpack('N*').inspect}" end end ruby-pg-0.17.0/sample/wal_shipper.rb000077500000000000000000000277561222421776500173430ustar00rootroot00000000000000#!/usr/bin/env ruby # # A script to wrap ssh and rsync for PostgreSQL WAL files shipping. # Mahlon E. Smith # # Based off of Joshua Drake's PITRTools concept, but with some important # differences: # # - Only supports PostgreSQL >= 8.3 # - No support for rsync version < 3 # - Only shipping, no client side sync (too much opportunity for failure, # and it's easy to get a base backup manually) # - WAL files are only stored once, regardless of how many # slaves are configured or not responding, and are removed from # the master when they are no longer needed. # - Each slave can have completely distinct settings, instead # of a single set of options applied to all slaves # - slave sync can be individually paused from the master # - can run synchronously, or if you have a lot of slaves, threaded async mode # - It's ruby, instead of python. :) # # wal_shipper is configurable via an external YAML file, and will create # a template on its first run -- you'll need to modify it! It expects # a directory structure like so: # # postgres/ # data/... # bin/wal_shipper.rb # etc/wal_shipper.conf <-- YAML settings! # wal/ # # It should be loaded from the PostgreSQL master's postgresql.conf # as such, after putting it into your postgres user homedir under 'bin': # # archive_command = '/path/to/postgres_home/bin/wal_shipper.rb %p' # # Passwordless ssh keys need to be set up for the postgres user on all # participating masters and slaves. # # You can use any replay method of your choosing on the slaves. # Here's a nice example using pg_standby, to be put in data/recovery.conf: # # restore_command = 'pg_standby -t /tmp/pgrecovery.done -s5 -w0 -c /path/to/postgres_home/wal_files/ %f %p %r' # # Or, here's another simple alternative data/recovery.conf, for using WAL shipping # alongside streaming replication: # # standby_mode = 'on' # primary_conninfo = 'host=master.example.com port=5432 user=repl password=XXXXXXX' # restore_command = 'cp /usr/local/pgsql/wal/%f %p' # trigger_file = '/usr/local/pgsql/pg.become_primary' # archive_cleanup_command = '/usr/local/bin/pg_archivecleanup /usr/local/pgsql/wal %r' # #======================================================================================== require 'pathname' require 'yaml' require 'fileutils' require 'ostruct' ### Encapsulate WAL shipping functionality. ### module WalShipper ### Send messages to the PostgreSQL log files. ### def log( msg ) return unless @debug puts "WAL Shipper: %s" % [ msg ] end ### An object that represents a single destination from the ### configuration file. ### class Destination < OpenStruct include WalShipper ### Create a new WalShipper::Destination object. def initialize( dest, debug=false ) @debug = debug super( dest ) self.validate end ######### protected ######### ### Check for required keys and normalize various keys. ### def validate # Check for required destination keys %w[ label kind ].each do |key| if self.send( key.to_sym ).nil? self.log "Destination %p missing required '%s' key." % [ self, key ] self.invalid = true end end # Ensure paths are Pathnames for the 'file' destination type. self.path = Pathname.new( self.path ) if self.kind == 'file' if self.kind == 'rsync-ssh' self.port ||= 22 self.user = self.user ? "#{self.user}@" : '' end end end # Class Destination ### Class for creating new Destination objects and determining how to ### ship WAL files to them. ### class Dispatcher include WalShipper ### Create a new Shipper object, given a +conf+ hash and a +wal+ file ### Pathname object. ### def initialize( wal, conf ) # Make the config keys instance variables. conf.each_pair {|key, val| self.instance_variable_set( "@#{key}", val ) } # Spool directory check. # @spool = Pathname.new( @spool ) @spool.exist? or raise "The configured spool directory (%s) doesn't exist." % [ @spool ] # Stop right away if we have disabled shipping. # unless @enabled self.log "WAL shipping is disabled, queuing segment %s" % [ wal.basename ] exit 1 end # Instantiate Destination objects, creating new spool directories # for each. # @destinations. collect!{|dest| WalShipper::Destination.new( dest, @debug ) }. reject {|dest| dest.invalid }. collect do |dest| dest.spool = @spool + dest.label dest.spool.mkdir( 0711 ) unless dest.spool.exist? dest end # Put the WAL file into the spool for processing! # @waldir = @spool + 'wal_segments' @waldir.mkdir( 0711 ) unless @waldir.exist? self.log "Copying %s to %s" % [ wal.basename, @waldir ] FileUtils::cp wal, @waldir # 'wal' now references the copy. The original is managed and auto-expired # by PostgreSQL when a new checkpoint segment it reached. @wal = @waldir + wal.basename end ### Create hardlinks for the WAL file into each of the destination directories ### for separate queueing and recording of what was shipped successfully. ### def link @destinations.each do |dest| self.log "Linking %s into %s" % [ @wal.basename, dest.spool.basename ] FileUtils::ln @wal, dest.spool, :force => true end end ### Decide to be synchronous or threaded, and delegate each destination ### to the proper ship method. ### def dispatch # Synchronous mode. # unless @async self.log "Performing a synchronous dispatch." @destinations.each {|dest| self.dispatch_dest( dest ) } return end tg = ThreadGroup.new # Async, one thread per destination # if @async_max.nil? || @async_max.to_i.zero? self.log "Performing an asynchronous dispatch: one thread per destination." @destinations.each do |dest| t = Thread.new do Thread.current.abort_on_exception = true self.dispatch_dest( dest ) end tg.add( t ) end tg.list.each {|t| t.join } return end # Async, one thread per destination, in groups of asynx_max size. # self.log "Performing an asynchronous dispatch: one thread per destination, %d at a time." % [ @async_max ] all_dests = @destinations.dup dest_chunks = [] until all_dests.empty? do dest_chunks << all_dests.slice!( 0, @async_max ) end dest_chunks.each do |chunk| chunk.each do |dest| t = Thread.new do Thread.current.abort_on_exception = true self.dispatch_dest( dest ) end tg.add( t ) end tg.list.each {|t| t.join } end return end ### Remove any WAL segments no longer needed by slaves. ### def clean_spool total = 0 @waldir.children.each do |wal| if wal.stat.nlink == 1 total += wal.unlink end end self.log "Removed %d WAL segment%s." % [ total, total == 1 ? '' : 's' ] end ######### protected ######### ### Send WAL segments to remote +dest+ via rsync+ssh. ### Passwordless keys between the user running this script (postmaster owner) ### and remote user need to be set up in advance. ### def ship_rsync_ssh( dest ) if dest.host.nil? self.log "Destination %p missing required 'host' key. WAL is queued." % [ dest.host ] return end rsync_flags = '-zc' ssh_string = "%s -o ConnectTimeout=%d -o StrictHostKeyChecking=no -p %d" % [ @ssh, @ssh_timeout || 10, dest.port ] src_string = '' dst_string = "%s%s:%s/" % [ dest.user, dest.host, dest.path ] # If there are numerous files in the spool dir, it means there was # an error transferring to this host in the past. Try and ship all # WAL segments, instead of just the new one. PostgreSQL on the slave # side will "do the right thing" as they come in, regardless of # ordering. # if dest.spool.children.length > 1 src_string = dest.spool.to_s + '/' rsync_flags << 'r' else src_string = dest.spool + @wal.basename end ship_wal_cmd = [ @rsync, @debug ? (rsync_flags << 'vh') : (rsync_flags << 'q'), '--remove-source-files', '-e', ssh_string, src_string, dst_string ] self.log "Running command '%s'" % [ ship_wal_cmd.join(' ') ] system *ship_wal_cmd # Run external notification program on error, if one is configured. # unless $?.success? self.log "Ack! Error while shipping to %p, WAL is queued." % [ dest.label ] system @error_cmd, dest.label if @error_cmd end end ### Copy WAL segments to remote path as set in +dest+. ### This is useful for longer term PITR, copying to NFS shares, etc. ### def ship_file( dest ) if dest.path.nil? self.log "Destination %p missing required 'path' key. WAL is queued." % [ dest ] return end dest.path.mkdir( 0711 ) unless dest.path.exist? # If there are numerous files in the spool dir, it means there was # an error transferring to this host in the past. Try and ship all # WAL segments, instead of just the new one. PostgreSQL on the slave # side will "do the right thing" as they come in, regardless of # ordering. # if dest.spool.children.length > 1 dest.spool.children.each do |wal| wal.unlink if self.copy_file( wal, dest.path, dest.label, dest.compress ) end else wal = dest.spool + @wal.basename wal.unlink if self.copy_file( wal, dest.path, dest.label, dest.compress ) end end ### Given a +wal+ Pathname, a +path+ destination, and the destination ### label, copy and optionally compress a WAL file. ### def copy_file( wal, path, label, compress=false ) dest_file = path + wal.basename FileUtils::cp wal, dest_file if compress system *[ 'gzip', '-f', dest_file ] raise "Error while compressing: %s" % [ wal.basename ] unless $?.success? end self.log "Copied %s%s to %s." % [ wal.basename, compress ? ' (and compressed)' : '', path ] return true rescue => err self.log "Ack! Error while copying '%s' (%s) to %p, WAL is queued." % [ wal.basename, err.message, path ] system @error_cmd, label if @error_cmd return false end ### Figure out how to send the WAL file to its intended destination +dest+. ### def dispatch_dest( dest ) if ! dest.enabled.nil? && ! dest.enabled self.log "Skipping explicity disabled destination %p, WAL is queued." % [ dest.label ] return end # Send to the appropriate method. ( rsync-ssh --> ship_rsync_ssh ) # meth = ( 'ship_' + dest.kind.gsub(/-/, '_') ).to_sym if WalShipper::Dispatcher.method_defined?( meth ) self.send( meth, dest ) else self.log "Unknown destination kind %p for %p. WAL is queued." % [ dest.kind, dest.label ] end end end end # Ship the WAL file! # if __FILE__ == $0 CONFIG_DIR = Pathname.new( __FILE__ ).dirname.parent + 'etc' CONFIG = CONFIG_DIR + 'wal_shipper.conf' unless CONFIG.exist? CONFIG_DIR.mkdir( 0711 ) unless CONFIG_DIR.exist? CONFIG.open('w') {|conf| conf.print(DATA.read) } CONFIG.chmod( 0644 ) puts "No WAL shipping configuration found, default file created." end wal = ARGV[0] or raise "No WAL file was specified on the command line." wal = Pathname.new( wal ) conf = YAML.load( CONFIG.read ) shipper = WalShipper::Dispatcher.new( wal, conf ) shipper.link shipper.dispatch shipper.clean_spool end __END__ --- # Spool from pg_xlog to the working area? # This must be set to 'true' for wal shipping to function! enabled: false # Log everything to the PostgreSQL log files? debug: true # The working area for WAL segments. spool: /opt/local/var/db/postgresql84/wal # With multiple slaves, ship WAL in parallel, or be synchronous? async: false # Put a ceiling on the parallel threads? # '0' or removing this option uses a thread for each destination, # regardless of how many you have. Keep in mind that's 16 * destination # count megs of simultaneous bandwidth. async_max: 5 # Paths and settings for various binaries. rsync: /usr/bin/rsync ssh: /usr/bin/ssh ssh_timeout: 10 destinations: - label: rsync-example port: 2222 kind: rsync-ssh host: localhost user: postgres path: wal # relative to the user's homedir on the remote host enabled: false - label: file-example kind: file compress: true enabled: true path: /tmp/someplace ruby-pg-0.17.0/sample/warehouse_partitions.rb000077500000000000000000000165001222421776500212650ustar00rootroot00000000000000#!/usr/bin/env ruby # vim: set nosta noet ts=4 sw=4: # # Script to automatically move partitioned tables and their indexes # to a separate area on disk. # # Mahlon E. Smith # # Example use case: # # - You've got a heavy insert table, such as syslog data. # - This table has a partitioning trigger (or is manually partitioned) # by date, to separate incoming stuff from archival/report stuff. # - You have a tablespace on cheap or slower disk (maybe even # ZFS compressed, or some such!) # # The only assumption this script makes is that your tables are dated, and # the tablespace they're moving into already exists. # # A full example, using the syslog idea from above, where each child # table is date partitioned by a convention of "syslog_YEAR-WEEKOFYEAR": # # syslog # <--- parent # syslog_2012_06 # <--- inherited # syslog_2012_07 # <--- inherited # syslog_2012_08 # <--- inherited # ... # # You'd run this script like so: # # ./warehouse_partitions.rb -F syslog_%Y_%U # # Assuming this was week 12 of the year, tables syslog_2012_06 through # syslog_2012_11 would start sequentially migrating into the tablespace # called 'warehouse'. # begin require 'date' require 'ostruct' require 'optparse' require 'pathname' require 'etc' require 'pg' rescue LoadError # 1.8 support unless Object.const_defined?( :Gem ) require 'rubygems' retry end raise end ### A tablespace migration class. ### class PGWarehouse def initialize( opts ) @opts = opts @db = PG.connect( :dbname => opts.database, :host => opts.host, :port => opts.port, :user => opts.user, :password => opts.pass, :sslmode => 'prefer' ) @db.exec "SET search_path TO %s" % [ opts.schema ] if opts.schema @relations = self.relations end attr_reader :db ###### public ###### ### Perform the tablespace moves. ### def migrate if @relations.empty? $stderr.puts 'No tables were found for warehousing.' return end $stderr.puts "Found %d relation%s to move." % [ relations.length, relations.length == 1 ? '' : 's' ] @relations.sort_by{|_,v| v[:name] }.each do |_, val| $stderr.print " - Moving table '%s' to '%s'... " % [ val[:name], @opts.tablespace ] if @opts.dryrun $stderr.puts '(not really)' else age = self.timer do db.exec "ALTER TABLE %s SET TABLESPACE %s;" % [ val[:name], @opts.tablespace ] end puts age end val[ :indexes ].each do |idx| $stderr.print " - Moving index '%s' to '%s'... " % [ idx, @opts.tablespace ] if @opts.dryrun $stderr.puts '(not really)' else age = self.timer do db.exec "ALTER INDEX %s SET TABLESPACE %s;" % [ idx, @opts.tablespace ] end puts age end end end end ######### protected ######### ### Get OIDs and current tablespaces for everything under the ### specified schema. ### def relations return @relations if @relations relations = {} query = %q{ SELECT c.oid AS oid, c.relname AS name, c.relkind AS kind, t.spcname AS tspace FROM pg_class AS c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace WHERE c.relkind = 'r' } query << "AND n.nspname='#{@opts.schema}'" if @opts.schema # Get the relations list, along with each element's current tablespace. # self.db.exec( query ) do |res| res.each do |row| relations[ row['oid'] ] = { :name => row['name'], :tablespace => row['tspace'], :indexes => [], :parent => nil } end end # Add table inheritence information. # db.exec 'SELECT inhrelid AS oid, inhparent AS parent FROM pg_inherits' do |res| res.each do |row| relations[ row['oid'] ][ :parent ] = row['parent'] end end # Remove tables that don't qualify for warehousing. # # - Tables that are not children of a parent # - Tables that are already in the warehouse tablespace # - The currently active child (it's likely being written to!) # - Any table that can't be parsed into the specified format # relations.reject! do |oid, val| begin val[:parent].nil? || val[:tablespace] == @opts.tablespace || val[:name] == Time.now.strftime( @opts.format ) || ! DateTime.strptime( val[:name], @opts.format ) rescue ArgumentError true end end query = %q{ SELECT c.oid AS oid, i.indexname AS name FROM pg_class AS c INNER JOIN pg_indexes AS i ON i.tablename = c.relname } query << "AND i.schemaname='#{@opts.schema}'" if @opts.schema # Attach index names to tables. # db.exec( query ) do |res| res.each do |row| relations[ row['oid'] ][ :indexes ] << row['name'] if relations[ row['oid'] ] end end return relations end ### Wrap arbitrary commands in a human readable timer. ### def timer start = Time.now yield age = Time.now - start diff = age secs = diff % 60 diff = ( diff - secs ) / 60 mins = diff % 60 diff = ( diff - mins ) / 60 hour = diff % 24 return "%02d:%02d:%02d" % [ hour, mins, secs ] end end ### Parse command line arguments. Return a struct of global options. ### def parse_args( args ) options = OpenStruct.new options.database = Etc.getpwuid( Process.uid ).name options.host = '127.0.0.1' options.port = 5432 options.user = Etc.getpwuid( Process.uid ).name options.sslmode = 'prefer' options.tablespace = 'warehouse' opts = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.separator '' opts.separator 'Connection options:' opts.on( '-d', '--database DBNAME', "specify the database to connect to (default: \"#{options.database}\")" ) do |db| options.database = db end opts.on( '-h', '--host HOSTNAME', 'database server host' ) do |host| options.host = host end opts.on( '-p', '--port PORT', Integer, "database server port (default: \"#{options.port}\")" ) do |port| options.port = port end opts.on( '-n', '--schema SCHEMA', String, "operate on the named schema only (default: none)" ) do |schema| options.schema = schema end opts.on( '-T', '--tablespace SPACE', String, "move old tables to this tablespace (default: \"#{options.tablespace}\")" ) do |tb| options.tablespace = tb end opts.on( '-F', '--tableformat FORMAT', String, "The naming format (strftime) for the inherited tables (default: none)" ) do |format| options.format = format end opts.on( '-U', '--user NAME', "database user name (default: \"#{options.user}\")" ) do |user| options.user = user end opts.on( '-W', 'force password prompt' ) do |pw| print 'Password: ' begin system 'stty -echo' options.pass = gets.chomp ensure system 'stty echo' puts end end opts.separator '' opts.separator 'Other options:' opts.on_tail( '--dry-run', "don't actually do anything" ) do options.dryrun = true end opts.on_tail( '--help', 'show this help, then exit' ) do $stderr.puts opts exit end opts.on_tail( '--version', 'output version information, then exit' ) do puts Stats::VERSION exit end end opts.parse!( args ) return options end if __FILE__ == $0 opts = parse_args( ARGV ) raise ArgumentError, "A naming format (-F) is required." unless opts.format $stdout.sync = true PGWarehouse.new( opts ).migrate end ruby-pg-0.17.0/spec/000077500000000000000000000000001222421776500141265ustar00rootroot00000000000000ruby-pg-0.17.0/spec/data/000077500000000000000000000000001222421776500150375ustar00rootroot00000000000000ruby-pg-0.17.0/spec/data/expected_trace.out000066400000000000000000000010361222421776500205470ustar00rootroot00000000000000To backend> Msg Q To backend> "SELECT 1 AS one" To backend> Msg complete, length 21 From backend> T From backend (#4)> 28 From backend (#2)> 1 From backend> "one" From backend (#4)> 0 From backend (#2)> 0 From backend (#4)> 23 From backend (#2)> 4 From backend (#4)> -1 From backend (#2)> 0 From backend> D From backend (#4)> 11 From backend (#2)> 1 From backend (#4)> 1 From backend (1)> 1 From backend> C From backend (#4)> 11 From backend> "SELECT" From backend> Z From backend (#4)> 5 From backend> Z From backend (#4)> 5 From backend> T ruby-pg-0.17.0/spec/data/random_binary_data000066400000000000000000000120001222421776500205700ustar00rootroot00000000000000ko W 5Py%{/b4fdyo0|p6@ hnK()EzMq~%du0/bQfXzթP:HX2r?;ӍT.0l686UiDlV+4IShIXJDqNi-Q~K(s P)1;ؽ'3fҳ_|?e0@=1WǦ"#їsʁbM($S&NmZq2ݩ&@&HىSb]V+nk#LL(W g`=U cԌ8gn#JoHj5n'|D 4P򕣎|}*YX\>@Ɣ&1,[\W]+H?vk[$}/DsNe-g-]+2Ȗ*SVRt00v|ʤIhz>wr`y:YL`s{T.w_0N[JvR&lcHaϒWAE=;2Hf^DZU^ܢqePv36QkPzwI]dׇkƮ)SgZb~PX3Baɻ%w g˂L_sV6=}JF6*}5G~иpz0I[|-H@F+2Fgㆋ%9P; BT_pOcM h>p3SӞ9^-5 60x@ e+F48 :F S3D@,鋾AQz nRMR=#H3Lfokhw^Е|ݱvw.HzYw (Vj'*Sѥsєpfk@ o!ˆ!B(bΐ%:?K徃mo]C^5 N k*nKW9jr7; (=΄ ~t)/Qq3X\AAnQTMǔƹ0XYFaȄYvG{~FmQg?A3=!etaEǞ|1=*yČTliH,e(_y.G)HU&12S7+#PMy/`)x{on-06t>YO}GߜZȜ'mecDȞ2pUn֣?6wִݿo/9?pIp)yP1hw8E!\)? R'iLR3{I.oQ%'pHFO40sɇ[bE:}ap?大A_x2h6&Tf ᅎK˃bKp`!Y¹NlKƭ+agI;qDf WvN>Ct}3rSVFZ6b+g x^LKG(_ܮN?ʒ?:cNk%L["v`;˜J)OɬG4xaܶB%6Qp-O+rqy .'(9_jswnSŖsC,aB;"I{[r-HQA:>{v  ˁ**]O ZSrͲY+'…ܽXKkьd3=V/l#aP҈E&kHHn1('m)8ʎxܹ?֬ 3{?h2U1\L)]tѓ;ߘu) S4UVi#[ xXL9j+20OX3Mepv9=>!P;MDqM_팅`Fh}Ha. KxPx3#1ۭZGrȢ0T~N@kx \7;гLpr;'Tkۻ`up<$mo~fU ' lJ^ſz>*/H(;K}Rao~ NmE5_|dO95Av hCѿ) =L]&(lB2+&tsވ] qX# jG674!{B^=Etс{YBE,vW&U|>%뻻Mui-UJnF &k;+s:z¯-tWtCjHs$k#ikNHi0('xգs3jh!e CY@? ʔ}x`s(ˍS ctLqUG]lJ ms9B`zw:\g7LJ3PT ;?uT Eqs#5zr22;cdaUCߎg=% )>>e_'^Gz|W'?L{ȸq tk-"ؽ^S*"jVM[<1V{VQ./x0иrY=M[N9S(j#A~~?yoX 5l~~C^P>D>oͬ"_$ʵP`jxz=}?vzέ_PD D 淟}a^,HbR%ɵz~c"x;tOm# mJF6b,94K+}vV=ǻboILQm .5JxkȪ5;ѣA?In Wj2L^,zJΧdgH M~Ž᥇%jlanυ 0U-[ k!Xݮ!JTYrVio *`|Q)p;&YZG!(n^rbv X"W/ jT'^.LⅎͲ8b#b}6ק|ɷV5͊oGH)寊+GB3%`2r%>z'0-uPBNS0D)>-K%񌀬@2ir_]TV)fpQƏny2Y=߇G?U2}v%A:ik D&dq ͩb-ӰJN(iÜ*#2ّ chZUl \E Zeu*$(K 'j?C wP{| O~O(|(i+sx W{y diTܕZ&GOD7Pp%=&i=U>*8RyY(~]M}5 JF^]H-aF%j=;{$ȻYѹ(GLS \AޥwAo^np`C2;d+; M76%M-Ϻq.G=)[(p4!(D =rL4Nqe^fw{KCx> 9l e)XRP'AU#gyGͦCR {| afU]uy؆^p/_/g%AG.{^\>ruby-pg-0.17.0/spec/lib/000077500000000000000000000000001222421776500146745ustar00rootroot00000000000000ruby-pg-0.17.0/spec/lib/helpers.rb000077500000000000000000000172351222421776500166760ustar00rootroot00000000000000#!/usr/bin/env ruby require 'pathname' require 'rspec' require 'shellwords' require 'pg' TEST_DIRECTORY = Pathname.getwd + "tmp_test_specs" module PG::TestingHelpers # Set some ANSI escape code constants (Shamelessly stolen from Perl's # Term::ANSIColor by Russ Allbery and Zenin ANSI_ATTRIBUTES = { 'clear' => 0, 'reset' => 0, 'bold' => 1, 'dark' => 2, 'underline' => 4, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'concealed' => 8, 'black' => 30, 'on_black' => 40, 'red' => 31, 'on_red' => 41, 'green' => 32, 'on_green' => 42, 'yellow' => 33, 'on_yellow' => 43, 'blue' => 34, 'on_blue' => 44, 'magenta' => 35, 'on_magenta' => 45, 'cyan' => 36, 'on_cyan' => 46, 'white' => 37, 'on_white' => 47 } ############### module_function ############### ### Create a string that contains the ANSI codes specified and return it def ansi_code( *attributes ) attributes.flatten! attributes.collect! {|at| at.to_s } return '' unless /(?:vt10[03]|xterm(?:-color)?|linux|screen)/i =~ ENV['TERM'] attributes = ANSI_ATTRIBUTES.values_at( *attributes ).compact.join(';') # $stderr.puts " attr is: %p" % [attributes] if attributes.empty? return '' else return "\e[%sm" % attributes end end ### Colorize the given +string+ with the specified +attributes+ and return it, handling ### line-endings, color reset, etc. def colorize( *args ) string = '' if block_given? string = yield else string = args.shift end ending = string[/(\s)$/] || '' string = string.rstrip return ansi_code( args.flatten ) + string + ansi_code( 'reset' ) + ending end ### Output a message with highlighting. def message( *msg ) $stderr.puts( colorize(:bold) { msg.flatten.join(' ') } ) end ### Output a logging message if $VERBOSE is true def trace( *msg ) return unless $VERBOSE output = colorize( msg.flatten.join(' '), 'yellow' ) $stderr.puts( output ) end ### Return the specified args as a string, quoting any that have a space. def quotelist( *args ) return args.flatten.collect {|part| part.to_s =~ /\s/ ? part.to_s.inspect : part.to_s } end ### Run the specified command +cmd+ with system(), failing if the execution ### fails. def run( *cmd ) cmd.flatten! if cmd.length > 1 trace( quotelist(*cmd) ) else trace( cmd ) end system( *cmd ) raise "Command failed: [%s]" % [cmd.join(' ')] unless $?.success? end ### Run the specified command +cmd+ after redirecting stdout and stderr to the specified ### +logpath+, failing if the execution fails. def log_and_run( logpath, *cmd ) cmd.flatten! if cmd.length > 1 trace( quotelist(*cmd) ) else trace( cmd ) end # Eliminate the noise of creating/tearing down the database by # redirecting STDERR/STDOUT to a logfile if the Ruby interpreter # supports fork() logfh = File.open( logpath, File::WRONLY|File::CREAT|File::APPEND ) begin pid = fork rescue NotImplementedError logfh.close system( *cmd ) else if pid logfh.close else $stdout.reopen( logfh ) $stderr.reopen( $stdout ) $stderr.puts( ">>> " + cmd.shelljoin ) exec( *cmd ) $stderr.puts "After the exec()?!??!" exit! end Process.wait( pid ) end raise "Command failed: [%s]" % [cmd.join(' ')] unless $?.success? end ### Check the current directory for directories that look like they're ### testing directories from previous tests, and tell any postgres instances ### running in them to shut down. def stop_existing_postmasters # tmp_test_0.22329534700318 pat = Pathname.getwd + 'tmp_test_*' Pathname.glob( pat.to_s ).each do |testdir| datadir = testdir + 'data' pidfile = datadir + 'postmaster.pid' if pidfile.exist? && pid = pidfile.read.chomp.to_i $stderr.puts "pidfile (%p) exists: %d" % [ pidfile, pid ] begin Process.kill( 0, pid ) rescue Errno::ESRCH $stderr.puts "No postmaster running for %s" % [ datadir ] # Process isn't alive, so don't try to stop it else $stderr.puts "Stopping lingering database at PID %d" % [ pid ] run 'pg_ctl', '-D', datadir.to_s, '-m', 'fast', 'stop' end else $stderr.puts "No pidfile (%p)" % [ pidfile ] end end end ### Set up a PostgreSQL database instance for testing. def setup_testing_db( description ) require 'pg' stop_existing_postmasters() puts "Setting up test database for #{description}" @test_pgdata = TEST_DIRECTORY + 'data' @test_pgdata.mkpath @port = 54321 ENV['PGPORT'] = @port.to_s ENV['PGHOST'] = 'localhost' @conninfo = "host=localhost port=#{@port} dbname=test" @logfile = TEST_DIRECTORY + 'setup.log' trace "Command output logged to #{@logfile}" begin unless (@test_pgdata+"postgresql.conf").exist? FileUtils.rm_rf( @test_pgdata, :verbose => $DEBUG ) $stderr.puts "Running initdb" log_and_run @logfile, 'initdb', '-E', 'UTF8', '--no-locale', '-D', @test_pgdata.to_s end trace "Starting postgres" log_and_run @logfile, 'pg_ctl', '-w', '-o', "-k #{TEST_DIRECTORY.to_s.dump}", '-D', @test_pgdata.to_s, 'start' sleep 2 $stderr.puts "Creating the test DB" log_and_run @logfile, 'psql', '-e', '-c', 'DROP DATABASE IF EXISTS test', 'postgres' log_and_run @logfile, 'createdb', '-e', 'test' rescue => err $stderr.puts "%p during test setup: %s" % [ err.class, err.message ] $stderr.puts "See #{@logfile} for details." $stderr.puts *err.backtrace if $DEBUG fail end conn = PG.connect( @conninfo ) conn.set_notice_processor do |message| $stderr.puts( description + ':' + message ) if $DEBUG end return conn end def teardown_testing_db( conn ) puts "Tearing down test database" if conn check_for_lingering_connections( conn ) conn.finish end log_and_run @logfile, 'pg_ctl', '-D', @test_pgdata.to_s, 'stop' end def check_for_lingering_connections( conn ) conn.exec( "SELECT * FROM pg_stat_activity" ) do |res| conns = res.find_all {|row| row['pid'].to_i != conn.backend_pid } unless conns.empty? puts "Lingering connections remain:" conns.each do |row| puts " [%d] {%s} %s -- %s" % row.values_at( 'pid', 'state', 'application_name', 'query' ) end end end end def connection_string_should_contain_application_name(conn_args, app_name) conn_name = conn_args.match(/application_name='(.*)'/)[1] conn_name.should include(app_name[0..10]) conn_name.should include(app_name[-10..-1]) conn_name.length.should <= 64 end # Ensure the connection is in a clean execution status. def verify_clean_exec_status @conn.send_query( "VALUES (1)" ) @conn.get_last_result.values.should == [["1"]] end end RSpec.configure do |config| ruby_version_vec = RUBY_VERSION.split('.').map {|c| c.to_i }.pack( "N*" ) config.include( PG::TestingHelpers ) config.treat_symbols_as_metadata_keys_with_true_values = true config.mock_with :rspec config.filter_run_excluding :ruby_19 if ruby_version_vec <= [1,9,1].pack( "N*" ) if RUBY_PLATFORM =~ /mingw|mswin/ config.filter_run_excluding :unix else config.filter_run_excluding :windows end config.filter_run_excluding :socket_io unless PG::Connection.instance_methods.map( &:to_sym ).include?( :socket_io ) config.filter_run_excluding :postgresql_90 unless PG::Connection.instance_methods.map( &:to_sym ).include?( :escape_literal ) if !PG.respond_to?( :library_version ) config.filter_run_excluding( :postgresql_91, :postgresql_92, :postgresql_93 ) elsif PG.library_version < 90200 config.filter_run_excluding( :postgresql_92, :postgresql_93 ) elsif PG.library_version < 90300 config.filter_run_excluding( :postgresql_93 ) end end ruby-pg-0.17.0/spec/pg/000077500000000000000000000000001222421776500145345ustar00rootroot00000000000000ruby-pg-0.17.0/spec/pg/connection_spec.rb000077500000000000000000001044611222421776500202430ustar00rootroot00000000000000#!/usr/bin/env rspec #encoding: utf-8 BEGIN { require 'pathname' basedir = Pathname( __FILE__ ).dirname.parent.parent libdir = basedir + 'lib' $LOAD_PATH.unshift( basedir.to_s ) unless $LOAD_PATH.include?( basedir.to_s ) $LOAD_PATH.unshift( libdir.to_s ) unless $LOAD_PATH.include?( libdir.to_s ) } require 'rspec' require 'spec/lib/helpers' require 'timeout' require 'socket' require 'pg' describe PG::Connection do before( :all ) do @conn = setup_testing_db( described_class.name ) end before( :each ) do @conn.exec( 'BEGIN' ) unless example.metadata[:without_transaction] if PG.respond_to?( :library_version ) @conn.exec_params %Q{SET application_name TO '%s'} % [@conn.escape_string(example.description[0,60])] end end after( :each ) do @conn.exec( 'ROLLBACK' ) unless example.metadata[:without_transaction] end after( :all ) do teardown_testing_db( @conn ) end # # Examples # it "can create a connection option string from a Hash of options" do optstring = described_class.parse_connect_args( :host => 'pgsql.example.com', :dbname => 'db01', 'sslmode' => 'require' ) optstring.should be_a( String ) optstring.should =~ /(^|\s)host='pgsql.example.com'/ optstring.should =~ /(^|\s)dbname='db01'/ optstring.should =~ /(^|\s)sslmode='require'/ end it "can create a connection option string from positional parameters" do optstring = described_class.parse_connect_args( 'pgsql.example.com', nil, '-c geqo=off', nil, 'sales' ) optstring.should be_a( String ) optstring.should =~ /(^|\s)host='pgsql.example.com'/ optstring.should =~ /(^|\s)dbname='sales'/ optstring.should =~ /(^|\s)options='-c geqo=off'/ optstring.should_not =~ /port=/ optstring.should_not =~ /tty=/ end it "can create a connection option string from a mix of positional and hash parameters" do optstring = described_class.parse_connect_args( 'pgsql.example.com', :dbname => 'licensing', :user => 'jrandom' ) optstring.should be_a( String ) optstring.should =~ /(^|\s)host='pgsql.example.com'/ optstring.should =~ /(^|\s)dbname='licensing'/ optstring.should =~ /(^|\s)user='jrandom'/ end it "escapes single quotes and backslashes in connection parameters" do described_class.parse_connect_args( "DB 'browser' \\" ). should =~ /host='DB \\'browser\\' \\\\'/ end it "connects with defaults if no connection parameters are given" do described_class.parse_connect_args.should == '' end it "connects successfully with connection string" do tmpconn = described_class.connect(@conninfo) tmpconn.status.should == PG::CONNECTION_OK tmpconn.finish end it "connects using 7 arguments converted to strings" do tmpconn = described_class.connect('localhost', @port, nil, nil, :test, nil, nil) tmpconn.status.should == PG::CONNECTION_OK tmpconn.finish end it "connects using a hash of connection parameters" do tmpconn = described_class.connect( :host => 'localhost', :port => @port, :dbname => :test) tmpconn.status.should == PG::CONNECTION_OK tmpconn.finish end it "connects using a hash of optional connection parameters", :postgresql_90 do tmpconn = described_class.connect( :host => 'localhost', :port => @port, :dbname => :test, :keepalives => 1) tmpconn.status.should == PG::CONNECTION_OK tmpconn.finish end it "raises an exception when connecting with an invalid number of arguments" do expect { described_class.connect( 1, 2, 3, 4, 5, 6, 7, 'extra' ) }.to raise_error( ArgumentError, /extra positional parameter/i ) end it "can connect asynchronously", :socket_io do tmpconn = described_class.connect_start( @conninfo ) tmpconn.should be_a( described_class ) socket = tmpconn.socket_io status = tmpconn.connect_poll while status != PG::PGRES_POLLING_OK if status == PG::PGRES_POLLING_READING select( [socket], [], [], 5.0 ) or raise "Asynchronous connection timed out!" elsif status == PG::PGRES_POLLING_WRITING select( [], [socket], [], 5.0 ) or raise "Asynchronous connection timed out!" end status = tmpconn.connect_poll end tmpconn.status.should == PG::CONNECTION_OK tmpconn.finish end it "can connect asynchronously for the duration of a block", :socket_io do conn = nil described_class.connect_start(@conninfo) do |tmpconn| tmpconn.should be_a( described_class ) conn = tmpconn socket = tmpconn.socket_io status = tmpconn.connect_poll while status != PG::PGRES_POLLING_OK if status == PG::PGRES_POLLING_READING if(not select([socket],[],[],5.0)) raise "Asynchronous connection timed out!" end elsif(status == PG::PGRES_POLLING_WRITING) if(not select([],[socket],[],5.0)) raise "Asynchronous connection timed out!" end end status = tmpconn.connect_poll end tmpconn.status.should == PG::CONNECTION_OK end conn.should be_finished() end it "raises proper error when sending fails" do conn = described_class.connect_start( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" ) expect{ conn.exec 'SELECT 1' }.to raise_error(PG::UnableToSend, /no connection/) end it "doesn't leave stale server connections after finish" do described_class.connect(@conninfo).finish sleep 0.5 res = @conn.exec(%[SELECT COUNT(*) AS n FROM pg_stat_activity WHERE usename IS NOT NULL]) # there's still the global @conn, but should be no more res[0]['n'].should == '1' end EXPECTED_TRACE_OUTPUT = %{ To backend> Msg Q To backend> "SELECT 1 AS one" To backend> Msg complete, length 21 From backend> T From backend (#4)> 28 From backend (#2)> 1 From backend> "one" From backend (#4)> 0 From backend (#2)> 0 From backend (#4)> 23 From backend (#2)> 4 From backend (#4)> -1 From backend (#2)> 0 From backend> D From backend (#4)> 11 From backend (#2)> 1 From backend (#4)> 1 From backend (1)> 1 From backend> C From backend (#4)> 13 From backend> "SELECT 1" From backend> Z From backend (#4)> 5 From backend> Z From backend (#4)> 5 From backend> T }.gsub( /^\t{2}/, '' ).lstrip it "trace and untrace client-server communication", :unix do # be careful to explicitly close files so that the # directory can be removed and we don't have to wait for # the GC to run. trace_file = TEST_DIRECTORY + "test_trace.out" trace_io = trace_file.open( 'w', 0600 ) @conn.trace( trace_io ) trace_io.close res = @conn.exec("SELECT 1 AS one") @conn.untrace res = @conn.exec("SELECT 2 AS two") trace_data = trace_file.read expected_trace_output = EXPECTED_TRACE_OUTPUT.dup # For PostgreSQL < 9.0, the output will be different: # -From backend (#4)> 13 # -From backend> "SELECT 1" # +From backend (#4)> 11 # +From backend> "SELECT" if @conn.server_version < 90000 expected_trace_output.sub!( /From backend \(#4\)> 13/, 'From backend (#4)> 11' ) expected_trace_output.sub!( /From backend> "SELECT 1"/, 'From backend> "SELECT"' ) end trace_data.should == expected_trace_output end it "allows a query to be cancelled" do error = false @conn.send_query("SELECT pg_sleep(1000)") @conn.cancel tmpres = @conn.get_result if(tmpres.result_status != PG::PGRES_TUPLES_OK) error = true end error.should == true end it "can stop a thread that runs a blocking query" do start = Time.now t = Thread.new do @conn.async_exec( 'select pg_sleep(10)' ) end sleep 0.1 t.kill t.join (Time.now - start).should < 10 end it "automatically rolls back a transaction started with Connection#transaction if an exception " + "is raised" do # abort the per-example transaction so we can test our own @conn.exec( 'ROLLBACK' ) res = nil @conn.exec( "CREATE TABLE pie ( flavor TEXT )" ) expect { res = @conn.transaction do @conn.exec( "INSERT INTO pie VALUES ('rhubarb'), ('cherry'), ('schizophrenia')" ) raise "Oh noes! All pie is gone!" end }.to raise_exception( RuntimeError, /all pie is gone/i ) res = @conn.exec( "SELECT * FROM pie" ) res.ntuples.should == 0 end it "returns the block result from Connection#transaction" do # abort the per-example transaction so we can test our own @conn.exec( 'ROLLBACK' ) res = @conn.transaction do "transaction result" end res.should == "transaction result" end it "not read past the end of a large object" do @conn.transaction do oid = @conn.lo_create( 0 ) fd = @conn.lo_open( oid, PG::INV_READ|PG::INV_WRITE ) @conn.lo_write( fd, "foobar" ) @conn.lo_read( fd, 10 ).should be_nil() @conn.lo_lseek( fd, 0, PG::SEEK_SET ) @conn.lo_read( fd, 10 ).should == 'foobar' end end it "supports parameters passed to #exec (backward compatibility)" do @conn.exec( "CREATE TABLE students ( name TEXT, age INTEGER )" ) @conn.exec( "INSERT INTO students VALUES( $1, $2 )", ['Wally', 8] ) @conn.exec( "INSERT INTO students VALUES( $1, $2 )", ['Sally', 6] ) @conn.exec( "INSERT INTO students VALUES( $1, $2 )", ['Dorothy', 4] ) res = @conn.exec( "SELECT name FROM students WHERE age >= $1", [6] ) res.values.should == [ ['Wally'], ['Sally'] ] end it "supports explicitly calling #exec_params" do @conn.exec( "CREATE TABLE students ( name TEXT, age INTEGER )" ) @conn.exec( "INSERT INTO students VALUES( $1, $2 )", ['Wally', 8] ) @conn.exec( "INSERT INTO students VALUES( $1, $2 )", ['Sally', 6] ) @conn.exec( "INSERT INTO students VALUES( $1, $2 )", ['Dorothy', 4] ) res = @conn.exec_params( "SELECT name FROM students WHERE age >= $1", [6] ) res.values.should == [ ['Wally'], ['Sally'] ] end it "can wait for NOTIFY events" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN woo' ) t = Thread.new do begin conn = described_class.connect( @conninfo ) sleep 1 conn.async_exec( 'NOTIFY woo' ) ensure conn.finish end end @conn.wait_for_notify( 10 ).should == 'woo' @conn.exec( 'UNLISTEN woo' ) t.join end it "calls a block for NOTIFY events if one is given" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN woo' ) t = Thread.new do begin conn = described_class.connect( @conninfo ) sleep 1 conn.async_exec( 'NOTIFY woo' ) ensure conn.finish end end eventpid = event = nil @conn.wait_for_notify( 10 ) {|*args| event, eventpid = args } event.should == 'woo' eventpid.should be_an( Integer ) @conn.exec( 'UNLISTEN woo' ) t.join end it "doesn't collapse sequential notifications" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN woo' ) @conn.exec( 'LISTEN war' ) @conn.exec( 'LISTEN woz' ) begin conn = described_class.connect( @conninfo ) conn.exec( 'NOTIFY woo' ) conn.exec( 'NOTIFY war' ) conn.exec( 'NOTIFY woz' ) ensure conn.finish end channels = [] 3.times do channels << @conn.wait_for_notify( 2 ) end channels.should have( 3 ).members channels.should include( 'woo', 'war', 'woz' ) @conn.exec( 'UNLISTEN woz' ) @conn.exec( 'UNLISTEN war' ) @conn.exec( 'UNLISTEN woo' ) end it "returns notifications which are already in the queue before wait_for_notify is called " + "without waiting for the socket to become readable" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN woo' ) begin conn = described_class.connect( @conninfo ) conn.exec( 'NOTIFY woo' ) ensure conn.finish end # Cause the notification to buffer, but not be read yet @conn.exec( 'SELECT 1' ) @conn.wait_for_notify( 10 ).should == 'woo' @conn.exec( 'UNLISTEN woo' ) end it "can receive notices while waiting for NOTIFY without exceeding the timeout", :postgresql_90 do notices = [] @conn.set_notice_processor do |msg| notices << [msg, Time.now] end st = Time.now @conn.send_query "SELECT pg_sleep(0.5); do $$ BEGIN RAISE NOTICE 'woohoo'; END; $$ LANGUAGE plpgsql;" @conn.wait_for_notify( 1 ).should be_nil notices.first.should_not be_nil et = Time.now (et - notices.first[1]).should >= 0.4 (et - st).should >= 0.9 (et - st).should < 1.4 end it "yields the result if block is given to exec" do rval = @conn.exec( "select 1234::int as a union select 5678::int as a" ) do |result| values = [] result.should be_kind_of( PG::Result ) result.ntuples.should == 2 result.each do |tuple| values << tuple['a'] end values end rval.should have( 2 ).members rval.should include( '5678', '1234' ) end it "can process #copy_data output queries" do rows = [] res2 = @conn.copy_data( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) do |res| res.result_status.should == PG::PGRES_COPY_OUT res.nfields.should == 1 while row=@conn.get_copy_data rows << row end end rows.should == ["1\n", "2\n"] res2.result_status.should == PG::PGRES_COMMAND_OK verify_clean_exec_status end it "can handle incomplete #copy_data output queries" do expect { @conn.copy_data( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) do |res| @conn.get_copy_data end }.to raise_error(PG::NotAllCopyDataRetrieved, /Not all/) verify_clean_exec_status end it "can handle client errors in #copy_data for output" do expect { @conn.copy_data( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) do raise "boom" end }.to raise_error(RuntimeError, "boom") verify_clean_exec_status end it "can handle server errors in #copy_data for output" do @conn.exec "ROLLBACK" @conn.transaction do @conn.exec( "CREATE FUNCTION errfunc() RETURNS int AS $$ BEGIN RAISE 'test-error'; END; $$ LANGUAGE plpgsql;" ) expect { @conn.copy_data( "COPY (SELECT errfunc()) TO STDOUT" ) do |res| while @conn.get_copy_data end end }.to raise_error(PG::Error, /test-error/) end verify_clean_exec_status end it "can process #copy_data input queries" do @conn.exec( "CREATE TEMP TABLE copytable (col1 TEXT)" ) res2 = @conn.copy_data( "COPY copytable FROM STDOUT" ) do |res| res.result_status.should == PG::PGRES_COPY_IN res.nfields.should == 1 @conn.put_copy_data "1\n" @conn.put_copy_data "2\n" end res2.result_status.should == PG::PGRES_COMMAND_OK verify_clean_exec_status res = @conn.exec( "SELECT * FROM copytable ORDER BY col1" ) res.values.should == [["1"], ["2"]] end it "can handle client errors in #copy_data for input" do @conn.exec "ROLLBACK" @conn.transaction do @conn.exec( "CREATE TEMP TABLE copytable (col1 TEXT)" ) expect { @conn.copy_data( "COPY copytable FROM STDOUT" ) do |res| raise "boom" end }.to raise_error(RuntimeError, "boom") end verify_clean_exec_status end it "can handle server errors in #copy_data for input" do @conn.exec "ROLLBACK" @conn.transaction do @conn.exec( "CREATE TEMP TABLE copytable (col1 INT)" ) expect { @conn.copy_data( "COPY copytable FROM STDOUT" ) do |res| @conn.put_copy_data "xyz\n" end }.to raise_error(PG::Error, /invalid input syntax for integer/) end verify_clean_exec_status end it "should raise an error for non copy statements in #copy_data" do expect { @conn.copy_data( "SELECT 1" ){} }.to raise_error(ArgumentError, /no COPY/) verify_clean_exec_status end it "correctly finishes COPY queries passed to #async_exec" do @conn.async_exec( "COPY (SELECT 1 UNION ALL SELECT 2) TO STDOUT" ) results = [] begin data = @conn.get_copy_data( true ) if false == data @conn.block( 2.0 ) data = @conn.get_copy_data( true ) end results << data if data end until data.nil? results.should have( 2 ).members results.should include( "1\n", "2\n" ) end it "described_class#block shouldn't block a second thread" do start = Time.now t = Thread.new do @conn.send_query( "select pg_sleep(3)" ) @conn.block end sleep 0.5 t.should be_alive() @conn.cancel t.join (Time.now - start).should < 3 end it "described_class#block should allow a timeout" do @conn.send_query( "select pg_sleep(3)" ) start = Time.now @conn.block( 0.1 ) finish = Time.now (finish - start).should be_within( 0.05 ).of( 0.1 ) end it "can encrypt a string given a password and username" do described_class.encrypt_password("postgres", "postgres"). should =~ /\S+/ end it "raises an appropriate error if either of the required arguments for encrypt_password " + "is not valid" do expect { described_class.encrypt_password( nil, nil ) }.to raise_error( TypeError ) expect { described_class.encrypt_password( "postgres", nil ) }.to raise_error( TypeError ) expect { described_class.encrypt_password( nil, "postgres" ) }.to raise_error( TypeError ) end it "allows fetching a column of values from a result by column number" do res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' ) res.column_values( 0 ).should == %w[1 2 3] res.column_values( 1 ).should == %w[2 3 4] end it "allows fetching a column of values from a result by field name" do res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' ) res.field_values( 'column1' ).should == %w[1 2 3] res.field_values( 'column2' ).should == %w[2 3 4] end it "raises an error if selecting an invalid column index" do res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' ) expect { res.column_values( 20 ) }.to raise_error( IndexError ) end it "raises an error if selecting an invalid field name" do res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' ) expect { res.field_values( 'hUUuurrg' ) }.to raise_error( IndexError ) end it "raises an error if column index is not a number" do res = @conn.exec( 'VALUES (1,2),(2,3),(3,4)' ) expect { res.column_values( 'hUUuurrg' ) }.to raise_error( TypeError ) end it "can connect asynchronously", :socket_io do serv = TCPServer.new( '127.0.0.1', 54320 ) conn = described_class.connect_start( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" ) [PG::PGRES_POLLING_WRITING, PG::CONNECTION_OK].should include conn.connect_poll select( nil, [conn.socket_io], nil, 0.2 ) serv.close if conn.connect_poll == PG::PGRES_POLLING_READING select( [conn.socket_io], nil, nil, 0.2 ) end conn.connect_poll.should == PG::PGRES_POLLING_FAILED end it "discards previous results (if any) before waiting on an #async_exec" it "calls the block if one is provided to #async_exec" do result = nil @conn.async_exec( "select 47 as one" ) do |pg_res| result = pg_res[0] end result.should == { 'one' => '47' } end it "raises a rescue-able error if #finish is called twice", :without_transaction do conn = PG.connect( @conninfo ) conn.finish expect { conn.finish }.to raise_error( PG::ConnectionBad, /connection is closed/i ) end it "closes the IO fetched from #socket_io when the connection is closed", :without_transaction, :socket_io do conn = PG.connect( @conninfo ) io = conn.socket_io conn.finish io.should be_closed() expect { conn.socket_io }.to raise_error( PG::ConnectionBad, /connection is closed/i ) end it "closes the IO fetched from #socket_io when the connection is reset", :without_transaction, :socket_io do conn = PG.connect( @conninfo ) io = conn.socket_io conn.reset io.should be_closed() conn.socket_io.should_not equal( io ) conn.finish end it "block should raise ConnectionBad for a closed connection" do serv = TCPServer.new( '127.0.0.1', 54320 ) conn = described_class.connect_start( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" ) while [PG::CONNECTION_STARTED, PG::CONNECTION_MADE].include?(conn.connect_poll) sleep 0.1 end serv.close expect{ conn.block }.to raise_error(PG::ConnectionBad, /server closed the connection unexpectedly/) expect{ conn.block }.to raise_error(PG::ConnectionBad, /can't get socket descriptor/) end context "under PostgreSQL 9", :postgresql_90 do before( :each ) do pending "only works with a PostgreSQL >= 9.0 server" if @conn.server_version < 9_00_00 end it "sets the fallback_application_name on new connections" do conn_string = PG::Connection.parse_connect_args( 'dbname=test' ) connection_string_should_contain_application_name(conn_string, $0) end it "sets a shortened fallback_application_name on new connections" do old_0 = $0 begin $0 = "/this/is/a/very/long/path/with/many/directories/to/our/beloved/ruby" conn_string = PG::Connection.parse_connect_args( 'dbname=test' ) connection_string_should_contain_application_name(conn_string, $0) ensure $0 = old_0 end end it "calls the block supplied to wait_for_notify with the notify payload if it accepts " + "any number of arguments" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN knees' ) conn = described_class.connect( @conninfo ) conn.exec( %Q{NOTIFY knees, 'skirt and boots'} ) conn.finish event, pid, msg = nil @conn.wait_for_notify( 10 ) do |*args| event, pid, msg = *args end @conn.exec( 'UNLISTEN knees' ) event.should == 'knees' pid.should be_a_kind_of( Integer ) msg.should == 'skirt and boots' end it "accepts nil as the timeout in #wait_for_notify " do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN knees' ) conn = described_class.connect( @conninfo ) conn.exec( %Q{NOTIFY knees} ) conn.finish event, pid = nil @conn.wait_for_notify( nil ) do |*args| event, pid = *args end @conn.exec( 'UNLISTEN knees' ) event.should == 'knees' pid.should be_a_kind_of( Integer ) end it "sends nil as the payload if the notification wasn't given one" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN knees' ) conn = described_class.connect( @conninfo ) conn.exec( %Q{NOTIFY knees} ) conn.finish payload = :notnil @conn.wait_for_notify( nil ) do |*args| payload = args[ 2 ] end @conn.exec( 'UNLISTEN knees' ) payload.should be_nil() end it "calls the block supplied to wait_for_notify with the notify payload if it accepts " + "two arguments" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN knees' ) conn = described_class.connect( @conninfo ) conn.exec( %Q{NOTIFY knees, 'skirt and boots'} ) conn.finish event, pid, msg = nil @conn.wait_for_notify( 10 ) do |arg1, arg2| event, pid, msg = arg1, arg2 end @conn.exec( 'UNLISTEN knees' ) event.should == 'knees' pid.should be_a_kind_of( Integer ) msg.should be_nil() end it "calls the block supplied to wait_for_notify with the notify payload if it " + "doesn't accept arguments" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN knees' ) conn = described_class.connect( @conninfo ) conn.exec( %Q{NOTIFY knees, 'skirt and boots'} ) conn.finish notification_received = false @conn.wait_for_notify( 10 ) do notification_received = true end @conn.exec( 'UNLISTEN knees' ) notification_received.should be_true() end it "calls the block supplied to wait_for_notify with the notify payload if it accepts " + "three arguments" do @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN knees' ) conn = described_class.connect( @conninfo ) conn.exec( %Q{NOTIFY knees, 'skirt and boots'} ) conn.finish event, pid, msg = nil @conn.wait_for_notify( 10 ) do |arg1, arg2, arg3| event, pid, msg = arg1, arg2, arg3 end @conn.exec( 'UNLISTEN knees' ) event.should == 'knees' pid.should be_a_kind_of( Integer ) msg.should == 'skirt and boots' end end context "under PostgreSQL 9.1 client library", :postgresql_91, :without_transaction do it "pings successfully with connection string" do ping = described_class.ping(@conninfo) ping.should == PG::PQPING_OK end it "pings using 7 arguments converted to strings" do ping = described_class.ping('localhost', @port, nil, nil, :test, nil, nil) ping.should == PG::PQPING_OK end it "pings using a hash of connection parameters" do ping = described_class.ping( :host => 'localhost', :port => @port, :dbname => :test) ping.should == PG::PQPING_OK end it "returns correct response when ping connection cannot be established" do ping = described_class.ping( :host => 'localhost', :port => 9999, :dbname => :test) ping.should == PG::PQPING_NO_RESPONSE end it "returns correct response when ping connection arguments are wrong" do ping = described_class.ping('localhost', 'localhost', nil, nil, :test, nil, nil) ping.should == PG::PQPING_NO_ATTEMPT end end context "under PostgreSQL 9.2 client library", :postgresql_92 do describe "set_single_row_mode" do it "raises an error when called at the wrong time" do expect { @conn.set_single_row_mode }.to raise_error(PG::Error) end it "should work in single row mode" do @conn.send_query( "SELECT generate_series(1,10)" ) @conn.set_single_row_mode results = [] loop do @conn.block res = @conn.get_result or break results << res end results.length.should == 11 results[0..-2].each do |res| res.result_status.should == PG::PGRES_SINGLE_TUPLE values = res.field_values('generate_series') values.length.should == 1 values.first.to_i.should > 0 end results.last.result_status.should == PG::PGRES_TUPLES_OK results.last.ntuples.should == 0 end it "should receive rows before entire query is finished" do @conn.send_query( "SELECT generate_series(0,999), NULL UNION ALL SELECT 1000, pg_sleep(1);" ) @conn.set_single_row_mode start_time = Time.now first_row_time = nil loop do res = @conn.get_result or break res.check first_row_time = Time.now unless first_row_time end (Time.now - start_time).should >= 1.0 (first_row_time - start_time).should < 1.0 end it "should receive rows before entire query fails" do @conn.exec( "CREATE FUNCTION errfunc() RETURNS int AS $$ BEGIN RAISE 'test-error'; END; $$ LANGUAGE plpgsql;" ) @conn.send_query( "SELECT generate_series(0,999), NULL UNION ALL SELECT 1000, errfunc();" ) @conn.set_single_row_mode first_result = nil expect do loop do res = @conn.get_result or break res.check first_result ||= res end end.to raise_error(PG::Error) first_result.kind_of?(PG::Result).should be_true first_result.result_status.should == PG::PGRES_SINGLE_TUPLE end end end context "multinationalization support", :ruby_19 do describe "rubyforge #22925: m17n support" do it "should return results in the same encoding as the client (iso-8859-1)" do out_string = nil @conn.transaction do |conn| conn.internal_encoding = 'iso8859-1' res = conn.exec("VALUES ('fantasia')", [], 0) out_string = res[0]['column1'] end out_string.should == 'fantasia' out_string.encoding.should == Encoding::ISO8859_1 end it "should return results in the same encoding as the client (utf-8)" do out_string = nil @conn.transaction do |conn| conn.internal_encoding = 'utf-8' res = conn.exec("VALUES ('世界線航跡蔵')", [], 0) out_string = res[0]['column1'] end out_string.should == '世界線航跡蔵' out_string.encoding.should == Encoding::UTF_8 end it "should return results in the same encoding as the client (EUC-JP)" do out_string = nil @conn.transaction do |conn| conn.internal_encoding = 'EUC-JP' stmt = "VALUES ('世界線航跡蔵')".encode('EUC-JP') res = conn.exec(stmt, [], 0) out_string = res[0]['column1'] end out_string.should == '世界線航跡蔵'.encode('EUC-JP') out_string.encoding.should == Encoding::EUC_JP end it "returns the results in the correct encoding even if the client_encoding has " + "changed since the results were fetched" do out_string = nil @conn.transaction do |conn| conn.internal_encoding = 'EUC-JP' stmt = "VALUES ('世界線航跡蔵')".encode('EUC-JP') res = conn.exec(stmt, [], 0) conn.internal_encoding = 'utf-8' out_string = res[0]['column1'] end out_string.should == '世界線航跡蔵'.encode('EUC-JP') out_string.encoding.should == Encoding::EUC_JP end it "the connection should return ASCII-8BIT when it's set to SQL_ASCII" do @conn.exec "SET client_encoding TO SQL_ASCII" @conn.internal_encoding.should == Encoding::ASCII_8BIT end it "works around the unsupported JOHAB encoding by returning stuff in 'ASCII_8BIT'" do pending "figuring out how to create a string in the JOHAB encoding" do out_string = nil @conn.transaction do |conn| conn.exec( "set client_encoding = 'JOHAB';" ) stmt = "VALUES ('foo')".encode('JOHAB') res = conn.exec( stmt, [], 0 ) out_string = res[0]['column1'] end out_string.should == 'foo'.encode( Encoding::ASCII_8BIT ) out_string.encoding.should == Encoding::ASCII_8BIT end end it "uses the client encoding for escaped string" do original = "string to\0 escape".force_encoding( "iso8859-1" ) @conn.set_client_encoding( "euc_jp" ) escaped = @conn.escape( original ) escaped.encoding.should == Encoding::EUC_JP escaped.should == "string to" end it "uses the client encoding for escaped literal", :postgresql_90 do original = "string to\0 escape".force_encoding( "iso8859-1" ) @conn.set_client_encoding( "euc_jp" ) escaped = @conn.escape_literal( original ) escaped.encoding.should == Encoding::EUC_JP escaped.should == "'string to'" end it "uses the client encoding for escaped identifier", :postgresql_90 do original = "string to\0 escape".force_encoding( "iso8859-1" ) @conn.set_client_encoding( "euc_jp" ) escaped = @conn.escape_identifier( original ) escaped.encoding.should == Encoding::EUC_JP escaped.should == "\"string to\"" end it "uses the client encoding for quote_ident" do original = "string to\0 escape".force_encoding( "iso8859-1" ) @conn.set_client_encoding( "euc_jp" ) escaped = @conn.quote_ident( original ) escaped.encoding.should == Encoding::EUC_JP escaped.should == "\"string to\"" end it "uses the previous string encoding for escaped string" do original = "string to\0 escape".force_encoding( "iso8859-1" ) @conn.set_client_encoding( "euc_jp" ) escaped = described_class.escape( original ) escaped.encoding.should == Encoding::ISO8859_1 escaped.should == "string to" end it "uses the previous string encoding for quote_ident" do original = "string to\0 escape".force_encoding( "iso8859-1" ) @conn.set_client_encoding( "euc_jp" ) escaped = described_class.quote_ident( original ) escaped.encoding.should == Encoding::ISO8859_1 escaped.should == "\"string to\"" end end describe "Ruby 1.9.x default_internal encoding" do it "honors the Encoding.default_internal if it's set and the synchronous interface is used" do @conn.transaction do |txn_conn| txn_conn.internal_encoding = Encoding::ISO8859_1 txn_conn.exec( "CREATE TABLE defaultinternaltest ( foo text )" ) txn_conn.exec( "INSERT INTO defaultinternaltest VALUES ('Grün und Weiß')" ) end begin prev_encoding = Encoding.default_internal Encoding.default_internal = Encoding::UTF_8 conn = PG.connect( @conninfo ) conn.internal_encoding.should == Encoding::UTF_8 res = conn.exec( "SELECT foo FROM defaultinternaltest" ) res[0]['foo'].encoding.should == Encoding::UTF_8 ensure conn.finish if conn Encoding.default_internal = prev_encoding end end it "allows users of the async interface to set the client_encoding to the default_internal" do begin prev_encoding = Encoding.default_internal Encoding.default_internal = Encoding::KOI8_R @conn.set_default_encoding @conn.internal_encoding.should == Encoding::KOI8_R ensure Encoding.default_internal = prev_encoding end end end it "encodes exception messages with the connection's encoding (#96)", :without_transaction do # Use a new connection so the client_encoding isn't set outside of this example conn = PG.connect( @conninfo ) conn.client_encoding = 'iso-8859-15' conn.transaction do conn.exec "CREATE TABLE foo (bar TEXT)" begin query = "INSERT INTO foo VALUES ('Côte d'Ivoire')".encode( 'iso-8859-15' ) conn.exec( query ) rescue => err err.message.encoding.should == Encoding::ISO8859_15 else fail "No exception raised?!" end end conn.finish if conn end it "receives properly encoded messages in the notice callbacks", :postgresql_90 do [:receiver, :processor].each do |kind| notices = [] @conn.internal_encoding = 'utf-8' if kind == :processor @conn.set_notice_processor do |msg| notices << msg end else @conn.set_notice_receiver do |result| notices << result.error_message end end 3.times do @conn.exec "do $$ BEGIN RAISE NOTICE '世界線航跡蔵'; END; $$ LANGUAGE plpgsql;" end notices.length.should == 3 notices.each do |notice| notice.should =~ /^NOTICE:.*世界線航跡蔵/ notice.encoding.should == Encoding::UTF_8 end @conn.set_notice_receiver @conn.set_notice_processor end end it "receives properly encoded text from wait_for_notify", :postgresql_90 do @conn.internal_encoding = 'utf-8' @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN "Möhre"' ) @conn.exec( %Q{NOTIFY "Möhre", '世界線航跡蔵'} ) event, pid, msg = nil @conn.wait_for_notify( 10 ) do |*args| event, pid, msg = *args end @conn.exec( 'UNLISTEN "Möhre"' ) event.should == "Möhre" event.encoding.should == Encoding::UTF_8 msg.should == '世界線航跡蔵' msg.encoding.should == Encoding::UTF_8 end it "returns properly encoded text from notifies", :postgresql_90 do @conn.internal_encoding = 'utf-8' @conn.exec( 'ROLLBACK' ) @conn.exec( 'LISTEN "Möhre"' ) @conn.exec( %Q{NOTIFY "Möhre", '世界線航跡蔵'} ) @conn.exec( 'UNLISTEN "Möhre"' ) notification = @conn.notifies notification[:relname].should == "Möhre" notification[:relname].encoding.should == Encoding::UTF_8 notification[:extra].should == '世界線航跡蔵' notification[:extra].encoding.should == Encoding::UTF_8 notification[:be_pid].should > 0 end end context "OS thread support", :ruby_19 do it "Connection#exec shouldn't block a second thread" do t = Thread.new do @conn.exec( "select pg_sleep(1)" ) end sleep 0.5 t.should be_alive() t.join end it "Connection.new shouldn't block a second thread" do serv = nil t = Thread.new do serv = TCPServer.new( '127.0.0.1', 54320 ) expect { described_class.new( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" ) }.to raise_error(PG::ConnectionBad, /server closed the connection unexpectedly/) end sleep 0.5 t.should be_alive() serv.close t.join end end end ruby-pg-0.17.0/spec/pg/result_spec.rb000066400000000000000000000275141222421776500174220ustar00rootroot00000000000000#!/usr/bin/env rspec # encoding: utf-8 BEGIN { require 'pathname' basedir = Pathname( __FILE__ ).dirname.parent.parent libdir = basedir + 'lib' $LOAD_PATH.unshift( basedir.to_s ) unless $LOAD_PATH.include?( basedir.to_s ) $LOAD_PATH.unshift( libdir.to_s ) unless $LOAD_PATH.include?( libdir.to_s ) } require 'rspec' require 'spec/lib/helpers' require 'pg' describe PG::Result do before( :all ) do @conn = setup_testing_db( "PG_Result" ) end before( :each ) do @conn.exec( 'BEGIN' ) end after( :each ) do @conn.exec( 'ROLLBACK' ) end after( :all ) do teardown_testing_db( @conn ) end # # Examples # it "should act as an array of hashes" do res = @conn.exec("SELECT 1 AS a, 2 AS b") res[0]['a'].should== '1' res[0]['b'].should== '2' end it "should yield a row as an array" do res = @conn.exec("SELECT 1 AS a, 2 AS b") list = [] res.each_row { |r| list << r } list.should eq [['1', '2']] end it "should insert nil AS NULL and return NULL as nil" do res = @conn.exec("SELECT $1::int AS n", [nil]) res[0]['n'].should be_nil() end it "encapsulates errors in a PGError object" do exception = nil begin @conn.exec( "SELECT * FROM nonexistant_table" ) rescue PGError => err exception = err end result = exception.result result.should be_a( described_class() ) result.error_field( PG::PG_DIAG_SEVERITY ).should == 'ERROR' result.error_field( PG::PG_DIAG_SQLSTATE ).should == '42P01' result.error_field( PG::PG_DIAG_MESSAGE_PRIMARY ). should == 'relation "nonexistant_table" does not exist' result.error_field( PG::PG_DIAG_MESSAGE_DETAIL ).should be_nil() result.error_field( PG::PG_DIAG_MESSAGE_HINT ).should be_nil() result.error_field( PG::PG_DIAG_STATEMENT_POSITION ).should == '15' result.error_field( PG::PG_DIAG_INTERNAL_POSITION ).should be_nil() result.error_field( PG::PG_DIAG_INTERNAL_QUERY ).should be_nil() result.error_field( PG::PG_DIAG_CONTEXT ).should be_nil() result.error_field( PG::PG_DIAG_SOURCE_FILE ).should =~ /parse_relation\.c$|namespace\.c$/ result.error_field( PG::PG_DIAG_SOURCE_LINE ).should =~ /^\d+$/ result.error_field( PG::PG_DIAG_SOURCE_FUNCTION ).should =~ /^parserOpenTable$|^RangeVarGetRelid$/ end it "encapsulates database object names for integrity constraint violations", :postgresql_93 do @conn.exec( "CREATE TABLE integrity (id SERIAL PRIMARY KEY)" ) exception = nil begin @conn.exec( "INSERT INTO integrity VALUES (NULL)" ) rescue PGError => err exception = err end result = exception.result result.error_field( PG::PG_DIAG_SCHEMA_NAME ).should == 'public' result.error_field( PG::PG_DIAG_TABLE_NAME ).should == 'integrity' result.error_field( PG::PG_DIAG_COLUMN_NAME ).should == 'id' result.error_field( PG::PG_DIAG_DATATYPE_NAME ).should be_nil result.error_field( PG::PG_DIAG_CONSTRAINT_NAME ).should be_nil end it "should detect division by zero as SQLSTATE 22012" do sqlstate = nil begin res = @conn.exec("SELECT 1/0") rescue PGError => e sqlstate = e.result.result_error_field( PG::PG_DIAG_SQLSTATE ).to_i end sqlstate.should == 22012 end it "should return the same bytes in binary format that are sent in binary format" do binary_file = File.join(Dir.pwd, 'spec/data', 'random_binary_data') bytes = File.open(binary_file, 'rb').read res = @conn.exec('VALUES ($1::bytea)', [ { :value => bytes, :format => 1 } ], 1) res[0]['column1'].should== bytes res.getvalue(0,0).should == bytes res.values[0][0].should == bytes res.column_values(0)[0].should == bytes end it "should return the same bytes in binary format that are sent as inline text" do binary_file = File.join(Dir.pwd, 'spec/data', 'random_binary_data') bytes = File.open(binary_file, 'rb').read @conn.exec("SET standard_conforming_strings=on") res = @conn.exec("VALUES ('#{PG::Connection.escape_bytea(bytes)}'::bytea)", [], 1) res[0]['column1'].should == bytes res.getvalue(0,0).should == bytes res.values[0][0].should == bytes res.column_values(0)[0].should == bytes end it "should return the same bytes in text format that are sent in binary format" do binary_file = File.join(Dir.pwd, 'spec/data', 'random_binary_data') bytes = File.open(binary_file, 'rb').read res = @conn.exec('VALUES ($1::bytea)', [ { :value => bytes, :format => 1 } ]) PG::Connection.unescape_bytea(res[0]['column1']).should== bytes end it "should return the same bytes in text format that are sent as inline text" do binary_file = File.join(Dir.pwd, 'spec/data', 'random_binary_data') in_bytes = File.open(binary_file, 'rb').read out_bytes = nil @conn.exec("SET standard_conforming_strings=on") res = @conn.exec("VALUES ('#{PG::Connection.escape_bytea(in_bytes)}'::bytea)", [], 0) out_bytes = PG::Connection.unescape_bytea(res[0]['column1']) out_bytes.should == in_bytes end it "should return the parameter type of the specified prepared statement parameter", :postgresql_92 do query = 'SELECT * FROM pg_stat_activity WHERE user = $1::name AND query = $2::text' @conn.prepare( 'queryfinder', query ) res = @conn.describe_prepared( 'queryfinder' ) @conn.exec( 'SELECT format_type($1, -1)', [res.paramtype(0)] ).getvalue( 0, 0 ). should == 'name' @conn.exec( 'SELECT format_type($1, -1)', [res.paramtype(1)] ).getvalue( 0, 0 ). should == 'text' end it "should raise an exception when a negative index is given to #fformat" do res = @conn.exec('SELECT * FROM pg_stat_activity') expect { res.fformat( -1 ) }.to raise_error( ArgumentError, /column number/i ) end it "should raise an exception when a negative index is given to #fmod" do res = @conn.exec('SELECT * FROM pg_stat_activity') expect { res.fmod( -1 ) }.to raise_error( ArgumentError, /column number/i ) end it "should raise an exception when a negative index is given to #[]" do res = @conn.exec('SELECT * FROM pg_stat_activity') expect { res[ -1 ] }.to raise_error( IndexError, /-1 is out of range/i ) end it "should raise allow for conversion to an array of arrays" do @conn.exec( 'CREATE TABLE valuestest ( foo varchar(33) )' ) @conn.exec( 'INSERT INTO valuestest ("foo") values (\'bar\')' ) @conn.exec( 'INSERT INTO valuestest ("foo") values (\'bar2\')' ) res = @conn.exec( 'SELECT * FROM valuestest' ) res.values.should == [ ["bar"], ["bar2"] ] end # PQfmod it "can return the type modifier for a result column" do @conn.exec( 'CREATE TABLE fmodtest ( foo varchar(33) )' ) res = @conn.exec( 'SELECT * FROM fmodtest' ) res.fmod( 0 ).should == 33 + 4 # Column length + varlena size (4) end it "should raise an exception when an invalid index is passed to PG::Result#fmod" do @conn.exec( 'CREATE TABLE fmodtest ( foo varchar(33) )' ) res = @conn.exec( 'SELECT * FROM fmodtest' ) expect { res.fmod(1) }.to raise_error( ArgumentError ) end it "should raise an exception when an invalid (negative) index is passed to PG::Result#fmod" do @conn.exec( 'CREATE TABLE fmodtest ( foo varchar(33) )' ) res = @conn.exec( 'SELECT * FROM fmodtest' ) expect { res.fmod(-11) }.to raise_error( ArgumentError ) end it "shouldn't raise an exception when a valid index is passed to PG::Result#fmod for a column with no typemod" do @conn.exec( 'CREATE TABLE fmodtest ( foo text )' ) res = @conn.exec( 'SELECT * FROM fmodtest' ) res.fmod( 0 ).should == -1 # and it shouldn't raise an exception, either end # PQftable it "can return the oid of the table from which a result column was fetched" do @conn.exec( 'CREATE TABLE ftabletest ( foo text )' ) res = @conn.exec( 'SELECT * FROM ftabletest' ) res.ftable( 0 ).should == be_nonzero() end it "should raise an exception when an invalid index is passed to PG::Result#ftable" do @conn.exec( 'CREATE TABLE ftabletest ( foo text )' ) res = @conn.exec( 'SELECT * FROM ftabletest' ) expect { res.ftable(18) }.to raise_error( ArgumentError ) end it "should raise an exception when an invalid (negative) index is passed to PG::Result#ftable" do @conn.exec( 'CREATE TABLE ftabletest ( foo text )' ) res = @conn.exec( 'SELECT * FROM ftabletest' ) expect { res.ftable(-2) }.to raise_error( ArgumentError ) end it "shouldn't raise an exception when a valid index is passed to PG::Result#ftable for a " + "column with no corresponding table" do @conn.exec( 'CREATE TABLE ftabletest ( foo text )' ) res = @conn.exec( 'SELECT foo, LENGTH(foo) as length FROM ftabletest' ) res.ftable( 1 ).should == PG::INVALID_OID # and it shouldn't raise an exception, either end # PQftablecol it "can return the column number (within its table) of a column in a result" do @conn.exec( 'CREATE TABLE ftablecoltest ( foo text, bar numeric )' ) res = @conn.exec( 'SELECT * FROM ftablecoltest' ) res.ftablecol( 0 ).should == 1 res.ftablecol( 1 ).should == 2 end it "should raise an exception when an invalid index is passed to PG::Result#ftablecol" do @conn.exec( 'CREATE TABLE ftablecoltest ( foo text, bar numeric )' ) res = @conn.exec( 'SELECT * FROM ftablecoltest' ) expect { res.ftablecol(32) }.to raise_error( ArgumentError ) end it "should raise an exception when an invalid (negative) index is passed to PG::Result#ftablecol" do @conn.exec( 'CREATE TABLE ftablecoltest ( foo text, bar numeric )' ) res = @conn.exec( 'SELECT * FROM ftablecoltest' ) expect { res.ftablecol(-1) }.to raise_error( ArgumentError ) end it "shouldn't raise an exception when a valid index is passed to PG::Result#ftablecol for a " + "column with no corresponding table" do @conn.exec( 'CREATE TABLE ftablecoltest ( foo text )' ) res = @conn.exec( 'SELECT foo, LENGTH(foo) as length FROM ftablecoltest' ) res.ftablecol(1).should == 0 # and it shouldn't raise an exception, either end it "can be manually checked for failed result status (async API)" do @conn.send_query( "SELECT * FROM nonexistant_table" ) res = @conn.get_result expect { res.check }.to raise_error( PG::Error, /relation "nonexistant_table" does not exist/ ) end it "can return the values of a single field" do res = @conn.exec( "SELECT 1 AS x, 'a' AS y UNION ALL SELECT 2, 'b'" ) res.field_values( 'x' ).should == ['1', '2'] res.field_values( 'y' ).should == ['a', 'b'] expect{ res.field_values( '' ) }.to raise_error(IndexError) expect{ res.field_values( :x ) }.to raise_error(TypeError) end it "should raise a proper exception for a nonexistant table" do expect { @conn.exec( "SELECT * FROM nonexistant_table" ) }.to raise_error( PG::UndefinedTable, /relation "nonexistant_table" does not exist/ ) end it "should raise a more generic exception for an unknown SQLSTATE" do old_error = PG::ERROR_CLASSES.delete('42P01') begin expect { @conn.exec( "SELECT * FROM nonexistant_table" ) }.to raise_error{|error| error.should be_an_instance_of(PG::SyntaxErrorOrAccessRuleViolation) error.to_s.should match(/relation "nonexistant_table" does not exist/) } ensure PG::ERROR_CLASSES['42P01'] = old_error end end it "should raise a ServerError for an unknown SQLSTATE class" do old_error1 = PG::ERROR_CLASSES.delete('42P01') old_error2 = PG::ERROR_CLASSES.delete('42') begin expect { @conn.exec( "SELECT * FROM nonexistant_table" ) }.to raise_error{|error| error.should be_an_instance_of(PG::ServerError) error.to_s.should match(/relation "nonexistant_table" does not exist/) } ensure PG::ERROR_CLASSES['42P01'] = old_error1 PG::ERROR_CLASSES['42'] = old_error2 end end it "should raise a proper exception for a nonexistant schema" do expect { @conn.exec( "DROP SCHEMA nonexistant_schema" ) }.to raise_error( PG::InvalidSchemaName, /schema "nonexistant_schema" does not exist/ ) end it "the raised result should be nil in case of a connection error" do c = PGconn.connect_start( '127.0.0.1', 54320, "", "", "me", "xxxx", "somedb" ) expect { c.exec "select 1" }.to raise_error{|error| error.should be_an_instance_of(PG::UnableToSend) error.result.should == nil } end end ruby-pg-0.17.0/spec/pg_spec.rb000066400000000000000000000016671222421776500161050ustar00rootroot00000000000000#!/usr/bin/env rspec # encoding: utf-8 BEGIN { require 'pathname' basedir = Pathname( __FILE__ ).dirname.parent libdir = basedir + 'lib' $LOAD_PATH.unshift( basedir.to_s ) unless $LOAD_PATH.include?( basedir.to_s ) $LOAD_PATH.unshift( libdir.to_s ) unless $LOAD_PATH.include?( libdir.to_s ) } require 'rspec' require 'spec/lib/helpers' require 'pg' describe PG do it "knows what version of the libpq library is loaded", :postgresql_91 do PG.library_version.should be_an( Integer ) PG.library_version.should >= 90100 end it "knows whether or not the library is threadsafe" do PG.should be_threadsafe() end it "does have hierarchical error classes" do PG::UndefinedTable.ancestors[0,4].should == [ PG::UndefinedTable, PG::SyntaxErrorOrAccessRuleViolation, PG::ServerError, PG::Error] PG::InvalidSchemaName.ancestors[0,3].should == [ PG::InvalidSchemaName, PG::ServerError, PG::Error] end end