Although the FQL language isn’t ANSI-SQL complete, it does have some simple operators and functions to help you work with user data. FQL has boolean operators (AND, OR, and NOT), comparison operators (=, >, >=, <, <=, <>), and arithmetic operators (+, -, *, and /). The functions included in FQL, although not exhaustive, allow you to perform some basic string manipulations. To conserve bandwidth, you can use the concat() function to group several tuples together:

<?php

$facebook_config['debug'] = false;

$facebook_config['api_key'] = '<your_api_key>';

$facebook_config['secret_key'] = '<your_secret_key>';

require_once('<path_to_client_library>/facebook.php');

$facebook = new Facebook($facebook_config['api_key'],

$facebook_config['secret']);

/**

* Ensure the user has logged on to Facebook

*/

$user = $facebook->require_login();

/**

* Construct the FQL request

*/

$fql = "SELECT concat(first_name, ' ', last_name)

FROM user

WHERE uid = '$user'";

/**

* Pass the FQL to Facebook through the API client

*/

$fql_result = $facebook->api_client->fql_query($fql);

/**

* Print the results to the screen

*/

echo "<pre>FQL Result:" . print_r($fql_result, true) .

"</pre>";

?>

The previous example simply selects the first and last names of the user who is currently making the request. The resulting page will display an array in the following format:

FQL Result:Array

(

[0] => Array

(

[anon] => <your_first_name> <your_last_name>

)

)

You might be saying to yourself, “This is pretty useless. What’s the difference between this and just calling both the fields?” Well, if you have any bandwidth concerns, you can alleviate some of those issues by using the concat function to put fields that you need together. For instance, you might want to put a specific string into your page that combines several fields in a specific way. Letting the Facebook servers do some of this processing before it gets back to your server will not only decrease your server load but can also cut down on your bandwidth in order to speed up your application.


Not only can you do simple SQL-style selects, but you can also perform subqueries. Take, for example, this FQL equivalent for the facebook.events.get REST API call:

SELECT eid, name, tagline, nid, pic, pic_big, pic_small, host, description,

event_type, event_subtype, start_time, end_time, creator, update_time,

location, venue

FROM event

WHERE eid IN (SELECT eid FROM event_member

WHERE uid=uid AND rsvp_status=rsvp_status) AND

eid IN (eids) AND

end_time >= start_time AND

start_time < end_time

I won’t go into the theory behind nested queries, but I will mention that they are very useful for testing set membership, set comparisons, and set cardinality. And, this expansion of the REST call serves as a good example for writing your own custom FQL expressions.

You might find that you will need to take some additional processing to make sure your information is displayed in a specific order. You’ll have to do this with your client language. For PHP, you need to sort the array and then slice it. Let’s take the following:

<?php

$fql = "SELECT eid, name, location

FROM event

WHERE eid IN (

SELECT eid

FROM event_member

WHERE uid = '$user'

)";

$fql_result = $facebook->api_client->fql_query($fql);

asort($fql_result);

array_slice($fql_result, 0, 5);

?>


The previous passes an FQL query to find events for the current user, sorts the resulting PHP array, and returns the array with the six elements (positions 0–5) of the query result.

FQL allows you as a developer to have granular control of the information that you retrieve about your users from the Facebook servers. Although it’s not as robust as you might sometimes need (or want) it to be, you can generally get around FQL’s limitations with some post-processing in the language in which you’re developing. Additionally, as the complexity of your FQL increases with subqueries, you might at some point run into problems. As I’ve mentioned earlier, using the Facebook API Test Console at http://developer.facebook.com/tools.php is a great place to help debug your code. For instance, if you take the previous query and take out the WHERE clause so that your FQL statement reads as follows:

SELECT eid, name, location

FROM event

WHERE eid IN (

SELECT eid

FROM event_member

)
then, when executed, this will raise an error because you must have a limiting WHERE clause. If you missed it when you look at your code, the resulting XML response shows an error code of 601 and an error message of “Parser error: WHERE clause is required.” Fortunately, this is an easy fix, but you might find yourself working with more complicated interactions with FBML and FQL, and this tool can provide invaluable help in discerning where your bugs exist.

Here’s a list to make sure you know what’s available to you in the different tables. (OK, these aren’t really tables; more likely these are views of specific data, but for simplicity’s sake, we’ll just call them tables.)

  • users(uid, first_name, last_name, name*, pic_small, pic_big, pic_square, pic, affiliations, profile_update_time, timezone, religion, birthday, sex, hometown_location, meeting_sex, meeting_for, relationship_status, significant_other_id, political, current_location, activities, interests, is_app_user, music, tv, movies, books, quotes, about_me, hs_info, education_history, work_history, notes_count, wall_count, status, has_added_app)
  • friend(uid1, uid2)
  • group(gid, name, nid, pic_small, pic_big, pic, description, group_type, group_subtype, recent_news, creator, update_time, office, website, venue)
  • group_member(uid, gid, positions)
  • event(eid, name, tagline, nid, pic_small, pic_big, pic, host, description, event_type, event_subtype, start_time, end_time, creator, update_time, location, venue)
  • event_member(uid, eid, rsvp_status)
  • photo(pid, aid, owner, src_small, src_big, src, link, caption, created)
  • album(aid, cover_pid, owner, name, created, modified, description, location, size)
  • photo_tag(pid, subject, xcoord, ycoord)

