Skip to content

Instantly share code, notes, and snippets.

@rjattrill
Created June 13, 2012 06:02
Show Gist options
  • Save rjattrill/2922156 to your computer and use it in GitHub Desktop.
Save rjattrill/2922156 to your computer and use it in GitHub Desktop.
Insert row - DBIx::DataModel
use strict;
use warnings;
use DBI;
use DBIx::DataModel;
use DateTime;
use Try::Tiny;
use Test::More;
use Carp;
use FindBin::libs;
use Scratch::Schema;
{
my $test = 'Insert row DBIDM';
try {
print "Running $test\n";
insert_row("Test Task");
pass($test);
} catch {
carp($_);
print "Failed test\n";
fail($test);
}
}
done_testing();
sub insert_row {
my $task = shift;
my $dbh = get_dbh();
my %dbh_options;
$dbh_options{last_insert_id} = \&get_last_insert_id;
Scratch::Schema->dbh($dbh, %dbh_options);
my $schema = Scratch::Schema->singleton();
my $table_name = 'Task';
my $dt = DateTime->now;
my $now = $dt->strftime('%F');
my $activity_id = 1;
my $table = $schema->table($table_name);
my $id = $table->insert({ TASK => $task,
ACTIVITY_ID => $activity_id,
CREATED => $now,
});
}
# last_insert_id code for MSSQL
sub get_last_insert_id() {
my ($dbh, $table, $col) = @_;
my $sql = 'SELECT @@IDENTITY';
my @row_ary = $dbh->selectrow_array($sql);
my $id = $row_ary[0];
}
sub get_dbh {
my $dbi_dsn = 'dbi:ODBC:Driver={SQL Server Native Client 10.0};Server=localhost,1433;Database=scratch;';
my $user = 'scratch';
my $password = 'PASSWORD';
my $dbh = DBI->connect($dbi_dsn, $user, $password);
$dbh->{RaiseError} = 1; # Required for DBIx::DataModel
return $dbh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment