xref: /plugin/struct/meta/Search.php (revision 9d7a36f9d8dd8c59ffc141b6e9f555d7b36c075f)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
315929be2SAndreas Gohrnamespace plugin\struct\meta;
415929be2SAndreas Gohr
515929be2SAndreas Gohruse Exception;
615929be2SAndreas Gohr
715929be2SAndreas Gohrclass Search {
8*9d7a36f9SAndreas Gohr    /**
9*9d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
10*9d7a36f9SAndreas Gohr     */
11*9d7a36f9SAndreas Gohr    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
12*9d7a36f9SAndreas Gohr
13*9d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
14*9d7a36f9SAndreas Gohr    protected $sqlite;
1515929be2SAndreas Gohr
1615929be2SAndreas Gohr    /** @var Schema[] list of schemas to query */
1715929be2SAndreas Gohr    protected $schemas = array();
1815929be2SAndreas Gohr
1915929be2SAndreas Gohr    /** @var Column[] list of columns to select */
2015929be2SAndreas Gohr    protected $columns = array();
2115929be2SAndreas Gohr
2215929be2SAndreas Gohr    /** @var array the sorting of the result */
2315929be2SAndreas Gohr    protected $sortby = array();
2415929be2SAndreas Gohr
25*9d7a36f9SAndreas Gohr    /** @var array the filters */
26*9d7a36f9SAndreas Gohr    protected $filter = array();
2715929be2SAndreas Gohr
2815929be2SAndreas Gohr    /** @var array list of aliases tables can be referenced by */
2915929be2SAndreas Gohr    protected $aliases = array();
3015929be2SAndreas Gohr
3115929be2SAndreas Gohr    /**
32*9d7a36f9SAndreas Gohr     * Search constructor.
33*9d7a36f9SAndreas Gohr     */
34*9d7a36f9SAndreas Gohr    public function __construct() {
35*9d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
36*9d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
37*9d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
38*9d7a36f9SAndreas Gohr    }
39*9d7a36f9SAndreas Gohr
40*9d7a36f9SAndreas Gohr    /**
4115929be2SAndreas Gohr     * Add a schema to be searched
4215929be2SAndreas Gohr     *
4315929be2SAndreas Gohr     * Call multiple times for multiple schemas.
4415929be2SAndreas Gohr     *
4515929be2SAndreas Gohr     * @param string $table
4615929be2SAndreas Gohr     * @param string $alias
4715929be2SAndreas Gohr     */
4815929be2SAndreas Gohr    public function addSchema($table, $alias = '') {
4915929be2SAndreas Gohr        $this->schemas[$table] = new Schema($table);
5015929be2SAndreas Gohr        if($alias) $this->aliases[$alias] = $table;
5115929be2SAndreas Gohr    }
5215929be2SAndreas Gohr
5315929be2SAndreas Gohr    /**
5415929be2SAndreas Gohr     * Add a column to be returned by the search
5515929be2SAndreas Gohr     *
5615929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
5715929be2SAndreas Gohr     * added before
5815929be2SAndreas Gohr     *
5915929be2SAndreas Gohr     * @param string $colname may contain an alias
6015929be2SAndreas Gohr     */
6115929be2SAndreas Gohr    public function addColumn($colname) {
6215929be2SAndreas Gohr        $col = $this->findColumn($colname);
6315929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
6415929be2SAndreas Gohr        $this->columns[] = $col;
6515929be2SAndreas Gohr    }
6615929be2SAndreas Gohr
6715929be2SAndreas Gohr    /**
6815929be2SAndreas Gohr     * Add sorting options
6915929be2SAndreas Gohr     *
7015929be2SAndreas Gohr     * Call multiple times for multiple columns. Be sure the referenced tables have been
7115929be2SAndreas Gohr     * added before
7215929be2SAndreas Gohr     *
7315929be2SAndreas Gohr     * @param string $colname may contain an alias
7415929be2SAndreas Gohr     * @param bool $asc sort direction (ASC = true, DESC = false)
7515929be2SAndreas Gohr     */
7615929be2SAndreas Gohr    public function addSort($colname, $asc = true) {
7715929be2SAndreas Gohr        $col = $this->findColumn($colname);
7815929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
7915929be2SAndreas Gohr
8015929be2SAndreas Gohr        $this->sortby[] = array($col, $asc);
8115929be2SAndreas Gohr    }
8215929be2SAndreas Gohr
8315929be2SAndreas Gohr    /**
84*9d7a36f9SAndreas Gohr     * Adds a filter
8515929be2SAndreas Gohr     *
8615929be2SAndreas Gohr     * @param string $colname may contain an alias
8715929be2SAndreas Gohr     * @param string $value
88*9d7a36f9SAndreas Gohr     * @param string $comp ('=', '<', '>', '<=', '>=', '~')
89*9d7a36f9SAndreas Gohr     * @param string $type either 'OR' or 'AND'
9015929be2SAndreas Gohr     */
91*9d7a36f9SAndreas Gohr    public function addFilter($colname, $value, $comp, $type = 'OR') {
92*9d7a36f9SAndreas Gohr        if(!in_array($comp, array('<', '>', '<=', '>=', '~'))) throw new SearchException("Bad comperator. Use '=', '<', '>', '<=', '>=' or '~'");
93*9d7a36f9SAndreas Gohr        if($type != 'OR' && $type != 'AND') throw new SearchException('Bad filter type . Only AND or OR allowed');
94*9d7a36f9SAndreas Gohr
9515929be2SAndreas Gohr        $col = $this->findColumn($colname);
9615929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
9715929be2SAndreas Gohr
98*9d7a36f9SAndreas Gohr        $this->filter[] = array($col, $value, $comp, $type);
9915929be2SAndreas Gohr    }
10015929be2SAndreas Gohr
10115929be2SAndreas Gohr    /**
10215929be2SAndreas Gohr     * Transform the set search parameters into a statement
10315929be2SAndreas Gohr     *
10415929be2SAndreas Gohr     * @todo limit to the newest data!
10515929be2SAndreas Gohr     * @return string
10615929be2SAndreas Gohr     */
10715929be2SAndreas Gohr    public function getSQL() {
10815929be2SAndreas Gohr        if(!$this->columns) throw new SearchException('nocolname');
10915929be2SAndreas Gohr
11015929be2SAndreas Gohr        $from = '';
111*9d7a36f9SAndreas Gohr        $select = '';
112*9d7a36f9SAndreas Gohr        $order = '';
113*9d7a36f9SAndreas Gohr        $grouping = array();
114*9d7a36f9SAndreas Gohr        $opts = array();
115*9d7a36f9SAndreas Gohr        $where = '1 = 1';
11615929be2SAndreas Gohr
117*9d7a36f9SAndreas Gohr        // basic tables
118*9d7a36f9SAndreas Gohr        $first = '';
119*9d7a36f9SAndreas Gohr        foreach($this->schemas as $schema) {
120*9d7a36f9SAndreas Gohr            if($first) {
121*9d7a36f9SAndreas Gohr                // follow up tables
122*9d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid";
123*9d7a36f9SAndreas Gohr            } else {
124*9d7a36f9SAndreas Gohr                // first table
125*9d7a36f9SAndreas Gohr                $select .= "data_{$schema->getTable()}.pid as PID, ";
126*9d7a36f9SAndreas Gohr                $from .= "data_{$schema->getTable()}";
127*9d7a36f9SAndreas Gohr                $first = $schema->getTable();
12815929be2SAndreas Gohr            }
129*9d7a36f9SAndreas Gohr        }
13015929be2SAndreas Gohr
13115929be2SAndreas Gohr        // columns to select, handling multis
132*9d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
13315929be2SAndreas Gohr        $n = 0;
13415929be2SAndreas Gohr        foreach($this->columns as $col) {
13515929be2SAndreas Gohr            $CN = 'C' . $n++;
13615929be2SAndreas Gohr
13715929be2SAndreas Gohr            if($col->isMulti()) {
13815929be2SAndreas Gohr                $tn = 'M' . $col->getColref();
139*9d7a36f9SAndreas Gohr                $select .= "GROUP_CONCAT($tn.value, '$sep') AS $CN, ";
140*9d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multivals AS $tn";
141*9d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
14215929be2SAndreas Gohr                $from .= " AND $tn.tbl = '{$col->getTable()}' AND $tn.colref = {$col->getColref()}\n";
14315929be2SAndreas Gohr            } else {
14415929be2SAndreas Gohr                $select .= 'data_' . $col->getTable() . ' . col' . $col->getColref() . " AS $CN, ";
145*9d7a36f9SAndreas Gohr                $grouping[] = $CN;
14615929be2SAndreas Gohr            }
14715929be2SAndreas Gohr        }
14815929be2SAndreas Gohr        $select = rtrim($select, ', ');
14915929be2SAndreas Gohr
150*9d7a36f9SAndreas Gohr        // where clauses
151*9d7a36f9SAndreas Gohr        foreach($this->filter as list($col, $value, $comp, $type)) {
152*9d7a36f9SAndreas Gohr            /** @var $col Column */
153*9d7a36f9SAndreas Gohr            if($col->isMulti()) {
154*9d7a36f9SAndreas Gohr                $tn = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
155*9d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multivals AS $tn";
156*9d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
157*9d7a36f9SAndreas Gohr                $from .= " AND $tn.tbl = '{$col->getTable()}' AND $tn.colref = {$col->getColref()}\n";
15815929be2SAndreas Gohr
159*9d7a36f9SAndreas Gohr                $column = "$tn.value";
160*9d7a36f9SAndreas Gohr            } else {
161*9d7a36f9SAndreas Gohr                $column = "data_{$col->getTable()}.col{$col->getColref()}";
162*9d7a36f9SAndreas Gohr            }
163*9d7a36f9SAndreas Gohr
164*9d7a36f9SAndreas Gohr            list($wsql, $wopt) = $col->getType()->compare($column, $comp, $value);
165*9d7a36f9SAndreas Gohr            $opts = array_merge($opts, $wopt);
166*9d7a36f9SAndreas Gohr
167*9d7a36f9SAndreas Gohr            $where .= " $type $wsql";
168*9d7a36f9SAndreas Gohr        }
169*9d7a36f9SAndreas Gohr
170*9d7a36f9SAndreas Gohr        // sorting
171*9d7a36f9SAndreas Gohr        foreach($this->sortby as list($col, $asc)) {
172*9d7a36f9SAndreas Gohr            /** @var $col Column */
173*9d7a36f9SAndreas Gohr            if($col->isMulti()) {
174*9d7a36f9SAndreas Gohr                // FIXME how to sort by multival?
175*9d7a36f9SAndreas Gohr                // FIXME what if sort by non merged multival?
176*9d7a36f9SAndreas Gohr            } else {
177*9d7a36f9SAndreas Gohr                $order .= "data_{$col->getTable()}.col{$col->getColref()} ";
178*9d7a36f9SAndreas Gohr                $order .= ($asc) ? 'ASC' : 'DESC';
179*9d7a36f9SAndreas Gohr                $order .= ', ';
180*9d7a36f9SAndreas Gohr            }
181*9d7a36f9SAndreas Gohr        }
182*9d7a36f9SAndreas Gohr        $order = rtrim($order, ', ');
183*9d7a36f9SAndreas Gohr
184*9d7a36f9SAndreas Gohr        $sql = "SELECT $select\n  FROM $from\nWHERE $where\nGROUP BY " . join(', ', $grouping);
185*9d7a36f9SAndreas Gohr        if($order) $sql .= "\nORDER BY $order";
186*9d7a36f9SAndreas Gohr
187*9d7a36f9SAndreas Gohr        {#debugging
188*9d7a36f9SAndreas Gohr            $res = $this->sqlite->query($sql, $opts);
189*9d7a36f9SAndreas Gohr            $data = $this->sqlite->res2arr($res);
190*9d7a36f9SAndreas Gohr            $this->sqlite->res_close($res);
191*9d7a36f9SAndreas Gohr            print_r($data);
192*9d7a36f9SAndreas Gohr        }
193*9d7a36f9SAndreas Gohr
19415929be2SAndreas Gohr        return $sql;
19515929be2SAndreas Gohr    }
19615929be2SAndreas Gohr
19715929be2SAndreas Gohr    /**
19815929be2SAndreas Gohr     * Find a column to be used in the search
19915929be2SAndreas Gohr     *
20015929be2SAndreas Gohr     * @param string $colname may contain an alias
20115929be2SAndreas Gohr     * @return bool|Column
20215929be2SAndreas Gohr     */
20315929be2SAndreas Gohr    protected function findColumn($colname) {
20415929be2SAndreas Gohr        if(!$this->schemas) throw new SearchException('noschemas');
20515929be2SAndreas Gohr
20615929be2SAndreas Gohr        // resolve the alias or table name
20715929be2SAndreas Gohr        list($table, $colname) = explode('.', $colname, 2);
20815929be2SAndreas Gohr        if(!$colname) {
20915929be2SAndreas Gohr            $colname = $table;
21015929be2SAndreas Gohr            $table = '';
21115929be2SAndreas Gohr        }
21215929be2SAndreas Gohr        if($table && isset($this->aliases[$table])) {
21315929be2SAndreas Gohr            $table = $this->aliases[$table];
21415929be2SAndreas Gohr        }
21515929be2SAndreas Gohr
21615929be2SAndreas Gohr        if(!$colname) throw new SearchException('nocolname');
21715929be2SAndreas Gohr
21815929be2SAndreas Gohr        // if table name given search only that, otherwiese try all for matching column name
21915929be2SAndreas Gohr        if($table) {
22015929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
22115929be2SAndreas Gohr        } else {
22215929be2SAndreas Gohr            $schemas = $this->schemas;
22315929be2SAndreas Gohr        }
22415929be2SAndreas Gohr
22515929be2SAndreas Gohr        // find it
22615929be2SAndreas Gohr        $col = false;
22715929be2SAndreas Gohr        foreach($schemas as $schema) {
22815929be2SAndreas Gohr            $col = $schema->findColumn($colname);
22915929be2SAndreas Gohr            if($col) break;
23015929be2SAndreas Gohr        }
23115929be2SAndreas Gohr
23215929be2SAndreas Gohr        return $col;
23315929be2SAndreas Gohr    }
23415929be2SAndreas Gohr
23515929be2SAndreas Gohr}
23615929be2SAndreas Gohr
23715929be2SAndreas Gohr/**
23815929be2SAndreas Gohr * Class SearchException
23915929be2SAndreas Gohr *
24015929be2SAndreas Gohr * A translatable exception
24115929be2SAndreas Gohr *
24215929be2SAndreas Gohr * @package plugin\struct\meta
24315929be2SAndreas Gohr */
24415929be2SAndreas Gohrclass SearchException extends \RuntimeException {
24515929be2SAndreas Gohr    public function __construct($message, $code = -1, Exception $previous = null) {
24615929be2SAndreas Gohr        /** @var \action_plugin_struct_autoloader $plugin */
24715929be2SAndreas Gohr        $plugin = plugin_load('action', 'struct_autoloader');
24815929be2SAndreas Gohr        $trans = $plugin->getLang('searchex_' . $message);
24915929be2SAndreas Gohr        if(!$trans) $trans = $message;
25015929be2SAndreas Gohr        parent::__construct($trans, $code, $previous);
25115929be2SAndreas Gohr    }
25215929be2SAndreas Gohr}
253