1DBIx::Class::Schema(3)User Contributed Perl DocumentationDBIx::Class::Schema(3)
2
3
4

NAME

6       DBIx::Class::Schema - composable schemas
7

SYNOPSIS

9         package Library::Schema;
10         use base qw/DBIx::Class::Schema/;
11
12         # load all Result classes in Library/Schema/Result/
13         __PACKAGE__->load_namespaces();
14
15         package Library::Schema::Result::CD;
16         use base qw/DBIx::Class::Core/;
17
18         __PACKAGE__->load_components(qw/InflateColumn::DateTime/); # for example
19         __PACKAGE__->table('cd');
20
21         # Elsewhere in your code:
22         my $schema1 = Library::Schema->connect(
23           $dsn,
24           $user,
25           $password,
26           { AutoCommit => 1 },
27         );
28
29         my $schema2 = Library::Schema->connect($coderef_returning_dbh);
30
31         # fetch objects using Library::Schema::Result::DVD
32         my $resultset = $schema1->resultset('DVD')->search( ... );
33         my @dvd_objects = $schema2->resultset('DVD')->search( ... );
34

DESCRIPTION

36       Creates database classes based on a schema. This is the recommended way
37       to use DBIx::Class and allows you to use more than one concurrent
38       connection with your classes.
39
40       NB: If you're used to Class::DBI it's worth reading the "SYNOPSIS"
41       carefully, as DBIx::Class does things a little differently. Note in
42       particular which module inherits off which.
43

SETUP METHODS

