1DBIx::Class::Storage::DUBsIe(r3)Contributed Perl DocumenDtBaItxi:o:nClass::Storage::DBI(3)
2
3
4

NAME

6       DBIx::Class::Storage::DBI - DBI storage handler
7

SYNOPSIS

9         my $schema = MySchema->connect('dbi:SQLite:my.db');
10
11         $schema->storage->debug(1);
12
13         my @stuff = $schema->storage->dbh_do(
14           sub {
15             my ($storage, $dbh, @args) = @_;
16             $dbh->do("DROP TABLE authors");
17           },
18           @column_list
19         );
20
21         $schema->resultset('Book')->search({
22            written_on => $schema->storage->datetime_parser->format_datetime(DateTime->now)
23         });
24

DESCRIPTION

26       This class represents the connection to an RDBMS via DBI.  See
27       DBIx::Class::Storage for general information.  This pod only documents
28       DBI-specific methods and behaviors.
29

METHODS

31   connect_info
32       This method is normally called by "connection" in DBIx::Class::Schema,
33       which encapsulates its argument list in an arrayref before passing them
34       here.
35
36       The argument list may contain:
37
38       ·   The same 4-element argument set one would normally pass to
39           "connect" in DBI, optionally followed by extra attributes
40           recognized by DBIx::Class:
41
42             $connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
43
44       ·   A single code reference which returns a connected DBI database
45           handle optionally followed by extra attributes recognized by
46           DBIx::Class:
47
48             $connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
49
50       ·   A single hashref with all the attributes and the dsn/user/password
51           mixed together:
52
53             $connect_info_args = [{
54               dsn => $dsn,
55               user => $user,
56               password => $pass,
57               %dbi_attributes,
58               %extra_attributes,
59             }];
60
61             $connect_info_args = [{
62               dbh_maker => sub { DBI->connect (...) },
63               %dbi_attributes,
64               %extra_attributes,
65             }];
66
67           This is particularly useful for Catalyst based applications,
68           allowing the following config (Config::General style):
69
70             <Model::DB>
71               schema_class   App::DB
72               <connect_info>
73                 dsn          dbi:mysql:database=test
74                 user         testuser
75                 password     TestPass
76                 AutoCommit   1
77               </connect_info>
78             </Model::DB>
79
80           The "dsn"/"user"/"password" combination can be substituted by the
81           "dbh_maker" key whose value is a coderef that returns a connected
82           DBI database handle
83
84       Please note that the DBI docs recommend that you always explicitly set
85       "AutoCommit" to either 0 or 1.  DBIx::Class further recommends that it
86       be set to 1, and that you perform transactions via our "txn_do" in
87       DBIx::Class::Schema method.  DBIx::Class will set it to 1 if you do not
88       do explicitly set it to zero.  This is the default for most DBDs. See
89       "DBIx::Class and AutoCommit" for details.
90
91       DBIx::Class specific connection attributes
92
93       In addition to the standard DBI connection attributes, DBIx::Class
94       recognizes the following connection options. These options can be mixed
95       in with your other DBI connection attributes, or placed in a separate
96       hashref ("\%extra_attributes") as shown above.
97
98       Every time "connect_info" is invoked, any previous settings for these
99       options will be cleared before setting the new ones, regardless of
100       whether any options are specified in the new "connect_info".
101
102       on_connect_do
103           Specifies things to do immediately after connecting or re-
104           connecting to the database.  Its value may contain:
105
106           a scalar
107               This contains one SQL statement to execute.
108
109           an array reference
110               This contains SQL statements to execute in order.  Each element
111               contains a string or a code reference that returns a string.
112
113           a code reference
114               This contains some code to execute.  Unlike code references
115               within an array reference, its return value is ignored.
116
117       on_disconnect_do
118           Takes arguments in the same form as "on_connect_do" and executes
119           them immediately before disconnecting from the database.
120
121           Note, this only runs if you explicitly call "disconnect" on the
122           storage object.
123
124       on_connect_call
125           A more generalized form of "on_connect_do" that calls the specified
126           "connect_call_METHOD" methods in your storage driver.
127
128             on_connect_do => 'select 1'
129
130           is equivalent to:
131
132             on_connect_call => [ [ do_sql => 'select 1' ] ]
133
134           Its values may contain:
135
136           a scalar
137               Will call the "connect_call_METHOD" method.
138
139           a code reference
140               Will execute "$code->($storage)"
141
142           an array reference
143               Each value can be a method name or code reference.
144
145           an array of arrays
146               For each array, the first item is taken to be the
147               "connect_call_" method name or code reference, and the rest are
148               parameters to it.
149
150           Some predefined storage methods you may use:
151
152           do_sql
153               Executes a SQL string or a code reference that returns a SQL
154               string. This is what "on_connect_do" and "on_disconnect_do"
155               use.
156
157               It can take:
158
159               a scalar
160                   Will execute the scalar as SQL.
161
162               an arrayref
163                   Taken to be arguments to "do" in DBI, the SQL string
164                   optionally followed by the attributes hashref and bind
165                   values.
166
167               a code reference
168                   Will execute "$code->($storage)" and execute the return
169                   array refs as above.
170
171           datetime_setup
172               Execute any statements necessary to initialize the database
173               session to return and accept datetime/timestamp values used
174               with DBIx::Class::InflateColumn::DateTime.
175
176               Only necessary for some databases, see your specific storage
177               driver for implementation details.
178
179       on_disconnect_call
180           Takes arguments in the same form as "on_connect_call" and executes
181           them immediately before disconnecting from the database.
182
183           Calls the "disconnect_call_METHOD" methods as opposed to the
184           "connect_call_METHOD" methods called by "on_connect_call".
185
186           Note, this only runs if you explicitly call "disconnect" on the
187           storage object.
188
189       disable_sth_caching
190           If set to a true value, this option will disable the caching of
191           statement handles via "prepare_cached" in DBI.
192
193       limit_dialect
194           Sets a specific SQL::Abstract::Limit-style limit dialect,
195           overriding the default "sql_limit_dialect" setting of the storage
196           (if any). For a list of available limit dialects see
197           DBIx::Class::SQLMaker::LimitDialects.
198
199       quote_names
200           When true automatically sets "quote_char" and "name_sep" to the
201           characters appropriate for your particular RDBMS. This option is
202           preferred over specifying "quote_char" directly.
203
204       quote_char
205           Specifies what characters to use to quote table and column names.
206
207           "quote_char" expects either a single character, in which case is it
208           is placed on either side of the table/column name, or an arrayref
209           of length 2 in which case the table/column name is placed between
210           the elements.
211
212           For example under MySQL you should use "quote_char => '`'", and for
213           SQL Server you should use "quote_char => [qw/[ ]/]".
214
215       name_sep
216           This parameter is only useful in conjunction with "quote_char", and
217           is used to specify the character that separates elements (schemas,
218           tables, columns) from each other. If unspecified it defaults to the
219           most commonly used ".".
220
221       unsafe
222           This Storage driver normally installs its own "HandleError", sets
223           "RaiseError" and "ShowErrorStatement" on, and sets "PrintError" off
224           on all database handles, including those supplied by a coderef.  It
225           does this so that it can have consistent and useful error behavior.
226
227           If you set this option to a true value, Storage will not do its
228           usual modifications to the database handle's attributes, and
229           instead relies on the settings in your connect_info DBI options (or
230           the values you set in your connection coderef, in the case that you
231           are connecting via coderef).
232
233           Note that your custom settings can cause Storage to malfunction,
234           especially if you set a "HandleError" handler that suppresses
235           exceptions and/or disable "RaiseError".
236
237       auto_savepoint
238           If this option is true, DBIx::Class will use savepoints when
239           nesting transactions, making it possible to recover from failure in
240           the inner transaction without having to abort all outer
241           transactions.
242
243       cursor_class
244           Use this argument to supply a cursor class other than the default
245           DBIx::Class::Storage::DBI::Cursor.
246
247       Some real-life examples of arguments to "connect_info" and "connect" in
248       DBIx::Class::Schema
249
250         # Simple SQLite connection
251         ->connect_info([ 'dbi:SQLite:./foo.db' ]);
252
253         # Connect via subref
254         ->connect_info([ sub { DBI->connect(...) } ]);
255
256         # Connect via subref in hashref
257         ->connect_info([{
258           dbh_maker => sub { DBI->connect(...) },
259           on_connect_do => 'alter session ...',
260         }]);
261
262         # A bit more complicated
263         ->connect_info(
264           [
265             'dbi:Pg:dbname=foo',
266             'postgres',
267             'my_pg_password',
268             { AutoCommit => 1 },
269             { quote_char => q{"} },
270           ]
271         );
272
273         # Equivalent to the previous example
274         ->connect_info(
275           [
276             'dbi:Pg:dbname=foo',
277             'postgres',
278             'my_pg_password',
279             { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
280           ]
281         );
282
283         # Same, but with hashref as argument
284         # See parse_connect_info for explanation
285         ->connect_info(
286           [{
287             dsn         => 'dbi:Pg:dbname=foo',
288             user        => 'postgres',
289             password    => 'my_pg_password',
290             AutoCommit  => 1,
291             quote_char  => q{"},
292             name_sep    => q{.},
293           }]
294         );
295
296         # Subref + DBIx::Class-specific connection options
297         ->connect_info(
298           [
299             sub { DBI->connect(...) },
300             {
301                 quote_char => q{`},
302                 name_sep => q{@},
303                 on_connect_do => ['SET search_path TO myschema,otherschema,public'],
304                 disable_sth_caching => 1,
305             },
306           ]
307         );
308
309   on_connect_do
310       This method is deprecated in favour of setting via "connect_info".
311
312   on_disconnect_do
313       This method is deprecated in favour of setting via "connect_info".
314
315   dbh_do
316       Arguments: ($subref | $method_name), @extra_coderef_args?
317
318       Execute the given $subref or $method_name using the new exception-based
319       connection management.
320
321       The first two arguments will be the storage object that "dbh_do" was
322       called on and a database handle to use.  Any additional arguments will
323       be passed verbatim to the called subref as arguments 2 and onwards.
324
325       Using this (instead of $self->_dbh or $self->dbh) ensures correct
326       exception handling and reconnection (or failover in future subclasses).
327
328       Your subref should have no side-effects outside of the database, as
329       there is the potential for your subref to be partially double-executed
330       if the database connection was stale/dysfunctional.
331
332       Example:
333
334         my @stuff = $schema->storage->dbh_do(
335           sub {
336             my ($storage, $dbh, @cols) = @_;
337             my $cols = join(q{, }, @cols);
338             $dbh->selectrow_array("SELECT $cols FROM foo");
339           },
340           @column_list
341         );
342
343   disconnect
344       Our "disconnect" method also performs a rollback first if the database
345       is not in "AutoCommit" mode.
346
347   with_deferred_fk_checks
348       Arguments: $coderef
349       Return Value: The return value of $coderef
350
351       Storage specific method to run the code ref with FK checks deferred or
352       in MySQL's case disabled entirely.
353
354   connected
355       Arguments: none
356       Return Value: 1|0
357
358       Verifies that the current database handle is active and ready to
359       execute an SQL statement (e.g. the connection did not get stale, server
360       is still answering, etc.) This method is used internally by "dbh".
361
362   dbh
363       Returns a $dbh - a data base handle of class DBI. The returned handle
364       is guaranteed to be healthy by implicitly calling "connected", and if
365       necessary performing a reconnection before returning. Keep in mind that
366       this is very expensive on some database engines. Consider using
367       "dbh_do" instead.
368
369   connect_call_datetime_setup
370       A no-op stub method, provided so that one can always safely supply the
371       connection option
372
373        on_connect_call => 'datetime_setup'
374
375       This way one does not need to know in advance whether the underlying
376       storage requires any sort of hand-holding when dealing with calendar
377       data.
378
379   select
380       Arguments: $ident, $select, $condition, $attrs
381
382       Handle a SQL select statement.
383
384   sql_limit_dialect
385       This is an accessor for the default SQL limit dialect used by a
386       particular storage driver. Can be overridden by supplying an explicit
387       "limit_dialect" to "connect" in DBIx::Class::Schema. For a list of
388       available limit dialects see DBIx::Class::SQLMaker::LimitDialects.
389
390   last_insert_id
391       Return the row id of the last insert.
392
393   _native_data_type
394       Arguments: $type_name
395
396       This API is EXPERIMENTAL, will almost definitely change in the future,
397       and currently only used by ::AutoCast and ::Sybase::ASE.
398
399       The default implementation returns "undef", implement in your Storage
400       driver if you need this functionality.
401
402       Should map types from other databases to the native RDBMS type, for
403       example "VARCHAR2" to "VARCHAR".
404
405       Types with modifiers should map to the underlying data type. For
406       example, "INTEGER AUTO_INCREMENT" should become "INTEGER".
407
408       Composite types should map to the container type, for example
409       "ENUM(foo,bar,baz)" becomes "ENUM".
410
411   sqlt_type
412       Returns the database driver name.
413
414   bind_attribute_by_data_type
415       Given a datatype from column info, returns a database specific bind
416       attribute for "$dbh->bind_param($val,$attribute)" or nothing if we will
417       let the database planner just handle it.
418
419       This method is always called after the driver has been determined and a
420       DBI connection has been established. Therefore you can refer to
421       "DBI::$constant" and/or "DBD::$driver::$constant" directly, without
422       worrying about loading the correct modules.
423
424   is_datatype_numeric
425       Given a datatype from column_info, returns a boolean value indicating
426       if the current RDBMS considers it a numeric value. This controls how
427       "set_column" in DBIx::Class::Row decides whether to mark the column as
428       dirty - when the datatype is deemed numeric a "!=" comparison will be
429       performed instead of the usual "eq".
430
431   create_ddl_dir
432       Arguments: $schema, \@databases, $version, $directory, $preversion,
433       \%sqlt_args
434
435       Creates a SQL file based on the Schema, for each of the specified
436       database engines in "\@databases" in the given directory.  (note:
437       specify SQL::Translator names, not DBI driver names).
438
439       Given a previous version number, this will also create a file
440       containing the ALTER TABLE statements to transform the previous schema
441       into the current one. Note that these statements may contain "DROP
442       TABLE" or "DROP COLUMN" statements that can potentially destroy data.
443
444       The file names are created using the "ddl_filename" method below,
445       please override this method in your schema if you would like a
446       different file name format. For the ALTER file, the same format is
447       used, replacing $version in the name with "$preversion-$version".
448
449       See "METHODS" in SQL::Translator for a list of values for
450       "\%sqlt_args".  The most common value for this would be "{
451       add_drop_table => 1 }" to have the SQL produced include a "DROP TABLE"
452       statement for each table created. For quoting purposes supply
453       "quote_identifiers".
454
455       If no arguments are passed, then the following default values are
456       assumed:
457
458       databases  - ['MySQL', 'SQLite', 'PostgreSQL']
459       version    - $schema->schema_version
460       directory  - './'
461       preversion - <none>
462
463       By default, "\%sqlt_args" will have
464
465        { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }
466
467       merged with the hash passed in. To disable any of those features, pass
468       in a hashref like the following
469
470        { ignore_constraint_names => 0, # ... other options }
471
472       WARNING: You are strongly advised to check all SQL files created,
473       before applying them.
474
475   deployment_statements
476       Arguments: $schema, $type, $version, $directory, $sqlt_args
477
478       Returns the statements used by "deploy" in DBIx::Class::Storage and
479       "deploy" in DBIx::Class::Schema.
480
481       The SQL::Translator (not DBI) database driver name can be explicitly
482       provided in $type, otherwise the result of "sqlt_type" is used as
483       default.
484
485       $directory is used to return statements from files in a previously
486       created "create_ddl_dir" directory and is optional. The filenames are
487       constructed from "ddl_filename" in DBIx::Class::Schema, the schema name
488       and the $version.
489
490       If no $directory is specified then the statements are constructed on
491       the fly using SQL::Translator and $version is ignored.
492
493       See "METHODS" in SQL::Translator for a list of values for $sqlt_args.
494
495   datetime_parser
496       Returns the datetime parser class
497
498   datetime_parser_type
499       Defines the datetime parser class - currently defaults to
500       DateTime::Format::MySQL
501
502   build_datetime_parser
503       See "datetime_parser"
504
505   is_replicating
506       A boolean that reports if a particular DBIx::Class::Storage::DBI is set
507       to replicate from a master database.  Default is undef, which is the
508       result returned by databases that don't support replication.
509
510   lag_behind_master
511       Returns a number that represents a certain amount of lag behind a
512       master db when a given storage is replicating.  The number is database
513       dependent, but starts at zero and increases with the amount of lag.
514       Default in undef
515
516   relname_to_table_alias
517       Arguments: $relname, $join_count
518       Return Value: $alias
519
520       DBIx::Class uses DBIx::Class::Relationship names as table aliases in
521       queries.
522
523       This hook is to allow specific DBIx::Class::Storage drivers to change
524       the way these aliases are named.
525
526       The default behavior is ""$relname_$join_count" if $join_count > 1",
527       otherwise "$relname".
528

USAGE NOTES

530   DBIx::Class and AutoCommit
531       DBIx::Class can do some wonderful magic with handling exceptions,
532       disconnections, and transactions when you use "AutoCommit => 1" (the
533       default) combined with txn_do for transaction support.
534
535       If you set "AutoCommit => 0" in your connect info, then you are always
536       in an assumed transaction between commits, and you're telling us you'd
537       like to manage that manually.  A lot of the magic protections offered
538       by this module will go away.  We can't protect you from exceptions due
539       to database disconnects because we don't know anything about how to
540       restart your transactions.  You're on your own for handling all sorts
541       of exceptional cases if you choose the "AutoCommit => 0" path, just as
542       you would be with raw DBI.
543

FURTHER QUESTIONS?

545       Check the list of additional DBIC resources.
546
548       This module is free software copyright by the DBIx::Class (DBIC)
549       authors. You can redistribute it and/or modify it under the same terms
550       as the DBIx::Class library.
551
552
553
554perl v5.28.0                      2018-01-29      DBIx::Class::Storage::DBI(3)
Impressum