in reply to Re: Generating portable SQL primary key sequences
in thread Generating portable SQL primary key sequences

That is a good thought. Something like this would be fine if the database supported trasactions (which MySQL does not). You would then create the table with or without AUTO_INCREMENT. For MySQL we return the required NULL value for id otherwise we generate one in an atomic select/update/commit/rollback.

use DBI; my $DB_TYPE = 'mysql'; my $AUTO_COMMIT = 1; my $DB = 'test'; my $DB_USERNAME = 'user'; my $DB_PASSWORD = 'pwd; my $dbh = DBI->connect( "dbi:$DB_TYPE:$DB", $DB_USERNAME, $DB_PASSWORD +, {AutoCommit => $AUTO_COMMIT} ) or die_nice( DBI->errstr() ); END { $dbh->disconnect } # do_sql('DROP TABLE unique_id'); # for debugging my $sql =<<SQL; CREATE TABLE unique_id ( id INT UNSIGNED NOT NULL, address_book INT UNSIGNED NOT NULL, task_list INT UNSIGNED NOT NULL, PRIMARY KEY (id) ) SQL # create unique id table; do_sql($sql); # initialize table; $sql = 'INSERT INTO unique_id VALUES (?,?,?)'; do_sql($sql, 1, 0, 0); print get_unique_id('address_book'), "\n" for 1..10; sub get_unique_id { my ( $table_name ) = @_; return 'NULL' if $DB_TYPE = 'mysql'; my ($select_sth, $update_sth); my $select_sth = get_sth("SELECT $table_name from unique_id where +id = 1" ); my $update_sth = get_sth("UPDATE unique_id SET $table_name = ? whe +re id = 1"); my $success = 1; $select_sth->execute() or $success = 0; my ($id) = $select_sth->fetchrow_array or $success = 0; $id++; $update_sth->execute($id) or $success = 0; $success = ($success ? $dbh->commit : $dbh->rollback) unless $AUTO +_COMMIT; die_nice( "Couldn't finish get_unique_id transaction: " . $dbh->er +rstr ) unless $success; $select_sth->finish; $update_sth->finish; return $success ? $id : 0; } sub do_sql { my $sql = shift; my $sth = $dbh->prepare($sql) or die_nice( "Could not prepare SQL statement\n\n$sql\n" . $dbh-> +errstr() ); $sth->execute(@_) or die_nice( "Could not execute SQL statement\n\n$sql\n" . $sth-> +errstr() ); $sth->finish; $dbh->commit unless $AUTO_COMMIT; } sub get_sth { my $sql = shift; my $sth = $dbh->prepare_cached($sql) or die_nice( "Could not prepare SQL statement\n\n$sql\n" . $dbh-> +errstr() ); return $sth; } sub die_nice { die shift; }

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
Re^3: Generating portable SQL primary key sequences
by dragonchild (Archbishop) on Jun 22, 2004 at 20:55 UTC
    Update - MySQL 4.1 and higher support transactions on the InnoDB and BDB table types.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested