Client Dataset Indexes
So far, we haven't created any indexes on the client dataset and you might be wondering if (and why) they're even necessary when sequential searches through the dataset (using Locate) are so fast.
Indexes are used on client datasets for at least three reasons:
To provide faster access to data. A single Locate operation executes very quickly, but if you need to perform thousands of Locate operations, there is a noticeable performance gain when using indexes.
To enable the client dataset to be sorted on-the-fly. This is useful when you want to order the data in a data-aware grid, for example.
To implement maintained aggregates.
Figure 3.6 The Navigate application demonstrates various navigational techniques.
Creating Indexes
Like field definitions, indexes can be created at design-time or at runtime. Unlike field definitions, which are usually created at design-time, you might want to create and destroy indexes at runtime. For example, some indexes are only used for a short timesay, to create a report in a certain order. In this case, you might want to create the index, use it, and then destroy it. If you constantly need an index, it's better to create it at design-time (or to create it the first time you need it and not destroy it afterward).
Creating Indexes at Design-Time
To create an index at design-time, click the TClientDataSet component located on the form or data module. In the Object Inspector, double-click the IndexDefs property. The index editor appears.
To add an index to the client dataset, right-click the index editor and select Add from the pop-up menu. Alternately, you can click the Add icon on the toolbar, or simply press Ins.
Next, go back to the Object Inspector and set the appropriate properties for the index. Table 3.2 shows the index properties.
Table 3.2 Index Properties
Property |
Description |
Name |
-The name of the index. I recommend prefixing index names with the letters by (as in byName, byState, and so on). |
Fields |
-Semicolon-delimited list of fields that make up the index. Example: 'ID' or 'Name;Salary'. |
DescFields |
-A list of the fields contained in the Fields property that should be indexed in descending order. For example, to sort ascending by name, and then descending by salary, set Fields to 'Name;Salary' and DescFields to 'Salary'. |
CaseInsFields |
-A list of the fields contained in the Fields property that should be indexed in a manner which is not case sensitive. For example, if the index is on the last and first name, and neither is case sensitive, set Fields to 'Last;First' and CaseInsFields to 'Last;First'. |
GroupingLevel |
Used for aggregation. |
Options |
-Sets additional options on the index. The options are discussed in Table 3.3. |
Expression |
Not applicable to client datasets. |
Source |
Not applicable to client datasets. |
Table 3.3 shows the various index options that can be set using the Options property.
Table 3.3 Index Options
Option |
Description |
IxPrimary |
The index is the primary index on the dataset. |
IxUnique |
The index is unique. |
IxDescending |
The index is in descending order. |
IxCaseInsensitive |
The index is not case sensitive. |
IxExpression |
Not applicable to client datasets. |
IxNonMaintained |
Not applicable to client datasets. |
You can create multiple indexes on a single dataset. So, you can easily have both an ascending and a descending index on EmployeeName, for example.
Creating and Deleting Indexes at Runtime
In contrast to field definitions (which you usually create at design-time), index definitions are something that you frequently create at runtime. There are a couple of very good reasons for this:
Indexes can be quickly and easily created and destroyed. So, if you only need an index for a short period of time (to print a report in a certain order, for example), creating and destroying the index on an as-needed basis helps conserve memory.
Index information is not saved to a file or a stream when you persist a client dataset. When you load a client database from a file or a stream, you must re-create any indexes in your code.
To create an index, you use the client dataset's AddIndex method. AddIndex takes three mandatory parameters, as well as three optional parameters, and is defined like this:
procedure AddIndex(const Name, Fields: string; Options: TIndexOptions; const DescFields: string = ''; const CaseInsFields: string = ''; const GroupingLevel: Integer = 0);
The parameters correspond to the TIndexDef properties listed in Table 3.2. The following code snippet shows how to create a unique index by last and first names:
ClientDataSet1.AddIndex('byName', 'Last;First', [ixUnique]);
When you decide that you no longer need an index (remember, you can always re-create it if you need it later), you can delete it using DeleteIndex. DeleteIndex takes a single parameter: the name of the index being deleted. The following line of code shows how to delete the index created in the preceding code snippet:
ClientDataSet1.DeleteIndex('byName');
Using Indexes
Creating an index doesn't perform any actual sorting of the dataset. It simply creates an available index to the data. After you create an index, you make it active by setting the dataset's IndexName property, like this:
ClientDataSet1.IndexName := 'byName';
If you have two or more indexes defined on a dataset, you can quickly switch back and forth by changing the value of the IndexName property. If you want to discontinue the use of an index and revert to the default record order, you can set the IndexName property to an empty string, as the following code snippet illustrates:
// Do something in name order ClientDataSet1.IndexName := 'byName'; // Do something in salary order ClientDataSet1.IndexName := 'bySalary'; // Switch back to the default ordering ClientDataSet1.IndexName := '';
There is a second way to specify indexes on-the-fly at runtime. Instead of creating an index and setting the IndexName property, you can simply set the IndexFieldNames property. IndexFieldNames accepts a semicolon-delimited list of fields to index on. The following code shows how to use it:
ClientDataSet1.IndexFieldNames := 'Last;First';
Though IndexFieldNames is quicker and easier to use than AddIndex/IndexName, its simplicity does not come without a price. Specifically,
You cannot set any index options, such as unique or descending indexes.
You cannot specify a grouping level or create maintained aggregates.
When you switch from one index to another (by changing the value of IndexFieldNames), the old index is automatically dropped. If you switch back at a later time, the index is re-created. This happens so fast that it's not likely to be noticeable, but you should be aware that it's happening, nonetheless. When you create indexes using AddIndex, the index is maintained until you specifically delete it using DeleteIndex.
NOTE
Though you can switch back and forth between IndexName and IndexFieldNames in the same application, you can't set both properties at the same time. Setting IndexName clears IndexFieldNames, and setting IndexFieldNames clears IndexName.
Retrieving Index Information
Delphi provides a couple of different methods for retrieving index information from a dataset. These methods are discussed in the following sections.
GetIndexNames
The simplest method for retrieving index information is GetIndexNames. GetIndexNames takes a single parameter, a TStrings object, in which to store the resultant index names. The following code snippet shows how to load a list box with the names of all indexes defined for a dataset.
ClientDataSet1.GetIndexNames(ListBox1.Items);
CAUTION
If you execute this code on a dataset for which you haven't defined any indexes, you'll notice that there are two indexes already defined for you: DEFAULT_ORDER and CHANGEINDEX. DEFAULT_ORDER is used internally to provide records in nonindexed order. CHANGEINDEX is used internally to provide undo support, which is discussed later in this chapter. You should not attempt to delete either of these indexes.
TIndexDefs
If you want to obtain more detailed information about an index, you can go directly to the source: TIndexDefs. TIndexDefs contains a list of all indexes, along with the information associated with each one (such as the fields that make up the index, which fields are descending, and so on).
The following code snippet shows how to access index information directly through TIndexDefs.
var Index: Integer; IndexDef: TIndexDef; begin ClientDataSet1.IndexDefs.Update; for Index := 0 to ClientDataSet1.IndexDefs.Count - 1 do begin IndexDef := ClientDataSet1.IndexDefs[Index]; ListBox1.Items.Add(IndexDef.Name); end; end;
Notice the call to IndexDefs.Update before the code that loops through the index definitions. This call is required to ensure that the internal IndexDefs list is up-to-date. Without it, it's possible that IndexDefs might not contain any information about recently added indexes.
The following application demonstrates how to provide on-the-fly indexing in a TDBGrid. It also contains code for retrieving detailed information about all the indexes defined on a dataset.
Figure 3.7 shows the CDSIndex application at runtime, as it displays index information for the employee client dataset.
Listing 3.3 contains the complete source code for the CDSIndex application.
Figure 3.7 CDSIndex shows how to create indexes on-the-fly.
Listing 3.3 CDSIndexMainForm.pas
unit MainForm; interface uses SysUtils, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, DB, DBClient, QExtCtrls, QActnList, QGrids, QDBGrids; type TfrmMain = class(TForm) DataSource1: TDataSource; pnlClient: TPanel; DBGrid1: TDBGrid; ClientDataSet1: TClientDataSet; pnlBottom: TPanel; btnDefaultOrder: TButton; btnIndexList: TButton; ListBox1: TListBox; procedure FormCreate(Sender: TObject); procedure DBGrid1TitleClick(Column: TColumn); procedure btnDefaultOrderClick(Sender: TObject); procedure btnIndexListClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.xfm} procedure TfrmMain.FormCreate(Sender: TObject); begin ClientDataSet1.LoadFromFile('C:\Employee.cds'); end; procedure TfrmMain.DBGrid1TitleClick(Column: TColumn); begin try ClientDataSet1.DeleteIndex('byUser'); except end; ClientDataSet1.AddIndex('byUser', Column.FieldName, []); ClientDataSet1.IndexName := 'byUser'; end; procedure TfrmMain.btnDefaultOrderClick(Sender: TObject); begin // Deleting the current index will revert to the default order try ClientDataSet1.DeleteIndex('byUser'); except end; ClientDataSet1.IndexFieldNames := ''; end; procedure TfrmMain.btnIndexListClick(Sender: TObject); var Index: Integer; IndexDef: TIndexDef; begin ClientDataSet1.IndexDefs.Update; ListBox1.Items.BeginUpdate; try ListBox1.Items.Clear; for Index := 0 to ClientDataSet1.IndexDefs.Count - 1 do begin IndexDef := ClientDataSet1.IndexDefs[Index]; ListBox1.Items.Add(IndexDef.Name); end; finally ListBox1.Items.EndUpdate; end; end; end.
The code to dynamically sort the grid at runtime is contained in the method DBGrid1TitleClick. First, it attempts to delete the temporary index named byUser, if it exists. If it doesn't exist, an exception is raised, which the code simply eats. A real application should not mask exceptions willy-nilly. Instead, it should trap for the specific exceptions that might be thrown by the call to DeleteIndex, and let the others be reported to the user.
The method then creates a new index named byUser, and sets it to be the current index.
NOTE
Though this code works, it is rudimentary at best. There is no support for sorting on multiple grid columns, and no visual indication of what column(s) the grid is sorted by. For an elegant solution to these issues, I urge you to take a look at John Kaster's TCDSDBGrid (available as ID 15099 on Code Central at http://codecentral.borland.com).