-
-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathjoinsorter.cpp
More file actions
2808 lines (2226 loc) · 86.7 KB
/
joinsorter.cpp
File metadata and controls
2808 lines (2226 loc) · 86.7 KB
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) 2024-2026, Manticore Software LTD (https://manticoresearch.com)
// 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 "joinsorter.h"
#include "std/hash.h"
#include "std/openhash.h"
#include "sphinxquery/sphinxquery.h"
#include "sphinxsort.h"
#include "sphinxjson.h"
#include "querycontext.h"
#include "docstore.h"
static int64_t g_iJoinCacheSize = 20971520;
static int g_iJoinBatchSize = 1000;
void SetJoinCacheSize ( int64_t iSize )
{
g_iJoinCacheSize = iSize;
}
int64_t GetJoinCacheSize()
{
return g_iJoinCacheSize;
}
void SetJoinBatchSize ( int iSize )
{
g_iJoinBatchSize = iSize;
}
int GetJoinBatchSize()
{
return g_iJoinBatchSize;
}
bool ExprHasLeftTableAttrs ( const CSphString & sAttr, const ISphSchema & tLeftSchema )
{
const char * szAttr = sAttr.cstr();
const int MAX_ATTR_NAME_LEN = 512;
char dAttrName[MAX_ATTR_NAME_LEN+1];
int iPos = 0;
while ( *szAttr )
{
if ( sphIsAlphaOnly(*szAttr) || *szAttr=='.' || *szAttr=='_' )
{
if ( iPos==MAX_ATTR_NAME_LEN-1 )
break;
dAttrName[iPos++] = *szAttr;
}
else
{
if (iPos)
{
dAttrName[iPos] = '\0';
if ( !strchr ( dAttrName, '.' ) && tLeftSchema.GetAttrIndex(dAttrName)!=-1 )
return true;
iPos = 0;
}
}
szAttr++;
}
if (iPos)
{
dAttrName[iPos] = '\0';
if ( !strchr ( dAttrName, '.' ) && tLeftSchema.GetAttrIndex(dAttrName)!=-1 )
return true;
}
return false;
}
static bool GetJoinAttrName ( const CSphString & sAttr, const CSphString & sJoinedIndex, const ISphSchema & tLeftSchema, CSphString * pModified = nullptr )
{
CSphString sPrefix;
sPrefix.SetSprintf ( "%s.", sJoinedIndex.cstr() );
int iPrefixLen = sPrefix.Length();
if ( ExprHasLeftTableAttrs ( sAttr, tLeftSchema ) )
return false;
bool bRightTable = false;
CSphString sMod = sAttr;
const char * szStart = sMod.cstr();
while ( true )
{
const char * szFound = strstr ( sMod.cstr(), sPrefix.cstr() );
if ( !szFound )
break;
if ( szFound > szStart )
{
char c = *(szFound-1);
if ( ( c>='0' && c<='9' ) || ( c>='a' && c<='z' ) || ( c>='A' && c<='Z' ) || c=='_' )
continue;
}
bRightTable = true;
int iStart = szFound-sMod.cstr();
CSphString sNewExprPre = iStart > 0 ? sMod.SubString ( 0, iStart ) : "";
int iPostLen = sMod.Length()-iStart-iPrefixLen;
CSphString sNewExprPost = iPostLen > 0 ? sMod.SubString ( iStart + iPrefixLen, sMod.Length()-iStart-iPrefixLen ) : "";
sMod.SetSprintf ( "%s%s", sNewExprPre.cstr(), sNewExprPost.cstr() );
}
if ( bRightTable )
{
if ( pModified )
*pModified = sMod;
return true;
}
return false;
}
bool SplitJoinedAttrName ( const CSphString & sJoinedAttr, CSphString & sTable, CSphString & sAttr, CSphString * pError )
{
StrVec_t dAttr = sphSplit ( sJoinedAttr.cstr(), "." );
if ( dAttr.GetLength()<2 )
{
if ( pError )
pError->SetSprintf ( "table not specified in JOIN ON clause: '%s'", sJoinedAttr.cstr() );
return false;
}
sTable = dAttr[0];
sAttr = Vec2Str ( dAttr.Slice ( 1, dAttr.GetLength()-1 ), "." );
if ( !sAttr.Length() )
{
if ( pError )
pError->SetSprintf ( "table not specified in JOIN ON clause: '%s'", sJoinedAttr.cstr() );
return false;
}
return true;
}
static StrVec_t ParseGroupBy ( const CSphString & sGroupBy )
{
StrVec_t dRes;
sphSplit ( dRes, sGroupBy.cstr(), ", \t\n" );
return dRes;
}
static const char * GetBatchedItemPrefix()
{
return "@batched_join_";
}
CSphVector<std::pair<int,bool>> FetchJoinRightTableFilters ( const CSphVector<CSphFilterSettings> & dFilters, const ISphSchema & tSchema, const char * szJoinedIndex )
{
CSphString sPrefix;
sPrefix.SetSprintf ( "%s.", szJoinedIndex );
CSphVector<std::pair<int,bool>> dRightFilters;
ARRAY_FOREACH ( i, dFilters )
{
const auto & tFilter = dFilters[i];
bool bHasPrefix = tFilter.m_sAttrName.Begins ( sPrefix.cstr() );
const CSphColumnInfo * pFilterAttr = tSchema.GetAttr ( tFilter.m_sAttrName.cstr() );
if ( pFilterAttr )
{
if ( !pFilterAttr->IsJoined() )
continue;
}
else
{
if ( !bHasPrefix )
continue;
}
dRightFilters.Add ( {i,bHasPrefix} );
}
return dRightFilters;
}
// check if any filter depends on an expression over joined attrs
// e.g. SELECT t2.i al, (al * 0.1) pct ... WHERE pct > 0
// pct itself is not ATTR_JOINED, but its expression depends on joined al
static bool HasFiltersDependingOnJoinedAttrs ( const CSphVector<CSphFilterSettings> & dFilters, const ISphSchema & tSchema )
{
for ( const auto & tFilter : dFilters )
{
const CSphColumnInfo * pFilterAttr = tSchema.GetAttr ( tFilter.m_sAttrName.cstr() );
if ( !pFilterAttr || !pFilterAttr->m_pExpr || pFilterAttr->IsJoined() )
continue;
StrVec_t dDeps;
dDeps.Add ( pFilterAttr->m_sName );
FetchAttrDependencies ( dDeps, tSchema );
for ( const auto & sDep : dDeps )
{
const CSphColumnInfo * pDep = tSchema.GetAttr ( sDep.cstr() );
if ( pDep && pDep->IsJoined() )
return true;
}
}
return false;
}
bool NeedPostJoinFilterEvaluation ( const CSphQuery & tQuery, const ISphSchema & tSchema )
{
return NeedPostJoinFilterEvaluation ( tQuery.m_dFilters, tQuery.m_sJoinIdx, tQuery.m_dFilterTree.GetLength()>0, tQuery.m_eJoinType, tSchema );
}
bool NeedPostJoinFilterEvaluation ( const CSphVector<CSphFilterSettings> & dFilters, const CSphString & sJoinIdx, bool bFilterTree, JoinType_e eJoinType, const ISphSchema & tSchema )
{
if ( HasFiltersDependingOnJoinedAttrs ( dFilters, tSchema ) )
return true;
CSphVector<std::pair<int,bool>> dRightFilters = FetchJoinRightTableFilters ( dFilters, tSchema, sJoinIdx.cstr() );
if ( !dRightFilters.GetLength() )
return false;
// move all filters to the left query in case of LEFT JOIN
// otherwise we can't distinguish between 'no match' and 'match with null part from right table'
if ( eJoinType==JoinType_e::LEFT )
return true;
if ( dRightFilters.GetLength()!=dFilters.GetLength() )
return bFilterTree; // we don't (yet) support splitting the filter tree between left and right queries
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class MatchPtrIterator_c
{
public:
MatchPtrIterator_c ( CSphMatch ** ppMatch ) : m_ppMatch ( ppMatch ) {}
FORCE_INLINE CSphMatch & operator*() const { return **m_ppMatch; }
FORCE_INLINE bool operator!= ( const MatchPtrIterator_c & tRhs ) const { return m_ppMatch != tRhs.m_ppMatch; }
FORCE_INLINE MatchPtrIterator_c & operator++()
{
++m_ppMatch;
return *this;
}
private:
CSphMatch ** m_ppMatch = nullptr;
};
class MatchPtrVec_c
{
public:
MatchPtrVec_c ( CSphVector<CSphMatch *> & dMatchPtrs ) : m_dMatchPtrs ( dMatchPtrs ) {}
FORCE_INLINE MatchPtrIterator_c begin() const { return MatchPtrIterator_c ( m_dMatchPtrs.begin() ); }
FORCE_INLINE MatchPtrIterator_c end() const { return MatchPtrIterator_c ( m_dMatchPtrs.end() ); }
int GetLength() const { return m_dMatchPtrs.GetLength(); }
private:
CSphVector<CSphMatch *> & m_dMatchPtrs;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FIXME! maybe replace it with a LRU cache
class MatchCache_c
{
public:
MatchCache_c ( uint64_t uCacheSize, int iBatchSize );
~MatchCache_c();
void SetSchema ( const ISphSchema * pSchema );
template <typename MATCHES>
bool Add ( uint64_t uHash, const MATCHES & dMatches );
FORCE_INLINE bool Fetch ( uint64_t uHash, CSphSwapVector<CSphMatch> & dMatches );
FORCE_INLINE bool IsFull() const { return m_uMaxSize && m_uCurSize>=m_uMaxSize; }
private:
// a simplified match (incoming matches don't have a static part)
struct StoredMatch_t
{
CSphRowitem * m_pDynamic = nullptr;
};
static const int INITIAL_HASH_SIZE = 4096;
using StoredMatches_t = CSphVector<StoredMatch_t>;
OpenHashTable_T<uint64_t, StoredMatches_t> m_hCache;
uint64_t m_uMaxSize = 0;
uint64_t m_uCurSize = 0;
uint64_t m_uFetched = 0;
int m_iBatchSize = 0;
std::unique_ptr<ISphSchema> m_pSchema;
uint64_t CalcMatchMem ( const CSphMatch & tMatch );
};
MatchCache_c::MatchCache_c ( uint64_t uCacheSize, int iBatchSize )
: m_hCache ( INITIAL_HASH_SIZE )
, m_uMaxSize ( uCacheSize )
, m_iBatchSize ( iBatchSize )
{}
MatchCache_c::~MatchCache_c()
{
int64_t iIterator = 0;
std::pair<SphGroupKey_t, StoredMatches_t*> tRes;
while ( ( tRes = m_hCache.Iterate ( iIterator ) ).second )
{
StoredMatches_t & dMatches = *tRes.second;
for ( auto & i : dMatches )
{
CSphMatch tStub;
tStub.m_pDynamic = i.m_pDynamic;
m_pSchema->FreeDataPtrs(tStub);
tStub.ResetDynamic();
}
}
}
void MatchCache_c::SetSchema ( const ISphSchema * pSchema )
{
if ( m_pSchema )
return;
// keep a clone of the schema
// we assume that the schema won't change during the lifetime of the cache
m_pSchema = std::unique_ptr<ISphSchema> ( pSchema->CloneMe() );
}
uint64_t MatchCache_c::CalcMatchMem ( const CSphMatch & tMatch )
{
uint64_t uMem = 0;
for ( int i = 0; i < m_pSchema->GetAttrsCount(); i++ )
{
const auto & tAttr = m_pSchema->GetAttr(i);
if ( !tAttr.IsDataPtr() )
continue;
const BYTE * pBlob = (const BYTE *)sphGetRowAttr ( tMatch.m_pDynamic, tAttr.m_tLocator );
uMem += sphUnpackPtrAttr(pBlob).second;
}
uMem += m_pSchema->GetDynamicSize()*sizeof(CSphRowitem);
uMem += sizeof(StoredMatch_t);
return uMem;
}
template <typename MATCHES>
bool MatchCache_c::Add ( uint64_t uHash, const MATCHES & dMatches )
{
if ( !m_pSchema )
return false;
if ( IsFull() )
return false;
// if we're inserting but not fetching anything back, there's high probability that we are dealing with unique JOIN ON conditions
// there's no point in caching those
int64_t iThresh = Max ( int64_t(8)*m_iBatchSize, 32768 );
if ( m_hCache.GetLength() >= iThresh )
{
float fRatio = float(m_uFetched)/iThresh;
if ( fRatio<=0.0001f )
return false;
}
uint64_t uEntrySize = 0;
StoredMatches_t dStoredMatches;
for ( const auto & i : dMatches )
{
dStoredMatches.Add ( { i.m_pDynamic } );
uEntrySize += CalcMatchMem(i);
}
uEntrySize += m_hCache.GetEntrySize();
if ( m_hCache.Add ( uHash, dStoredMatches ) )
{
m_uCurSize += uEntrySize;
return true;
}
return false;
}
bool MatchCache_c::Fetch ( uint64_t uHash, CSphSwapVector<CSphMatch> & dMatches )
{
StoredMatches_t * pMatches = m_hCache.Find(uHash);
if ( !pMatches )
return false;
dMatches.Resize ( pMatches->GetLength() );
for ( int i = 0; i < pMatches->GetLength(); i++ )
dMatches[i].m_pDynamic = (*pMatches)[i].m_pDynamic;
m_uFetched++;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class MatchCalc_c : public MatchProcessor_i
{
public:
MatchCalc_c ( ISphMatchSorter * pSorter ) : m_pSorter ( pSorter ) {}
void Process ( CSphMatch * pMatch ) override { m_pSorter->Push ( *pMatch ); }
bool ProcessInRowIdOrder() const override { return false; }
void Process ( VecTraits_T<CSphMatch *> & dMatches ) override
{
for ( auto & i : dMatches )
Process(i);
}
protected:
ISphMatchSorter * m_pSorter = nullptr;
};
class MatchCalcGrouped_c : public MatchCalc_c
{
public:
MatchCalcGrouped_c ( ISphMatchSorter * pSorter ) : MatchCalc_c ( pSorter ) {}
void Process ( CSphMatch * pMatch ) final
{
m_pSorter->PushGrouped ( *pMatch, m_bFirst );
m_bFirst = false;
}
private:
bool m_bFirst = true;
};
class StoredFetch_c : public MatchProcessor_i
{
public:
StoredFetch_c ( const ISphSchema & tSorterSchema, const CSphIndex & tRightIndex, const CSphString & sRightIndexName, uint64_t uNullMask );
void Process ( CSphMatch * pMatch ) override;
bool ProcessInRowIdOrder() const override { return false; }
void Process ( VecTraits_T<CSphMatch *> & dMatches ) override;
bool HasFieldToFetch() const { return !m_dFieldToFetch.IsEmpty(); }
private:
const ISphSchema & m_tSorterSchema;
const CSphIndex & m_tRightIndex;
CSphString m_sRightIndexName;
const CSphColumnInfo * m_pId = nullptr;
const CSphColumnInfo * m_pNullMaskAttr = nullptr;
std::unique_ptr<DocstoreSession_c> m_pSession;
int64_t m_iSessionUID = 0;
IntVec_t m_dFieldToFetch;
CSphVector<CSphAttrLocator> m_dAttrRemap;
uint64_t m_uNullMask = 0;
void CreateDocstoreSession();
void SetupAttrRemap();
};
StoredFetch_c::StoredFetch_c ( const ISphSchema & tSorterSchema, const CSphIndex & tRightIndex, const CSphString & sRightIndexName, uint64_t uNullMask )
: m_tSorterSchema ( tSorterSchema )
, m_tRightIndex ( tRightIndex )
, m_sRightIndexName ( sRightIndexName )
, m_uNullMask ( uNullMask )
{
CreateDocstoreSession();
SetupAttrRemap();
}
void StoredFetch_c::Process ( CSphMatch * pMatch )
{
assert ( !m_dFieldToFetch.IsEmpty() );
assert(m_pId);
SphAttr_t tDocId = pMatch->GetAttr ( m_pId->m_tLocator );
// compare against a preset null mask that the join sorter uses
bool bNull = m_pNullMaskAttr && pMatch->GetAttr ( m_pNullMaskAttr->m_tLocator )==(SphAttr_t)m_uNullMask;
DocstoreDoc_t tDoc;
if ( !bNull && m_tRightIndex.GetDoc ( tDoc, tDocId, &m_dFieldToFetch, m_iSessionUID, true ) )
{
ARRAY_FOREACH ( i, tDoc.m_dFields )
{
const CSphAttrLocator & tLoc = m_dAttrRemap[i];
auto pPrev = (BYTE*)pMatch->GetAttr(tLoc);
SafeDeleteArray(pPrev);
pMatch->SetAttr ( tLoc, (SphAttr_t)tDoc.m_dFields[i].LeakData() );
}
}
else
{
ARRAY_FOREACH ( i, tDoc.m_dFields )
{
auto pPrev = (BYTE*)pMatch->GetAttr ( m_dAttrRemap[i] );
SafeDeleteArray(pPrev);
}
}
}
void StoredFetch_c::Process ( VecTraits_T<CSphMatch *> & dMatches )
{
for ( auto & i : dMatches )
Process(i);
}
void StoredFetch_c::CreateDocstoreSession()
{
m_pSession = std::make_unique<DocstoreSession_c>();
m_iSessionUID = m_pSession->GetUID();
// spawn buffered readers for the current session
m_tRightIndex.CreateReader(m_iSessionUID);
}
void StoredFetch_c::SetupAttrRemap()
{
CSphString sAttrName;
sAttrName.SetSprintf ( "%s.%s", m_sRightIndexName.cstr(), sphGetDocidName() );
m_pId = m_tSorterSchema.GetAttr ( sAttrName.cstr() );
assert(m_pId);
const ISphSchema & tRightSchema = m_tRightIndex.GetMatchSchema();
for ( int i = 0; i < tRightSchema.GetFieldsCount(); i++ )
{
const CSphColumnInfo & tField = tRightSchema.GetField(i);
if ( !( tField.m_uFieldFlags & CSphColumnInfo::FIELD_STORED ) )
continue;
CSphString sAttrName;
sAttrName.SetSprintf ( "%s.%s", m_sRightIndexName.cstr(), tField.m_sName.cstr() );
int iDocStoreFieldId = m_tRightIndex.GetFieldId ( tField.m_sName, DOCSTORE_TEXT );
int iAttrId = m_tSorterSchema.GetAttrIndex ( sAttrName.cstr() );
assert ( iDocStoreFieldId!=-1 && iAttrId!=-1 );
m_dFieldToFetch.Add(iDocStoreFieldId);
m_dAttrRemap.Add ( m_tSorterSchema.GetAttr(iAttrId).m_tLocator );
}
m_pNullMaskAttr = m_tSorterSchema.GetAttr ( GetNullMaskAttrName() );
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class FilterEval_c
{
public:
void SetFilter ( std::unique_ptr<ISphFilter> & pFilter ) { m_pFilter = std::move ( pFilter ); }
void SetBlobPool ( const BYTE * pBlobPool ) { if ( m_pFilter ) m_pFilter->SetBlobStorage(pBlobPool); }
void SetColumnar ( columnar::Columnar_i * pColumnar ) { if ( m_pFilter ) m_pFilter->SetColumnar(pColumnar); }
FORCE_INLINE bool Eval ( const CSphMatch & tMatch ) const { return m_pFilter ? m_pFilter->Eval(tMatch) : true; }
private:
std::unique_ptr<ISphFilter> m_pFilter;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class JoinSorter_c : public ISphMatchSorter
{
public:
JoinSorter_c ( const CSphIndex * pIndex, const CSphIndex * pJoinedIndex, const CSphQuery & tQuery, const CSphQuery & tJoinQueryOptions, const CSphString & sRightIndexSchemaName, std::shared_ptr<ISphMatchSorter> pSorter, bool bJoinedGroupSort, int iBatchSize );
JoinSorter_c ( const CSphIndex * pIndex, const CSphIndex * pJoinedIndex, const VecTraits_T<const CSphQuery> & dQueries, const VecTraits_T<const CSphQuery> & dJoinQueryOptions, const CSphString & sRightIndexSchemaName, std::shared_ptr<ISphMatchSorter> pSorter, bool bJoinedGroupSort, int iBatchSize );
bool IsGroupby() const override { return m_pSorter->IsGroupby(); }
void SetState ( const CSphMatchComparatorState & tState ) override { m_pSorter->SetState(tState); }
const CSphMatchComparatorState & GetState() const override { return m_pSorter->GetState(); }
void SetGroupState ( const CSphMatchComparatorState & tState ) override { m_pSorter->SetGroupState(tState); }
void SetBlobPool ( const BYTE * pBlobPool ) override { SetBlobPoolImpl(pBlobPool); }
void SetColumnar ( columnar::Columnar_i * pColumnar ) override { SetColumnarImpl(pColumnar); }
void SetSchema ( ISphSchema * pSchema, bool bRemapCmp ) override;
const ISphSchema * GetSchema() const override { return m_pSorter->GetSchema(); }
bool Push ( const CSphMatch & tEntry ) override { return Push_T ( tEntry, [this]( const CSphMatch & tMatch ){ return m_pSorter->Push(tMatch); }, false ); }
void Push ( const VecTraits_T<const CSphMatch> & dMatches ) override;
bool PushGrouped ( const CSphMatch & tEntry, bool bNewSet ) override { return Push_T ( tEntry, [this,bNewSet]( const CSphMatch & tMatch ){ return m_pSorter->PushGrouped ( tMatch, bNewSet ); }, true ); }
int GetLength() override { return m_pSorter->GetLength(); }
int64_t GetTotalCount() const override;
void Finalize ( MatchProcessor_i & tProcessor, bool bCallProcessInResultSetOrder, bool bFinalizeMatches ) override { m_pSorter->Finalize ( tProcessor, bCallProcessInResultSetOrder, bFinalizeMatches ); }
int Flatten ( CSphMatch * pTo ) override { return m_pSorter->Flatten(pTo); }
const CSphMatch * GetWorst() const override { return m_pSorter->GetWorst(); }
bool CanBeCloned() const override { return m_pSorter->CanBeCloned(); }
ISphMatchSorter * Clone() const override;
void MoveTo ( ISphMatchSorter * pRhs, bool bCopyMeta ) override { m_pSorter->MoveTo ( ((JoinSorter_c *)pRhs)->m_pSorter.get(), bCopyMeta ); }
void CloneTo ( ISphMatchSorter * pTrg ) const override { m_pSorter->CloneTo(pTrg); }
void SetFilteredAttrs ( const sph::StringSet & hAttrs, bool bAddDocid ) override { m_pSorter->SetFilteredAttrs(hAttrs, bAddDocid); }
void TransformPooled2StandalonePtrs ( GetBlobPoolFromMatch_fn fnBlobPoolFromMatch, GetColumnarFromMatch_fn fnGetColumnarFromMatch, bool bFinalizeSorters ) override { m_pSorter->TransformPooled2StandalonePtrs(fnBlobPoolFromMatch, fnGetColumnarFromMatch, bFinalizeSorters); }
void SetRandom ( bool bRandom ) override { m_pSorter->SetRandom(bRandom); }
bool IsRandom() const override { return m_pSorter->IsRandom(); }
int GetMatchCapacity() const override { return m_pSorter->GetMatchCapacity(); }
RowTagged_t GetJustPushed() const override { return m_pSorter->GetJustPushed(); }
VecTraits_T<RowTagged_t> GetJustPopped() const override { return m_pSorter->GetJustPopped(); }
bool IsCutoffDisabled() const override { return m_pSorter->IsCutoffDisabled(); }
void SetMerge ( bool bMerge ) override { m_pSorter->SetMerge(bMerge); }
bool IsPrecalc() const override { return false; }
bool IsJoin() const override { return true; }
bool FinalizeJoin ( CSphString & sError, CSphString & sWarning ) override;
bool GetErrorFlag() const { return m_bErrorFlag; }
const CSphString & GetErrorMessage() const { return m_sErrorMessage; }
protected:
bool m_bCanBatch = true;
template <typename PUSH> bool RunBatch ( PUSH && fnPush );
template <typename PUSH> FORCE_INLINE bool Push_T ( const CSphMatch & tMatch, PUSH && fnPush, bool bGrouped );
template <typename PUSH, typename MATCHES> FORCE_INLINE bool PushJoinedMatches ( const CSphMatch & tEntry, const MATCHES & dMatches, PUSH && fnPush, const BYTE * pBlobPool, columnar::Columnar_i * pColumnar );
template <typename PUSH> FORCE_INLINE bool PushLeftMatch ( const CSphMatch & tEntry, PUSH && fnPush, const BYTE * pBlobPool, columnar::Columnar_i * pColumnar );
virtual bool RunFinalBatch();
FORCE_INLINE void SetBlobPoolImpl ( const BYTE * pBlobPool );
FORCE_INLINE void SetColumnarImpl ( columnar::Columnar_i * pColumnar );
private:
struct JoinAttrNameRemap_t
{
CSphString m_sFrom;
StrVec_t m_dTo;
};
struct JoinAttrRemap_t
{
CSphAttrLocator m_tLocSrc;
CSphAttrLocator m_tLocDst;
bool m_bJsonRepack = false;
};
struct FilterRemap_t
{
int m_iFilterId = -1;
CSphAttrLocator m_tLocator;
CSphAttrLocator m_tRightStandaloneLocator;
bool m_bBlob = false;
};
CSphQuery m_tJoinQuerySettings;
CSphQuery m_tJoinQuery;
std::unique_ptr<QueryParser_i> m_pJoinQueryParser;
const CSphIndex * m_pIndex = nullptr;
const CSphIndex * m_pJoinedIndex = nullptr;
const CSphQuery & m_tQuery;
VecTraits_T<const CSphQuery> m_dQueries;
VecTraits_T<const CSphQuery> m_dJoinQueryOptions;
CSphString m_sRightIndexSchemaName;
FilterEval_c m_tMixedFilter;
CSphMatch m_tMatch;
std::shared_ptr<ISphMatchSorter> m_pSorter;
std::shared_ptr<ISphMatchSorter> m_pOriginalSorter;
std::unique_ptr<ISphMatchSorter> m_pRightSorter;
std::unique_ptr<ISphSchema> m_pRightSorterRsetSchema;
const BYTE * m_pBlobPool = nullptr;
columnar::Columnar_i * m_pColumnar = nullptr;
const CSphColumnInfo * m_pAttrNullBitmask = nullptr;
CSphSwapVector<CSphMatch> m_dMatches;
CSphVector<JoinAttrNameRemap_t> m_dAttrRemap;
CSphVector<JoinAttrRemap_t> m_dJoinRemap;
bool m_bNeedToSetupRemap = true;
CSphVector<FilterRemap_t> m_dFilterRemap;
int m_iDynamicSize = 0;
bool m_bFinalCalcOnly = false;
const ISphSchema * m_pSorterSchema = nullptr;
CSphVector<ContextCalcItem_t> m_dCalcPrefilter;
CSphVector<ContextCalcItem_t> m_dCalcPresort;
CSphVector<ContextCalcItem_t> m_dAggregates;
IntVec_t m_dCalcPrefilterPtrAttrs;
IntVec_t m_dCalcPresortPtrAttrs;
bool m_bSorterSchemaHasDataPtrs = false;
MatchCache_c m_tCache;
std::unique_ptr<BYTE[]> m_pNullMask;
uint64_t m_uNullMask = 0;
bool m_bErrorFlag = false;
CSphString m_sErrorMessage;
CSphString m_sWarning;
int m_iBatchSize = 0;
int m_iBatched = 0;
CSphVector<SphAttr_t> m_dJoinOnFilterValues;
CSphVector<CSphString> m_dJoinOnFilterStrings;
CSphVector<SphAttr_t> m_dBatchedFilterValues;
CSphVector<CSphString> m_dBatchedFilterStrings;
CSphVector<CSphMatch *> m_dMatchPtrs;
IntVec_t m_dRightMatchUseCount;
OpenHashTableFastClear_T<uint64_t, IntVec_t> m_hRightMatches;
IntVec_t m_dIntFilters;
IntVec_t m_dStrFilters;
struct BatchedMatches_t
{
CSphMatch m_tMatch;
uint64_t m_uFilterHash = 0;
const BYTE * m_pBlobPool = nullptr; // each match potentially comes from a different chunk with different pools
columnar::Columnar_i * m_pColumnar = nullptr;
};
CSphFixedVector<BatchedMatches_t> m_dBatchedMatches;
bool SetupJoinQuery ( int iDynamicSize, CSphString & sError );
bool SetupJoinSorter ( CSphString & sError );
void SetupJoinAttrRemap();
void SetupDependentAttrCalc ( const IntVec_t & dJoinedAttrs );
void SetupSorterSchema();
void SetupNullMask();
void SetupAggregates();
FORCE_INLINE uint64_t SetupJoinFilters ( const CSphMatch & tEntry );
bool SetupRightFilters ( CSphString & sError );
bool ValidateLeftTableNotPrefixedInFilters ( CSphString & sError );
bool SetupOnFilters ( CSphString & sError );
bool SetupOnValueFilters ( CSphString & sError );
void SetupRightStandaloneLocators();
void AddToAttrRemap ( const CSphString & sFrom, const CSphString & sTo );
void AddToJoinSelectList ( const CSphString & sExpr );
void AddToJoinSelectList ( const CSphString & sExpr, const CSphString & sAlias );
void AddToJoinSelectList ( const CSphString & sExpr, const CSphString & sAlias, const char * szRemapPrefix );
void AddToJoinSelectList ( const CSphString & sExpr, const CSphString & sAlias, int iSorterAttrId, bool bConvertJsonType=false );
void AddToJoinSelectListForced ( const CSphString & sJoinExpr, const CSphString & sJoinAlias );
void AddOnFilterToFilterTree ( int iFilterId );
void AddStarItemsToJoinSelectList();
void AddQueryItemsToJoinSelectList();
void AddGroupbyItemsToJoinSelectList();
void AddOrderbyItemsToJoinSelectList();
void AddRemappedStringItemsToJoinSelectList();
void AddExpressionItemsToJoinSelectList();
void AddDocidToJoinSelectList();
void AddWeightToJoinSelectList();
void AddBatchedFilterItemsToJoinSelectList();
void SetupJoinSelectList();
void IncreaseJoinedMaxMatches ( int iTotalCount );
void RepackJsonFieldAsStr ( const CSphMatch & tSrcMatch, const CSphAttrLocator & tLocSrc, const CSphAttrLocator & tLocDst );
void ProduceCacheSizeWarning ( CSphString & sWarning );
void PopulateStoredFields();
CSphString GetJoinedIndexName() const { return m_sRightIndexSchemaName.IsEmpty() ? m_pJoinedIndex->GetName() : m_sRightIndexSchemaName; }
FORCE_INLINE void AddToBatch ( const CSphMatch & tEntry, uint64_t uFilterHash );
FORCE_INLINE bool IsBatchFull() const;
void SetupJoinFiltersBatch();
void ClearBatch();
uint64_t CalcRightFilterHash ( const CSphMatch & tEntry );
int DistributeRightMatches();
void CleanupUnusedRightMatches();
template <typename MATCHES> void CleanupRightMatches ( MATCHES & dMatches );
template <typename PUSH> void PushBatch ( PUSH && fnPush );
bool RunJoinedQuery ( int & iTotalCount );
bool RunJoinedQueryAndAdjustMaxMatches();
template <typename PUSH, typename MATCHES>
FORCE_INLINE bool AddToCacheAndPush ( const CSphMatch & tEntry, uint64_t uJoinOnFilterHash, PUSH && fnPush, MATCHES & dMatches, const BYTE * pBlobPool, columnar::Columnar_i * pColumnar, bool bAddToCache );
};
JoinSorter_c::JoinSorter_c ( const CSphIndex * pIndex, const CSphIndex * pJoinedIndex, const CSphQuery & tQuery, const CSphQuery & tJoinQueryOptions, const CSphString & sRightIndexSchemaName, std::shared_ptr<ISphMatchSorter> pSorter, bool bJoinedGroupSort, int iBatchSize )
: JoinSorter_c ( pIndex, pJoinedIndex, { &tQuery, 1 }, { &tJoinQueryOptions, 1 }, sRightIndexSchemaName, pSorter, bJoinedGroupSort, iBatchSize )
{}
JoinSorter_c::JoinSorter_c ( const CSphIndex * pIndex, const CSphIndex * pJoinedIndex, const VecTraits_T<const CSphQuery> & dQueries, const VecTraits_T<const CSphQuery> & dJoinQueryOptions, const CSphString & sRightIndexSchemaName, std::shared_ptr<ISphMatchSorter> pSorter, bool bJoinedGroupSort, int iBatchSize )
: m_tJoinQuerySettings ( dJoinQueryOptions[0] )
, m_pIndex ( pIndex )
, m_pJoinedIndex ( pJoinedIndex )
, m_tQuery ( dQueries.First() )
, m_dQueries ( dQueries )
, m_dJoinQueryOptions ( dJoinQueryOptions )
, m_sRightIndexSchemaName ( sRightIndexSchemaName )
, m_pSorter ( pSorter )
, m_tCache ( GetJoinCacheSize(), iBatchSize )
, m_iBatchSize ( iBatchSize )
, m_hRightMatches ( iBatchSize )
, m_dBatchedMatches ( iBatchSize )
{
assert ( pIndex && pJoinedIndex && pSorter );
const ISphSchema & tSorterSchema = *m_pSorter->GetSchema();
bool bHaveAggregates = false;
for ( int i = 0; i < tSorterSchema.GetAttrsCount(); i++ )
bHaveAggregates |= tSorterSchema.GetAttr(i).m_eAggrFunc!=SPH_AGGR_NONE;
CSphVector<std::pair<int,bool>> dRightFilters = FetchJoinRightTableFilters ( m_tQuery.m_dFilters, tSorterSchema, m_tQuery.m_sJoinIdx.cstr() );
bool bDisableByImplicitGrouping = HasImplicitGrouping(m_tQuery) && m_tQuery.m_eJoinType!=JoinType_e::LEFT;
m_bFinalCalcOnly = !pIndex->IsRT() && !bJoinedGroupSort && !bHaveAggregates && !dRightFilters.GetLength() && !NeedPostJoinFilterEvaluation ( m_tQuery, tSorterSchema ) && !pSorter->IsPrecalc() && !bDisableByImplicitGrouping;
m_bErrorFlag = !SetupJoinQuery ( m_pSorter->GetSchema()->GetDynamicSize(), m_sErrorMessage );
if ( m_bFinalCalcOnly || !m_iBatchSize )
m_bCanBatch = false;
}
void JoinSorter_c::SetBlobPoolImpl ( const BYTE * pBlobPool )
{
if ( m_pBlobPool==pBlobPool )
return;
m_pBlobPool = pBlobPool;
m_pSorter->SetBlobPool(pBlobPool);
m_tMixedFilter.SetBlobPool(pBlobPool);
}
void JoinSorter_c::SetColumnarImpl ( columnar::Columnar_i * pColumnar )
{
if ( m_pColumnar==pColumnar )
return;
m_pColumnar = pColumnar;
m_pSorter->SetColumnar(pColumnar);
m_tMixedFilter.SetColumnar(pColumnar);
}
void JoinSorter_c::SetSchema ( ISphSchema * pSchema, bool bRemapCmp )
{
m_pSorter->SetSchema ( pSchema, bRemapCmp );
m_bErrorFlag = !SetupJoinQuery ( pSchema->GetDynamicSize(), m_sErrorMessage );
}
void JoinSorter_c::SetupSorterSchema()
{
m_pSorterSchema = m_pSorter->GetSchema();
assert ( m_pSorterSchema );
m_pAttrNullBitmask = m_pSorterSchema->GetAttr ( GetNullMaskAttrName() );
for ( int i = 0; i < m_pSorterSchema->GetAttrsCount(); i++ )
m_bSorterSchemaHasDataPtrs |= m_pSorterSchema->GetAttr(i).IsDataPtr();
}
void JoinSorter_c::SetupNullMask()
{
if ( !m_pAttrNullBitmask )
return;
if ( m_pAttrNullBitmask->m_eAttrType==SPH_ATTR_STRINGPTR )
{
int iNumJoinAttrs = 0;
int iDynamic = 0;
for ( int i = 0; i < m_pSorterSchema->GetAttrsCount(); i++ )
{
const auto & tAttr = m_pSorterSchema->GetAttr(i);
if ( !tAttr.m_tLocator.m_bDynamic )
continue;
iDynamic++;
if ( tAttr.IsJoined() )
iNumJoinAttrs = Max ( iNumJoinAttrs, iDynamic );
}
BitVec_T<BYTE> tMask(iNumJoinAttrs);
iDynamic = 0;
for ( int i = 0; i < m_pSorterSchema->GetAttrsCount(); i++ )
{
const auto & tAttr = m_pSorterSchema->GetAttr(i);
if ( !tAttr.m_tLocator.m_bDynamic )
continue;
if ( tAttr.IsJoined() )
tMask.BitSet(iDynamic);
iDynamic++;
}
m_pNullMask = std::unique_ptr<BYTE[]>( sphPackPtrAttr ( { tMask.Begin(), tMask.GetSizeBytes() } ) );
m_uNullMask = (uint64_t)m_pNullMask.get();
return;
}
// we keep null flags only for attributes with a dynamic locator
// and these attributes need to be from the right table
m_uNullMask = 0;
int iDynamic = 0;
for ( int i = 0; i < m_pSorterSchema->GetAttrsCount(); i++ )
{
const auto & tAttr = m_pSorterSchema->GetAttr(i);
if ( !tAttr.m_tLocator.m_bDynamic )
continue;
if ( tAttr.IsJoined() )
m_uNullMask |= 1ULL << iDynamic;
iDynamic++;
}
}
void JoinSorter_c::SetupAggregates()
{
for ( int i = 0; i < m_pSorterSchema->GetAttrsCount(); i++ )
{
const auto & tAttr = m_pSorterSchema->GetAttr(i);
if ( tAttr.m_eAggrFunc!=SPH_AGGR_NONE && tAttr.m_eStage==SPH_EVAL_SORTER && GetJoinAttrName ( tAttr.m_sName, GetJoinedIndexName(), *m_pSorterSchema ) )
m_dAggregates.Add ( { tAttr.m_tLocator, tAttr.m_eAttrType, tAttr.m_pExpr } );
}
}
bool JoinSorter_c::SetupJoinQuery ( int iDynamicSize, CSphString & sError )
{
m_pJoinQueryParser = std::unique_ptr<QueryParser_i>( m_tQuery.m_pQueryParser->Clone() );
m_tJoinQuery = m_tJoinQuerySettings;
m_tJoinQuery.m_pQueryParser = m_pJoinQueryParser.get();
m_tJoinQuery.m_eQueryType = m_tQuery.m_eQueryType;
m_tJoinQuery.m_iLimit = m_tJoinQuery.m_iMaxMatches;
m_tJoinQuery.m_iCutoff = 0;
m_tJoinQuery.m_sQuery = m_tJoinQuery.m_sRawQuery = m_tQuery.m_sJoinQuery;
m_tMatch.Reset ( iDynamicSize );
SetupSorterSchema();
SetupJoinSelectList();
if ( !SetupRightFilters(sError) ) return false;
if ( !SetupOnFilters(sError) ) return false;
if ( !SetupOnValueFilters(sError) ) return false;
AddBatchedFilterItemsToJoinSelectList();
if ( !SetupJoinSorter(sError) ) return false;
SetupNullMask();
SetupAggregates();
m_iDynamicSize = iDynamicSize;
return true;
}
bool JoinSorter_c::SetupJoinSorter ( CSphString & sError )
{
SphQueueSettings_t tQueueSettings ( m_pJoinedIndex->GetMatchSchema() );
tQueueSettings.m_bComputeItems = true;
tQueueSettings.m_iMaxMatches = m_tJoinQuery.m_iMaxMatches;
SphQueueRes_t tRes;
m_pRightSorter = std::unique_ptr<ISphMatchSorter> ( sphCreateQueue ( tQueueSettings, m_tJoinQuery, sError, tRes ) );
if ( !m_pRightSorter )
return false;
m_pRightSorterRsetSchema = std::unique_ptr<ISphSchema> ( m_pRightSorter->GetSchema()->CloneMe() );
assert(m_pRightSorterRsetSchema);
return true;
}
void JoinSorter_c::SetupDependentAttrCalc ( const IntVec_t & dJoinedAttrs )
{
// find expressions that depend on joined attrs