SlideShare una empresa de Scribd logo
1 de 36
PostgreSQL Gems:
Running Perl and Ruby Inside the Database


David Fetter http://fetter.org/
Copyright 2007
All Rights Reserved
PostgreSQL
Procedural Languages
PL/PgSQL
PL/Perl(U)
PL/Ruby(U)
PL/Scheme(U)
PL/Java(U)
PL/Parrot(U)?
The Trust Issue
Untrusted
   Can open pipes, filehandles
   Superuser
Trusted
   Can't
   Regular user
Perl


The Onion We Know and Love
Tools and Techniques

http://www.cpan.org
More Tools and Techniques


%_SHARED
Debugging Basics

warn
die
elog
More Advanced Debugging

use YAML;
...
warn Dump($complex_thing);
Debuggers

Debugging is twice as   hard as writing
the code in the first   place. Therefore,
if you write the code   as cleverly as
possible, you are, by   definition, not
smart enough to debug   it.

                                Kernighan
Ruby


A Nifty Gem
Tools and Techniques

http://rubygems.org/
LOLCODE!

           IM IN UR DATABASE
           READING UR ROWS

http://pgfoundry.org/projects/pllolcode/
A Custom Data Type

Bar Codes:

* UPC
* EAN
* GTIN
* Oy vey!

So you have to ask yourself a question...
How to do it

Luckily, they are all GTINs

And they have a checksum
How (not!) to do it in PL/Perl
CREATE OR REPLACE FUNCTION is_gtin(bigint) RETURNS
BOOLEAN
LANGUAGE plperl
AS $$
  my $i = 0;
  my $total = 0;
  for my $c (reverse split //, shift) {
     $i++;
     $total += $i % 2 ? $c : $c * 3;
  }
  return $total % 10 ? 'false' : 'true';
$$;
How to do it in PL/Ruby
CREATE OR REPLACE FUNCTION isa_gtin(bigint)
RETURNS BOOLEAN
LANGUAGE plruby
AS $$
  chars = args[0].to_s.split('').reverse
  total = 0
  chars.each_index { |i|
    total += i % 2 == 0 ? chars[i].to_i : chars[i].to_i * 3
  }
  return !!(total % 10 == 0)
$$;
How to do it in SQL :)
CREATE OR REPLACE FUNCTION is_gtin(bigint)
RETURNS BOOLEAN
LANGUAGE sql
STRICT IMMUTABLE
AS $$
   SELECT ( sum(dgt) % 10 ) = 0
   FROM (
      SELECT substring($1 from idx for 1)::smallint AS dgt
      FROM (SELECT generate_series(length($1), 1, -2) as idx) AS foo
      UNION ALL
      SELECT substring($1 from idx for 1)::smallint * 3 AS dgt
      FROM (SELECT generate_series(length($1) -1, 1, -2) as idx) AS
foo
   ) AS bar;
$$;
Creating The GTIN Data Type


CREATE TYPE gtin AS BIGINT
    CHECK ( is_gtin(VALUE) );
A More Complex Data Type


CREATE TYPE email AS TEXT
    CHECK ( is_email(VALUE) );
Defining A Function

