Add Column / Index “If Not Exists” with Perl and SQLite

Categories: MySQL, Perl, SQLite
Comments: 2 Comments
Published on: Wednesday, December 12th, 2012

I recently updated a script that checks Apache httpd process sizes and saves the information to an SQLite database file. As part of some new functionality in the script, I needed to modify the SQLite database to add an additional column and some indexes. When creating new tables, you can use create table if not exists $table (); for example, but the same “if not exists” condition is not available when adding columns or creating indexes.

There are several solutions available to create a similar “if not exists” test for columns and indexes, but all of them (or at least the ones I found) are based on long SQL statements and/or stored procedures. I wanted something more flexible and perl-based, so wrote the following to set hash elements (%dbcol_exists and %dbidx_exists) using column and index names as references. The section that retrieves table / index names from the database and sets the hash elements, has been highlighted in the following snippet of code.

After setting the hash elements, perl can quickly loop through the column and index definition arrays (@dbcol and @dbidx) to create the missing columns and indexes. This snippet of code was written for SQLite, and assumes you’ve already connected to the database using $dbh = DBI->connect();.

Did you find this post useful? Share it with your circles / friends, or leave a quick note bellow.

Thank you,

js.

  • jsmoriss-photo
  • Looking for a Sr UNIX Systems Administrator specializing in Systems Integration? I may be available for freelance or contract work, either remotely or on-site. You can contact me by email at jsm@surniaulula.com to discuss your needs, and how my skills might contribute to your success. The Contact Me, Services and Rates pages contain additional information, including my current location and availability schedule.
  • facebook linkedin
Categories: MySQL, Perl, SQLite
Tags: , , , , , , ,
Published on: Wednesday, December 12th, 2012
2 Comments - Leave a comment
  1. Thomas Erskine says:
    Hi. Unfortunately, this (“PRAGMA TABLE_INFO”) is only valid for sqlite. In theory, you could use the DBI method table_info(), but my experience is that it is not widely supported and the support isn’t consistent. If you were use DBIx::Class, you could ask it which columns exist. If there were a consistent set of error codes between drivers, you could try to create the column, and check the error code to decide. I think the best you’ll get at the moment would be to “select * from table” and look at the column names in the result.

Leave a comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>