SlideShare una empresa de Scribd logo
1 de 21
# Migration Validators 
Data should always be consistent 
by Valeriy Prokopchuk. Sphere Consulting Inc.
# Data validation in RoR app 
Presentation Tier JS: Form Validations 
ActiveRecord: Validation helpers 
???? 
Application Tier 
Data Tier 
Controller validations, ActiveRecord validations 
???
# DB Constraints. Out of the box 
● Unique, Not Null, Primary Key, Default: 
create_table, { primary_key: :primary_key_column } do |t| 
t.integer int_column, nil: false, default: 5 
end 
add_index :table_name, :int_column, unique: true
# DB Constraints. Foreign Keys 
● Rails < 4 
https://github.com/matthuhiggins/foreigner 
change_table :comments do |t| 
t.foreign_key :posts, dependent: :delete 
end 
● Rails 4 
t.references :posts, index: :true
# DB Constraints. Complex 
Between? 
int_col >= 1 AND int_col <= 3 
● Check 
● Triggers
# DB Constraints. NO? 
Performance 
RDBMS dialects
# DB Constraints. NO? 
Trigger in MySQL … 
CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW 
BEGIN 
DECLARE var INT; 
IF NOT(NEW.int_col IS NOT NULL AND NEW.int_col >= 1 AND NEW.int_col <= 3) 
THEN SET var = (SELECT MAX(1) FROM `inclusion violated`); 
END IF; 
END
# DB Constraints. NO? 
Function first in PostgreSQL … 
CREATE OR REPLACE FUNCTION trg_mgr_validates_table_name_ins_func() RETURNS trigger AS $BODY$ 
BEGIN 
IF NOT(NEW.int_column IS NOT NULL AND NEW.int_column >= 1 AND NEW.int_column <= 3) 
THEN RAISE EXCEPTION 'inclusion violated for table_name field int_column'; 
END IF; 
RETURN NEW; 
END; 
$BODY$
# DB constraints in migrations? 
And trigger after that … 
CREATE TRIGGER trg_mgr_validates_table_name_ins 
BEFORE INSERT 
ON table_name 
FOR EACH ROW 
EXECUTE PROCEDURE trg_mgr_validates_table_name_ins_func();
# DB Constraints. YES! 
Shared DB 
Complex DB
# DB constraints in migrations? 
Let’s imagine… 
create_table :table_name do |t| 
t.integer :int_column, validates: { uniqueness: :true, 
inclusion: { in: 1..3 } } 
t.column :column_name, :integer, validates: { exclusion: { in: [1,2,3]} } 
end
# Migration Validators (MV) Project 
● RDBMs: 
● Helpers 
validates: { uniqueness: true, exclusion: true, inclusion: true, 
length: true, format: true, presence: true }
# MV. Simple. Familiar 
Create format validation... 
create_table :table_name do |t| 
t.change :str_column, validates: { 
format: { with: /interesting/, 
message: "value should be interesting"} 
} 
end
# MV. Simple. Familiar 
Update format validation... 
change_table :table_name do |t| 
t.string :str_column, validates: { 
format: { with: /VERY interesting/, 
message: "value should be VERY interesting" } 
} 
end
# MV. Simple. Familiar 
Delete format validation... 
change_table :table_name do |t| 
t.string :str_column, validates: { format: :false } 
end
# MV. Configurable 
Everything we already know… 
create_table :table_name do |t| 
t.string :column_name, validates: { 
length: { in: 5..8, 
too_long: 'Should be <= 8', too_short: 'Should be >= 5', 
on: :save, allow_nil: true, allow_blank: true } 
} 
end
# MV. Configurable 
And something related to db... 
create_table :table_name do |t| 
t.string :column_name, validates: { 
length: { in: 5..8, on: [:create, :update], as: :trigger, 
update_trigger_name: :upd_trg, 
create_trigger_name: :upd_trg } 
} 
end
# MV. RDBMS agnostic 
Same declaration: 
create_table do |t| 
t.integer :int_column, validates: { inclusion: { in: 1..3 } } 
end 
Different definitions: 
{ MySQL: :trigger, SQLite: :trigger, PostgreSQL: :check }
# MV. Not supported yet 
Change... 
class Order < ActiveRecord::Migration 
def change 
create_table :orders do |t| 
t.integer :int_column, validates: { uniqueness: true } 
end 
end 
end
# MV. Homepage 
● Core 
https://github.com/vprokopchuk256/mv-test 
https://github.com/vprokopchuk256/mv-core 
● Drivers 
https://github.com/vprokopchuk256/mv-mysql 
https://github.com/vprokopchuk256/mv-postgresql 
https://github.com/vprokopchuk256/mv-sqlite
# MV. Epilogue. Questions

Más contenido relacionado

La actualidad más candente

OpenWRT Makefile reference
OpenWRT Makefile referenceOpenWRT Makefile reference
OpenWRT Makefile reference家榮 吳
 
Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)brian d foy
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...ssuserd6b1fd
 
Python Function
Python FunctionPython Function
Python FunctionSoba Arjun
 
Gravity Forms Hooks & Filters
Gravity Forms Hooks & FiltersGravity Forms Hooks & Filters
Gravity Forms Hooks & Filtersiamdangavin
 

La actualidad más candente (7)

OpenWRT Makefile reference
OpenWRT Makefile referenceOpenWRT Makefile reference
OpenWRT Makefile reference
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)Benchmarking Perl (Chicago UniForum 2006)
Benchmarking Perl (Chicago UniForum 2006)
 
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
Notes for GNU Octave - Numerical Programming - for Students - 02 of 02 by aru...
 
Smarty Template Engine
Smarty Template EngineSmarty Template Engine
Smarty Template Engine
 
Python Function
Python FunctionPython Function
Python Function
 
Gravity Forms Hooks & Filters
Gravity Forms Hooks & FiltersGravity Forms Hooks & Filters
Gravity Forms Hooks & Filters
 

Destacado

How to manage an open source project
How to manage an open source projectHow to manage an open source project
How to manage an open source projectJuanjo Bazán
 
Anton Shemerey: Refactoring and SOLID principles in Ruby.
Anton Shemerey: Refactoring and SOLID principles in Ruby.Anton Shemerey: Refactoring and SOLID principles in Ruby.
Anton Shemerey: Refactoring and SOLID principles in Ruby.Sphere Consulting Inc
 
Anton Vasiljev: Continuations in Ruby.
Anton Vasiljev: Continuations in Ruby.Anton Vasiljev: Continuations in Ruby.
Anton Vasiljev: Continuations in Ruby.Sphere Consulting Inc
 
Roman Gorel: Building better APIs on Rails.
Roman Gorel: Building better APIs on Rails.Roman Gorel: Building better APIs on Rails.
Roman Gorel: Building better APIs on Rails.Sphere Consulting Inc
 
OpenSource Project. Where to Start? Dmitriy Zaporozhets
OpenSource Project. Where to Start? Dmitriy ZaporozhetsOpenSource Project. Where to Start? Dmitriy Zaporozhets
OpenSource Project. Where to Start? Dmitriy ZaporozhetsSphere Consulting Inc
 
Roman Kuznietsov: Zeromq: sockets on steroids.Zero mq
Roman Kuznietsov: Zeromq: sockets on steroids.Zero mqRoman Kuznietsov: Zeromq: sockets on steroids.Zero mq
Roman Kuznietsov: Zeromq: sockets on steroids.Zero mqSphere Consulting Inc
 

Destacado (6)

How to manage an open source project
How to manage an open source projectHow to manage an open source project
How to manage an open source project
 
Anton Shemerey: Refactoring and SOLID principles in Ruby.
Anton Shemerey: Refactoring and SOLID principles in Ruby.Anton Shemerey: Refactoring and SOLID principles in Ruby.
Anton Shemerey: Refactoring and SOLID principles in Ruby.
 
Anton Vasiljev: Continuations in Ruby.
Anton Vasiljev: Continuations in Ruby.Anton Vasiljev: Continuations in Ruby.
Anton Vasiljev: Continuations in Ruby.
 
Roman Gorel: Building better APIs on Rails.
Roman Gorel: Building better APIs on Rails.Roman Gorel: Building better APIs on Rails.
Roman Gorel: Building better APIs on Rails.
 
