Friday, June 22, 2012

Example: Strip Trailing Zeros After Decimal Point

Question: How do I strip trailing zeros after the decimal point from a string containing a number?

Mind-Boggling Answer: This C# solution got 24 up-votes on StackOverflow, and the author has almost half-a-million reputation points for his 21,000 answers, so it must be right!

using System;
using System.Numerics;

public static class DecimalExtensions
{
    // Avoiding implicit conversions just for clarity
    private static readonly BigInteger Ten = new BigInteger(10);
    private static readonly BigInteger UInt32Mask = new BigInteger(0xffffffffU);

    public static decimal Normalize(this decimal input)
    {
        unchecked
        {
            int[] bits = decimal.GetBits(input);
            BigInteger mantissa = 
                new BigInteger((uint) bits[0]) +
                (new BigInteger((uint) bits[1]) << 32) +
                (new BigInteger((uint) bits[2]) << 64);

            int sign = bits[3] & int.MinValue;            
            int exponent = (bits[3] & 0xff0000) >> 16;

            // The loop condition here is ugly, because we want
            // to do both the DivRem part and the exponent check :(
            while (exponent > 0)
            {
                BigInteger remainder;
                BigInteger divided = BigInteger.DivRem(mantissa, Ten, out remainder);
                if (remainder != BigInteger.Zero)
                {
                    break;
                }
                exponent--;
                mantissa = divided;
            }
            // Okay, now put it all back together again...
            bits[3] = (exponent << 16) | sign;
            // For each 32 bits, convert the bottom 32 bits into a uint (which won't
            // overflow) and then cast to int (which will respect the bits, which
            // is what we want)
            bits[0] = (int) (uint) (mantissa & UInt32Mask);
            mantissa >>= 32;
            bits[1] = (int) (uint) (mantissa & UInt32Mask);
            mantissa >>= 32;
            bits[2] = (int) (uint) (mantissa & UInt32Mask);

            return new decimal(bits);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Check(6.000m);
            Check(6000m);
            Check(6m);
            Check(60.00m);
            Check(12345.00100m);
            Check(-100.00m);
        }

        static void Check(decimal d)
        {
            Console.WriteLine("Before: {0}  -  after: {1}", d, d.Normalize());
        }
    }
}

Gasp! [shudder]

...words cannot express the horror.

How about this instead?

Just... write some code to look for trailing zeros after the decimal point and remove them from the string.

Sound familiar? It's the original Question almost word for word.
CREATE FUNCTION strip_trailing_zeros_after_decimal_point (
   IN @input_number VARCHAR ( 100 ) )
   RETURNS VARCHAR ( 100 ) 
BEGIN
   DECLARE @output_number VARCHAR ( 100 );

   SET @output_number = TRIM ( COALESCE ( @input_number, '' ) );

   IF LOCATE ( @output_number, '.' ) > 0 THEN

      WHILE RIGHT ( @output_number, 1 ) = '0' LOOP
         SET @output_number = LEFT ( @output_number, LENGTH ( @output_number ) - 1 );
      END LOOP;

      IF RIGHT ( @output_number, 1 ) = '.' THEN
         SET @output_number = LEFT ( @output_number, LENGTH ( @output_number ) - 1 );
      END IF;

   END IF;
      
   RETURN @output_number;

END;
  • The SET on line 7 does a bit of input editing: it turns NULL into '' and gets rid of leading and trailing spaces.

  • The IF LOCATE on line 9 makes sure the function doesn't do anything more if there's no decimal point at all.

  • The WHILE loop on lines 11 to 13 zaps each trailing zero, one at a time, from the RIGHT end of the string.

  • The IF RIGHT ... SET on lines 15 to 17 gets rid of the decimal point if it ends up being the last thing on the line.
Not as sexy as "(int) (uint) (mantissa & UInt32Mask)", but it's readable and it does seem to work...
SELECT '000' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.0' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.00' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.01' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.10' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.010' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.456' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.4560' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123.45600' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
UNION
SELECT '123000' AS x, strip_trailing_zeros_after_decimal_point ( x ) AS y
ORDER BY 1;

x         y
000       000
123       123
123.      123
123.0     123
123.00    123
123.01    123.01
123.010   123.01
123.10    123.1
123.456   123.456
123.4560  123.456
123.45600 123.456
123000    123000
...well, it works for trailing zeros, the "000" is a formatting question for another day.

And I'll bet you could do better! (even simpler, even more straightforward)

Dilbert.com




Wednesday, June 20, 2012

Botox for the Blog

Some items have been removed from this blog...

  • The big "Foxhound 1.2" ad is gone, but it something will be back when Version 2 ships.

  • The Search gadgets have been moved to the much-better Advanced Search page, joining others on the "links line" at the top of this page.

  • The Quantcast ego badge is gone... no, it had NOTHING to do with the fact traffic dropped in April :)

  • The blog lists have been [ahem] trimmed somewhat...
    WHEN active again THEN they will return;

In other news...

Work proceeds on the SQL Anywhere Technical Documents page on this blog:
  • Techwave 2004 presentations have been added... only Techwave 2003 remains, and their whereabouts are known.

  • A calculated "row number" column has been added to show that the list is now up to 499 articles with actual links.

  • Google seems to be indexing new entries as fast as they are added, so the Search gadget is quite effective.
The priority list looks like this:
  • keep up with new articles,

  • add the Techwave 2003 presentations,

  • fill in the Authors column, working from the top down (backwards in time), and

  • add entries from various blogs, again working backwards in time, starting with Chris Kleisath, Eric Farrar, Glenn Paulley, Jason Hinsperger and Tom Slee ...and ...and ...?


It's all in a database (of course!) so reports can be run...

Who's the Iron Man of Techwave?

WITH count_by_author AS
        ( SELECT COUNT(*) AS article_count,
                 article.authors AS "Iron Men"
            FROM article
           WHERE article.title LIKE 'Techwave %'
             AND article.authors <> '-'
           GROUP BY article.authors ),
     count_by_iron_men AS
       ( SELECT MAX ( count_by_author.article_count ) AS article_count
           FROM count_by_author )
SELECT count_by_author.*
  FROM count_by_author 
          INNER JOIN count_by_iron_men
                  ON count_by_iron_men.article_count = count_by_author.article_count
 ORDER BY count_by_author."Iron Men";

article_count  Iron Men
10             David Fishburn
10             Reg Domaratzki

Answer: Reg Domaratzki!

Sure, David Fishburn is currently tied with Reg for the most Techwave presentations in the list, but... David didn't play through the pain like Reg did!




Monday, June 18, 2012

Latest SQL Anywhere EBFs: 12.0.1 for (almost) everyone, plus direct links!

The three asterisks "***" show what's new since the previous list.

  • Only EBFs for the latest fully-supported versions of SQL Anywhere are shown here: 11.0.1 and 12.0.1.

  • Note: Just because an older version or different platform isn't "fully supported" any more doesn't mean you can't download files (or ask questions, or get help), it just means there won't be any more new EBFs released. For a complete list of everything available for download see Downloads - EBFs / Maintenance.

Current builds for the active platforms...

HP-UX Itanium     12.0.1.3740 EBF ***   15 Jun 2012 ***  <<-- Look! Direct Links!
                  11.0.1.2753 EBF       13 Feb 2012

IBM AIX           12.0.1.3740 EBF ***   15 Jun 2012 ***  <<-- Thank you, Jeff Albion!
                  11.0.1.2753 EBF       13 Feb 2012

Linux x86/x64     12.0.1.3740 EBF ***   15 Jun 2012 ***
                  11.0.1.2811 EBF       17 May 2012

Mac OS            12.0.1.3577 EBF       24 Feb 2012
                  11.0.1.2449 EBF       29 Jun 2010

Solaris SPARC     12.0.1.3740 EBF ***   15 Jun 2012 ***
                  11.0.1.2811 EBF       14 May 2012

Solaris x64       12.0.1.3740 EBF ***   15 Jun 2012 ***
                  11.0.1.2753 EBF       13 Feb 2012

Windows x86/x64   12.0.1.3742 EBF ***   15 Jun 2012 ***
                  11.0.1.2808 EBF       22 May 2012

