if FIsGroup then
begin
SetupGroupControls(PANEL_SPACING, BUTTON_SIZE, CONTROL_HEIGHT);
end else begin
SetupFilterControls(PANEL_SPACING, BUTTON_SIZE, CONTROL_HEIGHT);
end;
// Create close button last so it's always on top
FCloseButton := TscGPCharGlyphButton.Create(FPanel);
with FCloseButton do
begin
Parent := FPanel;
Width := BUTTON_SIZE;
Height := BUTTON_SIZE;
Left := FPanel.Width - Width - PANEL_SPACING;
Top := (FPanel.Height - Height) div 2;
procedure TFilterPanel.HandleDragStart(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
TORMSearchAdvForm(FPanel.Owner).FilterManager.BeginDrag(Self);
FPanel.BeginDrag(False);
end;
end;
procedure TFilterPanel.HandleDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
var
SourcePanel: TFilterPanel;
begin
Accept := False;
if not (Source is TscGPPanel) then Exit;
SourcePanel := TORMSearchAdvForm(FPanel.Owner).FilterManager.FDragPanel;
if not Assigned(SourcePanel) or (SourcePanel = Self) then Exit;
// Prevent dropping parent into child
if IsGroup and SourcePanel.IsGroup then
begin
var TestPanel := ParentGroup;
while Assigned(TestPanel) do
begin
if TestPanel = SourcePanel then Exit;
TestPanel := TestPanel.ParentGroup;
end;
end;
Accept := True;
end;
procedure TFilterPanel.HandleDragDrop(Sender, Source: TObject; X, Y: Integer);
var
SourcePanel: TFilterPanel;
DropPos: TPoint;
begin
if not (Source is TscGPPanel) then Exit;
SourcePanel := TORMSearchAdvForm(FPanel.Owner).FilterManager.FDragPanel;
if not Assigned(SourcePanel) or (SourcePanel = Self) then Exit;
procedure TFilterPanel.ExpandButtonClick(Sender: TObject);
begin
ToggleExpanded;
end;
procedure TFilterPanel.GroupTypeButtonClick(Sender: TObject);
begin
if GroupType = fgtAnd then
GroupType := fgtOr
else
GroupType := fgtAnd;
UpdateGroupTypeVisuals;
end;
procedure TFilterPanel.CloseButtonClick(Sender: TObject);
begin
TORMSearchAdvForm(FPanel.Owner).FilterManager.RemoveFilter(Self);
end;
procedure TFilterPanel.UpdateGroupTypeVisuals;
begin
if not FIsGroup then Exit;
case GroupType of
fgtAnd:
begin
FGroupTypeButton.Caption := 'AND';
FGroupTypeButton.Options.NormalColor := RGB(238, 242, 255);
FGroupTypeButton.Options.FontNormalColor := RGB(79, 70, 229);
end;
fgtOr:
begin
FGroupTypeButton.Caption := 'OR';
FGroupTypeButton.Options.NormalColor := RGB(254, 242, 242);
FGroupTypeButton.Options.FontNormalColor := RGB(220, 38, 38);
end;
end;
end;
procedure TFilterPanel.ToggleExpanded;
begin
if not FIsGroup then Exit;
FIsExpanded := not FIsExpanded;
FContentPanel.Visible := FIsExpanded;
if Assigned(FExpandButton) then
begin
if FIsExpanded then
FExpandButton.GlyphOptions.Index := 263 // chevron down
else
FExpandButton.GlyphOptions.Index := 261; // chevron right
end;
procedure TFilterPanel.SetPosition(const Top: Integer);
begin
FPanel.Top := Top;
end;
function TFilterPanel.CalculateHeight: Integer;
begin
Result := FPanel.Height;
if FIsGroup and FIsExpanded and Assigned(FChildFilters) then
begin
for var Child in FChildFilters do
Inc(Result, Child.CalculateHeight + 4); // 4px spacing
end;
end;
function TFilterPanel.GetFilterCondition: string;
var
SelectedColumn: TSearchAdvColumn;
Form: TORMSearchAdvForm;
begin
Result := '';
if FIsGroup then Exit;
Form := TORMSearchAdvForm(FPanel.Owner);
if not Assigned(Form) then Exit;
// Find selected column
SelectedColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Build condition based on operator
case FFilterInfo.OperationType of
fotEqual:
Result := Format('%s = %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotNotEqual:
Result := Format('%s <> %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotGreaterThan:
Result := Format('%s > %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotLessThan:
Result := Format('%s < %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotGreaterEqual:
Result := Format('%s >= %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotLessEqual:
Result := Format('%s <= %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotBetween:
Result := Format('(%s BETWEEN %s AND %s)', [SelectedColumn.FieldName,
QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType),
QuoteValue(FFilterInfo.Value2, SelectedColumn.DataType)]);
fotContains:
Result := Format('%s LIKE ''%%%s%%''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
fotStartsWith:
Result := Format('%s LIKE ''%s%%''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
fotEndsWith:
Result := Format('%s LIKE ''%%%s''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
fotIsNull:
Result := Format('(%s IS NULL)', [SelectedColumn.FieldName]);
fotIsNotNull:
Result := Format('(%s IS NOT NULL)', [SelectedColumn.FieldName]);
end;
end;
function TFilterPanel.ValidateFilter: Boolean;
begin
Result := False;
if FIsGroup then Exit(True);
// Basic validation
if FFieldCombo.ItemIndex < 0 then Exit;
if FOperatorCombo.ItemIndex < 0 then Exit;
// Find selected column
var Form := TORMSearchAdvForm(FPanel.Owner);
var SelectedColumn: TSearchAdvColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Skip value validation for null checks
if (FOperatorCombo.Text = 'Is Empty') or
(FOperatorCombo.Text = 'Is Not Empty') then
begin
Result := True;
Exit;
end;
// Validate based on data type
case SelectedColumn.DataType of
tiString:
// String values are always valid
Result := True;
tiInteger:
begin
var IntValue: Int64;
Result := TryStrToInt64(FValueEdit.Text, IntValue);
end;
tiFloat, tiMoney:
begin
var FloatValue: Extended;
Result := TryStrToFloat(FValueEdit.Text, FloatValue);
end;
tiDate, tiDateTime:
begin
Result := FDateValue.Date > 0;
end;
tiBoolean:
begin
var BoolStr := LowerCase(FValueEdit.Text);
Result := (BoolStr = 'true') or (BoolStr = 'false') or
(BoolStr = '1') or (BoolStr = '0') or
(BoolStr = 'yes') or (BoolStr = 'no');
end;
end;
end;
function TFilterPanel.QuoteValue(const Value: Variant; ADataType: TORMFormatType): string;
begin
if Value.Trim = '' then
Exit('NULL');
case ADataType of
tiString:
Result := QuotedStr(Value);
tiInteger, tiFloat, tiMoney:
begin
if ADataType = tiMoney then
Result := QuoteNum(GetMoney(Value))
else
Result := QuoteNum(Value);
end;
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', FDateValue.Date));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', FDateValue.Date));
tiBoolean:
begin
var BoolStr := LowerCase(Value);
if (BoolStr = 'true') or (BoolStr = '1') or (BoolStr = 'yes') then
Result := 'TRUE'
else
Result := 'FALSE';
end;
else
Result := QuotedStr(Value);
end;
end;
procedure TFilterPanel.UpdateLayout;
begin
if not FIsGroup then Exit;
var YPos := FPanel.Height;
if FIsExpanded and Assigned(FChildFilters) then
begin
for var Child in FChildFilters do
begin
Child.Panel.Top := YPos;
Inc(YPos, Child.Panel.Height + 4); // 4px spacing
Child.UpdateLayout;
end;
end;
if Assigned(FContentPanel) then
FContentPanel.Height := YPos;
end;
destructor TFilterManager.Destroy;
begin
FRootFilters.Free;
inherited;
end;
function TFilterManager.CreateUniqueId: Integer;
begin
Result := FNextId;
Inc(FNextId);
end;
function TFilterManager.CreateFilterGroup(GroupType: TFilterGroupType;
Parent: TFilterPanel = nil): TFilterPanel;
begin
if Assigned(Parent) then
Result := TFilterPanel.Create(FForm, Parent.Level + 1,
Parent, True)
else Result := TFilterPanel.Create(FForm, 0,
Parent, True);
Result.GroupType := GroupType;
if Assigned(Parent) then
Parent.AddChild(Result)
else
FRootFilters.Add(Result);
UpdateLayout;
end;
function TFilterManager.CreateFilter(Parent: TFilterPanel = nil): TFilterPanel;
begin
if Assigned(Parent) then
Result := TFilterPanel.Create(FForm, Parent.Level + 1,
Parent, False)
else Result := TFilterPanel.Create(FForm, 0,
Parent, False);
if Assigned(Parent) then
Parent.AddChild(Result)
else
FRootFilters.Add(Result);
UpdateLayout;
end;
procedure TFilterManager.RemoveFilter(Filter: TFilterPanel);
begin
if not Assigned(Filter) then Exit;
// First remove from parent if it has one
if Assigned(Filter.ParentGroup) then
Filter.ParentGroup.RemoveChild(Filter)
else
FRootFilters.Extract(Filter);
// Handle removal of child filters if this is a group
if Filter.IsGroup and Assigned(Filter.ChildFilters) then
begin
while Filter.ChildFilters.Count > 0 do
begin
var Child := Filter.ChildFilters[0];
Filter.RemoveChild(Child);
if not Assigned(Child.ParentGroup) then
Child.Free;
end;
end;
// Clean up the filter panel
Filter.Panel.Parent := nil;
Filter.Free;
UpdateLayout;
HandleFilterRemoved(Filter);
end;
procedure TFilterManager.HandleFilterRemoved(Filter: TFilterPanel);
begin
// Update UI state
FForm.UpdateLayout;
// Clear any active drag operation
if FDragPanel = Filter then
FDragPanel := nil;
end;
function TFilterManager.FindFilterById(Id: Integer): TFilterPanel;
function SearchInGroup(Group: TFilterPanel): TFilterPanel;
begin
Result := nil;
if not Assigned(Group) or not Group.IsGroup then Exit;
for var Child in Group.ChildFilters do
begin
if Child.Id = Id then
Exit(Child);
if Child.IsGroup then
begin
Result := SearchInGroup(Child);
if Assigned(Result) then
Exit;
end;
end;
end;
begin
Result := nil;
// Search in root filters first
for var Filter in FRootFilters do
begin
if Filter.Id = Id then
Exit(Filter);
if Filter.IsGroup then
begin
Result := SearchInGroup(Filter);
if Assigned(Result) then
Exit;
end;
end;
end;
procedure TFilterManager.MoveFilter(Source, Target: TFilterPanel; Position: TPoint);
var
OldParent: TFilterPanel;
InsertIndex: Integer;
begin
if not Assigned(Source) or not Assigned(Target) then Exit;
// Don't allow dropping on self or invalid hierarchy
if (Source = Target) or
(Target.IsGroup and IsFilterInHierarchy(Target, Source)) then
Exit;
OldParent := Source.ParentGroup;
// Remove from old parent
if Assigned(OldParent) then
OldParent.RemoveChild(Source)
else
FRootFilters.Extract(Source);
// Determine if dropping into group or between filters
if Target.IsGroup and (Position.Y < Target.Panel.Height) then
begin
// Dropping into group
Target.AddChild(Source);
end
else
begin
// Dropping between filters
if Assigned(Target.ParentGroup) then
begin
InsertIndex := Target.ParentGroup.ChildFilters.IndexOf(Target);
if Position.Y > Target.Panel.Height div 2 then
Inc(InsertIndex);
Source.ParentGroup := Target.ParentGroup;
Target.ParentGroup.ChildFilters.Insert(InsertIndex, Source);
end
else
begin
InsertIndex := FRootFilters.IndexOf(Target);
if Position.Y > Target.Panel.Height div 2 then
Inc(InsertIndex);
Source.ParentGroup := nil;
FRootFilters.Insert(InsertIndex, Source);
end;
end;
UpdateLayout;
end;
function TFilterManager.IsFilterInHierarchy(Parent, Child: TFilterPanel): Boolean;
var
Current: TFilterPanel;
begin
Result := False;
if not Assigned(Parent) or not Assigned(Child) then Exit;
Current := Child;
while Assigned(Current) do
begin
if Current = Parent then
Exit(True);
Current := Current.ParentGroup;
end;
end;
procedure TFilterManager.UpdateLayout;
var
TotalHeight: Integer;
begin
TotalHeight := 0;
for var Filter in FRootFilters do
begin
Filter.SetPosition(TotalHeight);
Inc(TotalHeight, Filter.CalculateHeight + 4); // 4px spacing
Filter.UpdateLayout;
end;
// Update container size
if TotalHeight > 0 then
Inc(TotalHeight, 8); // Add margins
// Force visual update
FForm.pnlFilterContainer.Invalidate;
Application.ProcessMessages;
end;
procedure TFilterManager.BeginDrag(Filter: TFilterPanel);
begin
FDragPanel := Filter;
end;
procedure TFilterManager.EndDrag;
begin
FDragPanel := nil;
end;
function TFilterManager.BuildFilterSQL: string;
var
SQL: TStringBuilder;
procedure AddGroupFilters(Group: TFilterPanel);
var
IsFirst: Boolean;
begin
if not Group.IsGroup then Exit;
IsFirst := True;
SQL.Append('(');
for var Child in Group.ChildFilters do
begin
if not IsFirst then
begin
if Group.GroupType = fgtAnd then
SQL.Append(' AND ')
else
SQL.Append(' OR ');
end;
if Child.IsGroup then
AddGroupFilters(Child)
else
begin
// Add individual filter condition
SQL.Append(Child.GetFilterCondition);
end;
IsFirst := False;
end;
SQL.Append(')');
end;
begin
SQL := TStringBuilder.Create;
try
var IsFirst := True;
for var Filter in FRootFilters do
begin
if not IsFirst then
SQL.Append(' AND ');
if Filter.IsGroup then
AddGroupFilters(Filter)
else
SQL.Append(Filter.GetFilterCondition);
IsFirst := False;
end;
Result := SQL.ToString;
finally
SQL.Free;
end;
end;
function TFilterManager.ValidateFilters: Boolean;
function ValidateGroup(Group: TFilterPanel): Boolean;
begin
Result := False;
if not Group.IsGroup then Exit;
// Group must have at least one child
if Group.ChildFilters.Count = 0 then Exit;
// Validate each child
for var Child in Group.ChildFilters do
begin
if Child.IsGroup then
begin
if not ValidateGroup(Child) then Exit;
end
else
begin
if not Child.ValidateFilter then Exit;
end;
end;
Result := True;
end;
begin
Result := True;
// Must have at least one filter
if FRootFilters.Count = 0 then
begin
Result := False;
Exit;
end;
// Validate all root filters
for var Filter in FRootFilters do
begin
if Filter.IsGroup then
begin
if not ValidateGroup(Filter) then
begin
Result := False;
Break;
end;
end
else
begin
if not Filter.ValidateFilter then
begin
Result := False;
Break;
end;
end;
end;
end;
{ TORMSearchAdvForm Implementation }
procedure TORMSearchAdvForm.SetupVisuals;
begin
// Configure form appearance
Font.Name := 'Segoe UI';
Font.Size := 9;
// Style the main container
pnlMain.FillColor := RGB(249, 250, 251);
pnlMain.FillColorAlpha := 255;
// Configure buttons
with btnAddAndGroup do
begin
GlyphOptions.Size := 16;
GlyphOptions.Index := 85; // Plus icon
Caption := 'Add AND Group';
Options.NormalColor := clWhite;
Options.NormalColorAlpha := 255;
Options.ShapeCornerRadius := 4;
end;
with btnAddOrGroup do
begin
GlyphOptions.Size := 16;
GlyphOptions.Index := 85; // Plus icon
Caption := 'Add OR Group';
Options.NormalColor := clWhite;
Options.NormalColorAlpha := 255;
Options.ShapeCornerRadius := 4;
end;
with btnClearAll do
begin
GlyphOptions.Size := 16;
GlyphOptions.Index := 13; // X icon
Caption := 'Clear All';
Options.NormalColor := clWhite;
Options.NormalColorAlpha := 255;
Options.ShapeCornerRadius := 4;
Enabled := False;
end;
// Copy search columns
for var Column in ASearchColumns do
FSearchColumns.Add(TSearchAdvColumn.Create(
Column.FieldName,
Column.DisplayName,
Column.Width,
Column.Visible,
Column.UsableAsFilter
));
SetupFieldTypes;
SetupGrid;
LoadData;
end;
procedure TORMSearchAdvForm.SetupFieldTypes;
begin
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
for var i := 0 to FSearchColumns.Count - 1 do
begin
with SearchGrid do
begin
// Set column header
Cells[i, 0] := FSearchColumns[i].DisplayName;
// Configure column width
ColWidths[i] := FSearchColumns[i].Width;
// Hide column if not visible
if not FSearchColumns[i].Visible then
ColWidths[i] := 0;
// Set column alignment based on data type
case FSearchColumns[i].DataType of
tiInteger, tiFloat, tiMoney:
Columns[i].Alignment := taRightJustify;
tiDate, tiDateTime:
Columns[i].Alignment := taCenter;
else
Columns[i].Alignment := taLeftJustify;
end;
end;
end;
finally
SearchGrid.EndUpdate;
end;
end;
procedure TORMSearchAdvForm.LoadData;
begin
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
function TORMSearchAdvForm.GetFilteredSQL: string;
var
FilterSQL: string;
begin
Result := FBaseQuery;
FilterSQL := FFilterManager.BuildFilterSQL;
if FilterSQL <> '' then
begin
if Pos('WHERE', UpperCase(Result)) > 0 then
Result := Result + ' AND (' + FilterSQL + ')'
else
Result := Result + ' WHERE ' + FilterSQL;
end;
end;
procedure TORMSearchAdvForm.UpdateGridData;
begin
SearchGrid.BeginUpdate;
try
SearchGrid.RowCount := FQuery.RecordCount + SearchGrid.FixedRows;
var Row := SearchGrid.FixedRows;
FQuery.First;
while not FQuery.Eof do
begin
for var i := 0 to FSearchColumns.Count - 1 do
begin
var Field := FQuery.FieldByName(FSearchColumns[i].FieldName);
if Assigned(Field) then
begin
if Field.IsNull then
SearchGrid.Cells[i, Row] := ''
else
case FSearchColumns[i].DataType of
tiDate:
SearchGrid.Cells[i, Row] := FormatDateTime('dd/mm/yyyy', Field.AsDateTime);
tiDateTime:
SearchGrid.Cells[i, Row] := FormatDateTime('dd/mm/yyyy hh:nn:ss', Field.AsDateTime);
tiFloat, tiMoney:
SearchGrid.Cells[i, Row] := FormatFloat('#,##0.00', Field.AsFloat);
else
SearchGrid.Cells[i, Row] := Field.AsString;
end;
end;
end;
Inc(Row);
FQuery.Next;
end;
finally
SearchGrid.EndUpdate;
end;
end;
procedure TORMSearchAdvForm.FormCreate(Sender: TObject);
begin
SetupVisuals;
end;
procedure TORMSearchAdvForm.FormDestroy(Sender: TObject);
begin
// Cleanup handled in destructor
end;
procedure TORMSearchAdvForm.btnAddAndGroupClick(Sender: TObject);
begin
FFilterManager.CreateFilterGroup(fgtAnd);
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnAddOrGroupClick(Sender: TObject);
begin
FFilterManager.CreateFilterGroup(fgtOr);
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnAddFilterClick(Sender: TObject);
begin
FFilterManager.CreateFilter;
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnClearAllClick(Sender: TObject);
begin
FFilterManager.FRootFilters.Clear;
FFilterManager.UpdateLayout;
LoadData;
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnApplyClick(Sender: TObject);
begin
if ValidateFilters then
begin
LoadData;
UpdateControlStates;
end;
end;
procedure TORMSearchAdvForm.UpdateControlStates;
var
HasFilters: Boolean;
begin
HasFilters := FFilterManager.FRootFilters.Count > 0;
btnApply.Enabled := HasFilters;
btnClearAll.Enabled := HasFilters;
end;
function TORMSearchAdvForm.ValidateFilters: Boolean;
begin
Result := FFilterManager.ValidateFilters;
if not Result then
begin
MessageDlg('Please ensure all filters are properly configured.',
mtWarning, [mbOK], 0);
end;
end;
procedure TORMSearchAdvForm.SearchGridDblClick(Sender: TObject);
begin
if SearchGrid.Row >= SearchGrid.FixedRows then
begin
UpdateSelectedSearch;
ModalResult := mrOk;
end;
end;
procedure TORMSearchAdvForm.UpdateSelectedSearch;
begin
if SearchGrid.Row < SearchGrid.FixedRows then Exit;
// Create new selected search
FreeAndNil(FSelectedSearch);
FSelectedSearch := TSelectedAdvSearch.Create;
// Calculate record number
var RecNo := SearchGrid.Row - SearchGrid.FixedRows;
// Move query to correct record
FQuery.First;
for var i := 0 to RecNo - 1 do
FQuery.Next;
// Get values from the record
for var i := 0 to FSearchColumns.Count - 1 do
begin
var Field := FQuery.FieldByName(FSearchColumns[i].FieldName);
if Assigned(Field) then
begin
var Value: TValue;
if Field.IsNull then
Value := TValue.Empty
else
case Field.DataType of
ftString, ftWideString:
Value := TValue.From(Field.AsString);
ftInteger, ftSmallint:
Value := TValue.From(Field.AsInteger);
ftFloat, ftCurrency:
Value := TValue.From(Field.AsFloat);
ftDateTime, ftDate:
Value := TValue.From(Field.AsDateTime);
ftBoolean:
Value := TValue.From(Field.AsBoolean);
else
Value := TValue.From(Field.AsString);
end;
class function TORMSearchAdvForm.Execute(
AConnection: TUniConnection;
const ABaseQuery: string;
const ASearchColumns: array of TSearchAdvColumn;
var ASelectedSearch: TSelectedAdvSearch;
ARecordClass: TClass = nil): Boolean;
var
SearchForm: TORMSearchAdvForm;
begin
Result := False;
SearchForm := TORMSearchAdvForm.Create(nil);
try
SearchForm.InitializeSearch(AConnection, ABaseQuery, ASearchColumns, ARecordClass);
if SearchForm.ShowModal = mrOk then
begin
ASelectedSearch := SearchForm.FSelectedSearch;
SearchForm.FSelectedSearch := nil; // Prevent double free
Result := True;
end;
function TSelectedAdvSearch.GetValue(const AFieldName: string): TValue;
begin
if not FValues.TryGetValue(AFieldName, Result) then
Result := TValue.Empty;
end;
function TSelectedAdvSearch.GetDisplayValue(const AFieldName: string): string;
begin
if not FDisplayValues.TryGetValue(AFieldName, Result) then
Result := '';
end;
{ TFilterPanel }
procedure TFilterPanel.FieldComboChange(Sender: TObject);
var
Form: TORMSearchAdvForm;
begin
if not Assigned(FFieldCombo) then Exit;
Form := TORMSearchAdvForm(FPanel.Owner);
// Update the filter info with new field
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
FFilterInfo.FieldName := Column.FieldName;
FFilterInfo.DataType := Column.DataType;
Break;
end;
end;
UpdateOperators;
UpdateValueControls;
end;
procedure TFilterPanel.OperatorComboChange(Sender: TObject);
begin
if FOperatorCombo.Text =
'Equals' then FFilterInfo.OperationType := fotEqual
else if FOperatorCombo.Text =
'Not Equals' then FFilterInfo.OperationType := fotNotEqual
else if FOperatorCombo.Text =
'Greater Than'then FFilterInfo.OperationType := fotGreaterThan
else if FOperatorCombo.Text =
'Less Than' then FFilterInfo.OperationType := fotLessThan
else if FOperatorCombo.Text =
'Greater or Equal' then FFilterInfo.OperationType := fotGreaterEqual
else if FOperatorCombo.Text =
'Less or Equal' then FFilterInfo.OperationType := fotLessEqual
else if FOperatorCombo.Text =
'Between' then FFilterInfo.OperationType := fotBetween
else if FOperatorCombo.Text =
'Contains' then FFilterInfo.OperationType := fotContains
else if FOperatorCombo.Text =
'Starts With' then FFilterInfo.OperationType := fotStartsWith
else if FOperatorCombo.Text =
'Ends With' then FFilterInfo.OperationType := fotEndsWith
else if FOperatorCombo.Text =
'Is Empty' then FFilterInfo.OperationType := fotIsNull
else if FOperatorCombo.Text =
'Is Not Empty' then FFilterInfo.OperationType := fotIsNotNull;
UpdateValueControls;
end;
procedure TFilterPanel.UpdateOperators;
begin
if not Assigned(FOperatorCombo) then Exit;
FOperatorCombo.Items.Clear;
// Common operators for all types
FOperatorCombo.Items.Add('Is Empty');
FOperatorCombo.Items.Add('Is Not Empty');
case FFilterInfo.DataType of
tiString:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals',
'Contains', 'Starts With', 'Ends With']);
end;
tiInteger, tiFloat, tiMoney:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals',
'Greater Than', 'Less Than', 'Greater or Equal',
'Less or Equal', 'Between']);
end;
tiDate, tiDateTime:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals',
'Greater Than', 'Less Than', 'Greater or Equal',
'Less or Equal', 'Between']);
end;
tiBoolean:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals']);
end;
end;
if FOperatorCombo.Items.Count > 0 then
FOperatorCombo.ItemIndex := 0;
end;
procedure TFilterPanel.UpdateValueControls;
var
ShowValue1, ShowValue2: Boolean;
begin
if not (Assigned(FValueEdit) and Assigned(FDateValue)) then Exit;
// Determine which controls to show
ShowValue1 := not (FFilterInfo.OperationType in [fotIsNull, fotIsNotNull]);
ShowValue2 := FFilterInfo.OperationType = fotBetween;
// Show appropriate controls based on data type
case FFilterInfo.DataType of
tiDate, tiDateTime:
begin
FDateValue.Visible := ShowValue1;
FDateValue2.Visible := ShowValue2;
FValueEdit.Visible := False;
FValueEdit2.Visible := ShowValue2;
end;
else
begin
FDateValue.Visible := False;
FDateValue2.Visible := False;
FValueEdit.Visible := ShowValue1;
FValueEdit2.Visible := ShowValue2;
end;
end;
end;
function TFilterPanel.FormatValue(const Value: Variant): string;
begin
if VarIsNull(Value) or VarIsEmpty(Value) then
Exit('NULL');
case FFilterInfo.DataType of
tiString:
Result := QuotedStr(VarToStr(Value));
tiInteger:
Result := Value;
tiFloat, tiMoney:
Result := FormatFloat('#,##0.00', Value);
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', VarToDateTime(Value)));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', VarToDateTime(Value)));
tiBoolean:
Result := IfThen(Boolean(Value), 'TRUE', 'FALSE');
end;
end;
function TFilterPanel.GetFilterInfo: TFilterValueInfo;
begin
// Update values before returning
if FFilterInfo.DataType in [tiDate, tiDateTime] then
begin
if FDateValue.Visible then
FFilterInfo.Value1 := FDateValue.Date;
if (FFilterInfo.OperationType = fotBetween) and FDateValue2.Visible then
FFilterInfo.Value2 := FDateValue2.Date;
end
else
begin
if FValueEdit.Visible then
FFilterInfo.Value1 := FValueEdit.Text;
if (FFilterInfo.OperationType = fotBetween) and FValueEdit2.Visible then
FFilterInfo.Value2 := FValueEdit2.Text;
end;
Result := FFilterInfo;
end;
{ TORMSearchAdvForm }
procedure TORMSearchAdvForm.UpdateLayout;
begin
if Assigned(FFilterManager) then
FFilterManager.UpdateLayout;
end;
procedure TORMSearchAdvForm.BuildFilter;
begin
LoadData;
end;
{ TFilterManager }
procedure TFilterManager.UpdateFilterLayout;
begin
var TotalHeight := 0;
for var Filter in FRootFilters do
begin
Filter.SetPosition(TotalHeight);
Inc(TotalHeight, Filter.CalculateHeight + 4); // 4px spacing
Filter.UpdateLayout;
end;
// Update container size
if TotalHeight > 0 then
Inc(TotalHeight, 8); // Add margins
// Group type button (AND/OR)
FGroupTypeButton := TscGPCharGlyphButton.Create(FPanel);
with FGroupTypeButton do
begin
Parent := FPanel;
Width := 60;
Height := ControlHeight;
Left := FExpandButton.Left + FExpandButton.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
ShowCaption := True;
Caption := IfThen(GroupType = fgtAnd, 'AND', 'OR');
Font.Style := [fsBold];
Options.ShapeStyle := scgpRect;
Options.ShapeCornerRadius := 4;
Options.NormalColor := IfThen(GroupType = fgtAnd,
RGB(238, 242, 255), // Light indigo for AND
RGB(254, 242, 242)); // Light red for OR
Options.NormalColorAlpha := 255;
Options.FontNormalColor := IfThen(GroupType = fgtAnd,
RGB(79, 70, 229), // Indigo for AND
RGB(220, 38, 38)); // Red for OR
OnClick := GroupTypeButtonClick;
end;
// Content panel for child filters
FContentPanel := TscGPPanel.Create(FPanel);
with FContentPanel do
begin
Parent := FPanel;
Left := INDENT_WIDTH;
Top := FPanel.Height;
Width := FPanel.Width - Left - PanelSpacing;
Align := alCustom;
Visible := FIsExpanded;
procedure TFilterPanel.SetupFilterControls(PanelSpacing, ButtonSize, ControlHeight: Integer);
const
FIELD_WIDTH = 150;
OPERATOR_WIDTH = 120;
VALUE_WIDTH = 150;
begin
// Field selector
FFieldCombo := TscComboBox.Create(FPanel);
with FFieldCombo do
begin
Parent := FPanel;
Width := FIELD_WIDTH;
Height := ControlHeight;
Left := FDragHandle.Left + FDragHandle.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
Style := csDropDownList;
// Style the dropdown
StyleKind := scscbPushButton;
{
Options.ShapeCornerRadius := 4;
Options.FrameNormalColor := RGB(209, 213, 219);
Options.FrameWidth := 1;
}
// Populate with available fields
Items.Clear;
for var Column in TORMSearchAdvForm(FPanel.Owner).FSearchColumns do
if Column.UsableAsFilter then
Items.Add(Column.DisplayName);
if Items.Count > 0 then
ItemIndex := 0;
OnChange := FieldComboChange;
end;
// Operator selector
FOperatorCombo := TscComboBox.Create(FPanel);
with FOperatorCombo do
begin
Parent := FPanel;
Width := OPERATOR_WIDTH;
Height := ControlHeight;
Left := FFieldCombo.Left + FFieldCombo.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
Style := csDropDownList;
// Value input
FValueEdit := TscGPEdit.Create(FPanel);
with FValueEdit do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FOperatorCombo.Left + FOperatorCombo.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
// Date picker (initially hidden)
FDateValue := TscGPDateEdit.Create(FPanel);
with FDateValue do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FValueEdit.Left;
Top := FValueEdit.Top;
Visible := False;
// Second Value input (hidden by default)
FValueEdit2 := TscGPEdit.Create(FPanel);
with FValueEdit2 do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FValueEdit.Left + FValueEdit.Width + PanelSpacing;
Top := FValueEdit.Top;
// Date picker for second value (hidden by default)
FDateValue2 := TscGPDateEdit.Create(FPanel);
with FDateValue2 do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FDateValue.Left + FDateValue.Width + PanelSpacing;
Top := FDateValue.Top;
Visible := False;
carefully review the unit above and check for bugs
After carefully reviewing the provided Delphi unit orm_advsearch, several potential bugs and areas for improvement were identified. Below is a detailed analysis highlighting these issues along with recommended fixes:
1. Missing QuoteEsc Function
Issue:
In the GetFilterCondition method of the TFilterPanel class, the function QuoteEsc is used to escape values for SQL queries. However, this function is not defined anywhere in the unit, leading to a compilation error.
case FFilterInfo.OperationType of
...
fotContains:
Result := Format('%s LIKE ''%%%s%%''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
...
end;
Impact:
This will cause a compilation error, preventing the application from building successfully. Additionally, the absence of proper escaping can lead to SQL injection vulnerabilities if not addressed.
Recommendation:
Implement the QuoteEsc function to safely escape any single quotes or other special characters in the input values. Alternatively, utilize existing Delphi functions like QuotedStr which automatically handle such scenarios.
Example Fix:
function QuoteEsc(const Value: string): string;
begin
Result := StringReplace(Value, '''', '''''', [rfReplaceAll]);
end;
Replace the usage of QuoteEsc with the newly defined function:
fotContains:
Result := Format('%s LIKE ''%%%s%%''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
2. Incorrect Handling of Variant.Trim
Issue:
In the QuoteValue method of the TFilterPanel class, the code attempts to call the Trim method directly on a Variant type, which does not support this method.
if Value.Trim = '' then
Exit('NULL');
Impact:
This will result in a runtime error (EInvalidOp) when trying to call Trim on a non-String variant, such as dates or numbers.
Recommendation:
Ensure that Value is cast to a String before calling Trim. Additionally, handle different data types appropriately to avoid misinterpretation.
Example Fix:
function TFilterPanel.QuoteValue(const Value: Variant; ADataType: TORMFormatType): string;
var
StrValue: string;
begin
StrValue := VarToStr(Value).Trim;
if StrValue = '' then
Exit('NULL');
case ADataType of
tiString:
Result := QuotedStr(StrValue);
tiInteger, tiFloat, tiMoney:
begin
if ADataType = tiMoney then
Result := QuoteNum(GetMoney(Value))
else
Result := QuoteNum(StrValue);
end;
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', FDateValue.Date));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', FDateValue.Date));
tiBoolean:
begin
var BoolStr := LowerCase(StrValue);
if (BoolStr = 'true') or (BoolStr = '1') or (BoolStr = 'yes') then
Result := 'TRUE'
else
Result := 'FALSE';
end;
else
Result := QuotedStr(StrValue);
end;
end;
3. Overgeneralized NULL Handling
Issue:
The QuoteValue method returns 'NULL' for any empty string, regardless of the data type. This behavior is inappropriate for non-string data types like integers, floats, dates, etc.
if Value.Trim = '' then
Exit('NULL');
Impact:
This could lead to invalid SQL queries, especially when dealing with numeric or date fields where 'NULL' might not be a valid representation of an empty value.
Recommendation:
Handle NULL values based on the specific data type. Only return 'NULL' for data types where an empty value logically corresponds to NULL.
Example Fix:
function TFilterPanel.QuoteValue(const Value: Variant; ADataType: TORMFormatType): string;
var
StrValue: string;
begin
StrValue := VarToStr(Value).Trim;
// Handle NULL based on data type
case ADataType of
tiString:
if StrValue = '' then
Exit('NULL');
tiInteger, tiFloat, tiMoney:
if StrValue = '' then
Exit('NULL');
tiDate, tiDateTime:
if StrValue = '' then
Exit('NULL');
tiBoolean:
if StrValue = '' then
Exit('NULL');
end;
// Proceed with quoting based on data type
case ADataType of
tiString:
Result := QuotedStr(StrValue);
tiInteger, tiFloat, tiMoney:
begin
if ADataType = tiMoney then
Result := QuoteNum(GetMoney(Value))
else
Result := QuoteNum(StrValue);
end;
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', FDateValue.Date));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', FDateValue.Date));
tiBoolean:
begin
var BoolStr := LowerCase(StrValue);
if (BoolStr = 'true') or (BoolStr = '1') or (BoolStr = 'yes') then
Result := 'TRUE'
else
Result := 'FALSE';
end;
else
Result := QuotedStr(StrValue);
end;
end;
4. Duplicated UpdateLayout Methods
Issue:
Both TFilterManager and TFilterPanel classes have methods named UpdateLayout, which can lead to confusion and potential conflicts. This duplication can cause inconsistent behavior when updating the UI layout.
Impact:
Having two separate UpdateLayout methods can make the code harder to maintain and understand. It may also result in one method not fully updating all necessary components because of the overlap.
Recommendation:
Consolidate the layout update logic into a single method within the TFilterManager class. Ensure that this method comprehensively updates the layout of all filter panels.
Example Fix:
Remove UpdateLayout from TFilterPanel:
// Remove this method from TFilterPanel
procedure TFilterPanel.UpdateLayout;
begin
if not FIsGroup then Exit;
var YPos := FPanel.Height;
if FIsGroup and FIsExpanded and Assigned(FChildFilters) then
begin
for var Child in FChildFilters do
begin
Child.Panel.Top := YPos;
Inc(YPos, Child.Panel.Height + 4); // 4px spacing
end;
end;
if Assigned(FContentPanel) then
FContentPanel.Height := YPos;
end;
Ensure TFilterManager.UpdateLayout Handles All Cases:
procedure TFilterManager.UpdateLayout;
var
TotalHeight: Integer;
begin
TotalHeight := 0;
for var Filter in FRootFilters do
begin
Filter.SetPosition(TotalHeight);
Inc(TotalHeight, Filter.CalculateHeight + 4); // 4px spacing
// Recursively update positions of child filters
if Filter.IsGroup then
inc(TotalHeight, Filter.ChildFilters.Count * (ControlHeight + 4));
end;
// Update container size
if TotalHeight > 0 then
Inc(TotalHeight, 8); // Add margins
FForm.pnlFilterContainer.Height := Max(TotalHeight, 100);
// Force visual update
FForm.pnlFilterContainer.Invalidate;
Application.ProcessMessages;
end;
5. Potential Memory Leak in TFilterPanel Destructor
Issue:
In the destructor of the TFilterPanel class, child filters are freed only if they exist but do not account for nested groups beyond one level.
destructor TFilterPanel.Destroy;
begin
if Assigned(FChildFilters) then
FreeAndNil(FChildFilters);
if Assigned(FPanel) then
begin
FPanel.Parent := nil;
FreeAndNil(FPanel);
end;
inherited;
end;
Impact:
If there are nested groups (groups within groups), the destructor does not recursively free all nested child filters, potentially leading to memory leaks.
Recommendation:
Ensure that all child filters, including those in nested groups, are properly freed. Since TObjectList<TFilterPanel> is used with OwnsObjects=True for FRootFilters, make sure nested TFilterPanel instances are also owned appropriately.
Example Fix:
Make sure that FChildFilters is created with OwnsObjects=True if it should own its children.
Issue:
When creating filter groups, the ALevel parameter determines the indentation level. However, there is no validation to prevent excessively deep nesting, which could lead to UI issues or stack overflows.
Impact:
Users might create deeply nested groups, causing UI elements to render incorrectly or even crash the application due to maximum recursion depth being exceeded.
Recommendation:
Implement a maximum nesting level and provide feedback to the user when this limit is reached.
Example Fix:
Introduce a constant for maximum nesting levels and check it before creating a new group.
const
MAX_NESTING_LEVEL = 5;
function TFilterManager.CreateFilterGroup(GroupType: TFilterGroupType;
Parent: TFilterPanel = nil): TFilterPanel;
begin
if Assigned(Parent) and (Parent.Level >= MAX_NESTING_LEVEL) then
begin
MessageDlg('Maximum filter group nesting level reached.', mtWarning, [mbOK], 0);
Exit(nil);
end;
if Assigned(Parent) then
Result := TFilterPanel.Create(FForm, Parent.Level + 1, Parent, True)
else
Result := TFilterPanel.Create(FForm, 0, Parent, True);
Result.GroupType := GroupType;
if Assigned(Parent) then
Parent.AddChild(Result)
else
FRootFilters.Add(Result);
UpdateLayout;
end;
7. Inconsistent Ownership and Memory Management
Issue:
The ownership of various dynamically created objects (like FQuery, FFilterManager, and others) is inconsistently managed. For instance, FQuery is created in InitializeSearch if not already assigned but is only freed in the destructor.
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
Impact:
If InitializeSearch is called multiple times, multiple instances of FQuery might be created without freeing the previous ones, leading to memory leaks.
Recommendation:
Ensure that FQuery is either always created in the constructor or properly freed before being reassigned.
Example Fix:
In the destructor, ensure FQuery is freed:
destructor TORMSearchAdvForm.Destroy;
begin
FreeAndNil(FFilterManager);
FreeAndNil(FSearchColumns);
FreeAndNil(FFieldTypes);
FreeAndNil(FQuery); // Ensure FQuery is freed
inherited;
end;
And in InitializeSearch, free existing FQuery before creating a new one if necessary.
8. Inefficient Record Navigation in UpdateSelectedSearch
Issue:
The method UpdateSelectedSearch navigates through the query records by iterating with Next to reach the desired record. This approach is inefficient, especially with large datasets.
FQuery.First;
for var i := 0 to RecNo - 1 do
FQuery.Next;
Impact:
Performance issues can arise when dealing with large datasets, leading to slow response times or UI freezes.
Recommendation:
Use bookmarks or RecNo (if supported) to navigate directly to the desired record without iterating through each one.
Example Fix:
procedure TORMSearchAdvForm.UpdateSelectedSearch;
begin
if SearchGrid.Row < SearchGrid.FixedRows then Exit;
// Create new selected search
FreeAndNil(FSelectedSearch);
FSelectedSearch := TSelectedAdvSearch.Create;
// Calculate record number
var RecNo := SearchGrid.Row - SearchGrid.FixedRows;
// Use bookmarks for efficient navigation
if FQuery.BookmarkAvailable then
begin
FQuery.DisableControls;
try
FQuery.First;
if RecNo > 0 then
FQuery.MoveBy(RecNo);
finally
FQuery.EnableControls;
end;
end
else
begin
// Fallback if bookmarks are not available
FQuery.First;
for var i := 0 to RecNo - 1 do
FQuery.Next;
end;
// Get values from the record
for var i := 0 to FSearchColumns.Count - 1 do
begin
var Field := FQuery.FieldByName(FSearchColumns[i].FieldName);
if Assigned(Field) then
begin
var Value: TValue;
if Field.IsNull then
Value := TValue.Empty
else
case FSearchColumns[i].DataType of
tiString:
Value := TValue.From<string>(Field.AsString);
tiInteger:
Value := TValue.From<Integer>(Field.AsInteger);
tiFloat, tiMoney:
Value := TValue.From<Double>(Field.AsFloat);
tiDate, tiDateTime:
Value := TValue.From<TDateTime>(Field.AsDateTime);
tiBoolean:
Value := TValue.From<Boolean>(Field.AsBoolean);
else
Value := TValue.From<string>(Field.AsString);
end;
FSelectedSearch.SetValue(
FSearchColumns[i].FieldName,
Value,
SearchGrid.Cells[i, SearchGrid.Row]
);
end;
end;
end;
9. Unsafe SQL Construction Without Parameters
Issue:
The SQL query in BuildFilterSQL is constructed by concatenating strings, which can lead to SQL injection vulnerabilities if user inputs are not properly sanitized.
Impact:
Malicious users can inject harmful SQL code, compromising the database's integrity and security.
Recommendation:
Use parameterized queries to safely incorporate user inputs into SQL statements. This approach ensures that inputs are treated as data rather than executable code.
Example Fix:
Refactor the BuildFilterSQL method to use parameters.
function TFilterManager.BuildFilterSQL: string;
var
SQL: TStringBuilder;
begin
SQL := TStringBuilder.Create;
try
var IsFirst := True;
for var Filter in FRootFilters do
begin
if not IsFirst then
SQL.Append(' AND ');
if Filter.IsGroup then
SQL.Append('(' + BuildGroupFilter(Filter) + ')')
else
SQL.Append(BuildIndividualFilter(Filter));
IsFirst := False;
end;
Result := SQL.ToString;
finally
SQL.Free;
end;
end;
// Helper method to build group filters with parameters
function TFilterManager.BuildGroupFilter(Group: TFilterPanel): string;
begin
// Implement parameterized filter building
end;
// Helper method to build individual filters with parameters
function TFilterManager.BuildIndividualFilter(Filter: TFilterPanel): string;
begin
// Implement parameterized filter building
end;
10. Unhandled Edge Cases in Filter Validation
Issue:
The ValidateFilter method in TFilterPanel performs basic validation but does not handle all possible edge cases, such as invalid date ranges for Between operations or incompatible data types.
Impact:
Invalid filters may pass validation, leading to runtime errors or incorrect SQL queries that can produce unexpected results.
Recommendation:
Enhance the ValidateFilter method to handle additional edge cases, providing more granular feedback to users when filters are incorrectly configured.
Example Fix:
function TFilterPanel.ValidateFilter: Boolean;
begin
Result := False;
if FIsGroup then Exit(True);
// Basic validation
if FFieldCombo.ItemIndex < 0 then
begin
ShowMessage('Please select a field.');
Exit;
end;
if FOperatorCombo.ItemIndex < 0 then
begin
ShowMessage('Please select an operator.');
Exit;
end;
// Find selected column
var Form := TORMSearchAdvForm(FPanel.Owner);
var SelectedColumn: TSearchAdvColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then
begin
ShowMessage('Selected field is not valid.');
Exit;
end;
// Skip value validation for null checks
if (FOperatorCombo.Text = 'Is Empty') or
(FOperatorCombo.Text = 'Is Not Empty') then
begin
Result := True;
Exit;
end;
// Validate based on data type
case SelectedColumn.DataType of
tiString:
begin
// Additional string validations if necessary
Result := True;
end;
tiInteger:
begin
var IntValue: Int64;
if TryStrToInt64(FValueEdit.Text, IntValue) then
Result := True
else
begin
ShowMessage('Please enter a valid integer value.');
Exit;
end;
end;
tiFloat, tiMoney:
begin
var FloatValue: Extended;
if TryStrToFloat(FValueEdit.Text, FloatValue) then
Result := True
else
begin
ShowMessage('Please enter a valid numeric value.');
Exit;
end;
end;
tiDate, tiDateTime:
begin
if FDateValue.Visible and (FDateValue.Date > 0) then
begin
if FFilterInfo.OperationType = fotBetween then
begin
if not (FDateValue2.Visible and (FDateValue2.Date > 0)) then
begin
ShowMessage('Please enter a valid second date.');
Exit;
end;
if FDateValue.Date > FDateValue2.Date then
begin
ShowMessage('Start date cannot be after end date.');
Exit;
end;
end;
Result := True;
end
else
begin
ShowMessage('Please enter a valid date.');
Exit;
end;
end;
tiBoolean:
begin
var BoolStr := LowerCase(FValueEdit.Text);
if (BoolStr = 'true') or (BoolStr = 'false') or
(BoolStr = '1') or (BoolStr = '0') or
(BoolStr = 'yes') or (BoolStr = 'no') then
Result := True
else
begin
ShowMessage('Please enter a valid boolean value (True/False, Yes/No, 1/0).');
Exit;
end;
end;
else
begin
ShowMessage('Unsupported data type.');
Exit;
end;
end;
end;
11. Inefficient UI Updates with Application.ProcessMessages
Issue:
The UpdateLayout method in the TFilterManager class calls Application.ProcessMessages, which can lead to reentrancy issues and unexpected behavior, especially during complex UI updates.
procedure TFilterManager.UpdateLayout;
begin
...
Application.ProcessMessages;
end;
Impact:
Frequent or unnecessary calls to ProcessMessages can cause the application to become unresponsive or behave unpredictably, as it allows other events to be processed during critical updates.
Recommendation:
Avoid using Application.ProcessMessages unless absolutely necessary. Instead, ensure that UI updates are performed efficiently and consider using asynchronous operations or background threads for long-running tasks.
12. Lack of Error Handling in Database Operations
Issue:
Database operations such as opening queries and applying filters lack comprehensive error handling. For instance, if the database connection fails or the query is malformed, the application does not gracefully handle these exceptions.
Impact:
Uncaught exceptions can cause the application to crash, leading to a poor user experience and potential data integrity issues.
Recommendation:
Implement robust error handling around all database operations, providing meaningful feedback to the user and ensuring that the application remains stable in the face of unexpected issues.
Example Fix:
procedure TORMSearchAdvForm.LoadData;
begin
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
Screen.Cursor := crHourGlass;
try
FQuery.Close;
FQuery.SQL.Text := GetFilteredSQL;
FQuery.Connection := FConnection;
try
FQuery.Open;
UpdateGridData;
UpdateControlStates;
except
on E: Exception do
begin
ShowMessage('Error loading data: ' + E.Message);
FQuery.Close;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
Summary of Identified Bugs and Fixes
Undefined QuoteEsc Function: Implement the missing QuoteEsc function to handle SQL value escaping.
Incorrect Variant.Trim Usage: Cast Variant to String before calling Trim in the QuoteValue method.
Overgeneralized NULL Handling: Customize NULL handling based on specific data types within the QuoteValue method.
Duplicated UpdateLayout Methods: Consolidate layout update logic to a single method within the TFilterManager class.
Memory Leak in TFilterPanel Destructor: Ensure all nested child filters are properly freed by setting OwnsObjects=True.
Improper Group Level Handling: Implement a maximum nesting level to prevent excessive UI nesting and potential crashes.
Inconsistent Ownership and Memory Management: Standardize object ownership and ensure all dynamically created objects are properly freed.
Inefficient Record Navigation: Use bookmarks or index-based navigation to efficiently locate records in the UpdateSelectedSearch method.
Unsafe SQL Construction: Transition to parameterized queries to prevent SQL injection vulnerabilities.
Unhandled Edge Cases in Filter Validation: Enhance the ValidateFilter method to handle a broader range of validation scenarios and provide user feedback.
Inefficient UI Updates: Remove unnecessary calls to Application.ProcessMessages to avoid reentrancy issues.
Lack of Error Handling in Database Operations: Implement comprehensive error handling around all database interactions to ensure application stability.
By addressing these issues, the orm_advsearch unit will become more robust, secure, and maintainable. It’s crucial to test each change thoroughly to ensure that the application behaves as expected and that no new issues are introduced during the fixes.