2013-01-06

SQL foreign key access and tree structures

Relation  in relational database theory means table  and nothing else, table with rows, columns and cells. Relational databases are tables, SQL is the programing language for manipulating and accessing those tables. The relational database is based on the theory of sets, this is a mixed blessing. On the positive side the theory of sets is mathematically proven and that is a good thing in itself at least it says the foundation is sound. But databases in applications are more than sets, a database is a model of the real world the application is supposed to support. E.g. sets do not have structure or order, the real world has. The structure the relational database have is the table structure and simple ‘relational links’ between tables, that can be used to restrict creation or deletion of rows in linked tables. Unfortunately SQL do not understand these links well, you cannot implicitly access linked data or show hierarchies.

Access via foreign keys.

Something I miss in SQL is the ability to walk through children and infer through parents via foreign key links. (You can to a certain extent compensate for these shortages with database views and virtual columns.)

For this database I would like to be able to say:

  1. select sono, customername , quantity sum-throu  SOlines as qty for SalesOrder;
  1. customername is the customername of the SalesOrder infer through the customerid foreign key link and in case of ambiguity can be qualified as SalesOrder.customername . Customer is a ‘link owner’ of SalesOrder.
  2. sum-throu is an infix function that sums the quantity of the SOlines children of the SalesOrder through sono foreign key link. Some other throu functions are max, min & mean. SalesOrder is a ‘link owner’ of the SOlines.

Compare this with the more correct SQL:

  1. select sono,customername, sum(quantity) as qty for SalesOrder left join Customer on customerid, left join SOlines on sono group by sono, customername;

I do not like specifying things the computer should be able to figure out. Getting rid of explicit joins is an advantage, even trivial joins are complex for most people. Ever since the introduction of foreign key links in DB2 I wondered when SQL should include access via foreign key links. I have thought of creating a preprocessor in MySQL proxy, but we still use MyISAM storage engine which do not support foreign keys. MyISAM is very convenient for BI system, and historically it has been the fastest storage engine, with the latest MySQL versions this may not be true anymore, I will  have a look at InnoDB when MySQL 5.6 is released.

(Foreign keys are the SQL feature I miss the most in MyISAM. Other features I miss in MySQL are computed/virtual columns and materialized views.)  

Tree structures.

The support for tree structures in SQL is at the best crappy.Good tree structure support includes:

  1.  Ability to go up and down the tree, starting from the top or the bottom.
  2. Stop traverse the tree at certain nodes or exclude nodes from the result tree.
  3. Tree level indicator so you know where in the tree you are.
  4. Ability to intercept updating if loops are found in the tree structure

Tree structures are very useful but unfortunately also very complex, so they are ‘under-utilized’. Simple and powerful support for tree structures including the bullets above would take SQL to a new level. Tree structures are a big topic that deserves a post of its own. I end this post with a link to a post  describing a tree structure we use.

 

 

2012-12-21

Planning the next IT year.

When I started my present employment (year 2000) I promised myself never again take on operational responsibility. Well, I kept my promise a week or two then I sat there again burning the midnight lamp fixing a corrupt database in an MRP system I had created 1980, that system is now scrapped, but now I’m  heavily involved in the operations of our BI system the Data Warehouse. I’m also involved in some other systems that needs some instant tinkering from time to time. Operations is the most important factor when I set up my calendar. Meetings is the second most important factor. To me it seems meeting is getting more and more important or frequent. I do not know if this is just a fact of my professional role is changing or if this is a more general trend.

The third most important factor for my calendar is projects. This is definitely a trend, more and more work are done as projects. When I started to work with IT most work was assigned to  individuals, only big ‘projects’ were actually organized in projects. Today no task is too small for a project organisation.

Vacations is something you have to take into consideration when planning the year. In western europe most of us take a month off in the summer. (In Sweden five weeks vacation is the minimum, I think I have six weeks. I remember when I was employed in the US I was given three weeks vacation since ‘you are from Europe, but please do not tell anyone’.)

Basically I use three cycles when I plan my next years calendar. First we have the year itself, then the month and last the week.

Week cycle.

Monday mornings is reserved to operations if anything gone wrong during the weekend. Monday afternoon project meetings, so project members can plan their week, the earlier in the week the better. Do operational changes on Mondays, so you can fix the problems on Tuesday. Wednesday is ‘meeting day’ experience have taught me operations problems are least likely to occur on Wednesday, so plan for important repeating meetings on Wednesday. Thursday small operational changes and ‘unplanned’ meetings, seminars etc.. Never change operations on Fridays, (not even a simple program bug fix if it can be postponed to next week) unless you want to work during the weekends. Fridays are for those boring sometimes unnecessary meetings you cannot avoid. Note the later a Friday meeting is held the shorter it will be. At 16.00 even a hopeless filibuster often keep quiet. Weekends lastly are for big operational tasks.

