@quillsql/react 2.13.22 → 2.13.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/cjs/ChartBuilder.d.ts +7 -3
  2. package/dist/cjs/ChartBuilder.d.ts.map +1 -1
  3. package/dist/cjs/ChartBuilder.js +36 -19
  4. package/dist/cjs/ReportBuilder.d.ts.map +1 -1
  5. package/dist/cjs/ReportBuilder.js +183 -233
  6. package/dist/cjs/SQLEditor.js +12 -10
  7. package/dist/cjs/components/Dashboard/DataLoader.d.ts.map +1 -1
  8. package/dist/cjs/components/QuillTable.d.ts +2 -1
  9. package/dist/cjs/components/QuillTable.d.ts.map +1 -1
  10. package/dist/cjs/components/QuillTable.js +5 -2
  11. package/dist/cjs/components/ReportBuilder/AddSortPopover.d.ts +1 -2
  12. package/dist/cjs/components/ReportBuilder/AddSortPopover.d.ts.map +1 -1
  13. package/dist/cjs/components/ReportBuilder/AddSortPopover.js +1 -2
  14. package/dist/cjs/components/ReportBuilder/convert.d.ts +1 -1
  15. package/dist/cjs/components/ReportBuilder/convert.d.ts.map +1 -1
  16. package/dist/cjs/components/ReportBuilder/convert.js +31 -4
  17. package/dist/cjs/components/ReportBuilder/util.js +1 -1
  18. package/dist/cjs/components/UiComponents.d.ts +3 -2
  19. package/dist/cjs/components/UiComponents.d.ts.map +1 -1
  20. package/dist/cjs/components/UiComponents.js +6 -3
  21. package/dist/cjs/utils/astFilterProcessing.d.ts.map +1 -1
  22. package/dist/cjs/utils/astFilterProcessing.js +921 -1604
  23. package/dist/cjs/utils/astProcessing.d.ts +1 -1
  24. package/dist/cjs/utils/astProcessing.d.ts.map +1 -1
  25. package/dist/cjs/utils/astProcessing.js +4 -2
  26. package/dist/cjs/utils/constants.d.ts.map +1 -1
  27. package/dist/cjs/utils/constants.js +2 -2
  28. package/dist/cjs/utils/logging.js +1 -1
  29. package/dist/cjs/utils/pivotConstructor.js +2 -2
  30. package/dist/cjs/utils/queryConstructor.js +2 -2
  31. package/dist/cjs/utils/report.d.ts.map +1 -1
  32. package/dist/cjs/utils/report.js +1 -1
  33. package/dist/esm/ChartBuilder.d.ts +7 -3
  34. package/dist/esm/ChartBuilder.d.ts.map +1 -1
  35. package/dist/esm/ChartBuilder.js +36 -19
  36. package/dist/esm/ReportBuilder.d.ts.map +1 -1
  37. package/dist/esm/ReportBuilder.js +190 -238
  38. package/dist/esm/SQLEditor.js +12 -10
  39. package/dist/esm/components/Dashboard/DataLoader.d.ts.map +1 -1
  40. package/dist/esm/components/QuillTable.d.ts +2 -1
  41. package/dist/esm/components/QuillTable.d.ts.map +1 -1
  42. package/dist/esm/components/QuillTable.js +5 -2
  43. package/dist/esm/components/ReportBuilder/AddSortPopover.d.ts +1 -2
  44. package/dist/esm/components/ReportBuilder/AddSortPopover.d.ts.map +1 -1
  45. package/dist/esm/components/ReportBuilder/AddSortPopover.js +1 -2
  46. package/dist/esm/components/ReportBuilder/convert.d.ts +1 -1
  47. package/dist/esm/components/ReportBuilder/convert.d.ts.map +1 -1
  48. package/dist/esm/components/ReportBuilder/convert.js +31 -4
  49. package/dist/esm/components/ReportBuilder/util.js +1 -1
  50. package/dist/esm/components/UiComponents.d.ts +3 -2
  51. package/dist/esm/components/UiComponents.d.ts.map +1 -1
  52. package/dist/esm/components/UiComponents.js +6 -3
  53. package/dist/esm/utils/astFilterProcessing.d.ts.map +1 -1
  54. package/dist/esm/utils/astFilterProcessing.js +921 -1604
  55. package/dist/esm/utils/astProcessing.d.ts +1 -1
  56. package/dist/esm/utils/astProcessing.d.ts.map +1 -1
  57. package/dist/esm/utils/astProcessing.js +4 -2
  58. package/dist/esm/utils/constants.d.ts.map +1 -1
  59. package/dist/esm/utils/constants.js +2 -2
  60. package/dist/esm/utils/logging.js +1 -1
  61. package/dist/esm/utils/pivotConstructor.js +2 -2
  62. package/dist/esm/utils/queryConstructor.js +2 -2
  63. package/dist/esm/utils/report.d.ts.map +1 -1
  64. package/dist/esm/utils/report.js +1 -1
  65. package/package.json +1 -1
@@ -97,7 +97,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
97
97
  const [selectedOrderedColumns, setSelectedOrderedColumns] = (0, react_1.useState)([]);
98
98
  const [activeQuery, setActiveQuery] = (0, react_1.useState)('');
99
99
  const [, setActiveEditItem] = (0, react_1.useState)(null);
100
- const [activePath, setActivePath] = (0, react_1.useState)(null);
101
100
  const [openPopover, setOpenPopover] = (0, react_1.useState)(null);
102
101
  const [loading, setLoading] = (0, react_1.useState)(!!initialTableName);
103
102
  const [isChartBuilderOpen, setIsChartBuilderOpen] = (0, react_1.useState)(false);
@@ -105,6 +104,8 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
105
104
  const [dataDisplayed, setDataDisplayed] = (0, react_1.useState)(false);
106
105
  const [rows, setRows] = (0, react_1.useState)([]);
107
106
  const [filteredRows, setFilteredRows] = (0, react_1.useState)([]);
