New database library

git-svn-id: svn+ssh://svn.gna.org/svn/gnustep/libs/sqlclient/trunk@19194 72102866-910b-0410-8b05-ffd578937521
This commit is contained in:
Richard Frith-Macdonald 2004-04-26 15:13:27 +00:00
commit c6cec117a0
21 changed files with 15485 additions and 0 deletions

504
COPYING.LIB Normal file
View file

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the 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
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
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-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

1068
ECPG.pgm Normal file

File diff suppressed because it is too large Load diff

71
GNUmakefile Normal file
View file

@ -0,0 +1,71 @@
include $(GNUSTEP_MAKEFILES)/common.make
-include config.make
TEST_TOOL_NAME = testPostgres testMySQL testECPG
testPostgres_OBJC_FILES = testPostgres.m
testPostgres_LIB_DIRS += -L./obj
testPostgres_TOOL_LIBS += -lSQLClient
testMySQL_OBJC_FILES = testMySQL.m
testMySQL_LIB_DIRS += -L./obj
testMySQL_TOOL_LIBS += -lSQLClient
testECPG_OBJC_FILES = testECPG.m
testECPG_TOOL_LIBS += -lSQLClient
testECPG_LIB_DIRS += -L./obj
LIBRARY_NAME=SQLClient
SQLClient_OBJC_FILES = SQLClient.m
DOCUMENT_NAME=SQLClient
SQLClient_AGSDOC_FILES = SQLClient.h
BUNDLE_NAME=
BUNDLE_INSTALL_DIR=$(GNUSTEP_LOCAL_ROOT)/Library/Bundles/SQLClient
ifneq ($(ECPG),)
BUNDLE_NAME += ECPG
ECPG_OBJC_FILES = ECPG.m
ECPG_BUNDLE_LIBS += -lgnustep-base -lobjc -lecpg
ECPG_PRINCIPAL_CLASS = SQLClientECPG
endif
ifneq ($(POSTGRES),)
BUNDLE_NAME += Postgres
Postgres_OBJC_FILES = Postgres.m
Postgres_BUNDLE_LIBS += -lgnustep-base -lobjc -lpq
Postgres_PRINCIPAL_CLASS = SQLClientPostgres
endif
ifneq ($(MYSQL),)
BUNDLE_NAME += MySQL
MySQL_OBJC_FILES = MySQL.m
MySQL_BUNDLE_LIBS += -lgnustep-base -lobjc -lmysqlclient
MySQL_PRINCIPAL_CLASS = SQLClientMySQL
endif
ifneq ($(ORACLE_HOME),)
BUNDLE_NAME += Oracle
Oracle_OBJC_FILES = Oracle.m
Oracle_BUNDLE_LIBS += -L$(ORACLE_HOME)/lib \
-lclntsh \
-lgnustep-base -lobjc \
$(shell cat $(ORACLE_HOME)/lib/ldflags) \
$(shell cat $(ORACLE_HOME)/lib/sysliblist) \
-ldl -lm
Oracle_PRINCIPAL_CLASS = SQLClientOracle
endif
-include GNUmakefile.preamble
include $(GNUSTEP_MAKEFILES)/library.make
include $(GNUSTEP_MAKEFILES)/bundle.make
include $(GNUSTEP_MAKEFILES)/test-tool.make
include $(GNUSTEP_MAKEFILES)/documentation.make
-include GNUmakefile.postamble

75
GNUmakefile.postamble Normal file
View file

@ -0,0 +1,75 @@
#
# 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)
# if you need to see the .m files for debugging, uncomment
# the following line
#.PRECIOUS: %.m
endif
ifneq ($(ORACLE_HOME),)
%.m: %.pm
proc iname=$< oname=$@ mode=ansi parse=none
# if you need to see the .m files for debugging, uncomment
# the following line
#.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.make.in
./configure

44
GNUmakefile.preamble Normal file
View file

@ -0,0 +1,44 @@
#
# 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 +=
# 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 +=

503
MySQL.m Normal file
View file

@ -0,0 +1,503 @@
/* -*-objc-*- */
/** Implementation of SQLClientMySQL for GNUStep
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
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 Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
$Date$ $Revision$
*/
#include <Foundation/NSString.h>
#include <Foundation/NSData.h>
#include <Foundation/NSDate.h>
#include <Foundation/NSCalendarDate.h>
#include <Foundation/NSException.h>
#include <Foundation/NSProcessInfo.h>
#include <Foundation/NSNotification.h>
#include <Foundation/NSUserDefaults.h>
#include <Foundation/NSMapTable.h>
#include <Foundation/NSLock.h>
#include <Foundation/NSNull.h>
#include <Foundation/NSValue.h>
#include <Foundation/NSAutoreleasePool.h>
#include "config.h"
#include "SQLClient.h"
#include <mysql/mysql.h>
@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 +0000"
calendarFormat: @"%Y-%m-%d %H:%M:%S %z"
locale: nil];
RETAIN(future);
null = [NSNull null];
RETAIN(null);
}
}
- (BOOL) backendConnect
{
if (connected == NO)
{
if (database != nil && user != nil && password != nil)
{
NSString *host = nil;
NSString *port = nil;
NSString *dbase = 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 %@", database, [self name]];
}
extra = mysql_init(0);
if (mysql_real_connect(connection,
[host UTF8String],
[user UTF8String],
[password UTF8String],
[dbase UTF8String],
[port intValue],
NULL,
0
) == 0)
{
[self debug: @"Error connecting to '%@' (%@) - %s",
[self name], database, mysql_error(connection)];
mysql_close(connection);
extra = 0;
}
#if 0
else if (mysql_query(connection, "SET CHARACTER SET utf8") != 0)
{
[self debug: @"Error setting utf8 support for '%@' (%@) - %s",
[self name], database, mysql_error(connection)];
mysql_close(connection);
extra = 0;
}
#endif
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 (inTransaction == YES)
{
[self rollback];
}
if ([self debugging] > 0)
{
[self debug: @"Disconnecting client %@", client];
}
mysql_close(connection);
extra = 0;
if ([self debugging] > 0)
{
[self debug: @"Disconnected client %@", client];
}
}
NS_HANDLER
{
[self debug: @"Error disconnecting from database (%@): %@",
client, localException];
}
NS_ENDHANDLER
connected = NO;
}
}
- (void) backendExecute: (NSArray*)info
{
NSString *stmt;
CREATE_AUTORELEASE_POOL(arp);
stmt = [info objectAtIndex: 0];
if ([stmt length] == 0)
{
RELEASE (arp);
[NSException raise: NSInternalInconsistencyException
format: @"Statement produced null string"];
}
NS_DURING
{
const char *statement;
unsigned length;
/*
* Ensure we have a working connection.
*/
if ([self backendConnect] == 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: 3
giving: &length];
if (mysql_real_query(connection, statement, length) != 0)
{
[NSException raise: SQLException format: @"%s",
mysql_error(connection)];
}
}
NS_HANDLER
{
NSString *n = [localException name];
if ([n isEqual: SQLConnectionException] == YES)
{
[self backendDisconnect];
}
if ([self debugging] > 0)
{
[self debug: @"Error executing statement:\n%@\n%@",
stmt, localException];
}
RETAIN (localException);
RELEASE (arp);
AUTORELEASE (localException);
[localException raise];
}
NS_ENDHANDLER
DESTROY(arp);
}
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
{
CREATE_AUTORELEASE_POOL(arp);
NSMutableArray *records = nil;
MYSQL_RES *result = 0;
if ([stmt length] == 0)
{
RELEASE (arp);
[NSException raise: NSInternalInconsistencyException
format: @"Statement produced null string"];
}
NS_DURING
{
char *statement;
/*
* Ensure we have a working connection.
*/
if ([self backendConnect] == 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);
id keys[fieldCount];
int i;
for (i = 0; i < fieldCount; i++)
{
keys[i] = [NSString stringWithUTF8String: fields[i].name];
}
records = [[NSMutableArray 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 = row[j];
if (p != 0)
{
int size = lengths[j];
NSLog(@"%@ type:%d size: %d val:%*.*s\n", keys[j], fields[j].type, size, size, size, p);
switch (fields[j].type)
{
case FIELD_TYPE_TIMESTAMP:
{
NSString *s;
s = [[NSString alloc] initWithBytes: p
length: size encoding: NSASCIIStringEncoding];
if (size > 14)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%Y-%m-%d %H:%M:%S"
locale: nil];
}
else if (size == 14)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%Y%m%d%H%M%S"
locale: nil];
}
else if (size == 12)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%y%m%d%H%M%S"
locale: nil];
}
else if (size == 10)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%y%m%d%H%M"
locale: nil];
}
else if (size == 8)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%y%m%d%H"
locale: nil];
}
else if (size == 6)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%y%m%d"
locale: nil];
}
else if (size == 4)
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%y%m"
locale: nil];
}
else
{
v = [NSCalendarDate dateWithString: s
calendarFormat: @"%y"
locale: nil];
}
RELEASE(s);
[v setCalendarFormat: @"%Y-%m-%d %H:%M:%S %z"];
}
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:
v = [NSData dataWithBytes: p length: size];
break;
default:
trim(p);
v = [NSString stringWithUTF8String: p];
break;
}
}
values[j] = v;
}
record = [SQLRecord newWithValues: values
keys: keys
count: fieldCount];
[records addObject: record];
RELEASE(record);
}
}
else
{
[NSException raise: SQLException format: @"%s",
mysql_error(connection)];
}
}
NS_HANDLER
{
NSString *n = [localException name];
if ([n isEqual: SQLConnectionException] == YES)
{
[self backendDisconnect];
}
if ([self debugging] > 0)
{
[self debug: @"Error executing statement:\n%@\n%@",
stmt, localException];
}
if (result != 0)
{
mysql_free_result(result);
}
DESTROY(records);
RETAIN (localException);
RELEASE (arp);
AUTORELEASE (localException);
[localException raise];
}
NS_ENDHANDLER
DESTROY(arp);
if (result != 0)
{
mysql_free_result(result);
}
return AUTORELEASE(records);
}
- (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;
}
@end

1040
Oracle.pm Normal file

File diff suppressed because it is too large Load diff

783
Postgres.m Normal file
View file

