TweetFollow Us on Twitter

Introduction to Database Events

Volume Number: 22 (2006)
Issue Number: 2
Column Tag: Programming

AppleScript Essentials

Introduction to Database Events

by Benjamin S. Waldie

Data storage and access is an important part of AppleScripting, particularly in complex AppleScript-based projects. Some scripts may need to store user-entered data for later reference, perhaps during an entirely new session. Some may need a location to log activity or errors during processing. Others may need to access structured data, in order to do something fairly complex, such as building a catalog.

In this month's column, we will discuss the use of Database Events, a new and exciting feature in Mac OS X, for storage and access of data during script execution.

Data Storage and Access Option

There are many techniques that are commonly used to store and access data with AppleScript. One common method is to simply write information to a text file on the user's hard drive, on a server, or elsewhere. This can be done with the File Read/Write Commands suite in the Standard Additions scripting addition, which is installed as part of Mac OS X. This technique of writing information to a text file may suffice for basic types of informational storage. However, depending on the complexity and amount of data being stored or accessed, you may need to write parsing code in order to work with the information.

In AppleScript Studio projects, another method of data storage and access is to make use of a project's preferences file, i.e. it's plist file. This is actually quite easily done, and is a common technique for storing such information as persistent user interface options and settings.

For complex data storage and access, a more robust solution may be necessary. Typically, developers will turn to a database of some kind. FileMaker Pro is usually quite popular among AppleScript developers, primarily due to its ease of use, customizable interface, and robust AppleScript support. For those not familiar with FileMaker Pro, I highly recommend downloading the 30 day demo from FileMaker's website at http://www.filemaker.com, and checking it out for yourself.

With Mac OS X Tiger, there is a new option - Database Events! If you have never heard of Database Events, that is not surprising. Database Events was released as part of Mac OS X 10.4 Tiger. However, it may have been missed by many, as the only mention of it that I could easily find was a small blurb on the AppleScript webpage at http://www.apple.com/macosx/features/applescript/. In this month's column, we will explore Database Events' syntax, and discuss ways that it can be integrated into your own scripts in order to store and access data during script execution.

What is Database Events?

Database Events is an AppleScriptable background application, which comes installed with Mac OS X 10.4 and higher. It is located in the System > Library > CoreServices folder, which you may recognize as the location of other scriptable background applications that are installed with Mac OS X, including Image Events and System Events.

Like its name implies, Database Events provides a way for AppleScript to perform basic events with databases, in particular, SQLite databases. Tasks that can be performed with Database Events include creating, opening, and saving databases, as well as accessing records and fields within databases.

By default, Database Events does not appear in the Script Editor's Library palette, which is accessible via the Window > Library menu. Click the + button in the Library palette, and navigate to Database Events in order to add it to the palette, thus making it quickly and easily accessible whenever Script Editor is launched. See figure 1.


Figure 1. Script Editor Library Palette

Once added to the Library palette, you may double click on Database Events in order to open its AppleScript dictionary. See figure 2.


Figure 2. Database Events AppleScript Dictionary

Getting Started with Scripting Database Events

If you launch the Activity Monitor application, located in the Applications > Utilities folder on your machine, immediately after logging in, you will notice that Database Events is not launched by default. To launch Database Events, use the launch command. For example:

tell application "Database Events"
   launch
end tell

As with any other application, when you are ready to quit Database Events, you may use the quit command. For example:

tell application "Database Events"
   quit
end tell

Please note that, in order to preserve memory, once launched, Database Events will automatically quit after 300 seconds, i.e. 5 minutes, of idle time or inactivity. When this occurs, it is important to note that any unsaved changes in any opened databases will be lost! Because of this, it is essential that you write your AppleScript code to save any database you may be modifying on a regular basis. We will discuss saving databases a little bit later.

If you require more than 5 minutes of inactivity, then it is actually possible to adjust the delay period by modifying the value of the quit delay property of the Database Events application. For example:

tell application "Database Events"
   set quit delay to 600
end tell

