in reply to Best Perlish way to test if a mysql table exists?

I'd suggest that your MySQL version is going to dictate exactly what features are supported. IIRC subselects aren't supported by MySQL versions before 4.1.

One solution is to wrap all your queries in eval blocks to catch any errors. I'd suggest the solution you don't want--running a SHOW TABLES and rejecting any tables that aren't available. Why is that such a terrible solution? Is it too slow? Why is it not "clean and simple" enough for you?

  • Comment on Re: Best Perlish way to test if a mysql table exists?

Replies are listed 'Best First'.
Re^2: Best Perlish way to test if a mysql table exists?
by Aristotle (Chancellor) on Jan 31, 2005 at 00:36 UTC

    eval is only necessary if DBI's RaiseError flag was set on connection to the database; otherwise $dbh->err must be checked. This should probably be done with a query such as SELECT 1 FROM table WHERE 0 which would always succeed but would never return any results, provided the table exists.

    Makeshifts last the longest.

      Just read up on RaiseError - maybe a possibility. But that would create an error trapping nightmare for me having to re-write trappig code for every line of sql in the script....

      Oh, for a "if table exists" function!

      Forget that fear of gravity,
      Get a little savagery in your life.

        To be honest, I don't think such functionality is particularly warranted. Constantly checking for the existence of a table smacks of bad design. Sometimes we are stuck with bad design, of course.

        Makeshifts last the longest.

        re-write trappig code for every line of sql in the script....
        Not necessary, you can set RaiseError for just that particular query. BTW, did you know you can localize hash/array values? Even if the hash/array is a lexical variable?
        eval { local $DBH->{RaiseError} = 1; local $DBH->{PrintError} = 0; $sth = $DBH->prepare($sql); $sth->execute; 1; }; # table was found if $@ is empty
        Alternately, you can just set RaiseError/PrintError on the individual statement handle (not the database connection handle).

        blokhead

Re^2: Best Perlish way to test if a mysql table exists?
by punch_card_don (Curate) on Jan 31, 2005 at 00:28 UTC
    'cause, like I said, there are tens of thousands of tables in the database, and perhaps hundreds of tables in the list - I don't want to bloat this with a lot of extra crunching.

    The more I think of it, the more a Perl solution that will trap the "table does not exist" error may be best.

    Forget that fear of gravity,
    Get a little savagery in your life.

      I don't think it would be a lot of extra crunching. Maybe a single query to list the tables, which you cache in a local hash. Then check the values in the hash to see if the current table you're querying is in the database. Hardly bloated.