---
name: "Jifty::DBI::Record"
section: "3pm"
platform: "linux"
package: "libjifty-dbi-perl"
version: "0.78-3"
release: "Debian 13 (Trixie)"
platforms: ["linux"]
url: "https://new.carta.tech/Jifty::DBI::Record"
---

# Jifty::DBI::Record(3pm)

Superclass for records loaded by Jifty::DBI::Collection

## NAME

Jifty::DBI::Record - Superclass for records loaded by Jifty::DBI::Collection

## SYNOPSIS

```
  package MyRecord;
  use base qw/Jifty::DBI::Record/;
```

## DESCRIPTION

Jifty::DBI::Record encapsulates records and tables as part of the Jifty::DBI object-relational mapper.

## METHODS

### new ARGS

Instantiate a new, empty record object.

ARGS is a hash used to pass parameters to the `"_init()"` function.

Unless it is overloaded, the **\_init()** function expects one key of 'handle' with a value containing a reference to a Jifty::DBI::Handle object.

### id

Returns this row's primary key.

### primary\_keys

Return a hash of the values of our primary keys for this function.

### \_accessible COLUMN ATTRIBUTE

Private method.

DEPRECATED

Returns undef unless `"COLUMN"` has a true value for `"ATTRIBUTE"`.

Otherwise returns `"COLUMN"`'s value for that attribute.

### \_primary\_keys

Return our primary keys. (Subclasses should override this, but our default is that we have one primary key, named 'id'.)

### \_init\_columns

Sets up the primary key columns.

### \_init\_methods\_for\_columns

This is an internal method responsible for calling "\_init\_methods\_for\_column" for each column that has been configured.

### schema\_version

If present, this method must return a string in '1.2.3' format to be used to determine which columns are currently active in the schema. That is, this value is used to determine which columns are defined, based upon comparison to values set in `"till"` and `"since"`.

If no implementation is present, the "latest" schema version is assumed, meaning that any column defining a `"till"` is not active and all others are.

### \_init\_methods\_for\_column COLUMN

This method is used internally to update the symbol table for the record class to include an accessor and mutator for each column based upon the column's name.

In addition, if your record class defines the method "schema\_version", it will automatically generate methods according to whether the column currently exists for the current application schema version returned by that method. The `"schema_version"` method must return a value in the same form used by `"since"` and `"till"`.

If the column doesn't currently exist, it will create the methods, but they will die with an error message stating that the column does not exist for the current version of the application. If it does exist, a normal accessor and mutator will be created.

See also "active" in Jifty::DBI::Column, "since" in Jifty::DBI::Schema, "till" in Jifty::DBI::Schema for more information.

### null\_reference

By default, Jifty::DBI::Record will return `"undef"` for non-existent foreign references which don't exist.  That is, if each Employee `"refers_to"` a Department, but isn't required to, `"<$model-"`department\>\> will return `"undef"` for employees not in a department.

Overriding this method to return 0 will cause it to return a record with no id.  That is, `"<$model-"`department\>\> will return a Department object, but `"<$model-"`department-\>id\>\> will be `"undef"`.

### \_to\_record COLUMN VALUE

This **PRIVATE** method takes a column name and a value for that column.

It returns `"undef"` unless `"COLUMN"` is a valid column for this record that refers to another record class.

If it is valid, this method returns a new record object with an id of `"VALUE"`.

### prefetched NAME

Returns the prefetched value for column of property `"NAME"`, if it exists.

### add\_column

### column

```
    my $column = $self->column($column_name);
```

Returns the Jifty::DBI::Column object of the specified column name.

### columns

```
    my @columns = $record->columns;
```

Returns a sorted list of a `$record`'s `@columns`.

### all\_columns

```
  my @all_columns = $record->all_columns;
```

Returns all the columns for the table, even those that are inactive.

### readable\_attributes

Returns the list of this table's readable columns. They are first sorted so that primary keys come first, and then they are sorted in alphabetical order.

### serialize\_metadata

Returns a hash which describes how this class is stored in the database.  Right now, the keys are `"class"`, `"table"`, and `"columns"`. `"class"` and `"table"` return simple scalars, but `"columns"` returns a hash of `"name =&gt; value"` pairs for all the columns in this model. See `"Jifty::DBI::Column/serialize_metadata"` for the format of that hash.

