-
Notifications
You must be signed in to change notification settings - Fork 2
/
SQLClient.h
2450 lines (2201 loc) · 96 KB
/
SQLClient.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Copyright (C) 2004 Free Software Foundation, Inc.
Written by: Richard Frith-Macdonald <[email protected]>
Date: April 2004
This file is part of the SQLClient Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
<title>SQLClient documentation</title>
<chapter>
<heading>The SQLClient library</heading>
<section>
<heading>What is the SQLClient library?</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>
SQLClient provides for the Objective-C programmer much the same thing
that JDBC provides for the Java programmer (though SQLClient is a bit
faster, easier to use, and easier to add new database backends for
than JDBC).
</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>
Simple API ([SQLTransaction])for combining multiple SQL statements
into a single transaction which can be used to minimise client-server
interactions to get the best possible performance from your database.
</item>
<item>
Supports multiple sumultaneous named connections to a database
server in a thread-safe manner.<br />
</item>
<item>
Supports multiple simultaneous connections to different database
servers with backend driver bundles loaded for different database
engines. Clear, simple subclassing of the abstract base class to
enable easy implementation of new backend bundles.
</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>
<item>
Support for standalone web applications ... eg to allow data to be
added to the database by people posting web forms to the application.
</item>
<item>
Supports notification of connection to and disconnection from the
database server.
</item>
</list>
</section>
<section>
<heading>What backend bundles are available?</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 was in production use
for over eighteen months, so it should be reliable, but inefficient.
</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 now well tested and known
to be efficient.
</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>
SQLite - a bundle using the sqlite3 library which supports an
SQL-like API for direct access to a database file (rather than
acting as a client of a database server process).<br />
Not as functional as the other backends (doesn't support dates
for instance), but good enough for many purposes and very
'lightweight'. See http://www.sqlite.org
</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>
<section>
<heading>Where can you get it? How can you install it?</heading>
<p>
The SQLClient library is currently only available via CVS from the
GNUstep CVS repository.<br />
See <https://savannah.gnu.org/cvs/?group=gnustep><br />
You need to check out <code>gnustep/dev-libs/SQLClient</code>
</p>
<p>
To build this library you must have a basic GNUstep environment set up ...
</p>
<list>
<item>
The gnustep-make package must have been built and installed.
</item>
<item>
The gnustep-base package must have been built and installed.
</item>
<item>
The Performance library (from the dev-libs area in GNUstep CVS)
must have been built and installed.
</item>
<item>
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.
</item>
<item>
Then you can run the test programs.
</item>
<item>
Your most likely problems are that the configure script may not
detect the database libraries you want ... Please figure out how
to modify <code>configure.ac</code> so that it will detect the
required headers and libraries on your system, and supply na patch.
</item>
<item>
Once the library is installed, you can include the header file
<code><SQLClient/SQLClient.h%gt;</code> and link your programs
with the <code>SQLClient</code> library to use it.
</item>
</list>
<p>
Bug reports, patches, and contributions (eg a backend bundle for a
new database) should be entered on the GNUstep project page
<http://savannah.gnu.org/projects/gnustep> and the bug
reporting page <http://savannah.gnu.org/bugs/?group=gnustep>
</p>
</section>
</chapter>
$Date$ $Revision$
*/
#ifndef INCLUDED_SQLClient_H
#define INCLUDED_SQLClient_H
#import <Foundation/NSArray.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>
@class NSConditionLock;
@class NSCountedSet;
@class NSMapTable;
@class NSMutableDictionary;
@class NSMutableSet;
@class NSRecursiveLock;
@class NSThread;
@class GSCache;
@class SQLClient;
@class SQLLiteral;
@class SQLTransaction;
/** Code including this header should define SQLCLIENT_COMPILE_TIME_QUOTE_CHECK
* to enable stricter compile time type checking to ensure that literal strings
* are used for sql queries/statements.<br />
* This makes arguments be expected to be SQLLiteral rather than NSString.
*/
#if defined(SQLCLIENT_COMPILE_TIME_QUOTE_CHECK)
#define SQLLitArg SQLLiteral
#else
#define SQLLitArg NSString
#endif
/**
* Notification sent when an instance becomes connected to the database
* server. The notification object is the instance connected.
*/
extern NSString * const SQLClientDidConnectNotification;
/**
* Notification sent when an instance becomes disconnected from the database
* server. The notification object is the instance disconnected.
*/
extern NSString * const SQLClientDidDisconnectNotification;
#if !defined(SQLCLIENT_PRIVATE)
#define SQLCLIENT_PRIVATE @private
#endif
/** This category is to extend NSObject with SQL oriented helper methods.
*/
@interface NSObject(SQLClient)
/** Trivial method to test a field in a record returned from the database
* to see if it is a NULL. This is equivalent to<br />
* (receiver == [NSNull null] ? YES : NO)<br />
*/
- (BOOL) isNull;
/** If the receiver can be represented as a 64bit integer,
* return the string literal representation as used in SQL,
* otherwise raise exception.
*/
- (SQLLiteral*) quoteBigInteger;
/** If the receiver can be represented as a 64bit non-negative integer,
* return the string literal representation as used in SQL,
* otherwise raise exception.
*/
- (SQLLiteral*) quoteBigNatural;
/** If the receiver can be represented as a 64bit positive (not zero) integer,
* return the string literal representation as used in SQL,
* otherwise raise exception.
*/
- (SQLLiteral*) quoteBigPositive;
/** If the -boolValue of the -description of the receiver is YES,
* return the string literal representation of the SQL true boolean,
* otherwise return the string literal false boolean.
*/
- (SQLLiteral*) quoteInteger;
/** Classes may override this method to provide a value for use as part of
* an SQL query or statement. The method is used internally when quoting
* objects.<br />
* The db argument may be examined to enable a class to support different
* quoting for different database backends, but an implementation must at
* least support quoting appropriate for standard SQL.<br />
* The default NSObject implementation simply returns nil, which means that
* the object may not be used in an SQL query/statement.
*/
- (SQLLiteral*) quoteForSQLClient: (SQLClient*)db;
/** If the receiver can be represented as a 32bit integer,
* return the string literal representation as used in SQL,
* otherwise raise exception.
*/
- (SQLLiteral*) quoteInteger;
/** If the receiver can be represented as a 32bit non-negative integer,
* return the string literal representation as used in SQL,
* otherwise raise exception.
*/
- (SQLLiteral*) quoteNatural;
/** If the receiver can be represented as a 32bit positive (not zero) integer,
* return the string literal representation as used in SQL,
* otherwise raise exception.
*/
- (SQLLiteral*) quotePositive;
@end
/** This class is used to hold key information for a set of SQLRecord
* objects produced by a single query.
*/
@interface SQLRecordKeys : NSObject
{
NSUInteger count; // Number of keys
NSArray *order; // Keys in order
NSMapTable *map; // Key to index
NSMapTable *low; // lowercase map
NSUInteger bytes; // Size in bytes
}
/** Returns the number of keys in the receiver.
*/
- (NSUInteger) count;
/** Returns the index of the object with the specified key,
* or NSNotFound if there is no such key.
*/
- (NSUInteger) indexForKey: (NSString*)key;
/** Initialiser
*/
- (id) initWithKeys: (NSString**)keys count: (NSUInteger)c;
/** Returns an array containing the record field names in order.
*/
- (NSArray*) order;
@end
/**
* <p>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.
* </p>
* <p>SQLRecord is the abstract base class of a class cluster.
* If you wish to subclass it you must implement the primitive methods
* +newWithValues:keys:count: -count -keyAtIndex: -objectAtIndex:
* and -replaceObjectAtIndex:withObject:
* </p>
* <p>NB. You do not need to use SQLRecord (or a subclass of it), all you
* actually need to supply is a class which responds to the
* +newWithValues:keys:count: method that the system uses to create
* new records ... none of the other methods of the SQLRecord class
* are used internally by the SQLClient system.
* </p>
*/
@interface SQLRecord : NSArray
/**
* Create a new SQLRecord containing the specified fields.<br />
* NB. The values and keys are <em>retained</em> by the record rather
* than being copied.<br />
* A nil value is represented by [NSNull null].<br />
* Keys must be unique string values (case insensitive comparison).
*/
+ (id) newWithValues: (id*)v
keys: (NSString**)k
count: (unsigned int)c;
/**
* Create a new SQLRecord containing the specified fields.<br />
* NB. The values and keys are <em>retained</em> by the record rather
* than being copied.<br />
* A nil value is represented by [NSNull null].<br />
* This constructor will be used for subsequent records after the first
* in a query iff the first record created returns a non-nil result when
* sent the -keys method.
*/
+ (id) newWithValues: (id*)v keys: (SQLRecordKeys*)k;
/**
* Returns an array containing the names of all the fields in the record.
*/
- (NSArray*) allKeys;
/**
* Returns the number of items in the record.<br />
* Subclasses must implement this method.
*/
- (NSUInteger) count;
/**
* Return the record as a mutable dictionary with the keys as the
* record field names standardised to be lowercase strings.
*/
- (NSMutableDictionary*) dictionary;
/**
* Optimised mechanism for retrieving all keys in order.
*/
- (void) getKeys: (id*)buf;
/**
* Optimised mechanism for retrieving all objects.
*/
- (void) getObjects: (id*)buf;
/** <override-subclass />
* Returns the key at the specified index.<br />
*/
- (NSString*) keyAtIndex: (NSUInteger)index;
/** Returns the keys used by this record.
* The abstract class returns nil, so subclasses should override if
* they wish to make use of the +newWithValues:keys: method.
*/
- (SQLRecordKeys*) keys;
/** <override-subclass />
* Returns the object at the specified indes.<br />
*/
- (id) objectAtIndex: (NSUInteger)index;
/**
* Returns the value of the named field.<br />
* The field name is case insensitive.
*/
- (id) objectForKey: (NSString*)key;
/**
* Replaces the value at the specified index.<br />
* Subclasses must implement this method.
*/
- (void) replaceObjectAtIndex: (NSUInteger)index withObject: (id)anObject;
/**
* Replaces the value of the named field.<br />
* The field name is case insensitive.<br />
* NB. You must be careful not to change the contents of a record which
* has been cached (unless you are sure you really want to), as you will
* be changing the contents of the cache, not just a private copy.
*/
- (void) setObject: (id)anObject forKey: (NSString*)aKey;
/**
* Return approximate size of this record in bytes.<br />
* The exclude set is used to specify objects to exclude from the
* calculation (to prevent recursion etc).
*/
- (NSUInteger) sizeInBytes: (NSMutableSet*)exclude;
@end
extern NSString *SQLException;
extern NSString *SQLConnectionException;
extern NSString *SQLEmptyException;
extern NSString *SQLUniqueException;
/**
* Returns the timestamp of the most recent call to SQLClientTimeNow().
*/
extern NSTimeInterval SQLClientTimeLast();
/**
* Convenience function to provide timing information quickly.<br />
* This returns the current date/time, and stores the value for use
* by the SQLClientTimeLast() function.
*/
extern NSTimeInterval SQLClientTimeNow();
/**
* This returns the timestamp from which any of the SQLClient classes was
* first used or SQLClientTimeNow() was first called (whichever came first).
*/
extern NSTimeInterval SQLClientTimeStart();
/**
* A convenience method to return the current clock 'tick' ... which is
* the current second based on the time we started. This does <em>not</em>
* check the current time, but relies on SQLClientTimeLast() returning an
* up to date value (so if you need an accurate tick, you should ensure
* that SQLClientTimeNow() is called at least once a second).<br />
* The returned value is always greater than zero, and is basically
* calculated as (SQLClientTimeLast() - SQLClientTimeStart() + 1).<br />
* In the event that the system clock is reset into the past, the value
* of SQLClientTimeStart() is automatically adjusted to ensure that the
* result of a call to SQLClientTimeTick() is never less than the result
* of any earlier call to the function.
*/
extern unsigned SQLClientTimeTick();
@class SQLClientPool;
/**
* <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
{
SQLCLIENT_PRIVATE
void *extra; /** For subclass specific data */
NSRecursiveLock *lock; /** Maintain thread-safety */
/**
* A flag indicating whether this instance is currently connected to
* the backend database server. This variable must <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? */
/**
* A flag indicating whether leading and trailing white space in values
* read from the database should automatically be removed.<br />
* This should only be modified by the -setShouldTrim: method.
*/
BOOL _shouldTrim; /** Should whitespace be trimmed? */
NSString *_name; /** Unique identifier for instance */
NSString *_client; /** Identifier within backend */
NSString *_database; /** The configured database name/host */
NSString *_password; /** The configured password */
NSString *_user; /** The configured user */
NSMutableArray *_statements; /** Uncommitted statements */
/**
* Timestamp of completion of last operation.<br />
* Maintained by -simpleExecute: -simpleQuery:recordType:listType:
* and [SQLClient(Caching)-cache:simpleQuery:recordType:listType:]
* Also set for a failed connection attempt, but not reported by the
* -lastOperation method in that case.
*/
NSTimeInterval _lastOperation;
NSTimeInterval _lastConnect; /** Last successful connect */
NSTimeInterval _lastStart; /** Last op start or connect */
NSTimeInterval _waitLock; /** When we blocked for locking */
NSTimeInterval _waitPool; /** When we blocked for pool access */
NSTimeInterval _duration; /** Duration logging threshold */
uint64_t _committed; /** Count of committed transactions */
unsigned int _debugging; /** The current debugging level */
GSCache *_cache; /** The cache for query results */
NSThread *_cacheThread; /** Thread for cache queries */
unsigned int _connectFails; /** The count of connection failures */
NSMapTable *_observers; /** Observations of async events */
NSCountedSet *_names; /** Track notification names */
SQLClientPool *_pool; /** The pool of the client (or nil) */
/** Allow for extensions by allocating memory and pointing to it from
* the _extra ivar. That way we can avoid binary incompatibility between
* minor releases.
*/
void *_extra;
}
/**
* Returns an array containing all the SQLClient instances .
*/
+ (NSArray*) allClients;
/**
* Return an existing SQLClient instance (using +existingClient:) if possible,
* or creates one, initialises it using -initWithConfiguration:name:, and
* returns the new instance (autoreleased).<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;
/**
* Returns the maximum number of simultaneous database connections
* permitted (set by +setMaxConnections: and defaults to 8) for
* connections outside of SQLClientPool instances.
*/
+ (unsigned int) maxConnections;
/**
* <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>
* <p>Purging does not apply to connections made by SQLClientPool
* instances.
* </p>
*/
+ (void) purgeConnections: (NSDate*)since;
/** Sets the retry period after which connection attempts are abandoned.
* a delay less than or equal to zero means that connection attempts are
* abandoned after the first failure (the -connect method behaves the
* same way as the -tryConnect method).
*/
+ (void) setAbandonFailedConnectionsAfter: (NSTimeInterval)delay;
/**
* <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>
* <p>Connections used by SQLClientPool instances are not considered by
* this maximum.
* </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>
* <p>Where possible, consider using the [SQLTransaction] class rather
* than calling -begin -commit or -rollback yourself.
* </p>
*/
- (void) begin;
/** Returns the number of committed transactions.
*/
- (uint64_t) committed;
/** This grabs the receiver for use by the current thread.<br />
* If limit is nil or in the past, makes a single immediate attempt.<br />
* Returns NO if it fails to obtain a lock by the specified date.<br />
* Must be matched by an -unlock if it succeeds.
*/
- (BOOL) lockBeforeDate: (NSDate*)limit;
/** <p>Build an sql query string using the supplied arguments to call
* [SQLClient-prepare:args:] to build a query and raises an exception
* if the result is not a simple query string.
* </p>
* <p>This method has at least one argument, the string starting the
* query 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 />
* Arguments in the list are automatically quoted as necessary, with the
* behavior for string arguments being controlled by the autoquote setting.
* </p>
* <example>
* sql = [db buildQuery: @"SELECT Name FROM ", table, nil];
* </example>
* <p>Upon error, an exception is raised.
* </p>
* <p>The method returns a string containing sql suitable for passing to
* the -simpleQuery:recordType:listType:
* or [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] methods.
* </p>
*/
- (SQLLiteral*) buildQuery: (NSString*)stmt,...;
/** <p>Build an sql query string using the supplied arguments to call
* [SQLClient-prepare:with:] to build a query and raises an exception
* if the result is not a simple query string.<br />
* Takes the query statement and substitutes in values from
* the dictionary where markup of the format {key} is found.<br />
* Returns the resulting query string.
* </p>
* <example>
* sql = [db buildQuery: @"SELECT Name FROM {Table} WHERE ID = {ID}"
* with: values];
* </example>
* <p>Arguments in the dictionary are automatically quoted as necessary,
* with the behavior for string arguments being controlled by the autoquote
* setting.<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.
* </p>
* <p>The method returns a string containing sql suitable for passing to
* the -simpleQuery:recordType:listType:
* or [SQLClient(Caching)-cache:simpleQuery:recordType:listType:] methods.
* </p>
*/
- (SQLLiteral*) buildQuery: (NSString*)stmt with: (NSDictionary*)values;
/**
* 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>
* <p>Where possible, consider using the [SQLTransaction] class rather
* than calling -begin -commit or -rollback yourself.
* </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.<br />
* This method also counts the number of consecutive failed connection
* attempts. A delay is enforced between each connection attempt, with
* the length of the delay growing with each failure. This ensures
* that applications which fail to deal with connection failures, and
* just keep trying to reconnect, will not overload the system/server.<br />
* The maximum delay is 30 seconds, so when the database server is restarted,
* the application can reconnect reasonably quickly.<br />
* If the connection attempt fails it is repeated until it succeds or until
* the time interval specified by +setAbandonFailedConnectionsAfter: has
* passed.
*/
- (BOOL) connect;
/**
* Return a flag to say whether a connection to the database server is
* currently live (the value of the 'connected' instance variable).<br />
* This is mostly useful for debug/reporting.
*/
- (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 -query:,... method.<br />
* Arguments in the list are automatically quoted as necessary, with the
* behavior for string arguments being controlled by the autoquote setting.
* <example>
* [db execute: @"UPDATE ", table, @" SET Name = ",
* myName, " WHERE ID = ", myId, nil];
* </example>
* Where the database backend support it, this method returns the count of
* the number of rows to which the operation applied. Otherwise this
* returns -1.
*/
- (NSInteger) execute: (NSString*)stmt,...;
/**
* Takes the statement and substitutes in values from
* the dictionary where markup of the format {key} is found.<br />
* Passes the result to the -execute:,... method.
* <example>
* [db execute: @"UPDATE {Table} SET Name = {Name} WHERE ID = {ID}"
* with: values];
* </example>
* Arguments in the dictionary are automatically quoted as necessary,
* with the behavior for string arguments being controlled by the autoquote
* setting.<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.<br />
* Where the database backend support it, this method returns the count of
* the number of rows to which the operation applied. Otherwise this
* returns -1.
*/
- (NSInteger) execute: (NSString*)stmt with: (NSDictionary*)values;
/**
* Calls -initWithConfiguration:name: passing a nil reference name.
*/
- (id) initWithConfiguration: (NSDictionary*)config;
/**
* Calls -initWithConfiguration:name:pool: passing NO to say the client is
* not in a pool.
*/
- (id) initWithConfiguration: (NSDictionary*)config
name: (NSString*)reference;
/**
* Initialise using the supplied configuration, or if that is nil, try to
* use values from NSUserDefaults (and automatically update when the
* defaults change).<br />
* Uses the reference name to determine configuration information ... and if
* a nil name is supplied, defaults to the value of SQLClientName in the
* configuration dictionary (or in the standard user defaults). If there is
* no value for SQLClientName, uses the string 'Database'.<br />
* If pool is nil and a SQLClient instance already exists with the
* name used for this instance, the receiver is deallocated and the existing
* instance is retained and returned ... there may only ever be one instance
* for a particular reference name which is not in a pool.<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 />
* The database name may be of the format 'name@host:port' when you wish to
* connect to a database on a different host over the network.
*/
- (id) initWithConfiguration: (NSDictionary*)config
name: (NSString*)reference
pool: (SQLClientPool*)pool;
/** Two clients are considered equal if they refer to the same database
* and are logged in as the same database user using the same protocol.
* These are the general criteria for transactions to be compatoible so
* that an SQLTransaction object generated by one client can be used by
* the other.
*/
- (BOOL) isEqual: (id)other;
/**
* Return the state of the flag indicating whether the library thinks
* a transaction is in progress. This flag is normally maintained by
* -begin, -commit, and -rollback.
*/
- (BOOL) isInTransaction;
/**
* Returns the date/time stamp of the last database connection established
* by the receiver, or nil if no connection has ever been established.
*/
- (NSDate*) lastConnect;
/**
* Returns the date/time stamp of the last database operation performed
* by the receiver, or nil if no operation has ever been done by it.<br />
* Simply connecting to or disconnecting from the databsse does not
* count as an operation.
*/
- (NSDate*) lastOperation;
/** Compares the receiver with the other client to see which one has been
* inactive but connected for longest (if they are connected) and returns
* that instance.<br />
* If neither is idle but connected, the method returns nil.<br />
* In a tie, the method returns the other instance.
*/
- (SQLClient*) longestIdle: (SQLClient*)other;
/**
* Return the database reference name for this instance (or nil).
*/
- (NSString*) name;
/**
* Return the database password for this instance (or nil).
*/
- (NSString*) password;
/** Calls [SQLClient-prepare:args:] where the argument list needs to be
* a nil terminated list of objects.
*/
- (NSMutableArray*) prepare: (NSString*)stmt, ...;
/**
* This is the method used to convert a query or statement to a standard
* form used internally by other methods.<br />
* This works to build an sql string by quoting any non-literal objects
* according to the autoquote setting, and concatenating the resulting
* strings in a nil terminated list.<br />
* Returns an array containing the statement as the first object and
* any NSData objects following. The NSData objects appear in the
* statement strings as the marker sequence - <code>'?'''?'</code><br />
* If the returned array contains a single object, that object is a
* simple SQL query/statement.
*/
- (NSMutableArray*) prepare: (NSString*)stmt args: (va_list)args;
/** This method is like [SQLClient-prepare:args:] but takes a dictionary of
* values to be substituted into the sql string.
*/
- (NSMutableArray*) prepare: (NSString*)stmt with: (NSDictionary*)values;
/**
* <p>Perform arbitrary query <em>which returns values.</em>
* </p>
* <p>This method handles its arguments in the same way as the -buildQuery:,...
* method and returns the result of the query.
* </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>Timestamp field items (a date and time) are returned as NSDate objects.
* If the database contains no timezone information, the local timezone
* is used.
* </p>
*/
- (NSMutableArray*) query: (NSString*)stmt,...;
/**
* Takes the query statement and substitutes in values from
* the dictionary (in the same manner as the -buildQuery:with: method)
* then executes the query and returns the response.<br />
* <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 />
* Subclasses may override this method to provide appropriate quoting for
* types of object which need database backend specific quoting conventions.
* However, the default implementation should be OK for most cases:<br />
* This method makes use of -quoteString: to quote strings.<br />
* It formats NSDate objects as YYYY-MM-DD hh:mm:ss.mmm ?ZZZZ.<br />
* For NSNumber objects it simply uses their string descriptions.<br />
* For NSNull and nil the method returns NULL.<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.<br />
* NSArray and NSSet objects are quoted as sets containing the quoted
* elements from the collection. If you want to use SQL arrays (and your
* database backend supports it) you must explicitly use the
* -quoteArray: method to convert an NSArray to a literal database array
* representation.<br />
* Other classes are not supported unless they implement the
* -quoteForSQLClient: method to return a non-nil literal string value.<br />
* Attempts to quote an object of an unsupported class (one where the
* method returns nil) will cause an NSInvalidArgumentException.
*/
- (SQLLiteral*) quote: (id)obj;
/**
* Produce a quoted string from the supplied arguments (printf style).
*/
- (SQLLiteral*) quotef: (NSString*)fmt, ...;
/* Produce a quoted string from an array on databases where arrays are
* supported (currently only Postgres). This method is implemented by
* calling -quoteArray:toString:quotingStrings: with the option to NOT
* quote strings found in the array.
*/
- (SQLLiteral*) quoteArray: (NSArray*)a;
/* Produce a quoted string from an array on databases where arrays are
* supported (currently only Postgres). This method is implemented by
* calling -quoteArray:toString:quotingStrings: with the option to
* quote strings found in the array.
*/
- (SQLLiteral*) quoteArraySafe: (NSArray*)a;
/* Produce a quoted string from an array on databases where arrays are
* supported (currently only Postgres).<br />
* If the s argument is nil, a new mutable string is created and returned.
* If the s argument is not nil, the quoted array is appended to it rather
* than being produced in a new string (this method uses that feature to
* recursively quote nested arrays) and the method returns the argument.<br />
* The q argument determines whether string values found in the array