drupal_read_record()
Today I was teaching our Junior Developer at Webdrop all about schemas and drupal_write_record() and he asked me a pretty decent question.
What's the complementary function to drupal_write_record?
By that he meant the function that retrieves a record, given a schema and a primary key.
I gave it some thought and quickly realized that there is no such function! Maybe I'm just being a stickler but not having this function just seems silly (maybe not, turns out it's not that simple to write something generic).
So I decided to go ahead and write it:
/**
* Retrieve a record from the databased based on a schema.
*
* @param string $schema
* @param mixed $key A single value or an array of values
* @return array
*/function drupal_read_record($schema, $key) {
$key = (array) $key;
$schema = drupal_get_schema($schema);
if (!$schema) {
return FALSE;
}
$pks = $schema['primary key'];
// make sure we have the same ammount of values as we do primary keys
$count = count($key);
if ($count !== count($pks)) {
return FALSE;
}
// build query
$query = "SELECT * FROM {$schema['name']} WHERE";
for ($i = 0; $i < $count; ++$i) {
// escape % signs
$name = str_replace('%', '%%', $pks[$i]);
$query .= " {$name} = ";
// determine variable type
if (is_numeric($key[$i])) {
$quotes = FALSE;
if (is_int($key[$i]) || ctype_digit($key[$i])) {
$placeholder = '%d';
}
else {
$placeholder = '%f';
}
} else {
// primary keys shouldn't really be binary in the first place
$placeholder = '%s';
$quotes = TRUE;
}
if ($quotes) {
$query .= '"';
}
$query .= $placeholder;
if ($quotes) {
$query .= '"';
}
}
$result = db_query($query, $key);
return db_fetch_object($result);}
And there you have it!
You can now easily read and write records like this:
$write_record = new stdClass();$write_record->foo = 'bar';// write record in the databasedrupal_write_record('my_schema', $write_record);// the primary key (in this case "id") will be populated by drupal_write_record()$id = $write_record->id;// we can now retrieve records without writing any SQL:$read_record = drupal_read_record('my_schema', $id);// check equalityvar_dump($write_record === $read_record);
Please let me know if you find any bugs and thanks for reading!
Tags:
30Sep2011
Language
English
Category:
Reviewed: Yes