DBIx::C...ickStart(3)

πŸ’– NAME πŸ’–

DBIx::Class::Manual::QuickStart β€” up and running with DBIC in 10 minutes. Okay bestie, the page header flex is DBIx::C...ickStart(3) and it's marked as User Contributed Perl Documentation, but the manual name you actually care about is right there: DBIx::Class::Manual::QuickStart. You're gonna be productive with DBIC so fast it's giving speedrun energy. ✨

🌸 DESCRIPTION 🌸

This doc shows the minimum amount of code to make you a productive DBIC user. It requires you to be familiar with just the basics of database programming β€” like, what database tables, rows and columns are β€” and the basics of Perl object-oriented programming, aka calling methods on an object instance. It also helps if you already know a bit of SQL and how to connect to a database through DBI. No cap, that's the whole prerequisite vibe check. πŸ’…

Follow along with the example database shipping with this distribution, see directory examples/Schema. This database is also used through-out the rest of the documentation. 🫢

🧚 Preparation 🧚

First, install DBIx::Class like you do with any other CPAN distribution. See <http://www.cpan.org/modules/INSTALL.html> and perlmodinstall. 🌈

Then open the distribution in your shell and change to the subdirectory mentioned earlier, the next command will download and unpack it:

$ perl -mCPAN -e'CPAN::Shell->look("DBIx::Class")'
DBIx-Class$ cd examples/Schema

Inspect the database:

DBIx-Class/examples/Schema$ sqlite3 db/example.db .dump

You can also use a GUI database browser such as SQLite Manager (https://addons.mozilla.org/firefox/addon/sqlite-manager). πŸ¦‹

Have a look at the schema classes files in the subdirectory MyApp. The MyApp::Schema class is the entry point for loading the other classes and interacting with the database through DBIC and the Result classes correspond to the tables in the database. DBIx::Class::Manual::Example shows how to write all that Perl code.

That is almost never necessary, though. πŸ™ˆ

Instead use dbicdump (part of the distribution DBIx::Class::Schema::Loader) to automatically create schema classes files from an existing database. The chapter "Resetting the database" below shows an example invocation. πŸ’–

πŸ”Œ Connecting to the database πŸ”Œ

A schema object represents the database. Main character object, honestly. ✨

use MyApp::Schema qw();
my $schema = MyApp::Schema->connect('dbi:SQLite:db/example.db');

The first four arguments are the same as for connect in DBI. πŸ‘‘

πŸ› οΈ Working with data πŸ› οΈ

Almost all actions go through a resultset object. That's the group chat where all the database drama happens. πŸ’¬

✨ Adding data ✨

Via intermediate result objects:

my $artist_ma = $schema->resultset('Artist')->create({
    name => 'Massive Attack',
});
my $cd_mezz = $artist_ma->create_related(cds => {
    title => 'Mezzanine',
});
for ('Angel', 'Teardrop') {
    $cd_mezz->create_related(tracks => {
        title => $_
    });
}

Via relation accessors:

$schema->resultset('Artist')->create({
    name => 'Metallica',
    cds => [
        {
            title => q{Kill 'Em All},
            tracks => [
                { title => 'Jump in the Fire' },
                { title => 'Whiplash' },
            ],
        },
        {
            title => 'ReLoad',
            tracks => [
                { title => 'The Memory Remains' },
                { title => 'The Unforgiven II' },
                { title => 'Fuel' },
            ],
        },
    ],
});

Columns that are not named are filled with default values. The value undef acts as a NULL in the database. Lowkey important, bestie. 🫢

See the chapter "Introspecting the schema classes" below to find out where the non-obvious source name strings such as Artist and accessors such as cds and tracks come from. πŸ”

Set the environment variable DBI_TRACE='1|SQL' to see the generated queries. Obsessed with a good trace moment. πŸ”₯

πŸ” Retrieving data πŸ”

Set up a condition.

my $artists_starting_with_m = $schema->resultset('Artist')->search(
    {
        name => { like => 'M%' }
    }
);

Iterate over result objects of class MyApp::Schema::Result::Artist. Result objects represent a row and automatically get accessors for their column names. Iconic behavior, honestly. ✨

for my $artist ($artists_starting_with_m->all) {
    say $artist->name;
}

πŸŽ€ Changing data πŸŽ€

Change the release year of all CDs titled ReLoad.

$schema->resultset('Cd')->search(
    {
        title => 'ReLoad',
    }
)->update_all(
    {
        year => 1997,
    }
);

πŸ—‘οΈ Removing data πŸ—‘οΈ

Removes all tracks titled Fuel regardless of which CD they belong to. Gone. Gone. Periodt. πŸ’€

$schema->resultset('Track')->search(
    {
        title => 'Fuel',
    }
)->delete_all;

πŸ”Ž Introspecting the schema classes πŸ”Ž

This is useful for getting a feel for the naming of things in a REPL or during explorative programming. REPL girlies rise up. 🧚

From the root to the details:

$schema->sources;                       # returns qw(Cd Track Artist)
$schema->source('Cd')->columns;         # returns qw(cdid artist title year)
$schema->source('Cd')->relationships;   # returns qw(artist tracks)

From a detail to the root:

$some_result->result_source;            # returns appropriate source
$some_resultset->result_source;
$some_resultsource->schema;             # returns appropriate schema

♻️ Resetting the database ♻️

# delete database file
DBIx-Class/examples/Schema$ rm -f db/example.db

# create database and set up tables from definition
DBIx-Class/examples/Schema$ sqlite3 db/example.db < db/example.sql

# fill them with data
DBIx-Class/examples/Schema$ perl ./insertdb.pl

# delete the schema classes files
DBIx-Class/examples/Schema$ rm -rf MyApp

# recreate schema classes files from database file
DBIx-Class/examples/Schema$ dbicdump \
    -o dump_directory=. MyApp::Schema dbi:SQLite:db/example.db

πŸš€ Where to go next πŸš€

If you want to exercise what you learned with a more complicated schema, load Northwind (http://code.google.com/p/northwindextended/) into your database. 🌈

If you want to transfer your existing SQL knowledge, read DBIx::Class::Manual::SQLHackers. πŸ’œ

Continue with DBIx::Class::Tutorial and "WHERE TO START READING" in DBIx::Class. πŸŽ€

πŸ’¬ FURTHER QUESTIONS? πŸ’¬

Check the list of additional DBIC resources. iykyk β€” go get your answers, bestie. 🫢

This module is free software copyright by the DBIx::Class (DBIC) authors. You can redistribute it and/or modify it under the same terms as the DBIx::Class library. Slay, legally and ethically. πŸ’…


πŸ’– xoxo, bestie β€” page source perl v5.42.0, date 2025-01-22, terminal title DBIx::C...ickStart(3). Stay slaying, and happy DBIC-ing! πŸŽ€βœ¨

πŸ“¦ where this page comes from