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

METHODS

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

AUTHORS

566       Matt S. Trout <mst@shadowcatsystems.co.uk>
567

LICENSE

569       You may distribute this code under the same terms as Perl itself.
570
571
572
573perl v5.12.0                      2010-05-12            DBIx::Class::Schema(3)
Impressum