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
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Templating
    • Utils
  • NetteModule
  • none
  • Tracy
    • Bridges
      • Nette

Classes

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