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
  
1001
  
1002
  
1003
  
1004
  
1005
  
1006
  
1007
  
1008
  
1009
  
1010
  
1011
  
1012
  
1013
  
1014
  
1015
  
1016
  
1017
  
1018
  
1019
  
1020
  
1021
  
1022
  
1023
  
1024
  
1025
  
1026
  
1027
  
1028
  
1029
  
1030
  
1031
  
1032
  
1033
  
1034
  
1035
  
1036
  
1037
  
1038
  
1039
  
1040
  
1041
  
1042
  
1043
  
1044
  
1045
  
1046
  
1047
  
1048
  
1049
  
1050
  
1051
  
1052
  
1053
  
1054
  
1055
  
1056
  
1057
  
1058
  
1059
  
1060
  
1061
  
1062
  
1063
  
1064
  
1065
  
1066
  
1067
  
1068
  
1069
  
1070
  
1071
  
1072
  
1073
  
1074
  
1075
  
1076
  
1077
  
1078
  
1079
  
1080
  
1081
  
1082
  
1083
  
1084
  
1085
  
1086
  
1087
  
1088
  
1089
  
1090
  
1091
  
1092
  
1093
  
1094
  
1095
  
1096
  
1097
  
1098
  
1099
  
1100
  
1101
  
1102
  
1103
  
1104
  
1105
  
1106
  
1107
  
1108
  
1109
  
1110
  
1111
  
1112
  
1113
  
1114
  
1115
  
1116
  
1117
  
1118
  
1119
  
1120
  
1121
  
1122
  
1123
  
1124
  
1125
  
1126
  
1127
  
1128
  
1129
  
1130
  
1131
  
1132
  
1133
  
1134
  
1135
  
1136
  
1137
  
1138
  
1139
  
1140
  
1141
  
1142
  
1143
  
1144
  
1145
  
1146
  
1147
  
1148
  
1149
  
1150
  
1151
  
1152
  
1153
  
1154
  
1155
  
1156
  
1157
  
1158
  
1159
  
1160
  
1161
  
1162
  
1163
  
1164
  
1165
  
1166
  
1167
  
1168
  
1169
  
1170
  
1171
  
1172
  
1173
  
1174
  
1175
  
1176
  
1177
  
1178
  
/* 
 * Some pgsql utility functions. 
 * They are kept here to avoid circular references. 
 */ 
 
//! The pgsql backend, shared between all connection instances. 
//! It runs even in non-callback mode in a separate thread and makes sure 
//! that communication with the database is real-time and event driven 
//! at all times. 
//! 
//! @note 
//! Callbacks running from this backend directly determine the latency 
//! in reacting to communication with the database server; so it 
//! would be prudent not to block in these callbacks. 
 
#pike __REAL_VERSION__ 
#require constant(Thread.Thread) 
 
#include "pgsql.h" 
 
//! The instance of the pgsql dedicated backend. 
final Pike.Backend local_backend = Pike.SmallBackend(); 
 
private Thread.Mutex backendmux = Thread.Mutex(); 
private int clientsregistered; 
 
constant emptyarray = ({}); 
final multiset censoroptions=(<"use_ssl","force_ssl", 
 "cache_autoprepared_statements","reconnect","text_query","is_superuser", 
 "server_encoding","server_version","integer_datetimes", 
 "session_authorization">); 
final multiset cachealways=(<"BEGIN","begin","END","end","COMMIT","commit">); 
 
 /* Statements matching createprefix cause the prepared statement cache 
  * to be flushed to prevent stale references to (temporary) tables 
  */ 
final Regexp createprefix=iregexp("^\a*(CREATE|DROP)\a"); 
 
 /* Statements matching dontcacheprefix never enter the cache 
  */ 
private Regexp dontcacheprefix=iregexp("^\a*(FETCH|COPY)\a"); 
 
 /* Statements not matching paralleliseprefix will cause the driver 
  * to stall submission until all previously started statements have 
  * run to completion 
  */ 
private Regexp paralleliseprefix 
 =iregexp("^\a*((SELEC|INSER)T|(UPDA|DELE)TE|FETCH)\a"); 
 
 /* For statements matching execfetchlimit the resultrows will not be 
  * fetched in pieces 
  */ 
private Regexp execfetchlimit 
 =iregexp("^\a*((UPDA|DELE)TE|INSERT)\a|\aLIMIT\a+[1-9][; \t\f\r\n]*$"); 
 
private Regexp iregexp(string expr) { 
  Stdio.Buffer ret=Stdio.Buffer(); 
  foreach(expr;;int c) 
    if(c>='A'&&c<='Z') 
      ret->add('[',c,c+'a'-'A',']'); 
    else if(c=='\a')                    // Replace with generic whitespace 
      ret->add("[ \t\f\r\n]"); 
    else 
      ret->add_int8(c); 
  return Regexp(ret->read()); 
} 
 
final void closestatement(bufcon|conxion plugbuffer,string oldprep) { 
  if(oldprep) { 
    PD("Close statement %s\n",oldprep); 
    plugbuffer->add_int8('C')->add_hstring(({'S',oldprep,0}),4,4); 
  } 
} 
 
private void run_local_backend() { 
  Thread.MutexKey lock; 
  int looponce; 
  do { 
    looponce=0; 
    if(lock=backendmux->trylock()) { 
      PD("Starting local backend\n"); 
      while (clientsregistered) {       // Autoterminate when not needed 
        mixed err; 
        if (err = catch(local_backend(4096.0))) 
          werror(describe_backtrace(err)); 
      } 
      PD("Terminating local backend\n"); 
      lock=0; 
      looponce=clientsregistered; 
    } 
  } while(looponce); 
} 
 
//! Registers yourself as a user of this backend.  If the backend 
//! has not been started yet, it will be spawned automatically. 
final void register_backend() { 
  if(!clientsregistered++) 
    Thread.Thread(run_local_backend); 
} 
 
//! Unregisters yourself as a user of this backend.  If there are 
//! no longer any registered users, the backend will be terminated. 
final void unregister_backend() { 
  --clientsregistered; 
} 
 
final void throwdelayederror(object parent) { 
  if(mixed err=parent._delayederror) { 
    parent._delayederror=UNDEFINED; 
    if(stringp(err)) 
      err=({err,backtrace()[..<2]}); 
    throw(err); 
  } 
} 
 
final int oidformat(int oid) { 
  switch(oid) { 
    case BOOLOID: 
    case BYTEAOID: 
    case CHAROID: 
    case INT8OID: 
    case INT2OID: 
    case INT4OID: 
    case TEXTOID: 
    case OIDOID: 
    case XMLOID: 
    case MACADDROID: 
    case BPCHAROID: 
    case VARCHAROID: 
    case CTIDOID: 
    case UUIDOID: 
      return 1; //binary 
  } 
  return 0; // text 
} 
 
private int mergemode(conxion realbuffer,int mode) { 
  if(mode>realbuffer->stashflushmode) 
    realbuffer->stashflushmode=mode; 
  return realbuffer->stashflushmode; 
} 
 
private inline mixed callout(function(mixed ...:void) f, 
 float|int delay,mixed ... args) { 
  return local_backend->call_out(f,delay,@args); 
} 
 
// Some pgsql utility functions 
 
class bufcon { 
  inherit Stdio.Buffer; 
 
  private conxion realbuffer; 
 
  protected void create(conxion _realbuffer) { 
    realbuffer=_realbuffer; 
  } 
 
  final bufcon start(void|int waitforreal) { 
    realbuffer->stashcount++; 
#ifdef PG_DEBUG 
    if(waitforreal) 
      error("pgsql.bufcon not allowed here\n"); 
#endif 
    return this; 
  } 
 
  final void sendcmd(int mode,void|sql_result portal) { 
    Thread.MutexKey lock=realbuffer->shortmux->lock(); 
    if(portal) 
      realbuffer->stashqueue->write(portal); 
    realbuffer->stash->add(this); 
    mode=mergemode(realbuffer,mode); 
    if(!--realbuffer->stashcount) 
      realbuffer->stashavail.signal(); 
    lock=0; 
    this->clear(); 
    if(lock=realbuffer->nostash->trylock(1)) { 
      realbuffer->started=lock; lock=0; 
      realbuffer->sendcmd(SENDOUT); 
    } 
  } 
 
}; 
 
class conxiin { 
  inherit Stdio.Buffer:i; 
 
  final Thread.Condition fillread; 
  final Thread.Mutex fillreadmux; 
  final int procmsg; 
  private int didreadcb; 
 
  protected bool range_error(int howmuch) { 
#ifdef PG_DEBUG 
    if(howmuch<=0) 
      error("Out of range %d\n",howmuch); 
#endif 
    if(fillread) { 
      Thread.MutexKey lock=fillreadmux->lock(); 
      if(!didreadcb) 
        fillread.wait(lock); 
      didreadcb=0; 
      lock=0; 
    } else 
      throw(MAGICTERMINATE); 
    return true; 
  } 
 
  final int read_cb(mixed id,mixed b) { 
    PD("Read callback %O\n",((string)b) 
#ifndef PG_DEBUGMORE 
      [..255] 
#endif 
     ); 
    Thread.MutexKey lock=fillreadmux->lock(); 
    if(procmsg&&id) 
      procmsg=0,lock=0,Thread.Thread(id); 
    else if(fillread) 
      didreadcb=1, fillread.signal(); 
    lock=0; 
    return 0; 
  } 
 
  protected void create() { 
    i::create(); 
    fillreadmux=Thread.Mutex(); 
    fillread=Thread.Condition(); 
  } 
}; 
 
class conxion { 
  inherit Stdio.Buffer:o; 
  final conxiin i; 
 
  private Thread.Queue qportals; 
  final Thread.Mutex shortmux; 
  private int closenext; 
 
  final Stdio.File socket; 
  private function(void|mixed:void) connectfail; 
  private int towrite; 
  final multiset(function(void|mixed:void)) closecallbacks=(<>); 
 
  final Thread.Mutex nostash; 
  final Thread.MutexKey started; 
  final Thread.Queue stashqueue; 
  final Thread.Condition stashavail; 
  final Stdio.Buffer stash; 
  final int stashflushmode; 
  final int stashcount; 
  final int synctransact; 
#ifdef PG_DEBUG 
  final int queueoutidx; 
  final int queueinidx=-1; 
#endif 
 
  private inline void queueup(sql_result portal) { 
    qportals->write(portal); portal->_synctransact=synctransact; 
    PD("%d>%O %d %d Queue portal %d bytes\n",socket->query_fd(), 
     portal._portalname,++queueoutidx,synctransact,sizeof(this)); 
  } 
 
  final conxion|bufcon start(void|int waitforreal) { 
    Thread.MutexKey lock; 
    if(lock=(waitforreal?nostash->lock:nostash->trylock)(1)) { 
      started=lock; 
      lock=shortmux->lock(); 
      if(stashcount) 
        PT(stashavail.wait(lock)); 
      add(stash); stash->clear(); 
      foreach(stashqueue->try_read_array();;sql_result portal) 
        queueup(portal); 
      lock=0; 
      return this; 
    } 
    stashcount++; 
    return bufcon(this); 
  } 
 
  private int write_cb() { 
    Thread.MutexKey lock = shortmux->lock(); 
    towrite -= output_to(socket,towrite); 
    lock = 0; 
#ifdef PG_DEBUG 
    if (!i->fillread) 
      PD("%d>Delayed close to go %d\n", socket->query_fd(), sizeof(this)); 
#endif 
    if (!i->fillread && !sizeof(this)) 
      close(); 
    return 0; 
  } 
 
  final void sendcmd(void|int mode, void|sql_result portal) { 
    if (portal) 
      queueup(portal); 
    Thread.MutexKey lock; 
    if (started) { 
      lock = shortmux->lock(); 
      if (sizeof(stash)) { 
        add(stash); 
        stash->clear(); 
        foreach (stashqueue->try_read_array();; sql_result portal) 
          queueup(portal); 
      } 
      mode = mergemode(this, mode); 
      stashflushmode = KEEP; 
    } 
nosync: 
    do { 
      switch (mode) { 
        default: 
          break nosync; 
        case SYNCSEND: 
          PD("%d>Sync %d %d Queue\n", 
           socket->query_fd(), synctransact, ++queueoutidx); 
          add(PGSYNC); 
          mode = SENDOUT; 
          break; 
        case FLUSHLOGSEND: 
          PD("%d>%O %d Queue simplequery %d bytes\n", 
           socket->query_fd(), portal._portalname, ++queueoutidx, sizeof(this)); 
          mode = FLUSHSEND; 
      } 
      qportals->write(synctransact++); 
    } while (0); 
    catch { 
outer: 
      do { 
        switch(mode) { 
          default: 
            PD("%d>Skip flush %d Queue %O\n", 
             socket->query_fd(), mode, (string)this); 
            break outer; 
          case FLUSHSEND: 
            PD("Flush\n"); 
            add(PGFLUSH); 
          case SENDOUT:; 
        } 
        if(!lock) 
          lock=shortmux->lock(); 
        if(towrite=sizeof(this)) { 
          PD("%d>Sendcmd %O\n",socket->query_fd(),((string)this)[..towrite-1]); 
          towrite-=output_to(socket,towrite); 
        } 
      } while(0); 
      lock=started=0; 
      return; 
    }; 
    lock=0; 
    catch(connectfail()); 
  } 
 
  final int close() { 
    if(!closenext && nostash) { 
      closenext=1; 
      Thread.MutexKey lock=i->fillreadmux->lock(); 
      if(i->fillread) {  // Delayed close() after flushing the output buffer 
        i->fillread.signal(); 
        i->fillread=0; 
      } 
      lock=0; 
      PD("%d>Delayed close, flush write\n",socket->query_fd()); 
      i->read_cb(socket->query_id(),0); 
      return 0; 
    } else 
      return -1; 
  } 
 
  protected void destroy() { 
    PD("%d>Close conxion %d\n", socket ? socket->query_fd() : -1, !!nostash); 
    if(nostash) { 
      catch { 
        while(sizeof(closecallbacks)) 
          foreach(closecallbacks;function(void|mixed:void) closecb;) 
            closecb(); 
        destruct(nostash); 
        PD("%d>Close socket\n",socket->query_fd()); 
        socket->close(); 
      }; 
    } 
    connectfail=0; 
  } 
 
  final void connectloop(object pgsqlsess, int nossl) { 
    mixed err=catch { 
      for(;;clear()) { 
        socket->connect(pgsqlsess._host,pgsqlsess._port); 
#if constant(SSL.File) 
        if(!nossl && !pgsqlsess->nossl 
         && (pgsqlsess._options.use_ssl || pgsqlsess._options.force_ssl)) { 
          PD("SSLRequest\n"); 
          start()->add_int32(8)->add_int32(PG_PROTOCOL(1234,5679)) 
           ->sendcmd(SENDOUT); 
          switch(read_int8()) { 
            case 'S': 
              object fcon=SSL.File(socket,SSL.Context()); 
              if(fcon->connect()) { 
                socket=fcon; 
                break; 
              } 
            default:PD("%d>Close socket\n",socket->query_fd()); 
              socket->close(); 
              pgsqlsess.nossl=1; 
              continue; 
            case 'N': 
              if(pgsqlsess._options.force_ssl) 
                error("Encryption not supported on connection to %s:%d\n", 
                      pgsqlsess.host,pgsqlsess.port); 
          } 
        } 
#else 
        if(pgsqlsess._options.force_ssl) 
          error("Encryption library missing," 
                " cannot establish connection to %s:%d\n", 
                pgsqlsess.host,pgsqlsess.port); 
#endif 
        break; 
      } 
      if(!socket->is_open()) 
        error(strerror(socket->errno())+".\n"); 
      connectfail=pgsqlsess->_connectfail; 
      socket->set_backend(local_backend); 
      socket->set_buffer_mode(i,0); 
      socket->set_nonblocking(i->read_cb,write_cb,close); 
      if (nossl != 2) { 
        connectfail=pgsqlsess->_connectfail; 
        Thread.Thread(pgsqlsess->_processloop,this); 
      } 
      return; 
    }; 
    catch(connectfail(err)); 
  } 
 
