SlideShare a Scribd company logo
1 of 15
PostgreSQL
table partitioning
in RubyOnRails App
Table Partitioning
is a technique for physically dividing
the data by smaller physical pieces
for best query perfomance.
Suppose we have
And we have many bandits.
Gang Bandit Crime
has_many :bandits has_many :crimes
belongs_to :gang belongs_to :bandit
specialization
Implementing
1. Create master table. In our case this will be the ‘bandits’ table.
2. Create ‘child’ tables.
3. Create condition for data partitioning.
Step 1. Create procedure
CREATE OR REPLACE FUNCTION bandits_insert_master() RETURNS TRIGGER AS $$
DECLARE
colname text := ‘specialization’;
colval text := NEW.specialization;
tblname text := 'bandits_' || colval;
BEGIN
IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname=tblname) THEN
EXECUTE 'CREATE TABLE ' || tblname || '(check (' || quote_ident(colname) || '=' || quote_literal(colval) || ')) INHERITS (' || TG_RELNAME || ');';
END IF;
EXECUTE 'INSERT INTO ' || tblname || ' SELECT ($1).*' USING NEW;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Step 2. Create before insert trigger
CREATE TRIGGER bandits_insert_trigger
BEFORE INSERT ON bandits
FOR EACH ROW EXECUTE PROCEDURE bandits_insert_master();
It's worked!
INSERT INTO bandits (name, specifiaction) VALUES (‘Al Capone’, ‘bootlegger’);
SELECT COUNT(*) FROM ONLY bandints;
Before
> 1 row
After
> 0 rows
SELECT COUNT(*) FROM bandints; SELECT COUNT(*) FROM bandints_botlegger;
> 1 row
> 1 row
However
Bandit.create!(name: ‘Al Capone’, specialization: ‘bootlegger’)
Before
=> #<Bandit id: 1, name: "Al Capone", specialization: "bootlegger" ...
After
=> #<Bandit id: nil, name: "Al Capone", specialization: "bootlegger" ...
Why?
EXECUTE 'INSERT INTO ' || tblname || ' SELECT ($1).*' USING NEW;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Change to
EXECUTE 'INSERT INTO ' || tblname || ' SELECT ($1).*' USING NEW;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
D'oh!
Bandit.create!(name: ‘Al Capone’, specialization: ‘bootlegger’)
=> #<Bandit id: 1, name: "Al Capone", specialization: "bootlegger" …
But...
SELECT COUNT(*) FROM ONLY bandints;
> 1 row
we have duplication of records in the tables ‘bandits’ and ‘bandits_bootlegger’
Fix
CREATE OR REPLACE FUNCTION bandits_delete_master() RETURNS TRIGGER AS $$
DECLARE
row bandits%rowtype;
BEGIN
DELETE FROM ONLY bandits WHERE id = NEW.id RETURNING * INTO row;
RETURN row;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS bandits_after_insert_trigger ON bandits;
CREATE TRIGGER bandits_after_insert_trigger
AFTER INSERT ON bandits
FOR EACH ROW EXECUTE PROCEDURE bandits_delete_master();
It's worked again!
Bandit.create!(name: ‘Al Capone’, specialization: ‘bootlegger’)
=> #<Bandit id: 1, name: "Al Capone", specialization: "bootlegger" …
SELECT COUNT(*) FROM ONLY bandints;
> 0 rows
SELECT COUNT(*) FROM bandints;
> 1 rows
SELECT COUNT(*) FROM ONLY bandints_bootlegger;
> 1 rows
RubyOnRails associations
has_many :bandits
@gang.bandits.create!(name: ‘Al Capone’, specialization: ‘bootlegger’); @gang.bandits.last
#<ActiveRecord::Relation [#<Bandit id: 1, name: "Al Cap", specialization: "bootlegger", gang_id: 1…
belongs_to :bandit
@bandit.crimes.create(title: ‘Loot’)
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "crimes" violates foreign
key constraint...
DETAIL: Key (bandit_id)=(1) is not present in table "bandits".
ForeignKey are useless (in this case)
A partitioned table is really an empty table
with multiple child tables all inheriting
from the main partitioned table.
remove_foreign_key :crimes, column: :bandit_id
Partitioning assistant for Rails
https://github.com/victor-magarlamov/pg_partitioning

