834a4d5c0e401ad0aeb18dc9c32569b91b3aed6b
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / SQLAnywhere.pm
1 package DBIx::Class::Storage::DBI::SQLAnywhere;
2
3 use strict;
4 use warnings;
5 use base qw/DBIx::Class::Storage::DBI::UniqueIdentifier/;
6 use mro 'c3';
7 use List::Util 'first';
8 use Try::Tiny;
9 use namespace::clean;
10
11 __PACKAGE__->mk_group_accessors(simple => qw/_identity/);
12 __PACKAGE__->sql_limit_dialect ('RowNumberOver');
13 __PACKAGE__->sql_quote_char ('"');
14
15 __PACKAGE__->new_guid('UUIDTOSTR(NEWID())');
16
17 # default to the UUID decoding cursor, overridable by the user
18 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::SQLAnywhere::Cursor');
19
20 =head1 NAME
21
22 DBIx::Class::Storage::DBI::SQLAnywhere - Driver for SQL Anywhere
23
24 =head1 DESCRIPTION
25
26 This class implements autoincrements for SQL Anywhere and provides
27 L<DBIx::Class::InflateColumn::DateTime> support and support for the
28 C<uniqueidentifier> type (via
29 L<DBIx::Class::Storage::DBI::SQLAnywhere::Cursor>.)
30
31 You need the C<DBD::SQLAnywhere> driver that comes with the SQL Anywhere
32 distribution, B<NOT> the one on CPAN. It is usually under a path such as:
33
34   /opt/sqlanywhere11/sdk/perl
35
36 Recommended L<connect_info|DBIx::Class::Storage::DBI/connect_info> settings:
37
38   on_connect_call => 'datetime_setup'
39
40 =head1 METHODS
41
42 =cut
43
44 sub last_insert_id { shift->_identity }
45
46 sub _prefetch_autovalues {
47   my $self = shift;
48   my ($source, $to_insert) = @_;
49
50   my $values = $self->next::method(@_);
51
52   my $colinfo = $source->columns_info;
53
54   my $identity_col =
55     first { $colinfo->{$_}{is_auto_increment} } keys %$colinfo;
56
57 # user might have an identity PK without is_auto_increment
58 #
59 # FIXME we probably should not have supported the above, see what
60 # does it take to move away from it
61   if (not $identity_col) {
62     foreach my $pk_col ($source->primary_columns) {
63       if (
64         ! exists $to_insert->{$pk_col}
65           and
66         $colinfo->{$pk_col}{data_type}
67           and
68         $colinfo->{$pk_col}{data_type} !~ /^uniqueidentifier/i
69       ) {
70         $identity_col = $pk_col;
71         last;
72       }
73     }
74   }
75
76   if ($identity_col && (not exists $to_insert->{$identity_col})) {
77     my $dbh = $self->_get_dbh;
78     my $table_name = $source->from;
79     $table_name    = $$table_name if ref $table_name;
80
81     my ($identity) = try {
82       $dbh->selectrow_array("SELECT GET_IDENTITY('$table_name')")
83     };
84
85     if (defined $identity) {
86       $values->{$identity_col} = $identity;
87       $self->_identity($identity);
88     }
89   }
90
91   return $values;
92 }
93
94 sub _uuid_to_str {
95   my ($self, $data) = @_;
96
97   $data = unpack 'H*', $data;
98
99   for my $pos (8, 13, 18, 23) {
100     substr($data, $pos, 0) = '-';
101   }
102
103   return $data;
104 }
105
106 # select_single does not invoke a cursor object at all, hence UUID decoding happens
107 # here if the proper cursor class is set
108 sub select_single {
109   my $self = shift;
110
111   my @row = $self->next::method(@_);
112
113   return @row
114     unless $self->cursor_class->isa('DBIx::Class::Storage::DBI::SQLAnywhere::Cursor');
115
116   my ($ident, $select) = @_;
117
118   my $col_info = $self->_resolve_column_info($ident);
119
120   for my $select_idx (0..$#$select) {
121     my $selected = $select->[$select_idx];
122
123     next if ref $selected;
124
125     my $data_type = $col_info->{$selected}{data_type}
126       or next;
127
128     if ($self->_is_guid_type($data_type)) {
129       my $returned = $row[$select_idx];
130
131       if (length $returned == 16) {
132         $row[$select_idx] = $self->_uuid_to_str($returned);
133       }
134     }
135   }
136
137   return @row;
138 }
139
140 # this sub stolen from MSSQL
141
142 sub build_datetime_parser {
143   my $self = shift;
144   my $type = "DateTime::Format::Strptime";
145   try {
146     eval "require ${type}"
147   }
148   catch {
149     $self->throw_exception("Couldn't load ${type}: $_");
150   };
151
152   return $type->new( pattern => '%Y-%m-%d %H:%M:%S.%6N' );
153 }
154
155 =head2 connect_call_datetime_setup
156
157 Used as:
158
159     on_connect_call => 'datetime_setup'
160
161 In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to set the date and
162 timestamp formats (as temporary options for the session) for use with
163 L<DBIx::Class::InflateColumn::DateTime>.
164
165 The C<TIMESTAMP> data type supports up to 6 digits after the decimal point for
166 second precision. The full precision is used.
167
168 The C<DATE> data type supposedly stores hours and minutes too, according to the
169 documentation, but I could not get that to work. It seems to only store the
170 date.
171
172 You will need the L<DateTime::Format::Strptime> module for inflation to work.
173
174 =cut
175
176 sub connect_call_datetime_setup {
177   my $self = shift;
178
179   $self->_do_query(
180     "set temporary option timestamp_format = 'yyyy-mm-dd hh:mm:ss.ssssss'"
181   );
182   $self->_do_query(
183     "set temporary option date_format      = 'yyyy-mm-dd hh:mm:ss.ssssss'"
184   );
185 }
186
187 sub _exec_svp_begin {
188     my ($self, $name) = @_;
189
190     $self->_dbh->do("SAVEPOINT $name");
191 }
192
193 # can't release savepoints that have been rolled back
194 sub _exec_svp_release { 1 }
195
196 sub _exec_svp_rollback {
197     my ($self, $name) = @_;
198
199     $self->_dbh->do("ROLLBACK TO SAVEPOINT $name")
200 }
201
202 1;
203
204 =head1 MAXIMUM CURSORS
205
206 A L<DBIx::Class> application can use a lot of cursors, due to the usage of
207 L<prepare_cached|DBI/prepare_cached>.
208
209 The default cursor maximum is C<50>, which can be a bit too low. This limit can
210 be turned off (or increased) by the DBA by executing:
211
212   set option max_statement_count = 0
213   set option max_cursor_count    = 0
214
215 Highly recommended.
216
217 =head1 AUTHOR
218
219 See L<DBIx::Class/AUTHOR> and L<DBIx::Class/CONTRIBUTORS>.
220
221 =head1 LICENSE
222
223 You may distribute this code under the same terms as Perl itself.
224
225 =cut