Month cycle.

First day of month is Business Intelligence day. The BI system must be up and cope with peak load. If the system is of any magnitude and have active users there are new/changed reports, it’s very likely there are problems to deal with. Do not plan for anything the first no matter what weekday it is, your BI system may need you. The second and third week in the month are the quiet weeks plan for repeating events and important meeting. Last we have month period closing that starts four days before month end and lasts to the third day of the next month. During this time the financial guys become hysterical if they do not get all attention from you (and everyone else for that matter).

Year cycle.

The year starts with what I call the ‘Iron day’, in my younger days I took a taxi from the new year party directly to the office and after a barrel of coffee I dealt with the year end’s problems. Nowadays I try to sleep a few hours before I log in from home and deal with year end’s problems. The ‘Iron day’ is the single most important IT operational day and it is an effort of will. Be prepared for anything. (Three years ago our VPN-system broke down so I could not log in at 06.00. I had to take a taxi to the office as in the old days. A software license had expired).

Be cautious with planning to much in the beginning of January, there might be difficult year end’s problems to deal with.  

February is software license renewal month. (Never ever have software licences expire in December, January or during the vacation period.)

For us the summer vacation period is July and August (in Sweden it is July and in Belgium it is August). Avoid plan anything during the vacation period. You should not start up anything new two weeks before the vacation period, and one week after the vacation period.

The most IT-critical period of the year is the year end. Do not start up any major IT-finance projects from mid november until mid January, the finance guys will be absorbed by year end. Declare ‘production freeze’ from second week in December to second week in January, only allow necessary maintenance in the IT landscape and infrastructure.

When these three cycles are firmly booked in the calendar you only have to mark up holidays like Xmas and easter and bank holidays and your calendar is ready for use and you are prepared for planning the next year.

2012-12-16

Office activity peaks and Business Intelligence users

Every Database Administrator knows there are work related activity peaks during the day in the office. You have a long peak of activity shortly after most workers arrive in the morning and another shorter one before lunch. After lunch there is an hour of intense activity and a short burst of activity at the end of the day. In between those two peaks not much is happening. How do I measure? In the ERP systems of course, when we work we tend to use the ERP systems, so to measure the work activity rate just calculate the ERP transaction rate. As you may have noticed I’m vague in timings of the peaks. If you have observed activity peaks in different countries you know activity  differs between countries.  I will not mention more about that other than Swedes tend to come in early in the morning, I myself is a bit extreme I often start between 05.30 and 06.00.
A good friend of mine and ex-colleague Ulf Davidsson co-creator of the Data Warehouse used the Business Intelligence system activity to categorise BI-workers into ‘ doers ’ and ‘thinkers ’. The doers start early in the morning and pick up the reports they need for their day tasks. The thinkers tend to come in later their activity peak coinciding with the after lunch peak. The classification into doers and thinkers are quite useful. Doers need precise detailed but rather limited amounts of information in Excel format, while the thinkers are more for quantity ‘give me all, I want all goods movements in all factories since the days of Eden’ and they prefer olap  presentation of the information, today we use Qlikview  for olap visualization. The doers request 100% quality of data, while thinkers demands performance. (The first thinker using the Data Warehouse Styrbjörn Horn  forced me to upgrade the hardware, at the time we were operating on scrapped laptops, ‘I go bonkers while waiting for my reports’. Styrbjörn later founded his own company Navetti .)
A common mistake creating BI is to create the BI for thinkers, since they seldom have detailed knowledge of data, they assume it is correct and when they finally find bad data quality they can be nasty to deal with. When you create a BI application you should find the doers that benefit from the system and start by create reports for them, if they find the reports useful they will help you iron out quality issues. (You should base your BI on solving problems rather than visions and grand ideas.) When the application is stable with correct data it is time to invite the thinkers, if they find your application useful they will help you with the performance issues. Thinkers often have a budget and they can be surprisingly generous if they like your BI system.
This post is based on generalized observations, there are swedish nighthawks and early birds from other countries. We do not only work in ERP and BI systems. BI doers can also be thinkers and vice versa.
I have no connections to those behind the olap video link, I stumbled across it and I like it, especially the brick wall, to create successful BI you must be in the business.
My only connections to Navetti are professional, we use their software and ‘my’ systems feed their software with information.
 
     