### writable\_attributes

Returns a list of this table's writable columns

### record values

As you've probably already noticed, `"Jifty::DBI::Record"` automatically creates methods for your standard get/set accessors. It also provides you with some hooks to massage the values being loaded or stored.

When you fetch a record value by calling `"$my_record->some_field"`, `"Jifty::DBI::Record"` provides the following hook

- after\_*column\_name*

  This hook is called with a reference to the value returned by Jifty::DBI. Its return value is discarded.

When you set a value, `"Jifty::DBI"` provides the following hooks

- before\_set\_*column\_name* PARAMHASH

  `"Jifty::DBI::Record"` passes this function a reference to a paramhash composed of:

  - column

    The name of the column we're updating.

  - value

    The new value for *column*.

  - is\_sql\_function

    A boolean that, if true, indicates that *value* is an SQL function, not just a value.

  If before\_set\_*column\_name* returns false, the new value isn't set.

- before\_set PARAMHASH

  This is identical to the `"before_set_`*column\_name*`"`, but is called for every column set.

- after\_set\_*column\_name* PARAMHASH

  This hook will be called after a value is successfully set in the database. It will be called with a reference to a paramhash that contains `"column"`, `"value"`, and `"old_value"` keys. If `"value"` was a SQL function, it will now contain the actual value that was set. If `"column"` has filters on it, `"value"` will be the result of going through an encode and decode cycle.

  This hook's return value is ignored.

- after\_set PARAMHASH

  This is identical to the `"after_set_`*column\_name*`"`, but is called for every column set.

- validate\_*column\_name* VALUE

  This hook is called just before updating the database. It expects the actual new value you're trying to set *column\_name* to. It returns two values.  The first is a boolean with truth indicating success. The second is an optional message. Note that validate\_*column\_name* may be called outside the context of a *set* operation to validate a potential value. (The Jifty application framework uses this as part of its AJAX validation system.)

### \_value

\_value takes a single column name and returns that column's value for this row.  Subclasses can override \_value to insert custom access control.

### \_\_raw\_value

Takes a column name and returns that column's raw value. Subclasses should never override \_\_raw\_value.

### resolve\_column

given a column name, resolve it, even if it's actually an alias  return the column object.

### \_\_value

Takes a column name and returns that column's value. Subclasses should never override \_\_value.

### as\_hash

Returns a version of this record's readable columns rendered as a hash of key =\> value pairs

### \_set

\_set takes a single column name and a single unquoted value.  It updates both the in-memory value of this column and the in-database copy.  Subclasses can override \_set to insert custom access control.

### load

`"load"` can be called as a class or object method.

Takes a single argument, `$id`. Calls load\_by\_cols to retrieve the row whose primary key is `$id`.

### load\_by\_cols

`"load_by_cols"` can be called as a class or object method.

Takes a hash of columns and values. Loads the first record that matches all keys.

The hash's keys are the columns to look at.

The hash's values are either: scalar values to look for OR hash references which contain 'operator', 'value', 'case\_sensitive'  or 'function'

To load something case sensitively on a case insensitive database, you can do:

```
  $record->load_by_cols( column => { operator => '=',
                                     value => 'Foo',
                                     case_sensitive => 1 } );
```

### load\_by\_primary\_keys

Loads records with a given set of primary keys.

### load\_from\_hash

Takes a hashref, such as created by Jifty::DBI and populates this record's loaded values hash.

### \_load\_from\_sql QUERYSTRING @BIND\_VALUES

Load a record as the result of an SQL statement

### create PARAMHASH

`"create"` can be called as either a class or object method

This method creates a new record with the values specified in the PARAMHASH.

This method calls two hooks in your subclass:

- before\_create

  When adding the `"before_create"` trigger, you can determine whether the trigger may cause an abort or not by passing the `"abortable"` parameter to the `"add_trigger"` method. If this is not set, then the return value is ignored regardless.

  ```
    sub before_create {
        my $self = shift;
        my $args = shift;
        # Do any checks and changes on $args here.
        $args->{first_name} = ucfirst $args->{first_name};
        return;      # false return vallue will abort the create
        return 1;    # true return value will allow create to continue
    }
  ```

  This method is called before trying to create our row in the database. It's handed a reference to your paramhash. (That means it can modify your parameters on the fly).  `"before_create"` returns a true or false value. If it returns `"undef"` and the trigger has been added as `"abortable"`, the create is aborted.

