Main menu:

Site search

Categories

Tags

intern

Oracle und SQL

Perl

XML Generation in Perl - how it should have always been

At first big thanks to Mark Overmeer for XML::Compile. I had the pleasure to meet Mark in .nl once - cheers and carry on the great work.

Whenever I had to create XML (either with perl or php) I did it one way or the other with some sort of templating toolkit. In php I use(d) http://www.tinybutstrong.com/ for creating xml . In perl several templating systems come into mind like

  • tt2
  • Template::Declare
  • and many others more
  • Feeling Wrong

    this always felt wrong and awkward for several reasons:

  • You need to build/have the xml before (and creating xml from xsd is not one of my many hobbies)
  • You/the templating system have to take care whether or not a whole tree needs to be displayed and so on
  • The Rescue: XML::Compile

    This nifty Module comes to the rescue. Using XML::Compile make xml+xsd behave like I always wanted to.

    I want to demonstrate this using epp as an example. I want to create a valid epp frame for creating a contact object.

    The epp schemas may be obtained by a simple internet search eg here.

    You may create a valid epp frame by reading the both the contact-1.0.xsd and the epp-1.0.xsd each approx. 400 lines of thrilling xml. Or use some code like:

    1. Convert xsd to perl hash

    use strict;
    use warnings;
    
    use XML::Compile::Schema;
    
    my $schema = XML::Compile::Schema->new([
         'epp-xsd/epp-1.0.xsd',
         'epp-xsd/eppcom-1.0.xsd',
         'epp-xsd/contact-1.0.xsd',
                          ]);
    
    my $s = $schema->template('PERL' => '{urn:ietf:params:xml:ns:contact-1.0}create');
    print $s;
    

    which gives you a more readable idea what your data should look like:

    # is a x0:createType
    { # sequence of id, postalInfo, voice, fax, email, authInfo, disclose
    
      # is a xs:token
      # length <= 16
      # length >= 3
      id => "token",
    
      # is a x0:postalInfoType
      # occurs 1 <= # <= 2 times
      postalInfo =>
      [ { # sequence of name, org, addr
    
          # is a xs:normalizedString
          # length <= 255
          # length >= 1
          name => "example",
    ....
    

    Using this perl hash template you create the first part of your epp-xml

    2. Use perl hash to xml conversion

    use strict;
    use warnings;
    
    use XML::Compile::Schema;
    
    my $schema = XML::Compile::Schema->new([
         'epp-xsd/epp-1.0.xsd',
         'epp-xsd/eppcom-1.0.xsd',
         'epp-xsd/contact-1.0.xsd'
       ]);
    
    my $write  = $schema->compile(WRITER => '{urn:ietf:params:xml:ns:contact-1.0}create');
    my $doc    = XML::LibXML::Document->new('1.0', 'UTF-8');
    my $hash = {
                  id => 'idid',
                  postalInfo => {
                    'name' => 'name',
                    'addr' => {
                        'street' => ['street', 'street2'],
                        'city'   => 'city',
                        'cc'     => 'cc',
                    },
                    type => 'int',
                  },
                  email => 'mymail',
                  "authInfo" => {pw => "PWauthInfo"},
               };
    my $xml    = $write->($doc, $hash);
    $doc->setDocumentElement($xml);
    
    print $doc->toString(1);
    

    this leads to the following xml

    <?xml version="1.0" encoding="UTF-8"?>
    <x0:create xmlns:x0="urn:ietf:params:xml:ns:contact-1.0">
      <x0:id>idid</x0:id>
      <x0:postalInfo type="int">
        <x0:name>name</x0:name>
        <x0:addr>
          <x0:street>street</x0:street>
          <x0:street>street2</x0:street>
          <x0:city>city</x0:city>
          <x0:cc>cc</x0:cc>
        </x0:addr>
      </x0:postalInfo>
      <x0:email>mymail</x0:email>
      <x0:authInfo>
        <x0:pw>PWauthInfo</x0:pw>
      </x0:authInfo>
    </x0:create>
    

    this xml has to be wrapped into an epp frame. As the epp frame uses xml any elements some “manual” work is necessary for creating the complete epp frame. In principle you start with {urn:ietf:params:xml:ns:epp-1.0}epp at step one.

    3. Generate epp-xml-frame and wrap contact-create command into it

    use strict;
    use warnings;
    
    use XML::Compile::Cache;
    use XML::Compile::Schema;
    
    my $cache = XML::Compile::Cache->new([
         'epp-xsd/eppcom-1.0.xsd',
         'epp-xsd/epp-1.0.xsd',
         'epp-xsd/extensions.xsd',
         'epp-xsd/contact-1.0.xsd',
       ]);
    
    my $create_contact_ns = '{urn:ietf:params:xml:ns:contact-1.0}create';
    my $epp_frame_ns = '{urn:ietf:params:xml:ns:epp-1.0}epp';
    my $prefixes = {'urn:ietf:params:xml:ns:contact-1.0' => 'contact'};
    
    $cache->declare(WRITER => [$create_contact_ns, $epp_frame_ns, ],
           (
             prefixes => $prefixes,
             use_default_namespace => 1,
             include_namespaces => 1,
            )
          );
    
    $cache->compileAll;
    
    my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
    $doc->setStandalone(0);
    
    my $contact_data = {
                    id => 'idid',
                    postalInfo => {
                      'name' => 'name',
                      'addr' => {
                          'street' => ['street', 'street2'],
                          'city'   => 'city',
                          'cc'     => 'cc',
                      },
                      type => 'int',
                    },
                    email => 'mymail',
                    "authInfo" => {pw => "PWauthInfo"},
                 };
    
    my $xml = $cache->writer($create_contact_ns)->($doc, $contact_data);
    
    my $epp_frame_data = {
    	         command => {
                  create => {
                    '{urn:ietf:params:xml:ns:contact-1.0}create' => $xml,
                    },
                  clTRID => "token",
                 },
               };
    
    my $eppxml = $cache->writer($epp_frame_ns)->($doc, $epp_frame_data);
    
    $eppxml->setNamespace( 'http://www.w3.org/2001/XMLSchema-instance', 'xsi', 0 ); ## append additonal ns for the feelinx
    
    print $doc->toString(1) .
          $eppxml->toString(1) ."n";
    

    Voila, we have a valid epp frame without even touching the xml! Again Kudos to Mark Overmeer for making this possible!

    4. The result

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <command>
        <create>
          <contact:create xmlns:contact="urn:ietf:params:xml:ns:contact-1.0">
            <contact:id>idid</contact:id>
            <contact:postalInfo type="int">
              <contact:name>name</contact:name>
              <contact:addr>
                <contact:street>street</contact:street>
                <contact:street>street2</contact:street>
                <contact:city>city</contact:city>
                <contact:cc>cc</contact:cc>
              </contact:addr>
            </contact:postalInfo>
            <contact:email>mymail</contact:email>
            <contact:authInfo>
              <contact:pw>PWauthInfo</contact:pw>
            </contact:authInfo>
          </contact:create>
        </create>
        <clTRID>token</clTRID>
      </command>
    </epp>
    

    Das XML der Statistik Austria

    Lobenswerterweise stellt die die Statistik-Austria sehr viele Daten zur “freien” Verfügung ins Netz. So auch alle Straßen- und Ortsnamen Österreichs. Wer sich allerdings das XML ausgedacht hat zb:

    <datensatz>
    <element>10101</element>
    <element>Eisenstadt</element>
    <element>00001</element>
    <element>Eisenstadt</element>
    <element>000001</element>
    <element>Josef Stanislaus Albach-Gasse</element>
    <element>7000</element>
    <element>10101</element>
    </datensatz>

    der hat geistig den Umstieg von csv zu xml noch nicht ganz verkraftet ;-)

    Registrar(Partner) bei der switch.ch werden

    Nachdem ich ja beruflich mit einigen Registries zu tun habe - ich arbeite primär für die nic.at - kenne ich einige Zulassungsprozesse für ccTLD Registries.

    Der bei weitem “lustigste” Prozess ist der der switch.ch, der Schweizer Registry. Dort sind nicht nur finanzielle und organisatorische Hürden zu nehmen (und auch die sind nicht zu knapp) sondern auch ein technischer Parcours.

    Dieser Parcours (der heißt wirklich so) besteht aus 23 epp transactionen (Querbeet, dh personen, hostobjekte, domains anlegen, löschen und so weiter) die einem Durchgang durchzuführen sind.

    Das bedeutet, daß jeder Registrar neben des Implementierungsaufwands für den normalen Clienten, sich nochmals zwei Tage (solange habe ich alles in allem gebraucht) Zeit & Geld nehmen darf um den Parcours zu implementieren. Man muß allerdings auch wirklich zugeben, wenn man den Parcour implementiert (und somit verstanden) hat, daß man auch die Prozesse der switch “durchschaut” hat.

    Scraping web pages in JavaScript with Perl

    Sometimes you want to scrape Webpages which contain JavaScript and therefore resist beeing scraped with Web::Scraper or the likes. Imagine some JavaScript code like the following to disguise a email address.

    function mail() {
    var name = "mail";
    var domain = "example.com";
    var mailto = 'mailto:' + name + '@' + domain;
    document.write(mailto);
    }
    mail();

    One could use somethink elaborate like Selenium to execute the code within a browser and then extract the address with “conventional” means. There are cases when this isn’t sufficent.
    Enter JavaScript::SpiderMonkey, which allows you to execute JavaScript Code on the console without a browser. The only problem remaining is that the console doesn’t provide some properties and methods the browser has, so you have to define them yourself. This happens from line 11-14 where we define the “document” and the method “write”. The rest of the code is pretty self explanatory.


    000: use strict;
    001: use warnings;
    002:
    003: use Slurp;
    004: use JavaScript::SpiderMonkey;
    005:
    006: my $js = JavaScript::SpiderMonkey->new();
    007: my $code = slurp('mailto.js');
    008:
    009: $js->init();
    010:
    011: my $obj = $js->object_by_path("document");
    012:
    013: my @write;
    014: $js->function_set("write", sub { push @write, @_ }, $obj);
    015:
    016: my $rc = $js->eval(
    017: $code
    018: );
    019:
    020: printf "document.write:\n%s\n", join "\n", @write;
    021: printf "Error: %s\n", $@;
    022: printf "Return Code: %s\n", $rc;
    023:
    024: $js->destroy();

    The output is:
    document.write:
    mailto:mail@example.com
    Error:
    Return Code: 1

    Oracle 11.2:IGNORE_ROW_ON_DUPKEY_INDEX - Please No!

    Oracle hat mit 11.2 neue optimizer hints “erfunden” und zwar auch IGNORE_ROW_ON_DUPKEY_INDEX.

    Er dient dazu (wie der Name schon sagt) bei einem INSERT  (und nicht bei einem UPDATE!) auf einen Unique Key die Exception zu ignorieren und das statement tut dann einfach nichts. Es würde dann also zb funktionieren (ohne unique key violation):

    insert into testtable (id, text) values (1, 'testtext der erste');
    insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(testtable(id))*/ into testtable (id, text) values (1, 'testtext der zweite');

    Dieser Hint ist eigentlich kein Hint sondern eine Option (…), und außerdem aus mehreren Gründen keine gute Idee:

    • andere Oracle Hints (zb für den Optimizer) verändern das Verhalten des Statments nicht, und sind somit kompatibel mit anderen Datenbanken
    • es gibt schon ein statment mit dem man den gleichen Effekt erreichen kann und zwar MERGE, welches man mittelfristig sicher auch in anderen Datenbanken wie Postgres erwarten kann

    Und gleich der Vollständigkeit halber das MERGE-Statement:

    merge into testtable
    using (select 1 from dual)
    on (id = :b_id)
    when not matched then
    insert (id, text) values (:b_id, :b_text);

    ich verwende deswegen bind Variablen weil man ansonsten den Wert :b_id zweimal einsetzen müßte. Entgegen anderslautenden Gerüchten muß es keinen “when matched … where 2=1″ (oder Ähnliches) Abschnitt geben. Das “select 1 from dual” dient dazu um genau ein Zeile zum bekommen und somit die Zahl der zu behandelnden Zeilen zu determinieren.

    Die Relevanz der Inflationsrate

    Zend, Oracle, perl, php

    Oracle XE on Suse 11 64bit

    Oracle XE (Express Edition) uses libaio 32bit. So if you want to install it on 64bit system you have to install the 32bit version. For example from here

    nic.at epp client on github (written in php)

    I decided that from now on the source code for the  epp client for domain registries (templates specifically for the austrian top level domain .at) will reside on github

    The giturl you’ll find the code at is

    http://github.com/MarkHofstetter/php-epp-client

    remarks/comments/suggestion are very welcome

    The Zend Guestbook demo with Oracle 11g

    The Zend Guestbook demo implemented with Zend 1.95, Oracle 11g and the xampp package

    download the complete example here

    First things first. Don’t, *again* don’t, use Zend 1.9 which seems to have some bugs, use at least 1.91.
    What I’ve done I changed as few things as possible to get the guestbook quickstart demo running on Oracle.
    Only some minor yak shaving had to take place:

    • You cannot easily user the Zend .ini style configuration  because you need some Db_Zend constansts, so you either have to use XML style config or hardcode the constants (and the credentials) directly in the Bootstrap.php file (the easy route which I have taken)
    • In Oracle its not possible to name a column “COMMENT” so I have chosen “COMMENTS” instead which is equally bad but at least working
    • Use at least Zend 1.91, have I already mentioned that?
    • I haven’t came around to get “Zend_Db::CASE_FOLDING => Zend_Db::CASE_UPPER” working quickly, so all the column names used have to be upper case as they are stored in the Oracle data dictonary views

    Installation

    • Be careful, if you break something it’s your fault not mine
    • Everything is you need is in the zip file which should be unpacked in a directory accessable by your webserver, in the many cases (also with the XAMPP and LAMPP packages) this folder is named “htdocs”

    Database (Oracle) Side

    • if you have user create privileges (usually SYSTEM or SYS user), you may execute the questbook.sql script found in the INSTALL folder
    • if you don’t have user create privileges, but a database user (the name doesn’t matter) login as the user and start with line 6 (the create sequence command) of the guestbook.sql file

    PHP Side

    • in application/Bootstrap.php change the dbname, username and password to your settings

    You are ready

    • navigate your web browser to http://<yourhostname>/quickstart/public/guestbook and everything should work out fine

    20 Jahre Mauerfall im Lichte von RDBMS

    In jedem meiner Datenbankkurse predige ich ein paar Stehsätze einer davon lautet

    jede Tabelle muß eine “abstrake” ID haben, und es ist sehr schlecht “scheinbar” eindeutige numerische Felder wie zum Beispiel Kontonummer, Personalnummer oder auch die Postleitzahl als ID zu mißbrauchen.

    Ich bringe immer das Beispiel das eine Personentabelle mit einer Orte Tabellen über die Postleitzahl verknüpft ist. Was von den meisten Teilnehmer mit einem begeisterten Kopfnicken quittiert wird “ist ja eh eindeutig und wird sich sicher NIE ändern”.

    Dann kommt mein großer Moment und ich sage: “Und dann kommt die Wiedervereinigung und das ganze Datenmodell bricht zusammen!”. Das ist sehr deutlich und einprägsam - nur sind mittlerweile auch so junge Teilnehmer dabei bei denen das große Ereignis eben nicht mehr so präsent ist. Hm ich werde alt. Meine Hoffnungen ruhen auf Nord- und Südkorea für neue Beispiele.

    In diesem Sinne ist der positive Beitrag des Mauerfalls zum Thema “Datenbankdidaktik” gar nicht hoch genug einzuschätzen!