Rose::DB::Object(3pm)

🌸 NAME 🌸

Rose::DB::Object β€” the extensible, high performance object-relational mapper (ORM), aka the Rose::DB::Object(3pm) bestie you're reading about right now. No cap: it's the base-class energy that turns database rows into Perl objects and makes it look easy. πŸ’…


✨ SYNOPSIS ✨

okay so before we get into the lore, here's the synopsis exactly as the original lays it out. I did not touch the code, bestie β€” every comment, ..., package, and option is here in its full unedited glory: 🫢

         ## For an informal overview of Rose::DB::Object, please
         ## see the Rose::DB::Object::Tutorial documentation.  The
         ## reference documentation follows.

         ## First, set up your Rose::DB data sources, otherwise you
         ## won't be able to connect to the database at all.  See
         ## the Rose::DB documentation for more information.  For
         ## a quick start, see the Rose::DB::Tutorial documentation.

         ##
         ## Create classes - two possible approaches:
         ##

         #
         # 1. Automatic configuration
         #

         package Category;
         use base qw(Rose::DB::Object);
         __PACKAGE__->meta->setup
         (
           table => 'categories',
           auto  => 1,
         );

         ...

         package Price;
         use base qw(Rose::DB::Object);
         __PACKAGE__->meta->setup
         (
           table => 'prices',
           auto  => 1,
         );

         ...

         package Product;
         use base qw(Rose::DB::Object);
         __PACKAGE__->meta->setup
         (
           table => 'products',
           auto  => 1,
         );

         #
         # 2. Manual configuration
         #

         package Category;

         use base qw(Rose::DB::Object);

         __PACKAGE__->meta->setup
         (
           table => 'categories',

           columns =>
           [
             id          => { type => 'int', primary_key => 1 },
             name        => { type => 'varchar', length => 255 },
             description => { type => 'text' },
           ],

           unique_key => 'name',
         );

         ...

         package Price;

         use base qw(Rose::DB::Object);

         __PACKAGE__->meta->setup
         (
           table => 'prices',

           columns =>
           [
             id         => { type => 'int', primary_key => 1 },
             price      => { type => 'decimal' },
             region     => { type => 'char', length => 3 },
             product_id => { type => 'int' }
           ],

           unique_key => [ 'product_id', 'region' ],
         );

         ...

         package Product;

         use base qw(Rose::DB::Object);

         __PACKAGE__->meta->setup
         (
           table => 'products',

           columns =>
           [
             id          => { type => 'int', primary_key => 1 },
             name        => { type => 'varchar', length => 255 },
             description => { type => 'text' },
             category_id => { type => 'int' },

             status =>
             {
               type      => 'varchar',
               check_in  => [ 'active', 'inactive' ],
               default   => 'inactive',
             },

             start_date  => { type => 'datetime' },
             end_date    => { type => 'datetime' },

             date_created     => { type => 'timestamp', default => 'now' },
             last_modified    => { type => 'timestamp', default => 'now' },
           ],

           unique_key => 'name',

           foreign_keys =>
           [
             category =>
             {
               class       => 'Category',
               key_columns => { category_id => 'id' },
             },
           ],

           relationships =>
           [
             prices =>
             {
               type       => 'one to many',
               class      => 'Price',
               column_map => { id => 'product_id' },
             },
           ],
         );

         ...

         #
         # Example usage
         #

         $product = Product->new(id          => 123,
                                 name        => 'GameCube',
                                 status      => 'active',
                                 start_date  => '11/5/2001',
                                 end_date    => '12/1/2007',
                                 category_id => 5);

         $product->save;

         ...

         $product = Product->new(id => 123);
         $product->load;

         # Load foreign object via "one to one" relationship
         print $product->category->name;

         $product->end_date->add(days => 45);

         $product->save;

         ...

         $product = Product->new(id => 456);
         $product->load;

         # Load foreign objects via "one to many" relationship
         print join ' ', $product->prices;

         ...

