Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Utils
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • MsSqlDriver
  • MySqlDriver
  • OciDriver
  • OdbcDriver
  • PgSqlDriver
  • Sqlite2Driver
  • SqliteDriver
  • SqlsrvDriver
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Other releases
  • Nette homepage
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Database\Drivers;
  9: 
 10: use Nette;
 11: 
 12: 
 13: /**
 14:  * Supplemental MySQL database driver.
 15:  */
 16: class MySqlDriver extends Nette\Object implements Nette\Database\ISupplementalDriver
 17: {
 18:     const ERROR_ACCESS_DENIED = 1045;
 19:     const ERROR_DUPLICATE_ENTRY = 1062;
 20:     const ERROR_DATA_TRUNCATED = 1265;
 21: 
 22:     /** @var Nette\Database\Connection */
 23:     private $connection;
 24: 
 25: 
 26:     /**
 27:      * Driver options:
 28:      *   - charset => character encoding to set (default is utf8 or utf8mb4 since MySQL 5.5.3)
 29:      *   - sqlmode => see http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html
 30:      */
 31:     public function __construct(Nette\Database\Connection $connection, array $options)
 32:     {
 33:         $this->connection = $connection;
 34:         $charset = isset($options['charset'])
 35:             ? $options['charset']
 36:             : (version_compare($connection->getPdo()->getAttribute(\PDO::ATTR_SERVER_VERSION), '5.5.3', '>=') ? 'utf8mb4' : 'utf8');
 37:         if ($charset) {
 38:             $connection->query("SET NAMES '$charset'");
 39:         }
 40:         if (isset($options['sqlmode'])) {
 41:             $connection->query("SET sql_mode='$options[sqlmode]'");
 42:         }
 43:     }
 44: 
 45: 
 46:     /**
 47:      * @return Nette\Database\DriverException
 48:      */
 49:     public function convertException(\PDOException $e)
 50:     {
 51:         $code = isset($e->errorInfo[1]) ? $e->errorInfo[1] : NULL;
 52:         if (in_array($code, array(1216, 1217, 1451, 1452, 1701), TRUE)) {
 53:             return Nette\Database\ForeignKeyConstraintViolationException::from($e);
 54: 
 55:         } elseif (in_array($code, array(1062, 1557, 1569, 1586), TRUE)) {
 56:             return Nette\Database\UniqueConstraintViolationException::from($e);
 57: 
 58:         } elseif ($code >= 2001 && $code <= 2028) {
 59:             return Nette\Database\ConnectionException::from($e);
 60: 
 61:         } elseif (in_array($code, array(1048, 1121, 1138, 1171, 1252, 1263, 1566), TRUE)) {
 62:             return Nette\Database\NotNullConstraintViolationException::from($e);
 63: 
 64:         } else {
 65:             return Nette\Database\DriverException::from($e);
 66:         }
 67:     }
 68: 
 69: 
 70:     /********************* SQL ****************d*g**/
 71: 
 72: 
 73:     /**
 74:      * Delimites identifier for use in a SQL statement.
 75:      */
 76:     public function delimite($name)
 77:     {
 78:         // @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
 79:         return '`' . str_replace('`', '``', $name) . '`';
 80:     }
 81: 
 82: 
 83:     /**
 84:      * Formats boolean for use in a SQL statement.
 85:      */
 86:     public function formatBool($value)
 87:     {
 88:         return $value ? '1' : '0';
 89:     }
 90: 
 91: 
 92:     /**
 93:      * Formats date-time for use in a SQL statement.
 94:      */
 95:     public function formatDateTime(/*\DateTimeInterface*/ $value)
 96:     {
 97:         return $value->format("'Y-m-d H:i:s'");
 98:     }
 99: 
100: 
101:     /**
102:      * Formats date-time interval for use in a SQL statement.
103:      */
104:     public function formatDateInterval(\DateInterval $value)
105:     {
106:         return $value->format("'%r%h:%I:%S'");
107:     }
108: 
109: 
110:     /**
111:      * Encodes string for use in a LIKE statement.
112:      */
113:     public function formatLike($value, $pos)
114:     {
115:         $value = addcslashes(str_replace('\\', '\\\\', $value), "\x00\n\r\\'%_");
116:         return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
117:     }
118: 
119: 
120:     /**
121:      * Injects LIMIT/OFFSET to the SQL query.
122:      */
123:     public function applyLimit(& $sql, $limit, $offset)
124:     {
125:         if ($limit < 0 || $offset < 0) {
126:             throw new Nette\InvalidArgumentException('Negative offset or limit.');
127: 
128:         } elseif ($limit !== NULL || $offset) {
129:             // see http://dev.mysql.com/doc/refman/5.0/en/select.html
130:             $sql .= ' LIMIT ' . ($limit === NULL ? '18446744073709551615' : (int) $limit)
131:                 . ($offset ? ' OFFSET ' . (int) $offset : '');
132:         }
133:     }
134: 
135: 
136:     /**
137:      * Normalizes result row.
138:      */
139:     public function normalizeRow($row)
140:     {
141:         return $row;
142:     }
143: 
144: 
145:     /********************* reflection ****************d*g**/
146: 
147: 
148:     /**
149:      * Returns list of tables.
150:      */
151:     public function getTables()
152:     {
153:         $tables = array();
154:         foreach ($this->connection->query('SHOW FULL TABLES') as $row) {
155:             $tables[] = array(
156:                 'name' => $row[0],
157:                 'view' => isset($row[1]) && $row[1] === 'VIEW',
158:             );
159:         }
160:         return $tables;
161:     }
162: 
163: 
164:     /**
165:      * Returns metadata for all columns in a table.
166:      */
167:     public function getColumns($table)
168:     {
169:         $columns = array();
170:         foreach ($this->connection->query('SHOW FULL COLUMNS FROM ' . $this->delimite($table)) as $row) {
171:             $type = explode('(', $row['Type']);
172:             $columns[] = array(
173:                 'name' => $row['Field'],
174:                 'table' => $table,
175:                 'nativetype' => strtoupper($type[0]),
176:                 'size' => isset($type[1]) ? (int) $type[1] : NULL,
177:                 'unsigned' => (bool) strstr($row['Type'], 'unsigned'),
178:                 'nullable' => $row['Null'] === 'YES',
179:                 'default' => $row['Default'],
180:                 'autoincrement' => $row['Extra'] === 'auto_increment',
181:                 'primary' => $row['Key'] === 'PRI',
182:                 'vendor' => (array) $row,
183:             );
184:         }
185:         return $columns;
186:     }
187: 
188: 
189:     /**
190:      * Returns metadata for all indexes in a table.
191:      */
192:     public function getIndexes($table)
193:     {
194:         $indexes = array();
195:         foreach ($this->connection->query('SHOW INDEX FROM ' . $this->delimite($table)) as $row) {
196:             $indexes[$row['Key_name']]['name'] = $row['Key_name'];
197:             $indexes[$row['Key_name']]['unique'] = !$row['Non_unique'];
198:             $indexes[$row['Key_name']]['primary'] = $row['Key_name'] === 'PRIMARY';
199:             $indexes[$row['Key_name']]['columns'][$row['Seq_in_index'] - 1] = $row['Column_name'];
200:         }
201:         return array_values($indexes);
202:     }
203: 
204: 
205:     /**
206:      * Returns metadata for all foreign keys in a table.
207:      */
208:     public function getForeignKeys($table)
209:     {
210:         $keys = array();
211:         $query = 'SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.KEY_COLUMN_USAGE '
212:             . 'WHERE TABLE_SCHEMA = DATABASE() AND REFERENCED_TABLE_NAME IS NOT NULL AND TABLE_NAME = ' . $this->connection->quote($table);
213: 
214:         foreach ($this->connection->query($query) as $id => $row) {
215:             $keys[$id]['name'] = $row['CONSTRAINT_NAME']; // foreign key name
216:             $keys[$id]['local'] = $row['COLUMN_NAME']; // local columns
217:             $keys[$id]['table'] = $row['REFERENCED_TABLE_NAME']; // referenced table
218:             $keys[$id]['foreign'] = $row['REFERENCED_COLUMN_NAME']; // referenced columns
219:         }
220: 
221:         return array_values($keys);
222:     }
223: 
224: 
225:     /**
226:      * Returns associative array of detected types (IReflection::FIELD_*) in result set.
227:      */
228:     public function getColumnTypes(\PDOStatement $statement)
229:     {
230:         $types = array();
231:         $count = $statement->columnCount();
232:         for ($col = 0; $col < $count; $col++) {
233:             $meta = $statement->getColumnMeta($col);
234:             if (isset($meta['native_type'])) {
235:                 $types[$meta['name']] = $type = Nette\Database\Helpers::detectType($meta['native_type']);
236:                 if ($type === Nette\Database\IStructure::FIELD_TIME) {
237:                     $types[$meta['name']] = Nette\Database\IStructure::FIELD_TIME_INTERVAL;
238:                 }
239:             }
240:         }
241:         return $types;
242:     }
243: 
244: 
245:     /**
246:      * @param  string
247:      * @return bool
248:      */
249:     public function isSupported($item)
250:     {
251:         // MULTI_COLUMN_AS_OR_COND due to mysql bugs:
252:         // - http://bugs.mysql.com/bug.php?id=31188
253:         // - http://bugs.mysql.com/bug.php?id=35819
254:         // and more.
255:         return $item === self::SUPPORT_SELECT_UNGROUPED_COLUMNS || $item === self::SUPPORT_MULTI_COLUMN_AS_OR_COND;
256:     }
257: 
258: }
259: 
Nette 2.3-20161221 API API documentation generated by ApiGen 2.8.0