summaryrefslogtreecommitdiff
path: root/buildscripts/phing/classes/phing/tasks/ext/dbdeploy/DbDeployTask.php
blob: a5cc23ff2d8993c85221c436a70b679a11e68949 (plain)
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php
/*
 *  $Id: 035d43c0c50ca9567e9c8a016fef6a3053164acb $
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information please see
 * <http://phing.info>.
 */

require_once 'phing/Task.php';
require_once 'phing/tasks/ext/dbdeploy/DbmsSyntaxFactory.php';


/**
 * Generate SQL script for db using dbdeploy schema version table
 * and delta scripts
 *
 * <dbdeploy url="mysql:host=localhost;dbname=test"
 *     userid="dbdeploy" password="dbdeploy" dir="db" outputfile="">
 *
 * @author   Luke Crouch at SourceForge (http://sourceforge.net)
 * @version  $Id$
 * @package  phing.tasks.ext.dbdeploy
 */
class DbDeployTask extends Task
{
    /**
     * The tablename to use from the database for storing all changes
     * This cannot be changed
     *
     * @var string
     */
    public static $TABLE_NAME = 'changelog';

    /**
     * Connection string for the database connection
     *
     * @var string
     */
    protected $url;

    /**
     * The userid for the database connection
     *
     * @var string
     */
    protected $userid;

    /**
     * The password of the database user
     *
     * @var string
     */
    protected $password;

    /**
     * Path to the directory that holds the database patch files
     *
     * @var string
     */
    protected $dir;

    /**
     * Output file for performing all database patches of this deployment
     * Contains all the SQL statements that need to be executed
     *
     * @var string
     */
    protected $outputFile = 'dbdeploy_deploy.sql';

    /**
     * Outputfile for undoing the database patches of this deployment
     * Contains all the SQL statements that need to be executed
     *
     * @var string
     */
    protected $undoOutputFile = 'dbdeploy_undo.sql';

    /**
     * The deltaset that's being used
     *
     * @var string
     */
    protected $deltaSet = 'Main';

    /**
     * The number of the last change to apply
     *
     * @var int
     */
    protected $lastChangeToApply = 999;

    /**
     * Contains the object for the DBMS that is used
     *
     * @var object
     */
    protected $dbmsSyntax = null;

    /**
     * Array with all change numbers that are applied already
     *
     * @var array
     */
    protected $appliedChangeNumbers = array();

    /**
     * Checkall attribute
     * False means dbdeploy will only apply patches that have a higher number
     * than the last patchnumber that was applied
     * True means dbdeploy will apply all changes that aren't applied
     * already (in ascending order)
     *
     * @var int
     */
    protected $checkall = false;

    /**
     * The main function for the task
     *
     * @throws BuildException
     * @return void
     */
    public function main()
    {
        try {
            // get correct DbmsSyntax object
            $dbms = substr($this->url, 0, strpos($this->url, ':'));
            $dbmsSyntaxFactory = new DbmsSyntaxFactory($dbms);
            $this->dbmsSyntax = $dbmsSyntaxFactory->getDbmsSyntax();

            // figure out which revisions are in the db already
            $this->appliedChangeNumbers = $this->getAppliedChangeNumbers();
            $this->log('Current db revision: '.$this->getLastChangeAppliedInDb());
            $this->log('Checkall: ' . $this->checkall);

            $this->deploy();

        } catch (Exception $e) {
            throw new BuildException($e);
        }
    }

    /**
     * Get the numbers of all the patches that are already applied according to
     * the changelog table in the database
     *
     * @return array
     */
    protected function getAppliedChangeNumbers()
    {
        if (count($this->appliedChangeNumbers) == 0) {
            $this->log('Getting applied changed numbers from DB: ' . $this->url);
            $appliedChangeNumbers = array();
            $dbh = new PDO($this->url, $this->userid, $this->password);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "SELECT *
                    FROM " . DbDeployTask::$TABLE_NAME . "
                    WHERE delta_set = '$this->deltaSet'
                    ORDER BY change_number";
            foreach ($dbh->query($sql) as $change) {
                $appliedChangeNumbers[] = $change['change_number'];
            }
            $this->appliedChangeNumbers = $appliedChangeNumbers;
        }
        return $this->appliedChangeNumbers;
    }

    /**
     * Get the number of the last patch applied to the database
     *
     * @return int|mixed The highest patch number that is applied in the db
     */
    protected function getLastChangeAppliedInDb()
    {
        return (count($this->appliedChangeNumbers) > 0)
                ? max($this->appliedChangeNumbers) : 0;
    }

    /**
     * Create the deploy and undo deploy outputfiles
     *
     * @return void
     */
    protected function deploy()
    {
        // create deploy outputfile
        $this->createOutputFile($this->outputFile, false);

        // create undo deploy outputfile
        $this->createOutputFile($this->undoOutputFile, true);
    }

    /**
     * Generate the sql for doing/undoing the deployment and write it to a file
     *
     * @param string $file
     * @param bool $undo
     * @return void
     */
    protected function createOutputFile($file, $undo = false)
    {
        $fileHandle = fopen($file, "w+");
        $sql = $this->generateSql($undo);
        fwrite($fileHandle, $sql);
    }

