xref: /plugin/struct/meta/QueryBuilder.php (revision 2f68434ddfdca372bc621625760a4d7b8a3a48b8)
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();
17*2f68434dSAndreas Gohr    /** @var array (alias -> "table"|"join") keeps how tables were added, as table or join*/
18*2f68434dSAndreas Gohr    protected $type = array();
198c551fd7SAndreas Gohr    /** @var QueryBuilderWhere */
208c551fd7SAndreas Gohr    protected $where;
2183cb959bSAndreas Gohr    /** @var  string[] */
22*2f68434dSAndreas Gohr    protected $orderby = array();
2383cb959bSAndreas Gohr    /** @var  string[] */
24*2f68434dSAndreas 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;
448c551fd7SAndreas Gohr        if(!isset($this->from[$tablealias])) throw new StructException('Table Alias does not exist');
458c551fd7SAndreas Gohr        $this->select[$alias] = "$tablealias.$column AS $alias";
468c551fd7SAndreas Gohr    }
478c551fd7SAndreas Gohr
488c551fd7SAndreas Gohr    /**
498c551fd7SAndreas Gohr     * Add a new select statement (the column part of it)
508c551fd7SAndreas Gohr     *
518c551fd7SAndreas Gohr     * Basically the same as @see addSelectColumn but accepts any statement. This is useful to
528c551fd7SAndreas Gohr     * select things like fixed strings or more complex function calls, but the correctness will not
538c551fd7SAndreas Gohr     * be checked.
548c551fd7SAndreas Gohr     *
558c551fd7SAndreas Gohr     * If the alias already exists, the current statement for that alias will be overwritten.
568c551fd7SAndreas Gohr     *
578c551fd7SAndreas Gohr     * @param string $statement
588c551fd7SAndreas Gohr     * @param string $alias
598c551fd7SAndreas Gohr     */
608c551fd7SAndreas Gohr    public function addSelectStatement($statement, $alias) {
618c551fd7SAndreas Gohr        $this->select[$alias] = "$statement AS $alias";
628c551fd7SAndreas Gohr    }
638c551fd7SAndreas Gohr
648c551fd7SAndreas Gohr    /**
658c551fd7SAndreas Gohr     * Adds the the table to the FROM statement part
668c551fd7SAndreas Gohr     *
678c551fd7SAndreas Gohr     * @param string $table the table to add
688c551fd7SAndreas Gohr     * @param string $alias alias for the table, blank for table name
698c551fd7SAndreas Gohr     */
708c551fd7SAndreas Gohr    public function addTable($table, $alias = '') {
718c551fd7SAndreas Gohr        if($alias === '') $alias = $table;
728c551fd7SAndreas Gohr        if(isset($this->from[$alias])) throw new StructException('Table Alias exists');
738c551fd7SAndreas Gohr        $this->from[$alias] = "$table AS $alias";
74*2f68434dSAndreas Gohr        $this->type[$alias] = 'table';
758c551fd7SAndreas Gohr    }
768c551fd7SAndreas Gohr
778c551fd7SAndreas Gohr    /**
788c551fd7SAndreas Gohr     * Adds a LEFT JOIN clause to the FROM statement part, sorted at the correct spot
798c551fd7SAndreas Gohr     *
808c551fd7SAndreas Gohr     * @param string $leftalias the alias of the left table you're joining on, has to exist already
818c551fd7SAndreas Gohr     * @param string $righttable the right table to be joined
828c551fd7SAndreas Gohr     * @param string $rightalias an alias for the right table, blank for table name
838c551fd7SAndreas Gohr     * @param string $onclause the ON clause condition the join is based on
848c551fd7SAndreas Gohr     */
858c551fd7SAndreas Gohr    public function addLeftJoin($leftalias, $righttable, $rightalias, $onclause) {
868c551fd7SAndreas Gohr        if($rightalias === '') $rightalias = $righttable;
878c551fd7SAndreas Gohr        if(!isset($this->from[$leftalias])) throw new StructException('Table Alias does not exist');
888c551fd7SAndreas Gohr        if(isset($this->from[$rightalias])) throw new StructException('Table Alias already exists');
898c551fd7SAndreas Gohr
908c551fd7SAndreas Gohr        $pos = array_search($leftalias, array_keys($this->from));
918c551fd7SAndreas Gohr        $statement = "LEFT OUTER JOIN $righttable AS $rightalias ON $onclause";
928c551fd7SAndreas Gohr        $this->from = $this->array_insert($this->from, array($rightalias => $statement), $pos + 1);
93*2f68434dSAndreas Gohr        $this->type[$rightalias] = 'join';
948c551fd7SAndreas Gohr    }
958c551fd7SAndreas Gohr
968c551fd7SAndreas Gohr    /**
978c551fd7SAndreas Gohr     * Returns the current WHERE filters and allows to set new ones
988c551fd7SAndreas Gohr     *
998c551fd7SAndreas Gohr     * @return QueryBuilderWhere
1008c551fd7SAndreas Gohr     */
101*2f68434dSAndreas Gohr    public function filters() {
1028c551fd7SAndreas Gohr        return $this->where;
1038c551fd7SAndreas Gohr    }
1048c551fd7SAndreas Gohr
1058c551fd7SAndreas Gohr    /**
10683cb959bSAndreas Gohr     * Add an ORDER BY clause
10783cb959bSAndreas Gohr     *
10883cb959bSAndreas Gohr     * @param string $sort a single sorting condition
10983cb959bSAndreas Gohr     */
11083cb959bSAndreas Gohr    public function addOrderBy($sort) {
11183cb959bSAndreas Gohr        $this->orderby[] = $sort;
11283cb959bSAndreas Gohr    }
11383cb959bSAndreas Gohr
11483cb959bSAndreas Gohr    /**
11583cb959bSAndreas Gohr     * Add an GROUP BY clause
11683cb959bSAndreas Gohr     *
117*2f68434dSAndreas Gohr     * @param string $tablealias
118*2f68434dSAndreas Gohr     * @param string $column
11983cb959bSAndreas Gohr     */
120*2f68434dSAndreas Gohr    public function addGroupByColumn($tablealias, $column) {
121*2f68434dSAndreas Gohr        if(!isset($this->from[$tablealias])) throw new StructException('Table Alias does not exist');
122*2f68434dSAndreas Gohr        $this->groupby[] = "$tablealias.$column";
123*2f68434dSAndreas Gohr    }
124*2f68434dSAndreas Gohr
125*2f68434dSAndreas Gohr    /**
126*2f68434dSAndreas Gohr     * Add an GROUP BY clause
127*2f68434dSAndreas Gohr     *
128*2f68434dSAndreas Gohr     * Like @see addGroupByColumn but accepts an arbitrary statement
129*2f68434dSAndreas Gohr     *
130*2f68434dSAndreas Gohr     * @param string $statement a single grouping clause
131*2f68434dSAndreas Gohr     */
132*2f68434dSAndreas Gohr    public function addGroupByStatement($statement) {
133*2f68434dSAndreas Gohr        $this->groupby[] = $statement;
13483cb959bSAndreas Gohr    }
13583cb959bSAndreas Gohr
13683cb959bSAndreas Gohr    /**
1378c551fd7SAndreas Gohr     * Adds a value to the statement
1388c551fd7SAndreas Gohr     *
139df30dbf7SAndreas Gohr     * This function returns the name of the placeholder you have to use in your statement, so whenever
140df30dbf7SAndreas Gohr     * you need to use a user value in a statement, call this first, then add the statement through the
141df30dbf7SAndreas Gohr     * other functions using the returned placeholder.
1428c551fd7SAndreas Gohr     *
1438c551fd7SAndreas Gohr     * @param mixed $value
1448c551fd7SAndreas Gohr     * @return string
1458c551fd7SAndreas Gohr     */
1468c551fd7SAndreas Gohr    public function addValue($value) {
1478c551fd7SAndreas Gohr        static $count = 0;
1488c551fd7SAndreas Gohr        $count++;
1498c551fd7SAndreas Gohr
1508c551fd7SAndreas Gohr        $placeholder = ":!!val$count!!:"; // sqlite plugin does not support named parameters, yet so we have simulate it
1518c551fd7SAndreas Gohr        $this->values[$placeholder] = $value;
1528c551fd7SAndreas Gohr        return $placeholder;
1538c551fd7SAndreas Gohr    }
1548c551fd7SAndreas Gohr
1558c551fd7SAndreas Gohr    /**
1568c551fd7SAndreas Gohr     * Creates a new table alias that has not been used before
1578c551fd7SAndreas Gohr     *
1588c551fd7SAndreas Gohr     * @return string
1598c551fd7SAndreas Gohr     */
1608c551fd7SAndreas Gohr    public function generateTableAlias() {
1618c551fd7SAndreas Gohr        static $count = 0;
1628c551fd7SAndreas Gohr        $count++;
1638c551fd7SAndreas Gohr        return "T$count";
1648c551fd7SAndreas Gohr    }
1658c551fd7SAndreas Gohr
1668c551fd7SAndreas Gohr    /**
1678c551fd7SAndreas Gohr     * Returns the complete SQL statement and the values to apply
1688c551fd7SAndreas Gohr     *
16983cb959bSAndreas Gohr     * @return array ($sql, $vals)
1708c551fd7SAndreas Gohr     */
1718c551fd7SAndreas Gohr    public function getSQL() {
172*2f68434dSAndreas Gohr        // FROM needs commas only for tables, not joins
173*2f68434dSAndreas Gohr        $from = '';
174*2f68434dSAndreas Gohr        foreach($this->from as $alias => $statement) {
175*2f68434dSAndreas Gohr            if($this->type[$alias] == 'table' && $from) {
176*2f68434dSAndreas Gohr                $from .= ",\n";
177*2f68434dSAndreas Gohr            } else {
178*2f68434dSAndreas Gohr                $from .= "\n";
179*2f68434dSAndreas Gohr            }
180*2f68434dSAndreas Gohr
181*2f68434dSAndreas Gohr            $from .= $statement;
182*2f68434dSAndreas Gohr        }
183*2f68434dSAndreas Gohr
1848c551fd7SAndreas Gohr        $sql =
1858c551fd7SAndreas Gohr            ' SELECT ' . join(",\n", $this->select) . "\n" .
186*2f68434dSAndreas Gohr            '   FROM ' . $from . "\n" .
1878c551fd7SAndreas Gohr            '  WHERE ' . $this->where->toSQL() . "\n";
1888c551fd7SAndreas Gohr
18983cb959bSAndreas Gohr        if($this->groupby) {
19083cb959bSAndreas Gohr            $sql .=
19183cb959bSAndreas Gohr                'GROUP BY ' . join(",\n", $this->groupby) . "\n";
19283cb959bSAndreas Gohr        }
19383cb959bSAndreas Gohr
194*2f68434dSAndreas Gohr        if($this->orderby) {
195*2f68434dSAndreas Gohr            $sql .=
196*2f68434dSAndreas Gohr                'ORDER BY ' . join(",\n", $this->orderby) . "\n";
197*2f68434dSAndreas Gohr        }
198*2f68434dSAndreas Gohr
1998c551fd7SAndreas Gohr        return $this->fixPlaceholders($sql);
2008c551fd7SAndreas Gohr    }
2018c551fd7SAndreas Gohr
2028c551fd7SAndreas Gohr    /**
2038c551fd7SAndreas Gohr     * Replaces the named placeholders with ? placeholders
2048c551fd7SAndreas Gohr     *
2058c551fd7SAndreas Gohr     * Until the sqlite plugin can use named placeholder properly
2068c551fd7SAndreas Gohr     *
2078c551fd7SAndreas Gohr     * @param string $sql
2088c551fd7SAndreas Gohr     * @return array
2098c551fd7SAndreas Gohr     */
2108c551fd7SAndreas Gohr    protected function fixPlaceholders($sql) {
2118c551fd7SAndreas Gohr        $vals = array();
2128c551fd7SAndreas Gohr
2138c551fd7SAndreas Gohr        while(preg_match('/(:!!val\d+!!:)/', $sql, $m)) {
2148c551fd7SAndreas Gohr            $pl = $m[1];
2152b5df26eSAndreas Gohr
2162b5df26eSAndreas Gohr            if(!isset($this->values[$pl])) throw new StructException('Placeholder not found');
2172b5df26eSAndreas Gohr
2182b5df26eSAndreas Gohr            $sql = preg_replace("/$pl/", '?', $sql, 1);
2198c551fd7SAndreas Gohr            $vals[] = $this->values[$pl];
2208c551fd7SAndreas Gohr        }
2218c551fd7SAndreas Gohr
2228c551fd7SAndreas Gohr        return array($sql, $vals);
2238c551fd7SAndreas Gohr    }
2248c551fd7SAndreas Gohr
2258c551fd7SAndreas Gohr    /**
2268c551fd7SAndreas Gohr     * Insert an array into another array at a given position in an associative array
2278c551fd7SAndreas Gohr     *
2288c551fd7SAndreas Gohr     * @param array $array The initial array
2298c551fd7SAndreas Gohr     * @param array $pairs The array to insert
2308c551fd7SAndreas Gohr     * @param string $key_pos The position at which to insert
2318c551fd7SAndreas Gohr     * @link https://gist.github.com/scribu/588429 simplified
2328c551fd7SAndreas Gohr     * @return array
2338c551fd7SAndreas Gohr     */
2348c551fd7SAndreas Gohr    protected function array_insert($array, $pairs, $key_pos) {
2358c551fd7SAndreas Gohr        $result = array_slice($array, 0, $key_pos);
2368c551fd7SAndreas Gohr        $result = array_merge($result, $pairs);
2378c551fd7SAndreas Gohr        $result = array_merge($result, array_slice($array, $key_pos));
2388c551fd7SAndreas Gohr        return $result;
2398c551fd7SAndreas Gohr    }
2408c551fd7SAndreas Gohr}
2418c551fd7SAndreas Gohr
242