統計
| ブランチ: | リビジョン:

pictcode_admin / lib / Cake / Console / Command / SchemaShell.php @ 5ad38a95

履歴 | 表示 | アノテート | ダウンロード (16.457 KB)

1 5ad38a95 spyder1211
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @since         CakePHP(tm) v 1.2.0.5550
13
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
14
 */
15
16
App::uses('AppShell', 'Console/Command');
17
App::uses('File', 'Utility');
18
App::uses('Folder', 'Utility');
19
App::uses('CakeSchema', 'Model');
20
21
/**
22
 * Schema is a command-line database management utility for automating programmer chores.
23
 *
24
 * Schema is CakePHP's database management utility. This helps you maintain versions of
25
 * of your database.
26
 *
27
 * @package       Cake.Console.Command
28
 * @link          http://book.cakephp.org/2.0/en/console-and-shells/schema-management-and-migrations.html
29
 */
30
class SchemaShell extends AppShell {
31
32
/**
33
 * Schema class being used.
34
 *
35
 * @var CakeSchema
36
 */
37
        public $Schema;
38
39
/**
40
 * is this a dry run?
41
 *
42
 * @var bool
43
 */
44
        protected $_dry = null;
45
46
/**
47
 * Override startup
48
 *
49
 * @return void
50
 */
51
        public function startup() {
52
                $this->_welcome();
53
                $this->out('Cake Schema Shell');
54
                $this->hr();
55
56
                Configure::write('Cache.disable', 1);
57
58
                $name = $path = $connection = $plugin = null;
59
                if (!empty($this->params['name'])) {
60
                        $name = $this->params['name'];
61
                } elseif (!empty($this->args[0]) && $this->args[0] !== 'snapshot') {
62
                        $name = $this->params['name'] = $this->args[0];
63
                }
64
65
                if (strpos($name, '.')) {
66
                        list($this->params['plugin'], $splitName) = pluginSplit($name);
67
                        $name = $this->params['name'] = $splitName;
68
                }
69
                if ($name && empty($this->params['file'])) {
70
                        $this->params['file'] = Inflector::underscore($name);
71
                } elseif (empty($this->params['file'])) {
72
                        $this->params['file'] = 'schema.php';
73
                }
74
                if (strpos($this->params['file'], '.php') === false) {
75
                        $this->params['file'] .= '.php';
76
                }
77
                $file = $this->params['file'];
78
79
                if (!empty($this->params['path'])) {
80
                        $path = $this->params['path'];
81
                }
82
83
                if (!empty($this->params['connection'])) {
84
                        $connection = $this->params['connection'];
85
                }
86
                if (!empty($this->params['plugin'])) {
87
                        $plugin = $this->params['plugin'];
88
                        if (empty($name)) {
89
                                $name = $plugin;
90
                        }
91
                }
92
                $name = Inflector::camelize($name);
93
                $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
94
        }
95
96
/**
97
 * Read and output contents of schema object
98
 * path to read as second arg
99
 *
100
 * @return void
101
 */
102
        public function view() {
103
                $File = new File($this->Schema->path . DS . $this->params['file']);
104
                if ($File->exists()) {
105
                        $this->out($File->read());
106
                        return $this->_stop();
107
                }
108
                $file = $this->Schema->path . DS . $this->params['file'];
109
                $this->err(__d('cake_console', 'Schema file (%s) could not be found.', $file));
110
                return $this->_stop();
111
        }
112
113
/**
114
 * Read database and Write schema object
115
 * accepts a connection as first arg or path to save as second arg
116
 *
117
 * @return void
118
 */
119
        public function generate() {
120
                $this->out(__d('cake_console', 'Generating Schema...'));
121
                $options = array();
122
                if ($this->params['force']) {
123
                        $options['models'] = false;
124
                } elseif (!empty($this->params['models'])) {
125
                        $options['models'] = CakeText::tokenize($this->params['models']);
126
                }
127
128
                $snapshot = false;
129
                if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
130
                        $snapshot = true;
131
                }
132
133
                if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
134
                        $snapshot = true;
135
                        $prompt = __d('cake_console', "Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?");
136
                        $result = strtolower($this->in($prompt, array('o', 's', 'q'), 's'));
137
                        if ($result === 'q') {
138
                                return $this->_stop();
139
                        }
140
                        if ($result === 'o') {
141
                                $snapshot = false;
142
                        }
143
                }
144
145
                $cacheDisable = Configure::read('Cache.disable');
146
                Configure::write('Cache.disable', true);
147
148
                $content = $this->Schema->read($options);
149
                $content['file'] = $this->params['file'];
150
151
                Configure::write('Cache.disable', $cacheDisable);