More Related Content

What's hot

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库YUCHENG HU
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
[Php] navigations
[Php] navigations[Php] navigations
[Php] navigationsThai Pham
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding HorrorsMark Baker
 
Feature flagsareflawed
Feature flagsareflawedFeature flagsareflawed
Feature flagsareflawedStephen Young
 
Threading
ThreadingThreading
Threadingb290572
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHPYogesh singh
 
MySQL Create Table
MySQL Create TableMySQL Create Table
MySQL Create TableHoyoung Jung
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Apache PIG Relational Operations
Apache PIG Relational Operations Apache PIG Relational Operations
Apache PIG Relational Operations Rupak Roy
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScriptryanstout
 

What's hot (17)

New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库与 PHP 和 Perl 使用 MySQL 数据库
与 PHP 和 Perl 使用 MySQL 数据库
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
[Php] navigations
[Php] navigations[Php] navigations
[Php] navigations
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Feature flagsareflawed
Feature flagsareflawedFeature flagsareflawed
Feature flagsareflawed
 
Threading
ThreadingThreading
Threading
 
Check username availability with vue.js and PHP
Check username availability with vue.js and PHPCheck username availability with vue.js and PHP
Check username availability with vue.js and PHP
 
Php
PhpPhp
Php
 
MySQL Create Table
MySQL Create TableMySQL Create Table
MySQL Create Table
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Apache PIG Relational Operations
Apache PIG Relational Operations Apache PIG Relational Operations
Apache PIG Relational Operations
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 

Viewers also liked

Factores que influyen en la dinámica de la Organización
Factores que influyen en la dinámica de la Organización Factores que influyen en la dinámica de la Organización
Factores que influyen en la dinámica de la Organización jennifergota
 
Gianluca Fiorelli - SMM Internazionale
Gianluca Fiorelli - SMM InternazionaleGianluca Fiorelli - SMM Internazionale
Gianluca Fiorelli - SMM InternazionaleElena Minchenok
 
Ln marchenasosa la navidad pdf
Ln marchenasosa la navidad pdfLn marchenasosa la navidad pdf
Ln marchenasosa la navidad pdfnevets123
 
inv de mercado
inv de mercadoinv de mercado
inv de mercadoErikabp456
 
INVESTIGACIÓN CUANTITATIVA
INVESTIGACIÓN CUANTITATIVAINVESTIGACIÓN CUANTITATIVA
INVESTIGACIÓN CUANTITATIVAErikabp456
 
Buku the manutiras kala chakra
Buku the manutiras kala chakraBuku the manutiras kala chakra
Buku the manutiras kala chakrajasapembuatnama
 
Jurassic world
Jurassic worldJurassic world
Jurassic worldcrincon44
 
Belajar ilmu manutiras kode rahasia bagian 1
Belajar ilmu manutiras kode rahasia bagian 1Belajar ilmu manutiras kode rahasia bagian 1
Belajar ilmu manutiras kode rahasia bagian 1jasapembuatnama
 
Snack-S11-2016
Snack-S11-2016 Snack-S11-2016
Snack-S11-2016 snackk4
 
Implementation of New Employee of the Year Program
Implementation of New Employee of the Year ProgramImplementation of New Employee of the Year Program
Implementation of New Employee of the Year ProgramCatherine Roberts
 

Viewers also liked (12)

Factores que influyen en la dinámica de la Organización
Factores que influyen en la dinámica de la Organización Factores que influyen en la dinámica de la Organización
Factores que influyen en la dinámica de la Organización
 
Gianluca Fiorelli - SMM Internazionale
Gianluca Fiorelli - SMM InternazionaleGianluca Fiorelli - SMM Internazionale
Gianluca Fiorelli - SMM Internazionale
 
Ln marchenasosa la navidad pdf
Ln marchenasosa la navidad pdfLn marchenasosa la navidad pdf
Ln marchenasosa la navidad pdf
 
inv de mercado
inv de mercadoinv de mercado
inv de mercado
 
INVESTIGACIÓN CUANTITATIVA
INVESTIGACIÓN CUANTITATIVAINVESTIGACIÓN CUANTITATIVA
INVESTIGACIÓN CUANTITATIVA
 
