Sunday, July 23, 2017

Characteristic Errors, Revision 6

A characteristic error is a mistake so easy to make it appears you're actively encouraged to make it by the very nature of the software you're using.

Here's the latest entry...

  1. SQL Anywhere: Forgetting to code AUTOSTOP OFF on a START DATABASE statement, then wondering why the database immediately stopped after starting.
Here's the full list...
  1. SQL: Seeing too little data, or no data at all, because a predicate in the WHERE clause effectively turned your OUTER JOIN into an INNER JOIN.

  2. SQL: Seeing too much data because a missing predicate in the WHERE clause effectively turned your INNER JOIN into a CROSS JOIN.

  3. SQL: Getting the wrong COUNT() or SUM() because you forgot to code WHERE ... IS NOT NULL, or you *did* code it when you shouldn't have.

  4. SQL: Getting the wrong answer because you forgot that, in general, NULL values [cough] suck.

  5. SQL Anywhere: Not seeing MESSAGE output because you forgot to run SET TEMPORARY OPTION DEBUG_MESSAGES = 'ON';

  6. SQL Anywhere: Not seeing any data because you forgot ON COMMIT PRESERVE ROWS or NOT TRANSACTIONAL.

  7. SQL Anywhere: Coding ENDIF where END IF was required, or vice versa (before Version 11).

  8. SQL Anywhere: Connecting to the wrong server because you forgot DOBROAD=NONE (before Version 12).

  9. SQL Anywhere: Forgetting the asterisk in SELECT TOP 10 FROM ...

  10. SQL Anywhere: Coding IF NOT VAREXISTS ( 'x' ) THEN ... instead of IF VAREXISTS ( 'x' ) = 0 THEN ...

  11. SQL Anywhere: Coding the wrong magic numbers 1, 2, 3, ... in the get_value() and set_value() calls in an EXTERNAL C DLL function.

  12. SQL Anywhere: Getting proxy table ODBC errors because the engine's running as a service and you've set up a User DSN instead of System DSN.

  13. SQL Anywhere: Getting file-related errors because the file specifications are relative to the server rather than the client.

  14. SQL Anywhere: Getting file-related errors because the engine's running as a service without the necessary permissions.

  15. SQL Anywhere: Coding CREATE TRIGGER IF NOT EXISTS instead of CREATE OR REPLACE TRIGGER, or vice versa for CREATE TABLE (in 11.0.1 or later).

  16. SQL Anywhere: Getting integer arithmetic when you wanted fractional parts because you forgot to CAST.

  17. Stored procedure debugger: Setting it to watch a specific user id other than the one you're using to test your code.

  18. Sybase Central: Setting it to display objects for owner names other than the one you're interested in.

  19. Copy and paste: Forgetting to edit after pasting; e.g., Copy and paste SET @continue = 'Y' into the body of a WHILE loop and then forgetting to change it to 'N'.

  20. MobiLink: Forgetting to call ml_add_column for any of the columns you're trying to synchronize, thus guaranteeing yourself a "Sassen Frassen Fricken Fracken!" moment when you run the first test.

  21. MobiLink: Forgetting to call ml_add_[various] with the NULL parameter to delete old ml_[whatever] rows, thus ending up with thousands of orphan system table rows in the consolidated database.

  22. OLAP Windowing: Coding the wrong combination of ASC and DESC in an inner OVER ORDER BY clause and the outer SELECT ORDER BY: different when they should be the same, the same when they should be different, or some other variation of "wrong combination"...
                SELECT older_sample_set.sample_set_number
                  INTO @20_older_sample_set_number
                  FROM ( SELECT TOP 20
                                ROW_NUMBER() OVER ( ORDER BY rroad_sample_set.sample_set_number ASC ) AS scrolling_row_number,
                                rroad_sample_set.sample_set_number                                    AS sample_set_number
                           FROM rroad_sample_set
                          WHERE rroad_sample_set.sampling_id       = @sampling_id
                            AND rroad_sample_set.sample_set_number < @sample_set_number
                          ORDER BY rroad_sample_set.sample_set_number DESC ) AS older_sample_set
                 WHERE older_sample_set.scrolling_row_number = 20;

  23. MobiLink: Forgetting to call ml_add_column() when trying to use named parameters instead of "?" in versions 10 and 11 MobiLink scripts, resulting in a "What the ... ? Sassen Frassen Fricken Fracken!" moment during the first test (thank you, Jeff Albion).

  24. SQL: Omitting a PRIMARY KEY column from the WHERE clause, thus turning a singleton SELECT (or DELETE!) into something rather more enthusiastic than expected (thank you, Ron Hiner).

  25. HTTP web services: Leaving an & in the code when a ? is required, and vice versa, when editing service URLs; e.g., 'HTTP://localhost:12345/web_service&service_parm2=!parm2'

  26. SQL Anywhere: Forgetting that not all functions look like functions: SELECT CAST ( CURRENT TIMESTAMP, VARCHAR )

  27. Batch file: Trailing spaces on SET commands; e.g., SELECT CAST ( xp_getenv ( 'DEBUG_MESSAGES' ) AS VARCHAR ) returns 'OFF ' instead of 'OFF' after SET DEBUG_MESSAGES=OFF

  28. Forum: Clicking Reply on the main Question or Answer entry instead of the comment you wanted.

  29. SQL Anywhere: Forgetting to run dblog to tell the database file where the log is now, after moving the database and log files to a different folder (thank you, Justin Willey).

  30. SQL Anywhere: Having to look up WAIT in the Help ... every ... single ... time, to be reminded that's it's WAITFOR, not WAIT.

  31. SQL: Forgetting to check the SELECT against the GROUP BY, resulting in "Function or column reference to ... must also appear in a GROUP BY" (thank you, Glenn Paulley).

  32. SQL: Coding too much in the GROUP BY (like, say, the primary key) so every group contains but a single row (thank you, Glenn Paulley).

  33. Design: Forgetting to accomodate or prevent loops in a tree structure, resulting in a tree traversal process that pegs the CPU at 100%... forever (thank you, Ove B).

  34. MobiLink: Unwittingly using a variety of user ids when running sync*.sql, updating MobiLink scripts and running the MobiLink server, resulting in inexplicable inconsistencies.

  35. MobiLink: Accidentally creating multiple script versions and then getting them crossed up when updating MobiLink scripts and running the MobiLink client.

  36. SQL Anywhere: Forgetting to run the 32-bit version of SQL Anywhere when working with Excel proxy tables.

  37. ODBC Administrator: Running the 64-bit version (huh?) of odbcad32.exe (say what?) when you need 32-bit version at C:\WINDOWS\SysWOW64\odbcad32.exe (oh, fer #*@&!!!)

  38. ODBC Administrator: Forgetting to click OK ... twice ... to actually save your new ODBC DSN after celebrating your success with Test Connection.

  39. ODBC Administrator: Setting up an ODBC DSN on the wrong computer: "It goes with the client!" ... but sometimes it's not obvious where the client is actually located.

  40. Security: Forgetting which Windows user id you're using on which system, then spending too much time with Windows menus, firewall software and Google searches before the "Doh!" moment.

  41. SQL: Getting an exception that is not only completely inexplicable, but absolutely impossible for the statement that raised it... until you think to look inside the triggers.

  42. SQL Anywhere: Getting an exception because a FOR loop variable has a scope conflict with a column name, or worse, NOT getting an exception, just a wrong result.

  43. SQL: Forgetting the comma between two columns in SELECT list, thus turning the second column name into a profoundly misleading alias name for the first column.

  44. SQL Anywhere: Coding SET OPTION instead of SET TEMPORARY OPTION, then wondering where the commit came from.

  45. SQL: Not bothering to check that you have the same number of columns and arguments in an INSERT statement and then wondering why you have an error (thank you, Justin Willey).

  46. SQL: Forgetting to omit your autoincrement primary key from your INSERT column name list (thank you, Justin Willey).

  47. Foxhound: Changing the "Default" Monitor option settings, then expecting them to apply to an existing target database.

  48. Foxhound: Creating two separate Foxhound Monitor sessions for the same actual target database, perhaps one using a DSN and the other a DSN-less connection string.

  49. SQL Anywhere: Forgetting to code AUTOSTOP OFF on a START DATABASE statement, then wondering why the database immediately stopped after starting.



Tuesday, July 11, 2017

Billion-Row Tables

Here's the good news, and the bad news, all on one line:


Foxhound fails when a single table hits one billion rows.

The bad news, it's a bug in Foxhound:

The Display Schema feature shows Value out of range for destination because some intermediate calculations use DECIMAL ( 11, 2 ) to hold the row count for indivdual tables.

The good news is

SQL Anywhere is being used to hold billion-row tables!

That's billion rows, not bytes.

And the problem was first reported for SQL Anywhere 9 which has been around longer than Facebook.

The Display Schema side of Foxhound isn't exactly popular, it's the Foxhound Monitor folks want. Nevertheless, Display Schema does have its fans:
Question: Do you like the Display Schema feature? If so, I can create a patch for you.

Answer: "Yes, it's a life saver being that I'm in the middle of converting from ASA9 to ASA17.

It gives me quick view of database information to compare each database stat from before unload and after reload."
Innocent Ekhelar
Dir. Network Services
LOG-NET, Inc.
More good news, a fix is available for Foxhound - click "Show Patches" and read about "Patch 4".
"It works perfectly!!"
Innocent Ekhelar

Saturday, March 25, 2017

Extending Foxhound, Part 3: Web Service

This article is the third in a series about extending Foxhound with adhoc queries:

  • The first article showed how to run adhoc queries in ISQL to simulate a single Monitor dashboard tab,

  • the second article showed how to use proxy tables to combine data from multiple Foxhound databases into one display, and

  • this article shows how to write a web service to show the results in a web browser like Chrome or, in this case, Vivaldi...

The first step is to enable SQL Anywhere's built-in HTTP server with the dbsrv17 -xs option:
"%SQLANY17%\bin64\dbspawn.exe"^
  -f "%SQLANY17%\bin64\dbsrv17.exe"^
  -o dbsrv17_log_dashboard17.txt^
  -x tcpip^
  -xs http(port=12345)^
  dashboard17.db 
Tip: This is a separate SQL Anywhere 17 database, created by you, that is different from any of the Foxhound databases, and different from any of your target databases being monitored by Foxhound. It is the same database as the one created in Step 1 of the previous article, except for the dbsrv17 -xs option which turns on HTTP processing.
The second step is to use the CREATE SERVICE statement to set up a web service in SQL Anywhere that calls a procedure:
CREATE SERVICE dashboard
   TYPE 'RAW' AUTHORIZATION OFF URL ON USER DBA
   AS CALL dashboard ( :refresh_count );
Tip: Don't get the CREATE SERVICE statement confused with CREATE SERVER. The CREATE SERVICE statement creates a web service in the local database whereas CREATE SERVER creates a pointer to a remote server, and both are used in this article.
The third step is to create a procedure that builds the HTML text in a single LONG VARCHAR string and returns that string to the browser when the service calls the procedure:
  • The "Refresh count:" display field is implemented by
    • the @in_refresh_count parameter defined on line 2 below
    • which is updated by the code on lines 12 through 18,
    • passed to the next (automatic) execution of the web service by the META HTTP-EQUIV="refresh" tag on line 42 and
    • displayed in the browser window on line 58.

  • The code on lines 20 through 127 is a rewrite of the code in Step 5: Query Data In Local Tables in the previous article.

  • The call on line 32 uses a whole whackload of code from the previous article, which you can see at the bottom of this article in the Supporting Code appendices.

  • The long LIST ( STRING ( ... calls starting on lines 73 and 107 turn the result sets from Step 5 into strings of HTML text.

  • The SELECT starting on line 39 fills the local variable @result with HTML text built from data retrieved from the "Summary List Of Target Databases" table.

  • The SELECT starting on line 95 appends more HTML text build from the "Active Alerts For Each Target Database" table to @result and returns the whole thing to the caller...

  • ...which is the CREATE SERVICE statement, which is how SQL Anywhere's HTTP server gets the HTML and returns it to the browser.
CREATE PROCEDURE dashboard (
   IN @in_refresh_count  LONG VARCHAR )
RESULT ( html_string LONG VARCHAR )
BEGIN

DECLARE @refresh_count   INTEGER;
DECLARE @result          LONG VARCHAR;

---------------------------------------------------------------------------------------- 
-- Initialize or increment the refresh count to pass to the next execution.

IF ISNUMERIC ( COALESCE ( @in_refresh_count, '0' ) ) = 1 THEN
   SET @refresh_count = CAST ( COALESCE ( @in_refresh_count, '0' ) AS INTEGER );
ELSE
   SET @refresh_count = 0;
END IF;

SET @refresh_count = @refresh_count + 1;

---------------------------------------------------------------------------------------- 
-- Fill in the list of remote Foxhound server names.

TRUNCATE TABLE foxhound_server_list;
INSERT foxhound_server_list VALUES ( 'Foxhound4' );
INSERT foxhound_server_list VALUES ( 'Foxhound4b' );
INSERT foxhound_server_list VALUES ( 'Foxhound4c' );
COMMIT;

---------------------------------------------------------------------------------------- 
-- Fill "Summary List Of Target Databases" and "Active Alerts For Each Target Database".

CALL refresh_dashboard_data();

---------------------------------------------------------------------------------------- 
-- Build part of the return HTML.

CALL dbo.sa_set_http_header( 'Content-Type', 'text/html' );

SELECT STRING ( 
   '<HTML>',
   '<HEAD>',
   '<META HTTP-EQUIV="refresh" CONTENT="10; URL=dashboard?refresh_count=', @refresh_count, '">',
   '<TITLE>Foxhound Dashboard</TITLE>',
   '<STYLE>',
      'BODY { margin: 0; padding: 0; font-family: "VERDANA", "ARIAL", "HELVETICA", "SANS-SERIF"; 
              font-size: 100%; }',
      'IMG { border: 0; margin: 0; }',
      'INPUT { font-family: "VERDANA", "ARIAL", "HELVETICA", "SANS-SERIF"; font-size: 1em; }',
      'P { font-family: "VERDANA", "ARIAL", "HELVETICA", "SANS-SERIF"; font-size: 1em; }',
      'TABLE { margin: 0; padding: 0; }',
      'TD { margin: 0; padding: 0 0 0 0.6em; vertical-align: bottom; 
            font-family: "VERDANA", "ARIAL", "HELVETICA", "SANS-SERIF"; font-size: 1em; }',
      'TR { margin: 0; padding: 0; }',
   '</STYLE>',
   '</HEAD>',
   '<BODY>',
   '<P STYLE="padding-left: 0.6em;">',
   'Refresh count: ', @refresh_count,
   '<P>',
   '<TABLE>',
   '<TR>',
   '<TD STYLE="text-align: center;"><B>Foxhound<BR />Server</B></TD>',
   '<TD STYLE="text-align: center;"><B>ID</B></TD>',
   '<TD STYLE="text-align: center;"><B>Target Database</B></TD>',
   '<TD STYLE="text-align: center;"><B>Monitor Status</B></TD>',
   '<TD STYLE="text-align: center;"><B>Active<BR />Alerts</B></TD>',
   '<TD STYLE="text-align: center;"><B>Heartbeat</B></TD>',
   '<TD STYLE="text-align: center;"><B>Unsch<BR />Req</B></TD>',
   '<TD STYLE="text-align: center;"><B>Conns</B></TD>',
   '<TD STYLE="text-align: center;"><B>Blocked<BR />Conns</B></TD>',
   '<TD STYLE="text-align: center;"><B>CPU Time</B></TD>',
   '</TR>',
   LIST ( STRING ( 
      '<TR>',
      '<TD STYLE="text-align: left;">',   "Summary List Of Target Databases"."Foxhound Server", '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases"."ID",              '</TD>',
      '<TD STYLE="text-align: left;">',   "Summary List Of Target Databases"."Target Database", '</TD>',
      '<TD STYLE="text-align: left;">',   "Summary List Of Target Databases"."Monitor Status",  '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases"."Active Alerts",   '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases".Heartbeat,         '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases"."Unsch Req",       '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases".Conns,             '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases".Blocked,           '</TD>',
      '<TD STYLE="text-align: center;">', "Summary List Of Target Databases"."CPU Time",        '</TD>',
      '</TR>' ),
      '' -- empty LIST row delimiter
      ORDER BY "Target Database", "ID" ),
   '</TABLE>' )
  INTO @result
  FROM "Summary List Of Target Databases";

---------------------------------------------------------------------------------------- 
-- Finish building the HTML page and return it to the browser.

SELECT STRING ( 
   @result,
   '<P>',
   '<TABLE>',
   '<TR>',
   '<TD STYLE="text-align: center;"><B>Foxhound<BR />Server</B></TD>',
   '<TD STYLE="text-align: center;"><B>ID</B></TD>',
   '<TD STYLE="text-align: center;"><B>Target Database</B></TD>',
   '<TD STYLE="text-align: center;"><B>Time Since<BR />Alert Recorded</B></TD>',
   '<TD STYLE="text-align: center;"><B>Active<BR />Alert #,</B></TD>',
   '<TD STYLE="text-align: left;"  ><B>Description</B></TD>',
   '</TR>',
   LIST ( STRING ( 
      '<TR>',
      '<TD STYLE="text-align: left;">',
         "Active Alerts For Each Target Database"."Foxhound Server", '</TD>',
      '<TD STYLE="text-align: center;">',
         "Active Alerts For Each Target Database"."ID", '</TD>',
      '<TD STYLE="text-align: left;">',
         "Active Alerts For Each Target Database"."Target Database", '</TD>',
      '<TD STYLE="text-align: center;">',
         "Active Alerts For Each Target Database"."Time Since Alert Recorded", '</TD>',
      '<TD STYLE="text-align: right;">',
         "Active Alerts For Each Target Database"."Alert #", '</TD>',
      '<TD STYLE="text-align: left;" NOWRAP>',
         "Active Alerts For Each Target Database"."Alert Description", '</TD>',
      '</TR>' ),
      '' -- empty LIST row delimiter
      ORDER BY "Target Database", "ID", "Alert #" ),
   '</TABLE>',
   '</BODY>',
   '</HTML>' )
  FROM "Active Alerts For Each Target Database";

END;

Here's the URL for launching the web service:
http://localhost:12345/dashboard

Supporting Code

The following appendices show the code described in the previous article and used here.

Appendix 1: Create Remote Server And Proxy Tables

CREATE SERVER Foxhound_server CLASS 'SAODBC' 
   USING 'DRIVER=SQL Anywhere Native; ENG=Foxhound4; DBN=f; UID=ADHOC; PWD=SQL;';

CREATE EXISTING TABLE sampling_options AT 'Foxhound_server...sampling_options';
CREATE EXISTING TABLE sample_detail    AT 'Foxhound_server...sample_detail';
CREATE EXISTING TABLE alert_union      AT 'Foxhound_server...alert_union';

CREATE FUNCTION rroad_f_msecs_as_abbreviated_d_h_m_s_ms
   ( IN @msecs   INTEGER )
   RETURNS VARCHAR ( 20 )
   AT 'Foxhound_server...rroad_f_msecs_as_abbreviated_d_h_m_s_ms';

Appendix 2: Create Local Views

CREATE VIEW v_latest_primary_key AS 
   SELECT sample_detail.sampling_id                           AS sampling_id,
          MAX ( sample_detail.sample_set_number )             AS sample_set_number
     FROM sample_detail
    GROUP BY sample_detail.sampling_id;

CREATE VIEW v_sample_detail AS
   SELECT sample_detail.*
     FROM sample_detail
             INNER JOIN v_latest_primary_key
                     ON v_latest_primary_key.sampling_id       = sample_detail.sampling_id
                    AND v_latest_primary_key.sample_set_number = sample_detail.sample_set_number;

CREATE VIEW v_active_alerts AS
   SELECT alert_union.sampling_id                             AS sampling_id,
          LIST ( DISTINCT STRING ( 
                     '#',  
                     alert_union.alert_number ),
                 ', '
                 ORDER BY alert_union.alert_number )          AS active_alert_number_list
    FROM alert_union
   WHERE alert_union.record_type                 = 'Alert'
     AND alert_union.alert_is_clear_or_cancelled = 'N'
    GROUP BY alert_union.sampling_id;

CREATE VIEW "vSummary List Of Target Databases" AS 
SELECT sampling_options.sampling_id                                AS "ID",
       STRING ( 
          sampling_options.selected_name,
          IF sampling_options.selected_tab = '1'
             THEN '(DSN)' 
             ELSE '' 
          END IF )                                                 AS "Target Database",
       sampling_options.connection_status_message                  AS "Monitor Status",
       COALESCE ( v_active_alerts.active_alert_number_list, '-' )  AS "Active Alerts",
       IF  sampling_options.sampling_should_be_running = 'Y' 
       AND sampling_options.connection_status_message  = 'Sampling OK'
          THEN rroad_f_msecs_as_abbreviated_d_h_m_s_ms ( 
                 v_sample_detail.canarian_query_elapsed_msec ) 
          ELSE '-'
       ENDIF                                                       AS "Heartbeat",
       IF COALESCE ( v_sample_detail.UnschReq, 0 ) = 0
          THEN '-'
          ELSE STRING ( v_sample_detail.UnschReq )
       ENDIF                                                       AS "Unsch Req",
       IF COALESCE ( v_sample_detail.ConnCount, 0 ) = 0
          THEN '-'
          ELSE STRING ( v_sample_detail.ConnCount )
       ENDIF                                                       AS "Conns",
       IF COALESCE ( v_sample_detail.total_blocked_connection_count, 0 ) = 0
          THEN '-'
          ELSE STRING ( 
             v_sample_detail.total_blocked_connection_count )
       ENDIF                                                       AS "Blocked",
       CASE
          WHEN COALESCE ( v_sample_detail.interval_CPU_percent, 0.0 ) = 0.0
             THEN '-'
          ELSE STRING ( ROUND ( 
             v_sample_detail.interval_CPU_percent, 1 ), '%' )
       END                                                         AS "CPU Time"
  FROM sampling_options
          LEFT OUTER JOIN v_sample_detail
                       ON v_sample_detail.sampling_id = sampling_options.sampling_id
          LEFT OUTER JOIN v_active_alerts
                       ON v_active_alerts.sampling_id = sampling_options.sampling_id;

CREATE VIEW "vActive Alerts For Each Target Database" AS 
SELECT sampling_options.sampling_id                 AS "ID",
       STRING ( 
          sampling_options.selected_name,
          IF sampling_options.selected_tab = '1'
             THEN '(DSN)' 
             ELSE '' 
          END IF )                                  AS "Target Database",
       rroad_f_msecs_as_abbreviated_d_h_m_s_ms ( 
          DATEDIFF ( MILLISECOND, 
                     alert_union.recorded_at, 
                     CURRENT TIMESTAMP ) )          AS "Time Since Alert Recorded",
       alert_union.alert_number                     AS "Alert #",
       alert_union.alert_description                AS "Alert Description"
  FROM sampling_options
          INNER JOIN alert_union
                  ON alert_union.sampling_id = sampling_options.sampling_id
 WHERE alert_union.record_type                 = 'Alert'
   AND alert_union.alert_is_clear_or_cancelled = 'N';

Appendix 3: Create Local Permanent Tables

CREATE TABLE "Summary List Of Target Databases" (
   "Foxhound Server"  VARCHAR ( 128 )   NOT NULL,
   "ID"               UNSIGNED INT      NOT NULL,
   "Target Database"  VARCHAR ( 133 )   NOT NULL,   
   "Monitor Status"   VARCHAR ( 32767 ) NOT NULL,   
   "Active Alerts"    LONG VARCHAR      NOT NULL, 
   Heartbeat          VARCHAR ( 20 )    NOT NULL,   
   "Unsch Req"        VARCHAR ( 21 )    NOT NULL,   
   Conns              VARCHAR ( 21 )    NOT NULL,   
   Blocked            VARCHAR ( 21 )    NOT NULL,   
   "CPU Time"         VARCHAR ( 34 )    NOT NULL,
   PRIMARY KEY ( "Foxhound Server", "ID" ) );

CREATE TABLE "Active Alerts For Each Target Database" (
   "Foxhound Server"            VARCHAR ( 128 )   NOT NULL,
   "ID"                         UNSIGNED INT      NOT NULL,
   "Target Database"            VARCHAR ( 133 )   NOT NULL,   
   "Time Since Alert Recorded"  VARCHAR ( 20 )    NOT NULL,   
   "Alert #"                    INTEGER           NOT NULL,
   "Alert Description"          LONG VARCHAR      NOT NULL,  
   PRIMARY KEY ( "Foxhound Server", "ID", "Alert #" ) );

CREATE TABLE foxhound_server_list (
   foxhound_server  VARCHAR ( 128 )   NOT NULL PRIMARY KEY );

Appendix 4: CREATE PROCEDURE refresh_dashboard_data

CREATE PROCEDURE refresh_dashboard_data()
BEGIN

TRUNCATE TABLE "Summary List Of Target Databases";

TRUNCATE TABLE "Active Alerts For Each Target Database";

FOR f_server AS c_server INSENSITIVE CURSOR FOR
SELECT foxhound_server AS @foxhound_server
  FROM foxhound_server_list
 ORDER BY foxhound_server
FOR READ ONLY
DO

   DROP REMOTE CONNECTION TO Foxhound_server CLOSE ALL;

   ALTER SERVER Foxhound_server 
      USING 'DRIVER=SQL Anywhere Native; ENG={@foxhound_server}; DBN=f; UID=ADHOC; PWD=SQL;';

   INSERT "Summary List Of Target Databases" 
   SELECT @foxhound_server,
          *
     FROM "vSummary List Of Target Databases";

   INSERT "Active Alerts for each target database" 
   SELECT @foxhound_server,
          *
     FROM "vActive Alerts for each target database";

   COMMIT;

END FOR;

END;


Saturday, March 18, 2017

Extending Foxhound, Part 2: Proxy Tables

In theory, a single copy of the Foxhound Extended Edition can monitor up to 100 target databases, each with an unlimited number of connections, but in reality multiple copies of Foxhound are often required to handle a large number of heavily-loaded target databases.

What you end up with, after following the instructions in Starting Multiple Copies of Foxhound, is a different browser window for each copy of Foxhound. Here's what that looks like for three copies of Foxhound monitoring a total of 31 target databases with 973 connections:



The previous article in this series showed how to code adhoc queries that simulate a single Monitor dashboard tab; this article shows how to code queries that combine multiple dashboards into one.

Result Set 1: Summary List Of All Target Databases

Here's what the result set looks like for three copies of Foxhound in one combined "Summary List":


Result Set 2: Active Alerts For All Target Databases

Here's what the combined "Active Alerts" result set looks like for three copies of Foxhound:



Since the Foxhound shortcut "Adhoc Query Foxhound Database via ISQL" can only connect to one Foxhound database at a time, and the result sets shown above require data from three different Foxhound databases, a different mechanism is required.

Remote Data Access

One solution is to create a separate SQL Anywhere database and use the Remote Data Access feature (also known as "remote servers" and "proxy tables") to gather data from all three Foxhound databases in one place.

Here's how the solution works:
  1. One proxy table is created in the new database for each of Foxhound adhoc views that were used by the original queries: sampling_options, sample_detail and alert_union.

  2. Two local views are created to gather the data from the proxy tables; these local views look almost identical to the original queries.

  3. Two local permanent tables are created to store the data gathered by the local views.

  4. A SQL FOR loop is executed to switch the proxy table definitions to point to each of the three Foxhound databases in turn, and to gather data from the two local views and store it in the local tables.

  5. Two local queries are written to display the local table data as shown earlier in this article: Result Set 1: Summary List Of All Target Databases and Result Set 2: Active Alerts For All Target Databases.

Step 1: Create Database And Proxy Tables

Here are the Windows commands to create and start a new database and launch ISQL:
"%SQLANY17%\bin64\dbinit.exe"^
  -dba dba,sql^
  -mpl 3^
  dashboard17.db

"%SQLANY17%\bin64\dbspawn.exe"^
  -f "%SQLANY17%\bin64\dbsrv17.exe"^
  -o dbsrv17_log_dashboard17.txt^
  -x tcpip^
  dashboard17.db 

"%SQLANY17%\bin64\dbisql.com"^
  -c "ENG=dashboard17; DBN=dashboard17; UID=dba; PWD=sql; CON=dashboard17-1"
...and here are the SQL statements to set up the proxy tables:
CREATE SERVER Foxhound_server CLASS 'SAODBC' 
   USING 'DRIVER=SQL Anywhere Native; ENG=Foxhound4; DBN=f; UID=ADHOC; PWD=SQL;';

CREATE EXISTING TABLE sampling_options AT 'Foxhound_server...sampling_options';
CREATE EXISTING TABLE sample_detail    AT 'Foxhound_server...sample_detail';
CREATE EXISTING TABLE alert_union      AT 'Foxhound_server...alert_union';

CREATE FUNCTION rroad_f_msecs_as_abbreviated_d_h_m_s_ms
   ( IN @msecs   INTEGER )
   RETURNS VARCHAR ( 20 )
   AT 'Foxhound_server...rroad_f_msecs_as_abbreviated_d_h_m_s_ms';
  • The CREATE SERVER statement on lines 1 and 2 specifies the remote server name (Foxhound_server) and connection string (the USING clause) that will be used to retrieve data from the Foxhound databases.

  • The three CREATE EXISTING TABLE statements on lines 4, 5 and 6 create proxy tables (schema but no data) in the local database.

  • Each proxy table corresponds to one Foxhound adhoc schema view in the Foxhound database: sampling_options, sample_detail and alert_union (yes, a proxy table can point to a view in the remote database).

  • The CREATE FUNCTION statement on lines 8 through 11 makes the internal Foxhound function rroad_f_msecs_as_abbreviated_d_h_m_s_ms available on a "remote procedure call" basis for proxy table queries.

  • Tip: The code shown here uses SQL Anywhere 17 but SQL Anywhere 16 will work just fine.

  • Caution: A "Count field incorrect" bug in both SQL Anywhere 16 and 17 prevented the CREATE FUNCTION statement on lines 8 through 11 from working properly. That bug was fixed in 16.0.0.2342, 17.0.4.2177 and later builds.

Step 2: Create Local Views

The previous article in this series showed a single SELECT statement for Query 1: Summary List Of Target Databases. That SELECT has been recoded as four separate CREATE VIEW statements, with only minor changes required:
CREATE VIEW v_latest_primary_key AS 
   SELECT sample_detail.sampling_id                           AS sampling_id,
          MAX ( sample_detail.sample_set_number )             AS sample_set_number
     FROM sample_detail
    GROUP BY sample_detail.sampling_id;

CREATE VIEW v_sample_detail AS
   SELECT sample_detail.*
     FROM sample_detail
             INNER JOIN v_latest_primary_key
                     ON v_latest_primary_key.sampling_id       = sample_detail.sampling_id
                    AND v_latest_primary_key.sample_set_number = sample_detail.sample_set_number;

CREATE VIEW v_active_alerts AS
   SELECT alert_union.sampling_id                             AS sampling_id,
          LIST ( DISTINCT STRING ( 
                     '#',  
                     alert_union.alert_number ),
                 ', '
                 ORDER BY alert_union.alert_number )          AS active_alert_number_list
    FROM alert_union
   WHERE alert_union.record_type                 = 'Alert'
     AND alert_union.alert_is_clear_or_cancelled = 'N'
    GROUP BY alert_union.sampling_id;

CREATE VIEW "vSummary List Of Target Databases" AS 
SELECT sampling_options.sampling_id                                AS "ID",
       STRING ( 
          sampling_options.selected_name,
          IF sampling_options.selected_tab = '1'
             THEN '(DSN)' 
             ELSE '' 
          END IF )                                                 AS "Target Database",
       sampling_options.connection_status_message                  AS "Monitor Status",
       COALESCE ( v_active_alerts.active_alert_number_list, '-' )  AS "Active Alerts",
       IF  sampling_options.sampling_should_be_running = 'Y' 
       AND sampling_options.connection_status_message  = 'Sampling OK'
          THEN rroad_f_msecs_as_abbreviated_d_h_m_s_ms ( 
                 v_sample_detail.canarian_query_elapsed_msec ) 
          ELSE '-'
       ENDIF                                                       AS "Heartbeat",
       IF COALESCE ( v_sample_detail.UnschReq, 0 ) = 0
          THEN '-'
          ELSE STRING ( v_sample_detail.UnschReq )
       ENDIF                                                       AS "Unsch Req",
       IF COALESCE ( v_sample_detail.ConnCount, 0 ) = 0
          THEN '-'
          ELSE STRING ( v_sample_detail.ConnCount )
       ENDIF                                                       AS "Conns",
       IF COALESCE ( v_sample_detail.total_blocked_connection_count, 0 ) = 0
          THEN '-'
          ELSE STRING ( 
             v_sample_detail.total_blocked_connection_count )
       ENDIF                                                       AS "Blocked",
       CASE
          WHEN COALESCE ( v_sample_detail.interval_CPU_percent, 0.0 ) = 0.0
             THEN '-'
          ELSE STRING ( ROUND ( 
             v_sample_detail.interval_CPU_percent, 1 ), '%' )
       END                                                         AS "CPU Time"
  FROM sampling_options
          LEFT OUTER JOIN v_sample_detail
                       ON v_sample_detail.sampling_id = sampling_options.sampling_id
          LEFT OUTER JOIN v_active_alerts
                       ON v_active_alerts.sampling_id = sampling_options.sampling_id;
The previous article in this series showed a single SELECT statement for Query 2: Active Alerts For Each Target Database. That SELECT has been recoded as a single CREATE VIEW statement which looks almost exactly the same:
CREATE VIEW "vActive Alerts For Each Target Database" AS 
SELECT sampling_options.sampling_id                 AS "ID",
       STRING ( 
          sampling_options.selected_name,
          IF sampling_options.selected_tab = '1'
             THEN '(DSN)' 
             ELSE '' 
          END IF )                                  AS "Target Database",
       rroad_f_msecs_as_abbreviated_d_h_m_s_ms ( 
          DATEDIFF ( MILLISECOND, 
                     alert_union.recorded_at, 
                     CURRENT TIMESTAMP ) )          AS "Time Since Alert Recorded",
       alert_union.alert_number                     AS "Alert #",
       alert_union.alert_description                AS "Alert Description"
  FROM sampling_options
          INNER JOIN alert_union
                  ON alert_union.sampling_id = sampling_options.sampling_id
 WHERE alert_union.record_type                 = 'Alert'
   AND alert_union.alert_is_clear_or_cancelled = 'N';

Step 3: Create Local Permanent Tables

These two local tables look exactly like the views in Step 2; same column names and same data types:
CREATE TABLE "Summary List Of Target Databases" (
   "Foxhound Server"  VARCHAR ( 128 )   NOT NULL,
   "ID"               UNSIGNED INT      NOT NULL,
   "Target Database"  VARCHAR ( 133 )   NOT NULL,   
   "Monitor Status"   VARCHAR ( 32767 ) NOT NULL,   
   "Active Alerts"    LONG VARCHAR      NOT NULL, 
   Heartbeat          VARCHAR ( 20 )    NOT NULL,   
   "Unsch Req"        VARCHAR ( 21 )    NOT NULL,   
   Conns              VARCHAR ( 21 )    NOT NULL,   
   Blocked            VARCHAR ( 21 )    NOT NULL,   
   "CPU Time"         VARCHAR ( 34 )    NOT NULL,
   PRIMARY KEY ( "Foxhound Server", "ID" ) );

CREATE TABLE "Active Alerts For Each Target Database" (
   "Foxhound Server"            VARCHAR ( 128 )   NOT NULL,
   "ID"                         UNSIGNED INT      NOT NULL,
   "Target Database"            VARCHAR ( 133 )   NOT NULL,   
   "Time Since Alert Recorded"  VARCHAR ( 20 )    NOT NULL,   
   "Alert #"                    INTEGER           NOT NULL,
   "Alert Description"          LONG VARCHAR      NOT NULL,  
   PRIMARY KEY ( "Foxhound Server", "ID", "Alert #" ) );

Step 4: Gather Data In A FOR Loop

A stored procedure is used to gather the data; here's how it works:
  • The local permanent table defined on lines 1 and 2 is used to hold the Foxhound server names that drive the FOR statement on lines 11 through 16.

  • The DROP REMOTE CONNECTION statement on line 18 causes the local remote server to be disconnected from the previous Foxhound database.

  • The ALTER SERVER statement on lines 20 and 21 changes the remote server USING clause to point to the next Foxhound database. The special {@foxhound_server} syntax in the USING clause allows it to be dynamically modified at run time without having to code an EXECUTE IMMEDIATE statement.

  • The two INSERT SELECT statements on lines 23 through 31 copies the data from the two local views defined in Step 2 and appends it to the local permanent tables defined in Step 3.

  • Tip: Remote server connections are not opened by the CREATE SERVER and ALTER SERVER statements, but by the first statement that actually needs data from the remote server; e.g., the CREATE EXISTING TABLE and SELECT statements. This is a subtle point, but it does explain why connection errors aren't detected as soon as a remote server is created.
CREATE TABLE foxhound_server_list (
   foxhound_server  VARCHAR ( 128 )   NOT NULL PRIMARY KEY );

CREATE PROCEDURE refresh_dashboard_data()
BEGIN

TRUNCATE TABLE "Summary List Of Target Databases";

TRUNCATE TABLE "Active Alerts For Each Target Database";

FOR f_server AS c_server INSENSITIVE CURSOR FOR
SELECT foxhound_server AS @foxhound_server
  FROM foxhound_server_list
 ORDER BY foxhound_server
FOR READ ONLY
DO

   DROP REMOTE CONNECTION TO Foxhound_server CLOSE ALL;

   ALTER SERVER Foxhound_server 
      USING 'DRIVER=SQL Anywhere Native; ENG={@foxhound_server}; DBN=f; UID=ADHOC; PWD=SQL;';

   INSERT "Summary List Of Target Databases" 
   SELECT @foxhound_server,
          *
     FROM "vSummary List Of Target Databases";

   INSERT "Active Alerts for each target database" 
   SELECT @foxhound_server,
          *
     FROM "vActive Alerts for each target database";

   COMMIT;

END FOR;

END;

Step 5: Query Data In Local Tables

Here's how the the two result sets are displayed:
  • The TRUNCATE TABLE and INSERT statements on lines 1 through 6 reload the foxhound_server table with the Foxhound ENG= values that drive the FOR loop.

  • The CALL statement on line 9 runs the FOR loop, and the SELECT statements on lines 10 through 19 display the data; the primary ORDER BY column is "Target Database" which is more convenient than sorting by Foxhound server name.
TRUNCATE TABLE foxhound_server_list;

INSERT foxhound_server_list VALUES ( 'Foxhound4' );
INSERT foxhound_server_list VALUES ( 'Foxhound4b' );
INSERT foxhound_server_list VALUES ( 'Foxhound4c' );
COMMIT;

CALL refresh_dashboard_data();

SELECT * 
  FROM "Summary List Of Target Databases"
 ORDER BY "Target Database", 
       "ID";

SELECT * 
  FROM "Active Alerts for each target database"
 ORDER BY "Target Database", 
       "ID", 
       "Alert #";
The two result sets are shown earlier; see Result Set 1: Summary List Of All Target Databases and Result Set 2: Active Alerts For All Target Databases;


Sunday, March 12, 2017

Extending Foxhound, Part 1

Adhoc queries are commonly run against the Foxhound Monitor database for one of two reasons:

  1. to search historical data for performance anomalies that aren't apparent in the standard Foxhound displays, and

  2. to duplicate and enhance Foxhound features.
This article explores the second point by constructing adhoc queries that mimic the Monitor dashboard tab of the Foxhound Menu page:


Here's where the data for the top list comes from, in the screenshot above:

Query 1: Summary List Of Target Databases

Jumping ahead, here's what the custom Summary List Of Target Databases query looks like when it's run in All Programs - Foxhound4 - Tools - Adhoc Query Foxhound Database via ISQL:



The SELECT below uses a WITH clause on lines 1 through 23 to create three local views:
  • v_latest_primary_key finds the latest sample_detail row for each target database; this is a big deal since Foxhound can store many thousands of sample_detail rows for each target database.

  • v_sample_detail makes use of v_latest_primary_key to return all the columns in those latest sample_detail rows.

  • v_active_alerts uses SQL Anywhere's LIST function to gather the alert_number values for all the Alerts that aren't Cancelled or All Clear; the predicate alert_union.alert_is_clear_or_cancelled = 'N' is an prime example of the value added by Foxhound's underlying rroad_alert_union view.

  • Tip: Foxhound doesn't let you create permanent views via CREATE VIEW, but it does let you create temporary views as "common table expressions" in the WITH clause. It also lets you code temporary views as "derived tables" inside the FROM clause, but the WITH clause is sometimes easier to understand and maintain.
WITH 
   v_latest_primary_key AS 
      ( SELECT sample_detail.sampling_id                           AS sampling_id,
               MAX ( sample_detail.sample_set_number )             AS sample_set_number
          FROM sample_detail
         GROUP BY sample_detail.sampling_id ),
   v_sample_detail AS
      ( SELECT sample_detail.*
          FROM sample_detail
                  INNER JOIN v_latest_primary_key
                          ON v_latest_primary_key.sampling_id       = sample_detail.sampling_id
                         AND v_latest_primary_key.sample_set_number = sample_detail.sample_set_number ),
   v_active_alerts AS
      ( SELECT alert_union.sampling_id                             AS sampling_id,
               LIST ( DISTINCT STRING ( 
                          '#',  
                          alert_union.alert_number ),
                      ', '
                      ORDER BY alert_union.alert_number )          AS active_alert_number_list
         FROM alert_union
        WHERE alert_union.record_type                 = 'Alert'
          AND alert_union.alert_is_clear_or_cancelled = 'N'
         GROUP BY alert_union.sampling_id )
SELECT sampling_options.sampling_id                                AS "ID",
       STRING ( 
          sampling_options.selected_name,
          IF sampling_options.selected_tab = '1'
             THEN '(DSN)' 
             ELSE '' 
          END IF )                                                 AS "Target Database",
       sampling_options.connection_status_message                  AS "Monitor Status",
       COALESCE ( v_active_alerts.active_alert_number_list, '-' )  AS "Active Alerts",
       IF  sampling_options.sampling_should_be_running = 'Y' 
       AND sampling_options.connection_status_message  = 'Sampling OK'
          THEN rroad_f_msecs_as_abbreviated_d_h_m_s_ms ( 
                 v_sample_detail.canarian_query_elapsed_msec ) 
          ELSE '-'
       ENDIF                                                       AS "Heartbeat",
       IF COALESCE ( v_sample_detail.UnschReq, 0 ) = 0
          THEN '-'
          ELSE STRING ( v_sample_detail.UnschReq )
       ENDIF                                                       AS "Unsch Req",
       IF COALESCE ( v_sample_detail.ConnCount, 0 ) = 0
          THEN '-'
          ELSE STRING ( v_sample_detail.ConnCount )
       ENDIF                                                       AS "Conns",
       IF COALESCE ( v_sample_detail.total_blocked_connection_count, 0 ) = 0
          THEN '-'
          ELSE STRING ( 
             v_sample_detail.total_blocked_connection_count )
       ENDIF                                                       AS "Blocked",
       CASE
          WHEN COALESCE ( v_sample_detail.interval_CPU_percent, 0.0 ) = 0.0
             THEN '-'
          ELSE STRING ( ROUND ( 
             v_sample_detail.interval_CPU_percent, 1 ), '%' )
       END                                                         AS "CPU Time"
  FROM sampling_options
          LEFT OUTER JOIN v_sample_detail
                       ON v_sample_detail.sampling_id = sampling_options.sampling_id
          LEFT OUTER JOIN v_active_alerts
                       ON v_active_alerts.sampling_id = sampling_options.sampling_id
 ORDER BY "Target Database", 
       "ID";
The SELECT statement on lines 24 through 64 gathers columns from sampling_options, v_sample_detail and v_active_alerts; in particular:
  • The STRING function call on lines 25 through 30 determines if the sampling_options.selected_name column contains a DSN or a Foxhound connection string name.

  • The IF expression on lines 33 through 38 makes use of the Foxhound function rroad_f_msecs_as_abbreviated_d_h_m_s_ms() to display the sample_detail.canarian_query_elapsed_msec column.

Query 2: Active Alerts For Each Target Database

Here's what the ISQL output looks like for the second custom query, the one listing "Active Alerts":



Here's where the data comes from:
  • The ID and Target Database columns come from sampling_id and selected_name in the sampling_options view.

  • The Time Since Alert Recorded column is calculated from the recorded_at column in the alert_union view, using DATEDIFF(), CURRENT TIMESTAMP and the Foxhound function rroad_f_msecs_as_abbreviated_d_h_m_s_ms().

  • The Alert # and Alert Description columns come from alert_number and alert_description in the alert_union view.
SELECT sampling_options.sampling_id                 AS "ID",
       STRING ( 
          sampling_options.selected_name,
          IF sampling_options.selected_tab = '1'
             THEN '(DSN)' 
             ELSE '' 
          END IF )                                  AS "Target Database",
       rroad_f_msecs_as_abbreviated_d_h_m_s_ms ( 
          DATEDIFF ( MILLISECOND, 
                     alert_union.recorded_at, 
                     CURRENT TIMESTAMP ) )          AS "Time Since Alert Recorded",
       alert_union.alert_number                     AS "Alert #",
       alert_union.alert_description                AS "Alert Description"
  FROM sampling_options
          INNER JOIN alert_union
                  ON alert_union.sampling_id = sampling_options.sampling_id
 WHERE alert_union.record_type                 = 'Alert'
   AND alert_union.alert_is_clear_or_cancelled = 'N'
 ORDER BY "Target Database", 
       "ID", 
       "Alert #";