tags:

views:

111

answers:

1

Hiya.

I have a script that parse the database and create php classes to work with that db. (zend-db-model-generator). is there a way to in php to have a DBMS agonstic commands so on each type of db it will return the table structure ?

so it doesn't matter if i use the pdo driver once for mysql and once for postgresql, it will still return the table structure.

the only solution that i see for now is to get the db type and to switch on each db type and execute the appropriate command.

+1  A: 

Using the same SQL query, unfortunatly, doesn't seem quite possible, as far as I can tell...


About your idea of going through the database to extract informations about each table to generate some PHP classes, that's one of the things that Doctrine (the most famous PHP ORM) does.

If you download it, and take a look at the classes in Doctrine/Import/[DatabaseType].php, you'll see this is done differently for each kind of database.

For instance, for MySQL, the following piece of code is used in Doctrine_Import_Mysql :

'listTableFields' => 'DESCRIBE %s',

On the other hand, for PostgreSQL, you've got the following, in Doctrine_Import_Pgsql :

'listTableColumns'     => "SELECT
                            a.attnum,
                            a.attname AS field,
                            t.typname AS type,
                            format_type(a.atttypid, a.atttypmod) AS complete_type,
                            a.attnotnull AS isnotnull,
                            (SELECT 't'
                              FROM pg_index
                              WHERE c.oid = pg_index.indrelid
                              AND a.attnum = ANY (pg_index.indkey)
                              AND pg_index.indisprimary = 't'
                            ) AS pri,
                            (SELECT pg_attrdef.adsrc
                              FROM pg_attrdef
                              WHERE c.oid = pg_attrdef.adrelid
                              AND pg_attrdef.adnum=a.attnum
                            ) AS default
                      FROM pg_attribute a, pg_class c, pg_type t
                      WHERE c.relname = %s
                            AND a.attnum > 0
                            AND a.attrelid = c.oid
                            AND a.atttypid = t.oid
                      ORDER BY a.attnum",

Not that easy, it seems ^^


And, farther down each class, there is a method called listTableColumns -- which is not the same for each database type...

So I'm guessing things will, unfortunatly, not be as simple as you hoped...

But, as a sidenote : maybe you could use Doctrine for that part of your project -- might be faster than re-inventing the wheel ;-)

Pascal MARTIN
hi. thanks for the update. i have my own project called zend-db-model-generator, it's on google code. wanna improve it a bit.
ufk
OK about having your own project :-) ;; Have fun !
Pascal MARTIN