  private string _sprintf(int type, void|mapping flags) { 
    string res=UNDEFINED; 
    switch(type) { 
      case 'O': 
        int fd=-1; 
        if(socket) 
          catch(fd=socket->query_fd()); 
        res=predef::sprintf("conxion  fd: %d input queue: %d/%d " 
                    "queued portals: %d  output queue: %d/%d\n", 
                    fd,sizeof(i),i->_size_object(), 
                    qportals->size(),sizeof(this),_size_object()); 
        break; 
    } 
    return res; 
  } 
 
  protected void create(object pgsqlsess,Thread.Queue _qportals,int nossl) { 
    o::create(); 
    qportals = _qportals; 
    synctransact = 1; 
    socket=Stdio.File(); 
    i=conxiin(); 
    shortmux=Thread.Mutex(); 
    nostash=Thread.Mutex(); 
    closenext = 0; 
    stashavail=Thread.Condition(); 
    stashqueue=Thread.Queue(); 
    stash=Stdio.Buffer(); 
    Thread.Thread(connectloop,pgsqlsess,nossl); 
  } 
}; 
 
//! The result object returned by @[Sql.pgsql()->big_query()], except for 
//! the noted differences it behaves the same as @[Sql.sql_result]. 
//! 
//! @seealso 
//!   @[Sql.sql_result], @[Sql.pgsql], @[Sql.Sql], @[Sql.pgsql()->big_query()] 
class sql_result { 
 
  private object pgsqlsess; 
  private int eoffound; 
  private conxion c; 
  private conxiin cr; 
  final mixed _delayederror; 
  final int _state; 
  final int _fetchlimit; 
  private int alltext; 
  final int _forcetext; 
 
  final string _portalname; 
 
  private int rowsreceived; 
  private int inflight; 
  private int portalbuffersize; 
  private Thread.Mutex closemux; 
  private Thread.Queue datarows; 
  private array(mapping(string:mixed)) datarowdesc; 
  private array(int) datarowtypes;  // types from datarowdesc 
  private string statuscmdcomplete; 
  private int bytesreceived; 
  final int _synctransact; 
  final Thread.Condition _ddescribe; 
  final Thread.Mutex _ddescribemux; 
  final Thread.MutexKey _unnamedportalkey,_unnamedstatementkey; 
  final array _params; 
  final string _query; 
  final string _preparedname; 
  final mapping(string:mixed) _tprepared; 
  private function(:void) gottimeout; 
  private int timeout; 
 
  private string _sprintf(int type, void|mapping flags) { 
    string res=UNDEFINED; 
    switch(type) { 
      case 'O': 
        int fd=-1; 
        if(c&&c->socket) 
          catch(fd=c->socket->query_fd()); 
        res=sprintf("sql_result state: %d numrows: %d eof: %d inflight: %d\n" 
                    "query: %O\n" 
                    "fd: %O portalname: %O  datarows: %d" 
                    "  laststatus: %s\n", 
                    _state,rowsreceived,eoffound,inflight, 
                    _query,fd,_portalname,datarowtypes&&sizeof(datarowtypes), 
                    statuscmdcomplete||(_unnamedstatementkey?"*parsing*":"")); 
        break; 
    } 
    return res; 
  } 
 
  protected void create(object _pgsqlsess,conxion _c,string query, 
   int _portalbuffersize,int alltyped,array params,int forcetext, 
   int _timeout) { 
    pgsqlsess = _pgsqlsess; 
    cr = (c = _c)->i; 
    _query = query; 
    datarows = Thread.Queue(); 
    _ddescribe=Thread.Condition(); 
    _ddescribemux=Thread.Mutex(); 
    closemux=Thread.Mutex(); 
    portalbuffersize=_portalbuffersize; 
    alltext = !alltyped; 
    _params = params; 
    _forcetext = forcetext; 
    _state = PORTALINIT; 
    timeout = _timeout; 
    gottimeout = _pgsqlsess->cancelquery; 
    c->closecallbacks+=(<destroy>); 
  } 
 
  //! Returns the command-complete status for this query. 
  //! 
  //! @seealso 
  //!  @[affected_rows()] 
  //! 
  //! @note 
  //! This function is PostgreSQL-specific, and thus it is not available 
  //! through the generic SQL-interface. 
  /*semi*/final string status_command_complete() { 
    return statuscmdcomplete; 
  } 
 
  //! Returns the number of affected rows by this query. 
  //! 
  //! @seealso 
  //!  @[status_command_complete()] 
  //! 
  //! @note 
  //! This function is PostgreSQL-specific, and thus it is not available 
  //! through the generic SQL-interface. 
  /*semi*/final int affected_rows() { 
    int rows; 
    if(statuscmdcomplete) 
      sscanf(statuscmdcomplete,"%*s %d",rows); 
    return rows; 
  } 
 
