-
-
Notifications
You must be signed in to change notification settings - Fork 506
/
sphinxsort.cpp
1218 lines (1019 loc) · 32.4 KB
/
sphinxsort.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
//
// Copyright (c) 2017-2024, Manticore Software LTD (https://manticoresearch.com)
// Copyright (c) 2001-2016, Andrew Aksyonoff
// Copyright (c) 2008-2016, Sphinx Technologies Inc
// All rights reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
#include "sphinxsort.h"
#include "sortcomp.h"
#include "aggregate.h"
#include "distinct.h"
#include "netreceive_ql.h"
#include "queuecreator.h"
#include "sortertraits.h"
#include "sortergroup.h"
#include "grouper.h"
#include "knnmisc.h"
#include "joinsorter.h"
#include "querycontext.h"
#include <ctime>
#if !_WIN32
#include <unistd.h>
#include <sys/time.h>
#endif
static bool g_bAccurateAggregation = false;
static int g_iDistinctThresh = 3500;
void SetAccurateAggregationDefault ( bool bEnabled )
{
g_bAccurateAggregation = bEnabled;
}
bool GetAccurateAggregationDefault()
{
return g_bAccurateAggregation;
}
void SetDistinctThreshDefault ( int iThresh )
{
g_iDistinctThresh = iThresh;
}
int GetDistinctThreshDefault()
{
return g_iDistinctThresh;
}
//////////////////////////////////////////////////////////////////////////
// SORTING QUEUES
//////////////////////////////////////////////////////////////////////////
template < typename COMP >
struct InvCompareIndex_fn
{
const VecTraits_T<CSphMatch>& m_dBase;
const CSphMatchComparatorState & m_tState;
explicit InvCompareIndex_fn ( const CSphMatchQueueTraits & tBase )
: m_dBase ( tBase.GetMatches() )
, m_tState ( tBase.GetState() )
{}
bool IsLess ( int a, int b ) const // inverts COMP::IsLess
{
return COMP::IsLess ( m_dBase[b], m_dBase[a], m_tState );
}
};
#define LOG_COMPONENT_KMQ __LINE__ << " *(" << this << ") "
#define LOG_LEVEL_DIAG false
#define KMQ LOC(DIAG,KMQ)
/// heap sorter
/// plain binary heap based PQ
template < typename COMP, bool NOTIFICATIONS >
class CSphMatchQueue final : public CSphMatchQueueTraits
{
using MYTYPE = CSphMatchQueue<COMP, NOTIFICATIONS>;
LOC_ADD;
public:
/// ctor
explicit CSphMatchQueue ( int iSize )
: CSphMatchQueueTraits ( iSize )
, m_fnComp ( *this )
{
if constexpr ( NOTIFICATIONS )
m_dJustPopped.Reserve(1);
}
bool IsGroupby () const final { return false; }
const CSphMatch * GetWorst() const final { return m_dIData.IsEmpty() ? nullptr : Root(); }
bool Push ( const CSphMatch & tEntry ) final { return PushT ( tEntry, [this] ( CSphMatch & tTrg, const CSphMatch & tMatch ) { m_pSchema->CloneMatch ( tTrg, tMatch ); }); }
void Push ( const VecTraits_T<const CSphMatch> & dMatches ) final
{
for ( auto & i : dMatches )
if ( i.m_tRowID!=INVALID_ROWID )
PushT ( i, [this] ( CSphMatch & tTrg, const CSphMatch & tMatch ) { m_pSchema->CloneMatch ( tTrg, tMatch ); } );
else
m_iTotal++;
}
bool PushGrouped ( const CSphMatch &, bool ) final { assert(0); return false; }
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch * pTo ) final
{
KMQ << "flatten";
assert ( !IsEmpty() );
int iReadyMatches = Used();
pTo += iReadyMatches;
while ( !IsEmpty() )
{
--pTo;
m_pSchema->FreeDataPtrs(*pTo);
pTo->ResetDynamic();
PopAndProcess_T ( [pTo] ( CSphMatch & tRoot )
{
Swap ( *pTo, tRoot );
return true;
}
);
}
m_iTotal = 0;
return iReadyMatches;
}
/// finalize, perform final sort/cut as needed
void Finalize ( MatchProcessor_i & tProcessor, bool bCallProcessInResultSetOrder, bool bFinalizeMatches ) final
{
KMQ << "finalize";
if ( !GetLength() )
return;
if ( bCallProcessInResultSetOrder )
m_dIData.Sort ( m_fnComp );
if ( tProcessor.ProcessInRowIdOrder() )
{
CSphFixedVector<int> dSorted ( m_dIData.GetLength() );
memcpy ( dSorted.Begin(), m_dIData.Begin(), m_dIData.GetLength()*sizeof(m_dIData[0]) );
// sort by tag, rowid. minimize columnar switches inside expressions and minimize seeks inside columnar iterators
dSorted.Sort ( Lesser ( [this] ( int l, int r )
{
int iTagL = m_dData[l].m_iTag;
int iTagR = m_dData[r].m_iTag;
if ( iTagL!=iTagR )
return iTagL < iTagR;
return m_dData[l].m_tRowID < m_dData[r].m_tRowID;
}
) );
CSphFixedVector<CSphMatch *> dMatchPtrs ( dSorted.GetLength() );
ARRAY_FOREACH ( i, dSorted )
dMatchPtrs[i] = &m_dData[dSorted[i]];
tProcessor.Process(dMatchPtrs);
}
else
{
for ( auto iMatch : m_dIData )
tProcessor.Process ( &m_dData[iMatch] );
}
}
// fixme! test
ISphMatchSorter * Clone () const final
{
auto pClone = new MYTYPE ( m_iSize );
CloneTo ( pClone );
return pClone;
}
// FIXME! test CSphMatchQueue
void MoveTo ( ISphMatchSorter * pRhs, bool bCopyMeta ) final
{
KMQ << "moveto";
// m_dLogger.Print ();
auto& dRhs = *(MYTYPE *) pRhs;
if ( IsEmpty() )
return; // no matches, nothing to do.
// dRhs.m_dLogger.Print ();
// install into virgin sorter - no need to do something; just swap
if ( dRhs.IsEmpty() )
{
SwapMatchQueueTraits ( dRhs );
return;
}
// work as in non-ordered finalize call, but we not need to
// clone the matches, may just move them instead.
// total need special care: just add two values and don't rely
// on result of moving, since it will be wrong
auto iTotal = dRhs.m_iTotal;
for ( auto i : m_dIData )
dRhs.PushT ( m_dData[i], [] ( CSphMatch & tTrg, CSphMatch & tMatch ) { Swap ( tTrg, tMatch ); } );
dRhs.m_iTotal = m_iTotal + iTotal;
}
void SetMerge ( bool bMerge ) final {}
private:
InvCompareIndex_fn<COMP> m_fnComp;
CSphMatch * Root() const
{
return &m_dData [ m_dIData.First() ];
}
/// generic add entry to the queue
template <typename MATCH, typename PUSHER>
bool PushT ( MATCH && tEntry, PUSHER && PUSH )
{
++m_iTotal;
if constexpr ( NOTIFICATIONS )
{
m_tJustPushed = RowTagged_t();
m_dJustPopped.Resize(0);
}
if ( Used()==m_iSize )
{
// if it's worse that current min, reject it, else pop off current min
if ( COMP::IsLess ( tEntry, *Root(), m_tState ) )
return true;
else
PopAndProcess_T ( [] ( const CSphMatch & ) { return false; } );
}
// do add
PUSH ( Add(), std::forward<MATCH> ( tEntry ));
if constexpr ( NOTIFICATIONS )
m_tJustPushed = RowTagged_t ( *Last() );
int iEntry = Used()-1;
// shift up if needed, so that worst (lesser) ones float to the top
while ( iEntry )
{
int iParent = ( iEntry-1 ) / 2;
if ( !m_fnComp.IsLess ( m_dIData[iParent], m_dIData[iEntry] ) )
break;
// entry is less than parent, should float to the top
Swap ( m_dIData[iEntry], m_dIData[iParent] );
iEntry = iParent;
}
return true;
}
/// remove root (ie. top priority) entry
template<typename POPPER>
void PopAndProcess_T ( POPPER && fnProcess )
{
assert ( !IsEmpty() );
auto& iJustRemoved = m_dIData.Pop();
if ( !IsEmpty() ) // for empty just popped is the root
Swap ( m_dIData.First (), iJustRemoved );
if ( !fnProcess ( m_dData[iJustRemoved] ) )
{
// make the last entry my new root
if constexpr ( NOTIFICATIONS )
{
if ( m_dJustPopped.IsEmpty () )
m_dJustPopped.Add ( RowTagged_t ( m_dData[iJustRemoved] ) );
else
m_dJustPopped[0] = RowTagged_t ( m_dData[iJustRemoved] );
}
}
// sift down if needed
int iEntry = 0;
auto iUsed = Used();
while (true)
{
// select child
int iChild = (iEntry*2) + 1;
if ( iChild>=iUsed )
break;
// select smallest child
if ( iChild+1<iUsed )
if ( m_fnComp.IsLess ( m_dIData[iChild], m_dIData[iChild+1] ) )
++iChild;
// if smallest child is less than entry, do float it to the top
if ( m_fnComp.IsLess ( m_dIData[iEntry], m_dIData[iChild] ) )
{
Swap ( m_dIData[iChild], m_dIData[iEntry] );
iEntry = iChild;
continue;
}
break;
}
}
};
#define LOG_COMPONENT_KBF __LINE__ << " *(" << this << ") "
#define KBF LOC(DIAG,KBF)
//////////////////////////////////////////////////////////////////////////
/// K-buffer (generalized double buffer) sorter
/// faster worst-case but slower average-case than the heap sorter
/// invoked with select ... OPTION sort_method=kbuffer
template < typename COMP, bool NOTIFICATIONS >
class CSphKbufferMatchQueue : public CSphMatchQueueTraits
{
using MYTYPE = CSphKbufferMatchQueue<COMP, NOTIFICATIONS>;
InvCompareIndex_fn<COMP> m_dComp;
LOC_ADD;
public:
/// ctor
explicit CSphKbufferMatchQueue ( int iSize )
: CSphMatchQueueTraits ( iSize*COEFF )
, m_dComp ( *this )
{
m_iSize /= COEFF;
if constexpr ( NOTIFICATIONS )
m_dJustPopped.Reserve ( m_iSize*(COEFF-1) );
}
bool IsGroupby () const final { return false; }
int GetLength () final { return Min ( Used(), m_iSize ); }
bool Push ( const CSphMatch & tEntry ) override { return PushT ( tEntry, [this] ( CSphMatch & tTrg, const CSphMatch & tMatch ) { m_pSchema->CloneMatch ( tTrg, tMatch ); }); }
void Push ( const VecTraits_T<const CSphMatch> & dMatches ) override
{
for ( const auto & i : dMatches )
if ( i.m_tRowID!=INVALID_ROWID )
PushT ( i, [this] ( CSphMatch & tTrg, const CSphMatch & tMatch ) { m_pSchema->CloneMatch ( tTrg, tMatch ); } );
else
m_iTotal++;
}
bool PushGrouped ( const CSphMatch &, bool ) final { assert(0); return false; }
/// store all entries into specified location in sorted order, and remove them from queue
int Flatten ( CSphMatch * pTo ) final
{
KBF << "Flatten";
FinalizeMatches ();
auto iReadyMatches = Used();
for ( auto iMatch : m_dIData )
{
KBF << "fltn " << m_dData[iMatch].m_iTag << ":" << m_dData[iMatch].m_tRowID;
Swap ( *pTo, m_dData[iMatch] );
++pTo;
}
m_iMaxUsed = ResetDynamic ( m_iMaxUsed );
// clean up for the next work session
m_pWorst = nullptr;
m_iTotal = 0;
m_bFinalized = false;
m_dIData.Resize(0);
return iReadyMatches;
}
/// finalize, perform final sort/cut as needed
void Finalize ( MatchProcessor_i & tProcessor, bool, bool bFinalizeMatches ) final
{
KBF << "Finalize";
if ( IsEmpty() )
return;
if ( bFinalizeMatches )
FinalizeMatches();
for ( auto iMatch : m_dIData )
tProcessor.Process ( &m_dData[iMatch] );
}
ISphMatchSorter* Clone() const final
{
auto pClone = new MYTYPE ( m_iSize );
CloneTo ( pClone );
return pClone;
}
// FIXME! test CSphKbufferMatchQueue
// FIXME! need to deal with justpushed/justpopped any other way!
void MoveTo ( ISphMatchSorter * pRhs, bool bCopyMeta ) final
{
auto& dRhs = *(CSphKbufferMatchQueue<COMP, NOTIFICATIONS>*) pRhs;
if ( IsEmpty () )
return;
if ( dRhs.IsEmpty () )
{
SwapMatchQueueTraits (dRhs);
dRhs.m_pWorst = m_pWorst;
dRhs.m_bFinalized = m_bFinalized;
return;
}
FinalizeMatches();
// both are non-empty - need to process.
// work as finalize call, but don't clone the matches; move them instead.
// total need special care!
auto iTotal = dRhs.m_iTotal;
for ( auto iMatch : m_dIData )
{
dRhs.PushT ( m_dData[iMatch],
[] ( CSphMatch & tTrg, CSphMatch & tMatch ) {
Swap ( tTrg, tMatch );
});
}
dRhs.m_iTotal = m_iTotal + iTotal;
}
void SetMerge ( bool bMerge ) final {}
protected:
CSphMatch * m_pWorst = nullptr;
bool m_bFinalized = false;
int m_iMaxUsed = -1;
static const int COEFF = 4;
private:
void SortMatches () // sort from best to worst
{
m_dIData.Sort ( m_dComp );
}
void FreeMatch ( int iMatch )
{
if constexpr ( NOTIFICATIONS )
m_dJustPopped.Add ( RowTagged_t ( m_dData[iMatch] ) );
m_pSchema->FreeDataPtrs ( m_dData[iMatch] );
}
void CutTail()
{
if ( Used()<=m_iSize)
return;
m_iMaxUsed = Max ( m_iMaxUsed, this->m_dIData.GetLength () ); // memorize it for free dynamics later.
m_dIData.Slice ( m_iSize ).Apply ( [this] ( int iMatch ) { FreeMatch ( iMatch ); } );
m_dIData.Resize ( m_iSize );
}
// conception: we have array of N*COEFF elems.
// We need only N the best elements from it (rest have to be disposed).
// direct way: rsort, then take first N elems.
// this way: rearrange array by performing one pass of quick sort
// if we have exactly N elems left hand from pivot - we're done.
// otherwise repeat rearranging only to right or left part until the target achieved.
void BinaryPartition ()
{
int iPivot = m_dIData[m_iSize / COEFF+1];
int iMaxIndex = m_iSize-1;
int a=0;
int b=Used()-1;
while (true)
{
int i=a;
int j=b;
while (i<=j)
{
while (m_dComp.IsLess (m_dIData[i],iPivot)) ++i;
while (m_dComp.IsLess (iPivot, m_dIData[j])) --j;
if ( i<=j ) ::Swap( m_dIData[i++], m_dIData[j--]);
}
if ( iMaxIndex == j )
break;
if ( iMaxIndex < j)
b = j; // too many elems acquired; continue with left part
else
a = i; // too less elems acquired; continue with right part
iPivot = m_dIData[( a * ( COEFF-1 )+b ) / COEFF];
}
}
void RepartitionMatches ()
{
assert ( Used ()>m_iSize );
BinaryPartition ();
CutTail();
}
void FinalizeMatches ()
{
if ( m_bFinalized )
return;
m_bFinalized = true;
if ( Used ()>m_iSize )
RepartitionMatches();
SortMatches();
}
// generic push entry (add it some way to the queue clone or swap PUSHER depends on)
template<typename MATCH, typename PUSHER>
FORCE_INLINE bool PushT ( MATCH && tEntry, PUSHER && PUSH )
{
if constexpr ( NOTIFICATIONS )
{
m_tJustPushed = RowTagged_t();
m_dJustPopped.Resize(0);
}
// quick early rejection checks
++m_iTotal;
if ( m_pWorst && COMP::IsLess ( tEntry, *m_pWorst, m_tState ) )
return true;
// quick check passed
// fill the data, back to front
m_bFinalized = false;
PUSH ( Add(), std::forward<MATCH> ( tEntry ));
if constexpr ( NOTIFICATIONS )
m_tJustPushed = RowTagged_t ( *Last() );
// do the initial sort once
if ( m_iTotal==m_iSize )
{
assert ( Used()==m_iSize && !m_pWorst );
SortMatches();
m_pWorst = Last();
m_bFinalized = true;
return true;
}
if ( Used ()<m_iSize*COEFF )
return true;
// do the sort/cut when the K-buffer is full
assert ( Used ()==m_iSize*COEFF );
RepartitionMatches();
SortMatches ();
m_pWorst = Last ();
m_bFinalized = true;
return true;
}
};
//////////////////////////////////////////////////////////////////////////
/// collect list of matched DOCIDs in aside compressed blob
/// (mainly used to collect docs in `DELETE... WHERE` statement)
class CollectQueue_c final : public MatchSorter_c, ISphNoncopyable
{
using BASE = MatchSorter_c;
public:
CollectQueue_c ( int iSize, CSphVector<BYTE>& dCollectedValues );
bool IsGroupby () const final { return false; }
int GetLength () final { return 0; } // that ensures, flatten() will never called;
bool Push ( const CSphMatch& tEntry ) final { return PushMatch(tEntry); }
void Push ( const VecTraits_T<const CSphMatch> & dMatches ) final
{
for ( const auto & i : dMatches )
if ( i.m_tRowID!=INVALID_ROWID )
PushMatch(i);
}
bool PushGrouped ( const CSphMatch &, bool ) final { assert(0); return false; }
int Flatten ( CSphMatch * ) final { return 0; }
void Finalize ( MatchProcessor_i &, bool, bool ) final;
bool CanBeCloned() const final { return false; }
ISphMatchSorter * Clone () const final { return nullptr; }
void MoveTo ( ISphMatchSorter *, bool ) final {}
void SetSchema ( ISphSchema * pSchema, bool bRemapCmp ) final;
bool IsCutoffDisabled() const final { return true; }
void SetMerge ( bool bMerge ) final {}
private:
DocID_t m_iLastID;
int m_iMaxMatches;
CSphVector<DocID_t> m_dUnsortedDocs;
MemoryWriter_c m_tWriter;
bool m_bDocIdDynamic = false;
inline bool PushMatch ( const CSphMatch & tEntry );
inline void ProcessPushed();
};
CollectQueue_c::CollectQueue_c ( int iSize, CSphVector<BYTE>& dCollectedValues )
: m_iLastID ( 0 )
, m_iMaxMatches ( iSize )
, m_tWriter ( dCollectedValues )
{}
/// sort/uniq already collected and store them to writer
void CollectQueue_c::ProcessPushed()
{
m_dUnsortedDocs.Uniq();
for ( auto& iCurId : m_dUnsortedDocs )
m_tWriter.ZipOffset ( iCurId - std::exchange ( m_iLastID, iCurId ) );
m_dUnsortedDocs.Resize ( 0 );
}
bool CollectQueue_c::PushMatch ( const CSphMatch & tEntry )
{
if ( m_dUnsortedDocs.GetLength() >= m_iMaxMatches && m_dUnsortedDocs.GetLength() == m_dUnsortedDocs.GetLimit() )
ProcessPushed();
m_dUnsortedDocs.Add ( sphGetDocID ( m_bDocIdDynamic ? tEntry.m_pDynamic : tEntry.m_pStatic ) );
return true;
}
/// final update pass
void CollectQueue_c::Finalize ( MatchProcessor_i&, bool, bool )
{
ProcessPushed();
m_iLastID = 0;
}
void CollectQueue_c::SetSchema ( ISphSchema * pSchema, bool bRemapCmp )
{
BASE::SetSchema ( pSchema, bRemapCmp );
const CSphColumnInfo * pDocId = pSchema->GetAttr ( sphGetDocidName() );
assert(pDocId);
m_bDocIdDynamic = pDocId->m_tLocator.m_bDynamic;
}
ISphMatchSorter * CreateCollectQueue ( int iMaxMatches, CSphVector<BYTE> & tCollection )
{
return new CollectQueue_c ( iMaxMatches, tCollection );
}
//////////////////////////////////////////////////////////////////////////
void SendSqlSchema ( const ISphSchema& tSchema, RowBuffer_i* pRows, const VecTraits_T<int>& dOrder )
{
pRows->HeadBegin ();
ARRAY_CONSTFOREACH ( i, dOrder )
{
const CSphColumnInfo& tCol = tSchema.GetAttr ( dOrder[i] );
if ( sphIsInternalAttr ( tCol ) )
continue;
if ( i == 0 )
{
assert (tCol.m_sName == "id");
pRows->HeadColumn ( "id", ESphAttr2MysqlColumnStreamed ( SPH_ATTR_UINT64 ) );
continue;
}
if ( tCol.m_eAttrType==SPH_ATTR_TOKENCOUNT )
continue;
pRows->HeadColumn ( tCol.m_sName.cstr(), ESphAttr2MysqlColumnStreamed ( tCol.m_eAttrType ) );
}
pRows->HeadEnd ( false, 0 );
}
using SqlEscapedBuilder_c = EscapedStringBuilder_T<BaseQuotation_T<SqlQuotator_t>>;
void SendSqlMatch ( const ISphSchema& tSchema, RowBuffer_i* pRows, CSphMatch& tMatch, const BYTE* pBlobPool, const VecTraits_T<int>& dOrder, bool bDynamicDocid )
{
auto& dRows = *pRows;
ARRAY_CONSTFOREACH ( i, dOrder )
{
const CSphColumnInfo& dAttr = tSchema.GetAttr ( dOrder[i] );
if ( sphIsInternalAttr ( dAttr ) )
continue;
if ( dAttr.m_eAttrType==SPH_ATTR_TOKENCOUNT )
continue;
CSphAttrLocator tLoc = dAttr.m_tLocator;
ESphAttr eAttrType = dAttr.m_eAttrType;
if ( i == 0 )
eAttrType = SPH_ATTR_UINT64;
switch ( eAttrType )
{
case SPH_ATTR_STRING:
dRows.PutArray ( sphGetBlobAttr ( tMatch, tLoc, pBlobPool ) );
break;
case SPH_ATTR_STRINGPTR:
{
const BYTE* pStr = nullptr;
if ( dAttr.m_eStage == SPH_EVAL_POSTLIMIT )
{
if ( bDynamicDocid )
{
dAttr.m_pExpr->StringEval ( tMatch, &pStr );
} else
{
auto pDynamic = tMatch.m_pDynamic;
if ( tMatch.m_pStatic )
tMatch.m_pDynamic = nullptr;
dAttr.m_pExpr->StringEval ( tMatch, &pStr );
tMatch.m_pDynamic = pDynamic;
}
dRows.PutString ( (const char*)pStr );
SafeDeleteArray ( pStr );
} else {
pStr = (const BYTE*)tMatch.GetAttr ( tLoc );
auto dString = sphUnpackPtrAttr ( pStr );
dRows.PutArray ( dString );
}
}
break;
case SPH_ATTR_INTEGER:
case SPH_ATTR_TIMESTAMP:
case SPH_ATTR_BOOL:
dRows.PutNumAsString ( (DWORD)tMatch.GetAttr ( tLoc ) );
break;
case SPH_ATTR_BIGINT:
dRows.PutNumAsString ( tMatch.GetAttr ( tLoc ) );
break;
case SPH_ATTR_UINT64:
dRows.PutNumAsString ( (uint64_t)tMatch.GetAttr ( tLoc ) );
break;
case SPH_ATTR_FLOAT:
dRows.PutFloatAsString ( tMatch.GetAttrFloat ( tLoc ) );
break;
case SPH_ATTR_DOUBLE:
dRows.PutDoubleAsString ( tMatch.GetAttrDouble ( tLoc ) );
break;
case SPH_ATTR_INT64SET:
case SPH_ATTR_UINT32SET:
{
StringBuilder_c dStr;
auto dMVA = sphGetBlobAttr ( tMatch, tLoc, pBlobPool );
dStr << "(";
sphMVA2Str ( dMVA, eAttrType == SPH_ATTR_INT64SET, dStr );
dStr << ")";
dRows.PutArray ( dStr, false );
break;
}
case SPH_ATTR_INT64SET_PTR:
case SPH_ATTR_UINT32SET_PTR:
{
StringBuilder_c dStr;
dStr << "(";
sphPackedMVA2Str ( (const BYTE*)tMatch.GetAttr ( tLoc ), eAttrType == SPH_ATTR_INT64SET_PTR, dStr );
dStr << ")";
dRows.PutArray ( dStr, false );
break;
}
case SPH_ATTR_FLOAT_VECTOR:
{
StringBuilder_c dStr;
auto dFloatVec = sphGetBlobAttr ( tMatch, tLoc, pBlobPool );
dStr << "(";
sphFloatVec2Str ( dFloatVec, dStr );
dStr << ")";
dRows.PutArray ( dStr, false );
}
break;
case SPH_ATTR_FLOAT_VECTOR_PTR:
{
StringBuilder_c dStr;
dStr << "(";
sphPackedFloatVec2Str ( (const BYTE*)tMatch.GetAttr(tLoc), dStr );
dStr << ")";
dRows.PutArray ( dStr, false );
}
break;
case SPH_ATTR_JSON:
{
auto pJson = sphGetBlobAttr ( tMatch, tLoc, pBlobPool );
JsonEscapedBuilder sTmp;
if ( pJson.second )
sphJsonFormat ( sTmp, pJson.first );
auto sJson = Str_t(sTmp);
SqlEscapedBuilder_c dEscaped;
dEscaped.FixupSpacedAndAppendEscapedNoQuotes ( sJson.first, sJson.second );
dRows.PutArray ( dEscaped, false );
}
break;
case SPH_ATTR_JSON_PTR:
{
auto* pString = (const BYTE*)tMatch.GetAttr ( tLoc );
JsonEscapedBuilder sTmp;
if ( pString )
{
auto dJson = sphUnpackPtrAttr ( pString );
sphJsonFormat ( sTmp, dJson.first );
}
auto sJson = Str_t ( sTmp );
SqlEscapedBuilder_c dEscaped;
dEscaped.FixupSpacedAndAppendEscapedNoQuotes ( sJson.first, sJson.second );
dRows.PutArray ( dEscaped, false );
}
break;
case SPH_ATTR_FACTORS:
case SPH_ATTR_FACTORS_JSON:
case SPH_ATTR_JSON_FIELD:
case SPH_ATTR_JSON_FIELD_PTR:
assert ( false ); // index schema never contain such column
break;
default:
dRows.Add ( 1 );
dRows.Add ( '-' );
break;
}
}
if ( !dRows.Commit() )
session::SetKilled ( true );
}
/// stream out matches
class DirectSqlQueue_c final : public MatchSorter_c, ISphNoncopyable
{
using BASE = MatchSorter_c;
public:
DirectSqlQueue_c ( RowBuffer_i * pOutput, void ** ppOpaque1, void ** ppOpaque2, StrVec_t dColumns );
~DirectSqlQueue_c() override;
bool IsGroupby () const final { return false; }
int GetLength () final { return 0; } // that ensures, flatten() will never called;
bool Push ( const CSphMatch& tEntry ) final { return PushMatch(const_cast<CSphMatch&>(tEntry)); }
void Push ( const VecTraits_T<const CSphMatch> & dMatches ) final
{
for ( const auto & i : dMatches )
if ( i.m_tRowID!=INVALID_ROWID )
PushMatch(const_cast<CSphMatch&>(i));
}
bool PushGrouped ( const CSphMatch &, bool ) final { assert(0); return false; }
int Flatten ( CSphMatch * ) final { return 0; }
void Finalize ( MatchProcessor_i &, bool, bool ) final;
bool CanBeCloned() const final { return false; }
ISphMatchSorter * Clone () const final { return nullptr; }
void MoveTo ( ISphMatchSorter *, bool ) final {}
void SetSchema ( ISphSchema * pSchema, bool bRemapCmp ) final;
bool IsCutoffDisabled() const final { return true; }
void SetMerge ( bool bMerge ) final {}
void SetBlobPool ( const BYTE* pBlobPool ) final
{
m_pBlobPool = pBlobPool;
MakeCtx();
}
void SetColumnar ( columnar::Columnar_i* pColumnar ) final
{
m_pColumnar = pColumnar;
MakeCtx();
}
private:
bool m_bSchemaSent = false;
int64_t m_iDocs = 0;
RowBuffer_i* m_pOutput;
const BYTE* m_pBlobPool = nullptr;
columnar::Columnar_i* m_pColumnar = nullptr;
CSphVector<ISphExpr*> m_dDocstores;
CSphVector<ISphExpr*> m_dFinals;
void ** m_ppOpaque1 = nullptr;
void ** m_ppOpaque2 = nullptr;
void * m_pCurDocstore = nullptr;
void * m_pCurDocstoreReader = nullptr;
CSphQuery m_dFake;
CSphQueryContext m_dCtx;
StrVec_t m_dColumns;
CSphVector<int> m_dOrder;
bool m_bDynamicDocid;
bool m_bNotYetFinalized = true;
inline bool PushMatch ( CSphMatch & tEntry );
void SendSchemaOnce();
void FinalizeOnce();
void MakeCtx();
};
DirectSqlQueue_c::DirectSqlQueue_c ( RowBuffer_i * pOutput, void ** ppOpaque1, void ** ppOpaque2, StrVec_t dColumns )
: m_pOutput ( pOutput )
, m_ppOpaque1 ( ppOpaque1 )
, m_ppOpaque2 ( ppOpaque2 )
, m_dCtx (m_dFake)
, m_dColumns ( std::move ( dColumns ) )
{}
DirectSqlQueue_c::~DirectSqlQueue_c()
{
FinalizeOnce();
}
void DirectSqlQueue_c::SendSchemaOnce()
{
if ( m_bSchemaSent )
return;
assert ( !m_iDocs );
for ( const auto& sColumn : m_dColumns )
{
auto iIdx = m_pSchema->GetAttrIndex ( sColumn.cstr() );
if ( iIdx >= 0 )
m_dOrder.Add ( iIdx );
}
for ( int i = 0; i < m_pSchema->GetAttrsCount(); ++i )
{
auto& tCol = const_cast< CSphColumnInfo &>(m_pSchema->GetAttr ( i ));
if ( tCol.m_sName == sphGetDocidName() )
m_bDynamicDocid = tCol.m_tLocator.m_bDynamic;
if ( !tCol.m_pExpr )
continue;
switch ( tCol.m_eStage )
{
case SPH_EVAL_FINAL : m_dFinals.Add ( tCol.m_pExpr ); break;
case SPH_EVAL_POSTLIMIT: m_dDocstores.Add ( tCol.m_pExpr ); break;
default:
sphWarning ("Unknown stage in SendSchema(): %d", tCol.m_eStage);
}
}
SendSqlSchema ( *m_pSchema, m_pOutput, m_dOrder );
m_bSchemaSent = true;
}
void DirectSqlQueue_c::MakeCtx()
{
CSphQueryResultMeta tFakeMeta;
CSphVector<const ISphSchema*> tFakeSchemas;
m_dCtx.SetupCalc ( tFakeMeta, *m_pSchema, *m_pSchema, m_pBlobPool, m_pColumnar, tFakeSchemas );
}
bool DirectSqlQueue_c::PushMatch ( CSphMatch & tEntry )
{
SendSchemaOnce();
++m_iDocs;
if ( m_ppOpaque1 )
{
auto pDocstoreReader = *m_ppOpaque1;
if ( pDocstoreReader!=std::exchange (m_pCurDocstore, pDocstoreReader) && pDocstoreReader )
{
DocstoreSession_c::InfoDocID_t tSessionInfo;
tSessionInfo.m_pDocstore = (const DocstoreReader_i *)pDocstoreReader;
tSessionInfo.m_iSessionId = -1;
// value is copied; no leak of pointer to local here.
m_dDocstores.for_each ( [&tSessionInfo] ( ISphExpr* pExpr ) { pExpr->Command ( SPH_EXPR_SET_DOCSTORE_DOCID, &tSessionInfo ); } );
}
}
if ( m_ppOpaque2 )
{
auto pDocstore = *m_ppOpaque2;
if ( pDocstore != std::exchange ( m_pCurDocstoreReader, pDocstore ) && pDocstore )
{
DocstoreSession_c::InfoRowID_t tSessionInfo;
tSessionInfo.m_pDocstore = (Docstore_i*)pDocstore;
tSessionInfo.m_iSessionId = -1;