OpenSource Project. Where to Start? Dmitriy Zaporozhets
OpenSource Project. Where to Start? Dmitriy ZaporozhetsOpenSource Project. Where to Start? Dmitriy Zaporozhets
OpenSource Project. Where to Start? Dmitriy Zaporozhets
 
Roman Kuznietsov: Zeromq: sockets on steroids.Zero mq
Roman Kuznietsov: Zeromq: sockets on steroids.Zero mqRoman Kuznietsov: Zeromq: sockets on steroids.Zero mq
Roman Kuznietsov: Zeromq: sockets on steroids.Zero mq
 

Similar a Valeriy Prokopchuk: Validators in Migrations.

Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsEleanor McHugh
 
Say Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick SuttererSay Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick SuttererRuby Meditation
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»Olga Lavrentieva
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)Jerome Eteve
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CDavid Wheeler
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumansNarendran R
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails Mohit Jain
 
Glorp Tutorial Guide
Glorp Tutorial GuideGlorp Tutorial Guide
Glorp Tutorial GuideESUG
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program ChangesRay Buse
 
Changing your huge table's data types in production
Changing your huge table's data types in productionChanging your huge table's data types in production
Changing your huge table's data types in productionJimmy Angelakos
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQLlubna19
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 

Similar a Valeriy Prokopchuk: Validators in Migrations. (20)

Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
Little Big Ruby
Little Big RubyLittle Big Ruby
Little Big Ruby
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
Schema plus
Schema plusSchema plus
Schema plus
 
Say Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick SuttererSay Goodbye to Procedural Programming - Nick Sutterer
Say Goodbye to Procedural Programming - Nick Sutterer
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»
 
PerlApp2Postgresql (2)
PerlApp2Postgresql (2)PerlApp2Postgresql (2)
PerlApp2Postgresql (2)
 
Building and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning CBuilding and Distributing PostgreSQL Extensions Without Learning C
Building and Distributing PostgreSQL Extensions Without Learning C
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
 
Ruby on rails
Ruby on rails Ruby on rails
Ruby on rails
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Glorp Tutorial Guide
Glorp Tutorial GuideGlorp Tutorial Guide
Glorp Tutorial Guide
 
Assignment#08
Assignment#08Assignment#08
Assignment#08
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
 
Changing your huge table's data types in production
Changing your huge table's data types in productionChanging your huge table's data types in production
Changing your huge table's data types in production
 
DataMapper
DataMapperDataMapper
DataMapper
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 

Último

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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)wesley chun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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...Drew Madelung
 
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
 
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 2024Rafal Los
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 

