XP: Log SQL queries

at 2010-10-18 in ExamplesDatabases by friebe (0 comments)

Reading PHP: 62 characters to see all MySQL queries, I thought I'd post a similar use case solution here. The task is to log all SQL queries and a backtrace of where they're executed from. In Ulf's post, this is accomplished by an extension function written in C, which needs to be compiled and loaded into PHP.

Altough a nice feature, this way has several downsides, first of all, the compilation, a hurdle big enough to keep me from trying it out, and second, it's only going to work with MySQL databases (and to be precise, only those newer than 4.0, because mysqlnd doesn't support MySQL's old password protocol handshake).



The XP group believes in solving problems in userspace if possible, so here's our solution, which will work for any database driver supported by the XP Framework:

  $conn= DriverManager::getConnection('driver://...');

// Add the observer
$observer= $conn->addObserver(newinstance('util.Observer', array(), '{
public $queries= array();
public function update($obs, $event= NULL) {
if ($event && "query" === $event->getName()) $this->queries[]= array(
"query" => $event->getArgument(),
"origin" => create(new Throwable(NULL))->getStackTrace()
);
}
}'
));

// Later on, dump them to the console
Console::writeLine($observer->queries);
Granted, it's a bit more than 62 characters:-)



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases
5.8-SERIES
Unicode
Language
5.9-SERIES

Related

Find related articles by a search for «XP:».