CREATE OR REPLACE FUNCTION
is_email(text)
RETURNS BOOLEAN
LANGUAGE plperlu
AS $$
...
$$;
Perl Regex for Email
        (?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn
        015()]|[^x80-xff])*))*))*(?:(?:[^(040)<>@,;:quot;.[]000-037x80-
        xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|quot;(?:[^x80-xffn015quot;
        ]|[^x80-xff])*quot;)(?:(?:[040t]|((?:[^x80-xffn015()]|[^x80-xf
          f]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*.(?:[040t]|((?:[
      ^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-
        xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;
        :quot;.[]000-037x80-xff])|quot;(?:[^x80-xffn015quot;]|[^x80-xff])*quot;))
        *(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xff
       n015()]|[^x80-xff])*))*))*@(?:[040t]|((?:[^x80-xffn015()]|
        [^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(04
      0)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-
         xff])|[(?:[^x80-xffn015[]]|[^x80-xff])*])(?:(?:[040t]|((?
      :[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80
          -xff])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|(
        (?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]
       000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^
      x80-xffn015[]]|[^x80-xff])*]))*|(?:[^(040)<>@,;:quot;.[]000-0
        37x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|quot;(?:[^x80-xf
        fn015quot;]|[^x80-xff])*quot;)(?:[^()<>@,;:quot;.[]x80-xff000-010012-03
       7]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|
       [^x80-xff])*))*)|quot;(?:[^x80-xffn015quot;]|[^x80-xff])*quot;)*<(?:[04
        0t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]
       |[^x80-xff])*))*))*(?:@(?:[040t]|((?:[^x80-xffn015()]|[^x
       80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@
         ,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff]
        )|[(?:[^x80-xffn015[]]|[^x80-xff])*])(?:(?:[040t]|((?:[^
       x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff
         ])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^
       x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-
       037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^x80-
        xffn015[]]|[^x80-xff])*]))*(?:(?:[040t]|((?:[^x80-xffn01
        5()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*,(?
       :[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn0
       15()]|[^x80-xff])*))*))*@(?:[040t]|((?:[^x80-xffn015()]|[^
        x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<
       >@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xf
         f])|[(?:[^x80-xffn015[]]|[^x80-xff])*])(?:(?:[040t]|((?:[^
      x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-x
          ff])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:
       [^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]00
       0-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^x8
         0-xffn015[]]|[^x80-xff])*]))*)*:(?:[040t]|((?:[^x80-xffn
        015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*)
      ?(?:[^(040)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000
          -037x80-xff])|quot;(?:[^x80-xffn015quot;]|[^x80-xff])*quot;)(?:(?:[040t]
       |((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[
         ^x80-xff])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xf
        f]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.
        []000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|quot;(?:
       [^x80-xffn015quot;]|[^x80-xff])*quot;))*(?:[040t]|((?:[^x80-xffn
       015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*@
        (?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn
        015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-037x80-xff
       ]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^x80-xffn015[
        ]]|[^x80-xff])*])(?:(?:[040t]|((?:[^x80-xffn015()]|[^x80-
          xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*.(?:[040t]|((?
      :[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80
       -xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@
        ,;:quot;.[]000-037x80-xff])|[(?:[^x80-xffn015[]]|[^x80-xff
       ])*]))*(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x8
         0-xffn015()]|[^x80-xff])*))*))*>)(?:[040t]|((?:[^x80-xffn
         015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*
Better Perl (1/3)


use strict;
use warnings;
Better Perl (2/3)
use Email::Valid;
my $address = shift;
my $checks = {
   -address => $address,
   -mxcheck => 1,
   -tldcheck => 1,
   -rfc822 => 1,
};
Better Perl (3/3)

if (defined Email::Valid->address( %$checks )) {
    return 'true'
}
warn quot;address failed $Email::Valid::Details check.quot;;
return 'false';
The Email Domain in Action
oscon_2007=> SELECT ‘david@fetter.org’::email;
       email
------------------
 david@fetter.org
(1 row)

oscon_2007=> SELECT ‘david@fetter.con’::email;
ERROR: value for domain email violates check constraint quot;email_checkquot;
Perl on Both Sides
#!/usr/bin/env perl

use strict;
use warnings;

use DBI;
my $dbh = DBI->connect(‘dbi:Pg:dbname=wow’,’user’,’secret’,
  {RaiseError => 1, AutoCommit => 0});

# And go on as usual
A Usual Program (1/3)

use Proc::ProcessTable;
my $t = new Proc::ProcessTable;
my $p = shift ( @{ $t->table });
my @fields = ();
Still Usual (2/3)
foreach my $f ($t->fields) {
    if ($p->{$f} =~ m/-?d*.?d+/) {
        push @fields, quot;$f FLOAT8quot;;
    }
    elsif ($p->{$f} =~ m/^-?d+$/) {
        push @fields, quot;$f INT8quot;;
    }
    else {
        push @fields, quot;$f TEXTquot;;
    }
}
Still Usual (3/3)

print <<CREATE_TYPE;
CREATE TYPE process_table_type AS (
    @{[ join(quot;,n    quot;, @fields) ]}
);
CREATE_TYPE
Down the Rabbit Hole

$ psql oscon_2007
Welcome to psql 8.2.4, the PostgreSQL interactive
terminal.
...
oscon_2007=> set mptt `./make_process_table_type.pl`
oscon_2007=> :mptt
CREATE TYPE
The PL/PerlU Function
CREATE OR REPLACE FUNCTION get_ps ()
RETURNS SETOF process_table_type
LANGUAGE plperlu AS
$$
    use Proc::ProcessTable;
    my $proctab = new Proc::ProcessTable;
    return $proctab->table;
$$;
A Query

SELECT *
FROM
  pg_class quot;c1quot;,
  pg_class quot;c2quot;,
  pg_class quot;c3quot;;
What is happening?!?
SELECT a.current_query, MAX(p.size)
FROM
     pg_stat_activity AS quot;aquot;
JOIN
     get_ps() AS quot;pquot;
     ON (a.procpid = p.pid)
GROUP BY a.current_query;
Aha!
       current_query    |   size
------------------------+-----------
SELECT *                |
FROM                    |
     pg_class quot;c1quot;,     |
     pg_class quot;c2quot;,     |
     pg_class quot;c3quot;;     | 195290000

(1 row)
Thanks!
Copyright David Fetter 2007
All Rights Reserved
http://fetter.org/

Más contenido relacionado

La actualidad más candente

Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...GeeksLab Odessa
 
JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APItvaleev
 
Naughty And Nice Bash Features
Naughty And Nice Bash FeaturesNaughty And Nice Bash Features
Naughty And Nice Bash FeaturesNati Cohen
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
CSS parsing: performance tips & tricks
CSS parsing: performance tips & tricksCSS parsing: performance tips & tricks
CSS parsing: performance tips & tricksRoman Dvornov
 
When RegEx is not enough
When RegEx is not enoughWhen RegEx is not enough
When RegEx is not enoughNati Cohen
 
Implementing pattern-matching in JavaScript (short version)
Implementing pattern-matching in JavaScript (short version)Implementing pattern-matching in JavaScript (short version)
Implementing pattern-matching in JavaScript (short version)François-Guillaume Ribreau
 
Clojure: Simple By Design
Clojure: Simple By DesignClojure: Simple By Design
Clojure: Simple By DesignAll Things Open
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers ToolboxStefan
 
Overpsss API / Overpass-Turbo
Overpsss API / Overpass-TurboOverpsss API / Overpass-Turbo
Overpsss API / Overpass-TurboYu-Chin Tsai
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Workhorse Computing
 
Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...
Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...
Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...Ontico
 
Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.David Tollmyr
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]Baruch Sadogursky
 
Comparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerlComparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerlJason Stajich
 
Expression trees in c#
Expression trees in c#Expression trees in c#
Expression trees in c#Oleksii Holub
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Workhorse Computing
 

La actualidad más candente (20)

Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
 
JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream API
 
Naughty And Nice Bash Features
Naughty And Nice Bash FeaturesNaughty And Nice Bash Features
Naughty And Nice Bash Features
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
CSS parsing: performance tips & tricks
CSS parsing: performance tips & tricksCSS parsing: performance tips & tricks
CSS parsing: performance tips & tricks
 
When RegEx is not enough
When RegEx is not enoughWhen RegEx is not enough
When RegEx is not enough
 
Implementing pattern-matching in JavaScript (short version)
Implementing pattern-matching in JavaScript (short version)Implementing pattern-matching in JavaScript (short version)
Implementing pattern-matching in JavaScript (short version)
 
Clojure: Simple By Design
Clojure: Simple By DesignClojure: Simple By Design
Clojure: Simple By Design
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
Overpsss API / Overpass-Turbo
Overpsss API / Overpass-TurboOverpsss API / Overpass-Turbo
Overpsss API / Overpass-Turbo
 
Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!Hypers and Gathers and Takes! Oh my!
Hypers and Gathers and Takes! Oh my!
 
Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...
Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...
Как писать сервис, поддержка которого не превращается в ад / Антон Резников, ...
 
Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.Gotcha! Ruby things that will come back to bite you.
Gotcha! Ruby things that will come back to bite you.
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Git
GitGit
Git
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
Comparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerlComparative Genomics with GMOD and BioPerl
Comparative Genomics with GMOD and BioPerl
 
Expression trees in c#
Expression trees in c#Expression trees in c#
Expression trees in c#
 
League of Graphs
League of GraphsLeague of Graphs
League of Graphs
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 

Destacado

Os Nightingale
Os NightingaleOs Nightingale
Os Nightingaleoscon2007
 
Os Nolen Gebhart
Os Nolen GebhartOs Nolen Gebhart
Os Nolen Gebhartoscon2007
 
Os Schlossnagle Theo
Os Schlossnagle TheoOs Schlossnagle Theo
Os Schlossnagle Theooscon2007
 
J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Touroscon2007
 

Destacado (8)

Os Nightingale
Os NightingaleOs Nightingale
Os Nightingale
 
Os Leonard
Os LeonardOs Leonard
Os Leonard
 
Os Lonergan
Os LonerganOs Lonergan
Os Lonergan
 
Os Pittaro
Os PittaroOs Pittaro
Os Pittaro
 
Os Nolen Gebhart
Os Nolen GebhartOs Nolen Gebhart
Os Nolen Gebhart
 
Os Schlossnagle Theo
Os Schlossnagle TheoOs Schlossnagle Theo
Os Schlossnagle Theo
 
Os Vandeven
Os VandevenOs Vandeven
Os Vandeven
 
J Ruby Whirlwind Tour
J Ruby Whirlwind TourJ Ruby Whirlwind Tour
J Ruby Whirlwind Tour
 

Similar a PostgreSQL Gems Running Code

Unsung Heroes of PHP
Unsung Heroes of PHPUnsung Heroes of PHP
Unsung Heroes of PHPjsmith92
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertextfrankieroberto
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011Scalac
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Raffi Krikorian
 
Get Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsGet Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsDavey Shafik
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And PortKeiichi Daiba
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And PortKeiichi Daiba
 
LAMP_TRAINING_SESSION_6
LAMP_TRAINING_SESSION_6LAMP_TRAINING_SESSION_6
LAMP_TRAINING_SESSION_6umapst
 
LAMP_TRAINING_SESSION_1
LAMP_TRAINING_SESSION_1LAMP_TRAINING_SESSION_1
LAMP_TRAINING_SESSION_1umapst
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With PhpJeremy Coates
 
Thinking regular expressions
Thinking regular expressionsThinking regular expressions
Thinking regular expressionsPinMeTo
 
JSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederJSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederChristoph Pickl
 
Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...
Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...
Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...Arc & Codementor
 
Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Damien Seguy
 
The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...
The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...
The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...Globus
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
 
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеТанки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеYandex
 

Similar a PostgreSQL Gems Running Code (20)

Unsung Heroes of PHP
Unsung Heroes of PHPUnsung Heroes of PHP
Unsung Heroes of PHP
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
Get Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsGet Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP Streams
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And Port
 
LAMP_TRAINING_SESSION_6
LAMP_TRAINING_SESSION_6LAMP_TRAINING_SESSION_6
LAMP_TRAINING_SESSION_6
 
Lettering js
Lettering jsLettering js
Lettering js
 
Ae internals
Ae internalsAe internals
Ae internals
 
LAMP_TRAINING_SESSION_1
LAMP_TRAINING_SESSION_1LAMP_TRAINING_SESSION_1
LAMP_TRAINING_SESSION_1
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
 
Thinking regular expressions
Thinking regular expressionsThinking regular expressions
Thinking regular expressions
 
JSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederJSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael Greifeneder
 
Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...
Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...
Codementor Office Hours with Eric Chiang: Stdin, Stdout: pup, Go, and life at...
 
Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020Top 10 php classic traps DPC 2020
Top 10 php classic traps DPC 2020
 
The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...
The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...
The NCAR RDA–Globus Integration: Experiences Developing a Modern Research Dat...
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеТанки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
 

Más de oscon2007

Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5oscon2007
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifmoscon2007
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Moleoscon2007
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashearsoscon2007
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swposcon2007
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Mythsoscon2007
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholisticoscon2007
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillipsoscon2007
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdatedoscon2007
 
Adventures In Copyright Reform
Adventures In Copyright ReformAdventures In Copyright Reform
Adventures In Copyright Reformoscon2007
 

Más de oscon2007 (20)

Solr Presentation5
Solr Presentation5Solr Presentation5
Solr Presentation5
 
Os Borger
Os BorgerOs Borger
Os Borger
 
Os Harkins
Os HarkinsOs Harkins
Os Harkins
 
Os Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman WiifmOs Fitzpatrick Sussman Wiifm
Os Fitzpatrick Sussman Wiifm
 
Os Bunce
Os BunceOs Bunce
Os Bunce
 
Yuicss R7
Yuicss R7Yuicss R7
Yuicss R7
 
Performance Whack A Mole
Performance Whack A MolePerformance Whack A Mole
Performance Whack A Mole
 
Os Fogel
Os FogelOs Fogel
Os Fogel
 
Os Lanphier Brashears
Os Lanphier BrashearsOs Lanphier Brashears
Os Lanphier Brashears
 
Os Tucker
Os TuckerOs Tucker
Os Tucker
 
Os Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman SwpOs Fitzpatrick Sussman Swp
Os Fitzpatrick Sussman Swp
 
Os Furlong
Os FurlongOs Furlong
Os Furlong
 
Os Berlin Dispelling Myths
Os Berlin Dispelling MythsOs Berlin Dispelling Myths
Os Berlin Dispelling Myths
 
Os Kimsal
Os KimsalOs Kimsal
Os Kimsal
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
Os Alrubaie
Os AlrubaieOs Alrubaie
Os Alrubaie
 
Os Keysholistic
Os KeysholisticOs Keysholistic
Os Keysholistic
 
Os Jonphillips
Os JonphillipsOs Jonphillips
Os Jonphillips
 
Os Urnerupdated
Os UrnerupdatedOs Urnerupdated
Os Urnerupdated
 
Adventures In Copyright Reform
Adventures In Copyright ReformAdventures In Copyright Reform
Adventures In Copyright Reform
 

Último

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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
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 future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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
 

Último (20)

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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
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 future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 

PostgreSQL Gems Running Code

  • 1. PostgreSQL Gems: Running Perl and Ruby Inside the Database David Fetter http://fetter.org/ Copyright 2007 All Rights Reserved
  • 4. The Trust Issue Untrusted Can open pipes, filehandles Superuser Trusted Can't Regular user
  • 5. Perl The Onion We Know and Love
  • 7. More Tools and Techniques %_SHARED
  • 9. More Advanced Debugging use YAML; ... warn Dump($complex_thing);
  • 10. Debuggers Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Kernighan
  • 13. LOLCODE! IM IN UR DATABASE READING UR ROWS http://pgfoundry.org/projects/pllolcode/
  • 14. A Custom Data Type Bar Codes: * UPC * EAN * GTIN * Oy vey! So you have to ask yourself a question...
  • 15. How to do it Luckily, they are all GTINs And they have a checksum
  • 16. How (not!) to do it in PL/Perl CREATE OR REPLACE FUNCTION is_gtin(bigint) RETURNS BOOLEAN LANGUAGE plperl AS $$ my $i = 0; my $total = 0; for my $c (reverse split //, shift) { $i++; $total += $i % 2 ? $c : $c * 3; } return $total % 10 ? 'false' : 'true'; $$;
  • 17. How to do it in PL/Ruby CREATE OR REPLACE FUNCTION isa_gtin(bigint) RETURNS BOOLEAN LANGUAGE plruby AS $$ chars = args[0].to_s.split('').reverse total = 0 chars.each_index { |i| total += i % 2 == 0 ? chars[i].to_i : chars[i].to_i * 3 } return !!(total % 10 == 0) $$;
  • 18. How to do it in SQL :) CREATE OR REPLACE FUNCTION is_gtin(bigint) RETURNS BOOLEAN LANGUAGE sql STRICT IMMUTABLE AS $$ SELECT ( sum(dgt) % 10 ) = 0 FROM ( SELECT substring($1 from idx for 1)::smallint AS dgt FROM (SELECT generate_series(length($1), 1, -2) as idx) AS foo UNION ALL SELECT substring($1 from idx for 1)::smallint * 3 AS dgt FROM (SELECT generate_series(length($1) -1, 1, -2) as idx) AS foo ) AS bar; $$;
  • 19. Creating The GTIN Data Type CREATE TYPE gtin AS BIGINT CHECK ( is_gtin(VALUE) );
  • 20. A More Complex Data Type CREATE TYPE email AS TEXT CHECK ( is_email(VALUE) );
  • 21. Defining A Function CREATE OR REPLACE FUNCTION is_email(text) RETURNS BOOLEAN LANGUAGE plperlu AS $$ ... $$;
  • 22. Perl Regex for Email (?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn 015()]|[^x80-xff])*))*))*(?:(?:[^(040)<>@,;:quot;.[]000-037x80- xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|quot;(?:[^x80-xffn015quot; ]|[^x80-xff])*quot;)(?:(?:[040t]|((?:[^x80-xffn015()]|[^x80-xf f]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*.(?:[040t]|((?:[ ^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80- xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,; :quot;.[]000-037x80-xff])|quot;(?:[^x80-xffn015quot;]|[^x80-xff])*quot;)) *(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xff n015()]|[^x80-xff])*))*))*@(?:[040t]|((?:[^x80-xffn015()]| [^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(04 0)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80- xff])|[(?:[^x80-xffn015[]]|[^x80-xff])*])(?:(?:[040t]|((? :[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80 -xff])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|( (?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[] 000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^ x80-xffn015[]]|[^x80-xff])*]))*|(?:[^(040)<>@,;:quot;.[]000-0 37x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|quot;(?:[^x80-xf fn015quot;]|[^x80-xff])*quot;)(?:[^()<>@,;:quot;.[]x80-xff000-010012-03 7]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]| [^x80-xff])*))*)|quot;(?:[^x80-xffn015quot;]|[^x80-xff])*quot;)*<(?:[04 0t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()] |[^x80-xff])*))*))*(?:@(?:[040t]|((?:[^x80-xffn015()]|[^x 80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@ ,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff] )|[(?:[^x80-xffn015[]]|[^x80-xff])*])(?:(?:[040t]|((?:[^ x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff ])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^ x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]000- 037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^x80- xffn015[]]|[^x80-xff])*]))*(?:(?:[040t]|((?:[^x80-xffn01 5()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*,(? :[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn0 15()]|[^x80-xff])*))*))*@(?:[040t]|((?:[^x80-xffn015()]|[^ x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)< >@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xf f])|[(?:[^x80-xffn015[]]|[^x80-xff])*])(?:(?:[040t]|((?:[^ x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-x ff])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?: [^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]00 0-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^x8 0-xffn015[]]|[^x80-xff])*]))*)*:(?:[040t]|((?:[^x80-xffn 015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*) ?(?:[^(040)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000 -037x80-xff])|quot;(?:[^x80-xffn015quot;]|[^x80-xff])*quot;)(?:(?:[040t] |((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[ ^x80-xff])*))*))*.(?:[040t]|((?:[^x80-xffn015()]|[^x80-xf f]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;. []000-037x80-xff]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|quot;(?: [^x80-xffn015quot;]|[^x80-xff])*quot;))*(?:[040t]|((?:[^x80-xffn 015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*@ (?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn 015()]|[^x80-xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-037x80-xff ]+(?![^(040)<>@,;:quot;.[]000-037x80-xff])|[(?:[^x80-xffn015[ ]]|[^x80-xff])*])(?:(?:[040t]|((?:[^x80-xffn015()]|[^x80- xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*.(?:[040t]|((? :[^x80-xffn015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80 -xff])*))*))*(?:[^(040)<>@,;:quot;.[]000-037x80-xff]+(?![^(040)<>@ ,;:quot;.[]000-037x80-xff])|[(?:[^x80-xffn015[]]|[^x80-xff ])*]))*(?:[040t]|((?:[^x80-xffn015()]|[^x80-xff]|((?:[^x8 0-xffn015()]|[^x80-xff])*))*))*>)(?:[040t]|((?:[^x80-xffn 015()]|[^x80-xff]|((?:[^x80-xffn015()]|[^x80-xff])*))*))*
  • 23. Better Perl (1/3) use strict; use warnings;
  • 24. Better Perl (2/3) use Email::Valid; my $address = shift; my $checks = { -address => $address, -mxcheck => 1, -tldcheck => 1, -rfc822 => 1, };
  • 25. Better Perl (3/3) if (defined Email::Valid->address( %$checks )) { return 'true' } warn quot;address failed $Email::Valid::Details check.quot;; return 'false';
  • 26. The Email Domain in Action oscon_2007=> SELECT ‘david@fetter.org’::email; email ------------------ david@fetter.org (1 row) oscon_2007=> SELECT ‘david@fetter.con’::email; ERROR: value for domain email violates check constraint quot;email_checkquot;
  • 27. Perl on Both Sides #!/usr/bin/env perl use strict; use warnings; use DBI; my $dbh = DBI->connect(‘dbi:Pg:dbname=wow’,’user’,’secret’, {RaiseError => 1, AutoCommit => 0}); # And go on as usual
  • 28. A Usual Program (1/3) use Proc::ProcessTable; my $t = new Proc::ProcessTable; my $p = shift ( @{ $t->table }); my @fields = ();
  • 29. Still Usual (2/3) foreach my $f ($t->fields) { if ($p->{$f} =~ m/-?d*.?d+/) { push @fields, quot;$f FLOAT8quot;; } elsif ($p->{$f} =~ m/^-?d+$/) { push @fields, quot;$f INT8quot;; } else { push @fields, quot;$f TEXTquot;; } }
  • 30. Still Usual (3/3) print <<CREATE_TYPE; CREATE TYPE process_table_type AS ( @{[ join(quot;,n quot;, @fields) ]} ); CREATE_TYPE
  • 31. Down the Rabbit Hole $ psql oscon_2007 Welcome to psql 8.2.4, the PostgreSQL interactive terminal. ... oscon_2007=> set mptt `./make_process_table_type.pl` oscon_2007=> :mptt CREATE TYPE
  • 32. The PL/PerlU Function CREATE OR REPLACE FUNCTION get_ps () RETURNS SETOF process_table_type LANGUAGE plperlu AS $$ use Proc::ProcessTable; my $proctab = new Proc::ProcessTable; return $proctab->table; $$;
  • 33. A Query SELECT * FROM pg_class quot;c1quot;, pg_class quot;c2quot;, pg_class quot;c3quot;;
  • 34. What is happening?!? SELECT a.current_query, MAX(p.size) FROM pg_stat_activity AS quot;aquot; JOIN get_ps() AS quot;pquot; ON (a.procpid = p.pid) GROUP BY a.current_query;
  • 35. Aha! current_query | size ------------------------+----------- SELECT * | FROM | pg_class quot;c1quot;, | pg_class quot;c2quot;, | pg_class quot;c3quot;; | 195290000 (1 row)
  • 36. Thanks! Copyright David Fetter 2007 All Rights Reserved http://fetter.org/