/
SqliteSchema.php
349 lines (328 loc) · 9.84 KB
/
SqliteSchema.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
/**
* PHP Version 5.4
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 3.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Cake\Database\Schema;
use Cake\Database\Exception;
use Cake\Database\Schema\Table;
/**
* Schema management/reflection features for Sqlite
*/
class SqliteSchema {
/**
* The driver instance being used.
*
* @var Cake\Database\Driver\Sqlite
*/
protected $_driver;
/**
* Constructor
*
* @param Cake\Database\Driver\Sqlite $driver Driver to use.
* @return void
*/
public function __construct($driver) {
$this->_driver = $driver;
}
/**
* Convert a column definition to the abstract types.
*
* The returned type will be a type that
* Cake\Database\Type can handle.
*
* @param string $column The column type + length
* @throws Cake\Database\Exception
* @return array Array of column information.
*/
public function convertColumn($column) {
preg_match('/([a-z]+)(?:\(([0-9,]+)\))?/i', $column, $matches);
if (empty($matches)) {
throw new Exception(__d('cake_dev', 'Unable to parse column type from "%s"', $column));
}
$col = strtolower($matches[1]);
$length = null;
if (isset($matches[2])) {
$length = (int)$matches[2];
}
if ($col === 'bigint') {
return ['type' => 'biginteger', 'length' => $length];
}
if (in_array($col, ['blob', 'clob'])) {
return ['type' => 'binary', 'length' => null];
}
if (in_array($col, ['date', 'time', 'timestamp', 'datetime'])) {
return ['type' => $col, 'length' => null];
}
if (strpos($col, 'decimal') !== false) {
return ['type' => 'decimal', 'length' => null];
}
if (strpos($col, 'boolean') !== false) {
return ['type' => 'boolean', 'length' => null];
}
if (strpos($col, 'int') !== false) {
return ['type' => 'integer', 'length' => $length];
}
if ($col === 'char') {
return ['type' => 'string', 'fixed' => true, 'length' => $length];
}
if (strpos($col, 'char') !== false) {
return ['type' => 'string', 'length' => $length];
}
if (in_array($col, ['float', 'real', 'double'])) {
return ['type' => 'float', 'length' => null];
}
return ['type' => 'text', 'length' => null];
}
/**
* Get the SQL to list the tables in Sqlite
*
* @param array $config The connection configuration to use for
* getting tables from.
* @return array An array of (sql, params) to execute.
*/
public function listTablesSql() {
return ["SELECT name FROM sqlite_master WHERE type='table' ORDER BY name", []];
}
/**
* Get the SQL to describe a table in Sqlite.
*
* @param string $table The table name to describe
* @return array An array of (sql, params) to execute.
*/
public function describeTableSql($table) {
return ["PRAGMA table_info(" . $this->_driver->quoteIdentifier($table) . ")", []];
}
/**
* Convert field description results into abstract schema fields.
*
* @param Cake\Database\Schema\Table $table The table object to append fields to.
* @param array $row The row data from describeTableSql
*/
public function convertFieldDescription(Table $table, $row) {
$field = $this->convertColumn($row['type']);
$field += [
'null' => !$row['notnull'],
'default' => $row['dflt_value'] === null ? null : trim($row['dflt_value'], "'"),
];
if ($row['pk'] == true) {
$field['null'] = false;
}
$table->addColumn($row['name'], $field);
if ($row['pk'] == true) {
$table->addConstraint('primary', [
'type' => Table::CONSTRAINT_PRIMARY,
'columns' => [$row['name']]
]);
}
}
/**
* Get the SQL to describe the indexes in a table.
*
* @param string $table The table name to get information on.
* @return array An array of (sql, params) to execute.
*/
public function describeIndexSql($table) {
$sql = sprintf(
'PRAGMA index_list(%s)',
$this->_driver->quoteIdentifier($table)
);
return [$sql, []];
}
/**
* Convert an index into the abstract description.
*
* Since SQLite does not have a way to get metadata about all indexes at once,
* additional queries are done here. Sqlite constraint names are not
* stable, and the names for constraints will not match those used to create
* the table. This is a limitation in Sqlite's metadata features.
*
* @param Cake\Database\Schema\Table $table The table object to append
* an index or constraint to.
* @param array $row The row data from describeIndexSql
* @return void
*/
public function convertIndexDescription(Table $table, $row) {
$sql = sprintf(
'PRAGMA index_info(%s)',
$this->_driver->quoteIdentifier($row['name'])
);
$statement = $this->_driver->prepare($sql);
$statement->execute();
$columns = [];
foreach ($statement->fetchAll('assoc') as $column) {
$columns[] = $column['name'];
}
if ($row['unique']) {
$table->addConstraint($row['name'], [
'type' => Table::CONSTRAINT_UNIQUE,
'columns' => $columns
]);
} else {
$table->addIndex($row['name'], [
'type' => Table::INDEX_INDEX,
'columns' => $columns
]);
}
}
/**
* Generate the SQL fragment for a single column in Sqlite
*
* @param Cake\Database\Schema\Table $table The table object the column is in.
* @param string $name The name of the column.
* @return string SQL fragment.
* @throws Cake\Database\Exception On unknown column types.
*/
public function columnSql(Table $table, $name) {
$data = $table->column($name);
$typeMap = [
'string' => ' VARCHAR',
'integer' => ' INTEGER',
'biginteger' => ' BIGINT',
'boolean' => ' BOOLEAN',
'binary' => ' BLOB',
'float' => ' FLOAT',
'decimal' => ' DECIMAL',
'text' => ' TEXT',
'date' => ' DATE',
'time' => ' TIME',
'datetime' => ' DATETIME',
'timestamp' => ' TIMESTAMP',
];
if (!isset($typeMap[$data['type']])) {
throw new Exception(__d('cake_dev', 'Unknown column type for "%s"', $name));
}
$out = $this->_driver->quoteIdentifier($name);
$out .= $typeMap[$data['type']];
$hasLength = ['integer', 'string'];
if (in_array($data['type'], $hasLength, true) && isset($data['length'])) {
$out .= '(' . (int)$data['length'] . ')';
}
$hasPrecision = ['float', 'decimal'];
if (
in_array($data['type'], $hasPrecision, true) &&
(isset($data['length']) || isset($data['precision']))
) {
$out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
}
if (isset($data['null']) && $data['null'] === false) {
$out .= ' NOT NULL';
}
if ($data['type'] === 'integer' && $name == $table->primaryKey()[0]) {
$out .= ' PRIMARY KEY AUTOINCREMENT';
}
if (isset($data['null']) && $data['null'] === true) {
$out .= ' DEFAULT NULL';
unset($data['default']);
}
if (isset($data['default'])) {
$out .= ' DEFAULT ' . $this->_driver->schemaValue($data['default']);
}
return $out;
}
/**
* Generate the SQL fragments for defining table constraints.
*
* Note integer primary keys will return ''. This is intentional as Sqlite requires
* that integer primary keys be defined in the column definition.
*
* @param Cake\Database\Schema\Table $table The table object the column is in.
* @param string $name The name of the column.
* @return string SQL fragment.
*/
public function constraintSql(Table $table, $name) {
$data = $table->constraint($name);
if (
count($data['columns']) === 1 &&
$table->column($data['columns'][0])['type'] === 'integer'
) {
return '';
}
if ($data['type'] === Table::CONSTRAINT_PRIMARY) {
$type = 'PRIMARY KEY';
}
if ($data['type'] === Table::CONSTRAINT_UNIQUE) {
$type = 'UNIQUE';
}
$columns = array_map(
[$this->_driver, 'quoteIdentifier'],
$data['columns']
);
return sprintf('CONSTRAINT %s %s (%s)',
$this->_driver->quoteIdentifier($name),
$type,
implode(', ', $columns)
);
}
/**
* Generate the SQL fragment for a single index.
*
* @param Cake\Database\Schema\Table $table The table object the column is in.
* @param string $name The name of the column.
* @return string SQL fragment.
*/
public function indexSql(Table $table, $name) {
$data = $table->index($name);
$columns = array_map(
[$this->_driver, 'quoteIdentifier'],
$data['columns']
);
return sprintf('CREATE INDEX %s ON %s (%s)',
$this->_driver->quoteIdentifier($name),
$this->_driver->quoteIdentifier($table->name()),
implode(', ', $columns)
);
}
/**
* Generate the SQL to create a table.
*
* @param Table $table Cake\Database\Schema\Table instance
* @param array $columns The columns to go inside the table.
* @param array $constraints The constraints for the table.
* @param array $indexes The indexes for the table.
* @return array Complete CREATE TABLE statement(s)S
*/
public function createTableSql($table, $columns, $constraints, $indexes) {
$lines = array_merge($columns, $constraints);
$content = implode(",\n", array_filter($lines));
$table = sprintf("CREATE TABLE \"%s\" (\n%s\n)", $table->name(), $content);
$out = [$table];
foreach ($indexes as $index) {
$out[] = $index;
}
return $out;
}
/**
* Generate the SQL to drop a table.
*
* @param Cake\Database\Schema\Table $table Table instance
* @return string DROP TABLE sql
*/
public function dropTableSql(Table $table) {
return [sprintf('DROP TABLE "%s"', $table->name())];
}
/**
* Generate the SQL to truncate a table.
*
* @param Cake\Database\Schema\Table $table Table instance
* @return array SQL statements to drop truncate a table.
*/
public function truncateTableSql(Table $table) {
$name = $table->name();
return [
sprintf('DELETE FROM sqlite_sequence WHERE name="%s"', $name),
sprintf('DELETE FROM "%s"', $name)
];
}
}