To see other choices you'll have to start at the top, here, and 
work your way down... pack a lunch!
Dilbert.com




Friday, June 15, 2012

The fRiDaY File - Spam, Spam, Spam

OK, I admit it, Google's better than I am at detecting spam.

Here's some anecdotal evidence from the spam folder:


This is the perfect blog for anyone who wants to know about this topic. You know so much its almost hard to argue with you (not that I really would want...HaHa). You definitely put a new spin on a subject that’s been written about for years. Great stuff, just great!
...stroke, stroke, stroke that ego, stroke!

I came THIS CLOSE to marking it "Not spam"... then I noticed who it was from: Camera Cell Phone Reviews (don't worry, it's not a real link any more)

As much as I'd like to believe Camera Cell Phone Reviews is a heavy user of SQL Anywhere, the truth is...

Google's right, I'm wrong. It's spam.


And the best part? Spam filtering is built in, no effort, no unstable plugin, no false positives, and nothing escapes.

I'm sure there's a good reason to use Wordpress but I can't think of one :)

And now, for your amusement...


These spammers might not be as good at social engineering as Camera Cell Phone Reviews but they're pretty good, and some of them show real effort:

It's going to be finish of mine day, but before ending I am reading this wonderful piece of writing to improve my experience. My website: Recover deleted mail Outlook without exchange server

 
  Anonymous
I've been browsing online more than 4 hours today, yet I never found any interesting article like yours. It's pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the internet will be a lot more useful than ever before. my site > backup online sure

 
  Anonymous
I really love your blog.. Very nice colors & theme. Did you make this website yourself? Please reply back as I'm planning to create my own personal site and would like to find out where you got this from or exactly what the theme is called. Appreciate it! my website > Mosaics The Artists Taste

 
  Anonymous
I wish you continued success and a very nice page boyac? dekorasyon boya ustas?

 
  dekorasyon
Its highly informative. I would be visiting your blog hereafter regularly to gather valuable information. Chrome Stacks

 
  bala murugan
You know, most people write a report in Reporting Services to get anything worth it's salt you need to have some pretty advanced t-sql experience or have a good background in databases to be productive in SQL Reporting Services.

 
  SQL Reports
Nice Post about PowerBuilder Development . Thanks for sharing few of information .

 
  Nelson
Its really so nice post. thanks for sharing all about PowerBuilder

 
  Millan
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. Thank You PowerBuilder development company
  jackob

Dilbert.com


Back up, start over, find another way

Sometimes you can solve a problem by backing up, starting over and taking a fresh look at the requirements.

How far should you back up? At least to the point you starting having trouble.

Here's a case in point:

Question: How do I get this trigger to work? I get SQLCODE -267 COMMIT/ROLLBACK not allowed within atomic operation.

CREATE TRIGGER trigger_before_insert_t2
   BEFORE INSERT ON t2
   REFERENCING NEW AS new_t2
   FOR EACH ROW
   WHEN ( new_t2.type NOT IN ( SELECT type FROM t1 ) )
BEGIN

   ALTER TABLE t2 
      DROP CONSTRAINT t2_is_a_child_of_t1;

   ALTER TABLE t1  
      DROP CONSTRAINT check_that_t1_type_exists_in_t2;

   INSERT t1 VALUES ( new_t2.type );

   ALTER TABLE t2  
      ADD CONSTRAINT t2_is_a_child_of_t1 
      FOREIGN KEY ( type )  
      REFERENCES t1;

   ALTER TABLE t1  
      ADD CONSTRAINT check_that_t1_type_exists_in_t2 
      CHECK ( type IN ( SELECT type FROM t2 ) );

END;

INSERT t2 VALUES ( 1, 100 );

COMMIT/ROLLBACK not allowed within atomic operation
SQLCODE=-267, ODBC 3 State="42000"

First Wrong Answer...

ALTER TABLE implies COMMIT, so try wrapping the ALTER TABLE statements with EXECUTE IMMEDIATE statements.

EXECUTE IMMEDIATE is wonderful for solving "you can't do that here" problems, like coding a FORWARD TO statement inside a stored procedure.

Yabbut...

SQLCODE -267 is not just a syntax issue, it is a semantic one:
  • The "INSERT t2" statement is an atomic operation,
  • and therefore, since the INSERT fires the trigger,
  • the whole trigger execution is part of the same atomic operation,
  • and since EXECUTE IMMEDIATE doesn't move the ALTER TABLE statements outside the trigger execution, say, to another thread or connection,
  • the ALTER TABLE statements and their implied commits are still inside the trigger execution
  • and therefore the ALTER TABLE statements and their implied commits are still within the atomic operation
  • which is not allowed.

Second Wrong Answer...

ALTER TABLE implies COMMIT, so try moving the code to a CREATE EVENT.

CREATE EVENT is wonderful for solving problems involving commits, like implementing nested transactions. When you use TRIGGER EVENT to execute an event, and that event does a commit, it doesn't affect the caller's transaction (where "caller" is the code that issued the TRIGGER EVENT)... the reason is, TRIGGER EVENT starts a new connection to run the event, and a transaction (inserts, updates, ..., commit) run on that connection is separate from the transaction running on the caller's connection.

TRIGGER EVENT is like a whole new user, one who works out of sight, doesn't need a keyboard or a monitor, and never asks for a raise.

Yabbut...

Events run asynchronously,
  • which means TRIGGER EVENT is a "fire and forget" operation with no guaranteed starting time and no guaranteed end time,
  • and not only that, it never returns to the caller
  • so the caller can't tell when it's safe to proceed.
So what's the big deal? Here's the big deal: The CREATE TRIGGER was coded with the BEFORE clause to guarantee the inner "INSERT t1" runs before the outer "INSERT t2".

If the "INSERT t1" is moved into a CREATE EVENT, it might (and probably will) execute after the outer "INSERT t2".

Are you sure? Let's try it!

In the following, all the code from the CREATE TRIGGER has been moved into a CREATE EVENT, and
  • the trigger uses the TRIGGER EVENT statement on lines 34 and 35 start the event,
  • the funky argument list on line 35 is used to pass the new value of t2.type to the event
  • where the EVENT_PARAMETER logic on lines 9 and 10 converts the funky argument back into an integer.
The code on lines 12 to 19 isn't quite "all the code" from the trigger; these two ALTER statements have been left out altogether because the SET TEMPORARY OPTION WAIT_FOR_COMMIT statement on line 42 is a much easier, safer and more efficient way to temporarily turn off foreign-key-checking:
ALTER TABLE t2 
      DROP CONSTRAINT t2_is_a_child_of_t1;

   ALTER TABLE t2  
      ADD CONSTRAINT t2_is_a_child_of_t1 
      FOREIGN KEY ( type )  
      REFERENCES t1;

CREATE EVENT event_on_insert_t2
HANDLER BEGIN

   DECLARE @string_type VARCHAR ( 128 );
   DECLARE @type        INTEGER;

   MESSAGE 'EVENT started' TO CONSOLE;

   SET @string_type = COALESCE ( EVENT_PARAMETER ( '@passed_type' ), '0' );
   SET @type        = CAST ( @string_type AS INTEGER );

   ALTER TABLE t1  
      DROP CONSTRAINT check_that_t1_type_exists_in_t2;

   INSERT t1 VALUES ( @type );

   ALTER TABLE t1  
      ADD CONSTRAINT check_that_t1_type_exists_in_t2 
      CHECK ( type IN ( SELECT type FROM t2 ) );

   MESSAGE 'EVENT finished' TO CONSOLE;

END;

CREATE TRIGGER trigger_before_insert_t2
   BEFORE INSERT ON t2
   REFERENCING NEW AS new_t2
   FOR EACH ROW
   WHEN ( new_t2.type NOT IN ( SELECT type FROM t1 ) )
BEGIN

   MESSAGE 'TRIGGER started' TO CONSOLE;

   TRIGGER EVENT event_on_insert_t2 
      ( @passed_type = STRING ( new_t2.type ) );

   MESSAGE 'TRIGGER finished' TO CONSOLE;

END;