152
153
                if (!empty($this->params['exclude']) && !empty($content)) {
154
                        $excluded = CakeText::tokenize($this->params['exclude']);
155
                        foreach ($excluded as $table) {
156
                                unset($content['tables'][$table]);
157
                        }
158
                }
159
160
                if ($snapshot === true) {
161
                        $fileName = basename($this->params['file'], '.php');
162
                        $Folder = new Folder($this->Schema->path);
163
                        $result = $Folder->read();
164
165
                        $numToUse = false;
166
                        if (isset($this->params['snapshot'])) {
167
                                $numToUse = $this->params['snapshot'];
168
                        }
169
170
                        $count = 0;
171
                        if (!empty($result[1])) {
172
                                foreach ($result[1] as $file) {
173
                                        if (preg_match('/' . preg_quote($fileName) . '(?:[_\d]*)?\.php$/', $file)) {
174
                                                $count++;
175
                                        }
176
                                }
177
                        }
178
179
                        if ($numToUse !== false) {
180
                                if ($numToUse > $count) {
181
                                        $count = $numToUse;
182
                                }
183
                        }
184
185
                        $content['file'] = $fileName . '_' . $count . '.php';
186
                }
187
188
                if ($this->Schema->write($content)) {
189
                        $this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
190
                        return $this->_stop();
191
                }
192
                $this->err(__d('cake_console', 'Schema file: %s generated'));
193
                return $this->_stop();
194
        }
195
196
/**
197
 * Dump Schema object to sql file
198
 * Use the `write` param to enable and control SQL file output location.
199
 * Simply using -write will write the sql file to the same dir as the schema file.
200
 * If -write contains a full path name the file will be saved there. If -write only
201
 * contains no DS, that will be used as the file name, in the same dir as the schema file.
202
 *
203
 * @return string
204
 */
205
        public function dump() {
206
                $write = false;
207
                $Schema = $this->Schema->load();
208
                if (!$Schema) {
209
                        $this->err(__d('cake_console', 'Schema could not be loaded'));
210
                        return $this->_stop();
211
                }
212
                if (!empty($this->params['write'])) {
213
                        if ($this->params['write'] == 1) {
214
                                $write = Inflector::underscore($this->Schema->name);
215
                        } else {
216
                                $write = $this->params['write'];
217
                        }
218
                }
219
                $db = ConnectionManager::getDataSource($this->Schema->connection);
220
                $contents = "\n\n" . $db->dropSchema($Schema) . "\n\n" . $db->createSchema($Schema);
221
222
                if ($write) {
223
                        if (strpos($write, '.sql') === false) {
224
                                $write .= '.sql';
225
                        }
226
                        if (strpos($write, DS) !== false) {
227
                                $File = new File($write, true);
228
                        } else {
229
                                $File = new File($this->Schema->path . DS . $write, true);
230
                        }
231
232
                        if ($File->write($contents)) {
233
                                $this->out(__d('cake_console', 'SQL dump file created in %s', $File->pwd()));
234
                                return $this->_stop();
235
                        }
236
                        $this->err(__d('cake_console', 'SQL dump could not be created'));
237
                        return $this->_stop();
238
                }
239
                $this->out($contents);
240
                return $contents;
241
        }
242
243
/**
244
 * Run database create commands. Alias for run create.
245
 *
246
 * @return void
247
 */
248
        public function create() {
249
                list($Schema, $table) = $this->_loadSchema();
250
                $this->_create($Schema, $table);
251
        }
252
253
/**
254
 * Run database create commands. Alias for run create.
255
 *
256
 * @return void
257
 */
258
        public function update() {
259
                list($Schema, $table) = $this->_loadSchema();
260
                $this->_update($Schema, $table);
261
        }
262
263
/**
264
 * Prepares the Schema objects for database operations.
265
 *
266
 * @return void
267
 */
268
        protected function _loadSchema() {
269
                $name = $plugin = null;
270
                if (!empty($this->params['name'])) {
271
                        $name = $this->params['name'];
272
                }
273
                if (!empty($this->params['plugin'])) {
274
                        $plugin = $this->params['plugin'];
275
                }
276
277
                if (!empty($this->params['dry'])) {
278
                        $this->_dry = true;
279
                        $this->out(__d('cake_console', 'Performing a dry run.'));
280
                }
281
282
                $options = array(
283
                        'name' => $name,
284
                        'plugin' => $plugin,
285
                        'connection' => $this->params['connection'],
286
                );
287
                if (!empty($this->params['snapshot'])) {
288
                        $fileName = basename($this->Schema->file, '.php');
289
                        $options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
290
                }
291
292
                $Schema = $this->Schema->load($options);
293
294
                if (!$Schema) {
295
                        $this->err(__d('cake_console', '<error>Error</error>: The chosen schema could not be loaded. Attempted to load:'));
296
                        $this->err(__d('cake_console', '- file: %s', $this->Schema->path . DS . $this->Schema->file));
297
                        $this->err(__d('cake_console', '- name: %s', $this->Schema->name));
298
                        return $this->_stop(2);
299
                }
300
                $table = null;
301
                if (isset($this->args[1])) {
302
                        $table = $this->args[1];
303
                }
304
                return array(&$Schema, $table);
305
        }
