SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Introduction to DBIx::Class