MESSAGE 'Test started' TO CONSOLE;
SET TEMPORARY OPTION WAIT_FOR_COMMIT = 'ON';
MESSAGE 'INSERT started' TO CONSOLE;
INSERT t2 VALUES ( 1, 100 );
MESSAGE 'INSERT finished' TO CONSOLE;
COMMIT;

No joy!

The WAIT_FOR_COMMIT did work as advertised (it delayed the referential integrity error until the COMMIT)

...but the error still happened:

No primary key value for foreign key 't2_is_a_child_of_t1' in table 't2'
SQLCODE=-194, ODBC 3 State="23000"
Line 6, column 1
COMMIT

Test started
INSERT started
TRIGGER started
TRIGGER finished
EVENT started
INSERT finished

Why?

Here's why:
  • The "TRIGGER finished" message appeared before "EVENT started"
  • which means the trigger finished executing before the event even started,
  • and even worse, the "INSERT finished" appeared before "EVENT finished"
  • which probably means INSERT t2 (the child) ran before the event had time to INSERT t1 (the parent)
  • which probably means there was no row in t1 when it hit the COMMIT
  • which probably explains the "No primary key value for foreign key" error.
No, it definitely explains the error :)

But wait, it gets worse!

There's no "EVENT finished" message at all,
  • which means the event connection started but never finished
  • because the event connection was blocked by a "Lock on t1" (Foxhound said so).

  • But wait... no other connection touched t1!
  • Oh, yes they did... the connection with the CREATE TRIGGER executed "SELECT type FROM t1" in the WHEN clause
  • and even a read-only SELECT is enough to grab something called a "schema lock" on the table.
  • A schema lock is a pretty feeble kind of lock,
  • it doesn't prevent another connection from doing a SELECT,
  • it doesn't even block an UPDATE,
  • but a schema lock is strong enough to block ALTER TABLE (because the docs say so),
  • so... by the very fact that the trigger did a SELECT FROM t1,
  • the event was blocked before it even got started.

Talk about useless!

The event started late, and when it did run, it couldn't do anything.

It's time...

It's time to stop, back up, start over, find another way.