  final void _storetiming() { 
    if(_tprepared) { 
      _tprepared.trun=gethrtime()-_tprepared.trunstart; 
      m_delete(_tprepared,"trunstart"); 
      _tprepared = UNDEFINED; 
    } 
  } 
 
  private void waitfordescribe() { 
    Thread.MutexKey lock=_ddescribemux->lock(); 
    if(!datarowtypes) 
      PT(_ddescribe->wait(lock)); 
    lock=0; 
  } 
 
  //! @seealso 
  //!  @[Sql.sql_result()->num_fields()] 
  /*semi*/final int num_fields() { 
    if(!datarowtypes) 
      waitfordescribe(); 
    trydelayederror(); 
    return sizeof(datarowtypes); 
  } 
 
  //! @note 
  //!  This method returns the number of rows already received from 
  //!  the database for the current query.  Note that this number 
  //!  can still increase between subsequent calls if the results from 
  //!  the query are not complete yet.  This function is only guaranteed to 
  //!  return the correct count after EOF has been reached. 
  //! @seealso 
  //!  @[Sql.sql_result()->num_rows()] 
  /*semi*/final int num_rows() { 
    trydelayederror(); 
    return rowsreceived; 
  } 
 
  private inline void trydelayederror() { 
    if(_delayederror) 
      throwdelayederror(this); 
  } 
 
  //! @seealso 
  //!  @[Sql.sql_result()->eof()] 
  /*semi*/final int eof() { 
    trydelayederror(); 
    return eoffound; 
  } 
 
  //! @seealso 
  //!  @[Sql.sql_result()->fetch_fields()] 
  /*semi*/final array(mapping(string:mixed)) fetch_fields() { 
    if(!datarowtypes) 
      waitfordescribe(); 
    trydelayederror(); 
    return datarowdesc+emptyarray; 
  } 
 
#ifdef PG_DEBUG 
#define INTVOID int 
#else 
#define INTVOID void 
#endif 
  final INTVOID _decodedata(int msglen,string cenc) { 
    _storetiming(); 
    string serror; 
    bytesreceived+=msglen; 
    int cols=cr->read_int16(); 
    array a=allocate(cols,!alltext&&Val.null); 
#ifdef PG_DEBUG 
    msglen-=2+4*cols; 
#endif 
    foreach(datarowtypes;int i;int typ) { 
      int collen=cr->read_sint(4); 
      if(collen>0) { 
#ifdef PG_DEBUG 
        msglen-=collen; 
#endif 
        mixed value; 
        switch(typ) { 
          case FLOAT4OID: 
#if SIZEOF_FLOAT>=8 
          case FLOAT8OID: 
#endif 
            if(!alltext) { 
              value=(float)cr->read(collen); 
              break; 
            } 
          default:value=cr->read(collen); 
            break; 
          case CHAROID: 
            value=alltext?cr->read(1):cr->read_int8(); 
            break; 
          case BOOLOID:value=cr->read_int8(); 
            switch(value) { 
              case 'f':value=0; 
                break; 
              case 't':value=1; 
            } 
            if(alltext) 
              value=value?"t":"f"; 
            break; 
          case TEXTOID: 
          case BPCHAROID: 
          case VARCHAROID: 
            value=cr->read(collen); 
            if(cenc==UTF8CHARSET && catch(value=utf8_to_string(value)) 
             && !serror) 
              serror=SERROR("%O contains non-%s characters\n", 
                                                     value,UTF8CHARSET); 
            break; 
          case INT8OID:case INT2OID: 
          case OIDOID:case INT4OID: 
            if(_forcetext) { 
              value=cr->read(collen); 
              if(!alltext) 
                value=(int)value; 
            } else { 
              switch(typ) { 
                case INT8OID:value=cr->read_sint(8); 
                  break; 
                case INT2OID:value=cr->read_sint(2); 
                  break; 
                case OIDOID: 
                case INT4OID:value=cr->read_sint(4); 
              } 
              if(alltext) 
                value=(string)value; 
            } 
        } 
        a[i]=value; 
      } else if(!collen) 
        a[i]=""; 
    } 
    _processdataready(a); 
    if(serror) 
      error(serror); 
#ifdef PG_DEBUG 
    return msglen; 
#endif 
  } 
 
  final void _setrowdesc(array(mapping(string:mixed)) drowdesc, 
   array(int) drowtypes) { 
    Thread.MutexKey lock=_ddescribemux->lock(); 
    datarowdesc=drowdesc; 
    datarowtypes=drowtypes; 
    _ddescribe->broadcast(); 
    lock=0; 
  } 
 
