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

Contenu connexe

Tendances

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
 

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

En vedette

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
 

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

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

Similaire à 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...
 
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_ЯндексеТанки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
 

Plus 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
 

Plus 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
 

Dernier

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
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Dernier (20)

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
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

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/