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
|
/* SQLite.m
*
* Copyright (C) 2006-2013 Free Software Foundation, Inc.
*
* Author: Enrico Sersale <enrico@imago.ro>
* Date: May 2006
*
* This file is part of the GNUstep GWorkspace application
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <float.h>
#include "config.h"
#import "SQLite.h"
#define GWDebugLog(format, args...) \
do { if (GW_DEBUG_LOG) \
NSLog(format , ## args); } while (0)
#define MAX_RETRY 1000
@implementation SQLite
- (void)dealloc
{
if (db != NULL) {
sqlite3_close(db);
}
RELEASE (preparedStatements);
[super dealloc];
}
+ (id)handlerForDbAtPath:(NSString *)path
isNew:(BOOL *)isnew
{
return TEST_AUTORELEASE ([[self alloc] initForDbAtPath: path isNew: isnew]);
}
- (id)initForDbAtPath:(NSString *)path
isNew:(BOOL *)isnew
{
self = [super init];
if (self) {
preparedStatements = [NSMutableDictionary new];
db = NULL;
fm = [NSFileManager defaultManager];
if ([self opendbAtPath: path isNew: isnew] == NO) {
DESTROY (self);
return self;
}
}
return self;
}
- (id)init
{
self = [super init];
if (self) {
preparedStatements = [NSMutableDictionary new];
db = NULL;
fm = [NSFileManager defaultManager];
}
return self;
}
- (BOOL)opendbAtPath:(NSString *)path
isNew:(BOOL *)isnew
{
*isnew = ([fm fileExistsAtPath: path] == NO);
if (db == NULL) {
NSArray *components = [path pathComponents];
unsigned count = [components count];
NSString *dbname = [components objectAtIndex: count - 1];
NSString *dbpath = [NSString string];
unsigned i;
for (i = 0; i < (count - 1); i++) {
NSString *dir = [components objectAtIndex: i];
BOOL isdir;
dbpath = [dbpath stringByAppendingPathComponent: dir];
if (([fm fileExistsAtPath: dbpath isDirectory: &isdir] &isdir) == NO) {
if ([fm createDirectoryAtPath: dbpath attributes: nil] == NO) {
NSLog(@"unable to create: %@", dbpath);
return NO;
}
}
}
dbpath = [dbpath stringByAppendingPathComponent: dbname];
if (sqlite3_open([dbpath fileSystemRepresentation], &db) != SQLITE_OK) {
NSLog(@"%s", sqlite3_errmsg(db));
return NO;
}
return YES;
}
return NO;
}
- (BOOL)attachDbAtPath:(NSString *)path
withName:(NSString *)name
isNew:(BOOL *)isnew
{
*isnew = ([fm fileExistsAtPath: path] == NO);
if (db != NULL) {
NSArray *components = [path pathComponents];
unsigned count = [components count];
NSString *dbname = [components objectAtIndex: count - 1];
NSString *dbpath = [NSString string];
NSString *query;
unsigned i;
for (i = 0; i < (count - 1); i++) {
NSString *dir = [components objectAtIndex: i];
BOOL isdir;
dbpath = [dbpath stringByAppendingPathComponent: dir];
if (([fm fileExistsAtPath: dbpath isDirectory: &isdir] &isdir) == NO) {
if ([fm createDirectoryAtPath: dbpath attributes: nil] == NO) {
NSLog(@"unable to create: %@", dbpath);
return NO;
}
}
}
dbpath = [dbpath stringByAppendingPathComponent: dbname];
query = [NSString stringWithFormat: @"ATTACH DATABASE '%@' AS %@", dbpath, name];
return [self executeSimpleQuery: query];
}
return NO;
}
- (void)closeDb
{
if (db != NULL) {
sqlite3_close(db);
db = NULL;
}
}
- (sqlite3 *)db
{
return db;
}
- (BOOL)executeSimpleQuery:(NSString *)query
{
char *err;
if (sqlite3_exec(db, [query UTF8String], NULL, 0, &err) != SQLITE_OK) {
NSLog(@"error at %@", query);
if (err != NULL) {
NSLog(@"%s", err);
sqlite3_free(err);
}
return NO;
}
return YES;
}
- (BOOL)executeQuery:(NSString *)query
{
const char *qbuff = [query UTF8String];
struct sqlite3_stmt *stmt;
int retry = 0;
int err;
err = sqlite3_prepare(db, qbuff, strlen(qbuff), &stmt, NULL);
if (err != SQLITE_OK) {
NSLog(@"%s", sqlite3_errmsg(db));
return NO;
}
while (1) {
err = sqlite3_step(stmt);
if (err == SQLITE_DONE) {
break;
} else if (err == SQLITE_BUSY) {
CREATE_AUTORELEASE_POOL(arp);
NSDate *when = [NSDate dateWithTimeIntervalSinceNow: 0.1];
[NSThread sleepUntilDate: when];
GWDebugLog(@"retry %i", retry);
RELEASE (arp);
if (retry++ >= MAX_RETRY) {
NSLog(@"timeout for query: %@", query);
NSLog(@"%s", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
return NO;
}
} else {
NSLog(@"error at: %@", query);
NSLog(@"%s", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
return NO;
}
}
sqlite3_finalize(stmt);
return YES;
}
- (NSArray *)resultsOfQuery:(NSString *)query
{
const char *qbuff = [query UTF8String];
NSMutableArray *lines = [NSMutableArray array];
struct sqlite3_stmt *stmt;
int retry = 0;
int err;
int i;
if (sqlite3_prepare(db, qbuff, strlen(qbuff), &stmt, NULL) == SQLITE_OK) {
while (1) {
err = sqlite3_step(stmt);
if (err == SQLITE_ROW) {
NSMutableDictionary *line = [NSMutableDictionary dictionary];
int count = sqlite3_data_count(stmt);
// we use "<= count" because sqlite sends also
// the id of the entry with type = 0
for (i = 0; i <= count; i++) {
const char *name = sqlite3_column_name(stmt, i);
if (name != NULL) {
int type = sqlite3_column_type(stmt, i);
if (type == SQLITE_INTEGER) {
[line setObject: [NSNumber numberWithInt: sqlite3_column_int(stmt, i)]
forKey: [NSString stringWithUTF8String: name]];
} else if (type == SQLITE_FLOAT) {
[line setObject: [NSNumber numberWithDouble: sqlite3_column_double(stmt, i)]
forKey: [NSString stringWithUTF8String: name]];
} else if (type == SQLITE_TEXT) {
[line setObject: [NSString stringWithUTF8String: (const char *)sqlite3_column_text(stmt, i)]
forKey: [NSString stringWithUTF8String: name]];
} else if (type == SQLITE_BLOB) {
const void *bytes = sqlite3_column_blob(stmt, i);
int length = sqlite3_column_bytes(stmt, i);
[line setObject: [NSData dataWithBytes: bytes length: length]
forKey: [NSString stringWithUTF8String: name]];
}
}
}
[lines addObject: line];
} else {
if (err == SQLITE_DONE) {
break;
} else if (err == SQLITE_BUSY) {
CREATE_AUTORELEASE_POOL(arp);
NSDate *when = [NSDate dateWithTimeIntervalSinceNow: 0.1];
[NSThread sleepUntilDate: when];
GWDebugLog(@"retry %i", retry);
RELEASE (arp);
if (retry++ >= MAX_RETRY) {
NSLog(@"timeout for query: %@", query);
NSLog(@"%s", sqlite3_errmsg(db));
break;
}
} else {
NSLog(@"error at: %@", query);
NSLog(@"%i %s", err, sqlite3_errmsg(db));
break;
}
}
}
sqlite3_finalize(stmt);
} else {
NSLog(@"error at: %@", query);
NSLog(@"%s", sqlite3_errmsg(db));
}
return lines;
}
- (int)getIntEntry:(NSString *)query
{
NSArray *result = [self resultsOfQuery: query];
if ([result count]) {
return [[[[result objectAtIndex: 0] allValues] objectAtIndex: 0] intValue];
}
return INT_MAX;
}
- (float)getFloatEntry:(NSString *)query
{
NSArray *result = [self resultsOfQuery: query];
if ([result count]) {
return [[[[result objectAtIndex: 0] allValues] objectAtIndex: 0] floatValue];
}
return FLT_MAX;
}
- (NSString *)getStringEntry:(NSString *)query
{
NSArray *result = [self resultsOfQuery: query];
if ([result count]) {
return [[[result objectAtIndex: 0] allValues] objectAtIndex: 0];
}
return nil;
}
- (NSData *)getBlobEntry:(NSString *)query
{
NSArray *result = [self resultsOfQuery: query];
if ([result count]) {
return [[[result objectAtIndex: 0] allValues] objectAtIndex: 0];
}
return nil;
}
- (BOOL)createFunctionWithName:(NSString *)fname
argumentsCount:(int)nargs
userFunction:(void *)funct
{
return (sqlite3_create_function(db, [fname UTF8String], nargs,
SQLITE_UTF8, 0, funct, 0, 0) == SQLITE_OK);
}
- (int)lastInsertRowId
{
return sqlite3_last_insert_rowid(db);
}
@end
@implementation SQLite (PreparedStatements)
- (id)statementForQuery:(NSString *)query
withIdentifier:(id)identifier
bindings:(int)firstTipe, ...
{
SQLitePreparedStatement *statement = [preparedStatements objectForKey: identifier];
if (statement == nil) {
statement = [SQLitePreparedStatement statementWithQuery: query onDb: db];
if (statement == nil) {
return nil;
}
[preparedStatements setObject: statement forKey: identifier];
}
if ([statement expired] && ([statement prepare] == NO)) {
[preparedStatements removeObjectForKey: identifier];
return nil;
}
if (firstTipe != 0) {
int type = firstTipe;
id name;
va_list ap;
va_start(ap, firstTipe);
while (type != 0) {
name = va_arg(ap, id);
if (type == SQLITE_INTEGER) {
if ([statement bindIntValue: va_arg(ap, int) forName: name] == NO) {
va_end(ap);
[preparedStatements removeObjectForKey: identifier];
return nil;
}
} else if (type == SQLITE_FLOAT) {
if ([statement bindDoubleValue: va_arg(ap, double) forName: name] == NO) {
va_end(ap);
[preparedStatements removeObjectForKey: identifier];
return nil;
}
} else if (type == SQLITE_TEXT) {
if ([statement bindTextValue: va_arg(ap, id) forName: name] == NO) {
va_end(ap);
[preparedStatements removeObjectForKey: identifier];
return nil;
}
} else if (type == SQLITE_BLOB) {
if ([statement bindBlobValue: va_arg(ap, id) forName: name] == NO) {
va_end(ap);
[preparedStatements removeObjectForKey: identifier];
return nil;
}
} else {
va_end(ap);
[preparedStatements removeObjectForKey: identifier];
return nil;
}
type = va_arg(ap, int);
}
va_end(ap);
}
return statement;
}
- (BOOL)executeQueryWithStatement:(SQLitePreparedStatement *)statement
{
if (statement) {
sqlite3_stmt *handle = [statement handle];
int retry = 0;
int err;
while (1) {
err = sqlite3_step(handle);
if (err == SQLITE_DONE) {
break;
} else if (err == SQLITE_BUSY) {
CREATE_AUTORELEASE_POOL(arp);
NSDate *when = [NSDate dateWithTimeIntervalSinceNow: 0.1];
[NSThread sleepUntilDate: when];
GWDebugLog(@"retry %i", retry);
RELEASE (arp);
if (retry++ > MAX_RETRY) {
NSLog(@"timeout for query: %@", [statement query]);
NSLog(@"%s", sqlite3_errmsg(db));
[statement reset];
return NO;
}
} else {
NSLog(@"error at: %@", [statement query]);
NSLog(@"%s", sqlite3_errmsg(db));
[statement reset];
return NO;
}
}
[statement reset];
return YES;
}
return NO;
}
- (NSArray *)resultsOfQueryWithStatement:(SQLitePreparedStatement *)statement
{
NSMutableArray *lines = [NSMutableArray array];
if (statement) {
sqlite3_stmt *handle = [statement handle];
int retry = 0;
int err;
int i;
while (1) {
err = sqlite3_step(handle);
if (err == SQLITE_ROW) {
NSMutableDictionary *line = [NSMutableDictionary dictionary];
int count = sqlite3_data_count(handle);
// we use "<= count" because sqlite sends also
// the id of the entry with type = 0
for (i = 0; i <= count; i++) {
const char *name = sqlite3_column_name(handle, i);
if (name != NULL) {
int type = sqlite3_column_type(handle, i);
if (type == SQLITE_INTEGER) {
[line setObject: [NSNumber numberWithInt: sqlite3_column_int(handle, i)]
forKey: [NSString stringWithUTF8String: name]];
} else if (type == SQLITE_FLOAT) {
[line setObject: [NSNumber numberWithDouble: sqlite3_column_double(handle, i)]
forKey: [NSString stringWithUTF8String: name]];
} else if (type == SQLITE_TEXT) {
[line setObject: [NSString stringWithUTF8String: (const char *)sqlite3_column_text(handle, i)]
forKey: [NSString stringWithUTF8String: name]];
} else if (type == SQLITE_BLOB) {
const void *bytes = sqlite3_column_blob(handle, i);
int length = sqlite3_column_bytes(handle, i);
[line setObject: [NSData dataWithBytes: bytes length: length]
forKey: [NSString stringWithUTF8String: name]];
}
}
}
[lines addObject: line];
} else {
if (err == SQLITE_DONE) {
break;
} else if (err == SQLITE_BUSY) {
CREATE_AUTORELEASE_POOL(arp);
NSDate *when = [NSDate dateWithTimeIntervalSinceNow: 0.1];
[NSThread sleepUntilDate: when];
GWDebugLog(@"retry %i", retry);
RELEASE (arp);
if (retry++ > MAX_RETRY) {
NSLog(@"timeout for query: %@", [statement query]);
NSLog(@"%s", sqlite3_errmsg(db));
break;
}
} else {
NSLog(@"error at: %@", [statement query]);
NSLog(@"%i %s", err, sqlite3_errmsg(db));
break;
}
}
}
[statement reset];
}
return lines;
}
- (int)getIntEntryWithStatement:(SQLitePreparedStatement *)statement
{
NSArray *result = [self resultsOfQueryWithStatement: statement];
if ([result count]) {
return [[[[result objectAtIndex: 0] allValues] objectAtIndex: 0] intValue];
}
return INT_MAX;
}
- (float)getFloatEntryWithStatement:(SQLitePreparedStatement *)statement
{
NSArray *result = [self resultsOfQueryWithStatement: statement];
if ([result count]) {
return [[[[result objectAtIndex: 0] allValues] objectAtIndex: 0] floatValue];
}
return FLT_MAX;
}
- (NSString *)getStringEntryWithStatement:(SQLitePreparedStatement *)statement
{
NSArray *result = [self resultsOfQueryWithStatement: statement];
if ([result count]) {
return [[[result objectAtIndex: 0] allValues] objectAtIndex: 0];
}
return nil;
}
- (NSData *)getBlobEntryWithStatement:(SQLitePreparedStatement *)statement
{
NSArray *result = [self resultsOfQueryWithStatement: statement];
if ([result count]) {
return [[[result objectAtIndex: 0] allValues] objectAtIndex: 0];
}
return nil;
}
@end
@implementation SQLitePreparedStatement
- (void)dealloc
{
if (handle != NULL) {
sqlite3_finalize(handle);
}
RELEASE (query);
[super dealloc];
}
+ (id)statementWithQuery:(NSString *)aquery
onDb:(sqlite3 *)dbptr
{
return TEST_AUTORELEASE ([[self alloc] initWithQuery: aquery onDb: dbptr]);
}
- (id)initWithQuery:(NSString *)aquery
onDb:(sqlite3 *)dbptr
{
self = [super init];
if (self) {
ASSIGN (query, stringForQuery(aquery));
db = dbptr;
handle = NULL;
if (sqlite3_prepare(db, [query UTF8String], -1, &handle, NULL) != SQLITE_OK) {
NSLog(@"%s", sqlite3_errmsg(db));
DESTROY (self);
}
}
return self;
}
- (BOOL)bindIntValue:(int)value
forName:(NSString *)name
{
int index = sqlite3_bind_parameter_index(handle, [name UTF8String]);
if (index != 0) {
return (sqlite3_bind_int(handle, index, value) == SQLITE_OK);
}
return NO;
}
- (BOOL)bindDoubleValue:(double)value
forName:(NSString *)name
{
int index = sqlite3_bind_parameter_index(handle, [name UTF8String]);
if (index != 0) {
return (sqlite3_bind_double(handle, index, value) == SQLITE_OK);
}
return NO;
}
- (BOOL)bindTextValue:(NSString *)value
forName:(NSString *)name
{
int index = sqlite3_bind_parameter_index(handle, [name UTF8String]);
if (index != 0) {
return (sqlite3_bind_text(handle, index, [value UTF8String], -1, SQLITE_TRANSIENT) == SQLITE_OK);
}
return NO;
}
- (BOOL)bindBlobValue:(NSData *)value
forName:(NSString *)name
{
int index = sqlite3_bind_parameter_index(handle, [name UTF8String]);
if (index != 0) {
const void *bytes = [value bytes];
return (sqlite3_bind_blob(handle, index, bytes, [value length], SQLITE_TRANSIENT) == SQLITE_OK);
}
return NO;
}
- (BOOL)expired
{
return (sqlite3_expired(handle) != 0);
}
- (BOOL)prepare
{
if (sqlite3_prepare(db, [query UTF8String], -1, &handle, NULL) != SQLITE_OK) {
NSLog(@"%s", sqlite3_errmsg(db));
return NO;
}
return YES;
}
- (BOOL)reset
{
return (sqlite3_reset(handle) == SQLITE_OK);
}
- (BOOL)finalizeStatement
{
int err = sqlite3_finalize(handle);
if (err == SQLITE_OK) {
handle = NULL;
return YES;
}
return NO;
}
- (NSString *)query
{
return query;
}
- (sqlite3_stmt *)handle
{
return handle;
}
@end
NSString *stringForQuery(NSString *str)
{
NSRange range, subRange;
NSMutableString *querystr;
range = NSMakeRange(0, [str length]);
subRange = [str rangeOfString: @"'" options: NSLiteralSearch range: range];
if (subRange.location == NSNotFound) {
return str;
}
querystr = [NSMutableString stringWithString: str];
while ((subRange.location != NSNotFound) && (range.length > 0)) {
subRange = [querystr rangeOfString: @"'"
options: NSLiteralSearch
range: range];
if (subRange.location != NSNotFound) {
[querystr replaceCharactersInRange: subRange withString: @"''"];
}
range.location = subRange.location + 2;
if ([querystr length] < range.location) {
range.length = 0;
} else {
range.length = [querystr length] - range.location;
}
}
return querystr;
}
|