In the example code above, the quit delay is changed from the default 300 seconds to 600 seconds, or 10 minutes. Alternatively, you may also choose to decrease the default delay period by setting the quit delay property to a value of less than 300 seconds. Please note that, when modifying the value of this property, it will be reset to 300 seconds again the next time Database Events is launched.

You may check the value of the delay period by retrieving the quit delay property. For example:

tell application "Database Events"
   quit delay
end tell
--> 300

In some cases, you may not want Database Events to quit automatically at all. To disable automatic quitting entirely, set the quit delay property to a value of 0. For example:

tell application "Database Events"
   set quit delay to 0
end tell

Working with Databases

Now that we have discussed the basics of the Database Events application, let's move on to databases.

According to Database Events' AppleScript dictionary, the database class is an element of the application class. The dictionary also indicates that a database possesses a name property and a location property.

You can instruct the Database Events application to create a new database by using the make command, and specifying a name for the database. For example, the following sample code will create a new database named "Super Heroes", and you can see that the result of the command is a reference to the newly created database.

tell application "Database Events"
   make new database with properties {name:"Super Heroes"}
end tell
--> database "Super Heroes" of application "Database Events"

Once a database has been created, you can access it by its name, or by its index. For example:

tell database "Super Heroes"

-- OR

tell database 1

The following example code demonstrates how to retrieve the properties of an opened database:

tell application "Database Events"
   properties of database 1
end tell
--> {class:database, name:"Super Heroes", location:"~/Documents/Databases"}

When accessing the properties of a newly created database, you may notice that the location property of the database is set to a value of "~/Documents/Databases" by default. This does not mean that the database has actually been created in this location. In fact, this folder may not even exist yet. It simply means that this is the location in which the database will be created, once a save command has been issued, or once a record has been created.

Optionally, when a database is created, you may choose to indicate a custom location for the database by specifying a value for the location property. For example, the following code will prompt the user to select an output folder. It will then create a new database with a location property value of the folder specified by the user.

set theOutputFolder to choose folder with prompt "Please select an output folder:"
tell application "Database Events"
   make new database with properties {name:"Super Heroes", location:theOutputFolder}
end tell
--> database "Super Heroes" of application "Database Events"

To save an opened database at any time, use the save command. This will cause the database to be saved into the value specified in the database's location property, using the name specified in the name property. For example:

tell application "Database Events"
   save database 1
end tell
--> database "Super Heroes" of application "Database Events"

To open a saved database, use the open command, and specify the path of the database file to be opened. However, please note that you must specify this path as a POSIX style path. Otherwise, you will receive an error message. For example, the following code will open a database named Super Heroes.dbev on my desktop.

set theDBPath to POSIX path of "Macintosh HD:Users:bwaldie:Desktop:Super Heroes.dbev"
tell application "Database Events"
   open database theDBPath
end tell
--> database "Super Heroes" of application "Database Events"

To determine the number of opened databases, use the count command. For example:

tell application "Database Events"
   count databases
end tell
--> 1

To close a database, use the close command. In order to eliminate the possibility of receiving an error when attempting to close an unsaved modified database, specify a value for the saving parameter. For example, the following code will close a database without saving.

tell application "Database Events"
   close database 1 saving no
end tell

Working with Records

Once a database exists, you can now begin creating records within that database. Like creating databases, the make command is used to create new records. Records possess an ID property and a name property. A value for the ID property is automatically assigned a unique ID number when a record is created. However, a value for the name property must be specified whenever a record is created. The following example code demonstrates how a new record is created, using a specified name.

tell application "Database Events"
   tell database "Super Heroes"
      make new record with properties {name:"Batman"}
   end tell
end tell
--> record id 157660455 of database "Super Heroes" of application "Database Events"

You can see that, in this case, the result of the make command is a reference to the newly created record, and that a unique ID of 157660455 has been applied.

Once a record exists, it may be referred to by its index, its unique ID, or its name. For example:

tell record 1

-- OR

tell record id 157660455


-- OR

tell record "Batman"

To count the records of a database, use the count command. For example:

