SlideShare a Scribd company logo
1 of 29
Introduction to
   DBIx::Lite
    id:motemen
me


• id:motemen
• motemen 美顔器
• Application engineer
 • DBIx::MoCo maintainer
ORM and me

• DBIx::MoCo
• DBIx::Skinny
• Data::Model
• Teng
DBIx::Lite

• AUTHOR cpan:AAR
• “Chained and minimal ORM”
• cf. DBIx::Class
SYNOPSIS
Preparation

• No classes required to declare
 • e.g. schemas, row classes
• Just use
Initialization
• Passing $dbh
  my $dbix = DBIx::Lite->new(dbh => $dbh);


• Using DBIx::Connector
  my $dbix = DBIx::Lite->connect(
      'dbi:mysql:dbname=...',
      $username, $password, {
          mysql_enable_utf8 => 1,
          RootClass => 'DBIx::Sunny',
      },
  );
CRUD

  my $entries = $dbix->table('entries');


• Call table() to start building query
• Returns ResultSet object
SELECT
• Build ResultSet by method chain
  my $entries_rs = $dbix->table('entries')
      ->search({ author_id => 1 })
      ->order_by('created_at');


• Finally retrieve row objects
  my @entries = $entries_rs->all;
  # SELECT me.* FROM entries AS me
  WHERE ( author_id = '1' ) ORDER BY created_at

  my $entry = $entries_rs->limit(1)->single;
  # SELECT me.* FROM entries AS me
  WHERE ( author_id = '1' ) ORDER BY created_at
  LIMIT 1 OFFSET 0
INSERT
my $entry = $dbix->table('entries')->insert({
    author_id => 47,
    body => '…',
    created_at => time(),
});

# INSERT INTO entries ( author_id, body, created_at)
VALUES ( '47', '…', '1345196410' )


• If the table has an auto-
  incremented pkey, LAST_INSERT_ID
  is filled in
UPDATE/DELETE
$dbix->table('entries')
    ->search({ id => [ 2, 3, 5 ] })
    ->update({ body => '…' });

# UPDATE entries AS me SET body = '…' WHERE ( ( id = '2' OR
id = '3' OR id = '5' ) )


$dbix->schema->table('entries')->pk('id');
$entry->update({ body => '…' });

# UPDATE entries AS me SET body = '…' WHERE ( id = '1' )
Components
• DBIx::Lite
 • DBIx::Lite::ResultSet
 • DBIx::Lite::Row
 • DBIx::Lite::Schema
 • DBIx::Lite::Schema::Table
DBIx::Lite
• Represents a database (connection)
• $dbix->{connector}
 • isa DBIx::Connector
• $dbix->{schema}
 • isa DBIx::Lite::Schema
• Generates ResultSet (next)
DBIL::ResultSet
• Represents a set of database rows
• Has most major methods
• Does not hold actual data in itself
 • To retrieve row objects:
  my @all = $rs->all;
  my $row = $rs->single;
DBIL::ResultSet
• Chain methods to build specific
  result set
  $rs   =   $dbix->table(…);
  $rs   =   $rs->search(%where);   #   WHERE
  $rs   =   $rs->order_by($col);    #   ORDER BY
  $rs   =   $rs->limit($n);         #   LIMIT
  $rs   =   $rs->select(@cols);     #   SELECT


• search() uses SQL::Abstract
• Multiple search()’es joined by “AND”
DBIL::Row
•Represents a database row
•Simple structure
 •$row->{data}, $row->{dbix_lite}
 •$row->hashref
•No inflates/deflates
•AUTOLOAD method names
DBIL::Row

• Row operation methods
 • $row->update(%cols)
 • $row->delete
• pk needed in schema (next)
DBIL::Schema
& DBIL::Schema::Table

• Represents metadata of tables
 • (Auto-increment) primary keys
 • Row classes, ResultSet classes
 • Has-a, has-many relationships
