Database structure

To use DBIx::Class, we need to teach it about the layout of the underlying database. Several methods are supported. The built-in method involves defining your database structure as a set of perl modules. The other oft used method is to import the definitions from an existing database using the module DBIx::Class::Schema::Loader.

Using Loader

TODO

Manual Result class creation (and understanding Loader results)

  1. CREATE TABLE

Standard table creation in SQL:

CREATE TABLE users (
   id INTEGER AUTO_INCREMENT,
   username VARCHAR(255),
   dob DATE,
   realname VARCHAR(255),
   password VARCHAR(255)
);

Translation to DBIx::Class:

The recommended version:

package My::Schema::Result::User;
use strict;
use warnings;

use base 'DBIx::Class::Core';

__PACKAGE__->table('users');
__PACKAGE__->add_columns(
  id => {
    data_type => 'integer',
    is_auto_increment => 1,
  },
  username => {
    data_type => 'varchar',
    size => 255,
  },
  dob => {
    data_type => 'date',
  },
  realname => {
    data_type => 'varchar',
    size => 255,
  },
  password => {
    data_type => 'varchar',
    size => 255,
  },
 );
 __PACKAGE__->set_primary_key('id');
 1;

The snappy version:

package My::Schema::Result::User;
use strict;
use warnings;

use base 'DBIx::Class::Core';

__PACKAGE__->table('users');
__PACKAGE__->add_columns(
  id => {
    data_type => 'integer',
    is_auto_increment => 1,
  },
  qw/username dob realname password/
 );
 __PACKAGE__->set_primary_key('id');

 1;

This shows a minimal Result class to represent our "users" table. DBIx::Class itself does not use or care about the field types or lengths. However many external components exist on CPAN, and some of may use this information.

  1. CREATE VIEW

  2. CREATE INDEX

My tags:
 
Popular tags:
 
Powered by Catalyst