setAttribute(\PDO::ATTR_AUTOCOMMIT, true); $pdo->setAttribute(\PDO::ATTR_CASE, \PDO::CASE_LOWER); $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); $pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC); $this->pdo = $pdo; } public function transaction(callable $fn){ $pdo = $this->pdo; if($pdo->inTransaction()){ throw new \Exception("Unable to start a new transaction"); } $transaction = new Transaction($this); if($fn($transaction) === false){ do{ $transaction->rollback(); }while($transaction->savepoint); $pdo->rollback(); }else{ $transaction->commit(); if($pdo->inTransaction()){ $pdo->commit(); } } unset($transaction); $pdo->setAttribute(\PDO::ATTR_AUTOCOMMIT, true); return $this; } public function table(string $name){ return new Table($this, $name); } public function prepare(string $statement, array $options = []){ $pdo = $this->pdo; if($pdo->getAttribute(\PDO::ATTR_DRIVER_NAME) == 'mysql'){ $options[\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY] = true; } $query = $pdo->prepare($statement); if($query === false){ throw $this->getError(); } return $query; } public function exec(string $statement){ $query = $this->prepare($statement); $count = 0; $query->execute(); while($query->fetch() !== false){ $count++; } if($count == 0){ $count = $query->rowCount(); } $query->closeCursor(); return $count; } public function query(string $statement, int $mode = null, ...$args){ $query = $this->prepare($statement); if(!is_null($mode)){ $query->setFetchMode($mode, ...$args); } $query->execute(); return $query; } public function quote(...$args){ return $this->pdo->quote(...$args); } public function beginTransaction(...$args){ return $this->pdo->beginTransaction(...$args); } public function setAttribute(...$args){ return $this->pdo->setAttribute(...$args); } public function getAttribute(...$args){ return $this->pdo->getAttribute(...$args); } public function lastInsertId(...$args){ return $this->pdo->lastInsertId(...$args); } public function getError(){ $error = $this->pdo->errorInfo(); return new \Exception($error[2], $error[1]); } public function stringFilter(array $filter = null){ $where = ''; if(!is_null($filter)){ $where = 'where '; foreach($filter as $name => $value){ $where .= "`{$name}` = {$this->quote($value)} and"; } $where = rtrim($where, ' and'); } return $where; } public function stringSet(array $data){ $sets = ''; foreach($data as $name => $value){ $sets .= "`{$name}` = {$this->quote($value)},"; } if(count($sets) > 0){ $sets = 'set '.rtrim($sets, ','); } return $sets; } } ?>