2012-11-11

Time flies

Not long ago I was just a kid and now I'm a member of the gold-club. It's nice to have the golden needle and the gold watch. And the Gold Club parties in the mirror hall of Grand Hotel are cool! History has been written here, the first Nobel Prize award ceremonies were held in the hall, the very same hall I got my gold club insignia, it's surreal. But it's also saddening,where have all these years gone?

2012-11-08

The € operator - supporting the Euro and SAP RFC_READ_TABLE

Recently we have started to use a new technique for extracting data from SAP. We dynamically create predicates for RFC_READ_TABLE . This technique has been very successful and we use it more and more. But there are some problems with our technique and RFC_READ_TABLE. We have to specify the entire predicate in one statement for each search. An example show you what I mean. We like to  find to parts A and B in factory 1100.
A natural predicate for this is:
 “PLANT EQ ’1100’ and (MATNR EQ ‘A’ or MATNR EQ ‘B’)”.
But this is not possible with the current technique, to build the predicate we have to write something like:
“(PLANT EQ ’1100’ and MATNR EQ ‘A’) or (PLANT EQ ’1100’ and MATNR EQ ‘B’)”.
This is not only unnecessary cumbersome, you want to be as precise and succinct as possible since it gives the DB-optimizer a better chance to efficiently walk through the database, and also the buffer in SAP for the predicate is limited, to make this even worse the row length for predicates in RFC_READ_TABLE is limited to 72 chars. Why?? Well its the amount of information a good ol’ punch card can carry.
Clearly the functionality described in the link above needed some enhancement, better support for creating dynamic predicates for RFC_READ_TABLE. And that’s where the € operator  comes in. The euro currency can do with some help, and I do what I can by introducing the € operator to popularize the euro. I think I’m first to introduce the € sign in a programming language, (the Integration Tag Language). The € operator syntax:
$ok = €()filename
It is a bit hard to explain the inner workings of the € operator, but some examples will hopefully show how it works. Example:

<sap>
    <rfc>
        <name>Z_LJ_READ_TABLE256</name>                
        <import>
            ('QUERY_TABLE','@TABLE2')
            ,('DELIMITER','')
            ,('NO_DATA',' ')
            ,('ROWSKIPS',0)
            ,('ROWCOUNT',0)
            ,('OPTIONS', € (MANDT EQ '300' and KAPPL EQ 'M' AND WERKS EQ '1100')/path/file)
        </import>
    </rfc>
<sap>
Take a look at the OPTIONS row in the example above, here we see the € operator in action. The expression between the parentheses  is the ‘constant’ part of the predicate  and connected to the expressions in the file with an AND like:
MANDT EQ '300' and KAPPL EQ 'M' AND WERKS EQ '1100'” AND ( filerow1 OR filerow2 OR … last_filerow)
A ‘real’ example:
In this example I extract rows from SAP table A17 for predicates (materials) generated in the first job genArray1 .  When running this example schedule the € operator  expands the OPTIONS expression into  this PHP array:
At last; the € operator conveniently chops the array elements into 72 char strings so RFC_READ_TABLE gets the input in punch card format :)

2012-10-21

Automatic replication of MySQL databases with Rsync

In some posts   I have written about replicating Business Intelligence information to Local Area Network satellites.
Instead of using normal database backup procedures that guarantees the integrity of the database I use rsync and file copy the database from the source database server over to the target database server. I can do this since I know no updates are done to the database while replicating and I use MySQL MyISAM storage engine. My rsync procedure is very simple, fast and self-healing, but
Do not try this at home
The real reason why I replicate this way is - I like to experiment and try new things and I have not seen anyone replicate databases like this before.  

The Setup

This is how I have set it up. From the controlling ETL server I issue commands via ssh  to the source and target systems:
           Source system           Target system
1        Flush tables
2                                                 Stop MySQL
3        Run Rsync_repl.sh
4                                                Start MySQL.
I use ssh from the ETL server (where my Job scheduler runs) and issue the commands from a job.
First I need to set up SHH (control server):
ssh-keygen
ssh-copy-id -i ~/.ssh/id_rsa.pub userid@targetDBserver
and then sudo (Target server/BI Satelite):
visudo  (add)
MYSQLADM ALL = NOPASSWD: /usr/sbin/service
and then test it:
ssh -t userid@targetDBserver sudo service mysql status
from the control server. You should receive mysql status from the target database server with any prompts for password.
In the source database server I did almost the same thing. First SHH (control server):
ssh-copy-id -i ~/.ssh/id_rsa.pub userid@sourceDBserver
and then sudo (Source server/BI Master):
User_Alias MYSQL_REPL = userid
MYSQL_REPL ALL=(ALL) NOPASSWD:/path2/rsync_repl.sh *
replicate.sh * is a bash script (appended below) that rsync Mysql databases to the target database server. Now I have all things in place and I can system test from my control server
ssh -t userid@targetDBserver sudo service mysql stop
ssh -t userid@sourceDBserver sudo rsync_repl.sh
ssh -t userid@targetDBserver sudo service mysql start

