Seitenanfang

Writing a DBI database driver

Dieser Post wurde aus meiner alten WordPress-Installation importiert. Sollte es Darstellungsprobleme, falsche Links oder fehlende Bilder geben, bitte einfach hier einen Kommentar hinterlassen. Danke.


DBI is the universal Perl database interface but it's using a so-called DBD driver module for each database type. I've been searching but didn't find a DBD module fitting my needs and so I started writing a new one.

DBI::DBD is DBI's documentation for writing DBD modules. Writing a database driver isn't much fun, you need to create highly efficient code which is nearly bug-free but my target was low-hanging fruit.

I just finished a database handling module suite for a project. All tests are successful, everything is fine. mySQL isn't my favorite database but testing error conditions is hard on any database server. You can't shut down a running database server for testing a "mysql has gone away" condition even if it's only a "development database" because other people are using it.

DBD::Simulated is not a real database driver but a database simulation: It can't store or fetch any data but it simulates any error code you want in many phases of database communication.

DBI::DBD shows all you need to write a DBD module and I won't paste the source which already made it's way to CPAN.

Most DBD::Simulated parts are simple copies of the DBI::DBD sample and there are many ideas which might be added to it one day but one little issue turned out to be complicated: column names! There is no sample neither any documentation on how to return them to DBI (and the calling application) - at least I didn't find anything. Here is my solution:

You simply need to fill two keys within your execute method(!), filling them during fetch* won't work:

$sth->STORE('NUM_OF_FIELDS', scalar keys %data);$sth->{'NAME'} = [sort keys %data];
The first line reports the number of columns returned by the (fake) query and the second like provides a list of column names.

PS: I didn't follow the suggestion of DBI to put all three packages into one file but made three files out of them. I clearly agree with PBP that every single package should have it's own file named like the package name.

 

1 Kommentar. Schreib was dazu

  1. dami

    Have a look at DBD::Mock; it serves similar purposes but goes further (allows you to simulate results from fake queries).

Schreib was dazu

Die folgenden HTML-Tags sind erlaubt:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>