@ -0,0 +1,783 @@
/* -*-objc-*- */
/** Implementation of SQLClientPostgres for GNUStep
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
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 Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
$Date$ $Revision$
*/
#include <Foundation/NSString.h>
#include <Foundation/NSData.h>
#include <Foundation/NSDate.h>
#include <Foundation/NSCalendarDate.h>
#include <Foundation/NSException.h>
#include <Foundation/NSProcessInfo.h>
#include <Foundation/NSNotification.h>
#include <Foundation/NSUserDefaults.h>
#include <Foundation/NSMapTable.h>
#include <Foundation/NSLock.h>
#include <Foundation/NSNull.h>
#include <Foundation/NSValue.h>
#include <Foundation/NSAutoreleasePool.h>
#include "config.h"
#include "SQLClient.h"
#include <libpq-fe.h>
@interface SQLClientPostgres : SQLClient
@end
@interface SQLClientPostgres(Embedded)
- (NSData*) dataFromBLOB: (const char *)blob;
- (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l;
@end
@implementation SQLClientPostgres
#define connection ((PGconn*)(self->extra))
static NSDate *future = nil;
static NSNull *null = 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];
RETAIN(future);
null = [NSNull null];
RETAIN(null);
}
}
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 AUTORELEASE(m);
}
- (BOOL) backendConnect
{
if (connection == 0)
{
connected = YES;
if (database != nil)
{
NSString *host = nil;
NSString *port = nil;
NSString *dbase = database;
NSString *str;
NSRange r;
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(user);
if (str != nil)
{
[m appendString: @" user="];
[m appendString: str];
}
str = connectQuote(password);
if (str != nil)
{
[m appendString: @" password="];
[m appendString: str];
}
if ([self debugging] > 0)
{
[self debug: @"Connect to '%@' as %@", m, [self name]];
}
extra = PQconnectdb([m UTF8String]);
if (PQstatus(connection) != CONNECTION_OK)
{
[self debug: @"Error connecting to '%@' (%@) - %s",
[self name], m, PQerrorMessage(connection)];
PQfinish(connection);
extra = 0;
connected = NO;
}
else
{
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 (connection != 0)
{
NS_DURING
{
if (inTransaction == YES)
{
[self rollback];
}
if ([self debugging] > 0)
{
[self debug: @"Disconnecting client %@", client];
}
PQfinish(connection);
extra = 0;
if ([self debugging] > 0)
{
[self debug: @"Disconnected client %@", client];
}
}
NS_HANDLER
{
[self debug: @"Error disconnecting from database (%@): %@",
client, localException];
}
NS_ENDHANDLER
connected = NO;
}
}
- (void) backendExecute: (NSArray*)info
{
CREATE_AUTORELEASE_POOL(arp);
PGresult *result = 0;
NSString *stmt = [info objectAtIndex: 0];
if ([stmt length] == 0)
{
RELEASE (arp);
[NSException raise: NSInternalInconsistencyException
format: @"Statement produced null string"];
}
NS_DURING
{
const char *statement;
unsigned length;
/*
* Ensure we have a working connection.
*/
if ([self backendConnect] == 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: 3
giving: &length];
result = PQexec(connection, statement);
if (result == 0 || PQresultStatus(result) == PGRES_FATAL_ERROR)
{
NSString *str;
const char *cstr;
if (result == 0)
{
cstr = PQerrorMessage(connection);
}
else
{
cstr = PQresultErrorMessage(result);
}
str = [NSString stringWithUTF8String: cstr];
[self backendDisconnect];
[NSException raise: SQLException format: @"%@", str];
}
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
[NSException raise: SQLException format: @"%s",
PQresultErrorMessage(result)];
}
}
NS_HANDLER
{
NSString *n = [localException name];
if ([n isEqual: SQLConnectionException] == YES)
{
[self backendDisconnect];
}
if ([self debugging] > 0)
{
[self debug: @"Error executing statement:\n%@\n%@",
stmt, localException];
}
if (result != 0)
{
PQclear(result);
}
RETAIN (localException);
RELEASE (arp);
AUTORELEASE (localException);
[localException raise];
}
NS_ENDHANDLER
if (result != 0)
{
PQclear(result);
}
DESTROY(arp);
}
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
{
CREATE_AUTORELEASE_POOL(arp);
PGresult *result = 0;
NSMutableArray *records = nil;
if ([stmt length] == 0)
{
RELEASE (arp);
[NSException raise: NSInternalInconsistencyException
format: @"Statement produced null string"];
}
NS_DURING
{
char *statement;
/*
* Ensure we have a working connection.
*/
if ([self backendConnect] == NO)
{
[NSException raise: SQLException
format: @"Unable to connect to '%@' to run query %@",
[self name], stmt];
}
statement = (char*)[stmt UTF8String];
result = PQexec(connection, statement);
if (result == 0 || PQresultStatus(result) == PGRES_FATAL_ERROR)
{
NSString *str;
const char *cstr;
if (result == 0)
{
cstr = PQerrorMessage(connection);
}
else
{
cstr = PQresultErrorMessage(result);
}
str = [NSString stringWithUTF8String: cstr];
[self backendDisconnect];
[NSException raise: SQLException format: @"%@", str];
}
if (PQresultStatus(result) == PGRES_TUPLES_OK)
{
int recordCount = PQntuples(result);
int fieldCount = PQnfields(result);
id keys[fieldCount];
int types[fieldCount];
int modifiers[fieldCount];
int formats[fieldCount];
int i;
for (i = 0; i < fieldCount; i++)
{
keys[i] = [NSString stringWithUTF8String: PQfname(result, i)];
types[i] = PQftype(result, i);
modifiers[i] = PQfmod(result, i);
formats[i] = PQfformat(result, i);
}
records = [[NSMutableArray alloc] initWithCapacity: recordCount];
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);
NSLog(@"%@ type:%d mod:%d size: %d\n", keys[j], types[j], modifiers[j], size);
if (formats[j] == 0) // Text
{
switch (types[j])
{
case 1082: // Date
case 1083: // Time
case 1114: // Timestamp without time zone.
case 1184: // Timestamp with time zone.
v = [self dbToDateFromBuffer: p
length: trim(p)];
break;
case 16: // BOOL
if (*p == 't')
{
v = @"YES";
}
else
{
v = @"NO";
}
break;
case 17: // BYTEA
v = [self dataFromBLOB: p];
break;
default:
trim(p);
v = [NSString stringWithUTF8String: p];
break;
}
}
else // Binary
{
NSLog(@"Binary data treated as NSNull "
@"in %@ type:%d mod:%d size:%d\n",
keys[j], types[j], modifiers[j], size);
}
}
values[j] = v;
}
record = [SQLRecord newWithValues: values
keys: keys
count: fieldCount];
[records addObject: record];
RELEASE(record);
}
}
else
{
[NSException raise: SQLException format: @"%s",
PQresultErrorMessage(result)];
}
}
NS_HANDLER
{
NSString *n = [localException name];
if ([n isEqual: SQLConnectionException] == YES)
{
[self backendDisconnect];
}
if ([self debugging] > 0)
{
[self debug: @"Error executing statement:\n%@\n%@",
stmt, localException];
}
if (result != 0)
{
PQclear(result);
}
DESTROY(records);
RETAIN (localException);
RELEASE (arp);
AUTORELEASE (localException);
[localException raise];
}
NS_ENDHANDLER
DESTROY(arp);
if (result != 0)
{
PQclear(result);
}
return AUTORELEASE(records);
}
- (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)
{
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)
{
length += 5;
}
else if (c == '\\')
{
length += 4;
}
else if (c == '\'')
{
length += 2;
}
else
{
length += 1;
}
}
return length;
}
- (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;
}
- (NSDate*) dbToDateFromBuffer: (char*)b length: (int)l
{
char buf[l+32]; /* Allow space to expand buffer. */
NSDate *d;
BOOL milliseconds = NO;
NSString *s;
int i;
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];
}
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 postgres returning 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;
}
}
@end

