RawSql.php 9.59 KB
Newer Older
1
<?php
lsmith's avatar
lsmith committed
2
/*
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *  $Id$
 *
 * 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, see
 * <http://www.phpdoctrine.com>.
 */
21
Doctrine::autoload('Doctrine_Query_Abstract');
22 23 24
/**
 * Doctrine_RawSql
 *
25 26 27 28 29 30 31 32
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
33
class Doctrine_RawSql extends Doctrine_Query_Abstract
lsmith's avatar
lsmith committed
34
{
35 36 37
    /**
     * @var array $fields
     */
zYne's avatar
zYne committed
38
    private $fields = array();
39
    /**
40 41
     * parseQueryPart
     * parses given query part
42
     *
43 44 45 46 47 48
     * @param string $queryPartName     the name of the query part
     * @param string $queryPart         query part to be parsed
     * @param boolean $append           whether or not to append the query part to its stack
     *                                  if false is given, this method will overwrite 
     *                                  the given query part stack with $queryPart
     * @return Doctrine_Query           this object
49
     */
50
    public function parseQueryPart($queryPartName, $queryPart, $append = false) 
lsmith's avatar
lsmith committed
51
    {
52 53
        if ($queryPartName == 'select') {
            preg_match_all('/{([^}{]*)}/U', $queryPart, $m);
54 55

            $this->fields = $m[1];
56
            $this->parts['select'] = array();
lsmith's avatar
lsmith committed
57
        } else {
58 59 60 61 62
            if ( ! $append) {
                $this->parts[$queryPartName] = array($queryPart);
            } else {
                $this->parts[$queryPartName][] = $queryPart;
            }
lsmith's avatar
lsmith committed
63
        }
64 65 66 67
        return $this;
    }
    /**
     * parseQuery
zYne's avatar
zYne committed
68
     * parses an sql query and adds the parts to internal array
69
     *
zYne's avatar
zYne committed
70 71
     * @param string $query         query to be parsed
     * @return Doctrine_RawSql      this object
72
     */
lsmith's avatar
lsmith committed
73 74
    public function parseQuery($query)
    {
75
        preg_match_all('/{([^}{]*)}/U', $query, $m);
76 77 78 79

        $this->fields = $m[1];
        $this->clear();

zYne's avatar
zYne committed
80
        $e = Doctrine_Tokenizer::sqlExplode($query,' ');
81

lsmith's avatar
lsmith committed
82
        foreach ($e as $k => $part) {
83
            $low = strtolower($part);
lsmith's avatar
lsmith committed
84
            switch (strtolower($part)) {
zYne's avatar
zYne committed
85 86 87 88 89 90
                case 'select':
                case 'from':
                case 'where':
                case 'limit':
                case 'offset':
                case 'having':
91
                    $p = $low;
92 93 94 95
                    if ( ! isset($parts[$low])) {
                        $parts[$low] = array();
                    }
                    break;
zYne's avatar
zYne committed
96 97
                case 'order':
                case 'group':
98
                    $i = ($k + 1);
zYne's avatar
zYne committed
99
                    if (isset($e[$i]) && strtolower($e[$i]) === 'by') {
100
                        $p = $low;
zYne's avatar
zYne committed
101 102
                        $p .= 'by';
                        $parts[$low . 'by'] = array();
lsmith's avatar
lsmith committed
103

104 105 106 107
                    } else {
                        $parts[$p][] = $part;
                    }
                    break;
zYne's avatar
zYne committed
108
                case 'by':
109 110 111 112 113 114 115
                    continue;
                default:
                    if ( ! isset($parts[$p][0])) {
                        $parts[$p][0] = $part;
                    } else {
                        $parts[$p][0] .= ' '.$part;
                    }
116 117
            }
        }
118 119

        $this->parts = $parts;
zYne's avatar
zYne committed
120
        $this->parts['select'] = array();
lsmith's avatar
lsmith committed
121

doctrine's avatar
doctrine committed
122
        return $this;
123 124 125
    }
    /**
     * getQuery
zYne's avatar
zYne committed
126
     * builds the sql query from the given query parts
127
     *
zYne's avatar
zYne committed
128
     * @return string       the built sql query
129
     */
lsmith's avatar
lsmith committed
130 131
    public function getQuery()
    {
lsmith's avatar
lsmith committed
132
        foreach ($this->fields as $field) {
zYne's avatar
zYne committed
133
            $e = explode('.', $field);
lsmith's avatar
lsmith committed
134
            if ( ! isset($e[1])) {
zYne's avatar
zYne committed
135
                throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName');
lsmith's avatar
lsmith committed
136
            }
zYne's avatar
zYne committed
137
            // try to auto-add component
zYne's avatar
zYne committed
138
            if ( ! $this->hasTableAlias($e[0])) {
139 140
                try {
                    $this->addComponent($e[0], ucwords($e[0]));
141
                } catch(Doctrine_Exception $exception) {
zYne's avatar
zYne committed
142
                    throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.');
143 144 145
                }
            }

lsmith's avatar
lsmith committed
146
            if ($e[1] == '*') {
zYne's avatar
zYne committed
147
                $componentAlias = $this->getComponentAlias($e[0]);
zYne's avatar
zYne committed
148 149

                foreach ($this->_aliasMap[$componentAlias]['table']->getColumnNames() as $name) {
zYne's avatar
zYne committed
150 151
                    $field = $e[0] . '.' . $name;
                    $this->parts['select'][$field] = $field . ' AS ' . $e[0] . '__' . $name;
152 153
                }
            } else {
zYne's avatar
zYne committed
154 155
                $field = $e[0] . '.' . $e[1];
                $this->parts['select'][$field] = $field . ' AS ' . $e[0] . '__' . $e[1];
156 157
            }
        }
158

159 160
        // force-add all primary key fields

zYne's avatar
zYne committed
161
        foreach ($this->getTableAliases() as $tableAlias => $componentAlias) {
zYne's avatar
zYne committed
162 163 164 165 166
            $map = $this->_aliasMap[$componentAlias];

            foreach ($map['table']->getPrimaryKeys() as $key) {
                $field = $tableAlias . '.' . $key;

zYne's avatar
zYne committed
167
                if ( ! isset($this->parts['select'][$field])) {
zYne's avatar
zYne committed
168
                    $this->parts['select'][$field] = $field . ' AS ' . $tableAlias . '__' . $key;
lsmith's avatar
lsmith committed
169
                }
170 171 172
            }
        }

zYne's avatar
zYne committed
173
        $q = 'SELECT ' . implode(', ', $this->parts['select']);
174

175
        $string = $this->applyInheritance();
lsmith's avatar
lsmith committed
176
        if ( ! empty($string)) {
177
            $this->parts['where'][] = $string;
lsmith's avatar
lsmith committed
178
        }
179 180 181
        $copy = $this->parts;
        unset($copy['select']);

182 183 184
        $q .= ( ! empty($this->parts['from']))?    ' FROM '     . implode(' ', $this->parts['from']) : '';
        $q .= ( ! empty($this->parts['where']))?   ' WHERE '    . implode(' AND ', $this->parts['where']) : '';
        $q .= ( ! empty($this->parts['groupby']))? ' GROUP BY ' . implode(', ', $this->parts['groupby']) : '';
zYne's avatar
zYne committed
185 186
        $q .= ( ! empty($this->parts['having']))?  ' HAVING '   . implode(' AND ', $this->parts['having']) : '';
        $q .= ( ! empty($this->parts['orderby']))? ' ORDER BY ' . implode(', ', $this->parts['orderby']) : '';
zYne's avatar
zYne committed
187 188
        $q .= ( ! empty($this->parts['limit']))?   ' LIMIT ' . implode(' ', $this->parts['limit']) : '';
        $q .= ( ! empty($this->parts['offset']))?  ' OFFSET ' . implode(' ', $this->parts['offset']) : '';
189

lsmith's avatar
lsmith committed
190
        if ( ! empty($string)) {
191
            array_pop($this->parts['where']);
lsmith's avatar
lsmith committed
192
        }
193
        return $q;
194 195 196
    }
    /**
     * getFields
zYne's avatar
zYne committed
197
     * returns the fields associated with this parser
198
     *
zYne's avatar
zYne committed
199
     * @return array    all the fields associated with this parser
200
     */
lsmith's avatar
lsmith committed
201 202
    public function getFields()
    {
203 204 205 206 207 208 209
        return $this->fields;
    }
    /**
     * addComponent
     *
     * @param string $tableAlias
     * @param string $componentName
doctrine's avatar
doctrine committed
210
     * @return Doctrine_RawSql
211
     */
zYne's avatar
zYne committed
212
    public function addComponent($tableAlias, $path)
lsmith's avatar
lsmith committed
213
    {
zYne's avatar
zYne committed
214 215 216 217 218 219 220
        $tmp           = explode(' ', $path);
        $originalAlias = (count($tmp) > 1) ? end($tmp) : null;

        $e = explode('.', $tmp[0]);

        $fullPath = $tmp[0];
        $fullLength = strlen($fullPath);
221

pookey's avatar
pookey committed
222
        $table = null;
zYne's avatar
zYne committed
223 224 225

        $currPath = '';

zYne's avatar
zYne committed
226 227 228
        if (isset($this->_aliasMap[$e[0]])) {
            $table = $this->_aliasMap[$e[0]]['table'];

zYne's avatar
zYne committed
229
            $currPath = $parent = array_shift($e);
zYne's avatar
zYne committed
230 231
        }

lsmith's avatar
lsmith committed
232
        foreach ($e as $k => $component) {
zYne's avatar
zYne committed
233 234 235 236
            // get length of the previous path
            $length = strlen($currPath);

            // build the current component path
zYne's avatar
zYne committed
237
            $currPath = ($currPath) ? $currPath . '.' . $component : $component;
238

zYne's avatar
zYne committed
239 240 241 242 243
            $delimeter = substr($fullPath, $length, 1);

            // if an alias is not given use the current path as an alias identifier
            if (strlen($currPath) === $fullLength && isset($originalAlias)) {
                $componentAlias = $originalAlias;
lsmith's avatar
lsmith committed
244
            } else {
zYne's avatar
zYne committed
245
                $componentAlias = $currPath;
lsmith's avatar
lsmith committed
246
            }
zYne's avatar
zYne committed
247 248
            if ( ! isset($table)) {
                $conn = Doctrine_Manager::getInstance()
zYne's avatar
zYne committed
249
                        ->getConnectionForComponent($component);
zYne's avatar
zYne committed
250 251 252 253
                        
                $table = $conn->getTable($component);
                $this->_aliasMap[$componentAlias] = array('table' => $table);
            } else {
zYne's avatar
zYne committed
254
                $relation = $table->getRelation($component);
255

zYne's avatar
zYne committed
256 257 258
                $this->_aliasMap[$componentAlias] = array('table'    => $relation->getTable(),
                                                          'parent'   => $parent,
                                                          'relation' => $relation);
pookey's avatar
pookey committed
259
            }
zYne's avatar
zYne committed
260
            $this->addTableAlias($tableAlias, $componentAlias);
261

zYne's avatar
zYne committed
262
            $parent = $currPath;
263
        }
lsmith's avatar
lsmith committed
264

doctrine's avatar
doctrine committed
265
        return $this;
266 267 268
    }

}