Tracking SQL statements sent

at 2007-07-18 in UnittestsDatabases by friebe (0 comments)

The XP framework's RDBMS access API offers logging of SQL queries sent to the server by adding observers to database connections:

<?php 
// First, set up logger
Logger::getInstance
()->getCategory('sql')->addAppender(new ConsoleAppender());

// Retrieve connection and add the log observer for the "sql" category to the connection
$conn= DriverManager::getConnection('sybase://user:pass@dbserv01');
$conn->addObserver(LogObserver::instanceFor('sql'));
?>

Now SQL statements and other connection events will be logged to the console. For most purposes, this will suffice.

If you need to store all SQL statements sent to the server in an array, for example to assert on them in unittest environments, here's how:

1) Add an observer that stores all statements in a Vector

<?php 
$observer= $conn->addObserver(newinstance('rdbms.DBObserver', array(new Vector())), '{
public $statements;
public function __construct($statements) {
$this->statements= $statements;
}
public static function instanceFor($arg) { }
public function update($observable, $event= NULL) {
if ($event instanceof DBEvent && "query" == $event->getName()) {
$this->statements[]= new String($event->getArgument());
}
}
}'
));
?>


2) Fire up some SQL
<?php 
$conn->query('select count(*) from customer');
?>


3) Look inside the statement list
<?php 
Console::writeLine
($observer->statements[0]);
?>

You will now see the count(*)-query appear.



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

Related

Find related articles by a search for «Tracking».