16
README Normal file
View file

@ -0,0 +1,16 @@
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 ...

754
SQLClient.h Normal file
View file

@ -0,0 +1,754 @@
/**
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
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 Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
<title>SQLClient documentation</title>
<chapter>
<heading>The SQLClient library</heading>
<section>
<heading>Overview</heading>
<p>
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.
</p>
<p>
The major features of the SQLClient library are -
</p>
<list>
<item>
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.
</item>
<item>
Support multiple sumultaneous named connections to a database
server in a thread-safe manner.<br />
</item>
<item>
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.
</item>
<item>
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.
</item>
<item>
Thread safe operation ... The base class supports locking such that
a single instance can be shared between multiple threads.
</item>
</list>
</section>
<section>
<heading>Backends</heading>
<p>
Current backend bundles are -
</p>
<list>
<item>
ECPG - a bundle using the embedded SQL interface for postgres.<br />
This is based on a similar code which has been in production use
for over eighteen months, so it should be reliable.
</item>
<item>
Postgres - a bundle using the libpq native interface for postgres.<br />
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.
</item>
<item>
MySQL - a bundle using the mysqlclient library for *recent* MySQL.<br />
I don't use MySQL ... but the test program ran successfully with a
vanilla install of the MySQL packages for recent Debian unstable.
</item>
<item>
Oracle - a bundle using embedded SQL for Oracle.<br />
Completely untested ... may even need some work to compile ... but
this *is* based on code which was working about a year ago.<br />
No support for BLOBs yet.
</item>
</list>
</section>
</chapter>
$Date$ $Revision$
*/
#ifndef INCLUDED_SQLClient_H
#define INCLUDED_SQLClient_H
#include <Foundation/NSObject.h>
#include <Foundation/NSArray.h>
@class NSData;
@class NSDate;
@class NSRecursiveLock;
@class NSString;
/**
* An enhanced array to represent a record returned from a query.
* You should <em>NOT</em> try to create instances of this class
* except via the +newWithValues:keys:count: method.
*/
@interface SQLRecord : NSArray
{
unsigned int count;
}
+ (id) newWithValues: (id*)v keys: (id*)k count: (unsigned int)c;
- (NSArray*) allKeys;
- (id) objectForKey: (NSString*)key;
@end
extern NSString *SQLException;
extern NSString *SQLConnectionException;
extern NSString *SQLEmptyException;
extern NSString *SQLUniqueException;
/**
* <p>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.
* </p>
* <p>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.
* </p>
*/
@interface SQLClient : NSObject
{
/**
* A flag indicating whether this instance is currently connected to
* the backend database server. This variable must <em>only</em> be
* set by the -backendConnect or -backendDisconnect methods.
*/
BOOL connected;
/**
* A flag indicating whether this instance is currently within a
* transaction. This variable must <em>only</em> be
* set by the -begin, -commit or -rollback methods.
*/
BOOL inTransaction; /** Are we inside a transaction? */
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 */
/**
* Timestamp of last operation.<br />
* Maintained by the -simpleExecute: and -simpleQuery: methods.
*/
NSDate *lastOperation;
NSRecursiveLock *lock; /** Maintain thread-safety */
unsigned int debugging; /** The current debugging level */
void *extra; /** For subclass specific data */
}
/**
* 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).<br />
* 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;
/**
* Return the maximum number of simultaneous database connections
* permitted (set by +setMaxConnections: and defaults to 8)
*/
+ (unsigned int) maxConnections;
/**
* <p>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.
* </p>
* <p>If since is not nil, then any connection which has not been
* used more recently than that date is disconnected anyway.<br />
* 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.
* </p>
*/
+ (void) purgeConnections: (NSDate*)since;
/**
* <p>Set the maximum number of simultaneous database connections
* permitted (defaults to 8 and may not be set less than 1).
* </p>
* <p>This value is used by the +purgeConnections: method to determine how
* many connections should be disconnected when it is called.
* </p>
*/
+ (void) setMaxConnections: (unsigned int)c;
/**
* Start a transaction for this database client.<br />
* You <strong>must</strong> match this with either a -commit
* or a -rollback.<br />
* <p>Normally, if you execute an SQL statement without using this
* method first, the <em>autocommit</em> 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.
* </p>
* <p>NB. You must <strong>not</strong> execute an SQL statement
* which would start a transaction directly ... use only this
* method.
* </p>
*/
- (void) begin;
/**
* Return the client name for this instance.<br />
* 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.<br />
* This <strong>must</strong> match an earlier -begin.
* <p>NB. You must <strong>not</strong> execute an SQL statement
* which would commit or rollback a transaction directly ... use
* only this method or the -rollback method.
* </p>
*/
- (void) commit;
/**
* If the <em>connected</em> instance variable is NO, this method
* calls -backendConnect to ensure that there is a connection to the
* database server established. Returns the result.<br />
* Performs any necessary locking for thread safety.
*/
- (BOOL) connect;
/**
* 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.
*/
- (BOOL) connected;
/**
* Return the database name for this instance (or nil).
*/
- (NSString*) database;
/**
* If the <em>connected</em> instance variable is YES, this method
* calls -backendDisconnect to ensure that the connection to the
* database server is dropped.<br />
* Performs any necessary locking for thread safety.
*/
- (void) disconnect;
/**
* Perform arbitrary operation <em>which does not return any value.</em><br />
* This arguments to this method are a nil terminated list which are
* concatenated in the manner of the * -prepare:args: method.<br />
* Any string arguments are assumed to have been quoted appropriately
* already, but non-string arguments are automatically quoted using the
* -quote: method.
* <example>
* [db execute: @"UPDATE ", table, @" SET Name = ",
* myName, " WHERE ID = ", myId, nil];
* </example>
*/
- (void) execute: (NSString*)stmt,...;
/**
* Takes the statement and substitutes in values from
* the dictionary where markup of the format {key} is found.<br />
* Passes the result to the -execute:,... method.
* <example>
* [db execute: @"UPDATE {Table} SET Name = {Name} WHERE ID = {ID}"
* with: values];
* </example>
* Any non-string values in the dictionary will be replaced by
* the results of the -quote: method.<br />
* The markup format may also be {key?default} where <em>default</em>
* is a string to be used if there is no value for the <em>key</em>
* in the dictionary.
*/
- (void) execute: (NSString*)stmt with: (NSDictionary*)values;
/**
* Calls -initWithConfiguration:name: passing a nil reference name.
*/
- (id) initWithConfiguration: (NSDictionary*)config;
/**
* Initialise using the supplied configuration, or if that is nil, try to
* use values from NSUserDefaults (and automatically update when the
* defaults change).<br />
* 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.<br />
* 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.<br />
* <br />
* 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.<br />
* Database ... is the name of the database to use, if it is missing
* then 'Database' may be used instead.<br />
* User ... is the name of the database user to use, if it is missing
* then 'User' may be used instead.<br />
* Password ... is the name of the database user password, if it is
* missing then 'Password' may be used instead.<br />
* 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.<br />
*/
- (id) initWithConfiguration: (NSDictionary*)config
name: (NSString*)reference;
/**
* 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 operation performed
* by the receiver, or nil if no operation has ever been done by it.<br />
* Simply connecting to or disconnecting from the databsse does not
* count as an operation.
*/
- (NSDate*) lastOperation;
/**
* Return the database reference name for this instance (or nil).
*/
- (NSString*) name;
/**
* Return the database password for this instance (or nil).
*/
- (NSString*) password;
/**
* <p>Perform arbitrary query <em>which returns values.</em>
* </p>
* <p>This method has at least one argument, the string starting the
* statement to be executed (which must have the prefix 'select ').
* </p>
* <p>Additional arguments are a nil terminated list which also be strings,
* and these are appended to the statement.<br />
* Any string arguments are assumed to have been quoted appropriately
* already, but non-string arguments are automatically quoted using the
* -quote: method.
* </p>
* <example>
* result = [db query: @"SELECT Name FROM ", table, nil];
* </example>
* <p>Upon error, an exception is raised.
* </p>
* <p>The query returns an array of records (each of which is represented
* by an SQLRecord object).
* </p>
* <p>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.
* </p>
* <p>NULL field items are returned as NSNull objects.
* </p>
* <p>Most other field items are returned as NSString objects.
* </p>
* <p>Date and timestamp field items are returned as NSDate objects.
* </p>
*/
- (NSMutableArray*) query: (NSString*)stmt,...;
/**
* Takes the query statement and substitutes in values from
* the dictionary where markup of the format {key} is found.<br />
* Passes the result to the -query:,... method to execute.
* <example>
* result = [db query: @"SELECT Name FROM {Table} WHERE ID = {ID}"
* with: values];
* </example>
* Any non-string values in the dictionary will be replaced by
* the results of the -quote: method.<br />
* The markup format may also be {key?default} where <em>default</em>
* is a string to be used if there is no value for the <em>key</em>
* in the dictionary.
*/
- (NSMutableArray*) query: (NSString*)stmt with: (NSDictionary*)values;
/**
* Convert an object to a string suitable for use in an SQL query.<br />
* Normally the -execute:,..., and -query:,... methods will call this
* method automatically for everything apart from string objects.<br />
* 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.<br />
* 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.<br />
* The base class implementation formats NSDate objects as<br />
* YYYY-MM-DD hh:mm:ss.mmm ?ZZZZ<br />
* 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.
*/
- (NSString*) quote: (id)obj;
/**
* Convert a 'C' string to a string suitable for use in an SQL query.
*/
- (NSString*) quoteCString: (const char *)s;
/**
* Convert a single character to a string suitable for use in an SQL query.
*/
- (NSString*) quoteChar: (char)c;
/**
* Convert a float to a string suitable for use in an SQL query.
*/
- (NSString*) quoteFloat: (float)f;
/**
* Convert an integer to a string suitable for use in an SQL query.
*/
- (NSString*) quoteInteger: (int)i;
/**
* Revert a transaction for this database client.<br />
* This <strong>must</strong> match an earlier -begin.
* <p>NB. You must <strong>not</strong> execute an SQL statement
* which would commit or rollback a transaction directly ... use
* only this method or the -rollback method.
* </p>
*/
- (void) rollback;
/**
* Set the database host/name for this object.<br />
* 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.<br />
* This is called automatically to configure the connection ...
* you normally shouldn't need to call it yourself.<br />
* NB. attempts to change the name of an instance to that of an existing
* instance are ignored.
*/
- (void) setName: (NSString*)s;
/**
* Set the database password for this object.<br />
* This is called automatically to configure the connection ...
* you normally shouldn't need to call it yourself.
*/
- (void) setPassword: (NSString*)s;
/**
* Set the database user for this object.<br />
* 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.<br />
* Handles locking.<br />
* Maintains -lastOperation date.
*/
- (void) simpleExecute: (NSArray*)info;
/**
* Calls -backendQuery: in a safe manner.<br />
* Handles locking.<br />
* Maintains -lastOperation date.
*/
- (NSMutableArray*) simpleQuery: (NSString*)stmt;
/**
* Return the database user for this instance (or nil).
*/
- (NSString*) user;
@end
/**
* This category contains the methods which a subclass <em>must</em>
* override to provide a working instance, and helper methods for the
* backend implementations.<br />
* Application programmers should <em>not</em> call the backend
* methods directly.<br />
* <p>When subclassing to produce a backend driver bundle, please be
* aware that the subclass must <em>NOT</em> introduce additional
* instance variables. Instead the <em>extra</em> instance variable
* is provided for use as a pointer to subclass specific data.
* </p>
*/
@interface SQLClient(Subclass)
/** <override-subclass />
* Attempts to establish a connection to the database server.<br />
* Returns a flag to indicate whether the connection has been established.<br />
* If a connection was already established, returns YES and does nothing.<br />
* You should not need to use this method normally, as it is called for you
* automatically when necessary.<br />
* <p>Subclasses <strong>must</strong> implement this method to establish a
* connection to the database server process (and initialise the
* <em>extra</em> instance variable if necessary), setting the
* <em>connected</em> instance variable to indicate the state of the object.
* </p>
* <p>This method must call +purgeConnections: to ensure that there is a
* free slot for the new connection.
* </p>
* <p>Application code must <em>not</em> call this method directly, it is
* for internal use only. The -connect method calls this method if the
* <em>connected</em> instance variable is NO.
* </p>
*/
- (BOOL) backendConnect;
/** <override-subclass />
* Disconnect from the database unless already disconnected.<br />
* <p>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.
* </p>
* <p>If the receiver is an instance of a subclass which uses the
* <em>extra</em> instance variable, it <strong>must</strong> clear that
* variable in the -backendDisconnect method, because a reconfiguration
* may cause the class of the receiver to change.
* </p>
* <p>This method must set the <em>connected</em> instance variable to NO.
* </p>
* <p>Application code must <em>not</em> call this method directly, it is
* for internal use only. The -disconnect method calls this method if the
* <em>connected</em> instance variable is YES.
* </p>
*/
- (void) backendDisconnect;
/** <override-subclass />
* Perform arbitrary operation <em>which does not return any value.</em><br />
* 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.<br />
* <example>
* [db backendExecute: [NSArray arrayWithObject:
* @"UPDATE MyTable SET Name = 'The name' WHERE ID = 123"]];
* </example>
* <p>The backend implementation is required to perform the SQL statement
* using the supplied NSData objects at the points in the statement
* marked by the <code>'''</code> sequence. The marker saequences are
* inserted into the statement at an earlier stage by the -execute:,...
* and -execute:with: methods.
* </p>
* <p>This method should lock the instance using the <em>lock</em>
* instance variable for the duration of the operation, and unlock
* it afterwards.
* </p>
* <p>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.
* </p>
* <p>Application code must <em>not</em> call this method directly, it is
* for internal use only.
* </p>
*/
- (void) backendExecute: (NSArray*)info;
/** <override-subclass />
* <p>Perform arbitrary query <em>which returns values.</em>
* </p>
* <example>
* result = [db backendQuery: @"SELECT Name FROM Table"];
* </example>
* <p>Upon error, an exception is raised.
* </p>
* <p>The query returns an array of records (each of which is represented
* by an SQLRecord object).
* </p>
* <p>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.
* </p>
* <p>NULL field items are returned as NSNull objects.
* </p>
* <p>This method should lock the instance using the <em>lock</em>
* instance variable for the duration of the operation, and unlock
* it afterwards.
* </p>
* <p>Application code must <em>not</em> call this method directly, it is
* for internal use only.
* </p>
*/
- (NSMutableArray*) backendQuery: (NSString*)stmt;
/** <override-subclass />
* This method is <em>only</em> for the use of the
* -insertBLOBs:intoStatement:length:withMarker:length:giving:
* method.<br />
* 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;
/**
* <p>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
* <em>must</em> be implemented by the subclass.
* </p>
* <p>The blobs array is an array containing the original SQL statement
* string (unused by this method) followed by the data items to be inserted.
* </p>
* <p>The statement and sLength arguments specify the datastream to be
* copied and into which the BLOBs are to be inserted.
* </p>
* <p>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.
* </p>
* <p>The method returns either the original statement or a copy containing
* the escaped BLOBs. The length of the returned data is stored in result.
* </p>
*/
- (const void*) insertBLOBs: (NSArray*)blobs
intoStatement: (const void*)statement
length: (unsigned)sLength
withMarker: (const void*)marker
length: (unsigned)mLength
giving: (unsigned*)result;
/** <override-subclass />
* This method is <em>only</em> for the use of the
* -insertBLOBs:intoStatement:length:withMarker:length:giving:
* method.<br />
* 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 convenience methods including those for
* frequently performed database operations ... message logging etc.
*/
@interface SQLClient(Convenience)
/**
* 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.<br />
* Raises an exception if the query did not contain a single record, or
* if the record did not contain a single field.<br />
* Returns the resulting field as a <em>string</em>.
*/
- (NSString*) queryString: (NSString*)stmt,...;
/**
* 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.
*/
- (void) singletons: (NSMutableArray*)records;
@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 minstances.
*/
+ (unsigned int) debugging;
/**
* Set the debugging level to be inherited by all new instances.
*/
+ (void) setDebugging: (unsigned int)level;
/**
* The default implementation calls NSLogv to log a debug message.<br />
* Override this in a category to provide more sophisticated logging.
*/
- (void) debug: (NSString*)fmt, ...;
/**
* Return the current debugging level.
*/
- (unsigned int) debugging;
/**
* Set the debugging level of this instance ... overrides the default
* level inherited from the class.
*/
- (void) setDebugging: (unsigned int)level;
@end
#endif