45   load_namespaces
46       Arguments: %options?
47
48         package MyApp::Schema;
49         __PACKAGE__->load_namespaces();
50
51         __PACKAGE__->load_namespaces(
52            result_namespace => 'Res',
53            resultset_namespace => 'RSet',
54            default_resultset_class => '+MyApp::Othernamespace::RSet',
55         );
56
57       With no arguments, this method uses Module::Find to load all of the
58       Result and ResultSet classes under the namespace of the schema from
59       which it is called.  For example, "My::Schema" will by default find and
60       load Result classes named "My::Schema::Result::*" and ResultSet classes
61       named "My::Schema::ResultSet::*".
62
63       ResultSet classes are associated with Result class of the same name.
64       For example, "My::Schema::Result::CD" will get the ResultSet class
65       "My::Schema::ResultSet::CD" if it is present.
66
67       Both Result and ResultSet namespaces are configurable via the
68       "result_namespace" and "resultset_namespace" options.
69
70       Another option, "default_resultset_class" specifies a custom default
71       ResultSet class for Result classes with no corresponding ResultSet.
72
73       All of the namespace and classname options are by default relative to
74       the schema classname.  To specify a fully-qualified name, prefix it
75       with a literal "+".  For example, "+Other::NameSpace::Result".
76
77       Warnings
78
79       You will be warned if ResultSet classes are discovered for which there
80       are no matching Result classes like this:
81
82         load_namespaces found ResultSet class $classname with no corresponding Result class
83
84       If a ResultSource instance is found to already have a ResultSet class
85       set using resultset_class to some other class, you will be warned like
86       this:
87
88         We found ResultSet class '$rs_class' for '$result_class', but it seems
89         that you had already set '$result_class' to use '$rs_set' instead
90
91       Examples
92
93         # load My::Schema::Result::CD, My::Schema::Result::Artist,
94         #    My::Schema::ResultSet::CD, etc...
95         My::Schema->load_namespaces;
96
97         # Override everything to use ugly names.
98         # In this example, if there is a My::Schema::Res::Foo, but no matching
99         #   My::Schema::RSets::Foo, then Foo will have its
100         #   resultset_class set to My::Schema::RSetBase
101         My::Schema->load_namespaces(
102           result_namespace => 'Res',
103           resultset_namespace => 'RSets',
104           default_resultset_class => 'RSetBase',
105         );
106
107         # Put things in other namespaces
108         My::Schema->load_namespaces(
109           result_namespace => '+Some::Place::Results',
110           resultset_namespace => '+Another::Place::RSets',
111         );
112
113       To search multiple namespaces for either Result or ResultSet classes,
114       use an arrayref of namespaces for that option.  In the case that the
115       same result (or resultset) class exists in multiple namespaces, later
116       entries in the list of namespaces will override earlier ones.
117
118         My::Schema->load_namespaces(
119           # My::Schema::Results_C::Foo takes precedence over My::Schema::Results_B::Foo :
120           result_namespace => [ 'Results_A', 'Results_B', 'Results_C' ],
121           resultset_namespace => [ '+Some::Place::RSets', 'RSets' ],
122         );
123
124   load_classes
125       Arguments: @classes?, { $namespace => [ @classes ] }+
126
127       "load_classes" is an alternative method to "load_namespaces", both of
128       which serve similar purposes, each with different advantages and
129       disadvantages.  In the general case you should use "load_namespaces",
130       unless you need to be able to specify that only specific classes are
131       loaded at runtime.
132
133       With no arguments, this method uses Module::Find to find all classes
134       under the schema's namespace. Otherwise, this method loads the classes
135       you specify (using use), and registers them (using "register_class").
136
137       It is possible to comment out classes with a leading "#", but note that
138       perl will think it's a mistake (trying to use a comment in a qw list),
139       so you'll need to add "no warnings 'qw';" before your load_classes
140       call.
141
142       If any classes found do not appear to be Result class files, you will
143       get the following warning:
144
145          Failed to load $comp_class. Can't find source_name method. Is
146          $comp_class really a full DBIC result class? Fix it, move it elsewhere,
147          or make your load_classes call more specific.
148
149       Example:
150
151         My::Schema->load_classes(); # loads My::Schema::CD, My::Schema::Artist,
152                                     # etc. (anything under the My::Schema namespace)
153
154         # loads My::Schema::CD, My::Schema::Artist, Other::Namespace::Producer but
155         # not Other::Namespace::LinerNotes nor My::Schema::Track
156         My::Schema->load_classes(qw/ CD Artist #Track /, {
157           Other::Namespace => [qw/ Producer #LinerNotes /],
158         });
159
160   storage_type
161       Arguments: $storage_type|{$storage_type, \%args}
162       Return Value: $storage_type|{$storage_type, \%args}
163       Default value: DBIx::Class::Storage::DBI
164
165       Set the storage class that will be instantiated when "connect" is
166       called.  If the classname starts with "::", the prefix
167       "DBIx::Class::Storage" is assumed by "connect".
168
169       You want to use this to set subclasses of DBIx::Class::Storage::DBI in
170       cases where the appropriate subclass is not autodetected.
171
172       If your storage type requires instantiation arguments, those are
173       defined as a second argument in the form of a hashref and the entire
174       value needs to be wrapped into an arrayref or a hashref.  We support
175       both types of refs here in order to play nice with your Config::[class]
176       or your choice. See DBIx::Class::Storage::DBI::Replicated for an
177       example of this.
178
179   exception_action
180       Arguments: $code_reference
181       Return Value: $code_reference
182       Default value: None
183
184       When "throw_exception" is invoked and "exception_action" is set to a
185       code reference, this reference will be called instead of "throw" in
186       DBIx::Class::Exception, with the exception message passed as the only
187       argument.
188
189       Your custom throw code must rethrow the exception, as "throw_exception"
190       is an integral part of DBIC's internal execution control flow.
191
192       Example:
193
194          package My::Schema;
195          use base qw/DBIx::Class::Schema/;
196          use My::ExceptionClass;
197          __PACKAGE__->exception_action(sub { My::ExceptionClass->throw(@_) });
198          __PACKAGE__->load_classes;
199
200          # or:
201          my $schema_obj = My::Schema->connect( .... );
202          $schema_obj->exception_action(sub { My::ExceptionClass->throw(@_) });
203
204   stacktrace
205       Arguments: boolean
206
207       Whether "throw_exception" should include stack trace information.
208       Defaults to false normally, but defaults to true if $ENV{DBIC_TRACE} is
209       true.
210
211   sqlt_deploy_hook
212       Arguments: $sqlt_schema
213
214       An optional sub which you can declare in your own Schema class that
215       will get passed the SQL::Translator::Schema object when you deploy the
216       schema via "create_ddl_dir" or "deploy".
217
218       For an example of what you can do with this, see "Adding Indexes And
219       Functions To Your SQL" in DBIx::Class::Manual::Cookbook.
220
221       Note that sqlt_deploy_hook is called by "deployment_statements", which
222       in turn is called before "deploy". Therefore the hook can be used only
223       to manipulate the SQL::Translator::Schema object before it is turned
224       into SQL fed to the database. If you want to execute post-deploy
225       statements which can not be generated by SQL::Translator, the currently
226       suggested method is to overload "deploy" and use dbh_do.
227