Back up all the way to the point the tables existed but not the CREATE TRIGGER:
(I know, you've been screaming "SHOW ME THE TABLES!" for quite some time now, so here they are.)

CREATE TABLE t1 (
   type            INTEGER NOT NULL PRIMARY KEY,
   CONSTRAINT check_that_t1_type_exists_in_t2 
      CHECK ( type IN ( SELECT type FROM t2 ) ) );

CREATE TABLE t2 (
   id              INTEGER NOT NULL PRIMARY KEY,
   type            INTEGER NOT NULL,
   CONSTRAINT t2_is_a_child_of_t1 
      FOREIGN KEY ( type )  
      REFERENCES t1 );

INSERT t1 VALUES ( 100 );

Constraint 'check_that_t1_type_exists_in_t2' violated: Invalid value in table 't1'
SQLCODE=-1091, ODBC 3 State="23000"

INSERT t2 VALUES ( 1, 100 );

No primary key value for foreign key 't2_is_a_child_of_t1' in table 't2'
SQLCODE=-194, ODBC 3 State="23000"
Here's what's going on:
  • There is a FOREIGN KEY relationship between t2 (the child) and t1 (the parent)
  • which means you can't INSERT t2 if there isn't already a single row in t1 with a matching value in type.
  • There is also a CHECK constraint which says the reverse:
  • you can't INSERT t1 if there isn't already one or more rows in t2 with a matching value in type.

Abort! Abort! I say again, Abort!


Or, if you prefer... Danger, Will Robinson!



How about Catch 22? You can't INSERT t2 before you INSERT t1, and you can't INSERT t1 before you INSERT t2.

From the end user's point of view, it's a perfectly reasonable request.

From a database designer's point of view, it's like those steenking fishhook foreign key relationships, only harder... and sharper... and more painful... like fishhooks in real life.



How about an epiphany?

Here's one: The WAIT_FOR_COMMIT option might not help with INSERT t1...

SET TEMPORARY OPTION WAIT_FOR_COMMIT = 'ON';

INSERT t1 VALUES ( 100 );

Constraint 'check_that_t1_type_exists_in_t2' violated: Invalid value in table 't1'
SQLCODE=-1091, ODBC 3 State="23000"

but it does let you get past INSERT t2 without an error, at least until you do a COMMIT...

SET TEMPORARY OPTION WAIT_FOR_COMMIT = 'ON';

INSERT t2 VALUES ( 1, 100 );

-- OK so far, but...

COMMIT;

No primary key value for foreign key 't2_is_a_child_of_t1' in table 't2'
SQLCODE=-194, ODBC 3 State="23000"
Line 7, column 1
-- OK so far, but...
COMMIT

The key word is AFTER

Here's another epiphany: Code a CREATE TRIGGER that runs after INSERT t2 finishes, but before the COMMIT, a trigger that does the INSERT t1 so the COMMIT doesn't crash out.

Step by step:
  1. Change the CREATE TRIGGER from BEFORE to AFTER,
  2. don't bother with EXECUTE IMMEDIATE,
  3. don't bother with CREATE EVENT,
  4. dump the ALTER TABLE statements so only thing left inside the trigger is the INSERT t1,
    CREATE TABLE t1 (
       type            INTEGER NOT NULL PRIMARY KEY,
       CONSTRAINT check_that_t1_type_exists_in_t2 
          CHECK ( type IN ( SELECT type FROM t2 ) ) );
    
    CREATE TABLE t2 (
       id              INTEGER NOT NULL PRIMARY KEY,
       type            INTEGER NOT NULL,
       CONSTRAINT t2_is_a_child_of_t1 
          FOREIGN KEY ( type )  
          REFERENCES t1 );
    
    CREATE TRIGGER trigger_after_insert_t2
       AFTER INSERT ON t2
       REFERENCING NEW AS new_t2
       FOR EACH ROW
       WHEN ( new_t2.type NOT IN ( SELECT type FROM t1 ) )
    BEGIN
       INSERT t1 ( type ) VALUES ( new_t2.type );
    END;
    
  5. use SET TEMPORARY WAIT_FOR_COMMIT = 'ON' before your INSERT t2 statements,
  6. and don't code INSERT t1 outside the trigger... let the trigger do it.
    SET TEMPORARY OPTION WAIT_FOR_COMMIT = 'ON';
    INSERT t2 VALUES ( 1, 100 );
    COMMIT;
    INSERT t2 VALUES ( 2, 100 );
    COMMIT;
    INSERT t2 VALUES ( 3, 200 );
    COMMIT;
    INSERT t2 VALUES ( 4, 200 );
    COMMIT;
    SET TEMPORARY OPTION WAIT_FOR_COMMIT = 'OFF';
    

Woohoo! It works!


SELECT * FROM t1;
SELECT * FROM t2;

type
100
200

id,type
1,100
2,100
3,200
4,200

Credits...


This article started life as a Q&A conversation "ALTER TABLE within trigger" on the SQL Anywere Forum.

Volker Barth suggested that "Instead of the "wait_on_commit" option, one might also declare the FK with the CHECK ON COMMIT clause..."

Thomas Duemesnil suggested using an INSTEAD OF trigger instead of... [snork! pun intended]... the traditional AFTER trigger used here.

I take full (dis)credit for the CREATE EVENT suggestion, for which this article is offered as penance.

Dilbert.com



Wednesday, June 13, 2012

Sometimes the tool you need is right in front of you


Email To: Coworkers
Subject: Remember that bug I had last week, the one where I was hoping for an epiphany?
No epiphany whatsoever.

Here's the symptom: When the main Foxhound service starts for the first time, it launches the Activation service and the Activation page is displayed.

When the user enters a registration code and clicks on a button on the Activation page, the HTML and JavaScript code was supposed to re-launch the Activation service to check the input, but instead it always launched the main Foxhound service again...

...and that service still thinks it's the "first time" and it launches the Activation service with an empty registration code... an endless loop from the user point of view.

Endless fiddling produced no improvement.

So, today, I used Google Chrome's debugging facility - the tool that's "right in front of you"...
  • right mouse on the page - Inspect element,

  • and when the bottom half of the display turns into a debugging frame,

  • switch to the Console tab to see error messages.
When I clicked on the misbehaving button, a red error message would flash momentarily on the Console display. By going click - click - click to get the message to flash - flash - flash, I could see it was saying the function submitF was undefined.

Aha! An HTML INPUT tag said to execute a JavaScript function called submitF() but the actual function was called submitF1().

One steenking character... bet that's never happened to YOU! :


Dilbert.com


It turns out you can tell the Chrome Console to keep the error message on-screen, by right mouse - Preserve log upon navigation:





Monday, June 11, 2012

COMPUTE: A Bed-Time Story

Question: Why do databases get so messed up over the years?

Answer: Because software rusts.

Once upon a time there was a software program that came in four "editions": Beta Edition, Evaluation Edition, Basic Edition and Extended Edition.

The Engineers were exceedingly lazy so instead of creating four different versions of the program, they only created one version, and they made it pretend to be whichever edition the customer asked for.

Whenever the program code needed to know which edition it was pretending to be, it would look inside this table:

CREATE TABLE edition (
   one_row_only   INTEGER NOT NULL DEFAULT 1 PRIMARY KEY CHECK ( one_row_only = 1 ),
   edition_name   VARCHAR ( 100 ) NOT NULL CHECK ( edition_name IN (
                     'Beta',
                     'Evaluation',
                     'Basic',
                     'Extended' ) ) );
For example...
IF EXISTS ( SELECT * FROM edition WHERE edition_name = 'Extended' ) THEN
   ... do some thing only the Extended Edition can do
END IF;
Then, one day, Marketing demanded that customers ask permission to use the Beta and Evaluation editions, and pay for the Basic and Extended editions. A registration key feature was added with a one-character code for the type of key:
CREATE TABLE edition (
   one_row_only   INTEGER NOT NULL DEFAULT 1 PRIMARY KEY CHECK ( one_row_only = 1 ),
   key_code       VARCHAR ( 1 ) NOT NULL CHECK ( key_code IN (
                     'B',        -- Beta
                     'E',        -- Evaluation
                     'S',        -- Basic
                     'X' ) ),    -- Extended
   edition_name   VARCHAR ( 100 ) NOT NULL CHECK ( edition_name IN (
                     'Beta',
                     'Evaluation',
                     'Basic',
                     'Extended' ) ) );

IF EXISTS ( SELECT * FROM edition WHERE edition_name = 'Extended' ) THEN
   ... do some thing only the Extended Edition can do
END IF;
A brilliant Alpha Engineer noticed
  • that key_code would always determine edition_name

  • and therefore edition_name was redundant, and dangerous,
and so, feeling full of Simplicity, Honor, Integrity and Truth, the Alpha Engineer eliminated edition_name:
CREATE TABLE edition (
   one_row_only   INTEGER NOT NULL DEFAULT 1 PRIMARY KEY CHECK ( one_row_only = 1 ),
   key_code       VARCHAR ( 1 ) NOT NULL CHECK ( key_code IN (
                     'B',        -- Beta
                     'E',        -- Evaluation
                     'S',        -- Basic
                     'X' ) ) );  -- Extended
This caused some grumbling among the Gamma Engineers who had to change the code:
IF EXISTS ( SELECT * FROM edition WHERE key_code = 'X' ) THEN
   ... do some thing only the Extended Edition can do
END IF;
Some time passed, and two new kinds of registration keys were introduced, R and U:
CREATE TABLE edition (
   one_row_only   INTEGER NOT NULL DEFAULT 1 PRIMARY KEY CHECK ( one_row_only = 1 ),
   key_code       VARCHAR ( 1 ) NOT NULL CHECK ( key_code IN (
                     'B',        -- Beta
                     'E',        -- Evaluation
                     'R',        -- Evaluation Renewal
                     'S',        -- Basic
                     'U',        -- Upgrade Basic To Extended
                     'X' ) ) );  -- Extended
Although key_code still determined edition, the program code had to be changed again and this caused more discontent among the Gammas:
IF EXISTS ( SELECT * FROM edition WHERE key_code IN ( 'U', 'X' ) ) THEN
   ... do some thing only the Extended Edition can do
END IF;
Then one day, Marketing dropped this bombshell:
  • the Beta Edition was eliminated,

  • the Evaluation Edition was replaced with the Rental Edition, and

  • four new "version upgrade" registration keys were introduced to make old customers pay for the new version.
Now they were back to only three editions, Rental, Basic and Extended... but with 8 different key_code values! (and the promise of more to come):
CREATE TABLE edition (
   one_row_only   INTEGER NOT NULL DEFAULT 1 PRIMARY KEY CHECK ( one_row_only = 1 ),
   key_code       VARCHAR ( 1 ) NOT NULL CHECK ( key_code IN (
                     'R',        -- Rental
                     'A',        -- Upgrade Basic from version 1.0 to version 2 
                     'C',        -- Upgrade Basic from version 1.1 to version 2
                     'S',        -- Basic
                     'D',        -- Upgrade Extended from version 1.0 to version 2 
                     'F',        -- Upgrade Extended from version 1.1 to version 2
                     'U',        -- Upgrade Basic To Extended
                     'X' ) ) );  -- Extended

"The peasants are revolting!"

Oh yes they were... you could tell the Gammas were disgruntled by the graffiti they coded into the program:
IF EXISTS ( SELECT * FROM edition WHERE key_code IN ( 'F', 'U', 'X', 'D' ) ) THEN
   ... do some thing only the Extended Edition can do
END IF;

To the rescue!

One of the Beta Engineers suggested using the CREATE TABLE COMPUTE clause to reintroduce edition_name without requiring any extra effort to insert or update the value:
CREATE TABLE edition (
   one_row_only   INTEGER NOT NULL DEFAULT 1 PRIMARY KEY CHECK ( one_row_only = 1 ),
   key_code       VARCHAR ( 1 ) NOT NULL CHECK ( key_code IN (
                     'R',        -- Rental
                     'A',        -- Upgrade Basic from version 1.0 to version 2 
                     'C',        -- Upgrade Basic from version 1.1 to version 2
                     'S',        -- Basic
                     'D',        -- Upgrade Extended from version 1.0 to version 2 
                     'F',        -- Upgrade Extended from version 1.1 to version 2
                     'U',        -- Upgrade Basic To Extended
                     'X' ) ),    -- Extended
   edition_name   VARCHAR ( 100 ) NOT NULL COMPUTE ( 
                     CASE 
                        WHEN key_code IN ( 'R'                ) THEN 'Rental' 
                        WHEN key_code IN ( 'A', 'C', 'S'      ) THEN 'Basic' 
                        WHEN key_code IN ( 'D', 'F', 'U', 'X' ) THEN 'Extended' 
                        ELSE                                         'Unknown'
                     END CASE ) ); 

INSERT edition ( key_code ) VALUES ( 'F' );

SELECT * FROM edition;

one_row_only,key_code,edition_name
1,'F','Extended'
The Gammas did have to make one more change, but it was a good change, back to the Old Way Of Doing Things when code was readable and programs were maintainable:
IF EXISTS ( SELECT * FROM edition WHERE edition_name = 'Extended' ) THEN
   ... do some thing only the Extended Edition can do
END IF;

And everyone lived happily ever after!

The moral of this story is that computed columns are your friend.

Dilbert.com



Friday, June 8, 2012

SQL Anywhere Advanced Search

No, this isn't an article about Full Text Search, it's a new home for some targeted web searches...

SQL Anywhere Technical Documents:
 
   
Help: Go to DocCommentXchange then choose a "Collection" and use the Contents, Index or Search tabs to find topics.
   
Version 12.0.1 Help:
 
   
SQL Anywhere Forum:
 
   
Glenn Paulley's blog:
 
   
This blog:
 
   
Foxhound:
 
   
Dilbert.com



Wednesday, June 6, 2012

New Gems From The Doc Mines

Here are the latest changes to the SQL Anywhere Technical Documents page on this blog:

...many thanks to Glenn Paulley for providing the HTMLinspiration!

More Good News!

The Google Custom Search facility seems to be working better: not only is it picking up new articles promptly but the weird behavior mentioned here seems to be gone...

... now when you search on "select", instead of only getting one or two hits you get "About 3,450,000 results".

Clearly, MapReduce has a sense of humor; if you try to scroll past page 5 the story changes: "About 46 results" :)






Monday, June 4, 2012

Example: OUTPUT TO From VB, Part 2

Part 1 of this article explained how to run SQL Anywhere's SELECT and OUTPUT TO statements via dbisql.exe from inside a Visual Basic application.

This article describes how to use the same technique to run much larger SQL scripts, scripts that might not fit on one command line...

...but first, here's a recap of Part 1:


Question: How do I write the result set from a SQL Anywhere 10 SELECT statement to a local tab-delimited text file from a Visual Basic 2008 application running on a client workstation?

Answer...
Here's the code:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" " _
                      & "-c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" " _
                      & "SELECT * FROM t1 ORDER BY pkey; " _
                      & "OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09'")
    End Sub
End Class



Part 2: Run a SQL Script Via Interactive SQL


SQL Anywhere's dbisql utility let's you put SQL statements inside text files and then load-and-execute those scripts via the READ statement.

The READ statement...
Those last two features are great for building large hierarchies of SQL scripts that are customized at runtime, but this article only talks about running one single script from the command line.

Here's what the VB code looks like when the SELECT and OUTPUT TO statements have been moved into a script file:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" " _
                      & "-c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" " _
                      & "READ ENCODING Cp1252 ""C:\data\select_output.sql""")
    End Sub
End Class

Here's what the C:\data\select_output.sql file looks like (OK, it's not a "much larger SQL script" like was promised earlier, but it COULD be larger, with no limit):
SELECT * FROM t1 ORDER BY pkey; 
OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09';

The whole business of the double-doublequotes and the "&" concatenation operator is explained in Part 1 of this article. For the record, the original dbisql.exe command line has been changed from this (CAUTION: these are one-line commands that have been split to avoid display problems on different browsers)
"C:\Program Files\SQL Anywhere 10\win32\dbisql.exe" 
-c "ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql" 
SELECT * FROM t1 ORDER BY pkey; OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09';
to this
"C:\Program Files\SQL Anywhere 10\win32\dbisql.exe" 
-c "ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql" 
READ ENCODING Cp1252 "C:\data\select_output.sql"
and then massaged to fit inside the VB call to Shell().


The ENCODING Cp1252 is semantic sugar: On Windows computers it is sometimes necessary to specify the "code page" to get READ to work properly. This is like waving a dead chicken over the keyboard: it never hurts, it sometimes helps, and very few people care understand why.

Tip: Like the OUTPUT TO statement, the READ statement is executed by the Interactive SQL (dbisql.exe) utility, not by the SQL Anywhere database server. This can lead to confusion, like "Why can't I put an OUTPUT TO statement inside a stored procedure? Answer: Because stored procedures are executed inside the SQL Anywhere server, and the server doesn't understand OUTPUT TO."

The fog lifts once you realize that, from the server's point of view, dbisql.exe is just another steenking client application, and that OUTPUT TO and READ statements are parsed and executed on the client... the server never sees them.


Friday, June 1, 2012

Example: OUTPUT TO From VB

Question: How do I write the result set from a SQL Anywhere 10 SELECT statement to a local tab-delimited text file from a Visual Basic 2008 application running on a client workstation?

Wrong Answer: Use the UNLOAD TO statement - that writes the file onto the computer where the SQL Anywhere server is running, not the computer where the VB application is running. You could mess around with \\UNC\file specifications, but chances are you'll never get it to work... especially if the SQL Anywhere server is running as a service and doesn't have permission to do file I/O across the network.

Another Wrong Answer: Use UNLOAD INTO CLIENT FILE statement - nice try, but no cigar! The question said "SQL Anywhere 10" and the cross-border version of UNLOAD wasn't introduced until Version 11.

Right Answer: Well, one right answer, one that works with SQL Anywhere 10, and 11, and 12...

That's a whole lotta words to describe one line of code in VB:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" -c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" SELECT * FROM t1 ORDER BY pkey; OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'")
    End Sub
End Class
...but ya gotta admit, it's one UGLY line of code, and it looks even worse in Visual Studio 2008 which doesn't wrap long lines of code (nor should it):


OK, so how about we make it "one statement" instead of "one line", with some line breaks to make it readable:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" " _
                      & "-c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" " _
                      & "SELECT * FROM t1 ORDER BY pkey; " _
                      & "OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09'")
    End Sub
End Class

Here's how the two calls to Shell() were constructed:
  1. First, a Windows command was written and tested using a *.BAT file:
    "C:\Program Files\SQL Anywhere 10\win32\dbisql.exe" -c "ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql" SELECT * FROM t1 ORDER BY pkey; OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09';
    

  2. Then, the command was turned into a Visual Basic string literal by wrapping it in a pair of "doublequotes":
    ""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe" -c "ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql" SELECT * FROM t1 ORDER BY pkey; OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09';"
    

  3. but that's wasn't right, because Visual Basic would choke on the single doublequotes inside the string, so those nested doublequotes had to be doubled-up like this:
    """C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" -c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" SELECT * FROM t1 ORDER BY pkey; OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'"
    

  4. Then, the string was wrapped in a call to Shell():
    Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" -c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" SELECT * FROM t1 ORDER BY pkey; OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'")
    

  5. That executes OK, but it's hard to read, so the string was broken up into 4 lines:
    Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" 
                  -c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql""  
                  SELECT * FROM t1 ORDER BY pkey;  
                  OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'")
    

  6. but that didn't work because VB needs a space and an underscore " _" to break a statement onto two lines, like this:
    Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" _ 
                  -c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" _  
                  SELECT * FROM t1 ORDER BY pkey; _  
                  OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'")
    

  7. but that STILL didn't work because VB doesn't let you break a one string literal across four lines, so one separate string literal per line was required, like this:
    Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" " _ 
                  "-c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" " _  
                  "SELECT * FROM t1 ORDER BY pkey; " _  
                  "OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'")
    

  8. but (again) that STILL didn't work because Shell() needed the four string literals to be concatenated into one string argument, using the VB concatenation operator "&" like this:
    Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" " _ 
                  & "-c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" " _  
                  & "SELECT * FROM t1 ORDER BY pkey; " _  
                  & "OUTPUT TO 'C:\data\select_output1.txt' DELIMITED BY '\X09'")
    

  9. ...and that works again (whew!)

But HOW does it work?

Here's how:
Public Class Form1
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Shell("""C:\Program Files\SQL Anywhere 10\win32\dbisql.exe"" " _
                      & "-c ""ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql"" " _
                      & "SELECT * FROM t1 ORDER BY pkey; " _
                      & "OUTPUT TO 'C:\data\select_output.txt' DELIMITED BY '\X09'")
    End Sub
End Class
  • The VB Shell() function call starting on line 3 needs at least one argument, called "Pathname" in the docs: Name of the program to execute, together with any required arguments and command-line switches. Pathname can also include the drive and the directory path or folder. (There are three other optional arguments described in the docs, all of which look interesting... for another day.)

  • The string "C:\Program Files\SQL Anywhere 10\win32\dbisql.exe" specifies exactly where to find the SQL Anywhere 10 utility program dbisql.exe on the workstation. If you trust the PATH, you can code just use "dbisql.exe" or "dbisql" or even leave off the "quotes". In the code shown here, the "quotes" are necessary because of the spaces in the path specification, and the full path is specified because, well, it's been many years since the Windows PATH environment variable was stable and trustworthy.

  • The connection string on line 4 specifies how dbisql is to connect to the SQL Anywhere database. In this example, it's a simple connection to a local database, -c "ENG=ddd10;DBN=ddd10;UID=dba;PWD=sql", but it could easily include a LINKS parameter to point across the network to another computer.

  • The SELECT statement on line 5 shows how dbisql can be run in batch mode: just code your SQL statement right on the command line, and dbisql will execute it without opening up the GUI.

  • The Interactive SQL OUTPUT TO statement on line 6 shows how you can code more than one statement on the dbisql command line if you separate them with semicolons.

  • The SELECT statement is sent to the database, and SQL Anywhere returns the result set to dbisql. Then, dbisql runs the OUTPUT TO statement locally (inside dbisql, not on the SQL Anywhere server) to format and write the result set to a tab-delimited text file... which is what the DELIMITED BY '\X09' is for.


Wednesday, May 30, 2012

Product Suggestion: INSERT SET


In the real world, many (almost all?) production INSERT statements look like this:

Syntax 1: INSERT table-name [ ( column-name, ... ) ] VALUES ( expression, ... )

   or

Syntax 2: INSERT table-name [ ( column-name, ... ) ] SELECT expression, ... FROM ...
In the real world, tables have dozens (hundreds?) of columns, and it is a real chore matching up the ( column-name ) list with the expression list.

It gets worse if you leave out the ( column-name ) list: you have to match the expression list up with the full CREATE TABLE column list, plus all the columns that have been added over the years with ALTER TABLE.

No such problem exists for the UPDATE statement; the column names and expressions are matched up in pairs:
UPDATE table-name SET column-name = expression, ...
SQL Anywhere needs the same thing:
Syntax 3: INSERT table-name SET column-name = expression, ...
That's the simple, real-world version of Syntax 3: INSERT SET.

For a more [ahem] sophisticated version of this suggestion, you can visit the Year 2002 in the Network News Tar Pit:
Newsgroups: sybase.public.sqlanywhere.product_futures_discussion
From: Breck Carter
Date: Sat, 13 Jul 2002 11:04:22 -0400
Local: Sat, Jul 13 2002 11:04 am
Subject: Insert Syntax 3

Insert statements involving long column name lists are difficult to 
write and maintain because the corresponding VALUES list (Insert 
Syntax 1) or select statement (Syntax 2) are coded separately. It's 
just too easy to get names and values in the wrong order and if the 
datatypes match there's no error message at runtime. 

The following "Insert Syntax 3" uses the more maintainable "SET column 
= value" syntax from the UPDATE statement: 

Insert Syntax 3 

INSERT [ INTO ] [ owner.]table-name SET set-item, ... 
[ FROM table-list ] 
[ WHERE search-condition ] 
[ ORDER BY expression [ ASC | DESC ], ... ] 

set-item : 
  column-name [.field-name...] = expression 
| column-name [.field-name...] = DEFAULT 
| column-name[.field-name...].method-name( [ expression ] ) 

Note: The special keyword "DEFAULT" should be allowed on the right 
side of a set-item. 

Note: The "@variable-name = expression" set-item is probably not 
necessary for INSERT. 

Insert Syntax 3 would be in addition to, NOT replacing, the current 
two formats: 

Insert Syntax 1 

INSERT [ INTO ] [ owner.]table-name [ ( column-name, ... ) ] 
VALUES ( expression | DEFAULT, ... ) 

Insert Syntax 2 

INSERT [ INTO ] [ owner.]table-name [ ( column-name, ... ) ] 
select-statement 

===== 

For the record, here's the corresponding Update syntax: 

Update Syntax 1 

UPDATE [ FIRST | TOP n ] table-list SET set-item, ... 
[ FROM table-list ] 
[ WHERE search-condition ] 
[ ORDER BY expression [ ASC | DESC ], ... ] 

set-item : 
  column-name [.field-name...] = expression 
| column-name[.field-name...].method-name( [ expression ] ) 
| @variable-name = expression 

==================================================================

Newsgroups: sybase.public.sqlanywhere.product_futures_discussion
From: "Richard Biffl"
Date: Sat, 13 Jul 2002 23:11:13 -0400
Local: Sat, Jul 13 2002 11:11 pm
Subject: Re: Insert Syntax 3

Allowing SET in an INSERT statement would make the statement more readable 
and maintainable -- though I'd probably stick with the old obscure standard 
form because it's standard -- but I don't see the function of the FROM, 
WHERE, and ORDER BY clauses to an INSERT statement, other than allowing your 
other, more controversial <g>, suggestion (INSERT OR UPDATE). 

==================================================================

Newsgroups: sybase.public.sqlanywhere.product_futures_discussion
From: "Paul Horan[TeamSybase]" 
Date: Sat, 13 Jul 2002 23:24:46 -0400
Local: Sat, Jul 13 2002 11:24 pm
Subject: Re: Insert Syntax 3

I think this borders on genius, personally...  Well done, Breck! 

You would need the FROM/WHERE/ORDER BY clauses because you're basically 
writing the SELECT statement from syntax 2, just splitting out the SELECT 
list from that statement into the separate SET statements. 

So, instead of 

INSERT into LongTable 
 (column list....) 
SELECT (expression list that hopefully lines up) 
  FROM OtherTable 
WHERE <condition> 
ORDER BY 1,2,3 

you would have: 

INSERT into LongTable 
  SET col1 = <previous SELECT's 1st expression>, 
  SET col2 = <previous SELECT's 2nd expression>, 
  SET col3 = DEFAULT, 
... 
FROM OtherTable 
WHERE <condition> 
ORDER BY 1,2,3 

Umm, yes please... 

Did he just say "genius"?


Dilbert.com



Monday, May 28, 2012

Latest SQL Anywhere EBFs: 11.0.1 Linux, SPARC, Windows

The three asterisks "***" show what's new since the previous list.

  • Only EBFs for the latest fully-supported versions of SQL Anywhere are shown here: 11.0.1 and 12.0.1.

  • Note: Just because an older version isn't "fully supported" doesn't mean you can't download files (or ask questions, or get help), it just means there won't be any more new EBFs released. For a complete list of everything available for download see Downloads - EBFs / Maintenance.

Current builds for the active platforms...

HP-UX Itanium    12.0.1.3523 EBF       15 Dec 2011
                 11.0.1.2753 EBF       13 Feb 2012

IBM AIX          12.0.1.3523 EBF       15 Dec 2011
                 11.0.1.2753 EBF       13 Feb 2012

Linux x86/x64    12.0.1.3723 EBF       04 May 2012
                 11.0.1.2811 EBF ***   17 May 2012 ***

Mac OS           12.0.1.3577 EBF       24 Feb 2012
                 11.0.1.2449 EBF       29 Jun 2010

Solaris SPARC    12.0.1.3574 EBF       23 Mar 2012
                 11.0.1.2811 EBF ***   14 May 2012 ***

Solaris x64      12.0.1.3523 EBF       15 Dec 2011
                 11.0.1.2753 EBF       13 Feb 2012

Windows x86/x64  12.0.1.3726 EBF       04 May 2012
                 11.0.1.2808 EBF ***   22 May 2012 ***
[Download EBFs here]


Friday, May 25, 2012

What's YOUR Klout score?



How did my Klout score get to be so high?

In case you were wondering,

Here's how I really feel about it...

Klout


Wednesday, May 23, 2012

Still More New Old Docs

Look up...

look way up...

OK, not that far


See the line that says "Technical Documents"?

That's a fixed link to the SQL Anywhere Technical Documents page on this blog.

Check it out...

  • The layout's been cleaned up to make the page easier to use,

  • Techwave presentations from 2001, 2002 and 2005 have been added (still looking for 2003 and 2004), and

  • the "authors" column has been filled in for a few more entries.
Behind the scenes, the all-important Google Custom Search Engine has been modified...
  • Instead of specifying one single url "http://sqlanywhere.blogspot.ca/2012/03/tales-from-doc-face.html" and expecting the Googlebot to take it from their, urls for all 472 documents have been specified.
I don't know if that will make any difference, but I'm willing to try anything to solve Google CSE's weird behavior; for example, search on "select" and you'll only get one or two hits:

Search on something else, like "OLAP", and it behaves much better.




Monday, May 21, 2012

Product Suggestion: Index Skip Key Processing

Here's simple query to display the MAX value of a column in each group:

SELECT g1, g2, g3, MAX ( t2 )
  FROM t
 GROUP BY g1, g2, g3 
 ORDER BY g1, g2, g3;