DBIL::Schema
& DBIL::Schema::Table
• Setting primary key lets row objects’
  update methods to work

 • Use autopk() for auto-inc pk
   $dbix->schema->table('entries')->pk('id');

• Give row objects custom methods
  from the package
   $dbix->schema->table('entries')
       ->class('My::Row::Entry');
DBIL::Schema
& DBIL::Schema::Table
• Register has-many relations
  $dbix->schema->one_to_many(
      'authors.id' => 'entries.author_id'
  );

• ResultSet gains relation method
  my @entries = $dbix->table('authors')
      ->search({ name => 'motemen' })
      ->entries->all;
  # SELECT entries.* FROM authors AS me
    INNER JOIN entries
      ON ( me.id = entries.author_id )
    WHERE ( name = 'motemen' )
Other features
Paging

• Paging by offset/limit
  my $entries_rs = $dbix->table('entries')
      ->rows_per_page(10)->page(3);
  $entries_rs->all;

  # SELECT COUNT(*) FROM entries AS me LIMIT 10
  OFFSET 0
  # SELECT me.* FROM entries AS me LIMIT 10 OFFSET 20

  my $pager = $entries_rs->pager; # => Data::Page
JOIN
$dbix->table('entries')
->left_join('authors', { author_id => 'id' })
->select_also([ 'authors.name' => 'author_name' ])
->all;

# SELECT me.*, authors.name AS `author_name`
  FROM entries AS me
  LEFT OUTER JOIN authors
    ON ( me.author_id = authors.id )



• Use $rs->select_also() to fetch
  joined tables
Raw DBI access
my $now = $dbix->dbh_do(sub {
    $_->selectcol_arrayref('SELECT NOW()')->[0]
});




• Internally uses DBIx::Connector#run
CAVEATS

• “SELECT me.* FROM …” queries
 • Sometimes need to prefix “me.” to
   field names

• Row classes are not automatically
  require’d
HACKING

• Auto-upgrade connection to master
• Need to alter DBIx::Lite and
  produced DBIL::ResultSet

• Use Role::Tiny
• gist:3378389
Sum up

• Simple APIs
• ResultSet
• No need to declare classes,
  easy to start

• Extending may need tricks
Questions?

More Related Content

What's hot

Country State City Dropdown in PHP
Country State City Dropdown in PHPCountry State City Dropdown in PHP
Country State City Dropdown in PHPVineet Kumar Saini
 
Add edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHPAdd edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHPVineet Kumar Saini
 
PHP object calisthenics
PHP object calisthenicsPHP object calisthenics
PHP object calisthenicsGiorgio Cefaro
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodJeremy Kendall
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tinywaniji
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
12. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor212. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor2Razvan Raducanu, PhD
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?Maksym Hopei
 
Leveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPJeremy Kendall
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBjorgeortiz85
 
13. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor313. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor3Razvan Raducanu, PhD
 
Leveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPJeremy Kendall
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of TransductionDavid Stockton
 
