pax_global_header00006660000000000000000000000064143602710440014513gustar00rootroot0000000000000052 comment=14dcbf5c7f37d109f2d867a01056534c1a35a2db SQLClient-1.9.0/000077500000000000000000000000001436027104400133205ustar00rootroot00000000000000SQLClient-1.9.0/.cvsignore000066400000000000000000000002171436027104400153200ustar00rootroot00000000000000*obj ECPG.bundle ECPG.m MySQL.bundle Oracle.bundle Oracle.lis Oracle.m Postgres.bundle SQLClient config.h config.log config.make config.status SQLClient-1.9.0/COPYING.LIB000066400000000000000000000167301436027104400147670ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. SQLClient-1.9.0/ChangeLog000066400000000000000000001627301436027104400151030ustar00rootroot000000000000002023-01-13 Richard Frith-Macdonald * GNUmakefile: bumped version to 1.9.0. 2022-06-08 Richard Frith-Macdonald * SQLClient.h: Declare new (-committed) method. * SQLClient.m: * SQLClientPool.m: Implement -committed to return the count of transactions committed by a client or pool. Update -description to report that too. 2022-06-08 Richard Frith-Macdonald * SQLClient.h: Declare new (-setOptions:) method. * SQLClient.m: Implement stub for new method and add code to call it to register any optional configuration, passing the configuration dictionary as a parameter. * Postgres.m: Implement new method to store configuration information and use sslmode option if (and only if) it is set to require an encrypted connection. 2020-09-01 Wolfgang Lux * SQLClient.m (release): Reinstate fix to avoid deadlock while purging pool. 2020-04-21 Richard Frith-Macdonald * Postgres.m: Change notification code to de-duplicate notifications if/when postgres sends many copies of the same notification at the same time. Also change the code to queue notifications in the thread that received them (as documented) and only queue them in the main thread if the receiving thread does not have an active run loop. 2020-04-13 Wolfgang Lux * MySQL.m (backendQuery:recordType:listType:): Change argument types to match those of the overridden base class implementation to make the override work with the GNUstep Objective-C runtime. 2020-04-08 Wolfgang Lux * SQLClient.m (clientWithConfiguration:name:): * SQLClient.m (initWithConfiguration:name:pool:): Eventually reconfigure a client connection that gets reused. 2020-03-21 Richard Frith-Macdonald * Postgres.m: Don't attempt to establish connection before query or execute (the superclass should do it). * SQLClient.m: Ensure connection is established before calling backend methods where possible. Add timing to establishment of connection. 2020-02-27 Richard Frith-Macdonald * SQLClient.m: Make the code aware of the tiny string class used by the gnustep base library. Treat tiny strings as literal strings because, unfortunately, we can't tell if they were created at compile time or at run time. 2020-02-25 Richard Frith-Macdonald * SQLClient.m: Changes to -release to avoid deadlock purging pool. 2020-02-14 Richard Frith-Macdonald * SQLClient.m: Re-implement SQLString as a true subclass rather than using trick depending on internals of gnustep-base (which change with the ObjC-2.0 ABI and would break). 2020-02-11 Richard Frith-Macdonald * SQLClient.h: Remove redundant -prepareQuery: method. * SQLClient.m: Remove redundant -prepareQuery: method and redundant code from query building methods. * SQLClientPool.m: Remove redundant -prepareQuery: method and redundant code from query building methods. 2020-01-22 Richard Frith-Macdonald * Postgres.m: Fix notification posting to refrain from coalescing. 2019-12-11 Wolfgang Lux * Postgres.m: Hide database connection password from debug logs. 2019-08-06 Richard Frith-Macdonald * SQLClientPool.m: Fix error specifying query string in exceptions 2019-07-29 Richard Frith-Macdonald * SQLClient.m: Improve logging of cache queries to indicate that the query was from the cache and whether it was a it or a miss. 2019-07-14 Wolfgang Lux * SQLClient.h * SQLClientPool.m: Hide definition of SQLClientPoolItem from the public interface, as it is incompatible with automatic reference counting. 2019-05-03 Wolfgang Lux * SQLClient.m: Rewrite release method to work with version 1.9 of the GNUstep Objective-C runtime system and also Apple's runtime. 2019-03-07 Wolfgang Lux * SQLClient.m: Fix insertTransaction:atIndex: to work as advertised and insert at the specified index. 2019-03-07 Richard Frith-Macdonald * SQLClient.m: fix to make the result of a prepare method contain 'literal' strings. In -begin do not set the flag to say we are in a transaction until the statement has actually executed. 2019-02-28 Wolfgang Lux * Postgres.m: Fix minor space leak in the Postgres backendConnect method. 2019-02-28 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Add -prepareQuery:... method and make simpleQuery methods check that they are given a literal (or proxy); 2019-02-19 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Remove transaction merging (deprecated in 2015). 2019-01-24 Wolfgang Lux * Postgres.m (backendQuery:recordType:listType:): Fix optimization to reuse small data values in query results so that it actually works. 2018-11-23 Wolfgang Lux * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Use a double for the argument of quoteFloat: and replace the inappropriate %f conversion by %.17g to avoid loss of precision when quoting floating-point numbers. 2018-07-27 Yavor Doganov * SQLClient.m: Fix some spelling errors. 2018-06-28 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Make SQLTransaction thread-safe, also add -lock and -unlock methods to allow a sequence of other methods to be called without another thread interfering. Add -setResetOnExecute: method to configure a transaction to be automatically reset on successful execution. 2018-04-16 Richard Frith-Macdonald * SQLClient.m: Fix error checking for nil values when preparing with a dictionary. This should make the {key?default} syntax work. 2017-09-19 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Simplify observation of database notifications ... one observation per name per observing object. 2017-07-27 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Temporarily restore earlier behavior ... Autoquote warnings off by default. Connection retries off by default. In future releases the plan is to a. have connection attempts retried forever by default b. first turn on warnings about autoquote issues by default c. later, rurn on autoquote by default 2017-07-27 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Have connection attempts automatically retried (blocking indefinitely). Have queries and statements outside a transaction automatically retried if they fail due to loss of connection. 2017-08-25 Richard Frith-Macdonald * Postgres.m: Cache the file descriptor to fix problem in cleanup when postgres returns -1 from PQsocket() as we are trying to remove descriptor from run loop. Also fix error in unlisten where we would stop monitoring the descriptor prematurely. 2017-08-15 Richard Frith-Macdonald * Postgres.m: Add code so that if the database connection is lost while we are listening for notifications from it, we notice that and clean up properly rather than continuing to process/ignore a stream of end-of-file events on the dead descriptor. 2017-07-04 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: * Postgres.m: Lots of changes introducing new concept of a 'literal' as a string which does not need to be quoted (and must not be autoquoted). Quoting via the -quote: method now raises an exception if the argument is not supported, but we have a new method to allow classes to provide a mechanism for quoting themselves (ie to add support for them being using in SQL queries/statements). 2017-06-29 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: New method to control warnings (on by default) about strings which would automaticaly be quoted when autoquote is turned on. 2017-04-07 Richard Frith-Macdonald * SQLClient.m: Fix leak of SQLString instances caused by inheriting memory management methods from the literal string class. 2017-03-06 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Add new +literal: and -literal: methods to make a normal string into one recognised as suitable for use literally (ie without quoting) in an SQL query/statement. Add +setAutoquote: method to turn on automatic quoting of non-literal strings as an aid to avoiding SQL injectiuon attacks. 2016-10-19 Richard Frith-Macdonald * Postgres.m: Wolfgang spotted that the asynchronous notification code is not thread safe ... we must not have one thread handle a notification at the same time that another is trying to use the database connectionto execute a query/statement. Use the client's lock to prevent that from happening. 2016-10-18 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Make -addObserver:selector:name: raise if applied to a client in a pool. Improve documentation to make it clear that pool clients can't be used as observers of database notifications. 2016-06-23 Richard Frith-Macdonald * SQLClient.m: Fixup to use case sensitive notification names. 2016-06-21 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Allow easy removal of all database notification observers. Remove all observers when a client is returned to a pool. Postgres.m: Implement asynchronous notification by watching descriptor. 2016-05-06 Richard Frith-Macdonald * SQLClient.m: Fix bug in initialisation ordering. * Postgres.m: Fix bug in array parsing. 2016-04-27 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add -isNull helper method for testing for null fields in records returned from the database. 2016-02-18 Richard Frith-Macdonald * configure.ac: get host and cpu with more recent gnustep-make * configure: regenerate * JDBC.m: Update for connection pools (bug #47178) * testJDBC.m: get rid of compiler warnings 2015-07-22 Richard Frith-Macdonald * Postgres.m: disconnect on fatal error, so we don't keep trying to re-use the same connection when there's a problem with the server. 2015-07-23 Wolfgang Lux * SQLClient.m (initialize): Restore initialization of NSDateClass so that dates are quoted correctly irrespective of their current format. 2015-07-22 Richard Frith-Macdonald * SQLClient.h: * SQLClientPool.m: Change internal pool data to allow for storing reference counts and the threads which own each client connection. Support exclusive and non-exclusive clients in the pool, where an exclusive client is one which is only usable by the code which fetched it from the pool, but a non-exclusive client may be provided to other code in the same thread. Change behavior of -provideClient and -provideClientBeforeDate: to provide non-exclusive clients. Add -provideClientExclusive and -provideClientBeforeDate:exclusive: to support the old behavior. 2015-07-17 Niels Grewe * Postgres.m: Support for "char"[] parsing. 2015-07-16 Wolfgang Lux * Postgres.m (newDateFromBuffer): Use local time zone instead of GMT when parsing a date without a time zone. 2015-06-29 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Implement another missing convenience method. Fix locking error when executing a batch. Add -prepare:with: method for use by transactions. Add -owner method to get a transaction's owner. 2015-06-27 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Implement -batch: method for client pools. 2015-06-26 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Implement -transaction method for client pools so that we can build a transaction which, when executed, will use any available client from the pool. Support setting of the client name for clients in a pool. 2015-06-25 Niels Grewe * SQLClient.[hm]: Add an accessor method to obtain the SQLClientPool object owning a specific SQLClient. 2015-06-25 Richard Frith-Macdonald * SQLClient.h: Add -name method for pools. * SQLClient.m: Match documentation and use 'Database' as default name. * SQLClientPool.m: Add -name method and fix default name. 2015-06-19 Richard Frith-Macdonald * Postgres.m: Fix error parsing timezone in date. 2015-06-09 Richard Frith-Macdonald * SQLClient.m: Fix race condition spotted by Wolfgang and change purge operation to avoid disconnecting clients while the class lock is locked. 2015-05-28 Richard Frith-Macdonald * SQLClient.h: Add pool purge control method. * SQLClient.m: Fix bug finding least recently used client. * SQLClientPool.m: Refine purging of pool. Fix autorelease bug. Improve diagnostics. Fix bug reporting time pool has blocked. 2015-05-27 Richard Frith-Macdonald * Postgres.m: bugfixes * SQLClient.m: bugfix for finding oldest idle connection * SQLClientPool.m: implement method to disconnect idle connections in pool. also check for clients being returned to pool while a transaction is still in progress. 2015-04-30 Richard Frith-Macdonald * Postgres.m: * testPostgres.m: Fix error parsing timestamps in arrays when the server quoters them. Also optimise string allocation, and add some tests. 2015-04-28 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * Postgres.m: Deprecate transaction merging. Rewrite SQLRecord concrete class to use a new SQLRecordKeys object shared between all the records produced by a query (as a performance enhancement for large queries). 2015-04-15 Richard Frith-Macdonald * Postgres.m: notifications are posted in main thread. 2015-04-13 Richard Frith-Macdonald * SQLClient.h: * SQLClientPool.m: Make sure clients provided temporarily in convenience methods are swallowed by the pool again as soon as possible. Also trap and re-raise exceptions after swallowing provided client, to avoid the client being in use longer than necessary after an exception. Also, avoid taking clients from the pool in a few cases wehere we don't actually need to. Add -cache method for SQLClientPool. 2015-04-12 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Expose method to add statement for insertion of data objects to transaction. 2015-04-09 Richard Frith-Macdonald * SQLClient.h: Add array quoting method for pool. Add pool ivar. * SQLClientPool.m: Implement array quoting and change other quoting to use new ivar rather than expensive provide/swallow sequence. 2015-04-01 Richard Frith-Macdonald * SQLClient.h: * Postgres.m: Fixup notification posting to be asynchronous using the default notification queue for the thread so that the notifications do not get delivered while the query/statement at which they were detected is still in progress. Add method to explicitly grab/release the client for the current thread. 2015-03-11 Richard Frith-Macdonald * SQLClientPool.m: Fixup for exposing prepare method * SQLClient.h: * SQLClient.m: * Postgres.m: * testPostgres.m: Add simple array support for char/varchar/text, integer/real, timestamp, bool and bytea. When a query returns an array of one of these types, the resulting object is an NSArray containing the database array elements rather than an NSString containing the string literal representation of the database array. Also added a method to convert an NSArray to a string literal representation of a database array. 2015-03-02 Richard Frith-Macdonald * Postgres.h: Drop support for old versions of postgres which didn't support standard conforming strings. This allows us to always turn on standard conforming strings and be able to quote string and bytea objects whether the database connection has been established or not. * GNUmakefile: Bumped version to 1.8.4. 2014-12-11 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * GNUmakefile: Expose method to prepare a statement and a convenience method to check for an existing cached value (using a prepared statement as the cache key). Bumped version to 1.8.3. 2014-12-11 Richard Frith-Macdonald * Postgres.m: Fix minor thread safety issue. * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Convenience methods to let a pool act as a client for any one-off op. 2014-11-19 Richard Frith-Macdonald * GNUmakefile: bump version to 1.8.2 for bugfix release. * Postgres.m: Fix error handling TIME fields. 2014-11-04 Richard Frith-Macdonald * GNUmakefile: bump version to 1.8.1 for connection pool tweaks. 2014-10-13 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * SQLClientPool.m: Keep connections in pools outside the normal count of maximum number of concurrent connections. If we are using a pool then we must assume we want the pool to operate to its configured capacity. 2014-10-07 Richard Frith-Macdonald * SQLClient.m: Add locking of the database client by SQLTransaction in case another thread tries to use the client whjile the transaction is using it (ie between an attempted transaction and a rollback if it fails). 2014-10-02 Richard Frith-Macdonald * SQLClient.m: On exception during SQLTransaction -execute, roll back. 2014-09-24 Richard Frith-Macdonald * Postgres.m: An SQL exception/error should not automatically disconnect. 2014-09-10 Richard Frith-Macdonald * SQLClient.m: Fix error in [-setUser:] ... was checking wrong instance variable to see if the user changed. 2014-08-09 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Redesign merging to give control over the number of statements merged and to make merging an attribute of the transaction rather than something done by a specific method. 2014-08-08 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add merging of insert/update statements in a transaction. 2014-07-17 Yavor Doganov Install bundles in a versioned directory. * GNUmakefile (BUNDLE_INSTALL_DIR): Append the interface version. * GNUmakefile.preamble (ADDITIONAL_CPPFLAGS): Define. * SQLClient.m (-_configure:): Load bundles from the versioned directory. 2014-07-11 Yavor Doganov * GNUmakefile (SQLClient_LIBRARIES_DEPEND_UPON): Add $(FND_LIBS) and $(OBJC_LIBS). 2014-06-20 Richard Frith-Macdonald * GNUmakefile: bump version to 1.8.0 for next release (will break binary compatibility due to changes for pools adding ivars). 2014-06-20 Richard Frith-Macdonald * SQLClient.h: Add SQLClientPool, new method to check idle clients and new initialiser. * SQLClient.m: Changes to support pools of clients and permit a pool to contain multiple clients with the same config. * SQLClientPool.m: new class to provide a pool of clients with the same config. 2014-05-27 Richard Frith-Macdonald * SQLClient.h: Warn about not using the database inside a notification handler. * Postgres.m: Add locking around database operations caused by asynchronous arrival of a notification. * GNUmakefile: new subminor version for bugfix release * Version 1.7.3: released 2014-05-19 Richard Frith-Macdonald * SQLClient.m: More locking to try to protect all access to the database connection. * GNUmakefile: new subminor version for bugfix release * Version 1.7.2: released 2014-05-13 Richard Frith-Macdonald * SQLClient.m: Fix tiny window in which a connection could be unlocked yet have the flag set to say it is in a transaction (thus potentially allowing a locking consistency error). Add locking to protect setting/changing configuration. 2014-05-08 Richard Frith-Macdonald * GNUmakefile: new subminor version for bugfix release * Version 1.7.1: released 2014-04-12 Richard Frith-Macdonald * SQLClient.m: Fix error removing database observer when last name is removed. 2014-03-05 Wolfgang Lux * Postgres.m (backendExecute:): Fix incorrect comparison operator. 2014-02-21 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add mutable copy implementation so that set and dictionary builders can be used by caching queries without raising an exception ... the mutable copy of the helper's content is what gets cached. 2014-02-15 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add helper for building counted set from query. 2013-09-06 Richard Frith-Macdonald * Version 1.7.0: released 2013-09-05 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Use NSUInteger for sizeInBytes: 2013-04-10 Richard Frith-Macdonald * ECPG.pgm: * MySQL.m: * Oracle.pm: * Postgres.m: * SQLClient.h: * SQLClient.m: * GNUmakefile: Change behavior to no longer trim leading and trailing space from values retrieved from database by default. Add method to restore automatic trimming for a connection if needed. 2013-03-04 Richard Frith-Macdonald * Version 1.6.1: released 2013-03-04 Richard Frith-Macdonald * SQLClient.h: Add helper classe interfaces. * SQLClient.m: Add helper classe implementations. Add performance helper classes for when querying a set of records containing single values and when querying a dataset which contains key/value pairs more naturally haqndled as a dictionary than an array. 2013-02-11 Sebastian Reitenbach * ECPG.pgm * testECPG.m * testMySQL.m * testSQLite.m use PRIuPTR to NSLog NSUIntegers 2013-01-31 Richard Frith-Macdonald * SQLClient.m: Check for -disconnect being called when inside a transaction and handle locking properly in that case. Change simple execute and query methods so they don't call -debug: inside locked regions, in case the method has been overridden to do something not safe in such locked sections (such as trying a query in another thread to report extra debug info). 2012-11-29 Richard Frith-Macdonald * Wrap more code in exception handlers where there is any potential for an exception in a lock protected region. 2012-11-10 Niels Grewe * GNUmakefile: Link against $(FND_LIBS) and $(OBJC_LIBS) instead of -lgnustep-base and -lobjc. 2012-10-22 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * Postgres.m: * GNUmakefile: Add support for asynchronous notifications and bump version number. 2012-10-18 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * ECPG.pgm: * MySQL.m: * Postgres.m: * Oracle.pm: * SQLite.m: * JDBC.m: * testPostgres.m: Change execute methods to return a count of the rows to which the executed operation applies, or -1 if not supported. Implement for postgresql and mysql. 2012-06-17 Richard Frith-Macdonald * Improve check for compatibility of transactions between clients. 2011-09-30 Richard Frith-Macdonald * configure.ac: try to use pg_config if available. * configure: regenerate * Postgres.m: Fix to handle new bytea with \x format * GNUmakefile: Bump to 1.5.3 2011-04-01 Richard Frith-Macdonald * SQLClient.m: Cleanup locking on -begin/-commit/-rollback * Version 1.5.2: bump version number 2011-04-01 Richard Frith-Macdonald * Version 1.5.1: bump version number 2010-11-17 Nicola Pero * GNUmakefile.postamble: Uncommented .PRECIOUS for ECPG and Oracle, so that typing 'make' does nothing when everything is already built. 2010-08-13 Richard Frith-Macdonald * MySQL.m: Try to recognise loss of connection. Fix bug in timezone management. 2010-07-16 Richard Frith-Macdonald * MySQL.m: Add support for TEXT data and for MySQL's failure to support timezones. Also add support for multiple statements in a batch. 2010-07-16 Richard Frith-Macdonald * configure.ac: Improve check for mysql library. 2010-02-15 Richard Frith-Macdonald * SQLClient.h: Just include Foundation.h, fix minor doc errors * GNUmakefile: Add documentation flag to avoid warning. 2010-01-29 Richard Frith-Macdonald * Postgres.m: Fix to cope with a new date format in recent postgres. 2009-11-18 Richard Frith-Macdonald Many tweaks to build under OSX snow leopard. 2009-10-27 Richard Frith-Macdonald * ECPG.pgm: * MySQL.m: * Postgres.m: * Oracle.pm: * SQLite.m: * JDBC.m: Don't call -backendConnect or -backendDisconnect ... should be using the public API so that notifications are sent properly. 2009-10-01 Richard Frith-Macdonald * configure.ac: workaround autoconf bug. * configure: regenerate 2009-09-16 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add convenience method to convert array of rows into an array of columns. 2009-09-08 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add method for executing a batch of statements/transactions and returning any failed statements/transactions to they can be re-done. Also add methods to manipulate the statements in a transaction so we can retry things intelligently. 2008-11-12 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add support for tracking the number of consecutive connection failures and imposing a delay between connection attempts. * JDBC.m: fix typo * GNUMmakefile: bump version 2008-07-19 Nicola Pero * configure.ac: Documented the --with-additional-include=, --with-additional-lib=, --with-postgres-dir= and --with-jre-architecture= options. * configure: Regenerated. * config.h.in: Regenerated. 2008-03-03 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * ECPG.pgm: * MySQL.m: * Postgres.m: * SQLite.m: * JDBC.m: Alter to allow control of both the way records are strored and the way they are listed ... so people can make performance optimisations. 2008-02-21 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Experimental new method to set a thread to do all cached queries on and to perform asynchronous updates if other threads request information which is in the cache but past its expiry date. Should allow threads to use config information from a database without blocking unnecessarily. 2008-02-15 Richard Frith-Macdonald * SQLClient.m: Fix memory leak when executing transaction. 2007-10-23 Richard Frith-Macdonald Postgres.m: Use E'...' syntax for bytea if it is available. 2007-09-14 Richard Frith-Macdonald Update to LGPL3 2007-07-21 Richard Frith-Macdonald * SQLClient.m: Fix retasin bug copying transactions. * JDBC.m: Update for new batch code 2007-07-09 Richard Frith-Macdonald * SQLClient.m: Post notifications upon connect and disconnect. 2007-07-07 Richard Frith-Macdonald * SQLClient.m: Fix error causing loss of some debug output when an exception occurs in a transaction. Rewrite transaction code to support execution with automatic retry of statements when batching. * JDBC.m: Update for new transaction code 2007-04-01 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * testSQLite.m: * testJDBC.m: * MySQL.m: * Postgres.m: * GNUmakefile: * SQLite.m: * JDBC.m: * testMySQL.m: * testPostgres.m: * testECPG.m: Updates to build on MacOS-X with apple-apple-appple 2007-03-08 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * MySQL.m: * ECPG.pgm: * Postgres.m: * Oracle.pm: * SQLite.m: * JDBC.m: Add KVC support for SQLRecord. Make SQLRecord into a class cluster with a single concrete implementation for now. Extend API to allow specifying of an alternative SQLRecord subclass when doing a query so that query results can be efficiently stored into custom subclasses rather than having to first be retrieved into an SQLRecord and then copied. 2007-02-14 Nicola Pero * GNUmakefile (BUNDLE_INSTALL_DIR): Set using GNUSTEP_BUNDLES, not GNUSTEP_INSTALLATION_DIR. 2007-01-29 Richard Frith-Macdonald * JDBC.m: Add JDBC2.0 batching for when all statements in a transaction are simple (ie no NSData arguments) and the batch API is supported by the driver. * testJDBC.m: Add simple transaction/batch test. 2007-01-29 Richard Frith-Macdonald * JDBC.m: Add support for SQLTransaction class to batch JDBC operations. 2006-12-24 Richard Frith-Macdonald * JDBC.m: Don't store pointer to jni information in local variable until after we have opened the connection to the database, or we may be using a null pointer and generate a crash. 2006-12-22 Richard Frith-Macdonald * configure.ac: save/restore LIBS after jdbc check so that other tests don't try to link jre 2006-10-06 Nicola Pero * GNUmakefile.wrapper.objc.preamble (ADDITIONAL_LIB_DIRS): Added variable so that the wrapper compiles before the library is installed. 2006-10-02 Nicola Pero * configure.ac: Do not read gnustep configuration which is never used. * configure.ac: Added --disable-jdbc-bundle, --disable-mysql-bundle, --disable-sqllite-bundle, --disable-postgres-bundle flags to be able to turn some bundles off (regardless of config results). * configure: Regenerated. 2006-10-01 Graham J Lee * configure.ac: Fix to use GNUSTEP_CONFIG_FILE environment variable. 2006-09-14 Richard Frith-Macdonald * JDBC push and pop local frames to avoid memory leaks. 2006-08-03 Nicola Pero * SQLClient.m ([SQLClient -quoteString:]): Renamed local variable that had the same name as the method argument. 2005-06-23 Richard Frith-Macdonald * SQLClient.m: transaction efficiency tweak. * GNUmakefile: bump version to 1.3 as the new blob marker changes and postgres quoting changes alter behavior. 2005-06-04 Richard Frith-Macdonald * SQLClient.m: avoid useless compiler warnings. 2005-05-25 Richard Frith-Macdonald * configure.ac: Check for new postgres string escaping * configure: Regenerate * SQLClient.h: Add quoteString method for subclasses to override * SQLClient.m: Add new method and change marker for blobs to be one that shouldn't occur in a quoted string. * SQLite.m: Use new blob marker * MySQL.m: Use new blob marker * config.h.in: Add new postgres escaping function * Postgres.m: Handle new escaping * testPostgres.m: Add check for escaping odd characters. 2005-02-22 Richard Frith-Macdonald * SQLClient.m: Support quoting of NSArray and NSSet objects. 2006-01-11 Nicola Pero * configure.ac: Do not source GNUSTEP_CONFIG_FILE if it doesn't exist, so that the library can be used with older versions of gnustep-make/gnustep-base too. :-) * configure: Regenerated. 2005-11-23 Richard Frith-Macdonald Added SQLite backend support. 2005-11-14 Richard Frith-Macdonald Factor out WebServer into separate library, and timer and caching stuff into Performance library. Make this library depend on the Performance library. 2005-10-27 Richard Frith-Macdonald * WebServer.m: Add more accurate timestamps and implement request and session duration logging. Also add a unique session ID number to each log to make it easy to track requests on a session. 2005-09-28 Richard Frith-Macdonald * GNUmakefile.wrapper.objc.preamble: new file * SQLClient.jigs: new file * GNUmakefile: Provide java wrappings for SQLClient and friends 2005-09-28 Richard Frith-Macdonald * SQLClient.m: boost performance of quoting a little. Provide -count method for transactions. 2005-09-26 Richard Frith-Macdonald * SQLClient.h: Clean up caching/timestamps. * SQLClient.m: ditto. 2005-09-22 Richard Frith-Macdonald * SQLClient.h: Rewrite caching, and expose cache for external use. * SQLClient.m: ditto. 2005-09-20 Richard Frith-Macdonald * SQLClient.h: make SQLRecord modifieable (replace values). * SQLClient.m: ditto. 2005-09-15 Richard Frith-Macdonald * configure.ac: Locate postgres 8.0 on debian * configure: regenerate 2005-08-03 Richard Frith-Macdonald * GNUmakefile: Add SQLClient_LIBRARIES_DEPEND_UPON for apple as suggested by Yen-Ju Chen. * SQLClient.m: Don't call allocation debug functions on apple, and avoid bogus apple compiler warning. Guard against nil object passed to NSMapRemove() ... the apple implementation crashes on this. 2005-08-02 Richard Frith-Macdonald * GNUmakefile: Don't build WebServer stuff on MacOS-X when using the apple runtime (and presumably foundation). 2005-07-07 Richard Frith-Macdonald * MySQL.m: * SQLClient.m: * WebServer.h: * WebServer.m: Tweaks to keep gcc-4 happy (signedness issues) and add support for using separate ssl conmfig for different IP addresses. 2005-06-21 Richard Frith-Macdonald * SQLClient.m: Expand tilde in paths searched for backend bundles. 2005-05-25 Richard Frith-Macdonald * Postgres.m: Clear connection if an exception occurs while disconnecting ... otherwise a failed disconnect can prevent any new connection from being established. Improve quoting of strings to be a bit more efficient and to remove nul characters. 2005-05-09 Richard Frith-Macdonald * WebServer.[hm]: Add method to encode a form from a dictionary into a data object ... convenience for where form data is needed. 2005-03-02 Richard Frith-Macdonald * WebServer.[hm]: Add support for basic http authentication either via username/password pairs in property list or in database table. * SQLClient.[hm]: Add methods to query database with local caching of results, for use on systems needing high performance, where database query (and/or database client-server comms) overheads are important. 2005-02-25 Adam Fedor * Version 1.1.0: * GNUmakefile: Add version. * README: Add ftp location. Sat Feb 19 04:20:00 2004 Richard Frith-Macdonald * Makefile: Build two versions of each bundle with different library linkage for systems where dybnamic linker symbol visibility differs. * SQLClient.m: Try alternative bundle versions. Mon Jan 07 15:20:00 2004 Richard Frith-Macdonald * Makefile: Bump version. * SQLClient.h: Improve documentation. Sat Dec 18 06:00:00 2004 Richard Frith-Macdonald * WebServer.m: Fix bug in substitution of nil values into templates. Add new method to vend static pages. Wed Dec 15 13:10:00 2004 Richard Frith-Macdonald * MySQL.m, Postgres.m, ECPG.pgm: Do NSLog() logging of field information only when debug level is greater than 1. Fri Dec 10 10:50:00 2004 Richard Frith-Macdonald * GNUmakefile: Remove unnecessary libraries from link commands for bundles. On Darwin, specifying these leads to multiply defined symbols when an executable attempts to load the bundle. Fri Nov 19 14:40:00 2004 Richard Frith-Macdonald * WebServer.m: parse basic authentication infor and set it in extra headers in request. * WebServerBundles.m: support handling of paths longer than the ones set for each bundle. Tue Nov 11 14:48:05 2004 Nicola Pero * GNUmakefile (BUNDLE_INSTALL_DIR): install bundles in GNUSTEP_INSTALLATION_DIR, not GNUSTEP_LOCAL_ROOT. Tue Nov 09 10:20:00 2004 Richard Frith-Macdonald * SQLClient.hm: add ([-append:]) method to merge transactions. Thu Oct 28 08:45:00 2004 Richard Frith-Macdonald * WebServer.m: Don't generate alert about connection with empty request if we have lready handled a request and reset. Tue Oct 26 16:50:00 2004 Richard Frith-Macdonald * SQLClient.m: debug and duration logging should be turned off by default ... a different value crept in somehow. Sat Oct 9 14:29:35 2004 Nicola Pero * SQLClient.m ([SQLClient -simpleExecute:]): Fixed logging durations and statements in transactions. Thu Oct 08 10:30:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Add ([-quotef:,...]) to perform efficient quoting of a string produced using printf style format and arguments. Thu Oct 07 10:30:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Optimise timing operations somewhat. Wed Oct 06 15:04:23 2004 Nicola Pero * WebServer.h: Fixed typo in parameter name. Wed Oct 06 13:10:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Allow a database transaction to already have been begun when [SQLTransactiuon-execute] is called, so we can have queries in the same database transaction as a list of statements. Wed Oct 06 06:15:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Make the rollback opoeration a safe no-op if there is no transaction in progress. * Postgres.m: Improve exception text by reporting the offending SQL statement(s). Fri Sep 17 16:55:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: When reporting the duration of a commit or rollback, report text of all the statements in the transaction. Fri Aug 28 09:30:00 2004 Richard Frith-Macdonald * WebServer.[hm]: Add support for limiting maximum number of incoming sessions permitted from mone host. Tue Aug 24 14:30:00 2004 Richard Frith-Macdonald * WebServer.[hm]: Add support for HTTP/1.1 persistent connections. Sun Aug 22 10:35:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Add ([SQLRecord-dictionary]) and tidy/comment the class a bit better. Sat Aug 07 14:25:00 2004 Richard Frith-Macdonald * WebServer.m: Add session timeouts to kill off idle sessions. Tue Jul 27 17:30:00 2004 Richard Frith-Macdonald * configure.ac: Give more help when postgres is not found. * configure: regenerate Mon Jul 26 09:50:00 2004 Richard Frith-Macdonald * SQLClient.h: Add -transaction method and SQLTransaction class * SQLClient.m: Implement -transaction method and SQLTransaction class to provide a simple convenient mechanism for executing a sequence of statements as a single transaction. Thu Jul 15 09:40:00 2004 Richard Frith-Macdonald * WebServer.m: ([_didRead:]) more informative logging upon reading an unexpected end-of-file Wed Jul 14 12:07:00 2004 Richard Frith-Macdonald * configure.ac: Check for PQfformat in libpq, if it is not there but the library is there, warn that it is too old. Thu Jul 02 17:40:00 2004 Richard Frith-Macdonald * WebServer.m: Add control over character encoding used to interpret form data. Thu Jul 02 13:25:00 2004 Richard Frith-Macdonald * WebServer.m: Fix error response when an exception occurs. Thu Jul 01 18:00:00 2004 Richard Frith-Macdonald * WebServer.m: Make ([setPort:secure:]) return a status. * WebServerBundles.m: Check that web server is able to start. * WebServer.h: ditto Wed Jun 30 05:40:00 2004 Richard Frith-Macdonald * GNUmakefile: Use ./obj as location for library to link, for initial case where we link the bundles before installing the library. * WebServer.m: Add casts to prevent compiler warning. * Postgres.m: Commented out NSLog() left over from debugging. Tue Jun 29 18:10:00 2004 Richard Frith-Macdonald * SQLClient.m: Fix code for retrieving reference name ... look in the config dictionary first, and in user defaults if not found there. * SQLClient.h: Document change. * GNUmakefile: Link bundles with the library to ensure that they find the SQLRecord class when loaded. Mon Jun 28 12:55:00 2004 Richard Frith-Macdonald * WebServer.h: New file. * WebServer.m: New file. * WebServerBundles.m: New file. * SQLClient.h: Mention WebServer. * GNUmakefile: Build WebServer classes. Added framework to make it easy to use SQLClient to produce standalone http/https applications, such as accepting POST'ed records for addition to a database. Fri May 07 09:15:00 2004 Richard Frith-Macdonald Add methods to log duration of any statements over a certain limit. Tidy instance variables ... prefix mprivate ones with underscore. Install header! Thu Apr 29 15:20:00 2004 Richard Frith-Macdonald * SQLClient.h: Fix URLs in documentation as suggested by Adam. * SQLClient.html: regenerate Mon Apr 26 16:20:00 2004 Richard Frith-Macdonald Initial checkin of library. 2009-10-01 Richard Frith-Macdonald * configure.ac: workaround autoconf bug. * configure: regenerate 2009-09-16 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add convenience method to convert array of rows into an array of columns. 2009-09-08 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add method for executing a batch of statements/transactions and returning any failed statements/transactions to they can be re-done. Also add methods to manipulate the statements in a transaction so we can retry things intelligently. 2008-11-12 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Add support for tracking the number of consecutive connection failures and imposing a delay between connection attempts. * JDBC.m: fix typo * GNUMmakefile: bump version 2008-07-19 Nicola Pero * configure.ac: Documented the --with-additional-include=, --with-additional-lib=, --with-postgres-dir= and --with-jre-architecture= options. * configure: Regenerated. * config.h.in: Regenerated. 2008-03-03 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * ECPG.pgm: * MySQL.m: * Postgres.m: * SQLite.m: * JDBC.m: Alter to allow control of both the way records are strored and the way they are listed ... so people can make performance optimisations. 2008-02-21 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: Experimental new method to set a thread to do all cached queries on and to perform asynchronous updates if other threads request information which is in the cache but past its expiry date. Should allow threads to use config information from a database without blocking unnecessarily. 2008-02-15 Richard Frith-Macdonald * SQLClient.m: Fix memory leak when executing transaction. 2007-10-23 Richard Frith-Macdonald Postgres.m: Use E'...' syntax for bytea if it is available. 2007-09-14 Richard Frith-Macdonald Update to LGPL3 2007-07-21 Richard Frith-Macdonald * SQLClient.m: Fix retasin bug copying transactions. * JDBC.m: Update for new batch code 2007-07-09 Richard Frith-Macdonald * SQLClient.m: Post notifications upon connect and disconnect. 2007-07-07 Richard Frith-Macdonald * SQLClient.m: Fix error causing loss of some debug output when an exception occurs in a transaction. Rewrite transaction code to support execution with automatic retry of statements when batching. * JDBC.m: Update for new transaction code 2007-04-01 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * testSQLite.m: * testJDBC.m: * MySQL.m: * Postgres.m: * GNUmakefile: * SQLite.m: * JDBC.m: * testMySQL.m: * testPostgres.m: * testECPG.m: Updates to build on MacOS-X with apple-apple-appple 2007-03-08 Richard Frith-Macdonald * SQLClient.h: * SQLClient.m: * MySQL.m: * ECPG.pgm: * Postgres.m: * Oracle.pm: * SQLite.m: * JDBC.m: Add KVC support for SQLRecord. Make SQLRecord into a class cluster with a single concrete implementation for now. Extend API to allow specifying of an alternative SQLRecord subclass when doing a query so that query results can be efficiently stored into custom subclasses rather than having to first be retrieved into an SQLRecord and then copied. 2007-02-14 Nicola Pero * GNUmakefile (BUNDLE_INSTALL_DIR): Set using GNUSTEP_BUNDLES, not GNUSTEP_INSTALLATION_DIR. 2007-01-29 Richard Frith-Macdonald * JDBC.m: Add JDBC2.0 batching for when all statements in a transaction are simple (ie no NSData arguments) and the batch API is supported by the driver. * testJDBC.m: Add simple transaction/batch test. 2007-01-29 Richard Frith-Macdonald * JDBC.m: Add support for SQLTransaction class to batch JDBC operations. 2006-12-24 Richard Frith-Macdonald * JDBC.m: Don't store pointer to jni information in local variable until after we have opened the connection to the database, or we may be using a null pointer and generate a crash. 2006-12-22 Richard Frith-Macdonald * configure.ac: save/restore LIBS after jdbc check so that other tests don't try to link jre 2006-10-06 Nicola Pero * GNUmakefile.wrapper.objc.preamble (ADDITIONAL_LIB_DIRS): Added variable so that the wrapper compiles before the library is installed. 2006-10-02 Nicola Pero * configure.ac: Do not read gnustep configuration which is never used. * configure.ac: Added --disable-jdbc-bundle, --disable-mysql-bundle, --disable-sqllite-bundle, --disable-postgres-bundle flags to be able to turn some bundles off (regardless of config results). * configure: Regenerated. 2006-10-01 Graham J Lee * configure.ac: Fix to use GNUSTEP_CONFIG_FILE environment variable. 2006-09-14 Richard Frith-Macdonald * JDBC push and pop local frames to avoid memory leaks. 2006-08-03 Nicola Pero * SQLClient.m ([SQLClient -quoteString:]): Renamed local variable that had the same name as the method argument. 2005-06-23 Richard Frith-Macdonald * SQLClient.m: transaction efficiency tweak. * GNUmakefile: bump version to 1.3 as the new blob marker changes and postgres quoting changes alter behavior. 2005-06-04 Richard Frith-Macdonald * SQLClient.m: avoid useless compiler warnings. 2005-05-25 Richard Frith-Macdonald * configure.ac: Check for new postgres string escaping * configure: Regenerate * SQLClient.h: Add quoteString method for subclasses to override * SQLClient.m: Add new method and change marker for blobs to be one that shouldn't occur in a quoted string. * SQLite.m: Use new blob marker * MySQL.m: Use new blob marker * config.h.in: Add new postgres escaping function * Postgres.m: Handle new escaping * testPostgres.m: Add check for escaping odd characters. 2005-02-22 Richard Frith-Macdonald * SQLClient.m: Support quoting of NSArray and NSSet objects. 2006-01-11 Nicola Pero * configure.ac: Do not source GNUSTEP_CONFIG_FILE if it doesn't exist, so that the library can be used with older versions of gnustep-make/gnustep-base too. :-) * configure: Regenerated. 2005-11-23 Richard Frith-Macdonald Added SQLite backend support. 2005-11-14 Richard Frith-Macdonald Factor out WebServer into separate library, and timer and caching stuff into Performance library. Make this library depend on the Performance library. 2005-10-27 Richard Frith-Macdonald * WebServer.m: Add more accurate timestamps and implement request and session duration logging. Also add a unique session ID number to each log to make it easy to track requests on a session. 2005-09-28 Richard Frith-Macdonald * GNUmakefile.wrapper.objc.preamble: new file * SQLClient.jigs: new file * GNUmakefile: Provide java wrappings for SQLClient and friends 2005-09-28 Richard Frith-Macdonald * SQLClient.m: boost performance of quoting a little. Provide -count method for transactions. 2005-09-26 Richard Frith-Macdonald * SQLClient.h: Clean up caching/timestamps. * SQLClient.m: ditto. 2005-09-22 Richard Frith-Macdonald * SQLClient.h: Rewrite caching, and expose cache for external use. * SQLClient.m: ditto. 2005-09-20 Richard Frith-Macdonald * SQLClient.h: make SQLRecord modifieable (replace values). * SQLClient.m: ditto. 2005-09-15 Richard Frith-Macdonald * configure.ac: Locate postgres 8.0 on debian * configure: regenerate 2005-08-03 Richard Frith-Macdonald * GNUmakefile: Add SQLClient_LIBRARIES_DEPEND_UPON for apple as suggested by Yen-Ju Chen. * SQLClient.m: Don't call allocation debug functions on apple, and avoid bogus apple compiler warning. Guard against nil object passed to NSMapRemove() ... the apple implementation crashes on this. 2005-08-02 Richard Frith-Macdonald * GNUmakefile: Don't build WebServer stuff on MacOS-X when using the apple runtime (and presumably foundation). 2005-07-07 Richard Frith-Macdonald * MySQL.m: * SQLClient.m: * WebServer.h: * WebServer.m: Tweaks to keep gcc-4 happy (signedness issues) and add support for using separate ssl conmfig for different IP addresses. 2005-06-21 Richard Frith-Macdonald * SQLClient.m: Expand tilde in paths searched for backend bundles. 2005-05-25 Richard Frith-Macdonald * Postgres.m: Clear connection if an exception occurs while disconnecting ... otherwise a failed disconnect can prevent any new connection from being established. Improve quoting of strings to be a bit more efficient and to remove nul characters. 2005-05-09 Richard Frith-Macdonald * WebServer.[hm]: Add method to encode a form from a dictionary into a data object ... convenience for where form data is needed. 2005-03-02 Richard Frith-Macdonald * WebServer.[hm]: Add support for basic http authentication either via username/password pairs in property list or in database table. * SQLClient.[hm]: Add methods to query database with local caching of results, for use on systems needing high performance, where database query (and/or database client-server comms) overheads are important. 2005-02-25 Adam Fedor * Version 1.1.0: * GNUmakefile: Add version. * README: Add ftp location. Sat Feb 19 04:20:00 2004 Richard Frith-Macdonald * Makefile: Build two versions of each bundle with different library linkage for systems where dybnamic linker symbol visibility differs. * SQLClient.m: Try alternative bundle versions. Mon Jan 07 15:20:00 2004 Richard Frith-Macdonald * Makefile: Bump version. * SQLClient.h: Improve documentation. Sat Dec 18 06:00:00 2004 Richard Frith-Macdonald * WebServer.m: Fix bug in substitution of nil values into templates. Add new method to vend static pages. Wed Dec 15 13:10:00 2004 Richard Frith-Macdonald * MySQL.m, Postgres.m, ECPG.pgm: Do NSLog() logging of field information only when debug level is greater than 1. Fri Dec 10 10:50:00 2004 Richard Frith-Macdonald * GNUmakefile: Remove unnecessary libraries from link commands for bundles. On Darwin, specifying these leads to multiply defined symbols when an executable attempts to load the bundle. Fri Nov 19 14:40:00 2004 Richard Frith-Macdonald * WebServer.m: parse basic authentication infor and set it in extra headers in request. * WebServerBundles.m: support handling of paths longer than the ones set for each bundle. Tue Nov 11 14:48:05 2004 Nicola Pero * GNUmakefile (BUNDLE_INSTALL_DIR): install bundles in GNUSTEP_INSTALLATION_DIR, not GNUSTEP_LOCAL_ROOT. Tue Nov 09 10:20:00 2004 Richard Frith-Macdonald * SQLClient.hm: add ([-append:]) method to merge transactions. Thu Oct 28 08:45:00 2004 Richard Frith-Macdonald * WebServer.m: Don't generate alert about connection with empty request if we have lready handled a request and reset. Tue Oct 26 16:50:00 2004 Richard Frith-Macdonald * SQLClient.m: debug and duration logging should be turned off by default ... a different value crept in somehow. Sat Oct 9 14:29:35 2004 Nicola Pero * SQLClient.m ([SQLClient -simpleExecute:]): Fixed logging durations and statements in transactions. Thu Oct 08 10:30:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Add ([-quotef:,...]) to perform efficient quoting of a string produced using printf style format and arguments. Thu Oct 07 10:30:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Optimise timing operations somewhat. Wed Oct 06 15:04:23 2004 Nicola Pero * WebServer.h: Fixed typo in parameter name. Wed Oct 06 13:10:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Allow a database transaction to already have been begun when [SQLTransactiuon-execute] is called, so we can have queries in the same database transaction as a list of statements. Wed Oct 06 06:15:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Make the rollback opoeration a safe no-op if there is no transaction in progress. * Postgres.m: Improve exception text by reporting the offending SQL statement(s). Fri Sep 17 16:55:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: When reporting the duration of a commit or rollback, report text of all the statements in the transaction. Fri Aug 28 09:30:00 2004 Richard Frith-Macdonald * WebServer.[hm]: Add support for limiting maximum number of incoming sessions permitted from mone host. Tue Aug 24 14:30:00 2004 Richard Frith-Macdonald * WebServer.[hm]: Add support for HTTP/1.1 persistent connections. Sun Aug 22 10:35:00 2004 Richard Frith-Macdonald * SQLClient.[hm]: Add ([SQLRecord-dictionary]) and tidy/comment the class a bit better. Sat Aug 07 14:25:00 2004 Richard Frith-Macdonald * WebServer.m: Add session timeouts to kill off idle sessions. Tue Jul 27 17:30:00 2004 Richard Frith-Macdonald * configure.ac: Give more help when postgres is not found. * configure: regenerate Mon Jul 26 09:50:00 2004 Richard Frith-Macdonald * SQLClient.h: Add -transaction method and SQLTransaction class * SQLClient.m: Implement -transaction method and SQLTransaction class to provide a simple convenient mechanism for executing a sequence of statements as a single transaction. Thu Jul 15 09:40:00 2004 Richard Frith-Macdonald * WebServer.m: ([_didRead:]) more informative logging upon reading an unexpected end-of-file Wed Jul 14 12:07:00 2004 Richard Frith-Macdonald * configure.ac: Check for PQfformat in libpq, if it is not there but the library is there, warn that it is too old. Thu Jul 02 17:40:00 2004 Richard Frith-Macdonald * WebServer.m: Add control over character encoding used to interpret form data. Thu Jul 02 13:25:00 2004 Richard Frith-Macdonald * WebServer.m: Fix error response when an exception occurs. Thu Jul 01 18:00:00 2004 Richard Frith-Macdonald * WebServer.m: Make ([setPort:secure:]) return a status. * WebServerBundles.m: Check that web server is able to start. * WebServer.h: ditto Wed Jun 30 05:40:00 2004 Richard Frith-Macdonald * GNUmakefile: Use ./obj as location for library to link, for initial case where we link the bundles before installing the library. * WebServer.m: Add casts to prevent compiler warning. * Postgres.m: Commented out NSLog() left over from debugging. Tue Jun 29 18:10:00 2004 Richard Frith-Macdonald * SQLClient.m: Fix code for retrieving reference name ... look in the config dictionary first, and in user defaults if not found there. * SQLClient.h: Document change. * GNUmakefile: Link bundles with the library to ensure that they find the SQLRecord class when loaded. Mon Jun 28 12:55:00 2004 Richard Frith-Macdonald * WebServer.h: New file. * WebServer.m: New file. * WebServerBundles.m: New file. * SQLClient.h: Mention WebServer. * GNUmakefile: Build WebServer classes. Added framework to make it easy to use SQLClient to produce standalone http/https applications, such as accepting POST'ed records for addition to a database. Fri May 07 09:15:00 2004 Richard Frith-Macdonald Add methods to log duration of any statements over a certain limit. Tidy instance variables ... prefix mprivate ones with underscore. Install header! Thu Apr 29 15:20:00 2004 Richard Frith-Macdonald * SQLClient.h: Fix URLs in documentation as suggested by Adam. * SQLClient.html: regenerate Mon Apr 26 16:20:00 2004 Richard Frith-Macdonald Initial checkin of library. SQLClient-1.9.0/ECPG.pgm000066400000000000000000000623361436027104400145550ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientECPG for GNUStep Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "config.h" #define SQLCLIENT_PRIVATE @public #include "SQLClient.h" @interface SQLClientECPG : SQLClient @end @interface SQLClientECPG(Embedded) - (const char *) blobFromData: (NSData*)data; - (NSData *) dataFromBlob: (const char *)blob; - (BOOL) dbFromDate: (NSDate*)d toBuffer: (char*)b length: (int)l; - (BOOL) dbFromString: (NSString*)s toBuffer: (char*)b length: (int)l; - (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l; - (NSString*) dbToStringFromBuffer: (char*)b length: (int)l; @end /* This looks like a Postgres specific issue/feature/bug - for some * reason, ':' inside a string often causes the string to be * horribly mutilated before being handed to the database * ... probably postgres is trying to replace variables or something * - avoid all these problems by replacing ':' with its octal code * \\072. */ static NSString * hackForPrepare(NSString *s) { NSRange r; r = [s rangeOfString: @":"]; if (r.length > 0) { s = [s stringByReplacingString: @":" withString: @"\\072"]; } return s; } EXEC SQL INCLUDE sql3types; EXEC SQL INCLUDE sqlca; EXEC SQL WHENEVER SQLERROR CALL SQLErrorHandler(); /** * Return YES of the last SQL error indicated we are out of data, * NO otherwise. */ BOOL SQLOutOfData() { if (sqlca.sqlcode == 100) { return YES; } else { return NO; } } /** * This error handler is called for most errors ... so we can get it to * raise an exception for us. */ void SQLErrorHandler() { int code = sqlca.sqlcode; const char *ptr = sqlca.sqlerrm.sqlerrmc; const char *e0 = "'no connection to the server'"; const char *e1 = "Error in transaction processing"; sqlca.sqlcode = 0; // Reset error code NSLog (@"Raising an exception, %d, %s", code, sqlca.sqlerrm.sqlerrmc); if (strncmp(ptr, e0, strlen(e0)) == 0 || strncmp(ptr, e1, strlen(e1)) == 0) { [NSException raise: SQLConnectionException format: @"SQL Error: SQLCODE=(%d): %s", code, ptr]; } else { [NSException raise: SQLException format: @"SQL Error: SQLCODE=(%d): %s", code, ptr]; } } @implementation SQLClientECPG static NSDate *future = nil; + (void) initialize { if (future == nil) { future = [NSCalendarDate dateWithString: @"9999-01-01 00:00:00 +0000" calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; [future retain]; } } - (BOOL) backendConnect { if (connected == NO) { if ([self database] != nil && [self user] != nil && [self password] != nil) { Class c = NSClassFromString(@"CmdClient"); [[self class] purgeConnections: nil]; NS_DURING { EXEC SQL BEGIN DECLARE SECTION; const char *database_c; const char *user_c; const char *password_c; const char *client_c; EXEC SQL END DECLARE SECTION; database_c = [[self database] UTF8String]; user_c = [[self user] UTF8String]; password_c = [[self password] UTF8String]; client_c = [[self clientName] UTF8String]; if (c != 0) { if ([self debugging] > 0) { [self debug: @"Connect to '%@' database %s user %s as %s", [self name], database_c, user_c, client_c]; } } EXEC SQL CONNECT TO :database_c AS :client_c USER :user_c USING :password_c; connected = YES; if (c != 0) { if ([self debugging] > 0) { [self debug: @"Connected to '%@' (%s)", [self name], client_c]; } } EXEC SQL AT :client_c SET AUTOCOMMIT TO ON; // For backwards compat, make this the default EXEC SQL SET CONNECTION TO :client_c; } NS_HANDLER { [self debug: @"Error connecting to '%@' database: %@", [self name], localException]; } NS_ENDHANDLER } else { [self debug: @"Connect to '%@' with no user/password/database configured", [self name]]; } } return connected; } - (void) backendDisconnect { if (connected == YES) { NS_DURING { EXEC SQL BEGIN DECLARE SECTION; const char *client_c; EXEC SQL END DECLARE SECTION; if ([self isInTransaction] == YES) { [self rollback]; } client_c = [[self clientName] UTF8String]; if ([self debugging] > 0) { [self debug: @"Disconnecting client %@", [self clientName]]; } EXEC SQL DISCONNECT :client_c; if ([self debugging] > 0) { [self debug: @"Disconnected client %@", [self clientName]]; } } NS_HANDLER { [self debug: @"Error disconnecting from database (%@): %@", [self clientName], localException]; } NS_ENDHANDLER connected = NO; } } - (NSInteger) backendExecute: (NSArray*)info { EXEC SQL BEGIN DECLARE SECTION; char *statement; char *handle; EXEC SQL END DECLARE SECTION; NSAutoreleasePool *arp = [NSAutoreleasePool new]; unsigned int length; NSString *stmt = [info objectAtIndex: 0]; length = [stmt length]; if (length == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } statement = (char*)[hackForPrepare(stmt) UTF8String]; length = strlen(statement); statement = (char*)[self insertBLOBs: info intoStatement: statement length: length withMarker: "'''" length: 3 giving: &length]; handle = (char*)[[self clientName] UTF8String]; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [arp release]; [NSException raise: SQLException format: @"Unable to connect to '%@' to execute statement %@", [self name], stmt]; } NS_DURING { EXEC SQL PREPARE command from :statement; EXEC SQL AT :handle EXECUTE command; } NS_HANDLER { NSString *n = [localException name]; NSString *msg = [localException reason]; if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } /* * remove line number information from database exception message * since it's meaningless to the developer as it's the line number * in this file rather than the code which is calling us. */ if ([n isEqual: SQLException] == YES || [n isEqual: SQLConnectionException] == YES) { NSRange r; r = [msg rangeOfString: @" in line " options: NSBackwardsSearch]; if (r.length > 0) { msg = [msg substringToIndex: r.location]; localException = [NSException exceptionWithName: n reason: msg userInfo: nil]; } } if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return -1; } static unsigned int trim(char *str) { char *start = str; while (isspace(*str)) { str++; } if (str != start) { strcpy(start, str); } str = start; while (*str != '\0') { str++; } while (str > start && isspace(str[-1])) { *--str = '\0'; } return (str - start); } - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype { EXEC SQL BEGIN DECLARE SECTION; bool aBool; int anInt; int count; int index; int indicator; int type; int length; int octetLength; int precision; int scale; int returnedOctetLength; int dtiCode; char fieldName[120]; char *aString; float aFloat; double aDouble; char *query; char *handle; EXEC SQL END DECLARE SECTION; NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSMutableArray *records; BOOL isOpen = NO; BOOL localTransaction = NO; length = [stmt length]; if (length == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } query = (char*)[hackForPrepare(stmt) UTF8String]; handle = (char*)[[self clientName] UTF8String]; records = [[ltype alloc] initWithCapacity: 32]; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [arp release]; [NSException raise: SQLException format: @"Unable to connect to '%@' to run query %@", [self name], stmt]; } NS_DURING { EXEC SQL ALLOCATE DESCRIPTOR myDesc; EXEC SQL PREPARE myQuery from :query; if ([self isInTransaction] == NO) { EXEC SQL AT :handle BEGIN; localTransaction = YES; } EXEC SQL AT :handle DECLARE myCursor CURSOR FOR myQuery; EXEC SQL AT :handle OPEN myCursor; isOpen = YES; while (1) { EXEC SQL AT :handle FETCH IN myCursor INTO SQL DESCRIPTOR myDesc; if (sqlca.sqlcode) { break; } EXEC SQL GET DESCRIPTOR myDesc :count = COUNT; if (count > 0) { SQLRecord *record; id keys[count]; id values[count]; for (index = 1; index <= count; ++index) { id v; EXEC SQL GET DESCRIPTOR myDesc VALUE :index :indicator = INDICATOR, :length = LENGTH, :fieldName = NAME, :octetLength = OCTET_LENGTH, :precision = PRECISION, :returnedOctetLength = RETURNED_OCTET_LENGTH, :scale = SCALE, :type = TYPE; // printf("%s type:%d scale:%d\n", fieldName, type, scale); if (indicator == -1) { v = [NSNull null]; } else { /* * HACK ... for some reason date/time data seems to * get a negative type returned, so we check any * negative time to see if it is really date/time * and bodg the type code to fit. */ if (type < 0) { EXEC SQL GET DESCRIPTOR myDesc VALUE :index :dtiCode = DATETIME_INTERVAL_CODE; if (dtiCode != SQL3_DDT_ILLEGAL) { type = SQL3_DATE_TIME_TIMESTAMP; } } aString = 0; switch (type) { case SQL3_BOOLEAN: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aBool = DATA; if (aBool == 1) { v = [NSNumber numberWithBool: YES]; } else if (aBool == 0) { v = [NSNumber numberWithBool: NO]; } else { [NSException raise: NSGenericException format: @"Bad bool for '%s' - '%d'", fieldName, aBool]; } break; case SQL3_NUMERIC: case SQL3_DECIMAL: if (scale == 0) { EXEC SQL GET DESCRIPTOR myDesc VALUE :index :anInt = DATA; v = [NSNumber numberWithInt: anInt]; } else { EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aFloat = DATA; v = [NSNumber numberWithFloat: aFloat]; } break; case SQL3_INTEGER: case SQL3_SMALLINT: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :anInt = DATA; v = [NSNumber numberWithInt: anInt]; break; case SQL3_FLOAT: case SQL3_REAL: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aFloat = DATA; v = [NSNumber numberWithFloat: aFloat]; break; case SQL3_DOUBLE_PRECISION: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aDouble = DATA; v = [NSNumber numberWithDouble: aDouble]; break; case SQL3_DATE_TIME_TIMESTAMP: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :dtiCode = DATETIME_INTERVAL_CODE, :aString = DATA; v = [self dbToDateFromBuffer: aString length: trim(aString)]; free(aString); break; case SQL3_INTERVAL: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aString = DATA; trim(aString); v = [NSString stringWithUTF8String: aString]; free(aString); break; case SQL3_CHARACTER: case SQL3_CHARACTER_VARYING: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aString = DATA; if (_shouldTrim) { trim(aString); } v = [NSString stringWithUTF8String: aString]; free(aString); break; case -17: /* * HACK ... BYTEA type determined by experiment. * who knows how/why this might change. */ EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aString = DATA; v = [self dataFromBlob: aString]; free(aString); break; case -20: /* * HACK ... by experiment this seems to be an * integer returned by a function. */ EXEC SQL GET DESCRIPTOR myDesc VALUE :index :anInt = DATA; v = [NSNumber numberWithInt: anInt]; break; default: EXEC SQL GET DESCRIPTOR myDesc VALUE :index :aString = DATA; if (_shouldTrim) { trim(aString); } v = [NSString stringWithUTF8String: aString]; free(aString); if ([self debugging] > 0) { [self debug: @"Unknown data type (%d) for '%s' ... '%@'", type, fieldName, v]; } break; } } values[index-1] = v; keys[index-1] = [NSString stringWithUTF8String: fieldName]; } record = [rtype newWithValues: values keys: keys count: count]; [records addObject: record]; [record release]; } } isOpen = NO; EXEC SQL AT :handle CLOSE myCursor; if (localTransaction == YES) { EXEC SQL AT :handle COMMIT; localTransaction = NO; } EXEC SQL DEALLOCATE DESCRIPTOR myDesc; } NS_HANDLER { NSString *n = [localException name]; NSString *msg = [localException reason]; [records release]; records = nil; NS_DURING { if (isOpen == YES) { EXEC SQL AT :handle CLOSE myCursor; } if (localTransaction == YES) { EXEC SQL AT :handle ROLLBACK; } } NS_HANDLER { NSString *e = [localException name]; if ([e isEqual: SQLConnectionException] == YES) { [self disconnect]; } } NS_ENDHANDLER if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } /* * remove line number information from database exception message * since it's meaningless to the developer as it's the line number * in this file rather than the code which is calling us. */ if ([n isEqual: SQLException] == YES || [n isEqual: SQLConnectionException] == YES) { NSRange r; r = [msg rangeOfString: @" in line " options: NSBackwardsSearch]; if (r.length > 0) { msg = [msg substringToIndex: r.location]; localException = [NSException exceptionWithName: n reason: msg userInfo: nil]; } } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return [records autorelease]; } - (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf { const unsigned char *src = [blob bytes]; unsigned sLen = [blob length]; unsigned char *ptr = (unsigned char*)buf; unsigned length = 0; unsigned i; ptr[length++] = '\''; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126 || c == ':') { ptr[length] = '\\'; ptr[length+1] = '\\'; ptr[length + 4] = (c & 7) + '0'; c >>= 3; ptr[length + 3] = (c & 7) + '0'; c >>= 3; ptr[length + 2] = (c & 7) + '0'; length += 5; } else if (c == '\\') { ptr[length++] = '\\'; ptr[length++] = '\\'; ptr[length++] = '\\'; ptr[length++] = '\\'; } else if (c == '\'') { ptr[length++] = '\\'; ptr[length++] = '\''; } else { ptr[length++] = c; } } ptr[length++] = '\''; return length; } - (unsigned) lengthOfEscapedBLOB: (NSData*)blob { unsigned int sLen = [blob length]; unsigned char *src = (unsigned char*)[blob bytes]; unsigned int length = 2; unsigned int i; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126 || c == ':') { length += 5; } else if (c == '\\') { length += 4; } else if (c == '\'') { length += 2; } else { length += 1; } } return length; } - (const char *) blobFromData: (NSData*)data { NSMutableData *md; unsigned sLen = [data length]; unsigned char *src = (unsigned char*)[data bytes]; unsigned dLen = 0; unsigned char *dst; unsigned i; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126) { dLen += 4; } else if (c == 92) { dLen += 2; } else { dLen += 1; } } md = [NSMutableData dataWithLength: dLen + 1]; dst = (unsigned char*)[md mutableBytes]; dLen = 0; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126) { dst[dLen] = '\\'; dst[dLen + 3] = (c & 7) + '0'; c >>= 3; dst[dLen + 2] = (c & 7) + '0'; c >>= 3; dst[dLen + 1] = (c & 7) + '0'; dLen += 4; } else if (c == 92) { dst[dLen++] = '\\'; dst[dLen++] = '\\'; } else { dst[dLen++] = c; } } dst[dLen] = '\0'; return (const char*)dst; // Owned by autoreleased NSMutableData } - (NSData *) dataFromBlob: (const char *)blob { NSMutableData *md; unsigned sLen = strlen(blob == 0 ? "" : blob); unsigned dLen = 0; unsigned char *dst; unsigned i; for (i = 0; i < sLen; i++) { unsigned c = blob[i]; dLen++; if (c == '\\') { c = blob[++i]; if (c != '\\') { i += 2; // Skip 2 digits octal } } } md = [NSMutableData dataWithLength: dLen]; dst = (unsigned char*)[md mutableBytes]; dLen = 0; for (i = 0; i < sLen; i++) { unsigned c = blob[i]; if (c == '\\') { c = blob[++i]; if (c != '\\') { c = c - '0'; c <<= 3; c += blob[++i] - '0'; c <<= 3; c += blob[++i] - '0'; } } dst[dLen++] = c; } return md; } - (BOOL) dbFromDate: (NSDate*)d toBuffer: (char*)b length: (int)l { NSString *s; /* * Ensure we have a four digit year. */ if ([d timeIntervalSinceDate: future] > 0) { d = future; } s = [d descriptionWithCalendarFormat: @"%Y-%m-%d %H:%M:%S %z" timeZone: nil locale: nil]; return [self dbFromString: s toBuffer: b length: l]; } - (BOOL) dbFromString: (NSString*)s toBuffer: (char*)b length: (int)l { NSData *d; BOOL ok = YES; unsigned size = l; if (l <= 0) { [NSException raise: NSInvalidArgumentException format: @"-%@: length too small (%d)", NSStringFromSelector(_cmd), l]; } if (b == 0) { [NSException raise: NSInvalidArgumentException format: @"-%@: buffer is null", NSStringFromSelector(_cmd)]; } if (s == nil) { s = @""; } d = [s dataUsingEncoding: NSUTF8StringEncoding]; if (l < (int)[d length]) { /* * As the data is UTF8, we need to avoid truncating in the * middle of a multibyte character, so we shorten the * original string and reconvert to UTF8 until we find a * string that fits. */ if ((int)[s length] > l) { s = [s substringToIndex: l]; d = [s dataUsingEncoding: NSUTF8StringEncoding]; } while ((int)[d length] > l) { s = [s substringToIndex: [s length] - 1]; d = [s dataUsingEncoding: NSUTF8StringEncoding]; } ok = NO; } size = [d length]; memcpy(b, (const char*)[d bytes], size); /* * Pad with nuls and ensure there is a nul terminator. */ while ((int)size <= l) { b[size++] = '\0'; } return ok; } - (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l { char buf[l+32]; /* Allow space to expand buffer. */ NSCalendarDate *d; BOOL milliseconds = NO; BOOL timezone = NO; NSString *s; int i; int e; memcpy(buf, b, l); b = buf; /* * Find end of string. */ for (i = 0; i < l; i++) { if (b[i] == '\0') { l = i; break; } } while (l > 0 && isspace(b[l-1])) { l--; } b[l] = '\0'; if (l == 10) { s = [NSString stringWithUTF8String: b]; return [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d" locale: nil]; } i = l; /* Convert +/-HH:SS timezone to +/-HHSS */ if (i > 5 && b[i-3] == ':' && (b[i-6] == '+' || b[i-6] == '-')) { b[i-3] = b[i-2]; b[i-2] = b[i-1]; b[--i] = '\0'; } while (i-- > 0) { if (b[i] == '+' || b[i] == '-') { break; } if (b[i] == ':' || b[i] == ' ') { i = 0; break; /* No time zone found */ } } if (i == 0) { e = l; } else { timezone = YES; e = i; if (isdigit(b[i-1])) { /* * Make space between seconds and timezone. */ memmove(&b[i+1], &b[i], l - i); b[i++] = ' '; b[++l] = '\0'; } /* * Ensure we have a four digit timezone value. */ if (isdigit(b[i+1]) && isdigit(b[i+2])) { if (b[i+3] == '\0') { // Two digit time zone ... append zero minutes b[l++] = '0'; b[l++] = '0'; b[l] = '\0'; } else if (b[i+3] == ':') { // Zone with colon before minutes ... remove it b[i+3] = b[i+4]; b[i+4] = b[i+5]; b[--l] = '\0'; } } } /* kludge for timestamps with fractional second information. * Force it to 3 digit millisecond */ while (i-- > 0) { if (b[i] == '.') { milliseconds = YES; i++; if (!isdigit(b[i])) { memmove(&b[i+3], &b[i], e-i); l += 3; memcpy(&b[i], "000", 3); } i++; if (!isdigit(b[i])) { memmove(&b[i+2], &b[i], e-i); l += 2; memcpy(&b[i], "00", 2); } i++; if (!isdigit(b[i])) { memmove(&b[i+1], &b[i], e-i); l += 1; memcpy(&b[i], "0", 1); } i++; break; } } if (i > 0 && i < e) { memmove(&b[i], &b[e], l - e); l -= (e - i); } b[l] = '\0'; if (l == 0) { return nil; } s = [NSString stringWithUTF8String: b]; if (YES == timezone) { if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F %z" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; } } else { if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S" locale: nil]; } } [d setCalendarFormat: @"%Y-%m-%d %H:%M:%S %z"]; return d; } - (NSString*) dbToStringFromBuffer: (char*)b length: (int)l { NSData *d; NSString *s; /* * Database fields are padded to the full field size with spaces or nuls ... * we need to remove that padding before placing in a string. */ while (l > 0 && b[l-1] <= ' ') { l--; } d = [[NSData alloc] initWithBytes: b length: l]; s = [[NSString alloc] initWithData: d encoding: NSUTF8StringEncoding]; [d release]; return [s autorelease]; } @end SQLClient-1.9.0/GNUmakefile000066400000000000000000000163451436027104400154030ustar00rootroot00000000000000 ifeq ($(GNUSTEP_MAKEFILES),) GNUSTEP_MAKEFILES := $(shell gnustep-config --variable=GNUSTEP_MAKEFILES 2>/dev/null) ifeq ($(GNUSTEP_MAKEFILES),) $(warning ) $(warning Unable to obtain GNUSTEP_MAKEFILES setting from gnustep-config!) $(warning Perhaps gnustep-make is not properly installed,) $(warning so gnustep-config is not in your PATH.) $(warning ) $(warning Your PATH is currently $(PATH)) $(warning ) endif endif ifeq ($(GNUSTEP_MAKEFILES),) $(error You need to set GNUSTEP_MAKEFILES before compiling!) endif include $(GNUSTEP_MAKEFILES)/common.make # Force sequential build to prevent different versions of the same # bundle overwriting each other's temporary files during building. GNUSTEP_MAKE_PARALLEL_BUILDING=no -include config.make PACKAGE_NAME = SQLClient PACKAGE_VERSION = 1.9.0 CVS_MODULE_NAME = gnustep/dev-libs/SQLClient CVS_TAG_NAME = SQLClient SVN_BASE_URL=svn+ssh://svn.gna.org/svn/gnustep/libs SVN_MODULE_NAME=sqlclient NEEDS_GUI = NO TEST_TOOL_NAME= LIBRARY_NAME=SQLClient DOCUMENT_NAME=SQLClient SQLClient_INTERFACE_VERSION=1.9 SQLClient_OBJC_FILES = SQLClient.m SQLClientPool.m SQLClient_LIBRARIES_DEPEND_UPON = -lPerformance $(FND_LIBS) $(OBJC_LIBS) SQLClient_HEADER_FILES = SQLClient.h SQLClient_AGSDOC_FILES = SQLClient.h SQLClient_AGSDOC_FLAGS = -WordMap '{SQLCLIENT_PRIVATE="";}' # Optional Java wrappers for the library JAVA_WRAPPER_NAME = SQLClient SQLClient_HEADER_FILES_INSTALL_DIR = SQLClient BUNDLE_NAME= BUNDLE_INSTALL_DIR=$(GNUSTEP_BUNDLES)/SQLClient$(SQLClient_INTERFACE_VERSION) # In some systems and situations the dynamic linker needs to haved the # SQLClient, gnustep-base, and objc libraries explicityly linked into # the bundle, but in others it requires them to not be linked. # To handle that, we create two versions of each bundle, the seond version # has _libs appended to the bundle name, and has the extra libraries linked. ifeq ($(LINKSQLCLIENT),) LINKSQLCLIENT=0 ifeq ($(findstring darwin, $(GNUSTEP_TARGET_OS)), darwin) LINKSQLCLIENT=1 endif endif ifneq ($(ECPG),) ifeq ($(LINKSQLCLIENT),1) BUNDLE_NAME += ECPG ECPG_OBJC_FILES = ECPG.m ECPG_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) ECPG_BUNDLE_LIBS += -lSQLClient -lecpg ECPG_PRINCIPAL_CLASS = SQLClientECPG else BUNDLE_NAME += ECPG ECPG_OBJC_FILES = ECPG.m ECPG_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) ECPG_BUNDLE_LIBS += -lecpg ECPG_PRINCIPAL_CLASS = SQLClientECPG BUNDLE_NAME += ECPG_libs ECPG_libs_OBJC_FILES = ECPG.m ECPG_libs_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) ECPG_libs_BUNDLE_LIBS += -lSQLClient -lPerformance \ $(FND_LIBS) $(OBJC_LIBS) -lecpg ECPG_libs_PRINCIPAL_CLASS = SQLClientECPG_libs endif TEST_TOOL_NAME += testECPG testECPG_OBJC_FILES = testECPG.m testECPG_LIB_DIRS += -L./$(GNUSTEP_OBJ_DIR) testECPG_TOOL_LIBS += -lSQLClient -lPerformance endif ifneq ($(POSTGRES),) ifeq ($(LINKSQLCLIENT),1) BUNDLE_NAME += Postgres Postgres_OBJC_FILES = Postgres.m Postgres_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) Postgres_BUNDLE_LIBS += -lSQLClient -lpq Postgres_PRINCIPAL_CLASS = SQLClientPostgres else BUNDLE_NAME += Postgres Postgres_OBJC_FILES = Postgres.m Postgres_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) Postgres_BUNDLE_LIBS += -lpq Postgres_PRINCIPAL_CLASS = SQLClientPostgres BUNDLE_NAME += Postgres_libs Postgres_libs_OBJC_FILES = Postgres.m Postgres_libs_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) Postgres_libs_BUNDLE_LIBS += -lSQLClient -lPerformance \ $(FND_LIBS) $(OBJC_LIBS) -lpq Postgres_libs_PRINCIPAL_CLASS = SQLClientPostgres_libs endif TEST_TOOL_NAME += testPostgres testPostgres_OBJC_FILES = testPostgres.m testPostgres_LIB_DIRS += -L./$(GNUSTEP_OBJ_DIR) testPostgres_TOOL_LIBS += -lSQLClient -lPerformance endif ifneq ($(JDBC),) ifeq ($(LINKSQLCLIENT),1) BUNDLE_NAME += JDBC JDBC_OBJC_FILES = JDBC.m JDBC_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) $(JDBC_VM_LIBDIRS) JDBC_BUNDLE_LIBS += -lSQLClient $(JDBC_VM_LIBS) JDBC_PRINCIPAL_CLASS = SQLClientJDBC else BUNDLE_NAME += JDBC JDBC_OBJC_FILES = JDBC.m JDBC_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) $(JDBC_VM_LIBDIRS) JDBC_BUNDLE_LIBS += $(JDBC_VM_LIBS) JDBC_PRINCIPAL_CLASS = SQLClientJDBC BUNDLE_NAME += JDBC_libs JDBC_libs_OBJC_FILES = JDBC.m JDBC_libs_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) $(JDBC_VM_LIBDIRS) JDBC_libs_BUNDLE_LIBS += -lSQLClient -lPerformance \ $(FND_LIBS) $(OBJC_LIBS) $(JDBC_VM_LIBS) JDBC_libs_PRINCIPAL_CLASS = SQLClientJDBC_libs endif TEST_TOOL_NAME += testJDBC testJDBC_OBJC_FILES = testJDBC.m testJDBC_LIB_DIRS += -L./$(GNUSTEP_OBJ_DIR) testJDBC_TOOL_LIBS += -lSQLClient -lPerformance endif ifneq ($(MYSQL),) ifeq ($(LINKSQLCLIENT),1) BUNDLE_NAME += MySQL MySQL_OBJC_FILES = MySQL.m MySQL_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) MySQL_BUNDLE_LIBS += -lSQLClient -lmysqlclient MySQL_PRINCIPAL_CLASS = SQLClientMySQL else BUNDLE_NAME += MySQL MySQL_OBJC_FILES = MySQL.m MySQL_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) MySQL_BUNDLE_LIBS += -lmysqlclient MySQL_PRINCIPAL_CLASS = SQLClientMySQL BUNDLE_NAME += MySQL_libs MySQL_libs_OBJC_FILES = MySQL.m MySQL_libs_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) MySQL_libs_BUNDLE_LIBS += -lSQLClient -lPerformance \ $(FND_LIBS) $(OBJC_LIBS) -lmysqlclient MySQL_libs_PRINCIPAL_CLASS = SQLClientMySQL_libs endif TEST_TOOL_NAME += testMySQL testMySQL_OBJC_FILES = testMySQL.m testMySQL_LIB_DIRS += -L./$(GNUSTEP_OBJ_DIR) testMySQL_TOOL_LIBS += -lSQLClient -lPerformance endif ifneq ($(SQLITE),) ifeq ($(LINKSQLCLIENT),1) BUNDLE_NAME += SQLite SQLite_OBJC_FILES = SQLite.m SQLite_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) SQLite_BUNDLE_LIBS += -lSQLClient -lsqlite3 SQLite_PRINCIPAL_CLASS = SQLClientSQLite else BUNDLE_NAME += SQLite SQLite_OBJC_FILES = SQLite.m SQLite_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) SQLite_BUNDLE_LIBS += -lsqlite3 SQLite_PRINCIPAL_CLASS = SQLClientSQLite BUNDLE_NAME += SQLite_libs SQLite_libs_OBJC_FILES = SQLite.m SQLite_libs_LIB_DIRS = -L./$(GNUSTEP_OBJ_DIR) SQLite_libs_BUNDLE_LIBS += -lSQLClient -lPerformance \ $(FND_LIBS) $(OBJC_LIBS) -lsqlite3 SQLite_libs_PRINCIPAL_CLASS = SQLClientSQLite_libs endif TEST_TOOL_NAME += testSQLite testSQLite_OBJC_FILES = testSQLite.m testSQLite_LIB_DIRS += -L./$(GNUSTEP_OBJ_DIR) testSQLite_TOOL_LIBS += -lSQLClient -lPerformance endif ifneq ($(ORACLE_HOME),) BUNDLE_NAME += Oracle Oracle_OBJC_FILES = Oracle.m Oracle_LIB_DIRS = -L$(ORACLE_HOME)/lib -L./$(GNUSTEP_OBJ_DIR) \ $(shell cat $(ORACLE_HOME)/lib/ldflags) Oracle_BUNDLE_LIBS += -lclntsh \ $(shell cat $(ORACLE_HOME)/lib/sysliblist) \ -ldl -lm Oracle_PRINCIPAL_CLASS = SQLClientOracle BUNDLE_NAME += Oracle_libs Oracle_libs_OBJC_FILES = Oracle.m Oracle_libs_LIB_DIRS = -L$(ORACLE_HOME)/lib -L./$(GNUSTEP_OBJ_DIR) \ $(shell cat $(ORACLE_HOME)/lib/ldflags) Oracle_libs_BUNDLE_LIBS += -lclntsh \ -lSQLClient -lPerformance $(FND_LIBS) $(OBJC_LIBS) \ $(shell cat $(ORACLE_HOME)/lib/sysliblist) \ -ldl -lm Oracle_libs_PRINCIPAL_CLASS = SQLClientOracle_libs endif -include GNUmakefile.preamble include $(GNUSTEP_MAKEFILES)/library.make include $(GNUSTEP_MAKEFILES)/bundle.make # If JIGS is installed, automatically generate Java wrappers as well. # Because of the '-', should not complain if java-wrapper.make can't be # found ... simply skip generation of java wrappers in that case. -include $(GNUSTEP_MAKEFILES)/java-wrapper.make include $(GNUSTEP_MAKEFILES)/test-tool.make include $(GNUSTEP_MAKEFILES)/documentation.make -include GNUmakefile.postamble SQLClient-1.9.0/GNUmakefile.postamble000066400000000000000000000023751436027104400173660ustar00rootroot00000000000000# # Makefile.postamble # # Project specific makefile rules # # Uncomment the targets you want. # The double colons (::) are important, do not make them single colons # otherwise the normal makefile rules will not be performed. # ifneq ($(ECPG),) %.m: %.pgm ecpg -o $@ $< $(ADDITIONAL_INCLUDE_DIRS) .PRECIOUS: %.m endif ifneq ($(ORACLE_HOME),) %.m: %.pm proc iname=$< oname=$@ mode=ansi parse=none .PRECIOUS: %.m endif # Things to do before compiling # before-all:: # Things to do after compiling # after-all:: # Things to do before installing # before-install:: # Things to do after installing # after-install:: # Things to do before uninstalling # before-uninstall:: # Things to do after uninstalling # after-uninstall:: # Things to do before cleaning # before-clean:: # Things to do after cleaning # after-clean:: # Things to do before distcleaning # before-distclean:: # Things to do after distcleaning after-distclean:: -rm -f ECPG.m Oracle.m -rm -f config.h config.make config.log config.status -rm -rf autom4te.cache # Things to do before checking # before-check:: # Things to do after checking # after-check:: config.make: config.status if [ -x config.status ]; then \ ./config.status --recheck; \ else \ ./configure; \ fi SQLClient-1.9.0/GNUmakefile.preamble000066400000000000000000000020221436027104400171540ustar00rootroot00000000000000# # Makefile.preamble # # Project specific makefile variables, and additional # # Do not put any Makefile rules in this file, instead they should # be put into Makefile.postamble. # # # Flags dealing with compiling and linking # # Additional flags to pass to the preprocessor ADDITIONAL_CPPFLAGS += -DSOVERSION=\"$(SQLClient_INTERFACE_VERSION)\" # Additional flags to pass to the Objective-C compiler # ADDITIONAL_OBJCFLAGS += # Additional flags to pass to the C compiler # ADDITIONAL_CFLAGS += # Additional include directories the compiler should search # ADDITIONAL_INCLUDE_DIRS += # Additional LDFLAGS to pass to the linker # ADDITIONAL_LDFLAGS += # Additional library directories the linker should search # ADDITIONAL_LIB_DIRS += # Additional libraries when linking tools # ADDITIONAL_TOOL_LIBS += # Additional libraries when linking applications # ADDITIONAL_GUI_LIBS += # # Flags dealing with installing and uninstalling # # Additional directories to be created during installation # ADDITIONAL_INSTALL_DIRS += SQLClient-1.9.0/GNUmakefile.wrapper.objc.preamble000066400000000000000000000001321436027104400215470ustar00rootroot00000000000000LIBRARIES_DEPEND_UPON += -lPerformance.A ADDITIONAL_LIB_DIRS = -L../../$(GNUSTEP_OBJ_DIR) SQLClient-1.9.0/JDBC.m000066400000000000000000001323261436027104400142070ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientJDBC for GNUStep Copyright (C) 2006 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: August 2006 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date: 2006-06-04 10:19:28 +0100 (Sun, 04 Jun 2006) $ $Revision: 23028 $ */ #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #include "config.h" #define SQLCLIENT_PRIVATE @public #include "SQLClient.h" @interface _JDBCTransaction : SQLTransaction @end #include static NSString *JDBCException = @"SQLClientJDBCException"; /* * Cache connection information */ typedef struct { jobject connection; jmethodID commit; jmethodID rollback; jmethodID prepare; jobject statement; jmethodID executeUpdate; jmethodID executeQuery; jmethodID addBatch; jmethodID clearBatch; jmethodID executeBatch; } JInfo; /* SQLClientJVM shamelessly stolen from JIGS ... written by Nicola Pero * and copyright the Free Software Foundation. */ @interface SQLClientJVM : NSObject { } + (void) startVirtualMachineWithClassPath: (NSString *)classPath libraryPath: (NSString *)libraryPath; + (void) destroyVirtualMachine; + (BOOL) isVirtualMachineRunning; + (NSString *) defaultClassPath; + (NSString *) defaultLibraryPath; + (void) attachCurrentThread; + (void) detachCurrentThread; + (void) registerJavaVM: (JavaVM *)javaVMHandle; @end /* * A fast function to get the (JNIEnv *) variable. */ static JNIEnv *SQLClientJNIEnv (); static JavaVM *SQLClientJavaVM = NULL; /* * Return the (JNIEnv *) associated with the current thread, * or NULL if no java virtual machine is running (or if the thread * is not attached to the JVM). * * NB: This function performs a call. Better use your (JNIEnv *) if * you already have it. * */ JNIEnv *SQLClientJNIEnv () { JNIEnv *penv; if ((*SQLClientJavaVM)->GetEnv (SQLClientJavaVM, (void **)&penv, JNI_VERSION_1_2) == JNI_OK) { return penv; } else { return NULL; } } @implementation SQLClientJVM (GNUstepInternals) + (void) _attachCurrentThread: (NSNotification *)not { [self attachCurrentThread]; } + (void) _detachCurrentThread: (NSNotification *)not { [self detachCurrentThread]; } @end @implementation SQLClientJVM + (void) startVirtualMachineWithClassPath: (NSString *)classPath libraryPath: (NSString *)libraryPath { JavaVMInitArgs jvm_args; JavaVMOption options[32]; int args = 0; jint result; JNIEnv *env; NSString *path; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; if (SQLClientJavaVM != NULL) { [NSException raise: NSGenericException format: @"Only one Java Virtual Machine " @"can be running at each time"]; } // If we don't pass these options, it assumes they are really @"" if (classPath == nil) { classPath = [self defaultClassPath]; if (classPath == nil) { classPath = @""; } } if (libraryPath == nil) { libraryPath = [self defaultLibraryPath]; if (libraryPath == nil) { libraryPath = @""; } } path = [NSString stringWithFormat: @"-Djava.library.path=%@", libraryPath]; options[args].optionString = strdup([path UTF8String]); options[args++].extraInfo = 0; path = [NSString stringWithFormat: @"-Djava.class.path=%@", classPath]; options[args].optionString = strdup([path UTF8String]); options[args++].extraInfo = 0; path = [NSString stringWithFormat: @"-Xbootclasspath/a:%@", classPath]; options[args].optionString = strdup([path UTF8String]); options[args++].extraInfo = 0; options[args].optionString = "-verbose:class,jni"; options[args++].extraInfo = 0; jvm_args.nOptions = args; jvm_args.version = JNI_VERSION_1_2; jvm_args.options = options; jvm_args.ignoreUnrecognized = JNI_FALSE; result = JNI_CreateJavaVM (&SQLClientJavaVM, (void **)&env, &jvm_args); if (result < 0) { [NSException raise: NSGenericException format: @"Could not start Java Virtual Machine"]; } /* Whenever a thread start or ends, we want to automatically attach or detach it to/from the JVM */ [nc addObserver: self selector: @selector (_attachCurrentThread:) name: NSThreadDidStartNotification object: nil]; [nc addObserver: self selector: @selector (_detachCurrentThread:) name: NSThreadWillExitNotification object: nil]; return; } + (void) destroyVirtualMachine { jint result; if (SQLClientJavaVM == NULL) { [NSException raise: NSGenericException format: @"destroyJVM called without a JVM running"]; } result = (*SQLClientJavaVM)->DestroyJavaVM (SQLClientJavaVM); if (result < 0) { [NSException raise: NSGenericException format: @"Could not destroy Java Virtual Machine"]; } else { SQLClientJavaVM = NULL; } } + (BOOL) isVirtualMachineRunning { if (SQLClientJavaVM == NULL) { return NO; } else { return YES; } } + (NSString *) defaultClassPath { NSDictionary *environment = [[NSProcessInfo processInfo] environment]; return [environment objectForKey: @"CLASSPATH"]; } + (NSString *) defaultLibraryPath { NSDictionary *environment = [[NSProcessInfo processInfo] environment]; return [environment objectForKey: @"LD_LIBRARY_PATH"]; } + (void) attachCurrentThread { static int count = 0; JNIEnv *env; JavaVMAttachArgs args; jint result; if (SQLClientJavaVM == NULL) { /* No JVM - nothing to do */ return; } if (SQLClientJNIEnv () != NULL) { /* The thread is already attached */ return; } { NSAutoreleasePool *pool = [NSAutoreleasePool new]; args.version = JNI_VERSION_1_2; args.name = (char *)[[NSString stringWithFormat: @"GNUstepThread-%d", count] cString]; args.group = NULL; result = (*SQLClientJavaVM)->AttachCurrentThread (SQLClientJavaVM, (void **)&env, &args); [pool release]; } if (result < 0) { [NSException raise: NSGenericException format: @"Could not attach thread to the Java VM"]; } count++; if (count > 100000) { /* Duplicated names shouldn't cause any problem */ count = 0; } return; } + (void) detachCurrentThread { jint result; if (SQLClientJavaVM == NULL) { /* No JVM - nothing to do */ return; } if (SQLClientJNIEnv () == NULL) { /* The thread is not attached */ return; } result = (*SQLClientJavaVM)->DetachCurrentThread (SQLClientJavaVM); if (result < 0) { [NSException raise: NSGenericException format: @"Could not detach thread from the Java VM"]; } return; } + (void) registerJavaVM: (JavaVM *)javaVMHandle { if (javaVMHandle == NULL) { [NSException raise: NSInvalidArgumentException format: @"Trying to register a NULL Java VM"]; } if (SQLClientJavaVM != NULL) { if (javaVMHandle == SQLClientJavaVM) { return; } else { [NSException raise: NSGenericException format: @"Trying to register a Java VM " @"while one is already running"]; } } SQLClientJavaVM = javaVMHandle; // Safety check. If javaVMHandle is invalid, the following will crash // your app. The app would crash anyway later on, so it's better to crash // it here, where it is easier to debug. SQLClientJNIEnv (); return; } @end static jstring JStringFromNSString (JNIEnv *env, NSString *string) { jstring javaString; int length = [string length]; /* We allocate strings of up to 10k on the stack - others using malloc. */ if (length < 10000) { unichar uniString[length]; // Get a unicode representation of the string in the buffer [string getCharacters: uniString]; // Create a java string using the buffer javaString = (*env)->NewString (env, uniString, length); // NB: if javaString is NULL, an exception has been thrown. } else { unichar *uniString; uniString = malloc (sizeof (unichar) * length); [string getCharacters: uniString]; javaString = (*env)->NewString (env, uniString, length); free (uniString); } return javaString; } static NSString* NSStringFromJString (JNIEnv *env, jstring string) { unichar *uniString; jsize length; NSString *gnustepString; // Get a Unicode string from the jstring uniString = (unichar *)(*env)->GetStringChars (env, string, NULL); if (uniString == NULL) { // OutOfMemoryError thrown return NULL; } // Get the Unicode string length length = (*env)->GetStringLength (env, string); // Create a GNUstep string from the Unicode string gnustepString = [NSString stringWithCharacters: uniString length: length]; // Release the temporary string (*env)->ReleaseStringChars (env, string, uniString); return gnustepString; } static NSData * NSDataFromByteArray (JNIEnv *env, jbyteArray array) { NSData *returnData; jbyte *bytes; unsigned length; length = (*env)->GetArrayLength (env, array); bytes = (*env)->GetByteArrayElements (env, array, NULL); if (bytes == NULL) { /* OutOfMemoryError */ return nil; } returnData = [NSData dataWithBytes: bytes length: length]; (*env)->ReleaseByteArrayElements (env, array, bytes, 0); return returnData; } static jbyteArray ByteArrayFromNSData (JNIEnv *env, NSData *data) { const jbyte *bytes; unsigned length; jbyteArray javaArray; length = [data length]; bytes = [data bytes]; javaArray = (*env)->NewByteArray (env, length); if (javaArray == NULL) { /* OutOfMemory exception thrown */ return NULL; } (*env)->SetByteArrayRegion (env, javaArray, 0, length, (jbyte *)bytes); if ((*env)->ExceptionCheck (env)) { /* No reason for this to happen - except a bug in NSData */ return NULL; } return javaArray; } static NSString *JExceptionClear (JNIEnv *env) { NSString *desc = nil; jthrowable exc = (*env)->ExceptionOccurred (env); if (exc != NULL) { static jclass java_lang_Exception = NULL; jmethodID jid = NULL; jstring jstr = NULL; // (*env)->ExceptionDescribe (env); // We need to clear the exception before doing anything else. (*env)->ExceptionClear (env); java_lang_Exception = (*env)->FindClass(env, "java/lang/Exception"); if (java_lang_Exception == NULL) { (*env)->DeleteLocalRef (env, exc); (*env)->ExceptionDescribe (env); desc = @"Could not get global reference to " @"java/lang/Exception to describe exception"; goto done; } jid = (*env)->GetMethodID (env, java_lang_Exception, "getMessage", "()Ljava/lang/String;"); if (jid == NULL) { (*env)->DeleteLocalRef (env, exc); desc = @"Could not get the jmethodID of getMessage" @"of java/lang/Exception to describe exception"; goto done; } if ((*env)->PushLocalFrame (env, 1) < 0) { (*env)->DeleteLocalRef (env, exc); (*env)->ExceptionDescribe (env); desc = @"Could not create enough JNI local references " @"to get a description of the exception"; goto done; } // Get the message jstr = (*env)->CallObjectMethod (env, exc, jid); if ((*env)->ExceptionOccurred (env)) { (*env)->ExceptionDescribe (env); (*env)->PopLocalFrame (env, NULL); desc = @"Exception occurred while getting a description of exception"; goto done; } (*env)->DeleteLocalRef (env, exc); if ((*env)->ExceptionOccurred (env)) { (*env)->ExceptionDescribe (env); (*env)->PopLocalFrame (env, NULL); desc = @"Exception occurred while getting a description of exception"; goto done; } if (jstr == NULL) // Oh oh - something really wrong here { (*env)->PopLocalFrame (env, NULL); desc = @"NULL description of exception"; goto done; } desc = NSStringFromJString (env, jstr); if (desc == nil) { (*env)->PopLocalFrame (env, NULL); desc = @"Exception while converting string of exception"; } (*env)->PopLocalFrame (env, NULL); } done: return desc; } // Throw an exception if one occurred static void JException (JNIEnv *env) { NSString *text = JExceptionClear (env); if (text != nil) { [NSException raise: JDBCException format: @"%@", text]; } } static NSDate* NSDateFromNSString (NSString *s) { NSDate *d; char b[32]; BOOL milliseconds = NO; int l; int i; strcpy(b, [s UTF8String]); l = strlen(b); for (i = 0; i < l; i++) { if (b[i] == '\0') { l = i; break; } } while (l > 0 && isspace(b[l-1])) { l--; } b[l] = '\0'; if (l == 10) { s = [NSString stringWithUTF8String: b]; return [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d" locale: nil]; } else { int e; /* If it's a simple date (YYYY-MM-DD) append time for start of day. */ if (l == 10) { strcat(b, " 00:00:00 +0000"); l += 15; } i = l; while (i-- > 0) { if (b[i] == '+' || b[i] == '-') { break; } if (b[i] == ':' || b[i] == ' ') { i = 0; break; /* No time zone found */ } } if (i == 0) { /* A date and time without a timezone ... assume gmt */ strcpy(b + l, " +0000"); i = l + 1; l += 6; } e = i; if (isdigit(b[i-1])) { /* * Make space between seconds and timezone. */ memmove(&b[i+1], &b[i], l - i); b[i++] = ' '; b[++l] = '\0'; } /* * Ensure we have a four digit timezone value. */ if (isdigit(b[i+1]) && isdigit(b[i+2])) { if (b[i+3] == '\0') { // Two digit time zone ... append zero minutes b[l++] = '0'; b[l++] = '0'; b[l] = '\0'; } else if (b[i+3] == ':') { // Zone with colon before minutes ... remove it b[i+3] = b[i+4]; b[i+4] = b[i+5]; b[--l] = '\0'; } } /* FIXME ... horrible kludge for timestamps with fractional * second information. Force it to 3 digit millisecond */ while (i-- > 0) { if (b[i] == '.') { milliseconds = YES; i++; if (!isdigit(b[i])) { memmove(&b[i+3], &b[i], e-i); l += 3; memcpy(&b[i], "000", 3); } i++; if (!isdigit(b[i])) { memmove(&b[i+2], &b[i], e-i); l += 2; memcpy(&b[i], "00", 2); } i++; if (!isdigit(b[i])) { memmove(&b[i+1], &b[i], e-i); l += 1; memcpy(&b[i], "0", 1); } i++; break; } } if (i > 0 && i < e) { memmove(&b[i], &b[e], l - e); l -= (e - i); } b[l] = '\0'; if (l == 0) { return nil; } s = [NSString stringWithUTF8String: b]; if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F %z" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; } return d; } } @interface SQLClientJDBC : SQLClient @end static NSDate *future = nil; static NSNull *null = nil; @implementation SQLClientJDBC static int JDBCDATE = 0; static int JDBCTIME = 0; static int JDBCTIMESTAMP = 0; static int JDBCBOOLEAN = 0; static int JDBCBLOB = 0; static int JDBCBINARY = 0; static int JDBCVARBINARY = 0; static int JDBCLONGVARBINARY = 0; static int JDBCVARCHAR = 0; + (void) initialize { if (future == nil) { JNIEnv *env; jclass jc; jfieldID jf; future = [NSCalendarDate dateWithString: @"9999-01-01 00:00:00 +0000" calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; [future retain]; null = [NSNull null]; [null retain]; [SQLClientJVM startVirtualMachineWithClassPath: nil libraryPath: nil]; env = SQLClientJNIEnv(); jc = (*env)->FindClass(env, "java/sql/Types"); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "DATE", "I"); JException (env); JDBCDATE = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "TIME", "I"); JException (env); JDBCTIME = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "TIMESTAMP", "I"); JException (env); JDBCTIMESTAMP = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "BOOLEAN", "I"); JException (env); JDBCBOOLEAN = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "BLOB", "I"); JException (env); JDBCBLOB = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "BINARY", "I"); JException (env); JDBCBINARY = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "VARBINARY", "I"); JException (env); JDBCVARBINARY = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "LONGVARBINARY", "I"); JException (env); JDBCLONGVARBINARY = (*env)->GetStaticIntField(env, jc, jf); JException (env); jf = (*env)->GetStaticFieldID(env, jc, "VARCHAR", "I"); JException (env); JDBCVARCHAR = (*env)->GetStaticIntField(env, jc, jf); JException (env); } } /* Disconnect and deallocate all resources used. * Do NOT raise an exception. */ - (void) _backendDisconnect { if (extra != 0) { JNIEnv *env = SQLClientJNIEnv(); JInfo *ji = (JInfo*)extra; jclass jc; jmethodID jm; if ((*env)->PushLocalFrame (env, 16) >= 0) { if (ji->statement != 0) { jc = (*env)->GetObjectClass(env, ji->statement); jm = (*env)->GetMethodID (env, jc, "close", "()V"); if (jm == 0) JExceptionClear(env); else (*env)->CallVoidMethod (env, ji->statement, jm); if (jm == 0) JExceptionClear(env); (*env)->DeleteGlobalRef (env, ji->statement); if (jm == 0) JExceptionClear(env); } if (ji->connection != 0) { jc = (*env)->GetObjectClass(env, ji->connection); jm = (*env)->GetMethodID (env, jc, "close", "()V"); if (jm == 0) JExceptionClear(env); else (*env)->CallVoidMethod (env, ji->connection, jm); if (jm == 0) JExceptionClear(env); (*env)->DeleteGlobalRef (env, ji->connection); if (jm == 0) JExceptionClear(env); } (*env)->PopLocalFrame (env, NULL); } NSZoneFree(NSDefaultMallocZone(), extra); extra = 0; } } - (JInfo*) _backendExtra { return (JInfo*)extra; } - (BOOL) backendConnect { if (extra == 0) { connected = NO; if ([self database] != nil) { NSString *dbase = [self database]; NSRange r; [[self class] purgeConnections: nil]; r = [dbase rangeOfString: @":"]; if (r.length > 0) { NSString *url; NSString *cname; JNIEnv *env; jclass jc; jmethodID jm; jobject jo; url = [dbase substringFromIndex: NSMaxRange(r)]; cname = [dbase substringToIndex: r.location]; env = SQLClientJNIEnv(); if (env == 0) { NSLog(@"Connect to '%@' failed to set up Java runtime", [self name]); return NO; } /* Ensure the driver for the database is loaded. */ cname = [cname stringByReplacingString: @"." withString: @"/"]; if ((*env)->FindClass(env, [cname UTF8String]) == 0) { JExceptionClear (env); NSLog(@"Connect to '%@' failed to load driver '%@'.\n" @"Perhaps you need to set your CLASSPATH environment " @"variable to point to the location of your JDBC library.", [self name], cname); return NO; } if ((*env)->PushLocalFrame (env, 32) < 0) { JExceptionClear (env); [self debug: @"Connect to '%@' failed memory allocation '%@'", [self name], cname]; return NO; } /* Get the driver manager class. */ jc = (*env)->FindClass(env, "java/sql/DriverManager"); if (jc == 0) { JExceptionClear (env); (*env)->PopLocalFrame (env, NULL); NSLog(@"Connect to '%@' failed to load DriverManager\n" @"Perhaps you need to set your CLASSPATH environment " @"variable to point to the location of your JDBC library.", [self name]); return NO; } /* Get the method to get a connection. */ jm = (*env)->GetStaticMethodID(env, jc, "getConnection", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)" "Ljava/sql/Connection;"); if (jm == 0) { JExceptionClear (env); (*env)->PopLocalFrame (env, NULL); [self debug: @"Connect to '%@' failed to get connect method", [self name]]; return NO; } /* Get the new connection object */ jobject js1 = JStringFromNSString(env, url); jobject js2 = JStringFromNSString(env, [self user]); jobject js3 = JStringFromNSString(env, [self password]); /* NSLog(@"CONNECT '%@', '%@', '%@'", NSStringFromJString(env, js1), NSStringFromJString(env, js2), NSStringFromJString(env, js3)); */ jo = (*env)->CallStaticObjectMethod(env, jc, jm, js1, js2, js3); if (jo == 0) { JExceptionClear (env); (*env)->PopLocalFrame (env, NULL); [self debug: @"Connect to '%@' failed to get connection", [self name]]; return NO; } /* Make a reference so it can't be garbage collected. */ jo = (*env)->NewGlobalRef(env, jo); if (jo == 0) { JExceptionClear (env); (*env)->PopLocalFrame (env, NULL); [self debug: @"Connect to '%@' failed to get global ref", [self name]]; return NO; } else { JInfo *ji; ji = NSZoneMalloc(NSDefaultMallocZone(), sizeof(JInfo)); memset(ji, '\0', sizeof(*ji)); extra = ji; NS_DURING { ji->connection = jo; jc = (*env)->GetObjectClass(env, ji->connection); /* Get the method to set autocommit. */ jm = (*env)->GetMethodID(env, jc, "setAutoCommit", "(Z)V"); JException (env); /* Turn off autocommit */ (*env)->CallVoidMethod (env, ji->connection, jm, JNI_FALSE); JException (env); ji->commit = (*env)->GetMethodID (env, jc, "commit", "()V"); JException(env); ji->rollback = (*env)->GetMethodID (env, jc, "rollback", "()V"); JException(env); ji->prepare = (*env)->GetMethodID (env, jc, "prepareStatement", "(Ljava/lang/String;)Ljava/sql/PreparedStatement;"); JException(env); jm = (*env)->GetMethodID (env, jc, "createStatement", "()Ljava/sql/Statement;"); JException(env); jo = (*env)->CallObjectMethod (env, ji->connection, jm); JException(env); ji->statement = (*env)->NewGlobalRef(env, jo); JException(env); jc = (*env)->GetObjectClass(env, ji->statement); ji->executeUpdate = (*env)->GetMethodID (env, jc, "executeUpdate", "(Ljava/lang/String;)I"); JException(env); ji->executeQuery = (*env)->GetMethodID (env, jc, "executeQuery", "(Ljava/lang/String;)Ljava/sql/ResultSet;"); JException(env); (*env)->PopLocalFrame (env, NULL); jc = (*env)->GetObjectClass(env, ji->connection); jm = (*env)->GetMethodID (env, jc, "getMetaData", "()Ljava/sql/DatabaseMetaData;"); JException(env); jo = (*env)->CallObjectMethod (env, ji->connection, jm); JException(env); jc = (*env)->GetObjectClass(env, jo); jm = (*env)->GetMethodID (env, jc, "supportsBatchUpdates", "()Z"); JException(env); if ((*env)->CallBooleanMethod (env, jo, jm) == JNI_TRUE) { jc = (*env)->GetObjectClass(env, ji->statement); ji->addBatch = (*env)->GetMethodID (env, jc, "addBatch", "(Ljava/lang/String;)V"); JException(env); ji->clearBatch = (*env)->GetMethodID (env, jc, "clearBatch", "()V"); JException(env); ji->executeBatch = (*env)->GetMethodID (env, jc, "executeBatch", "()[I"); JException(env); } else { ji->addBatch = 0; ji->clearBatch = 0; ji->executeBatch = 0; } } NS_HANDLER { (*env)->PopLocalFrame (env, NULL); [self _backendDisconnect]; [self debug: @"Connect to '%@' using '%@' problem: %@", [self name], [self database], localException]; return NO; } NS_ENDHANDLER connected = YES; } } else { [self debug: @"Connect to '%@' using '%@' has no class", [self name], [self database]]; return NO; } } else { [self debug: @"Connect to '%@' with no user/password/database configured", [self name]]; } } return connected; } - (void) backendDisconnect { if (extra != 0) { NS_DURING { if ([self isInTransaction] == YES) { [self rollback]; } if ([self debugging] > 0) { [self debug: @"Disconnecting client %@", [self clientName]]; } [self _backendDisconnect]; if ([self debugging] > 0) { [self debug: @"Disconnected client %@", [self clientName]]; } } NS_HANDLER { [self _backendDisconnect]; [self debug: @"Error disconnecting from database (%@): %@", [self clientName], localException]; } NS_ENDHANDLER connected = NO; } } - (NSInteger) backendExecute: (NSArray*)info { NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSString *stmt = [info objectAtIndex: 0]; JNIEnv *env = SQLClientJNIEnv(); JInfo *ji; if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } if ((*env)->PushLocalFrame (env, 32) < 0) { JExceptionClear(env); [arp release]; [NSException raise: NSInternalInconsistencyException format: @"No java memory for execute"]; } NS_DURING { jmethodID jm; jobject js; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to execute statement %@", [self name], stmt]; } ji = (JInfo*)extra; if ([info count] > 1) { unsigned i; jclass jc; stmt = [stmt stringByReplacingString: @"'?'''?'" withString: @"?"]; js = (*env)->CallObjectMethod (env, ji->connection, ji->prepare, JStringFromNSString(env, stmt)); JException(env); jc = (*env)->GetObjectClass(env, js); JException(env); jm = (*env)->GetMethodID (env, jc, "setBytes", "(I[B)V"); JException(env); for (i = 1; i < [info count]; i++) { (*env)->CallIntMethod (env, js, jm, i, ByteArrayFromNSData(env, [info objectAtIndex: i])); JException(env); } jm = (*env)->GetMethodID (env, jc, "executeUpdate", "()I"); JException(env); (*env)->CallIntMethod (env, js, jm); } else { (*env)->CallIntMethod (env, ji->statement, ji->executeUpdate, JStringFromNSString(env, stmt)); } JException(env); if (_inTransaction == NO) { // Not in a transaction ... commit at once. (*env)->CallVoidMethod (env, ji->connection, ji->commit); JException (env); } (*env)->PopLocalFrame (env, NULL); } NS_HANDLER { if (connected == YES) { if (_inTransaction == NO) { ji = (JInfo*)extra; // Not in a transaction ... rollback to clear error state (*env)->CallVoidMethod (env, ji->connection, ji->rollback); JExceptionClear (env); } (*env)->PopLocalFrame (env, NULL); if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return -1; } - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rType listType: (id)lType { NSMutableArray *records = nil; NSAutoreleasePool *arp = [NSAutoreleasePool new]; JNIEnv *env = SQLClientJNIEnv(); JInfo *ji; if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } if ((*env)->PushLocalFrame (env, 32) < 0) { JExceptionClear(env); [arp release]; [NSException raise: NSInternalInconsistencyException format: @"No java memory for query"]; } NS_DURING { int fieldCount; jclass resultClass; jobject result; jclass metaDatlType; jobject metaData; jmethodID jm; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to run query %@", [self name], stmt]; } ji = (JInfo*)extra; result = (*env)->CallObjectMethod (env, ji->statement, ji->executeQuery, JStringFromNSString(env, stmt)); JException (env); resultClass = (*env)->GetObjectClass(env, result); JException (env); jm = (*env)->GetMethodID (env, resultClass, "getMetaData", "()Ljava/sql/ResultSetMetaData;"); JException (env); metaData = (*env)->CallObjectMethod (env, result, jm); JException (env); metaDatlType = (*env)->GetObjectClass(env, metaData); JException (env); jm = (*env)->GetMethodID (env, metaDatlType, "getColumnCount", "()I"); JException (env); fieldCount = (*env)->CallIntMethod (env, metaData, jm); JException (env); if (fieldCount > 0) { NSString *keys[fieldCount]; int types[fieldCount]; unsigned i; jmethodID next; jmethodID wasNull; jmethodID getBinaryStream; jmethodID getBoolean; jmethodID getBytes; jmethodID getString; /* Get the names of each field */ jm = (*env)->GetMethodID (env, metaDatlType, "getColumnName", "(I)Ljava/lang/String;"); JException (env); for (i = 0; i < fieldCount; i++) { jstring js = (*env)->CallObjectMethod (env, metaData, jm, i+1); JException (env); keys[i] = NSStringFromJString (env, js); } /* Get the types of each field. * We treat most as strings. */ jm = (*env)->GetMethodID (env, metaDatlType, "getColumnType", "(I)I"); JException (env); for (i = 0; i < fieldCount; i++) { int v = (*env)->CallIntMethod (env, metaData, jm, i+1); if (v == JDBCDATE || v == JDBCTIME || v == JDBCTIMESTAMP) { types[i] = JDBCTIMESTAMP; } else if (v == JDBCBOOLEAN) { types[i] = JDBCBOOLEAN; } else if (v == JDBCBLOB || v == JDBCBINARY || v == JDBCVARBINARY || v == JDBCLONGVARBINARY) { types[i] = JDBCBLOB; } else { types[i] = JDBCVARCHAR; } } /* Iterate through the result set */ wasNull = (*env)->GetMethodID (env, resultClass, "wasNull", "()Z"); JException (env); getBinaryStream = (*env)->GetMethodID (env, resultClass, "getBinaryStream", "(I)Ljava/io/InputStream;"); JException (env); getBoolean = (*env)->GetMethodID (env, resultClass, "getBoolean", "(I)Z"); JException (env); getBytes = (*env)->GetMethodID (env, resultClass, "getBytes", "(I)[B"); JException (env); getString = (*env)->GetMethodID (env, resultClass, "getString", "(I)Ljava/lang/String;"); JException (env); next = (*env)->GetMethodID (env, resultClass, "next", "()Z"); JException (env); records = [[lType alloc] initWithCapacity: 2]; while ((*env)->CallBooleanMethod (env, result, next) == JNI_TRUE) { SQLRecord *record; id values[fieldCount]; int j; if ((*env)->PushLocalFrame (env, fieldCount * 2) < 0) { JExceptionClear(env); [arp release]; [NSException raise: NSInternalInconsistencyException format: @"No java memory for query"]; } NS_DURING { for (j = 0; j < fieldCount; j++) { id v = null; if (types[j] == JDBCBOOLEAN) { BOOL b = NO; if ((*env)->CallBooleanMethod (env, result, getBoolean, j+1) == JNI_TRUE) { b = YES; } JException (env); if ((*env)->CallBooleanMethod (env, result, wasNull) == JNI_FALSE) { if (b == YES) { v = @"Y"; } else { v = @"N"; } } JException (env); } else if (types[j] == JDBCTIMESTAMP) { jobject jo; jo = (*env)->CallObjectMethod (env, result, getString, j+1); JException (env); if ((*env)->CallBooleanMethod (env, result, wasNull) == JNI_FALSE) { v = NSStringFromJString(env, jo); v = NSDateFromNSString(v); } JException (env); } else if (types[j] == JDBCBLOB) { jbyteArray jo; jo = (*env)->CallObjectMethod (env, result, getBytes, j+1); JException (env); if ((*env)->CallBooleanMethod (env, result, wasNull) == JNI_FALSE) { v = NSDataFromByteArray(env, jo); } JException (env); } else { jobject jo; jo = (*env)->CallObjectMethod (env, result, getString, j+1); JException (env); if ((*env)->CallBooleanMethod (env, result, wasNull) == JNI_FALSE) { v = NSStringFromJString(env, jo); } JException (env); } values[j] = v; } (*env)->PopLocalFrame (env, NULL); } NS_HANDLER { (*env)->PopLocalFrame (env, NULL); [localException raise]; } NS_ENDHANDLER record = [rType newWithValues: values keys: keys count: fieldCount]; [records addObject: record]; [record release]; } } else { records = [[lType alloc] initWithCapacity: 0]; } (*env)->PopLocalFrame (env, NULL); } NS_HANDLER { NSString *n = [localException name]; if (connected == YES) { (*env)->PopLocalFrame (env, NULL); if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } } [records release]; records = nil; [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return [records autorelease]; } - (SQLTransaction*) batch: (BOOL)stopOnFailure { _JDBCTransaction *transaction; transaction = (_JDBCTransaction*)NSAllocateObject([_JDBCTransaction class], 0, NSDefaultMallocZone()); transaction->_owner = [self retain]; transaction->_info = [NSMutableArray new]; transaction->_batch = YES; transaction->_stop = stopOnFailure; return [(SQLTransaction*)transaction autorelease]; } - (void) begin { [lock lock]; if (_inTransaction == NO) { _inTransaction = YES; // Leave us locked so the transaction can't be interfered with } else { [lock unlock]; [NSException raise: NSInternalInconsistencyException format: @"begin used inside transaction"]; } } - (void) commit { [lock lock]; if (_inTransaction == NO) { [lock unlock]; [NSException raise: NSInternalInconsistencyException format: @"commit used outside transaction"]; } NS_DURING { JNIEnv *env = SQLClientJNIEnv(); JInfo *ji = (JInfo*)extra; (*env)->CallVoidMethod (env, ji->connection, ji->commit); JException(env); _inTransaction = NO; [lock unlock]; // Locked at start of -commit [lock unlock]; // Locked by -begin } NS_HANDLER { _inTransaction = NO; [lock unlock]; // Locked at start of -commit [lock unlock]; // Locked by -begin [localException raise]; } NS_ENDHANDLER } - (void) dealloc { [self disconnect]; [super dealloc]; } - (NSString*) quoteString: (NSString *)s { static NSCharacterSet *special = nil; NSMutableString *m; NSRange r; unsigned l; if (special == nil) { NSString *stemp; /* * NB. length of C string is 3, so we include a nul character as a * special. */ stemp = [[NSString alloc] initWithBytes: "'\\" length: 3 encoding: NSASCIIStringEncoding]; special = [NSCharacterSet characterSetWithCharactersInString: stemp]; [stemp release]; [special retain]; } /* * Step through string removing nul characters * and escaping quote characters as required. */ m = [[s mutableCopy] autorelease]; l = [m length]; r = NSMakeRange(0, l); r = [m rangeOfCharacterFromSet: special options: NSLiteralSearch range: r]; while (r.length > 0) { unichar c = [m characterAtIndex: r.location]; if (c == 0) { r.length = 1; [m replaceCharactersInRange: r withString: @""]; l--; } else if (c == '\\') { r.length = 0; [m replaceCharactersInRange: r withString: @"\\"]; l++; r.location += 2; } else { r.length = 0; [m replaceCharactersInRange: r withString: @"'"]; l++; r.location += 2; } r = NSMakeRange(r.location, l - r.location); r = [m rangeOfCharacterFromSet: special options: NSLiteralSearch range: r]; } /* Add quoting around it. */ [m replaceCharactersInRange: NSMakeRange(0, 0) withString: @"'"]; [m appendString: @"'"]; return m; } - (void) rollback { [lock lock]; if (_inTransaction == YES) { _inTransaction = NO; NS_DURING { JNIEnv *env = SQLClientJNIEnv(); JInfo *ji = (JInfo*)extra; (*env)->CallVoidMethod (env, ji->connection, ji->rollback); JException(env); [lock unlock]; // Locked at start of -rollback [lock unlock]; // Locked by -begin } NS_HANDLER { [lock unlock]; // Locked at start of -rollback [lock unlock]; // Locked by -begin [localException raise]; } NS_ENDHANDLER } } - (SQLTransaction*) transaction { _JDBCTransaction *transaction; transaction = (_JDBCTransaction*)NSAllocateObject([_JDBCTransaction class], 0, NSDefaultMallocZone()); transaction->_owner = [self retain]; transaction->_info = [NSMutableArray new]; return [(SQLTransaction*)transaction autorelease]; } @end @implementation _JDBCTransaction - (BOOL) _batchable: (NSArray*)a { unsigned c = [a count]; unsigned i; for (i = 0; i < c; i++) { if ([[a objectAtIndex: i] count] > 1) { return NO; } } return YES; } - (void) _merge: (NSMutableArray*)a { unsigned c = [_info count]; unsigned i; for (i = 0; i < c; i++) { id o = [_info objectAtIndex: i]; if ([o isKindOfClass: [NSArray class]] == YES) { [a addObject: o]; } else { [(_JDBCTransaction*)o _merge: a]; } } } - (void) execute { if (_count > 0) { NSAutoreleasePool *arp = [NSAutoreleasePool new]; SQLClientPool *pool; SQLClient *db; BOOL wrapped = NO; BOOL batched = NO; JNIEnv *env; JInfo *ji; env = SQLClientJNIEnv(); if ((*env)->PushLocalFrame (env, 32) < 0) { JExceptionClear(env); [arp release]; [NSException raise: NSInternalInconsistencyException format: @"No java memory for execute"]; } if ([_owner isKindOfClass: [SQLClientPool class]]) { pool = (SQLClientPool*)_owner; db = [pool provideClient]; } else { pool = nil; db = _owner; } ji = [(SQLClientJDBC*)db _backendExtra]; NS_DURING { NSMutableArray *statements; unsigned numberOfStatements; unsigned statement; NSTimeInterval _duration; NSTimeInterval start = 0.0; /* * Ensure we have a working connection. */ if ([db connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to execute transaction %@", [_owner name], self]; } _duration = [db durationLogging]; statements = [NSMutableArray arrayWithCapacity: 100]; [self _merge: statements]; numberOfStatements = [statements count]; if (_duration >= 0) { start = GSTickerTimeNow(); } if ([db isInTransaction] == NO) { wrapped = YES; } if (numberOfStatements > 1 && ji->addBatch != 0 && [self _batchable: statements] == YES) { jintArray ja; jint *array; int status = 0; for (statement = 0; statement < numberOfStatements; statement++) { NSString *stmt = [statements objectAtIndex: statement]; jobject js; js = (*env)->CallObjectMethod(env, ji->statement, ji->addBatch, JStringFromNSString(env, stmt)); JException(env); batched = YES; } ja = (*env)->CallObjectMethod(env, ji->statement, ji->executeBatch); JException(env); array = (*env)->GetIntArrayElements(env, ja, 0); for (statement = 0; statement < numberOfStatements; statement++) { status = array[statement]; if (status < 0 && status != -2) { break; } } (*env)->ReleaseIntArrayElements(env, ja, array, 0); batched = NO; (*env)->CallVoidMethod(env, ji->statement, ji->clearBatch); JException(env); if (statement != numberOfStatements) { [NSException raise: NSGenericException format: @"Statement %d error %d in batch with %@", statement, status, [statements objectAtIndex: statement]]; } } else { /* Not batchable ... execute as a transaction without * batching :-( */ for (statement = 0; statement < numberOfStatements; statement++) { NSArray *info = [statements objectAtIndex: statement]; NSString *stmt = [info objectAtIndex: 0]; unsigned c = [info count]; jmethodID jm; jobject js; if (c == 1) { (*env)->CallIntMethod (env, ji->statement, ji->executeUpdate, JStringFromNSString(env, stmt)); } else { unsigned i; jclass jc; stmt = [stmt stringByReplacingString: @"'?'''?'" withString: @"?"]; js = (*env)->CallObjectMethod (env, ji->connection, ji->prepare, JStringFromNSString(env, stmt)); JException(env); jc = (*env)->GetObjectClass(env, js); JException(env); jm = (*env)->GetMethodID (env, jc, "setBytes", "(I[B)V"); JException(env); /* Get data arguments for statement. */ for (i = 1; i < c; i++) { NSData *data; data = [info objectAtIndex: i]; (*env)->CallIntMethod (env, js, jm, i, ByteArrayFromNSData(env, data)); JException(env); } jm = (*env)->GetMethodID(env, jc, "executeUpdate", "()I"); JException(env); (*env)->CallIntMethod (env, js, jm); } JException(env); } } if (wrapped == YES) { wrapped = NO; (*env)->CallVoidMethod (env, ji->connection, ji->commit); JException(env); } (*env)->PopLocalFrame (env, NULL); db->_lastOperation = GSTickerTimeNow(); if (_duration >= 0) { NSTimeInterval d; d = db->_lastOperation - start; if (d >= _duration) { [db debug: @"Duration %g for transaction %@", d, statements]; } } } NS_HANDLER { if (wrapped == YES) { (*env)->CallVoidMethod (env, ji->connection, ji->rollback); JException(env); } if (batched == YES) { (*env)->CallVoidMethod(env, ji->statement, ji->clearBatch); JException(env); } (*env)->PopLocalFrame (env, NULL); [localException raise]; } NS_ENDHANDLER if (nil != pool) { [pool swallowClient: db]; } [arp release]; } } @end SQLClient-1.9.0/MySQL.m000066400000000000000000000316011436027104400144440ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientMySQL for GNUStep Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import #import #import #import #import #import #import #import #import #import #import #import #import #include "config.h" #define SQLCLIENT_PRIVATE @public #include "SQLClient.h" #include @interface SQLClientMySQL : SQLClient @end @implementation SQLClientMySQL #define connection ((MYSQL*)(self->extra)) static NSDate *future = nil; static NSNull *null = nil; + (void) initialize { if (future == nil) { future = [NSCalendarDate dateWithString: @"9999-01-01 00:00:00" calendarFormat: @"%Y-%m-%d %H:%M:%S" locale: nil]; [future retain]; null = [NSNull null]; [null retain]; } } - (BOOL) backendConnect { if (connected == NO) { if ([self database] != nil && [self user] != nil && [self password] != nil) { NSString *host = nil; NSString *port = nil; NSString *dbase = [self database]; NSRange r; [[self class] purgeConnections: nil]; r = [dbase rangeOfString: @"@"]; if (r.length > 0) { host = [dbase substringFromIndex: NSMaxRange(r)]; dbase = [dbase substringToIndex: r.location]; r = [host rangeOfString: @":"]; if (r.length > 0) { port = [host substringFromIndex: NSMaxRange(r)]; host = [host substringToIndex: r.location]; } } if ([self debugging] > 0) { [self debug: @"Connect to '%@' as %@", [self database], [self name]]; } extra = mysql_init(0); mysql_options(connection, MYSQL_SET_CHARSET_NAME, "utf8"); if (mysql_real_connect(connection, [host UTF8String], [[self user] UTF8String], [[self password] UTF8String], [dbase UTF8String], [port intValue], NULL, CLIENT_MULTI_STATEMENTS) == 0) { [self debug: @"Error connecting to '%@' (%@) - %s", [self name], [self database], mysql_error(connection)]; mysql_close(connection); extra = 0; } else { connected = YES; if ([self debugging] > 0) { [self debug: @"Connected to '%@'", [self name]]; } } } else { [self debug: @"Connect to '%@' with no user/password/database configured", [self name]]; } } return connected; } - (void) backendDisconnect { if (connected == YES) { NS_DURING { if ([self isInTransaction] == YES) { [self rollback]; } if ([self debugging] > 0) { [self debug: @"Disconnecting client %@", [self clientName]]; } mysql_close(connection); extra = 0; if ([self debugging] > 0) { [self debug: @"Disconnected client %@", [self clientName]]; } } NS_HANDLER { extra = 0; [self debug: @"Error disconnecting from database (%@): %@", [self clientName], localException]; } NS_ENDHANDLER connected = NO; } } - (NSInteger) backendExecute: (NSArray*)info { NSString *stmt; NSInteger rowCount = 0; NSAutoreleasePool *arp = [NSAutoreleasePool new]; stmt = [info objectAtIndex: 0]; if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } NS_DURING { MYSQL_RES *result; const char *statement; unsigned length; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to execute statement %@", [self name], stmt]; } statement = (char*)[stmt UTF8String]; length = strlen(statement); statement = [self insertBLOBs: info intoStatement: statement length: length withMarker: "'?'''?'" length: 7 giving: &length]; if (mysql_real_query(connection, statement, length) != 0) { NSString *s; s = [NSString stringWithFormat: @"%s", mysql_error(connection)]; if (mysql_ping(connection) == 0) { [NSException raise: SQLException format: @"%@", s]; } else { [NSException raise: SQLConnectionException format: @"%@", s]; } } /* See how many rows were modified. */ rowCount = mysql_affected_rows(connection); /* discard any results. */ result = mysql_store_result(connection); if (result != 0) mysql_free_result(result); while (mysql_more_results(connection)) { if (mysql_next_result(connection) == 0) { result = mysql_store_result(connection); if (result != 0) mysql_free_result(result); } } } NS_HANDLER { NSString *n = [localException name]; if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return rowCount; } static unsigned int trim(char *str) { char *start = str; while (isspace(*str)) { str++; } if (str != start) { strcpy(start, str); } str = start; while (*str != '\0') { str++; } while (str > start && isspace(str[-1])) { *--str = '\0'; } return (str - start); } - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype { NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSMutableArray *records = nil; MYSQL_RES *result = 0; if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } NS_DURING { char *statement; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to run query %@", [self name], stmt]; } statement = (char*)[stmt UTF8String]; if (mysql_query(connection, statement) == 0 && (result = mysql_store_result(connection)) != 0) { int recordCount = mysql_num_rows(result); int fieldCount = mysql_num_fields(result); MYSQL_FIELD *fields = mysql_fetch_fields(result); NSString *keys[fieldCount]; int i; for (i = 0; i < fieldCount; i++) { keys[i] = [NSString stringWithUTF8String: (char*)fields[i].name]; } records = [[ltype alloc] initWithCapacity: recordCount]; for (i = 0; i < recordCount; i++) { SQLRecord *record; MYSQL_ROW row = mysql_fetch_row(result); unsigned long *lengths = mysql_fetch_lengths(result); id values[fieldCount]; int j; for (j = 0; j < fieldCount; j++) { id v = null; unsigned char *p = (unsigned char*)row[j]; if (p != 0) { int size = lengths[j]; if ([self debugging] > 1) { [self debug: @"%@ type:%d size: %d val:%*.*s\n", keys[j], fields[j].type, size, size, size, p]; } switch (fields[j].type) { case FIELD_TYPE_TIMESTAMP: { char b[32]; NSString *f; NSString *s; if (size > 14) { size = 19; f = @"%Y-%m-%d %H:%M:%S %z"; } else if (size == 14) { f = @"%Y%m%d%H%M%S %z"; } else if (size == 12) { f = @"%y%m%d%H%M%S %z"; } else if (size == 10) { f = @"%y%m%d%H%M %z"; } else if (size == 8) { f = @"%y%m%d%H %z"; } else if (size == 6) { f = @"%y%m%d %z"; } else if (size == 4) { f = @"%y%m %z"; } else { f = @"%y %z"; } strncpy(b, (char*)p, size); strncpy(b + size, (char*)" +0000", 6); s = [[NSString alloc] initWithBytes: b length: size + 6 encoding: NSASCIIStringEncoding]; v = [NSCalendarDate dateWithString: s calendarFormat: f locale: nil]; [v setCalendarFormat: @"%Y-%m-%d %H:%M:%S %z"]; if ([self debugging] > 1) [self debug: @"Parsed '%@' as '%@'\n", s, v]; [s release]; } break; case FIELD_TYPE_TINY: v = [NSString stringWithFormat: @"%u", *p]; break; case FIELD_TYPE_BLOB: case FIELD_TYPE_TINY_BLOB: case FIELD_TYPE_MEDIUM_BLOB: case FIELD_TYPE_LONG_BLOB: if (63 == fields[j].charsetnr) { v = [NSData dataWithBytes: p length: size]; } else { v = [[[NSString alloc] initWithBytes: p length: size encoding: NSUTF8StringEncoding] autorelease]; } break; default: if (YES == _shouldTrim) { trim((char*)p); } v = [NSString stringWithUTF8String: (char*)p]; break; } } values[j] = v; } record = [rtype newWithValues: values keys: keys count: fieldCount]; [records addObject: record]; [record release]; } } else { NSString *s; s = [NSString stringWithFormat: @"%s", mysql_error(connection)]; if (mysql_ping(connection) == 0) { [NSException raise: SQLException format: @"%@", s]; } else { [NSException raise: SQLConnectionException format: @"%@", s]; } } } NS_HANDLER { NSString *n = [localException name]; if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } if (result != 0) { mysql_free_result(result); } [records release]; records = nil; [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; if (result != 0) { mysql_free_result(result); } return [records autorelease]; } - (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf { const unsigned char *bytes = [blob bytes]; unsigned char *ptr = buf; unsigned l = [blob length]; unsigned i; *ptr++ = '\''; for (i = 0; i < l; i++) { unsigned char c = bytes[i]; if (c == '\0') { *ptr++ = '\\'; *ptr++ = '0'; } else if (c == '\\' || c == '\'' || c == '"') { *ptr++ = '\\'; *ptr++ = c; } else { *ptr++ = c; } } *ptr++ = '\''; return ((void*)ptr - buf); } - (unsigned) lengthOfEscapedBLOB: (NSData*)blob { const unsigned char *bytes = [blob bytes]; unsigned l = [blob length]; unsigned length = 2; // Quotes around BLOB while (l-- > 0) { unsigned char c = bytes[l]; if (c == '\0' || c == '\\' || c == '\'' || c == '"') { length++; } length++; } return length; } - (NSString*) quote: (id)obj { /* MySQL doesn't support timezones ... convert dates to simple GMT. */ if ([obj isKindOfClass: [NSDate class]] == YES) { NSString *fmt = nil; static NSTimeZone *gmt = nil; if (nil == gmt) { gmt = [[NSTimeZone timeZoneForSecondsFromGMT: 0] retain]; } if ([obj isKindOfClass: [NSCalendarDate class]] == YES) { fmt = [obj calendarFormat]; if ([fmt length] > 17) { fmt = nil; // bad format ... had timezone } } if (nil == fmt) { fmt = @"%Y-%m-%d %H:%M:%S"; } fmt = [NSString stringWithFormat: @"'%@'", fmt]; return [obj descriptionWithCalendarFormat: fmt timeZone: gmt locale: nil]; } return [super quote: obj]; } @end SQLClient-1.9.0/Oracle.pm000066400000000000000000000635511436027104400150750ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientOracle for GNUStep Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Written by: Nicola Pero Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #include #include #include #include #include #include #include #include #include #include #include "SQLClient.h" /* * Example configuration for an Oracle database: * * oracle-test = { * ServerType = "Oracle" * SQLDatabase = "nicola"; * SQLPassword = "mbrand"; * SQLUser = "mbrand"; * }; * * Where SQLDatabase is the Unique database Identifier. * */ @interface SQLClientOracle : SQLClient @end @interface SQLClientOracle(Embedded) - (const char *) blobFromData: (NSData*)data; - (NSData *) dataFromBlob: (const char *)blob; - (BOOL) dbFromDate: (NSDate*)d toBuffer: (char*)b length: (int)l; - (BOOL) dbFromString: (NSString*)s toBuffer: (char*)b length: (int)l; - (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l; - (NSString*) dbToStringFromBuffer: (char*)b length: (int)l; @end EXEC SQL INCLUDE sqlca; EXEC SQL WHENEVER SQLERROR DO SQLClientOracleErrorHandler(); /** * Return YES of the last SQL error indicated we are out of data, * NO otherwise. */ BOOL SQLClientOracleOutOfData() { if (sqlca.sqlcode == 100) { return YES; } else { return NO; } } /** * This error handler is called for most errors ... so we can get it to * raise an exception for us. */ void SQLClientOracleErrorHandler() { int code = sqlca.sqlcode; const char *ptr = sqlca.sqlerrm.sqlerrmc; const char *e0 = "'no connection to the server'"; const char *e1 = "Error in transaction processing"; sqlca.sqlcode = 0; // Reset error code NSLog (@"(Oracle) Raising an exception, %ld, %s", code, sqlca.sqlerrm.sqlerrmc); if (strncmp(ptr, e0, strlen(e0)) == 0 || strncmp(ptr, e1, strlen(e1)) == 0) { [NSException raise: SQLConnectionException format: @"(Oracle) SQL Error: SQLCODE=(%ld): %s", code, ptr]; } else { [NSException raise: SQLException format: @"(Oracle) SQL Error: SQLCODE=(%ld): %s", code, ptr]; } } @implementation SQLClientOracle - (BOOL) backendConnect { if (connected == NO) { if ([self database] != nil && [self user] != nil && [self password] != nil) { Class c = NSClassFromString(@"CmdClient"); [[self class] purgeConnections: nil]; NS_DURING { EXEC SQL BEGIN DECLARE SECTION; const char *database_c; const char *user_c; const char *password_c; const char *client_c; EXEC SQL END DECLARE SECTION; /* Database is the Oracle Net identifier for the database. */ database_c = [[self database] UTF8String]; /* User and password are used to connect to the database. */ user_c = [[self user] UTF8String]; password_c = [[self password] UTF8String]; /* Client is only used to give this connection a name * and distinguish it from other connections. */ client_c = [[self clientName] UTF8String]; if (c != 0) { [self debug: @"(Oracle) Connect to database %s user %s as %s", database_c, user_c, client_c]; } EXEC SQL CONNECT :user_c IDENTIFIED BY :password_c AT :client_c USING :database_c; if (c != 0) { [self debug: @"(Oracle) Connected (%s)", client_c]; } connected = YES; } NS_HANDLER { [self error: @"(Oracle) Error connecting to database: %@", localException]; } NS_ENDHANDLER } else { [self error: @"(Oracle) Connect with no user/password/database configured"]; } } return connected; } - (void) backendDisconnect { if (connected == YES) { NS_DURING { EXEC SQL BEGIN DECLARE SECTION; const char *client_c; EXEC SQL END DECLARE SECTION; if ([self isInTransaction] == YES) { [self rollback]; } client_c = [[self clientName] UTF8String]; [self debug: @"(Oracle) Disconnecting client %@", [self clientName]]; /* To disconnect from the database, we issuse a COMMIT * statement with the RELEASE option. The RELEASE option * causes it to disconnect after the COMMIT. */ EXEC SQL AT :client_c COMMIT WORK RELEASE; [self debug: @"(Oracle) Disconnected client %@", [self clientName]]; } NS_HANDLER { [self error: @"(Oracle) Error disconnecting from database (%@): %@", [self clientName], localException]; } NS_ENDHANDLER connected = NO; } } - (NSInteger) backendExecute: (NSArray*)info { EXEC SQL BEGIN DECLARE SECTION; char *statement; char *handle; EXEC SQL END DECLARE SECTION; CREATE_AUTORELEASE_POOL(arp); NSString *stmt = [info objectAtIndex: 0]; unsigned int length; BOOL manuallyAutoCommit = NO; length = [stmt length]; if (length == 0) { [NSException raise: NSInternalInconsistencyException format: @"(Oracle) Statement produced null string"]; } statement = (char*)[stmt UTF8String]; handle = (char*)[[self clientName] UTF8String]; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"(Oracle) Unable to connect to database"]; } NS_DURING { if ([self isInTransaction] == NO) { manuallyAutoCommit = YES; } EXEC SQL AT :handle PREPARE command FROM :statement; EXEC SQL AT :handle EXECUTE command; if (manuallyAutoCommit) { EXEC SQL AT :handle COMMIT; } } NS_HANDLER { NSString *n = [localException name]; NSString *msg = [localException reason]; if (manuallyAutoCommit) { EXEC SQL AT :handle ROLLBACK; } if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } /* * remove line number information from database exception message * since it's meaningless to the developer as it's the line number * in this file rather than the code which is calling us. */ if ([n isEqual: SQLException] == YES || [n isEqual: SQLConnectionException] == YES) { NSRange r; r = [msg rangeOfString: @" in line " options: NSBackwardsSearch]; if (r.length > 0) { msg = [msg substringToIndex: r.location]; localException = [NSException exceptionWithName: n reason: msg userInfo: nil]; } } [self error: @"(Oracle) Error executing statement:\n%@\n%@", stmt, localException]; [localException raise]; } NS_ENDHANDLER DESTROY(arp); return -1; } static unsigned int trim(char *str) { char *start = str; while (isspace(*str)) { str++; } if (str != start) { strcpy(start, str); } str = start; while (*str != '\0') { str++; } while (str > start && isspace(str[-1])) { *--str = '\0'; } return (str - start); } - (NSMutableArray*) backendQuery: (NSString*)stmt recordClass: (Class)rClass { EXEC SQL BEGIN DECLARE SECTION; int count; int index; short int indicator; int type; int length; int octetLength; short int returnedOctetLength; char fieldName[120]; char *aString; /* This holds a string representation of numbers returned by Oracle. * 128 seems a safe bound - else they'll be truncated. */ char aNumber[128]; char *query; char *handle; EXEC SQL END DECLARE SECTION; CREATE_AUTORELEASE_POOL(arp); NSMutableArray *records; BOOL isOpen = NO; BOOL wasInTransaction = [self isInTransaction]; BOOL allocatedDescriptor = NO; length = [stmt length]; if (length == 0) { [NSException raise: NSInternalInconsistencyException format: @"(Oracle) Statement produced null string"]; } handle = (char*)[[self clientName] UTF8String]; query = (char*)[stmt UTF8String]; records = [[NSMutableArray alloc] initWithCapacity: 32]; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"(Oracle) Unable to connect to database"]; } NS_DURING { /* This is really the output descriptor. We do not use input * descriptors; all the input is in the SQL statement. */ EXEC SQL ALLOCATE DESCRIPTOR 'myDesc'; allocatedDescriptor = YES; EXEC SQL AT :handle PREPARE myQuery from :query; if ([self isInTransaction] == NO) { /* EXEC SQL AT :handle BEGIN; */ _inTransaction = YES; } EXEC SQL AT :handle DECLARE myCursor CURSOR FOR myQuery; EXEC SQL AT :handle OPEN myCursor; isOpen = YES; EXEC SQL AT :handle DESCRIBE OUTPUT myQuery USING DESCRIPTOR 'myDesc'; EXEC SQL GET DESCRIPTOR 'myDesc' :count = COUNT; if (count > 0) { /* Now we do what the Oracle examples do, which is we forcefully * require to the library to convert everything into types * chosen by us (mostly strings). The reason we do it is that * managing the 'internal' Oracle datatypes is a daunting task * (for example numbers are returned in a 22 byte representation * used internally by Oracle ...) and apparently it's now how * they expect you to use it - they provide no examples or * explanations of how to do it btw! They expect you to choose * which 'external' Oracle representation you want, by using SET * DESCRIPTOR as we do here, and then FETCH comfortably data * which is returned in the representation you chose. So we do * that way. */ int originalType[count]; for (index = 1; index <= count; index++) { EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :length = LENGTH, :octetLength = OCTET_LENGTH, :type = TYPE; /* Save the original type so that we know later what's * inside each returned value. */ originalType[index - 1] = type; switch (type) { /* Negative values of 'type' are used for Oracle * proprietary extensions; positive values for ANSI * types. */ /* We get character types as they are. */ case 1 /* CHARACTER */: case 12 /* CHARACTER_VARYING */: case -1 /* Oracle VARCHAR2 */: type = -1; /* Oracle VARCHAR2 */ EXEC SQL SET DESCRIPTOR 'myDesc' VALUE :index TYPE = :type; break; /* We get a string representation (128 bytes long) * of any number. */ case 2 /* NUMERIC */: case 3 /* DECIMAL */: case 4 /* INTEGER */: case 5 /* SMALLINT*/: case 6 /* FLOAT */: case 7 /* REAL */: case 8 /* DOUBLE_PRECISION */: type = 12; /* ANSI CHARACTER_VARYING */ octetLength = 128; EXEC SQL SET DESCRIPTOR 'myDesc' VALUE :index LENGTH = :octetLength, TYPE = :type; break; } } while (1) { SQLRecord *record; id keys[count]; id values[count]; EXEC SQL AT :handle FETCH myCursor INTO SQL DESCRIPTOR 'myDesc'; if (sqlca.sqlcode) { break; } for (index = 1; index <= count; ++index) { id v; EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :indicator = INDICATOR, :length = LENGTH, :fieldName = NAME, :octetLength = OCTET_LENGTH, :returnedOctetLength = RETURNED_OCTET_LENGTH, :type = TYPE; if (indicator == -1) { v = [NSNull null]; } else { switch (originalType[index - 1]) { case 3 /* DECIMAL */: case 4 /* INTEGER */: case 5 /* SMALLINT*/: { int aInt; EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :aNumber = DATA; aInt = [[NSString stringWithUTF8String: aNumber] intValue]; v = [NSNumber numberWithInt: aInt]; break; } case 2 /* NUMERIC */: case 6 /* FLOAT */: case 7 /* REAL */: case 8 /* DOUBLE_PRECISION */: { float aFloat; EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :aNumber = DATA; aFloat = [[NSString stringWithUTF8String: aNumber] floatValue]; v = [NSNumber numberWithFloat: aFloat]; break; } case 1 /* CHARACTER */: case 12 /* CHARACTER_VARYING */: case -1 /* Oracle VARCHAR2 */: /* For unclear reasons, returnedOctetLength is always 0. */ /* This code (patchy and experimentally * determined) really works if the database * field contains something like UTF-8, * returned as UTF-8 (such as for CHAR(20) * fields). If UNICODE stuff is returned, * then it's not the right way. We might * need to make a different depending on the * originalField type. */ /* Add 1 byte to \0-pad the string. */ aString = malloc (octetLength + 1); if (aString == NULL) { [NSException raise: @"OutOfMemoryException" format: @"(Oracle) could not malloc %d bytes", octetLength]; } EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :aString = DATA; /* \0-pad the string. */ aString[octetLength] = '\0'; if (YES == _shouldTrim) { trim (aString); } v = [NSString stringWithUTF8String: aString]; free(aString); break; /* TODO: DATES */ /* TODO TODO case BLOB: EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :aString = DATA; v = [self dataFromBlob: aString]; free(aString); break; */ default: aString = malloc (octetLength + 1); if (aString == NULL) { [NSException raise: @"OutOfMemoryException" format: @"(Oracle) could not malloc %d bytes", octetLength]; } EXEC SQL GET DESCRIPTOR 'myDesc' VALUE :index :aString = DATA; aString[octetLength] = '\0'; if (YES == _shouldTrim) { trim (aString); } v = [NSString stringWithUTF8String: aString]; free (aString); NSLog(@"(Oracle) Unknown data type (%d) for '%s': '%@'", type, fieldName, v); break; } } values[index - 1] = v; keys[index - 1] = [NSString stringWithUTF8String: fieldName]; } record = [rClass newWithValues: values keys: keys count: count]; [records addObject: record]; RELEASE(record); } } isOpen = NO; EXEC SQL AT :handle CLOSE myCursor; if (wasInTransaction == NO && [self isInTransaction] == YES) { EXEC SQL AT :handle COMMIT; _inTransaction = NO; } EXEC SQL DEALLOCATE DESCRIPTOR 'myDesc'; allocatedDescriptor = NO; } NS_HANDLER { NSString *n = [localException name]; NSString *msg = [localException reason]; DESTROY(records); NS_DURING { if (isOpen == YES) { EXEC SQL AT :handle CLOSE myCursor; } if (wasInTransaction == NO && [self isInTransaction] == YES) { EXEC SQL AT :handle ROLLBACK; _inTransaction = NO; } } NS_HANDLER { NSString *e = [localException name]; if (wasInTransaction == NO && [self isInTransaction] == YES) { _inTransaction = NO; } if ([e isEqual: SQLConnectionException] == YES) { [self disconnect]; } } NS_ENDHANDLER NS_DURING { if (allocatedDescriptor) { EXEC SQL DEALLOCATE DESCRIPTOR 'myDesc'; allocatedDescriptor = NO; } } NS_HANDLER { NSLog (@"Can't deallocate descriptor ... serious problem."); } NS_ENDHANDLER if ([n isEqual: SQLConnectionException] == YES) { _inTransaction = NO; [self disconnect]; } /* * remove line number information from database exception message * since it's meaningless to the developer as it's the line number * in this file rather than the code which is calling us. */ if ([n isEqual: SQLException] == YES || [n isEqual: SQLConnectionException] == YES) { NSRange r; r = [msg rangeOfString: @" in line " options: NSBackwardsSearch]; if (r.length > 0) { msg = [msg substringToIndex: r.location]; localException = [NSException exceptionWithName: n reason: msg userInfo: nil]; } } RETAIN(localException); RELEASE(arp); AUTORELEASE(localException); [localException raise]; } NS_ENDHANDLER DESTROY(arp); return AUTORELEASE(records); } /** * Convert NSData object with raw binary data into escaped sequence */ - (const char *) blobFromData: (NSData*)data { NSMutableData *md; unsigned sLen = [data length]; unsigned char *src = (unsigned char*)[data bytes]; unsigned dLen = 0; unsigned char *dst; unsigned i; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126) { dLen += 4; } else if (c == 92) { dLen += 2; } else { dLen += 1; } } md = [NSMutableData dataWithLength: dLen + 1]; dst = (unsigned char*)[md mutableBytes]; dLen = 0; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126) { dst[dLen] = '\\'; dst[dLen + 3] = (c & 7) + '0'; c >>= 3; dst[dLen + 2] = (c & 7) + '0'; c >>= 3; dst[dLen + 1] = (c & 7) + '0'; dLen += 4; } else if (c == 92) { dst[dLen++] = '\\'; dst[dLen++] = '\\'; } else { dst[dLen++] = c; } } dst[dLen] = '\0'; return dst; // Owned by autoreleased NSMutableData } /** * Convert escaped sequence to raw binary data in NSData object */ - (NSData *) dataFromBlob: (const char *)blob { NSMutableData *md; unsigned sLen = strlen(blob == 0 ? "" : blob); unsigned dLen = 0; unsigned char *dst; unsigned i; for (i = 0; i < sLen; i++) { unsigned c = blob[i]; dLen++; if (c == '\\') { c = blob[++i]; if (c != '\\') { i += 2; // Skip 2 digits octal } } } md = [NSMutableData dataWithLength: dLen]; dst = (unsigned char*)[md mutableBytes]; dLen = 0; for (i = 0; i < sLen; i++) { unsigned c = blob[i]; if (c == '\\') { c = blob[++i]; if (c != '\\') { c = c - '0'; c <<= 3; c += blob[++i] - '0'; c <<= 3; c += blob[++i] - '0'; } } dst[dLen++] = c; } return md; } /** * Convert an NSdate into a buffer for sending to the database. * Return YES if the conversion fitted, NO if it was truncated. * The value of l is expected to be one less than the size of the buffer. * A nul character is appended to the bytes in the buffer. */ - (BOOL) dbFromDate: (NSDate*)d toBuffer: (char*)b length: (int)l { NSString *s; s = [d descriptionWithCalendarFormat: @"%Y-%m-%d %H:%M:%S %z" timeZone: nil locale: nil]; return [self dbFromString: s toBuffer: b length: l]; } /** * Convert an NSString into a buffer for sending to the database.
* Return YES if the conversion fitted, NO if it was truncated.
* If s is nil, it is treated as an empty string.
* The value of l is expected to be one less than the size of the buffer * and must be at least 1.
* The pointer b must not be null.
* A nul character is appended to the bytes in the buffer.
* Raises an exception when passed invalid arguments. */ - (BOOL) dbFromString: (NSString*)s toBuffer: (char*)b length: (int)l { NSData *d; BOOL ok = YES; unsigned size = l; if (l <= 0) { [NSException raise: NSInvalidArgumentException format: @"(Oracle) -%@: length too small (%d)", NSStringFromSelector(_cmd), l]; } if (b == 0) { [NSException raise: NSInvalidArgumentException format: @"(Oracle) -%@: buffer is null", NSStringFromSelector(_cmd)]; } if (s == nil) { s = @""; } d = [s dataUsingEncoding: NSUTF8StringEncoding]; if (l < (int)[d length]) { /* * As the data is UTF8, we need to avoid truncating in the * middle of a multibyte character, so we shorten the * original string and reconvert to UTF8 until we find a * string that fits. */ if ((int)[s length] > l) { s = [s substringToIndex: l]; d = [s dataUsingEncoding: NSUTF8StringEncoding]; } while ((int)[d length] > l) { s = [s substringToIndex: [s length] - 1]; d = [s dataUsingEncoding: NSUTF8StringEncoding]; } ok = NO; } size = [d length]; memcpy(b, (const char*)[d bytes], size); /* * Pad with nuls and ensure there is a nul terminator. */ while ((int)size <= l) { b[size++] = '\0'; } return ok; } - (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l { char buf[l+32]; /* Allow space to expand buffer. */ NSCalendarDate *d; BOOL milliseconds = NO; BOOL timezone = NO; NSString *s; int i; int e; memcpy(buf, b, l); b = buf; /* * Find end of string. */ for (i = 0; i < l; i++) { if (b[i] == '\0') { l = i; break; } } while (l > 0 && isspace(b[l-1])) { l--; } b[l] = '\0'; if (l == 10) { s = [NSString stringWithUTF8String: b]; return [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d" locale: nil]; } i = l; /* Convert +/-HH:SS timezone to +/-HHSS */ if (i > 5 && b[i-3] == ':' && (b[i-6] == '+' || b[i-6] == '-')) { b[i-3] = b[i-2]; b[i-2] = b[i-1]; b[--i] = '\0'; } while (i-- > 0) { if (b[i] == '+' || b[i] == '-') { break; } if (b[i] == ':' || b[i] == ' ') { i = 0; break; /* No time zone found */ } } if (i == 0) { e = l; } else { timezone = YES; e = i; if (isdigit(b[i-1])) { /* * Make space between seconds and timezone. */ memmove(&b[i+1], &b[i], l - i); b[i++] = ' '; b[++l] = '\0'; } /* * Ensure we have a four digit timezone value. */ if (isdigit(b[i+1]) && isdigit(b[i+2])) { if (b[i+3] == '\0') { // Two digit time zone ... append zero minutes b[l++] = '0'; b[l++] = '0'; b[l] = '\0'; } else if (b[i+3] == ':') { // Zone with colon before minutes ... remove it b[i+3] = b[i+4]; b[i+4] = b[i+5]; b[--l] = '\0'; } } } /* kludge for timestamps with fractional second information. * Force it to 3 digit millisecond */ while (i-- > 0) { if (b[i] == '.') { milliseconds = YES; i++; if (!isdigit(b[i])) { memmove(&b[i+3], &b[i], e-i); l += 3; memcpy(&b[i], "000", 3); } i++; if (!isdigit(b[i])) { memmove(&b[i+2], &b[i], e-i); l += 2; memcpy(&b[i], "00", 2); } i++; if (!isdigit(b[i])) { memmove(&b[i+1], &b[i], e-i); l += 1; memcpy(&b[i], "0", 1); } i++; break; } } if (i > 0 && i < e) { memmove(&b[i], &b[e], l - e); l -= (e - i); } b[l] = '\0'; if (l == 0) { return nil; } s = [NSString stringWithUTF8String: b]; if (YES == timezone) { if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F %z" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; } } else { if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S" locale: nil]; } } [d setCalendarFormat: @"%Y-%m-%d %H:%M:%S %z"]; return d; } /** * Convert from a database character buffer to an NSString. */ - (NSString*) dbToStringFromBuffer: (char*)b length: (int)l { NSData *d; NSString *s; /* * Database fields are padded to the full field size with spaces or nuls ... * we need to remove that padding before placing in a string. */ while (l > 0 && b[l-1] <= ' ') { l--; } d = [[NSData alloc] initWithBytes: b length: l]; s = [[NSString alloc] initWithData: d encoding: NSUTF8StringEncoding]; RELEASE(d); return AUTORELEASE(s); } @end SQLClient-1.9.0/Performance.import000066400000000000000000000000451436027104400170140ustar00rootroot00000000000000 import gnu.gnustep.Performance.*; SQLClient-1.9.0/Postgres.m000066400000000000000000001361211436027104400153100ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientPostgres for GNUStep Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #include "config.h" #define SQLCLIENT_PRIVATE @public #include "SQLClient.h" #include @interface SQLClientPostgres : SQLClient { NSDictionary *options; } @end @interface SQLClientPostgres(Embedded) - (NSData*) dataFromBLOB: (const char *)blob; - (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l; @end #if defined(GNUSTEP_BASE_LIBRARY) && !defined(__MINGW__) @interface SQLClientPostgres (RunLoop) - (void) receivedEvent: (void*)data type: (RunLoopEventType)type extra: (void*)extra forMode: (NSString*)mode; @end #endif typedef struct { PGconn *_connection; int _backendPID; int _descriptor; // For monitoring in run loop NSRunLoop *_runLoop; // For listen/unlisten monitoring NSDictionary *_options; } ConnectionInfo; #define cInfo ((ConnectionInfo*)(self->extra)) #define backendPID (cInfo->_backendPID) #define connection (cInfo->_connection) #define options (cInfo->_options) static NSDate *future = nil; static NSNull *null = nil; #if defined(GNUSTEP) static NSString *placeholder = nil; #else static Class stringClass = Nil; static SEL allocStringSel = 0; static IMP allocStringImp = 0; #endif static SEL initStringSel = 0; static IMP initStringImp = 0; static NSTimeZone *zones[47]; // For -23 to +23 hours static inline NSString* newString(const char *b, int l, NSStringEncoding e) { #if defined(GNUSTEP) return (*initStringImp)(placeholder, initStringSel, b, l, e); #else NSString *s = (*allocStringImp)(stringClass, allocStringSel); return (*initStringImp)(s, initStringSel, b, l, e); #endif } static NSDate* newDateFromBuffer(const char *b, int l) { NSCalendarDate *d; NSTimeZone *zone = nil; int milliseconds = 0; int day; int month; int year; int hour; int minute; int second; int i; i = 0; if (i >= l || !isdigit(b[i])) return nil; year = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; year = year * 10 + b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; year = year * 10 + b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; year = year * 10 + b[i++] - '0'; if (i >= l || b[i++] != '-') return nil; if (i >= l || !isdigit(b[i])) return nil; month = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; month = month * 10 + b[i++] - '0'; if (month < 1 || month > 12) return nil; if (i >= l || b[i++] != '-') return nil; if (i >= l || !isdigit(b[i])) return nil; day = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; day = day * 10 + b[i++] - '0'; if (day < 1 || day > 31) return nil; if (i == l) { hour = 0; minute = 0; second = 0; zone = [NSTimeZone localTimeZone]; } else { if (i >= l || b[i++] != ' ') return nil; if (i >= l || !isdigit(b[i])) return nil; hour = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; hour = hour * 10 + b[i++] - '0'; if (hour < 0 || hour > 23) return nil; if (i >= l || b[i++] != ':') return nil; if (i >= l || !isdigit(b[i])) return nil; minute = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; minute = minute * 10 + b[i++] - '0'; if (minute < 0 || minute > 59) return nil; if (i >= l || b[i++] != ':') return nil; if (i >= l || !isdigit(b[i])) return nil; second = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; second = second * 10 + b[i++] - '0'; if (second < 0 || second > 60) return nil; if (i < l && '.' == b[i]) { i++; if (i >= l || !isdigit(b[i])) return nil; milliseconds = b[i++] - '0'; milliseconds *=- 10; if (i < l && isdigit(b[i])) milliseconds += b[i++] - '0'; milliseconds *=- 10; if (i < l && isdigit(b[i])) milliseconds += b[i++] - '0'; while (i < l && isdigit(b[i])) i++; } if (i < l && ('+' == b[i] || '-' == b[i])) { char sign = b[i++]; int timezone; if (i >= l || !isdigit(b[i])) return nil; timezone = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; timezone = timezone * 10 + b[i++] - '0'; if (timezone < 0 || timezone > 23) return nil; timezone *= 60; // Convert to minutes if (i < l && ':' == b[i]) { int tzmin; i++; if (i >= l || !isdigit(b[i])) return nil; tzmin = b[i++] - '0'; if (i >= l || !isdigit(b[i])) return nil; tzmin = tzmin * 10 + b[i++] - '0'; if (tzmin < 0 || tzmin > 59) return nil; timezone += tzmin; } if ('-' == sign) timezone = -timezone; if (timezone % 60 == 0) { zone = zones[23 + timezone / 60]; } else { zone = [NSTimeZone timeZoneForSecondsFromGMT: timezone * 60]; } } else { zone = [NSTimeZone localTimeZone]; } } d = [NSCalendarDate alloc]; if (year <= 1) { static NSTimeInterval p = 0.0; if (0.0 == p) { p = [[NSDate distantPast] timeIntervalSinceReferenceDate]; } d = [d initWithTimeIntervalSinceReferenceDate: p]; [d setTimeZone: zone]; } else if (year > 4000) { static NSTimeInterval f = 0.0; if (0.0 == f) { f = [[NSDate distantFuture] timeIntervalSinceReferenceDate]; } d = [d initWithTimeIntervalSinceReferenceDate: f]; [d setTimeZone: zone]; } else { d = [d initWithYear: year month: month day: day hour: hour minute: minute second: second timeZone: zone]; if (milliseconds > 0) { NSTimeInterval ti; ti = milliseconds; ti /= 1000.0; ti += [d timeIntervalSinceReferenceDate]; d = [d initWithTimeIntervalSinceReferenceDate: ti]; [d setTimeZone: zone]; } } [d setCalendarFormat: @"%Y-%m-%d %H:%M:%S %z"]; return d; } static inline NSString * sanitize(NSString *str, NSRange range) { if (range.length != 0) { str = [str stringByReplacingCharactersInRange: range withString: @"'******'"]; } return str; } @implementation SQLClientPostgres + (void) initialize { if (future == nil) { int i; initStringSel = @selector(initWithBytes:length:encoding:); #if defined(GNUSTEP) placeholder = [NSString alloc]; initStringImp = [[placeholder class] instanceMethodForSelector: initStringSel]; #else stringClass = [NSString class]; allocStringSel = @selector(alloc); allocStringImp = [stringClass methodForSelector: allocStringSel]; initStringImp = [stringClass instanceMethodForSelector: initStringSel]; #endif future = [NSCalendarDate dateWithString: @"9999-01-01 00:00:00 +0000" calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; [future retain]; null = [NSNull null]; [null retain]; for (i = -23; i <= 23; i++) { zones[i + 23] = [[NSTimeZone timeZoneForSecondsFromGMT: i * 60 * 60] retain]; } } } static NSString* connectQuote(NSString *str) { NSMutableString *m; m = [str mutableCopy]; [m replaceString: @"\\" withString: @"\\\\"]; [m replaceString: @"'" withString: @"\\'"]; [m replaceCharactersInRange: NSMakeRange(0, 0) withString: @"'"]; [m appendString: @"'"]; return [m autorelease]; } /* Encapsulates cleanup to be done when the database connection is lost * or should be dropped by us (eg due to an unrecoverable error). */ - (void) _backendDisconnected { if (extra != 0 && connection != 0) { #if defined(GNUSTEP_BASE_LIBRARY) && !defined(__MINGW__) if (cInfo->_runLoop != nil) { if (cInfo->_descriptor >= 0) { [cInfo->_runLoop removeEvent: (void*)(uintptr_t)cInfo->_descriptor type: ET_RDESC forMode: NSDefaultRunLoopMode all: YES]; cInfo->_descriptor = -1; } DESTROY(cInfo->_runLoop); } #endif PQfinish(connection); connection = 0; connected = NO; } } - (BOOL) backendConnect { if (extra == 0) { extra = NSZoneMalloc(NSDefaultMallocZone(), sizeof(ConnectionInfo)); memset(extra, '\0', sizeof(ConnectionInfo)); cInfo->_descriptor = -1; } if (connection == 0) { connected = NO; if ([self database] != nil) { NSString *host = nil; NSString *port = nil; NSString *dbase = [self database]; NSString *sslmode = [options objectForKey: @"sslmode"]; NSString *str; NSRange r; NSRange pwRange = NSMakeRange(NSNotFound, 0); NSMutableString *m; [[self class] purgeConnections: nil]; r = [dbase rangeOfString: @"@"]; if (r.length > 0) { host = [dbase substringFromIndex: NSMaxRange(r)]; dbase = [dbase substringToIndex: r.location]; r = [host rangeOfString: @":"]; if (r.length > 0) { port = [host substringFromIndex: NSMaxRange(r)]; host = [host substringToIndex: r.location]; } } m = [NSMutableString stringWithCapacity: 156]; [m appendString: @"dbname="]; [m appendString: connectQuote(dbase)]; str = connectQuote(host); if (str != nil) { unichar c = [str characterAtIndex: 1]; if (c >= '0' && c <= '9') { [m appendString: @" hostaddr="]; // Numeric IP } else { [m appendString: @" host="]; // Domain name } [m appendString: str]; } str = connectQuote(port); if (str != nil) { [m appendString: @" port="]; [m appendString: str]; } str = connectQuote([self user]); if (str != nil) { [m appendString: @" user="]; [m appendString: str]; } str = connectQuote([self password]); if (str != nil) { [m appendString: @" password="]; pwRange = NSMakeRange([m length], [str length]); [m appendString: str]; } str = connectQuote([self clientName]); if (str != nil) { [m appendString: @" application_name="]; [m appendString: str]; } if ([sslmode isEqual: @"require"]) { str = connectQuote(@"require"); if (str != nil) { [m appendString: @" sslmode="]; [m appendString: str]; } } if ([self debugging] > 0) { [self debug: @"Connect to '%@' as %@ (%@)", sanitize(m, pwRange), [self name], [self clientName]]; } connection = PQconnectdb([m UTF8String]); if (PQstatus(connection) != CONNECTION_OK) { [self debug: @"Error connecting to '%@' (%@) - %s", [self name], sanitize(m, pwRange), PQerrorMessage(connection)]; [self _backendDisconnected]; } else if (PQsetClientEncoding(connection, "UTF-8") < 0) { [self debug: @"Error setting UTF-8 with '%@' (%@) - %s", [self name], sanitize(m, pwRange), PQerrorMessage(connection)]; [self _backendDisconnected]; } else { const char *p; backendPID = PQbackendPID(connection); connected = YES; p = PQparameterStatus(connection, "standard_conforming_strings"); if (p != 0) { PGresult *result; /* If the escape_string_warning setting is on, * the server will warn about backslashes even * in properly quoted strings, so turn it off. */ if (strcmp(p, "on") == 0) { result = PQexec(connection, "SET escape_string_warning=off"); } else { result = PQexec(connection, "SET standard_conforming_strings=on;" "SET escape_string_warning=off"); } if (0 == result || PQresultStatus(result) != PGRES_COMMAND_OK) { [self debug: @"Error setting string handling" @" with '%@' (%@) - %s", [self name], sanitize(m, pwRange), PQerrorMessage(connection)]; if (result != 0) { PQclear(result); result = 0; } [self _backendDisconnected]; } if (result != 0) { PQclear(result); } } else { [self _backendDisconnected]; [self debug: @"Postgres without standard conforming strings"]; } if ([self debugging] > 0) { if (YES == connected) { [self debug: @"Connected to '%@'", [self name]]; } else { [self debug: @"Disconnected '%@'", [self name]]; } } } } else { [self debug: @"Connect to '%@' with no user/password/database configured", [self name]]; } } return connected; } /* Called by the -disconnect method aftert it has updated ivars/locks. */ - (void) backendDisconnect { if (extra != 0 && connection != 0) { NS_DURING { if ([self debugging] > 0) { [self debug: @"Disconnecting client %@", [self clientName]]; } [self _backendDisconnected]; if ([self debugging] > 0) { [self debug: @"Disconnected client %@", [self clientName]]; } } NS_HANDLER { connection = 0; [self debug: @"Error disconnecting from database (%@): %@", [self clientName], localException]; } NS_ENDHANDLER } connected = NO; } - (void) _postNotification: (NSNotification*)n { NSNotificationQueue *nq; /* Post asynchronously */ if ([self debugging] > 0) { [self debug: @"Notified (database): %@", n]; } nq = [NSNotificationQueue defaultQueue]; [nq enqueueNotification: n postingStyle: NSPostASAP coalesceMask: NSNotificationNoCoalescing forModes: nil]; } - (void) _postNotifications: (NSArray*)notifications { NSUInteger count = [notifications count]; NSUInteger index; for (index = 0; index < count; index++) { NSNotification *n = [notifications objectAtIndex: index]; NS_DURING { [self _postNotification: n]; } NS_HANDLER { NSLog(@"Problem posting notification: %@ %@", n, localException); } NS_ENDHANDLER } } - (void) _post: (NSMutableArray*)notifications { if ([notifications count] > 0) { if ([[NSRunLoop currentRunLoop] currentMode] == nil) { if ([self debugging] > 0) { [self debug: @"Notifying (main thread): %@", notifications]; } NS_DURING { [self performSelectorOnMainThread: @selector(_postNotifications:) withObject: notifications waitUntilDone: NO]; } NS_HANDLER { NSLog(@"Problem posting to main thread: %@ %@", notifications, localException); } NS_ENDHANDLER } else { if ([self debugging] > 0) { [self debug: @"Notifying (receiving thread): %@", notifications]; } NS_DURING { [self _postNotifications: notifications]; } NS_HANDLER { NSLog(@"Problem posting in receiving thread: %@ %@", notifications, localException); } NS_ENDHANDLER } [notifications removeAllObjects]; } } /* This method must only be called when the receiver is locked. */ - (void) _checkNotifications: (BOOL)async { NSMutableArray *notifications = nil; PGnotify *notify; /* While postgres sometimes de-duplicates notifications it is not guaranteed * that it will do so, and it is therefore possible for the database server * to send many duplicate notifications. * So we read the notifications and add them to an array only if they are not * already present, flushing the buffer when it gets large. */ while ((notify = PQnotifies(connection)) != 0) { NS_DURING { static NSNumber *nY = nil; static NSNumber *nN = nil; NSNotification *n; NSMutableDictionary *userInfo; NSString *name; if (nil == nN) { ASSIGN(nN, [NSNumber numberWithBool: NO]); } if (nil == nY) { ASSIGN(nY, [NSNumber numberWithBool: YES]); } name = [[NSString alloc] initWithUTF8String: notify->relname]; userInfo = [[NSMutableDictionary alloc] initWithCapacity: 3]; if (0 != notify->extra) { NSString *payload; payload = [[NSString alloc] initWithUTF8String: notify->extra]; if (nil != payload) { [userInfo setObject: payload forKey: @"Payload"]; RELEASE(payload); } } if (notify->be_pid == backendPID) { [userInfo setObject: nY forKey: @"Local"]; } else { [userInfo setObject: nN forKey: @"Local"]; } if (YES == async) { [userInfo setObject: nY forKey: @"Async"]; } else { [userInfo setObject: nN forKey: @"Async"]; } n = [NSNotification notificationWithName: name object: self userInfo: (NSDictionary*)userInfo]; if (nil == notifications) { notifications = [[NSMutableArray alloc] initWithCapacity: 10]; } if (NO == [notifications containsObject: n]) { [notifications addObject: n]; } RELEASE(name); RELEASE(userInfo); } NS_HANDLER { NSLog(@"Problem handling %@ notification: %@", (async ? @"asynchronous" : @"query/execute"), localException); } NS_ENDHANDLER PQfreemem(notify); if ([notifications count] >= 1000) { NSLog(@"WARNING ... 1000 dbase notifications in buffer (flushing)"); [self _post: notifications]; } } /* Now that we have read all the available notifications from the database, * we post them locally in the current thread (if its run loop is active) * or the main thread. */ [self _post: notifications]; RELEASE(notifications); } - (NSInteger) backendExecute: (NSArray*)info { NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSInteger rowCount = -1; PGresult *result = 0; NSString *stmt = SQLClientUnProxyLiteral([info objectAtIndex: 0]); if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } NS_DURING { const char *statement; const char *tuples; unsigned length; statement = (char*)[stmt UTF8String]; length = strlen(statement); statement = [self insertBLOBs: info intoStatement: statement length: length withMarker: "'?'''?'" length: 7 giving: &length]; result = PQexec(connection, statement); if (0 == result || (PQresultStatus(result) != PGRES_COMMAND_OK && PQresultStatus(result) != PGRES_TUPLES_OK)) { NSString *str; const char *cstr; if (0 == result) { cstr = PQerrorMessage(connection); } else { cstr = PQresultErrorMessage(result); } str = [NSString stringWithUTF8String: cstr]; if (nil == str) { str = [NSString stringWithCString: cstr]; } if (result != 0) { PQclear(result); result = 0; } if (PQstatus(connection) != CONNECTION_OK) { [self disconnect]; [NSException raise: SQLConnectionException format: @"Error executing %@: %@", stmt, str]; } else { [NSException raise: SQLException format: @"Error executing %@: %@", stmt, str]; } } tuples = PQcmdTuples(result); if (0 != tuples) { rowCount = atol(tuples); } } NS_HANDLER { if (result != 0) { PQclear(result); } if (YES == connected && PQstatus(connection) != CONNECTION_OK) { [self disconnect]; } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER if (result != 0) { PQclear(result); } [self _checkNotifications: NO]; [arp release]; return rowCount; } - (void) backendListen: (NSString*)name { [self execute: @"LISTEN ", name, nil]; #if defined(GNUSTEP_BASE_LIBRARY) && !defined(__MINGW__) if (extra != 0 && connection != 0) { if (nil == cInfo->_runLoop) { ASSIGN(cInfo->_runLoop, [NSRunLoop currentRunLoop]); if (nil == cInfo->_runLoop) { [NSException raise: NSInternalInconsistencyException format: @"Observer can't be set up ... no runloop in thread"]; } } else if ([NSRunLoop currentRunLoop] != cInfo->_runLoop) { [NSException raise: NSInternalInconsistencyException format: @"Observer added to the same client from another runloop"]; } if (cInfo->_descriptor < 0) { int descriptor = PQsocket(connection); if (descriptor < 0) { DESTROY(cInfo->_runLoop); [NSException raise: NSInternalInconsistencyException format: @"Observer can't be set up ... bad file descriptor"]; } cInfo->_descriptor = descriptor; } [cInfo->_runLoop addEvent: (void*)(uintptr_t)cInfo->_descriptor type: ET_RDESC watcher: self forMode: NSDefaultRunLoopMode]; } #endif } - (void) backendNotify: (NSString*)name payload: (NSString*)more { if (nil == more) { [self execute: @"NOTIFY ", name, nil]; } else { [self execute: @"NOTIFY ", name, @",", [self quote: more], nil]; } } static inline unsigned int trim(char *str, unsigned len) { while (len > 0 && isspace(str[len - 1])) { len--; } return len; } - (char*) parseIntoArray: (NSMutableArray *)a type: (int)t from: (char*)p { p++; /* Step past '{' */ while (*p && *p != '}') { id v = nil; /* Ignore leading space before field data. */ while (isspace(*p)) { p++; } if ('{' == *p) { /* Found a nested array. */ v = [[NSMutableArray alloc] initWithCapacity: 10]; p = [self parseIntoArray: v type: t from: p]; } else if ('\"' == *p) { char *start = ++p; int len = 0; /* Found something quoted (char, varchar, text, bytea etc) */ while (*p != '\0' && *p != '\"') { if ('\\' == *p) { p++; } p++; len++; } if ('\"' == *p) { *p = '\0'; } if (len == (p - start)) { if ('T' == t) { /* This is expected to be a timestamp */ v = newDateFromBuffer(start, p - start); } else if ('D' == t) { /* This is expected to be bytea data */ v = [[self dataFromBLOB: start] retain]; } else { v = newString(start, p - start, NSUTF8StringEncoding); } } else { char *buf; char *ptr; int i; buf = malloc(len+1); ptr = start; i = 0; while (*ptr != '\0') { if ('\\' == *ptr) { ptr++; } buf[i++] = *ptr++; } buf[len] = '\0'; if ('T' == t) { /* This is expected to be a timestamp */ v = newDateFromBuffer(buf, len); free(buf); } else if ('D' == t) { /* This is expected to be bytea data */ v = [[self dataFromBLOB: buf] retain]; free(buf); } else { v = [NSString alloc]; v = [v initWithBytesNoCopy: buf length: len encoding: NSUTF8StringEncoding freeWhenDone: YES]; } } *p++ = '\"'; } else { char *start = p; char save; int len; /* This is an unquoted field ... could be NULL or a boolean, * or a numeric field, or a timestamp or just a simple string. */ while (*p != '\0' && *p != ',' && *p != '}') { p++; } save = *p; *p = '\0'; len = trim(start, p - start); if (strcmp(start, "NULL") == 0) { v = null; } else if ('T' == t) { v = newDateFromBuffer(start, len); } else if ('D' == t) { v = [[self dataFromBLOB: start] retain]; } else if ('B' == t) { if (*start == 't') v = @"YES"; else v = @"NO"; } else if ('I' == t || 'F' == t) { v = SQLClientNewLiteral(start, p - start); } else { v = newString(start, p - start, NSUTF8StringEncoding); } *p = save; } if (nil != v) { [a addObject: v]; [v release]; } if (',' == *p) { p++; } } if ('}' == *p) { p++; } return p; } - (id) newParseField: (char *)p type: (int)t size: (int)s { char arrayType = 0; switch (t) { case 1082: // Date (treat as string) s = trim(p, s); return newString(p, s, NSASCIIStringEncoding); case 1083: // Time (treat as string) s = trim(p, s); return newString(p, s, NSASCIIStringEncoding); case 1114: // Timestamp without time zone. case 1184: // Timestamp with time zone. return newDateFromBuffer(p, trim(p, s)); case 16: // BOOL if (*p == 't') { return @"YES"; } else { return @"NO"; } case 17: // BYTEA return [[self dataFromBLOB: p] retain]; case 18: // "char" return newString(p, s, NSUTF8StringEncoding); case 20: // INT8 case 21: // INT2 case 23: // INT4 s = trim(p, s); return SQLClientNewLiteral(p, s); case 700: // FLOAT4 case 701: // FLOAT8 s = trim(p, s); return SQLClientNewLiteral(p, s); case 1115: // TS without TZ ARRAY case 1185: // TS with TZ ARRAY if (0 == arrayType) arrayType = 'T'; // Timestamp case 1000: // BOOL ARRAY if (0 == arrayType) arrayType = 'B'; // Boolean case 1001: // BYTEA ARRAY if (0 == arrayType) arrayType = 'D'; // Data case 1005: // INT2 ARRAY case 1007: // INT4 ARRAY case 1016: // INT8 ARRAY if (0 == arrayType) arrayType = 'I'; // Integer case 1021: // FLOAT ARRAY case 1022: // DOUBLE ARRAY if (0 == arrayType) arrayType = 'F'; // Float case 1002: // CHAR ARRAY case 1009: // TEXT ARRAY case 1014: // "char" ARRAY case 1015: // VARCHAR ARRAY case 1182: // DATE ARRAY case 1183: // TIME ARRAY case 1263: // CSTRING ARRAY if ('{' == *p) { NSMutableArray *a; a = [[NSMutableArray alloc] initWithCapacity: 10]; (void)[self parseIntoArray: a type: arrayType from: p]; if ([self debugging] > 2) { NSLog(@"Parsed array is %@", a); } return a; } case 25: // TEXT default: if (YES == _shouldTrim) { s = trim(p, s); } return newString(p, s, NSUTF8StringEncoding); } } - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype { NSAutoreleasePool *arp = [NSAutoreleasePool new]; PGresult *result = 0; NSMutableArray *records = nil; stmt = SQLClientUnProxyLiteral(stmt); if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } NS_DURING { char *statement; statement = (char*)[stmt UTF8String]; result = PQexec(connection, statement); if (0 == result || (PQresultStatus(result) != PGRES_COMMAND_OK && PQresultStatus(result) != PGRES_TUPLES_OK)) { NSString *str; const char *cstr; if (0 == result) { cstr = PQerrorMessage(connection); } else { cstr = PQresultErrorMessage(result); } str = [NSString stringWithUTF8String: cstr]; if (nil == str) { str = [NSString stringWithCString: cstr]; } if (result != 0) { PQclear(result); result = 0; } if (PQstatus(connection) != CONNECTION_OK) { [self disconnect]; [NSException raise: SQLConnectionException format: @"Error executing %@: %@", stmt, str]; } else { [NSException raise: SQLException format: @"Error executing %@: %@", stmt, str]; } } if (PQresultStatus(result) == PGRES_TUPLES_OK) { int recordCount = PQntuples(result); int fieldCount = PQnfields(result); NSString *keys[fieldCount]; int ftype[fieldCount]; int fmod[fieldCount]; int fformat[fieldCount]; SQLRecordKeys *k = nil; int d = [self debugging]; int i; for (i = 0; i < fieldCount; i++) { keys[i] = [NSString stringWithUTF8String: PQfname(result, i)]; ftype[i] = PQftype(result, i); fmod[i] = PQfmod(result, i); fformat[i] = PQfformat(result, i); } records = [[ltype alloc] initWithCapacity: recordCount]; /* Create buffers to store the previous row from the * database and the previous objc values. */ int len[fieldCount]; const char *ptr[fieldCount]; id obj[fieldCount]; for (i = 0; i < fieldCount; i++) { len[i] = -1; obj[i] = nil; } for (i = 0; i < recordCount; i++) { SQLRecord *record; id values[fieldCount]; int j; for (j = 0; j < fieldCount; j++) { id v = null; if (PQgetisnull(result, i, j) == 0) { char *p = PQgetvalue(result, i, j); int size = PQgetlength(result, i, j); if (d > 1) { [self debug: @"%@ type:%d mod:%d size: %d\n", keys[j], ftype[j], fmod[j], size]; } /* Often many rows will contain the same data in * one or more columns, so we check to see if the * value we have just read is small and identical * to the value in the same column of the previous * row. Only if it isn't do we create a new object. */ if (size == len[j] && size <= 20 && memcmp(p, ptr[j], (size_t)size) == 0) { v = obj[j]; } else { [obj[j] release]; if (fformat[j] == 0) // Text { v = [self newParseField: p type: ftype[j] size: size]; obj[j] = v; len[j] = size; ptr[j] = p; } else // Binary { NSLog(@"Binary data treated as NSNull " @"in %@ type:%d mod:%d size:%d\n", keys[j], ftype[j], fmod[j], size); } } } values[j] = v; } if (nil == k) { /* We don't have keys information, so use the * constructor where we list keys and, if the * resulting record provides keys information * on the first record, we save it for later. */ record = [rtype newWithValues: values keys: keys count: fieldCount]; if (0 == i && [record respondsToSelector: @selector(keys)]) { k = [record keys]; } } else { record = [rtype newWithValues: values keys: k]; } [records addObject: record]; [record release]; } for (i = 0; i < fieldCount; i++) { [obj[i] release]; } } else { [NSException raise: SQLException format: @"Error executing %@: %s", stmt, "query produced no result"]; } } NS_HANDLER { if (result != 0) { PQclear(result); result = 0; } if (YES == connected && PQstatus(connection) != CONNECTION_OK) { [self disconnect]; } [records release]; records = nil; [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; if (result != 0) { PQclear(result); } [self _checkNotifications: NO]; return [records autorelease]; } - (void) backendUnlisten: (NSString*)name { #if defined(GNUSTEP_BASE_LIBRARY) && !defined(__MINGW__) if (extra != 0 && cInfo->_runLoop != nil && cInfo->_descriptor >= 0) { BOOL all = ([_names count] == 0) ? YES : NO; /* Remove the event added to listen for this name. * If there are no remaining names listened for, cleanup. */ [cInfo->_runLoop removeEvent: (void*)(uintptr_t)cInfo->_descriptor type: ET_RDESC forMode: NSDefaultRunLoopMode all: all]; if (YES == all) { cInfo->_descriptor = -1; DESTROY(cInfo->_runLoop); } } #endif [self execute: @"UNLISTEN ", name, nil]; } - (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf { const unsigned char *src = [blob bytes]; unsigned sLen = [blob length]; unsigned char *ptr = (unsigned char*)buf; unsigned length = 0; unsigned i; ptr[length++] = 'E'; ptr[length++] = '\''; for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126 || c == '\'') { ptr[length] = '\\'; ptr[length+1] = '\\'; ptr[length + 4] = (c & 7) + '0'; c >>= 3; ptr[length + 3] = (c & 7) + '0'; c >>= 3; ptr[length + 2] = (c & 7) + '0'; length += 5; } else if (c == '\\') { ptr[length++] = '\\'; ptr[length++] = '\\'; ptr[length++] = '\\'; ptr[length++] = '\\'; } else { ptr[length++] = c; } } ptr[length++] = '\''; return length; } - (unsigned) lengthOfEscapedBLOB: (NSData*)blob { unsigned int sLen = [blob length]; unsigned char *src = (unsigned char*)[blob bytes]; unsigned int length = sLen + 2; unsigned int i; length++; // Allow for leading 'E' for (i = 0; i < sLen; i++) { unsigned char c = src[i]; if (c < 32 || c > 126 || c == '\'') { length += 4; } else if (c == '\\') { length += 3; } } return length; } - (NSData *) dataFromBLOB: (const char *)blob { NSMutableData *md; unsigned sLen = strlen(blob == 0 ? "" : blob); unsigned dLen = 0; unsigned char *dst; unsigned i; if (sLen > 1 && '\\' == blob[0] && 'x' == blob[1]) { dLen = (sLen - 2) / 2; dst = (unsigned char*)NSAllocateCollectable(dLen, 0); md = [NSMutableData dataWithBytesNoCopy: dst length: dLen]; dLen = 0; for (i = 2; i < sLen; i += 2) { unsigned hi = blob[i]; unsigned lo = blob[i + 1]; hi = (hi > '9') ? (hi - 'a' + 10) : (hi - '0'); lo = (lo > '9') ? (lo - 'a' + 10) : (lo - '0'); dst[dLen++] = (hi << 4) + lo; } } else { for (i = 0; i < sLen; i++) { unsigned c = blob[i]; dLen++; if (c == '\\') { c = blob[++i]; if (c != '\\') { i += 2; // Skip 2 digits octal } } } dst = (unsigned char*)NSAllocateCollectable(i, dLen); md = [NSMutableData dataWithBytesNoCopy: dst length: dLen]; dLen = 0; for (i = 0; i < sLen; i++) { unsigned c = blob[i]; if (c == '\\') { c = blob[++i]; if (c != '\\') { c = c - '0'; c <<= 3; c += blob[++i] - '0'; c <<= 3; c += blob[++i] - '0'; } } dst[dLen++] = c; } } return md; } - (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l { char buf[l+32]; /* Allow space to expand buffer. */ NSCalendarDate *d; BOOL milliseconds = NO; BOOL timezone = NO; NSString *s; int i; int e; memcpy(buf, b, l); b = buf; /* * Find end of string. */ for (i = 0; i < l; i++) { if (b[i] == '\0') { l = i; break; } } while (l > 0 && isspace(b[l-1])) { l--; } b[l] = '\0'; if (l == 10) { s = [NSString stringWithUTF8String: b]; return [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d" locale: nil]; } i = l; /* Convert +/-HH:SS timezone to +/-HHSS */ if (i > 5 && b[i-3] == ':' && (b[i-6] == '+' || b[i-6] == '-')) { b[i-3] = b[i-2]; b[i-2] = b[i-1]; b[--i] = '\0'; } while (i-- > 0) { if (b[i] == '+' || b[i] == '-') { break; } if (b[i] == ':' || b[i] == ' ') { i = 0; break; /* No time zone found */ } } if (i == 0) { e = l; } else { timezone = YES; e = i; if (isdigit(b[i-1])) { /* * Make space between seconds and timezone. */ memmove(&b[i+1], &b[i], l - i); b[i++] = ' '; b[++l] = '\0'; } /* * Ensure we have a four digit timezone value. */ if (isdigit(b[i+1]) && isdigit(b[i+2])) { if (b[i+3] == '\0') { // Two digit time zone ... append zero minutes b[l++] = '0'; b[l++] = '0'; b[l] = '\0'; } else if (b[i+3] == ':') { // Zone with colon before minutes ... remove it b[i+3] = b[i+4]; b[i+4] = b[i+5]; b[--l] = '\0'; } } } /* kludge for timestamps with fractional second information. * Force it to 3 digit millisecond */ while (i-- > 0) { if (b[i] == '.') { milliseconds = YES; i++; if (!isdigit(b[i])) { memmove(&b[i+3], &b[i], e-i); l += 3; memcpy(&b[i], "000", 3); } i++; if (!isdigit(b[i])) { memmove(&b[i+2], &b[i], e-i); l += 2; memcpy(&b[i], "00", 2); } i++; if (!isdigit(b[i])) { memmove(&b[i+1], &b[i], e-i); l += 1; memcpy(&b[i], "0", 1); } i++; break; } } if (i > 0 && i < e) { memmove(&b[i], &b[e], l - e); l -= (e - i); } b[l] = '\0'; if (l == 0) { return nil; } s = [NSString stringWithUTF8String: b]; if (YES == timezone) { if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F %z" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S %z" locale: nil]; } } else { if (milliseconds == YES) { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S.%F" locale: nil]; } else { d = [NSCalendarDate dateWithString: s calendarFormat: @"%Y-%m-%d %H:%M:%S" locale: nil]; } } [d setCalendarFormat: @"%Y-%m-%d %H:%M:%S %z"]; return d; } - (void) dealloc { if (extra != 0) { if (YES == connected) { [self disconnect]; } RELEASE(options); NSZoneFree(NSDefaultMallocZone(), extra); } [super dealloc]; } - (NSMutableString*) quoteArray: (NSArray *)a toString: (NSMutableString *)s quotingStrings: (BOOL)q { NSUInteger count; NSUInteger index; NSAssert([a isKindOfClass: [NSArray class]], NSInvalidArgumentException); if (nil == s) { s = [NSMutableString stringWithCapacity: 1000]; } [s appendString: @"ARRAY["]; count = [a count]; for (index = 0; index < count; index++) { id o = [a objectAtIndex: index]; if (index > 0) { [s appendString: @","]; } if ([o isKindOfClass: [NSArray class]]) { [self quoteArray: (NSArray *)o toString: s quotingStrings: q]; } else if ([o isKindOfClass: [NSString class]]) { if (YES == q) { o = [self quoteString: (NSString*)o]; } [s appendString: (NSString*)o]; } else if ([o isKindOfClass: [NSDate class]]) { [s appendString: [self quote: (NSString*)o]]; [s appendString: @"::timestamp with time zone"]; } else if ([o isKindOfClass: [NSData class]]) { unsigned len = [self lengthOfEscapedBLOB: o]; uint8_t *buf; buf = malloc(len+1); [self copyEscapedBLOB: o into: buf]; buf[len] = '\0'; [s appendFormat: @"%s::bytea", buf]; free(buf); } else { o = [self quote: (NSString*)o]; [s appendString: (NSString*)o]; } } [s appendString: @"]"]; return s; } - (void) setOptions: (NSDictionary*)o { if (0 == extra) { extra = NSZoneMalloc(NSDefaultMallocZone(), sizeof(ConnectionInfo)); memset(extra, '\0', sizeof(ConnectionInfo)); cInfo->_descriptor = -1; } ASSIGNCOPY(options, o); } @end #if defined(GNUSTEP_BASE_LIBRARY) && !defined(__MINGW__) @implementation SQLClientPostgres (RunLoop) - (void) receivedEvent: (void*)data type: (RunLoopEventType)type extra: (void*)extra forMode: (NSString*)mode { BOOL wasConnected; /* Ensure that the receiver is locked so that no other thread can * be using the database connection while we use it. */ [lock lock]; wasConnected = [self connected]; if (0 == connection) { /* The connection has gone, so we must remove the descriptor from * the current run loop as we can no longer handle events. */ [[NSRunLoop currentRunLoop] removeEvent: data type: ET_RDESC forMode: NSDefaultRunLoopMode all: YES]; [self debug: @"Listen event on disconnected client, desc: %d", (int)data]; } else { if (0 == PQconsumeInput(connection)) { NSString *nam = [[[self name] copy] autorelease]; char msg[1000]; strncpy(msg, PQerrorMessage(connection), sizeof(msg)-1); msg[sizeof(msg)-1] = '\0'; if (PQstatus(connection) != CONNECTION_OK || PQsocket(connection) != (int)data) { /* The connection has been lost, so we must disconnect, * which will stop us receiving events on the descriptor. */ [self disconnect]; } [self debug: @"Error consuming input for '%@' - %s", nam, msg]; } else { [self _checkNotifications: YES]; } } /* If we are listening, try to reconnect. */ if (YES == wasConnected && NO == [self connected] && [_names count] > 0) { [self connect]; } [lock unlock]; } @end #endif SQLClient-1.9.0/README000066400000000000000000000105371436027104400142060ustar00rootroot00000000000000What is the SQLClient library? The SQLClient library is designed to provide a simple interface to SQL databases for GNUstep applications. It does not attempt the sort of abstraction provided by the much more sophisticated GDL2 library but rather allows applications to directly execute SQL queries and statements. SQLClient provides for the Objective-C programmer much the same thing that JDBC provides for the Java programmer (though SQLClient is a bit faster, easier to use, and easier to add new database backends for than JDBC). The major features of the SQLClient library are - * Simple API for executing queries and statements... a variable length sequence of comma separated strings and other objects (NSNumber, NSDate, NSData) are concatenated into a single SQL statement and executed. * Simple API for combining multiple SQL statements into a single transaction which can be used to minimise client-server interactions to get the best possible performance from your database. * Supports multiple sumultaneous named connections to a database server in a thread-safe manner. * Supports multiple simultaneous connections to different database servers with backend driver bundles loaded for different database engines. Clear, simple subclassing of the abstract base class to enable easy implementation of new backend bundles. * Configuration for all connections held in one place and referenced by connection name for ease of configuration control. Changes via NSUserDefaults can even allow reconfiguration of client instances within a running application. * Thread safe operation... The base class supports locking such that a single instance can be shared between multiple threads. What backend bundles are available? Current backend bundles are - * ECPG - a bundle using the embedded SQL interface for postgres. This is based on a similar code which has been in production use for over eighteen months, so it should be reliable. * Postgres - a bundle using the libpq native interface for postgres. This is the preferred backend as it allows 'SELECT FOR UPDATE', which the ECPG backend cannot support due to limitations in the postgres implementation of cursors. Now well tested efficient, and in use in large commercial systems. * MySQL - a bundle using the mysqlclient library for *recent* MySQL. I don't use MySQL... but the test program ran successfully with a vanilla install of the MySQL packages for recent Debian unstable. * SQLite - a bundle using the sqlite3 library which supports an SQL-like API for direct access to a database file (rather than acting as a client of a database server process). Not as functional as the other backends (doesn't support dates for instance), but good enough for many purposes and very 'lightweight'. See http://www.sqlite.org * Oracle - a bundle using embedded SQL for Oracle. Completely untested... may even need some work to compile... but this *is* based on code which was working about a year ago. No support for BLOBs yet. Where can you get it? How can you install it? The SQLClient library is currently available at or via CVS from the GNUstep CVS repository (See . Check out gnustep/dev-libs/SQLClient). To build this library you must have a basic GNUstep environment set up... * The gnustep-make package must have been built and installed. * The gnustep-base package must have been built and installed. * The Performance library (from the dev-libs area in GNUstep CVS) must have been built and installed. * If this environment is in place, all you should need to do is run 'make' to configure and build the library, 'make install' to install it. * Then you can run the test programs. * Your most likely problems are that the configure script may not detect the database libraries you want... Please figure out how to modify configure.ac so that it will detect the required headers and libraries on your system, and supply a patch. Bug reports, patches, and contributions (eg a backend bundle for a new database) should be entered on the GNUstep project page SQLClient-1.9.0/SQLClient.h000066400000000000000000002775701436027104400153110ustar00rootroot00000000000000/** Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. SQLClient documentation The SQLClient library
What is the SQLClient library?

The SQLClient library is designed to provide a simple interface to SQL databases for GNUstep applications. It does not attempt the sort of abstraction provided by the much more sophisticated GDL2 library, but rather allows applications to directly execute SQL queries and statements.

SQLClient provides for the Objective-C programmer much the same thing that JDBC provides for the Java programmer (though SQLClient is a bit faster, easier to use, and easier to add new database backends for than JDBC).

The major features of the SQLClient library are -

Simple API for executing queries and statements ... a variable length sequence of comma separated strings and other objects (NSNumber, NSDate, NSData) are concatenated into a single SQL statement and executed. Simple API ([SQLTransaction])for combining multiple SQL statements into a single transaction which can be used to minimise client-server interactions to get the best possible performance from your database. Supports multiple sumultaneous named connections to a database server in a thread-safe manner.
Supports multiple simultaneous connections to different database servers with backend driver bundles loaded for different database engines. Clear, simple subclassing of the abstract base class to enable easy implementation of new backend bundles. Configuration for all connections held in one place and referenced by connection name for ease of configuration control. Changes via NSUserDefaults can even allow reconfiguration of client instances within a running application. Thread safe operation ... The base class supports locking such that a single instance can be shared between multiple threads. Support for standalone web applications ... eg to allow data to be added to the database by people posting web forms to the application. Supports notification of connection to and disconnection from the database server.
What backend bundles are available?

Current backend bundles are -

ECPG - a bundle using the embedded SQL interface for postgres.
This is based on a similar code which was in production use for over eighteen months, so it should be reliable, but inefficient.
Postgres - a bundle using the libpq native interface for postgres.
This is the preferred backend as it allows 'SELECT FOR UPDATE', which the ECPG backend cannot support due to limitations in the postgres implementation of cursors. The code is now well tested and known to be efficient.
MySQL - a bundle using the mysqlclient library for *recent* MySQL.
I don't use MySQL ... but the test program ran successfully with a vanilla install of the MySQL packages for recent Debian unstable.
SQLite - a bundle using the sqlite3 library which supports an SQL-like API for direct access to a database file (rather than acting as a client of a database server process).
Not as functional as the other backends (doesn't support dates for instance), but good enough for many purposes and very 'lightweight'. See http://www.sqlite.org
Oracle - a bundle using embedded SQL for Oracle.
Completely untested ... may even need some work to compile ... but this *is* based on code which was working about a year ago.
No support for BLOBs yet.
Where can you get it? How can you install it?

The SQLClient library is currently only available via CVS from the GNUstep CVS repository.
See <https://savannah.gnu.org/cvs/?group=gnustep>
You need to check out gnustep/dev-libs/SQLClient

To build this library you must have a basic GNUstep environment set up ...

The gnustep-make package must have been built and installed. The gnustep-base package must have been built and installed. The Performance library (from the dev-libs area in GNUstep CVS) must have been built and installed. If this environment is in place, all you should need to do is run 'make' to configure and build the library, 'make install' to install it. Then you can run the test programs. Your most likely problems are that the configure script may not detect the database libraries you want ... Please figure out how to modify configure.ac so that it will detect the required headers and libraries on your system, and supply na patch. Once the library is installed, you can include the header file <SQLClient/SQLClient.h%gt; and link your programs with the SQLClient library to use it.

Bug reports, patches, and contributions (eg a backend bundle for a new database) should be entered on the GNUstep project page <http://savannah.gnu.org/projects/gnustep> and the bug reporting page <http://savannah.gnu.org/bugs/?group=gnustep>

$Date$ $Revision$ */ #ifndef INCLUDED_SQLClient_H #define INCLUDED_SQLClient_H #import #import #import @class NSConditionLock; @class NSCountedSet; @class NSMapTable; @class NSMutableDictionary; @class NSMutableSet; @class NSRecursiveLock; @class NSThread; @class GSCache; @class SQLClient; @class SQLLiteral; @class SQLTransaction; /** Code including this header should define SQLCLIENT_COMPILE_TIME_QUOTE_CHECK * to enable stricter compile time type checking to ensure that literal strings * are used for sql queries/statements.
* This makes arguments be expected to be SQLLiteral rather than NSString. */ #if defined(SQLCLIENT_COMPILE_TIME_QUOTE_CHECK) #define SQLLitArg SQLLiteral #else #define SQLLitArg NSString #endif /** * Notification sent when an instance becomes connected to the database * server. The notification object is the instance connected. */ extern NSString * const SQLClientDidConnectNotification; /** * Notification sent when an instance becomes disconnected from the database * server. The notification object is the instance disconnected. */ extern NSString * const SQLClientDidDisconnectNotification; #if !defined(SQLCLIENT_PRIVATE) #define SQLCLIENT_PRIVATE @private #endif /** This category is to extend NSObject with SQL oriented helper methods. */ @interface NSObject(SQLClient) /** Trivial method to test a field in a record returned from the database * to see if it is a NULL. This is equivalent to
* (receiver == [NSNull null] ? YES : NO)
*/ - (BOOL) isNull; /** If the receiver can be represented as a 64bit integer, * return the string literal representation as used in SQL, * otherwise raise exception. */ - (SQLLiteral*) quoteBigInteger; /** If the receiver can be represented as a 64bit non-negative integer, * return the string literal representation as used in SQL, * otherwise raise exception. */ - (SQLLiteral*) quoteBigNatural; /** If the receiver can be represented as a 64bit positive (not zero) integer, * return the string literal representation as used in SQL, * otherwise raise exception. */ - (SQLLiteral*) quoteBigPositive; /** If the -boolValue of the -description of the receiver is YES, * return the string literal representation of the SQL true boolean, * otherwise return the string literal false boolean. */ - (SQLLiteral*) quoteInteger; /** Classes may override this method to provide a value for use as part of * an SQL query or statement. The method is used internally when quoting * objects.
* The db argument may be examined to enable a class to support different * quoting for different database backends, but an implementation must at * least support quoting appropriate for standard SQL.
* The default NSObject implementation simply returns nil, which means that * the object may not be used in an SQL query/statement. */ - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db; /** If the receiver can be represented as a 32bit integer, * return the string literal representation as used in SQL, * otherwise raise exception. */ - (SQLLiteral*) quoteInteger; /** If the receiver can be represented as a 32bit non-negative integer, * return the string literal representation as used in SQL, * otherwise raise exception. */ - (SQLLiteral*) quoteNatural; /** If the receiver can be represented as a 32bit positive (not zero) integer, * return the string literal representation as used in SQL, * otherwise raise exception. */ - (SQLLiteral*) quotePositive; @end /** This class is used to hold key information for a set of SQLRecord * objects produced by a single query. */ @interface SQLRecordKeys : NSObject { NSUInteger count; // Number of keys NSArray *order; // Keys in order NSMapTable *map; // Key to index NSMapTable *low; // lowercase map NSUInteger bytes; // Size in bytes } /** Returns the number of keys in the receiver. */ - (NSUInteger) count; /** Returns the index of the object with the specified key, * or NSNotFound if there is no such key. */ - (NSUInteger) indexForKey: (NSString*)key; /** Initialiser */ - (id) initWithKeys: (NSString**)keys count: (NSUInteger)c; /** Returns an array containing the record field names in order. */ - (NSArray*) order; @end /** *

An enhanced array to represent a record returned from a query. * You should NOT try to create instances of this class * except via the +newWithValues:keys:count: method. *

*

SQLRecord is the abstract base class of a class cluster. * If you wish to subclass it you must implement the primitive methods * +newWithValues:keys:count: -count -keyAtIndex: -objectAtIndex: * and -replaceObjectAtIndex:withObject: *

*

NB. You do not need to use SQLRecord (or a subclass of it), all you * actually need to supply is a class which responds to the * +newWithValues:keys:count: method that the system uses to create * new records ... none of the other methods of the SQLRecord class * are used internally by the SQLClient system. *

*/ @interface SQLRecord : NSArray /** * Create a new SQLRecord containing the specified fields.
* NB. The values and keys are retained by the record rather * than being copied.
* A nil value is represented by [NSNull null].
* Keys must be unique string values (case insensitive comparison). */ + (id) newWithValues: (id*)v keys: (NSString**)k count: (unsigned int)c; /** * Create a new SQLRecord containing the specified fields.
* NB. The values and keys are retained by the record rather * than being copied.
* A nil value is represented by [NSNull null].
* This constructor will be used for subsequent records after the first * in a query iff the first record created returns a non-nil result when * sent the -keys method. */ + (id) newWithValues: (id*)v keys: (SQLRecordKeys*)k; /** * Returns an array containing the names of all the fields in the record. */ - (NSArray*) allKeys; /** * Returns the number of items in the record.
* Subclasses must implement this method. */ - (NSUInteger) count; /** * Return the record as a mutable dictionary with the keys as the * record field names standardised to be lowercase strings. */ - (NSMutableDictionary*) dictionary; /** * Optimised mechanism for retrieving all keys in order. */ - (void) getKeys: (id*)buf; /** * Optimised mechanism for retrieving all objects. */ - (void) getObjects: (id*)buf; /** * Returns the key at the specified index.
*/ - (NSString*) keyAtIndex: (NSUInteger)index; /** Returns the keys used by this record. * The abstract class returns nil, so subclasses should override if * they wish to make use of the +newWithValues:keys: method. */ - (SQLRecordKeys*) keys; /** * Returns the object at the specified indes.
*/ - (id) objectAtIndex: (NSUInteger)index; /** * Returns the value of the named field.
* The field name is case insensitive. */ - (id) objectForKey: (NSString*)key; /** * Replaces the value at the specified index.
* Subclasses must implement this method. */ - (void) replaceObjectAtIndex: (NSUInteger)index withObject: (id)anObject; /** * Replaces the value of the named field.
* The field name is case insensitive.
* NB. You must be careful not to change the contents of a record which * has been cached (unless you are sure you really want to), as you will * be changing the contents of the cache, not just a private copy. */ - (void) setObject: (id)anObject forKey: (NSString*)aKey; /** * Return approximate size of this record in bytes.
* The exclude set is used to specify objects to exclude from the * calculation (to prevent recursion etc). */ - (NSUInteger) sizeInBytes: (NSMutableSet*)exclude; @end extern NSString *SQLException; extern NSString *SQLConnectionException; extern NSString *SQLEmptyException; extern NSString *SQLUniqueException; /** * Returns the timestamp of the most recent call to SQLClientTimeNow(). */ extern NSTimeInterval SQLClientTimeLast(); /** * Convenience function to provide timing information quickly.
* This returns the current date/time, and stores the value for use * by the SQLClientTimeLast() function. */ extern NSTimeInterval SQLClientTimeNow(); /** * This returns the timestamp from which any of the SQLClient classes was * first used or SQLClientTimeNow() was first called (whichever came first). */ extern NSTimeInterval SQLClientTimeStart(); /** * A convenience method to return the current clock 'tick' ... which is * the current second based on the time we started. This does not * check the current time, but relies on SQLClientTimeLast() returning an * up to date value (so if you need an accurate tick, you should ensure * that SQLClientTimeNow() is called at least once a second).
* The returned value is always greater than zero, and is basically * calculated as (SQLClientTimeLast() - SQLClientTimeStart() + 1).
* In the event that the system clock is reset into the past, the value * of SQLClientTimeStart() is automatically adjusted to ensure that the * result of a call to SQLClientTimeTick() is never less than the result * of any earlier call to the function. */ extern unsigned SQLClientTimeTick(); @class SQLClientPool; /** *

The SQLClient class encapsulates dynamic SQL access to relational * database systems. A shared instance of the class is used for * each database (as identified by the name of the database), and * the number of simultanous database connections is managed too. *

*

SQLClient is an abstract base class ... when you create an instance * of it, you are actually creating an instance of a concrete subclass * whose implementation is loaded from a bundle. *

*/ @interface SQLClient : NSObject { SQLCLIENT_PRIVATE void *extra; /** For subclass specific data */ NSRecursiveLock *lock; /** Maintain thread-safety */ /** * A flag indicating whether this instance is currently connected to * the backend database server. This variable must only be * set by the -backendConnect or -backendDisconnect methods. */ BOOL connected; /** * A flag indicating whether this instance is currently within a * transaction. This variable must only be * set by the -begin, -commit or -rollback methods. */ BOOL _inTransaction; /** Are we inside a transaction? */ /** * A flag indicating whether leading and trailing white space in values * read from the database should automatically be removed.
* This should only be modified by the -setShouldTrim: method. */ BOOL _shouldTrim; /** Should whitespace be trimmed? */ NSString *_name; /** Unique identifier for instance */ NSString *_client; /** Identifier within backend */ NSString *_database; /** The configured database name/host */ NSString *_password; /** The configured password */ NSString *_user; /** The configured user */ NSMutableArray *_statements; /** Uncommitted statements */ /** * Timestamp of completion of last operation.
* Maintained by -simpleExecute: -simpleQuery:recordType:listType: * and [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] * Also set for a failed connection attempt, but not reported by the * -lastOperation method in that case. */ NSTimeInterval _lastOperation; NSTimeInterval _lastConnect; /** Last successful connect */ NSTimeInterval _lastStart; /** Last op start or connect */ NSTimeInterval _duration; /** Duration logging threshold */ uint64_t _committed; /** Count of committed transactions */ unsigned int _debugging; /** The current debugging level */ GSCache *_cache; /** The cache for query results */ NSThread *_cacheThread; /** Thread for cache queries */ unsigned int _connectFails; /** The count of connection failures */ NSMapTable *_observers; /** Observations of async events */ NSCountedSet *_names; /** Track notification names */ SQLClientPool *_pool; /** The pool of the client (or nil) */ /** Allow for extensions by allocating memory and pointing to it from * the _extra ivar. That way we can avoid binary incompatibility between * minor releases. */ void *_extra; } /** * Returns an array containing all the SQLClient instances . */ + (NSArray*) allClients; /** * Return an existing SQLClient instance (using +existingClient:) if possible, * or creates one, initialises it using -initWithConfiguration:name:, and * returns the new instance (autoreleased).
* Returns nil on failure. */ + (SQLClient*) clientWithConfiguration: (NSDictionary*)config name: (NSString*)reference; /** * Return an existing SQLClient instance for the specified name * if one exists, otherwise returns nil. */ + (SQLClient*) existingClient: (NSString*)reference; /** * Returns the maximum number of simultaneous database connections * permitted (set by +setMaxConnections: and defaults to 8) for * connections outside of SQLClientPool instances. */ + (unsigned int) maxConnections; /** *

Use this method to reduce the number of database connections * currently active so that it is less than the limit set by the * +setMaxConnections: method. This mechanism is used internally * by the class to ensure that, when it is about to open a new * connection, the limit is not exceeded. *

*

If since is not nil, then any connection which has not been * used more recently than that date is disconnected anyway.
* You can (and probably should) use this periodically to purge * idle connections, but you can also pass a date in the future to * close all connections. *

*

Purging does not apply to connections made by SQLClientPool * instances. *

*/ + (void) purgeConnections: (NSDate*)since; /** Sets the retry period after which connection attempts are abandoned. * a delay less than or equal to zero means that connection attempts are * abandoned after the first failure (the -connect method behaves the * same way as the -tryConnect method). */ + (void) setAbandonFailedConnectionsAfter: (NSTimeInterval)delay; /** *

Set the maximum number of simultaneous database connections * permitted (defaults to 8 and may not be set less than 1). *

*

This value is used by the +purgeConnections: method to determine how * many connections should be disconnected when it is called. *

*

Connections used by SQLClientPool instances are not considered by * this maximum. *

*/ + (void) setMaxConnections: (unsigned int)c; /** * Start a transaction for this database client.
* You must match this with either a -commit * or a -rollback.
*

Normally, if you execute an SQL statement without using this * method first, the autocommit feature is employed, and * the statement takes effect immediately. Use of this method * permits you to execute several statements in sequence, and * only have them take effect (as a single operation) when you * call the -commit method. *

*

NB. You must not execute an SQL statement * which would start a transaction directly ... use only this * method. *

*

Where possible, consider using the [SQLTransaction] class rather * than calling -begin -commit or -rollback yourself. *

*/ - (void) begin; /** Returns the number of committed transactions. */ - (uint64_t) committed; /** This grabs the receiver for use by the current thread.
* If limit is nil or in the past, makes a single immediate attempt.
* Returns NO if it fails to obtain a lock by the specified date.
* Must be matched by an -unlock if it succeeds. */ - (BOOL) lockBeforeDate: (NSDate*)limit; /**

Build an sql query string using the supplied arguments to call * [SQLClient-prepare:args:] to build a query and raises an exception * if the result is not a simple query string. *

*

This method has at least one argument, the string starting the * query to be executed (which must have the prefix 'select '). *

*

Additional arguments are a nil terminated list which also be strings, * and these are appended to the statement.
* Arguments in the list are automatically quoted as necessary, with the * behavior for string arguments being controlled by the autoquote setting. *

* * sql = [db buildQuery: @"SELECT Name FROM ", table, nil]; * *

Upon error, an exception is raised. *

*

The method returns a string containing sql suitable for passing to * the -simpleQuery:recordType:listType: * or [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] methods. *

*/ - (SQLLiteral*) buildQuery: (NSString*)stmt,...; /**

Build an sql query string using the supplied arguments to call * [SQLClient-prepare:with:] to build a query and raises an exception * if the result is not a simple query string.
* Takes the query statement and substitutes in values from * the dictionary where markup of the format {key} is found.
* Returns the resulting query string. *

* * sql = [db buildQuery: @"SELECT Name FROM {Table} WHERE ID = {ID}" * with: values]; * *

Arguments in the dictionary are automatically quoted as necessary, * with the behavior for string arguments being controlled by the autoquote * setting.
* The markup format may also be {key?default} where default * is a string to be used if there is no value for the key * in the dictionary. *

*

The method returns a string containing sql suitable for passing to * the -simpleQuery:recordType:listType: * or [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] methods. *

*/ - (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values; /** * Return the client name for this instance.
* Normally this is useful only for debugging/reporting purposes, but * if you are using multiple instances of this class in your application, * and you are using embedded SQL, you will need to use this * method to fetch the client/connection name and store its C-string * representation in a variable 'connectionName' declared to the sql * preprocessor, so you can then have statements of the form - * 'exec sql at :connectionName ...'. */ - (NSString*) clientName; /** * Complete a transaction for this database client.
* This must match an earlier -begin. *

NB. You must not execute an SQL statement * which would commit or rollback a transaction directly ... use * only this method or the -rollback method. *

*

Where possible, consider using the [SQLTransaction] class rather * than calling -begin -commit or -rollback yourself. *

*/ - (void) commit; /** * If the connected instance variable is NO, this method * calls -backendConnect to ensure that there is a connection to the * database server established. Returns the result.
* Performs any necessary locking for thread safety.
* This method also counts the number of consecutive failed connection * attempts. A delay is enforced between each connection attempt, with * the length of the delay growing with each failure. This ensures * that applications which fail to deal with connection failures, and * just keep trying to reconnect, will not overload the system/server.
* The maximum delay is 30 seconds, so when the database server is restarted, * the application can reconnect reasonably quickly.
* If the connection attempt fails it is repeated until it succeds or until * the time interval specified by +setAbandonFailedConnectionsAfter: has * passed. */ - (BOOL) connect; /** * Return a flag to say whether a connection to the database server is * currently live (the value of the 'connected' instance variable).
* This is mostly useful for debug/reporting. */ - (BOOL) connected; /** * Return the database name for this instance (or nil). */ - (NSString*) database; /** * If the connected instance variable is YES, this method * calls -backendDisconnect to ensure that the connection to the * database server is dropped.
* Performs any necessary locking for thread safety. */ - (void) disconnect; /** * Perform arbitrary operation which does not return any value.
* This arguments to this method are a nil terminated list which are * concatenated in the manner of the -query:,... method.
* Arguments in the list are automatically quoted as necessary, with the * behavior for string arguments being controlled by the autoquote setting. * * [db execute: @"UPDATE ", table, @" SET Name = ", * myName, " WHERE ID = ", myId, nil]; * * Where the database backend support it, this method returns the count of * the number of rows to which the operation applied. Otherwise this * returns -1. */ - (NSInteger) execute: (NSString*)stmt,...; /** * Takes the statement and substitutes in values from * the dictionary where markup of the format {key} is found.
* Passes the result to the -execute:,... method. * * [db execute: @"UPDATE {Table} SET Name = {Name} WHERE ID = {ID}" * with: values]; * * Arguments in the dictionary are automatically quoted as necessary, * with the behavior for string arguments being controlled by the autoquote * setting.
* The markup format may also be {key?default} where default * is a string to be used if there is no value for the key * in the dictionary.
* Where the database backend support it, this method returns the count of * the number of rows to which the operation applied. Otherwise this * returns -1. */ - (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values; /** * Calls -initWithConfiguration:name: passing a nil reference name. */ - (id) initWithConfiguration: (NSDictionary*)config; /** * Calls -initWithConfiguration:name:pool: passing NO to say the client is * not in a pool. */ - (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference; /** * Initialise using the supplied configuration, or if that is nil, try to * use values from NSUserDefaults (and automatically update when the * defaults change).
* Uses the reference name to determine configuration information ... and if * a nil name is supplied, defaults to the value of SQLClientName in the * configuration dictionary (or in the standard user defaults). If there is * no value for SQLClientName, uses the string 'Database'.
* If pool is nil and a SQLClient instance already exists with the * name used for this instance, the receiver is deallocated and the existing * instance is retained and returned ... there may only ever be one instance * for a particular reference name which is not in a pool.
*
* The config argument (or the SQLClientReferences user default) * is a dictionary with names as keys and dictionaries * as its values. Configuration entries from the dictionary corresponding * to the database client are used if possible, general entries are used * otherwise.
* Database ... is the name of the database to use, if it is missing * then 'Database' may be used instead.
* User ... is the name of the database user to use, if it is missing * then 'User' may be used instead.
* Password ... is the name of the database user password, if it is * missing then 'Password' may be used instead.
* ServerType ... is the name of the backend server to be used ... by * convention the name of a bundle containing the interface to that backend. * If this is missing then 'Postgres' is used.
* The database name may be of the format 'name@host:port' when you wish to * connect to a database on a different host over the network. */ - (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference pool: (SQLClientPool*)pool; /** Two clients are considered equal if they refer to the same database * and are logged in as the same database user using the same protocol. * These are the general criteria for transactions to be compatoible so * that an SQLTransaction object generated by one client can be used by * the other. */ - (BOOL) isEqual: (id)other; /** * Return the state of the flag indicating whether the library thinks * a transaction is in progress. This flag is normally maintained by * -begin, -commit, and -rollback. */ - (BOOL) isInTransaction; /** * Returns the date/time stamp of the last database connection established * by the receiver, or nil if no connection has ever been established. */ - (NSDate*) lastConnect; /** * Returns the date/time stamp of the last database operation performed * by the receiver, or nil if no operation has ever been done by it.
* Simply connecting to or disconnecting from the databsse does not * count as an operation. */ - (NSDate*) lastOperation; /** Compares the receiver with the other client to see which one has been * inactive but connected for longest (if they are connected) and returns * that instance.
* If neither is idle but connected, the method returns nil.
* In a tie, the method returns the other instance. */ - (SQLClient*) longestIdle: (SQLClient*)other; /** * Return the database reference name for this instance (or nil). */ - (NSString*) name; /** * Return the database password for this instance (or nil). */ - (NSString*) password; /** Calls [SQLClient-prepare:args:] where the argument list needs to be * a nil terminated list of objects. */ - (NSMutableArray*) prepare: (NSString*)stmt, ...; /** * This is the method used to convert a query or statement to a standard * form used internally by other methods.
* This works to build an sql string by quoting any non-literal objects * according to the autoquote setting, and concatenating the resulting * strings in a nil terminated list.
* Returns an array containing the statement as the first object and * any NSData objects following. The NSData objects appear in the * statement strings as the marker sequence - '?'''?'
* If the returned array contains a single object, that object is a * simple SQL query/statement. */ - (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args; /** This method is like [SQLClient-prepare:args:] but takes a dictionary of * values to be substituted into the sql string. */ - (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values; /** *

Perform arbitrary query which returns values. *

*

This method handles its arguments in the same way as the -buildQuery:,... * method and returns the result of the query. *

* * result = [db query: @"SELECT Name FROM ", table, nil]; * *

Upon error, an exception is raised. *

*

The query returns an array of records (each of which is represented * by an SQLRecord object). *

*

Each SQLRecord object contains one or more fields, in the order in * which they occurred in the query. Fields may also be retrieved by name. *

*

NULL field items are returned as NSNull objects. *

*

Most other field items are returned as NSString objects. *

*

Timestamp field items (a date and time) are returned as NSDate objects. * If the database contains no timezone information, the local timezone * is used. *

*/ - (NSMutableArray*) query: (NSString*)stmt,...; /** * Takes the query statement and substitutes in values from * the dictionary (in the same manner as the -buildQuery:with: method) * then executes the query and returns the response.
* * result = [db query: @"SELECT Name FROM {Table} WHERE ID = {ID}" * with: values]; * * Any non-string values in the dictionary will be replaced by * the results of the -quote: method.
* The markup format may also be {key?default} where default * is a string to be used if there is no value for the key * in the dictionary. */ - (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values; /** * Convert an object to a string suitable for use in an SQL query.
* Normally the -execute:,..., and -query:,... methods will call this * method automatically for everything apart from string objects.
* Subclasses may override this method to provide appropriate quoting for * types of object which need database backend specific quoting conventions. * However, the default implementation should be OK for most cases:
* This method makes use of -quoteString: to quote strings.
* It formats NSDate objects as YYYY-MM-DD hh:mm:ss.mmm ?ZZZZ.
* For NSNumber objects it simply uses their string descriptions.
* For NSNull and nil the method returns NULL.
* NSData objects are not quoted ... they must not appear in queries, and * where used for insert/update operations, they need to be passed to the * -backendExecute: method unchanged.
* NSArray and NSSet objects are quoted as sets containing the quoted * elements from the collection. If you want to use SQL arrays (and your * database backend supports it) you must explicitly use the * -quoteArray: method to convert an NSArray to a literal database array * representation.
* Other classes are not supported unless they implement the * -quoteForSQLClient: method to return a non-nil literal string value.
* Attempts to quote an object of an unsupported class (one where the * method returns nil) will cause an NSInvalidArgumentException. */ - (SQLLiteral*) quote: (id)obj; /** * Produce a quoted string from the supplied arguments (printf style). */ - (SQLLiteral*) quotef: (NSString*)fmt, ...; /* Produce a quoted string from an array on databases where arrays are * supported (currently only Postgres). This method is implemented by * calling -quoteArray:toString:quotingStrings: with the option to NOT * quote strings found in the array. */ - (SQLLiteral*) quoteArray: (NSArray*)a; /* Produce a quoted string from an array on databases where arrays are * supported (currently only Postgres). This method is implemented by * calling -quoteArray:toString:quotingStrings: with the option to * quote strings found in the array. */ - (SQLLiteral*) quoteArraySafe: (NSArray*)a; /* Produce a quoted string from an array on databases where arrays are * supported (currently only Postgres).
* If the s argument is nil, a new mutable string is created and returned. * If the s argument is not nil, the quoted array is appended to it rather * than being produced in a new string (this method uses that feature to * recursively quote nested arrays) and the method returns the argument.
* The q argument determines whether string values found in the array * are quoted or added literally.
* NB. Passing NO to prevent strings from being quoted is dangerous since * it could result in an invalid quoted array if any of the array contents * is a string which would not be syntactically valid; use it only when * you are certain that the strings in the array are either already * quoted or are valid representations of some other type. */ - (NSMutableString*) quoteArray: (NSArray *)a toString: (NSMutableString *)s quotingStrings: (BOOL)q; /** * Convert a big (64 bit) integer to a string suitable for use in an SQL query. */ - (SQLLiteral*) quoteBigInteger: (int64_t)i; /** Return the string literal representation of the SQL true boolean * if i is non-zero, and the false boolean if it is zero. */ - (SQLLiteral*) quoteInteger: (int)i; /** * Convert a 'C' string to a string suitable for use in an SQL query * by using -quoteString: to convert it to a literal string format.
* NB. a null pointer is treated as an empty string. */ - (SQLLiteral*) quoteCString: (const char *)s; /** * Convert a single character to a string suitable for use in an SQL query * by using -quoteString: to convert it to a literal string format.
* NB. a nul character is not allowed and will cause an exception. */ - (SQLLiteral*) quoteChar: (char)c; /** * Convert a float to a string suitable for use in an SQL query. */ - (SQLLiteral*) quoteFloat: (double)f; /** * Convert an integer to a string suitable for use in an SQL query. */ - (SQLLiteral*) quoteInteger: (int)i; /** * Convert a string to a form suitable for use as a case sensitive table * or column name in an SQL query. This uses the double quotes character * rather than single quotes.
*/ - (SQLLiteral*) quoteName: (NSString *)s; /** * Quotes the values in any collection (responds to -objectEnumerator) * as a set (bracketed list of values) for use in an SQL query. */ - (SQLLiteral*) quoteSet: (id)obj; /** * Convert a string to a form suitable for use as a string * literal in an SQL query.
* Subclasses may override this for non-standard literal string * quoting conventions. */ - (SQLLiteral*) quoteString: (NSString *)s; /** * Revert a transaction for this database client.
* If there is no transaction in progress, this method does nothing.
*

NB. You must not execute an SQL statement * which would commit or rollback a transaction directly ... use * only this method or the -rollback method. *

*

Where possible, consider using the [SQLTransaction] class rather * than calling -begin -commit or -rollback yourself. *

*/ - (void) rollback; /** * Set the client name for this client.
* If this is not set (or is set to nul) a globally unique string is used.
* NB. Setting the name may not be reflected in the database server until * the client disconnects and reconnects. */ - (void) setClientName: (NSString*)s; /** * Set the database host/name for this object.
* This is called automatically to configure the connection ... * you normally shouldn't need to call it yourself. */ - (void) setDatabase: (NSString*)s; /** * Set the database reference name for this object. This is used to * differentiate between multiple connections to the database.
* This is called automatically to configure the connection ... * you normally shouldn't need to call it yourself.
* NB. attempts to change the name of an instance to that of an existing * instance are ignored. */ - (void) setName: (NSString*)s; /** Sets any backend specific parameters for the database connection. * The base class implementation does nothing; subclasses are expected * to store any optional configuration information that they wish to use * themselves.
* This is called automatically to configure the connection ... * you normally shouldn't need to call it yourself. */ - (void) setOptions: (NSDictionary*)o; /** * Set the database password for this object.
* This is called automatically to configure the connection ... * you normally shouldn't need to call it yourself. */ - (void) setPassword: (NSString*)s; /** Sets an internal flag to indicate whether leading and trailing white * space characters should be removed from values retrieved from the * database by the receiver. */ - (void) setShouldTrim: (BOOL)aFlag; /** * Set the database user for this object.
* This is called automatically to configure the connection ... * you normally shouldn't need to call it yourself. */ - (void) setUser: (NSString*)s; /** * Calls -backendExecute: in a safe manner.
* Handles locking.
* Maintains -lastOperation date.
* Returns the result of the -backendExecute: method call.
* Accepts a mutable array argument (as produced by the prepare methods) * or a simple SQL statement (a string), otherwise raises an exception. */ - (NSInteger) simpleExecute: (id)info; /** * Calls -simpleQuery:recordType:listType: with the default record class * and default array class. */ - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt; /** * Calls -backendQuery:recordType:listType: in a safe manner.
* Handles locking.
* Maintains -lastOperation date.
* The value of rtype must respond to the * [SQLRecord+newWithValues:keys:count:] method.
* If rtype is nil then the [SQLRecord] class is used.
* The value of ltype must respond to the [NSObject+alloc] method to produce * a container which must repond to the [NSMutableArray-initWithCapacity:] * method to initialise itsself and the [NSMutableArray-addObject:] method * to add records to the list.
* If ltype is nil then the [NSMutableArray] class is used.
* This library provides a few helper classes to provide alternative * values for rtype and ltype. */ - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype; /** If there is no database connection, attempts to establish one.
* This does not do automatic retries on connection failure.
* Returns the current connection status. */ - (BOOL) tryConnect; /** Releases a lock previously obtained using -lockBeforeDate: */ - (void) unlock; /** * Return the database user for this instance (or nil). */ - (NSString*) user; /** * Return the pool to which the receiver belongs, or nil if it is not part of a * connection pool. */ - (SQLClientPool*) pool; @end /** * This category contains the methods which a subclass must * override to provide a working instance, and helper methods for the * backend implementations.
* Application programmers should not call the backend * methods directly.
*

When subclassing to produce a backend driver bundle, please be * aware that the subclass must NOT introduce additional * instance variables. Instead the extra instance variable * is provided for use as a pointer to subclass specific data. *

*/ @interface SQLClient(Subclass) /** * Attempts to establish a connection to the database server.
* Returns a flag to indicate whether the connection has been established.
* If a connection was already established, returns YES and does nothing.
* You should not need to use this method normally, as it is called for you * automatically when necessary.
*

Subclasses must implement this method to establish a * connection to the database server process (and initialise the * extra instance variable if necessary), setting the * connected instance variable to indicate the state of the object. *

*

This method must call +purgeConnections: to ensure that there is a * free slot for the new connection. *

*

Application code must not call this method directly, it is * for internal use only. The -connect method calls this method if the * connected instance variable is NO. *

*/ - (BOOL) backendConnect; /** * Disconnect from the database unless already disconnected.
*

This method is called automatically when the receiver is deallocated * or reconfigured, and may also be called automatically when there are * too many database connections active. *

*

If the receiver is an instance of a subclass which uses the * extra instance variable, it must clear that * variable in the -backendDisconnect method, because a reconfiguration * may cause the class of the receiver to change. *

*

This method must set the connected instance variable to NO. *

*

Application code must not call this method directly, it is * for internal use only. The -disconnect method calls this method if the * connected instance variable is YES. *

*/ - (void) backendDisconnect; /** * Perform arbitrary operation which does not return any value.
* This method has a single argument, an array containing the string * representing the statement to be executed as its first object, and an * optional sequence of data objects following it.
* * [db backendExecute: [NSArray arrayWithObject: * @"UPDATE MyTable SET Name = 'The name' WHERE ID = 123"]]; * *

The backend implementation is required to perform the SQL statement * using the supplied NSData objects at the points in the statement * marked by the '?'''?' sequence. The marker saequences are * inserted into the statement at an earlier stage by the -execute:,... * and -execute:with: methods. *

*

Callers should lock the instance using the lock * instance variable for the duration of the operation, and unlock * it afterwards. *

*

NB. callers (other than the -begin, -commit, and -rollback methods) * should not pass any statement to this method which would cause a * transaction to begin or end. *

*

Application code must not call this method directly, it is * for internal use only. *

*

Where the database backend support it, this method returns the count of * the number of rows to which the operation applied. Otherwise this * returns -1. *

*/ - (NSInteger) backendExecute: (NSArray*)info; /** *

Perform arbitrary query which returns values. *

* * result = [db backendQuery: @"SELECT Name FROM Table" * recordType: [SQLRecord class]] * listType: [NSMutableArray class]]; * *

Upon error, an exception is raised. *

*

The query returns an array of records (each of which is represented * by an SQLRecord object). *

*

Each SQLRecord object contains one or more fields, in the order in * which they occurred in the query. Fields may also be retrieved by name. *

*

NULL field items are returned as NSNull objects. *

*

Callers should lock the instance using the lock * instance variable for the duration of the operation, and unlock * it afterwards. *

*

Application code must not call this method directly, it is * for internal use only. *

*

The rtype argument specifies an object to be used to * create the records produced by the query.
* This is provided as a performance optimisation when you want to store * data directly into a special class of your own.
* The object must respond to the [SQLRecord +newWithValues:keys:count:] * method to produce a new record initialised with the supplied data. *

*

The ltype argument specifies an object to be used to create objects to * store the records produced by the query.
* The should be a subclass of NSMutableArray. It must at least * implement the [NSObject+alloc] method to create an instance to store * records. The instance must implement [NSMutableArray-initWithCapacity:] * to initialise itsself, [NSMutableArray-addObject:] to allow the * backend to add records to it, and -count to return the number of records * added.
* For caching to work, it must be possible to make a mutable copy of the * instance using the mutableCopy method. *

*/ - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype; /** * Called to enable asynchronous notification of database events using the * specified name (which must be a valid identifier consisting of ascii * letters, digits, and underscore characters, starting with a letter).
* Repeated calls to list on the same name should be treated as a single * call.
* The backend is responsible for implicitly unlistening when a connection * is closed.
* There is a default implementation which does nothing ... for backends * which don't support asynchronous notifications.
* If a backend does support asynchronous notifications, * it should do so by posting NSNotification instances to the main thread * [NSNotificationQueue defaultQueue] with the posting style NSPostASAP * (to post asynchronously) and using the SQLClient instance as * the notification object and supplying any payload as a string using * the 'Payload' key in the NSNotification userInfo dictionary. * The userInfo dictionary should also contain a boolean (NSNumber) value, * using the 'Local' key, to indicate whether the notification was sent by * the current SQLClient instance or by some other client/ */ - (void) backendListen: (NSString*)name; /** * The backend should implement this to send asynchronous notifications * to anything listening for them. The name of the notification is an * SQL identifier used for listening for the asynchronous data.
* The payload string may be nil if no additional information is * needed in the notification. */ - (void) backendNotify: (NSString*)name payload: (NSString*)more; /** * Called to disable asynchronous notification of database events using the * specified name. This has no effect if the name has not been used in an * earlier call to -backendListen:, or if the name has already been * unlistened since the last call to listen. on it.
* There is a default implementation which does nothing ... for backends * which don't support asynchronous notifications. */ - (void) backendUnlisten: (NSString*)name; /** * This method is only for the use of the * -insertBLOBs:intoStatement:length:withMarker:length:giving: * method.
* Subclasses which need to insert binary data into a statement * must implement this method to copy the escaped data into place * and return the number of bytes actually copied. */ - (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf; /** *

This method is a convenience method provided for subclasses which need * to insert escaped binary data into an SQL statement before sending the * statement to a backend server process. This method makes use of the * -copyEscapedBLOB:into: and -lengthOfEscapedBLOB: methods, which * must be implemented by the subclass. *

*

The blobs array is an array containing the original SQL statement * string (unused by this method) followed by the data items to be inserted. *

*

The statement and sLength arguments specify the datastream to be * copied and into which the BLOBs are to be inserted. *

*

The marker and mLength arguments specify the sequence of marker bytes * in the statement which indicate a position for insertion of an escaped BLOB. *

*

The method returns either the original statement or a copy containing * the escaped BLOBs. The length of the returned data is stored in result. *

*/ - (const void*) insertBLOBs: (NSArray*)blobs intoStatement: (const void*)statement length: (unsigned)sLength withMarker: (const void*)marker length: (unsigned)mLength giving: (unsigned*)result; /** * This method is only for the use of the * -insertBLOBs:intoStatement:length:withMarker:length:giving: * method.
* Subclasses which need to insert binary data into a statement * must implement this method to return the length of the escaped * bytestream which will be inserted. */ - (unsigned) lengthOfEscapedBLOB: (NSData*)blob; @end /** * This category contains methods for asynchronous notification of * events via the database (for those database backends which support * it: currently only PostgreSQL). */ @interface SQLClient (Notifications) /** Adds anObserver to receive notifications when the backend database * server sends an asynchronous event identified by the specified name * (which must be a valid database identifier).
* When a notification (NSNotification instance) is received by the method * specified by aSelector, its object will be the SQLClient * instance to which anObserver was added and its userInfo dictionary * will contain the key 'Local' and possibly the key 'Payload'.
* If the 'Local' value is the boolean YES, the notification originated * as an action by this SQLClient instance.
* If the 'Payload' value is not nil, then it is a string providing extra * information about the notification.
* Notifications are posted asynchronously using the default notification * queue for the thread which receives them (or the main thread if the * receiving thread run loop is not active), so they should be delivered to * the observer after the database statement in which they were detected * has completed. However, delivery of the notification could still * occur inside a transaction if the -begin and -commit statements * are used. For this reason, observing code may want to use the * -lockBeforeDate: -isInTransaction and -unlock methods to ensure * that they don't interfere with ongoing transactions.
* For observation of notifications to be immediately effective, the * instance must be connected to the database (and remain connected), * so you can't call this method on a client from a pool, and you should * make sure that you don't close the client connection (or if you do, * that you make sure to re-open it in order to start receiving * notifications again).
* Each observer, may only have one observation set up for a particular * name. If an attempt is made to add a second observation for the same * name it will be silently ignored. */ - (void) addObserver: (id)anObserver selector: (SEL)aSelector name: (NSString*)name; /** Posts a notification via the database. The name is an SQL identifier * (for which observers may have registered) and the extra payload * information may be nil if not required. */ - (void) postNotificationName: (NSString*)name payload: (NSString*)more; /** Removes anObserver as an observer for asynchronous notifications from * the database server.
* If name is omitted, the observer will be removed for all names.
* If anObserver is nil, the removal will be performed for all current * observers (and if both name and anObserver are nil, then all observations * are removed).
* Any attempt to remove a non existent observation is silently ignored. */ - (void) removeObserver: (id)anObserver name: (NSString*)name; @end /** * This category contains convenience methods including those for * frequently performed database operations ... message logging etc. */ @interface SQLClient (Convenience) /** * Convenience method to deal with the results of a query converting the * normal array of records into an array of record columns. Each column * in the array is an array containing all the values from that column. */ + (NSMutableArray*) columns: (NSMutableArray*)records; /** * Convenience method to deal with the results of a query where each * record contains a single field ... it converts the array of records * returned by the query to an array containing the fields.
* NB. This does not check that the contents of the records array are * actually instances of [SQLRecord], so you must ensure you don't * call it more than once on the same array (something that may happen * if you retrieve the array using a cache based query). */ + (void) singletons: (NSMutableArray*)records; /** * Returns a transaction object configured to handle batching and * execute part of a batch of statements if execution of the whole * using the [SQLTransaction-executeBatch] method fails.
* If stopOnFailure is YES than execution of the transaction will * stop with the first statement to fail, otherwise it will execute * all the statements it can, skipping any failed statements. */ - (SQLTransaction*) batch: (BOOL)stopOnFailure; /** The same as the [SQLClient(Convenience)+columns:] method. */ - (NSMutableArray*) columns: (NSMutableArray*)records; /** * Executes a query (like the -query:,... method) and checks the result * (raising an exception if the query did not contain a single record) * and returns the resulting record. */ - (SQLRecord*) queryRecord: (NSString*)stmt,...; /** * Executes a query (like the -query:,... method) and checks the result.
* Raises an exception if the query did not contain a single record, or * if the record did not contain a single field.
* Returns the resulting field as a string. */ - (NSString*) queryString: (NSString*)stmt,...; /** The same as the [SQLClient(Convenience)+singletons:] method. */ - (void) singletons: (NSMutableArray*)records; /** Creates and returns an autoreleased SQLTransaction instance which will * use the receiver as the database connection to perform transactions. */ - (SQLTransaction*) transaction; @end /** * This category porovides basic methods for logging debug information. */ @interface SQLClient (Logging) /** * Return the class-wide debugging level, which is inherited by all * newly created instances. */ + (unsigned int) debugging; /** * Return the class-wide duration logging threshold, which is inherited by all * newly created instances. */ + (NSTimeInterval) durationLogging; /** * Set the debugging level to be inherited by all new instances.
* See [SQLClient(Logging)-setDebugging:] * for controlling an individual instance of the class. */ + (void) setDebugging: (unsigned int)level; /** * Set the duration logging threshold to be inherited by new instances.
* See [SQLClient(Logging)-setDurationLogging:] * for controlling an individual instance of the class. */ + (void) setDurationLogging: (NSTimeInterval)threshold; /** * The default implementation calls NSLogv to log a debug message.
* Override this in a category to provide more sophisticated logging.
* Do NOT override with code which can be slow or which calls (directly * or indirectly) any SQLCLient methods, since this method will be used * inside locked regions of the SQLClient code and you could cause * deadlocks or long delays to other threads using the class. */ - (void) debug: (NSString*)fmt, ...; /** * Return the current debugging level.
* A level of zero (default) means that no debug output is produced, * except for that concerned with logging the database transactions * taking over a certain amount of time (see the -setDurationLogging: method). */ - (unsigned int) debugging; /** * Returns the threshold above which queries and statements taking a long * time to execute are logged. A negative value (default) indicates that * this logging is disabled. A value of zero means that all statements * are logged. */ - (NSTimeInterval) durationLogging; /** * Set the debugging level of this instance ... overrides the default * level inherited from the class. */ - (void) setDebugging: (unsigned int)level; /** * Set a threshold above which queries and statements taking a long * time to execute are logged. A negative value (default) disables * this logging. A value of zero logs all statements. */ - (void) setDurationLogging: (NSTimeInterval)threshold; @end /** * This category provides methods for caching the results of queries * in order to reduce the number of client-server trips and the database * load produced by an application which needs update its information * from the database frequently. */ @interface SQLClient (Caching) /** * Returns the cache used by the receiver for storing the results of * requests made through it. Creates a new cache if necessary. */ - (GSCache*) cache; /** Returns an autoreleased mutable copy of the cached object corresponding * to the supplied query/statement (or nil if no such object is cached). */ - (NSMutableArray*) cacheCheckSimpleQuery: (NSString*)stmt; /** * Calls [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] with * the default record class, array class, and with a query string formed from * stmt and the following values (if any). */ - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt,...; /** * Calls [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] with * the default record class array class and with a query string formed * from stmt and values. */ - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt with: (NSDictionary*)values; /** * Calls [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] with * the default record class and array class. */ - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt; /** * If the result of the query is already cached and has not expired, * return an autoreleased mutable copy. Otherwise, perform the query * and cache the result giving it the specified lifetime in seconds.
* If seconds is negative, the query is performed irrespective of * whether it is already cached, and its absolute value is used to * set the lifetime of the results.
* If seconds is zero, the cache for this query is emptied.
* Handles locking.
* Maintains -lastOperation date.
* The value of rtype must respond to the * [SQLRecord+newWithValues:keys:count:] method.
* If rtype is nil then the [SQLRecord] class is used.
* The value of ltype must respond to the [NSObject+alloc] method to produce * a container which must repond to the [NSMutableArray-initWithCapacity:] * method to initialise itsself, the [NSMutableArray-addObject:] method * to add records to the list, and the [NSMutableArray-count] method to * return the number of records added.
* If ltype is nil then the [NSMutableArray] class is used.
* The list produced by this argument is used as the return value of * this method.
* NB. cache lookups for the instance created from ltype will be provided * by sending -mutableCopy and autorelease messages to the original * instance.
* If a cache thread has been set using the -setCacheThread: method, and the * [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] method is * called from a thread other than the cache thread, then any query to retrieve * uncached data will be performed in the cache thread, and for cached * (but expired) data, the old (expired) results may be returned ... * in which case an asynchronous query to update the cache will be * executed as soon as possible in the cache thread. */ - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype; /** * Sets the cache to be used by the receiver for storing the results of * requests made through it.
* If aCache is nil, the current cache is released, and a new cache will * be automatically created as soon as there is a need to cache anything. */ - (void) setCache: (GSCache*)aCache; /** Sets the thread to be used to retrieve data to populate the cache.
* All cached queries will be performed in this thread (if non-nil).
* The setting of a thread for the cache also implies that expired items in * the cache may not be removed when they are queried from another thread, * rather they can be kept (if they are not too old) and an * asynchronous query to update them will be run on the cache thread.
* The rule is that, if the item's age is more than twice its nominal * lifetime, it will be retrieved immediately, otherwise it will be * retrieved asynchronously.
* Currently this may only be the main thread or nil. Any attempt to set * another thread will use the main thread instead. */ - (void) setCacheThread: (NSThread*)aThread; @end typedef struct _SQLClientPoolItem SQLClientPoolItem; /**

An SQLClientPool instance may be used to create/control a pool of * client objects. Code may obtain autoreleased proxies to the clients * from the pool and use them safe in the knowledge that they won't be * used anywhere else ... as soon as the client would be deallocated, it * is returned to the pool. *

*

All clients in the pool share the same cache object, so query results * cached by one client will be available to other clients in the pool. *

*

As a convenience, an SQLClientPool instance acts as a proxy for the * clients it contains, so you may (where it makes sense) send the same * messages to a pool that you would send to an individual client, and the * pool will temporarily allocate one of its clients to handle it.
* In this case the client will be returned to the pool immediately * after the message has been handled (and subsequent messages may go * to a different client), so you can't change settings or send any other * method which would be required to be followed up by another message to * the same client. *

*

NB. Any client provided from a pool should be returned to the * pool as soon as reasonably possible (and if left idle will have its * connection to the server closed anyway) so that it can be used by * other threads. If you want a permenantly open database connection * you should use a normal SQLClient instance, not one from a pool. * You must not call -addObserver:selector:name: on a client from a pool. *

*/ @interface SQLClientPool : NSObject { NSConditionLock *_lock; /** Controls access to items */ SQLClientPoolItem *_items; /** The items in the pool */ int _max; /** Maximum connection count */ int _min; /** Minimum connection count */ NSDictionary *_config; /** The pool configuration object */ NSString *_name; /** The pool configuration name */ NSTimeInterval _duration; /** Duration logging threshold */ unsigned int _debugging; /** The current debugging level */ uint64_t _immediate; /** Immediate client provisions */ uint64_t _delayed; /** Count of delayed provisions */ uint64_t _failed; /** Count of timed out provisions */ NSTimeInterval _longest; /** Count of longest delay */ NSTimeInterval _delayWaits; /** Time waiting for provisions */ NSTimeInterval _failWaits; /** Time waiting for timewouts */ NSTimeInterval _purgeAll; /** Age to purge all connections */ NSTimeInterval _purgeMin; /** Age to purge excess connections */ } /** Returns the count of currently available connections in the pool. */ - (int) availableConnections; /** Creates and returns an autoreleased SQLTransaction instance which will * use the receiver as the database connection to perform transactions. */ - (SQLTransaction*) batch: (BOOL)stopOnFailure; /** * Returns the cache used by clients in the pool for storing the results of * requests made through them. Creates a new cache if necessary. */ - (GSCache*) cache; /** Returns the number of committed transactions. */ - (uint64_t) committed; /** * Creates a pool of clients using a single client configuration.
* Calls -initWithConfiguration:name:pool: (passing NO to say the client * is not in a pool) to create each client.
* The value of maxConnections is the size of the pool (ie the number of * clients created) and thus the maximum number of concurrent connections * to the database server.
* The value of minConnections is the minimum number of connected clients * normally expected to be in the pool. The pool tries to ensure that it * doesn't contain more than this number of idle connected clients. */ - (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference max: (int)maxConnections min: (int)minConnections; /** Returns a long description of the pool including statistics, status, * and the description of a sample client. */ - (NSString*) longDescription; /** Return the maximum number of database connections in the pool. */ - (int) maxConnections; /** Return the minimum number of database connections in the pool. */ - (int) minConnections; /** Returns the name of the database configuration for the connections in * the pool. */ - (NSString*) name; /** Fetches an (autoreleased) client from the pool.
* This method blocks indefinitely waiting for a client to become * available in the pool.
* Calls -provideClientBeforeDate:exclusive: for a date in the distant * future and for a non-exclusive client. */ - (SQLClient*) provideClient; /** Fetches an (autoreleased) client from the pool.
* Calls -provideClientBeforeDate:exclusive: for a non-exclusive client. */ - (SQLClient*) provideClientBeforeDate: (NSDate*)when; /** Fetches an (autoreleased) client from the pool.
* If no client is or becomes available before the specified date then * the method returns nil.
* If when is nil then a date in the distant future is used so that * the method will effectively wait forever to get a client.
* If isLocal is YES, this method provides a client which will not be * used elsewhere in the same thread until/unless the calling code * returns it to the pool. Otherwise (isLocal is NO), the client may * be used by other code in the same thread.
* NB. Any client provided using this method should be returned to the * pool as soon as reasonably possible (and if left idle will have its * connection to the server closed anyway) so that it can be used by * other threads. If you want a permenantly open database connection * you should use a normal SQLClient instance, not one from a pool. */ - (SQLClient*) provideClientBeforeDate: (NSDate*)when exclusive: (BOOL)isLocal; /** Fetches an (autoreleased) client from the pool.
* This method blocks indefinitely waiting for a client to become * available in the pool.
* Calls -provideClientBeforeDate:exclusive: for a date in the distant * future and for an exclusive client. */ - (SQLClient*) provideClientExclusive; /** * Disconnects the least recently active unused database clients in the * pool, but only while there are more than the minimum number of clients * currently connected to the database, and only if the client has been * idle for at least ten seconds. */ - (void) purge; /** * Sets the cache for all the clients in the pool. */ - (void) setCache: (GSCache*)aCache; /** Sets the cache thread for all the clients in the pool. */ - (void) setCacheThread: (NSThread*)aThread; /** Set the client name for all the client connections in the pool.
* If the argument is not nil, the name of each client in the pool * is set to the argument with a suffix of '(x)' where x is the number * of the client within the pool, otherwise (nil argument) each client * is allocated a globally unique string as its name.
* NB. This setting does not apply to new connections added when the pool * maximum size is increased. */ - (void) setClientName: (NSString*)s; /** Set the debugging level for all clients in the pool. */ - (void) setDebugging: (unsigned int)level; /** Set the duration logging threshold for all clients in the pool. */ - (void) setDurationLogging: (NSTimeInterval)threshold; /** Sets the pool size limits (number of connections we try to maintain).
* The value of maxConnections is the size of the pool (ie the number of * clients created) and thus the maximum number of concurrent connections * to the database server.
* The value of minConnections is the minimum number of connected clients * normally expected to be in the pool. The pool tries to ensure that it * contains at least this number of connected clients.
* The value of maxConnections must be greater than or equal to that of * minConnections and may not be greater than 100. * The value of minConnections must be less than or equal to that of * maxConnections and may not be less than 1. */ - (void) setMax: (int)maxConnections min: (int)minConnections; /** Sets the ages (in seconds) after which idle connections are closed in * the -purge method. Where there are excess connections (more than the * minimum configured connection count) in the pool, minSeconds is used, * otherwise allSeconds is used. */ - (void) setPurgeAll: (int)allSeconds min: (int)minSeconds; /** Returns a string describing the usage of the pool. */ - (NSString*) statistics; /** Returns a string describing the status of the pool. */ - (NSString*) status; /** Puts the client back in the pool. This happens automatically * when a client from a pool would normally be deallocated so you don't * generally need to do it.
* Returns YES if the supplied client was from the pool, NO otherwise. */ - (BOOL) swallowClient: (SQLClient*)client; /** Creates and returns an autoreleased SQLTransaction instance which will * use the receiver as the database connection to perform transactions. */ - (SQLTransaction*) transaction; @end /** This category lists the convenience methods provided by a pool instance * for proxying messages to a one-off client instance in the pool.
* The behavior of each method is, of course, as documentf for instances * of the [SQLClient] class. */ @interface SQLClientPool (Convenience) - (SQLLiteral*) buildQuery: (NSString*)stmt,...; - (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values; - (NSMutableArray*) cacheCheckSimpleQuery: (NSString*)stmt; - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt,...; - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt with: (NSDictionary*)values; - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt; - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype; - (NSMutableArray*) columns: (NSMutableArray*)records; - (NSInteger) execute: (NSString*)stmt,...; - (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values; - (SQLClientPool*) pool; - (NSMutableArray*) prepare: (NSString*)stmt, ...; - (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args; - (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values; - (NSMutableArray*) query: (NSString*)stmt,...; - (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values; - (SQLRecord*) queryRecord: (NSString*)stmt,...; - (NSString*) queryString: (NSString*)stmt,...; - (SQLLiteral*) quote: (id)obj; - (SQLLiteral*) quoteArray: (NSArray *)a; - (SQLLiteral*) quoteArraySafe: (NSArray *)a; - (NSMutableString*) quoteArray: (NSArray *)a toString: (NSMutableString *)s quotingStrings: (BOOL)_q; - (SQLLiteral*) quotef: (NSString*)fmt, ...; - (SQLLiteral*) quoteBigInteger: (int64_t)i; - (SQLLiteral*) quoteCString: (const char *)s; - (SQLLiteral*) quoteChar: (char)c; - (SQLLiteral*) quoteFloat: (double)f; - (SQLLiteral*) quoteInteger: (int)i; - (SQLLiteral*) quoteName: (NSString *)s; - (SQLLiteral*) quoteSet: (id)obj; - (SQLLiteral*) quoteString: (NSString *)s; - (NSInteger) simpleExecute: (NSArray*)info; - (void) singletons: (NSMutableArray*)records; - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt; - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype; @end /** * The SQLTransaction transaction class provides a convenient mechanism * for grouping together a series of SQL statements to be executed as a * single transaction. It avoids the need for handling begin/commit, * and should be as efficient as reasonably possible.
* You obtain an instance by calling [SQLClient(Convenience)-transaction], * add SQL statements to it using the -add:,... and/or -add:with: methods, * and then use the -execute method to perform all the statements as a * single operation.
* Any exception is caught and re-raised in the -execute method after any * tidying up to leave the database in a consistent state. */ @interface SQLTransaction : NSObject { SQLCLIENT_PRIVATE id _owner; NSMutableArray *_info; unsigned _count; BOOL _batch; BOOL _stop; BOOL _reset; NSRecursiveLock *_lock; } /** * Adds an SQL statement to the transaction. This is similar to * [SQLClient-execute:,...] but does not cause any database operation * until -execute is called, so it will not raise a database exception. */ - (void) add: (NSString*)stmt,...; /** * Adds an SQL statement to the transaction. This is similar to * [SQLClient-execute:with:] but does not cause any database operation * until -execute is called, so it will not raise a database exception. */ - (void) add: (NSString*)stmt with: (NSDictionary*)values; /** Adds a prepared statement. */ - (void) addPrepared: (NSArray*)statement; /** * Appends a copy of the other transaction to the receiver.
* This provides a convenient way of merging transactions which have been * built by different code modules, in order to have them all executed * together in a single operation (for efficiency etc).
* This does not alter the other transaction, so if the execution of * a group of merged transactions fails, it is then possible to attempt * to commit the individual transactions separately.
* NB. All transactions appended must be using the same database * connection (SQLClient/SQLClientPool instance). */ - (void) append: (SQLTransaction*)other; /** * Make a copy of the receiver. */ - (id) copyWithZone: (NSZone*)z; /** * Returns the number of individual statements and/or subsidiary transactions * which have been added to the receiver. For a count of the total number * of statements, use the -totalCount method. */ - (NSUInteger) count; /** *

Performs any statements added to the transaction as a single operation. * If any problem occurs, an NSException is raised, but the database connection * is left in a consistent state and a partially completed operation is * rolled back. *

*

NB. If the database is not already in a transaction, this implicitly * calls the -begin method to start the transaction before executing the * statements.
* The method always commits the transaction, even if the transaction was * begun earlier rather than in -execute.
* This behavior allows you to call [SQLClient-begin], then run one or more * queries, build up a transaction based upon the query results, and then * -execute that transaction, causing the entire process to be commited as * a single transaction . *

*/ - (void) execute; /** Convenience method which calls * -executeBatchReturningFailures:logExceptions: with * a nil failures argument and exception logging off. */ - (unsigned) executeBatch; /** *

This is similar to the -execute method, but may allow partial * execution of the transaction if appropriate: *

*

If the transaction was created using the [SQLClient(Convenience)-batch:] * method and the transaction as a whole fails, individual statements are * retried.
* The stopOnFailure flag for the batch creation indicates whether the * retries are stopped at the first statement to fail, or continue (skipping * any failed statements). *

*

If the transaction has had transactions appended to it, those * subsidiary transactions may succeed or fail atomically depending * on their individual attributes. *

*

If the transaction was not created using [SQLClient(Convenience)-batch:], * then calling this method is equivalent to calling the -execute method. *

*

If any statements/transactions in the batch fail, they are added to * the transaction supplied in the failures parameter (if it's not nil) * so that you can retry them later.
* NB. statements/transactions which are not executed at all (because the * batch is set to stop on the first failure) are also added to * the failures transaction. *

*

If the log argument is YES, then any exceptions encountered when * executing the batch are logged using the [SQLClient(Logging)-debug:,...] * method, even if debug logging is not enabled with * [SQLClient(Logging)-setDebugging:]. *

* The method returns the number of statements which actually succeeded. */ - (unsigned) executeBatchReturningFailures: (SQLTransaction*)failures logExceptions: (BOOL)log; /** * Insert trn at the index'th position in the receiver.
* The transaction trn must be non-empty and must use the same * database client/pool as the receiver. */ - (void) insertTransaction: (SQLTransaction*)trn atIndex: (unsigned)index; /** Explicitly obtains the transaction lock so that multiple methods may * be called without another thread interfering. Each call to this method * must be matched by a call to the -unlock method. */ - (void) lock; /** * Returns the database client with which this instance operates.
* This client is retained by the transaction.
* If the transaction was created by/for an SQLClientPool, this method * returns that pool rather than an individual client. */ - (id) owner; /** Remove the index'th transaction or statement from the receiver. */ - (void) removeTransactionAtIndex: (unsigned)index; /** Resets the transaction, removing all previously added statements. * This allows the transaction object to be re-used for multiple * transactions. See also the -setResetOnExecute: method. */ - (void) reset; /** Configures the transaction to be reset automatically whenever it is * successfully executed. Normally transaction execution leaves all the * statements in the transaction after execution.
* Returns the previous setting. */ - (BOOL) setResetOnExecute: (BOOL)aFlag; /** * Returns the total count of statements in this transaction including * those in any subsidiary transactions. For a count of the statements * and/or transactions directly added to the receiver, use the -count method. */ - (unsigned) totalCount; /** Return an autoreleased copy of the index'th transaction or statement * added to the receiver.
* Since the returned transaction contains a copy of the statement/transaction * in the receiver, you can modify it without effecting the original. */ - (SQLTransaction*) transactionAtIndex: (unsigned)index; /** Explicitly unlocks the thransaction. This should only be called by code * which has previously called the -lock method. */ - (void) unlock; @end /** The SQLLiteral subclass of NSString is used to tell * [SQLClient-prepare:args:] and [SQLClient-prepare:with:] methods that * a string is to be treated as a literal which should not be quoted when * it is used as part of an SQL query or statement.
* You should enable compile time checking of string types by defining the * SQLCLIENT_COMPILE_TIME_QUOTE_CHECK preprocessor macro before including * this header. When compile time checking is in place, the methods which * expect a query or statement to be provided as a single string will be * declared as taking an SQLLiteral argument rather than an NSString. * The compiler will then complain about passing arguments of the wrong * type.
* NB. The runtime checking for literal strings actually uses different classes * not the SQLLiteral class. In fact this class declaration is only used for * compile time checking and you should not expect runtime checks to actually * ever see an instance of this class. */ @interface SQLLiteral : NSString @end /** This category encapsulates methods used to control automatic quoting * of non-literal strings.
* The point of this feature is to help prevent SQL injection attacks on * your software (where you read in something from some UI, and use that * data in creating a database query/statement, and an attacker might try * to fool your code into doing something bad to the database).
* When autoquote is turned on, the methods to build queries/statements * ([SQLClient-prepare:args:] and [SQLClient-prepare:with:] and other * methods based on those) will perform a runtime check for strings in the * arguments list they are given, and will automatically quote any string * which is not considered a literal.
* The types of literal string are: * * compiler literalA string literal in your source code * of the form @"text", generated by the compiler.
* The rationale is that if it's a literal constant in the source code, * the programmer should know (and be able to clearly see) that it's * properly quoted for the context in which it is used.
* copy literalA string of a special class which has * been produced by calling one of the quote methods, or by calling the * SQLClientCopyLiteral(), SQLClientMakeLiteral(), or SQLClientNewLiteral() * functions to make a copy of a string to be treated as a literal. * proxy literalA string of a special class which has * been produced by calling the SQLClientProxyLiteral() function to wrap * an existing string to mark it to be treated as a literal. This should * only be used as a performance tweak when a programmer has built a very * large SQL statement, and copying it would hurt performance. *
* NB. column values in the results of a database query are not returned as * literals unless they are NULL or come from a column whose actual type is * a form of number or boolean (since booleans and numbers do not need any * form of quoting in an SQL query/statement). */ @interface SQLClient (Quote) /** Returns a BOOL saying whether autoquote is on or off. */ + (BOOL) autoquote; /** Returns a BOOL saying whether autoquote warnings are on or off. */ + (BOOL) autoquoteWarning; /** Turns autoquote on/off for the process.
* When autoquote is on, the arguments to the [SQLClient-prepare:args:] * method (and therefore all methods that use it) are automatically quoted * unless they are literal strings.
* The purpose of autoquoting is to help prevent SQL injection attacks on * your software; it helps ensure that only strings you really want to use * literally are embedded in the SQL without quoting. */ + (void) setAutoquote: (BOOL)aFlag; /** Turns autoquote warning on/off for the process.
* When autoquote warning is on, an NSLog() warning is generated whenever * the arguments to the [SQLClient-prepare:args:] method (and therefore * all methods that use it) are automatically quoted (or would be if * autoquote was turned on).
* Turn this on when using software which you expect to migrate to using * autoquote. */ + (void) setAutoquoteWarning: (BOOL)aFlag; @end /** Creates and returns a copy of aString as a literal, * whether or not aString is already a literal string. */ extern SQLLiteral * SQLClientCopyLiteral(NSString *aString); /** Function to test an object to see if it is considered to be a literal * string by SQLClient. Use this rather than trying to chewck the class * hierarchy (which is not reliable). */ extern BOOL SQLClientIsLiteral(NSString *aString); /** Returns a literal string version of aString.
* A literal is an instance of the literal string class produced by the * compiler or the SQLString class (which subclasses it).
* If aString is already a literal string, this method returns it unchanged, * otherwise the returned value is an autoreleased newly created copy of the * argument. */ extern SQLLiteral * SQLClientMakeLiteral(NSString *aString); /** Function to create an SQL literal (string which won't be autoquoted) * from a UTF8 or ASCII C string whose length (not including any nul * terminator) is the specified count. */ extern SQLLiteral * SQLClientNewLiteral(const char *bytes, unsigned count); /** Creates and returns an autoreleased proxy to aString, recording the * fact that the programmer considers the string to be a valid literal * (ie one that doesn't need to be quoted when used as part of an SQL * statement or query). The original string is retained by the object * returned.
* Use this when aString is large and the overheads of the * SQLClientCopyLiteral() or SQLClientMakeLiteral() functions * would be too high.
* NB. Manipulation of proxy objects is inefficient ... you should leave * creation of the proxy to the last moment before passing it to a method * which would otherwise autoquote your string. */ extern SQLLiteral * SQLClientProxyLiteral(NSString *aString); /** Returns the original string which was previously wrapped by a call * to SQLClientProxyLiteral(). If aString is not an SQLLiteral proxy, * this returns aString. */ extern NSString * SQLClientUnProxyLiteral(id aString); /* A helper for building a dictionary from an SQL query which returns * key-value pairs (you can subclass it to handle other records).
* You create an instance of this class, and pass it as both the * record and list class arguments of the low level SQLClient query.
* The query (which must return a number of records, each with two fields) * will result in a mutable dictionary being built, with dictionary keys * being the first field from each record and dictionary values being the * second field of each record.
* You may use the same instance for more than one query, but a second query * will replace the content dictionary produced by the first.
* If you want to handle records containing more than two values, you * must create a subclass which overrides the -newWithValues:keys:count: * method to create the record objects and add them to the content * dictionary.
* See [SQLClient-simpleQuery:recordType:listType:] also.
* NB. When this class is used, the query will actually return an * [NSMutableDictionary] instance rather than an [NSMutableArray] of * [SQLRecord] objects. */ @interface SQLDictionaryBuilder : NSObject { NSMutableDictionary *content; } /** No need to do anything ... the object will already have been added by * the -newWithValues:keys:count: method. */ - (void) addObject: (id)anObject; /** When a container is supposed to be allocated, we just return the * receiver (which will then quietly ignore -addObject: messages). */ - (id) alloc; /** Returns the content dictionary for the receiver. */ - (NSMutableDictionary*) content; /** Creates a new content dictionary ... this method will be called * automatically by the SQLClient object when it performs a query, * so there is no need to call it at any other time. */ - (id) initWithCapacity: (NSUInteger)capacity; /** Makes a mutable copy of the content dictionary (called when a caching * query uses this helper to produce the cached collection). */ - (id) mutableCopyWithZone: (NSZone*)aZone; /** This is the main workhorse of the class ... it is called once for * every record read from the database, and is responsible for adding * that record to the content dictionary. The default implementation, * instead of creating an object to hold the supplied record data, * uses the two fields from the record as a key-value pair to add to * the content dictionary, and returns nil as the record object. * It's OK to return a nil object since we ignore the -addObject: * argument. */ - (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count; @end /* A helper for building a counted set from an SQL query which returns * individual values (you can subclass it to handle other records).
* You create an instance of this class, and pass it as both the * record and list class arguments of the low level SQLClient query.
* The query (which must return a number of records, each with one field) * will result in a counted set being built and a record of the number of * added objects being kept.
* You may use the same instance for more than one query, but a second query * will replace the content set produced by the first.
* If you want to handle records containing more than one value, you * must create a subclass which overrides the -newWithValues:keys:count: * method to create the record objects and add them to the content * set, and increment the counter.
* See [SQLClient-simpleQuery:recordType:listType:] also.
* NB. When this class is used, the query will actually return an * [NSCountedSet] instance rather than an [NSMutableArray] of * [SQLRecord] objects. */ @interface SQLSetBuilder : NSObject { NSCountedSet *content; NSUInteger added; } /** Returns the number of objects actually added to the counted set. */ - (NSUInteger) added; /** No need to do anything ... the object will already have been added by * the -newWithValues:keys:count: method. */ - (void) addObject: (id)anObject; /** When a container is supposed to be allocated, we just return the * receiver (which will then quietly ignore -addObject: messages). */ - (id) alloc; /** Returns the counted set for the receiver. */ - (NSCountedSet*) content; /** Creates a new content set ... this method will be called * automatically by the SQLClient object when it performs a query, * so there is no need to call it at any other time. */ - (id) initWithCapacity: (NSUInteger)capacity; /** Makes a mutable copy of the content dictionary (called when a caching * query uses this helper to produce the cached collection). */ - (id) mutableCopyWithZone: (NSZone*)aZone; /** This is the main workhorse of the class ... it is called once for * every record read from the database, and is responsible for adding * that record to the content set. The default implementation, * instead of creating an object to hold the supplied record data, * uses the singe field from the record to add to * the content set, and returns nil as the record object. * It's OK to return a nil object since we ignore the -addObject: * argument. */ - (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count; @end /* A helper for building a collection of singletons from an SQL query * which returns singleton values.
* You create an instance of this class, and pass it as the record * class argument of the low level SQLClient query.
* The query (which must return a number of records, each with one field) * will result in the singleton values being stored in the list class.
* See [SQLClient-simpleQuery:recordType:listType:] also. */ @interface SQLSingletonBuilder : NSObject - (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count; @end #endif SQLClient-1.9.0/SQLClient.html000066400000000000000000002265371436027104400160230ustar00rootroot00000000000000 SQLClient documentation

SQLClient documentation

Authors

Richard Frith-Macdonald (rfm@gnu.org)

Version: 1.4

Date: 2004/05/07 08:16:16

Copyright: (C) 2004 Free Software Foundation, Inc.

The SQLClient library

What is the SQLClient library?

The SQLClient library is designed to provide a simple interface to SQL databases for GNUstep applications. It does not attempt the sort of abstraction provided by the much more sophisticated GDL2 library, but rather allows applications to directly execute SQL queries and statements.

The major features of the SQLClient library are -

  • Simple API for executing queries and statements... a variable length sequence of comma separated strings and other objects (NSNumber, NSDate, NSData) are concatenated into a single SQL statement and executed.
  • Support multiple sumultaneous named connections to a database server in a thread-safe manner.
  • Support multiple simultaneous connections to different database servers with backend driver bundles loaded for different database engines. Clear, simple subclassing of the abstract base class to enable easy implementation of new backend bundles.
  • Configuration for all connections held in one place and referenced by connection name for ease of configuration control. Changes via NSUserDefaults can even allow reconfiguration of client instances within a running application.
  • Thread safe operation... The base class supports locking such that a single instance can be shared between multiple threads.

What backend bundles are available?

Current backend bundles are -

  • ECPG - a bundle using the embedded SQL interface for postgres.
    This is based on a similar code which has been in production use for over eighteen months, so it should be reliable.
  • Postgres - a bundle using the libpq native interface for postgres.
    This is the preferred backend as it allows 'SELECT FOR UPDATE', which the ECPG backend cannot support due to limitations in the postgres implementation of cursors. The code is however not as well tested as the ECPG interface.
  • MySQL - a bundle using the mysqlclient library for *recent* MySQL.
    I don't use MySQL... but the test program ran successfully with a vanilla install of the MySQL packages for recent Debian unstable.
  • Oracle - a bundle using embedded SQL for Oracle.
    Completely untested... may even need some work to compile... but this *is* based on code which was working about a year ago.
    No support for BLOBs yet.

Where can you get it? How can you install it?

The SQLClient library is currently only available via CVS from the GNUstep CVS repository.
See <https://savannah.gnu.org/cvs/?group=gnustep>
You need to check out gnustep/dev-libs/SQLClient

To build this library you must have a basic GNUstep environment set up...

  • The gnustep-make package must have been built and installed.
  • The gnustep-base package must have been built and installed.
  • You must hace sourced the GNUstep.sh script (from gnustep-make) to set up environment variables needed for building this.
  • If this environment is in place, all you should need to do is run 'make' to configure and build the library, 'make install' to install it.
  • Then you can run the test programs.
  • Your most likely problems are that the configure script may not detect the database libraries you want... Please figure out how to modify configure.ac so that it will detect the required headers and libraries on your system, and supply na patch.
  • Once the library is installed, you can include the header file <SQLClient/SQLClient.h%gt; and link your programs with the SQLClient library to use it.

Bug reports, patches, and contributions (eg a backend bundle for a new database) should be entered on the GNUstep project page <http://savannah.gnu.org/projects/gnustep> and the bug reporting page <http://savannah.gnu.org/bugs/?group=gnustep>

Software documentation for the SQLClient class

SQLClient : NSObject

Declared in:
SQLClient.h

The SQLClient class encapsulates dynamic SQL access to relational database systems. A shared instance of the class is used for each database (as identified by the name of the database), and the number of simultanous database connections is managed too.

SQLClient is an abstract base class... when you create an instance of it, you are actually creating an instance of a concrete subclass whose implementation is loaded from a bundle.



Instance Variables for SQLClient Class

_client

@private NSString* _client;

Identifier within backend


_database

@private NSString* _database;

The configured database name/host


_debugging

@private unsigned int _debugging;

The current debugging level


_duration

@private NSTimeInterval _duration;

Description forthcoming.


_inTransaction

@private BOOL _inTransaction;

A flag indicating whether this instance is currently within a transaction. This variable must only be set by the -begin , -commit or -rollback methods.
Are we inside a transaction?


_lastOperation

@private NSDate* _lastOperation;

Timestamp of last operation.
Maintained by the -simpleExecute: and -simpleQuery: methods.


_name

@private NSString* _name;

Unique identifier for instance


_password

@private NSString* _password;

The configured password


_user

@private NSString* _user;

The configured user


connected

@private BOOL connected;

A flag indicating whether this instance is currently connected to the backend database server. This variable must only be set by the -backendConnect or -backendDisconnect methods.


extra

@private void* extra;

For subclass specific data


lock

@private NSRecursiveLock* lock;

Maintain thread-safety





Method summary

allClients 

+ (NSArray*) allClients;

Returns an array containing all the SQLClient instances.


clientWithConfiguration: name: 

+ (SQLClient*) clientWithConfiguration: (NSDictionary*)config name: (NSString*)reference;

Return an existing SQLClient instance (using +existingClient:) if possible, or creates one, initialises it using -initWithConfiguration:name: , and returns the new instance (autoreleased).
Returns nil on failure.


existingClient: 

+ (SQLClient*) existingClient: (NSString*)reference;

Return an existing SQLClient instance for the specified name if one exists, otherwise returns nil.


maxConnections 

+ (unsigned int) maxConnections;

Return the maximum number of simultaneous database connections permitted (set by +setMaxConnections: and defaults to 8)


purgeConnections: 

+ (void) purgeConnections: (NSDate*)since;

Use this method to reduce the number of database connections currently active so that it is less than the limit set by the +setMaxConnections: method. This mechanism is used internally by the class to ensure that, when it is about to open a new connection, the limit is not exceeded.

If since is not nil, then any connection which has not been used more recently than that date is disconnected anyway.
You can (and probably should) use this periodically to purge idle connections, but you can also pass a date in the future to close all connections.


setMaxConnections: 

+ (void) setMaxConnections: (unsigned int)c;

Set the maximum number of simultaneous database connections permitted (defaults to 8 and may not be set less than 1).

This value is used by the +purgeConnections: method to determine how many connections should be disconnected when it is called.


begin 

- (void) begin;

Start a transaction for this database client.
You must match this with either a -commit or a -rollback .

Normally, if you execute an SQL statement without using this method first, the autocommit feature is employed, and the statement takes effect immediately. Use of this method permits you to execute several statements in sequence, and only have them take effect (as a single operation) when you call the -commit method.

NB. You must not execute an SQL statement which would start a transaction directly... use only this method.


clientName 

- (NSString*) clientName;

Return the client name for this instance.
Normally this is useful only for debugging/reporting purposes, but if you are using multiple instances of this class in your application, and you are using embedded SQL, you will need to use this method to fetch the client/connection name and store its C-string representation in a variable 'connectionName' declared to the sql preprocessor, so you can then have statements of the form - 'exec sql at :connectionName...'.


commit 

- (void) commit;

Complete a transaction for this database client.
This must match an earlier -begin .

NB. You must not execute an SQL statement which would commit or rollback a transaction directly... use only this method or the -rollback method.


connect 

- (BOOL) connect;

If the connected instance variable is NO, this method calls -backendConnect to ensure that there is a connection to the database server established. Returns the result.
Performs any necessary locking for thread safety.


connected 

- (BOOL) connected;

Return a flag to say whether a connection to the database server is currently live. This is mostly useful for debug/reporting, but is used internally to keep track of active connections.


database 

- (NSString*) database;

Return the database name for this instance (or nil).


disconnect 

- (void) disconnect;

If the connected instance variable is YES, this method calls -backendDisconnect to ensure that the connection to the database server is dropped.
Performs any necessary locking for thread safety.


execute: ,...

- (void) execute: (NSString*)stmt,...;

Perform arbitrary operation which does not return any value.
This arguments to this method are a nil terminated list which are concatenated in the manner of the * -prepare:args: method.
Any string arguments are assumed to have been quoted appropriately already, but non-string arguments are automatically quoted using the -quote: method.

   [db execute: @"UPDATE ", table, @" SET Name = ",
     myName, " WHERE ID = ", myId, nil];
 


execute: with: 

- (void) execute: (NSString*)stmt with: (NSDictionary*)values;

Takes the statement and substitutes in values from the dictionary where markup of the format {key} is found.
Passes the result to the -execute:,... method.

   [db execute: @"UPDATE {Table} SET Name = {Name} WHERE ID = {ID}"
          with: values];
 
Any non-string values in the dictionary will be replaced by the results of the -quote: method.
The markup format may also be {key?default} where default is a string to be used if there is no value for the key in the dictionary.


initWithConfiguration: 

- (id) initWithConfiguration: (NSDictionary*)config;

Calls -initWithConfiguration:name: passing a nil reference name.


initWithConfiguration: name: 

- (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference;

Initialise using the supplied configuration, or if that is nil, try to use values from NSUserDefaults (and automatically update when the defaults change).
Uses the reference name to determine configuration information... and if a nil name is supplied, defaults to the value of the SQLClientName as a user default string or 'Database' if no other name is provided.
If a SQLClient instance already exists with the name used for this instance, the receiver is deallocated and the existing instance is retained and returned... there may only ever be one instance for a particular reference name.

The config argument (or the SQLClientReferences user default) is a dictionary with names as keys and dictionaries as its values. Configuration entries from the dictionary corresponding to the database client are used if possible, general entries are used otherwise.
Database... is the name of the database to use, if it is missing then 'Database' may be used instead.
User... is the name of the database user to use, if it is missing then 'User' may be used instead.
Password... is the name of the database user password, if it is missing then 'Password' may be used instead.
ServerType... is the name of the backend server to be used... by convention the name of a bundle containing the interface to that backend. If this is missing then 'Postgres' is used.


isInTransaction 

- (BOOL) isInTransaction;

Return the state of the flag indicating whether the library thinks a transaction is in progress. This flag is normally maintained by -begin , -commit , and -rollback .


lastOperation 

- (NSDate*) lastOperation;

Returns the date/time stamp of the last database operation performed by the receiver, or nil if no operation has ever been done by it.
Simply connecting to or disconnecting from the databsse does not count as an operation.


name 

- (NSString*) name;

Return the database reference name for this instance (or nil).


password 

- (NSString*) password;

Return the database password for this instance (or nil).


query: ,...

- (NSMutableArray*) query: (NSString*)stmt,...;

Perform arbitrary query which returns values.

This method has at least one argument, the string starting the statement to be executed (which must have the prefix 'select ').

Additional arguments are a nil terminated list which also be strings, and these are appended to the statement.
Any string arguments are assumed to have been quoted appropriately already, but non-string arguments are automatically quoted using the -quote: method.

   result = [db query: @"SELECT Name FROM ", table, nil];
 

Upon error, an exception is raised.

The query returns an array of records (each of which is represented by an SQLRecord object).

Each SQLRecord object contains one or more fields, in the order in which they occurred in the query. Fields may also be retrieved by name.

NULL field items are returned as NSNull objects.

Most other field items are returned as NSString objects.

Date and timestamp field items are returned as NSDate objects.


query: with: 

- (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values;

Takes the query statement and substitutes in values from the dictionary where markup of the format {key} is found.
Passes the result to the -query:,... method to execute.

   result = [db query: @"SELECT Name FROM {Table} WHERE ID = {ID}"
                 with: values];
 
Any non-string values in the dictionary will be replaced by the results of the -quote: method.
The markup format may also be {key?default} where default is a string to be used if there is no value for the key in the dictionary.


quote: 

- (NSString*) quote: (id)obj;

Convert an object to a string suitable for use in an SQL query.
Normally the -execute:,... , and -query:,... methods will call this method automatically for everything apart from string objects.
Strings have to be handled specially, because they are used both for parts of the SQL command, and as values (where they need to be quoted). So where you need to pass a string value which needs quoting, you must call this method explicitly.
Subclasses may override this method to provide appropriate quoting for types of object which need database backend specific quoting conventions. However, the defalt implementation should be OK for most cases.
The base class implementation formats NSDate objects as
YYYY-MM-DD hh:mm:ss.mmm ?ZZZZ
NSData objects are not quoted... they must not appear in queries, and where used for insert/update operations, they need to be passed to the -backendExecute: method unchanged.
For a nil or NSNull object, we return NULL.
For a number, we simply convert directly to a string.
For a date, we convert to the text format used by the database, and add leading and trailing quotes.
For a data object, we don't quote... the other parts of the code need to know they have an NSData object and pass it on unchanged to the -backendExecute: method.
For any other type of data, we just produce a quoted string representation.


quoteCString: 

- (NSString*) quoteCString: (const char*)s;

Convert a 'C' string to a string suitable for use in an SQL query.


quoteChar: 

- (NSString*) quoteChar: (char)c;

Convert a single character to a string suitable for use in an SQL query.


quoteFloat: 

- (NSString*) quoteFloat: (float)f;

Convert a float to a string suitable for use in an SQL query.


quoteInteger: 

- (NSString*) quoteInteger: (int)i;

Convert an integer to a string suitable for use in an SQL query.


rollback 

- (void) rollback;

Revert a transaction for this database client.
This must match an earlier -begin .

NB. You must not execute an SQL statement which would commit or rollback a transaction directly... use only this method or the -rollback method.


setDatabase: 

- (void) setDatabase: (NSString*)s;

Set the database host/name for this object.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.


setName: 

- (void) setName: (NSString*)s;

Set the database reference name for this object. This is used to differentiate between multiple connections to the database.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.
NB. attempts to change the name of an instance to that of an existing instance are ignored.


setPassword: 

- (void) setPassword: (NSString*)s;

Set the database password for this object.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.


setUser: 

- (void) setUser: (NSString*)s;

Set the database user for this object.
This is called automatically to configure the connection... you normally shouldn't need to call it yourself.


simpleExecute: 

- (void) simpleExecute: (NSArray*)info;

Calls -backendExecute: in a safe manner.
Handles locking.
Maintains -lastOperation date.


simpleQuery: 

- (NSMutableArray*) simpleQuery: (NSString*)stmt;

Calls -backendQuery: in a safe manner.
Handles locking.
Maintains -lastOperation date.


user 

- (NSString*) user;

Return the database user for this instance (or nil).


Software documentation for the SQLRecord class

SQLRecord : NSArray

Declared in:
SQLClient.h

An enhanced array to represent a record returned from a query. You should NOT try to create instances of this class except via the +newWithValues:keys:count: method.



Instance Variables for SQLRecord Class

count

@private unsigned int count;

Description forthcoming.





Method summary

newWithValues: keys: count: 

+ (id) newWithValues: (id*)v keys: (id*)k count: (unsigned int)c;

Description forthcoming.


allKeys 

- (NSArray*) allKeys;

Returns an array containing the names of all the fields in the record, in the order in which they occur in the record.


objectForKey: 

- (id) objectForKey: (NSString*)key;

Returns the first field in the record whose name matches the specified key. Uses an exact match in preference to a case-insensitive match.


Software documentation for the SQLClient(Convenience) category

SQLClient(Convenience)

Declared in:
SQLClient.h

This category contains convenience methods including those for frequently performed database operations... message logging etc.

Method summary

queryRecord: ,...

- (SQLRecord*) queryRecord: (NSString*)stmt,...;

Executes a query (like the -query:,... method) and checks the result (raising an exception if the query did not contain a single record) and returns the resulting record.


queryString: ,...

- (NSString*) queryString: (NSString*)stmt,...;

Executes a query (like the -query:,... method) and checks the result.
Raises an exception if the query did not contain a single record, or if the record did not contain a single field.
Returns the resulting field as a string.


singletons: 

- (void) singletons: (NSMutableArray*)records;

Convenience method to deal with the results of a query where each record contains a single field... it converts the array of records returned by the query to an array containing the fields.


Software documentation for the SQLClient(Logging) category

SQLClient(Logging)

Declared in:
SQLClient.h

This category porovides basic methods for logging debug information.

Method summary

debugging 

+ (unsigned int) debugging;

Return the class-wide debugging level, which is inherited by all newly created instances.


durationLogging 

+ (NSTimeInterval) durationLogging;

Return the class-wide duration logging threshold, which is inherited by all newly created instances.


setDebugging: 

+ (void) setDebugging: (unsigned int)level;

Set the debugging level to be inherited by all new instances.


setDurationLogging: 

+ (void) setDurationLogging: (NSTimeInterval)threshold;

Set the duration logging threshold to be inherited by all new instances.


debug: ,...

- (void) debug: (NSString*)fmt,...;

The default implementation calls NSLogv to log a debug message.
Override this in a category to provide more sophisticated logging.


debugging 

- (unsigned int) debugging;

Return the current debugging level.


durationLogging 

- (NSTimeInterval) durationLogging;

Returns the threshold above which queries and statements taking a long time to execute are logged. A negative value (default) indicates that this logging is disabled. A value of zero means that all statements are logged.


setDebugging: 

- (void) setDebugging: (unsigned int)level;

Set the debugging level of this instance... overrides the default level inherited from the class.


setDurationLogging: 

- (void) setDurationLogging: (NSTimeInterval)threshold;

Set a threshold above which queries and statements taking a long time to execute are logged. A negative value (default) disables this logging. A value of zero logs all statements.


Software documentation for the SQLClient(Subclass) category

SQLClient(Subclass)

Declared in:
SQLClient.h

This category contains the methods which a subclass must override to provide a working instance, and helper methods for the backend implementations.
Application programmers should not call the backend methods directly.

When subclassing to produce a backend driver bundle, please be aware that the subclass must NOT introduce additional instance variables. Instead the extra instance variable is provided for use as a pointer to subclass specific data.

Method summary

backendConnect 

- (BOOL) backendConnect;
Subclasses should override this method.

Attempts to establish a connection to the database server.
Returns a flag to indicate whether the connection has been established.
If a connection was already established, returns YES and does nothing.
You should not need to use this method normally, as it is called for you automatically when necessary.

Subclasses must implement this method to establish a connection to the database server process (and initialise the extra instance variable if necessary), setting the connected instance variable to indicate the state of the object.

This method must call +purgeConnections: to ensure that there is a free slot for the new connection.

Application code must not call this method directly, it is for internal use only. The -connect method calls this method if the connected instance variable is NO.


backendDisconnect 

- (void) backendDisconnect;
Subclasses should override this method.

Disconnect from the database unless already disconnected.

This method is called automatically when the receiver is deallocated or reconfigured, and may also be called automatically when there are too many database connections active.

If the receiver is an instance of a subclass which uses the extra instance variable, it must clear that variable in the -backendDisconnect method, because a reconfiguration may cause the class of the receiver to change.

This method must set the connected instance variable to NO.

Application code must not call this method directly, it is for internal use only. The -disconnect method calls this method if the connected instance variable is YES.


backendExecute: 

- (void) backendExecute: (NSArray*)info;
Subclasses should override this method.

Perform arbitrary operation which does not return any value.
This method has a single argument, an array containing the string representing the statement to be executed as its first object, and an optional sequence of data objects following it.

   [db backendExecute: [NSArray arrayWithObject:
     @"UPDATE MyTable SET Name = 'The name' WHERE ID = 123"]];
 

The backend implementation is required to perform the SQL statement using the supplied NSData objects at the points in the statement marked by the ''' sequence. The marker saequences are inserted into the statement at an earlier stage by the -execute:,... and -execute:with: methods.

This method should lock the instance using the lock instance variable for the duration of the operation, and unlock it afterwards.

NB. callers (other than the -begin , -commit , and -rollback methods) should not pass any statement to this method which would cause a transaction to begin or end.

Application code must not call this method directly, it is for internal use only.


backendQuery: 

- (NSMutableArray*) backendQuery: (NSString*)stmt;
Subclasses should override this method.

Perform arbitrary query which returns values.

   result = [db backendQuery: @"SELECT Name FROM Table"];
 

Upon error, an exception is raised.

The query returns an array of records (each of which is represented by an SQLRecord object).

Each SQLRecord object contains one or more fields, in the order in which they occurred in the query. Fields may also be retrieved by name.

NULL field items are returned as NSNull objects.

This method should lock the instance using the lock instance variable for the duration of the operation, and unlock it afterwards.

Application code must not call this method directly, it is for internal use only.


copyEscapedBLOB: into: 

- (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf;
Subclasses should override this method.

This method is only for the use of the -insertBLOBs:intoStatement:length:withMarker:length:giving: method.
Subclasses which need to insert binary data into a statement must implement this method to copy the escaped data into place and return the number of bytes actually copied.


insertBLOBs: intoStatement: length: withMarker: length: giving: 

- (const void*) insertBLOBs: (NSArray*)blobs intoStatement: (const void*)statement length: (unsigned)sLength withMarker: (const void*)marker length: (unsigned)mLength giving: (unsigned*)result;

This method is a convenience method provided for subclasses which need to insert escaped binary data into an SQL statement before sending the statement to a backend server process. This method makes use of the -copyEscapedBLOB:into: and -lengthOfEscapedBLOB: methods, which must be implemented by the subclass.

The blobs array is an array containing the original SQL statement string (unused by this method) followed by the data items to be inserted.

The statement and sLength arguments specify the datastream to be copied and into which the BLOBs are to be inserted.

The marker and mLength arguments specify the sequence of marker bytes in the statement which indicate a position for insertion of a n escaped BLOB.

The method returns either the original statement or a copy containing the escaped BLOBs. The length of the returned data is stored in result.


lengthOfEscapedBLOB: 

- (unsigned) lengthOfEscapedBLOB: (NSData*)blob;
Subclasses should override this method.

This method is only for the use of the -insertBLOBs:intoStatement:length:withMarker:length:giving: method.
Subclasses which need to insert binary data into a statement must implement this method to return the length of the escaped bytestream which will be inserted.


SQLClient variables

SQLConnectionException

NSString* SQLConnectionException;

Exception for when a connection to the server is lost.


SQLEmptyException

NSString* SQLEmptyException;

Exception for when a query is supposed to return data and doesn't.


SQLException

NSString* SQLException;

Exception raised when an error with the remote database server occurs.


SQLUniqueException

NSString* SQLUniqueException;

Exception for when an insert/update would break the uniqueness of a field or index.



SQLClient-1.9.0/SQLClient.jigs000066400000000000000000000027011436027104400157740ustar00rootroot00000000000000{ /* -*-c-*- */ "prerequisite libraries" = ( "gnustep-base", "Performance" ); types = { NSTimeInterval = double; }; classes = ( { "file to include in preamble java code" = "Performance.import"; "java name" = "gnu.gnustep.SQLClient.SQLClient"; "objective-c name" = "SQLClient"; "class methods" = ( "allClients", "clientWithConfiguration:name:", "existingClient:", "maxConnections", "purgeConnections:", "setMaxConnections:", ); "instance methods" = ( "begin", "cache", "cache:query:with:", "cache:simpleQuery:", "clientName", "commit", "connect", "connected", "database", "debugging", "disconnect", "durationLogging", "isInTransaction", "lastOperation", "name", "password", "query:with:", "quote:", "quoteChar:", "quoteFloat:", "quoteInteger:", "rollback", "setCache:", "setDatabase:", "setDebugging:", "setDurationLogging:", "setName:", "setPassword:", "setUser:", "simpleExecute:", "simpleQuery:", "singletons:", "transaction", "user" ); }, { "java name" = "gnu.gnustep.SQLClient.SQLRecord"; "objective-c name" = "SQLRecord"; "instance methods" = ( "allKeys", "dictionary", "sizeInBytes:" ); }, { "java name" = "gnu.gnustep.SQLClient.SQLTransaction"; "objective-c name" = "SQLTransaction"; "instance methods" = ( "add:with:", "append:", "count", "owner", "execute", "reset" ); } ); } SQLClient-1.9.0/SQLClient.m000066400000000000000000003724211436027104400153050ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClient for GNUStep Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #import #define SQLCLIENT_PRIVATE @public #define SQLCLIENT_COMPILE_TIME_QUOTE_CHECK 1 #include #include "SQLClient.h" #if defined(GNUSTEP_BASE_LIBRARY) #define SUBCLASS_RESPONSIBILITY [self subclassResponsibility: _cmd]; #else #define SUBCLASS_RESPONSIBILITY #endif NSString * const SQLClientDidConnectNotification = @"SQLClientDidConnectNotification"; NSString * const SQLClientDidDisconnectNotification = @"SQLClientDidDisconnectNotification"; static unsigned int classDebugging = 0; static NSTimeInterval classDuration = -1; static NSNull *null = nil; static NSArray *queryModes = nil; static NSThread *mainThread = nil; static Class NSStringClass = Nil; static Class NSArrayClass = Nil; static Class NSDateClass = Nil; static Class NSSetClass = Nil; static Class SQLClientClass = Nil; static Class LitProxyClass = Nil; static Class LitStringClass = Nil; static Class TinyStringClass = Nil; static Class SQLStringClass = Nil; static unsigned SQLStringSize = 0; static BOOL autoquote = NO; static BOOL autoquoteWarning = NO; static BOOL isByteCoding(NSStringEncoding encoding) { if (NSASCIIStringEncoding == encoding || NSNEXTSTEPStringEncoding == encoding || NSISOLatin1StringEncoding == encoding || NSISOLatin2StringEncoding == encoding || NSISOThaiStringEncoding == encoding || NSISOLatin9StringEncoding == encoding) { return YES; } return NO; } /* Determine the length of the UTF-8 string as a unicode (UTF-16) string. * sets the ascii flag according to the content found. */ static NSUInteger lengthUTF8(const uint8_t *p, unsigned l, BOOL *ascii, BOOL *latin1) { const uint8_t *e = p + l; BOOL a = YES; BOOL l1 = YES; l = 0; while (p < e) { uint8_t c = *p; uint32_t u = c; if (c > 0x7f) { int i, sle = 0; a = NO; /* calculated the expected sequence length */ while (c & 0x80) { c = c << 1; sle++; } /* legal ? */ if ((sle < 2) || (sle > 6)) { [NSException raise: NSInternalInconsistencyException format: @"Bad sequence length in constant string"]; } if (p + sle > e) { [NSException raise: NSInternalInconsistencyException format: @"Short data in constant string"]; } /* get the codepoint */ for (i = 1; i < sle; i++) { if (p[i] < 0x80 || p[i] >= 0xc0) break; u = (u << 6) | (p[i] & 0x3f); } if (i < sle) { [NSException raise: NSInternalInconsistencyException format: @"Codepoint out of range in constant string"]; } u = u & ~(0xffffffff << ((5 * sle) + 1)); p += sle; /* * We check for invalid codepoints here. */ if (u > 0x10ffff) { [NSException raise: NSInternalInconsistencyException format: @"Codepoint invalid in constant string"]; } if ((u >= 0xd800) && (u <= 0xdfff)) { [NSException raise: NSInternalInconsistencyException format: @"Bad surrogate pair in constant string"]; } } else { p++; } /* * Add codepoint as either a single unichar for BMP * or as a pair of surrogates for codepoints over 16 bits. */ if (u < 0x10000) { l++; if (u > 255) { l1 = NO; } } else { l += 2; l1 = NO; } } if (0 != ascii) { *ascii = a; } if (0 != latin1) { *latin1 = l1; } return l; } /* */ @interface SQLString: SQLLiteral { @public NSUInteger hash; BOOL hasHash; BOOL ascii; BOOL latin1; const uint8_t *utf8Bytes; NSUInteger byteLen; NSUInteger charLen; } @end @interface SQLLiteralProxy: SQLLiteral { @public NSString *content; } @end BOOL SQLClientIsLiteral(NSString *aString) { if (nil != aString) { Class c = object_getClass(aString); if (c == LitStringClass || c == TinyStringClass || c == SQLStringClass || c == LitProxyClass) { return YES; } } return NO; } SQLLiteral * SQLClientNewLiteral(const char *bytes, unsigned count) { SQLString *s; uint8_t *p; s = NSAllocateObject(SQLStringClass, count+1, NSDefaultMallocZone()); s->utf8Bytes = p = ((uint8_t*)(void*)s) + SQLStringSize; s->byteLen = count; memcpy(p, bytes, count); p[count] = '\0'; s->charLen = lengthUTF8(s->utf8Bytes, s->byteLen, &s->ascii, &s->latin1); return s; } SQLLiteral * SQLClientCopyLiteral(NSString *aString) { if (nil != aString) { Class c = object_getClass(aString); if (c == LitProxyClass) { aString = ((SQLLiteralProxy*)aString)->content; c = object_getClass(aString); } if (c != LitStringClass && c != TinyStringClass && c != SQLStringClass) { /* The SQLString class uses utf8 and can be very inefficient * if it's too long. For long strings we use a proxy instead. */ if ([aString length] > 64) { SQLLiteralProxy *l; l = (SQLLiteralProxy*) NSAllocateObject(LitProxyClass, 0, NSDefaultMallocZone()); l->content = [aString copy]; aString = l; } else { const char *p = [aString UTF8String]; int l = strlen(p); aString = SQLClientNewLiteral(p, l); } } else { aString = [aString copy]; } } return (SQLLiteral*)aString; } SQLLiteral * SQLClientMakeLiteral(NSString *aString) { if (nil != aString) { Class c = object_getClass(aString); if (c == LitProxyClass) { aString = ((SQLLiteralProxy*)aString)->content; c = object_getClass(aString); } if (c != LitStringClass && c != TinyStringClass && c != SQLStringClass) { /* The SQLString class uses utf8 and can be very inefficient * if it's too long. For long strings we use a proxy instead. */ if ([aString length] > 64) { SQLLiteralProxy *l; l = (SQLLiteralProxy*) NSAllocateObject(LitProxyClass, 0, NSDefaultMallocZone()); l->content = [aString copy]; return (SQLLiteral*)[l autorelease]; } else { const char *p = [aString UTF8String]; int l = strlen(p); NSString *s = SQLClientNewLiteral(p, l); aString = [s autorelease]; } } } return (SQLLiteral*)aString; } SQLLiteral * SQLClientProxyLiteral(NSString *aString) { if (nil == aString) { return nil; } else if (SQLClientIsLiteral(aString)) { return (SQLLiteral*)[[aString retain] autorelease]; } else if (NO == [aString isKindOfClass: NSStringClass]) { [NSException raise: NSInvalidArgumentException format: @"Attempt to cast non-string to SQLLiteral"]; return nil; } else { SQLLiteralProxy *l; l = (SQLLiteralProxy*) NSAllocateObject(LitProxyClass, 0, NSDefaultMallocZone()); l->content = [aString retain]; return (SQLLiteral*)[l autorelease]; } } NSString * SQLClientUnProxyLiteral(id aString) { if (nil != aString) { Class c = object_getClass(aString); if (c == LitProxyClass) { aString = ((SQLLiteralProxy*)aString)->content; } else if (c != LitStringClass && c != TinyStringClass && c != SQLStringClass) { aString = [aString description]; if (YES == autoquoteWarning) { NSLog(@"SQLClient expected SQLLiteral type for %@ (%@)", aString, NSStringFromClass(c)); } } } return (NSString*)aString; } static SQLLiteral * quoteBigInteger(int64_t i) { char buf[32]; unsigned len; SQLLiteral *s; len = sprintf(buf, "%"PRId64, i); s = SQLClientNewLiteral(buf, len); return [s autorelease]; } @interface SQLClientPool (Swallow) - (BOOL) _swallowClient: (SQLClient*)client explicit: (BOOL)swallowed; @end @interface SQLTransaction (Creation) + (SQLTransaction*) _transactionUsing: (id)clientOrPool batch: (BOOL)isBatched stop: (BOOL)stopOnFailure; @end @implementation SQLLiteral + (id) allocWithZone: (NSZone*)z { [NSException raise: NSInternalInconsistencyException format: @"Illegal attempt to allocate instance of SQLLiteral"]; return nil; } - (id) copy { return RETAIN(self); } - (id) copyWithZone: (NSZone*)z { return RETAIN(self); } @end @implementation SQLLiteralProxy - (unichar) characterAtIndex: (NSUInteger)i { return [content characterAtIndex: i]; } - (void) dealloc { [content release]; [super dealloc]; } - (void) getCharacters: (unichar*)buffer { [content getCharacters: buffer]; } - (void) getCharacters: (unichar*)buffer range: (NSRange)aRange { return [content getCharacters: buffer range: aRange]; } - (NSUInteger) hash { return [content hash]; } - (BOOL) isEqual: (id)other { return [content isEqual: other]; } - (NSUInteger) length { return [content length]; } - (const char *) UTF8String { return [content UTF8String]; } @end @implementation SQLRecordKeys - (NSUInteger) count { return count; } - (void) dealloc { if (nil != order) [order release]; if (nil != map) [map release]; if (nil != low) [low release]; [super dealloc]; } - (NSUInteger) indexForKey: (NSString*)key { NSUInteger c; c = (NSUInteger)NSMapGet(map, key); if (c > 0) { return c - 1; } key = [key lowercaseString]; c = (NSUInteger)NSMapGet(low, key); if (c > 0) { if (classDebugging > 0) { NSLog(@"[SQLRecordKeys-indexForKey:] lowercase '%@'", key); } return c - 1; } return NSNotFound; } - (id) initWithKeys: (NSString**)keys count: (NSUInteger)c { if (nil != (self = [super init])) { count = c; order = [[NSArray alloc] initWithObjects: keys count: c]; map = NSCreateMapTable(NSObjectMapKeyCallBacks, NSIntegerMapValueCallBacks, count); low = NSCreateMapTable(NSObjectMapKeyCallBacks, NSIntegerMapValueCallBacks, count); for (c = 1; c <= count; c++) { NSString *k = keys[c-1]; NSMapInsert(map, (void*)k, (void*)c); k = [k lowercaseString]; NSMapInsert(low, (void*)k, (void*)c); } } return self; } - (NSArray*) order { return order; } - (NSUInteger) sizeInBytesExcluding: (NSHashTable*)exclude { NSUInteger size = [super sizeInBytesExcluding: exclude]; if (size > 0) { if (0 == bytes) { bytes = size; bytes += [order sizeInBytesExcluding: exclude]; bytes += [map sizeInBytesExcluding: exclude]; bytes += [low sizeInBytesExcluding: exclude]; } size = bytes; } return size; } @end @interface _ConcreteSQLRecord : SQLRecord { SQLRecordKeys *keys; NSUInteger count; // Must be last } @end @interface CacheQuery : NSObject { @public SQLLiteral *query; id recordType; id listType; unsigned lifetime; } @end @implementation CacheQuery - (void) dealloc { [query release]; [super dealloc]; } @end static Class aClass = 0; static Class rClass = 0; @implementation SQLRecord + (id) allocWithZone: (NSZone*)aZone { NSLog(@"Illegal attempt to allocate an SQLRecord"); return nil; } + (void) initialize { GSTickerTimeNow(); if (nil == null) { null = [NSNull new]; } if (Nil == aClass) { aClass = [NSMutableArray class]; } if (Nil == rClass) { rClass = [_ConcreteSQLRecord class]; } } + (id) newWithValues: (id*)v keys: (NSString**)k count: (unsigned int)c { return [rClass newWithValues: v keys: k count: c]; } + (id) newWithValues: (id*)v keys: (SQLRecordKeys*)k { return [rClass newWithValues: v keys: k]; } - (NSArray*) allKeys { NSUInteger count = [self count]; if (count > 0) { id buf[count]; while (count-- > 0) { buf[count] = [self keyAtIndex: count]; } return [NSArray arrayWithObjects: buf count: count]; } else { return [NSArray array]; } } - (id) copyWithZone: (NSZone*)z { return [self retain]; } - (NSUInteger) count { SUBCLASS_RESPONSIBILITY return 0; } - (NSMutableDictionary*) dictionary { NSUInteger count = [self count]; if (count > 0) { id keys[count]; id vals[count]; [self getKeys: keys]; [self getObjects: vals]; return [NSMutableDictionary dictionaryWithObjects: vals forKeys: keys count: count]; } else { return [NSMutableDictionary dictionary]; } } - (void) getKeys: (id*)buf { NSUInteger i = [self count]; while (i-- > 0) { buf[i] = [self keyAtIndex: i]; } } - (void) getObjects: (id*)buf { NSUInteger i = [self count]; while (i-- > 0) { buf[i] = [self objectAtIndex: i]; } } - (id) init { NSLog(@"Illegal attempt to -init an SQLRecord"); [self release]; return nil; } - (NSString*) keyAtIndex: (NSUInteger)index { SUBCLASS_RESPONSIBILITY return nil; } - (SQLRecordKeys*) keys { return nil; } - (id) objectAtIndex: (NSUInteger)index { SUBCLASS_RESPONSIBILITY return nil; } - (id) objectForKey: (NSString*)key { NSUInteger count = [self count]; if (count > 0) { NSUInteger pos; id keys[count]; [self getKeys: keys]; for (pos = 0; pos < count; pos++) { if ([key isEqualToString: keys[pos]] == YES) { break; } } if (pos == count) { for (pos = 0; pos < count; pos++) { if ([key caseInsensitiveCompare: keys[pos]] == NSOrderedSame) { break; } } } if (pos != count) { return [self objectAtIndex: pos]; } } return nil; } - (void) replaceObjectAtIndex: (NSUInteger)index withObject: (id)anObject { SUBCLASS_RESPONSIBILITY } - (void) setObject: (id)anObject forKey: (NSString*)aKey { NSUInteger count = [self count]; if (count > 0) { NSUInteger pos; id keys[count]; if (anObject == nil) { anObject = null; } [self getKeys: keys]; for (pos = 0; pos < count; pos++) { if ([aKey isEqualToString: keys[pos]] == YES) { break; } } if (pos == count) { for (pos = 0; pos < count; pos++) { if ([aKey caseInsensitiveCompare: keys[pos]] == NSOrderedSame) { break; } } } if (pos == count) { [NSException raise: NSInvalidArgumentException format: @"Bad key (%@) in -setObject:forKey:", aKey]; } else { [self replaceObjectAtIndex: pos withObject: anObject]; } } else { [NSException raise: NSInvalidArgumentException format: @"Bad key (%@) in -setObject:forKey:", aKey]; } } - (NSUInteger) sizeInBytes: (NSMutableSet*)exclude { NSUInteger size = [super sizeInBytes: exclude]; NSUInteger count = [self count]; if (size > 0 && count > 0) { NSUInteger pos; id vals[count]; [self getObjects: vals]; for (pos = 0; pos < count; pos++) { size += [vals[pos] sizeInBytes: exclude]; } } return size; } @end @implementation SQLRecord (KVC) - (void) setValue: (id)aValue forKey: (NSString*)aKey { [self setObject: aValue forKey: aKey]; } - (id) valueForKey: (NSString*)aKey { id v = [self objectForKey: aKey]; if (v == nil) { v = [super valueForKey: aKey]; } return v; } @end @implementation _ConcreteSQLRecord + (id) newWithValues: (id*)v keys: (SQLRecordKeys*)k { id *ptr; _ConcreteSQLRecord *r; NSUInteger c; c = [k count]; r = (_ConcreteSQLRecord*)NSAllocateObject(self, c*sizeof(id), NSDefaultMallocZone()); r->count = c; r->keys = [k retain]; ptr = (id*)(((void*)&(r->count)) + sizeof(r->count)); while (c-- > 0) { if (nil == v[c]) { ptr[c] = [null retain]; } else { ptr[c] = [v[c] retain]; } } return r; } + (id) newWithValues: (id*)v keys: (NSString**)k count: (unsigned int)c { SQLRecordKeys *o; _ConcreteSQLRecord *r; o = [[SQLRecordKeys alloc] initWithKeys: k count: c]; r = [self newWithValues: v keys: o]; [o release]; return r; } - (NSArray*) allKeys { return [keys order]; } - (id) copyWithZone: (NSZone*)z { return [self retain]; } - (NSUInteger) count { return count; } - (void) dealloc { id *ptr; NSUInteger pos; [keys release]; ptr = (id*)(((void*)&count) + sizeof(count)); for (pos = 0; pos < count; pos++) { [ptr[pos] release]; ptr[pos] = nil; } [super dealloc]; } - (NSMutableDictionary*) dictionary { NSMutableDictionary *d; NSUInteger pos; NSArray *k = [keys order]; id *ptr; ptr = (id*)(((void*)&count) + sizeof(count)); d = [NSMutableDictionary dictionaryWithCapacity: count]; for (pos = 0; pos < count; pos++) { [d setObject: ptr[pos] forKey: [[k objectAtIndex: pos] lowercaseString]]; } return d; } - (void) getKeys: (id*)buf { [[keys order] getObjects: buf]; } - (void) getObjects: (id*)buf { id *ptr; NSUInteger pos; ptr = (id*)(((void*)&count) + sizeof(count)); for (pos = 0; pos < count; pos++) { buf[pos] = ptr[pos]; } } - (id) init { NSLog(@"Illegal attempt to -init an SQLRecord"); [self release]; return nil; } - (NSString*) keyAtIndex: (NSUInteger)pos { return [[keys order] objectAtIndex: pos]; } - (SQLRecordKeys*) keys { return keys; } - (id) objectAtIndex: (NSUInteger)pos { id *ptr; if (pos >= count) { [NSException raise: NSRangeException format: @"Array index too large"]; } ptr = (id*)(((void*)&count) + sizeof(count)); return ptr[pos]; } - (id) objectForKey: (NSString*)key { NSUInteger pos = [keys indexForKey: key]; if (NSNotFound == pos) { return nil; } else { id *ptr; ptr = (id*)(((void*)&count) + sizeof(count)); return ptr[pos]; } } - (void) replaceObjectAtIndex: (NSUInteger)index withObject: (id)anObject { id *ptr; if (index >= count) { [NSException raise: NSRangeException format: @"Array index too large"]; } if (anObject == nil) { anObject = null; } ptr = (id*)(((void*)&count) + sizeof(count)); ptr += index; [anObject retain]; [*ptr release]; *ptr = anObject; } - (void) setObject: (id)anObject forKey: (NSString*)aKey { id *ptr; NSUInteger pos; if (anObject == nil) { anObject = null; } ptr = (id*)(((void*)&count) + sizeof(count)); pos = [keys indexForKey: aKey]; if (NSNotFound == pos) { [NSException raise: NSInvalidArgumentException format: @"Bad key (%@) in -setObject:forKey:", aKey]; } else { [anObject retain]; [ptr[pos] release]; ptr[pos] = anObject; } } - (NSUInteger) sizeInBytes: (NSMutableSet*)exclude { if ([exclude member: self] != nil) { return 0; } else { NSUInteger size = [super sizeInBytes: exclude]; NSUInteger pos; id *ptr; ptr = (id*)(((void*)&count) + sizeof(count)); for (pos = 0; pos < count; pos++) { size += [ptr[pos] sizeInBytes: exclude]; } return size; } } - (NSUInteger) sizeInBytesExcluding: (NSHashTable*)exclude { static NSUInteger (*imp)(id,SEL,id) = 0; NSUInteger size; /* We use the NSObject implementation to get the memory used, * and then add in the fields within the record. */ if (0 == imp) { imp = (NSUInteger(*)(id,SEL,id)) [NSObject instanceMethodForSelector: _cmd]; } size = (*imp)(self, _cmd, exclude); if (size > 0) { NSUInteger pos; id *ptr; size += [keys sizeInBytesExcluding: exclude]; size += sizeof(void*) * count; ptr = (id*)(((void*)&count) + sizeof(count)); for (pos = 0; pos < count; pos++) { size += [ptr[pos] sizeInBytesExcluding: exclude]; } } return size; } @end /** * Exception raised when an error with the remote database server occurs. */ NSString *SQLException = @"SQLException"; /** * Exception for when a connection to the server is lost. */ NSString *SQLConnectionException = @"SQLConnectionException"; /** * Exception for when a query is supposed to return data and doesn't. */ NSString *SQLEmptyException = @"SQLEmptyException"; /** * Exception for when an insert/update would break the uniqueness of a * field or index. */ NSString *SQLUniqueException = @"SQLUniqueException"; @implementation SQLClient (Logging) + (unsigned int) debugging { return classDebugging; } + (NSTimeInterval) durationLogging { return classDuration; } + (void) setDebugging: (unsigned int)level { classDebugging = level; } + (void) setDurationLogging: (NSTimeInterval)threshold { classDuration = threshold; } - (void) debug: (NSString*)fmt, ... { va_list ap; va_start(ap, fmt); NSLogv(fmt, ap); va_end(ap); } - (unsigned int) debugging { return _debugging; } - (NSTimeInterval) durationLogging { return _duration; } - (void) setDebugging: (unsigned int)level { _debugging = level; } - (void) setDurationLogging: (NSTimeInterval)threshold { _duration = threshold; } @end /* Containers for all instances. * Access to and update of these containers is protected by classLock. * Most other operations involving an instance are protected by a lock * in that instance. * To avoid deadlocks, we always obtain the instance lock *before* we * obtain the class lock, so we don't get the situation where one thread * has locked the instance and another has locked the class lock, and * each thread then tries to get the other lock. */ static NSHashTable *clientsHash = 0; static NSMapTable *clientsMap = 0; static NSRecursiveLock *clientsLock = nil; /* Protect changes to the cache used for queries by any individual client. */ static NSRecursiveLock *cacheLock = nil; static NSString *beginString = @"begin"; static NSArray *beginStatement = nil; static NSString *commitString = @"commit"; static NSArray *commitStatement = nil; static NSString *rollbackString = @"rollback"; static NSArray *rollbackStatement = nil; @interface SQLClient (Private) /** * Internal method to handle configuration using the notification object. * This object may be either a configuration front end or a user defaults * object ... so we have to be careful that we work with both. */ - (void) _configure: (NSNotification*)n; /** Internal method to make the client instance lock available to * an associated SQLTransaction */ - (NSRecursiveLock*) _lock; /** Internal method to populate the cache with the result of a query. */ - (void) _populateCache: (CacheQuery*)a; /** Internal method called to record the 'main' thread in which automated * cache updates are to be performed. */ - (void) _recordMainThread; /* * Called at one second intervals to ensure that our current timestamp * is reasonably accurate. */ + (void) _tick: (NSTimer*)t; @end @interface SQLClient (GSCacheDelegate) - (BOOL) shouldKeepItem: (id)anObject withKey: (id)aKey lifetime: (unsigned)lifetime after: (unsigned)delay; @end @implementation SQLClient static NSTimeInterval abandonAfter = 0.0; static unsigned int maxConnections = 8; static int poolConnections = 0; + (NSArray*) allClients { NSMutableArray *a; NSHashEnumerator e; id o; [clientsLock lock]; a = [NSMutableArray arrayWithCapacity: NSCountHashTable(clientsHash)]; e = NSEnumerateHashTable(clientsHash); while (nil != (o = (id)NSNextHashEnumeratorItem(&e))) { [a addObject: o]; } NSEndHashTableEnumeration(&e); [clientsLock unlock]; return a; } + (SQLClient*) clientWithConfiguration: (NSDictionary*)config name: (NSString*)reference { SQLClient *o; if ([reference isKindOfClass: NSStringClass] == NO) { if (nil == config) { config = (NSDictionary*)[NSUserDefaults standardUserDefaults]; } reference = [config objectForKey: @"SQLClientName"]; if ([reference isKindOfClass: NSStringClass] == NO) { reference = @"Database"; } } o = [self existingClient: reference]; if (nil == o) { o = [[[SQLClient alloc] initWithConfiguration: config name: reference] autorelease]; } else if ([config isKindOfClass: [NSUserDefaults class]] == NO) { /* If the configuration object is not the user defaults * make sure to update the existing connnection's configuration. */ NSNotification *n = [NSNotification notificationWithName: NSUserDefaultsDidChangeNotification object: config userInfo: nil]; [o _configure: n]; } return o; } + (SQLClient*) existingClient: (NSString*)reference { SQLClient *existing; if ([reference isKindOfClass: NSStringClass] == NO) { reference = [[NSUserDefaults standardUserDefaults] stringForKey: @"SQLClientName"]; if (reference == nil) { reference = @"Database"; } } [clientsLock lock]; existing = (SQLClient*)NSMapGet(clientsMap, reference); [[existing retain] autorelease]; [clientsLock unlock]; return existing; } + (void) initialize { if (Nil == SQLClientClass && [SQLClient class] == self) { static id modes[1]; if (Nil == LitStringClass) { /* Find the literal string class used by the foundation library. * We may have two varieties. */ LitStringClass = object_getClass(@"test string"); TinyStringClass = object_getClass(@"test"); SQLStringClass = [SQLString class]; SQLStringSize = class_getInstanceSize(SQLStringClass); LitProxyClass = [SQLLiteralProxy class]; } if (nil == null) { null = [NSNull new]; } SQLClientClass = self; modes[0] = NSDefaultRunLoopMode; queryModes = [[NSArray alloc] initWithObjects: modes count: 1]; GSTickerTimeNow(); [SQLRecord class]; // Force initialisatio if (0 == clientsHash) { cacheLock = [NSRecursiveLock new]; clientsHash = NSCreateHashTable(NSNonOwnedPointerHashCallBacks, 0); clientsMap = NSCreateMapTable(NSObjectMapKeyCallBacks, NSNonRetainedObjectMapValueCallBacks, 0); clientsLock = [NSRecursiveLock new]; beginStatement = [[NSArray arrayWithObject: beginString] retain]; commitStatement = [[NSArray arrayWithObject: commitString] retain]; rollbackStatement = [[NSArray arrayWithObject: rollbackString] retain]; NSStringClass = [NSString class]; NSDateClass = [NSDate class]; NSArrayClass = [NSArray class]; NSSetClass = [NSSet class]; [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(_tick:) userInfo: 0 repeats: YES]; } } } + (unsigned int) maxConnections { return maxConnections; } + (void) purgeConnections: (NSDate*)since { NSHashEnumerator e; NSMutableArray *a = nil; SQLClient *o; unsigned int connectionCount = 0; NSTimeInterval t; t = (nil == since) ? 0.0 : [since timeIntervalSinceReferenceDate]; /* Find clients we may want to disconnect. */ [clientsLock lock]; e = NSEnumerateHashTable(clientsHash); while (nil != (o = (SQLClient*)NSNextHashEnumeratorItem(&e))) { if (YES == o->connected) { connectionCount++; if (since != nil) { NSTimeInterval when = o->_lastOperation; if (when < o->_lastStart) { when = o->_lastStart; } if (when < t) { if (nil == a) { a = [NSMutableArray array]; } [a addObject: o]; } } } } NSEndHashTableEnumeration(&e); [clientsLock unlock]; /* Disconnect any clients idle too long */ while ([a count] > 0) { o = [a lastObject]; if ([o->lock tryLock]) { if (YES == o->connected) { NSTimeInterval when = o->_lastOperation; if (when < o->_lastStart) { when = o->_lastStart; } if (when < t) { NS_DURING { [o disconnect]; } NS_HANDLER { NSLog(@"Problem disconnecting: %@", localException); } NS_ENDHANDLER } } if (NO == o->connected) { connectionCount--; } [o->lock unlock]; } [a removeLastObject]; } while (connectionCount >= (maxConnections + poolConnections)) { SQLClient *other = nil; NSTimeInterval oldest = 0.0; connectionCount = 0; [clientsLock lock]; e = NSEnumerateHashTable(clientsHash); while (nil != (o = (SQLClient*)NSNextHashEnumeratorItem(&e))) { if (YES == o->connected) { NSTimeInterval when = o->_lastOperation; if (when < o->_lastStart) { when = o->_lastStart; } connectionCount++; if (oldest == 0.0 || when < oldest) { oldest = when; ASSIGN(other, o); } } } NSEndHashTableEnumeration(&e); [clientsLock unlock]; connectionCount--; if ([other debugging] > 0) { [other debug: @"Force disconnect of '%@' because max connections (%u) reached", other, maxConnections]; } [AUTORELEASE(other) disconnect]; } } + (void) setAbandonFailedConnectionsAfter: (NSTimeInterval)delay { abandonAfter = delay; } + (void) setMaxConnections: (unsigned int)c { if (c > 0) { maxConnections = c; [self purgeConnections: nil]; } } - (void) begin { [lock lock]; if (_inTransaction == NO) { NS_DURING { [self simpleExecute: beginStatement]; _inTransaction = YES; /* NB. We leave the lock locked ... until a matching -commit * or -rollback is called. This prevents other threads from * interfering with this transaction. */ } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER } else { [lock unlock]; [NSException raise: NSInternalInconsistencyException format: @"begin used inside transaction"]; } } - (SQLLiteral*) buildQuery: (NSString*)stmt, ... { va_list ap; NSString *sql = nil; /* * First check validity and concatenate parts of the query. */ va_start (ap, stmt); sql = [[self prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); if ([sql length] < 1000) { return SQLClientMakeLiteral(sql); } return SQLClientProxyLiteral(sql); } - (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values { NSString *sql = nil; sql = [[self prepare: stmt with: values] objectAtIndex: 0]; if ([sql length] < 1000) { return SQLClientMakeLiteral(sql); } return SQLClientProxyLiteral(sql); } - (NSString*) clientName { NSString *s; [lock lock]; if (nil == _client) { _client = [[[NSProcessInfo processInfo] globallyUniqueString] retain]; } s = [_client retain]; [lock unlock]; return [s autorelease]; } - (void) commit { [lock lock]; if (_inTransaction == NO) { [lock unlock]; [NSException raise: NSInternalInconsistencyException format: @"commit used outside transaction"]; } /* Since we are in a transaction we must be doubly locked right now, * so we unlock once, and we still have the lock (which was locked * in the earlier call to the -begin method). */ [lock unlock]; _inTransaction = NO; NS_DURING { [self simpleExecute: commitStatement]; [_statements removeAllObjects]; [lock unlock]; // Locked by -begin } NS_HANDLER { [_statements removeAllObjects]; [lock unlock]; // Locked by -begin [localException raise]; } NS_ENDHANDLER } - (uint64_t) committed { return _committed; } - (BOOL) connect { if (NO == [self tryConnect] && abandonAfter > 0.0) { NSTimeInterval end; end = [NSDate timeIntervalSinceReferenceDate] + abandonAfter; while (NO == connected && [NSDate timeIntervalSinceReferenceDate] < end) { [self tryConnect]; } } return connected; } - (BOOL) connected { return connected; } - (NSString*) database { return _database; } - (void) dealloc { NSNotificationCenter *nc; [clientsLock lock]; NSHashRemove(clientsHash, (void*)self); if (_name != nil && (SQLClient*)NSMapGet(clientsMap, (void*)_name) == self) { NSMapRemove(clientsMap, (void*)_name); } [clientsLock unlock]; nc = [NSNotificationCenter defaultCenter]; [nc removeObserver: self]; if (YES == connected) [self disconnect]; [lock release]; lock = nil; [_client release]; _client = nil; [_database release]; _database = nil; [_password release]; _password = nil; [_user release]; _user = nil; [_name release]; _name = nil; [_statements release]; _statements = nil; [_cache release]; _cache = nil; [_cacheThread release]; _cacheThread = nil; if (0 != _observers) { NSNotificationCenter *nc; NSMapEnumerator e; NSMutableSet *n; id o; nc = [NSNotificationCenter defaultCenter]; e = NSEnumerateMapTable(_observers); while (NSNextMapEnumeratorPair(&e, (void**)&o, (void**)&n) != 0) { NSEnumerator *ne = [n objectEnumerator]; NSString *name; while (nil != (name = [ne nextObject])) { [nc removeObserver: o name: name object: nil]; } } NSEndMapTableEnumeration(&e); NSFreeMapTable(_observers); _observers = 0; } [_names release]; _names = 0; [super dealloc]; } - (NSString*) description { NSMutableString *s = [[NSMutableString new] autorelease]; [lock lock]; NS_DURING { [s appendFormat: @"Database - %@\n", [self clientName]]; [s appendFormat: @" Name - %@\n", [self name]]; [s appendFormat: @" DBase - %@\n", [self database]]; [s appendFormat: @" DB User - %@\n", [self user]]; [s appendFormat: @" Password - %@\n", [self password] == nil ? @"unknown" : @"known"]; [s appendFormat: @" Connected - %@\n", connected ? @"yes" : @"no"]; [s appendFormat: @" Committed - %"PRIu64"\n", _committed]; [s appendFormat: @" Transaction - %@\n", _inTransaction ? @"yes" : @"no"]; } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; return s; } - (void) disconnect { if (YES == connected) { NSNotificationCenter *nc; [lock lock]; if (YES == _inTransaction) { /* If we are inside a transaction we must be doubly locked, * so we do an unlock corresponding to the -begin before we * disconnect (the disconnect implicitly rolls back the * transaction). */ _inTransaction = NO; [lock unlock]; } if (YES == connected) { NS_DURING { [self backendDisconnect]; } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER } [lock unlock]; nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName: SQLClientDidDisconnectNotification object: self]; } } - (NSInteger) execute: (NSString*)stmt, ... { NSArray *info; va_list ap; va_start (ap, stmt); info = [self prepare: stmt args: ap]; va_end (ap); return [self simpleExecute: info]; } - (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values { NSArray *info; info = [self prepare: stmt with: values]; return [self simpleExecute: info]; } - (id) init { return [self initWithConfiguration: nil name: nil]; } - (id) initWithConfiguration: (NSDictionary*)config { return [self initWithConfiguration: config name: nil]; } - (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference { return [self initWithConfiguration: config name: reference pool: nil]; } - (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference pool: (SQLClientPool*)pool { NSNotification *n; NSDictionary *conf = config; id existing; if (conf == nil) { // Pretend the defaults object is a dictionary. conf = (NSDictionary*)[NSUserDefaults standardUserDefaults]; } if ([reference isKindOfClass: NSStringClass] == NO) { reference = [conf objectForKey: @"SQLClientName"]; if ([reference isKindOfClass: NSStringClass] == NO) { reference = @"Database"; } } [clientsLock lock]; _pool = pool; if (nil != _pool) { existing = nil; // Pool, object ... can't already exist } else { existing = (SQLClient*)NSMapGet(clientsMap, reference); } if (nil == existing) { lock = [NSRecursiveLock new]; // Ensure thread-safety. [self setDebugging: [[self class] debugging]]; [self setDurationLogging: [[self class] durationLogging]]; [self setName: reference]; // Set name and store in cache. _statements = [NSMutableArray new]; if ([conf isKindOfClass: [NSUserDefaults class]] == YES) { NSNotificationCenter *nc; nc = [NSNotificationCenter defaultCenter]; [nc addObserver: self selector: @selector(_configure:) name: NSUserDefaultsDidChangeNotification object: conf]; } n = [NSNotification notificationWithName: NSUserDefaultsDidChangeNotification object: conf userInfo: nil]; NSHashInsert(clientsHash, (void*)self); [self _configure: n]; // Actually set up the configuration. } else { [self release]; self = [existing retain]; if ([conf isKindOfClass: [NSUserDefaults class]] == NO) { /* If the configuration object is not the user defaults * make sure to update the existing connnection's configuration. */ n = [NSNotification notificationWithName: NSUserDefaultsDidChangeNotification object: conf userInfo: nil]; [self _configure: n]; } } [clientsLock unlock]; return self; } - (NSUInteger) hash { return [[self database] hash] + [[self user] hash]; } - (BOOL) isEqual: (id)other { if (self == other) { return YES; } if ([self class] != [other class]) { return NO; } if (NO == [[self database] isEqual: [other database]]) { return NO; } if (NO == [[self user] isEqual: [other user]]) { return NO; } return YES; } - (BOOL) isInTransaction { return _inTransaction; } - (NSDate*) lastConnect { if (_lastConnect > 0.0) { return [NSDate dateWithTimeIntervalSinceReferenceDate: _lastConnect]; } return nil; } - (NSDate*) lastOperation { if (_lastOperation > 0.0 && _connectFails == 0) { return [NSDate dateWithTimeIntervalSinceReferenceDate: _lastOperation]; } return nil; } - (BOOL) lockBeforeDate: (NSDate*)limit { if (nil == limit) { return [lock tryLock]; } return [lock lockBeforeDate: limit]; } - (SQLClient*) longestIdle: (SQLClient*)other { NSTimeInterval t0; NSTimeInterval t1; t0 = _lastOperation; if (t0 < _lastStart) { t0 = _lastStart; } if (NO == connected || 0 != _connectFails) { t0 = 0.0; } if (NO == [other isKindOfClass: SQLClientClass] || YES == [other isProxy]) { t1 = 0.0; } else { t1 = other->_lastOperation; if (t1 < other->_lastStart) { t1 = other->_lastStart; } if (NO == other->connected || 0 != other->_connectFails) { t1 = 0.0; } } if (t1 > 0.0 && (t1 <= t0 || 0.0 == t0)) { return other; } if (t0 > 0.0 && (t0 <= t1 || 0.0 == t1)) { return self; } return nil; } - (NSString*) name { return _name; } - (NSString*) password { return _password; } - (NSMutableArray*) prepare: (NSString*)stmt, ... { va_list ap; NSMutableArray *result; va_start (ap, stmt); result = [self prepare: stmt args: ap]; va_end (ap); return result; } - (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args { NSMutableArray *ma = [NSMutableArray arrayWithCapacity: 2]; NSString *tmp = va_arg(args, NSString*); NSAutoreleasePool *arp = [NSAutoreleasePool new]; if (tmp != nil) { NSMutableString *s = [NSMutableString stringWithCapacity: 1024]; NSString *warn = nil; unsigned index = 0; [s appendString: stmt]; /* * Append any values from the nil terminated varargs */ while (tmp != nil) { index++; if ([tmp isKindOfClass: [NSData class]] == YES) { [ma addObject: tmp]; tmp = @"'?'''?'"; // Marker. } else if ([tmp isKindOfClass: NSStringClass] == NO) { tmp = [self quote: tmp]; } else { Class c = object_getClass(tmp); if (c == LitProxyClass) { tmp = ((SQLLiteralProxy*)tmp)->content; } else if (c != LitStringClass && c != TinyStringClass && c != SQLStringClass) { if (nil == warn) { warn = [NSString stringWithFormat: @"\"%@\" (argument %u, %@)", tmp, index, NSStringFromClass(c)]; } if (YES == autoquote) { tmp = [self quote: tmp]; } } } [s appendString: tmp]; tmp = va_arg(args, NSString*); } stmt = s; if (nil != warn && YES == autoquoteWarning) { if (YES == autoquote) { NSLog(@"SQLClient autoquote performed for %@ in \"%@\"", warn, stmt); } else { NSLog(@"SQLClient autoquote proposed for %@ in \"%@\"", warn, stmt); } } } [ma insertObject: SQLClientMakeLiteral(stmt) atIndex: 0]; [arp release]; return ma; } - (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values { unsigned int l = [stmt length]; NSRange r; NSMutableArray *ma = [NSMutableArray arrayWithCapacity: 2]; NSAutoreleasePool *arp = [NSAutoreleasePool new]; if (l < 2) { [ma addObject: SQLClientMakeLiteral(stmt)]; // Can't contain {...} } else if ((r = [stmt rangeOfString: @"{"]).length == 0) { [ma addObject: SQLClientMakeLiteral(stmt)]; // No '{' markup } else if (l - r.location < 2) { [ma addObject: SQLClientMakeLiteral(stmt)]; // Can't contain {...} } else if ([stmt rangeOfString: @"}" options: NSLiteralSearch range: NSMakeRange(r.location, l - r.location)].length == 0 && [stmt rangeOfString: @"{{" options: NSLiteralSearch range: NSMakeRange(0, l)].length == 0) { [ma addObject: SQLClientMakeLiteral(stmt)]; // No '}' or '{{' } else if (r.length == 0) { [ma addObject: SQLClientMakeLiteral(stmt)]; // Nothing to do. } else { NSMutableString *mtext = [[stmt mutableCopy] autorelease]; NSString *warn = nil; /* * Replace {FieldName} with the value of the field */ while (r.length > 0) { unsigned pos = r.location; unsigned nxt; unsigned vLength; NSArray *a; NSRange s; NSString *k; NSString *v; NSString *alt; id o; unsigned i; r.length = l - pos; /* * If the length of the string from the '{' onwards is less than two, * there is nothing to do and we can end processing. */ if (r.length < 2) { break; } if ([mtext characterAtIndex: r.location + 1] == '{') { // Got '{{' ... remove one of them. r.length = 1; [mtext replaceCharactersInRange: r withString: @""]; l--; r.location++; r.length = l - r.location; r = [mtext rangeOfString: @"{" options: NSLiteralSearch range: r]; continue; } r = [mtext rangeOfString: @"}" options: NSLiteralSearch range: r]; if (r.length == 0) { break; // No closing bracket } nxt = NSMaxRange(r); r = NSMakeRange(pos, nxt - pos); s.location = r.location + 1; s.length = r.length - 2; k = v = [mtext substringWithRange: s]; /* * If the value contains a '?', it is actually in two parts, * the first part is the field name, and the second part is * an alternative text to be used if the value from the * dictionary is empty. */ s = [v rangeOfString: @"?"]; if (s.length == 0) { alt = @""; // No alternative value. } else { alt = [v substringFromIndex: NSMaxRange(s)]; v = [v substringToIndex: s.location]; } /* * If the value we are substituting contains dots, we split it apart. * We use the value to make a reference into the dictionary we are * given. */ a = [v componentsSeparatedByString: @"."]; o = values; for (i = 0; i < [a count]; i++) { NSString *k = [a objectAtIndex: i]; if ([k length] > 0) { o = [(NSDictionary*)o objectForKey: k]; } } if (o == values || o == nil) { v = nil; // Mo match found. } else { if ([o isKindOfClass: [NSData class]] == YES) { [ma addObject: o]; v = @"'?'''?'"; } else if ([o isKindOfClass: NSStringClass] == NO) { v = [self quote: o]; } else { Class c = object_getClass(o); v = o; if (c == LitProxyClass) { v = ((SQLLiteralProxy*)o)->content; } else if (c != LitStringClass && c != TinyStringClass && c != SQLStringClass) { if (nil == warn) { warn = [NSString stringWithFormat: @"\"%@\" (value for \"%@\", %@)", o, k, NSStringFromClass(c)]; } if (YES == autoquote) { v = [self quote: o]; } } } } if ([v length] == 0) { v = alt; if (v == nil) { v = @""; } } vLength = [v length]; [mtext replaceCharactersInRange: r withString: v]; l += vLength; // Add length of string inserted l -= r.length; // Remove length of string replaced r.location += vLength; if (r.location >= l) { break; } r.length = l - r.location; r = [mtext rangeOfString: @"{" options: NSLiteralSearch range: r]; } [ma insertObject: SQLClientProxyLiteral(mtext) atIndex: 0]; if (nil != warn && YES == autoquoteWarning) { if (YES == autoquote) { NSLog(@"SQLClient autoquote performed for %@ in \"%@\"", warn, mtext); } else { NSLog(@"SQLClient autoquote proposed for %@ in \"%@\"", warn, mtext); } } } [arp release]; return ma; } - (NSMutableArray*) query: (NSString*)stmt, ... { va_list ap; NSMutableArray *result = nil; SQLLiteral *query; /* * First check validity and concatenate parts of the query. */ va_start (ap, stmt); query = [[self prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); result = [self simpleQuery: query]; return result; } - (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values { NSMutableArray *result = nil; SQLLiteral *query; query = [[self prepare: stmt with: values] objectAtIndex: 0]; result = [self simpleQuery: query]; return result; } - (SQLLiteral*) quote: (id)obj { /* For a nil object, we return NULL. */ if (obj == nil || obj == null) { return (SQLLiteral*)@"NULL"; } else if ([obj isKindOfClass: NSStringClass] == NO) { /* For a data object, we don't quote ... the other parts of the code * need to know they have an NSData object and pass it on unchanged * to the -backendExecute: method. */ if ([obj isKindOfClass: [NSData class]] == YES) { return obj; } SQLLiteral *tmp = [obj quoteForSQLClient: self]; if (nil == tmp) { [NSException raise: NSInvalidArgumentException format: @"Attempt to SQL quote instance of unsupported class: %@", obj]; } return tmp; } /* Get a string description of the object. */ obj = [self quoteString: obj]; return obj; } - (SQLLiteral*) quotef: (NSString*)fmt, ... { va_list ap; NSString *str; SQLLiteral *quoted; va_start(ap, fmt); str = [[NSString allocWithZone: NSDefaultMallocZone()] initWithFormat: fmt arguments: ap]; va_end(ap); quoted = [self quoteString: str]; [str release]; return quoted; } - (SQLLiteral*) quoteArray: (NSArray *)a { NSMutableString *s; s = [self quoteArray: a toString: nil quotingStrings: NO]; return SQLClientProxyLiteral(s); } - (SQLLiteral*) quoteArraySafe: (NSArray *)a { NSMutableString *s; s = [self quoteArray: a toString: nil quotingStrings: YES]; return SQLClientProxyLiteral(s); } - (NSMutableString*) quoteArray: (NSArray *)a toString: (NSMutableString *)s quotingStrings: (BOOL)q { [NSException raise: NSGenericException format: @"%@ not supported for this database", NSStringFromSelector(_cmd)]; return nil; } - (SQLLiteral*) quoteBigInteger: (int64_t)i { char buf[32]; unsigned len; SQLLiteral *s; len = sprintf(buf, "%"PRId64, i); s = SQLClientNewLiteral(buf, len); return [s autorelease]; } - (SQLLiteral*) quoteBoolean: (int)i { return (SQLLiteral*)(i ? @"true" : @"false"); } - (SQLLiteral*) quoteCString: (const char *)s { NSString *str; SQLLiteral *quoted; if (s == 0) { s = ""; } str = [[NSString alloc] initWithCString: s]; quoted = [self quoteString: str]; [str release]; return quoted; } - (SQLLiteral*) quoteChar: (char)c { NSString *str; SQLLiteral *quoted; if (c == 0) { [NSException raise: NSInvalidArgumentException format: @"Attempt to quote a nul character in -quoteChar:"]; } str = [[NSString alloc] initWithFormat: @"%c", c]; quoted = [self quoteString: str]; [str release]; return quoted; } - (SQLLiteral*) quoteFloat: (double)f { char buf[32]; unsigned len; SQLLiteral *s; len = sprintf(buf, "%.17g", f); s = SQLClientNewLiteral(buf, len); return [s autorelease]; } - (SQLLiteral*) quoteInteger: (int)i { char buf[32]; unsigned len; SQLLiteral *s; len = sprintf(buf, "%i", i); s = SQLClientNewLiteral(buf, len); return [s autorelease]; } - (SQLLiteral*) quoteName: (NSString *)s { NSData *d = [s dataUsingEncoding: NSUTF8StringEncoding]; const char *src = (const char*)[d bytes]; char *dst; unsigned len = [d length]; unsigned count = 2; unsigned i; SQLString *q; for (i = 0; i < len; i++) { char c = src[i]; if ('\"' == c) { count++; // A quote needs to be doubled } if ('\0' != c) { count++; // A nul needs to be ignored } } q = NSAllocateObject(SQLStringClass, count + 1, NSDefaultMallocZone()); dst = ((char*)(void*)q) + SQLStringSize; q->utf8Bytes = (uint8_t*)dst; q->byteLen = count; *dst++ = '\"'; for (i = 0; i < len; i++) { char c = src[i]; if ('\"' == c) { *dst++ = '\"'; } if ('\0' != c) { *dst++ = c; } } *dst++ = '\"'; *dst = '\0'; q->charLen = lengthUTF8(q->utf8Bytes, q->byteLen, &q->ascii, &q->latin1); return [q autorelease]; } - (SQLLiteral*) quoteSet: (id)obj { NSEnumerator *enumerator = [obj objectEnumerator]; NSMutableString *ms = [NSMutableString stringWithCapacity: 100]; id value = [enumerator nextObject]; [ms appendString: @"("]; if (value != nil) { [ms appendString: [self quote: value]]; } while ((value = [enumerator nextObject]) != nil) { [ms appendString: @","]; [ms appendString: [self quote: value]]; } [ms appendString: @")"]; return SQLClientMakeLiteral(ms); } - (SQLLiteral*) quoteString: (NSString *)s { NSData *d = [s dataUsingEncoding: NSUTF8StringEncoding]; const char *src = (const char*)[d bytes]; char *dst; unsigned len = [d length]; unsigned count = 2; unsigned i; SQLString *q; for (i = 0; i < len; i++) { char c = src[i]; if ('\'' == c) { count++; // A quote needs to be doubled } if ('\0' != c) { count++; // A nul needs to be ignored } } q = NSAllocateObject(SQLStringClass, count + 1, NSDefaultMallocZone()); dst = ((char*)(void*)q) + SQLStringSize; q->utf8Bytes = (uint8_t*)dst; q->byteLen = count; *dst++ = '\''; for (i = 0; i < len; i++) { char c = src[i]; if ('\'' == c) { *dst++ = '\''; } if ('\0' != c) { *dst++ = c; } } *dst++ = '\''; *dst = '\0'; q->charLen = lengthUTF8(q->utf8Bytes, q->byteLen, &q->ascii, &q->latin1); return [q autorelease]; } - (oneway void) release { /* We lock the table while checking, to prevent another thread * from grabbing this object while we are checking it. */ [clientsLock lock]; if (nil != _pool && [self retainCount] == 1) { /* This is the only reference to a client associated with * a connection pool we put this client back to the pool. * * That being the case, we know that this thread 'owns' * the client and it's not going to be deallocated and not * going to have the _pool iinstance variable changed, so it * is safe to unlock clientsLock before returning the client * to the pool. This avoids a possible deadlock when a pool * is being purged. * * wl 2019-05-01: The original implementation was calling this code * when NSDecrementExtraRefCountWasZero returns YES, but * this does not work with newer versions of the GNUstep * Objective-C runtime nor with recent versions of Apple's * Objective-C runtime, which both don't handle resurrection * gracefully for objects whose retain count has become zero. */ [clientsLock unlock]; [_pool _swallowClient: self explicit: NO]; } else { [super release]; [clientsLock unlock]; } } - (SQLClientPool*) pool { return _pool; } - (void) rollback { [lock lock]; if (NO == _inTransaction) { [lock unlock]; // Not in a transaction ... nothing to do. return; } /* Since we are in a transaction we must be doubly locked right now, * so we unlock once, and we still have the lock (which was locked * in the earlier call to the -begin method). */ [lock unlock]; _inTransaction = NO; NS_DURING { /* If the connection was lost, the transaction has implicitly * rolled back anyway, so we should skip the rollback statement. */ if (YES == [self connected]) { [self simpleExecute: rollbackStatement]; } [_statements removeAllObjects]; [lock unlock]; // Locked by -begin } NS_HANDLER { [_statements removeAllObjects]; [lock unlock]; // Locked by -begin [localException raise]; } NS_ENDHANDLER } - (void) setClientName: (NSString*)s { [lock lock]; ASSIGNCOPY(_client, s); [lock unlock]; } - (void) setDatabase: (NSString*)s { [lock lock]; NS_DURING { if ([s isEqual: _database] == NO) { if (YES == connected) { [self disconnect]; } s = [s copy]; [_database release]; _database = s; } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (void) setName: (NSString*)s { [lock lock]; NS_DURING { if ([s isEqual: _name] == NO) { [clientsLock lock]; if (nil == _pool) { if (NSMapGet(clientsMap, s) != 0) { [clientsLock unlock]; [lock unlock]; if ([self debugging] > 0) { [self debug: @"Error attempt to re-use client name %@", s]; } NS_VOIDRETURN; } } if (YES == connected) { [self disconnect]; } if (_name != nil && (SQLClient*)NSMapGet(clientsMap, (void*)_name) == self) { NSMapRemove(clientsMap, (void*)_name); } s = [s copy]; [_name release]; _name = s; if (nil == _client) { _client = [[[NSProcessInfo processInfo] globallyUniqueString] retain]; } if (nil == _pool && _name != nil) { NSMapInsert(clientsMap, (void*)_name, (void*)self); } [clientsLock unlock]; } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (void) setOptions: (NSDictionary*)o { return; // Abstract class does not use options } - (void) setPassword: (NSString*)s { [lock lock]; NS_DURING { if ([s isEqual: _password] == NO) { if (YES == connected) { [self disconnect]; } s = [s copy]; [_password release]; _password = s; } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (void) setShouldTrim: (BOOL)aFlag { _shouldTrim = (YES == aFlag) ? YES : NO; } - (void) setUser: (NSString*)s { [lock lock]; NS_DURING { if ([s isEqual: _user] == NO) { if (YES == connected) { [self disconnect]; } s = [s copy]; [_user release]; _user = s; } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (NSInteger) simpleExecute: (id)info { NSInteger result; NSString *debug = nil; BOOL done = NO; BOOL isCommit = NO; BOOL isRollback = NO; NSString *statement; if ([info isKindOfClass: NSArrayClass] == NO) { if ([info isKindOfClass: NSStringClass] == NO) { [NSException raise: NSInvalidArgumentException format: @"[%@ -simpleExecute: %@ (class %@)]", NSStringFromClass([self class]), info, NSStringFromClass([info class])]; } info = [NSMutableArray arrayWithObject: info]; } [lock lock]; statement = [info objectAtIndex: 0]; /* Ensure we have a working connection. */ if ([self connect] == NO) { [lock unlock]; [NSException raise: SQLConnectionException format: @"Unable to connect to '%@' to run statement %@", [self name], statement]; } if ([statement isEqualToString: commitString]) { isCommit = YES; } if ([statement isEqualToString: rollbackString]) { isRollback = YES; } while (NO == done) { debug = nil; done = YES; NS_DURING { _lastStart = GSTickerTimeNow(); result = [self backendExecute: info]; _lastOperation = GSTickerTimeNow(); [_statements addObject: statement]; if (_duration >= 0) { NSTimeInterval d; d = _lastOperation - _lastStart; if (d >= _duration) { NSMutableString *m; if (isCommit || isRollback) { NSEnumerator *e = [_statements objectEnumerator]; if (isCommit) { m = [NSMutableString stringWithFormat: @"Duration %g for transaction commit ...\n", d]; } else { m = [NSMutableString stringWithFormat: @"Duration %g for transaction rollback ...\n", d]; } while ((statement = [e nextObject]) != nil) { [m appendFormat: @" %@;\n", statement]; } [m appendFormat: @" affected %"PRIdPTR" record%s\n", result, ((1 == result) ? "" : "s")]; } else if ([self debugging] > 1) { /* * For higher debug levels, we log data objects as well * as the query string, otherwise we omit them. */ m = [NSMutableString stringWithFormat: @"Duration %g for statement %@;", d, info]; [m appendFormat: @" affected %"PRIdPTR" record%s", result, ((1 == result) ? "" : "s")]; } else { m = [NSMutableString stringWithFormat: @"Duration %g for statement %@;", d, statement]; [m appendFormat: @" affected %"PRIdPTR" record%s", result, ((1 == result) ? "" : "s")]; } debug = m; } } if (_inTransaction == NO) { [_statements removeAllObjects]; _committed++; } } NS_HANDLER { result = -1; if (NO == _inTransaction) { [_statements removeAllObjects]; if ([[localException name] isEqual: SQLConnectionException]) { /* A connection failure while not in a transaction ... * we can and should retry. */ done = NO; if (nil != debug) { NSLog(@"Will retry after: %@", localException); } [self connect]; } } if (done) { [lock unlock]; [localException raise]; } } NS_ENDHANDLER } [lock unlock]; if (nil != debug) { [self debug: @"%@", debug]; } return result; } - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt { return [self simpleQuery: stmt recordType: rClass listType: aClass]; } - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype { NSMutableArray *result = nil; NSString *debug = nil; BOOL done = NO; if (rtype == 0) rtype = rClass; if (ltype == 0) ltype = aClass; [lock lock]; if ([self connect] == NO) { [lock unlock]; [NSException raise: SQLConnectionException format: @"Unable to connect to '%@' to run query %@", [self name], stmt]; } while (NO == done) { done = YES; NS_DURING { _lastStart = GSTickerTimeNow(); result = [self backendQuery: stmt recordType: rtype listType: ltype]; _lastOperation = GSTickerTimeNow(); if (_duration >= 0) { NSTimeInterval d; d = _lastOperation - _lastStart; if (d >= _duration) { NSUInteger count = [result count]; debug = [NSString stringWithFormat: @"Duration %g for query %@; produced %"PRIuPTR" record%s", d, stmt, count, ((1 == count) ? "" : "s")]; } } if (_inTransaction == NO) { _committed++; } } NS_HANDLER { if (NO == _inTransaction) { if ([[localException name] isEqual: SQLConnectionException]) { /* A connection failure while not in a transaction ... * we can and should retry. */ done = NO; if (nil != debug) { NSLog(@"Will retry after: %@", localException); } [self connect]; } } if (done) { [lock unlock]; [localException raise]; } } NS_ENDHANDLER } [lock unlock]; if (nil != debug) { [self debug: @"%@", debug]; } return result; } - (BOOL) tryConnect { if (NO == connected) { [lock lock]; if (NO == connected) { NS_DURING { NSTimeInterval _lastListen = 0.0; if (_connectFails > 1) { NSTimeInterval delay; NSTimeInterval elapsed; /* If we have repeated connection failures, we enforce a * delay of up to 30 seconds between connection attempts * to avoid overloading the system with too frequent * connection attempts. */ delay = (_connectFails < 30) ? _connectFails : 30; elapsed = GSTickerTimeNow() - _lastOperation; if (elapsed < delay) { [NSThread sleepForTimeInterval: delay - elapsed]; } } _lastStart = GSTickerTimeNow(); if (YES == [self backendConnect]) { /* On establishing a new connection, we must restore any * listen instructions in the backend. */ if (nil != _names) { NSEnumerator *e; NSString *n; _lastListen = GSTickerTimeNow(); e = [_names objectEnumerator]; while (nil != (n = [e nextObject])) { [self backendListen: [self quoteName: n]]; } } _lastConnect = GSTickerTimeNow(); _connectFails = 0; } else { _lastOperation = GSTickerTimeNow(); _connectFails++; } if (_duration >= 0) { NSTimeInterval d; NSString *s; if (0 == _connectFails) { s = @"success"; d = _lastConnect - _lastStart; } else { s = @"failure"; d = _lastOperation - _lastStart; } if (d >= _duration) { if (_lastListen > 0.0) { [self debug: @"Duration %g for connection (%@)" @", of which %g adding observers.", d, s, _lastOperation - _lastListen]; } else { [self debug: @"Duration %g for connection (%@).", d, s]; } } } } NS_HANDLER { _lastOperation = GSTickerTimeNow(); _connectFails++; [lock unlock]; [localException raise]; } NS_ENDHANDLER } [lock unlock]; if (YES == connected) { NSNotificationCenter *nc; nc = [NSNotificationCenter defaultCenter]; [nc postNotificationName: SQLClientDidConnectNotification object: self]; } } return connected; } - (void) unlock { [lock unlock]; } - (NSString*) user { return _user; } @end @implementation SQLClient (Subclass) - (BOOL) backendConnect { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle loaded", NSStringFromSelector(_cmd)]; return NO; } - (void) backendDisconnect { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle loaded", NSStringFromSelector(_cmd)]; } - (NSInteger) backendExecute: (NSArray*)info { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle loaded", NSStringFromSelector(_cmd)]; return -1; } - (void) backendListen: (NSString*)name { return; } - (void) backendNotify: (NSString*)name payload: (NSString*)more { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle implementation", NSStringFromSelector(_cmd)]; return; } - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle loaded", NSStringFromSelector(_cmd)]; return nil; } - (void) backendUnlisten: (NSString*)name { return; } - (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle loaded", NSStringFromSelector(_cmd)]; return 0; } - (const void*) insertBLOBs: (NSArray*)blobs intoStatement: (const void*)statement length: (unsigned)sLength withMarker: (const void*)marker length: (unsigned)mLength giving: (unsigned*)result { unsigned count = [blobs count]; unsigned length = sLength; if (count > 1) { unsigned i; unsigned char *buf; unsigned char *ptr; const unsigned char *from = (const unsigned char*)statement; /* * Calculate length of buffer needed. */ for (i = 1; i < count; i++) { length += [self lengthOfEscapedBLOB: [blobs objectAtIndex: i]]; length -= mLength; } buf = NSZoneMalloc(NSDefaultMallocZone(), length + 1); [NSData dataWithBytesNoCopy: buf length: length + 1]; // autoreleased ptr = buf; /* * Merge quoted data objects into statement. */ i = 1; from = (unsigned char*)statement; while (*from != 0) { if (*from == *(unsigned char*)marker && memcmp(from, marker, mLength) == 0) { NSData *d = [blobs objectAtIndex: i++]; from += mLength; ptr += [self copyEscapedBLOB: d into: ptr]; } else { *ptr++ = *from++; } } *ptr = '\0'; statement = buf; } *result = length; return statement; } - (unsigned) lengthOfEscapedBLOB: (NSData*)blob { [NSException raise: NSInternalInconsistencyException format: @"Called -%@ without backend bundle loaded", NSStringFromSelector(_cmd)]; return 0; } @end @implementation SQLClient (Private) - (void) _configure: (NSNotification*)n { NSDictionary *o; NSDictionary *d; NSString *s; Class c; [lock lock]; NS_DURING { o = [n object]; /* * get dictionary containing config info for this client by name. */ d = [o objectForKey: @"SQLClientReferences"]; if ([d isKindOfClass: [NSDictionary class]] == NO) { [self debug: @"Unable to find SQLClientReferences config dictionary"]; d = nil; } d = [d objectForKey: _name]; if ([d isKindOfClass: [NSDictionary class]] == NO) { [self debug: @"Unable to find config for client '%@'", _name]; d = nil; } s = [d objectForKey: @"ServerType"]; if ([s isKindOfClass: NSStringClass] == NO) { s = @"Postgres"; } c = NSClassFromString([@"SQLClient" stringByAppendingString: s]); if (c == nil) { NSString *path; NSBundle *bundle; NSArray *paths; NSMutableArray *tried; unsigned count; paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask, YES); count = [paths count]; tried = [NSMutableArray arrayWithCapacity: count]; while (count-- > 0) { path = [paths objectAtIndex: count]; path = [path stringByAppendingPathComponent: @"Bundles"]; path = [path stringByAppendingPathComponent: @"SQLClient"SOVERSION""]; path = [path stringByAppendingPathComponent: s]; path = [path stringByAppendingPathExtension: @"bundle"]; bundle = [NSBundle bundleWithPath: path]; if (bundle != nil) { [tried addObject: path]; if ((c = [bundle principalClass]) != nil) { break; // Found it. } } /* Try alternative version with more libraries linked in. * In some systems and situations the dynamic linker needs * to haved the SQLClient, gnustep-base, and objc libraries * explicitly linked into the bundle, but in others it * requires them to not be linked. To handle that, we create * two versions of each bundle, the seond version has _libs * appended to the bundle name, and has the extra libraries * linked. */ path = [path stringByDeletingPathExtension]; path = [path stringByAppendingString: @"_libs"]; path = [path stringByAppendingPathExtension: @"bundle"]; bundle = [NSBundle bundleWithPath: path]; if (bundle != nil) { [tried addObject: path]; if ((c = [bundle principalClass]) != nil) { break; // Found it. } } } if (c == nil) { if ([tried count] == 0) { [self debug: @"unable to load bundle for '%@' server type" @" ... failed to locate bundle in %@", s, paths]; } else { [self debug: @"unable to load backend class for '%@' server" @" type ... dynamic library load failed in %@", s, tried]; } [lock unlock]; NS_VOIDRETURN; } } if (c != [self class]) { if (YES == connected) { [self disconnect]; } #ifdef GNUSTEP GSDebugAllocationRemove(object_getClass(self), self); #endif object_setClass(self, c); #ifdef GNUSTEP GSDebugAllocationAdd(object_getClass(self), self); #endif } s = [d objectForKey: @"Database"]; if ([s isKindOfClass: NSStringClass] == NO) { s = [o objectForKey: @"Database"]; if ([s isKindOfClass: NSStringClass] == NO) { s = nil; } } [self setDatabase: s]; s = [d objectForKey: @"User"]; if ([s isKindOfClass: NSStringClass] == NO) { s = [o objectForKey: @"User"]; if ([s isKindOfClass: NSStringClass] == NO) { s = @""; } } [self setUser: s]; s = [d objectForKey: @"Password"]; if ([s isKindOfClass: NSStringClass] == NO) { s = [o objectForKey: @"Password"]; if ([s isKindOfClass: NSStringClass] == NO) { s = @""; } } [self setPassword: s]; if (nil == d && [o isKindOfClass: [NSDictionary class]]) { d = (NSDictionary*)o; } [self setOptions: d]; } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (NSRecursiveLock*) _lock { return lock; } - (void) _populateCache: (CacheQuery*)a { GSCache *cache; id result; result = [self simpleQuery: a->query recordType: a->recordType listType: a->listType]; cache = [self cache]; [cache setObject: result forKey: a->query lifetime: a->lifetime]; } - (void) _recordMainThread { mainThread = [NSThread currentThread]; } + (void) _tick: (NSTimer*)t { (void) GSTickerTimeNow(); } @end @implementation SQLClient (GSCacheDelegate) - (BOOL) shouldKeepItem: (id)anObject withKey: (id)aKey lifetime: (unsigned)lifetime after: (unsigned)delay { CacheQuery *a; NSDictionary *d; a = [CacheQuery new]; aKey = [aKey copy]; [a->query release]; a->query = aKey; d = [[NSThread currentThread] threadDictionary]; a->recordType = [d objectForKey: @"SQLClientRecordType"]; a->listType = [d objectForKey: @"SQLClientListType"]; a->lifetime = lifetime; [a autorelease]; if (_cacheThread == nil) { [self _populateCache: a]; } else { /* We schedule an asynchronous update if the item is not too old, * otherwise (more than lifetime seconds past its expiry) we wait * for the update to complete. */ [self performSelectorOnMainThread: @selector(_populateCache:) withObject: a waitUntilDone: (delay > lifetime) ? YES : NO modes: queryModes]; } return YES; // Always keep items ... } @end @implementation SQLClient(Convenience) + (NSMutableArray*) columns: (NSMutableArray*)records { SQLRecord *r = [records lastObject]; unsigned rowCount = [records count]; unsigned colCount = [r count]; NSMutableArray *m; if (rowCount == 0 || colCount == 0) { m = [NSMutableArray array]; } else { NSMutableArray *cols[colCount]; unsigned i; m = [NSMutableArray arrayWithCapacity: colCount]; for (i = 0; i < colCount; i++) { cols[i] = [[NSMutableArray alloc] initWithCapacity: rowCount]; [m addObject: cols[i]]; [cols[i] release]; } for (i = 0; i < rowCount; i++) { unsigned j; r = [records objectAtIndex: i]; for (j = 0; j < colCount; j++) { [cols[j] addObject: [r objectAtIndex: j]]; } } } return m; } + (void) singletons: (NSMutableArray*)records { unsigned c = [records count]; while (c-- > 0) { [records replaceObjectAtIndex: c withObject: [[records objectAtIndex: c] lastObject]]; } } - (SQLTransaction*) batch: (BOOL)stopOnFailure { return [SQLTransaction _transactionUsing: self batch: YES stop: stopOnFailure]; } - (NSMutableArray*) columns: (NSMutableArray*)records { return [SQLClient columns: records]; } - (SQLRecord*) queryRecord: (NSString*)stmt, ... { va_list ap; NSArray *result = nil; SQLRecord *record; SQLLiteral *query; va_start (ap, stmt); query = [[self prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); result = [self simpleQuery: query]; if ([result count] > 1) { [NSException raise: NSInvalidArgumentException format: @"Query returns more than one record -\n%@\n", query]; } record = [result lastObject]; if (record == nil) { [NSException raise: SQLEmptyException format: @"Query returns no data -\n%@\n", query]; } return record; } - (NSString*) queryString: (NSString*)stmt, ... { va_list ap; NSArray *result = nil; SQLRecord *record; SQLLiteral *query; va_start (ap, stmt); query = [[self prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); result = [self simpleQuery: query]; if ([result count] > 1) { [NSException raise: NSInvalidArgumentException format: @"Query returns more than one record -\n%@\n", query]; } record = [result lastObject]; if (record == nil) { [NSException raise: SQLEmptyException format: @"Query returns no data -\n%@\n", query]; } if ([record count] > 1) { [NSException raise: NSInvalidArgumentException format: @"Query returns multiple fields -\n%@\n", query]; } return [[record lastObject] description]; } - (void) singletons: (NSMutableArray*)records { [SQLClient singletons: records]; } - (SQLTransaction*) transaction { return [SQLTransaction _transactionUsing: self batch: NO stop: NO]; } @end @interface SQLClientCacheInfo : NSObject { @public NSString *query; NSMutableArray *result; NSTimeInterval expires; } @end @implementation SQLClientCacheInfo - (void) dealloc { [query release]; query = nil; [result release]; result = nil; [super dealloc]; } - (NSUInteger) hash { return [query hash]; } - (BOOL) isEqual: (id)other { return [query isEqual: ((SQLClientCacheInfo*)other)->query]; } @end @implementation SQLClient (Caching) - (GSCache*) cache { GSCache *c; /* NB we use a different lock to protect the cache from the lock * used to protect the database query. That allows multiple * connections (a connection pool) to share the same cache. */ [cacheLock lock]; if (nil == _cache) { _cache = [GSCache new]; [_cache setName: [self clientName]]; if (_cacheThread != nil) { [_cache setDelegate: self]; } } c = [_cache retain]; [cacheLock unlock]; return [c autorelease]; } - (NSMutableArray*) cacheCheckSimpleQuery: (NSString*)stmt { NSMutableArray *result = [[self cache] objectForKey: stmt]; if (result != nil) { result = [[result mutableCopy] autorelease]; } return result; } - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt,... { va_list ap; SQLLiteral *query; va_start (ap, stmt); query = [[self prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); return [self cache: seconds simpleQuery: query]; } - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt with: (NSDictionary*)values { SQLLiteral *query; query = [[self prepare: stmt with: values] objectAtIndex: 0]; return [self cache: seconds simpleQuery: query]; } - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt { return [self cache: seconds simpleQuery: stmt recordType: nil listType: nil]; } - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype { NSMutableArray *result; NSMutableDictionary *md; GSCache *c; id toCache; BOOL cacheHit; if (rtype == 0) rtype = rClass; if (ltype == 0) ltype = aClass; md = [[NSThread currentThread] threadDictionary]; [md setObject: rtype forKey: @"SQLClientRecordType"]; [md setObject: ltype forKey: @"SQLClientListType"]; _lastStart = GSTickerTimeNow(); c = [self cache]; toCache = nil; if (seconds < 0) { seconds = -seconds; result = nil; } else { result = [c objectForKey: stmt]; } if (result == nil) { CacheQuery *a; cacheHit = NO; a = [CacheQuery new]; a->query = [stmt copy]; a->recordType = rtype; a->listType = ltype; a->lifetime = seconds; [a autorelease]; if (_cacheThread == nil) { [self _populateCache: a]; } else { /* Not really an asynchronous query because we wait until it's * done in order to have a result we can return. */ [self performSelectorOnMainThread: @selector(_populateCache:) withObject: a waitUntilDone: YES modes: queryModes]; } result = [c objectForKey: stmt]; } else { cacheHit = YES; } if (seconds == 0) { // We have been told to remove the existing cached item. [c setObject: nil forKey: stmt lifetime: seconds]; toCache = nil; } if (toCache != nil) { // We have a newly retrieved object ... cache it. [c setObject: toCache forKey: stmt lifetime: seconds]; } if (result != nil) { /* * Return an autoreleased copy ... not the original cached data. */ result = [[result mutableCopy] autorelease]; } _lastOperation = GSTickerTimeNow(); if (_duration >= 0) { NSTimeInterval d; d = _lastOperation - _lastStart; if (d >= _duration) { [self debug: @"Duration %g for cache-%@ query %@", d, (YES == cacheHit) ? @"hit" : @"miss", stmt]; } } return result; } - (void) setCache: (GSCache*)aCache { /* NB we use a different lock to protect the cache from the lock * used to protect the database query. That allows multiple * connections (a connection pool) to share the same cache. */ [cacheLock lock]; NS_DURING { if (_cacheThread != nil) { [_cache setDelegate: nil]; } [aCache retain]; [_cache release]; _cache = aCache; if (_cacheThread != nil) { [_cache setDelegate: self]; } } NS_HANDLER { [cacheLock unlock]; [localException raise]; } NS_ENDHANDLER [cacheLock unlock]; } - (void) setCacheThread: (NSThread*)aThread { if (mainThread == nil) { [self performSelectorOnMainThread: @selector(_recordMainThread) withObject: nil waitUntilDone: NO modes: queryModes]; } if (aThread != nil && aThread != mainThread) { NSLog(@"SQLClient: only the main thread is usable as cache thread"); aThread = mainThread; } [lock lock]; NS_DURING { if (_cacheThread != nil) { [_cache setDelegate: nil]; } [aThread retain]; [_cacheThread release]; _cacheThread = aThread; if (_cacheThread != nil) { [_cache setDelegate: self]; } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } @end @implementation SQLTransaction + (SQLTransaction*) _transactionUsing: (id)clientOrPool batch: (BOOL)isBatched stop: (BOOL)stopOnFailure { SQLTransaction *transaction; transaction = (SQLTransaction*)NSAllocateObject(self, 0, NSDefaultMallocZone()); transaction->_owner = [clientOrPool retain]; transaction->_info = [NSMutableArray new]; transaction->_batch = isBatched; transaction->_stop = stopOnFailure; transaction->_lock = [NSRecursiveLock new]; return [transaction autorelease]; } - (void) _addSQL: (NSMutableString*)sql andArgs: (NSMutableArray*)args { unsigned count = [_info count]; unsigned index; for (index = 0; index < count; index++) { id o = [_info objectAtIndex: index]; if ([o isKindOfClass: NSArrayClass] == YES) { unsigned c = [(NSArray*)o count]; if (c > 0) { unsigned i; [sql appendString: [(NSArray*)o objectAtIndex: 0]]; [sql appendString: @";"]; for (i = 1; i < c; i++) { [args addObject: [(NSArray*)o objectAtIndex: i]]; } } } else { [(SQLTransaction*)o _addSQL: sql andArgs: args]; } } } - (void) addPrepared: (NSArray*)statement { [_lock lock]; [_info addObject: statement]; _count++; [_lock unlock]; } - (void) _countLength: (unsigned*)length andArgs: (unsigned*)args { unsigned count = [_info count]; unsigned index; for (index = 0; index < count; index++) { id o = [_info objectAtIndex: index]; if ([o isKindOfClass: NSArrayClass] == YES) { unsigned c = [(NSArray*)o count]; if (c > 0) { length += [[(NSArray*)o objectAtIndex: 0] length] + 1; args += c - 1; } } else { [(SQLTransaction*)o _countLength: length andArgs: args]; } } } - (void) add: (NSString*)stmt,... { va_list ap; NSMutableArray *p; va_start (ap, stmt); p = [_owner prepare: stmt args: ap]; va_end (ap); [self addPrepared: p]; } - (void) add: (NSString*)stmt with: (NSDictionary*)values { NSMutableArray *p; p = [_owner prepare: stmt with: values]; [self addPrepared: p]; } - (void) append: (SQLTransaction*)other { if (nil == other) { return; } NSAssert(other != self, NSInvalidArgumentException); NSAssert([other isKindOfClass: [SQLTransaction class]], NSInvalidArgumentException); [other lock]; [_lock lock]; NS_DURING { if (other->_count > 0) { SQLTransaction *t; /* Owners must the the same client, or the same pool, or members * of the same pool or a client and the pool it belongs to. */ if (NO == [_owner isEqual: other->_owner] && NO == [[_owner pool] isEqual: [other->_owner pool]]) { [NSException raise: NSInvalidArgumentException format: @"[%@-%@] database owner mismatch", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } t = [other copy]; [_info addObject: t]; _count += t->_count; [t release]; } } NS_HANDLER { [_lock unlock]; [other unlock]; [localException raise]; } NS_ENDHANDLER [_lock unlock]; [other unlock]; } - (id) copyWithZone: (NSZone*)z { SQLTransaction *c; [_lock lock]; c = (SQLTransaction*)NSCopyObject(self, 0, z); c->_owner = [c->_owner retain]; c->_info = [c->_info mutableCopy]; c->_lock = [NSRecursiveLock new]; [_lock unlock]; return c; } - (NSUInteger) count { NSUInteger count; [_lock lock]; count = [_info count]; [_lock unlock]; return count; } - (id) db { return _owner; } - (void) dealloc { [_owner release]; _owner = nil; [_info release]; _info = nil; [_lock release]; _lock = nil; [super dealloc]; } - (NSString*) description { NSString *str; [_lock lock]; str = [NSString stringWithFormat: @"%@ with SQL '%@' for %@", [super description], (_count == 0 ? (id)@"" : (id)_info), _owner]; [_lock unlock]; return str; } - (void) execute { [_lock lock]; if (_count > 0) { NS_DURING { NSMutableArray *info = nil; SQLClientPool *pool = nil; SQLClient *db; NSRecursiveLock *dbLock; BOOL wrap; if ([_owner isKindOfClass: [SQLClientPool class]]) { pool = (SQLClientPool*)_owner; db = [pool provideClient]; } else { db = _owner; } dbLock = [db _lock]; [dbLock lock]; wrap = [db isInTransaction] ? NO : YES; NS_DURING { NSMutableString *sql; unsigned sqlSize = 0; unsigned argCount = 0; [self _countLength: &sqlSize andArgs: &argCount]; /* Allocate and initialise the transaction statement. */ info = [[NSMutableArray alloc] initWithCapacity: argCount + 1]; sql = [[NSMutableString alloc] initWithCapacity: sqlSize + 13]; [info addObject: SQLClientProxyLiteral(sql)]; [sql release]; if (YES == wrap) { [sql appendString: @"begin;"]; } [self _addSQL: sql andArgs: info]; if (YES == wrap) { [sql appendString: @"commit;"]; } [db simpleExecute: info]; [info release]; info = nil; [dbLock unlock]; if (nil != pool) { [pool swallowClient: db]; } } NS_HANDLER { NSException *e = localException; [info release]; if (YES == wrap && NO == [[e name] isEqual: SQLConnectionException]) { NS_DURING { [db simpleExecute: rollbackStatement]; } NS_HANDLER { [db disconnect]; NSLog(@"Disconnected due to failed rollback after %@", e); } NS_ENDHANDLER } [dbLock unlock]; if (nil != pool) { [pool swallowClient: db]; } [e raise]; } NS_ENDHANDLER } NS_HANDLER { [_lock unlock]; [localException raise]; } NS_ENDHANDLER if (YES == _reset) { [self reset]; } } [_lock unlock]; } - (unsigned) executeBatch { return [self executeBatchReturningFailures: nil logExceptions: NO]; } - (unsigned) executeBatchReturningFailures: (SQLTransaction*)failures logExceptions: (BOOL)log { unsigned executed = 0; [_lock lock]; if (_count > 0) { NS_DURING { NSRecursiveLock *dbLock; SQLClientPool *pool = nil; SQLClient *db; if ([_owner isKindOfClass: [SQLClientPool class]]) { pool = (SQLClientPool*)_owner; db = [pool provideClient]; } else { db = _owner; } dbLock = [db _lock]; [dbLock lock]; NS_DURING { [self execute]; executed = _count; } NS_HANDLER { if (log == YES || [db debugging] > 0) { [db debug: @"Initial failure executing batch %@: %@", self, localException]; } if (_batch == YES) { SQLTransaction *wrapper = nil; NSUInteger count = [_info count]; NSUInteger i; for (i = 0; i < count; i++) { BOOL success = NO; id o = [_info objectAtIndex: i]; if ([o isKindOfClass: NSArrayClass] == YES) { NS_DURING { /* Wrap the statement inside a transaction so * its context will still be that of a statement * in a transaction rather than a standalone * statement. This might be important if the * statement is actually a call to a stored * procedure whose code must all be executed * with the visibility rules of a single * transaction. */ if (wrapper == nil) { wrapper = [db transaction]; } [wrapper reset]; [wrapper addPrepared: o]; [wrapper execute]; executed++; success = YES; } NS_HANDLER { if (failures != nil) { [failures addPrepared: o]; } if (log == YES || [db debugging] > 0) { [db debug: @"Failure of %d executing batch %@: %@", i, self, localException]; } success = NO; } NS_ENDHANDLER } else { unsigned result; result = [(SQLTransaction*)o executeBatchReturningFailures: failures logExceptions: log]; executed += result; if (result == [(SQLTransaction*)o totalCount]) { success = YES; } } if (success == NO && _stop == YES) { /* We are configured to stop after a failure, * so we need to add all the subsequent statements * or transactions to the list of those which have * not been done. */ i++; while (i < count) { id o = [_info objectAtIndex: i++]; if ([o isKindOfClass: NSArrayClass] == YES) { [failures addPrepared: o]; } else { [failures append: (SQLTransaction*)o]; } } break; } } } } NS_ENDHANDLER [dbLock unlock]; if (nil != pool) { [pool swallowClient: db]; } } NS_HANDLER { [_lock unlock]; [localException raise]; } NS_ENDHANDLER if (YES == _reset) { [self reset]; } } [_lock unlock]; return executed; } - (void) insertTransaction: (SQLTransaction*)trn atIndex: (unsigned)index { [_lock lock]; if (index > [_info count]) { [_lock unlock]; [NSException raise: NSRangeException format: @"[%@-%@] index too large", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if (trn == nil || trn->_count == 0) { [_lock unlock]; [NSException raise: NSInvalidArgumentException format: @"[%@-%@] attempt to insert nil/empty transaction", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if (NO == [_owner isEqual: trn->_owner] && NO == [[_owner pool] isEqual: [trn->_owner pool]]) { [_lock unlock]; [NSException raise: NSInvalidArgumentException format: @"[%@-%@] database owner mismatch", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } trn = [trn copy]; [_info insertObject: trn atIndex: index]; _count += trn->_count; [trn release]; [_lock unlock]; } - (void) lock { [_lock lock]; } - (id) owner { return _owner; } - (void) removeTransactionAtIndex: (unsigned)index { id o; [_lock lock]; if (index >= [_info count]) { [_lock unlock]; [NSException raise: NSRangeException format: @"[%@-%@] index too large", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } o = [_info objectAtIndex: index]; if ([o isKindOfClass: NSArrayClass] == YES) { _count--; } else { _count -= [(SQLTransaction*)o totalCount]; } [_info removeObjectAtIndex: index]; [_lock unlock]; } - (void) reset { [_lock lock]; [_info removeAllObjects]; _count = 0; [_lock unlock]; } - (BOOL) setResetOnExecute: (BOOL)aFlag { BOOL old; [_lock lock]; old = _reset; _reset = (aFlag ? YES : NO); [_lock unlock]; return old; } - (unsigned) totalCount { return _count; } - (SQLTransaction*) transactionAtIndex: (unsigned)index { id o; [_lock lock]; if (index >= [_info count]) { [_lock unlock]; [NSException raise: NSRangeException format: @"[%@-%@] index too large", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } o = [_info objectAtIndex: index]; if ([o isKindOfClass: NSArrayClass] == YES) { SQLTransaction *t = [[self owner] transaction]; [t addPrepared: o]; [_lock unlock]; return t; } else { o = [o copy]; [_lock unlock]; return [o autorelease]; } } - (void) unlock { [_lock unlock]; } @end @implementation SQLClient (Notifications) static NSString * validName(NSString *name) { const char *ptr; if (NO == [name isKindOfClass: [NSString class]]) { [NSException raise: NSInvalidArgumentException format: @"Notification name must be a string"]; } ptr = [name UTF8String]; if (!isalpha(*ptr)) { [NSException raise: NSInvalidArgumentException format: @"Notification name must begin with letter"]; } ptr++; while (0 != *ptr) { if (!isdigit(*ptr) && !isalpha(*ptr) && *ptr != '_') { [NSException raise: NSInvalidArgumentException format: @"Notification name must contain only letters," @" digits, and underscores"]; } ptr++; } return name; } - (void) addObserver: (id)anObserver selector: (SEL)aSelector name: (NSString*)name { if (nil == anObserver) { [NSException raise: NSInvalidArgumentException format: @"Attempt to add nil observer to SQL client"]; } if (nil != _pool) { [NSException raise: NSInvalidArgumentException format: @"Attempt to use pool client as observer"]; } name = validName(name); [lock lock]; NS_DURING { NSMutableSet *set; if (nil == _observers) { _observers = NSCreateMapTable(NSNonRetainedObjectMapKeyCallBacks, NSObjectMapValueCallBacks, 0); _names = [NSCountedSet new]; } set = (NSMutableSet*)NSMapGet(_observers, (void*)anObserver); if (nil == set) { set = [NSMutableSet new]; NSMapInsert(_observers, anObserver, set); [set release]; } if (nil == [set member: name]) { [set addObject: name]; [[NSNotificationCenter defaultCenter] addObserver: anObserver selector: aSelector name: name object: self]; [_names addObject: name]; if (YES == connected && 1 == [_names countForObject: name]) { [self backendListen: [self quoteName: name]]; } } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (void) postNotificationName: (NSString*)name payload: (NSString*)more { name = validName(name); if (nil != more) { if (NO == [more isKindOfClass: [NSString class]]) { [NSException raise: NSInvalidArgumentException format: @"Notification payload is not a string"]; } } [lock lock]; if ([self connect] == NO) { [lock unlock]; [NSException raise: SQLConnectionException format: @"Unable to connect to '%@' to notify %@ with %@", [self name], name, more]; } NS_DURING { [self backendNotify: [self quoteName: name] payload: more]; } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } - (void) removeObserver: (id)anObserver name: (NSString*)name { if (nil != name) { name = validName(name); } [lock lock]; NS_DURING { if (_observers != nil) { NSNotificationCenter *nc; NSEnumerator *oe = nil; nc = [NSNotificationCenter defaultCenter]; if (nil == anObserver) { oe = [NSAllMapTableKeys(_observers) objectEnumerator]; anObserver = [oe nextObject]; } while (anObserver != nil) { NSMutableSet *set; NSEnumerator *nameEnumerator = nil; set = (NSMutableSet*)NSMapGet(_observers, (void*)anObserver); if (nil == name) { /* Remove all names for this observer. */ nameEnumerator = [[set allObjects] objectEnumerator]; } else { nameEnumerator = [[NSArray arrayWithObject: name] objectEnumerator]; } while (nil != (name = [nameEnumerator nextObject])) { if (nil != [set member: name]) { [[name retain] autorelease]; [set removeObject: name]; [nc removeObserver: anObserver name: name object: self]; [_names removeObject: name]; if (YES == connected && 0 == [_names countForObject: name]) { [self backendUnlisten: [self quoteName: name]]; } } } if ([set count] == 0) { NSMapRemove(_observers, (void*)anObserver); } anObserver = [oe nextObject]; } } } NS_HANDLER { [lock unlock]; [localException raise]; } NS_ENDHANDLER [lock unlock]; } @end @implementation SQLDictionaryBuilder - (void) addObject: (id)anObject { return; } - (id) alloc { return [self retain]; } - (NSMutableDictionary*) content { return content; } - (NSUInteger) count { return [content count]; } - (void) dealloc { [content release]; [super dealloc]; } - (id) initWithCapacity: (NSUInteger)capacity { if (nil != (self = [super init])) { DESTROY(content); content = [[NSMutableDictionary alloc] initWithCapacity: capacity]; } return self; } - (id) mutableCopyWithZone: (NSZone*)aZone { return [content mutableCopyWithZone: aZone]; } - (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count { if (count != 2) { [NSException raise: NSInvalidArgumentException format: @"Query did not return key/value pairs"]; } [content setObject: values[1] forKey: values[0]]; return nil; } @end @implementation SQLSetBuilder - (NSUInteger) added { return added; } - (void) addObject: (id)anObject { return; } - (id) alloc { return [self retain]; } - (NSCountedSet*) content { return content; } - (NSUInteger) count { return [content count]; } - (void) dealloc { [content release]; [super dealloc]; } - (id) initWithCapacity: (NSUInteger)capacity { if (nil != (self = [super init])) { DESTROY(content); content = [[NSCountedSet alloc] initWithCapacity: capacity]; added = 0; } return self; } - (id) mutableCopyWithZone: (NSZone*)aZone { return [content mutableCopyWithZone: aZone]; } - (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count { if (count != 1) { [NSException raise: NSInvalidArgumentException format: @"Query did not return a single value"]; } added++; [content addObject: values[0]]; return nil; } @end @implementation SQLSingletonBuilder - (id) newWithValues: (id*)values keys: (NSString**)keys count: (unsigned int)count { /* Instead of creating an object to hold the supplied record, * we use the field from the record as the value to be used. */ if (count != 1) { [NSException raise: NSInvalidArgumentException format: @"Query did not return singleton values"]; } return [values[0] retain]; } @end @implementation SQLClientPool (Adjust) + (void) _adjustPoolConnections: (int)n { unsigned err = 0; [clientsLock lock]; poolConnections += n; if (poolConnections < 0) { err -= poolConnections; poolConnections = 0; } [clientsLock unlock]; NSAssert(0 == err, NSInvalidArgumentException); } @end @implementation NSObject (SQLClient) - (BOOL) isNull { if (nil == null) { null = [NSNull new]; } return (self == null ? YES : NO); } - (SQLLiteral*) quoteBigInteger { int64_t v = (int64_t)[[self description] longLongValue]; return quoteBigInteger(v); } - (SQLLiteral*) quoteBigNatural { int64_t v = (int64_t)[[self description] longLongValue]; if (v < 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a natural number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quoteBigPositive { int64_t v = (int64_t)[[self description] longLongValue]; if (v <= 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a positive number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quoteBoolean { return (SQLLiteral*)([[self description] boolValue] ? @"true" : @"false"); } - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db { return nil; } - (SQLLiteral*) quoteInteger { int64_t v = (int64_t)[[self description] longLongValue]; if (v > (int64_t)2147483647LL || v < (int64_t)-2147483648LL) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a 32bit number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quoteNatural { int64_t v = (int64_t)[[self description] longLongValue]; if (v > (int64_t)2147483647LL || v < (int64_t)-2147483648LL) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a 32bit number", self]; } if (v < 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a natural number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quotePositive { int64_t v = (int64_t)[[self description] longLongValue]; if (v > (int64_t)2147483647LL || v < (int64_t)-2147483648LL) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a 32bit number", self]; } if (v <= 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a positive number", self]; } return quoteBigInteger(v); } @end @implementation SQLClient (Quote) + (BOOL) autoquote { return autoquote; } + (BOOL) autoquoteWarning { return autoquoteWarning; } + (void) setAutoquote: (BOOL)aFlag { autoquote = (aFlag ? YES : NO); } + (void) setAutoquoteWarning: (BOOL)aFlag { autoquoteWarning = (aFlag ? YES : NO); } @end @implementation NSArray (Quote) - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db { return [db quoteSet: self]; } @end @implementation NSDate (Quote) - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db { return SQLClientMakeLiteral([self descriptionWithCalendarFormat: @"'%Y-%m-%d %H:%M:%S.%F %z'" timeZone: nil locale: nil]); } @end @implementation NSNull (Quote) - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db { return (SQLLiteral*)@"NULL"; } @end @implementation NSNumber (Quote) - (SQLLiteral*) quoteBigInteger { int64_t v = (int64_t)[self longLongValue]; return quoteBigInteger(v); } - (SQLLiteral*) quoteBigNatural { int64_t v = (int64_t)[self longLongValue]; if (v < 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a natural number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quoteBigPositive { int64_t v = (int64_t)[self longLongValue]; if (v <= 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a positive number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db { return SQLClientMakeLiteral([self description]); } - (SQLLiteral*) quoteInteger { int64_t v = (int64_t)[self longLongValue]; if (v > (int64_t)2147483647LL || v < (int64_t)-2147483648LL) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a 32bit number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quoteNatural { int64_t v = (int64_t)[self longLongValue]; if (v > (int64_t)2147483647LL || v < (int64_t)-2147483648LL) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a 32bit number", self]; } if (v < 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a natural number", self]; } return quoteBigInteger(v); } - (SQLLiteral*) quotePositive { int64_t v = (int64_t)[self longLongValue]; if (v > (int64_t)2147483647LL || v < (int64_t)-2147483648LL) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a 32bit number", self]; } if (v <= 0) { [NSException raise: NSInternalInconsistencyException format: @"Object (%@) is not a positive number", self]; } return quoteBigInteger(v); } @end @implementation NSSet (Quote) - (SQLLiteral*) quoteForSQLClient: (SQLClient*)db { return [db quoteSet: self]; } @end /* Count the number of bytes that make up this UTF-8 code point. * This to keep in mind: * This macro doesn't return anything larger than '4' * Legal UTF-8 cannot be larger than 4 bytes long (0x10FFFF) * It will return 0 for anything illegal */ #define UTF8_BYTE_COUNT(c) \ (((c) < 0xf8) ? 1 + ((c) >= 0xc0) + ((c) >= 0xe0) + ((c) >= 0xf0) : 0) /* Sequentially extracts characters from UTF-8 string * p = pointer to the utf-8 data * l = length (bytes) of the utf-8 data * o = pointer to current offset within the data * n = pointer to either zero or the next pre-read part of a surrogate pair. * The condition for having read the entire string is that the offset (*o) * is the number of bytes in the string, and the unichar pointed to by *n * is zero (meaning there is no second part of a surrogate pair remaining). */ static inline unichar nextUTF8(const uint8_t *p, unsigned l, unsigned *o, unichar *n) { unsigned i; /* If we still have the second part of a surrogate pair, return it. */ if (*n > 0) { unichar u = *n; *n = 0; return u; } if ((i = *o) < l) { uint8_t c = p[i]; uint32_t u = c; if (c > 0x7f) { int j, sle = 0; /* calculated the expected sequence length */ sle = UTF8_BYTE_COUNT(c); /* legal ? */ if (sle < 2) { [NSException raise: NSInvalidArgumentException format: @"bad multibyte character length"]; } if (sle + i > l) { [NSException raise: NSInvalidArgumentException format: @"multibyte character extends beyond data"]; } /* get the codepoint */ for (j = 1; j < sle; j++) { uint8_t b = p[i + j]; if (b < 0x80 || b >= 0xc0) break; u = (u << 6) | (b & 0x3f); } if (j < sle) { [NSException raise: NSInvalidArgumentException format: @"bad data in multibyte character"]; } u = u & ~(0xffffffff << ((5 * sle) + 1)); i += sle; /* * We discard invalid codepoints here. */ if (u > 0x10ffff) { [NSException raise: NSInvalidArgumentException format: @"invalid unicode codepoint"]; } } else { i++; } /* * Add codepoint as either a single unichar for BMP * or as a pair of surrogates for codepoints over 16 bits. */ if (u >= 0x10000) { unichar ul, uh; u -= 0x10000; ul = u & 0x3ff; uh = (u >> 10) & 0x3ff; *n = ul + 0xdc00; // record second part of pair u = uh + 0xd800; // return first part. } *o = i; // Return new index return (unichar)u; } [NSException raise: NSInvalidArgumentException format: @"no more data in UTF-8 string"]; return 0; } @implementation SQLString - (const char*) UTF8String { return (const char*)utf8Bytes; } - (unichar) characterAtIndex: (NSUInteger)index { NSUInteger l = 0; unichar u; unichar n = 0; unsigned i = 0; while (i < byteLen || n > 0) { u = nextUTF8(utf8Bytes, byteLen, &i, &n); if (l++ == index) { return u; } } [NSException raise: NSInvalidArgumentException format: @"-characterAtIndex: index out of range"]; return 0; } - (BOOL) canBeConvertedToEncoding: (NSStringEncoding)encoding { if (NSUTF8StringEncoding == encoding || NSUnicodeStringEncoding == encoding || (NSISOLatin1StringEncoding == encoding && YES == latin1) || (isByteCoding(encoding) && YES == ascii)) { return YES; } NS_DURING { id d = [self dataUsingEncoding: encoding allowLossyConversion: NO]; NS_VALRETURN(d != nil ? YES : NO); } NS_HANDLER { return NO; } NS_ENDHANDLER } - (NSData*) dataUsingEncoding: (NSStringEncoding)encoding allowLossyConversion: (BOOL)flag { if (0 == byteLen) { return [NSData data]; } if (NSUTF8StringEncoding == encoding || (YES == ascii && YES == isByteCoding(encoding))) { /* We can just copy the data unmodified */ return [NSData dataWithBytes: (void*)utf8Bytes length: byteLen]; } else if (YES == latin1 && NSISOLatin1StringEncoding == encoding) { unichar n = 0; unsigned i = 0; NSUInteger index = 0; uint8_t *buf = malloc(charLen); while (index < charLen && (i < byteLen || n > 0)) { buf[index++] = nextUTF8(utf8Bytes, byteLen, &i, &n); } return [NSData dataWithBytesNoCopy: buf length: charLen freeWhenDone: YES]; } else if (NSUnicodeStringEncoding == encoding) { unichar n = 0; unsigned i = 0; NSUInteger index = 0; unichar *buf = malloc(charLen * sizeof(unichar)); while (index < charLen && (i < byteLen || n > 0)) { buf[index++] = nextUTF8(utf8Bytes, byteLen, &i, &n); } return [NSData dataWithBytesNoCopy: buf length: charLen * sizeof(unichar) freeWhenDone: YES]; } return [super dataUsingEncoding: encoding allowLossyConversion: flag]; } - (void) getCharacters: (unichar*)buffer range: (NSRange)aRange { unichar n = 0; unsigned i = 0; NSUInteger max = NSMaxRange(aRange); NSUInteger index = 0; if (NSNotFound == aRange.location) [NSException raise: NSRangeException format: @"in %s, range { %"PRIuPTR", %"PRIuPTR" } extends beyond string", GSNameFromSelector(_cmd), aRange.location, aRange.length]; while (index < aRange.location && (i < byteLen || n > 0)) { nextUTF8(utf8Bytes, byteLen, &i, &n); index++; } if (index == aRange.location) { while (index < max && (i < byteLen || n > 0)) { *buffer++ = nextUTF8(utf8Bytes, byteLen, &i, &n); index++; } } if (index != max) { [NSException raise: NSRangeException format: @"in %s, range { %"PRIuPTR", %"PRIuPTR" } extends beyond string", GSNameFromSelector(_cmd), aRange.location, aRange.length]; } } - (BOOL) getCString: (char*)buffer maxLength: (NSUInteger)maxLength encoding: (NSStringEncoding)encoding { const uint8_t *ptr = utf8Bytes; int length = byteLen; int index; if (0 == maxLength || 0 == buffer) { return NO; // Can't fit in here } if (NSUTF8StringEncoding == encoding || (YES == ascii && isByteCoding(encoding))) { BOOL result = (length < maxLength) ? YES : NO; /* We can just copy directly. */ if (maxLength <= length) { length = maxLength - 1; } for (index = 0; index < length; index++) { buffer[index] = (char)ptr[index]; } /* Step back before any multibyte sequence */ while (index > 0 && (ptr[index - 1] & 0x80)) { index--; } buffer[index] = '\0'; return result; } return [super getCString: buffer maxLength: maxLength encoding: encoding]; } /* Must match the implementation in NSString * To avoid allocating memory, we build the hash incrementally. */ - (NSUInteger) hash { if (NO == hasHash) { hash = [super hash]; hasHash = YES; } return hash; } - (id) initWithBytes: (const void*)bytes length: (NSUInteger)length encoding: (NSStringEncoding)encoding { RELEASE(self); [NSException raise: NSGenericException format: @"Attempt to init an SQL string"]; return nil; } - (id) initWithBytesNoCopy: (void*)bytes length: (NSUInteger)length encoding: (NSStringEncoding)encoding freeWhenDone: (BOOL)flag { RELEASE(self); [NSException raise: NSGenericException format: @"Attempt to init an SQL string"]; return nil; } - (int) intValue { return strtol((const char*)utf8Bytes, 0, 10); } - (NSInteger) integerValue { return (NSInteger)strtoll((const char*)utf8Bytes, 0, 10); } - (NSUInteger) length { return charLen; } - (long long) longLongValue { return strtoll((const char*)utf8Bytes, 0, 10); } - (NSRange) rangeOfCharacterFromSet: (NSCharacterSet*)aSet options: (NSUInteger)mask range: (NSRange)aRange { NSUInteger index; NSUInteger start; NSUInteger stop; NSRange range; GS_RANGE_CHECK(aRange, charLen); start = aRange.location; stop = NSMaxRange(aRange); range.location = NSNotFound; range.length = 0; if (stop > start) { BOOL (*mImp)(id, SEL, unichar); unichar n = 0; unsigned i = 0; mImp = (BOOL(*)(id,SEL,unichar)) [aSet methodForSelector: @selector(characterIsMember:)]; for (index = 0; index < start; index++) { nextUTF8(utf8Bytes, byteLen, &i, &n); } if ((mask & NSBackwardsSearch) == NSBackwardsSearch) { unichar buf[stop - start]; NSUInteger pos = 0; for (pos = 0; pos + start < stop; pos++) { buf[pos] = nextUTF8(utf8Bytes, byteLen, &i, &n); } index = stop; while (index-- > start) { if ((*mImp)(aSet, @selector(characterIsMember:), buf[--pos])) { range = NSMakeRange(index, 1); break; } } } else { while (index < stop) { unichar letter; letter = nextUTF8(utf8Bytes, byteLen, &i, &n); if ((*mImp)(aSet, @selector(characterIsMember:), letter)) { range = NSMakeRange(index, 1); break; } index++; } } } return range; } - (id) copyWithZone: (NSZone*)z { return RETAIN(self); } - (NSZone*) zone { return NSDefaultMallocZone(); } - (NSStringEncoding) fastestEncoding { return NSUTF8StringEncoding; } - (NSStringEncoding) smallestEncoding { return NSUTF8StringEncoding; } - (NSUInteger) sizeOfContentExcluding: (NSHashTable*)exclude { return byteLen + 1; } @end SQLClient-1.9.0/SQLClientPool.m000066400000000000000000001066771436027104400161470ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientPool for GNUStep Copyright (C) 2014 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: June 2014 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date: 2014-05-19 10:31:02 +0100 (Mon, 19 May 2014) $ $Revision: 37893 $ */ #import #import #import #import #import #import #import #import #import #import #import #import "SQLClient.h" struct _SQLClientPoolItem { SQLClient *c; /** The clients of the pool. */ NSThread *o; /** The thread owning the client */ NSUInteger u; /** Count of client usage. */ NSTimeInterval t; /** When client was removed from pool. */ }; @interface SQLClient(Pool) - (void) _clearPool: (SQLClientPool*)p; @end @implementation SQLClient(Pool) - (void) _clearPool: (SQLClientPool*)p { NSAssert(_pool == p, NSInternalInconsistencyException); _pool = nil; } @end @interface SQLClientPool (Adjust) + (void) _adjustPoolConnections: (int)n; @end @interface SQLClientPool (Private) - (void) _lock; - (NSString*) _rc: (SQLClient*)o; - (void) _unlock; @end @interface SQLTransaction (Creation) + (SQLTransaction*) _transactionUsing: (id)clientOrPool batch: (BOOL)isBatched stop: (BOOL)stopOnFailure; @end @implementation SQLClientPool #if defined(GNUSTEP) static Class cls = Nil; + (void) initialize { if (Nil == cls) { cls = [NSAutoreleasePool class]; } } #endif - (int) availableConnections { int available; int index; [self _lock]; available = index = _max; while (index-- > 0) { if (_items[index].u > 0) { available--; } } [self _unlock]; return available; } - (SQLTransaction*) batch: (BOOL)stopOnFailure { return [SQLTransaction _transactionUsing: self batch: YES stop: stopOnFailure]; } - (GSCache*) cache { return [_items[0].c cache]; } - (uint64_t) committed { NSUInteger index; uint64_t total = 0; [_lock lock]; for (index = 0; index < _max; index++) { SQLClient *client = _items[index].c; total += [client committed]; } [_lock unlock]; return total; } - (void) dealloc { SQLClientPoolItem *old; int count; int i; [_lock lock]; count = _max; old = _items; _max = 0; _min = 0; _items = 0; if (0 != old) { for (i = 0; i < count; i++) { [old[i].c _clearPool: self]; [old[i].o release]; if (0 == old[i].u) { [old[i].c release]; } } free(old); } [_lock unlock]; DESTROY(_lock); DESTROY(_config); DESTROY(_name); [SQLClientPool _adjustPoolConnections: -count]; [super dealloc]; } - (NSString*) description { return [NSString stringWithFormat: @"%@ '%@'", [super description], _name]; } - (id) initWithConfiguration: (NSDictionary*)config name: (NSString*)reference max: (int)maxConnections min: (int)minConnections { if (nil != (self = [super init])) { if (nil == config) { config = (NSDictionary*)[NSUserDefaults standardUserDefaults]; } ASSIGN(_config, config); if (NO == [reference isKindOfClass: [NSString class]]) { reference = [_config objectForKey: @"SQLClientName"]; if (NO == [reference isKindOfClass: [NSString class]]) { reference = @"Database"; } } ASSIGNCOPY(_name, reference); _lock = [[NSConditionLock alloc] initWithCondition: 0]; [self setMax: maxConnections min: minConnections]; } return self; } - (NSString*) longDescription { NSMutableString *s = [[NSMutableString new] autorelease]; [s appendString: [self description]]; [s appendString: @", "]; [s appendString: [self status]]; [s appendString: [self statistics]]; [s appendString: [_items[0].c description]]; return s; } - (int) maxConnections { return _max; } - (int) minConnections { return _min; } - (NSString*) name { return _name; } - (SQLClient*) provideClient { return [self provideClientBeforeDate: nil exclusive: NO]; } - (SQLClient*) provideClientBeforeDate: (NSDate*)when { return [self provideClientBeforeDate: when exclusive: NO]; } - (SQLClient*) provideClientBeforeDate: (NSDate*)when exclusive: (BOOL)isLocal { NSThread *thread = [NSThread currentThread]; NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate]; NSTimeInterval now = start; SQLClient *client = nil; int preferred = -1; int found = -1; int cond = 0; int index; /* If this is a request for a non-exclusive connection, we can simply * check to see if there's already such a connection available. */ if (NO == isLocal) { [_lock lock]; for (index = 0; index < _max; index++) { if (_items[index].o == thread && _items[index].u < NSNotFound && NO == [_items[index].c isInTransaction]) { preferred = index; // Ignore any other connected client break; } if (nil == _items[index].o && 0 == _items[index].u) { if (preferred < 0 && YES == [_items[index].c connected]) { preferred = index; } else { found = index; } } } if (preferred >= 0) { found = preferred; // Prefer a connected client. } if (found >= 0) { _items[found].t = now; if (0 == _items[found].u++) { ASSIGN(_items[found].o, thread); client = [_items[found].c autorelease]; } else { /* We have already provided this client, so we must retain it * before we autorelease it, to keep retain counts in sync. */ client = [[_items[found].c retain] autorelease]; } _immediate++; } [self _unlock]; if (nil != client) { if (_debugging > 2) { NSLog(@"%@ provides %p%@", self, _items[found].c, [self _rc: client]); } return client; } } /* If we haven't been given a timeout, we should wait for a client * indefinitely ... so we set the timeout to be in the distant future. */ if (nil == when) { static NSDate *future = nil; if (nil == future) { future = RETAIN([NSDate distantFuture]); } when = future; } /* We want to log stuff if we don't get a client quickly. * Ideally we get the lock straight away, * but if not we want to log every ten seconds (and possibly * when we begin waiting). */ if (YES == [_lock tryLockWhenCondition: 1]) { _immediate++; } else { NSTimeInterval end = [when timeIntervalSinceReferenceDate]; NSTimeInterval dif = 0.0; NSDate *until; BOOL locked; if (_debugging > 1) { NSLog(@"%@ has no clients available", self); } until = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: now + 10.0]; locked = NO; while (NO == locked && now < end) { if (now >= end) { /* End date is passed ... try to get the lock immediately. */ locked = [_lock tryLockWhenCondition: 1]; } else if ([when earlierDate: until] == until) { locked = [_lock lockWhenCondition: 1 beforeDate: until]; } else { locked = [_lock lockWhenCondition: 1 beforeDate: when]; } now = [NSDate timeIntervalSinceReferenceDate]; dif = now - start; if (NO == locked && now < end) { if (_debugging > 0 || dif > 30.0 || (_duration >= 0.0 && dif > _duration)) { NSLog(@"%@ still waiting after %g seconds:\n%@", self, dif, [self status]); } [until release]; until = [[NSDate alloc] initWithTimeIntervalSinceNow: 10.0]; } } [until release]; if (dif > _longest) { _longest = dif; } if (NO == locked) { if (_debugging > 0 || dif > 30.0 || (_duration >= 0.0 && dif > _duration)) { NSLog(@"%@ abandoned wait after %g seconds:\n%@", self, dif, [self status]); } _failed++; _failWaits += dif; return nil; } if (_debugging > 0 || (_duration >= 0.0 && dif > _duration)) { NSLog(@"%@ provided client after %g seconds", self, dif); } _delayed++; _delayWaits += dif; } for (index = 0; index < _max && 0 == cond; index++) { if (0 == _items[index].u) { if (preferred >= 0 || found >= 0) { /* There's at least one more client available to be * provided, so we want to re-lock with condition 1. */ cond = 1; } if (preferred < 0 && YES == [_items[index].c connected]) { preferred = index; } else { found = index; } } else if (NO == isLocal && _items[index].o == thread && _items[index].u < NSNotFound && NO == [_items[index].c isInTransaction]) { /* We are allowed to re-use connections in the current thread, * so if we have found one, treat it as the preferred choice. */ preferred = index; } } /* We prefer to use a client which is already connected, so we * avoid opening unnecessary connections. */ if (preferred >= 0) { found = preferred; } if (YES == isLocal) { _items[found].u = NSNotFound; } else { _items[found].u++; } _items[found].t = now; ASSIGN(_items[found].o, thread); [self _unlock]; client = [_items[found].c autorelease]; if (_debugging > 2) { NSLog(@"%@ provides %p%@", self, _items[found].c, [self _rc: client]); } return client; } - (SQLClient*) provideClientExclusive { return [self provideClientBeforeDate: nil exclusive: YES]; } - (void) purge { BOOL more = YES; [self _lock]; while (YES == more) { SQLClient *found = nil; int connected = 0; int index; more = NO; for (index = 0; index < _max; index++) { if (YES == [_items[index].c connected]) { /* This is a connected client. */ connected++; if (0 == _items[index].u) { /* Not in use; so a candidate to be purged */ found = [_items[index].c longestIdle: found]; } } } if (nil != found) { NSTimeInterval age; age = -[[found lastOperation] timeIntervalSinceNow]; if (_debugging > 2) { NSLog(@"%@ purge found %p age %g", self, found, age); } if (age > _purgeAll || (connected > _min && age > _purgeMin)) { NS_DURING { [found disconnect]; more = YES; } NS_HANDLER { NSLog(@"Error disconnecting client in pool: %@", localException); } NS_ENDHANDLER } } } [self _unlock]; } - (void) setCache: (GSCache*)aCache { int index; /* We don't allow a nil cache for the pool (each client would create its * own cache on demand). So we treat a nil cache as a request to create * a new cache with the default config. */ [self _lock]; if (nil == aCache) { [_items[0].c setCache: nil]; aCache = [_items[0].c cache]; } for (index = 1; index < _max; index++) { [_items[index].c setCache: aCache]; } [self _unlock]; } - (void) setCacheThread: (NSThread*)aThread { int index; [self _lock]; for (index = 0; index < _max; index++) { [_items[index].c setCacheThread: aThread]; } [self _unlock]; } - (void) setDebugging: (unsigned int)level { int index; [self _lock]; _debugging = level; for (index = 0; index < _max; index++) { [_items[index].c setDebugging: _debugging]; } [self _unlock]; } - (void) setDurationLogging: (NSTimeInterval)threshold { int index; [self _lock]; _duration = threshold; for (index = 0; index < _max; index++) { [_items[index].c setDurationLogging: _duration]; } [self _unlock]; } - (void) setMax: (int)maxConnections min: (int)minConnections { int old; int index; if (minConnections < 1) minConnections = 1; if (maxConnections < 1) maxConnections = 5; if (maxConnections > 100) maxConnections = 100; if (minConnections > maxConnections) minConnections = maxConnections; [self _lock]; old = _max; if (maxConnections != _max) { GSCache *cache = nil; if (_max > 0) { while (_max > maxConnections) { _max--; [_items[_max].c _clearPool: self]; if (0 == _items[_max].u) { [_items[_max].c release]; } DESTROY(_items[_max].o); } _items = realloc(_items, maxConnections * sizeof(SQLClientPoolItem)); } else { _items = calloc(maxConnections, sizeof(SQLClientPoolItem)); } for (index = _max; index < maxConnections; index++) { _items[index].o = nil; _items[index].t = 0.0; _items[index].u = 0; _items[index].c = [[SQLClient alloc] initWithConfiguration: _config name: _name pool: self]; /* All the clients in the pool should share the same cache. */ if (0 == index) { cache = [_items[index].c cache]; } else { [_items[index].c setCache: cache]; } } _max = maxConnections; [SQLClientPool _adjustPoolConnections: _max - old]; } _min = minConnections; [self _unlock]; } - (void) setPurgeAll: (int)allSeconds min: (int)minSeconds { if (allSeconds < 1) { allSeconds = 300; } if (minSeconds < 1) { minSeconds = 10; } if (allSeconds < minSeconds) { allSeconds = minSeconds; } _purgeMin = minSeconds; _purgeAll = allSeconds; } - (NSString*) statistics { NSString *s; s = [NSString stringWithFormat: @" Immediate provisions: %llu\n" @" Delayed provisions: %llu\n" @" Timed out provisions: %llu\n" @" Slowest provision: %g\n" @" Average delay: %g\n" @" Average timeout: %g\n" @" Average over all: %g\n" @" Committed transactions: %"PRIu64"\n", (unsigned long long)_immediate, (unsigned long long)_delayed, (unsigned long long)_failed, _longest, (_delayed > 0) ? _delayWaits / _delayed : 0.0, (_failed > 0) ? _failWaits / _failed : 0.0, (_immediate + _delayed + _failed) > 0 ? (_failWaits + _delayWaits) / (_immediate + _delayed + _failed) : 0.0, [self committed]]; return s; } - (NSString*) status { NSMutableArray *idleInfo = nil; NSMutableArray *liveInfo = nil; NSMutableString *retainInfo = nil; unsigned int cond = 0; unsigned int free = 0; unsigned int dead = 0; unsigned int idle = 0; unsigned int live = 0; unsigned int used = 0; int index; NSMutableString *s; [_lock lock]; for (index = 0; index < _max; index++) { SQLClient *client = _items[index].c; NSUInteger rc = [client retainCount]; NSUInteger uc = _items[index].u; /* Check to see if this client is free to be taken from the pool. * Also, if a client is connected but not in use, we call it idle. */ if (uc > 0) { NSString *tmp; if (NSNotFound == uc) { tmp = [NSString stringWithFormat: @" Client '%@'" @" provided exclusively (retained:%"PRIuPTR, [client name], rc]; } else { tmp = [NSString stringWithFormat: @" Client '%@'" @" provided %"PRIuPTR @" time%s (retained:%"PRIuPTR, [client name], uc, ((1 == uc) ? "" : "s"), rc]; } #if defined(GNUSTEP) NSUInteger ac = [cls autoreleaseCountForObject: client]; tmp = [tmp stringByAppendingFormat: @" - autoreleased:%"PRIuPTR, ac]; #endif /* This is a client which has been provided by the pool, * so it is in use by some code. */ if (YES == [client isInTransaction]) { NSDate *d = [client lastOperation]; live++; if (nil == liveInfo) { liveInfo = [NSMutableArray array]; } [liveInfo addObject: [tmp stringByAppendingFormat: @") active in transaction since %@\n", d]]; } else { if (YES == [client connected]) { NSDate *d = [client lastOperation]; used++; if (nil == d) { d = [client lastConnect]; } if ([d timeIntervalSinceReferenceDate] < _items[index].t) { d = [NSDate dateWithTimeIntervalSinceReferenceDate: _items[index].t]; } if (nil == idleInfo) { idleInfo = [NSMutableArray array]; } [idleInfo addObject: [tmp stringByAppendingFormat: @") taken from pool but idle since %@\n", d]]; } else { idle++; [idleInfo addObject: [tmp stringByAppendingFormat: @") taken from pool and recently used\n"]]; } } } else { BOOL connected = [_items[index].c connected]; /* The client is not in use and can be provided by the pool, * so we must therefore re-lock with condition 1. */ cond = 1; if (_debugging > 0) { if (nil == retainInfo) { retainInfo = [NSMutableString stringWithCapacity: 100]; } [retainInfo appendFormat: @" Client '%@' (retain count %"PRIuPTR @") %s pool %s connected to server\n", [client name], rc, ((_items[index].u > 0) ? "taken from" : "available in"), ((YES == connected) ? "and" : "but not")]; } if (YES == connected) { /* Still connected, so we count it as a free connection. */ free++; } else { /* Not connected, so we count it as a dead connection. */ dead++; } } } s = [NSMutableString stringWithFormat: @" size min: %u, max: %u\n" @" live:%u, used:%u, idle:%u, free:%u, dead:%u\n", _min, _max, live, used, idle, free, dead]; if (liveInfo) { for (index = 0; index < [liveInfo count]; index++) { [s appendString: [liveInfo objectAtIndex: index]]; } } if (idleInfo) { for (index = 0; index < [idleInfo count]; index++) { [s appendString: [idleInfo objectAtIndex: index]]; } } if (retainInfo) { [s appendString: retainInfo]; } [_lock unlockWithCondition: cond]; return s; } - (BOOL) _swallowClient: (SQLClient*)client explicit: (BOOL)swallowed { BOOL found = NO; int index; if (YES == [client isInTransaction]) { /* The client has a transaction in progress ... if it's in the * current thread we should be able to disconnect (implicit rollback) * and return the client to the pool, otherwise we raise an exception. */ if (YES == [client lockBeforeDate: nil]) { [client disconnect]; [client unlock]; NSLog(@"ERROR: Disconnected client which was returned to pool" @" while a transaction was in progress: %@", client); } else { [NSException raise: SQLConnectionException format: @"failed to return to pool because a transaction" @" was in progress: %@", client]; } } /* The client must not have any observers if it's in a pool. */ [client removeObserver: nil name: nil]; [self _lock]; for (index = 0; index < _max && NO == found; index++) { if (_items[index].u > 0 && client == _items[index].c) { found = YES; if (YES == swallowed) { if (NSNotFound == _items[index].u || 1 == _items[index].u) { /* This was only provided once, and has been explicitly * swallowed by the pool again, so we should increment * the reference count to prevent an implicit swallow * caused by deallocation. */ _items[index].u = 0; if (client) { NSIncrementExtraRefCount(client); } } else { _items[index].u--; } } else { /* Nothing is using this client connection any more (it had * -dealloc called), so we know the count must be zero. */ _items[index].u = 0; } if (0 == _items[index].u) { DESTROY(_items[index].o); } } } [self _unlock]; if (_debugging > 2) { if (YES == found) { NSLog(@"%@ swallows %p%@", self, client, [self _rc: client]); } else { NSLog(@"%@ rejects %p%@", self, client, [self _rc: client]); } } return found; } - (BOOL) swallowClient: (SQLClient*)client { return [self _swallowClient: client explicit: YES]; } - (void) setClientName: (NSString*)s { unsigned int index; [self _lock]; for (index = 0; index < _max; index++) { SQLClient *client = _items[index].c; if (nil == s) { [client setClientName: s]; } else { NSString *n; n = [s stringByAppendingFormat: @" (%u)", index]; [client setClientName: n]; } } [self _unlock]; } - (SQLTransaction*) transaction { return [SQLTransaction _transactionUsing: self batch: NO stop: NO]; } @end @implementation SQLClientPool (Private) - (void) _lock { [_lock lock]; } - (NSString*) _rc: (SQLClient*)o { #if defined(GNUSTEP) if (_debugging > 3) { NSUInteger rc; NSUInteger ac; NSUInteger uc; int index; rc = [o retainCount]; ac = [cls autoreleaseCountForObject: o]; [_lock lock]; uc = 0; for (index = 0; index < _max; index++) { if (o == _items[index].c) { uc = _items[index].u; break; } } [self _unlock]; if (NSNotFound == uc) { return [NSString stringWithFormat: @" provided exclusively (retained:%"PRIuPTR @" - autoreleased:%"PRIuPTR @")", rc, ac]; } else { return [NSString stringWithFormat: @" provided %"PRIuPTR @" time%s (retained:%"PRIuPTR @" - autoreleased:%"PRIuPTR @")", uc, ((1 == uc) ? "" : "s"), rc, ac]; } } #endif return @""; } - (void) _unlock { int index; for (index = 0; index < _max; index++) { /* Check to see if this client is free to be taken from the pool. */ if (0 == _items[index].u) { [_lock unlockWithCondition: 1]; return; } } [_lock unlockWithCondition: 0]; } @end @implementation SQLClientPool (ConvenienceMethods) - (SQLLiteral*) buildQuery: (NSString*)stmt, ... { SQLLiteral *sql; va_list ap; /* * First check validity and concatenate parts of the query. */ va_start (ap, stmt); sql = [[_items[0].c prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); return sql; } - (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values { SQLLiteral *sql; sql = [_items[0].c buildQuery: stmt with: values]; return sql; } - (NSMutableArray*) cacheCheckSimpleQuery: (NSString*)stmt { NSMutableArray *result = [[_items[0].c cache] objectForKey: stmt]; if (result != nil) { result = [[result mutableCopy] autorelease]; } return result; } - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt,... { SQLClient *db; NSMutableArray *result; SQLLiteral *query; va_list ap; va_start (ap, stmt); query = [[_items[0].c prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); db = [self provideClient]; NS_DURING result = [db cache: seconds simpleQuery: query]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) cache: (int)seconds query: (NSString*)stmt with: (NSDictionary*)values { SQLClient *db; NSMutableArray *result; db = [self provideClient]; NS_DURING result = [db cache: seconds query: stmt with: values]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt; { SQLClient *db; NSMutableArray *result; db = [self provideClient]; NS_DURING result = [db cache: seconds simpleQuery: stmt]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) cache: (int)seconds simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype { SQLClient *db; NSMutableArray *result; db = [self provideClient]; NS_DURING result = [db cache: seconds simpleQuery: stmt recordType: rtype listType: ltype]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) columns: (NSMutableArray*)records { return [SQLClient columns: records]; } - (NSInteger) execute: (NSString*)stmt, ... { SQLClient *db; NSInteger result; NSArray *info; va_list ap; va_start (ap, stmt); info = [_items[0].c prepare: stmt args: ap]; va_end (ap); db = [self provideClient]; NS_DURING result = [db simpleExecute: info]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values { SQLClient *db; NSInteger result; db = [self provideClient]; NS_DURING result = [db execute: stmt with: values]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (SQLClientPool*) pool { return self; } - (NSMutableArray*) prepare: (NSString*)stmt, ... { va_list ap; NSMutableArray *result; va_start (ap, stmt); result = [_items[0].c prepare: stmt args: ap]; va_end (ap); return result; } - (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args { return [_items[0].c prepare: stmt args: args]; } - (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values { return [_items[0].c prepare: stmt with: values]; } - (NSMutableArray*) query: (NSString*)stmt, ... { SQLClient *db; NSMutableArray *result; SQLLiteral *query; va_list ap; /* * First check validity and concatenate parts of the query. */ va_start (ap, stmt); query = [[_items[0].c prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); db = [self provideClient]; NS_DURING result = [db simpleQuery: query]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values { SQLClient *db; NSMutableArray *result; db = [self provideClient]; NS_DURING result = [db query: stmt with: values]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (SQLRecord*) queryRecord: (NSString*)stmt, ... { SQLClient *db; NSArray *result; SQLRecord *record; SQLLiteral *query; va_list ap; va_start (ap, stmt); query = [[_items[0].c prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); db = [self provideClient]; NS_DURING result = [db simpleQuery: query]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; if ([result count] > 1) { [NSException raise: NSInvalidArgumentException format: @"Query returns more than one record -\n%@\n", query]; } record = [result lastObject]; if (record == nil) { [NSException raise: SQLEmptyException format: @"Query returns no data -\n%@\n", query]; } return record; } - (NSString*) queryString: (NSString*)stmt, ... { SQLClient *db; NSArray *result; SQLRecord *record; SQLLiteral *query; va_list ap; va_start (ap, stmt); query = [[_items[0].c prepare: stmt args: ap] objectAtIndex: 0]; va_end (ap); db = [self provideClient]; NS_DURING result = [db simpleQuery: query]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; if ([result count] > 1) { [NSException raise: NSInvalidArgumentException format: @"Query returns more than one record -\n%@\n", query]; } record = [result lastObject]; if (record == nil) { [NSException raise: SQLEmptyException format: @"Query returns no data -\n%@\n", query]; } if ([record count] > 1) { [NSException raise: NSInvalidArgumentException format: @"Query returns multiple fields -\n%@\n", query]; } return [[record lastObject] description]; } - (SQLLiteral*) quote: (id)obj { return (SQLLiteral*)[_items[0].c quote: obj]; } - (SQLLiteral*) quoteArray: (NSArray*)a { return (SQLLiteral*)[_items[0].c quoteArray: a]; } - (SQLLiteral*) quoteArraySafe: (NSArray*)a { return (SQLLiteral*)[_items[0].c quoteArraySafe: a]; } - (NSMutableString*) quoteArray: (NSArray *)a toString: (NSMutableString *)s quotingStrings: (BOOL)_q { NSMutableString *result; result = [_items[0].c quoteArray: a toString:s quotingStrings: _q]; return result; } - (SQLLiteral*) quotef: (NSString*)fmt, ... { va_list ap; NSString *str; SQLLiteral *quoted; va_start(ap, fmt); str = [[NSString allocWithZone: NSDefaultMallocZone()] initWithFormat: fmt arguments: ap]; va_end(ap); quoted = (SQLLiteral*)[_items[0].c quoteString: str]; [str release]; return (SQLLiteral*)quoted; } - (SQLLiteral*) quoteBigInteger: (int64_t)i { return (SQLLiteral*)[_items[0].c quoteBigInteger: i]; } - (SQLLiteral*) quoteCString: (const char *)s { return (SQLLiteral*)[_items[0].c quoteCString: s]; } - (SQLLiteral*) quoteChar: (char)chr { return (SQLLiteral*)[_items[0].c quoteChar: chr]; } - (SQLLiteral*) quoteFloat: (double)f { return (SQLLiteral*)[_items[0].c quoteFloat: f]; } - (SQLLiteral*) quoteInteger: (int)i { return (SQLLiteral*)[_items[0].c quoteInteger: i]; } - (SQLLiteral*) quoteName: (NSString *)s { return (SQLLiteral*)[_items[0].c quoteName: s]; } - (SQLLiteral*) quoteSet: (id)obj { return (SQLLiteral*)[_items[0].c quoteSet: obj]; } - (SQLLiteral*) quoteString: (NSString *)s { return (SQLLiteral*)[_items[0].c quoteString: s]; } - (NSInteger) simpleExecute: (NSArray*)info { SQLClient *db; NSInteger result; db = [self provideClient]; NS_DURING result = [db simpleExecute: info]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt { SQLClient *db; NSMutableArray *result; db = [self provideClient]; NS_DURING result = [db simpleQuery: stmt]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (NSMutableArray*) simpleQuery: (SQLLitArg*)stmt recordType: (id)rtype listType: (id)ltype { SQLClient *db; NSMutableArray *result; db = [self provideClient]; NS_DURING result = [db simpleQuery: stmt recordType: rtype listType: ltype]; NS_HANDLER [self swallowClient: db]; [localException raise]; NS_ENDHANDLER [self swallowClient: db]; return result; } - (void) singletons: (NSMutableArray*)records { [SQLClient singletons: records]; } @end SQLClient-1.9.0/SQLite.m000066400000000000000000000206611436027104400146440ustar00rootroot00000000000000/* -*-objc-*- */ /** Implementation of SQLClientSQLite for GNUStep Copyright (C) 2005 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: Nov 2005 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import #import #import #import #import #import #import #import #import #import #import #import #import #include "config.h" #define SQLCLIENT_PRIVATE @public #include "SQLClient.h" #include #include @interface SQLClientSQLite : SQLClient @end @implementation SQLClientSQLite /* use [self database] as path to database file */ - (BOOL) backendConnect { if (connected == NO) { if ([self database] != nil) { NSString *dbase = [self database]; sqlite3 *sql; int result; [[self class] purgeConnections: nil]; if ([self debugging] > 0) { [self debug: @"Connect to '%@' as %@", [self database], [self name]]; } result = sqlite3_open([dbase fileSystemRepresentation], &sql); if (result != 0) { [self debug: @"Error connecting to '%@' (%@) - %s", [self name], [self database], sqlite3_errmsg(sql)]; sqlite3_close(sql); extra = 0; } else { connected = YES; extra = sql; if ([self debugging] > 0) { [self debug: @"Connected to '%@'", [self name]]; } } } else { [self debug: @"Connect to '%@' with no database configured", [self name]]; } } return connected; } - (void) backendDisconnect { if (connected == YES) { NS_DURING { if ([self isInTransaction] == YES) { [self rollback]; } if ([self debugging] > 0) { [self debug: @"Disconnecting client %@", [self clientName]]; } sqlite3_close((sqlite3 *)extra); extra = 0; if ([self debugging] > 0) { [self debug: @"Disconnected client %@", [self clientName]]; } } NS_HANDLER { extra = 0; [self debug: @"Error disconnecting from database (%@): %@", [self clientName], localException]; } NS_ENDHANDLER connected = NO; } } - (NSInteger) backendExecute: (NSArray*)info { NSString *stmt; NSAutoreleasePool *arp = [NSAutoreleasePool new]; stmt = [info objectAtIndex: 0]; if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } NS_DURING { const char *statement; unsigned length; int result; char *err; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to execute statement %@", [self name], stmt]; } statement = (char*)[stmt UTF8String]; length = strlen(statement); statement = [self insertBLOBs: info intoStatement: statement length: length withMarker: "'?'''?'" length: 7 giving: &length]; result = sqlite3_exec((sqlite3 *)extra, statement, 0, 0, &err); if (result != SQLITE_OK) { [NSException raise: SQLException format: @"%s", err]; } } NS_HANDLER { NSString *n = [localException name]; if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return -1; } - (NSMutableArray*) backendQuery: (NSString*)stmt recordType: (id)rtype listType: (id)ltype { NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSMutableArray *records = [[ltype alloc] initWithCapacity: 2]; if ([stmt length] == 0) { [arp release]; [NSException raise: NSInternalInconsistencyException format: @"Statement produced null string"]; } NS_DURING { char *statement; int result; sqlite3_stmt *prepared; const char *stmtEnd; /* * Ensure we have a working connection. */ if ([self connect] == NO) { [NSException raise: SQLException format: @"Unable to connect to '%@' to run query %@", [self name], stmt]; } statement = (char*)[stmt UTF8String]; result = sqlite3_prepare((sqlite3 *)extra, statement, strlen(statement), &prepared, &stmtEnd); if (result != SQLITE_OK) { [NSException raise: SQLException format: @"Unable to prepare '%@'", stmt]; } if ((result = sqlite3_step(prepared)) == SQLITE_ROW) { int columns = sqlite3_column_count(prepared); NSString *keys[columns]; int i; for (i = 0; i < columns; i++) { keys[i] = [NSString stringWithUTF8String: sqlite3_column_name(prepared, i)]; } do { id values[columns]; SQLRecord *record; for (i = 0; i < columns; i++) { int type = sqlite3_column_type(prepared, i); switch (type) { case SQLITE_INTEGER: values[i] = [NSNumber numberWithInt: sqlite3_column_int(prepared, i)]; break; case SQLITE_FLOAT: values[i] = [NSNumber numberWithDouble: sqlite3_column_double(prepared, i)]; break; case SQLITE_TEXT: values[i] = [NSString stringWithUTF8String: (char *)sqlite3_column_text(prepared, i)]; break; case SQLITE_BLOB: values[i] = [NSData dataWithBytes: sqlite3_column_blob(prepared, i) length: sqlite3_column_bytes(prepared, i)]; break; case SQLITE_NULL: values[i] = nil; break; } } record = [rtype newWithValues: values keys: keys count: columns]; [records addObject: record]; [record release]; } while ((result = sqlite3_step(prepared)) == SQLITE_ROW); } if (result != SQLITE_DONE) { [NSException raise: SQLException format: @"%s", sqlite3_errmsg((sqlite3 *)extra)]; } sqlite3_finalize(prepared); } NS_HANDLER { NSString *n = [localException name]; if ([n isEqual: SQLConnectionException] == YES) { [self disconnect]; } if ([self debugging] > 0) { [self debug: @"Error executing statement:\n%@\n%@", stmt, localException]; } [localException retain]; [arp release]; [localException autorelease]; [localException raise]; } NS_ENDHANDLER [arp release]; return [records autorelease]; } static char hex[16] = "0123456789ABCDEF"; - (unsigned) copyEscapedBLOB: (NSData*)blob into: (void*)buf { const unsigned char *bytes = [blob bytes]; unsigned char *ptr = buf; unsigned length = [blob length]; unsigned i; *ptr++ = 'X'; *ptr++ = '\''; for (i = 0; i < length; i++) { unsigned char c = bytes[i]; *ptr++ = hex[c / 16]; *ptr++ = hex[c % 16];; } *ptr++ = '\''; return ((void*)ptr - buf); } - (unsigned) lengthOfEscapedBLOB: (NSData*)blob { /* * A blob is X'xx' where xx is hexadecimal encoded binary data ... * two hex digits per byte. */ return 3 + [blob length] * 2; } - (NSString*) quote: (id)obj { if ([obj isKindOfClass: [NSDate class]] == YES) { obj = [NSNumber numberWithDouble: [obj timeIntervalSinceReferenceDate]]; } return [super quote: obj]; } @end SQLClient-1.9.0/config.h.in000066400000000000000000000067371436027104400153600ustar00rootroot00000000000000/* config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the header file. */ #undef HAVE_ECPGLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_JNI_H /* Define to 1 if you have the `ecpg' library (-lecpg). */ #undef HAVE_LIBECPG /* Define to 1 if you have the `jvm' library (-ljvm). */ #undef HAVE_LIBJVM /* Define to 1 if you have the `mysqlclient' library (-lmysqlclient). */ #undef HAVE_LIBMYSQLCLIENT /* Define to 1 if you have the `pq' library (-lpq). */ #undef HAVE_LIBPQ /* Define to 1 if you have the header file. */ #undef HAVE_LIBPQ_FE_H /* Define to 1 if you have the `sqlite3' library (-lsqlite3). */ #undef HAVE_LIBSQLITE3 /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_MYSQL_MYSQL_H /* Define to 1 if you have the `PQescapeStringConn' function. */ #undef HAVE_PQESCAPESTRINGCONN /* Define to 1 if you have the header file. */ #undef HAVE_SQLITE3_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_INCLUDE_PGSQL_ECPGLIB_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_INCLUDE_PGSQL_LIBPQ_FE_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_INCLUDE_POSTGRESQL_8_0_ECPGLIB_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_INCLUDE_POSTGRESQL_8_0_LIBPQ_FE_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_INCLUDE_POSTGRESQL_ECPGLIB_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_INCLUDE_POSTGRESQL_LIBPQ_FE_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_LOCAL_INCLUDE_PGSQL_ECPGLIB_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_LOCAL_INCLUDE_PGSQL_LIBPQ_FE_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_LOCAL_PGSQL_INCLUDE_ECPGLIB_H /* Define to 1 if you have the header file. */ #undef HAVE__USR_LOCAL_PGSQL_INCLUDE_LIBPQ_FE_H /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS SQLClient-1.9.0/config.make.in000066400000000000000000000003561436027104400160350ustar00rootroot00000000000000 ECPG=@ECPG@ JDBC=@JDBC@ JDBC_VM_LIBS=@JDBC_VM_LIBS@ JDBC_VM_LIBDIRS=@JDBC_VM_LIBDIRS@ MYSQL=@MYSQL@ SQLITE=@SQLITE@ ORACLE_HOME=@ORACLE_HOME@ POSTGRES=@POSTGRES@ ADDITIONAL_INCLUDE_DIRS += \ @INCD@ \ ADDITIONAL_LIB_DIRS += \ @LIBD@ \ SQLClient-1.9.0/configure000077500000000000000000005024701436027104400152370ustar00rootroot00000000000000#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69. # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME= PACKAGE_TARNAME= PACKAGE_VERSION= PACKAGE_STRING= PACKAGE_BUGREPORT= PACKAGE_URL= ac_unique_file="SQLClient.h" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='LTLIBOBJS LIBOBJS LIBD INCD ORACLE_HOME ECPG POSTGRES SQLITE MYSQL JDBC_VM_LIBDIRS JDBC_VM_LIBS JDBC EGREP GREP CPP OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking with_additional_include with_additional_lib with_postgres_dir enable_jdbc_bundle with_jre_architecture enable_mysql_bundle enable_sqllite_bundle enable_postgres_bundle enable_ecpg_bundle ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures this package to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/PACKAGE] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF _ACEOF fi if test -n "$ac_init_help"; then cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-jdbc-bundle Disable creating the Jdbc bundle. Use this option to force the Jdbc bundle not to be built even if the Jdbc libraries look like being present. --disable-mysql-bundle Disable creating the Mysql bundle. Use this option to force the Mysql bundle not to be built even if the Mysql libraries look like being present. --disable-sqllite-bundle Disable creating the Sqllite bundle. Use this option to force the Sqllite bundle not to be built even if the Sqllite libraries look like being present. --disable-postgres-bundle Disable creating the Postgres bundle. Use this option to force the Postgres bundle not to be built even if the Postgres libraries look like being present. --disable-ecpg-bundle Disable creating the ECPG bundle. Use this option to force the ECPG bundle not to be built even if the Postgres libraries look like being present. Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-additional-include=flags Specifies additional include compiler flags to use. If configure can not find your database library headers, you may want to use this flag to help it find them. For example: --with-additional-include=-I/usr/local/include --with-additional-lib=flags Specifies additional library compiler flags to use. If configure can not find your database libraries, you may want to use this flag to help it find them. For example: --with-additional-lib=-L/usr/local/lib/mysql --with-postgres-dir=PATH Specifies the postgres installation dir; configure will add the appropriate additional include and lib flags. Useful when you installed postgres in some unusual place and want to help configure find it. For example: --with-postgres-dir=/usr/local/pgsql (which is equivalent to --with-additional-include=-L/usr/local/pgsql/include --with-additional-lib=-L/usr/local/pgsql/lib) --with-jre-architecture=value Specifies the CPU architecture to use for the JRE (only used when building the JDBC module). Example values are i386, amd64 and sparc. Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to the package provider. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF configure generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by $as_me, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers config.h" if test -z "$GNUSTEP_MAKEFILES"; then GNUSTEP_MAKEFILES=`gnustep-config --variable=GNUSTEP_MAKEFILES 2>/dev/null` export GNUSTEP_MAKEFILES fi if test -z "$GNUSTEP_MAKEFILES"; then as_fn_error $? "You must have the gnustep-make package installed and set up the GNUSTEP_MAKEFILES environment variable to contain the path to the makefiles directory before configuring!" "$LINENO" 5 else . $GNUSTEP_MAKEFILES/GNUstep.sh fi if test "x$GNUSTEP_HOST_OS" = "x"; then GNUSTEP_HOST_OS=`gnustep-config --variable=GNUSTEP_HOST_OS` GNUSTEP_HOST_CPU=`gnustep-config --variable=GNUSTEP_HOST_CPU` fi #-------------------------------------------------------------------- # Check whether --with-additional-include was given. if test "${with_additional_include+set}" = set; then : withval=$with_additional_include; additional_include="$withval" else additional_include="no" fi if test "$additional_include" != "no"; then CPPFLAGS="$CPPFLAGS $additional_include" INCD="$INCD $additional_include" fi # Check whether --with-additional-lib was given. if test "${with_additional_lib+set}" = set; then : withval=$with_additional_lib; additional_lib="$withval" else additional_lib="no" fi if test "$additional_lib" != "no"; then LDFLAGS="$LDFLAGS $additional_lib" LIBD="$LIBD $additional_lib" fi # Check whether --with-postgres-dir was given. if test "${with_postgres_dir+set}" = set; then : withval=$with_postgres_dir; postgres_topdir="$withval" else postgres_topdir="no" fi if test "$postgres_topdir" != "no"; then CPPFLAGS="$CPPFLAGS -I$postgres_topdir/include -L$postgres_topdir/lib" INCD="$INCD -I$postgres_topdir/include" LIBD="$LIBD -L$postgres_topdir/lib" else PGINC=`pg_config --includedir` if test "$PGINC" != ""; then CPPFLAGS="$CPPFLAGS -I$PGINC" INCD="$INCD -I$PGINC" fi PGLIB=`pg_config --libdir` if test "$PGLIB" != ""; then CPPFLAGS="$CPPFLAGS -L$PGLIB" LIBD="$LIBD -I$PGLIB" fi fi # Call AC_CHECK_HEADERS here as a workaround for a configure bug/feature # which messes up all subsequent tests if the first occurrence in the # file does not get called ... as would otherwise be the case if jdbc # support is disabled. ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_header in stdio.h do : ac_fn_c_check_header_mongrel "$LINENO" "stdio.h" "ac_cv_header_stdio_h" "$ac_includes_default" if test "x$ac_cv_header_stdio_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STDIO_H 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking if Jdbc support was manually disabled" >&5 $as_echo_n "checking if Jdbc support was manually disabled... " >&6; } # Check whether --enable-jdbc-bundle was given. if test "${enable_jdbc_bundle+set}" = set; then : enableval=$enable_jdbc_bundle; ac_cv_jdbc_bundle=$enableval else ac_cv_jdbc_bundle="yes" fi if test "$ac_cv_jdbc_bundle" = "no"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes: disabled from the command-line" >&5 $as_echo "yes: disabled from the command-line" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no: build if possible" >&5 $as_echo "no: build if possible" >&6; } # Get likely subdirectory for system specific java include case "$GNUSTEP_HOST_OS" in bsdi*) _JNI_SUBDIR="bsdos";; linux*) _JNI_SUBDIR="linux";; osf*) _JNI_SUBDIR="alpha";; solaris*) _JNI_SUBDIR="solaris";; mingw*) _JNI_SUBDIR="win32";; cygwin*) _JNI_SUBDIR="win32";; *) _JNI_SUBDIR="genunix";; esac # Check whether --with-jre-architecture was given. if test "${with_jre_architecture+set}" = set; then : withval=$with_jre_architecture; jre_architecture="$withval" else jre_architecture="" fi save_LIBS="$LIBS" save_CFLAGS="$CFLAGS" save_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS -I$JAVA_HOME/include -I$JAVA_HOME/include/$_JNI_SUBDIR" for ac_header in jni.h do : ac_fn_c_check_header_mongrel "$LINENO" "jni.h" "ac_cv_header_jni_h" "$ac_includes_default" if test "x$ac_cv_header_jni_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_JNI_H 1 _ACEOF fi done if test "$ac_cv_header_jni_h" = "yes"; then JDBC_VM_LIBS="-ljvm" jre_lib="$JAVA_HOME/jre/lib" if test "$jre_architecture" = ""; then # If on a 32/64bit system and compiling for the 64bit model # adjust the cpu type to be the 64bit version case "$CFLAGS" in *-m64*) if test "$GNUSTEP_HOST_CPU" = "ix86"; then _CPU="x86_64" else _CPU="$GNUSTEP_HOST_CPU" fi;; *) _CPU="$GNUSTEP_HOST_CPU";; esac case "$_CPU" in ix86) JAVA_CPU=i386;; x86_64) JAVA_CPU=amd64;; sparc) JAVA_CPU=sparc;; *) JAVA_CPU=i386;; esac else JAVA_CPU="$jre_architecture" fi jre_cpu="$jre_lib/$JAVA_CPU" JDBC_VM_LIBDIRS="-L$jre_cpu/server" CFLAGS="$CFLAGS $JDBC_VM_LIBDIRS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for JNI_CreateJavaVM in -ljvm" >&5 $as_echo_n "checking for JNI_CreateJavaVM in -ljvm... " >&6; } if ${ac_cv_lib_jvm_JNI_CreateJavaVM+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ljvm $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char JNI_CreateJavaVM (); int main () { return JNI_CreateJavaVM (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_jvm_JNI_CreateJavaVM=yes else ac_cv_lib_jvm_JNI_CreateJavaVM=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jvm_JNI_CreateJavaVM" >&5 $as_echo "$ac_cv_lib_jvm_JNI_CreateJavaVM" >&6; } if test "x$ac_cv_lib_jvm_JNI_CreateJavaVM" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBJVM 1 _ACEOF LIBS="-ljvm $LIBS" fi if test "$ac_cv_lib_jvm_JNI_CreateJavaVM" = "yes"; then INCD="$INCD -I$JAVA_HOME/include -I$JAVA_HOME/include/$_JNI_SUBDIR" JDBC=yes else JDBC= JDBC_VM_LIBS= JDBC_VM_LIBDIRS= echo "**********************************************" echo "Unable to locate jvm library (is it installed)" echo "**********************************************" fi else JDBC= JDBC_VM_LIBS= JDBC_VM_LIBDIRS= echo "*********************************************" echo "Unable to locate jni header (is it installed)" echo "*********************************************" fi LIBS="$save_LIBS" CFLAGS="$save_CFLAGS" CPPFLAGS="$save_CPPFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if Mysql support was manually disabled" >&5 $as_echo_n "checking if Mysql support was manually disabled... " >&6; } # Check whether --enable-mysql-bundle was given. if test "${enable_mysql_bundle+set}" = set; then : enableval=$enable_mysql_bundle; ac_cv_mysql_bundle=$enableval else ac_cv_mysql_bundle="yes" fi if test "$ac_cv_mysql_bundle" = "no"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes: disabled from the command-line" >&5 $as_echo "yes: disabled from the command-line" >&6; } MYSQL= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no: build if possible" >&5 $as_echo "no: build if possible" >&6; } for ac_header in mysql/mysql.h do : ac_fn_c_check_header_mongrel "$LINENO" "mysql/mysql.h" "ac_cv_header_mysql_mysql_h" "$ac_includes_default" if test "x$ac_cv_header_mysql_mysql_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_MYSQL_MYSQL_H 1 _ACEOF fi done if test "$ac_cv_header_mysql_mysql_h" = "yes"; then MYSQL=yes else MYSQL= echo "*********************************************************" echo "Unable to locate mysqlclient headers (are they installed)" echo "*********************************************************" fi if test "$MYSQL" = "yes"; then if test -d /usr/lib/mysql ; then CPPFLAGS="$CPPFLAGS -L/usr/lib/mysql" LIBD="$LIBD -L/usr/lib/mysql" else if test -d /usr/local/lib/mysql ; then CPPFLAGS="$CPPFLAGS -L/usr/local/lib/mysql" LIBD="$LIBD -L/usr/local/lib/mysql" else if test -d /usr/local/mysql/lib ; then CPPFLAGS="$CPPFLAGS -L/usr/local/mysql/lib" LIBD="$LIBD -L/usr/local/mysql/lib" fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for mysql_init in -lmysqlclient" >&5 $as_echo_n "checking for mysql_init in -lmysqlclient... " >&6; } if ${ac_cv_lib_mysqlclient_mysql_init+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lmysqlclient $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char mysql_init (); int main () { return mysql_init (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_mysqlclient_mysql_init=yes else ac_cv_lib_mysqlclient_mysql_init=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_mysqlclient_mysql_init" >&5 $as_echo "$ac_cv_lib_mysqlclient_mysql_init" >&6; } if test "x$ac_cv_lib_mysqlclient_mysql_init" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBMYSQLCLIENT 1 _ACEOF LIBS="-lmysqlclient $LIBS" fi if test "$ac_cv_lib_mysqlclient_mysql_init" != "yes"; then MYSQL= echo "******************************************************" echo "Unable to locate mysqlclient library (is it installed)" echo "******************************************************" fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if Sqllite support was manually disabled" >&5 $as_echo_n "checking if Sqllite support was manually disabled... " >&6; } # Check whether --enable-sqllite-bundle was given. if test "${enable_sqllite_bundle+set}" = set; then : enableval=$enable_sqllite_bundle; ac_cv_sqllite_bundle=$enableval else ac_cv_sqllite_bundle="yes" fi if test "$ac_cv_sqllite_bundle" = "no"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes: disabled from the command-line" >&5 $as_echo "yes: disabled from the command-line" >&6; } SQLLITE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no: build if possible" >&5 $as_echo "no: build if possible" >&6; } for ac_header in sqlite3.h do : ac_fn_c_check_header_mongrel "$LINENO" "sqlite3.h" "ac_cv_header_sqlite3_h" "$ac_includes_default" if test "x$ac_cv_header_sqlite3_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_SQLITE3_H 1 _ACEOF fi done if test "$ac_cv_header_sqlite3_h" = "yes"; then SQLITE=yes else SQLITE= echo "*****************************************************" echo "Unable to locate sqlite3 headers (are they installed)" echo "*****************************************************" fi if test "$SQLITE" = "yes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sqlite3_open in -lsqlite3" >&5 $as_echo_n "checking for sqlite3_open in -lsqlite3... " >&6; } if ${ac_cv_lib_sqlite3_sqlite3_open+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsqlite3 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char sqlite3_open (); int main () { return sqlite3_open (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_sqlite3_sqlite3_open=yes else ac_cv_lib_sqlite3_sqlite3_open=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sqlite3_sqlite3_open" >&5 $as_echo "$ac_cv_lib_sqlite3_sqlite3_open" >&6; } if test "x$ac_cv_lib_sqlite3_sqlite3_open" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBSQLITE3 1 _ACEOF LIBS="-lsqlite3 $LIBS" fi if test "$ac_cv_lib_sqlite3_sqlite3_open" != "yes"; then SQLITE= echo "******************************************************" echo "Unable to locate sqlite3 library (is it installed)" echo "******************************************************" fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if Postgres support was manually disabled" >&5 $as_echo_n "checking if Postgres support was manually disabled... " >&6; } # Check whether --enable-postgres-bundle was given. if test "${enable_postgres_bundle+set}" = set; then : enableval=$enable_postgres_bundle; ac_cv_postgres_bundle=$enableval else ac_cv_postgres_bundle="yes" fi if test "$ac_cv_postgres_bundle" = "no"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes: disabled from the command-line" >&5 $as_echo "yes: disabled from the command-line" >&6; } POSTGRES= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no: build if possible" >&5 $as_echo "no: build if possible" >&6; } # Start POSTGRES checks POSTGRES= if test "$POSTGRES" = ""; then for ac_header in libpq-fe.h do : ac_fn_c_check_header_mongrel "$LINENO" "libpq-fe.h" "ac_cv_header_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header_libpq_fe_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPQ_FE_H 1 _ACEOF fi done if test "$ac_cv_header_libpq_fe_h" = "yes"; then POSTGRES=yes fi fi if test "$POSTGRES" = ""; then for ac_header in /usr/include/postgresql/libpq-fe.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/include/postgresql/libpq-fe.h" "ac_cv_header__usr_include_postgresql_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header__usr_include_postgresql_libpq_fe_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_INCLUDE_POSTGRESQL_LIBPQ_FE_H 1 _ACEOF fi done CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_include_postgresql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then for ac_header in /usr/include/postgresql/8.0/libpq-fe.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/include/postgresql/8.0/libpq-fe.h" "ac_cv_header__usr_include_postgresql_8_0_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header__usr_include_postgresql_8_0_libpq_fe_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_INCLUDE_POSTGRESQL_8_0_LIBPQ_FE_H 1 _ACEOF fi done CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_include_postgresql_8_0_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql/8.0" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then for ac_header in /usr/include/pgsql/libpq-fe.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/include/pgsql/libpq-fe.h" "ac_cv_header__usr_include_pgsql_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header__usr_include_pgsql_libpq_fe_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_INCLUDE_PGSQL_LIBPQ_FE_H 1 _ACEOF fi done CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/pgsql" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then for ac_header in /usr/local/include/pgsql/libpq-fe.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/local/include/pgsql/libpq-fe.h" "ac_cv_header__usr_local_include_pgsql_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header__usr_local_include_pgsql_libpq_fe_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_LOCAL_INCLUDE_PGSQL_LIBPQ_FE_H 1 _ACEOF fi done CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_local_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/include/pgsql" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then for ac_header in /usr/local/pgsql/include/libpq-fe.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/local/pgsql/include/libpq-fe.h" "ac_cv_header__usr_local_pgsql_include_libpq_fe_h" "$ac_includes_default" if test "x$ac_cv_header__usr_local_pgsql_include_libpq_fe_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_LOCAL_PGSQL_INCLUDE_LIBPQ_FE_H 1 _ACEOF fi done CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_local_pgsql_include_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/pgsql/include" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then echo "**************************************************************" echo "Unable to locate libpq (postgres) headers (are they installed)" echo "**************************************************************" fi if test "$POSTGRES" = "yes"; then # NICOLA - hack if test -d /usr/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/lib/pgsql" LIBD="$LIBD -L/usr/lib/pgsql" else if test -d /usr/local/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/local/lib/pgsql" LIBD="$LIBD -L/usr/local/lib/pgsql" else if test -d /usr/local/pgsql/lib ; then CPPFLAGS="$CPPFLAGS -L/usr/local/pgsql/lib" LIBD="$LIBD -L/usr/local/pgsql/lib" fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQfformat in -lpq" >&5 $as_echo_n "checking for PQfformat in -lpq... " >&6; } if ${ac_cv_lib_pq_PQfformat+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpq $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char PQfformat (); int main () { return PQfformat (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pq_PQfformat=yes else ac_cv_lib_pq_PQfformat=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQfformat" >&5 $as_echo "$ac_cv_lib_pq_PQfformat" >&6; } if test "x$ac_cv_lib_pq_PQfformat" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPQ 1 _ACEOF LIBS="-lpq $LIBS" fi if test "$ac_cv_lib_pq_PQfformat" != "yes"; then POSTGRES= { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQclear in -lpq" >&5 $as_echo_n "checking for PQclear in -lpq... " >&6; } if ${ac_cv_lib_pq_PQclear+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpq $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char PQclear (); int main () { return PQclear (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pq_PQclear=yes else ac_cv_lib_pq_PQclear=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQclear" >&5 $as_echo "$ac_cv_lib_pq_PQclear" >&6; } if test "x$ac_cv_lib_pq_PQclear" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPQ 1 _ACEOF LIBS="-lpq $LIBS" fi echo "******************************************************" if test "$ac_cv_lib_pq_PQclear" != "yes"; then echo "Unable to locate postgres pq library (is it installed)" else echo "Located postgres pq library, but it is too old to use!" fi echo "Perhaps you can try 'configure --with-postgres=dir=path'" echo "to point to the postgres version you wish to use." echo "******************************************************" else for ac_func in PQescapeStringConn do : ac_fn_c_check_func "$LINENO" "PQescapeStringConn" "ac_cv_func_PQescapeStringConn" if test "x$ac_cv_func_PQescapeStringConn" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_PQESCAPESTRINGCONN 1 _ACEOF fi done fi fi # End POSTGRES checks fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if ECPG (Old Postgres) support was manually disabled" >&5 $as_echo_n "checking if ECPG (Old Postgres) support was manually disabled... " >&6; } # Check whether --enable-ecpg-bundle was given. if test "${enable_ecpg_bundle+set}" = set; then : enableval=$enable_ecpg_bundle; ac_cv_ecpg_bundle=$enableval else ac_cv_ecpg_bundle="yes" fi if test "$ac_cv_ecpg_bundle" = "no"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes: disabled from the command-line" >&5 $as_echo "yes: disabled from the command-line" >&6; } ECPG= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no: build if possible" >&5 $as_echo "no: build if possible" >&6; } # Start ECPG checks ECPG= if test "$ECPG" = ""; then for ac_header in ecpglib.h do : ac_fn_c_check_header_mongrel "$LINENO" "ecpglib.h" "ac_cv_header_ecpglib_h" "$ac_includes_default" if test "x$ac_cv_header_ecpglib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_ECPGLIB_H 1 _ACEOF fi done if test "$ac_cv_header_ecpglib_h" = "yes"; then ECPG=yes fi fi if test "$ECPG" = ""; then for ac_header in /usr/include/postgresql/ecpglib.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/include/postgresql/ecpglib.h" "ac_cv_header__usr_include_postgresql_ecpglib_h" "$ac_includes_default" if test "x$ac_cv_header__usr_include_postgresql_ecpglib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_INCLUDE_POSTGRESQL_ECPGLIB_H 1 _ACEOF fi done if test "$ac_cv_header__usr_include_postgresql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql" ECPG=yes fi fi if test "$ECPG" = ""; then for ac_header in /usr/include/postgresql/8.0/ecpglib.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/include/postgresql/8.0/ecpglib.h" "ac_cv_header__usr_include_postgresql_8_0_ecpglib_h" "$ac_includes_default" if test "x$ac_cv_header__usr_include_postgresql_8_0_ecpglib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_INCLUDE_POSTGRESQL_8_0_ECPGLIB_H 1 _ACEOF fi done if test "$ac_cv_header__usr_include_postgresql_8_0_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql/8.0" ECPG=yes fi fi if test "$ECPG" = ""; then for ac_header in /usr/include/pgsql/ecpglib.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/include/pgsql/ecpglib.h" "ac_cv_header__usr_include_pgsql_ecpglib_h" "$ac_includes_default" if test "x$ac_cv_header__usr_include_pgsql_ecpglib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_INCLUDE_PGSQL_ECPGLIB_H 1 _ACEOF fi done if test "$ac_cv_header__usr_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/pgsql" ECPG=yes fi fi if test "$ECPG" = ""; then for ac_header in /usr/local/include/pgsql/ecpglib.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/local/include/pgsql/ecpglib.h" "ac_cv_header__usr_local_include_pgsql_ecpglib_h" "$ac_includes_default" if test "x$ac_cv_header__usr_local_include_pgsql_ecpglib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_LOCAL_INCLUDE_PGSQL_ECPGLIB_H 1 _ACEOF fi done if test "$ac_cv_header__usr_local_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/include/pgsql" ECPG=yes fi fi if test "$ECPG" = ""; then for ac_header in /usr/local/pgsql/include/ecpglib.h do : ac_fn_c_check_header_mongrel "$LINENO" "/usr/local/pgsql/include/ecpglib.h" "ac_cv_header__usr_local_pgsql_include_ecpglib_h" "$ac_includes_default" if test "x$ac_cv_header__usr_local_pgsql_include_ecpglib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE__USR_LOCAL_PGSQL_INCLUDE_ECPGLIB_H 1 _ACEOF fi done if test "$ac_cv_header__usr_local_pgsql_include_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/pgsql/include" ECPG=yes fi fi if test "$ECPG" = ""; then echo "*************************************************************" echo "Unable to locate ecpg (postgres) headers (are they installed)" echo "*************************************************************" fi if test "$ECPG" = "yes"; then # NICOLA - hack if test -d /usr/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/lib/pgsql" LIBD="$LIBD -L/usr/lib/pgsql" else if test -d /usr/local/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/local/lib/pgsql" LIBD="$LIBD -L/usr/local/lib/pgsql" else if test -d /usr/local/pgsql/lib ; then CPPFLAGS="$CPPFLAGS -L/usr/local/pgsql/lib" LIBD="$LIBD -L/usr/local/pgsql/lib" fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PQfformat in -lpq" >&5 $as_echo_n "checking for PQfformat in -lpq... " >&6; } if ${ac_cv_lib_pq_PQfformat+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lpq $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char PQfformat (); int main () { return PQfformat (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_pq_PQfformat=yes else ac_cv_lib_pq_PQfformat=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pq_PQfformat" >&5 $as_echo "$ac_cv_lib_pq_PQfformat" >&6; } if test "x$ac_cv_lib_pq_PQfformat" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBPQ 1 _ACEOF LIBS="-lpq $LIBS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ECPGconnect in -lecpg" >&5 $as_echo_n "checking for ECPGconnect in -lecpg... " >&6; } if ${ac_cv_lib_ecpg_ECPGconnect+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lecpg $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char ECPGconnect (); int main () { return ECPGconnect (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_ecpg_ECPGconnect=yes else ac_cv_lib_ecpg_ECPGconnect=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ecpg_ECPGconnect" >&5 $as_echo "$ac_cv_lib_ecpg_ECPGconnect" >&6; } if test "x$ac_cv_lib_ecpg_ECPGconnect" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBECPG 1 _ACEOF LIBS="-lecpg $LIBS" fi if test "$ac_cv_lib_ecpg_ECPGconnect" != "yes"; then ECPG= echo "********************************************************" echo "Unable to locate postgres ecpg library (is it installed)" echo "Perhaps you can try 'configure --with-postgres=dir=path'" echo "to point to the postgres version you wish to use." echo "********************************************************" fi fi # End ECPG checks fi ORACLE_HOME= if test "$JDBC" = "yes"; then BUNDLE="The JDBC backend bundle will be built" else BUNDLE="The JDBC backend bundle will NOT be built" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${BUNDLE}" >&5 $as_echo "${BUNDLE}" >&6; } if test "$MYSQL" = "yes"; then BUNDLE="The MySQL backend bundle will be built" else BUNDLE="The MySQL backend bundle will NOT be built" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${BUNDLE}" >&5 $as_echo "${BUNDLE}" >&6; } if test "$SQLITE" = "yes"; then BUNDLE="The SQLite backend bundle will be built" else BUNDLE="The SQLite backend bundle will NOT be built" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${BUNDLE}" >&5 $as_echo "${BUNDLE}" >&6; } if test "$POSTGRES" = "yes"; then BUNDLE="The Postgres backend bundle will be built" else BUNDLE="The Postgres backend bundle will NOT be built" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${BUNDLE}" >&5 $as_echo "${BUNDLE}" >&6; } if test "$ECPG" = "yes"; then BUNDLE="The ECPG backend bundle will be built" else BUNDLE="The ECPG backend bundle will NOT be built" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${BUNDLE}" >&5 $as_echo "${BUNDLE}" >&6; } if test "$ORACLE" = "yes"; then BUNDLE="The Oracle backend bundle will be built" else BUNDLE="The Oracle backend bundle will NOT be built" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${BUNDLE}" >&5 $as_echo "${BUNDLE}" >&6; } ac_config_files="$ac_config_files config.make" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by $as_me, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Report bugs to the package provider." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ config.status configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "config.make") CONFIG_FILES="$CONFIG_FILES config.make" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi SQLClient-1.9.0/configure.ac000066400000000000000000000377661436027104400156310ustar00rootroot00000000000000dnl Process this file with autoconf to produce configure. AC_INIT(SQLClient.h) AC_CONFIG_HEADER(config.h) if test -z "$GNUSTEP_MAKEFILES"; then GNUSTEP_MAKEFILES=`gnustep-config --variable=GNUSTEP_MAKEFILES 2>/dev/null` export GNUSTEP_MAKEFILES fi if test -z "$GNUSTEP_MAKEFILES"; then AC_MSG_ERROR([You must have the gnustep-make package installed and set up the GNUSTEP_MAKEFILES environment variable to contain the path to the makefiles directory before configuring!]) else . $GNUSTEP_MAKEFILES/GNUstep.sh fi if test "x$GNUSTEP_HOST_OS" = "x"; then GNUSTEP_HOST_OS=`gnustep-config --variable=GNUSTEP_HOST_OS` GNUSTEP_HOST_CPU=`gnustep-config --variable=GNUSTEP_HOST_CPU` fi #-------------------------------------------------------------------- AC_ARG_WITH(additional-include, [ --with-additional-include=flags Specifies additional include compiler flags to use. If configure can not find your database library headers, you may want to use this flag to help it find them. For example: --with-additional-include=-I/usr/local/include ], additional_include="$withval", additional_include="no") if test "$additional_include" != "no"; then CPPFLAGS="$CPPFLAGS $additional_include" INCD="$INCD $additional_include" fi AC_ARG_WITH(additional-lib, [ --with-additional-lib=flags Specifies additional library compiler flags to use. If configure can not find your database libraries, you may want to use this flag to help it find them. For example: --with-additional-lib=-L/usr/local/lib/mysql ], additional_lib="$withval", additional_lib="no") if test "$additional_lib" != "no"; then LDFLAGS="$LDFLAGS $additional_lib" LIBD="$LIBD $additional_lib" fi AC_ARG_WITH(postgres-dir, [ --with-postgres-dir=PATH Specifies the postgres installation dir; configure will add the appropriate additional include and lib flags. Useful when you installed postgres in some unusual place and want to help configure find it. For example: --with-postgres-dir=/usr/local/pgsql (which is equivalent to --with-additional-include=-L/usr/local/pgsql/include --with-additional-lib=-L/usr/local/pgsql/lib) ], postgres_topdir="$withval", postgres_topdir="no") if test "$postgres_topdir" != "no"; then CPPFLAGS="$CPPFLAGS -I$postgres_topdir/include -L$postgres_topdir/lib" INCD="$INCD -I$postgres_topdir/include" LIBD="$LIBD -L$postgres_topdir/lib" else PGINC=`pg_config --includedir` if test "$PGINC" != ""; then CPPFLAGS="$CPPFLAGS -I$PGINC" INCD="$INCD -I$PGINC" fi PGLIB=`pg_config --libdir` if test "$PGLIB" != ""; then CPPFLAGS="$CPPFLAGS -L$PGLIB" LIBD="$LIBD -I$PGLIB" fi fi # Call AC_CHECK_HEADERS here as a workaround for a configure bug/feature # which messes up all subsequent tests if the first occurrence in the # file does not get called ... as would otherwise be the case if jdbc # support is disabled. AC_CHECK_HEADERS(stdio.h) AC_MSG_CHECKING([if Jdbc support was manually disabled]) AC_ARG_ENABLE(jdbc-bundle, [ --disable-jdbc-bundle Disable creating the Jdbc bundle. Use this option to force the Jdbc bundle not to be built even if the Jdbc libraries look like being present. ], ac_cv_jdbc_bundle=$enableval, ac_cv_jdbc_bundle="yes") if test "$ac_cv_jdbc_bundle" = "no"; then AC_MSG_RESULT([yes: disabled from the command-line]) else AC_MSG_RESULT([no: build if possible]) # Get likely subdirectory for system specific java include case "$GNUSTEP_HOST_OS" in bsdi*) _JNI_SUBDIR="bsdos";; linux*) _JNI_SUBDIR="linux";; osf*) _JNI_SUBDIR="alpha";; solaris*) _JNI_SUBDIR="solaris";; mingw*) _JNI_SUBDIR="win32";; cygwin*) _JNI_SUBDIR="win32";; *) _JNI_SUBDIR="genunix";; esac AC_ARG_WITH(jre-architecture, [ --with-jre-architecture=value Specifies the CPU architecture to use for the JRE (only used when building the JDBC module). Example values are i386, amd64 and sparc. ], jre_architecture="$withval", jre_architecture="") save_LIBS="$LIBS" save_CFLAGS="$CFLAGS" save_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS -I$JAVA_HOME/include -I$JAVA_HOME/include/$_JNI_SUBDIR" AC_CHECK_HEADERS(jni.h) if test "$ac_cv_header_jni_h" = "yes"; then JDBC_VM_LIBS="-ljvm" jre_lib="$JAVA_HOME/jre/lib" if test "$jre_architecture" = ""; then # If on a 32/64bit system and compiling for the 64bit model # adjust the cpu type to be the 64bit version case "$CFLAGS" in *-m64*) if test "$GNUSTEP_HOST_CPU" = "ix86"; then _CPU="x86_64" else _CPU="$GNUSTEP_HOST_CPU" fi;; *) _CPU="$GNUSTEP_HOST_CPU";; esac case "$_CPU" in ix86) JAVA_CPU=i386;; x86_64) JAVA_CPU=amd64;; sparc) JAVA_CPU=sparc;; *) JAVA_CPU=i386;; esac else JAVA_CPU="$jre_architecture" fi jre_cpu="$jre_lib/$JAVA_CPU" JDBC_VM_LIBDIRS="-L$jre_cpu/server" CFLAGS="$CFLAGS $JDBC_VM_LIBDIRS" AC_CHECK_LIB(jvm,JNI_CreateJavaVM) if test "$ac_cv_lib_jvm_JNI_CreateJavaVM" = "yes"; then INCD="$INCD -I$JAVA_HOME/include -I$JAVA_HOME/include/$_JNI_SUBDIR" JDBC=yes else JDBC= JDBC_VM_LIBS= JDBC_VM_LIBDIRS= echo "**********************************************" echo "Unable to locate jvm library (is it installed)" echo "**********************************************" fi else JDBC= JDBC_VM_LIBS= JDBC_VM_LIBDIRS= echo "*********************************************" echo "Unable to locate jni header (is it installed)" echo "*********************************************" fi AC_SUBST(JDBC) AC_SUBST(JDBC_VM_LIBS) AC_SUBST(JDBC_VM_LIBDIRS) LIBS="$save_LIBS" CFLAGS="$save_CFLAGS" CPPFLAGS="$save_CPPFLAGS" fi AC_MSG_CHECKING([if Mysql support was manually disabled]) AC_ARG_ENABLE(mysql-bundle, [ --disable-mysql-bundle Disable creating the Mysql bundle. Use this option to force the Mysql bundle not to be built even if the Mysql libraries look like being present. ], ac_cv_mysql_bundle=$enableval, ac_cv_mysql_bundle="yes") if test "$ac_cv_mysql_bundle" = "no"; then AC_MSG_RESULT([yes: disabled from the command-line]) MYSQL= else AC_MSG_RESULT([no: build if possible]) AC_CHECK_HEADERS(mysql/mysql.h) if test "$ac_cv_header_mysql_mysql_h" = "yes"; then MYSQL=yes else MYSQL= echo "*********************************************************" echo "Unable to locate mysqlclient headers (are they installed)" echo "*********************************************************" fi if test "$MYSQL" = "yes"; then if test -d /usr/lib/mysql ; then CPPFLAGS="$CPPFLAGS -L/usr/lib/mysql" LIBD="$LIBD -L/usr/lib/mysql" else if test -d /usr/local/lib/mysql ; then CPPFLAGS="$CPPFLAGS -L/usr/local/lib/mysql" LIBD="$LIBD -L/usr/local/lib/mysql" else if test -d /usr/local/mysql/lib ; then CPPFLAGS="$CPPFLAGS -L/usr/local/mysql/lib" LIBD="$LIBD -L/usr/local/mysql/lib" fi fi fi AC_CHECK_LIB(mysqlclient,mysql_init) if test "$ac_cv_lib_mysqlclient_mysql_init" != "yes"; then MYSQL= echo "******************************************************" echo "Unable to locate mysqlclient library (is it installed)" echo "******************************************************" fi fi fi AC_SUBST(MYSQL) AC_MSG_CHECKING([if Sqllite support was manually disabled]) AC_ARG_ENABLE(sqllite-bundle, [ --disable-sqllite-bundle Disable creating the Sqllite bundle. Use this option to force the Sqllite bundle not to be built even if the Sqllite libraries look like being present. ], ac_cv_sqllite_bundle=$enableval, ac_cv_sqllite_bundle="yes") if test "$ac_cv_sqllite_bundle" = "no"; then AC_MSG_RESULT([yes: disabled from the command-line]) SQLLITE= else AC_MSG_RESULT([no: build if possible]) AC_CHECK_HEADERS(sqlite3.h) if test "$ac_cv_header_sqlite3_h" = "yes"; then SQLITE=yes else SQLITE= echo "*****************************************************" echo "Unable to locate sqlite3 headers (are they installed)" echo "*****************************************************" fi if test "$SQLITE" = "yes"; then AC_CHECK_LIB(sqlite3,sqlite3_open) if test "$ac_cv_lib_sqlite3_sqlite3_open" != "yes"; then SQLITE= echo "******************************************************" echo "Unable to locate sqlite3 library (is it installed)" echo "******************************************************" fi fi fi AC_SUBST(SQLITE) AC_MSG_CHECKING([if Postgres support was manually disabled]) AC_ARG_ENABLE(postgres-bundle, [ --disable-postgres-bundle Disable creating the Postgres bundle. Use this option to force the Postgres bundle not to be built even if the Postgres libraries look like being present. ], ac_cv_postgres_bundle=$enableval, ac_cv_postgres_bundle="yes") if test "$ac_cv_postgres_bundle" = "no"; then AC_MSG_RESULT([yes: disabled from the command-line]) POSTGRES= else AC_MSG_RESULT([no: build if possible]) # Start POSTGRES checks POSTGRES= if test "$POSTGRES" = ""; then AC_CHECK_HEADERS(libpq-fe.h) if test "$ac_cv_header_libpq_fe_h" = "yes"; then POSTGRES=yes fi fi if test "$POSTGRES" = ""; then AC_CHECK_HEADERS(/usr/include/postgresql/libpq-fe.h) CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_include_postgresql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then AC_CHECK_HEADERS(/usr/include/postgresql/8.0/libpq-fe.h) CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_include_postgresql_8_0_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql/8.0" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then AC_CHECK_HEADERS(/usr/include/pgsql/libpq-fe.h) CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/pgsql" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then AC_CHECK_HEADERS(/usr/local/include/pgsql/libpq-fe.h) CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_local_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/include/pgsql" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then AC_CHECK_HEADERS(/usr/local/pgsql/include/libpq-fe.h) CPPFLAGS="$save_CPPFLAGS" if test "$ac_cv_header__usr_local_pgsql_include_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/pgsql/include" POSTGRES=yes fi fi if test "$POSTGRES" = ""; then echo "**************************************************************" echo "Unable to locate libpq (postgres) headers (are they installed)" echo "**************************************************************" fi if test "$POSTGRES" = "yes"; then # NICOLA - hack if test -d /usr/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/lib/pgsql" LIBD="$LIBD -L/usr/lib/pgsql" else if test -d /usr/local/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/local/lib/pgsql" LIBD="$LIBD -L/usr/local/lib/pgsql" else if test -d /usr/local/pgsql/lib ; then CPPFLAGS="$CPPFLAGS -L/usr/local/pgsql/lib" LIBD="$LIBD -L/usr/local/pgsql/lib" fi fi fi AC_CHECK_LIB(pq,PQfformat) if test "$ac_cv_lib_pq_PQfformat" != "yes"; then POSTGRES= AC_CHECK_LIB(pq,PQclear) echo "******************************************************" if test "$ac_cv_lib_pq_PQclear" != "yes"; then echo "Unable to locate postgres pq library (is it installed)" else echo "Located postgres pq library, but it is too old to use!" fi echo "Perhaps you can try 'configure --with-postgres=dir=path'" echo "to point to the postgres version you wish to use." echo "******************************************************" else AC_CHECK_FUNCS(PQescapeStringConn) fi fi # End POSTGRES checks fi AC_SUBST(POSTGRES) AC_MSG_CHECKING([if ECPG (Old Postgres) support was manually disabled]) AC_ARG_ENABLE(ecpg-bundle, [ --disable-ecpg-bundle Disable creating the ECPG bundle. Use this option to force the ECPG bundle not to be built even if the Postgres libraries look like being present. ], ac_cv_ecpg_bundle=$enableval, ac_cv_ecpg_bundle="yes") if test "$ac_cv_ecpg_bundle" = "no"; then AC_MSG_RESULT([yes: disabled from the command-line]) ECPG= else AC_MSG_RESULT([no: build if possible]) # Start ECPG checks ECPG= if test "$ECPG" = ""; then AC_CHECK_HEADERS(ecpglib.h) if test "$ac_cv_header_ecpglib_h" = "yes"; then ECPG=yes fi fi if test "$ECPG" = ""; then AC_CHECK_HEADERS(/usr/include/postgresql/ecpglib.h) if test "$ac_cv_header__usr_include_postgresql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql" ECPG=yes fi fi if test "$ECPG" = ""; then AC_CHECK_HEADERS(/usr/include/postgresql/8.0/ecpglib.h) if test "$ac_cv_header__usr_include_postgresql_8_0_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/postgresql/8.0" ECPG=yes fi fi if test "$ECPG" = ""; then AC_CHECK_HEADERS(/usr/include/pgsql/ecpglib.h) if test "$ac_cv_header__usr_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/include/pgsql" ECPG=yes fi fi if test "$ECPG" = ""; then AC_CHECK_HEADERS(/usr/local/include/pgsql/ecpglib.h) if test "$ac_cv_header__usr_local_include_pgsql_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/include/pgsql" ECPG=yes fi fi if test "$ECPG" = ""; then AC_CHECK_HEADERS(/usr/local/pgsql/include/ecpglib.h) if test "$ac_cv_header__usr_local_pgsql_include_libpq_fe_h" = "yes"; then INCD="$INCD -I/usr/local/pgsql/include" ECPG=yes fi fi if test "$ECPG" = ""; then echo "*************************************************************" echo "Unable to locate ecpg (postgres) headers (are they installed)" echo "*************************************************************" fi if test "$ECPG" = "yes"; then # NICOLA - hack if test -d /usr/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/lib/pgsql" LIBD="$LIBD -L/usr/lib/pgsql" else if test -d /usr/local/lib/pgsql ; then CPPFLAGS="$CPPFLAGS -L/usr/local/lib/pgsql" LIBD="$LIBD -L/usr/local/lib/pgsql" else if test -d /usr/local/pgsql/lib ; then CPPFLAGS="$CPPFLAGS -L/usr/local/pgsql/lib" LIBD="$LIBD -L/usr/local/pgsql/lib" fi fi fi AC_CHECK_LIB(pq,PQfformat) AC_CHECK_LIB(ecpg,ECPGconnect) if test "$ac_cv_lib_ecpg_ECPGconnect" != "yes"; then ECPG= echo "********************************************************" echo "Unable to locate postgres ecpg library (is it installed)" echo "Perhaps you can try 'configure --with-postgres=dir=path'" echo "to point to the postgres version you wish to use." echo "********************************************************" fi fi # End ECPG checks fi AC_SUBST(ECPG) ORACLE_HOME= AC_SUBST(ORACLE_HOME) AC_SUBST(INCD) AC_SUBST(LIBD) AC_SUBST(LIBS) if test "$JDBC" = "yes"; then BUNDLE="The JDBC backend bundle will be built" else BUNDLE="The JDBC backend bundle will NOT be built" fi AC_MSG_RESULT(${BUNDLE}) if test "$MYSQL" = "yes"; then BUNDLE="The MySQL backend bundle will be built" else BUNDLE="The MySQL backend bundle will NOT be built" fi AC_MSG_RESULT(${BUNDLE}) if test "$SQLITE" = "yes"; then BUNDLE="The SQLite backend bundle will be built" else BUNDLE="The SQLite backend bundle will NOT be built" fi AC_MSG_RESULT(${BUNDLE}) if test "$POSTGRES" = "yes"; then BUNDLE="The Postgres backend bundle will be built" else BUNDLE="The Postgres backend bundle will NOT be built" fi AC_MSG_RESULT(${BUNDLE}) if test "$ECPG" = "yes"; then BUNDLE="The ECPG backend bundle will be built" else BUNDLE="The ECPG backend bundle will NOT be built" fi AC_MSG_RESULT(${BUNDLE}) if test "$ORACLE" = "yes"; then BUNDLE="The Oracle backend bundle will be built" else BUNDLE="The Oracle backend bundle will NOT be built" fi AC_MSG_RESULT(${BUNDLE}) AC_OUTPUT(config.make) SQLClient-1.9.0/testECPG.m000066400000000000000000000064321436027104400151210ustar00rootroot00000000000000/** Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import "SQLClient.h" int main() { NSAutoreleasePool *pool = [NSAutoreleasePool new]; SQLClient *db; NSUserDefaults *defs; NSMutableArray *records; SQLRecord *record; unsigned char dbuf[256]; unsigned int i; NSData *data; defs = [NSUserDefaults standardUserDefaults]; [defs registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: @"template1@localhost", @"Database", @"postgres", @"User", @"postgres", @"Password", @"ECPG", @"ServerType", nil], @"test", nil], @"SQLClientReferences", nil] ]; for (i = 0; i < 256; i++) { dbuf[i] = i; } data = [NSData dataWithBytes: dbuf length: i]; db = [SQLClient clientWithConfiguration: nil name: @"test"]; [db setDurationLogging: 0]; NS_DURING [db execute: @"drop table xxx", nil]; NS_HANDLER NS_ENDHANDLER [db execute: @"create table xxx ( " @"k char(40), " @"char1 char(1), " @"boolval BOOL, " @"intval int, " @"when1 timestamp with time zone, " @"when2 timestamp, " @"b bytea" @")", nil]; [db execute: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (" @"'hello', " @"'X', " @"TRUE, " @"1, " @"CURRENT_TIMESTAMP, " @"CURRENT_TIMESTAMP, ", data, @")", nil]; [db execute: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (" @"'hello', " @"'X', " @"TRUE, " @"1, ", [NSDate date], @", ", [NSDate date], @", ", [NSData dataWithBytes: "" length: 0], @")", nil]; records = [db query: @"select * from xxx", nil]; [db execute: @"drop table xxx", nil]; if ([records count] != 2) { NSLog(@"Expected 2 records but got %" PRIuPTR "", [records count]); } else { record = [records objectAtIndex: 0]; if ([[record objectForKey: @"b"] isEqual: data] == NO) { NSLog(@"Retrieved data does not match saved data %@ %@", data, [record objectForKey: @"b"]); } record = [records objectAtIndex: 1]; if ([[record objectForKey: @"b"] isEqual: [NSData data]] == NO) { NSLog(@"Retrieved empty data does not match saved data"); } } NSLog(@"Records - %@", records); [pool release]; return 0; } SQLClient-1.9.0/testJDBC.m000066400000000000000000000211521436027104400151010ustar00rootroot00000000000000/** Copyright (C) 2006 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: August 2006 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date: 2006-05-25 12:34:03 +0100 (Thu, 25 May 2006) $ $Revision: 22982 $ */ #import #import #import "SQLClient.h" int main() { NSAutoreleasePool *pool = [NSAutoreleasePool new]; SQLClient *db; NSUserDefaults *defs; NSMutableArray *records; SQLRecord *record; unsigned char dbuf[256]; unsigned int i; NSData *data; NSString *name; defs = [NSUserDefaults standardUserDefaults]; [defs registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: @"org.postgresql.Driver:jdbc:postgresql://localhost/template1", @"Database", @"postgres", @"User", @"postgres", @"Password", @"JDBC", @"ServerType", nil], @"test", nil], @"SQLClientReferences", nil] ]; db = [SQLClient clientWithConfiguration: nil name: @"test"]; [db connect]; if ((name = [defs stringForKey: @"Producer"]) != nil) { NS_DURING { [db execute: @"CREATE TABLE Queue ( " @"ID SERIAL, " @"Consumer CHAR(40) NOT NULL, " @"ServiceID INT NOT NULL, " @"Status CHAR(1) DEFAULT 'Q' NOT NULL, " @"Delivery TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, " @"Reference CHAR(128), " @"Destination CHAR(15) NOT NULL, " @"Payload CHAR(250) DEFAULT '' NOT NULL" @")", nil]; [db execute: @"CREATE UNIQUE INDEX QueueIDX ON Queue (ID)", nil]; [db execute: @"CREATE INDEX ServiceIDX ON Queue (ServiceID)", nil]; [db execute: @"CREATE INDEX ConsumerIDX ON Queue (Consumer,Status,Delivery)", nil]; [db execute: @"CREATE INDEX ReferenceIDX ON Queue (Reference,Consumer)", nil]; } NS_HANDLER { NSLog(@"%@", localException); } NS_ENDHANDLER NSLog(@"Start producing"); for (i = 0; i < 100000; i++) { NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSString *destination = [NSString stringWithFormat: @"%d", i]; NSString *sid = [NSString stringWithFormat: @"%d", i%100]; [db execute: @"INSERT INTO Queue (Consumer, Destination, ServiceID, Payload) VALUES (", [db quote: name], @", ", [db quote: destination], @", ", sid, @", ", @"'helo there'", @")", nil]; [arp release]; } NSLog(@"End producing"); } else if ((name = [defs stringForKey: @"Consumer"]) != nil) { NSLog(@"Start consuming"); for (i = 0; i < 100000;) { NSAutoreleasePool *arp = [NSAutoreleasePool new]; unsigned count; int j; [db begin]; records = [db query: @"SELECT * FROM Queue WHERE Consumer = ", [db quote: name], @" AND Status = 'Q' AND Delivery < CURRENT_TIMESTAMP", @" ORDER BY Delivery LIMIT 1000 FOR UPDATE" , nil]; count = [records count]; if (count == 0) { [db commit]; [NSThread sleepForTimeInterval: 1.0]; [db begin]; records = [db query: @"SELECT * FROM Queue WHERE Consumer = ", [db quote: name], @" AND Status = 'Q' AND Delivery < CURRENT_TIMESTAMP", @" ORDER BY Delivery LIMIT 50 FOR UPDATE" , nil]; count = [records count]; if (count == 0) { break; } } for (j = 0; j < count; j++) { SQLRecord *record = [records objectAtIndex: j]; NSString *reference = [record objectForKey: @"ID"]; [db execute: @"UPDATE Queue SET Status = 'S', Reference = ", [db quote: reference], @" WHERE ID = ", [record objectForKey: @"ID"], nil]; [db execute: @"UPDATE Queue SET Status = 'D'", @" WHERE Consumer = ", [db quote: name], @" AND Reference = ", [db quote: reference], nil]; } [db commit]; i += count; [arp release]; } NSLog(@"End consuming (%d records)", i); /* [db execute: @"DROP INDEX ReferenceIDX", nil]; [db execute: @"DROP INDEX ServiceIDX", nil]; [db execute: @"DROP INDEX ConsumerIDX", nil]; [db execute: @"DROP INDEX QueueIDX", nil]; [db execute: @"DROP TABLE Queue", nil]; */ } else { SQLTransaction *t; NSString *oddChars; NSString *nonLatin; id r0; id r1; oddChars = @"'a\\b'c\r\nd'\\ed\\"; nonLatin = [[NSString stringWithCString: "\"\\U2A11\""] propertyList]; for (i = 0; i < 256; i++) { dbuf[i] = i; } data = [NSData dataWithBytes: dbuf length: i]; NS_DURING [db execute: @"drop table xxx", nil]; NS_HANDLER NS_ENDHANDLER [db setDurationLogging: 0]; [db begin]; [db execute: @"create table xxx ( " @"k char(40), " @"char1 char(1), " @"boolval BOOL, " @"intval int, " @"when1 timestamp with time zone, " @"when2 timestamp, " @"b bytea" @")", nil]; [db execute: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (" @"'hello', " @"'X', " @"TRUE, " @"1, " @"CURRENT_TIMESTAMP, " @"CURRENT_TIMESTAMP, ", data, @")", nil]; [db execute: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (" @"'hello', " @"'X', " @"TRUE, " @"1, ", [NSDate date], @", ", [NSDate date], @", ", [NSData dataWithBytes: "" length: 0], @")", nil]; [db execute: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (", [db quote: oddChars], @", ", [db quote: nonLatin], @",TRUE, " @"1, ", [NSDate date], @", ", [NSDate date], @", ", [NSData dataWithBytes: "" length: 0], @")", nil]; [db commit]; r0 = [db cache: 1 query: @"select * from xxx", nil]; r1 = [db cache: 1 query: @"select * from xxx", nil]; NSCAssert([r0 lastObject] == [r1 lastObject], @"Cache failed"); [NSThread sleepForTimeInterval: 2.0]; records = [db cache: 1 query: @"select * from xxx", nil]; NSCAssert([r0 lastObject] != [records lastObject], @"Lifetime failed"); [db execute: @"drop table xxx", nil]; if ([records count] != 3) { NSLog(@"Expected 3 records but got %"PRIuPTR, [records count]); } else { record = [records objectAtIndex: 0]; if ([[record objectForKey: @"b"] isEqual: data] == NO) { NSLog(@"Retrieved data does not match saved data %@ %@", data, [record objectForKey: @"b"]); } record = [records objectAtIndex: 1]; if ([[record objectForKey: @"b"] isEqual: [NSData data]] == NO) { NSLog(@"Retrieved empty data does not match saved data"); } record = [records objectAtIndex: 2]; if ([[record objectForKey: @"char1"] isEqual: nonLatin] == NO) { NSLog(@"Retrieved non-latin does not match saved string"); } if ([[record objectForKey: @"k"] isEqual: oddChars] == NO) { NSLog(@"Retrieved odd chars does not match saved string"); } } [db execute: @"create table xxx ( " @"k char(40), " @"char1 char(1), " @"boolval BOOL, " @"intval int, " @"when1 timestamp with time zone, " @"when2 timestamp, " @"b bytea" @")", nil]; t = [db transaction]; [t add: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (", [db quote: oddChars], @", ", [db quote: nonLatin], @",TRUE, " @"0, ", [NSDate date], @", ", [NSDate date], @", ", [db quote: nil], @")", nil]; [t add: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (", [db quote: oddChars], @", ", [db quote: nonLatin], @",TRUE, " @"1, ", [NSDate date], @", ", [NSDate date], @", ", [db quote: nil], @")", nil]; [t add: @"insert into xxx " @"(k, char1, boolval, intval, when1, when2, b) " @"values (", [db quote: oddChars], @", ", [db quote: nonLatin], @",TRUE, " @"2, ", [NSDate date], @", ", [NSDate date], @", ", [db quote: nil], @")", nil]; [t execute]; [db execute: @"drop table xxx", nil]; NSLog(@"Records - %@", [GSCache class]); } [pool release]; return 0; } SQLClient-1.9.0/testMySQL.m000066400000000000000000000063461436027104400153540ustar00rootroot00000000000000/** Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import "SQLClient.h" int main() { NSAutoreleasePool *pool = [NSAutoreleasePool new]; SQLClient *db; NSUserDefaults *defs; NSMutableArray *records; SQLRecord *record; unsigned char dbuf[256]; unsigned int i; NSData *data; defs = [NSUserDefaults standardUserDefaults]; [defs registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: @"test", @"Database", @"", @"User", @"", @"Password", @"MySQL", @"ServerType", nil], @"test", nil], @"SQLClientReferences", nil] ]; for (i = 0; i < 256; i++) { dbuf[i] = i; } data = [NSData dataWithBytes: dbuf length: i]; db = [SQLClient clientWithConfiguration: nil name: @"test"]; [db setDurationLogging: 0]; NS_DURING [db execute: @"drop table xxx", nil]; NS_HANDLER NS_ENDHANDLER [db execute: @"create table xxx ( " @"k char(40), " @"char1 char(1), " @"intval int, " @"realval real, " @"b blob, " @"when2 timestamp" @")", nil]; [db execute: @"insert into xxx " @"(k, char1, intval, realval, b, when2) " @"values (" @"'hello', " @"'X', " @"1, " @"9.99, ", data, @", ", @"CURRENT_TIMESTAMP", @")", nil]; [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: 1]]; [db execute: @"insert into xxx " @"(k, char1, intval, realval, b, when2) " @"values (" @"'hello', " @"'X', " @"1, ", @"12345.6789, ", [NSData dataWithBytes: "" length: 0], @", ", [NSDate date], @")", nil]; records = [db query: @"select * from xxx", nil]; [db execute: @"drop table xxx", nil]; if ([records count] != 2) { NSLog(@"Expected 2 records but got %" PRIuPTR "", [records count]); } else { record = [records objectAtIndex: 0]; if ([[record objectForKey: @"b"] isEqual: data] == NO) { NSLog(@"Retrieved data does not match saved data %@ %@", data, [record objectForKey: @"b"]); } record = [records objectAtIndex: 1]; if ([[record objectForKey: @"b"] isEqual: [NSData data]] == NO) { NSLog(@"Retrieved empty data does not match saved data"); } } NSLog(@"Records - %@", records); [pool release]; return 0; } SQLClient-1.9.0/testPostgres.m000066400000000000000000000355671436027104400162240ustar00rootroot00000000000000/** Copyright (C) 2004 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2004 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import #import "SQLClient.h" @interface Logger : NSObject - (void) notified: (NSNotification*)n; @end @implementation Logger - (void) notified: (NSNotification*)n { NSLog(@"Received %@", n); } @end int main() { NSAutoreleasePool *pool = [NSAutoreleasePool new]; SQLClientPool *sp; SQLClient *db; NSUserDefaults *defs; NSMutableArray *records; SQLRecord *record; unsigned char dbuf[256]; unsigned int i; NSData *data; NSString *name; Logger *l; defs = [NSUserDefaults standardUserDefaults]; [defs registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: @"template1@localhost", @"Database", @"postgres", @"User", @"postgres", @"Password", @"Postgres", @"ServerType", nil], @"test", nil], @"SQLClientReferences", nil] ]; sp = [[[SQLClientPool alloc] initWithConfiguration: nil name: @"test" max: 2 min: 1] autorelease]; #if 0 { NSAutoreleasePool *p; NSAutoreleasePool *q; SQLClient *c0; SQLClient *c1; [sp setDebugging: 4]; p = [NSAutoreleasePool new]; c0 = [sp provideClientExclusive]; c1 = [sp provideClientExclusive]; NSLog(@"Got two clients from pool"); [c0 connect]; [c1 connect]; NSLog(@"Now putting clients back in pool again"); [sp swallowClient: c0]; [sp swallowClient: c1]; NSLog(@"And emptying autorelease pool"); [p release]; p = [NSAutoreleasePool new]; [sp setPurgeAll: 60 min: 1]; [NSThread sleepForTimeInterval: 1.0]; NSLog(@"Expecting purge to disconnect one client"); [sp purge]; c0 = [sp provideClientExclusive]; c1 = [sp provideClientExclusive]; NSLog(@"Expecting connected: %@", [c0 connected] ? @"YES" : @"NO"); NSLog(@"Expecting not connected: %@", [c1 connected] ? @"NO" : @"YES"); NSLog(@"Pool has provided both it's clients ... now try for another with a 15 second timeout"); [sp provideClientBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 15.0] exclusive: YES]; NSLog(@"Emptying autorelease pool ... clients should be put back in pool"); [p release]; p = [NSAutoreleasePool new]; NSLog(@"Getting two clients again"); c0 = [sp provideClientExclusive]; c1 = [sp provideClientExclusive]; NSLog(@"Pool has provided both it's clients ... now try for another with a 15 second timeout"); [sp provideClientBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 15.0] exclusive: YES]; NSLog(@"Emptying autorelease pool again"); [p release]; p = [NSAutoreleasePool new]; c0 = [sp provideClient]; q = [NSAutoreleasePool new]; c1 = [sp provideClient]; if (c0 != c1) { NSLog(@"ERROR was expecting provideClient to give the same object"); exit(1); } [q release]; [c0 connect]; [p release]; NSLog(@"Expect to get client immediately"); } #endif db = [sp provideClientExclusive]; [sp swallowClient: db]; [sp queryString: @"SELECT CURRENT_TIMESTAMP", nil]; db = [sp provideClientExclusive]; l = [Logger new]; [[NSNotificationCenter defaultCenter] addObserver: l selector: @selector(notified:) name: SQLClientDidConnectNotification object: db]; [[NSNotificationCenter defaultCenter] addObserver: l selector: @selector(notified:) name: SQLClientDidDisconnectNotification object: db]; if ((name = [defs stringForKey: @"Producer"]) != nil) { NS_DURING { [db execute: @"CREATE TABLE Queue ( " @"ID SERIAL, " @"Consumer CHAR(40) NOT NULL, " @"ServiceID INT NOT NULL, " @"Status CHAR(1) DEFAULT 'Q' NOT NULL, " @"Delivery TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, " @"Reference CHAR(128), " @"Destination CHAR(15) NOT NULL, " @"Payload CHAR(250) DEFAULT '' NOT NULL," @")", nil]; [db execute: @"CREATE UNIQUE INDEX QueueIDX ON Queue (ID)", nil]; [db execute: @"CREATE INDEX ServiceIDX ON Queue (ServiceID)", nil]; [db execute: @"CREATE INDEX ConsumerIDX ON Queue (Consumer,Status,Delivery)", nil]; [db execute: @"CREATE INDEX ReferenceIDX ON Queue (Reference,Consumer)", nil]; } NS_HANDLER { NSLog(@"%@", localException); } NS_ENDHANDLER NSLog(@"Start producing"); for (i = 0; i < 100000; i++) { NSAutoreleasePool *arp = [NSAutoreleasePool new]; NSString *destination = [NSString stringWithFormat: @"%d", i]; NSString *sid = [NSString stringWithFormat: @"%d", i%100]; if (i % 1000 == 999) { [db postNotificationName: @"Producing" payload: [NSString stringWithFormat: @"%d", i]]; } [db execute: @"INSERT INTO Queue (Consumer, Destination," @" ServiceID, Payload) VALUES (", [db quote: name], @", ", [db quote: destination], @", ", sid, @", ", @"'helo there'", @")", nil]; [arp release]; } NSLog(@"End producing"); } else if ((name = [defs stringForKey: @"Consumer"]) != nil) { [db addObserver: l selector: @selector(notified:) name: @"Producing"]; NSLog(@"Start consuming"); for (i = 0; i < 100000;) { NSAutoreleasePool *arp = [NSAutoreleasePool new]; unsigned count; int j; [db begin]; records = [db query: @"SELECT * FROM Queue WHERE Consumer = ", [db quote: name], @" AND Status = 'Q' AND Delivery < CURRENT_TIMESTAMP", @" ORDER BY Delivery LIMIT 1000 FOR UPDATE" , nil]; count = [records count]; if (count == 0) { [db commit]; [NSThread sleepForTimeInterval: 1.0]; [db begin]; records = [db query: @"SELECT * FROM Queue WHERE Consumer = ", [db quote: name], @" AND Status = 'Q' AND Delivery < CURRENT_TIMESTAMP", @" ORDER BY Delivery LIMIT 50 FOR UPDATE" , nil]; count = [records count]; if (count == 0) { break; } } for (j = 0; j < count; j++) { SQLRecord *record = [records objectAtIndex: j]; NSString *reference = [record objectForKey: @"ID"]; [db execute: @"UPDATE Queue SET Status = 'S', Reference = ", [db quote: reference], @" WHERE ID = ", [record objectForKey: @"ID"], nil]; [db execute: @"UPDATE Queue SET Status = 'D'", @" WHERE Consumer = ", [db quote: name], @" AND Reference = ", [db quote: reference], nil]; } [db commit]; i += count; [arp release]; } NSLog(@"End consuming (%d records)", i); /* [db execute: @"DROP INDEX ReferenceIDX", nil]; [db execute: @"DROP INDEX ServiceIDX", nil]; [db execute: @"DROP INDEX ConsumerIDX", nil]; [db execute: @"DROP INDEX QueueIDX", nil]; [db execute: @"DROP TABLE Queue", nil]; */ } else { NSString *oddChars; NSString *oddNoNul; NSString *nonLatin; id e1, e2, e3, e4, e5; id d; id d0; id d1; id d2; id r0; id r1; oddChars = @"'a\\b'c\0\r\nd'\\ed\\"; oddNoNul = @"'a\\b'c\r\nd'\\ed\\"; nonLatin = [[NSString stringWithCString: "\"\\U2A11\""] propertyList]; for (i = 0; i < 256; i++) { dbuf[i] = i; } data = [NSData dataWithBytes: dbuf length: i]; NS_DURING [db execute: @"drop table xxx", nil]; NS_HANDLER NS_ENDHANDLER [db setDurationLogging: 0]; [db begin]; [db execute: @"create table xxx ( " @"id int, " @"k char(40), " @"char1 char(1), " @"boolval BOOL, " @"intval int, " @"when1 timestamp with time zone, " @"when2 timestamp, " @"b bytea," @"extra1 int[]," @"extra2 varchar[]," @"extra3 bytea[]," @"extra4 boolean[]," @"extra5 timestamp with time zone[]" @")", nil]; if (1 != [db execute: @"INSERT into xxx (id, k, char1, boolval, intval," @" when1, when2, b, extra1, extra2, extra3, extra4, extra5) " @"values (1," @"'{hello', " @"'X', " @"TRUE, " @"1, " @"CURRENT_TIMESTAMP, " @"CURRENT_TIMESTAMP, ", data, @", ", [db quoteArray: (e1 = [NSArray arrayWithObjects: @"1", @"2", [NSNull null], nil]) toString: nil quotingStrings: NO], @", ", [db quoteArray: (e2 = [NSArray arrayWithObjects: @"on,e", @"t'wo", @"many", nil]) toString: nil quotingStrings: YES], @", ", [db quoteArray: (e3 = [NSArray arrayWithObjects: data, nil]) toString: nil quotingStrings: YES], @", ", [db quoteArray: (e4 =[NSArray arrayWithObjects: @"TRUE", @"FALSE", nil]) toString: nil quotingStrings: NO], @", ", [db quoteArray: (e5 = [NSArray arrayWithObjects: [NSDate date], nil]) toString: nil quotingStrings: YES], @")", nil]) { NSLog(@"Insert failed to return row count"); } [db setDebugging: 0]; [db query: @"select * from xxx", nil]; [db setDebugging: 0]; [db execute: @"INSERT into xxx " @"(id, k, char1, boolval, intval, when1, when2, b) " @"values (2," @"'hello', " @"'X', " @"TRUE, " @"1, ", [NSDate date], @", ", [NSDate date], @", ", [NSData dataWithBytes: "" length: 0], @")", nil]; [db execute: @"INSERT into xxx " @"(id, k, char1, boolval, intval, when1, when2, b) " @"values (3,", [db quote: oddChars], @", ", [db quote: nonLatin], @",TRUE, " @"1, ", [NSDate date], @", ", [NSDate date], @", ", [NSData dataWithBytes: "" length: 0], @")", nil]; [db commit]; r0 = [db cache: 1 query: @"select * from xxx order by id", nil]; r1 = [db cache: 1 query: @"select * from xxx order by id", nil]; NSCAssert([r0 lastObject] == [r1 lastObject], @"Cache failed"); [NSThread sleepForTimeInterval: 2.0]; records = [db cache: 1 query: @"select * from xxx order by id", nil]; NSCAssert([r0 lastObject] != [records lastObject], @"Lifetime failed"); db = [[[SQLClient alloc] initWithConfiguration: nil name: @"test"] autorelease]; [db addObserver: l selector: @selector(notified:) name: @"foo"]; [db postNotificationName: @"foo" payload: @"hello"]; [db execute: @"drop table xxx", nil]; if ([records count] != 3) { NSLog(@"Expected 3 records but got %lu", [records count]); } else { int i; record = [records objectAtIndex: 0]; if ([[record objectForKey: @"b"] isEqual: data] == NO) { NSLog(@"Retrieved data does not match saved data %@ %@", data, [record objectForKey: @"b"]); } record = [records objectAtIndex: 1]; if ([[record objectForKey: @"b"] isEqual: [NSData data]] == NO) { NSLog(@"Retrieved empty data does not match saved data"); } record = [records objectAtIndex: 2]; if ([[record objectForKey: @"char1"] isEqual: nonLatin] == NO) { NSLog(@"Retrieved non-latin does not match saved string"); } id o = [[record objectForKey: @"k"] stringByTrimmingSpaces]; if ([o isEqual: oddNoNul] == NO) { NSLog(@"Retrieved odd chars (%@) does not match oddNoNul (%@)", o, oddNoNul); } else { NSLog(@"Embedded nul correctly removed"); } record = [records objectAtIndex: 0]; o = [record objectForKey: @"extra1"]; if ([o isEqual: e1] == NO) { NSLog(@"Retrieved extra1 (%@) does not match saved (%@)", o, e1); } o = [record objectForKey: @"extra2"]; if ([o isEqual: e2] == NO) { NSLog(@"Retrieved extra2 (%@) does not match saved (%@)", o, e2); } o = [record objectForKey: @"extra3"]; if ([o isEqual: e3] == NO) { NSLog(@"Retrieved extra3 (%@) does not match saved (%@)", o, e3); } o = [record objectForKey: @"extra4"]; if ([o count] != [e4 count]) { NSLog(@"Retrieved extra4 (%@) does not match saved (%@)", o, e4); } for (i = 0; i < [o count]; i++) { if ([[o objectAtIndex: i] boolValue] != [[e4 objectAtIndex: i] boolValue]) { NSLog(@"Retrieved extra4 (%@) does not match saved (%@)", o, e4); } } o = [record objectForKey: @"extra5"]; if ([o count] != [e5 count]) { NSLog(@"Retrieved extra5 (%@) does not match saved (%@)", o, e5); } for (i = 0; i < [o count]; i++) { if (floor([[o objectAtIndex: i] timeIntervalSinceReferenceDate]) != floor([[e5 objectAtIndex: i] timeIntervalSinceReferenceDate])) { NSLog(@"Retrieved extra5 (%@) does not match saved (%@)", o, e5); } } } NSLog(@"Records - %@", [GSCache class]); d = [NSCalendarDate date]; [d setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 240]]; [db begin]; [db execute: @"create table xxx ( " @"id int, " @"when0 timestamp with time zone, " @"when1 timestamp with time zone, " @"when2 timestamp)", nil]; [db execute: @"INSERT into xxx (id, when0, when1, when2) " @"values (99,", d, @", ", [NSDate distantPast], @", ", [NSDate distantFuture], @")", nil]; r0 = [[db query: @"select * from xxx where id=99", nil] lastObject]; [db execute: @"drop table xxx", nil]; [db commit]; d0 = [r0 objectForKey:@"when0"]; NSCAssert(floor([d0 timeIntervalSinceReferenceDate]) == floor([d timeIntervalSinceReferenceDate]), NSInternalInconsistencyException); d1 = [r0 objectForKey:@"when1"]; NSCAssert([d1 timeIntervalSinceReferenceDate] == [[NSDate distantPast] timeIntervalSinceReferenceDate], NSInternalInconsistencyException); d2 = [r0 objectForKey:@"when2"]; NSCAssert([d2 timeIntervalSinceReferenceDate] == [[NSDate distantFuture] timeIntervalSinceReferenceDate], NSInternalInconsistencyException); } NSLog(@"Pool stats:\n%@", [sp statistics]); [pool release]; return 0; } SQLClient-1.9.0/testSQLite.m000066400000000000000000000062231436027104400155420ustar00rootroot00000000000000/** Copyright (C) 2005 Free Software Foundation, Inc. Written by: Richard Frith-Macdonald Date: April 2005 This file is part of the SQLClient Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA. $Date$ $Revision$ */ #import #import "SQLClient.h" int main() { NSAutoreleasePool *pool = [NSAutoreleasePool new]; SQLClient *db; NSUserDefaults *defs; NSMutableArray *records; SQLRecord *record; unsigned char dbuf[256]; unsigned int i; NSData *data; defs = [NSUserDefaults standardUserDefaults]; [defs registerDefaults: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: [NSDictionary dictionaryWithObjectsAndKeys: @"test", @"Database", @"", @"User", @"", @"Password", @"SQLite", @"ServerType", nil], @"test", nil], @"SQLClientReferences", nil] ]; for (i = 0; i < 256; i++) { dbuf[i] = i; } data = [NSData dataWithBytes: dbuf length: i]; db = [SQLClient clientWithConfiguration: nil name: @"test"]; [db setDurationLogging: 0]; NS_DURING [db execute: @"drop table xxx", nil]; NS_HANDLER NS_ENDHANDLER [db execute: @"create table xxx ( " @"k char(40), " @"char1 char(1), " @"intval int, " @"realval real, " @"b blob)", nil]; [db execute: @"insert into xxx " @"(k, char1, intval, realval, b) " @"values (" @"'hello', " @"'X', " @"1, " @"9.99, ", data, @")", nil]; [NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow: 1]]; [db execute: @"insert into xxx " @"(k, char1, intval, realval, b) " @"values (", [db quoteString: @"hello"], @", " @"'X', " @"1, ", @"12345.6789, ", [NSData dataWithBytes: "" length: 0], @")", nil]; records = [db query: @"select * from xxx", nil]; [db execute: @"drop table xxx", nil]; if ([records count] != 2) { NSLog(@"Expected 2 records but got %" PRIuPTR "", [records count]); } else { record = [records objectAtIndex: 0]; if ([[record objectForKey: @"b"] isEqual: data] == NO) { NSLog(@"Retrieved data does not match saved data %@ %@", data, [record objectForKey: @"b"]); } record = [records objectAtIndex: 1]; if ([[record objectForKey: @"b"] isEqual: [NSData data]] == NO) { NSLog(@"Retrieved empty data does not match saved data"); } } NSLog(@"Records - %@", records); [pool release]; return 0; }