SlideShare a Scribd company logo
1 of 50
Download to read offline
Volver al futuro con SQL
      y stored procedures

                              Norman Clarke
                            Business Vision Ruby Labs
                                   @compay


Wednesday, November 9, 11
Wednesday, November 9, 11
Wednesday, November 9, 11
Wednesday, November 9, 11
Lo que les espera...

              • Características, ventajas y desventajas de
                    stored procedures
              • Una librería experimental basada en stored
                    procedures
              • Stored procedures vs. ORM

Wednesday, November 9, 11
Stored Procedures
                            programación "real" con SQL




Wednesday, November 9, 11
postgres=# select greeting();

               greeting
             -------------
              hello world!

             (1 row)



Wednesday, November 9, 11
1 CREATE FUNCTION greeting()
   2 RETURNS TEXT AS $$
   3   BEGIN
   4     RETURN 'hello world!';
   5   END;
   6 $$ LANGUAGE 'plpgsql';


Wednesday, November 9, 11
declare
                            begin
                              select ...
                              if ... then
                                 update ...
                              else
                                 while ... loop
                                   ...
                                 end loop;
                              end if;
                              return ...;
                            end;
Wednesday, November 9, 11
¿Cuántas funciones?
                            Postgres: 2333
                               Lua: 135




Wednesday, November 9, 11
Ventajas



Wednesday, November 9, 11
Cacheo automático
                         de consultas


Wednesday, November 9, 11
Menos coordinación
                    entre la BD y Ruby

                            O Java, Python, Perl, PHP, etc.




Wednesday, November 9, 11
Encapsulación del esquema

                              Stored
          Esquema                        Ruby
                            Procedures




Wednesday, November 9, 11
Toda la lógica de negocios
                  en SQL


Wednesday, November 9, 11
Wednesday, November 9, 11
No hagan eso por favor




Wednesday, November 9, 11
Squirm
                            github.com/bvision/squirm




Wednesday, November 9, 11
Squirm

              • Azúcar sintáctico para la gema "pg"
              • Connection pool básico
              • Stored procedures como procs o lambdas


Wednesday, November 9, 11
1 Squirm.connect host: "localhost"
     2 Squirm.transaction do
     3   Squirm.exec "SELECT ..." do |result|
     4     result.to_a
     5   end
     6   Squirm.rollback
     7 end




Wednesday, November 9, 11
1 Squirm do
     2   connect host: "localhost"
     3   transaction do
     4     exec "SELECT ..." do |result|
     5       result.to_a
     6     end
     7     rollback
     8   end
     9 end



Wednesday, November 9, 11
1 Squirm do
        2   exec "CREATE FUNCTION ..."
        3   proc = procedure "greeting"
        4   proc.call "Juan"
        5   #=> "¡hola Juan!"
        6 end



Wednesday, November 9, 11
1        class Foo
    2
    3              @@bar = Procedure.load "bar"
    4
    5          def bar(*args)
    6            @@bar.call(*args)
    7          end
    8        end
    9
   10        foo = Foo.new
   11        foo.bar("hello")
Wednesday, November 9, 11
GET        followers/ids
                 GET        friends/ids
                 GET        lists/all
                 GET        favorites
                 GET        statuses/home_timeline
                 GET        statuses/mentions
                 GET        statuses/user_timeline
                 GET        direct_messages


Wednesday, November 9, 11
SELECT            followers.ids()
          SELECT            friends.ids()
          SELECT            lists.all()
          SELECT            favorites()
          SELECT            statuses.home_timeline()
          SELECT            statuses.mentions()
          SELECT            statuses.user_timeline()
          SELECT            direct_messages()


Wednesday, November 9, 11
Squirm Model
                            github.com/bvision/squirm_model




Wednesday, November 9, 11
Squirm Model

              • Generador de tablas, procedures
              • SQL "scaffolding"
              • Active Model


Wednesday, November 9, 11
$ squirm table person id email birth_date access_time bio

     1     CREATE TABLE "person" (
     2        "id"          SERIAL NOT NULL PRIMARY KEY,
     3        "email"       VARCHAR(64) NOT NULL UNIQUE,
     4        "birth_date" DATE,
     5        "access_time" TIMESTAMP WITH TIME ZONE,
     6        "bio"         TEXT
     7     );