Here's what the table looks like; notice there's a UNIQUE index "ukey" on all the columns in the query:
CREATE TABLE t (
   g1           VARCHAR ( 12 ) NOT NULL,
   g2           VARCHAR ( 4 ) NOT NULL,
   g3           SMALLINT NOT NULL,
   t1           TIMESTAMP NOT NULL,
   t2           TIMESTAMP NOT NULL,
   other        VARCHAR ( 100 ) NOT NULL,
   CONSTRAINT pkey PRIMARY KEY ( g1, g2, g3, t1 ),
   CONSTRAINT ukey UNIQUE ( g1, g2, g3, t2 ),
   CONSTRAINT tchk CHECK ( t1 <= t2 ) );
In the world of IBM, that index might be used to efficiently satisfy the query by "skipping" from one group ( g1, g2, g3 ) to the next and plucking the MAX ( t2 ) value out of that group; after all, the index is sorted on t2 within each group ( g1, g2, g3 ).

Here an excerpt from the IBM docs on the subject, with the really interesting bits highlighted in bold:


IBM i 7.1 Information Center > Database > Performance and query optimization > Processing queries: Overview > Grouping optimization

Optimizing grouping by using index skip key processing

Index Skip Key processing can be used when grouping with the keyed sequence implementation algorithm which uses an existing index. It is a specialized version of ordered grouping that processes few records in each group rather than all records in each group.

The index skip key processing algorithm:

1. Uses the index to position to a group and

2. finds the first row matching the selection criteria for the group, and if specified the first non-null MIN or MAX value in the group

3. Returns the group to the user

4. "Skip" to the next group and repeat processing

This algorithm improves performance by potentially not processing all index key values for a group.

Index skip key processing can be used:

  • For single table queries using the keyed sequence grouping implementation when:

    • There are no column functions in the query, or

    • There is only a single MIN or MAX column function and the MIN or MAX operand is the next index key column after the grouping columns. There can be no other grouping functions in the query. For the MIN function, the key column must be an ascending key; for the MAX function, the key column must be a descending key. If the query is whole table grouping, the operand of the MIN or MAX must be the first key column.

      Example 1, using SQL:
      CREATE INDEX IX1 ON EMPLOYEE (SALARY DESC)
      
      DECLARE C1 CURSOR FOR
         SELECT MAX(SALARY) FROM EMPLOYEE;
      
      The query optimizer chooses to use the index IX1. The SLIC runtime code scans the index until it finds the first non-null value for SALARY. Assuming that SALARY is not null, the runtime code positions to the first index key and return that key value as the MAX of salary. No more index keys are processed.

      Example 2, using SQL:
      CREATE INDEX IX2 ON EMPLOYEE (WORKDEPT, JOB, SALARY)
      
      DECLARE C1 CURSOR FOR 
       SELECT WORKDEPT, MIN(SALARY)
        FROM EMPLOYEE
        WHERE JOB='CLERK'
        GROUP BY WORKDEPT
      
      The query optimizer chooses to use Index IX2. The database manager positions to the first group for DEPT where JOB equals 'CLERK' and returns the SALARY. The code then skips to the next DEPT group where JOB equals 'CLERK'.

Here's an excerpt that explains what "ordered grouping" means in the earlier phrase "specialized version of ordered grouping":

IBM i 7.1 Information Center > Database > Performance and query optimization > Processing queries: Overview > Grouping optimization

Index grouping implementation

There are two primary ways to implement grouping using an index: Ordered grouping and pre-summarized processing.

Ordered grouping

This implementation uses the Radix Index Scan or the Radix Index Probe access methods to perform the grouping. An index is required that contains all the grouping columns as contiguous leftmost key columns. The database manager accesses the individual groups through the index and performs the requested summary functions.

Since the index, by definition, already has all the key values grouped, the first group result can be returned in less time than the hashing method. This index performance is faster because the hashing method requires a temporary result. This implementation can be beneficial if an application does not need to retrieve all the group results, or if an index exists that matches the grouping columns.

When the grouping is implemented with an index and a permanent index does not exist that satisfies grouping columns, a temporary index is created. The grouping columns specified within the query are used as the key columns for this index.


Soooo, what does SQL Anywhere do with this query?

Welllll, as far as I can tell, it uses the Hash Group By algorithm together with a sequential scan of table t... all three million rows of table t.

Sometimes, if the table has tiny rows, it uses an eight-way parallel table scan (on a computer with eight processors), but it never does anything with the "ukey" index.

Here's a test you can run yourself; the combo table is used help INSERT sixteen groups of data spread across 3,000,000 rows in t. In other words, the SELECT returns only 16 rows:

CREATE TABLE combo (
   combo_number INTEGER NOT NULL PRIMARY KEY,
   g1           VARCHAR ( 12 ) NOT NULL,
   g2           VARCHAR ( 4 ) NOT NULL,
   g3           SMALLINT NOT NULL );

INSERT combo VALUES (  1, 'aaaaaaaaaa', 'bbbb', 1 );
INSERT combo VALUES (  2, 'bbbbbbbbbb', 'cccc', 2 );
INSERT combo VALUES (  3, 'cccccccccc', 'dddd', 1 );
INSERT combo VALUES (  4, 'dddddddddd', 'eeee', 2 );
INSERT combo VALUES (  5, 'eeeeeeeeee', 'ffff', 1 );
INSERT combo VALUES (  6, 'ffffffffff', 'gggg', 2 );
INSERT combo VALUES (  7, 'bbbbbbbbbb', 'bbbb', 1 );
INSERT combo VALUES (  8, 'cccccccccc', 'cccc', 2 );
INSERT combo VALUES (  9, 'gggggggggg', 'dddd', 1 );
INSERT combo VALUES ( 10, 'hhhhhhhhhh', 'eeee', 2 );
INSERT combo VALUES ( 11, 'iiiiiiiiii', 'ffff', 1 );
INSERT combo VALUES ( 12, 'bbbbbbbbbb', 'gggg', 2 );
INSERT combo VALUES ( 13, 'dddddddddd', 'bbbb', 1 );
INSERT combo VALUES ( 14, 'gggggggggg', 'cccc', 2 );
INSERT combo VALUES ( 15, 'jjjjjjjjjj', 'dddd', 1 );
INSERT combo VALUES ( 16, 'kkkkkkkkkk', 'eeee', 2 );
COMMIT;

BEGIN

DECLARE @insert_count BIGINT;
DECLARE @combo_number BIGINT;

SET @insert_count = 1;
SET @combo_number = 0;

WHILE @insert_count <= 3000000 LOOP 

   SET @combo_number = @combo_number + 1;
   IF @combo_number > 16 THEN
      SET @combo_number = 1;
   END IF;

   INSERT t
   SELECT combo.g1,
          combo.g2,
          combo.g3,
          DATEADD ( MINUTE, 10 * @insert_count, '1901-01-01 00:00' ),
          DATEADD ( MINUTE, 10 * @insert_count, '1901-01-01 00:05' ),
          REPEAT ( 'x', 100 ) 
     FROM combo
    WHERE combo.combo_number = @combo_number;

   IF MOD ( @insert_count, 1000 ) = 0 THEN
      COMMIT;
      MESSAGE STRING ( @insert_count, ' rows inserted' ) TO CLIENT;
   END IF;

   SET @insert_count = @insert_count + 1;

END LOOP;

COMMIT;
MESSAGE STRING ( 'All done' ) TO CLIENT;

END;

------------------------------------------------------
-- query 1

CALL sa_flush_cache();

SELECT g1, g2, g3, MAX ( t2 )
  FROM t
 GROUP BY g1, g2, g3 
 ORDER BY g1, g2, g3;

g1,g2,g3,MAX(t.t2)
'aaaaaaaaaa','bbbb',1,'1958-01-15 05:35:00.000'
'bbbbbbbbbb','bbbb',1,'1958-01-15 06:35:00.000'
'bbbbbbbbbb','cccc',2,'1958-01-15 05:45:00.000'
'bbbbbbbbbb','gggg',2,'1958-01-15 07:25:00.000'
'cccccccccc','cccc',2,'1958-01-15 06:45:00.000'
'cccccccccc','dddd',1,'1958-01-15 05:55:00.000'
'dddddddddd','bbbb',1,'1958-01-15 07:35:00.000'
'dddddddddd','eeee',2,'1958-01-15 06:05:00.000'
'eeeeeeeeee','ffff',1,'1958-01-15 06:15:00.000'
'ffffffffff','gggg',2,'1958-01-15 06:25:00.000'
'gggggggggg','cccc',2,'1958-01-15 07:45:00.000'
'gggggggggg','dddd',1,'1958-01-15 06:55:00.000'
'hhhhhhhhhh','eeee',2,'1958-01-15 07:05:00.000'
'iiiiiiiiii','ffff',1,'1958-01-15 07:15:00.000'
'jjjjjjjjjj','dddd',1,'1958-01-15 07:55:00.000'
'kkkkkkkkkk','eeee',2,'1958-01-15 08:05:00.000'
Query 1 took 14.7 seconds to execute... that's an average over 7 tests, with the cache flushed each time and the server restarted once.

Here's a glimpse into the plan:

Depending on your expectations, 14.7 seconds might not be bad, but a sequential table scan?

Really?

Surely one can do better... after all, there's a bloody index that covers all the columns in the query and it wasn't even considered:

Here's a clue...

Why wasn't the "ukey" index considered for query 1? Here's a clue from the SQL Anywhere 12 Help (with emphasis added):

Cost-based optimization with MIN and MAX functions

The min/max cost-based optimization is designed to exploit an existing index to compute efficiently the result of a simple aggregation query involving the MAX or MIN aggregate functions. The goal of this optimization is to be able to compute the result by retrieving only a few rows from the index. To be a candidate for this optimization, the query:

  • must not contain a GROUP BY clause

  • must be over a single table

  • must contain only a single aggregate function (MAX or MIN) in the query's SELECT-list

Taking that clue as a starting point, here's a version of query 1 that
  • separates the GROUP BY from the MAX into different derived tables gt and mt and

  • uses the LATERAL keyword to join them via the WHERE clause inside the second SELECT:
------------------------------------------------------
-- query 2

CALL sa_flush_cache();

SELECT gt.g1, gt.g2, gt.g3, mt.t2
  FROM ( 
         SELECT g1, g2, g3
           FROM t
          GROUP BY g1, g2, g3 
       ) AS gt,
       LATERAL
       (
         SELECT MAX ( t.t2 ) AS t2
             FROM t
            WHERE t.g1 = gt.g1
              AND t.g2 = gt.g2
              AND t.g3 = gt.g3
       ) AS mt
 ORDER BY gt.g1, gt.g2, gt.g3;
On average over six tests, query 2 took 13.9 seconds, which isn't much of an improvement over 14.7 seconds, probably within the margin of error for experiments like this.

The performance might be the same, but the plan sure has changed!

Woohoo! An Index Only Retrieval Scan!

The SELECT MAX() does a "Scan t using index ukey":

But wait... what's all that other stuff?

That other stuff is an eight-way Parallel Hash Group By, together with an eight-way Parallel Table Scan, used to compute the first derived table gt, the one that does the GROUP BY. The Index Only Retrieval Scan is used to compute the SELECT MAX ( t.t2 ) query.

Here's the view from the Foxhound Monitor showing the eight "INT: EXCHANGE" internal connections running all those parallel processes:

Which query is faster? GROUP BY or MAX?

If query 2 is split into separate SELECT statements, with a temporary table used to pass the GROUP BY results to the query doing doing the MAX(), it's the GROUP BY that takes most of the time:
------------------------------------------------------
-- query 3A - prepare for query 3B

CALL sa_flush_cache();

SELECT g1, g2, g3
  INTO #g
  FROM t
 GROUP BY g1, g2, g3; 

Execution time: 13.5 seconds

------------------------------------------------------
-- query 3B

CALL sa_flush_cache();

SELECT #g.g1, #g.g2, #g.g3, mt.t2
  FROM #g,
       LATERAL
       (
         SELECT MAX ( t.t2 ) AS t2
             FROM t
            WHERE t.g1 = #g.g1
              AND t.g2 = #g.g2
              AND t.g3 = #g.g3
       ) AS mt
 ORDER BY #g.g1, #g.g2, #g.g3;

Execution time: 0.4 seconds

So... in the (unlikely?) case that the GROUP BY result remains unchanged while the MAX() needs to be recalculated multiple times, it makes sense to jump through hoops to divide and conquer the problem with funky techniques like LATERAL.

In the real world, this is a job for Index Skip Key Processing, doncha think?


Friday, May 18, 2012

RUN anywhere

RUN anywhere is one of the slogans in this new TV commercial:



Yes, an actual SAP TV commercial, actually running in prime time on the Fox News Channel.

...and we all know what RUN anywhere means, don't we? nudge, nudge, wink, wink [ahem] SQL Anywhere [cough]


Wednesday, May 16, 2012

"Whaddaya mean, backups have failed for the last month?"

Oren Jacob and Galyn Susman tell the story of how all the Toy Story 2 files vanished:


The moral of the story?

Test your backups, of course.


Monday, May 14, 2012

Author, Author!

The "author" column has been added to list of SQL Anywhere technical documents found at Tales From The Doc Face.

...and now the bad news


It will take some time before the author column is completely filled in... right now, the authors are only shown for the freshly-added Techwave 2006 presentations.

Which brings us to the question, "Why weren't the authors included from the beginning?"

Answer: Sigh... just plain stupid, I guess... too much focus on the hard stuff (figuring out the publication dates and the SQL Anywhere versions), not enough on the easy task (capturing the authors).

What's the old saying?


Never enough time to do it right, always enough time to do it over?


Friday, May 11, 2012

From The Golden Age of Techwave

Do you remember 2007?

That's when outsiders were still invited to make presentations at Techwave.

And that's when 24 (twenty four!) separate technical presentations were made on the subject of SQL Anywhere ...actually, I think there were 25 but I can't find the second day of Glenn Paulley's SQL Anywhere Internals class.

Anyway, the 24 Techwave 2007 presentations that do exist on the web have been added to the list at Tales From The Doc Face.

Did you know?

Did you know that Tales From The Doc Face now lists 412 SQL Anywhere technical documents?

The "official list" of SQL Anywhere Technical Documents over at sybase.com only contains 312 entries, and that list includes all sorts of documents that have been left out of Tales From The Doc Face because they really aren't "technical documents": announcements, notices, bulletins, bug fixes, licensing details, certification reports, various listicles (components, requirements, platforms, links), and straight links to DCX topics.


Wednesday, May 9, 2012

Yet More New Old Docs: Techwave 2008

Eighteen SQL Anywhere presentations from Techwave 2008 have been added to the list at Tales From The Doc Face.

...and this time, they're all available online: none are missing, and none of them had to be copied so they can be indexed by Google.



Monday, May 7, 2012

Latest SQL Anywhere EBFs: Linux and Windows

The three asterisks "***" show what's new since the previous list.

  • Only EBFs for the latest fully-supported versions of SQL Anywhere are shown here: 11.0.1 and 12.0.1.

  • Note: Just because an older version isn't "fully supported" doesn't mean you can't download files (or ask questions, or get help), it just means there won't be any more new EBFs released. For a complete list of everything available for download see Downloads - EBFs / Maintenance.

Current builds for the active platforms...

HP-UX Itanium    12.0.1.3523 EBF       15 Dec 2011
                 11.0.1.2753 EBF       13 Feb 2012

IBM AIX          12.0.1.3523 EBF       15 Dec 2011
                 11.0.1.2753 EBF       13 Feb 2012

Linux x86/x64    12.0.1.3723 EBF ***   04 May 2012 ***
                 11.0.1.2794 EBF       18 Apr 2012

Mac OS           12.0.1.3577 EBF       24 Feb 2012
                 11.0.1.2449 EBF       29 Jun 2010

Solaris SPARC    12.0.1.3574 EBF       23 Mar 2012
                 11.0.1.2794 EBF       18 Apr 2012

Solaris x64      12.0.1.3523 EBF       15 Dec 2011
                 11.0.1.2753 EBF       13 Feb 2012

Windows x86/x64  12.0.1.3726 EBF ***   04 May 2012 ***
                 11.0.1.2803 EBF ***   03 May 2012 ***
[Download EBFs here]