-
Notifications
You must be signed in to change notification settings - Fork 315
/
QueryWindowController.mm
1109 lines (1012 loc) · 38.1 KB
/
QueryWindowController.mm
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
//
// QueryWindowController.m
// MongoHub
//
// Created by Syd on 10-4-28.
// Copyright 2010 ThePeppersStudio.COM. All rights reserved.
//
#import "Configure.h"
#import "NSProgressIndicator+Extras.h"
#import "QueryWindowController.h"
#import "DatabasesArrayController.h"
#import "ResultsOutlineViewController.h"
#import "Connection.h"
#import "MongoDB.h"
#import <BWToolkitFramework/BWToolkitFramework.h>
#import "NSString+Extras.h"
#import "JsonWindowController.h"
#include <fstream>
#include <iostream>
#include <boost/filesystem/operations.hpp>
@implementation QueryWindowController
@synthesize managedObjectContext;
@synthesize databasesArrayController;
@synthesize findResultsViewController;
@synthesize mongoDB;
@synthesize conn;
@synthesize dbname;
@synthesize collectionname;
@synthesize criticalTextField;
@synthesize fieldsTextField;
@synthesize skipTextField;
@synthesize limitTextField;
@synthesize sortTextField;
@synthesize totalResultsTextField;
@synthesize findQueryTextField;
@synthesize findResultsOutlineView;
@synthesize findQueryLoaderIndicator;
@synthesize updateCriticalTextField;
@synthesize updateSetTextField;
@synthesize upsetCheckBox;
@synthesize updateResultsTextField;
@synthesize updateQueryTextField;
@synthesize updateQueryLoaderIndicator;
@synthesize removeCriticalTextField;
@synthesize removeResultsTextField;
@synthesize removeQueryTextField;
@synthesize removeQueryLoaderIndicator;
@synthesize insertDataTextView;
@synthesize insertResultsTextField;
@synthesize insertLoaderIndicator;
@synthesize indexTextField;
@synthesize indexesOutlineViewController;
@synthesize indexLoaderIndicator;
@synthesize mapFunctionTextView;
@synthesize reduceFunctionTextView;
@synthesize mrcriticalTextField;
@synthesize mroutputTextField;
@synthesize mrOutlineViewController;
@synthesize mrLoaderIndicator;
@synthesize expCriticalTextField;
@synthesize expFieldsTextField;
@synthesize expSkipTextField;
@synthesize expLimitTextField;
@synthesize expSortTextField;
@synthesize expResultsTextField;
@synthesize expPathTextField;
@synthesize expTypePopUpButton;
@synthesize expQueryTextField;
@synthesize expJsonArrayCheckBox;
@synthesize expProgressIndicator;
@synthesize impIgnoreBlanksCheckBox;
@synthesize impDropCheckBox;
@synthesize impHeaderlineCheckBox;
@synthesize impFieldsTextField;
@synthesize impResultsTextField;
@synthesize impPathTextField;
@synthesize impTypePopUpButton;
@synthesize impJsonArrayCheckBox;
@synthesize impStopOnErrorCheckBox;
@synthesize impProgressIndicator;
- (id)init {
if (![super initWithWindowNibName:@"QueryWindow"]) return nil;
return self;
}
- (void)dealloc {
[managedObjectContext release];
[databasesArrayController release];
[findResultsViewController release];
[conn release];
[mongoDB release];
[dbname release];
[collectionname release];
[criticalTextField release];
[fieldsTextField release];
[skipTextField release];
[limitTextField release];
[sortTextField release];
[totalResultsTextField release];
[findQueryTextField release];
[findResultsOutlineView release];
[findQueryLoaderIndicator release];
[updateCriticalTextField release];
[updateSetTextField release];
[upsetCheckBox release];
[updateResultsTextField release];
[updateQueryTextField release];
[updateQueryLoaderIndicator release];
[removeCriticalTextField release];
[removeResultsTextField release];
[removeQueryTextField release];
[removeQueryLoaderIndicator release];
[insertDataTextView release];
[insertResultsTextField release];
[insertLoaderIndicator release];
[indexTextField release];
[indexesOutlineViewController release];
[indexLoaderIndicator release];
[mapFunctionTextView release];
[reduceFunctionTextView release];
[mrcriticalTextField release];
[mroutputTextField release];
[mrOutlineViewController release];
[mrLoaderIndicator release];
[expCriticalTextField release];
[expFieldsTextField release];
[expSkipTextField release];
[expLimitTextField release];
[expSortTextField release];
[expResultsTextField release];
[expPathTextField release];
[expTypePopUpButton release];
[expQueryTextField release];
[expJsonArrayCheckBox release];
[expProgressIndicator release];
[impIgnoreBlanksCheckBox release];
[impDropCheckBox release];
[impHeaderlineCheckBox release];
[impFieldsTextField release];
[impResultsTextField release];
[impPathTextField release];
[impTypePopUpButton release];
[impJsonArrayCheckBox release];
[impStopOnErrorCheckBox release];
[impProgressIndicator release];
[super dealloc];
}
- (void)windowDidLoad {
[super windowDidLoad];
NSString *title = [[NSString alloc] initWithFormat:@"Query in %@.%@", dbname, collectionname];
[self.window setTitle:title];
[title release];
}
- (void)windowWillClose:(NSNotification *)notification {
[self release];
}
- (IBAction)findQuery:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doFindQuery) toTarget:self withObject:nil];
}
- (void)doFindQuery {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSTimeInterval speed = [NSDate timeIntervalSinceReferenceDate];
[findQueryLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *critical = [criticalTextField stringValue];
NSString *fields = [fieldsTextField stringValue];
NSString *sort = [sortTextField stringValue];
NSNumber *skip = [NSNumber numberWithInt:[skipTextField intValue]];
NSNumber *limit;
if ([limitTextField intValue] == 0) {
limit = [NSNumber numberWithInt:30];
}else {
limit = [NSNumber numberWithInt:[limitTextField intValue]];
}
NSMutableArray *results = [[NSMutableArray alloc] initWithArray:[mongoDB findInDB:dbname
collection:collectionname
user:user
password:password
critical:critical
fields:fields
skip:skip
limit:limit
sort:sort]];
long long int total = [mongoDB countInDB:dbname
collection:collectionname
user:user
password:password
critical:critical];
[totalResultsTextField setStringValue:[NSString stringWithFormat:@"Total Results: %d (%0.2fs)", total, [NSDate timeIntervalSinceReferenceDate]-speed]];
findResultsViewController.results = results;
[findResultsViewController.myOutlineView reloadData];
[results release];
[findQueryLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction)expandFindResults:(id)sender
{
[findResultsOutlineView expandItem:nil expandChildren:YES];
}
- (IBAction)collapseFindResults:(id)sender
{
[findResultsOutlineView collapseItem:nil collapseChildren:YES];
}
- (IBAction)updateQuery:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doUpdateQuery) toTarget:self withObject:nil];
}
- (void)doUpdateQuery {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[updateQueryLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *critical = [updateCriticalTextField stringValue];
NSString *fields = [updateSetTextField stringValue];
NSNumber *upset = [NSNumber numberWithInt:[upsetCheckBox state]];
int total = [mongoDB countInDB:dbname
collection:collectionname
user:user
password:password
critical:critical];
[mongoDB updateInDB:dbname
collection:collectionname
user:user
password:password
critical:critical
fields:fields
upset:upset];
[updateResultsTextField setStringValue:[NSString stringWithFormat:@"Affected Rows: %d", total]];
[updateQueryLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction)removeQuery:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doRemoveQuery) toTarget:self withObject:nil];
}
- (IBAction)doRemoveQuery {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[removeQueryLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *critical = [removeCriticalTextField stringValue];
int total = [mongoDB countInDB:dbname
collection:collectionname
user:user
password:password
critical:critical];
[mongoDB removeInDB:dbname
collection:collectionname
user:user
password:password
critical:critical];
[removeResultsTextField setStringValue:[NSString stringWithFormat:@"Affected Rows: %d", total]];
[removeQueryLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) insertQuery:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doInsertQuery) toTarget:self withObject:nil];
}
- (void)doInsertQuery {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[insertLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *insertData = [insertDataTextView string];
[mongoDB insertInDB:dbname
collection:collectionname
user:user
password:password
insertData:insertData];
[insertResultsTextField setStringValue:@"Completed!"];
[insertLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) indexQuery:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doIndexQuery) toTarget:self withObject:nil];
}
- (void)doIndexQuery {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[indexLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSMutableArray *results = [[NSMutableArray alloc] initWithArray:[mongoDB indexInDB:dbname
collection:collectionname
user:user
password:password]];
indexesOutlineViewController.results = results;
[indexesOutlineViewController.myOutlineView reloadData];
[results release];
[indexLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) ensureIndex:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doEnsureIndex) toTarget:self withObject:nil];
}
- (void) doEnsureIndex {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[indexLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *indexData = [indexTextField stringValue];
[mongoDB ensureIndexInDB:dbname
collection:collectionname
user:user
password:password
indexData:indexData];
[self indexQuery:nil];
[indexLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) reIndex:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doReIndex) toTarget:self withObject:nil];
}
- (void) doReIndex {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[indexLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
[mongoDB reIndexInDB:dbname
collection:collectionname
user:user
password:password];
[self indexQuery:nil];
[indexLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) dropIndex:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doDropIndex) toTarget:self withObject:nil];
}
- (void) doDropIndex {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[indexLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *indexName = [indexTextField stringValue];
[mongoDB dropIndexInDB:dbname
collection:collectionname
user:user
password:password
indexName:indexName];
[self indexQuery:nil];
[indexLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) mapReduce:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doMapReduce) toTarget:self withObject:nil];
}
- (void)doMapReduce {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[mrLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *mapFunction = [mapFunctionTextView string];
NSString *reduceFunction = [reduceFunctionTextView string];
NSString *critical = [mrcriticalTextField stringValue];
NSString *output = [mroutputTextField stringValue];
NSMutableArray *results = [[NSMutableArray alloc] initWithArray:[mongoDB mapReduceInDB:dbname
collection:collectionname
user:user
password:password
mapJs:mapFunction
reduceJs:reduceFunction
critical:critical
output:output]];
mrOutlineViewController.results = results;
[mrOutlineViewController.myOutlineView reloadData];
[results release];
[mrLoaderIndicator stop];
[NSThread exit];
[pool release];
}
- (IBAction) export:(id)sender
{
if (![[expPathTextField stringValue] isPresent]) {
NSRunAlertPanel(@"Error", @"Please choose export path", @"OK", nil, nil);
return;
}
if (![[expFieldsTextField stringValue] isPresent] && [[expTypePopUpButton selectedItem] tag]==1)
{
NSRunAlertPanel(@"Error", @"You need to specify fields", @"OK", nil, nil);
return;
}
[NSThread detachNewThreadSelector:@selector(doExport) toTarget:self withObject:nil];
}
- (void)doExport
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
std::auto_ptr<std::ofstream> fileStream;
std::ofstream * s = new std::ofstream( [[expPathTextField stringValue] UTF8String] , std::ios_base::out );
fileStream.reset( s );
ostream *outPtr = &std::cout;
outPtr = s;
if ( ! s->good() ) {
NSRunAlertPanel(@"Error", [NSString stringWithFormat:@"Couldn't open [%@]", [expPathTextField stringValue]], @"OK", nil, nil);
}
std::ostream &out = *outPtr;
bool _jsonArray = false;
if ([expJsonArrayCheckBox state] == 1) {
_jsonArray = true;
}
unsigned int exportType = [[expTypePopUpButton selectedItem] tag];
[expResultsTextField setStringValue:@"Start exporting"];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *critical = [expCriticalTextField stringValue];
NSString *fields = [expFieldsTextField stringValue];
NSString *sort = [expSortTextField stringValue];
NSNumber *skip = [NSNumber numberWithInt:[expSkipTextField intValue]];
NSNumber *limit = [NSNumber numberWithInt:[expLimitTextField intValue]];
long long int total = [mongoDB countInDB:dbname
collection:collectionname
user:user
password:password
critical:critical];
if (total == 0) {
[expResultsTextField setStringValue:@"No data to export!"];
return;
}
if ( exportType == 1 ) {
out << [fields UTF8String] << std::endl;
}else if (_jsonArray) {
out << '[';
}
[expProgressIndicator setUsesThreadedAnimation:YES];
[expProgressIndicator startAnimation: self];
[expProgressIndicator setDoubleValue:0];
std::auto_ptr<mongo::DBClientCursor> cursor = [mongoDB findCursorInDB:dbname
collection:collectionname
user:user
password:password
critical:critical
fields:fields
skip:skip
limit:limit
sort:sort];
unsigned int i = 1;
while( cursor->more() )
{
mongo::BSONObj obj = cursor->next();
if ( exportType == 1 ) {
NSArray *keys = [[NSArray alloc] initWithArray:[fields componentsSeparatedByString:@","]];
unsigned int fieldIndex = 0;
for (NSString *str in keys) {
if (fieldIndex > 0) {
out << ",";
}
const mongo::BSONElement & e = obj.getFieldDotted([str UTF8String]);
if ( ! e.eoo() ) {
out << e.jsonString( mongo::TenGen , false );
}
fieldIndex ++;
}
[keys release];
out << std::endl;
}else {
if (_jsonArray && i != 1)
out << ',';
out << obj.jsonString();
if (!_jsonArray)
{
out << std::endl;
}
}
[expProgressIndicator setDoubleValue:(double)i/total*100];
i ++;
}
if ( exportType == 1 && _jsonArray)
out << ']' << endl;
[expProgressIndicator stopAnimation: self];
[expResultsTextField setStringValue:[NSString stringWithFormat:@"Exported %d records.", total]];
[NSThread exit];
[pool release];
}
- (IBAction) import:(id)sender
{
if (![[impPathTextField stringValue] isPresent]) {
NSRunAlertPanel(@"Error", @"Please choose import file", @"OK", nil, nil);
return;
}
if (![[expFieldsTextField stringValue] isPresent] && [[expTypePopUpButton selectedItem] tag]==1)
{
NSRunAlertPanel(@"Error", @"You need to specify fields", @"OK", nil, nil);
return;
}
[NSThread detachNewThreadSelector:@selector(doImport) toTarget:self withObject:nil];
}
- (void)doImport
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[impProgressIndicator setUsesThreadedAnimation:YES];
[impProgressIndicator startAnimation: self];
[impProgressIndicator setDoubleValue:0];
long long fileSize = 0;
std::istream * in = &std::cin;
std::ifstream file( [[impPathTextField stringValue] UTF8String] , std::ios_base::in);
in = &file;
fileSize = boost::filesystem::file_size( [[impPathTextField stringValue] UTF8String] );
bool _ignoreBlanks = false;
bool _headerLine = false;
bool _jsonArray = false;
bool _stopOnError = false;
if ([impHeaderlineCheckBox state] == 1)
{
_headerLine = true;
}
if ([impJsonArrayCheckBox state] == 1) {
_jsonArray = true;
}
if ([impStopOnErrorCheckBox state] == 1) {
_stopOnError = true;
}
unsigned int _type = [[impTypePopUpButton selectedItem] tag];
std::string _sep;
if (_type == 1)
{
_sep = ",";
}else if(_type == 2){
_sep = "\t";
}
std::vector<std::string> _fields;
if (!_headerLine && [[impFieldsTextField stringValue] isPresent])
{
NSArray *keys = [[NSArray alloc] initWithArray:[[impFieldsTextField stringValue] componentsSeparatedByString:@","]];
for (NSString *str in keys) {
_fields.push_back([str UTF8String]);
}
[keys release];
}
if (_type!=0 && !_headerLine && _fields.empty())
{
NSRunAlertPanel(@"Error", @"Please check headerline", @"OK", nil, nil);
return;
}
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
if ([impDropCheckBox state] == 1)
{
[mongoDB dropCollection:collectionname forDB:dbname user:user password:password];
}
if ([impIgnoreBlanksCheckBox state] == 1)
{
_ignoreBlanks = true;
}
int errors = 0;
int num = 0;
const int BUF_SIZE = 1024 * 1024 * 4;
boost::scoped_array<char> line(new char[BUF_SIZE+2]);
char * buf = line.get();
while ( _jsonArray || in->rdstate() == 0 ) {
if (_jsonArray) {
if (buf == line.get()) { //first pass
in->read(buf, BUF_SIZE);
if (!(in->rdstate() & std::ios_base::eofbit))
{
NSRunAlertPanel(@"Error", @"JSONArray file too large", @"OK", nil, nil);
return;
}
buf[ in->gcount() ] = '\0';
}
}else {
buf = line.get();
in->getline( buf , BUF_SIZE );
}
if (!((!(in->rdstate() & std::ios_base::badbit)) && (!(in->rdstate() & std::ios_base::failbit) || (in->rdstate() & std::ios_base::eofbit))))
{
NSRunAlertPanel(@"Error", @"unknown error reading file", @"OK", nil, nil);
return;
}
int len = 0;
if (strncmp("\xEF\xBB\xBF", buf, 3) == 0) { // UTF-8 BOM (notepad is stupid)
buf += 3;
len += 3;
}
if (_jsonArray) {
while (buf[0] != '{' && buf[0] != '\0') {
len++;
buf++;
}
if (buf[0] == '\0')
break;
}else {
while (std::isspace( buf[0] )) {
len++;
buf++;
}
if (buf[0] == '\0')
continue;
len += strlen( buf );
}
try {
mongo::BSONObj o;
if (_jsonArray) {
int jslen;
o = mongo::fromjson(buf, &jslen);
len += jslen;
buf += jslen;
}else {
o = [self parseCSVLine:buf type:_type sep:_sep.c_str() headerLine:_headerLine ignoreBlanks:_ignoreBlanks fields:_fields];NSLog(@"%@", [NSString stringWithUTF8String:o.jsonString( mongo::TenGen , false ).c_str()]);
}
if ( _headerLine ) {
_headerLine = false;
}else{
[mongoDB insertInDB:dbname
collection:collectionname
user:user
password:password
insertData:[NSString stringWithUTF8String:o.jsonString( mongo::TenGen , false ).c_str()]
];
}
num++;
}catch ( std::exception& e ) {
std::cout << "exception:" << e.what() << std::endl;
std::cout << buf << std::endl;
errors++;
if (_stopOnError || _jsonArray)
break;
}
}
[impProgressIndicator stopAnimation: self];
[impResultsTextField setStringValue:[NSString stringWithFormat:@"Imported %d records, %d failed", num, errors]];
[NSThread exit];
[pool release];
}
- (IBAction)removeRecord:(id)sender
{
[NSThread detachNewThreadSelector:@selector(doRemoveRecord) toTarget:self withObject:nil];
}
- (void)doRemoveRecord
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ([findResultsViewController.myOutlineView selectedRow] != -1)
{
id currentItem = [findResultsViewController.myOutlineView itemAtRow:[findResultsViewController.myOutlineView selectedRow]];
//NSLog(@"%@", [findResultsViewController rootForItem:currentItem]);
[removeQueryLoaderIndicator start];
NSString *user=nil;
NSString *password=nil;
Database *db = [databasesArrayController dbInfo:conn name:dbname];
if (db) {
user = db.user;
password = db.password;
}
[db release];
NSString *critical;
if ([[currentItem objectForKey:@"type"] isEqualToString:@"ObjectId"]) {
critical = [NSString stringWithFormat:@"{_id:ObjectId(\"%@\")}", [currentItem objectForKey:@"value"]];
}else if ([[currentItem objectForKey:@"type"] isEqualToString:@"String"]) {
critical = [NSString stringWithFormat:@"{_id:\"%@\"}", [currentItem objectForKey:@"value"]];
}else {
critical = [NSString stringWithFormat:@"{_id:%@}", [currentItem objectForKey:@"value"]];
}NSLog(@"%@", critical);
[mongoDB removeInDB:dbname
collection:collectionname
user:user
password:password
critical:critical];
[removeQueryLoaderIndicator stop];
[self findQuery:nil];
}
[NSThread exit];
[pool release];
}
- (void)controlTextDidChange:(NSNotification *)nd
{
NSTextField *ed = [nd object];
if (ed == criticalTextField || ed == fieldsTextField || ed == sortTextField || ed == skipTextField || ed == limitTextField)
{
[self findQueryComposer:nil];
}else if (ed == updateCriticalTextField || ed == updateSetTextField) {
[self updateQueryComposer:nil];
}else if (ed == removeCriticalTextField) {
[self removeQueryComposer:nil];
}else if (ed == expCriticalTextField || ed == expFieldsTextField || ed == expSortTextField || ed == expSkipTextField || ed == expLimitTextField)
{
[self exportQueryComposer:nil];
}
}
- (IBAction) findQueryComposer:(id)sender
{
NSString *critical;
if ([[criticalTextField stringValue] isPresent]) {
critical = [[NSString alloc] initWithString:[criticalTextField stringValue]];
}else {
critical = [[NSString alloc] initWithString:@""];
}
NSString *jsFields;
if ([[fieldsTextField stringValue] isPresent]) {
NSArray *keys = [[NSArray alloc] initWithArray:[[fieldsTextField stringValue] componentsSeparatedByString:@","]];
NSMutableArray *tmpstr = [[NSMutableArray alloc] initWithCapacity:[keys count]];
for (NSString *str in keys) {
[tmpstr addObject:[NSString stringWithFormat:@"%@:1", str]];
}
jsFields = [[NSString alloc] initWithFormat:@", {%@}", [tmpstr componentsJoinedByString:@","] ];
[keys release];
[tmpstr release];
}else {
jsFields = [[NSString alloc] initWithString:@""];
}
NSString *sort;
if ([[sortTextField stringValue] isPresent]) {
sort = [[NSString alloc] initWithFormat:@".sort(%@)"];
}else {
sort = [[NSString alloc] initWithString:@""];
}
NSString *skip = [[NSString alloc] initWithFormat:@".skip(%d)", [skipTextField intValue]];
NSString *limit = [[NSString alloc] initWithFormat:@".limit(%d)", [limitTextField intValue]];
NSString *col = [NSString stringWithFormat:@"%@.%@", dbname, collectionname];
NSString *query = [NSString stringWithFormat:@"db.%@.find(%@%@)%@%@%@", col, critical, jsFields, sort, skip, limit];
[critical release];
[jsFields release];
[sort release];
[skip release];
[limit release];
[findQueryTextField setStringValue:query];
}
- (IBAction)updateQueryComposer:(id)sender
{
NSString *col = [NSString stringWithFormat:@"%@.%@", dbname, collectionname];
NSString *critical;
if ([[updateCriticalTextField stringValue] isPresent]) {
critical = [[NSString alloc] initWithString:[updateCriticalTextField stringValue]];
}else {
critical = [[NSString alloc] initWithString:@""];
}
NSString *sets;
if ([[updateSetTextField stringValue] isPresent]) {
//sets = [[NSString alloc] initWithFormat:@", {$set:%@}", [updateSetTextField stringValue]];
sets = [[NSString alloc] initWithFormat:@", %@", [updateSetTextField stringValue]];
}else {
sets = [[NSString alloc] initWithString:@""];
}
NSString *upset;
if ([upsetCheckBox state] == 1) {
upset = [[NSString alloc] initWithString:@", true"];
}else {
upset = [[NSString alloc] initWithString:@", false"];
}
NSString *query = [NSString stringWithFormat:@"db.%@.update(%@%@%@)", col, critical, sets, upset];
[critical release];
[sets release];
[upset release];
[updateQueryTextField setStringValue:query];
}
- (IBAction)removeQueryComposer:(id)sender
{
NSString *col = [NSString stringWithFormat:@"%@.%@", dbname, collectionname];
NSString *critical;
if ([[removeCriticalTextField stringValue] isPresent]) {
critical = [[NSString alloc] initWithString:[removeCriticalTextField stringValue]];
}else {
critical = [[NSString alloc] initWithString:@""];
}
NSString *query = [NSString stringWithFormat:@"db.%@.remove(%@)", col, critical];
[critical release];
[removeQueryTextField setStringValue:query];
}
- (IBAction) exportQueryComposer:(id)sender
{
NSString *critical;
if ([[expCriticalTextField stringValue] isPresent]) {
critical = [[NSString alloc] initWithString:[expCriticalTextField stringValue]];
}else {
critical = [[NSString alloc] initWithString:@""];
}
NSString *jsFields;
if ([[expFieldsTextField stringValue] isPresent]) {
NSArray *keys = [[NSArray alloc] initWithArray:[[expFieldsTextField stringValue] componentsSeparatedByString:@","]];
NSMutableArray *tmpstr = [[NSMutableArray alloc] initWithCapacity:[keys count]];
for (NSString *str in keys) {
[tmpstr addObject:[NSString stringWithFormat:@"%@:1", str]];
}
jsFields = [[NSString alloc] initWithFormat:@", {%@}", [tmpstr componentsJoinedByString:@","] ];
[keys release];
[tmpstr release];
}else {
jsFields = [[NSString alloc] initWithString:@""];
}
NSString *sort;
if ([[expSortTextField stringValue] isPresent]) {
sort = [[NSString alloc] initWithFormat:@".sort(%@)"];
}else {
sort = [[NSString alloc] initWithString:@""];
}
NSString *skip = [[NSString alloc] initWithFormat:@".skip(%d)", [expSkipTextField intValue]];
NSString *limit = [[NSString alloc] initWithFormat:@".limit(%d)", [expLimitTextField intValue]];
NSString *col = [NSString stringWithFormat:@"%@.%@", dbname, collectionname];
NSString *query = [NSString stringWithFormat:@"db.%@.find(%@%@)%@%@%@", col, critical, jsFields, sort, skip, limit];
[critical release];
[jsFields release];
[sort release];
[skip release];
[limit release];
[expQueryTextField setStringValue:query];
}
- (void)showEditWindow:(id)sender
{
switch([findResultsViewController.myOutlineView selectedRow])
{
case -1:
break;
default:{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findQuery:) name:kJsonWindowSaved object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jsonWindowWillClose:) name:kJsonWindowWillClose object:nil];
id currentItem = [findResultsViewController.myOutlineView itemAtRow:[findResultsViewController.myOutlineView selectedRow]];
//NSLog(@"%@", [findResultsViewController rootForItem:currentItem]);
JsonWindowController *jsonWindowController = [[JsonWindowController alloc] init];
jsonWindowController.managedObjectContext = self.managedObjectContext;
jsonWindowController.conn = conn;
jsonWindowController.dbname = dbname;
jsonWindowController.collectionname = collectionname;
jsonWindowController.mongoDB = mongoDB;
jsonWindowController.jsonDict = [findResultsViewController rootForItem:currentItem];
[jsonWindowController showWindow:sender];
break;
}
}
}
- (void)jsonWindowWillClose:(id)sender
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (IBAction)chooseExportPath:(id)sender
{
NSSavePanel *tvarNSSavePanelObj = [NSSavePanel savePanel];
int tvarInt = [tvarNSSavePanelObj runModal];
if(tvarInt == NSOKButton){
NSLog(@"doSaveAs we have an OK button");
//NSString * tvarDirectory = [tvarNSSavePanelObj directory];
//NSLog(@"doSaveAs directory = %@",tvarDirectory);
NSString * tvarFilename = [tvarNSSavePanelObj filename];
NSLog(@"doSaveAs filename = %@",tvarFilename);