Home > Articles > Data

Client Dataset Basics

This chapter is from the book

This chapter is from the book

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 time—say, 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 CDSIndex—MainForm.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).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020