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

Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
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 below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.