-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDataSheet.php
More file actions
3604 lines (3269 loc) · 169 KB
/
DataSheet.php
File metadata and controls
3604 lines (3269 loc) · 169 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
<?php
namespace exface\Core\CommonLogic\DataSheets;
use exface\Core\CommonLogic\UxonObject;
use exface\Core\CommonLogic\Model\ConditionGroup;
use exface\Core\DataTypes\BinaryDataType;
use exface\Core\DataTypes\ByteSizeDataType;
use exface\Core\DataTypes\IntegerDataType;
use exface\Core\Interfaces\DataSheets\DataAggregationListInterface;
use exface\Core\Interfaces\DataSheets\DataColumnListInterface;
use exface\Core\Interfaces\DataSheets\DataSheetListInterface;
use exface\Core\Interfaces\Debug\DataLogBookInterface;
use exface\Core\Interfaces\Model\ConditionGroupInterface;
use exface\Core\Interfaces\Model\MetaObjectInterface;
use exface\Core\Exceptions\DataSheets\DataSheetMergeError;
use exface\Core\Factories\QueryBuilderFactory;
use exface\Core\Interfaces\DataSheets\DataSheetInterface;
use exface\Core\Factories\ConditionFactory;
use exface\Core\Factories\ConditionGroupFactory;
use exface\Core\Factories\DataColumnFactory;
use exface\Core\CommonLogic\Model\RelationPath;
use exface\Core\Factories\DataColumnTotalsFactory;
use exface\Core\Interfaces\DataSheets\DataSorterListInterface;
use exface\Core\Interfaces\DataSheets\DataColumnInterface;
use exface\Core\Interfaces\DataSources\DataTransactionInterface;
use exface\Core\Factories\DataSheetFactory;
use exface\Core\Exceptions\DataSheets\DataSheetJoinError;
use exface\Core\Exceptions\DataSheets\DataSheetImportRowError;
use exface\Core\Exceptions\DataSheets\DataSheetWriteError;
use exface\Core\Exceptions\DataSheets\DataSheetColumnNotFoundError;
use exface\Core\Exceptions\DataSheets\DataSheetRuntimeError;
use exface\Core\Exceptions\Model\MetaAttributeNotFoundError;
use exface\Core\Exceptions\DataSheets\DataSheetReadError;
use exface\Core\Exceptions\DataSheets\DataSheetMissingRequiredValueError;
use exface\Core\Exceptions\DataSheets\DataSheetDeleteError;
use exface\Core\Exceptions\Model\MetaObjectHasNoDataSourceError;
use exface\Core\Interfaces\Model\ConditionalExpressionInterface;
use exface\Core\CommonLogic\QueryBuilder\RowDataArraySorter;
use exface\Core\Exceptions\DataSheets\DataSheetStructureError;
use exface\Core\Interfaces\QueryBuilderInterface;
use exface\Core\Events\DataSheet\OnBeforeValidateDataEvent;
use exface\Core\Events\DataSheet\OnValidateDataEvent;
use exface\Core\Events\DataSheet\OnBeforeReadDataEvent;
use exface\Core\Events\DataSheet\OnReadDataEvent;
use exface\Core\Events\DataSheet\OnBeforeUpdateDataEvent;
use exface\Core\Events\DataSheet\OnUpdateDataEvent;
use exface\Core\Events\DataSheet\OnBeforeCreateDataEvent;
use exface\Core\Events\DataSheet\OnCreateDataEvent;
use exface\Core\Events\DataSheet\OnBeforeDeleteDataEvent;
use exface\Core\Events\DataSheet\OnDeleteDataEvent;
use exface\Core\Events\DataSheet\OnBeforeReplaceDataEvent;
use exface\Core\Events\DataSheet\OnReplaceDataEvent;
use exface\Core\Factories\RelationPathFactory;
use exface\Core\DataTypes\DataSheetDataType;
use exface\Core\DataTypes\RelationCardinalityDataType;
use exface\Core\DataTypes\ComparatorDataType;
use exface\Core\Interfaces\Model\ConditionInterface;
use exface\Core\DataTypes\EncryptedDataType;
use exface\Core\DataTypes\StringDataType;
use exface\Core\Exceptions\InvalidArgumentException;
use exface\Core\Widgets\DebugMessage;
use exface\Core\Factories\WidgetFactory;
use exface\Core\Exceptions\DataSheets\DataSheetInvalidValueError;
use exface\Core\Exceptions\DataSheets\DataSheetExtractError;
use exface\Core\Interfaces\Model\MetaAttributeInterface;
use exface\Core\DataTypes\PhpClassDataType;
use exface\Core\DataTypes\AggregatorFunctionsDataType;
use exface\Core\Exceptions\Contexts\ContextAccessDeniedError;
use exface\Core\DataTypes\BooleanDataType;
use exface\Core\Exceptions\DataSheets\DataNotFoundError;
/**
* Default implementation of DataSheetInterface
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface
*
* @author Andrej Kabachnik
*
*/
class DataSheet implements DataSheetInterface
{
// properties to be copied on copy()
private $cols = array();
private $rows = array();
private $totals_rows = array();
private $filters = null;
private $sorters = array();
private $autosort = true;
private $total_row_count = null;
private $autocount = true;
private $subsheets = array();
private $aggregation_columns = null;
private $aggregateAll = null;
private $rows_on_page = null;
private $row_offset = 0;
private $uid_column_name = null;
private $invalid_data_flag = false;
private $is_fresh = true;
private $is_fresh_tag = null;
// properties NOT to be copied on copy()
private $exface;
private $meta_object;
private $dataSourceHasMoreRows = true;
/**
* The maximum number of characters of string data to be represented in debug data.
* Truncate any string data to this length before displaying it for debug purposes
* to avoid memory overflow.
*/
private const DEBUG_STRING_MAX_LENGTH = 10000;
public function __construct(\exface\Core\Interfaces\Model\MetaObjectInterface $meta_object)
{
$this->exface = $meta_object->getModel()->getWorkbench();
$this->meta_object = $meta_object;
$this->filters = ConditionGroupFactory::createEmpty($this->exface, EXF_LOGICAL_AND, $this->getMetaObject());
$this->cols = new DataColumnList($this->exface, $this);
$this->aggregation_columns = new DataAggregationList($this->exface, $this);
$this->sorters = new DataSorterList($this->exface, $this);
// IDEA Can we use the generic EntityListFactory here or do we need a dedicated factory for subsheet lists?
$this->subsheets = new DataSheetList($this->exface, $this);
}
/**
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::addRows()
*/
public function addRows(array $rows, bool $merge_uid_dublicates = false, bool $auto_add_columns = true) : DataSheetInterface
{
foreach ($rows as $row) {
$this->addRow($row, $merge_uid_dublicates, $auto_add_columns);
}
return $this;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::addRow()
*/
public function addRow(array $row, bool $merge_uid_dublicates = false, bool $auto_add_columns = true, int $index = null) : DataSheetInterface
{
if (! empty($row)) {
// Compare the keys of the row with column names. If there are row keys, that are NOT column names, we
// should do something!
// - We can assume, that the key is actually an expression, that produces a different column name, so
// we can check if the key matches the expression of any column.
// - We can add a new column if allowed by $auto_add_columns. But be careful: that column could actually
// also have a column name, that differs from the key if the latter has forbidden characters
$colExprMap = $this->getColumns()->getColumnsExpressions();
foreach (array_diff(array_keys($row), array_keys($colExprMap)) as $missingKey) {
// Check if there is column, where the expression matches the array key. If so, use that
if (false === $colName = array_search($missingKey, $colExprMap, true)) {
// If the column does not exist, add it unless explicitly forbidden
$colName = null;
if ($auto_add_columns === true) {
$col = $this->getColumns()->addFromExpression($missingKey);
$colName = $col->getName();
}
}
// If a column is found, BUT its name is different from the key used in the row, change the key
// in the row!
if ($colName !== null && $colName !== $missingKey) {
$row[$colName] = $row[$missingKey];
unset($row[$missingKey]);
}
}
// Now actually add the row
// If we merge by UID and there is a duplicate, merge the existing UID row with the new one
if ($merge_uid_dublicates === true
&& $this->hasUidColumn() === true
&& (null !== $uid = $row[$this->getUidColumn()->getName()])
&& (false !== $uid_row_nr = $this->getUidColumn()->findRowByValue($uid))
) {
$this->rows[$uid_row_nr] = array_merge($this->rows[$uid_row_nr], $row);
} else {
// If no $index provided, append at the end of the rows array - otherwise insert in the middle
if ($index === null || is_numeric($index) === false) {
$this->rows[] = $row;
} else {
array_splice($this->rows, $index, 0, [$row]);
}
}
$this->setFresh(true);
}
return $this;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::joinLeft()
*/
public function joinLeft(DataSheetInterface $other_sheet, string $leftKeyColName = null, string $rightKeyColName = null, string $relation_path = '') : DataSheetInterface
{
// First copy the columns of the right data sheet ot the left one
$right_cols = array();
foreach ($other_sheet->getColumns() as $col) {
$right_cols[] = $col->copy();
}
$this->getColumns()->addMultiple($right_cols, RelationPathFactory::createFromString($this->getMetaObject(), $relation_path));
$leftColNamesUpdated = [];
// Now process the data and join rows
if (! is_null($leftKeyColName) && ! is_null($rightKeyColName)) {
$addedRowsCnt = 0;
foreach ($this->rows as $left_row_nr => $row) {
// foreach() iterates over a COPY of the array, so $left_row_nr will always
// be the number of the original left row! If rows are added while joining,
// it must be increasead in order to match the index of that row in the new
// data.
$left_row_nr += $addedRowsCnt;
// Check if the right column is really present in the data to be joined
if (! $rightKeyCol = $other_sheet->getColumns()->get($rightKeyColName)) {
throw new DataSheetMergeError($this, 'Cannot find right key column "' . $rightKeyColName . '" for a left join!', '6T5E849');
}
// Find rows in the other sheet, that match the currently processed key
$right_row_nrs = $rightKeyCol->findRowsByValue($row[$leftKeyColName]);
// If corresponding rows are found in the right sheet, apply their values
if (false === empty($right_row_nrs)) {
// Since we do an OUTER JOIN, there may be multiple matching rows, so we need
// to loop through them. The first row is simply joined to the current left row
// (i.e. the columns of the other sheet are appended). For subsequent rows a
// copy of the left row is created and appended right next to it, than the
// right columns are appended to this row copy.
$needRowCopy = false;
$left_row_new_nr = null;
// Make sure to get the current state of the left row instead of using $row
// because theoretically it may have been changed already
$left_row = $row;
foreach ($right_row_nrs as $right_row_nr) {
if ($needRowCopy === true) {
$left_row_new_nr = ($left_row_new_nr ?? $left_row_nr) + 1;
$this->addRow($left_row, false, false, $left_row_new_nr);
$addedRowsCnt++;
}
$right_row = $other_sheet->getRow($right_row_nr);
foreach ($right_row as $col_name => $val) {
$leftColName = RelationPath::join($relation_path, $col_name);
$leftColNamesUpdated[] = $leftColName;
$this->setCellValue($leftColName, ($left_row_new_nr ?? $left_row_nr), $val);
}
$needRowCopy = true;
}
} else {
// If the right sheet does not have corresponding rows, treat them as empty.
// BUT only if we are JOINing with a relation. If JOINing the same object,
// do not empty its values just because the right sheet did not has less data!
if ($relation_path !== '') {
foreach ($right_cols as $col) {
$leftColName = RelationPath::join($relation_path, $col->getName());
$leftColNamesUpdated[] = $leftColName;
$this->setCellValue($leftColName, $left_row_nr, null);
}
}
}
}
} elseif (is_null($leftKeyColName) && is_null($rightKeyColName)) {
// TODO this only joins the first other sheet row. A real LEFT OUT JOIN would
// need to dublicate rows as in the case above - but it's unclear, what should
// happen if there are actually no key columns...
foreach ($this->rows as $left_row_nr => $row) {
$rightRow = $other_sheet->getRow($left_row_nr);
$rightColNames = array_keys($rightRow);
$leftColNamesUpdated = array_merge($leftColNamesUpdated, $rightColNames);
$this->rows[$left_row_nr] = array_merge($row, $rightRow);
}
} else {
throw new DataSheetJoinError($this, 'Cannot join data sheets, if only one key column specified!', '6T5V0GU');
}
// Mark all columns of this sheet, that were updated while JOINing as fresh
$leftColNamesUpdated = array_unique($leftColNamesUpdated);
foreach ($leftColNamesUpdated as $leftColName) {
$leftCol = $this->getColumns()->get($leftColName);
if ($leftCol) {
$leftCol->setFresh(true);
}
}
return $this;
}
/**
*
* {@inheritdoc}
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::importRows()
*/
public function importRows(DataSheetInterface $other_sheet, bool $calculateFormulas = true) : DataSheetInterface
{
if (! $this->getMetaObject()->is($other_sheet->getMetaObject()->getAliasWithNamespace())) {
throw new DataSheetImportRowError($this, 'Cannot replace rows for object "' . $this->getMetaObject()->getAliasWithNamespace() . '" with rows from "' . $other_sheet->getMetaObject()->getAliasWithNamespace() . '": replacing rows only possible for compatible objects!', '6T5V1DR');
}
// Make sure, the UID is present in the result if it is there in the other sheet
if (! $this->getUidColumn() && $other_sheet->getUidColumn()) {
$uid_column = $other_sheet->getUidColumn()->copy();
$this->getColumns()->add($uid_column);
}
// Make sure, all columns for system attributes are copied too
foreach ($this->getMetaObject()->getAttributes()->getSystem() as $attr){
if (! $this->getColumns()->getByAttribute($attr) && $col = $other_sheet->getColumns()->getByAttribute($attr)) {
$sys_col = $col->copy();
$this->getColumns()->add($sys_col);
}
}
$columns_with_formulas = array();
foreach ($this->getColumns() as $this_col) {
// calculate formulas again, not regarding if the sheet importing to already has values
if ($this_col->isFormula() && $calculateFormulas === true) {
$columns_with_formulas[] = $this_col->getName();
continue;
}
if ($other_col = $other_sheet->getColumns()->get($this_col->getName())) {
$thisColVals = $this_col->getValues(false);
$otherColVals = $other_col->getValues(false);
// TODO probably need to copy values to rows with matching UIDs instead of relying on identical sorting here
if (count($thisColVals) > 0 && count($thisColVals) !== count($otherColVals)) {
throw new DataSheetImportRowError($this, 'Cannot replace rows of column "' . $this_col->getName() . '": source and target columns have different amount of rows!', '6T5V1XX');
}
$this_col->setValues($otherColVals);
}
// if the column is formula and still has empty values, add it to columns to be calculated again
if ($this_col->isFormula() && $this_col->hasEmptyValues()) {
$columns_with_formulas[] = $this_col->getName();
}
}
foreach ($columns_with_formulas as $name) {
$this->getColumn($name)->setValuesByExpression($this->getColumn($name)->getFormula());
}
return $this;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::getColumnValues()
*/
public function getColumnValues(string $column_name, bool $include_totals = false) : array
{
$col = array();
$rows = $include_totals ? array_merge($this->rows, $this->totals_rows) : $this->rows;
foreach ($rows as $row_nr => $row) {
$col[$row_nr] = $row[$column_name];
}
return $col;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::setColumnValues()
*/
public function setColumnValues(string $column_name, $column_values, $totals_values = null) : DataSheetInterface
{
// If the column is not yet there, add it, but make it hidden
if (! $this->getColumn($column_name)) {
$this->getColumns()->addFromExpression($column_name, null, true);
}
if (is_array($column_values)) {
if ($this->countRows() > 0 && $this->countRows() !== count($column_values)) {
throw new DataSheetRuntimeError($this, 'Cannot update ' . $this->countRows() . ' data rows with ' . count($column_values) . ' values: expecting as many values as rows or a single value to apply to all rows!');
}
// first update data rows
foreach ($column_values as $row => $val) {
$this->rows[$row][$column_name] = $val;
}
} else {
foreach ($this->rows as $nr => $row) {
$this->rows[$nr][$column_name] = $column_values;
}
}
// if totals given, update the columns totals
if ($totals_values) {
foreach ($this->totals_rows as $nt => $row) {
$this->totals_rows[$nt][$column_name] = (is_array($totals_values) ? $totals_values[$nt] : $totals_values);
}
}
// Mark the column as up to date
$this->getColumn($column_name)->setFresh(true);
return $this;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::getCellValue()
*/
public function getCellValue(string $column_name, int $row_number)
{
if ($row = $this->rows[$row_number]) {
return $row[$column_name];
} elseif ($row_number >= $this->countRows()) {
return $this->totals_rows[$row_number - $this->countRows()][$column_name];
}
return null;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::setCellValue()
*/
public function setCellValue(string $column_name, int $row_number, $value) : DataSheetInterface
{
// Create the column, if not already there
if (! $this->getColumn($column_name)) {
$this->getColumns()->addFromExpression($column_name);
}
// Detect, if the cell belongs to a total row
$data_row_cnt = $this->countRows();
$total_row_cnt = count($this->getTotalsRows());
if ($row_number >= $data_row_cnt && $row_number < ($data_row_cnt + $total_row_cnt)) {
$this->totals_rows[$row_number - $data_row_cnt][$column_name] = $value;
}
// Set the cell valu in the data matrix
$this->rows[$row_number][$column_name] = $value;
return $this;
}
/**
*
* {@inheritdoc}
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::getTotalValue()
*/
public function getTotalValue(string $column_name, int $row_number)
{
return $this->totals_rows[$row_number][$column_name];
}
/**
*
* @param DataColumnInterface $col
* @param \exface\Core\CommonLogic\QueryBuilder\AbstractQueryBuilder $query
*/
protected function dataReadAddColumnToQuery(DataColumnInterface $col, QueryBuilderInterface $query)
{
$sheetObject = $this->getMetaObject();
$colIsAttribute = $col->isAttribute();
// add the required attributes
foreach ($col->getExpressionObj()->getRequiredAttributes() as $attr) {
try {
$attribute = $sheetObject->getAttribute($attr);
$attribute_aggregator = DataAggregation::getAggregatorFromAlias($this->getWorkbench(), $attr);
} catch (MetaAttributeNotFoundError $e) {
continue;
}
// If the sheet does not have such a column yet, add it as a hidden column. This means, that we
// are dealing with an expression argument, that references a column, that is not explicitly
// in the sheet.
// Checking first, wether the column is a regular attribute reference, just prevents unneeded
// searching through the columns. If the column represents an attribute, it is obvious that this
// attribute is already in the sheet :)
if (! $col->getExpressionObj()->isMetaAttribute() && ! $this->getColumns()->getByExpression($attr)) {
$this->getColumns()->addFromExpression($attr, null, true);
}
// If the QueryBuilder for the current object can read the attribute, add it
if ($query->canReadAttribute($attribute)) {
// Make sure to keep custom column names for columns with attributes. In most cases, the column
// name will be the attribute alias, but it might get overwritten explicitly!
$query->addAttribute($attr, ($colIsAttribute ? $col->getName() : null));
} elseif (! $attribute->getRelationPath()->isEmpty()) {
// If the query builder cannot read the attribute, make a subsheet and ultimately a separate query.
// To create a subsheet we need to split the relation path to the current attribute into the part
// leading to the foreign key in the main data source and the part in the next data source.
// We always split into two parts by the first data source border: if there are more data sources
// involved, the subsheet will take care of splitting the rest of the path.
// Here is an example: Concider comparing turnover between the point-of-sale system and
// the backend ERP. Each system shall have stores and their turnover in different data bases:
// TURNOVER<-POS->FLOOR->POS_STORE<->ERP_STORE<-ERP_STATS->TURNOVER.
// One way to make the comparison would be creating a data sheet for the POS object with one of
// the columns being FLOOR__POS_STORE__ERP_STORE__ERP_STATS__TURNOVER. This relation path will need to be split
// into FLOOR__POS_STORE__STORE_ID and ERP_STORE__ERP_STATS__TURNOVER. The first path will make
// sure, the main sheet will have a key to join the subsheet afterwards, while the second part will
// become on of the subsheet columns.
// In the following code, this example would result in a subsheet based on the object ERP_STORE with
// two columns: ID (of the ERP_STORE) and ERP_STATS__TURNOVER.
// IDEA This will probably not work, if the relation path returns to some attribute of the initial data source. Is it possible at all?!
/* @var $relPathToSubsheet \exface\Core\Interfaces\Model\MetaRelationPathInterface
* In the above example, this would be FLOOR__POS_STORE__ERP_STORE
*/
$relPathToSubsheet = null;
/* @var $relPathInParentSheet \exface\Core\Interfaces\Model\MetaRelationPathInterface
* In the above example, this would be FLOOR__POS_STORE
*/
$relPathInParentSheet = RelationPathFactory::createForObject($sheetObject);
/* @var $relPathInSubsheet \exface\Core\Interfaces\Model\MetaRelationPathInterface
* In the above example, this would be ERP_STATS
*/
$relPathInSubsheet = null;
// Loop through the relations in the path to the target attribute, to find the
// data source border.
/* @var $lastRelPath \exface\Core\Interfaces\Model\MetaRelationPathInterface */
$lastRelPath = RelationPathFactory::createForObject($sheetObject);
foreach ($attribute->getRelationPath()->getRelations() as $rel) {
$relPath = $lastRelPath->copy()->appendRelation($rel);
$relRightKey = $relPath->getAttributeOfEndObject($relPath->getRelationLast()->getRightKeyAttribute()->getAlias());
if (true === $query->canRead($relRightKey->getAliasWithRelationPath())) {
$relPathInParentSheet->appendRelation($rel);
} else {
if ($relPathToSubsheet === null) {
// Remember the path to the relation to the object of the other query
$relPathToSubsheet = $relPath->copy();
$relPathInSubsheet = RelationPathFactory::createForObject($relPathToSubsheet->getEndObject());
} else {
// All path parts following the one to the other data source, go into the subsheet
$relPathInSubsheet->appendRelation($rel);
}
}
$lastRelPath = $relPath;
}
// Determine the attribute alias for the subsheet
// Also find out if we will need to aggregate the subsheet
$subsheetAttributeAlias = $relPathInSubsheet->getAttributeOfEndObject($attribute->getAlias())->getAliasWithRelationPath();
if ($attribute_aggregator) {
$subsheetAttributeAlias = DataAggregation::addAggregatorToAlias($subsheetAttributeAlias, $attribute_aggregator);
// If the attribute, we are looking for has an aggregator, we need to aggregate
// the subsheet over the key, that we are going to use for our join later on.
$needGroup = true;
} else {
$needGroup = false;
}
// Create a subsheet for the relation if not yet existent and add the required attribute
// NOTE: if we have multiple attributes to join via the same relation, we need to do it separately for
// those with aggregations and those without. Aggregated subsheets will not be able to read non-aggregated
// attributes. On the other hand, we can't aggregate the automatically as we do not really know, what this
// will mean for the specific data.
$subsheetId = $relPathToSubsheet->toString() . ($needGroup ? ':GROUPED' : '');
if (! $subsheet = $this->getSubsheets()->get($subsheetId)) {
$parentSheetKeyAlias = $relPathInParentSheet->getAttributeOfEndObject($relPathToSubsheet->getRelationLast()->getLeftKeyAttribute()->getAlias())->getAliasWithRelationPath();
$parentSheetKeyAttr = $sheetObject->getAttribute($parentSheetKeyAlias);
$subsheetObj = $relPathToSubsheet->getEndObject();
$subsheetKeyAlias = $relPathToSubsheet->getRelationLast()->getRightKeyAttribute()->getAlias();
// If the attribute being loaded is aggregated, there are different case to treat depending on
// where exactly the aggregation needs to be done: in the subsheet only or in both sheets.
// Concider the following two examples for an app with a `DEPARTMENT` object, that references
// a core `USER_ROLE` (thus, all members of that role are seen as department members) and a `COMPANY`
// inside the app itself.
// - if the rows of the parent sheet do not need to be aggregated, we can leave it as-is and will
// have a single foreign key per row. This is the case, if the relation path in the parent sheet
// only has forward relations. This guarantees, that each row will only have at most one key for
// the future JOIN. In the above example this would happen if we list all employees of a departnemnt
// via `DEPARTMENT__USER_ROLE__USER__USERNAME:LIST`. The parent sheet will have `DEPARTMENT__USER_ROLE`,
// which is one per department. The aggregation will only take place in the subsheet, where all users
// per role will be listed.
// - otherwise the parent sheet rows will need to be grouped too. Thus, we need to define an aggregator
// for the key expressions on both sides. We will use the non-distinct LIST aggreator to make sure,
// the list contains as many items as there were rows - even if some rows had the same key values.
// In the above example that would be the case if listing all employees for an entire company:
// `COMPANY__DEPARTMENT__USER_ROLE__USER__USERNAME`. The parent sheet would have `COMPANY__DEPARTMENT`,
// which contains a reverse relation from department to company and thus, would need to be aggregated
// too.
$groupedKeys = $parentSheetKeyAttr && $parentSheetKeyAttr->isRelated() && $parentSheetKeyAttr->getRelationPath()->containsReverseRelations() ? true : false;
if ($groupedKeys === true) {
$groupedKeysAggr = AggregatorFunctionsDataType::LIST_ALL . '(,)';
$parentSheetKeyAlias = DataAggregation::addAggregatorToAlias($parentSheetKeyAlias, $groupedKeysAggr);
$subsheetKeyAlias = DataAggregation::addAggregatorToAlias($subsheetKeyAlias, $groupedKeysAggr);
// Now, that we know, the JOIN key is an aggregation itself, we can't group the subsheet by it.
// Simply because it is not an attribute.
$needGroup = false;
}
$subsheet = DataSheetFactory::createSubsheet($this, $subsheetObj, $subsheetKeyAlias, $parentSheetKeyAlias, $relPathToSubsheet);
$this->getSubsheets()->add($subsheet, $subsheetId);
// Add the foreign key to the main query
// If the foreign key is calculated, add all attributes required to the query, otherwise just add
// the attribute itself
if (null !== $parentSheetKeyExpr = $parentSheetKeyAttr->getCalculationExpression()) {
foreach ($parentSheetKeyExpr->getRequiredAttributes() as $alias) {
$query->addAttribute($alias);
}
} else {
$query->addAttribute($parentSheetKeyAlias);
}
// Also add the foreign key to this sheet
// IDEA do we need to add the column to the sheet? This is just useless data...
// Additionally it would make trouble when the column has formatters...
$this->getColumns()->addFromExpression($parentSheetKeyAlias, null, true);
}
// Add the current attribute to the subsheet prefixing it with it's relation path relative to the subsheet's object
$subsheet->getColumns()->addFromExpression($subsheetAttributeAlias);
// Add the related object key alias of the relation to the subsheet to that subsheet. This will be the right key in the future JOIN.
$subsheet->getColumns()->addFromExpression($subsheet->getJoinKeyAliasOfSubsheet());
// Aggregate of the right key of the future JOIN if there are attributes, that need aggregation
if ($needGroup === true) {
$subsheet->getAggregations()->addFromString($subsheet->getJoinKeyAliasOfSubsheet());
}
} else {
throw new DataSheetReadError($this, 'QueryBuilder "' . get_class($query) . '" cannot read attribute "' . $attribute->getAliasWithRelationPath() . '" of object "' . $attribute->getObject()->getAliasWithNamespace() .'"!');
}
if ($attribute->hasCalculation()) {
foreach ($attribute->getCalculationExpression()->getRequiredAttributes() as $req) {
if (! $this->getColumn($req)) {
$column = $this->getColumns()->addFromExpression($req, null, true);
$this->dataReadAddColumnToQuery($column, $query);
}
}
}
}
return $this;
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::dataRead()
*/
public function dataRead(int $limit = null, int $offset = null) : int
{
$thisObject = $this->getMetaObject();
if (is_null($limit)) {
$limit = $this->getRowsLimit();
}
if (is_null($offset)) {
$offset = $this->getRowsOffset();
}
$eventBefore = $this->getWorkbench()->eventManager()->dispatch(new OnBeforeReadDataEvent($this, $limit, $offset));
if ($eventBefore->isPreventRead() === true) {
return 0;
}
// Empty the data before reading
// IDEA Enable incremental reading by distinguishing between reading the same page an reading a new page
$this->removeRows();
try {
$query = $this->dataReadInitQueryBuilder($thisObject);
} catch (DataSheetReadError $dsre) {
throw $dsre;
} catch (\Throwable $e) {
throw new DataSheetReadError($this, 'Cannot initialize query builder for object ' . $thisObject->__toString() . ': ' . $e->getMessage(), null, $e);
}
// set sorting
$sorters = $this->getSorters();
// If no sorters set, add default sorters from the object, UNLESS explicitly disallowed or
// aggregated to a single line.
if ($sorters->isEmpty() && $this->getAutoSort() === true && $this->hasAggregateAll() === false) {
// Also do not add default sorters when aggregating over something
// IDEA actually it is not quite clear if and how default sorters should work with aggregators.
// Some SQL engines (like MS SQL) require sorted column to be in the SELECT or GROUP BY,
// others sorte before doint the aggregation. For now, we just don't apply default sorters when
// aggregating, but in future we might check if the sorted columns are being read and apply the
// sorters then.
if ($this->hasAggregations() === false) {
$sorters = $this->getMetaObject()->getDefaultSorters();
}
}
$postprocessorSorters = new DataSorterList($this->getWorkbench(), $this);
foreach ($sorters as $sorter) {
// If the sorter can be applied by the query, pass it to the query, otherwise
// save it for a runtime sort after reading the data.
if (! $query->canReadAttribute($thisObject->getAttribute($sorter->getAttributeAlias()))) {
$postprocessorSorters->add($sorter);
} else {
if (! $postprocessorSorters->isEmpty()) {
throw new DataSheetReadError($this, 'Cannot apply sorter ' . $sorter . ' after ' . $postprocessorSorters->getLast() . ', because the latter cannot be performed by the data source and, thus, must be applied after reading data.');
}
$query->addSorter($sorter->getAttributeAlias(), $sorter->getDirection());
}
}
if ($limit > 0) {
$query->setLimit($limit, $offset);
}
try {
$result = $query->read($thisObject->getDataConnection());
} catch (\Throwable $e) {
throw new DataSheetReadError($this, $e->getMessage(), null, $e);
}
$this->addRows($result->getResultRows());
$this->totals_rows = $result->getTotalsRows();
$this->total_row_count = $result->getAllRowsCounter();
$this->dataSourceHasMoreRows = $result->hasMoreRows();
// load data for subsheets if needed
if ($this->isEmpty() === false) {
foreach ($this->getSubsheets() as $subsheet) {
// Add filter over parent keys
$parentSheetKeyCol = $subsheet->getJoinKeyColumnOfParentSheet();
// If the foreign key column is calculated, do the calculation first!
if (null !== $parentSheetKeyExpr = $parentSheetKeyCol->getAttribute()->getCalculationExpression()) {
$this->setColumnValues($parentSheetKeyCol->getName(), $parentSheetKeyExpr->evaluate($this));
}
if ($subsheet->getJoinKeyColumnOfSubsheet()->isAttribute() && $subsheet->getJoinKeyColumnOfSubsheet()->getAttribute()->isReadable() === false) {
throw new DataSheetJoinError($this, 'Cannot join subsheet based on object "' . $subsheet->getMetaObject()->getName() . '" to data sheet of "' . $this->getMetaObject()->getName() . '": the subsheet\'s key column attribute "' . $subsheet->getJoinKeyColumnOfSubsheet()->getAttribute()->getName() . '" is not readable!');
}
// Let the subsheet inherit all the filters of this sheet that apply to
// the subsheet's object (= start with the relation path to the subsheet)
// Do this before adding the foreign-key filter as this operation __replaces__
// all subsheet filters.
$subsheetRelPath = $subsheet->getRelationPathFromParentSheet()->toString();
$subsheet->setFilters($this->getFilters()->rebase($subsheetRelPath, function(ConditionInterface $condition) use ($subsheetRelPath) {
return StringDataType::startsWith($condition->getAttributeAlias(), $subsheetRelPath . RelationPath::RELATION_SEPARATOR);
}));
// Add a subsheet-filter over the UIDs of this sheet for the later JOIN
$foreignKeys = array_unique($parentSheetKeyCol->getValues(false));
$foreignKeys = array_filter($foreignKeys, function($val) {
return $val !== '' && $val !== null;
});
// Stop here if there are no foreign key - we won't be able to JOIN anything!
if (empty($foreignKeys)) {
continue;
}
// Otherwise add an IN-filter for foreign keys
$foreignKeysUidAlias = DataAggregation::stripAggregator($subsheet->getJoinKeyAliasOfSubsheet());
$foreignKeysUidAttr = $subsheet->getMetaObject()->getAttribute($foreignKeysUidAlias);
$subsheet->getFilters()->addConditionFromString($foreignKeysUidAlias, implode($foreignKeysUidAttr->getValueListDelimiter(), $foreignKeys), EXF_COMPARATOR_IN);
// Do not sort subsheets and do not count data in data source!
$subsheet->setAutoSort(false);
$subsheet->setAutoCount(false);
// Read data
$subsheet->dataRead();
// Do the JOIN
$this->joinLeft($subsheet, $parentSheetKeyCol->getName(), $subsheet->getJoinKeyColumnOfSubsheet()->getName(), ($subsheet->hasRelationToParent() ? $subsheet->getRelationPathFromParentSheet()->toString() : ''));
}
}
// Look for columns, that need calculation and perform that calculation
foreach ($this->getColumns() as $name => $col) {
switch (true) {
case $col->getExpressionObj()->isFormula() === true:
case $col->getExpressionObj()->isStatic() === true:
$expr = $col->getExpressionObj();
break;
case $col->isAttribute() && $col->getAttribute()->hasCalculation():
$expr = $col->getAttribute()->getCalculationExpression();
break;
default:
continue 2;
}
try {
$vals = $expr->evaluate($this);
} catch (Throwable $e) {
throw new DataSheetReadError($this, $e->getMessage(), null, $e);
}
if (is_array($vals)) {
// See if the expression returned more results, than there were rows. If so, it was also performed on
// the total rows. In this case, we need to slice them off and pass to set_column_values() separately.
// This only works, because evaluating an expression cannot change the number of data rows! This justifies
// the assumption, that any values after count_rows() must be total values.
if ($this->countRows() < count($vals)) {
$totals = array_slice($vals, $this->countRows());
$vals = array_slice($vals, 0, $this->countRows());
}
}
$this->setColumnValues($name, $vals, $totals);
}
if (! $postprocessorSorters->isEmpty()) {
if ($this->isPaged() === true) {
throw new DataSheetReadError($this, 'Cannot sort by columns from different data sources when using pagination: either increase page length or filter data to fit on one page!');
}
$this->sort($postprocessorSorters);
}
// Read nested data
foreach ($this->getColumns() as $col) {
if (null === $col->getNestedDataTemplateUxon()) {
continue;
}
$this->dataReadNestedSheet($col);
}
$this->getWorkbench()->eventManager()->dispatch(new onReadDataEvent(
$this,
null,
0,
$result->getAffectedRowsCounter()
));
return $result->getAffectedRowsCounter();
}
protected function dataReadInitQueryBuilder(MetaObjectInterface $object) : QueryBuilderInterface
{
if ($object->isReadable() === false) {
throw new DataSheetReadError($this, 'Cannot read data for object ' . $object->getAliasWithNamespace() . ': object is marked as not readable in model!', '73H79S1');
}
// create new query for the main object
$query = QueryBuilderFactory::createForObject($object);
foreach ($this->getColumns() as $col) {
if ($col->getExpressionObj()->isMetaAttribute() === true && $col->getAttribute()->isReadable() === false) {
continue;
}
$this->dataReadAddColumnToQuery($col, $query);
foreach ($col->getTotals()->getAll() as $row => $total) {
$query->addTotal($col->getAttributeAlias(), $total->getAggregator(), $row);
}
}
// Ensure, the columns with system attributes are always in the select if a row represents a
// single UID. Adding system attributes does not make sense for aggregated rows as it is
// unclear, how they should be aggregated.
//
// FIXME With growing numbers of behaviors and system attributes, this becomes a pain, as more and more possibly
// aggregated columns are added automatically - even if the sheet is only meant for reading. Maybe we should let
// the code creating the sheet add the system columns. The behaviors will prduce errors if this does not happen anyway.
if ($this->hasAggregateAll() === false) {
foreach ($object->getAttributes()->getSystem()->getAll() as $attr) {
if (! $this->getColumns()->getByAttribute($attr)) {
// Check if the system attribute has a default aggregator if the data sheet is being aggregated
if ($this->hasAggregations() && $attr->getDefaultAggregateFunction()) {
$col = $this->getColumns()->addFromExpression($attr->getAlias() . DataAggregation::AGGREGATION_SEPARATOR . $attr->getDefaultAggregateFunction(), null, true);
} else {
$col = $this->getColumns()->addFromAttribute($attr, true);
}
$this->dataReadAddColumnToQuery($col, $query);
}
}
}
// Look for conditions based on related expressions that cannot be read by the query and try to get
// their values here by reading them separately.
$foreignConditions = [];
foreach ($this->getFilters()->getConditionsRecursive() as $cond) {
if ($cond->getExpression()->isMetaAttribute()) {
$condAttr = $cond->getExpression()->getAttribute();
if (! $condAttr->getRelationPath()->isEmpty() && ! $query->canReadAttribute($condAttr)) {
$foreignConditions[] = $cond;
}
}
}
// If there are no foreign conditions, just pass the filters of the data sheet to the query.
// If foreign conditions are found, replace them with IN conditions on the foreign key in this
// object (the relations left key attribute) having explicit key values. These key values
// are read separately in the foreach() below. This should even work for relations over multiple
// data sources as the $condDS might again use this technique resolve its foreign conditions, etc.
if (empty($foreignConditions)) {
$queryFilters = $this->getFilters();
} else {
$queryFilters = $this->getFilters()->copy();
foreach ($foreignConditions as $foreignCond) {
/* @var $cond \exface\Core\CommonLogic\Model\Condition */
foreach ($queryFilters->getConditionsRecursive() as $cond) {
if ($cond->exportUxonObject()->toArray() === $foreignCond->exportUxonObject()->toArray()) {
if ($foreignCond->isEmpty()) {
$queryFilters->removeCondition($cond);
}
$condAttr = $cond->getExpression()->getAttribute();
$condRelPath = $condAttr->getRelationPath();
if (! $condRelPath->isEmpty()) {
$condRel = $condRelPath->getRelationFirst();
$condDS = DataSheetFactory::createFromObject($condRel->getRightObject());
$condCol = $condDS->getColumns()->addFromAttribute($condRel->getRightKeyAttribute());
$condDS->getFilters()->addConditionFromExpression($cond->getExpression()->rebase($condRel->getAliasWithModifier()), $cond->getValue(), $cond->getComparator());
$condDS->dataRead();
$newCond = ConditionFactory::createFromAttribute($condRel->getLeftKeyAttribute(), implode($condAttr->getValueListDelimiter(), array_filter(array_unique($condCol->getValues()))), ComparatorDataType::IN);
if ($newCond->getExpression()->getAttribute()->isFilterable() === false) {
throw new DataSheetReadError($this, 'Cannot use corss-data-source filter "' . $cond->toString() . '" for object ' . $this->getMetaObject()->__toString() . ': the foreign key ' . $newCond->getExpression()->getAttribute()->getAliasWithRelationPath() . ' is not filterable according to the metamodel!');
}
$queryFilters->replaceCondition($cond, $newCond);
}
}
}
}
}
// Set explicitly defined filters
$query->setFiltersConditionGroup($queryFilters);
// Add filters from the contexts
try {
foreach ($this->exface->getContext()->getScopeApplication()->getFilterContext()->getConditions($object) as $cond) {
$query->addFilterCondition($cond);
}
} catch (ContextAccessDeniedError $e) {
// ignore if access to context denied
}
// set aggregations
foreach ($this->getAggregations() as $aggr) {
if (! $query->canReadAttribute($object->getAttribute($aggr->getAttributeAlias()))) {
throw new DataSheetReadError($this, 'Cannot apply aggregation "' . $aggr->getAttributeAlias() . '": Aggregations over attributes in other data sources, than the man sheet object are currently not supported!');
}
$query->addAggregation($aggr->getAttributeAlias());
}
return $query;
}
protected function dataReadNestedSheet(DataColumnInterface $column) : int
{
if (! $column->isNestedData()) {
throw new InvalidArgumentException('Cannot read nested data for data sheet column "' . $column->getName() . '": invalid column data type "' . $column->getDataType()->getAliasWithNamespace() . '"! Expecting type "exface.Core.DataSheet" or a derivative!');
}
$relPathToNestedSheet = RelationPathFactory::createFromString($this->getMetaObject(), $column->getAttributeAlias());
$relPathFromNestedSheet = $relPathToNestedSheet->reverse();
$relThisSheetKeyAttr = $relPathFromNestedSheet->getRelationLast()->getRightKeyAttribute();
$relThisSheetKeyCol = $this->getColumns()->getByAttribute($relThisSheetKeyAttr);
if (! $relThisSheetKeyCol) {
throw new DataSheetWriteError($this, 'Cannot read nested data - missing key value in main data sheet!');
}
// Instantiate a subsheet from the value
$nestedSheet = DataSheetFactory::createSubsheetFromUxon(
$this, // parent
$column->getNestedDataTemplateUxon(), // subsheet UXON
$relPathFromNestedSheet->toString(), // JOIN key alias in subsheet
$relThisSheetKeyCol->getAttributeAlias(), // JOIN key alias in parent
$relPathToNestedSheet //relation path from parent sheet to nested sheet
);
// Add a column with the relation to the parent sheet
if (! $relNestedSheetCol = $nestedSheet->getColumns()->getByExpression($relPathFromNestedSheet->toString())) {
$relNestedSheetCol = $nestedSheet->getColumns()->addFromExpression($relPathFromNestedSheet->toString());
}
$filterVals = array_unique($relThisSheetKeyCol->getValues());
$nestedSheet->getFilters()->addConditionFromValueArray($relPathFromNestedSheet->toString(), $filterVals);
$counter = $nestedSheet->dataRead();
foreach ($relThisSheetKeyCol->getValues() as $rowIdx => $thisSheetKey) {
$rowIdxs = $relNestedSheetCol->findRowsByValue($thisSheetKey);
$rows = $nestedSheet->getRowsByIndex($rowIdxs);
$column->setValue($rowIdx, [
'oId' => $nestedSheet->getMetaObject()->getId(),
'rows' => array_values($rows)
]);
}
return $counter;
}
public function countRows() : int
{
return count($this->rows);
}
/**
*
* {@inheritdoc}
*
* @see \exface\Core\Interfaces\DataSheets\DataSheetInterface::dataSave()
*/
public function dataSave(DataTransactionInterface $transaction = null) : int
{
if ($this->hasUidColumn(false) === true) {
return $this->dataUpdate(true, $transaction);
} else {
return $this->dataCreate(true, $transaction);
}