1431
SQLClient.m Normal file

File diff suppressed because it is too large Load diff

1326
config.guess vendored Executable file

File diff suppressed because it is too large Load diff

13
config.h.in Normal file
View file

@ -0,0 +1,13 @@
/* config.h.in. Generated from configure.in by autoheader. */
/* Define to 1 if you have the </usr/include/pgsql/ecpglib.h> header file. */
#undef HAVE__USR_INCLUDE_PGSQL_ECPGLIB_H
/* Define to 1 if you have the </usr/include/postgresql/ecpglib.h> header
file. */
#undef HAVE__USR_INCLUDE_POSTGRESQL_ECPGLIB_H
/* Define to 1 if you have the </usr/local/include/pgsql/ecpglib.h> header
file. */
#undef HAVE__USR_LOCAL_INCLUDE_PGSQL_ECPGLIB_H

12
config.make.in Normal file
View file

@ -0,0 +1,12 @@
ECPG=@ECPG@
MYSQL=@MYSQL@
ORACLE_HOME=@ORACLE_HOME@
POSTGRES=@POSTGRES@
ADDITIONAL_INCLUDE_DIRS += \
@INCD@ \
ADDITIONAL_LIB_DIRS += \
@LIBD@ \

1451
config.sub vendored Executable file

File diff suppressed because it is too large Load diff