METHODS

229   connect
230       Arguments: @connectinfo
231       Return Value: $new_schema
232
233       Creates and returns a new Schema object. The connection info set on it
234       is used to create a new instance of the storage backend and set it on
235       the Schema object.
236
237       See "connect_info" in DBIx::Class::Storage::DBI for DBI-specific syntax
238       on the @connectinfo argument, or DBIx::Class::Storage in general.
239
240       Note that "connect_info" expects an arrayref of arguments, but
241       "connect" does not. "connect" wraps its arguments in an arrayref before
242       passing them to "connect_info".
243
244       Overloading
245
246       "connect" is a convenience method. It is equivalent to calling
247       $schema->clone->connection(@connectinfo). To write your own overloaded
248       version, overload "connection" instead.
249
250   resultset
251       Arguments: $source_name
252       Return Value: $resultset
253
254         my $rs = $schema->resultset('DVD');
255
256       Returns the DBIx::Class::ResultSet object for the registered source
257       name.
258
259   sources
260       Return Value: @source_names
261
262         my @source_names = $schema->sources;
263
264       Lists names of all the sources registered on this Schema object.
265
266   source
267       Arguments: $source_name
268       Return Value: $result_source
269
270         my $source = $schema->source('Book');
271
272       Returns the DBIx::Class::ResultSource object for the registered source
273       name.
274
275   class
276       Arguments: $source_name
277       Return Value: $classname
278
279         my $class = $schema->class('CD');
280
281       Retrieves the Result class name for the given source name.
282
283   txn_do
284       Arguments: $coderef, @coderef_args?
285       Return Value: The return value of $coderef
286
287       Executes $coderef with (optional) arguments @coderef_args atomically,
288       returning its result (if any). Equivalent to calling
289       $schema->storage->txn_do.  See "txn_do" in DBIx::Class::Storage for
290       more information.
291
292       This interface is preferred over using the individual methods
293       "txn_begin", "txn_commit", and "txn_rollback" below.
294
295       WARNING: If you are connected with "AutoCommit => 0" the transaction is
296       considered nested, and you will still need to call "txn_commit" to
297       write your changes when appropriate. You will also want to connect with
298       "auto_savepoint => 1" to get partial rollback to work, if the storage
299       driver for your database supports it.
300
301       Connecting with "AutoCommit => 1" is recommended.
302
303   txn_scope_guard
304       Runs "txn_scope_guard" on the schema's storage. See "txn_scope_guard"
305       in DBIx::Class::Storage.
306
307   txn_begin
308       Begins a transaction (does nothing if AutoCommit is off). Equivalent to
309       calling $schema->storage->txn_begin. See "txn_begin" in
310       DBIx::Class::Storage for more information.
311
312   txn_commit
313       Commits the current transaction. Equivalent to calling
314       $schema->storage->txn_commit. See "txn_commit" in DBIx::Class::Storage
315       for more information.
316
317   txn_rollback
318       Rolls back the current transaction. Equivalent to calling
319       $schema->storage->txn_rollback. See "txn_rollback" in
320       DBIx::Class::Storage for more information.
321
322   storage
323         my $storage = $schema->storage;
324
325       Returns the DBIx::Class::Storage object for this Schema. Grab this if
326       you want to turn on SQL statement debugging at runtime, or set the
327       quote character. For the default storage, the documentation can be
328       found in DBIx::Class::Storage::DBI.
329
330   populate
331       Arguments: $source_name, [ \@column_list, \@row_values+ ] | [
332       \%col_data+ ]
333       Return Value: \@result_objects (scalar context) | @result_objects (list
334       context)
335
336       A convenience shortcut to "populate" in DBIx::Class::ResultSet.
337       Equivalent to:
338
339        $schema->resultset($source_name)->populate([...]);
340
341       NOTE
342           The context of this method call has an important effect on what is
343           submitted to storage. In void context data is fed directly to
344           fastpath insertion routines provided by the underlying storage
345           (most often "execute_for_fetch" in DBI), bypassing the new and
346           insert calls on the Result class, including any augmentation of
347           these methods provided by components. For example if you are using
348           something like DBIx::Class::UUIDColumns to create primary keys for
349           you, you will find that your PKs are empty.  In this case you will
350           have to explicitly force scalar or list context in order to create
351           those values.
352
353   connection
354       Arguments: @args
355       Return Value: $new_schema
356
357       Similar to "connect" except sets the storage object and connection data
358       in-place on the Schema class. You should probably be calling "connect"
359       to get a proper Schema object instead.
360
361       Overloading
362
363       Overload "connection" to change the behaviour of "connect".
364
365   compose_namespace
366       Arguments: $target_namespace, $additional_base_class?
367       Return Value: $new_schema
368
369       For each DBIx::Class::ResultSource in the schema, this method creates a
370       class in the target namespace (e.g. $target_namespace::CD,
371       $target_namespace::Artist) that inherits from the corresponding classes
372       attached to the current schema.
373
374       It also attaches a corresponding DBIx::Class::ResultSource object to
375       the new $schema object. If $additional_base_class is given, the new
376       composed classes will inherit from first the corresponding class from
377       the current schema then the base class.
378
379       For example, for a schema with My::Schema::CD and My::Schema::Artist
380       classes,
381
382         $schema->compose_namespace('My::DB', 'Base::Class');
383         print join (', ', @My::DB::CD::ISA) . "\n";
384         print join (', ', @My::DB::Artist::ISA) ."\n";
385
386       will produce the output
387
388         My::Schema::CD, Base::Class
389         My::Schema::Artist, Base::Class
390
391   svp_begin
392       Creates a new savepoint (does nothing outside a transaction).
393       Equivalent to calling $schema->storage->svp_begin.  See "svp_begin" in
394       DBIx::Class::Storage for more information.
395
396   svp_release
397       Releases a savepoint (does nothing outside a transaction).  Equivalent
398       to calling $schema->storage->svp_release.  See "svp_release" in
399       DBIx::Class::Storage for more information.
400
401   svp_rollback
402       Rollback to a savepoint (does nothing outside a transaction).
403       Equivalent to calling $schema->storage->svp_rollback.  See
404       "svp_rollback" in DBIx::Class::Storage for more information.
405
406   clone
407       Arguments: %attrs?
408       Return Value: $new_schema
409
410       Clones the schema and its associated result_source objects and returns
411       the copy. The resulting copy will have the same attributes as the
412       source schema, except for those attributes explicitly overridden by the
413       provided %attrs.
414
415   throw_exception
416       Arguments: $message
417
418       Throws an exception. Obeys the exemption rules of DBIx::Class::Carp to
419       report errors from outer-user's perspective. See "exception_action" for
420       details on overriding this method's behavior.  If "stacktrace" is
421       turned on, "throw_exception"'s default behavior will provide a detailed
422       stack trace.
423
424   deploy
425       Arguments: \%sqlt_args, $dir
426
427       Attempts to deploy the schema to the current storage using
428       SQL::Translator.
429
430       See "METHODS" in SQL::Translator for a list of values for
431       "\%sqlt_args".  The most common value for this would be "{
432       add_drop_table => 1 }" to have the SQL produced include a "DROP TABLE"
433       statement for each table created. For quoting purposes supply
434       "quote_identifiers".
435
436       Additionally, the DBIx::Class parser accepts a "sources" parameter as a
437       hash ref or an array ref, containing a list of source to deploy. If
438       present, then only the sources listed will get deployed. Furthermore,
439       you can use the "add_fk_index" parser parameter to prevent the parser
440       from creating an index for each FK.
441
442   deployment_statements
443       Arguments: See "deployment_statements" in DBIx::Class::Storage::DBI
444       Return Value: $listofstatements
445
446       A convenient shortcut to "$self->storage->deployment_statements($self,
447       @args)".  Returns the statements used by "deploy" and "deploy" in
448       DBIx::Class::Storage.
449
450   create_ddl_dir
451       Arguments: See "create_ddl_dir" in DBIx::Class::Storage::DBI
452
453       A convenient shortcut to "$self->storage->create_ddl_dir($self,
454       @args)".
455
456       Creates an SQL file based on the Schema, for each of the specified
457       database types, in the given directory.
458
459   ddl_filename
460       Arguments: $database-type, $version, $directory, $preversion
461       Return Value: $normalised_filename
462
463         my $filename = $table->ddl_filename($type, $version, $dir, $preversion)
464
465       This method is called by "create_ddl_dir" to compose a file name out of
466       the supplied directory, database type and version number. The default
467       file name format is: "$dir$schema-$version-$type.sql".
468
469       You may override this method in your schema if you wish to use a
470       different format.
471
472        WARNING
473
474        Prior to DBIx::Class version 0.08100 this method had a different signature:
475
476           my $filename = $table->ddl_filename($type, $dir, $version, $preversion)
477
478        In recent versions variables $dir and $version were reversed in order to
479        bring the signature in line with other Schema/Storage methods. If you
480        really need to maintain backward compatibility, you can do the following
481        in any overriding methods:
482
483           ($dir, $version) = ($version, $dir) if ($DBIx::Class::VERSION < 0.08100);
484
485   thaw
486       Provided as the recommended way of thawing schema objects. You can call
487       "Storable::thaw" directly if you wish, but the thawed objects will not
488       have a reference to any schema, so are rather useless.
489
490   freeze
491       This doesn't actually do anything beyond calling nfreeze, it is just
492       provided here for symmetry.
493
494   dclone
495       Arguments: $object
496       Return Value: dcloned $object
497
498       Recommended way of dcloning DBIx::Class::Row and DBIx::Class::ResultSet
499       objects so their references to the schema object (which itself is not
500       cloned) are properly maintained.
501
502   schema_version
503       Returns the current schema class' $VERSION in a normalised way.
504
505   register_class
506       Arguments: $source_name, $component_class
507
508       This method is called by "load_namespaces" and "load_classes" to
509       install the found classes into your Schema. You should be using those
510       instead of this one.
511
512       You will only need this method if you have your Result classes in files
513       which are not named after the packages (or all in the same file). You
514       may also need it to register classes at runtime.
515
516       Registers a class which isa DBIx::Class::ResultSourceProxy. Equivalent
517       to calling:
518
519         $schema->register_source($source_name, $component_class->result_source_instance);
520
521   register_source
522       Arguments: $source_name, $result_source
523
524       This method is called by "register_class".
525
526       Registers the DBIx::Class::ResultSource in the schema with the given
527       source name.
528
529   unregister_source
530       Arguments: $source_name
531
532       Removes the DBIx::Class::ResultSource from the schema for the given
533       source name.
534
535   register_extra_source
536       Arguments: $source_name, $result_source
537
538       As "register_source" but should be used if the result class already has
539       a source and you want to register an extra one.
540
541   compose_connection (DEPRECATED)
542       Arguments: $target_namespace, @db_info
543       Return Value: $new_schema
544
545       DEPRECATED. You probably wanted compose_namespace.
546
547       Actually, you probably just wanted to call connect.
548

FURTHER QUESTIONS?

550       Check the list of additional DBIC resources.
551
553       This module is free software copyright by the DBIx::Class (DBIC)
554       authors. You can redistribute it and/or modify it under the same terms
555       as the DBIx::Class library.
556
557
558
559perl v5.28.0                      2018-01-29            DBIx::Class::Schema(3)
Impressum