Introduction to DBIx::Class

Doran Barton
Doran BartonSenior Software Developer at Bluehost
Introduction to DBIx::Class
Doran Barton
Bluehost
doran@bluehost.com
Background: DBI
● DBI is awesome
– Abstraction layer between code and database
backend
– “Easy” to migrate code from one RDBMS to another
DBIx::Class
● Is an ORM class
ORM: Object Relational Mapper
● Database tables become objects
● Table data and relationships between tables become
object methods
● Example ORMs:
– Hibernate (Java)
– SQLAlchemy (Python)
– CakePHP (PHP)
– DBIx::Class (Perl)
DBIx::Class
● Founded by Matt S. Trout (mst)
● Website: http://www.dbix-class.org/
DBIx::Class Benefits
● No more writing SQL
– (You still can, if needed.)
● Ease of use
– Put junior developers to work faster
DBIx::Class Caveats
● No SQL
– Figuring out how to express complex queries can be
irksome
● Startup overhead
– DBIx::Class leverages lots of other CPAN modules
● Result class code
– Rewriting CREATE TABLEs in DBIx::Class result class
code may seem redundant
Using DBIx::Class
● Write your schema class
● Write a result class for each table
Example: Simple blog schema
blog_post comment
author
Example: Schema class
package MyBlog::Schema;
use base qw/DBIx::Class::Schema/;
__PACKAGE__­>load_namespaces();
1;
 
Example: blog_post
CREATE TABLE blog_post (
    post_id         SERIAL          PRIMARY KEY,
    headline        VARCHAR(100)    NOT NULL,
    post_timestamp  TIMESTAMP       NOT NULL DEFAULT NOW(),
    author_id       INTEGER         NOT NULL
        REFERENCES author(author_id),
    body            TEXT            NOT NULL
);
package MyBlog::Schema::Result::BlogPost;
use base qw/ DBIx::Class::Core /;
__PACKAGE__­>table('blog_post');
__PACKAGE__­>add_columns(
    qw/post_id headline post_timestamp author_id body/);
__PACKAGE__­>set_primary_key('post_id');
__PACKAGE__­>belongs_to(
    author => 'MyBlog::Schema::Result::Author',
    'author_id');
__PACKAGE__­>has_many(
    comments => 'MyBlog::Schema::Result::Comment',
    'post_id');
Example: author
CREATE TABLE author (
    author_id       SERIAL          PRIMARY KEY,
    username        VARCHAR(20)     UNIQUE NOT NULL,
    enc_password    VARCHAR(100)    NOT NULL,
    first_name      VARCHAR(100)    NOT NULL,
    last_name       VARCHAR(100)    NOT NULL,
    email           VARCHAR(300)    NOT NULL,
    can_blog        BOOLEAN         NOT NULL DEFAULT 'f'
);
package MyBlog::Schema::Result::Author;
use base qw/ DBIx::Class::Core /;
__PACKAGE__­>table('author');
__PACKAGE__­>add_columns(
    qw/author_id username enc_password first_name last_name
       email can_blog/);
__PACKAGE__­>set_primary_key('author_id');
__PACKAGE__­>has_many(
    posts => 'MyBlog::Schema::Result::BlogPost',
    'author_id');
__PACKAGE__­>has_many(
    comments => 'MyBlog::Schema::Result::Comment',
    'author_id');
1;
Example: comment
CREATE TABLE comment (
    comment_id      SERIAL      PRIMARY KEY,
    post_id         INTEGER     NOT NULL
        REFERENCES blog_post(post_id),
    author_id       INTEGER     NOT NULL
        REFERENCES author(author_id),
    comment_dt      TIMESTAMP   NOT NULL DEFAULT NOW(),
    body            TEXT        NOT NULL
);
package MyBlog::Schema::Result::Comment;
use base qw/ DBIx::Class::Core /;
__PACKAGE__­>table('comment');
__PACKAGE__­>add_columns(
    qw/comment_id post_id author_id comment_dt body/);
