xref: /plugin/struct/meta/QueryBuilder.php (revision aa1f50747d4c06c4cd033f5bb6213ba08543ee04)
18c551fd7SAndreas Gohr<?php
28c551fd7SAndreas Gohr
38c551fd7SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
48c551fd7SAndreas Gohr
58c551fd7SAndreas Gohr/**
68c551fd7SAndreas Gohr * Class QueryBuilder
78c551fd7SAndreas Gohr * @package dokuwiki\plugin\struct\meta
88c551fd7SAndreas Gohr */
98c551fd7SAndreas Gohrclass QueryBuilder {
108c551fd7SAndreas Gohr
118c551fd7SAndreas Gohr    /** @var array placeholder -> values */
128c551fd7SAndreas Gohr    protected $values = array();
138c551fd7SAndreas Gohr    /** @var array (alias -> statement */
148c551fd7SAndreas Gohr    protected $select = array();
158c551fd7SAndreas Gohr    /** @var array (alias -> statement) */
168c551fd7SAndreas Gohr    protected $from = array();
172f68434dSAndreas Gohr    /** @var array (alias -> "table"|"join") keeps how tables were added, as table or join */
182f68434dSAndreas Gohr    protected $type = array();
198c551fd7SAndreas Gohr    /** @var QueryBuilderWhere */
208c551fd7SAndreas Gohr    protected $where;
2183cb959bSAndreas Gohr    /** @var  string[] */
222f68434dSAndreas Gohr    protected $orderby = array();
2383cb959bSAndreas Gohr    /** @var  string[] */
242f68434dSAndreas Gohr    protected $groupby = array();
258c551fd7SAndreas Gohr
268c551fd7SAndreas Gohr    /**
278c551fd7SAndreas Gohr     * QueryBuilder constructor.
288c551fd7SAndreas Gohr     */
298c551fd7SAndreas Gohr    public function __construct() {
308c551fd7SAndreas Gohr        $this->where = new QueryBuilderWhere();
318c551fd7SAndreas Gohr    }
328c551fd7SAndreas Gohr
338c551fd7SAndreas Gohr    /**
348c551fd7SAndreas Gohr     * Adds a column to select
358c551fd7SAndreas Gohr     *
368c551fd7SAndreas Gohr     * If the alias already exists, the current statement for that alias will be overwritten.
378c551fd7SAndreas Gohr     *
388c551fd7SAndreas Gohr     * @param string $tablealias The table to select from
398c551fd7SAndreas Gohr     * @param string $column The column to select
408c551fd7SAndreas Gohr     * @param string $alias Under whichname to slect the column. blank for column name
418c551fd7SAndreas Gohr     */
428c551fd7SAndreas Gohr    public function addSelectColumn($tablealias, $column, $alias = '') {
438c551fd7SAndreas Gohr        if($alias === '') $alias = $column;
44*aa1f5074SAndreas Gohr        if(!isset($this->from[$tablealias])) {
45*aa1f5074SAndreas Gohr            throw new StructException('Table Alias does not exist');
46*aa1f5074SAndreas Gohr        }
478c551fd7SAndreas Gohr        $this->select[$alias] = "$tablealias.$column AS $alias";
488c551fd7SAndreas Gohr    }
498c551fd7SAndreas Gohr
508c551fd7SAndreas Gohr    /**
518c551fd7SAndreas Gohr     * Add a new select statement (the column part of it)
528c551fd7SAndreas Gohr     *
538c551fd7SAndreas Gohr     * Basically the same as @see addSelectColumn but accepts any statement. This is useful to
548c551fd7SAndreas Gohr     * select things like fixed strings or more complex function calls, but the correctness will not
558c551fd7SAndreas Gohr     * be checked.
568c551fd7SAndreas Gohr     *
578c551fd7SAndreas Gohr     * If the alias already exists, the current statement for that alias will be overwritten.
588c551fd7SAndreas Gohr     *
598c551fd7SAndreas Gohr     * @param string $statement
608c551fd7SAndreas Gohr     * @param string $alias
618c551fd7SAndreas Gohr     */
628c551fd7SAndreas Gohr    public function addSelectStatement($statement, $alias) {
638c551fd7SAndreas Gohr        $this->select[$alias] = "$statement AS $alias";
648c551fd7SAndreas Gohr    }
658c551fd7SAndreas Gohr
668c551fd7SAndreas Gohr    /**
678c551fd7SAndreas Gohr     * Adds the the table to the FROM statement part
688c551fd7SAndreas Gohr     *
698c551fd7SAndreas Gohr     * @param string $table the table to add
708c551fd7SAndreas Gohr     * @param string $alias alias for the table, blank for table name
718c551fd7SAndreas Gohr     */
728c551fd7SAndreas Gohr    public function addTable($table, $alias = '') {
738c551fd7SAndreas Gohr        if($alias === '') $alias = $table;
74*aa1f5074SAndreas Gohr        if(isset($this->from[$alias])) {
75*aa1f5074SAndreas Gohr            throw new StructException('Table Alias exists');
76*aa1f5074SAndreas Gohr        }
778c551fd7SAndreas Gohr        $this->from[$alias] = "$table AS $alias";
782f68434dSAndreas Gohr        $this->type[$alias] = 'table';
798c551fd7SAndreas Gohr    }
808c551fd7SAndreas Gohr
818c551fd7SAndreas Gohr    /**
828c551fd7SAndreas Gohr     * Adds a LEFT JOIN clause to the FROM statement part, sorted at the correct spot
838c551fd7SAndreas Gohr     *
848c551fd7SAndreas Gohr     * @param string $leftalias the alias of the left table you're joining on, has to exist already
858c551fd7SAndreas Gohr     * @param string $righttable the right table to be joined
868c551fd7SAndreas Gohr     * @param string $rightalias an alias for the right table, blank for table name
878c551fd7SAndreas Gohr     * @param string $onclause the ON clause condition the join is based on
888c551fd7SAndreas Gohr     */
898c551fd7SAndreas Gohr    public function addLeftJoin($leftalias, $righttable, $rightalias, $onclause) {
908c551fd7SAndreas Gohr        if($rightalias === '') $rightalias = $righttable;
91*aa1f5074SAndreas Gohr        if(!isset($this->from[$leftalias])) {
92*aa1f5074SAndreas Gohr            throw new StructException('Table Alias does not exist');
93*aa1f5074SAndreas Gohr        }
94*aa1f5074SAndreas Gohr        if(isset($this->from[$rightalias])) {
95*aa1f5074SAndreas Gohr            throw new StructException('Table Alias already exists');
96*aa1f5074SAndreas Gohr        }
978c551fd7SAndreas Gohr
988c551fd7SAndreas Gohr        $pos = array_search($leftalias, array_keys($this->from));
998c551fd7SAndreas Gohr        $statement = "LEFT OUTER JOIN $righttable AS $rightalias ON $onclause";
1008c551fd7SAndreas Gohr        $this->from = $this->array_insert($this->from, array($rightalias => $statement), $pos + 1);
1012f68434dSAndreas Gohr        $this->type[$rightalias] = 'join';
1028c551fd7SAndreas Gohr    }
1038c551fd7SAndreas Gohr
1048c551fd7SAndreas Gohr    /**
1058c551fd7SAndreas Gohr     * Returns the current WHERE filters and allows to set new ones
1068c551fd7SAndreas Gohr     *
1078c551fd7SAndreas Gohr     * @return QueryBuilderWhere
1088c551fd7SAndreas Gohr     */
1092f68434dSAndreas Gohr    public function filters() {
1108c551fd7SAndreas Gohr        return $this->where;
1118c551fd7SAndreas Gohr    }
1128c551fd7SAndreas Gohr
1138c551fd7SAndreas Gohr    /**
11483cb959bSAndreas Gohr     * Add an ORDER BY clause
11583cb959bSAndreas Gohr     *
11683cb959bSAndreas Gohr     * @param string $sort a single sorting condition
11783cb959bSAndreas Gohr     */
11883cb959bSAndreas Gohr    public function addOrderBy($sort) {
11983cb959bSAndreas Gohr        $this->orderby[] = $sort;
12083cb959bSAndreas Gohr    }
12183cb959bSAndreas Gohr
12283cb959bSAndreas Gohr    /**
12383cb959bSAndreas Gohr     * Add an GROUP BY clause
12483cb959bSAndreas Gohr     *
1252f68434dSAndreas Gohr     * @param string $tablealias
1262f68434dSAndreas Gohr     * @param string $column
12783cb959bSAndreas Gohr     */
1282f68434dSAndreas Gohr    public function addGroupByColumn($tablealias, $column) {
129*aa1f5074SAndreas Gohr        if(!isset($this->from[$tablealias])) {
130*aa1f5074SAndreas Gohr            throw new StructException('Table Alias does not exist');
131*aa1f5074SAndreas Gohr        }
1322f68434dSAndreas Gohr        $this->groupby[] = "$tablealias.$column";
1332f68434dSAndreas Gohr    }
1342f68434dSAndreas Gohr
1352f68434dSAndreas Gohr    /**
1362f68434dSAndreas Gohr     * Add an GROUP BY clause
1372f68434dSAndreas Gohr     *
1382f68434dSAndreas Gohr     * Like @see addGroupByColumn but accepts an arbitrary statement
1392f68434dSAndreas Gohr     *
1402f68434dSAndreas Gohr     * @param string $statement a single grouping clause
1412f68434dSAndreas Gohr     */
1422f68434dSAndreas Gohr    public function addGroupByStatement($statement) {
1432f68434dSAndreas Gohr        $this->groupby[] = $statement;
14483cb959bSAndreas Gohr    }
14583cb959bSAndreas Gohr
14683cb959bSAndreas Gohr    /**
1478c551fd7SAndreas Gohr     * Adds a value to the statement
1488c551fd7SAndreas Gohr     *
149df30dbf7SAndreas Gohr     * This function returns the name of the placeholder you have to use in your statement, so whenever
150df30dbf7SAndreas Gohr     * you need to use a user value in a statement, call this first, then add the statement through the
151df30dbf7SAndreas Gohr     * other functions using the returned placeholder.
1528c551fd7SAndreas Gohr     *
1538c551fd7SAndreas Gohr     * @param mixed $value
1548c551fd7SAndreas Gohr     * @return string
1558c551fd7SAndreas Gohr     */
1568c551fd7SAndreas Gohr    public function addValue($value) {
1578c551fd7SAndreas Gohr        static $count = 0;
1588c551fd7SAndreas Gohr        $count++;
1598c551fd7SAndreas Gohr
1608c551fd7SAndreas Gohr        $placeholder = ":!!val$count!!:"; // sqlite plugin does not support named parameters, yet so we have simulate it
1618c551fd7SAndreas Gohr        $this->values[$placeholder] = $value;
1628c551fd7SAndreas Gohr        return $placeholder;
1638c551fd7SAndreas Gohr    }
1648c551fd7SAndreas Gohr
1658c551fd7SAndreas Gohr    /**
1668c551fd7SAndreas Gohr     * Creates a new table alias that has not been used before
1678c551fd7SAndreas Gohr     *
1688c551fd7SAndreas Gohr     * @return string
1698c551fd7SAndreas Gohr     */
1708c551fd7SAndreas Gohr    public function generateTableAlias() {
1718c551fd7SAndreas Gohr        static $count = 0;
1728c551fd7SAndreas Gohr        $count++;
1738c551fd7SAndreas Gohr        return "T$count";
1748c551fd7SAndreas Gohr    }
1758c551fd7SAndreas Gohr
1768c551fd7SAndreas Gohr    /**
1778c551fd7SAndreas Gohr     * Returns the complete SQL statement and the values to apply
1788c551fd7SAndreas Gohr     *
17983cb959bSAndreas Gohr     * @return array ($sql, $vals)
1808c551fd7SAndreas Gohr     */
1818c551fd7SAndreas Gohr    public function getSQL() {
1822f68434dSAndreas Gohr        // FROM needs commas only for tables, not joins
1832f68434dSAndreas Gohr        $from = '';
1842f68434dSAndreas Gohr        foreach($this->from as $alias => $statement) {
1852f68434dSAndreas Gohr            if($this->type[$alias] == 'table' && $from) {
1862f68434dSAndreas Gohr                $from .= ",\n";
1872f68434dSAndreas Gohr            } else {
1882f68434dSAndreas Gohr                $from .= "\n";
1892f68434dSAndreas Gohr            }
1902f68434dSAndreas Gohr
1912f68434dSAndreas Gohr            $from .= $statement;
1922f68434dSAndreas Gohr        }
1932f68434dSAndreas Gohr
1948c551fd7SAndreas Gohr        $sql =
1958c551fd7SAndreas Gohr            ' SELECT ' . join(",\n", $this->select) . "\n" .
1962f68434dSAndreas Gohr            '   FROM ' . $from . "\n" .
1978c551fd7SAndreas Gohr            '  WHERE ' . $this->where->toSQL() . "\n";
1988c551fd7SAndreas Gohr
19983cb959bSAndreas Gohr        if($this->groupby) {
20083cb959bSAndreas Gohr            $sql .=
20183cb959bSAndreas Gohr                'GROUP BY ' . join(",\n", $this->groupby) . "\n";
20283cb959bSAndreas Gohr        }
20383cb959bSAndreas Gohr
2042f68434dSAndreas Gohr        if($this->orderby) {
2052f68434dSAndreas Gohr            $sql .=
2062f68434dSAndreas Gohr                'ORDER BY ' . join(",\n", $this->orderby) . "\n";
2072f68434dSAndreas Gohr        }
2082f68434dSAndreas Gohr
2098c551fd7SAndreas Gohr        return $this->fixPlaceholders($sql);
2108c551fd7SAndreas Gohr    }
2118c551fd7SAndreas Gohr
2128c551fd7SAndreas Gohr    /**
2138c551fd7SAndreas Gohr     * Replaces the named placeholders with ? placeholders
2148c551fd7SAndreas Gohr     *
2158c551fd7SAndreas Gohr     * Until the sqlite plugin can use named placeholder properly
2168c551fd7SAndreas Gohr     *
2178c551fd7SAndreas Gohr     * @param string $sql
2188c551fd7SAndreas Gohr     * @return array
2198c551fd7SAndreas Gohr     */
2208c551fd7SAndreas Gohr    protected function fixPlaceholders($sql) {
2218c551fd7SAndreas Gohr        $vals = array();
2228c551fd7SAndreas Gohr
2238c551fd7SAndreas Gohr        while(preg_match('/(:!!val\d+!!:)/', $sql, $m)) {
2248c551fd7SAndreas Gohr            $pl = $m[1];
2252b5df26eSAndreas Gohr
226*aa1f5074SAndreas Gohr            if(!isset($this->values[$pl])) {
227*aa1f5074SAndreas Gohr                throw new StructException('Placeholder not found');
228*aa1f5074SAndreas Gohr            }
2292b5df26eSAndreas Gohr
2302b5df26eSAndreas Gohr            $sql = preg_replace("/$pl/", '?', $sql, 1);
2318c551fd7SAndreas Gohr            $vals[] = $this->values[$pl];
2328c551fd7SAndreas Gohr        }
2338c551fd7SAndreas Gohr
2348c551fd7SAndreas Gohr        return array($sql, $vals);
2358c551fd7SAndreas Gohr    }
2368c551fd7SAndreas Gohr
2378c551fd7SAndreas Gohr    /**
2388c551fd7SAndreas Gohr     * Insert an array into another array at a given position in an associative array
2398c551fd7SAndreas Gohr     *
2408c551fd7SAndreas Gohr     * @param array $array The initial array
2418c551fd7SAndreas Gohr     * @param array $pairs The array to insert
2428c551fd7SAndreas Gohr     * @param string $key_pos The position at which to insert
2438c551fd7SAndreas Gohr     * @link https://gist.github.com/scribu/588429 simplified
2448c551fd7SAndreas Gohr     * @return array
2458c551fd7SAndreas Gohr     */
2468c551fd7SAndreas Gohr    protected function array_insert($array, $pairs, $key_pos) {
2478c551fd7SAndreas Gohr        $result = array_slice($array, 0, $key_pos);
2488c551fd7SAndreas Gohr        $result = array_merge($result, $pairs);
2498c551fd7SAndreas Gohr        $result = array_merge($result, array_slice($array, $key_pos));
2508c551fd7SAndreas Gohr        return $result;
2518c551fd7SAndreas Gohr    }
2528c551fd7SAndreas Gohr}
2538c551fd7SAndreas Gohr
254