Wednesday, November 9, 11
$ squirm table person id created_at

  1    CREATE TABLE "person" (
  2       "id"         SERIAL NOT NULL PRIMARY KEY,
  3       "created_at" TIMESTAMP WITH TIME ZONE NOT NULL
  4    );
  5
  6    CREATE OR REPLACE FUNCTION "update_person_created_at_timestamp"
  7      RETURNS TRIGGER AS $$
  8      BEGIN
  9        NEW.created_at = NOW();
 10        RETURN NEW;
 11      END;
 12    $$ LANGUAGE 'plpgsql';
 13
 14    CREATE TRIGGER "update_person_created_at_timestamp"
 15      BEFORE INSERT ON "person"
 16      FOR EACH ROW EXECUTE PROCEDURE "update_person_created_at_time


Wednesday, November 9, 11
$ squirm table person id email --api


         CREATE             TABLE      "person"          ...
         CREATE             SCHEMA     "person"          ...
         CREATE             FUNCTION   "person.get"      ...
         CREATE             FUNCTION   "person.create"   ...
         CREATE             FUNCTION   "person.update"   ...
         CREATE             FUNCTION   "person.delete"   ...



Wednesday, November 9, 11
1 class Person
    2   extend Squirm::Model
        ...
    3   validates_presence_of :name
    4 end
    5
    6 Person.create(...)
    7 @person = Person.find(1)
    8 @person.valid?
    9 @person.to_json
   10 redirect_to @person
Wednesday, November 9, 11
1 class Person
              2   extend Squirm::Model
              3
              4   sample do |s|
              5     s.id   = 1
              6     s.name = "Juan Fulano"
              7   end
              8
              9   validates_presence_of :name
             10 end


Wednesday, November 9, 11
1 class PersonTest < Test::Unit::TestCase
   2   def test_create
   3     assert Person.create(Person.sample)
   4   end
   5 end




Wednesday, November 9, 11
1 Squirm do
   2   connect host: "localhost"
   3
   4   exec Person.to_ddl
   5
   6   Person.finalize
   7
   8   p = Person.create name: "John"
   9   p.update name: "Johnny"
  10   p.delete
  11 end
Wednesday, November 9, 11
Benchmarks



ROFLSCALE




                 0          7.5            15             22.5   30


                            Squirm Model   ActiveRecord


Wednesday, November 9, 11
¿Por qué no usar un
                           ORM?


Wednesday, November 9, 11
Usen los ORM
                              • Active Record
                              • DataMapper
                              • Sequel
                              • otros

Wednesday, November 9, 11
Pero conozcan
                             sus defectos


Wednesday, November 9, 11
Exhibition.all(
       :run_time.gt => 2,
       :run_time.lt => 5
     )

     run_time > 1 AND run_time < 5

  ...you might be wondering how we can specify conditions
  beyond equality without resorting to SQL.Well, thanks to some
  clever additions to the Symbol class, it’s easy!

Wednesday, November 9, 11
table = Product.arel_table
   Product.where(
     table[:price].eq(2.99).
     or(table[:name].matches("%foo"))
   ).to_sql

   #=> "WHERE price = 2.99 OR name LIKE '%foo'"



     railscasts.com/episodes/215-advanced-queries-in-rails-3


Wednesday, November 9, 11
SQL (mal) generado



Wednesday, November 9, 11
La abstracción dificulta
                 el uso de features
                     avanzados


Wednesday, November 9, 11
Los stored procedures
               ofrecen una alternativa
                     interesante


Wednesday, November 9, 11
"Pensemos diferente"



Wednesday, November 9, 11
Nihil sub sole novum



Wednesday, November 9, 11
Postgres y MySQL están
             muy desaprovechados


Wednesday, November 9, 11
No usemos
                            abstracciones
                             innecesarias


Wednesday, November 9, 11
¡Gracias!



Wednesday, November 9, 11
Wednesday, November 9, 11
Gracias, fotógrafos
            Obelisco: flickr.com/photos/budgetplaces/4173902613/
              Matz: flickr.com/photos/rrrodrigo/2394122680/