(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and ProfitOlaf Alders
 

What's hot (20)

Country State City Dropdown in PHP
Country State City Dropdown in PHPCountry State City Dropdown in PHP
Country State City Dropdown in PHP
 
Add edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHPAdd edit delete in Codeigniter in PHP
Add edit delete in Codeigniter in PHP
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Tax management-system
Tax management-systemTax management-system
Tax management-system
 
DBI
DBIDBI
DBI
 
Database api
Database apiDatabase api
Database api
 
PHP object calisthenics
PHP object calisthenicsPHP object calisthenics
PHP object calisthenics
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
画像Hacks
画像Hacks画像Hacks
画像Hacks
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tiny
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
12. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor212. CodeIgniter vederea inregistrarilor2
12. CodeIgniter vederea inregistrarilor2
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?
 
Leveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHP
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDB
 
13. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor313. CodeIgniter vederea inregistrarilor3
13. CodeIgniter vederea inregistrarilor3
 
Leveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHP
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit(Ab)Using the MetaCPAN API for Fun and Profit
(Ab)Using the MetaCPAN API for Fun and Profit
 

Similar to Introduction to DBIx::Lite - Kyoto.pm tech talk #2

DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMetatagg Solutions
 
DBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちDBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちRyo Miyake
 
DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail Laurent Dami
 
DB API Usage - How to write DBAL compliant code
DB API Usage - How to write DBAL compliant codeDB API Usage - How to write DBAL compliant code
DB API Usage - How to write DBAL compliant codeKarsten Dambekalns
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPVineet Kumar Saini
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in PerlLaurent Dami
 
supporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tableMahabubur Rahaman
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLitecharsbar
 
Elasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko DeElasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko DeDebarko De
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Database Programming
Database ProgrammingDatabase Programming
Database ProgrammingHenry Osborne
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friendkikoalonsob
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?alexbrasetvik
 

Similar to Introduction to DBIx::Lite - Kyoto.pm tech talk #2 (20)

DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
DBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちDBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たち
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail DBIx-DataModel v2.0 in detail
DBIx-DataModel v2.0 in detail
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
DB API Usage - How to write DBAL compliant code
DB API Usage - How to write DBAL compliant codeDB API Usage - How to write DBAL compliant code
DB API Usage - How to write DBAL compliant code
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHPDifference between mysql_fetch_array and mysql_fetch_assoc in PHP
Difference between mysql_fetch_array and mysql_fetch_assoc in PHP
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
supporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered tablesupporting t-sql scripts for Heap vs clustered table
supporting t-sql scripts for Heap vs clustered table
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
 
Elasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko DeElasticsearch and Symfony Integration - Debarko De
Elasticsearch and Symfony Integration - Debarko De
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Database Programming
Database ProgrammingDatabase Programming
Database Programming
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
Postgres can do THAT?
Postgres can do THAT?Postgres can do THAT?
Postgres can do THAT?
 

Recently uploaded

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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 Processorsdebabhi2
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Recently uploaded (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Introduction to DBIx::Lite - Kyoto.pm tech talk #2

  • 1. Introduction to DBIx::Lite id:motemen
  • 2. me • id:motemen • motemen 美顔器 • Application engineer • DBIx::MoCo maintainer
  • 3. ORM and me • DBIx::MoCo • DBIx::Skinny • Data::Model • Teng
  • 4. DBIx::Lite • AUTHOR cpan:AAR • “Chained and minimal ORM” • cf. DBIx::Class
  • 6. Preparation • No classes required to declare • e.g. schemas, row classes • Just use
  • 7. Initialization • Passing $dbh my $dbix = DBIx::Lite->new(dbh => $dbh); • Using DBIx::Connector my $dbix = DBIx::Lite->connect( 'dbi:mysql:dbname=...', $username, $password, { mysql_enable_utf8 => 1, RootClass => 'DBIx::Sunny', }, );
  • 8. CRUD my $entries = $dbix->table('entries'); • Call table() to start building query • Returns ResultSet object
  • 9. SELECT • Build ResultSet by method chain my $entries_rs = $dbix->table('entries') ->search({ author_id => 1 }) ->order_by('created_at'); • Finally retrieve row objects my @entries = $entries_rs->all; # SELECT me.* FROM entries AS me WHERE ( author_id = '1' ) ORDER BY created_at my $entry = $entries_rs->limit(1)->single; # SELECT me.* FROM entries AS me WHERE ( author_id = '1' ) ORDER BY created_at LIMIT 1 OFFSET 0
  • 10. INSERT my $entry = $dbix->table('entries')->insert({ author_id => 47, body => '…', created_at => time(), }); # INSERT INTO entries ( author_id, body, created_at) VALUES ( '47', '…', '1345196410' ) • If the table has an auto- incremented pkey, LAST_INSERT_ID is filled in
  • 11. UPDATE/DELETE $dbix->table('entries') ->search({ id => [ 2, 3, 5 ] }) ->update({ body => '…' }); # UPDATE entries AS me SET body = '…' WHERE ( ( id = '2' OR id = '3' OR id = '5' ) ) $dbix->schema->table('entries')->pk('id'); $entry->update({ body => '…' }); # UPDATE entries AS me SET body = '…' WHERE ( id = '1' )
  • 13. • DBIx::Lite • DBIx::Lite::ResultSet • DBIx::Lite::Row • DBIx::Lite::Schema • DBIx::Lite::Schema::Table
  • 14. DBIx::Lite • Represents a database (connection) • $dbix->{connector} • isa DBIx::Connector • $dbix->{schema} • isa DBIx::Lite::Schema • Generates ResultSet (next)
  • 15. DBIL::ResultSet • Represents a set of database rows • Has most major methods • Does not hold actual data in itself • To retrieve row objects: my @all = $rs->all; my $row = $rs->single;
  • 16. DBIL::ResultSet • Chain methods to build specific result set $rs = $dbix->table(…); $rs = $rs->search(%where); # WHERE $rs = $rs->order_by($col); # ORDER BY $rs = $rs->limit($n); # LIMIT $rs = $rs->select(@cols); # SELECT • search() uses SQL::Abstract • Multiple search()’es joined by “AND”
  • 17. DBIL::Row •Represents a database row •Simple structure •$row->{data}, $row->{dbix_lite} •$row->hashref •No inflates/deflates •AUTOLOAD method names
  • 18. DBIL::Row • Row operation methods • $row->update(%cols) • $row->delete • pk needed in schema (next)
  • 19. DBIL::Schema & DBIL::Schema::Table • Represents metadata of tables • (Auto-increment) primary keys • Row classes, ResultSet classes • Has-a, has-many relationships
  • 20. DBIL::Schema & DBIL::Schema::Table • Setting primary key lets row objects’ update methods to work • Use autopk() for auto-inc pk $dbix->schema->table('entries')->pk('id'); • Give row objects custom methods from the package $dbix->schema->table('entries') ->class('My::Row::Entry');
  • 21. DBIL::Schema & DBIL::Schema::Table • Register has-many relations $dbix->schema->one_to_many( 'authors.id' => 'entries.author_id' ); • ResultSet gains relation method my @entries = $dbix->table('authors') ->search({ name => 'motemen' }) ->entries->all; # SELECT entries.* FROM authors AS me INNER JOIN entries ON ( me.id = entries.author_id ) WHERE ( name = 'motemen' )
  • 23. Paging • Paging by offset/limit my $entries_rs = $dbix->table('entries') ->rows_per_page(10)->page(3); $entries_rs->all; # SELECT COUNT(*) FROM entries AS me LIMIT 10 OFFSET 0 # SELECT me.* FROM entries AS me LIMIT 10 OFFSET 20 my $pager = $entries_rs->pager; # => Data::Page
  • 24. JOIN $dbix->table('entries') ->left_join('authors', { author_id => 'id' }) ->select_also([ 'authors.name' => 'author_name' ]) ->all; # SELECT me.*, authors.name AS `author_name` FROM entries AS me LEFT OUTER JOIN authors ON ( me.author_id = authors.id ) • Use $rs->select_also() to fetch joined tables
  • 25. Raw DBI access my $now = $dbix->dbh_do(sub { $_->selectcol_arrayref('SELECT NOW()')->[0] }); • Internally uses DBIx::Connector#run
  • 26. CAVEATS • “SELECT me.* FROM …” queries • Sometimes need to prefix “me.” to field names • Row classes are not automatically require’d
  • 27. HACKING • Auto-upgrade connection to master • Need to alter DBIx::Lite and produced DBIL::ResultSet • Use Role::Tiny • gist:3378389
  • 28. Sum up • Simple APIs • ResultSet • No need to declare classes, easy to start • Extending may need tricks

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n