5561
configure vendored Executable file

File diff suppressed because it is too large Load diff

184
configure.ac Normal file
View file

@ -0,0 +1,184 @@
dnl Process this file with autoconf to produce configure.
AC_INIT(SQLClient.h)
AC_CONFIG_HEADER(config.h)
AC_ARG_WITH(additional-include-dir,
[ --with-additional-include-dir=PATH specify additional include dirs to use],
additional_include_dir="$withval", additional_include_dir="no")
if test "$additional_include_dir" != "no"; then
CPPFLAGS="$CPPFLAGS $additional_include_dir"
INCD="$INCD $additional_include_dir"
fi
echo "Postgres development support"
AC_ARG_WITH(postgres-dir,
[ --with-postgres-dir=PATH specify postgres installation dir],
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"
fi
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
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
AC_SUBST(MYSQL)
AC_CHECK_HEADERS(libpq-fe.h)
if test "$ac_cv_header_libpq_fe_h" = "yes"; then
POSTGRES=yes
else
old="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS -I/usr/include/postgresql"
AC_CHECK_HEADERS(/usr/include/postgresql/libpq-fe.h)
CPPFLAGS="$old"
if test "$ac_cv_header__usr_include_postgresql_libpq_fe_h" = "yes"; then
INCD="$INCD -I/usr/include/postgresql"
POSTGRES=yes
else
CPPFLAGS="$CPPFLAGS -I/usr/include/pgsql"
AC_CHECK_HEADERS(/usr/include/pgsql/libpq-fe.h)
CPPFLAGS="$old"
if test "$ac_cv_header__usr_include_pgsql_libpq_fe_h" = "yes"; then
INCD="$INCD -I/usr/include/pgsql"
POSTGRES=yes
else
CPPFLAGS="$CPPFLAGS -I/usr/local/include/pgsql"
AC_CHECK_HEADERS(/usr/local/include/pgsql/libpq-fe.h)
CPPFLAGS="$old"
if test "$ac_cv_header__usr_local_include_pgsql_libpq_fe_h" = "yes"; then
INCD="$INCD -I/usr/local/include/pgsql"
POSTGRES=yes
else
CPPFLAGS="$save_CPPFLAGS"
POSTGRES=
echo "**************************************************************"
echo "Unable to locate libpq (postgres) headers (are they installed)"
echo "**************************************************************"
fi
fi
fi
fi
AC_CHECK_HEADERS(ecpglib.h)
if test "$ac_cv_header_ecpglib_h" = "yes"; then
ECPG=yes
else
old="$CPPFLAGS"
CPPFLAGS="$CPPFLAGS -I/usr/include/postgresql"
AC_CHECK_HEADERS(/usr/include/postgresql/ecpglib.h)
CPPFLAGS="$old"
if test "$ac_cv_header__usr_include_postgresql_ecpglib_h" = "yes"; then
INCD="$INCD -I/usr/include/postgresql"
ECPG=yes
else
CPPFLAGS="$CPPFLAGS -I/usr/include/pgsql"
AC_CHECK_HEADERS(/usr/include/pgsql/ecpglib.h)
CPPFLAGS="$old"
if test "$ac_cv_header__usr_include_pgsql_ecpglib_h" = "yes"; then
INCD="$INCD -I/usr/include/pgsql"
ECPG=yes
else
CPPFLAGS="$CPPFLAGS -I/usr/local/include/pgsql"
AC_CHECK_HEADERS(/usr/local/include/pgsql/ecpglib.h)
CPPFLAGS="$old"
if test "$ac_cv_header__usr_local_include_pgsql_ecpglib_h" = "yes"; then
INCD="$INCD -I/usr/local/include/pgsql"
ECPG=yes
else
CPPFLAGS="$save_CPPFLAGS"
ECPG=
echo "*************************************************************"
echo "Unable to locate ecpg (postgres) headers (are they installed)"
echo "*************************************************************"
fi
fi
fi
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"
fi
fi
AC_CHECK_LIB(pq,PQclear)
if test "$ac_cv_lib_pq_PQclear" != "yes"; then
POSTGRES=
echo "******************************************************"
echo "Unable to locate postgres pq library (is it installed)"
echo "******************************************************"
fi
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 "********************************************************"
fi
fi
AC_SUBST(POSTGRES)
AC_SUBST(ECPG)
ORACLE_HOME=
AC_SUBST(ORACLE_HOME)
AC_SUBST(INCD)
AC_SUBST(LIBD)
AC_SUBST(LIBS)
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 "$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)

250
install-sh Executable file
View file

@ -0,0 +1,250 @@
#! /bin/sh
#
# install - install a program, script, or datafile
# This comes from X11R5 (mit/util/scripts/install.sh).
#
# Copyright 1991 by the Massachusetts Institute of Technology
#
# Permission to use, copy, modify, distribute, and sell this software and its
# documentation for any purpose is hereby granted without fee, provided that
# the above copyright notice appear in all copies and that both that
# copyright notice and this permission notice appear in supporting
# documentation, and that the name of M.I.T. not be used in advertising or
# publicity pertaining to distribution of the software without specific,
# written prior permission. M.I.T. makes no representations about the
# suitability of this software for any purpose. It is provided "as is"
# without express or implied warranty.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch. It can only install one file at a time, a restriction
# shared with many OS's install programs.
# set DOITPROG to echo to test this script
# Don't use :- since 4.3BSD and earlier shells don't like it.
doit="${DOITPROG-}"
# put in absolute paths if you don't have them in your path; or use env. vars.
mvprog="${MVPROG-mv}"
cpprog="${CPPROG-cp}"
chmodprog="${CHMODPROG-chmod}"
chownprog="${CHOWNPROG-chown}"
chgrpprog="${CHGRPPROG-chgrp}"
stripprog="${STRIPPROG-strip}"
rmprog="${RMPROG-rm}"
mkdirprog="${MKDIRPROG-mkdir}"
transformbasename=""
transform_arg=""
instcmd="$mvprog"
chmodcmd="$chmodprog 0755"
chowncmd=""
chgrpcmd=""
stripcmd=""
rmcmd="$rmprog -f"
mvcmd="$mvprog"
src=""
dst=""
dir_arg=""
while [ x"$1" != x ]; do
case $1 in
-c) instcmd="$cpprog"
shift
continue;;
-d) dir_arg=true
shift
continue;;
-m) chmodcmd="$chmodprog $2"
shift
shift
continue;;
-o) chowncmd="$chownprog $2"
shift
shift
continue;;
-g) chgrpcmd="$chgrpprog $2"
shift
shift
continue;;
-s) stripcmd="$stripprog"
shift
continue;;
-t=*) transformarg=`echo $1 | sed 's/-t=//'`
shift
continue;;
-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
shift
continue;;
*) if [ x"$src" = x ]
then
src=$1
else
# this colon is to work around a 386BSD /bin/sh bug
:
dst=$1
fi
shift
continue;;
esac
done
if [ x"$src" = x ]
then
echo "install: no input file specified"
exit 1
else
true
fi
if [ x"$dir_arg" != x ]; then
dst=$src
src=""
if [ -d $dst ]; then
instcmd=:
else
instcmd=mkdir
fi
else
# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if [ -f $src -o -d $src ]
then
true
else
echo "install: $src does not exist"
exit 1
fi
if [ x"$dst" = x ]
then
echo "install: no destination specified"
exit 1
else
true
fi
# If destination is a directory, append the input filename; if your system
# does not like double slashes in filenames, you may need to add some logic
if [ -d $dst ]
then
dst="$dst"/`basename $src`
else
true
fi
fi
## this sed command emulates the dirname command
dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
# Make sure that the destination directory exists.
# this part is taken from Noah Friedman's mkinstalldirs script
# Skip lots of stat calls in the usual case.
if [ ! -d "$dstdir" ]; then
defaultIFS='
'
IFS="${IFS-${defaultIFS}}"
oIFS="${IFS}"
# Some sh's can't handle IFS=/ for some reason.
IFS='%'
set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
IFS="${oIFS}"
pathcomp=''
while [ $# -ne 0 ] ; do
pathcomp="${pathcomp}${1}"
shift
if [ ! -d "${pathcomp}" ] ;
then
$mkdirprog "${pathcomp}"
else
true
fi
pathcomp="${pathcomp}/"
done
fi
if [ x"$dir_arg" != x ]
then
$doit $instcmd $dst &&
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
else
# If we're going to rename the final executable, determine the name now.
if [ x"$transformarg" = x ]
then
dstfile=`basename $dst`
else
dstfile=`basename $dst $transformbasename |
sed $transformarg`$transformbasename
fi
# don't allow the sed command to completely eliminate the filename
if [ x"$dstfile" = x ]
then
dstfile=`basename $dst`
else
true
fi
# Make a temp file name in the proper directory.
dsttmp=$dstdir/#inst.$$#
# Move or copy the file name to the temp name
$doit $instcmd $src $dsttmp &&
trap "rm -f ${dsttmp}" 0 &&
# and set any options; do chmod last to preserve setuid bits
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $instcmd $src $dsttmp" command.
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
# Now rename the file to the real destination.
$doit $rmcmd -f $dstdir/$dstfile &&
$doit $mvcmd $dsttmp $dstdir/$dstfile
fi &&
exit 0

133
testECPG.m Normal file
View file

@ -0,0 +1,133 @@
/**
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
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 Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
$Date$ $Revision$
*/
#include <Foundation/Foundation.h>
#include "SQLClient.h"
int
main()
{
CREATE_AUTORELEASE_POOL(pool);
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"];
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 %u", [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);
RELEASE(pool);
return 0;
}

133
testMySQL.m Normal file
View file

@ -0,0 +1,133 @@
/**
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
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 Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
$Date$ $Revision$
*/
#include <Foundation/Foundation.h>
#include "SQLClient.h"
int
main()
{
CREATE_AUTORELEASE_POOL(pool);
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"];
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 %u", [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);
RELEASE(pool);
return 0;
}

133
testPostgres.m Normal file
View file

@ -0,0 +1,133 @@
/**
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <rfm@gnu.org>
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 Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
$Date$ $Revision$
*/
#include <Foundation/Foundation.h>
#include "SQLClient.h"
int
main()
{
CREATE_AUTORELEASE_POOL(pool);
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",
@"Postgres", @"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"];
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 %u", [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);
RELEASE(pool);
return 0;
}