306
307
/**
308
 * Create database from Schema object
309
 * Should be called via the run method
310
 *
311
 * @param CakeSchema $Schema The schema instance to create.
312
 * @param string $table The table name.
313
 * @return void
314
 */
315
        protected function _create(CakeSchema $Schema, $table = null) {
316
                $db = ConnectionManager::getDataSource($this->Schema->connection);
317
318
                $drop = $create = array();
319
320
                if (!$table) {
321
                        foreach ($Schema->tables as $table => $fields) {
322
                                $drop[$table] = $db->dropSchema($Schema, $table);
323
                                $create[$table] = $db->createSchema($Schema, $table);
324
                        }
325
                } elseif (isset($Schema->tables[$table])) {
326
                        $drop[$table] = $db->dropSchema($Schema, $table);
327
                        $create[$table] = $db->createSchema($Schema, $table);
328
                }
329
                if (empty($drop) || empty($create)) {
330
                        $this->out(__d('cake_console', 'Schema is up to date.'));
331
                        return $this->_stop();
332
                }
333
334
                $this->out("\n" . __d('cake_console', 'The following table(s) will be dropped.'));
335
                $this->out(array_keys($drop));
336
337
                if (!empty($this->params['yes']) ||
338
                        $this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n') === 'y'
339
                ) {
340
                        $this->out(__d('cake_console', 'Dropping table(s).'));
341
                        $this->_run($drop, 'drop', $Schema);
342
                }
343
344
                $this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
345
                $this->out(array_keys($create));
346
347
                if (!empty($this->params['yes']) ||
348
                        $this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y') === 'y'
349
                ) {
350
                        $this->out(__d('cake_console', 'Creating table(s).'));
351
                        $this->_run($create, 'create', $Schema);
352
                }
353
                $this->out(__d('cake_console', 'End create.'));
354
        }
355
356
/**
357
 * Update database with Schema object
358
 * Should be called via the run method
359
 *
360
 * @param CakeSchema &$Schema The schema instance
361
 * @param string $table The table name.
362
 * @return void
363
 */
364
        protected function _update(&$Schema, $table = null) {
365
                $db = ConnectionManager::getDataSource($this->Schema->connection);
366
367
                $this->out(__d('cake_console', 'Comparing Database to Schema...'));
368
                $options = array();
369
                if (isset($this->params['force'])) {
370
                        $options['models'] = false;
371
                }
372
                $Old = $this->Schema->read($options);
373
                $compare = $this->Schema->compare($Old, $Schema);
374
375
                $contents = array();
376
377
                if (empty($table)) {
378
                        foreach ($compare as $table => $changes) {
379
                                if (isset($compare[$table]['create'])) {
380
                                        $contents[$table] = $db->createSchema($Schema, $table);
381
                                } else {
382
                                        $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
383
                                }
384
                        }
385
                } elseif (isset($compare[$table])) {
386
                        if (isset($compare[$table]['create'])) {
387
                                $contents[$table] = $db->createSchema($Schema, $table);
388
                        } else {
389
                                $contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
390
                        }
391
                }
392
393
                if (empty($contents)) {
394
                        $this->out(__d('cake_console', 'Schema is up to date.'));
395
                        return $this->_stop();
396
                }
397
398
                $this->out("\n" . __d('cake_console', 'The following statements will run.'));
399
                $this->out(array_map('trim', $contents));
400
                if (!empty($this->params['yes']) ||
401
                        $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n') === 'y'
402
                ) {
403
                        $this->out();
404
                        $this->out(__d('cake_console', 'Updating Database...'));
405
                        $this->_run($contents, 'update', $Schema);
406
407
                        Configure::write('Cache.disable', false);
408
                        Cache::clear(false, '_cake_model_');
409
                }
410
411
                $this->out(__d('cake_console', 'End update.'));
412
        }
413
414
/**
415
 * Runs sql from _create() or _update()
416
 *
417
 * @param array $contents The contents to execute.
418
 * @param string $event The event to fire
419
 * @param CakeSchema $Schema The schema instance.
420
 * @return void
421
 */