Wednesday, November 9, 11

More Related Content

Viewers also liked

Stored Procedure Superpowers: A Developer’s Guide
Stored Procedure Superpowers: A Developer’s GuideStored Procedure Superpowers: A Developer’s Guide
Stored Procedure Superpowers: A Developer’s GuideVoltDB
 
An Introduction to Cassandra - Oracle User Group
An Introduction to Cassandra - Oracle User GroupAn Introduction to Cassandra - Oracle User Group
An Introduction to Cassandra - Oracle User GroupCarlos Juzarte Rolo
 
Silicon Valley Data Science: From Oracle to Cassandra with Spark
Silicon Valley Data Science: From Oracle to Cassandra with SparkSilicon Valley Data Science: From Oracle to Cassandra with Spark
Silicon Valley Data Science: From Oracle to Cassandra with SparkDataStax Academy
 
Topic2 Understanding Middleware
Topic2 Understanding MiddlewareTopic2 Understanding Middleware
Topic2 Understanding Middlewaresanjoysanyal
 
Netflix's Big Leap from Oracle to Cassandra
Netflix's Big Leap from Oracle to CassandraNetflix's Big Leap from Oracle to Cassandra
Netflix's Big Leap from Oracle to CassandraRoopa Tangirala
 
Microservices in the Enterprise: A Research Study and Reference Architecture
Microservices in the Enterprise: A Research Study and Reference ArchitectureMicroservices in the Enterprise: A Research Study and Reference Architecture
Microservices in the Enterprise: A Research Study and Reference ArchitectureJesus Rodriguez
 
Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...
Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...
Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...DataStax
 
Bulk Loading Data into Cassandra
Bulk Loading Data into CassandraBulk Loading Data into Cassandra
Bulk Loading Data into CassandraDataStax
 
Migration Best Practices: From RDBMS to Cassandra without a Hitch
Migration Best Practices: From RDBMS to Cassandra without a HitchMigration Best Practices: From RDBMS to Cassandra without a Hitch
Migration Best Practices: From RDBMS to Cassandra without a HitchDataStax Academy
 
Oracle to Cassandra Core Concepts Guid Part 1: A new hope
Oracle to Cassandra Core Concepts Guid Part 1: A new hopeOracle to Cassandra Core Concepts Guid Part 1: A new hope
Oracle to Cassandra Core Concepts Guid Part 1: A new hopeDataStax
 
Migrating Netflix from Datacenter Oracle to Global Cassandra
Migrating Netflix from Datacenter Oracle to Global CassandraMigrating Netflix from Datacenter Oracle to Global Cassandra
Migrating Netflix from Datacenter Oracle to Global CassandraAdrian Cockcroft
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureKelly Goetsch
 

Viewers also liked (13)

Stored Procedure Superpowers: A Developer’s Guide
Stored Procedure Superpowers: A Developer’s GuideStored Procedure Superpowers: A Developer’s Guide
Stored Procedure Superpowers: A Developer’s Guide
 
An Introduction to Cassandra - Oracle User Group
An Introduction to Cassandra - Oracle User GroupAn Introduction to Cassandra - Oracle User Group
An Introduction to Cassandra - Oracle User Group
 
Silicon Valley Data Science: From Oracle to Cassandra with Spark
Silicon Valley Data Science: From Oracle to Cassandra with SparkSilicon Valley Data Science: From Oracle to Cassandra with Spark
Silicon Valley Data Science: From Oracle to Cassandra with Spark
 
Topic2 Understanding Middleware
Topic2 Understanding MiddlewareTopic2 Understanding Middleware
Topic2 Understanding Middleware
 
Netflix's Big Leap from Oracle to Cassandra
Netflix's Big Leap from Oracle to CassandraNetflix's Big Leap from Oracle to Cassandra
Netflix's Big Leap from Oracle to Cassandra
 
Microservices in the Enterprise: A Research Study and Reference Architecture
Microservices in the Enterprise: A Research Study and Reference ArchitectureMicroservices in the Enterprise: A Research Study and Reference Architecture
Microservices in the Enterprise: A Research Study and Reference Architecture
 
Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...
Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...
Oracle: Let My People Go! (Shu Zhang, Ilya Sokolov, Symantec) | Cassandra Sum...
 