Buku the manutiras kala chakra
Buku the manutiras kala chakraBuku the manutiras kala chakra
Buku the manutiras kala chakra
 
Jurassic world
Jurassic worldJurassic world
Jurassic world
 
Belajar ilmu manutiras kode rahasia bagian 1
Belajar ilmu manutiras kode rahasia bagian 1Belajar ilmu manutiras kode rahasia bagian 1
Belajar ilmu manutiras kode rahasia bagian 1
 
Snack-S11-2016
Snack-S11-2016 Snack-S11-2016
Snack-S11-2016
 
Implementation of New Employee of the Year Program
Implementation of New Employee of the Year ProgramImplementation of New Employee of the Year Program
Implementation of New Employee of the Year Program
 
TESI triennale COMPLETA
TESI triennale COMPLETATESI triennale COMPLETA
TESI triennale COMPLETA
 
S&S
S&SS&S
S&S
 

Similar to PostgreSQL table partitioning

PHP record- with all programs and output
PHP record- with all programs and outputPHP record- with all programs and output
PHP record- with all programs and outputKavithaK23
 
Rob Sullivan at Heroku's Waza 2013: Your Database -- A Story of Indifference
Rob Sullivan at Heroku's Waza 2013: Your Database -- A Story of IndifferenceRob Sullivan at Heroku's Waza 2013: Your Database -- A Story of Indifference
Rob Sullivan at Heroku's Waza 2013: Your Database -- A Story of IndifferenceHeroku
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎juzihua1102
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎anzhong70
 
Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWorkhorse Computing
 
Tips for using Firebird system tables
Tips for using Firebird system tablesTips for using Firebird system tables
Tips for using Firebird system tablesMind The Firebird
 
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012Amazon Web Services
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #statesKonstantin Käfer
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
CS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and PerformanceCS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and PerformanceJ Singh
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsSunil Kumar Gunasekaran
 
SQL Stored Procedures For My Library Project
SQL Stored Procedures For My Library ProjectSQL Stored Procedures For My Library Project
SQL Stored Procedures For My Library ProjectRick Massouh
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Karsten Dambekalns
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worldsChristopher Spring
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)brian d foy
 

Similar to PostgreSQL table partitioning (20)

PHP record- with all programs and output
PHP record- with all programs and outputPHP record- with all programs and output
PHP record- with all programs and output
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Rob Sullivan at Heroku's Waza 2013: Your Database -- A Story of Indifference
Rob Sullivan at Heroku's Waza 2013: Your Database -- A Story of IndifferenceRob Sullivan at Heroku's Waza 2013: Your Database -- A Story of Indifference
Rob Sullivan at Heroku's Waza 2013: Your Database -- A Story of Indifference
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
Wheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility ModulesWheels we didn't re-invent: Perl's Utility Modules
Wheels we didn't re-invent: Perl's Utility Modules
 
Tips for using Firebird system tables
Tips for using Firebird system tablesTips for using Firebird system tables
Tips for using Firebird system tables
 
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
CS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and PerformanceCS 542 Controlling Database Integrity and Performance
CS 542 Controlling Database Integrity and Performance
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
SQL Stored Procedures For My Library Project
SQL Stored Procedures For My Library ProjectSQL Stored Procedures For My Library Project
SQL Stored Procedures For My Library Project
 
Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3Transparent Object Persistence with FLOW3
Transparent Object Persistence with FLOW3
 
Mips1
Mips1Mips1
Mips1
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 

Recently uploaded

Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Sapana Sha
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort servicejennyeacort
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一fhwihughh
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home ServiceSapana Sha
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxFurkanTasci3
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfJohn Sterrett
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改atducpo
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一F sss
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 

Recently uploaded (20)

Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
Saket, (-DELHI )+91-9654467111-(=)CHEAP Call Girls in Escorts Service Saket C...
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
9711147426✨Call In girls Gurgaon Sector 31. SCO 25 escort service
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptx
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdf
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
办理学位证中佛罗里达大学毕业证,UCF成绩单原版一比一
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
Decoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in ActionDecoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in Action
 