422
        protected function _run($contents, $event, CakeSchema $Schema) {
423
                if (empty($contents)) {
424
                        $this->err(__d('cake_console', 'Sql could not be run'));
425
                        return;
426
                }
427
                Configure::write('debug', 2);
428
                $db = ConnectionManager::getDataSource($this->Schema->connection);
429
430
                foreach ($contents as $table => $sql) {
431
                        if (empty($sql)) {
432
                                $this->out(__d('cake_console', '%s is up to date.', $table));
433
                        } else {
434
                                if ($this->_dry === true) {
435
                                        $this->out(__d('cake_console', 'Dry run for %s :', $table));
436
                                        $this->out($sql);
437
                                } else {
438
                                        if (!$Schema->before(array($event => $table))) {
439
                                                return false;
440
                                        }
441
                                        $error = null;
442
                                        try {
443
                                                $db->execute($sql);
444
                                        } catch (PDOException $e) {
445
                                                $error = $table . ': ' . $e->getMessage();
446
                                        }
447
448
                                        $Schema->after(array($event => $table, 'errors' => $error));
449
450
                                        if (!empty($error)) {
451
                                                $this->err($error);
452
                                        } else {
453
                                                $this->out(__d('cake_console', '%s updated.', $table));
454
                                        }
455
                                }
456
                        }
457
                }
458
        }
459
460
/**
461
 * Gets the option parser instance and configures it.
462
 *
463
 * @return ConsoleOptionParser
464
 */
465
        public function getOptionParser() {
466
                $parser = parent::getOptionParser();
467
468
                $plugin = array(
469
                        'short' => 'p',
470
                        'help' => __d('cake_console', 'The plugin to use.'),
471
                );
472
                $connection = array(
473
                        'short' => 'c',
474
                        'help' => __d('cake_console', 'Set the db config to use.'),
475
                        'default' => 'default'
476
                );
477
                $path = array(
478
                        'help' => __d('cake_console', 'Path to read and write schema.php'),
479
                        'default' => APP . 'Config' . DS . 'Schema'
480
                );
481
                $file = array(
482
                        'help' => __d('cake_console', 'File name to read and write.'),
483
                );
484
                $name = array(
485
                        'help' => __d('cake_console',
486
                                'Classname to use. If its Plugin.class, both name and plugin options will be set.'
487
                        )
488
                );
489
                $snapshot = array(
490
                        'short' => 's',
491
                        'help' => __d('cake_console', 'Snapshot number to use/make.')
492
                );
493
                $models = array(
494
                        'short' => 'm',
495
                        'help' => __d('cake_console', 'Specify models as comma separated list.'),
496
                );
497
                $dry = array(
498
                        'help' => __d('cake_console',
499
                                'Perform a dry run on create and update commands. Queries will be output instead of run.'
500
                        ),
501
                        'boolean' => true
502
                );
503
                $force = array(
504
                        'short' => 'f',
505
                        'help' => __d('cake_console', 'Force "generate" to create a new schema'),
506
                        'boolean' => true
507
                );
508
                $write = array(
509
                        'help' => __d('cake_console', 'Write the dumped SQL to a file.')
510
                );
511
                $exclude = array(
512
                        'help' => __d('cake_console', 'Tables to exclude as comma separated list.')
513
                );
514
                $yes = array(
515
                        'short' => 'y',
516
                        'help' => __d('cake_console', 'Do not prompt for confirmation. Be careful!'),
517
                        'boolean' => true
518
                );
519
520
                $parser->description(
521
                        __d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
522
                )->addSubcommand('view', array(
523
                        'help' => __d('cake_console', 'Read and output the contents of a schema file'),
524
                        'parser' => array(
525
                                'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
526
                                'arguments' => compact('name')
527
                        )
528
                ))->addSubcommand('generate', array(
529
                        'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
530
                        'parser' => array(
531
                                'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force', 'models', 'exclude'),
532
                                'arguments' => array(
533
                                        'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
534
                                )
535
                        )
536
                ))->addSubcommand('dump', array(
537
                        'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
538
                        'parser' => array(
539
                                'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'write'),
540
                                'arguments' => compact('name')
541
                        )
542
                ))->addSubcommand('create', array(
543
                        'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
544
                        'parser' => array(
545
                                'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'yes'),
546
                                'args' => array(
547
                                        'name' => array(
548
                                                'help' => __d('cake_console', 'Name of schema to use.')
549
                                        ),
550
                                        'table' => array(
551
                                                'help' => __d('cake_console', 'Only create the specified table.')
552
                                        )
553
                                )
554
                        )
555
                ))->addSubcommand('update', array(
556
                        'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
557
                        'parser' => array(
558
                                'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'force', 'yes'),
559
                                'args' => array(
560
                                        'name' => array(
561
                                                'help' => __d('cake_console', 'Name of schema to use.')
562
                                        ),
563
                                        'table' => array(
564
                                                'help' => __d('cake_console', 'Only create the specified table.')
565
                                        )
566
                                )
567
                        )
568
                ));
569
570
                return $parser;
571
        }
572
573
}