Bulk Loading Data into Cassandra
Bulk Loading Data into CassandraBulk Loading Data into Cassandra
Bulk Loading Data into Cassandra
 
Migration Best Practices: From RDBMS to Cassandra without a Hitch
Migration Best Practices: From RDBMS to Cassandra without a HitchMigration Best Practices: From RDBMS to Cassandra without a Hitch
Migration Best Practices: From RDBMS to Cassandra without a Hitch
 
Oracle to Cassandra Core Concepts Guid Part 1: A new hope
Oracle to Cassandra Core Concepts Guid Part 1: A new hopeOracle to Cassandra Core Concepts Guid Part 1: A new hope
Oracle to Cassandra Core Concepts Guid Part 1: A new hope
 
In Search of Segmentation
In Search of SegmentationIn Search of Segmentation
In Search of Segmentation
 
Migrating Netflix from Datacenter Oracle to Global Cassandra
Migrating Netflix from Datacenter Oracle to Global CassandraMigrating Netflix from Datacenter Oracle to Global Cassandra
Migrating Netflix from Datacenter Oracle to Global Cassandra
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright Future
 

Similar to De vuelta al pasado con SQL y stored procedures

Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3Blazing Cloud
 
Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)benwaine
 
NoSQL CGN: CouchDB (11/2011)
NoSQL CGN: CouchDB (11/2011)NoSQL CGN: CouchDB (11/2011)
NoSQL CGN: CouchDB (11/2011)Sebastian Cohnen
 
Mastering ElasticSearch with Ruby and Tire
Mastering ElasticSearch with Ruby and TireMastering ElasticSearch with Ruby and Tire
Mastering ElasticSearch with Ruby and TireLuca Bonmassar
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Matt Aimonetti
 
Localizing iOS Apps
Localizing iOS AppsLocalizing iOS Apps
Localizing iOS Appsweissazool
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2Blazing Cloud
 
Rcos presentation
Rcos presentationRcos presentation
Rcos presentationmskmoorthy
 
Ruby + Rails
Ruby + RailsRuby + Rails
Ruby + Railsbetabeers
 
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011Carlo Sciolla
 
Cooking an Omelette with Chef
Cooking an Omelette with ChefCooking an Omelette with Chef
Cooking an Omelette with Chefctaintor
 
The Not Java That's Not Scala
The Not Java That's Not ScalaThe Not Java That's Not Scala
The Not Java That's Not ScalaJustin Lee
 
What to do when things go wrong
What to do when things go wrongWhat to do when things go wrong
What to do when things go wrongDorneles Treméa
 
Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2Yeqi He
 
Tackling Big Data with Hadoop
Tackling Big Data with HadoopTackling Big Data with Hadoop
Tackling Big Data with Hadooppoorlytrainedape
 

Similar to De vuelta al pasado con SQL y stored procedures (20)

Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3
 
Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)Acceptance & Integration Testing With Behat (PHPNw2011)
Acceptance & Integration Testing With Behat (PHPNw2011)
 
NoSQL CGN: CouchDB (11/2011)
NoSQL CGN: CouchDB (11/2011)NoSQL CGN: CouchDB (11/2011)
NoSQL CGN: CouchDB (11/2011)
 
Mastering ElasticSearch with Ruby and Tire
Mastering ElasticSearch with Ruby and TireMastering ElasticSearch with Ruby and Tire
Mastering ElasticSearch with Ruby and Tire
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010
 
Localizing iOS Apps
Localizing iOS AppsLocalizing iOS Apps
Localizing iOS Apps
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2
 
JRuby and You
JRuby and YouJRuby and You
JRuby and You
 
Rcos presentation
Rcos presentationRcos presentation
Rcos presentation
 
Ruby + Rails
Ruby + RailsRuby + Rails
Ruby + Rails
 
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011Alfresco the clojure way -- Slides from the Alfresco DevCon2011
Alfresco the clojure way -- Slides from the Alfresco DevCon2011
 
Cooking an Omelette with Chef
Cooking an Omelette with ChefCooking an Omelette with Chef
Cooking an Omelette with Chef
 