If you’ve worked with SQL before (and I assume you have), FQL isn’t a big deal. You use the same syntax as typical ANSI-SQL, and there are only nine tables to deal with. There are, however, some important differences. There are no joins, and FQL has not implemented the LIMIT, GROUP BY, or ORDER BY clauses that are common to ANSI SQL–compliant implementations.

Facebook also has implemented an API for basic database manipulations with its Data Store API. This API provides a basic create, read, update, and delete (CRUD) API for storing data that you access through REST. If you’re unfamiliar with object-oriented database management systems (OODMSs), some of the terminology is a bit different from that for relational database management systems (RDBMSs). For instance, to use the Data Store API, you must define your schema (your database), which consists of object types (tables) and properties (columns).

One of the really nice features of the Facebook Data Store API is that Facebook does not plan to charge for normal use! You basically have use of Facebook’s servers to perform your database manipulations for you. However, it’s probably not quite time to get rid of your RDBMS yet, because there aren’t any structured queries, full-text search, or transaction-level query processing in the Facebook Data Store API.

Note:
Data Store API may be in beta stage. Please consult the wiki documentation for the latest information before you deploy any projects using the Data Store API.

The Data Store API consists of three basic functions: specialized tables, distributed tables, and associations that are split into five separate APIs (User Preference, Object Data Definition, Object Data Access, Association Data Definition, and Association Data Access). Since Facebook provides access to millions of users, the tables (objects) you create are distributed. Facebook does provide a specialized table of users that is optimized (if you find that you really need more, let the Facebook developers know at their Bugzilla site, http://bugs.developers.facebook.com/). The associations component of this API is a mechanism to provide performance for fast lookups (such as indexes). Because indexing tables in a distributed environment won’t necessarily provide a performance boost, this mechanism has been implemented to provide fast lookups without centralized indexes or parallel queries.

The user preferences for the API consist of 128-character strings, for which you can store up to 201 for each user (numbered 0–200). Access to the getters/setters are accessed through getters and setters in the REST API (facebook.data.setUserPreference and facebook.data.getUserPreferences).

Data objects (that is, tables) are created with facebook.createObjectType. The object type takes a name and contains a set of object properties (that is, columns). Object properties have names and data types. You don’t quite have the same type of control over the data types with the API as you do with your own RDBMS because you are limited to integers, strings (less than 256 characters), and text blobs (with a maximum of 64KB).

After defining your objects and object types, you create, read, update, and delete through the Object Data Access API. These are rather straightforward (facebook.data.createObject, and so on).

To work with the associations between objects, you first need to define the relationship between objects in the facebook.defineAssociation call. You can define two types of associations: one-way, symmetric associations and asymmetric associations. If you’re familiar with RDBMS joins, think of an asymmetric association as a many-to-many join and a symmetric association as a one-to-many join. One-way associations are an association between objects that can happen only one way (in other words, there’s no need to look up a value by some ID) for a given object. You then create the actual associations with the Association Data Access API. These methods allow you to create, remove, and retrieve these associations and retrieve the object details from the data contained in the data definition.

This can be confusing at first, so let’s look at an example:
<?php
$createObject = $facebook->api_client->data_createObjectType("wallpost");
$uid = $facebook->api_client->data_defineObjectProperty("wallpost", "uid", 1);
$time = $facebook->api_client->data_defineObjectProperty("wallpost", "timePosted",2);
$post = $facebook->api_client->data_defineObjectProperty("wallpost", "post", 3);
?>

The previous snippet of code is analogous to the following SQL DDL:
CREATE TABLE wallpost(
uid integer,
timePosted timestamp,
post text
)

As you can see in this simple example, this can take a little bit to get used to because you’re not performing your typical SQL DDL; however, once you get your mind around how to create the objects, it’s relatively trivial to use the API as the persistence layer for your application. I suspect that this API will eventually make it out of beta and be quite a powerful tool in the Facebook developer’s toolbox, at least for those who choose to have Facebook manage their data.

Sometimes when you’re developing an application, you make mistakes. Fortunately, Facebook returns rather robust error messages when something goes wrong (like you forgot to provide a specific parameter for an API call). The error codes are returned with both a numeric value and a message. Generally, if you receive an error message (in a structure), it’s rather obvious when you read the error message (in the err_msg element). If you can’t figure out what’s going on with a specific call, it’s always a good idea to check out the code in the API Test Console (http://developer.facebook.com/tools.php). Although this won’t give you any more information than you are getting returned, it can help you narrow down what’s going on (in case you have multiple errors).

The final set of methods in the REST API gives you access to some user information for your application. The first, facebook.users.isAppAdded, tells you whether the user has added your application. To get information from your user’s profile, you can call the method facebook.users.getInfo. Lastly, to get the user ID (uid) from a session key, use the facebook.users.getLoggedInUser method.

To easily interact with setting information in the user’s profile, there are two methods to work with, facebook.profile.setFBML and facebook.profile.getFBML. These methods allow you to set and get FBML for a user’s profile box and profile actions.