18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Database Access<br />

Advanced subjects<br />

While the five basic types of queries cover the vast majority of our database needs,<br />

there are two other advanced subjects we should cover: Transactions and master/<br />

slave replication. We will just touch on each briefly.<br />

Transactions<br />

A transaction in a database is a way to wrap two or more queries together and<br />

declare that they should be atomic. That is, either all succeed or none succeed. That<br />

can be very useful when, say, saving a node; we don't want only some fields to get<br />

written and then an error to break the process halfway through. We saw an example<br />

of that in Chapter 6. In a nutshell, in <strong>Drupal</strong> we start a transaction by creating a<br />

transaction object. Everything we do to the database is then part of the transaction<br />

until that object is destroyed, at which point the entire query is committed at once. In<br />

most cases, we let PHP destroy the transaction object for us when a function ends.<br />

function my_function() {<br />

$transaction = db_transaction();<br />

try {<br />

$id = db_insert('example')<br />

->fields(array(<br />

'field1' => 'mystring',<br />

'field2' => 5,<br />

))<br />

->execute();<br />

my_other_function($id);<br />

return $id;<br />

}<br />

catch (Exception $e) {<br />

$transaction->rollback();<br />

watchdog_exception('type', $e);<br />

}<br />

}<br />

In most cases we don't need a transaction, and they have no effect on Select queries.<br />

They're most useful when we're going to be running a lot of data modification<br />

queries (Insert, Update, Delete, and Merge) together, and the system will be broken<br />

if only some of them run. Imports, rebuilds of lookup tables, and other modules<br />

allowed to run queries via hook in the middle of our process are good candidates.<br />

[ 372 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!