The Not Java That's Not Scala
The Not Java That's Not ScalaThe Not Java That's Not Scala
The Not Java That's Not Scala
 
Ruby 20th birthday
Ruby 20th birthdayRuby 20th birthday
Ruby 20th birthday
 
Ruby
RubyRuby
Ruby
 
Script it
Script itScript it
Script it
 
What to do when things go wrong
What to do when things go wrongWhat to do when things go wrong
What to do when things go wrong
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
 
Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2
 
Tackling Big Data with Hadoop
Tackling Big Data with HadoopTackling Big Data with Hadoop
Tackling Big Data with Hadoop
 

Recently uploaded

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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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
 
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
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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
 

Recently uploaded (20)

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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
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
 
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...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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
 

De vuelta al pasado con SQL y stored procedures

  • 1. Volver al futuro con SQL y stored procedures Norman Clarke Business Vision Ruby Labs @compay Wednesday, November 9, 11
  • 5. Lo que les espera... • Características, ventajas y desventajas de stored procedures • Una librería experimental basada en stored procedures • Stored procedures vs. ORM Wednesday, November 9, 11
  • 6. Stored Procedures programación "real" con SQL Wednesday, November 9, 11
  • 7. postgres=# select greeting(); greeting ------------- hello world! (1 row) Wednesday, November 9, 11
  • 8. 1 CREATE FUNCTION greeting() 2 RETURNS TEXT AS $$ 3 BEGIN 4 RETURN 'hello world!'; 5 END; 6 $$ LANGUAGE 'plpgsql'; Wednesday, November 9, 11
  • 9. declare begin select ... if ... then update ... else while ... loop ... end loop; end if; return ...; end; Wednesday, November 9, 11
  • 10. ¿Cuántas funciones? Postgres: 2333 Lua: 135 Wednesday, November 9, 11
  • 12. Cacheo automático de consultas Wednesday, November 9, 11
  • 13. Menos coordinación entre la BD y Ruby O Java, Python, Perl, PHP, etc. Wednesday, November 9, 11
  • 14. Encapsulación del esquema Stored Esquema Ruby Procedures Wednesday, November 9, 11
  • 15. Toda la lógica de negocios en SQL Wednesday, November 9, 11
  • 17. No hagan eso por favor Wednesday, November 9, 11
  • 18. Squirm github.com/bvision/squirm Wednesday, November 9, 11
  • 19. Squirm • Azúcar sintáctico para la gema "pg" • Connection pool básico • Stored procedures como procs o lambdas Wednesday, November 9, 11
  • 20. 1 Squirm.connect host: "localhost" 2 Squirm.transaction do 3 Squirm.exec "SELECT ..." do |result| 4 result.to_a 5 end 6 Squirm.rollback 7 end Wednesday, November 9, 11
  • 21. 1 Squirm do 2 connect host: "localhost" 3 transaction do 4 exec "SELECT ..." do |result| 5 result.to_a 6 end 7 rollback 8 end 9 end Wednesday, November 9, 11
  • 22. 1 Squirm do 2 exec "CREATE FUNCTION ..." 3 proc = procedure "greeting" 4 proc.call "Juan" 5 #=> "¡hola Juan!" 6 end Wednesday, November 9, 11
  • 23. 1 class Foo 2 3 @@bar = Procedure.load "bar" 4 5 def bar(*args) 6 @@bar.call(*args) 7 end 8 end 9 10 foo = Foo.new 11 foo.bar("hello") Wednesday, November 9, 11
  • 24. GET followers/ids GET friends/ids GET lists/all GET favorites GET statuses/home_timeline GET statuses/mentions GET statuses/user_timeline GET direct_messages Wednesday, November 9, 11
  • 25. SELECT followers.ids() SELECT friends.ids() SELECT lists.all() SELECT favorites() SELECT statuses.home_timeline() SELECT statuses.mentions() SELECT statuses.user_timeline() SELECT direct_messages() Wednesday, November 9, 11
  • 26. Squirm Model github.com/bvision/squirm_model Wednesday, November 9, 11
  • 27. Squirm Model • Generador de tablas, procedures • SQL "scaffolding" • Active Model Wednesday, November 9, 11
  • 28. $ squirm table person id email birth_date access_time bio 1 CREATE TABLE "person" ( 2 "id" SERIAL NOT NULL PRIMARY KEY, 3 "email" VARCHAR(64) NOT NULL UNIQUE, 4 "birth_date" DATE, 5 "access_time" TIMESTAMP WITH TIME ZONE, 6 "bio" TEXT 7 ); Wednesday, November 9, 11
  • 29. $ squirm table person id created_at 1 CREATE TABLE "person" ( 2 "id" SERIAL NOT NULL PRIMARY KEY, 3 "created_at" TIMESTAMP WITH TIME ZONE NOT NULL 4 ); 5 6 CREATE OR REPLACE FUNCTION "update_person_created_at_timestamp" 7 RETURNS TRIGGER AS $$ 8 BEGIN 9 NEW.created_at = NOW(); 10 RETURN NEW; 11 END; 12 $$ LANGUAGE 'plpgsql'; 13 14 CREATE TRIGGER "update_person_created_at_timestamp" 15 BEFORE INSERT ON "person" 16 FOR EACH ROW EXECUTE PROCEDURE "update_person_created_at_time Wednesday, November 9, 11
  • 30. $ squirm table person id email --api CREATE TABLE "person" ... CREATE SCHEMA "person" ... CREATE FUNCTION "person.get" ... CREATE FUNCTION "person.create" ... CREATE FUNCTION "person.update" ... CREATE FUNCTION "person.delete" ... Wednesday, November 9, 11
  • 31. 1 class Person 2 extend Squirm::Model ... 3 validates_presence_of :name 4 end 5 6 Person.create(...) 7 @person = Person.find(1) 8 @person.valid? 9 @person.to_json 10 redirect_to @person Wednesday, November 9, 11
  • 32. 1 class Person 2 extend Squirm::Model 3 4 sample do |s| 5 s.id = 1 6 s.name = "Juan Fulano" 7 end 8 9 validates_presence_of :name 10 end Wednesday, November 9, 11
  • 33. 1 class PersonTest < Test::Unit::TestCase 2 def test_create 3 assert Person.create(Person.sample) 4 end 5 end Wednesday, November 9, 11
  • 34. 1 Squirm do 2 connect host: "localhost" 3 4 exec Person.to_ddl 5 6 Person.finalize 7 8 p = Person.create name: "John" 9 p.update name: "Johnny" 10 p.delete 11 end Wednesday, November 9, 11
  • 35. Benchmarks ROFLSCALE 0 7.5 15 22.5 30 Squirm Model ActiveRecord Wednesday, November 9, 11
  • 36. ¿Por qué no usar un ORM? Wednesday, November 9, 11
  • 37. Usen los ORM • Active Record • DataMapper • Sequel • otros Wednesday, November 9, 11
  • 38. Pero conozcan sus defectos Wednesday, November 9, 11
  • 39. Exhibition.all( :run_time.gt => 2, :run_time.lt => 5 ) run_time > 1 AND run_time < 5 ...you might be wondering how we can specify conditions beyond equality without resorting to SQL.Well, thanks to some clever additions to the Symbol class, it’s easy! Wednesday, November 9, 11
  • 40. table = Product.arel_table Product.where( table[:price].eq(2.99). or(table[:name].matches("%foo")) ).to_sql #=> "WHERE price = 2.99 OR name LIKE '%foo'" railscasts.com/episodes/215-advanced-queries-in-rails-3 Wednesday, November 9, 11
  • 42. La abstracción dificulta el uso de features avanzados Wednesday, November 9, 11
  • 43. Los stored procedures ofrecen una alternativa interesante Wednesday, November 9, 11
  • 45. Nihil sub sole novum Wednesday, November 9, 11
  • 46. Postgres y MySQL están muy desaprovechados Wednesday, November 9, 11
  • 47. No usemos abstracciones innecesarias Wednesday, November 9, 11
  • 50. Gracias, fotógrafos Obelisco: flickr.com/photos/budgetplaces/4173902613/ Matz: flickr.com/photos/rrrodrigo/2394122680/ Wednesday, November 9, 11