xref: /plugin/struct/meta/Search.php (revision 7059e7e1a02cfabd1f398aeb25ae4b1db66c5b4d)
115929be2SAndreas Gohr<?php
215929be2SAndreas Gohr
315929be2SAndreas Gohrnamespace plugin\struct\meta;
415929be2SAndreas Gohr
515929be2SAndreas Gohruse Exception;
615929be2SAndreas Gohr
715929be2SAndreas Gohrclass Search {
89d7a36f9SAndreas Gohr    /**
99d7a36f9SAndreas Gohr     * This separator will be used to concat multi values to flatten them in the result set
109d7a36f9SAndreas Gohr     */
119d7a36f9SAndreas Gohr    const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n";
129d7a36f9SAndreas Gohr
139d7a36f9SAndreas Gohr    /** @var  \helper_plugin_sqlite */
149d7a36f9SAndreas 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
259d7a36f9SAndreas Gohr    /** @var array the filters */
269d7a36f9SAndreas 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    /**
329d7a36f9SAndreas Gohr     * Search constructor.
339d7a36f9SAndreas Gohr     */
349d7a36f9SAndreas Gohr    public function __construct() {
359d7a36f9SAndreas Gohr        /** @var \helper_plugin_struct_db $plugin */
369d7a36f9SAndreas Gohr        $plugin = plugin_load('helper', 'struct_db');
379d7a36f9SAndreas Gohr        $this->sqlite = $plugin->getDB();
389d7a36f9SAndreas Gohr    }
399d7a36f9SAndreas Gohr
409d7a36f9SAndreas 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    /**
849d7a36f9SAndreas Gohr     * Adds a filter
8515929be2SAndreas Gohr     *
8615929be2SAndreas Gohr     * @param string $colname may contain an alias
8715929be2SAndreas Gohr     * @param string $value
889d7a36f9SAndreas Gohr     * @param string $comp ('=', '<', '>', '<=', '>=', '~')
899d7a36f9SAndreas Gohr     * @param string $type either 'OR' or 'AND'
9015929be2SAndreas Gohr     */
919d7a36f9SAndreas Gohr    public function addFilter($colname, $value, $comp, $type = 'OR') {
929d7a36f9SAndreas Gohr        if(!in_array($comp, array('<', '>', '<=', '>=', '~'))) throw new SearchException("Bad comperator. Use '=', '<', '>', '<=', '>=' or '~'");
939d7a36f9SAndreas Gohr        if($type != 'OR' && $type != 'AND') throw new SearchException('Bad filter type . Only AND or OR allowed');
949d7a36f9SAndreas Gohr
9515929be2SAndreas Gohr        $col = $this->findColumn($colname);
9615929be2SAndreas Gohr        if(!$col) return; //FIXME do we really want to ignore missing columns?
9715929be2SAndreas Gohr
989d7a36f9SAndreas 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 = '';
1119d7a36f9SAndreas Gohr        $select = '';
1129d7a36f9SAndreas Gohr        $order = '';
1139d7a36f9SAndreas Gohr        $grouping = array();
1149d7a36f9SAndreas Gohr        $opts = array();
1159d7a36f9SAndreas Gohr        $where = '1 = 1';
11615929be2SAndreas Gohr
1179d7a36f9SAndreas Gohr        // basic tables
1189d7a36f9SAndreas Gohr        $first = '';
1199d7a36f9SAndreas Gohr        foreach($this->schemas as $schema) {
1209d7a36f9SAndreas Gohr            if($first) {
1219d7a36f9SAndreas Gohr                // follow up tables
1229d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid";
1239d7a36f9SAndreas Gohr            } else {
1249d7a36f9SAndreas Gohr                // first table
1259d7a36f9SAndreas Gohr                $select .= "data_{$schema->getTable()}.pid as PID, ";
1269d7a36f9SAndreas Gohr                $from .= "data_{$schema->getTable()}";
1279d7a36f9SAndreas Gohr                $first = $schema->getTable();
12815929be2SAndreas Gohr            }
129*7059e7e1SAndreas Gohr
130*7059e7e1SAndreas Gohr            $where .= "\nAND data_{$schema->getTable()}.latest = 1";
1319d7a36f9SAndreas Gohr        }
13215929be2SAndreas Gohr
13315929be2SAndreas Gohr        // columns to select, handling multis
1349d7a36f9SAndreas Gohr        $sep = self::CONCAT_SEPARATOR;
13515929be2SAndreas Gohr        $n = 0;
13615929be2SAndreas Gohr        foreach($this->columns as $col) {
13715929be2SAndreas Gohr            $CN = 'C' . $n++;
13815929be2SAndreas Gohr
13915929be2SAndreas Gohr            if($col->isMulti()) {
14015929be2SAndreas Gohr                $tn = 'M' . $col->getColref();
1419d7a36f9SAndreas Gohr                $select .= "GROUP_CONCAT($tn.value, '$sep') AS $CN, ";
1429d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multivals AS $tn";
1439d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
14415929be2SAndreas Gohr                $from .= " AND $tn.tbl = '{$col->getTable()}' AND $tn.colref = {$col->getColref()}\n";
14515929be2SAndreas Gohr            } else {
14615929be2SAndreas Gohr                $select .= 'data_' . $col->getTable() . ' . col' . $col->getColref() . " AS $CN, ";
1479d7a36f9SAndreas Gohr                $grouping[] = $CN;
14815929be2SAndreas Gohr            }
14915929be2SAndreas Gohr        }
15015929be2SAndreas Gohr        $select = rtrim($select, ', ');
15115929be2SAndreas Gohr
1529d7a36f9SAndreas Gohr        // where clauses
153b8fe6730SAndreas Gohr        foreach($this->filter as $filter) {
154b8fe6730SAndreas Gohr            list($col, $value, $comp, $type) = $filter;
155b8fe6730SAndreas Gohr
1569d7a36f9SAndreas Gohr            /** @var $col Column */
1579d7a36f9SAndreas Gohr            if($col->isMulti()) {
1589d7a36f9SAndreas Gohr                $tn = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before
1599d7a36f9SAndreas Gohr                $from .= "\nLEFT OUTER JOIN multivals AS $tn";
1609d7a36f9SAndreas Gohr                $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev";
1619d7a36f9SAndreas Gohr                $from .= " AND $tn.tbl = '{$col->getTable()}' AND $tn.colref = {$col->getColref()}\n";
16215929be2SAndreas Gohr
1639d7a36f9SAndreas Gohr                $column = "$tn.value";
1649d7a36f9SAndreas Gohr            } else {
1659d7a36f9SAndreas Gohr                $column = "data_{$col->getTable()}.col{$col->getColref()}";
1669d7a36f9SAndreas Gohr            }
1679d7a36f9SAndreas Gohr
1689d7a36f9SAndreas Gohr            list($wsql, $wopt) = $col->getType()->compare($column, $comp, $value);
1699d7a36f9SAndreas Gohr            $opts = array_merge($opts, $wopt);
1709d7a36f9SAndreas Gohr
1719d7a36f9SAndreas Gohr            $where .= " $type $wsql";
1729d7a36f9SAndreas Gohr        }
1739d7a36f9SAndreas Gohr
1749d7a36f9SAndreas Gohr        // sorting
175b8fe6730SAndreas Gohr        foreach($this->sortby as $sort) {
176b8fe6730SAndreas Gohr            list($col, $asc) = $sort;
177b8fe6730SAndreas Gohr
1789d7a36f9SAndreas Gohr            /** @var $col Column */
1799d7a36f9SAndreas Gohr            if($col->isMulti()) {
1809d7a36f9SAndreas Gohr                // FIXME how to sort by multival?
1819d7a36f9SAndreas Gohr                // FIXME what if sort by non merged multival?
1829d7a36f9SAndreas Gohr            } else {
1839d7a36f9SAndreas Gohr                $order .= "data_{$col->getTable()}.col{$col->getColref()} ";
1849d7a36f9SAndreas Gohr                $order .= ($asc) ? 'ASC' : 'DESC';
1859d7a36f9SAndreas Gohr                $order .= ', ';
1869d7a36f9SAndreas Gohr            }
1879d7a36f9SAndreas Gohr        }
1889d7a36f9SAndreas Gohr        $order = rtrim($order, ', ');
1899d7a36f9SAndreas Gohr
1909d7a36f9SAndreas Gohr        $sql = "SELECT $select\n  FROM $from\nWHERE $where\nGROUP BY " . join(', ', $grouping);
1919d7a36f9SAndreas Gohr        if($order) $sql .= "\nORDER BY $order";
1929d7a36f9SAndreas Gohr
1939d7a36f9SAndreas Gohr        {#debugging
1949d7a36f9SAndreas Gohr            $res = $this->sqlite->query($sql, $opts);
1959d7a36f9SAndreas Gohr            $data = $this->sqlite->res2arr($res);
1969d7a36f9SAndreas Gohr            $this->sqlite->res_close($res);
1979d7a36f9SAndreas Gohr            print_r($data);
1989d7a36f9SAndreas Gohr        }
1999d7a36f9SAndreas Gohr
20015929be2SAndreas Gohr        return $sql;
20115929be2SAndreas Gohr    }
20215929be2SAndreas Gohr
20315929be2SAndreas Gohr    /**
20415929be2SAndreas Gohr     * Find a column to be used in the search
20515929be2SAndreas Gohr     *
20615929be2SAndreas Gohr     * @param string $colname may contain an alias
20715929be2SAndreas Gohr     * @return bool|Column
20815929be2SAndreas Gohr     */
20915929be2SAndreas Gohr    protected function findColumn($colname) {
21015929be2SAndreas Gohr        if(!$this->schemas) throw new SearchException('noschemas');
21115929be2SAndreas Gohr
21215929be2SAndreas Gohr        // resolve the alias or table name
21315929be2SAndreas Gohr        list($table, $colname) = explode('.', $colname, 2);
21415929be2SAndreas Gohr        if(!$colname) {
21515929be2SAndreas Gohr            $colname = $table;
21615929be2SAndreas Gohr            $table = '';
21715929be2SAndreas Gohr        }
21815929be2SAndreas Gohr        if($table && isset($this->aliases[$table])) {
21915929be2SAndreas Gohr            $table = $this->aliases[$table];
22015929be2SAndreas Gohr        }
22115929be2SAndreas Gohr
22215929be2SAndreas Gohr        if(!$colname) throw new SearchException('nocolname');
22315929be2SAndreas Gohr
22415929be2SAndreas Gohr        // if table name given search only that, otherwiese try all for matching column name
22515929be2SAndreas Gohr        if($table) {
22615929be2SAndreas Gohr            $schemas = array($table => $this->schemas[$table]);
22715929be2SAndreas Gohr        } else {
22815929be2SAndreas Gohr            $schemas = $this->schemas;
22915929be2SAndreas Gohr        }
23015929be2SAndreas Gohr
23115929be2SAndreas Gohr        // find it
23215929be2SAndreas Gohr        $col = false;
23315929be2SAndreas Gohr        foreach($schemas as $schema) {
23415929be2SAndreas Gohr            $col = $schema->findColumn($colname);
23515929be2SAndreas Gohr            if($col) break;
23615929be2SAndreas Gohr        }
23715929be2SAndreas Gohr
23815929be2SAndreas Gohr        return $col;
23915929be2SAndreas Gohr    }
24015929be2SAndreas Gohr
24115929be2SAndreas Gohr}
24215929be2SAndreas Gohr
24315929be2SAndreas Gohr/**
24415929be2SAndreas Gohr * Class SearchException
24515929be2SAndreas Gohr *
24615929be2SAndreas Gohr * A translatable exception
24715929be2SAndreas Gohr *
24815929be2SAndreas Gohr * @package plugin\struct\meta
24915929be2SAndreas Gohr */
25015929be2SAndreas Gohrclass SearchException extends \RuntimeException {
25115929be2SAndreas Gohr    public function __construct($message, $code = -1, Exception $previous = null) {
25215929be2SAndreas Gohr        /** @var \action_plugin_struct_autoloader $plugin */
25315929be2SAndreas Gohr        $plugin = plugin_load('action', 'struct_autoloader');
25415929be2SAndreas Gohr        $trans = $plugin->getLang('searchex_' . $message);
25515929be2SAndreas Gohr        if(!$trans) $trans = $message;
25615929be2SAndreas Gohr        parent::__construct($trans, $code, $previous);
25715929be2SAndreas Gohr    }
25815929be2SAndreas Gohr}
259