Replace inadequate $dbh->ping SQLite implementation (RT#78420)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / SQLite.pm
1 package DBIx::Class::Storage::DBI::SQLite;
2
3 use strict;
4 use warnings;
5
6 use base qw/DBIx::Class::Storage::DBI/;
7 use mro 'c3';
8
9 use DBIx::Class::Carp;
10 use Scalar::Util 'looks_like_number';
11 use Try::Tiny;
12 use namespace::clean;
13
14 __PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker::SQLite');
15 __PACKAGE__->sql_limit_dialect ('LimitOffset');
16 __PACKAGE__->sql_quote_char ('"');
17 __PACKAGE__->datetime_parser_type ('DateTime::Format::SQLite');
18
19 =head1 NAME
20
21 DBIx::Class::Storage::DBI::SQLite - Automatic primary key class for SQLite
22
23 =head1 SYNOPSIS
24
25   # In your table classes
26   use base 'DBIx::Class::Core';
27   __PACKAGE__->set_primary_key('id');
28
29 =head1 DESCRIPTION
30
31 This class implements autoincrements for SQLite.
32
33 =head1 METHODS
34
35 =cut
36
37 sub backup {
38
39   require File::Spec;
40   require File::Copy;
41   require POSIX;
42
43   my ($self, $dir) = @_;
44   $dir ||= './';
45
46   ## Where is the db file?
47   my $dsn = $self->_dbi_connect_info()->[0];
48
49   my $dbname = $1 if($dsn =~ /dbname=([^;]+)/);
50   if(!$dbname)
51   {
52     $dbname = $1 if($dsn =~ /^dbi:SQLite:(.+)$/i);
53   }
54   $self->throw_exception("Cannot determine name of SQLite db file")
55     if(!$dbname || !-f $dbname);
56
57 #  print "Found database: $dbname\n";
58 #  my $dbfile = file($dbname);
59   my ($vol, $dbdir, $file) = File::Spec->splitpath($dbname);
60 #  my $file = $dbfile->basename();
61   $file = POSIX::strftime("%Y-%m-%d-%H_%M_%S", localtime()) . $file;
62   $file = "B$file" while(-f $file);
63
64   mkdir($dir) unless -f $dir;
65   my $backupfile = File::Spec->catfile($dir, $file);
66
67   my $res = File::Copy::copy($dbname, $backupfile);
68   $self->throw_exception("Backup failed! ($!)") if(!$res);
69
70   return $backupfile;
71 }
72
73 sub _exec_svp_begin {
74   my ($self, $name) = @_;
75
76   $self->_dbh->do("SAVEPOINT $name");
77 }
78
79 sub _exec_svp_release {
80   my ($self, $name) = @_;
81
82   $self->_dbh->do("RELEASE SAVEPOINT $name");
83 }
84
85 sub _exec_svp_rollback {
86   my ($self, $name) = @_;
87
88   # For some reason this statement changes the value of $dbh->{AutoCommit}, so
89   # we localize it here to preserve the original value.
90   local $self->_dbh->{AutoCommit} = $self->_dbh->{AutoCommit};
91
92   $self->_dbh->do("ROLLBACK TRANSACTION TO SAVEPOINT $name");
93 }
94
95 sub _ping {
96   my $self = shift;
97   try { $self->_dbh->do('SELECT * FROM sqlite_master LIMIT 1'); 1 };
98 }
99
100 sub deployment_statements {
101   my $self = shift;
102   my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
103
104   $sqltargs ||= {};
105
106   if (
107     ! exists $sqltargs->{producer_args}{sqlite_version}
108       and
109     my $dver = $self->_server_info->{normalized_dbms_version}
110   ) {
111     $sqltargs->{producer_args}{sqlite_version} = $dver;
112   }
113
114   $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
115 }
116
117 sub bind_attribute_by_data_type {
118   $_[1] =~ /^ (?: int(?:eger)? | (?:tiny|small|medium)int ) $/ix
119     ? do { require DBI; DBI::SQL_INTEGER() }
120     : undef
121   ;
122 }
123
124 # DBD::SQLite (at least up to version 1.31 has a bug where it will
125 # non-fatally nummify a string value bound as an integer, resulting
126 # in insertions of '0' into supposed-to-be-numeric fields
127 # Since this can result in severe data inconsistency, remove the
128 # bind attr if such a sitation is detected
129 #
130 # FIXME - when a DBD::SQLite version is released that eventually fixes
131 # this sutiation (somehow) - no-op this override once a proper DBD
132 # version is detected
133 sub _dbi_attrs_for_bind {
134   my ($self, $ident, $bind) = @_;
135   my $bindattrs = $self->next::method($ident, $bind);
136
137   for (0.. $#$bindattrs) {
138     if (
139       defined $bindattrs->[$_]
140         and
141       defined $bind->[$_][1]
142         and
143       $bindattrs->[$_] eq DBI::SQL_INTEGER()
144         and
145       ! looks_like_number ($bind->[$_][1])
146     ) {
147       carp_unique( sprintf (
148         "Non-numeric value supplied for column '%s' despite the numeric datatype",
149         $bind->[$_][0]{dbic_colname} || "# $_"
150       ) );
151       undef $bindattrs->[$_];
152     }
153   }
154
155   return $bindattrs;
156 }
157
158 =head2 connect_call_use_foreign_keys
159
160 Used as:
161
162     on_connect_call => 'use_foreign_keys'
163
164 In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to turn on foreign key
165 (including cascading) support for recent versions of SQLite and L<DBD::SQLite>.
166
167 Executes:
168
169   PRAGMA foreign_keys = ON
170
171 See L<http://www.sqlite.org/foreignkeys.html> for more information.
172
173 =cut
174
175 sub connect_call_use_foreign_keys {
176   my $self = shift;
177
178   $self->_do_query(
179     'PRAGMA foreign_keys = ON'
180   );
181 }
182
183 1;
184
185 =head1 AUTHORS
186
187 Matt S. Trout <mst@shadowcatsystems.co.uk>
188
189 =head1 LICENSE
190
191 You may distribute this code under the same terms as Perl itself.
192
193 =cut