    /**
     * Generate the sql for doing/undoing this deployment
     *
     * @param bool $undo
     * @return string The sql
     */
    protected function generateSql($undo = false)
    {
        $sql = '';
        $lastChangeAppliedInDb = $this->getLastChangeAppliedInDb();
        $files = $this->getDeltasFilesArray();
        $this->sortFiles($files, $undo);

        foreach ($files as $fileChangeNumber => $fileName) {
            if ($this->fileNeedsToBeRead($fileChangeNumber, $lastChangeAppliedInDb)) {
                $sql .= '-- Fragment begins: ' . $fileChangeNumber . ' --' . "\n";

                if (!$undo) {
                    $sql .= 'INSERT INTO ' . DbDeployTask::$TABLE_NAME . '
                                (change_number, delta_set, start_dt, applied_by, description)' .
                            ' VALUES (' . $fileChangeNumber . ', \'' . $this->deltaSet . '\', ' .
                                $this->dbmsSyntax->generateTimestamp() .
                                ', \'dbdeploy\', \'' . $fileName . '\');' . "\n";
                }

                // read the file
                $fullFileName = $this->dir . '/' . $fileName;
                $fh = fopen($fullFileName, 'r');
                $contents = fread($fh, filesize($fullFileName));
                // allow construct with and without space added
                $split = strpos($contents, '-- //@UNDO');
                if ($split === false)
                    $split = strpos($contents, '--//@UNDO');

                if ($undo) {
                    $sql .= substr($contents, $split + 10) . "\n";
                    $sql .= 'DELETE FROM ' . DbDeployTask::$TABLE_NAME . '
	                         WHERE change_number = ' . $fileChangeNumber . '
	                         AND delta_set = \'' . $this->deltaSet . '\';' . "\n";
                } else {
                    $sql .= substr($contents, 0, $split);
                    $sql .= 'UPDATE ' . DbDeployTask::$TABLE_NAME . '
	                         SET complete_dt = ' . $this->dbmsSyntax->generateTimestamp() . '
	                         WHERE change_number = ' . $fileChangeNumber . '
	                         AND delta_set = \'' . $this->deltaSet . '\';' . "\n";
                }

                $sql .= '-- Fragment ends: ' . $fileChangeNumber . ' --' . "\n";
            }
        }

        return $sql;
    }

    /**
     * Get a list of all the patch files in the patch file directory
     *
     * @return array
     */
    protected function getDeltasFilesArray()
    {
        $files = array();
        $baseDir = realpath($this->dir);
        $dh = opendir($baseDir);
        $fileChangeNumberPrefix = '';
        while (($file = readdir($dh)) !== false) {
            if (preg_match('[\d+]', $file, $fileChangeNumberPrefix)) {
                $files[intval($fileChangeNumberPrefix[0])] = $file;
            }
        }
        return $files;
    }

    /**
     * Sort files in the patch files directory (ascending or descending depending on $undo boolean)
     *
     * @param array $files
     * @param bool $undo
     * @return void
     */
    protected function sortFiles(&$files, $undo)
    {
        if ($undo) {
            krsort($files);
        } else {
            ksort($files);
        }
    }

    /**
     * Determine if this patch file need to be deployed
     * (using fileChangeNumber, lastChangeAppliedInDb and $this->checkall)
     *
     * @param int $fileChangeNumber
     * @param string $lastChangeAppliedInDb
     * @return bool True or false if patch file needs to be deployed
     */
    protected function fileNeedsToBeRead($fileChangeNumber, $lastChangeAppliedInDb)
    {
        if ($this->checkall) {
            return (!in_array($fileChangeNumber, $this->appliedChangeNumbers));
        } else {
            return ($fileChangeNumber > $lastChangeAppliedInDb && $fileChangeNumber <= $this->lastChangeToApply);
        }
    }

    /**
     * Set the url for the database connection
     *
     * @param string $url
     * @return void
     */
    public function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * Set the userid for the database connection
     *
     * @param string $userid
     * @return void
     */
    public function setUserId($userid)
    {
        $this->userid = $userid;
    }

    /**
     * Set the password for the database connection
     *
     * @param string $password
     * @return void
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * Set the directory where to find the patchfiles
     *
     * @param string $dir
     * @return void
     */
    public function setDir($dir)
    {
        $this->dir = $dir;
    }

    /**
     * Set the outputfile which contains all patch sql statements for this deployment
     *
     * @param string $outputFile
     * @return void
     */
    public function setOutputFile($outputFile)
    {
        $this->outputFile = $outputFile;
    }

    /**
     * Set the undo outputfile which contains all undo statements for this deployment
     *
     * @param string $undoOutputFile
     * @return void
     */
    public function setUndoOutputFile($undoOutputFile)
    {
        $this->undoOutputFile = $undoOutputFile;
    }

    /**
     * Set the lastchangetoapply property
     *
     * @param int $lastChangeToApply
     * @return void
     */
    public function setLastChangeToApply($lastChangeToApply)
    {
        $this->lastChangeToApply = $lastChangeToApply;
    }

    /**
     * Set the deltaset property
     *
     * @param string $deltaSet
     * @return void
     */
    public function setDeltaSet($deltaSet)
    {
        $this->deltaSet = $deltaSet;
    }

    /**
     * Set the checkall property
     *
     * @param bool $checkall
     * @return void
     */
    public function setCheckAll($checkall)
    {
        $this->checkall = (int)$checkall;
    }

    /**
     * Add a new fileset.
     * @return FileSet
     */
    public function createFileSet()
    {
        $this->fileset = new FileSet();
        $this->filesets[] = $this->fileset;
        return $this->fileset;
    }
}