-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvrtosql.cpp
2842 lines (2572 loc) · 75.9 KB
/
vrtosql.cpp
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
/*
20000629 ljz Logging of trouble now starts with '***'
20010330 ljz Added a few debug printf's
20010420 ljz Fixed memory leaks in all query levels
20020519 mvh Clear BindField result strings before reading (NULL does not read)
20021028 mvh Restructured queries to give lowest level of de-normalized databases
Fixed sorting on PatientName in denormalized study query
20021030 mvh Reversed this again apart from study level because SQL server becomes very slow
20030113 mvh Added PatientQuerySortOrder etc overrides for sorting
20030114 mvh Added in querycolumns (even if akreday present);
tested for SQL server, requires testing for other datasources
20030122 ljz+mvh Remove unused entries from Tables string in queries
20040930 mvh Started adapt such that query strings etc and not limited in length
For now: query string max 8192 (here and in odbci.cpp); sql statement max 16384 (in odbci.hpp)
Enough for query with one multiple values UID of about 100 images (list truncated if too long)
Added safestrcat protection of SearchString
20041003 mvh Truncated debug prints, malloc strings at image level
Analysed string lenghts; limited 'records =' debug log
20041013 mvh Used MAXQUERYLENGTH
20050107 mvh Removed UNIX flags: solve difference in database interface
20050206 mvh Image query can send filename and device in 0x9999,0x800/0x0801
20050401 mvh Added QueryOnModalityWorkList; - todo - put selected items into sequence 0040,0100
20050404 mvh Take query for Scheduled Procedure Step from sequence, put results into sequence
20050414 mvh Made sequence unfolding for worklist more generic - accepts any number of and nested N=1 sequences
This is correct behavior for query input, but limited for query results
20050417 mvh Removed unused variable
20050831 mvh Fixes in worklist code: is ok for all OFFIS tests except 1 (empty seq not returned) and
10 (undef non-empty seq takes one entry from higher level) - good enough for initial release?
20050901 mvh Fix for test 10: allow undefined sequence in query
20050907 mvh Merged change by Hans-Peter Hellemann: fix missing max() macro
20051229 mvh Debug log show records of all queries. DumpVR only left in worklistquery and shows sequence layout
20051230 mvh Removed 2 forgotten dumpvr's
20060103 mvh Added debug info from testing phase inside nested sequences for modality query
20060211 mvh Added empty required modality sequences 8,1110 and 8,1120 when not there
20060224 mvh Fixed modality worklist query: empty result sequences were not handled correctly (Thanks Tony Tong)
20060311 mvh Worklist change was tested OK with Agfa (thanks Frank Grogan), cleaned debug log a bit
20060607 mvh Fix crash when coding empty sequence as last item in worklist query (thanks Francois Piette)
20061219 mvh Small fix in layout debug log
20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
20080817 mvh Fixed bug found by larc: worklist sql syntax error (fields start with ,) when 1st item is sequence
mvh Fixed bug found by Alberto Smulders: sometimes sequence level in response would not come down
The problem was that a higher levels the reported sequence level was inconsistent with the 1st level
Changed CodeSequence stop criterium and level coding for deeper levels; now works with varies sequence combination
Added WorkListReturnsISO_IR_100 flag (default 1)
20080818 mvh DbaseIII check now uses DB flags, not PATHSEP in datasource name
20080901 mvh Implemented 'Number of Patient Related Studies' (0x0020, 0x1200) etc
20080902 mvh Fixed that option for VirtualServers; added EnableComputedFields
20080905 bcb Added void* cast for deivr change
20081016 mvh Fixed for WC compile
20081121 mvh Fixed ISO_IR 100
20090930 mvh Fixed ImageQuerySortOrder: crashed on C-MOVE, because sortcolumn was inserted before the filename
20091005 mvh Fixed ComputeField: return VR was used during cleanup
20091231 bcb Changed char* to const char* for gcc4.2 warnings
20100111 mvh Merged
20100309 bcb Added double parentheses (gcc4.2 Warnings)
20100309 bcb Changed int to unsigned int, commented out unused variables (gcc4.2 Warnings)
20100706 bcb Init Level
20100717 mvh Merged
20100822 mvh Delete 9999,0802 virtualservermask control VR from searches and pass it to ComputeField
20100823 mvh Fixed compile for ms8amd64
20100901 mvh Rephrased "Failed on VR Search...."
20101003 mvh Delete 9999,0900 script control from queries
20101120 mvh Delete 0002,0010 transfer syntax from queries
20101127 mvh Added CountOnly mode to accelerate e.g., NumberOfStudyRelatedInstances queries
20110105 mvh Pass database to MakeSafeString to allow db_type dependent processing; use LIKE only when needed
20110105 mvh Moved local routines here: MakeSafeString, DICOM2SQLQuery, BuildSearchString, BuildColumnString
20110603 mvh Fully init vr used for MakeSafeString
20110605 mvh Allow ' *' for query
20120214 mvh Allow WorkListReturnsISO_IR_100 to be any value (e.g., 192)
20120422 mvh Fix search in DT_MSTR with embedded _ to use =, was a LIKE that failed for MySQL
20120624 mvh Fix DT_MSTR for DoubleBackSlashToDB (mysql and pgsql): requires 4 backslashses (!)
20120701 mvh Fix in BuildSearchString for UseEscapeStringConstants for DT_MSTR and DT_DATE
20120703 bcb Removed WHEDGE, fixed prototypes
20130226 bcb Replaced gpps with IniValue class, fixed strlen and size warnings. Version to 1.4.18a.
*/
# include "dgate.hpp"
//# include "dbsql.hpp"
# include "configpacs.hpp"
#ifndef UINT32_MAX
#define UINT32_MAX 0xFFFFFFFF
#endif
//extern char PatientQuerySortOrder[];
//extern char StudyQuerySortOrder[];
//extern char SeriesQuerySortOrder[];
//extern char ImageQuerySortOrder[];
//extern int WorkListReturnsISO_IR_100;
//extern int EnableComputedFields;
//extern int DoubleBackSlashToDB;
//extern int UseEscapeStringConstants;
void safestrcat(char *result, const char *tocat, int maxlen)
{ int len = strnlenint(result), len2 = strnlenint(tocat);
if (len+len2 < maxlen)
strcpy(result+len, tocat);
}
BOOL
MakeSafeString (
VR *vr,
char *string,
Database *db )
{
UINT32 Length;//Vr max
char *sout;
char *sin;
char *s;
UINT Index;
BOOL AddEscape = FALSE;
BOOL UseLike = FALSE;
s = SetString(vr, NULL, 0);
Length = strnlen32u(s);
sin = (char*)s;
sout = string;
// convert ** query to * query (efilm problem)
if (Length==2 && s[0]=='*' && s[1]=='*') Length--;
// convert ' *' query to '*' query (some other pacs problem)
if (Length==2 && s[0]==' ' && s[1]=='*') { Length--; s[0]='*'; }
if (strchr(s, '*') || strchr(s, '?')) // 20110105: force use of 'LIKE' (pattern matching), else use exact matching
{
(*sout++) = '?'; // is processed by BuildSearchString defined and only used below
UseLike = TRUE;
}
IniValue *iniValuePtr = IniValue::GetInstance();
if (iniValuePtr->sscscpPtr->UseEscapeStringConstants) // typically for postgres
(*sout++) = 'E';
(*sout++) = '\'';
if (vr)
if(vr->Data)
{
Index = 0;
while(Index < Length)
{
switch (*sin)
{
case '*':
(*sout) = '%';++sout;
break;
case '?':
(*sout) = '_';++sout;
break;
// original code
// case '%':
// (*sout) = '\\';++sout;
// (*sout) = '%';++sout;
// break;
// case '[':
// (*sout) = '\\';++sout;
// (*sout) = '[';++sout;
// break;
// case '_':
// (*sout) = '_';++sout;
// break;
// case '\\': // not OK: mysql, sqlite, sqlserver
// if (iniValuePtr->sscscpPtr->DoubleBackSlashToDB)// OK: dbase (set for mysql and postgres)`
// {
// if ((Index > 0) && (sin[-1] != '\\'))
// {
// (*sout) = '\\';++sout;
// (*sout) = '\\';++sout;
// }
// }
// else
// {
// (*sout) = (*sin);
// ++sout;
// }
// break;
// end original code
// redone these special characters: mvh 20110105
case '%':
if (db->db_type==DT_ODBC && UseLike) // sql server
{
(*sout) = '[';++sout;
(*sout) = '%';++sout;
(*sout) = ']';++sout;
}
else if (db->db_type==DT_SQLITE && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '%';++sout;
AddEscape = TRUE;
}
else if (db->db_type==DT_POSTGRES && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
(*sout) = '%';++sout;
AddEscape = TRUE;
}
else if (UseLike)
{
(*sout) = '\\';++sout; // ok: mysql, dbase
(*sout) = '%';++sout;
}
else
{
(*sout) = '%';++sout;
}
break;
case '[':
if (db->db_type==DT_ODBC && UseLike) // sql server
{
(*sout) = '[';++sout;
(*sout) = '[';++sout;
(*sout) = ']';++sout;
}
else if (db->db_type==DT_SQLITE && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '[';++sout;
AddEscape = TRUE;
}
else if (db->db_type==DT_POSTGRES && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
(*sout) = '[';++sout;
AddEscape = TRUE;
}
else if (UseLike)
{
(*sout) = '\\';++sout; // ok: mysql, dbase
(*sout) = '[';++sout;
}
else
{
(*sout) = '[';++sout;
}
break;
case '_':
if (db->db_type==DT_ODBC && UseLike) // sql server
{
(*sout) = '[';++sout;
(*sout) = '_';++sout;
(*sout) = ']';++sout;
}
else if (db->db_type==DT_SQLITE && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '_';++sout;
AddEscape = TRUE;
}
else if (db->db_type==DT_POSTGRES && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
(*sout) = '_';++sout;
AddEscape = TRUE;
}
else if (UseLike)
{
(*sout) = '\\';++sout; // ok: mysql, dbase
(*sout) = '_';++sout;
}
else
{
(*sout) = '_';++sout;
}
break;
case '\\':
if (db->db_type==DT_ODBC && UseLike) // sql server
{
(*sout) = '[';++sout;
(*sout) = '\\';++sout;
(*sout) = ']';++sout;
}
else if (db->db_type==DT_SQLITE && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
AddEscape = TRUE;
}
else if (db->db_type==DT_POSTGRES && UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
AddEscape = TRUE;
}
else if (db->db_type==DT_POSTGRES && !UseLike)
{
(*sout) = '\\';++sout;
(*sout) = '\\';++sout;
}
else if (UseLike)
{
(*sout) = '\\';++sout; // ok:
(*sout) = '\\';++sout; // not ok: mysql
}
else if (iniValuePtr->sscscpPtr->DoubleBackSlashToDB)
{
if ((Index > 0) && (sin[-1] != '\\'))
{
(*sout) = '\\';++sout; // ok:
(*sout) = '\\';++sout; // not ok:
}
}
else
{
(*sout) = '\\';++sout;
}
break;
// end redone these special characters: mvh 20110105
case '\'':
(*sout) = '\'';++sout;
(*sout) = '\'';++sout;
break;
case '\"':
(*sout) = '\"';++sout;
break;
case 0: break;
default:
(*sout) = (*sin);
++sout;
}
++sin;
++Index;
}
}
/* new code removes all trailing spaces (no check on begin: sout always start with ') */
sout--;
while (*sout == ' ') sout--;
sout++;
(*sout) = '\'';++sout;
(*sout) = '\0';++sout;
// redone these special characters: mvh 20110105
//20120701: seems this is not needed and highly complicates further processing
//if (AddEscape && db->db_type==DT_POSTGRES) strcpy(sout-1, " ESCAPE E'\\\\'");
//else if (AddEscape) strcpy(sout-1, " ESCAPE '\\'");
// end redone these special characters: mvh 20110105
delete s;
return ( TRUE );
}
BOOL DICOM2SQLQuery (
char *s,
Database *db )
{
VR vr;
char *s1;
if(*s)
{
vr.Data = (void*)s;
vr.Length = strnlen32u(s);
vr.Group = 0;
vr.Element = 0;
s1 = (char *)malloc(vr.Length*3 + 20); // must allow MakeSafeString in-place (!) ?E'[_]' ESCAPE '\'
MakeSafeString(&vr, s1, db);
strcpy(s, s1);
free(s1);
vr.Data = NULL;
vr.Length = 0;
}
return ( TRUE );
}
BOOL
BuildSearchString(Database *DB, DBENTRY *DBE, char *TableName, VR *vr, char *Search,
char *TempString, int maxlen)
{
char *s, *t, *search;
char ch;
char TempString1[64];
char TempString2[64];
UINT Index = DBEIndex(DBE, vr);
int len;
char escape[16];
IniValue *iniValuePtr = IniValue::GetInstance();
if (iniValuePtr->sscscpPtr->UseEscapeStringConstants)
{
escape[0]='E';
escape[1]=0;
}
else
escape[0]=0;
search = Search;
if (*search=='?') search++;
if (*search=='E') search++;
if(vr->Length)
{
if(DBE[Index].DICOMType==DT_DATE)
{
if((s=strchr(search, '-')))
{
// Date Range
if((*(s+1))=='\'')
{
(*(s+1)) = '\0';
(*s) = '\'';
sprintf(TempString, "%s.%s >= %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
}
else if((*(s-1))=='\'')
{
(*s) = '\'';
sprintf(TempString, "%s.%s <= %s%s", TableName, DBE[Index].SQLColumn,
escape, s);
}
else
{
// Bummer format is 'date-date'
ch = (*(s+1));
(*(s+1)) = '\0';
(*s) = '\'';
sprintf(TempString1, "%s.%s >= %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
(*(s+1)) = ch;
sprintf(TempString2, "%s.%s <= %s%s", TableName, DBE[Index].SQLColumn,
escape, s);
sprintf(TempString, "%s and %s", TempString1, TempString2);
}
}
else
{
if (Search[0]=='?')
sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
else
sprintf(TempString, "%s.%s = %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
}
}
// Multiple UID matching
else if(DBE[Index].DICOMType==DT_UI)
{
BOOL dbiii = (DB->db_type == DT_DBASEIII);
s = strchr(search, '\\');
if (s && !dbiii)
{
// Multiple UID matching sql server style with syntax: field in ('a','b','c')
// requires 3 characters per UID, e.g., 8192-512 fits about 110 UIDs
sprintf(TempString, "%s.%s in (", TableName, DBE[Index].SQLColumn);
t = search + 1; // skip '
while (s) // before each \ is an UID
{
*s = 0;
if (s[1] == '\\') // also process double backslash correctly
{
s++;
*s = 0;
}
len = strnlenint(TempString);//maxlen is int
if (len<maxlen)
sprintf(TempString + len, "'%s',", t);
t = s + 1;
s = strchr(t, '\\');
}
// the last UID ends with a '
sprintf(TempString + strlen(TempString), "'%s)", t);
}
else if (s && dbiii)
{
// Multiple UID matching built-in dbaseIII style with | syntax: field in 'a|b|c'
// requires 1 character per UID, e.g., 8192-512 fit max about 115 UIDs
sprintf(TempString, "%s.%s in '", TableName, DBE[Index].SQLColumn);
t = search + 1; // skip '
while (s) // before each \ is an UID
{
*s = 0;
if (s[1] == '\\') // also process double backslash correctly
{
s++;
*s = 0;
}
len = strnlenint(TempString);
if (len<maxlen)
sprintf(TempString + len, "%s|", t);
t = s + 1;
s = strchr(t, '\\');
}
// the last UID ends with a '
sprintf(TempString + strlen(TempString), "%s", t);
}
else
{
if (Search[0]=='?')
sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
else
sprintf(TempString, "%s.%s = %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
}
}
// DT_MSTR: PET matches 'PET', 'PET\CT', 'MR\PET\CT', and 'CT\PET'
// not implemented yet for DBASEIII, also wildcards give original query
else if((DBE[Index].DICOMType==DT_MSTR) && (DB->db_type != DT_DBASEIII))
{
if (Search[0]=='?')
sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
else
{
char *p = search + strlen(search) - 1;
const char *d;
// mysql and postgres require four backslashes
if (iniValuePtr->sscscpPtr->DoubleBackSlashToDB) d = "\\\\\\\\"; else d = "\\";
sprintf(TempString, "(%s.%s = %s%s or ", TableName, DBE[Index].SQLColumn,
escape, search);
*p = 0;
sprintf(TempString + strlen(TempString), "%s.%s LIKE %s'%s%s%%' or ", TableName, DBE[Index].SQLColumn,
escape, search+1, d);
sprintf(TempString + strlen(TempString), "%s.%s LIKE %s'%%%s%s%s%%' or ", TableName, DBE[Index].SQLColumn,
escape, d, search+1, d);
sprintf(TempString + strlen(TempString), "%s.%s LIKE %s'%%%s%s')", TableName, DBE[Index].SQLColumn,
escape, d, search+1);
*p = '\'';
}
}
else
{
if (Search[0]=='?')
sprintf(TempString, "%s.%s LIKE %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
else
{
sprintf(TempString, "%s.%s = %s%s", TableName, DBE[Index].SQLColumn,
escape, search);
if (DBE[Index].DICOMType==DT_MSTR)
SystemDebug.printf("warning: query for this multi-valued item (%s) will not test individual values\n", DBE[Index].SQLColumn);
}
}
return (TRUE);
}
return ( FALSE );
}
BOOL
BuildColumnString(DBENTRY *DBE, char *TableName, VR *vr, char *TempString)
{
UINT Index = DBEIndex(DBE, vr);
strcpy(TempString, TableName);
strcat(TempString, ".");
strcat(TempString, DBE[Index].SQLColumn);
return ( TRUE );
}
UINT32
SQLRealSize(char *Str, SDWORD Max)
{
UNUSED_ARGUMENT(Str);
#if 0
UINT32 Index = 0;
UINT32 RSize = 0;
#endif
if(Max<0) return 0;
return (UINT32)(Max & UINT32_MAX);
#if 0
while (Index < Max) // mvh 20051123
{
if(Str[Index]== 0 ) break;
if(Str[Index]!=' ') RSize = Index+1;
++Index;
}
return ( RSize );
#endif
}
// compute items like 'Number of Patient Related Studies' and generate VR with the result
// allowcount should only be set TRUE for databases that allows SELECT COUNT(1) statements
static VR *ComputeField(DICOMDataObject *DDO, int group, int element, UINT16 mask, BOOL allowcount)
{
Array < DICOMDataObject * > ADDO;
char count[16];
const char *Level;
VR *vr, *vr2;
int save = DebugLevel, count1, count2, sources=0;
unsigned int i;
BOOL CountOnly = FALSE;
// level for VirtualQueries to other servers
Level = NULL;
if (element==0x1200) Level = "STUDY";
if (element==0x1202) Level = "SERIES";
if (element==0x1206) Level = "SERIES";
if (element==0x1204) Level = "IMAGE";
if (element==0x1208) Level = "IMAGE";
if (element==0x1209) Level = "IMAGE";
// make that a UNIQUE query will result the correct count
if (element==0x1200 && DDO->GetVR(0x0020, 0x000d)==NULL) DDO->Push(new VR(0x0020, 0x000d, 0, FALSE));
if (element==0x1202 && DDO->GetVR(0x0020, 0x000e)==NULL) DDO->Push(new VR(0x0020, 0x000e, 0, FALSE));
if (element==0x1206 && DDO->GetVR(0x0020, 0x000e)==NULL) DDO->Push(new VR(0x0020, 0x000e, 0, FALSE));
if (element==0x1204 && DDO->GetVR(0x0008, 0x0018)==NULL) DDO->Push(new VR(0x0008, 0x0018, 0, FALSE));
if (element==0x1208 && DDO->GetVR(0x0008, 0x0018)==NULL) DDO->Push(new VR(0x0008, 0x0018, 0, FALSE));
if (element==0x1209 && DDO->GetVR(0x0008, 0x0018)==NULL) DDO->Push(new VR(0x0008, 0x0018, 0, FALSE));
// query other virtualfor servers
for (i=0; i<10; i++)
if (mask & (1<<i))
sources += VirtualQuery(DDO, Level, i, &ADDO, NULL)!=0;
count1 = ADDO.GetSize();
if (allowcount && count1==0)
{
CountOnly = TRUE;
DDO->Push(new VR(0x9999, 0x9999, 0, FALSE)); // no need to locate duplicates: force CountOnly
sources = 0;
}
// query this server
DebugLevel=0;
if (element==0x1200) QueryOnStudy (DDO, &ADDO); // Number of Patient Related Studies
if (element==0x1202) QueryOnSeries (DDO, &ADDO); // Number of Patient Related Series
if (element==0x1206) QueryOnSeries (DDO, &ADDO); // Number of Study Related Series
if (element==0x1204) QueryOnImage (DDO, &ADDO); // Number of Patient Related Instances
if (element==0x1208) QueryOnImage (DDO, &ADDO); // Number of Study Related Instances
if (element==0x1209) QueryOnImage (DDO, &ADDO); // Number of Series Related Instances
DebugLevel=save;
// count number of servers accessed
count2 = ADDO.GetSize()-count1;
sources += count2!=0;
if (sources>1) // more than one source; data can be duplicated
RemoveQueryDuplicates(Level, &ADDO);
// create result VR
sprintf(count, "%d", ADDO.GetSize());
if (strlen(count)&1) strcat(count, " ");
vr = new VR( group, element, strnlen32u(count), TRUE);
memcpy(vr->Data, count, strlen(count));
if (!CountOnly)
{
// free arrays
for (i=0; i<ADDO.GetSize(); i++)
while((vr2=ADDO.Get(i)->Pop())) delete vr2;
while (ADDO.GetSize())
{
delete ADDO.Get(0);
ADDO.RemoveAt(0);
}
}
else
while (ADDO.GetSize())
ADDO.RemoveAt(0);
return vr;
}
BOOL QueryOnPatient (
DICOMDataObject *DDO,
Array < DICOMDataObject *> *ADDO)
{
UINT Index, CIndex, CCIndex;
UINT32 VRLength;
DICOMDataObject *RDDO;
Database DB;
char *SQLResultString;
Array < char * > SQLResult, SQLResultPatient;
Array < VR * > EMaskPatient, EMask;
Array < SQLLEN *> SQLResultLength;
Array < DBENTRY * > DBQPatient;
Array < DBENTRY * > DBQMaster;
DBENTRY *TempDBEPtr;
char *DBR;
SQLLEN *DBL;
VR *vr;
VR VRPatientName;
DBENTRY *DBEntryPatientName;
char SortOrder[128];
char *Sorting;
BOOL DoSort;
BOOL SendAE = FALSE;
char TempString [ 8192 ];
char SearchString [ 8192 ];
char ColumnString [ 4096 ];
char Tables [ 256 ];
char *Sort=NULL;
DICOMDataObject *qStudies = NULL;
DICOMDataObject *qSeries = NULL;
DICOMDataObject *qSops = NULL;
UINT16 mask = 0xffff;
BOOL CountOnly = FALSE;
SystemDebug.printf("Query On Patient\n");
IniValue *iniValuePtr = IniValue::GetInstance();
if (!DB.Open ( iniValuePtr->sscscpPtr->DataSource, iniValuePtr->sscscpPtr->UserName,
iniValuePtr->sscscpPtr->Password, iniValuePtr->sscscpPtr->DataHost ) )
{
DB.PrintLastError();
return ( FALSE ); // failed open
}
// First. Check that all the asked-for elements are actually in
// the Patient/Study database. If they are not, well, then we
// return FALSE.
DoSort = FALSE;
while ((vr = DDO->Pop()))
{
if(vr->Element == 0x0000)
{
delete vr;
continue; // discard length codes
}
if(vr->Group == 0x0002)
if(vr->Element == 0x0010)
{
delete vr;
continue; // discard transfer syntax
}
if(vr->Group == 0x0008)
if(vr->Element == 0x0052)
{
delete vr;
continue; // discard model level
}
if(vr->Group == 0x0008)
if(vr->Element == 0x0054)
{
SendAE = TRUE;
delete vr;
continue; // discard it (but send it)
}
if(vr->Group == 0x0020 && iniValuePtr->sscscpPtr->EnableComputedFields)
if(vr->Element == 0x1200)
{
qStudies = new DICOMDataObject;
delete vr;
continue; // discard 'Number of' items (but send them)
}
if(vr->Group == 0x0020 && iniValuePtr->sscscpPtr->EnableComputedFields)
if(vr->Element == 0x1202)
{
qSeries = new DICOMDataObject;
delete vr;
continue; // discard 'Number of' items (but send them)
}
if(vr->Group == 0x0020 && iniValuePtr->sscscpPtr->EnableComputedFields)
if(vr->Element == 0x1204)
{
qSops = new DICOMDataObject;
delete vr;
continue; // discard 'Number of' items (but send them)
}
if(vr->Group == 0x9999)
if(vr->Element == 0x0802)
{
mask = vr->GetUINT16();
delete vr;
continue; // discard it
}
if(vr->Group == 0x9999)
if(vr->Element == 0x0900)
{
mask = vr->GetUINT16();
delete vr;
continue; // discard it
}
if(vr->Group == 0x9999)
if(vr->Element == 0x9999)
{
CountOnly = TRUE;
delete vr;
continue; // discard it
}
if(!VerifyIsInDBE(vr, PatientDB, TempDBEPtr))
{
SystemDebug.printf("Queried item %4.4x %4.4x is not in the database\n",
vr->Group, vr->Element);
delete vr;
continue;
while(EMaskPatient.GetSize())
{
delete EMaskPatient.Get(0);
EMaskPatient.RemoveAt(0);
}
while(SQLResultPatient.GetSize())
{
delete SQLResultPatient.Get(0);
SQLResultPatient.RemoveAt(0);
}
return ( FALSE );
}
else
{
if(vr->Group == 0x0010)
if(vr->Element == 0x0010)
DoSort = TRUE;
SQLResultString = SetString(vr, NULL, 0);
DICOM2SQLQuery(SQLResultString, &DB);
SQLResultPatient.Add ( SQLResultString );
EMaskPatient.Add ( vr );
DBQPatient.Add ( TempDBEPtr );
}
}
// Prepare the query string.
// from EMasks, and SQLResults
SearchString[0] = '\0';
ColumnString[0] = '\0';
Index = 0;CIndex = 0;CCIndex = 0;
while ( Index < SQLResultPatient.GetSize() )
{
SQLResultString = SQLResultPatient.Get(Index);
if(BuildSearchString(&DB, PatientDB, iniValuePtr->sscscpPtr->PatientTableName, EMaskPatient.Get(Index),
SQLResultString, TempString, sizeof(TempString)-512))
{
if(CIndex++)
safestrcat(SearchString, " and ", sizeof(SearchString));
safestrcat(SearchString, TempString, sizeof(SearchString));
}
BuildColumnString(PatientDB, iniValuePtr->sscscpPtr->PatientTableName, EMaskPatient.Get(Index), TempString);
if(CCIndex)
strcat(ColumnString, ", ");
strcat(ColumnString, TempString);
EMask.Add(EMaskPatient.Get(Index));
DBQMaster.Add(DBQPatient.Get(Index));
++Index;++CCIndex;
}
if (iniValuePtr->sscscpPtr->PatientQuerySortOrder[0])
{
if(CCIndex)
strcat(ColumnString, ", ");
strcat(ColumnString, iniValuePtr->sscscpPtr->PatientQuerySortOrder);
}
sprintf(Tables, "%s",
iniValuePtr->sscscpPtr->PatientTableName);
if (CountOnly)
sprintf(ColumnString, "COUNT(1)");
SystemDebug.printf("Issue Query on Columns: %s\n", ColumnString);
SystemDebug.printf("Values: %.1000s\n", SearchString);
SystemDebug.printf("Tables: %.1000s\n", Tables);
while(SQLResultPatient.GetSize())
{
delete SQLResultPatient.Get(0);
SQLResultPatient.RemoveAt(0);
}
VRPatientName.Group = 0x0010;
VRPatientName.Element = 0x0010;
DBEntryPatientName = FindDBE(&VRPatientName);
if(DBEntryPatientName)
{
sprintf(SortOrder, "%s.%s",
iniValuePtr->sscscpPtr->PatientTableName,
DBEntryPatientName->SQLColumn);
if(DoSort)
Sorting = SortOrder;
else
Sorting = NULL;
}
else
Sorting = NULL;
Sort = Sorting;
if (iniValuePtr->sscscpPtr->PatientQuerySortOrder[0]) Sort = iniValuePtr->sscscpPtr->PatientQuerySortOrder;
SystemDebug.printf("Sorting (%s) DoSort := %d\n", Sort, DoSort);
if(strlen(SearchString))
{
if (!DB.QueryDistinct ( Tables, ColumnString, SearchString, Sort) )
{
DB.PrintLastError();
return ( FALSE ); // failed query
}
}
else
if (!DB.QueryDistinct ( Tables, ColumnString, NULL, Sort))
{
DB.PrintLastError();
return ( FALSE ); // failed query
}
if (!CountOnly)
{
Index = 0;
while ( Index < CCIndex )
{
DBR = new char[255];
DBR[0] = 0; // in case a field is NULL it does not read
SQLResult.Add(DBR);
DBL = new SQLLEN;
SQLResultLength.Add(DBL);
if(!DB.BindField (Index+1, SQL_C_CHAR,
SQLResult.Get(Index), 255,
SQLResultLength.Get(Index)))
{
SystemDebug.printf("Column Number : %d\n", Index+1);
DB.PrintLastError();
while(SQLResult.GetSize())
{
delete SQLResult.Get(0);
SQLResult.RemoveAt(0);
}
while(SQLResultLength.GetSize())
{
delete SQLResultLength.Get(0);
SQLResultLength.RemoveAt(0);
}
return ( FALSE ); // failed to bind column
}
++Index;
}
while (DB.NextRecord())
{
RDDO = new DICOMDataObject;
Index = 0;
while ( Index < CCIndex )
{
VRLength = SQLRealSize(SQLResult.Get(Index),
*SQLResultLength.Get(Index));
vr = ConstructVRFromSQL (
DBQMaster.Get(Index),
EMask.Get(Index)->Group,
EMask.Get(Index)->Element,
VRLength,
SQLResult.Get(Index));
if (qStudies)
qStudies->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
if (qSeries)
qSeries->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
if (qSops)
qSops->Push(ConstructVRFromSQL (DBQMaster.Get(Index), EMask.Get(Index)->Group, EMask.Get(Index)->Element, VRLength, SQLResult.Get(Index)));
RDDO->Push(vr);
++Index;
}
if(SendAE)
RDDO->Push(ConstructAE());
if (qStudies)
{