[development] External database handling

Larry Garfield larry at garfieldtech.com
Fri Aug 22 05:24:12 UTC 2008


On Thursday 21 August 2008 10:21:37 pm Chris Johnson wrote:
> Is it generally desirable that contributed modules use the Drupal
> database abstraction whenever possible when accessing external
> databases?  That is, is it generally preferable to use db_query() and
> friends, instead of mysql_connect(), mysql_query(), etc. whenever
> possible?

Yes, very much so.  All of the security system is built into the abstraction 
layer; using mysql_query() directly means you're totally on your own for 
security.

> I'd especially like to chat with the folks working on the DB layer for
> D7.  It would be nice to provide an interface to allow adding an
> additional DB programmatically from the contrib module.
>
> ..chris

Well hi there! :-)

What you describe was absolutely an issue in the D6 and earlier DB layer.  The 
new DB layer is still not perfect, but has improved on it in two ways:

1) The $databases value is always an array.  It can be a flattened array, as 
some layers are optional, but since the installer populates it in the first 
place it will in almost every case already be an array.  

2) You can actually instantiate a connection object directly.  I wouldn't 
recommend it as then the core system can't switch to it, but it's 
possible. :-)

3) (Nobody expects the Spanish Inquisition!)  The db_*() functions are all 
dumb wrappers.  You can grab a database connection with 
Database::getConnection($key) and then do everything after that with method 
calls; $db->query(), $db->insert(), $db->select(), etc.  So if you want to 
use a given database connection and just pull yourself out of the 
Drupal "active database" definition entirely, you can do so.

It's still not perfect, though, I agree.  If you have a suggestion for how to 
make the connection management more flexible without hurting performance (it 
is along the critical path, so we have to be careful) please post an issue.  
Just because the mega-patch landed doesn't mean we're done changing things 
yet. :-)

-- 
Larry Garfield
larry at garfieldtech.com


More information about the development mailing list