__PACKAGE__­>set_primary_key('comment_id');
__PACKAGE__­>belongs_to(
    author => 'MyBlog::Schema::Result::Author',
    'author_id');
__PACKAGE__­>belongs_to(
    post => 'MyBlog::Schema::Result::BlogPost',
    'post_id');
1;
Using DBIC classes
use feature 'say';
use MyBlog::Schema;
use Lingua::EN::Inflect qw/PL_N PL_V/;
my $schema = MyBlog::Schema­>connect('dbi:Pg:dbname=myblog');
my @posts = $schema­>resultset('BlogPost')­>search(
    { 'author.username' => 'fozz', },
    { prefetch          =>  'author'},
)­>all;
say "There ", 
    PL_V("is", scalar @posts), " ", 
    scalar @posts, " ", 
    PL_N("post", scalar @posts), " by this author.";
DBIx::Class::Schema::Loader
● Creates result classes for you
– On-the-fly or one-time
● Can also generate CREATE TABLE commands from
schema classes
Example: dbicdump
● $ dbicdump -o dump_directory=./lib 
-o components='["InflateColumn::DateTime"]' 
MyBlog::Schema dbi:Pg:dbname=myblog
Dynamic DBIC
● In Schema class:
package MyBlog::Schema;
use base qw/DBIx::Class::Schema::Loader/;
Components/Inflating
● DBIx::Class makes it easy to coerce a table field into an
object.
– __PACKAGE__­>load_components("InflateColumn::DateTime");
● Then, specify the column type as datetime
– __PACKAGE__­>add_columns(
    ...
    post_timestamp => { type => 'datetime' },
    ...
);
● For more info, see DBIx::Class::InflateColumn::DateTime
Other inflators
● DBIx::Class::InflateColumn::IP
– Coerces field into NetAddr::IP
● DBIx::Class::InflateColumn::URI
– Coerces field into URI
● DBIx::Class::InflateColumn::Currency
– Coerces field into Data::Currency
● And you can roll your own!
Learning more
● Excellent POD
– DBIx::Class::Manual::DocMap
– DBIx::Class::Manual::Intro
– DBIx::Class::Manual::Cookbook
● http://www.dbix-class.org/
● Mailing list
– http://lists.scsys.co.uk/mailman/listinfo/dbix-class
● IRC
– irc.perl.org#dbix-class
1 of 20

Recommended

Database Programming with Perl and DBIx::Class by
Database Programming with Perl and DBIx::ClassDatabase Programming with Perl and DBIx::Class
Database Programming with Perl and DBIx::ClassDave Cross
14.7K views188 slides
Object-Oriented Programming with Perl and Moose by
Object-Oriented Programming with Perl and MooseObject-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and MooseDave Cross
10.6K views175 slides
Two graph data models : RDF and Property Graphs by
Two graph data models : RDF and Property GraphsTwo graph data models : RDF and Property Graphs
Two graph data models : RDF and Property Graphsandyseaborne
2.4K views19 slides
Sparql service-description by
Sparql service-descriptionSparql service-description
Sparql service-descriptionSTI Innsbruck
458 views10 slides
PostgreSQL - Object Relational Database by
PostgreSQL - Object Relational DatabasePostgreSQL - Object Relational Database
PostgreSQL - Object Relational DatabaseMubashar Iqbal
3.4K views35 slides
RDF, linked data and semantic web by
RDF, linked data and semantic webRDF, linked data and semantic web
RDF, linked data and semantic webJose Emilio Labra Gayo
1.5K views75 slides

More Related Content

What's hot

Non-Framework MVC sites with PHP by
Non-Framework MVC sites with PHPNon-Framework MVC sites with PHP
Non-Framework MVC sites with PHPCésar Rodas
2K views24 slides
The Semantic Web #10 - SPARQL by
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLMyungjin Lee
1.8K views35 slides
A Little SPARQL in your Analytics by
A Little SPARQL in your AnalyticsA Little SPARQL in your Analytics
A Little SPARQL in your AnalyticsDr. Neil Brittliff
760 views54 slides
Sw 06-repository and-sparql by
Sw 06-repository and-sparqlSw 06-repository and-sparql
Sw 06-repository and-sparqlSTI Innsbruck
65 views61 slides
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs by
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIsJosef Petrák
617 views45 slides
Introduction to SPARQL by
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQLJose Emilio Labra Gayo
3.9K views78 slides