Último (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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...
 
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
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 

Valeriy Prokopchuk: Validators in Migrations.

  • 1. # Migration Validators Data should always be consistent by Valeriy Prokopchuk. Sphere Consulting Inc.
  • 2. # Data validation in RoR app Presentation Tier JS: Form Validations ActiveRecord: Validation helpers ???? Application Tier Data Tier Controller validations, ActiveRecord validations ???
  • 3. # DB Constraints. Out of the box ● Unique, Not Null, Primary Key, Default: create_table, { primary_key: :primary_key_column } do |t| t.integer int_column, nil: false, default: 5 end add_index :table_name, :int_column, unique: true
  • 4. # DB Constraints. Foreign Keys ● Rails < 4 https://github.com/matthuhiggins/foreigner change_table :comments do |t| t.foreign_key :posts, dependent: :delete end ● Rails 4 t.references :posts, index: :true
  • 5. # DB Constraints. Complex Between? int_col >= 1 AND int_col <= 3 ● Check ● Triggers
  • 6. # DB Constraints. NO? Performance RDBMS dialects
  • 7. # DB Constraints. NO? Trigger in MySQL … CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN DECLARE var INT; IF NOT(NEW.int_col IS NOT NULL AND NEW.int_col >= 1 AND NEW.int_col <= 3) THEN SET var = (SELECT MAX(1) FROM `inclusion violated`); END IF; END
  • 8. # DB Constraints. NO? Function first in PostgreSQL … CREATE OR REPLACE FUNCTION trg_mgr_validates_table_name_ins_func() RETURNS trigger AS $BODY$ BEGIN IF NOT(NEW.int_column IS NOT NULL AND NEW.int_column >= 1 AND NEW.int_column <= 3) THEN RAISE EXCEPTION 'inclusion violated for table_name field int_column'; END IF; RETURN NEW; END; $BODY$
  • 9. # DB constraints in migrations? And trigger after that … CREATE TRIGGER trg_mgr_validates_table_name_ins BEFORE INSERT ON table_name FOR EACH ROW EXECUTE PROCEDURE trg_mgr_validates_table_name_ins_func();
  • 10. # DB Constraints. YES! Shared DB Complex DB
  • 11. # DB constraints in migrations? Let’s imagine… create_table :table_name do |t| t.integer :int_column, validates: { uniqueness: :true, inclusion: { in: 1..3 } } t.column :column_name, :integer, validates: { exclusion: { in: [1,2,3]} } end
  • 12. # Migration Validators (MV) Project ● RDBMs: ● Helpers validates: { uniqueness: true, exclusion: true, inclusion: true, length: true, format: true, presence: true }
  • 13. # MV. Simple. Familiar Create format validation... create_table :table_name do |t| t.change :str_column, validates: { format: { with: /interesting/, message: "value should be interesting"} } end
  • 14. # MV. Simple. Familiar Update format validation... change_table :table_name do |t| t.string :str_column, validates: { format: { with: /VERY interesting/, message: "value should be VERY interesting" } } end
  • 15. # MV. Simple. Familiar Delete format validation... change_table :table_name do |t| t.string :str_column, validates: { format: :false } end
  • 16. # MV. Configurable Everything we already know… create_table :table_name do |t| t.string :column_name, validates: { length: { in: 5..8, too_long: 'Should be <= 8', too_short: 'Should be >= 5', on: :save, allow_nil: true, allow_blank: true } } end
  • 17. # MV. Configurable And something related to db... create_table :table_name do |t| t.string :column_name, validates: { length: { in: 5..8, on: [:create, :update], as: :trigger, update_trigger_name: :upd_trg, create_trigger_name: :upd_trg } } end
  • 18. # MV. RDBMS agnostic Same declaration: create_table do |t| t.integer :int_column, validates: { inclusion: { in: 1..3 } } end Different definitions: { MySQL: :trigger, SQLite: :trigger, PostgreSQL: :check }
  • 19. # MV. Not supported yet Change... class Order < ActiveRecord::Migration def change create_table :orders do |t| t.integer :int_column, validates: { uniqueness: true } end end end
  • 20. # MV. Homepage ● Core https://github.com/vprokopchuk256/mv-test https://github.com/vprokopchuk256/mv-core ● Drivers https://github.com/vprokopchuk256/mv-mysql https://github.com/vprokopchuk256/mv-postgresql https://github.com/vprokopchuk256/mv-sqlite
  • 21. # MV. Epilogue. Questions

Notas del editor

  1. На картинке вы можете наблюдать схему, которую, скорее всего, видели неоднократно. Это банальная Three - tier application model, согласно которой построены большинство Web applications, включая Rails приложения. В данной модели есть три уровня - Presentation Tier, Application Tier & Data Tier. Presentation Tier - это, обычно, какая то вариация JS framework, как то jQuery , Angular.js, Backbone.js, Ember.js либо их комбинация. В каждом из этих framework предусмотрены те или иные механизны проверки данных, полученных от пользователя. В подавляющем большинстве случаев все сводится к валидации данных формы перед их отправкой на сервер. Application Tier. В Rails обыно выделяют два вида валидации уровня приложения - Validation in controller и ActiveRecord validation. В контроллере обычно производится базовая валидация данных, как то наличие или отсутсвие запрашиваемых записей либо какая то иная, достаточно примитивная проверка данных, полученных с запросом. ActiveRecord validation - это валидация данных перед их записью в базу данных, что позволяет контролировать целостность данных одного Rails application. Data tier. В Rails - world, обычно, считают что проверки данных на уровне presentation tier & application tier вполне достаточно и нет смысла определять еще одну, на уровне базы данных. Рассмотрим