  final void _preparebind(array dtoid) { 
    array(string|int) paramValues=_params?_params[2]:({}); 
    if(sizeof(dtoid)!=sizeof(paramValues)) 
      SUSERERROR("Invalid number of bindings, expected %d, got %d\n", 
                 sizeof(dtoid),sizeof(paramValues)); 
    Thread.MutexKey lock=_ddescribemux->lock(); 
    if(!_portalname) { 
      _portalname=(_unnamedportalkey=pgsqlsess._unnamedportalmux->trylock(1)) 
         ? "" : PORTALPREFIX 
#ifdef PG_DEBUG 
          +(string)(c->socket->query_fd())+"_" 
#endif 
          +int2hex(pgsqlsess._pportalcount++); 
      lock=0; 
#ifdef PG_DEBUGMORE 
      PD("ParamValues to bind: %O\n",paramValues); 
#endif 
      Stdio.Buffer plugbuffer=Stdio.Buffer(); 
      { array dta=({sizeof(dtoid)}); 
        plugbuffer->add(_portalname,0,_preparedname,0) 
         ->add_ints(dta+map(dtoid,oidformat)+dta,2); 
      } 
      string cenc=pgsqlsess._runtimeparameter[CLIENT_ENCODING]; 
      foreach(paramValues;int i;mixed value) { 
        if(undefinedp(value) || objectp(value)&&value->is_val_null) 
          plugbuffer->add_int32(-1);                            // NULL 
        else if(stringp(value) && !sizeof(value)) { 
          int k=0; 
          switch(dtoid[i]) { 
            default: 
              k=-1;          // cast empty strings to NULL for non-string types 
            case BYTEAOID: 
            case TEXTOID: 
            case XMLOID: 
            case BPCHAROID: 
            case VARCHAROID:; 
          } 
          plugbuffer->add_int32(k); 
        } else 
          switch(dtoid[i]) { 
            case TEXTOID: 
            case BPCHAROID: 
            case VARCHAROID: { 
              if(!value) { 
                plugbuffer->add_int32(-1); 
                break; 
              } 
              value=(string)value; 
              switch(cenc) { 
                case UTF8CHARSET: 
                  value=string_to_utf8(value); 
                  break; 
                default: 
                  if(String.width(value)>8) { 
                    SUSERERROR("Don't know how to convert %O to %s encoding\n", 
                               value,cenc); 
                    value=""; 
                  } 
              } 
              plugbuffer->add_hstring(value,4); 
              break; 
            } 
            default: { 
              if(!value) { 
                plugbuffer->add_int32(-1); 
                break; 
              } 
              value=(string)value; 
              if(String.width(value)>8) 
                if(dtoid[i]==BYTEAOID) 
                  value=string_to_utf8(value); 
                else { 
                  SUSERERROR("Wide string %O not supported for type OID %d\n", 
                             value,dtoid[i]); 
                  value=""; 
                } 
              plugbuffer->add_hstring(value,4); 
              break; 
            } 
            case BOOLOID: 
              do { 
                int tval; 
                if(stringp(value)) 
                  tval=value[0]; 
                else if(!intp(value)) { 
                  value=!!value;                        // cast to boolean 
                  break; 
                } else 
                  tval=value; 
                switch(tval) { 
                  case 'o':case 'O': 
                    catch { 
                      tval=value[1]; 
                      value=tval=='n'||tval=='N'; 
                    }; 
                    break; 
                  default: 
                    value=1; 
                    break; 
                  case 0:case '0':case 'f':case 'F':case 'n':case 'N': 
                    value=0; 
                      break; 
                } 
              } while(0); 
              plugbuffer->add_int32(1)->add_int8(value); 
              break; 
            case CHAROID: 
              if(intp(value)) 
                plugbuffer->add_hstring(value,4); 
              else { 
                value=(string)value; 
                switch(sizeof(value)) { 
                  default: 
                    SUSERERROR( 
                     "\"char\" types must be 1 byte wide, got %O\n",value); 
                  case 0: 
                    plugbuffer->add_int32(-1);                  // NULL 
                    break; 
                  case 1: 
                    plugbuffer->add_hstring(value[0],4); 
                } 
              } 
              break; 
            case INT8OID: 
              plugbuffer->add_int32(8)->add_int((int)value,8); 
              break; 
            case OIDOID: 
            case INT4OID: 
              plugbuffer->add_int32(4)->add_int32((int)value); 
              break; 
            case INT2OID: 
              plugbuffer->add_int32(2)->add_int16((int)value); 
              break; 
          } 
      } 
      if(!datarowtypes) { 
        if(_tprepared && dontcacheprefix->match(_query)) 
          m_delete(pgsqlsess->_prepareds,_query),_tprepared=0; 
        waitfordescribe(); 
      } 
      if(_state>=CLOSING) 
        lock=_unnamedstatementkey=0; 
      else { 
        plugbuffer->add_int16(sizeof(datarowtypes)); 
        if(sizeof(datarowtypes)) 
          plugbuffer->add_ints(map(datarowtypes,oidformat),2); 
        else if(!paralleliseprefix->match(_query)) { 
          lock=pgsqlsess->_shortmux->lock(); 
          if(pgsqlsess->_portalsinflight) { 
            pgsqlsess->_waittocommit++; 
            PD("Commit waiting for portals to finish\n"); 
            catch(PT(pgsqlsess->_readyforcommit->wait(lock))); 
            pgsqlsess->_waittocommit--; 
          } 
        } 
        lock=0; 
        PD("Bind portal %O statement %O\n",_portalname,_preparedname); 
        _fetchlimit=pgsqlsess->_fetchlimit; 
        _openportal(); 
        conxion bindbuffer=c->start(1); 
        _unnamedstatementkey=0; 
        bindbuffer->add_int8('B')->add_hstring(plugbuffer,4,4); 
        if(!_tprepared && sizeof(_preparedname)) 
          closestatement(bindbuffer,_preparedname); 
        _sendexecute(_fetchlimit 
                             && !(cachealways[_query] 
                                  || sizeof(_query)>=MINPREPARELENGTH && 
                                  execfetchlimit->match(_query)) 
                             && _fetchlimit,bindbuffer); 
      } 
    } else 
      lock=0; 
  } 
 
