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

Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...gajnagarg
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...SOFTTECHHUB
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabiaahmedjiabur940
 
7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.pptibrahimabdi22
 
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...HyderabadDolls
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...HyderabadDolls
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...HyderabadDolls
 
Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareGraham Ware
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...gajnagarg
 
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...nirzagarg
 
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...kumargunjan9515
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Aspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraAspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraGovindSinghDasila
 
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...HyderabadDolls
 
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...nirzagarg
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...Elaine Werffeli
 
Dubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls DubaiDubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls Dubaikojalkojal131
 
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...gajnagarg
 
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...nirzagarg
 
20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdf20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdfkhraisr
 

Recently uploaded (20)

Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In bhavnagar [ 7014168258 ] Call Me For Genuine Models...
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
 
7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt
 
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
Charbagh + Female Escorts Service in Lucknow | Starting ₹,5K To @25k with A/C...
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
 
Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham Ware
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
 
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Purnia [ 7014168258 ] Call Me For Genuine Models We...
 
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Aspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - AlmoraAspirational Block Program Block Syaldey District - Almora
Aspirational Block Program Block Syaldey District - Almora
 
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
 
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Hapur [ 7014168258 ] Call Me For Genuine Models We ...
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
 
Dubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls DubaiDubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls Dubai
 
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
Top profile Call Girls In dimapur [ 7014168258 ] Call Me For Genuine Models W...
 
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
 
20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdf20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdf
 

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