PostgreSQL table partitioning

  • 2. Table Partitioning is a technique for physically dividing the data by smaller physical pieces for best query perfomance.
  • 3. Suppose we have And we have many bandits. Gang Bandit Crime has_many :bandits has_many :crimes belongs_to :gang belongs_to :bandit specialization
  • 4. Implementing 1. Create master table. In our case this will be the ‘bandits’ table. 2. Create ‘child’ tables. 3. Create condition for data partitioning.
  • 5. Step 1. Create procedure CREATE OR REPLACE FUNCTION bandits_insert_master() RETURNS TRIGGER AS $$ DECLARE colname text := ‘specialization’; colval text := NEW.specialization; tblname text := 'bandits_' || colval; BEGIN IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname=tblname) THEN EXECUTE 'CREATE TABLE ' || tblname || '(check (' || quote_ident(colname) || '=' || quote_literal(colval) || ')) INHERITS (' || TG_RELNAME || ');'; END IF; EXECUTE 'INSERT INTO ' || tblname || ' SELECT ($1).*' USING NEW; RETURN NULL; END; $$ LANGUAGE plpgsql;
  • 6. Step 2. Create before insert trigger CREATE TRIGGER bandits_insert_trigger BEFORE INSERT ON bandits FOR EACH ROW EXECUTE PROCEDURE bandits_insert_master();
  • 7. It's worked! INSERT INTO bandits (name, specifiaction) VALUES (‘Al Capone’, ‘bootlegger’); SELECT COUNT(*) FROM ONLY bandints; Before > 1 row After > 0 rows SELECT COUNT(*) FROM bandints; SELECT COUNT(*) FROM bandints_botlegger; > 1 row > 1 row
  • 8. However Bandit.create!(name: ‘Al Capone’, specialization: ‘bootlegger’) Before => #<Bandit id: 1, name: "Al Capone", specialization: "bootlegger" ... After => #<Bandit id: nil, name: "Al Capone", specialization: "bootlegger" ...
  • 9. Why? EXECUTE 'INSERT INTO ' || tblname || ' SELECT ($1).*' USING NEW; RETURN NULL; END; $$ LANGUAGE plpgsql; Change to EXECUTE 'INSERT INTO ' || tblname || ' SELECT ($1).*' USING NEW; RETURN NEW; END; $$ LANGUAGE plpgsql;
  • 10. D'oh! Bandit.create!(name: ‘Al Capone’, specialization: ‘bootlegger’) => #<Bandit id: 1, name: "Al Capone", specialization: "bootlegger" … But... SELECT COUNT(*) FROM ONLY bandints; > 1 row we have duplication of records in the tables ‘bandits’ and ‘bandits_bootlegger’
  • 11. Fix CREATE OR REPLACE FUNCTION bandits_delete_master() RETURNS TRIGGER AS $$ DECLARE row bandits%rowtype; BEGIN DELETE FROM ONLY bandits WHERE id = NEW.id RETURNING * INTO row; RETURN row; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS bandits_after_insert_trigger ON bandits; CREATE TRIGGER bandits_after_insert_trigger AFTER INSERT ON bandits FOR EACH ROW EXECUTE PROCEDURE bandits_delete_master();
  • 12. It's worked again! Bandit.create!(name: ‘Al Capone’, specialization: ‘bootlegger’) => #<Bandit id: 1, name: "Al Capone", specialization: "bootlegger" … SELECT COUNT(*) FROM ONLY bandints; > 0 rows SELECT COUNT(*) FROM bandints; > 1 rows SELECT COUNT(*) FROM ONLY bandints_bootlegger; > 1 rows
  • 13. RubyOnRails associations has_many :bandits @gang.bandits.create!(name: ‘Al Capone’, specialization: ‘bootlegger’); @gang.bandits.last #<ActiveRecord::Relation [#<Bandit id: 1, name: "Al Cap", specialization: "bootlegger", gang_id: 1… belongs_to :bandit @bandit.crimes.create(title: ‘Loot’) ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "crimes" violates foreign key constraint... DETAIL: Key (bandit_id)=(1) is not present in table "bandits".
  • 14. ForeignKey are useless (in this case) A partitioned table is really an empty table with multiple child tables all inheriting from the main partitioned table. remove_foreign_key :crimes, column: :bandit_id
  • 15. Partitioning assistant for Rails https://github.com/victor-magarlamov/pg_partitioning