πŸ’– DESCRIPTION πŸ’–

Rose::DB::Object is the base class for objects that encapsulate a single row in a database table. These Rose::DB::Object-derived objects are sometimes just called β€œRose::DB::Object objects” in the docs for brevity, but bestie, derivation is the only reasonable way to use this class. Like, do not try to use it raw β€” that's not the vibe. πŸ™ˆ

It inherits from, and follows the conventions of, Rose::Object. See the Rose::Object documentation for more information. Also: for an informal overview of this module distribution, consult the Rose::DB::Object::Tutorial.


🚧 Restrictions 🚧

Rose::DB::Object objects can represent rows in almost any database table, subject to these constraints:

  • The database server must be supported by Rose::DB.
  • The database table must have a primary key.
  • The primary key must not allow null values in any of its columns.

Those are literally the only hard and fast rules, but there can be other real-life plot twists you'll need to work around. 😭

The most common example is a column name in the database table that conflicts with the name of a method in the Rose::DB::Object API. Two possible workarounds: either explicitly alias the column, or define a mapping function. See the alias_column and column_name_to_method_name_mapper methods in the Rose::DB::Object::Metadata documentation for more details.

There are also varying degrees of support for data types in each database server supported by Rose::DB. If you have a table that uses a data type not supported by an existing Rose::DB::Object::Metadata::Column-derived class, you will have to write your own column class and then map it to a type name using Rose::DB::Object::Metadata's column_type_class method, yada yada. (Or, of course, you can map the new type to an existing column class.) iykyk πŸ’…

The entire framework is extensible. This module distribution contains straightforward implementations of the most common column types, but there's certainly more that can be done. Submissions are welcome. 🌈


πŸ‘‘ Features πŸ‘‘

Rose::DB::Object provides the following functions:

  • Create a row in the database by saving a newly constructed object.
  • Initialize an object by loading a row from the database.
  • Update a row by saving a modified object back to the database.
  • Delete a row from the database.
  • Fetch an object referred to by a foreign key in the current object. (i.e., β€œone to one” and β€œmany to one” relationships.)
  • Fetch multiple objects that refer to the current object, either directly through foreign keys or indirectly through a mapping table. (i.e., β€œone to many” and β€œmany to many” relationships.)
  • Load an object along with β€œforeign objects” that are related through any of the supported relationship types.

Objects can be loaded based on either a primary key or a unique key. Since all tables fronted by Rose::DB::Objects must have non-null primary keys, insert, update, and delete operations are done based on the primary key.

In addition, its sibling class, Rose::DB::Object::Manager, can do the following:

  • Fetch multiple objects from the database using arbitrary query conditions, limits, and offsets.
  • Iterate over a list of objects, fetching from the database in response to each step of the iterator.
  • Fetch objects along with β€œforeign objects” (related through any of the supported relationship types) in a single query by automatically generating the appropriate SQL join(s).
  • Count the number of objects that match a complex query.
  • Update objects that match a complex query.
  • Delete objects that match a complex query.

Rose::DB::Object::Manager can be subclassed and used separately (the recommended approach), or it can create object manager methods within a Rose::DB::Object subclass. See the Rose::DB::Object::Manager documentation for more information.

Rose::DB::Object can parse, coerce, inflate, and deflate column values on your behalf, providing the most convenient possible data representations on the Perl side of the fence, while allowing the programmer to completely forget about the ugly details of the data formats required by the database. Default implementations are included for most common column types, and the framework is completely extensible. Slay. πŸ’š

Finally, the Rose::DB::Object::Loader can be used to automatically create a suite of Rose::DB::Object and Rose::DB::Object::Manager subclasses based on the contents of the database.


πŸŽ€ Configuration πŸŽ€

Before Rose::DB::Object can do any useful work, you must register at least one Rose::DB data source. By default, Rose::DB::Object instantiates a Rose::DB object by passing no arguments to its constructor. (See the db method.) If you register a Rose::DB data source using the default type and domain, this will work fine. Otherwise, you must override the meta method in your Rose::DB::Object subclass and have it return the appropriate Rose::DB-derived object.