The automation.

With everything in place and tested, I only have to create a job and schedule it.

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<job name='replicateDB' type='sql'>
<!-- This job replicate databases from Source Host to Target Host -->
<!-- Note of Warning! This is not according to any safe procedure. Do not try this at home! -->
 
<tag><name>TargetHost</name><value>TIPaddr</value></tag>
  <tag><name>TargetUser</name><value>Tuserid</value></tag>
  <tag><name>SourceHost</name><value>SIPaddr</value></tag>
  <tag><name>SourceUser</name><value>Suserid</value></tag>
 
  <sql>FLUSH TABLES</sql>
  <exit>
    <!--Action 1:  stop mysql in target server -->
    <!--Action 2:  replicate from Source to Target -->
    <!--Action 3:  start mysql in target server -->
    <action wait='yes' cmd='ssh' parm='-t @TargetUser@@TargetHost sudo service mysql stop'/>
    <action wait='yes' cmd='ssh' parm='-t @SourceUser@@SourceHost sudo /path2/rsync_repl.sh'/>
    <action wait='yes' cmd='ssh' parm='-t @TargetUser@@TargetHost sudo service mysql start'/>
  </exit>
</job>
As a safety measure this job first flush MySQL tables to disk and then runs the exit actions. And that’s it.
If which God forbid the replicated database is trashed, I just have to run the job again. You can guarantee the integrity of the database by running the job repeatedly until no data is replicated, basically if this replication is faster than the ‘update rate’ your database will be fine.  
 I conclude this series of posts  with the rsync_repl.sh script. The comments say it all ‘hopefully the replicated database is OK’ no guarantees!
p.s.
You can make this procedure secure by take a table lock before the second replicate, but in my case it is not necessary.
 

2012-10-12

Having PHP FUN(ctions) with SAP shop calendar

The other day I needed to calculate number of workdays in a 60 days period for our Tierp Factory .
Since I had to do this in our BI system I needed the shop calendar for Tierp from SAP. I started to look around for some procedure to extract the shop/factory calendar from SAP. To my surprise I didn’t find anything. The closest I found was  the bapi  DATE_CONVERT_TO_FACTORYDATE. This piece of code takes a date and gives the shop calendar equivalent, i.e. it tells you if the date is a work day or not and the closest  work day if it is a holiday. By exposing a range of dates to date_convert_to_factorydate you can create a shop calendar. I also found some interesting tables in SAP where I could extract the information I needed, but I decided to have some fun with my PHP job scheduler and call  date_convert_to_factorydate repeatedly for a long date span, and assemble the shop calendar with the result. I needed to feed the date_convert_to_factorydate with the id  of the Tierp factory calendar, a range of dates , and a flag  telling date_convert_to_factorydate to look forward or backward for closest work day.
The id is stored in SAP TFACD  table, the date span could easily be created by a function and I wanted a backward search. Then I just had to call SAP once  for each date in the span, for this I could use a job iterator, which would do the job, but with a nasty side effect, since the job calling SAP would repeat itself it would log on and log off from SAP once for each date. Instead I pushed down the iterator to the SAP communicator sap2.php, which logs on once and then iterates through  the dates and appends the results. After this its just a simple matter of loading the result into our BI systems mySQL database. OK here we go:
For you who have followed my posts about my PHP job scheduler  and the SAP communications examples . The interesting pieces here are the PHP functions to generate the start of the calendar in <tag name=’CALSTART’...>  and the use of the iterator <mydriver>  which creates a date span, which the script sap2.php will iterate through and call date_convert_to_factorydate once for each date. The second job in this schedule createCalendar just loads the result into MySQL.
Here you see part of the created shop calendar:
Example - The date 2012-07-08 is a holiday and the closest work day is 2012-07-06.  
If you take the time to study the first job getCalendar you will notice there is actually quite a lot FUNctionality packed in there.
My first use of this shop calendar is an advanced formatted Excel sheet, which I will create and email in subsequent jobs. That will be fun too.