  final void _processrowdesc(array(mapping(string:mixed)) datarowdesc, 
   array(int) datarowtypes) { 
    _setrowdesc(datarowdesc,datarowtypes); 
    if(_tprepared) { 
      _tprepared.datarowdesc=datarowdesc; 
      _tprepared.datarowtypes=datarowtypes; 
    } 
  } 
 
  final void _openportal() { 
    pgsqlsess->_portalsinflight++; 
    Thread.MutexKey lock=closemux->lock(); 
    _state=BOUND; 
    lock=0; 
    statuscmdcomplete=UNDEFINED; 
  } 
 
  final void _purgeportal() { 
    datarows->write(1);                            // Signal EOF 
    Thread.MutexKey lock=closemux->lock(); 
    _fetchlimit=0;                                 // disables further Executes 
    switch(_state) { 
      case COPYINPROGRESS: 
      case BOUND: 
        --pgsqlsess->_portalsinflight; 
    } 
    _state=CLOSED; 
    lock=0; 
    releaseconditions(); 
  } 
 
  final int _closeportal(bufcon plugbuffer) { 
    int retval=KEEP; 
    PD("%O Try Closeportal %d\n",_portalname,_state); 
    Thread.MutexKey lock=closemux->lock(); 
    _fetchlimit=0;                                 // disables further Executes 
    int alreadyfilled=sizeof(plugbuffer); 
    /* alreadyfilled will be non-zero if a parse request has been queued 
     * before the close was initiated. 
     * It's a bit of a tricky race, but this check should be sufficient. 
     */ 
    switch(_state) { 
      case PORTALINIT: 
        _unnamedstatementkey=0; 
        _state=CLOSING; 
        break; 
      case COPYINPROGRESS: 
        PD("CopyDone\n"); 
        plugbuffer->add("c\0\0\0\4"); 
      case BOUND: 
        _state=CLOSING; 
        lock=0; 
        PD("Close portal %O\n",_portalname); 
        if(sizeof(_portalname)) { 
          plugbuffer->add_int8('C')->add_hstring(({'P',_portalname,0}),4,4); 
          retval=FLUSHSEND; 
        } else 
          _unnamedportalkey=0; 
        Thread.MutexKey lockc=pgsqlsess->_shortmux->lock(); 
        if(!--pgsqlsess->_portalsinflight) { 
          if(pgsqlsess->_waittocommit) { 
            PD("Signal no portals in flight\n"); 
            catch(pgsqlsess->_readyforcommit->signal()); 
            lockc=0; 
          } else if(!alreadyfilled) 
            pgsqlsess->_readyforquerycount++, retval=SYNCSEND; 
          pgsqlsess->_pportalcount=0; 
        } 
        lockc=0; 
    } 
    lock=0; 
    return retval; 
  } 
 
  final void _processdataready(array datarow,void|int msglen) { 
    bytesreceived+=msglen; 
    inflight--; 
    if(_state<CLOSED) 
      datarows->write(datarow); 
    if(++rowsreceived==1) 
      PD("<%O _fetchlimit %d=min(%d||1,%d), inflight %d\n",_portalname, 
       _fetchlimit,(portalbuffersize>>1)*rowsreceived/bytesreceived, 
       pgsqlsess._fetchlimit,inflight); 
    if(_fetchlimit) { 
      _fetchlimit= 
       min((portalbuffersize>>1)*rowsreceived/bytesreceived||1, 
        pgsqlsess._fetchlimit); 
      Thread.MutexKey lock=closemux->lock(); 
      if(_fetchlimit && inflight<=(_fetchlimit-1)>>1) 
        _sendexecute(_fetchlimit); 
      else if(!_fetchlimit) 
        PD("<%O _fetchlimit %d, inflight %d, skip execute\n", 
         _portalname,_fetchlimit,inflight); 
      lock=0; 
    } 
  } 
 
  private void releaseconditions() { 
    _unnamedportalkey=_unnamedstatementkey=0; 
    pgsqlsess=0; 
    if(!datarowtypes) { 
      Thread.MutexKey lock=_ddescribemux->lock(); 
      datarowtypes=emptyarray; 
      datarowdesc=emptyarray; 
      _ddescribe->broadcast(); 
      lock=0; 
    } 
  } 
 
  final void _releasesession(void|string statusccomplete) { 
    c->closecallbacks-=(<destroy>); 
    if(statusccomplete && !statuscmdcomplete) 
      statuscmdcomplete=statusccomplete; 
    inflight=0; 
    catch { 
      conxion plugbuffer=c->start(1); 
      plugbuffer->sendcmd(_closeportal(plugbuffer)); 
    }; 
    _state=CLOSED; 
    datarows->write(1);                         // Signal EOF 
    releaseconditions(); 
  } 
 
  protected void destroy() { 
    catch {                        // inside destructors, exceptions don't work 
      _releasesession(); 
    }; 
  } 
 