What's hot(20)

Non-Framework MVC sites with PHP by César Rodas
Non-Framework MVC sites with PHPNon-Framework MVC sites with PHP
Non-Framework MVC sites with PHP
César Rodas2K views
The Semantic Web #10 - SPARQL by Myungjin Lee
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQL
Myungjin Lee1.8K views
Sw 06-repository and-sparql by STI Innsbruck
Sw 06-repository and-sparqlSw 06-repository and-sparql
Sw 06-repository and-sparql
STI Innsbruck65 views
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs by Josef Petrák
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
Josef Petrák617 views
Cassandra 3 new features @ Geecon Krakow 2016 by Duyhai Doan
Cassandra 3 new features  @ Geecon Krakow 2016Cassandra 3 new features  @ Geecon Krakow 2016
Cassandra 3 new features @ Geecon Krakow 2016
Duyhai Doan611 views
An introduction to Semantic Web and Linked Data by Fabien Gandon
An introduction to Semantic Web and Linked DataAn introduction to Semantic Web and Linked Data
An introduction to Semantic Web and Linked Data
Fabien Gandon38.8K views
XFILES, The APEX 4 version - The truth is in there by Marco Gralike
XFILES, The APEX 4 version - The truth is in thereXFILES, The APEX 4 version - The truth is in there
XFILES, The APEX 4 version - The truth is in there
Marco Gralike1.1K views
Running MRuby in a Database - ArangoDB - RuPy 2012 by ArangoDB Database
Running MRuby in a Database - ArangoDB - RuPy 2012 Running MRuby in a Database - ArangoDB - RuPy 2012
Running MRuby in a Database - ArangoDB - RuPy 2012
ArangoDB Database1.9K views
Homework help on oracle by Steve Nash
Homework help on oracleHomework help on oracle
Homework help on oracle
Steve Nash665 views
Yapceu2015 geneva courts by Laurent Dami
Yapceu2015 geneva courtsYapceu2015 geneva courts
Yapceu2015 geneva courts
Laurent Dami859 views
#sod14 - ok, è un endpoint SPARQL non facciamoci prendere dal panico by Diego Valerio Camarda
#sod14 - ok, è un endpoint SPARQL non facciamoci prendere dal panico#sod14 - ok, è un endpoint SPARQL non facciamoci prendere dal panico
#sod14 - ok, è un endpoint SPARQL non facciamoci prendere dal panico
Best practices for generating Bio2RDF linked data by alison.callahan
Best practices for generating Bio2RDF linked dataBest practices for generating Bio2RDF linked data
Best practices for generating Bio2RDF linked data
alison.callahan912 views

Similar to Introduction to DBIx::Class

DB2 and PHP in Depth on IBM i by
DB2 and PHP in Depth on IBM iDB2 and PHP in Depth on IBM i
DB2 and PHP in Depth on IBM iAlan Seiden
2.4K views122 slides
Dev buchan leveraging by
Dev buchan leveragingDev buchan leveraging
Dev buchan leveragingBill Buchan
806 views61 slides
Change RelationalDB to GraphDB with OrientDB by
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBApaichon Punopas
1.8K views48 slides
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S... by
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...Trivadis
277 views36 slides
The Basics of MongoDB by
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDBvaluebound
9.2K views17 slides
Obevo Javasig.pptx by
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptxLadduAnanu
3 views40 slides

Similar to Introduction to DBIx::Class(20)