107
+ const [filteredRowCount, setFilteredRowCount] = (0, react_1.useState)(0);
108
+ const [filteredTableIsLoading, setFilteredTableIsLoading] = (0, react_1.useState)(false);
108
109
  const [chartBuilderInFilteredPreview, setChartBuilderInFilteredPreview] = (0, react_1.useState)(true);
109
110
  const [formattedRows, setFormattedRows] = (0, react_1.useState)([]);
110
111
  const [columns, setColumns] = (0, react_1.useState)([]);
@@ -280,7 +281,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
280
281
  setSelectedColumns([]);
281
282
  setActiveQuery('');
282
283
  setActiveEditItem(null);
283
- setActivePath(null);
284
284
  setOpenPopover(null);
285
285
  setLoading(false);
286
286
  setDataDisplayed(false);
@@ -401,7 +401,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
401
401
  });
402
402
  const data = await response.json();
403
403
  setActiveQuery(data.query);
404
- fetchFilteredRows(data.query);
405
404
  if (fetchData) {
406
405
  fetchReportFromASTHelper(ast, formData);
407
406
  }
@@ -541,166 +540,35 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
541
540
  (0, react_1.useEffect)(() => {
542
541
  onSchemaChange();
543
542
  }, [schemaData.schema, initialTableName, reportId]);
