Last active
December 12, 2023 09:14
-
-
Save srcmaker/0b9155df50414019067298748c66355f to your computer and use it in GitHub Desktop.
php class to get singlton sqlite connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Manny; | |
/** | |
* SQLite Connection Manager | |
* | |
*/ | |
class Sqliter | |
{ | |
protected $sqlite = null; | |
/** | |
* @param $dbname | |
* @param $path | |
*/ | |
public function __construct($dbname,$path) | |
{ | |
$this->dbname = $dbname; | |
$this->dirpath = $path; | |
} | |
public function close() | |
{ | |
try { | |
$this->sqlite->close(); | |
$this->sqlite = null; | |
} catch (\Exception $e){ | |
$this->sqlite = null; | |
} | |
return true; | |
} | |
public function getConn(){ | |
$allowed_memory = ini_get('memory_limit'); | |
if($allowed_memory != -1){ | |
$lastChar = strtoupper(substr($allowed_memory,'-1')); | |
if(in_array($lastChar,['K','M','G'])){ | |
$allowed_memory = (int) $allowed_memory; | |
switch ($lastChar){ | |
case 'K': $allowed_memory *= 1024;break; | |
case 'M': $allowed_memory *= 1024*1024;break; | |
case 'G': $allowed_memory *= 1024*1024*1024; | |
} | |
} | |
$current_memory = memory_get_usage(true); | |
$mem_ratio = $current_memory / $allowed_memory; | |
if($mem_ratio > 0.9) throw new \Exception('REACHED_MEMORY_LIMIT'); | |
} | |
try { | |
if(is_object($this->sqlite)){ | |
$this->sqlite->query('select 1'); | |
} else { | |
$dbfile = $this->dirpath.'/'.$this->dbname.'.db'; | |
if(! is_file($dbfile)){ | |
exec('touch '.$dbfile.';chmod 777 '.$dbfile); | |
} | |
$sqlite = new \SQLite3($dbfile, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE); | |
$sqlite->enableExceptions(true); | |
$sqlite->exec('PRAGMA journal_mode =WAL;'); // FOR PERFORMANCE, CONCURRENCY | |
$this->sqlite = $sqlite; | |
} | |
return $this->sqlite; | |
} catch (\Exception $e){ | |
$this->sqlite = null; | |
time_nanosleep(0,10000000); | |
return $this->getConn(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment