Subversion-Projekte lars-tiefland.php_share

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
1 lars 1
<?php
2
/*
3
 *  $Id: Mssql.php 7690 2010-08-31 17:11:24Z jwage $
4
 *
5
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16
 *
17
 * This software consists of voluntary contributions made by many individuals
18
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.doctrine-project.org>.
20
 */
21
 
22
/**
23
 * Doctrine_Connection_Mssql
24
 *
25
 * @package     Doctrine
26
 * @subpackage  Connection
27
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
28
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
29
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
30
 * @version     $Revision: 7690 $
31
 * @link        www.doctrine-project.org
32
 * @since       1.0
33
 */
34
class Doctrine_Connection_Mssql extends Doctrine_Connection_Common
35
{
36
    /**
37
     * @var string $driverName                  the name of this connection driver
38
     */
39
    protected $driverName = 'Mssql';
40
 
41
    /**
42
     * the constructor
43
     *
44
     * @param Doctrine_Manager $manager
45
     * @param PDO $pdo                          database handle
46
     */
47
    public function __construct(Doctrine_Manager $manager, $adapter)
48
    {
49
        // initialize all driver options
50
        $this->supported = array(
51
                          'sequences'             => 'emulated',
52
                          'indexes'               => true,
53
                          'affected_rows'         => true,
54
                          'transactions'          => true,
55
                          'summary_functions'     => true,
56
                          'order_by_text'         => true,
57
                          'current_id'            => 'emulated',
58
                          'limit_queries'         => 'emulated',
59
                          'LOBs'                  => true,
60
                          'replace'               => 'emulated',
61
                          'sub_selects'           => true,
62
                          'auto_increment'        => true,
63
                          'primary_key'           => true,
64
                          'result_introspection'  => true,
65
                          'prepared_statements'   => 'emulated',
66
                          );
67
 
68
        $this->properties['varchar_max_length'] = 8000;
69
 
70
        parent::__construct($manager, $adapter);
71
    }
72
 
73
    /**
74
     * quoteIdentifier
75
     * Quote a string so it can be safely used as a table / column name
76
     *
77
     * Quoting style depends on which database driver is being used.
78
     *
79
     * @param string $identifier    identifier name to be quoted
80
     * @param bool   $checkOption   check the 'quote_identifier' option
81
     *
82
     * @return string  quoted identifier string
83
     */
84
    public function quoteIdentifier($identifier, $checkOption = false)
85
    {
86
        if ($checkOption && ! $this->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) {
87
            return $identifier;
88
        }
89
 
90
        if (strpos($identifier, '.') !== false) {
91
            $parts = explode('.', $identifier);
92
            $quotedParts = array();
93
            foreach ($parts as $p) {
94
                $quotedParts[] = $this->quoteIdentifier($p);
95
            }
96
 
97
            return implode('.', $quotedParts);
98
        }
99
 
100
        return '[' . str_replace(']', ']]', $identifier) . ']';
101
    }
102
 
103
    /**
104
     * Adds an adapter-specific LIMIT clause to the SELECT statement.
105
     * [ original code borrowed from Zend Framework ]
106
     *
107
     * License available at: http://framework.zend.com/license
108
     *
109
     * Copyright (c) 2005-2008, Zend Technologies USA, Inc.
110
     * All rights reserved.
111
     *
112
     * Redistribution and use in source and binary forms, with or without modification,
113
     * are permitted provided that the following conditions are met:
114
     *
115
     *     * Redistributions of source code must retain the above copyright notice,
116
     *       this list of conditions and the following disclaimer.
117
     *
118
     *     * Redistributions in binary form must reproduce the above copyright notice,
119
     *       this list of conditions and the following disclaimer in the documentation
120
     *       and/or other materials provided with the distribution.
121
     *
122
     *     * Neither the name of Zend Technologies USA, Inc. nor the names of its
123
     *       contributors may be used to endorse or promote products derived from this
124
     *       software without specific prior written permission.
125
     *
126
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
127
     * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
128
     * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
129
     * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
130
     * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
131
     * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
132
     * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
133
     * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
134
     * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
135
     * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
136
     *
137
     * @param string $query
138
     * @param mixed $limit
139
     * @param mixed $offset
140
     * @link http://lists.bestpractical.com/pipermail/rt-devel/2005-June/007339.html
141
     * @return string
142
     */
143
    public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false, $isSubQuery = false, Doctrine_Query $queryOrigin = null)
144
    {
145
        if ($limit === false || !($limit > 0)) {
146
            return $query;
147
        }
148
 
149
        $orderby = stristr($query, 'ORDER BY');
150
 
151
        if ($offset !== false && $orderby === false) {
152
            throw new Doctrine_Connection_Exception("OFFSET cannot be used in MSSQL without ORDER BY due to emulation reasons.");
153
        }
154
 
155
        $count = intval($limit);
156
        $offset = intval($offset);
157
 
158
        if ($offset < 0) {
159
            throw new Doctrine_Connection_Exception("LIMIT argument offset=$offset is not valid");
160
        }
161
 
162
        $orderbySql = $queryOrigin->getSqlQueryPart('orderby');
163
        $orderbyDql = $queryOrigin->getDqlPart('orderby');
164
 
165
        if ($orderby !== false) {
166
            $orders = $this->parseOrderBy(implode(', ', $queryOrigin->getDqlPart('orderby')));
167
 
168
            for ($i = 0; $i < count($orders); $i++) {
169
                $sorts[$i] = (stripos($orders[$i], ' desc') !== false) ? 'DESC' : 'ASC';
170
                $orders[$i] = trim(preg_replace('/\s+(ASC|DESC)$/i', '', $orders[$i]));
171
 
172
                list($fieldAliases[$i], $fields[$i]) = strstr($orders[$i], '.') ? explode('.', $orders[$i]) : array('', $orders[$i]);
173
                $columnAlias[$i] = $queryOrigin->getSqlTableAlias($queryOrigin->getExpressionOwner($orders[$i]));
174
 
175
                $cmp = $queryOrigin->getQueryComponent($queryOrigin->getExpressionOwner($orders[$i]));
176
                $tables[$i] = $cmp['table'];
177
                $columns[$i] = $cmp['table']->getColumnName($fields[$i]);
178
 
179
                // TODO: This sould be refactored as method called Doctrine_Table::getColumnAlias(<column name>).
180
                $aliases[$i] = $columnAlias[$i] . '__' . $columns[$i];
181
            }
182
        }
183
 
184
        // Ticket #1259: Fix for limit-subquery in MSSQL
185
        $selectRegExp = 'SELECT\s+';
186
        $selectReplace = 'SELECT ';
187
 
188
        if (preg_match('/^SELECT(\s+)DISTINCT/i', $query)) {
189
            $selectRegExp .= 'DISTINCT\s+';
190
            $selectReplace .= 'DISTINCT ';
191
        }
192
 
193
        $fields_string = substr($query, strlen($selectReplace), strpos($query, ' FROM ') - strlen($selectReplace));
194
        $field_array = explode(',', $fields_string);
195
        $field_array = array_shift($field_array);
196
        $aux2 = preg_split('/ as /i', $field_array);
197
        $aux2 = explode('.', end($aux2));
198
        $key_field = trim(end($aux2));
199
 
200
        $query = preg_replace('/^'.$selectRegExp.'/i', $selectReplace . 'TOP ' . ($count + $offset) . ' ', $query);
201
 
202
        if ($isSubQuery === true) {
203
            $query = 'SELECT TOP ' . $count . ' ' . $this->quoteIdentifier('inner_tbl') . '.' . $key_field . ' FROM (' . $query . ') AS ' . $this->quoteIdentifier('inner_tbl');
204
        } else {
205
            $query = 'SELECT * FROM (SELECT TOP ' . $count . ' * FROM (' . $query . ') AS ' . $this->quoteIdentifier('inner_tbl');
206
        }
207
 
208
        if ($orderby !== false) {
209
            $query .= ' ORDER BY ';
210
 
211
            for ($i = 0, $l = count($orders); $i < $l; $i++) {
212
                if ($i > 0) { // not first order clause
213
                    $query .= ', ';
214
                }
215
 
216
                $query .= $this->modifyOrderByColumn($tables[$i], $columns[$i], $this->quoteIdentifier('inner_tbl') . '.' . $this->quoteIdentifier($aliases[$i])) . ' ';
217
                $query .= (stripos($sorts[$i], 'asc') !== false) ? 'DESC' : 'ASC';
218
            }
219
        }
220
 
221
        if ($isSubQuery !== true) {
222
            $query .= ') AS ' . $this->quoteIdentifier('outer_tbl');
223
 
224
            if ($orderby !== false) {
225
                $query .= ' ORDER BY ';
226
 
227
                for ($i = 0, $l = count($orders); $i < $l; $i++) {
228
                    if ($i > 0) { // not first order clause
229
                        $query .= ', ';
230
                    }
231
 
232
                    $query .= $this->modifyOrderByColumn($tables[$i], $columns[$i], $this->quoteIdentifier('outer_tbl') . '.' . $this->quoteIdentifier($aliases[$i])) . ' ' . $sorts[$i];
233
                }
234
            }
235
        }
236
 
237
        return $query;
238
    }
239
 
240
    /**
241
     * Parse an OrderBy-Statement into chunks
242
     *
243
     * @param string $orderby
244
     */
245
    private function parseOrderBy($orderby)
246
    {
247
        $matches = array();
248
        $chunks  = array();
249
        $tokens  = array();
250
        $parsed  = str_ireplace('ORDER BY', '', $orderby);
251
 
252
        preg_match_all('/(\w+\(.+?\)\s+(ASC|DESC)),?/', $orderby, $matches);
253
 
254
        $matchesWithExpressions = $matches[1];
255
 
256
        foreach ($matchesWithExpressions as $match) {
257
            $chunks[] = $match;
258
            $parsed = str_replace($match, '##' . (count($chunks) - 1) . '##', $parsed);
259
        }
260
 
261
        $tokens = preg_split('/,/', $parsed);
262
 
263
        for ($i = 0, $iMax = count($tokens); $i < $iMax; $i++) {
264
            $tokens[$i] = trim(preg_replace('/##(\d+)##/e', "\$chunks[\\1]", $tokens[$i]));
265
        }
266
 
267
        return $tokens;
268
    }
269
 
270
    /**
271
     * Order and Group By are not possible on columns from type text.
272
     * This method fix this issue by wrap the given term (column) into a CAST directive.
273
     *
274
     * @see DC-828
275
     * @param Doctrine_Table $table
276
     * @param string $field
277
     * @param string $term The term which will changed if it's necessary, depending to the field type.
278
     * @return string
279
     */
280
    public function modifyOrderByColumn(Doctrine_Table $table, $field, $term)
281
    {
282
        $def = $table->getDefinitionOf($field);
283
 
284
        if ($def['type'] == 'string' && $def['length'] === NULL) {
285
            $term = 'CAST(' . $term . ' AS varchar(8000))';
286
        }
287
 
288
        return $term;
289
    }
290
 
291
    /**
292
     * Creates dbms specific LIMIT/OFFSET SQL for the subqueries that are used in the
293
     * context of the limit-subquery algorithm.
294
     *
295
     * @return string
296
     */
297
    public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, $offset = false, $isManip = false)
298
    {
299
        return $this->modifyLimitQuery($query, $limit, $offset, $isManip, true);
300
    }
301
 
302
    /**
303
     * return version information about the server
304
     *
305
     * @param bool   $native  determines if the raw version string should be returned
306
     * @return array    version information
307
     */
308
    public function getServerVersion($native = false)
309
    {
310
        if ($this->serverInfo) {
311
            $serverInfo = $this->serverInfo;
312
        } else {
313
            $query      = 'SELECT @@VERSION';
314
            $serverInfo = $this->fetchOne($query);
315
        }
316
        // cache server_info
317
        $this->serverInfo = $serverInfo;
318
        if ( ! $native) {
319
            if (preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $serverInfo, $tmp)) {
320
                $serverInfo = array(
321
                    'major' => $tmp[1],
322
                    'minor' => $tmp[2],
323
                    'patch' => $tmp[3],
324
                    'extra' => null,
325
                    'native' => $serverInfo,
326
                );
327
            } else {
328
                $serverInfo = array(
329
                    'major' => null,
330
                    'minor' => null,
331
                    'patch' => null,
332
                    'extra' => null,
333
                    'native' => $serverInfo,
334
                );
335
            }
336
        }
