1use strict;
2use warnings;  
3
4use Test::More;
5use Test::Exception;
6use lib qw(t/lib);
7use DBICTest;
8
9my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_SYBASE_${_}" } qw/DSN USER PASS/};
10
11if (not ($dsn && $user)) {
12  plan skip_all =>
13    'Set $ENV{DBICTEST_SYBASE_DSN}, _USER and _PASS to run this test' .
14    "\nWarning: This test drops and creates a table called 'track'";
15} else {
16  eval "use DateTime; use DateTime::Format::Sybase;";
17  if ($@) {
18    plan skip_all => 'needs DateTime and DateTime::Format::Sybase for testing';
19  }
20}
21
22my @storage_types = (
23  'DBI::Sybase::ASE',
24  'DBI::Sybase::ASE::NoBindVars',
25);
26my $schema;
27
28for my $storage_type (@storage_types) {
29  $schema = DBICTest::Schema->clone;
30
31  unless ($storage_type eq 'DBI::Sybase::ASE') { # autodetect
32    $schema->storage_type("::$storage_type");
33  }
34  $schema->connection($dsn, $user, $pass, {
35    AutoCommit => 1,
36    on_connect_call => [ 'datetime_setup' ],
37  });
38
39  $schema->storage->ensure_connected;
40
41  isa_ok( $schema->storage, "DBIx::Class::Storage::$storage_type" );
42
43# coltype, col, date
44  my @dt_types = (
45    ['DATETIME', 'last_updated_at', '2004-08-21T14:36:48.080Z'],
46# minute precision
47    ['SMALLDATETIME', 'small_dt', '2004-08-21T14:36:00.000Z'],
48  );
49  
50  for my $dt_type (@dt_types) {
51    my ($type, $col, $sample_dt) = @$dt_type;
52
53    eval { $schema->storage->dbh->do("DROP TABLE track") };
54    $schema->storage->dbh->do(<<"SQL");
55CREATE TABLE track (
56   trackid INT IDENTITY PRIMARY KEY,
57   cd INT NULL,
58   position INT NULL,
59   $col $type NULL
60)
61SQL
62    ok(my $dt = DateTime::Format::Sybase->parse_datetime($sample_dt));
63
64    my $row;
65    ok( $row = $schema->resultset('Track')->create({
66          $col => $dt,
67          cd => 1,
68        }));
69    ok( $row = $schema->resultset('Track')
70      ->search({ trackid => $row->trackid }, { select => [$col] })
71      ->first
72    );
73    is( $row->$col, $dt, 'DateTime roundtrip' );
74  }
75
76  # test a computed datetime column
77  eval { $schema->storage->dbh->do("DROP TABLE track") };
78  $schema->storage->dbh->do(<<"SQL");
79CREATE TABLE track (
80   trackid INT IDENTITY PRIMARY KEY,
81   cd INT NULL,
82   position INT NULL,
83   title VARCHAR(100) NULL,
84   last_updated_on DATETIME NULL,
85   last_updated_at AS getdate(),
86   small_dt SMALLDATETIME NULL
87)
88SQL
89
90  my $now     = DateTime->now;
91  sleep 1;
92  my $new_row = $schema->resultset('Track')->create({});
93  $new_row->discard_changes;
94
95  lives_and {
96    cmp_ok (($new_row->last_updated_at - $now)->seconds, '>=', 1)
97  } 'getdate() computed column works';
98}
99
100done_testing;
101
102# clean up our mess
103END {
104  if (my $dbh = eval { $schema->storage->_dbh }) {
105    $dbh->do('DROP TABLE track');
106  }
107}
108