_config = new WebserviceConfig(); $this->_lastErrorMessage = ""; $this->_database = null; if(!$this->_config->dataDirectory()){ $this->_lastErrorMessage = "No data directory set!"; error_log("Could not connect to the database: "+ $this->lastErrorMessage()); $this->databaseFile = null; } else{ $this->_databaseFile = $this->_config->dataDirectory() ."/siweather.sqlite"; } } function __destruct() { if(!is_null($this->_database)){ $this->close(); } } public function databaseFile() { return $this->_databaseFile; } public function lastErrorMessage() { return $this->_lastErrorMessage; } public function connect() { if(!is_null($this->_database)){ return true; } if(is_null($this->_databaseFile) || empty($this->_databaseFile)){ $this->_lastErrorMessage = "No database file given"; error_log("Could not connect to the database: "+ $this->lastErrorMessage()); return false; } try { $db = new \SQLite3($this->_databaseFile, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); } catch(\Exception $exception){ $this->_lastErrorMessage = $exception->getMessage(); error_log("Could not connect to the database: "+ $this->lastErrorMessage()); return false; } // loading SpatiaLite as an extension $extension = $this->_config->getConfig("spatialiteExtension"); if(empty($extension)){ $this->_lastErrorMessage("No spatialiteExtension set!"); error_log($this->lastErrorMessage()); return false; } if(!$db->loadExtension($extension)){ $this->_lastErrorMessage = "Could not load SpatialLite extension: ". $db->lastErrorMsg(); error_log($this->lastErrorMessage()); return false; } $this->_database = $db; return true; } public function close() { if(is_null($this->_database)){ return true; } if($this->_database->close()){ $this->_database = null; return true; } $this->_lastErrorMessage = $this->_database->lastErrorMsg(); error_log("Failed to close the database: "+ $this->lastErrorMessage()); return false; } public function exec($query) { if(is_null($this->_database)){ return false; } if(!$this->connect()){ return false; } return $this->_database->exec($query); } public function prepare($query) { if(is_null($this->_database)){ return false; } if(!$this->connect()){ return false; } return $this->_database->prepare($query); } public function versionSpatialite(){ if(is_null($this->_database)){ $this->_lastErrorMessage = "Unknown (No database connection)"; return 0; } if(!$this->connect()){ return 0; } $result = $this->_database->query("SELECT spatialite_version()"); while($row = $result->fetchArray()){ return $row[0]; } return 0; } public function versionSqlite(){ if(is_null($this->_database)){ $this->_lastErrorMessage = "Unknown (No database connection)"; return 0; } if(!$this->connect()){ return 0; } $result = $this->_database->query("SELECT sqlite_version()"); while($row = $result->fetchArray()){ return $row[0]; } return 0; } private $_database; private $_databaseFile; private $_lastErrorMessage; private $_config; } ?>