SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Dernier (20)

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

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

Notes de l'éditeur

  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 вполне достаточно и нет смысла определять еще одну, на уровне базы данных. Рассмотрим