544
- const updateFormData = (updates, { isDeletion = false, isInsertion = false, isReplaceSubtree = false, isAddVariant = false, isDeleteVariant = false, topLevelBinOp = 'OR', isCondition = undefined, }) => {
545
- // Function to immutably update or delete nodes based on their path
546
- // TODO: fix the following horible code
547
- updates.forEach(({ path, value }) => {
548
- const globalPath = [
549
- (activePath ?? isDeletion) ? path : '',
550
- isDeletion || isReplaceSubtree ? '' : path,
551
- ]
552
- .filter(Boolean)
553
- .join('.');
554
- const paths = globalPath.split('.').filter((p) => p);
555
- if (paths.length === 0 && !isInsertion && !isReplaceSubtree) {
556
- setFormData(null);
557
- const newAst = (0, util_1.deepCopy)({
558
- ...constants_1.defaultAST,
559
- ...baseAst,
560
- ...(!baseAst?.columns && {
561
- columns: (0, astProcessing_1.getAllPossibleColumns)(baseAst, schemaData.schema).map((c) => {
562
- const newColumn = (0, util_1.deepCopy)(constants_1.defaultColumn);
563
- newColumn.expr.column = c.field;
564
- return newColumn;
565
- }),
566
- }),
567
- ...(!baseAst?.from && {
568
- from: [{ ...constants_1.defaultTable, table: initialTableName }],
569
- }),
570
- where: null,
571
- });
572
- setBaseAst(newAst);
573
- fetchSqlQuery(newAst, null);
574
- return;
575
- }
576
- if (!formData && isInsertion) {
577
- const newAst = (0, util_1.deepCopy)({
578
- ...constants_1.defaultAST,
579
- ...baseAst,
580
- ...(!baseAst?.columns && {
581
- columns: (0, astProcessing_1.getAllPossibleColumns)(baseAst, schemaData.schema).map((c) => {
582
- const newColumn = (0, util_1.deepCopy)(constants_1.defaultColumn);
583
- newColumn.expr.column = c.field;
584
- return newColumn;
585
- }),
586
- }),
587
- ...(!baseAst?.from && {
588
- from: [{ ...constants_1.defaultTable, table: initialTableName }],
589
- }),
590
- where: value,
591
- });
592
- setFormData(value);
593
- setBaseAst(newAst);
594
- fetchSqlQuery(newAst, value);
595
- return;
596
- }
597
- let newState = (0, util_1.deepCopy)(formData);
598
- let current = newState;
599
- let parent = null;
600
- let parentKey = null;
601
- for (let i = 0; i < paths.length - 1; i++) {
602
- if (current[paths[i]]) {
603
- parent = current;
604
- parentKey = paths[i];
605
- current = current[paths[i]];
606
- }
607
- }
608
- const lastKey = paths[paths.length - 1];
609
- if (isDeletion) {
610
- if (lastKey === 'left' || lastKey === 'right') {
611
- if (parent) {
612
- if (lastKey === 'right') {
613
- parent[parentKey] = parent[parentKey].left;
614
- }
615
- else {
616
- parent[parentKey] = parent[parentKey].right;
617
- }
618
- }
619
- else {
620
- delete current[lastKey];
621
- if (newState?.left && !newState?.right) {
622
- newState = newState.left;
623
- }
624
- else if (newState?.right && !newState?.left) {
625
- newState = newState.right;
626
- }
627
- }
628
- }
629
- }
630
- else if (isInsertion) {
631
- newState = {
632
- type: 'binary_expr',
633
- operator: topLevelBinOp,
634
- isCondition: isCondition,
635
- left: newState,
636
- right: value,
637
- };
638
- }
639
- else if (isAddVariant) {
640
- const newVariant = (0, util_1.deepCopy)(constants_1.defaultVariant);
641
- if (value) {
642
- newVariant.args.value[0].value = value;
643
- // if there is already a single default value there,
644
- // let's remove it so when we push we replace.
645
- if (current[lastKey].length === 1 &&
646
- current[lastKey][0].args.value[0].value === '') {
647
- current[lastKey].pop();
648
- }
649
- }
650
- current[lastKey].push(newVariant);
651
- }
652
- else if (isDeleteVariant) {
653
- if (value) {
654
- const argList = current[lastKey];
655
- argList.splice(argList.findIndex((arg) => arg.args.value[0].value === name), 1);
656
- }
657
- else {
658
- current[lastKey].pop();
659
- }
660
- }
661
- else if (isReplaceSubtree) {
662
- if (lastKey) {
663
- current[lastKey] = value;
664
- }
665
- else {
666
- newState = value;
667
- }
668
- }
669
- else {
670
- if (typeof current[lastKey] === 'object' && current[lastKey] !== null) {
671
- current[lastKey].value = value;
672
- }
673
- else {
674
- current[lastKey] = value;
675
- }
676
- }
677
- setFormData(newState);
678
- const newAst = {
679
- ...constants_1.defaultAST,
680
- ...baseAst,
681
- ...(!baseAst?.columns && {
682
- columns: (0, astProcessing_1.getAllPossibleColumns)(baseAst, schemaData.schema).map((c) => {
683
- const newColumn = (0, util_1.deepCopy)(constants_1.defaultColumn);
684
- newColumn.expr.column = c.field;
685
- return newColumn;
686
- }),
687
- }),
688
- ...(!baseAst?.from && {
689
- from: [{ ...constants_1.defaultTable, table: initialTableName }],
690
- }),
691
- where: { ...newState },
543
+ // Function to handle the insertion of expressions
544
+ const handleInsertion = (value) => {
545
+ const newFilterStack = [...filterStack];
546
+ if (newFilterStack.length > 0) {
547
+ const tabNode = {
548
+ leaf: false,
549
+ operator: 'and',
550
+ leftNode: null,
551
+ rightNode: null,
692
552
  };
553
+ newFilterStack.push(tabNode);
554
+ }
555
+ const newItem = {
556
+ leaf: true,
557
+ operator: null,
558
+ leftNode: null,
559
+ rightNode: null,
560
+ value: value,
561
+ };
562
+ newFilterStack.push(newItem);
563
+ const tree = (0, filterProcessing_1.filterStackToFilterTree)(newFilterStack);
564
+ if (tree) {
565
+ const newFormData = (0, astFilterProcessing_1.filterTreeToAst)(tree, client.databaseType.toLowerCase());
566
+ setFormData(newFormData);
567
+ const newAst = { ...baseAst };
568
+ newAst.where = newFormData;
693
569
  setBaseAst(newAst);
694
- fetchSqlQuery(newAst, newState);
695
- });
696
- };
697
- // Function to handle the insertion of expressions
698
- const handleInsertion = (value, op = 'OR', isCondition = undefined) => {
699
- updateFormData([{ path: '', value }], {
700
- isInsertion: true,
701
- topLevelBinOp: op,
702
- isCondition,
703
- });
570
+ fetchSqlQuery(newAst, newFormData);
571
+ }
704
572
  };
705
573
  /**
706
574
  * Searches for the column by name and returns the field type.
@@ -740,36 +608,93 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
740
608
  }
741
609
  };
742
610
  const [previousPage, setPreviousPage] = (0, react_1.useState)(0);
611
+ const [filteredPreviousPage, setFilteredPreviousPage] = (0, react_1.useState)(0);
743
612
  const [currentProcessing, setCurrentProcessing] = (0, react_1.useState)({
744
613
  page: REPORT_BUILDER_PAGINATION,
745
614
  });
615
+ const [filteredProcessing, setFilteredProcessing] = (0, react_1.useState)({
616
+ page: paginationProcessing_1.DEFAULT_PAGINATION,
617
+ });
746
618
  const [numberOfRows, setNumberOfRows] = (0, react_1.useState)(0);
747
619
  const [rowCountIsLoading, setRowCountIsLoading] = (0, react_1.useState)(false);
748
620
  const [tableLoading, setTableLoading] = (0, react_1.useState)(false);
749
- const onPageChange = (page) => {
750
- if (currentProcessing.page &&
751
- (0, paginationProcessing_1.shouldFetchMore)(REPORT_BUILDER_PAGINATION, page, previousPage)) {
752
- const newPagination = { ...currentProcessing.page, page };
753
- const updatedProcessing = { ...currentProcessing, page: newPagination };
754
- setCurrentProcessing(updatedProcessing);
755
- handleRunQuery(updatedProcessing);
621
+ const onPageChange = (page, isFilteredRows, initiator = 'ReportBuilder') => {
622
+ const pagination = initiator === 'ReportBuilder'
623
+ ? REPORT_BUILDER_PAGINATION
624
+ : paginationProcessing_1.DEFAULT_PAGINATION;
625
+ if (isFilteredRows) {
626
+ if (filteredProcessing.page &&
627
+ (0, paginationProcessing_1.shouldFetchMore)(pagination, page, filteredPreviousPage)) {
628
+ const newPagination = { ...filteredProcessing.page, page };
629
+ const updatedProcessing = {
630
+ ...filteredProcessing,
631
+ page: newPagination,
632
+ };
633
+ setFilteredProcessing(updatedProcessing);
634
+ fetchFilteredRows(activeQuery, updatedProcessing, false);
635
+ }
636
+ if (page > filteredPreviousPage) {
637
+ setFilteredPreviousPage(page);
638
+ }
756
639
  }
757
- if (page > previousPage) {
758
- setPreviousPage(page);
640
+ else {
641
+ if (currentProcessing.page &&
642
+ (0, paginationProcessing_1.shouldFetchMore)(pagination, page, previousPage)) {
643
+ const newPagination = { ...currentProcessing.page, page };
644
+ const updatedProcessing = { ...currentProcessing, page: newPagination };
645
+ setCurrentProcessing(updatedProcessing);
646
+ handleRunQuery(updatedProcessing);
647
+ }
648
+ if (page > previousPage) {
649
+ setPreviousPage(page);
650
+ }
759
651
  }
760
652
  };
761
- const onSortChange = (sort) => {
762
- if ((0, paginationProcessing_1.shouldSortInMemory)(REPORT_BUILDER_PAGINATION, numberOfRows, !!pivot)) {
763
- return;
653
+ const onSortChange = (sort, isFilteredRows, persistSort = false) => {
654
+ // if (shouldSortInMemory(REPORT_BUILDER_PAGINATION, numberOfRows, !!pivot)) {
655
+ // return;
656
+ // }
657
+ if (isFilteredRows) {
658
+ const updatedProcessing = { page: paginationProcessing_1.DEFAULT_PAGINATION, sort };
659
+ fetchFilteredRows(activeQuery, updatedProcessing, true);
660
+ setFilteredProcessing(updatedProcessing);
661
+ setFilteredPreviousPage(0);
662
+ }
663
+ else {
664
+ const updatedProcessing = { page: REPORT_BUILDER_PAGINATION, sort };
665
+ if (persistSort) {
666
+ const newAst = { ...baseAst };
667
+ if (!newAst.orderby) {
668
+ newAst.orderby = [];
669
+ }
670
+ const existingSortIndex = newAst.orderby.findIndex((item) => (0, astFilterProcessing_1.getFieldFromExpression)(item.expr) === sort.field);
671
+ if (existingSortIndex !== -1) {
672
+ newAst.orderby[existingSortIndex] = {
673
+ expr: { type: 'column_ref', column: sort.field },
674
+ type: sort.direction.toUpperCase(),
675
+ };
676
+ }
677
+ else {
678
+ newAst.orderby.push({
679
+ expr: { type: 'column_ref', column: sort.field },
680
+ type: sort.direction.toUpperCase(),
681
+ });
682
+ }
683
+ setBaseAst((0, util_1.deepCopy)(newAst));
684
+ fetchReportFromASTHelper(newAst, newAst.where);
685
+ }
686
+ else {
687
+ handleRunQuery(updatedProcessing, true);
688
+ }
689
+ setCurrentProcessing(updatedProcessing);
690
+ setPreviousPage(0);
764
691
  }
765
- const updatedProcessing = { page: REPORT_BUILDER_PAGINATION, sort };
766
- handleRunQuery(updatedProcessing, true);
767
- setCurrentProcessing(updatedProcessing);
768
- setPreviousPage(0);
769
692
  };
770
693
  const onFilterPreviewChange = (preview) => {
771
694
  setChartBuilderInFilteredPreview(preview);
772
- // handleRunQuery(currentProcessing, true, preview);
695
+ if (preview) {
696
+ fetchFilteredRows(activeQuery);
697
+ }
773
698
  };
774
699
  const fetchRowCount = async (processing, includeFilters) => {
775
700
  if (!client || !activeQuery) {
@@ -802,38 +727,45 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
802
727
  }
803
728
  setRowCountIsLoading(false);
804
729
  };
805
- const fetchFilteredRows = async (query) => {
806
- const filteredTableInfo = await (0, tableProcessing_1.fetchResultsByQuery)(query, client, currentProcessing, schemaData.customFields, specificDashboardFilters, tempReport.dateField, true);
730
+ const fetchFilteredRows = async (query, processing, resetRows = true) => {
731
+ setFilteredTableIsLoading(true);
732
+ const filteredTableInfo = await (0, tableProcessing_1.fetchResultsByQuery)(query, client, processing ?? filteredProcessing, schemaData.customFields, specificDashboardFilters, tempReport.dateField, resetRows ? false : true);
807
733
  if (filteredTableInfo.error) {
808
734
  throw new Error(filteredTableInfo.error);
809
735
  }
810
- setFilteredRows([...filteredRows, ...filteredTableInfo.rows]);
736
+ if (resetRows) {
737
+ setFilteredRows(filteredTableInfo.rows);
738
+ }
739
+ else {
740
+ setFilteredRows((filteredRows) => [
741
+ ...filteredRows,
742
+ ...filteredTableInfo.rows,
743
+ ]);
744
+ }
745
+ if (resetRows) {
746
+ setFilteredRowCount(filteredTableInfo.rowCount ?? 0);
747
+ }
748
+ setFilteredTableIsLoading(false);
811
749
  };
812
750
  const handleRunQuery = async (processing, resetRows = false, includeFilters = false) => {
813
751
  try {
814
752
  setErrorMessage('');
815
753
  setTableLoading(true);
816
754
  const tableInfo = await (0, tableProcessing_1.fetchResultsByQuery)(activeQuery, client, processing, schemaData.customFields, undefined, undefined, true);
817
- const filteredTableInfo = await (0, tableProcessing_1.fetchResultsByQuery)(activeQuery, client, processing, schemaData.customFields, specificDashboardFilters, tempReport.dateField, true);
818
755
  if (tableInfo.error) {
819
756
  throw new Error(tableInfo.error);
820
757
  }
821
- else if (filteredTableInfo.error) {
822
- throw new Error(filteredTableInfo.error);
823
- }
824
758
  else if (tableInfo.rows.length === 0) {
825
759
  throw new Error('No data found');
826
760
  }
827
761
  fetchRowCount(processing, includeFilters);
828
762
  setCurrentProcessing(processing);
829
763
  let tempRows = [...rows, ...tableInfo.rows];
830
- let tempFilteredRows = [...filteredRows, ...filteredTableInfo.rows];
831
764
  if (resetRows) {
832
765
  tempRows = tableInfo.rows;
833
- tempFilteredRows = filteredTableInfo.rows;
766
+ setPreviousPage(0);
834
767
  }
835
768
  setRows(tempRows);
836
- setFilteredRows(tempFilteredRows);
837
769
  setFormattedRows((0, report_1.formatRowsFromReport)({ rows: tempRows, columns: tableInfo.columns }));
838
770
  setTempReport((tempReport) => ({
839
771
  ...tempReport,
@@ -916,7 +848,7 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
916
848
  const prevTable = currentTable;
917
849
  const prevOrganization = currentOrganizationId;
918
850
  setRows(reportBuilderInfo.rows);
919
- setFilteredRows(reportBuilderInfo.rows);
851
+ setPreviousPage(0);
920
852
  if (!(client.databaseType.toLowerCase() === 'bigquery') ||
921
853
  (reportBuilderInfo.rows && reportBuilderInfo.rows.length > 0)) {
922
854
  setColumns(reportBuilderInfo.columns);
@@ -945,6 +877,27 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
945
877
  setLoading(false);
946
878
  }
947
879
  setReportInfo(reportBuilderInfo.report);
880
+ const schema = curSchema ?? schemaData.schema;
881
+ const tableInfo = schema.find((tableInfo) => tableInfo.name === reportBuilderInfo?.table);
882
+ let query = reportBuilderInfo.query;
883
+ if (!query && tableInfo) {
884
+ const ast = baseAst ??
885
+ (0, astProcessing_1.createBasicSelectASTFromColumns)(tableInfo.columns, reportBuilderInfo.table);
886
+ const queryResult = await fetchSqlQuery({
887
+ ...ast,
888
+ where: curFormData,
889
+ }, curFormData, false);
890
+ if (queryResult.error) {
891
+ console.error(queryResult.error);
892
+ }
893
+ else {
894
+ query = queryResult;
895
+ setActiveQuery(queryResult);
896
+ }
897
+ }
898
+ else if (query) {
899
+ setActiveQuery(query);
900
+ }
948
901
  // fetch unique values after everything else since it is the most expensive
949
902
  if (prevTable !== reportBuilderInfo.table ||
950
903
  !(0, fast_deep_equal_1.default)(prevFormData, curFormData) ||
@@ -954,42 +907,27 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
954
907
  if (reportBuilderInfo.pivot) {
955
908
  setUnresolvedReportMessage('Processing pivot selection options...');
956
909
  }
957
- const schema = curSchema ?? schemaData.schema;
958
- const tableInfo = schema.find((tableInfo) => tableInfo.name === reportBuilderInfo?.table);
959
- if (!reportBuilderInfo.table || !tableInfo) {
960
- throw new Error('No table found;');
961
- }
962
- let query = reportBuilderInfo.query;
963
- if (!query) {
964
- const queryResult = await fetchSqlQuery({
965
- ...(0, astProcessing_1.createBasicSelectASTFromColumns)(tableInfo.columns, reportBuilderInfo.table),
966
- where: curFormData,
967
- }, curFormData, false);
968
- if (queryResult.error) {
969
- console.error(queryResult.error);
970
- }
971
- else {
972
- query = queryResult.query;
973
- }
910
+ if (!tableInfo) {
911
+ throw new Error('Table info not found');
974
912
  }
975
913
  const uniqueStrings = await (0, tableProcessing_1.getUniqueStringValues)(tableInfo.columns, reportBuilderInfo.table, client, schemaData.customFields, undefined, true, query);
976
914
  const newUnique = updateUniqueValue(uniqueStrings, reportBuilderInfo.table);
977
915
  let pivotChanged = false;
978
916
  let newPivot;
979
917
  if (reportBuilderInfo.pivot &&
980
- !isValidPivotForReport(reportBuilderInfo.pivot, newUnique)) {
918
+ !isValidPivotForReport(reportBuilderInfo.pivot, newUnique, reportBuilderInfo.table, reportBuilderInfo.columns)) {
981
919
  // try flipping row and column field
982
920
  newPivot = {
983
921
  ...reportBuilderInfo.pivot,
984
922
  rowField: reportBuilderInfo.pivot.columnField,
985
923
  columnField: reportBuilderInfo.pivot.rowField,
986
924
  };
987
- if (isValidPivotForReport(newPivot, newUnique)) {
925
+ if (isValidPivotForReport(newPivot, newUnique, reportBuilderInfo.table, reportBuilderInfo.columns)) {
988
926
  setPivot(newPivot);
989
927
  pivotChanged = true;
990
928
  setPivotHint('Flipped pivot row and column fields to maintain validity');
991
929
  }
992
- else if (isValidPivotForReport({ ...reportBuilderInfo.pivot, columnField: undefined }, newUnique)) {
930
+ else if (isValidPivotForReport({ ...reportBuilderInfo.pivot, columnField: undefined }, newUnique, reportBuilderInfo.table, reportBuilderInfo.columns)) {
993
931
  // try removing column field
994
932
  newPivot = {
995
933
  ...reportBuilderInfo.pivot,
@@ -1025,6 +963,9 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1025
963
  return { error: true, message: 'Failed to fetch', rows: [] };
1026
964
  }
1027
965
  }
966
+ else {
967
+ setLoading(false);
968
+ }
1028
969
  };
1029
970
  const fetchAstFromPromptHelper = async (overridePrompt) => {
1030
971
  let astInfo = {};
@@ -1036,7 +977,7 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1036
977
  try {
1037
978
  setLoading(true);
1038
979
  setAskAILoading(true);
1039
- astInfo = await (0, astProcessing_1.fetchAndProcessASTFromPrompt)(prompt, schemaData.schema, client, pivot, activeQuery);
980
+ astInfo = await (0, astProcessing_1.fetchAndProcessASTFromPrompt)(prompt, schemaData.schema, client, pivot, activeQuery, currentTable);
1040
981
  if (astInfo.error) {
1041
982
  throw new Error(astInfo.error);
1042
983
  }
@@ -1066,13 +1007,15 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1066
1007
  setAskAILoading(false);
1067
1008
  await fetchReportFromASTHelper(astInfo.ast, cleanAst, astInfo.pivot);
1068
1009
  };
1069
- const isValidPivotForReport = (pivot, uniqueValuesForPivot) => {
1070
- if (!pivotProcessing_1.isValidPivot) {
1010
+ const isValidPivotForReport = (pivot, uniqueValuesForPivot, reportTable, reportColumns) => {
1011
+ if (!(0, pivotProcessing_1.isValidPivot)(pivot)) {
1071
1012
  return false;
1072
1013
  }
1073
1014
  const uniqueValuesToCheck = uniqueValuesForPivot ?? uniqueValues;
1074
1015
  // check that pivot rows and columns
1075
- const possibleOptions = (0, pivotProcessing_1.getPossiblePivotFieldOptions)(columns, uniqueValuesToCheck[currentTable] ?? {});
1016
+ const pivotTable = reportTable ?? currentTable;
1017
+ const pivotColumns = reportColumns ?? columns;
1018
+ const possibleOptions = (0, pivotProcessing_1.getPossiblePivotFieldOptions)(pivotColumns, uniqueValuesToCheck[pivotTable] ?? {});
1076
1019
  if (pivot.rowField &&
1077
1020
  pivot.columnField &&
1078
1021
  pivot.rowField === pivot.columnField) {
@@ -1220,13 +1163,11 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1220
1163
  // delay onClose callback so onClick no-ops
1221
1164
  setTimeout(() => {
1222
1165
  setActiveEditItem(null);
1223
- setActivePath(null);
1224
1166
  setOpenPopover(null);
1225
1167
  }, 100);
1226
1168
  }
1227
1169
  }, title: "Select columns", children: (0, jsx_runtime_1.jsx)(AddColumnModal_1.default, { onSave: () => {
1228
1170
  setActiveEditItem(null);
1229
- setActivePath(null);
1230
1171
  setOpenPopover(null);
1231
1172
  }, orderedColumnNames: orderedColumnNames, setOrderedColumnNames: setOrderedColumnNames, selectedColumns: selectedColumns, setSelectedColumns: setSelectedColumns, isSelectedAllColumns: isSelectedAllColumns, clearAllState: clearAllState, nameToColumn: nameToColumn, baseAst: baseAst, setBaseAst: (ast) => {
1232
1173
  if (baseAst &&
@@ -1275,7 +1216,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1275
1216
  setActiveEditItem(newSubtree);
1276
1217
  }
1277
1218
  setOpenPopover('AddFilterPopover');
1278
- setActivePath('');
1279
1219
  }
1280
1220
  }, label: 'Add filter' }), (0, jsx_runtime_1.jsx)("div", { style: {
1281
1221
  position: 'relative',
@@ -1285,7 +1225,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1285
1225
  // delay onClose callback so onClick no-ops
1286
1226
  setOpenPopover(null);
1287
1227
  setTimeout(() => {
1288
- setActivePath(null);
1289
1228
  clearCheckboxes();
1290
1229
  setActiveEditItem(null);
1291
1230
  }, 300);
@@ -1293,8 +1232,7 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1293
1232
  }, popoverTitle: "Add filter", popoverChildren: (0, jsx_runtime_1.jsx)(FilterModal_1.default, { schema: schemaData.schema.find((s) => s.name === currentTable ||
1294
1233
  s.displayName === currentTable) ?? schemaData.schema[0], fieldValuesMap: fieldValuesMap, fieldValuesMapIsLoading: uniqueValuesIsLoading, onSubmitFilter: (filter) => {
1295
1234
  setOpenPopover(null);
1296
- const item = (0, astFilterProcessing_1.filterToAst)(filter, client.databaseType.toLowerCase());
1297
- handleInsertion(item, 'AND', false);
1235
+ handleInsertion(filter);
1298
1236
  }, onDeleteFilter: () => { }, ButtonComponent: ButtonComponent, SelectComponent: SelectComponent, TextInputComponent: TextInputComponent, MultiSelectComponent: MultiSelectComponent }) }) })] })] }), (0, jsx_runtime_1.jsxs)("div", { style: { width: '100%' }, children: [(0, jsx_runtime_1.jsx)(SidebarHeadingComponent, { label: "Pivot" }), (0, jsx_runtime_1.jsx)(PivotModal_1.PivotModal, { pivotRowField: pivotRowField, setPivotRowField: setPivotRowField, pivotColumnField: pivotColumnField, setPivotColumnField: setPivotColumnField, pivotValueField: pivotValueField, pivotValueField2: pivotValueField2, setPivotValueField: setPivotValueField, setPivotValueField2: setPivotValueField2, pivotAggregation: pivotAggregation, setPivotAggregation: setPivotAggregation, createdPivots: createdPivots, setCreatedPivots: setCreatedPivots, recommendedPivots: recommendedPivots, setRecommendedPivots: setRecommendedPivots, popUpTitle: pivotPopUpTitle, setPopUpTitle: setPivotPopUpTitle, selectedTable: initialTableName, SelectComponent: SelectComponent, ButtonComponent: ButtonComponent, CardComponent: CardComponent, SecondaryButtonComponent: SecondaryButtonComponent, PopoverComponent: PopoverComponent, TextComponent: TextComponent, ErrorMessageComponent: ErrorMessageComponent, PivotRowContainer: PivotRowContainer, PivotColumnContainer: PivotColumnContainer, LoadingComponent: LoadingComponent, isOpen: showPivotPopover, setIsOpen: setShowPivotPopover, showUpdatePivot: isEditingPivot, setShowUpdatePivot: setIsEditingPivot, parentRef: parentRef, data: rows, columns: columns, triggerButtonText: 'Add pivot', selectedPivotIndex: selectedPivotIndex, setSelectedPivotIndex: setSelectedPivotIndex, removePivot: () => {
1299
1237
  setPivot(null);
1300
1238
  setPivotHint('');
@@ -1377,7 +1315,7 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1377
1315
  `.${pivot.rowField}`,
1378
1316
  `.${pivot.valueField || 'count'}`,
1379
1317
  ]
1380
- : selectedColumns, setIsPending: () => { }, setEditPopoverKey: () => { }, setActiveEditItem: setActiveEditItem, setActivePath: setActivePath, setOpenPopover: setOpenPopover, SortPopover: SortPopoverComponent, EditPopover: AddSortPopover_1.AddSortPopover, handleDelete: async () => {
1318
+ : selectedColumns, setIsPending: () => { }, setEditPopoverKey: () => { }, setActiveEditItem: setActiveEditItem, setOpenPopover: setOpenPopover, SortPopover: SortPopoverComponent, EditPopover: AddSortPopover_1.AddSortPopover, handleDelete: async () => {
1381
1319
  if (!pivot) {
1382
1320
  setBaseAst((0, util_1.deepCopy)(baseAst));
1383
1321
  fetchSqlQuery((0, util_1.deepCopy)(baseAst));
@@ -1458,12 +1396,12 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1458
1396
  if (e instanceof Error)
1459
1397
  setPivotError(e.message);
1460
1398
  }
1461
- }, Select: SelectComponent, Button: ButtonComponent, SecondaryButton: SecondaryButtonComponent, disabled: tableLoading || loading }, `sort-sentence-pivot`) })), baseAst && baseAst.orderby && ((0, jsx_runtime_1.jsx)("div", { style: {
1399
+ }, Select: SelectComponent, Button: ButtonComponent, SecondaryButton: SecondaryButtonComponent, disabled: tableLoading || loading }, `sort-sentence-pivot`) })), baseAst && baseAst.orderby && baseAst.orderby.length > 0 && ((0, jsx_runtime_1.jsx)("div", { style: {
1462
1400
  display: 'flex',
1463
1401
  flexDirection: 'column',
1464
1402
  gap: 8,
1465
1403
  marginBottom: 12,
1466
- }, children: baseAst.orderby.map((sortData, id) => ((0, jsx_runtime_1.jsx)(AddSortPopover_1.SortSentence, { sortData: sortData, columns: selectedColumns, setIsPending: () => { }, setEditPopoverKey: () => { }, setActiveEditItem: setActiveEditItem, setActivePath: setActivePath, setOpenPopover: setOpenPopover, SortPopover: SortPopoverComponent, EditPopover: AddSortPopover_1.AddSortPopover, handleDelete: () => {
1404
+ }, children: baseAst.orderby.map((sortData, id) => ((0, jsx_runtime_1.jsx)(AddSortPopover_1.SortSentence, { sortData: sortData, columns: selectedColumns, setIsPending: () => { }, setEditPopoverKey: () => { }, setActiveEditItem: setActiveEditItem, setOpenPopover: setOpenPopover, SortPopover: SortPopoverComponent, EditPopover: AddSortPopover_1.AddSortPopover, handleDelete: () => {
1467
1405
  if (pivot) {
1468
1406
  setPivot({ ...pivot, sort: false });
1469
1407
  setPivotHint('');
@@ -1471,6 +1409,9 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1471
1409
  }
1472
1410
  const newAst = { ...baseAst };
1473
1411
  newAst.orderby.splice(id, 1);
1412
+ if (newAst.orderby.length === 0) {
1413
+ newAst.orderby = null;
1414
+ }
1474
1415
  setBaseAst((0, util_1.deepCopy)(newAst));
1475
1416
  fetchSqlQuery((0, util_1.deepCopy)(newAst));
1476
1417
  }, onSave: (column, direction) => {
@@ -1502,7 +1443,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1502
1443
  type: direction,
1503
1444
  };
1504
1445
  // look through the columns
1505
- setActivePath(null);
1506
1446
  setOpenPopover(null);
1507
1447
  setBaseAst((0, util_1.deepCopy)(newAst));
1508
1448
  fetchSqlQuery((0, util_1.deepCopy)(newAst));
@@ -1519,7 +1459,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1519
1459
  }, children: (0, jsx_runtime_1.jsx)(PopoverComponent, { isOpen: openPopover === 'AddSortPopover', setIsOpen: (isOpen) => {
1520
1460
  if (!isOpen) {
1521
1461
  setActiveEditItem(null);
1522
- setActivePath(null);
1523
1462
  setOpenPopover(null);
1524
1463
  }
1525
1464
  }, popoverTitle: "Sort by", popoverChildren: (0, jsx_runtime_1.jsx)(AddSortPopover_1.AddSortPopover, { columns: pivot
@@ -1569,7 +1508,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1569
1508
  if (e instanceof Error)
1570
1509
  setPivotError(e.message);
1571
1510
  }
1572
- setActivePath(null);
1573
1511
  setOpenPopover(null);
1574
1512
  setBaseAst((0, util_1.deepCopy)(baseAst));
1575
1513
  return;
@@ -1577,12 +1515,20 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1577
1515
  const newAst = { ...baseAst };
1578
1516
  if (!newAst.orderby)
1579
1517
  newAst.orderby = [];
1580
- newAst.orderby.push({
1581
- expr: { type: 'column_ref', column },
1582
- type: direction,
1583
- });
1518
+ const existingSortIndex = newAst.orderby.findIndex((item) => (0, astFilterProcessing_1.getFieldFromExpression)(item.expr) === column);
1519
+ if (existingSortIndex !== -1) {
1520
+ newAst.orderby[existingSortIndex] = {
1521
+ expr: { type: 'column_ref', column },
1522
+ type: direction,
1523
+ };
1524
+ }
1525
+ else {
1526
+ newAst.orderby.push({
1527
+ expr: { type: 'column_ref', column },
1528
+ type: direction,
1529
+ });
1530
+ }
1584
1531
  // look through the columns
1585
- setActivePath(null);
1586
1532
  setOpenPopover(null);
1587
1533
  setBaseAst((0, util_1.deepCopy)(newAst));
1588
1534
  fetchSqlQuery((0, util_1.deepCopy)(newAst));
@@ -1626,7 +1572,6 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1626
1572
  }, children: (0, jsx_runtime_1.jsx)(PopoverComponent, { isOpen: openPopover === 'AddLimitPopover', setIsOpen: (isOpen) => {
1627
1573
  if (!isOpen) {
1628
1574
  setActiveEditItem(null);
1629
- setActivePath(null);
1630
1575
  setOpenPopover(null);
1631
1576
  }
1632
1577
  }, popoverTitle: "Add limit", popoverChildren: (0, jsx_runtime_1.jsx)(AddLimitPopover_1.AddLimitPopover, { TextInputComponent: TextInputComponent, Button: ButtonComponent, SecondaryButton: SecondaryButtonComponent, onSave: (limit) => {
@@ -1665,7 +1610,9 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1665
1610
  label: (0, textProcessing_1.snakeAndCamelCaseToTitleCase)(c),
1666
1611
  field: c,
1667
1612
  };
1668
- }), onPageChange: onPageChange, onSortChange: onSortChange, containerStyle: {
1613
+ }), onPageChange: onPageChange, onSortChange: (sort) => {
1614
+ onSortChange(sort, false, true);
1615
+ }, containerStyle: {
1669
1616
  maxHeight: Math.max(window.innerHeight - 290, 75 + Math.min(Math.max(10, rows.length), 20) * 37),
1670
1617
  } })), (0, jsx_runtime_1.jsxs)("div", { style: {
1671
1618
  display: 'flex',
@@ -1684,6 +1631,7 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1684
1631
  fetchAstFromPromptHelper();
1685
1632
  }, label: 'Retry' })] })) : ((0, jsx_runtime_1.jsx)("div", { style: { width: '100%' } })), baseAst && dataDisplayed && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [onDiscardChanges && ((0, jsx_runtime_1.jsx)(SecondaryButtonComponent, { onClick: onDiscardChanges, label: "Discard changes" })), !hideCopySQL && ((0, jsx_runtime_1.jsx)(SecondaryButtonComponent, { label: isCopying ? 'Copied' : 'Copy SQL', onClick: () => copySQLToClipboard() })), (0, jsx_runtime_1.jsx)(ButtonComponent, { onClick: async () => {
1686
1633
  onSaveChanges && onSaveChanges();
1634
+ fetchFilteredRows(activeQuery);
1687
1635
  setIsChartBuilderOpen(true);
1688
1636
  }, disabled: !!errorMessage ||
1689
1637
  tableLoading ||
@@ -1704,5 +1652,7 @@ SidebarComponent = ui_1.QuillSidebar, ContainerComponent = ui_1.CustomContainer,
1704
1652
  }
1705
1653
  : {
1706
1654
  ...tempReport,
1707
- }, rows: chartBuilderInFilteredPreview ? filteredRows : rows, columns: columns, pivot: pivot, query: activeQuery, showTableFormatOptions: showChartBuilderTableFormatOptions, showDateFieldOptions: isAdminEnabled, showAccessControlOptions: isAdminEnabled, isAdmin: isAdminEnabled, title: reportId ? 'Save changes' : 'Add to dashboard', isHorizontalView: true, isOpen: isChartBuilderOpen, setIsOpen: setIsChartBuilderOpen, onAddToDashboardComplete: reportId ? onSubmitEditReport : onSubmitCreateReport, destinationDashboard: destinationDashboard, organizationName: organizationName, pivotData: pivotData, initialUniqueValues: uniqueValues[currentTable], initialUniqueValuesIsLoading: uniqueValuesIsLoading, pivotRecommendationsEnabled: pivotRecommendationsEnabledState, SelectComponent: SelectComponent, TextInputComponent: TextInputComponent, ButtonComponent: ButtonComponent, SecondaryButtonComponent: SecondaryButtonComponent, HeaderComponent: HeaderComponent, SubHeaderComponent: SubHeaderComponent, LabelComponent: LabelComponent, TextComponent: TextComponent, CardComponent: CardComponent, ModalComponent: ChartBuilderModalComponent, PopoverComponent: PopoverComponent, TableComponent: TableComponent, DeleteButtonComponent: DeleteButtonComponent, LoadingComponent: LoadingComponent, ChartBuilderInputRowContainer: ChartBuilderInputRowContainer, ChartBuilderInputColumnContainer: ChartBuilderInputColumnContainer, FormContainer: ChartBuilderFormContainer, hideDateRangeFilter: true, buttonLabel: !!reportId ? 'Save changes' : 'Add to dashboard', onClickChartElement: onClickChartElement, rowCount: numberOfRows, onPageChange: onPageChange, onSortChange: onSortChange, onFilterPreviewChange: onFilterPreviewChange, isLoading: tableLoading, isEditingMode: true }))] }));
1655
+ }, rows: chartBuilderInFilteredPreview ? filteredRows : rows, columns: columns, pivot: pivot, query: activeQuery, showTableFormatOptions: showChartBuilderTableFormatOptions, showDateFieldOptions: isAdminEnabled, showAccessControlOptions: isAdminEnabled, isAdmin: isAdminEnabled, title: reportId ? 'Save changes' : 'Add to dashboard', isHorizontalView: true, isOpen: isChartBuilderOpen, setIsOpen: setIsChartBuilderOpen, onAddToDashboardComplete: reportId ? onSubmitEditReport : onSubmitCreateReport, destinationDashboard: destinationDashboard, organizationName: organizationName, pivotData: pivotData, initialUniqueValues: uniqueValues[currentTable], initialUniqueValuesIsLoading: uniqueValuesIsLoading, pivotRecommendationsEnabled: pivotRecommendationsEnabledState, SelectComponent: SelectComponent, TextInputComponent: TextInputComponent, ButtonComponent: ButtonComponent, SecondaryButtonComponent: SecondaryButtonComponent, HeaderComponent: HeaderComponent, SubHeaderComponent: SubHeaderComponent, LabelComponent: LabelComponent, TextComponent: TextComponent, CardComponent: CardComponent, ModalComponent: ChartBuilderModalComponent, PopoverComponent: PopoverComponent, TableComponent: TableComponent, DeleteButtonComponent: DeleteButtonComponent, LoadingComponent: LoadingComponent, ChartBuilderInputRowContainer: ChartBuilderInputRowContainer, ChartBuilderInputColumnContainer: ChartBuilderInputColumnContainer, FormContainer: ChartBuilderFormContainer, hideDateRangeFilter: true, buttonLabel: !!reportId ? 'Save changes' : 'Add to dashboard', onClickChartElement: onClickChartElement, rowCount: chartBuilderInFilteredPreview ? filteredRowCount : numberOfRows, onPageChange: onPageChange, onSortChange: onSortChange, onFilterPreviewChange: reportId ? onFilterPreviewChange : undefined, isLoading: chartBuilderInFilteredPreview
1656
+ ? filteredTableIsLoading
1657
+ : tableLoading, isEditingMode: true }))] }));
1708
1658
  }