- after\_create

  When adding the `"after_create"` trigger, you can determine whether the trigger may cause an abort or not by passing the `"abortable"` parameter to the `"add_trigger"` method. If this is not set, then the return value is ignored regardless.

  ```
    sub after_create {
        my $self                    = shift;
        my $insert_return_value_ref = shift;
        return unless $$insert_return_value_ref;    # bail if insert failed
        $self->load($$insert_return_value_ref);     # load ourselves from db
        # Do whatever needs to be done here
        return;   # aborts the create, possibly preventing a load
        return 1; # continue normally
    }
  ```

  This method is called after attempting to insert the record into the database. It gets handed a reference to the return value of the insert. That will either be a true value or a Class::ReturnValue.

  Aborting the trigger merely causes `"create"` to return a false (undefined) value even thought he create may have succeeded. This prevents the loading of the record that would normally be returned.

### delete

Delete this record from the database. On failure return a Class::ReturnValue with the error. On success, return 1;

This method has two hooks:

- before\_delete

  This method is called before the record deletion, if it exists. On failure it returns a Class::ReturnValue with the error.  On success it returns 1.

  If this method returns an error, it causes the delete to abort and return the return value from this hook.

- after\_delete

  This method is called after deletion, with a reference to the return value from the delete operation.

### table

This method returns this class's default table name. It uses Lingua::EN::Inflect to pluralize the class's name as we believe that class names for records should be in the singular and table names should be plural.

If your class name is `"My::App::Rhino"`, your table name will default to `"rhinos"`. If your class name is `"My::App::RhinoOctopus"`, your default table name will be `"rhino_octopuses"`. Not perfect, but arguably correct.

### collection\_class

Returns the collection class which this record belongs to; override this to subclass.  If you haven't specified a collection class, this returns a best guess at the name of the collection class for this collection.

It uses a simple heuristic to determine the collection class name -- It appends "Collection" to its own name. If you want to name your records and collections differently, go right ahead, but don't say we didn't warn you.

### \_guess\_table\_name

Guesses a table name based on the class's last part.

### \_handle

Returns or sets the current Jifty::DBI::Handle object

### PRIVATE refers\_to

used for the declarative syntax

### is\_distinct COLUMN\_NAME, VALUE

Checks to see if there is already a record in the database where COLUMN\_NAME equals VALUE.  If no such record exists then the COLUMN\_NAME and VALUE pair is considered distinct and it returns 1. If a value is already present the test is considered to have failed and it returns a Class::ReturnValue with the error.

### run\_canonicalization\_for\_column column =\> 'COLUMN', value =\> 'VALUE'

Runs all canonicalizers for the specified column.

### has\_canonicalizer\_for\_column COLUMN

Returns true if COLUMN has a canonicalizer, otherwise returns undef.

### run\_validation\_for\_column column =\> 'COLUMN', value =\> 'VALUE' \[extra =\> \\@ARGS\]

Runs all validators for the specified column.

### has\_validator\_for\_column COLUMN

Returns true if COLUMN has a validator, otherwise returns undef.

### unload\_value COLUMN

Purges the cached value of COLUMN from the object, forcing it to be fetched from the database next time it is queried.

## AUTHOR

Jesse Vincent \<jesse@bestpractical.com\>, Alex Vandiver \<alexmv@bestpractical.com\>, David Glasser \<glasser@bestpractical.com\>, Ruslan Zakirov \<ruslan.zakirov@gmail.com\>

Based on DBIx::SearchBuilder::Record, whose credits read:

```
 Jesse Vincent, <jesse@fsck.com>
 Enhancements by Ivan Kohler, <ivan-rt@420.am>
 Docs by Matt Knopp <mhat@netlag.com>
```

## SEE ALSO

Jifty::DBI, Jifty::DBI::Handle, Jifty::DBI::Collection.