tell application "Database Events"
   tell database "Super Heroes"
      count records
   end tell
end tell
--> 1

You can delete records in a database by using the delete command. For example, the following code demonstrates how to delete every record in a specified database.

tell application "Database Events"
   tell database "Super Heroes"
      delete every record
   end tell
end tell

Working with Fields

Once a record has been created, you must create fields to be populated within that record. This must be done every time a new record is created. Fields may not be created at the database level in Database Events.

By default, a name field already exists when a record is created, and it contains the name of the record. You may create additional fields by using the make command. Fields have a name property and a value property, which may be specified at the time of field creation.

The following code demonstrates how to create a record with two fields. The first field, called name, is created automatically and assigned a value of Batman when the record is created. The second field, called Secret Identity, is assigned a value of Bruce Wayne when the field is created.

tell application "Database Events"
   tell database "Super Heroes"
      set theRecord to make new record with properties {name:"Batman"}
      tell theRecord
         make new field with properties {name:"Secret Identity", value:"Bruce Wayne"}
      end tell
   end tell
end tell
--> field "Secret Identity" of record id 157660455 of database "Super Heroes" of 
   application "Database Events"

To count the fields of a specified record, use the count command. For example:

tell application "Database Events"
   tell database "Super Heroes"
      tell record "Batman"
         count fields
      end tell
   end tell
end tell
--> 2

Pulling it Together

Now that we have discussed creating databases, records, and fields, let's pull it all together. The following example code demonstrates how to create a new database of records, based on a list of data. The database's name will be Super Heroes, and it will consist of a record for each super hero. Each record will contain a name field, and a secret identity field. Once built, the database will be saved into the default location, the Documents > Databases folder within your user folder.

set theSuperHeroes to {{"Batman", "Bruce Wayne"}, {"Spiderman", "Peter Parker"}, 
   {"Superman", "Clark Kent"}}
tell application "Database Events"
   set theDatabase to make new database with properties {name:"Super Heroes"}
   tell theDatabase
      repeat with a from 1 to length of theSuperHeroes
         set theCurrentSuperHeroInfo to item a of theSuperHeroes
         set theRecord to make new record with properties {name:item 1 of theCurrentSuperHeroInfo}
         tell theRecord
            make new field with properties {name:"Secret Identity", value:item 2 of 
               theCurrentSuperHeroInfo}
         end tell
      end repeat
   end tell
end tell

Now that you have a database, complete with fields and records, you can search for records in a variety of ways. For example, the following code demonstrates how to locate a record by name:

tell application "Database Events"
   tell database "Super Heroes"
      first record whose name = "Superman"
   end tell
end tell
--> record id 157661083 of database "Super Heroes" of application "Database Events"

The following code demonstrates how to locate a record by the value of one of its fields:

tell application "Database Events"
   tell database "Super Heroes"
      first record whose value of field "Secret Identity" contains "Parker"
   end tell
end tell
--> record id 157672965 of database "Super Heroes" of application "Database Events"

You can also retrieve and modify the values of fields in existing records. The following example code demonstrates how to retrieve the value of a specified field:

tell application "Database Events"
   tell database "Super Heroes"
      set theRecord to first record whose name = "Superman"
      tell theRecord
         value of field "Secret Identity"
      end tell
   end tell
end tell
--> "Clark Kent"

The following code demonstrates how to modify the value of a specified field:

tell application "Database Events"
   tell database "Super Heroes"
      set theRecord to first record whose name = "Superman"
      tell theRecord
         set value of field "Secret Identity" to "Kent, Clark"
      end tell
   end tell
end tell

In Closing

As you can see, there is a lot that can be done with Database Events. I encourage you to begin using it, testing it on your own, and integrating it into your scripts. While Database Events is not as robust as a fully featured database application, it can provide a quick and easy way to store and access structured data.

Also, please be aware that Database Events is currently at version 1.0. As it continues to mature, I am sure that it will continue to grow and will become an important part of many AppleScript-based workflows.

Until next time, keep scripting!


Ben Waldie is author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.