Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16591 anikendra 1
<?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
 
408
		$this->out(__d('cake_console', 'End update.'));
409
	}
410
 
411
/**
412
 * Runs sql from _create() or _update()
413
 *
414
 * @param array $contents The contents to execute.
415
 * @param string $event The event to fire
416
 * @param CakeSchema $Schema The schema instance.
417
 * @return void
418
 */
419
	protected function _run($contents, $event, CakeSchema $Schema) {
420
		if (empty($contents)) {
421
			$this->err(__d('cake_console', 'Sql could not be run'));
422
			return;
423
		}
424
		Configure::write('debug', 2);
425
		$db = ConnectionManager::getDataSource($this->Schema->connection);
426
 
427
		foreach ($contents as $table => $sql) {
428
			if (empty($sql)) {
429
				$this->out(__d('cake_console', '%s is up to date.', $table));
430
			} else {
431
				if ($this->_dry === true) {
432
					$this->out(__d('cake_console', 'Dry run for %s :', $table));
433
					$this->out($sql);
434
				} else {
435
					if (!$Schema->before(array($event => $table))) {
436
						return false;
437
					}
438
					$error = null;
439
					try {
440
						$db->execute($sql);
441
					} catch (PDOException $e) {
442
						$error = $table . ': ' . $e->getMessage();
443
					}
444
 
445
					$Schema->after(array($event => $table, 'errors' => $error));
446
 
447
					if (!empty($error)) {
448
						$this->err($error);
449
					} else {
450
						$this->out(__d('cake_console', '%s updated.', $table));
451
					}
452
				}
453
			}
454
		}
455
	}
456
 
457
/**
458
 * Gets the option parser instance and configures it.
459
 *
460
 * @return ConsoleOptionParser
461
 */
462
	public function getOptionParser() {
463
		$parser = parent::getOptionParser();
464
 
465
		$plugin = array(
466
			'short' => 'p',
467
			'help' => __d('cake_console', 'The plugin to use.'),
468
		);
469
		$connection = array(
470
			'short' => 'c',
471
			'help' => __d('cake_console', 'Set the db config to use.'),
472
			'default' => 'default'
473
		);
474
		$path = array(
475
			'help' => __d('cake_console', 'Path to read and write schema.php'),
476
			'default' => APP . 'Config' . DS . 'Schema'
477
		);
478
		$file = array(
479
			'help' => __d('cake_console', 'File name to read and write.'),
480
		);
481
		$name = array(
482
			'help' => __d('cake_console',
483
				'Classname to use. If its Plugin.class, both name and plugin options will be set.'
484
			)
485
		);
486
		$snapshot = array(
487
			'short' => 's',
488
			'help' => __d('cake_console', 'Snapshot number to use/make.')
489
		);
490
		$models = array(
491
			'short' => 'm',
492
			'help' => __d('cake_console', 'Specify models as comma separated list.'),
493
		);
494
		$dry = array(
495
			'help' => __d('cake_console',
496
				'Perform a dry run on create and update commands. Queries will be output instead of run.'
497
			),
498
			'boolean' => true
499
		);
500
		$force = array(
501
			'short' => 'f',
502
			'help' => __d('cake_console', 'Force "generate" to create a new schema'),
503
			'boolean' => true
504
		);
505
		$write = array(
506
			'help' => __d('cake_console', 'Write the dumped SQL to a file.')
507
		);
508
		$exclude = array(
509
			'help' => __d('cake_console', 'Tables to exclude as comma separated list.')
510
		);
511
		$yes = array(
512
			'short' => 'y',
513
			'help' => __d('cake_console', 'Do not prompt for confirmation. Be careful!'),
514
			'boolean' => true
515
		);
516
 
517
		$parser->description(
518
			__d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
519
		)->addSubcommand('view', array(
520
			'help' => __d('cake_console', 'Read and output the contents of a schema file'),
521
			'parser' => array(
522
				'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
523
				'arguments' => compact('name')
524
			)
525
		))->addSubcommand('generate', array(
526
			'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
527
			'parser' => array(
528
				'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force', 'models', 'exclude'),
529
				'arguments' => array(
530
					'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
531
				)
532
			)
533
		))->addSubcommand('dump', array(
534
			'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
535
			'parser' => array(
536
				'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'write'),
537
				'arguments' => compact('name')
538
			)
539
		))->addSubcommand('create', array(
540
			'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
541
			'parser' => array(
542
				'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'yes'),
543
				'args' => array(
544
					'name' => array(
545
						'help' => __d('cake_console', 'Name of schema to use.')
546
					),
547
					'table' => array(
548
						'help' => __d('cake_console', 'Only create the specified table.')
549
					)
550
				)
551
			)
552
		))->addSubcommand('update', array(
553
			'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
554
			'parser' => array(
555
				'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot', 'force', 'yes'),
556
				'args' => array(
557
					'name' => array(
558
						'help' => __d('cake_console', 'Name of schema to use.')
559
					),
560
					'table' => array(
561
						'help' => __d('cake_console', 'Only create the specified table.')
562
					)
563
				)
564
			)
565
		));
566
 
567
		return $parser;
568
	}
569
 
570
}