Category: nice to know

  • Just some updates on PLSQL

    From time to time, I just repeat old exercises. I do this to maintain my knowledge before it gets lost in the mist of time. One such areas is PLSQL. You never forget that PL SQL is used to maintain data on an Oracle database. But I do forget tiny details such as how to insert a parameter.
    I like to insert the PLSQL code in the client tool SQL Developper. This tool clearly shows where the code is created. It also shows how the PLSQL functions and procedures are related to other database objects like schemes, tables and views.

    Let me show the example. I created one procedure that calls a function. The function looks like:

    create or replace PROCEDURE MAIN AS 
      terug int;
    BEGIN
      dbms_output.put_line(' Hello World');
      terug := test(110221);
    END MAIN;
    

    This procedure is quite simple. It writes something to screen (‘Hello World’) and it calls a function with a parameter (110221). It can be invoked from the command line by the command “exec main”. in this case “main” is the name of the procedure and “exec” indicates that a procedure must be run.
    Starting this from sqlplus looks like:

    We see that ‘Hello World’ is returned.
    The procedure calls a function. This function looks like:

    create or replace function TEST
    (
    INVOER IN INT
    ) RETURN INT AS
    v_name HR.CUSTOMER_IND.CURPNM%TYPE;
    n_table INT;
    teller INT:=0;
    l_uitvoer VARCHAR(100);
    p_table_name VARCHAR(100);
    stmt VARCHAR(250);
    naam VARCHAR(100);
    CURSOR cur_chief
    IS
    select curptw into v_name
    from CUSTOMER_IND where CUNOCU=invoer;
    r_chief cur_chief%ROWTYPE;
    BEGIN
    p_table_name :='ff';
    SELECT COUNT(*) INTO n_table FROM user_tables WHERE table_name = UPPER(p_table_name);
    IF (n_table = 0) THEN
    EXECUTE IMMEDIATE 'create table ' || p_table_name || '(teller int, naam varchar(50))';
    else
    EXECUTE IMMEDIATE 'truncate table ' || p_table_name;
    END IF;
    OPEN cur_chief;
    LOOP
    teller := teller + 1;
    FETCH cur_chief INTO r_chief;
    EXIT WHEN cur_chief%NOTFOUND;
    naam := r_chief.CURPTW;
    stmt := 'insert into '||p_table_name || ' (teller, naam) values(' || teller ||','''||naam||''')';
    DBMS_OUTPUT.PUT_LINE(stmt);
    EXECUTE IMMEDIATE stmt;
    END LOOP;
    RETURN 1;
    END TEST;

    This function contains some ideas that I like. The first idea is the creation of a cursor that contains an outcome set. This cursor is based on a table for which the code is given here. This outcome is made dependent on a parameter. The set of outcomes will be translated into a series of records that will be translated one by one. Such a record is indicated by variable “r_chief”.
    Another trick is a check whether a certain table already exists. This is done by checking the user_tables. If it is already present, the count will be larger than 0. In that case a command will be executed that truncates the table.
    A final trick is looping through the cursor. Each loop writes one record to “r_chief”. From that record, some values are retrieved. The values are then stored in an insert statement. The most tricky part is getting an apostrophe around the value of a string. The apostrophe is also used to terminate a string in the PLSQL code.

  • Swaps: currency swap and foreign exchange swap

    A little note from the area of financial economics. When going through the databases of a financial institution, one often encounters terms like foreign exchange swap, currency swap, interest swap. What is this anyway?

    I understand that a foreign exchange swap is related to a situation that one has foreign currency now, while it is only needed in a future period. One may opt to sell available foreign exchange now with a right to buy the foreign exchange back in a future period. The advantage is that one gets local currency that is available until the moment a payment is due.

    A currency swap involves a situation where the rights and benefits of a loan expressed in foreign currency are exchanged against a foreign party that desires to have local currency. This allows every party to raise money in its local currency and having the benefit to use foreign exchange. I raise Euros on my local market; an American raises dollars on his local markets. We then swap and I get dollars and the American gets Euros. I will pays the dollar interest and I will pay the dollar reimbursement. The American will pay the Euro interest and he will pay the Euro reimbursement.

    An interest swap involves swapping interest payment. Assume I pay a variable interest where I would like pay a fixed interest. If I meet someone who pays fixed interest whereas he prefers to pay a variable interest rate, we may decide to swap the obligations.

  • the Zachman framework

    The Zachman framework is a nice example of so-called “IT Entreprise Architecture”. Such approach is directed at a comprehensive approach to the design, implementation and execution of IT strategy within an enterprise.
    The Zachman framework has two dimensions.
    The first dimension is the dimension of a party. Going from top to bottom,

    • we show the enterprise from an executive point of view, that sets the scope,
    • an owner view, that steers the daily business within the scope provided
    • an architectural view that provides a logical overview of the daily processes as defined above
    • the engineering view that translates a logical overview into something that can be built
    • the technical view that actually implements the strategy
    • the user perspective that uses above components

    Next to that, we have a second dimensions that describes what items must be modelled.

    We have:

    • “what”: identification of items
    • “how”: identification of processes
    • “where”: the geographical component
    • “who”: the division into roles and responsibilities
    • “when”: the division over time
    • “why”: the motivation why everything above is undertaken.

    A nice overview is given here: Zachman Framework 3.0

  • Using IDA

    IBM launched InfoSphere Data Architect (IDA). This is a data modelling tool that acts as a competitor with Erwin and PowerDesigner. I played a bit with this tool to see what the capabilities are and in which areas these products are different from Erwin and PowerDesigner. As a general remark, I must say that I like IDA. It works quite smoothly and i did not encounter any issues with the tools. I did not receive any unexpected error.
    It is good to know that if one starts with an existing project, one has to import the files. This can be done with (start from menu): file > import.

     

     

    The files must be stored in a project directory. One must achieve a situation where all files are stored in a project directory. Once the files are stored in such project directory, one may start using them.

     

     
    The concept on how to create your data model is similar to Erwin and Powerdesigner. It is important to create a logical data model first and to generate a physical model after that. The philosophy is roughly similar.
    If one starts with a new modelling exercise, one has several options.
    The first option is to start a new logical model.
    The second option is to import an existing project and continue from there.
    The third option is to reverse engineer an existing database.
    All options are supported by IDA. I worked with these options and I could start a project without any problems being encountered.
     
    I noticed one difference with Erwin/ Powerdesigner. It is possible to create two files that allow to set up a centralized set of domains and abbreviations that allow a physical data model that is aligned over different modelers.

    The common set of abbreviations is maintained in a ndm file. An example is provided below. The advantage of having such a list of abbreviations is that one may share such list over different modelers. One may then enforce a common nomenclature over different people.

     

     
    More or less the same reasoning holds for a list of domains. The domains are stored in a ddm file. An example is provided below. If shows how different domains can be added, updated or deleted. Also here, one may exchange this file over different data modellers. That allows to enforce a common set of domains.
     

     
    To enforce the usage of such files, one must indicate the usage in the advanced properties of the project. There are two tabs to store the location of such files. One for the naming alignment and one for the domains.
     

  • Create a description of a system

    From time to time, I must provide a scheme on how a system works. It is not really to find a technique in which all details can be shown. I was to make a differentiation between processes, like sending mail, databases and applications. I also want to indicate what techniques are used. Moreover, I would like to indicate which elements belong to each other. I then misuse the SDL stencil in Visio. This allows to make such distinction. See the figure below:
    . There within the arrows, the techniques can be shown. I also use the separated processes to indicate which applications are used with the platform on which they run. Finally this stencil has a diagramme for databases which is most convenient. Another example can be found here

  • Network reaction from Python

    I have a php script that runs as cgi on a webserver. The programme is quite simple. First is asks for a userid and password. The userid and password are sent as a parameter. If these value coincide with expected value, the system returns a page where the user may click on a hyperlink to continue his journey.
    We thus have a stream with two parameters that is sent from the user browser to the webserver, upon which the system may react.

    It is possible to mimick this with a python programme that sends the same stream to the webserver. This programme looks like:

    from urllib import request, parse
    url='http://62.131.51.129/load_pr/password.php'
    parms = {
        'txtUsername' : 'tom',
        'txtPassword' : 'binvegni'
            }
    querystring = parse.urlencode(parms)
    u = request.urlopen(url, querystring.encode('ascii'))
    resp = u.read()
    print (resp)
    

    This stream is sent to the webserver that runs on http://62.131.51.129. It sends the same stream of bytes as requested from script http://62.131.51.129/load_pr/password.php as it contains two parameter values (‘txtUsername’, ‘txtPassword’).
    We call this Python programme with “D:\Users\tmaanen\Documents>python sendPost.py”. The answer received is:


    This matches the stream as sent by the webserver as from the php script.

    Finally, in case of get instead of post, the programme is slightly different:

    from urllib import request, parse
    url='http://62.131.51.129/load_pr/password.php'
    parms = {
        'txtUsername' : 'tom',
        'txtPassword' : 'bunvegni'
            }
    querystring = parse.urlencode(parms)
    u = request.urlopen(url+'?'+querystring)
    resp = u.read()
    print (resp)
    
  • With Python in Hive

    In this small note, it is described how an HDFS file can be stored in a Hive context. In it stored in a Hive context, it can be accessed from outside via ODBC. It is also possible to access the data as a SQL compliant database. The idea is that an abstraction is created on top of the HDFS datasets. One may then access the HDFS datasets, much like an ordinary database.
    We will use the python language via spark. This avoids the bottleneck that MapReduce has created.
    One starts python via spark with the command “pyspark”. If everything goes correct, we see:
    untitled
    Two variables are important: sc that is an anchor point for methods that can be used within Spark and HiveContext that be used as a starting point for Hive methods.

    We first import the relevant libraries and create the context:

    from pyspark.sql import HiveContext
    sqlContext = HiveContext(sc)
    

    Then the table is defined:

    sqlContext.sql("CREATE TABLE IF NOT EXISTS HiveTom (key STRING, value STRING) ROW FORMAT DELIMITED FIELDS TERMINATED BY ';'")
    

    In the last step, an existing HDFS file is connected to that table definition:

    sqlContext.sql("LOAD DATA INPATH 'hdfs:/Chapter5/uit2' INTO TABLE HiveTom")
    

    We may now approach this dataset as a table. The tablename is HiveTom. A possibility is to access the table via ODBC. We can download an ODBC connector. Each distribution (Cloudera, MapR, Hortonworks) has a ODBC connector. Once installed, we may retrieve the data in a ODBC compliant tool. As example, we may undertake this in Ecel:
    untitled

  • Connect from 32 bit environment to 64 Oracle instance

    One may retrieve the version of Oracle with a simple command: “select * from v$version;”. One may then see that the Oracle instance is a 64 bit version. In my case, the full version name is “Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 – 64bit Production”. Once this is known, one may ask whether it is possible to access this database from a 32 bit environment. Accessing an Oracle instance from a 32 bit environment is the subject of this small note.
    We have multiple ways to access an Oracle instance.
    The first method to access an Oracle instance is via SQL Developer. This works straightforward. Once installed, one may access from a 32 bit SQL Developer the 64 bit Oracle instance. No strings attached.
    I then created a line in the tnsnames.ora. The entry is labeled as ORCL. I checked whether this worked with “tnsping ORCL”. This also worked without any issues. I then connected to the database with sqlplus. That also worked fine. I used a 11gR2 client. No issues were found to connect this to the Oracle version 12.

    So the standard tools worked fine. They were all 32 bits whereas the Oracle instance was 64 bits.

    Then I created a report. This can be done from the OBIEE environment. One connects to BI Publisher on an OBIEE server (something like http://van-maenen.com:7780/xmlpserver). One may then create a report. Let us assume that the report is stored as Tom\JaarAantal. The question is whether it is possible to access the report from a 32 bit tool. To this end, we start a 32 bit Word application that has a BI publisher add-in. It was straightforward to access the report. It was also possible to create a report from Word. See below the result from a 32 bit Word application using data from a 64 bit OBIEE server.
    Naamloos

    Then I tried to create a 32 bits ODBC connection to the 64 bits Oracle instance. I could directly use the Oracle client ODBC facilities to set up an ODBC connection. I could also use this ODBC connection to retrieve data into a 32 bits Excel sheet. I also used this 32 bit ODBC connection to connect from Qlikview to the 64 bit Oracle instance. No issue found there:
    Untitled

    Subsequently, I tried to access the 64 bits Oracle database with a 32 bit OLE DB connection. I used the connectstring; “Provider=OraOLEDB.Oracle.1;Password=bonvegni;Persist Security Info=True;User ID=hr;Data Source=ORCL;”. This worked nicely. I checked the OLE DB connection from Excel. This allows a very intuitive interface to connect to a database (such as Oracle). One may choose how to connect, be it ODBC or OLE DB.

    I also tried to access the Oracle database from the squirrel client. This is a java client that uses java jar files to connect to an Oracle instance. Also there, no issue found when connecting to the Oracle database.
    Untitled

    It is also possible to connect from Perl on the 32 bit environment to the Oracle 64 bit environment. I used:

    #!/usr/bin/perl 
    use DBI;
    use DBD::Oracle; 
    print "Hello World.\n"; 
    print $DBI::VERSION,"\n";
    print $DBD::Oracle::VERSION,"\n";
    
    my $db=DBI->connect("dbi:Oracle:orcl", "scott", "bunvegni");
    my $SEL = "select * from scott.employees";
    my $sth = $db->prepare($SEL);
    $sth->execute();
    while ( my @row = $sth->fetchrow_array() ) {
        foreach (@row) {
            $_ = "\t" if !defined($_);
            print "$_\t";
        }
        print "\n";
    }END {
        $db->disconnect if defined($db);
        }
    

    This also worked nicely.

    All in all, I had absolutely no issue connecting from a 11G 32 bit client to the Oracle 12 64 server instance.

  • Create a report with BI Publisher

    One could create reports within the OBIEE sphere with the analytics. Another possibility is to use the BI Publisher. This option has several advantages. One advantage is that one choose between a direct query on the database or use the route via the creating of a subject area.
    I can see advantages using a direct query on the database.
    Let us take a table that may be used as a source for a report. The take looks like:
    Untitled
    We want to create a report where name is shown along with the sum of Aantal. So, we expect something like pipo having 4 and jan having 6.

    The first step is to invoke the BI Publisher with something like https://archief.van-maanen.com/xmlpserver, where archief.van-maanen.com/ is the server, 7780 the port and xmlpserver the application.
    One must check whether a datasource is available to the database where the table is stored. This can be done with Administration>JDBC where the datastores are listed.
    Such a datasource is not limited to Oracle databases. It is possible to use other databases as well. From OBIEE interface, I got the impression that SQL Server and NCR was well supported. However, I could create a link to a MySQL database quite easily. I assume that all databases that have a JDBC connection can be reached. This would imply that Postgress etc can be used as a source as well.
    Once that is fixed, one must create a so-called data model. The data model can be created from the homepage. There the possibility is to select under Create, the data model option.
    Untitled
    There one comes into a menu where one might opt to use a query builder to create a structure that contains the necessary data:
    Untitled
    This can then be saved to have a data model. Roughly stated, a data model is a dataset that one may capture in a report.
    The report can subsequently be created from this environment.
    See:
    Untitled
    This allows to create a report. Do not forget to save the report.
    A nice twist is that one may create the final version of the report with Word. When the proper BI Publisher version is installed (in my case BIPublisherDesktop32), one could use Word as a means to modify the report. If properly installed, one has a Bi Publisher tab in Word. This allows to include fields from the report in a word document. One must log in to to the weblogic server (where the report is stored), select the report and one may then enter fields from that report in a word document. See:

    Untitled.
    The actual content can be shown if the preview is selected from the menu. This then finally renders the report that we expected to see:
    Untitled

  • Reading XML in Oracle -2

    Loading XML into Oracle might require some SQLLDR code. Of course, the standard insert is a possibility, but this might be slow if many XML files are to be loaded. From publications, I got the idea that the SQLLDR is the most recommended tool to do it. It does require some time and tuning but once, the script is ready, it might be re-used and it saves quite some time.
    Using this SQLLDR vehicle, one might load a series of XML files into an Oracle table.
    The code to do so is not really trivial. I used this table:

    CREATE TABLE "XML_TAB" 
        (filename char(60),
       	"XML_DATA" "XMLTYPE", 
    	"ID" NUMBER(*,0)
       );
    

    and the code to load XML files is as follows:

    load data
    infile *
    append
    into table XML_TAB
    fields terminated by ';' 
    (
     "FILENAME" CHAR (60),
     XML_DATA  lobfile(filename) terminated by eof,
     id  
    )
    begindata
    C:\app\tmaanen\product\12.1.0\dbhome_1\BIN\weg.xml;14
    C:\app\tmaanen\product\12.1.0\dbhome_1\BIN\weg1.xml;15
    C:\app\tmaanen\product\12.1.0\dbhome_1\BIN\weg2.xml;16
    
    This file can be loaded by a SQLLDR command that may be something like:
    SQLLDR CONTROL=C:\Users\Tom\Dropbox\Uitwisseling\xml.ctl LOG=sample.log, BAD=baz.bad, USERID=scott/binvegni, ERRORS=999, LOAD=500000, DISCARD=toss.dsc, DISCARDMAX=5