SlideShare ist ein Scribd-Unternehmen logo
1 von 20
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

Weitere ähnliche Inhalte

Was ist angesagt?

2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
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ák
 

Was ist angesagt? (18)

The Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQLThe Semantic Web #10 - SPARQL
The Semantic Web #10 - SPARQL
 
A Little SPARQL in your Analytics
A Little SPARQL in your AnalyticsA Little SPARQL in your Analytics
A Little SPARQL in your Analytics
 
2011 4IZ440 Semantic Web – RDF, SPARQL, and software APIs
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
 
Introduction to SPARQL
Introduction to SPARQLIntroduction to SPARQL
Introduction to SPARQL
 
Cassandra 3 new features @ Geecon Krakow 2016
Cassandra 3 new features  @ Geecon Krakow 2016Cassandra 3 new features  @ Geecon Krakow 2016
Cassandra 3 new features @ Geecon Krakow 2016
 
An introduction to Semantic Web and Linked Data
An introduction to Semantic Web and Linked DataAn introduction to Semantic Web and Linked Data
An introduction to Semantic Web and Linked Data
 
Challenges and applications of RDF shapes
Challenges and applications of RDF shapesChallenges and applications of RDF shapes
Challenges and applications of RDF shapes
 
ShEx by Example
ShEx by ExampleShEx by Example
ShEx by Example
 
XFILES, The APEX 4 version - The truth is in there
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
 
Neo4j (Part 1)
Neo4j (Part 1)Neo4j (Part 1)
Neo4j (Part 1)
 
Using MRuby in a database
Using MRuby in a databaseUsing MRuby in a database
Using MRuby in a 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
Running MRuby in a Database - ArangoDB - RuPy 2012
 
Homework help on oracle
Homework help on oracleHomework help on oracle
Homework help on oracle
 
Yapceu2015 geneva courts
Yapceu2015 geneva courtsYapceu2015 geneva courts
Yapceu2015 geneva courts
 
RDF validation tutorial
RDF validation tutorialRDF validation tutorial
RDF validation tutorial
 
#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
#sod14 - ok, è un endpoint SPARQL non facciamoci prendere dal panico
 
Best practices for generating Bio2RDF linked data
Best practices for generating Bio2RDF linked dataBest practices for generating Bio2RDF linked data
Best practices for generating Bio2RDF linked data
 
Data shapes-test-suite
Data shapes-test-suiteData shapes-test-suite
Data shapes-test-suite
 

Ähnlich wie Introduction to DBIx::Class

Dev buchan leveraging
Dev buchan leveragingDev buchan leveraging
Dev buchan leveraging
Bill Buchan
 
Challenges of Implementing an Advanced SQL Engine on Hadoop
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 Summit
 
Hadoop Spark - Reuniao SouJava 12/04/2014
Hadoop Spark - Reuniao SouJava 12/04/2014Hadoop Spark - Reuniao SouJava 12/04/2014
Hadoop Spark - Reuniao SouJava 12/04/2014
soujavajug
 
The View - Leveraging Lotuscript for Database Connectivity
The View - Leveraging Lotuscript for Database ConnectivityThe View - Leveraging Lotuscript for Database Connectivity
The View - Leveraging Lotuscript for Database Connectivity
Bill Buchan
 
Dbms & prog lang
Dbms & prog langDbms & prog lang
Dbms & prog lang
Tech_MX
 

Ähnlich wie Introduction to DBIx::Class (20)

DB2 and PHP in Depth on IBM i
DB2 and PHP in Depth on IBM iDB2 and PHP in Depth on IBM i
DB2 and PHP in Depth on IBM i
 
Dev buchan leveraging
Dev buchan leveragingDev buchan leveraging
Dev buchan leveraging
 
Change RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDBChange RelationalDB to GraphDB with OrientDB
Change RelationalDB to GraphDB with OrientDB
 
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...
TechEvent 2019: Oracle to PostgreSQL - a Travel Guide from Practice; Roland S...
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
Obevo Javasig.pptx
Obevo Javasig.pptxObevo Javasig.pptx
Obevo Javasig.pptx
 
Challenges of Implementing an Advanced SQL Engine on Hadoop
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
 
Hadoop Spark - Reuniao SouJava 12/04/2014
Hadoop Spark - Reuniao SouJava 12/04/2014Hadoop Spark - Reuniao SouJava 12/04/2014
Hadoop Spark - Reuniao SouJava 12/04/2014
 
The View - Leveraging Lotuscript for Database Connectivity
The View - Leveraging Lotuscript for Database ConnectivityThe View - Leveraging Lotuscript for Database Connectivity
The View - Leveraging Lotuscript for Database Connectivity
 
JS App Architecture
JS App ArchitectureJS App Architecture
JS App Architecture
 
Transactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric LiangTransactional writes to cloud storage with Eric Liang
Transactional writes to cloud storage with Eric Liang
 
Dbms & prog lang
Dbms & prog langDbms & prog lang
Dbms & prog lang
 
oodb.ppt
oodb.pptoodb.ppt
oodb.ppt
 
Doctrine Project
Doctrine ProjectDoctrine Project
Doctrine Project
 
NoSQL
NoSQLNoSQL
NoSQL
 
Open source Technology
Open source TechnologyOpen source Technology
Open source Technology
 
Integrating Deep Learning Libraries with Apache Spark
Integrating Deep Learning Libraries with Apache SparkIntegrating Deep Learning Libraries with Apache Spark
Integrating Deep Learning Libraries with Apache Spark
 
Building a high-performance, scalable ML & NLP platform with Python, Sheer El...
Building a high-performance, scalable ML & NLP platform with Python, Sheer El...Building a high-performance, scalable ML & NLP platform with Python, Sheer El...
Building a high-performance, scalable ML & NLP platform with Python, Sheer El...
 
Nosql databases
Nosql databasesNosql databases
Nosql databases
 
ORM Methodology
ORM MethodologyORM Methodology
ORM Methodology
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Introduction to DBIx::Class