DB2 and PHP in Depth on IBM i by Alan Seiden
DB2 and PHP in Depth on IBM iDB2 and PHP in Depth on IBM i
DB2 and PHP in Depth on IBM i
Alan Seiden2.4K views
Dev buchan leveraging by Bill Buchan
Dev buchan leveragingDev buchan leveraging
Dev buchan leveraging
Bill Buchan806 views
Change RelationalDB to GraphDB with OrientDB by Apaichon Punopas
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDB
Apaichon Punopas1.8K views
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S... by Trivadis
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...
Trivadis277 views
The Basics of MongoDB by valuebound
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
valuebound9.2K views
Obevo Javasig.pptx by LadduAnanu
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptx
LadduAnanu3 views
Challenges of Implementing an Advanced SQL Engine on Hadoop by DataWorks Summit
Challenges of Implementing an Advanced SQL Engine on HadoopChallenges of Implementing an Advanced SQL Engine on Hadoop
Challenges of Implementing an Advanced SQL Engine on Hadoop
DataWorks Summit2.2K views
Hadoop Spark - Reuniao SouJava 12/04/2014 by soujavajug
Hadoop Spark - Reuniao SouJava 12/04/2014Hadoop Spark - Reuniao SouJava 12/04/2014
Hadoop Spark - Reuniao SouJava 12/04/2014
soujavajug3.2K views
The View - Leveraging Lotuscript for Database Connectivity by Bill Buchan
The View - Leveraging Lotuscript for Database ConnectivityThe View - Leveraging Lotuscript for Database Connectivity
The View - Leveraging Lotuscript for Database Connectivity
Bill Buchan1.8K views
Transactional writes to cloud storage with Eric Liang by Databricks
Transactional writes to cloud storage with Eric LiangTransactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric Liang
Databricks2.4K views
Dbms & prog lang by Tech_MX
Dbms & prog langDbms & prog lang
Dbms & prog lang
Tech_MX1.3K views
Doctrine Project by Daniel Lima
Doctrine ProjectDoctrine Project
Doctrine Project
Daniel Lima468 views
NoSQL by dbulic
NoSQLNoSQL
NoSQL
dbulic1.4K views
Integrating Deep Learning Libraries with Apache Spark by Databricks
Integrating Deep Learning Libraries with Apache SparkIntegrating Deep Learning Libraries with Apache Spark
Integrating Deep Learning Libraries with Apache Spark
Databricks3.7K views
ORM Methodology by Ahmed Gomaa
ORM MethodologyORM Methodology
ORM Methodology
Ahmed Gomaa1.1K views

Recently uploaded

Future of Indian ConsumerTech by
Future of Indian ConsumerTechFuture of Indian ConsumerTech
Future of Indian ConsumerTechKapil Khandelwal (KK)
22 views68 slides
Uni Systems for Power Platform.pptx by
Uni Systems for Power Platform.pptxUni Systems for Power Platform.pptx
Uni Systems for Power Platform.pptxUni Systems S.M.S.A.
56 views21 slides
Mini-Track: Challenges to Network Automation Adoption by
Mini-Track: Challenges to Network Automation AdoptionMini-Track: Challenges to Network Automation Adoption
Mini-Track: Challenges to Network Automation AdoptionNetwork Automation Forum
13 views27 slides
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...Jasper Oosterveld
19 views49 slides
Five Things You SHOULD Know About Postman by
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About PostmanPostman
36 views43 slides
Special_edition_innovator_2023.pdf by
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdfWillDavies22
18 views6 slides

Recently uploaded(20)

ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by Jasper Oosterveld
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman36 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2218 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma39 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi132 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views
6g - REPORT.pdf by Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex10 views
"Running students' code in isolation. The hard way", Yurii Holiuk by Fwdays
"Running students' code in isolation. The hard way", Yurii Holiuk "Running students' code in isolation. The hard way", Yurii Holiuk
"Running students' code in isolation. The hard way", Yurii Holiuk
Fwdays17 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely25 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
SAP Automation Using Bar Code and FIORI.pdf by Virendra Rai, PMP
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdf

Introduction to DBIx::Class