  final void _sendexecute(int fetchlimit,void|bufcon plugbuffer) { 
    int flushmode; 
    PD("Execute portal %O fetchlimit %d\n",_portalname,fetchlimit); 
    if(!plugbuffer) 
      plugbuffer=c->start(1); 
    plugbuffer->add_int8('E')->add_hstring(({_portalname,0}),4,8) 
     ->add_int32(fetchlimit); 
    if(!fetchlimit) 
      flushmode=_closeportal(plugbuffer)==SYNCSEND?SYNCSEND:FLUSHSEND; 
    else 
      inflight+=fetchlimit, flushmode=FLUSHSEND; 
    plugbuffer->sendcmd(flushmode,this); 
  } 
 
  //! @returns 
  //!  One result row at a time. 
  //! 
  //! When using COPY FROM STDOUT, this method returns one row at a time 
  //! as a single string containing the entire row. 
  //! 
  //! @seealso 
  //!  @[eof()], @[send_row()] 
  /*semi*/final array(mixed) fetch_row() { 
    int|array datarow; 
    if(arrayp(datarow=datarows->try_read())) 
      return datarow; 
    if(!eoffound) { 
      if(!datarow) { 
        PD("%O Block for datarow\n",_portalname); 
        array cid=callout(gottimeout,timeout); 
        PT(datarow=datarows->read()); 
        local_backend->remove_call_out(cid); 
        if(arrayp(datarow)) 
          return datarow; 
      } 
      eoffound=1; 
      datarows->write(1);                       // Signal EOF for other threads 
    } 
    trydelayederror(); 
    return 0; 
  } 
 
  //! @returns 
  //!  Multiple result rows at a time (at least one). 
  //! 
  //! When using COPY FROM STDOUT, this method returns one row at a time 
  //! as a single string containing the entire row. 
  //! 
  //! @seealso 
  //!  @[eof()], @[fetch_row()] 
  /*semi*/final array(array(mixed)) fetch_row_array() { 
    if(eoffound) 
      return 0; 
    array(array|int) datarow=datarows->try_read_array(); 
    if(!datarow) { 
      array cid=callout(gottimeout,timeout); 
      PT(datarow=datarows->read_array()); 
      local_backend->remove_call_out(cid); 
    } 
    if(arrayp(datarow[-1])) 
      return datarow; 
    trydelayederror(); 
    eoffound=1; 
    datarows->write(1);                         // Signal EOF for other threads 
    return (datarow=datarow[..<1]); 
  } 
 
  //! @param copydata 
  //! When using COPY FROM STDIN, this method accepts a string or an 
  //! array of strings to be processed by the COPY command; when sending 
  //! the amount of data sent per call does not have to hit row or column 
  //! boundaries. 
  //! 
  //! The COPY FROM STDIN sequence needs to be completed by either 
  //! explicitly or implicitly destroying the result object, or by passing no 
  //! argument to this method. 
  //! 
  //! @seealso 
  //!  @[fetch_row()], @[eof()] 
  /*semi*/final void send_row(void|string|array(string) copydata) { 
    trydelayederror(); 
    if(copydata) { 
      PD("CopyData\n"); 
      c->start()->add_int8('d')->add_hstring(copydata,4,4)->sendcmd(SENDOUT); 
    } else 
      _releasesession(); 
  } 
 
  private void run_result_cb( 
   function(sql_result, array(mixed), mixed ...:void) callback, 
   array(mixed) args) { 
    int|array datarow; 
    for(;;) { 
      array cid=callout(gottimeout,timeout); 
      PT(datarow=datarows->read()); 
      local_backend->remove_call_out(cid); 
      if(!arrayp(datarow)) 
        break; 
      callout(callback, 0, this, datarow, @args); 
    } 
    trydelayederror(); 
    eoffound=1; 
    callout(callback, 0, this, 0, @args); 
  } 
 
  //! Sets up a callback for every row returned from the database. 
  //! First argument passed is the resultobject itself, second argument 
  //! is the result row (zero on EOF). 
  //! 
  //! @seealso 
  //!  @[fetch_row()] 
  /*semi*/final void set_result_callback( 
   function(sql_result, array(mixed), mixed ...:void) callback, 
   mixed ... args) { 
    if(callback) 
      Thread.Thread(run_result_cb,callback,args); 
  } 
 
  private void run_result_array_cb( 
   function(sql_result, array(array(mixed)), mixed ...:void) callback, 
   array(mixed) args) { 
    array(array|int) datarow; 
    for(;;) { 
      array cid=callout(gottimeout,timeout); 
      PT(datarow=datarows->read_array()); 
      local_backend->remove_call_out(cid); 
      if(!datarow || !arrayp(datarow[-1])) 
        break; 
      callout(callback, 0, this, datarow, @args); 
    } 
    trydelayederror(); 
    eoffound=1; 
    if(sizeof(datarow)>1) 
      callout(callback, 0, this, datarow=datarow[..<1], @args); 
    callout(callback, 0, this, 0, @args); 
  } 
 
  //! Sets up a callback for sets of rows returned from the database. 
  //! First argument passed is the resultobject itself, second argument 
  //! is the array of result rows (zero on EOF). 
  //! 
  //! @seealso 
  //!  @[fetch_row()] 
  /*semi*/final void set_result_array_callback( 
   function(sql_result, array(array(mixed)), mixed ...:void) callback, 
   mixed ... args) { 
    if(callback) 
      Thread.Thread(run_result_array_cb,callback,args); 
  } 
 
};