337
        return $serverInfo;
338
    }
339
 
340
    /**
341
     * Checks if there's a sequence that exists.
342
     *
343
     * @param  string $seq_name     The sequence name to verify.
344
     * @return boolean              The value if the table exists or not
345
     */
346
    public function checkSequence($seqName)
347
    {
348
        $query = 'SELECT * FROM ' . $seqName;
349
        try {
350
            $this->exec($query);
351
        } catch(Doctrine_Connection_Exception $e) {
352
            if ($e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) {
353
                return false;
354
            }
355
 
356
            throw $e;
357
        }
358
        return true;
359
    }
360
 
361
    /**
362
     * execute
363
     * @param string $query     sql query
364
     * @param array $params     query parameters
365
     *
366
     * @return PDOStatement|Doctrine_Adapter_Statement
367
     */
368
    public function execute($query, array $params = array())
369
    {
370
        if(! empty($params)) {
371
            $query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params);
372
        }
373
 
374
        return parent::execute($query, array());
375
    }
376
 
377
    /**
378
     * execute
379
     * @param string $query     sql query
380
     * @param array $params     query parameters
381
     *
382
     * @return PDOStatement|Doctrine_Adapter_Statement
383
     */
384
    public function exec($query, array $params = array())
385
    {
386
        if(! empty($params)) {
387
            $query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params);
388
        }
389
 
390
        return parent::exec($query, array());
391
    }
392
 
393
    /**
394
     * Replaces bound parameters and their placeholders with explicit values.
395
     *
396
     * Workaround for http://bugs.php.net/36561
397
     *
398
     * @param string $query
399
     * @param array $params
400
     */
401
    protected function replaceBoundParamsWithInlineValuesInQuery($query, array $params) {
402
 
403
        foreach($params as $key => $value) {
404
            $re = '/(?<=WHERE|VALUES|SET|JOIN)(.*?)(\?)/';
405
            $query = preg_replace($re, "\\1##{$key}##", $query, 1);
406
        }
407
 
408
        $replacement = 'is_null($value) ? \'NULL\' : $this->quote($params[\\1])';
409
        $query = preg_replace('/##(\d+)##/e', $replacement, $query);
410
 
411
        return $query;
412
 
413
    }
414
 
415
    /**
416
     * Inserts a table row with specified data.
417
     *
418
     * @param Doctrine_Table $table     The table to insert data into.
419
     * @param array $values             An associative array containing column-value pairs.
420
     *                                  Values can be strings or Doctrine_Expression instances.
421
     * @return integer                  the number of affected rows. Boolean false if empty value array was given,
422
     */
423
    public function insert(Doctrine_Table $table, array $fields)
424
    {
425
        $identifiers = $table->getIdentifierColumnNames();
426
 
427
        $settingNullIdentifier = false;
428
        $fields = array_change_key_case($fields);
429
        foreach($identifiers as $identifier) {
430
            $lcIdentifier = strtolower($identifier);
431
 
432
            if(array_key_exists($lcIdentifier, $fields)) {
433
                if(is_null($fields[$lcIdentifier])) {
434
                    $settingNullIdentifier = true;
435
                    unset($fields[$lcIdentifier]);
436
                }
437
            }
438
        }
439
 
440
        // MSSQL won't allow the setting of identifier columns to null, so insert a default record and then update it
441
        if ($settingNullIdentifier) {
442
            $count = $this->exec('INSERT INTO ' . $this->quoteIdentifier($table->getTableName()) . ' DEFAULT VALUES');
443
 
444
            if(! $count) {
445
                return $count;
446
            }
447
 
448
            $id = $this->lastInsertId($table->getTableName());
449
 
450
            return $this->update($table, $fields, array($id));
451
        }
452
 
453
        return parent::insert($table, $fields);
454
    }
455
}