To define your own Rose::DB::Object-derived class, you must describe the table that your class will act as a front-end for. This is done through the Rose::DB::Object::Metadata object associated with each Rose::DB::Object-derived class. The metadata object is accessible via Rose::DB::Object's meta method.

Metadata objects can be populated manually or automatically. Both techniques are shown in the synopsis above. The automatic mode works by asking the database itself for the information. There are some caveats to this approach. See the auto-initialization section of the Rose::DB::Object::Metadata documentation for more information. 🫢


πŸ¦‹ Serial and Auto-Incremented Columns πŸ¦‹

Most databases provide a way to use a series of arbitrary integers as primary key column values. Some support a native "SERIAL" column data type. Others use a special auto-increment column attribute.

Rose::DB::Object supports at least one such serial or auto-incremented column type in each supported database. In all cases, the Rose::DB::Object-derived class setup is the same:

    package My::DB::Object;
    ...
    __PACKAGE__->meta->setup
    (
      columns =>
      [
        id => { type => 'serial', primary_key => 1, not_null => 1 },
        ...
      ],
      ...
    );

(Note that the column doesn't have to be named "id"; it can be named anything.)

If the database column uses big integers, use "bigserial" column "type" instead. Big integer energy. ✨

So like, given that column metadata definition from up there ☝️, Rose::DB::Object will auto-generate and/or retrieve the primary key column value whenever an object gets save()d. Iconic. Check it:

$o = My::DB::Object->new(name => 'bud'); # no id specified
$o->save; # new id value generated here

print "Generated new id value: ", $o->id;

Now β€” huge caveat, bestie, do not skip this β€” this only works if the matching column definition in the database is set up correctly. The exact technique varies from vendor to vendor. Below are examples of primary key column definitions that provide auto-generated values, one example for each of the databases supported by Rose::DB. πŸ’…

  • PostgreSQL
CREATE TABLE mytable
(
  id   SERIAL PRIMARY KEY,
  ...
);
  • MySQL
CREATE TABLE mytable
(
  id   INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  ...
);
  • SQLite
CREATE TABLE mytable
(
  id   INTEGER PRIMARY KEY AUTOINCREMENT,
  ...
);
  • Informix
CREATE TABLE mytable
(
  id   SERIAL NOT NULL PRIMARY KEY,
  ...
);
  • Oracle

Since Oracle does not natively support a serial or auto-incremented column data type, an explicit sequence and trigger must be created to simulate the behavior. The sequence should be named according to this convention: <table>_<column>_seq. For example, if the table is named mytable and the column is named id, then the sequence should be named mytable_id_seq. Here's an example database setup.

CREATE TABLE mytable
(
  id   INT NOT NULL PRIMARY KEY,
  ...
);

CREATE SEQUENCE mytable_id_seq;

CREATE TRIGGER mytable_insert BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
   IF :new.id IS NULL THEN
       :new.id := mytable_id_seq.nextval;
   END IF;
END;

Note the conditional that checks if :new.id is null, which allows the value of the id column to be set explicitly. If a non-NULL value for the id column is provided, then a new value is not pulled from the sequence. 🧚

If the sequence is not named according to the <table>_<column>_seq convention, you can specify the sequence name explicitly in the column metadata. Example:

columns =>
[
  id => { type => 'serial', primary_key => 1, not_null => 1,
          sequence => 'some_other_seq' },
  ...

Okay but what if your table has a multi-column primary key, or uses a column type that doesn't support auto-generated values? No panic β€” you can define a custom primary key generator function using the primary_key_generator method of the Rose::DB::Object::Metadata-derived object that contains the metadata for this class. Slay, custom keys. Example:

package MyDBObject;

use base qw(Rose::DB::Object);

__PACKAGE__->meta->setup
(
  table => 'mytable',

  columns =>
  [
    k1   => { type => 'int', not_null => 1 },
    k2   => { type => 'int', not_null => 1 },
    name => { type => 'varchar', length => 255 },
    ...
  ],

  primary_key_columns => [ 'k1', 'k2' ],

  primary_key_generator => sub
  {
    my($meta, $db) = @_;

    # Generate primary key values somehow
    my $k1 = ...;
    my $k2 = ...;

    return $k1, $k2;
  },
);

See the Rose::DB::Object::Metadata documentation for more information on custom primary key generators. πŸ“š

Inheritance

Simple, single inheritance between Rose::DB::Object-derived classes is supported. (Multiple inheritance is not currently supported β€” sorry to the overachievers, we can't have it all.) The first time the metadata object for a given class is accessed, it is created by making a one-time "deep copy" of the base class's metadata object (as long as that base class has one or more columns set). This includes all columns, relationships, foreign keys, and other metadata from the base class. From that point on, the subclass may add to or modify its metadata without affecting any other class. Main character independence, love that for us. ✨

Tip: When using perl 5.8.0 or later, the Scalar::Util::Clone module is highly recommended. If it's installed, it will be used to more efficiently clone base-class metadata objects.

If the base class has already been initialized, the subclass must explicitly specify whether it wants to create a new set of column and relationship methods, or merely inherit the methods from the base class. If the subclass contains any metadata modifications that affect method creation, then it must create a new set of methods to reflect those changes. No vibe-based guessing here, you gotta say it out loud. πŸ—£οΈ

Finally, note that column types cannot be changed "in-place." To change a column type, delete the old column and add a new one with the same name. This can be done in one step with the replace_column method. (Not me dropping the whole column and rebuilding it β€” glow-up via replacement. πŸ’…)

Example:

package BaseClass;
use base 'Rose::DB::Object';

__PACKAGE__->meta->setup
(
  table => 'objects',

  columns =>
  [
    id    => { type => 'int', primary_key => 1 },
    start => { type => 'scalar' },
  ],
);

...

package SubClass;
use base 'BaseClass';

# Set a default value for this column.
__PACKAGE__->meta->column('id')->default(123);

# Change the "start" column into a datetime column.
__PACKAGE__->meta->replace_column(start => { type => 'datetime' });

# Initialize, replacing any inherited methods with newly created ones
__PACKAGE__->meta->initialize(replace_existing => 1);

...

$b = BaseClass->new;

$id = $b->id; # undef

$b->start('1/2/2003');
print $b->start; # '1/2/2003' (plain string)

$s = SubClass->new;

$id = $s->id; # 123

$b->start('1/2/2003'); # Value is converted to a DateTime object
print $b->start->strftime('%B'); # 'January'

To preserve all inherited methods in a subclass, do this instead:

package SubClass;
use base 'BaseClass';
__PACKAGE__->meta->initialize(preserve_existing => 1);

Error Handling

Error handling for Rose::DB::Object-derived objects is controlled by the error_mode method of the Rose::DB::Object::Metadata object associated with the class (accessible via the meta method). The default setting is fatal, which means that Rose::DB::Object methods will croak if they encounter an error. Yeah, it will simply end you. πŸ’€

PLEASE NOTE: The error return values described in the object method documentation are only relevant when the error mode is set to something "non-fatal." In other words, if an error occurs, you'll never see any of those return values if the selected error mode dies or croaks or otherwise throws an exception when an error occurs. So like, don't count on getting a cute little undef back when things are set to fatal β€” you're getting an exception, periodt. 🫢

CONSTRUCTOR πŸ‘‘

new PARAMS

Returns a new Rose::DB::Object constructed according to PARAMS, where PARAMS are name/value pairs. Any object method is a valid parameter name. Like, any of them. That's the whole menu. πŸŽ€


CLASS METHODS 🌈

init_db

Returns the Rose::DB-derived object used to access the database in the absence of an explicit db value. The default implementation simply calls Rose::DB->new() with no arguments.

Override this method in your subclass in order to use a different default data source. Note: This method must be callable as both an object method and a class method. Yes, both. It's flexible like that. πŸ¦‹

meta

Returns the Rose::DB::Object::Metadata-derived object associated with this class. This object describes the database table whose rows are fronted by this class: the name of the table, its columns, unique keys, foreign keys, etc. Basically the whole backstage situation. ✨

See the Rose::DB::Object::Metadata documentation for more information.

meta_class

Return the name of the Rose::DB::Object::Metadata-derived class used to store this object's metadata. Subclasses should override this method if they want to use a custom Rose::DB::Object::Metadata subclass. (See the source code for Rose::DB::Object::Std for an example of this.) πŸ‘€


OBJECT METHODS πŸ’–

db [DB]

Get or set the Rose::DB object used to access the database that contains the table whose rows are fronted by the Rose::DB::Object-derived class.

If it does not already exist, this object is created with a simple, argument-less call to Rose::DB->new(). To override this default in a subclass, override the init_db method and return the Rose::DB to be used as the new default. πŸŽ€

init_db

Returns the Rose::DB-derived object used to access the database in the absence of an explicit db value. The default implementation simply calls Rose::DB->new() with no arguments.

Override this method in your subclass in order to use a different default data source. Note: This method must be callable as both an object method and a class method. (Yeah, it shows up in both lists, it's that method. Iykyk. πŸ’…)

dbh [DBH]

Get or set the DBI database handle contained in db. Simple as. 🫢

delete [PARAMS]

Delete the row represented by the current object. The object must have been previously loaded from the database (or must otherwise have a defined primary key value) in order to be deleted β€” no key, no delete, them's the rules. Returns true if the row was deleted or did not exist, false otherwise.

PARAMS are optional name/value pairs. Valid PARAMS are:

cascade TYPE

Also process related rows. TYPE must be delete, null, or 1. The value 1 is an alias for delete. Passing an illegal TYPE value will cause a fatal error. πŸ™ˆ So, you know, pick a real one.

For each "one to many" relationship, all of the rows in the foreign ("many") table that reference the current object ("one") will be deleted in delete mode, or will have the column(s) that reference the current object set to NULL in null mode.

For each "many to many" relationship, all of the rows in the "mapping table" that reference the current object will deleted in delete mode, or will have the columns that reference the two tables that the mapping table maps between set to NULL in null mode.

For each "one to one" relationship or foreign key with a "one to one" relationship type, all of the rows in the foreign table that reference the current object will deleted in delete mode, or will have the column(s) that reference the current object set to NULL in null mode.

In all modes, if the db is not currently in a transaction, a new transaction is started. If any part of the cascaded delete fails, the transaction is rolled back. So either the whole chain-eating delete situation goes through, or none of it does. All-or-nothing energy. πŸ”₯

  • prepare_cached BOOL β€” if this is true, then DBI's prepare_cached method gets used (instead of plain prepare) when preparing the SQL statement that deletes the object. If you omit it, the default value comes from the metadata object's dbi_prepare_cached class method. ✨

Okay so about that cascaded delete thing we just talked about β€” it plays it safe, like, very safe. It only deletes rows that aren't referenced by any other rows (according to the metadata each Rose::DB::Object-derived class provides). And honestly? I strongly recommend you implement "cascaded delete" in the database itself rather than leaning on this feature. It'll be faster and more robust than doing it "client-side," no cap. You may also want to cascade only to certain tables, or otherwise deviate from the "safe" plan. If your database supports automatic cascaded delete and/or triggers, please consider using those features. πŸ’…

Fr fr, the client-side cascade is a convenience, not a flex. Let the database cook.

error 🫢

Returns the text message associated with the last error that occurred.

insert [PARAMS] πŸ”₯

Insert the current object into the database table. Only use this method when you're absolutely sure you want to force the current object to be inserted rather than updated. In most circumstances the recommendation is to use save instead β€” save will "do the right thing," executing an insert or update as is appropriate for the current situation.

PARAMS are optional name/value pairs. Valid PARAMS are:

  • changes_only BOOL β€” if true, only the columns whose values have been modified are included in the insert query. Otherwise, all columns are included. Note that any column with a default value set in its column metadata counts as "modified" during an insert operation. If omitted, the default value of this parameter is determined by the metadata object's default_insert_changes_only class method, which returns false by default. ✨
  • prepare_cached BOOL β€” if true, DBI's prepare_cached method is used (instead of the prepare method) when preparing the SQL statement that will insert the object. If omitted, the default value is determined by the metadata object's dbi_prepare_cached class method.

Returns true if the row was inserted successfully, false otherwise. The true value returned on success will be the object itself. If the object overloads its boolean value such that it's not true, then a true value is returned instead of the object itself. πŸŽ€

load [PARAMS] πŸ¦‹

Load a row from the database table, initializing the object with the values from that row. An object can be loaded based on either a primary key or a unique key.

Returns true if the row was loaded successfully, undef if the row could not be loaded due to an error, or zero (0) if the row does not exist. The true value returned on success will be the object itself. If the object overloads its boolean value such that it's not true, then a true value is returned instead of the object itself. 🫢

When loading based on a unique key, unique keys are considered in the order in which they were defined in the metadata for this class. If the object has defined values for every column in a unique key, then that key is used. If no such key is found, then the first key for which the object has at least one defined value is used.

PARAMS are optional name/value pairs. Valid PARAMS are:

  • for_update BOOL β€” if true, this parameter is translated into the equivalent of passing the lock parameter and setting the "type" to "for update". For example, these are both equivalent:
$object->load(for_update => 1);
$object->load(lock => { type => 'for update' });

See the lock parameter below for more information.

  • lock [ TYPE | HASHREF ] β€” load the object using some form of locking. These lock directives have database-specific behavior and not all directives are supported by all databases. The value should be a reference to a hash or a TYPE string, which is equivalent to setting the value of the "type" key in the hash reference form. For example, these are both equivalent:
$object->load(lock => 'for update');
$object->load(lock => { type => 'for update' });

Valid hash keys are:

  • columns ARRAYREF β€” a reference to an array of column names to lock. References to scalars will be de-referenced and used as-is, included literally in the SQL locking clause.
  • "nowait BOOL" β€” if true, do not wait to acquire the lock. If supported, this is usually done by adding a "NOWAIT" directive to the SQL.
  • "type TYPE" β€” the lock type. Valid values for TYPE are "for update" and "shared". This parameter is required unless the for_update parameter was passed with a true value.
  • "wait TIME" β€” wait for the specified TIME (generally seconds) before giving up on acquiring the lock. If supported, this is usually done by adding a "WAIT ..." clause to the SQL.
  • nonlazy BOOL β€” if true, then all columns are fetched from the database, even lazy columns. If omitted, the default is false.
  • prepare_cached BOOL β€” if true, then DBI's prepare_cached method is used (instead of the prepare method) when preparing the SQL query that will load the object. If omitted, the default value is determined by the metadata object's dbi_prepare_cached class method.
  • speculative BOOL β€” if this parameter is passed with a true value, and if the load failed because the row was not found, then the error_mode setting is ignored and zero (0) is returned. In the absence of an explicitly set value, this parameter defaults to the value returned by the metadata object's default_load_speculative method.
  • use_key KEY β€” use the unique key named KEY to load the object. This overrides the unique key selection process described above. The key must have a defined value in at least one of its columns.
  • with OBJECTS β€” load the object and the specified "foreign objects" simultaneously. OBJECTS should be a reference to an array of foreign key or relationship names.
SUBCLASS NOTE: if you're going to override the load method in your subclass, you must pass an alias to the actual object as the first argument to the method, rather than passing a copy of the object reference. Example:
# This is the CORRECT way to override load() while still
# calling the base class version of the method.
sub load
{
  my $self = $_[0]; # Copy, not shift

  ... # Do your stuff

  shift->SUPER::load(@_); # Call superclass
}

Now here's the wrong way:

# This is the WRONG way to override load() while still
# calling the base class version of the method.
sub load
{
  my $self = shift; # WRONG! The alias to the object is now lost!

  ... # Do your stuff

  $self->SUPER::load(@_); # This won't work right!
}

This requirement exists in order to preserve some sneaky object-replacement optimizations in the base class implementation of load. At some point, those optimizations may change or go away. But if you follow these guidelines, your code will continue to work no matter what. πŸ’€

not_found 🌸

Returns true if the previous call to load failed because a row in the database table with the specified primary or unique key did not exist, false otherwise.

meta πŸ‘‘

Returns the Rose::DB::Object::Metadata object associated with this class. This object describes the database table whose rows are fronted by this class: the name of the table, its columns, unique keys, foreign keys, etc.

See the Rose::DB::Object::Metadata documentation for more information.

save [PARAMS] πŸ’–

Save the current object to the database table. In the absence of PARAMS, if the object was previously loaded from the database, the row will be updated. Otherwise, a new row will be inserted. PARAMS are name/value pairs. Valid PARAMS are listed below.

Actions associated with sub-objects that were added or deleted using one of the "*_on_save" relationship or foreign key method types are also performed when this method is called. If there are any such actions to perform, a new transaction is started if the db is not already in one, and rollback() is called if any of the actions fail during the save(). Example:

$product = Product->new(name => 'Sled');
$vendor  = Vendor->new(name => 'Acme');

$product->vendor($vendor);

# Product and vendor records created and linked together,
# all within a single transaction.
$product->save;

See the "making methods" sections of the Rose::DB::Object::Metadata::Relationship and Rose::DB::Object::Metadata::ForeignKey documentation for a description of the "method map" associated with each relationship and foreign key. Only the actions initiated through one of the "*_on_save" method types are handled when save() is called. See the documentation for each individual "*_on_save" method type for more specific information. ✨

Valid parameters to save() are:

  • cascade BOOL β€” if true, then sub-objects related to this object through a foreign key or relationship that have been previously loaded using methods called on this object and that contain unsaved changes will be saved after the parent object is saved. This proceeds recursively through all sub-objects. (All other parameters to the original call to save are also passed on when saving sub-objects.)

All database operations are done within a single transaction. If the db is not currently in a transaction, a new transaction is started. If any part of the cascaded save fails, the transaction is rolled back. πŸ”₯

Example β€” watch the cascade do its thing:

$p = Product->new(id => 123)->load;

print join(', ', $p->colors); # related Color objects loaded
$p->colors->[0]->code('zzz'); # one Color object is modified

# The Product object and the modified Color object are saved
$p->save(cascade => 1);
  • changes_only BOOL β€” like, if this is true, only the columns whose values actually changed get shoved into the insert or update query. Otherwise every eligible column comes along for the ride. Oh and heads up: any column with a default value set in its column metadata counts as "modified" during an insert. If you omit this param, the default comes from the metadata object's default_update_changes_only class method on update, and its default_insert_changes_only class method on insert β€” and both of those return false by default πŸ’…
  • insert BOOL β€” set it true and an insert is attempted, periodt. Doesn't matter if the object was previously loaded from the database or not.
  • prepare_cached BOOL β€” if true, DBI's prepare_cached method gets used (instead of plain old prepare) when preparing the SQL that's gonna save your object. Omit it and the default comes from the metadata object's dbi_prepare_cached class method.
  • update BOOL β€” set it true and an update is attempted, regardless of whether the object was previously loaded from the database.
Real talk: passing both the insert and update params in a single call is an error. Pick a lane bestie 😭

Returns true if the row got inserted or updated successfully, false otherwise. And the true value on success? It's the object itself πŸ‘‘ (unless your object overloads its boolean value in a way that makes it not-true β€” then you just get a plain true value instead of the object).

If an insert happened and the primary key is a single column that supports auto-generated values, then the object accessor for that primary key column will hold the auto-generated value. Peep the Serial and Auto-Incremented Columns section for the full tea πŸ«–

✨ update [PARAMS] ✨

Update the current object in the database table. Bestie, only reach for this one when you're absolutely certain you want to force the current object to be updated rather than inserted. In most circumstances I'm begging you to use save instead β€” save literally "does the right thing," firing off an insert or an update as appropriate for whatever situation you're in 🌸

PARAMS are optional name/value pairs. The valid ones are:

  • changes_only BOOL β€” true means only the columns whose values have been modified get updated. Otherwise, all columns whose values were loaded from the database get updated. Omit it and the default comes from the metadata object's default_update_changes_only class method, which returns false by default.
  • prepare_cached BOOL β€” if true, DBI's prepare_cached method is used (instead of prepare) when preparing the SQL statement that will insert the object. If omitted, the default value of this parameter is determined by the metadata object's dbi_prepare_cached class method.

Returns true if the row was updated successfully, false otherwise. The true value on success is the object itself β€” same deal as before, if the object overloads its boolean value so it's not true, you get a true value instead of the object πŸ¦‹


πŸ”’ RESERVED METHODS πŸ”’

Okay so, as the Rose::DB::Object::Metadata docs explain, every column in the database table gets its own get/set accessor method on the Rose::DB::Object. But the Rose::DB::Object API already defines a ton of methods (load, save, meta, etc.) β€” so if a column happens to share a name with an existing method, we have a situation πŸ™ˆ The solution is to alias such columns using Rose::DB::Object::Metadata's alias_column method.

Here's the full list of method names reserved by the Rose::DB::Object API. Got a column with one of these names? You must alias it.

db
dbh
delete
DESTROY
error
init_db
_init_db
insert
load
meta
meta_class
not_found
save
update
Not all of these methods are public, bestie. They do NOT suddenly become public just because you now know their names πŸ’€ Remember the stated policy of the Rose web application framework: if a method is not documented, it does not exist. (And no, the list of method names above does not constitute "documentation.") We don't make the rules, we just respect them ✨

🌈 DEVELOPMENT POLICY 🌈

The Rose development policy applies to this module and to all Rose::* modules. Please install Rose from CPAN and then run "perldoc Rose" for more info πŸŽ€

🫢 SUPPORT 🫢

For an informal overview of Rose::DB::Object, go read the Rose::DB::Object::Tutorial:

perldoc Rose::DB::Object::Tutorial

Got any Rose::DB::Object questions or problems? You can post them to the Rose::DB::Object mailing list. To subscribe or browse the archives, click through here:

<http://groups.google.com/group/rose-db-object>

The mailing list is the preferred support mechanism, but you can also email the author (see below) or file bugs using the CPAN bug tracking system:

<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Rose-DB-Object>

There's also a wiki and other resources linked from the Rose project home page:

<http://rosecode.org>

πŸ’œ CONTRIBUTORS πŸ’œ

Shoutout to the icons: Bradley C Bailey, Graham Barr, Kostas Chatzikokolakis, David Christensen, Lucian Dragus, Justin Ellison, Perrin Harkins, Cees Hek, Benjamin Hitz, Dave Howorth, Peter Karman, Ed Loehr, Adam Mackler, Michael Reece, Thomas Whaples, Douglas Wilson, Teodor Zlatanov 🌟

πŸ‘‘ AUTHOR πŸ‘‘

John C. Siracusa (siracusa@gmail.com)

πŸ“œ LICENSE πŸ“œ

Copyright (c) 2010 by John C. Siracusa. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


And that's a wrap on the whole page, bestie!! πŸŽ‰ You just read Rose::DB::Object(3pm) β€” Perl v5.40.1, dated 2025-08-21, straight from the User Contributed Perl Documentation. Now go forth and slay those database objects πŸ’…πŸ§šπŸ“

πŸ“¦ where this page comes from