-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathAggNodes.cpp
More file actions
3001 lines (2456 loc) · 77.2 KB
/
AggNodes.cpp
File metadata and controls
3001 lines (2456 loc) · 77.2 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
/*
* The contents of this file are subject to the Interbase Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy
* of the License at http://www.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
* Adriano dos Santos Fernandes - refactored from pass1.cpp, gen.cpp, cmp.cpp, par.cpp and evl.cpp
*/
#include "firebird.h"
#include "../dsql/AggNodes.h"
#include "../dsql/ExprNodes.h"
#include "../jrd/jrd.h"
#include "firebird/impl/blr.h"
#include "../jrd/btr.h"
#include "../jrd/exe.h"
#include "../jrd/tra.h"
#include "../jrd/recsrc/RecordSource.h"
#include "../jrd/blb_proto.h"
#include "../jrd/cmp_proto.h"
#include "../jrd/evl_proto.h"
#include "../jrd/intl_proto.h"
#include "../jrd/mov_proto.h"
#include "../jrd/par_proto.h"
#include "../dsql/ddl_proto.h"
#include "../dsql/errd_proto.h"
#include "../dsql/gen_proto.h"
#include "../dsql/make_proto.h"
#include "../dsql/pass1_proto.h"
#include "../dsql/utld_proto.h"
#include "../jrd/DataTypeUtil.h"
#include <math.h>
using namespace Firebird;
using namespace Jrd;
namespace Jrd {
static RegisterNode<AggNode> regAggNode({blr_agg_function});
AggNode::Factory* AggNode::factories = NULL;
AggNode::AggNode(MemoryPool& pool, const AggInfo& aAggInfo, bool aDistinct, bool aDialect1,
ValueExprNode* aArg)
: TypedNode<ValueExprNode, ExprNode::TYPE_AGGREGATE>(pool),
aggInfo(aAggInfo),
arg(aArg),
asb(NULL),
distinct(aDistinct),
dialect1(aDialect1),
indexed(false)
{
}
DmlNode* AggNode::parse(thread_db* tdbb, MemoryPool& pool, CompilerScratch* csb, const UCHAR /*blrOp*/)
{
MetaName name;
csb->csb_blr_reader.getMetaName(name);
AggNode* node = NULL;
for (const Factory* factory = factories; factory; factory = factory->next)
{
if (name == factory->name)
{
node = factory->newInstance(pool);
break;
}
}
if (!node)
PAR_error(csb, Arg::Gds(isc_funnotdef) << name);
const UCHAR count = csb->csb_blr_reader.getByte();
NodeRefsHolder holder(pool);
node->getChildren(holder, false);
if (count != holder.refs.getCount())
PAR_error(csb, Arg::Gds(isc_funmismat) << name);
node->parseArgs(tdbb, csb, count);
return node;
}
AggNode* AggNode::dsqlPass(DsqlCompilerScratch* dsqlScratch)
{
if (dsqlScratch->isPsql())
{
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-104) <<
Arg::Gds(isc_dsql_command_err));
}
if (!(dsqlScratch->inSelectList || dsqlScratch->inWhereClause || dsqlScratch->inGroupByClause ||
dsqlScratch->inHavingClause || dsqlScratch->inOrderByClause))
{
// not part of a select list, where clause, group by clause,
// having clause, or order by clause
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-104) <<
Arg::Gds(isc_dsql_agg_ref_err));
}
AutoSetRestore<USHORT> autoInAggregateFunction(&dsqlScratch->inAggregateFunction,
static_cast<USHORT>(dsqlScratch->inAggregateFunction + 1));
return dsqlCopy(dsqlScratch);
}
string AggNode::internalPrint(NodePrinter& printer) const
{
ValueExprNode::internalPrint(printer);
NODE_PRINT(printer, distinct);
NODE_PRINT(printer, dialect1);
NODE_PRINT(printer, arg);
NODE_PRINT(printer, asb);
NODE_PRINT(printer, sort);
NODE_PRINT(printer, indexed);
return aggInfo.name;
}
bool AggNode::dsqlAggregateFinder(AggregateFinder& visitor)
{
if (visitor.window || visitor.ignoreSubSelects)
return false;
bool aggregate = false;
USHORT localDeepestLevel = 0;
// If we are already in an aggregate function don't search inside
// sub-selects and other aggregate-functions for the deepest field
// used else we would have a wrong deepest_level value.
{ // scope
// We disable visiting of subqueries to handle this kind of query:
// select (select sum((select outer.column from inner1)) from inner2)
// from outer;
AutoSetRestore<USHORT> autoDeepestLevel(&visitor.deepestLevel, 0);
AutoSetRestore<bool> autoIgnoreSubSelects(&visitor.ignoreSubSelects, true);
NodeRefsHolder holder(visitor.getPool());
getChildren(holder, true);
for (auto i : holder.refs)
visitor.visit(*i);
localDeepestLevel = visitor.deepestLevel;
}
if (localDeepestLevel == 0)
{
// ASF: There were no usage of a field of this scope [COUNT(*) or SUM(1)] or
// they are inside a subquery [COUNT((select outer.field from inner))].
// So the level found (deepestLevel) is the one of the current query in
// processing.
visitor.deepestLevel = visitor.currentLevel;
}
else
visitor.deepestLevel = localDeepestLevel;
// If the deepestLevel is the same as the current scopeLevel this is an
// aggregate that belongs to the current context.
if (visitor.deepestLevel == visitor.dsqlScratch->scopeLevel)
aggregate = true;
else
{
// Check also for a nested aggregate that could belong to this context. Example:
// select (select count(count(outer.n)) from inner) from outer
AutoSetRestore<USHORT> autoDeepestLevel(&visitor.deepestLevel, localDeepestLevel);
NodeRefsHolder holder(visitor.getPool());
getChildren(holder, true);
for (auto i : holder.refs)
aggregate |= visitor.visit(*i);
}
return aggregate;
}
bool AggNode::dsqlAggregate2Finder(Aggregate2Finder& visitor)
{
if (visitor.windowOnly)
return false;
bool found = false;
FieldFinder fieldFinder(visitor.getPool(), visitor.checkScopeLevel, visitor.matchType);
NodeRefsHolder holder(visitor.getPool());
getChildren(holder, true);
for (auto i : holder.refs)
found |= fieldFinder.visit(*i);
if (!fieldFinder.getField())
{
// For example COUNT(*) is always same scope_level (node->nod_count = 0)
// Normally COUNT(*) is the only way to come here but something stupid
// as SUM(5) is also possible.
// If currentScopeLevelEqual is false scopeLevel is always higher
switch (visitor.matchType)
{
case FIELD_MATCH_TYPE_LOWER_EQUAL:
case FIELD_MATCH_TYPE_EQUAL:
return visitor.currentScopeLevelEqual;
///case FIELD_MATCH_TYPE_HIGHER_EQUAL:
/// return true;
case FIELD_MATCH_TYPE_LOWER: // Not used here
///case FIELD_MATCH_TYPE_HIGHER:
fb_assert(false);
return false;
default:
fb_assert(false);
}
}
return found;
}
bool AggNode::dsqlInvalidReferenceFinder(InvalidReferenceFinder& visitor)
{
bool invalid = false;
if (!visitor.insideOwnMap)
{
// We are not in an aggregate from the same scope_level so
// check for valid fields inside this aggregate
invalid |= ExprNode::dsqlInvalidReferenceFinder(visitor);
}
if (!visitor.insideHigherMap)
{
NodeRefsHolder holder(visitor.dsqlScratch->getPool());
getChildren(holder, true);
for (auto i : holder.refs)
{
// If there's another aggregate with the same scope_level or
// an higher one then it's a invalid aggregate, because
// aggregate-functions from the same context can't
// be part of each other.
if (Aggregate2Finder::find(visitor.dsqlScratch->getPool(), visitor.context->ctx_scope_level,
FIELD_MATCH_TYPE_EQUAL, false, *i))
{
// Nested aggregate functions are not allowed
ERRD_post(Arg::Gds(isc_sqlerr) << Arg::Num(-104) <<
Arg::Gds(isc_dsql_agg_nested_err));
}
}
}
return invalid;
}
bool AggNode::dsqlSubSelectFinder(SubSelectFinder& /*visitor*/)
{
return false;
}
ValueExprNode* AggNode::dsqlFieldRemapper(FieldRemapper& visitor)
{
AggregateFinder aggFinder(visitor.getPool(), visitor.dsqlScratch, false);
aggFinder.deepestLevel = visitor.dsqlScratch->scopeLevel;
aggFinder.currentLevel = visitor.currentLevel;
if (dsqlAggregateFinder(aggFinder))
{
if (!visitor.window && visitor.dsqlScratch->scopeLevel == aggFinder.deepestLevel)
return PASS1_post_map(visitor.dsqlScratch, this, visitor.context, visitor.windowNode);
}
NodeRefsHolder holder(visitor.getPool());
getChildren(holder, true);
for (auto i : holder.refs)
{
if (*i)
*i = (*i)->dsqlFieldRemapper(visitor);
}
return this;
}
bool AggNode::dsqlMatch(DsqlCompilerScratch* dsqlScratch, const ExprNode* other, bool ignoreMapCast) const
{
if (!ExprNode::dsqlMatch(dsqlScratch, other, ignoreMapCast))
return false;
const AggNode* o = nodeAs<AggNode>(other);
fb_assert(o);
// ASF: We compare name address. That should be ok, as we have only one AggInfo instance
// per function.
return aggInfo.blr == o->aggInfo.blr && aggInfo.name == o->aggInfo.name &&
distinct == o->distinct && dialect1 == o->dialect1;
}
void AggNode::setParameterName(dsql_par* parameter) const
{
parameter->par_name = parameter->par_alias = aggInfo.name;
}
void AggNode::genBlr(DsqlCompilerScratch* dsqlScratch)
{
NodeRefsHolder holder(dsqlScratch->getPool());
getChildren(holder, true);
if (aggInfo.blr) // Is this a standard aggregate function?
dsqlScratch->appendUChar((distinct ? aggInfo.distinctBlr : aggInfo.blr));
else // This is a new window function.
{
dsqlScratch->appendUChar(blr_agg_function);
dsqlScratch->appendNullString(aggInfo.name);
unsigned count = 0;
for (auto i : holder.refs)
{
if (*i)
++count;
}
dsqlScratch->appendUChar(UCHAR(count));
}
for (auto i : holder.refs)
{
if (*i)
GEN_expr(dsqlScratch, *i);
}
}
AggNode* AggNode::pass2(thread_db* tdbb, CompilerScratch* csb)
{
ValueExprNode::pass2(tdbb, csb);
dsc desc;
getDesc(tdbb, csb, &desc);
impureOffset = csb->allocImpure<impure_value_ex>();
if (sort)
doPass2(tdbb, csb, sort.getAddress());
return this;
}
void AggNode::makeSortDesc(thread_db* tdbb, CompilerScratch* csb, dsc* desc)
{
arg->getDesc(tdbb, csb, desc);
}
void AggNode::aggInit(thread_db* tdbb, Request* request) const
{
impure_value_ex* impure = request->getImpure<impure_value_ex>(impureOffset);
impure->vlux_count = 0;
if (distinct || sort)
{
// Initialize a sort to reject duplicate values.
impure_agg_sort* asbImpure = request->getImpure<impure_agg_sort>(asb->impure);
// Get rid of the old sort areas if this request has been used already.
delete asbImpure->iasb_sort;
asbImpure->iasb_sort = NULL;
asbImpure->iasb_sort = FB_NEW_POOL(request->req_sorts.getPool()) Sort(
tdbb->getDatabase(), &request->req_sorts, asb->length,
asb->keyItems.getCount(), (distinct ? 1 : asb->keyItems.getCount()),
asb->keyItems.begin(), (distinct ? RecordSource::rejectDuplicate : nullptr), 0);
}
}
bool AggNode::aggPass(thread_db* tdbb, Request* request) const
{
dsc* desc = NULL;
if (arg)
{
desc = EVL_expr(tdbb, request, arg);
if (!desc)
return false;
if (distinct)
{
fb_assert(asb);
// "Put" the value to sort.
impure_agg_sort* asbImpure = request->getImpure<impure_agg_sort>(asb->impure);
UCHAR* data;
asbImpure->iasb_sort->put(tdbb, reinterpret_cast<ULONG**>(&data));
MOVE_CLEAR(data, asb->length);
if (asb->intl)
{
// Convert to an international byte array.
dsc to;
to.dsc_dtype = dtype_text;
to.dsc_flags = 0;
to.dsc_sub_type = 0;
to.dsc_scale = 0;
to.setTextType(ttype_sort_key);
to.dsc_length = asb->keyItems[0].getSkdLength();
to.dsc_address = data;
INTL_string_to_key(tdbb, INTL_TEXT_TO_INDEX(desc->getTextType()),
desc, &to, INTL_KEY_UNIQUE);
}
dsc toDesc = asb->desc;
toDesc.dsc_address = data +
(asb->intl ? asb->keyItems[1].getSkdOffset() : 0);
MOV_move(tdbb, desc, &toDesc);
// dimitr: Here we add a monotonically increasing value to the sort record.
// It allows the record to look more random than it was originally.
// This helps the quick sort algorithm to avoid the worst-case of
// all equal values (see CORE-214).
ULONG* const pDummy = reinterpret_cast<ULONG*>(data + asb->length - sizeof(ULONG));
*pDummy = asbImpure->iasb_dummy++;
return true;
}
else if (sort)
{
fb_assert(asb);
// "Put" the value to sort.
impure_agg_sort* asbImpure = request->getImpure<impure_agg_sort>(asb->impure);
UCHAR* data;
asbImpure->iasb_sort->put(tdbb, reinterpret_cast<ULONG**>(&data));
MOVE_CLEAR(data, asb->length);
auto descOrder = asb->descOrder.begin();
auto keyItem = asb->keyItems.begin();
for (auto& nodeOrder : sort->expressions)
{
dsc toDesc = *(descOrder++);
toDesc.dsc_address = data + (IPTR) toDesc.dsc_address;
if (const auto fromDsc = EVL_expr(tdbb, request, nodeOrder))
{
if (IS_INTL_DATA(fromDsc))
{
INTL_string_to_key(tdbb, INTL_TEXT_TO_INDEX(fromDsc->getTextType()),
fromDsc, &toDesc, INTL_KEY_UNIQUE);
}
else
MOV_move(tdbb, fromDsc, &toDesc);
}
else
*(data + keyItem->getSkdOffset()) = TRUE;
// The first key for NULLS FIRST/LAST, the second key for the sorter
keyItem += 2;
}
dsc toDesc = asb->desc;
toDesc.dsc_address = data + (IPTR) toDesc.dsc_address;
MOV_move(tdbb, desc, &toDesc);
return true;
}
}
aggPass(tdbb, request, desc);
return true;
}
void AggNode::aggFinish(thread_db* /*tdbb*/, Request* request) const
{
if (asb)
{
impure_agg_sort* const asbImpure = request->getImpure<impure_agg_sort>(asb->impure);
delete asbImpure->iasb_sort;
asbImpure->iasb_sort = NULL;
}
}
dsc* AggNode::execute(thread_db* tdbb, Request* request) const
{
impure_value_ex* impure = request->getImpure<impure_value_ex>(impureOffset);
if (impure->vlu_blob)
{
impure->vlu_blob->BLB_close(tdbb);
impure->vlu_blob = NULL;
}
if (distinct || sort)
{
impure_agg_sort* asbImpure = request->getImpure<impure_agg_sort>(asb->impure);
dsc desc = asb->desc;
// Sort the values already "put" to sort.
asbImpure->iasb_sort->sort(tdbb);
// Now get the sorted/projected values and compute the aggregate.
while (true)
{
UCHAR* data;
asbImpure->iasb_sort->get(tdbb, reinterpret_cast<ULONG**>(&data));
if (!data)
{
// We are done, close the sort.
delete asbImpure->iasb_sort;
asbImpure->iasb_sort = NULL;
break;
}
if (distinct)
desc.dsc_address = data + (asb->intl ? asb->keyItems[1].getSkdOffset() : 0);
else
desc.dsc_address = data + (IPTR) asb->desc.dsc_address;
aggPass(tdbb, request, &desc);
}
}
return aggExecute(tdbb, request);
}
//--------------------
static AggNode::RegisterFactory0<AnyValueAggNode> anyValueAggInfo("ANY_VALUE");
AnyValueAggNode::AnyValueAggNode(MemoryPool& pool, ValueExprNode* aArg)
: AggNode(pool, anyValueAggInfo, false, false, aArg)
{
}
DmlNode* AnyValueAggNode::parse(thread_db* tdbb, MemoryPool& pool, CompilerScratch* csb, const UCHAR /*blrOp*/)
{
const auto node = FB_NEW_POOL(pool) AnyValueAggNode(pool);
node->arg = PAR_parse_value(tdbb, csb);
return node;
}
void AnyValueAggNode::parseArgs(thread_db* tdbb, CompilerScratch* csb, unsigned /*count*/)
{
arg = PAR_parse_value(tdbb, csb);
}
void AnyValueAggNode::make(DsqlCompilerScratch* dsqlScratch, dsc* desc)
{
DsqlDescMaker::fromNode(dsqlScratch, desc, arg, true);
}
void AnyValueAggNode::getDesc(thread_db* tdbb, CompilerScratch* csb, dsc* desc)
{
arg->getDesc(tdbb, csb, desc);
}
ValueExprNode* AnyValueAggNode::copy(thread_db* tdbb, NodeCopier& copier) const
{
const auto node = FB_NEW_POOL(*tdbb->getDefaultPool()) AnyValueAggNode(*tdbb->getDefaultPool());
node->nodScale = nodScale;
node->arg = copier.copy(tdbb, arg);
return node;
}
string AnyValueAggNode::internalPrint(NodePrinter& printer) const
{
AggNode::internalPrint(printer);
return "AnyValueAggNode";
}
void AnyValueAggNode::aggInit(thread_db* tdbb, Request* request) const
{
AggNode::aggInit(tdbb, request);
const auto impure = request->getImpure<impure_value_ex>(impureOffset);
impure->vlu_desc.dsc_dtype = 0;
}
void AnyValueAggNode::aggPass(thread_db* tdbb, Request* request, dsc* desc) const
{
const auto impure = request->getImpure<impure_value_ex>(impureOffset);
if (!impure->vlu_desc.dsc_dtype)
{
const auto argValue = EVL_expr(tdbb, request, arg);
if (argValue)
EVL_make_value(tdbb, argValue, impure);
}
}
dsc* AnyValueAggNode::aggExecute(thread_db* /*tdbb*/, Request* request) const
{
const auto impure = request->getImpure<impure_value_ex>(impureOffset);
if (impure->vlu_desc.dsc_dtype)
return &impure->vlu_desc;
return nullptr;
}
AggNode* AnyValueAggNode::dsqlCopy(DsqlCompilerScratch* dsqlScratch) /*const*/
{
return FB_NEW_POOL(dsqlScratch->getPool()) AnyValueAggNode(dsqlScratch->getPool(),
doDsqlPass(dsqlScratch, arg));
}
//--------------------
static AggNode::Register<AvgAggNode> avgAggInfo("AVG", blr_agg_average, blr_agg_average_distinct);
AvgAggNode::AvgAggNode(MemoryPool& pool, bool aDistinct, bool aDialect1, ValueExprNode* aArg)
: AggNode(pool, avgAggInfo, aDistinct, aDialect1, aArg),
tempImpure(0)
{
}
DmlNode* AvgAggNode::parse(thread_db* tdbb, MemoryPool& pool, CompilerScratch* csb, const UCHAR blrOp)
{
AvgAggNode* node = FB_NEW_POOL(pool) AvgAggNode(pool,
(blrOp == blr_agg_average_distinct),
(csb->blrVersion == 4));
node->arg = PAR_parse_value(tdbb, csb);
return node;
}
void AvgAggNode::make(DsqlCompilerScratch* dsqlScratch, dsc* desc)
{
DsqlDescMaker::fromNode(dsqlScratch, desc, arg, true);
if (desc->isNull())
return;
if (DTYPE_IS_DECFLOAT(desc->dsc_dtype))
return;
if (dialect1)
{
if (!DTYPE_IS_NUMERIC(desc->dsc_dtype) && !DTYPE_IS_TEXT(desc->dsc_dtype))
{
ERRD_post(Arg::Gds(isc_expression_eval_err) <<
Arg::Gds(isc_dsql_agg_wrongarg) << Arg::Str("AVG"));
}
else if (DTYPE_IS_TEXT(desc->dsc_dtype))
{
desc->dsc_dtype = dtype_double;
desc->dsc_length = sizeof(double);
}
}
else
{
if (!DTYPE_IS_NUMERIC(desc->dsc_dtype))
{
ERRD_post(Arg::Gds(isc_expression_eval_err) <<
Arg::Gds(isc_dsql_agg2_wrongarg) << Arg::Str("AVG"));
}
else if (desc->dsc_dtype == dtype_int128)
{
desc->dsc_dtype = dtype_int128;
desc->dsc_length = sizeof(Int128);
}
else if (DTYPE_IS_EXACT(desc->dsc_dtype))
{
desc->dsc_dtype = dtype_int64;
desc->dsc_length = sizeof(SINT64);
}
else
{
desc->dsc_dtype = dtype_double;
desc->dsc_length = sizeof(double);
}
}
}
void AvgAggNode::getDesc(thread_db* tdbb, CompilerScratch* csb, dsc* desc)
{
arg->getDesc(tdbb, csb, desc);
outputDesc(desc);
switch (desc->dsc_dtype)
{
case dtype_dec64:
case dtype_dec128:
nodFlags |= FLAG_DECFLOAT;
break;
case dtype_int64:
case dtype_int128:
nodFlags |= FLAG_INT128;
// fall down...
case dtype_short:
case dtype_long:
nodScale = desc->dsc_scale;
break;
case dtype_unknown:
break;
default:
nodFlags |= FLAG_DOUBLE;
break;
}
}
void AvgAggNode::outputDesc(dsc* desc) const
{
if (DTYPE_IS_DECFLOAT(desc->dsc_dtype))
{
desc->dsc_scale = 0;
desc->dsc_sub_type = 0;
desc->dsc_flags = 0;
return;
}
if (dialect1)
{
if (!(DTYPE_IS_NUMERIC(desc->dsc_dtype) || DTYPE_IS_TEXT(desc->dsc_dtype)))
{
if (desc->dsc_dtype != dtype_unknown)
ERR_post(Arg::Gds(isc_datype_notsup)); // data type not supported for arithmetic
}
desc->dsc_dtype = DEFAULT_DOUBLE;
desc->dsc_length = sizeof(double);
desc->dsc_scale = 0;
desc->dsc_sub_type = 0;
desc->dsc_flags = 0;
return;
}
switch (desc->dsc_dtype)
{
case dtype_short:
case dtype_long:
case dtype_int64:
desc->dsc_dtype = dtype_int64;
desc->dsc_length = sizeof(SINT64);
desc->dsc_flags = 0;
break;
case dtype_int128:
desc->dsc_dtype = dtype_int128;
desc->dsc_length = sizeof(Int128);
desc->dsc_flags = 0;
break;
case dtype_unknown:
desc->dsc_dtype = dtype_unknown;
desc->dsc_length = 0;
desc->dsc_scale = 0;
desc->dsc_sub_type = 0;
desc->dsc_flags = 0;
break;
default:
if (!DTYPE_IS_NUMERIC(desc->dsc_dtype))
{
if (desc->dsc_dtype == dtype_quad)
IBERROR(224); // msg 224 quad word arithmetic not supported
ERR_post(Arg::Gds(isc_datype_notsup)); // data type not supported for arithmetic
}
desc->dsc_dtype = DEFAULT_DOUBLE;
desc->dsc_length = sizeof(double);
desc->dsc_scale = 0;
desc->dsc_sub_type = 0;
desc->dsc_flags = 0;
break;
}
}
ValueExprNode* AvgAggNode::copy(thread_db* tdbb, NodeCopier& copier) const
{
AvgAggNode* node = FB_NEW_POOL(*tdbb->getDefaultPool()) AvgAggNode(*tdbb->getDefaultPool(),
distinct, dialect1);
node->nodScale = nodScale;
node->arg = copier.copy(tdbb, arg);
return node;
}
AggNode* AvgAggNode::pass2(thread_db* tdbb, CompilerScratch* csb)
{
AggNode::pass2(tdbb, csb);
if (dialect1 && !(nodFlags & FLAG_DECFLOAT))
nodFlags |= FLAG_DOUBLE;
// We need a second descriptor in the impure area for AVG.
tempImpure = csb->allocImpure<impure_value_ex>();
return this;
}
string AvgAggNode::internalPrint(NodePrinter& printer) const
{
AggNode::internalPrint(printer);
NODE_PRINT(printer, tempImpure);
return "AvgAggNode";
}
void AvgAggNode::aggInit(thread_db* tdbb, Request* request) const
{
AggNode::aggInit(tdbb, request);
impure_value_ex* impure = request->getImpure<impure_value_ex>(impureOffset);
if (dialect1)
{
impure->vlu_desc.makeDouble(&impure->vlu_misc.vlu_double);
impure->vlu_misc.vlu_double = 0;
}
else
{
// Initialize the result area as an int64. If the field being aggregated is approximate
// numeric, the first call to add will convert the descriptor.
impure->make_int64(0, nodScale);
}
}
void AvgAggNode::aggPass(thread_db* tdbb, Request* request, dsc* desc) const
{
impure_value_ex* impure = request->getImpure<impure_value_ex>(impureOffset);
if (impure->vlux_count++ == 0) // first call to aggPass()
{
impure_value_ex* impureTemp = request->getImpure<impure_value_ex>(tempImpure);
impureTemp->vlu_desc = *desc;
outputDesc(&impureTemp->vlu_desc);
}
ArithmeticNode::add(tdbb, desc, &impure->vlu_desc, impure, blr_add, dialect1, nodScale, nodFlags);
}
dsc* AvgAggNode::aggExecute(thread_db* tdbb, Request* request) const
{
impure_value_ex* impure = request->getImpure<impure_value_ex>(impureOffset);
if (!impure->vlux_count)
return NULL;
dsc temp;
SINT64 i;
double d;
Decimal128 dec;
Decimal64 d64;
Int128 i128;
impure_value_ex* impureTemp = request->getImpure<impure_value_ex>(tempImpure);
UCHAR dtype = impureTemp->vlu_desc.dsc_dtype;
if (!dialect1 && impure->vlu_desc.dsc_dtype == dtype_int64)
{
i = *((SINT64*) impure->vlu_desc.dsc_address) / impure->vlux_count;
temp.makeInt64(impure->vlu_desc.dsc_scale, &i);
}
else if (!dialect1 && impure->vlu_desc.dsc_dtype == dtype_int128)
{
i128.set(impure->vlux_count, 0);
i128 = ((Int128*) impure->vlu_desc.dsc_address)->div(i128, 0);
if (dtype == dtype_int128)
temp.makeInt128(impure->vlu_desc.dsc_scale, &i128);
else
{
fb_assert(dtype == dtype_int64);
i = i128.toInt64(0);
temp.makeInt64(impure->vlu_desc.dsc_scale, &i);
}
}
else if (dtype == dtype_dec128)
{
DecimalStatus decSt = tdbb->getAttachment()->att_dec_status;
dec.set(impure->vlux_count, decSt, 0);
dec = MOV_get_dec128(tdbb, &impure->vlu_desc).div(decSt, dec);
temp.makeDecimal128(&dec);
}
else if (dtype == dtype_dec64)
{
DecimalStatus decSt = tdbb->getAttachment()->att_dec_status;
// use higher precision for division
dec.set(impure->vlux_count, decSt, 0);
d64 = MOV_get_dec128(tdbb, &impure->vlu_desc).div(decSt, dec).toDecimal64(decSt);
temp.makeDecimal64(&d64);
}
else
{
d = MOV_get_double(tdbb, &impure->vlu_desc) / impure->vlux_count;
temp.makeDouble(&d);
}
EVL_make_value(tdbb, &temp, impureTemp);
return &impureTemp->vlu_desc;
}
AggNode* AvgAggNode::dsqlCopy(DsqlCompilerScratch* dsqlScratch) /*const*/
{
return FB_NEW_POOL(dsqlScratch->getPool()) AvgAggNode(dsqlScratch->getPool(), distinct, dialect1,
doDsqlPass(dsqlScratch, arg));
}
//--------------------
static AggNode::Register<ListAggNode> listAggInfo("LIST", blr_agg_list, blr_agg_list_distinct);
ListAggNode::ListAggNode(MemoryPool& pool, bool aDistinct, ValueExprNode* aArg,
ValueExprNode* aDelimiter, ValueListNode* aOrderClause)
: AggNode(pool, listAggInfo, aDistinct, false, aArg),
delimiter(aDelimiter),
dsqlOrderClause(aOrderClause)
{
}
DmlNode* ListAggNode::parse(thread_db* tdbb, MemoryPool& pool, CompilerScratch* csb, const UCHAR blrOp)
{
ListAggNode* node = FB_NEW_POOL(pool) ListAggNode(pool, (blrOp == blr_agg_list_distinct));
node->arg = PAR_parse_value(tdbb, csb);
node->delimiter = PAR_parse_value(tdbb, csb);
if (csb->csb_blr_reader.peekByte() == blr_within_group_order)
{
csb->csb_blr_reader.getByte(); // skip blr_within_group_order
if (const auto count = csb->csb_blr_reader.getByte())
node->sort = PAR_sort_internal(tdbb, csb, true, count);
}
return node;
}
bool ListAggNode::dsqlMatch(DsqlCompilerScratch* dsqlScratch, const ExprNode* other, bool ignoreMapCast) const
{
if (!AggNode::dsqlMatch(dsqlScratch, other, ignoreMapCast))
return false;
const ListAggNode* o = nodeAs<ListAggNode>(other);
fb_assert(o);
if (dsqlOrderClause || o->dsqlOrderClause)
return PASS1_node_match(dsqlScratch, dsqlOrderClause, o->dsqlOrderClause, ignoreMapCast);
return true;
}
void ListAggNode::make(DsqlCompilerScratch* dsqlScratch, dsc* desc)
{
DsqlDescMaker::fromNode(dsqlScratch, desc, arg);
desc->makeBlob(desc->getBlobSubType(), desc->getTextType());
desc->setNullable(true);
}
void ListAggNode::genBlr(DsqlCompilerScratch* dsqlScratch)
{
AggNode::genBlr(dsqlScratch);
if (dsqlOrderClause)
GEN_sort(dsqlScratch, blr_within_group_order, dsqlOrderClause);
}
bool ListAggNode::setParameterType(DsqlCompilerScratch* dsqlScratch,
std::function<void (dsc*)> makeDesc, bool forceVarChar)
{
const bool argType = PASS1_set_parameter_type(dsqlScratch, arg, makeDesc, forceVarChar);
const bool delimiterType = PASS1_set_parameter_type(dsqlScratch, delimiter, makeDesc, forceVarChar);
return argType || delimiterType;
}
void ListAggNode::getDesc(thread_db* tdbb, CompilerScratch* csb, dsc* desc)
{
arg->getDesc(tdbb, csb, desc);
desc->makeBlob(desc->getBlobSubType(), desc->getTextType());
}
ValueExprNode* ListAggNode::copy(thread_db* tdbb, NodeCopier& copier) const
{
ListAggNode* node = FB_NEW_POOL(*tdbb->getDefaultPool()) ListAggNode(*tdbb->getDefaultPool(), distinct);