2 * Copyright (c) 2017 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 #import "SFSQLiteStatement.h"
26 #import "SFObjCType.h"
28 @interface SFSQLiteStatement ()
29 @property (nonatomic, strong) NSMutableArray *temporaryBoundObjects;
31 @implementation SFSQLiteStatement
33 @synthesize SQLite = _SQLite;
34 @synthesize SQL = _SQL;
35 @synthesize handle = _handle;
36 @synthesize reset = _reset;
37 @synthesize temporaryBoundObjects = _temporaryBoundObjects;
39 - (id)initWithSQLite:(SFSQLite *)SQLite SQL:(NSString *)SQL handle:(sqlite3_stmt *)handle {
40 if ((self = [super init])) {
49 - (void)finalizeStatement {
50 SFSQLite *strongSQLite = _SQLite;
53 [strongSQLite raise: @"Statement not reset after last use: \"%@\"", _SQL];
55 if (sqlite3_finalize(_handle)) {
56 [strongSQLite raise:@"Error finalizing prepared statement: \"%@\"", _SQL];
60 - (void)resetAfterStepError
63 (void)sqlite3_reset(_handle); // we expect this to return an error
64 (void)sqlite3_clear_bindings(_handle);
65 [_temporaryBoundObjects removeAllObjects];
75 int rc = sqlite3_step(_handle);
76 if ((rc & 0x00FF) == SQLITE_ROW) {
78 } else if ((rc & 0x00FF) == SQLITE_DONE) {
81 [self resetAfterStepError];
82 [_SQLite raise:@"Failed to step (%d): \"%@\"", rc, _SQL];
88 SFSQLite *strongSQLite = _SQLite;
91 if (sqlite3_reset(_handle)) {
92 [strongSQLite raise:@"Error resetting prepared statement: \"%@\"", _SQL];
95 if (sqlite3_clear_bindings(_handle)) {
96 [strongSQLite raise:@"Error clearing prepared statement bindings: \"%@\"", _SQL];
98 [_temporaryBoundObjects removeAllObjects];
103 - (void)bindInt:(SInt32)value atIndex:(NSUInteger)index {
104 NSAssert(_reset, @"Statement is not reset: \"%@\"", _SQL);
106 if (sqlite3_bind_int(_handle, (int)index+1, value)) {
107 [_SQLite raise:@"Error binding int at %ld: \"%@\"", (unsigned long)index, _SQL];
111 - (void)bindInt64:(SInt64)value atIndex:(NSUInteger)index {
112 NSAssert(_reset, @"Statement is not reset: \"%@\"", _SQL);
114 if (sqlite3_bind_int64(_handle, (int)index+1, value)) {
115 [_SQLite raise:@"Error binding int64 at %ld: \"%@\"", (unsigned long)index, _SQL];
119 - (void)bindDouble:(double)value atIndex:(NSUInteger)index {
120 NSAssert(_reset, @"Statement is not reset: \"%@\"", _SQL);
122 if (sqlite3_bind_double(_handle, (int)index+1, value)) {
123 [_SQLite raise:@"Error binding double at %ld: \"%@\"", (unsigned long)index, _SQL];
127 - (void)bindBlob:(NSData *)value atIndex:(NSUInteger)index {
128 NSAssert(_reset, @"Statement is not reset: \"%@\"", _SQL);
131 NS_VALID_UNTIL_END_OF_SCOPE NSData *arcSafeValue = value;
132 if (sqlite3_bind_blob(_handle, (int)index+1, [arcSafeValue bytes], (int)[arcSafeValue length], NULL)) {
133 [_SQLite raise:@"Error binding blob at %ld: \"%@\"", (unsigned long)index, _SQL];
136 [self bindNullAtIndex:index];
140 - (void)bindText:(NSString *)value atIndex:(NSUInteger)index {
141 NSAssert(_reset, @"Statement is not reset: \"%@\"", _SQL);
144 NS_VALID_UNTIL_END_OF_SCOPE NSString *arcSafeValue = value;
145 if (sqlite3_bind_text(_handle, (int)index+1, [arcSafeValue UTF8String], -1, NULL)) {
146 [_SQLite raise:@"Error binding text at %ld: \"%@\"", (unsigned long)index, _SQL];
149 [self bindNullAtIndex:index];
153 - (void)bindNullAtIndex:(NSUInteger)index {
154 int rc = sqlite3_bind_null(_handle, (int)index+1);
155 if ((rc & 0x00FF) != SQLITE_OK) {
156 [_SQLite raise:@"sqlite3_bind_null error"];
160 - (id)retainedTemporaryBoundObject:(id)object
162 if (!_temporaryBoundObjects) {
163 _temporaryBoundObjects = [NSMutableArray new];
165 [_temporaryBoundObjects addObject:object];
169 - (void)bindValue:(id)value atIndex:(NSUInteger)index {
170 if ([value isKindOfClass:[NSNumber class]]) {
171 SFObjCType *type = [SFObjCType typeForValue:value];
172 if (type.isIntegerNumber) {
173 if (type.size <= 4) {
174 [self bindInt:[value intValue] atIndex:index];
176 [self bindInt64:[value longLongValue] atIndex:index];
179 NSAssert(type.isFloatingPointNumber, @"Expected number type to be either integer or floating point");
180 if (type.code == SFObjCTypeFloat) {
181 [self bindInt:[value intValue] atIndex:index];
183 NSAssert(type.code == SFObjCTypeDouble, @"Unexpected floating point number type: %@", type);
184 [self bindInt64:[value longLongValue] atIndex:index];
187 } else if ([value isKindOfClass:[NSData class]]) {
188 [self bindBlob:value atIndex:index];
189 } else if ([value isKindOfClass:[NSUUID class]]) {
191 [(NSUUID *)value getUUIDBytes:uuid];
192 [self bindBlob:[self retainedTemporaryBoundObject:[NSData dataWithBytes:uuid length:sizeof(uuid_t)]] atIndex:index];
193 } else if ([value isKindOfClass:[NSString class]]) {
194 [self bindText:value atIndex:index];
195 } else if ([value isKindOfClass:[NSNull class]]) {
196 [self bindNullAtIndex:index];
197 } else if ([value isKindOfClass:[NSDate class]]) {
198 [self bindDouble:[(NSDate *)value timeIntervalSinceReferenceDate] atIndex:index];
199 } else if ([value isKindOfClass:[NSError class]]) {
200 [self bindBlob:[self retainedTemporaryBoundObject:[NSKeyedArchiver archivedDataWithRootObject:value]] atIndex:index];
201 } else if ([value isKindOfClass:[NSURL class]]) {
202 [self bindText:[self retainedTemporaryBoundObject:[value absoluteString]] atIndex:index];
204 [NSException raise:NSInvalidArgumentException format:@"Can't bind object of type %@", [value class]];
208 - (void)bindValues:(NSArray *)values {
209 for (NSUInteger i = 0; i < values.count; i++) {
210 [self bindValue:values[i] atIndex:i];
214 - (NSUInteger)columnCount {
215 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
217 return sqlite3_column_count(_handle);
220 - (int)columnTypeAtIndex:(NSUInteger)index {
221 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
223 return sqlite3_column_type(_handle, (int)index);
226 - (NSString *)columnNameAtIndex:(NSUInteger)index {
227 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
229 return @(sqlite3_column_name(_handle, (int)index));
232 - (SInt32)intAtIndex:(NSUInteger)index {
233 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
235 return sqlite3_column_int(_handle, (int)index);
238 - (SInt64)int64AtIndex:(NSUInteger)index {
239 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
241 return sqlite3_column_int64(_handle, (int)index);
244 - (double)doubleAtIndex:(NSUInteger)index {
245 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
247 return sqlite3_column_double(_handle, (int)index);
250 - (NSData *)blobAtIndex:(NSUInteger)index {
251 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
253 const void *bytes = sqlite3_column_blob(_handle, (int)index);
255 int length = sqlite3_column_bytes(_handle, (int)index);
256 return [NSData dataWithBytes:bytes length:length];
262 - (NSString *)textAtIndex:(NSUInteger)index {
263 NSAssert(!_reset, @"Statement is reset: \"%@\"", _SQL);
265 const char *text = (const char *)sqlite3_column_text(_handle, (int)index);
273 - (id)objectAtIndex:(NSUInteger)index {
274 int type = [self columnTypeAtIndex:index];
277 return @([self int64AtIndex:index]);
280 return @([self doubleAtIndex:index]);
283 return [self textAtIndex:index];
286 return [self blobAtIndex:index];
292 [NSException raise:NSGenericException format:@"Unexpected column type: %d", type];
297 - (NSArray *)allObjects {
298 NSUInteger columnCount = [self columnCount];
299 NSMutableArray *objects = [NSMutableArray arrayWithCapacity:columnCount];
300 for (NSUInteger i = 0; i < columnCount; i++) {
301 objects[i] = [self objectAtIndex:i] ?: [NSNull null];
306 - (NSDictionary *)allObjectsByColumnName {
307 NSUInteger columnCount = [self columnCount];
308 NSMutableDictionary *objectsByColumnName = [NSMutableDictionary dictionaryWithCapacity:columnCount];
309 for (NSUInteger i = 0; i < columnCount; i++) {
310 NSString *columnName = [self columnNameAtIndex:i];
311 id object = [self objectAtIndex:i];
313 objectsByColumnName[columnName] = object;
316 return objectsByColumnName;