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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.