/** This is our pseudo-__construct, called whenever our public functions are called. */
 private static function checkDatabase()
 {
     // Have we already run?
     if (self::$checked != false) {
         return;
     }
     if (!isset(self::$db)) {
         self::$db = FreePBX::create()->Database;
     }
     // Definitions
     $create = "CREATE TABLE IF NOT EXISTS " . self::$dbname . " ( `module` CHAR(64) NOT NULL, `key` CHAR(255) NOT NULL, `val` LONGBLOB, `type` CHAR(16) DEFAULT NULL, `id` CHAR(255) DEFAULT NULL)";
     // These are limited to 50 chars as prefixes are limited to 255 chars in total (or 1000 in later versions
     // of mysql), and UTF can cause that to overflow. 50 is plenty.
     $index['index1'] = "ALTER TABLE " . self::$dbname . " ADD INDEX index1 (`key`(50))";
     $index['index3'] = "ALTER TABLE " . self::$dbname . " ADD UNIQUE INDEX index3 (`module`, `key`(50), `id`(50))";
     $index['index5'] = "ALTER TABLE " . self::$dbname . " ADD INDEX index5 (`module`, `id`(50))";
     // Check to make sure our Key/Value table exists.
     try {
         $res = self::$db->query("SELECT * FROM `" . self::$dbname . "` LIMIT 1");
     } catch (Exception $e) {
         if ($e->getCode() == "42S02") {
             // Table does not exist
             self::$db->query($create);
         } else {
             self::checkException($e);
         }
     }
     // Check for indexes.
     // TODO: This only works on MySQL
     $res = self::$db->query("SHOW INDEX FROM `" . self::$dbname . "`");
     $out = $res->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP, 2);
     foreach ($out as $i => $null) {
         // Do we not know about this index? (Are we upgrading?)
         if (!isset($index[$i])) {
             self::$db->query("ALTER TABLE " . self::$dbname . " DROP INDEX {$i}");
         }
     }
     // Now lets make sure all our indexes exist.
     foreach ($index as $i => $sql) {
         if (!isset($out[$i])) {
             self::$db->query($sql);
         }
     }
     // Add our stored procedures
     self::$dbGet = self::$db->prepare("SELECT `val`, `type` FROM `" . self::$dbname . "` WHERE `module` = :mod AND `key` = :key AND `id` = :id");
     self::$dbGetAll = self::$db->prepare("SELECT `key` FROM `" . self::$dbname . "` WHERE `module` = :mod AND `id` = :id ORDER BY `key`");
     self::$dbDel = self::$db->prepare("DELETE FROM `" . self::$dbname . "` WHERE `module` = :mod AND `key` = :key  AND `id` = :id");
     self::$dbAdd = self::$db->prepare("INSERT INTO `" . self::$dbname . "` ( `module`, `key`, `val`, `type`, `id` ) VALUES ( :mod, :key, :val, :type, :id )");
     self::$dbDelId = self::$db->prepare("DELETE FROM `" . self::$dbname . "` WHERE `module` = :mod AND `id` = :id");
     self::$dbDelMod = self::$db->prepare("DELETE FROM `" . self::$dbname . "` WHERE `module` = :mod");
     // Now this has run, everything IS JUST FINE.
     self::$checked = true;
 }