Neevo Public API
  • Namespace
  • Class
  • Tree

Namespaces

  • Neevo
    • Nette
  • None
  • PHP

Classes

  • Neevo
  • NeevoBaseStmt
  • NeevoCacheFile
  • NeevoCacheMemcache
  • NeevoCacheMemory
  • NeevoCacheSession
  • NeevoConnection
  • NeevoDriverMySQL
  • NeevoDriverMySQLi
  • NeevoDriverPgSQL
  • NeevoDriverSQLite2
  • NeevoDriverSQLite3
  • NeevoLiteral
  • NeevoLoader
  • NeevoObserverMap
  • NeevoParser
  • NeevoResult
  • NeevoResultIterator
  • NeevoRow
  • NeevoStmt

Interfaces

  • INeevoCache
  • INeevoDriver
  • INeevoObservable
  • INeevoObserver

Exceptions

  • NeevoDriverException
  • NeevoException
  • NeevoImplementationException
  1 <?php
  2 /**
  3  * Neevo - Tiny database layer for PHP. (http://neevo.smasty.net)
  4  *
  5  * This source file is subject to the MIT license that is bundled
  6  * with this package in the file license.txt.
  7  *
  8  * Copyright (c) 2011 Martin Srank (http://smasty.net)
  9  *
 10  */
 11 
 12 
 13 /**
 14  * Neevo MySQL driver (PHP extension 'mysql')
 15  *
 16  * Driver configuration:
 17  *  - host => MySQL server name or address
 18  *  - port (int) => MySQL server port
 19  *  - username
 20  *  - password
 21  *  - database => database to select
 22  *  - charset => Character encoding to set (defaults to utf8)
 23  *  - persistent (bool) => Try to find a persistent link
 24  *  - unbuffered (bool) => Sends query without fetching and buffering the result
 25  *
 26  *  - resource (type resource) => Existing MySQL link
 27  *  - lazy, table_prefix... => see NeevoConnection
 28  *
 29  * @author Martin Srank
 30  * @package Neevo\Drivers
 31  */
 32 class NeevoDriverMySQL extends NeevoParser implements INeevoDriver {
 33 
 34 
 35     /** @var resource */
 36     private $resource;
 37 
 38     /** @var bool */
 39     private $unbuffered;
 40 
 41     /** @var int */
 42     private $affectedRows;
 43 
 44 
 45     /**
 46      * Check for required PHP extension.
 47      * @return void
 48      * @throws NeevoDriverException
 49      */
 50     public function __construct(NeevoBaseStmt $statement = null){
 51         if(!extension_loaded("mysql"))
 52             throw new NeevoDriverException("Cannot instantiate Neevo MySQL driver - PHP extension 'mysql' not loaded.");
 53         if($statement instanceof NeevoBaseStmt)
 54             parent::__construct($statement);
 55     }
 56 
 57 
 58     /**
 59      * Create connection to database.
 60      * @param array $config Configuration options
 61      * @return void
 62      * @throws NeevoException
 63      */
 64     public function connect(array $config){
 65 
 66         // Defaults
 67         $defaults = array(
 68             'resource' => null,
 69             'charset' => 'utf8',
 70             'username' => ini_get('mysql.default_user'),
 71             'password' => ini_get('mysql.default_password'),
 72             'host' => ini_get('mysql.default_host'),
 73             'port' => ini_get('mysql.default_port'),
 74             'persistent' => false,
 75             'unbuffered' => false
 76         );
 77 
 78         $config += $defaults;
 79         if(isset($config['port']))
 80             $host = $config['host'] .':'. $config['port'];
 81         else
 82             $host = $config['host'];
 83 
 84         // Connect
 85         if(is_resource($config['resource']))
 86             $connection = $config['resource'];
 87         elseif($config['persistent'])
 88             $connection = @mysql_pconnect($host, $config['username'], $config['password']);
 89         else
 90             $connection = @mysql_connect($host, $config['username'], $config['password']);
 91 
 92         if(!is_resource($connection))
 93             throw new NeevoException("Connection to host '$host' failed.");
 94 
 95         // Select DB
 96         if($config['database']){
 97             $db = mysql_select_db($config['database']);
 98             if(!$db) throw new NeevoException("Could not select database '$config[database]'.");
 99         }
100 
101         $this->resource = $connection;
102 
103         //Set charset
104         if(is_resource($connection)){
105             if(function_exists('mysql_set_charset'))
106                 @mysql_set_charset($config['charset'], $connection);
107             else
108                 $this->runQuery("SET NAMES ".$config['charset']);
109         }
110 
111         $this->unbuffered = $config['unbuffered'];
112     }
113 
114 
115     /**
116      * Close the connection.
117      * @return void
118      */
119     public function closeConnection(){
120         @mysql_close($this->resource);
121     }
122 
123 
124     /**
125      * Free memory used by given result set.
126      * @param resource $resultSet
127      * @return bool
128      */
129     public function freeResultSet($resultSet){
130         return @mysql_free_result($resultSet);
131     }
132 
133 
134     /**
135      * Execute given SQL statement.
136      * @param string $queryString
137      * @return resource|bool
138      * @throws NeevoException
139      */
140     public function runQuery($queryString){
141 
142         $this->affectedRows = false;
143         if($this->unbuffered)
144             $result = @mysql_unbuffered_query($queryString, $this->resource);
145         else
146             $result = @mysql_query($queryString, $this->resource);
147 
148         $error = str_replace('You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use', 'Syntax error', @mysql_error($this->resource));
149         if($error && $result === false)
150             throw new NeevoException("Query failed. $error", @mysql_errno($this->resource), $queryString);
151 
152         $this->affectedRows = @mysql_affected_rows($this->resource);
153         return $result;
154     }
155 
156 
157     /**
158      * Begin a transaction if supported.
159      * @param string $savepoint
160      * @return void
161      */
162     public function beginTransaction($savepoint = null){
163         $this->runQuery($savepoint ? "SAVEPOINT $savepoint" : 'START TRANSACTION');
164     }
165 
166 
167     /**
168      * Commit statements in a transaction.
169      * @param string $savepoint
170      * @return void
171      */
172     public function commit($savepoint = null){
173         $this->runQuery($savepoint ? "RELEASE SAVEPOINT $savepoint" : 'COMMIT');
174     }
175 
176 
177     /**
178      * Rollback changes in a transaction.
179      * @param string $savepoint
180      * @return void
181      */
182     public function rollback($savepoint = null){
183         $this->runQuery($savepoint ? "ROLLBACK TO SAVEPOINT $savepoint" : 'ROLLBACK');
184     }
185 
186 
187     /**
188      * Fetch row from given result set as an associative array.
189      * @param resource $resultSet
190      * @return array
191      */
192     public function fetch($resultSet){
193         return @mysql_fetch_assoc($resultSet);
194     }
195 
196 
197     /**
198      * Move internal result pointer.
199      * @param resource $resultSet
200      * @param int $offset
201      * @return bool
202      * @throws NeevoDriverException
203      */
204     public function seek($resultSet, $offset){
205         if($this->unbuffered){
206             throw new NeevoDriverException('Cannot seek on unbuffered result.');
207         }
208         return @mysql_data_seek($resultSet, $offset);
209     }
210 
211 
212     /**
213      * Get the ID generated in the INSERT statement.
214      * @return int
215      */
216     public function getInsertId(){
217         return @mysql_insert_id($this->resource);
218     }
219 
220 
221     /**
222      * Randomize result order.
223      * @param NeevoBaseStmt $statement
224      * @return void
225      */
226     public function randomizeOrder(NeevoBaseStmt $statement){
227         $statement->order('RAND()');
228     }
229 
230 
231     /**
232      * Get the number of rows in the given result set.
233      * @param resource $resultSet
234      * @return int|FALSE
235      * @throws NeevoDriverException
236      */
237     public function getNumRows($resultSet){
238         if($this->unbuffered)
239             throw new NeevoDriverException('Cannot count rows on unbuffered result.');
240         return @mysql_num_rows($resultSet);
241     }
242 
243 
244     /**
245      * Get the number of affected rows in previous operation.
246      * @return int
247      */
248     public function getAffectedRows(){
249         return $this->affectedRows;
250     }
251 
252 
253     /**
254      * Escape given value.
255      * @param mixed $value
256      * @param string $type
257      * @return mixed
258      * @throws InvalidArgumentException
259      */
260     public function escape($value, $type){
261         switch($type){
262             case Neevo::BOOL:
263                 return $value ? 1 : 0;
264 
265             case Neevo::TEXT:
266                 return "'". mysql_real_escape_string($value, $this->resource) ."'";
267 
268             case Neevo::IDENTIFIER:
269                 return str_replace('`*`', '*', '`' . str_replace('.', '`.`', str_replace('`', '``', $value)) . '`');
270 
271             case Neevo::BINARY:
272                 return "_binary'" . mysql_real_escape_string($value, $this->resource) . "'";
273 
274             case Neevo::DATETIME:
275                 return ($value instanceof DateTime) ? $value->format("'Y-m-d H:i:s'") : date("'Y-m-d H:i:s'", $value);
276 
277             default:
278                 throw new InvalidArgumentException('Unsupported data type.');
279                 break;
280         }
281     }
282 
283 
284     /**
285      * Decode given value.
286      * @param mixed $value
287      * @param string $type
288      * @return mixed
289      * @throws InvalidArgumentException
290      */
291     public function unescape($value, $type){
292         if($type === Neevo::BINARY)
293             return $value;
294         throw new InvalidArgumentException('Unsupported data type.');
295     }
296 
297 
298     /**
299      * Get the PRIMARY KEY column for given table.
300      * @param string $table
301      * @return string
302      */
303     public function getPrimaryKey($table){
304         $key = '';
305         $q = $this->runQuery('SHOW FULL COLUMNS FROM '.$table);
306         while($col = $this->fetch($q)){
307             if(strtolower($col['Key']) === 'pri' && $key === '')
308                 $key = $col['Field'];
309         }
310         return $key;
311     }
312 
313 
314     /**
315      * Get types of columns in given result set.
316      * @param resource $resultSet
317      * @param string $table
318      * @return array
319      */
320     public function getColumnTypes($resultSet, $table){
321         $cols = array();
322         $count = mysql_num_fields($resultSet);
323         for($i = 0; $i < $count; $i++){
324             $field = mysql_fetch_field($resultSet, $i);
325             $cols[$field->name] = $field->type;
326         }
327         return $cols;
328     }
329 
330 
331     /*  ************  NeevoParser overrides  ************  */
332 
333 
334     /**
335      * Parse UPDATE statement.
336      * @return string
337      */
338     protected function parseUpdateStmt(){
339         $sql = parent::parseUpdateStmt();
340         return $this->applyLimit($sql . $this->clauses[3]);
341     }
342 
343 
344     /**
345      * Parse DELETE statement.
346      * @return string
347      */
348     protected function parseDeleteStmt(){
349         $sql = parent::parseDeleteStmt();
350         return $this->applyLimit($sql . $this->clauses[3]);
351     }
352 
353 
354 }
355 
Neevo Public API API documentation generated by ApiGen 2.8.0