1<?php
2/*
3    Copyright (C) 2016 Volker Krause <vkrause@kde.org>
4
5    Permission is hereby granted, free of charge, to any person obtaining
6    a copy of this software and associated documentation files (the
7    "Software"), to deal in the Software without restriction, including
8    without limitation the rights to use, copy, modify, merge, publish,
9    distribute, sublicense, and/or sell copies of the Software, and to
10    permit persons to whom the Software is furnished to do so, subject to
11    the following conditions:
12
13    The above copyright notice and this permission notice shall be included
14    in all copies or substantial portions of the Software.
15
16    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23*/
24
25require_once('schemaentryelement.php');
26require_once('utils.php');
27
28/** Represents a product schema entry. */
29class SchemaEntry
30{
31    public $name;
32    public $type;
33    public $elements = array();
34
35    private $entryId = -1;
36    private $m_product = null;
37
38    const SCALAR_TPYE = 'scalar';
39    const LIST_TYPE = 'list';
40    const MAP_TYPE = 'map';
41
42    public function __construct(Product $product)
43    {
44        $this->m_product = &$product;
45    }
46
47    /** Checks if this is a schema entry. */
48    public function isValid()
49    {
50        if ($this->type != self::SCALAR_TPYE && $this->type != self::LIST_TYPE && $this->type != self::MAP_TYPE)
51            return false;
52        if (!Utils::isValidIdentifier($this->name))
53            return false;
54        return true;
55    }
56
57    /** Checks if this is a scalar type, ie. samples go into the primary data table. */
58    public function isScalar()
59    {
60        return $this->type === self::SCALAR_TPYE;
61    }
62
63    /** Returns the product this entry belongs to. */
64    public function product()
65    {
66        return $this->m_product;
67    }
68
69    /** Load product schema from storage. */
70    static public function loadSchema(Datastore $db, Product &$product)
71    {
72        $stmt = $db->prepare('SELECT
73                tbl_schema.col_id, tbl_schema.col_name, tbl_schema.col_type, tbl_schema_element.col_name, tbl_schema_element.col_type
74            FROM tbl_schema_element JOIN tbl_schema ON (tbl_schema.col_id = tbl_schema_element.col_schema_id)
75            WHERE tbl_schema.col_product_id = :productId
76            ORDER BY tbl_schema.col_id
77        ');
78        $stmt->bindValue(':productId', $product->id(), PDO::PARAM_INT);
79        $db->execute($stmt);
80        $schema = array();
81        $entry = new SchemaEntry($product);
82        foreach ($stmt as $row) {
83            if ($entry->entryId != $row[0]) {
84                if ($entry->isValid()) {
85                    array_push($schema, $entry);
86                    $entry = new SchemaEntry($product);
87                }
88                $entry->entryId = $row[0];
89                $entry->name = $row[1];
90                $entry->type = $row[2];
91            }
92            $elem = new SchemaEntryElement($entry);
93            $elem->name = $row[3];
94            $elem->type = $row[4];
95            array_push($entry->elements, $elem);
96        }
97        if ($entry->isValid())
98            array_push($schema, $entry);
99
100        return $schema;
101    }
102
103    /** Insert a new schema entry into storage. */
104    public function insert(Datastore $db, $productId)
105    {
106        $stmt = $db->prepare('INSERT INTO
107            tbl_schema (col_product_id, col_name, col_type)
108            VALUES (:productId, :name, :type)
109        ');
110        $stmt->bindValue(':productId', $productId, PDO::PARAM_INT);
111        $stmt->bindValue(':name', $this->name, PDO::PARAM_STR);
112        $stmt->bindValue(':type', $this->type, PDO::PARAM_STR);
113        $db->execute($stmt);
114        $this->entryId = $db->pdoHandle()->lastInsertId();
115
116        // add secondary data tables for non-scalars
117        switch ($this->type) {
118            case self::LIST_TYPE:
119                $this->createListDataTable($db);
120                break;
121            case self::MAP_TYPE:
122                $this->createMapDataTable($db);
123                break;
124        }
125
126        // add elements (which will create data table columns, so this needs to be last)
127        foreach ($this->elements as $elem)
128            $elem->insert($db, $this->entryId);
129    }
130
131    /** Update this schema entry in storage. */
132    public function update(Datastore $db, SchemaEntry $newEntry)
133    {
134        // TODO reject type changes
135
136        // update elements
137        $oldElements = array();
138        foreach ($this->elements as $oldElem)
139            $oldElements[$oldElem->name] = $oldElem;
140
141        foreach ($newEntry->elements as $newElem) {
142            if (array_key_exists($newElem->name, $oldElements)) {
143                // update
144                // TODO this would require type conversion of the data!?
145            } else {
146                // insert
147                $newElem->insert($db, $this->entryId);
148            }
149            unset($oldElements[$newElem->name]);
150        }
151
152        // delete whatever is left
153        foreach($oldElements as $elem) {
154            $elem->dropDataColumn($db);
155            $elem->delete($db, $this->entryId);
156        }
157    }
158
159    /** Delete this schema entry from storage. */
160    public function delete(Datastore $db, $productId)
161    {
162        // delete data
163        if ($this->isScalar()) {
164            foreach ($this->elements as $elem)
165                $elem->dropDataColumn($db);
166        } else {
167            $this->dropDataTable($db);
168        }
169
170        // delete elements
171        $stmt = $db->prepare('DELETE FROM tbl_schema_element WHERE col_schema_id = :id');
172        $stmt->bindValue(':id', $this->entryId, PDO::PARAM_INT);
173        $db->execute($stmt);
174
175        // delete entry
176        $stmt = $db->prepare('DELETE FROM tbl_schema WHERE col_id = :id');
177        $stmt->bindValue(':id', $this->entryId, PDO::PARAM_INT);
178        $db->execute($stmt);
179    }
180
181    /** Convert a JSON object into an array of SchemaEntry instances. */
182    static public function fromJson($jsonArray, Product &$product)
183    {
184        $entries = array();
185        foreach ($jsonArray as $jsonObj) {
186            if (!property_exists($jsonObj, 'name') || !property_exists($jsonObj, 'type'))
187                throw new RESTException('Incomplete schema entry object.', 400);
188            $e = new SchemaEntry($product);
189            $e->name = strval($jsonObj->name);
190            $e->type = strval($jsonObj->type);
191            if (property_exists($jsonObj, 'elements'))
192                $e->elements = SchemaEntryElement::fromJson($jsonObj->elements, $e);
193            if (!$e->isValid())
194                throw new RESTException('Invalid schema entry.', 400);
195            array_push($entries, $e);
196        }
197        return $entries;
198    }
199
200    /** Data table name for secondary data tables. */
201    public function dataTableName()
202    {
203        $tableName = 'pd2_' . Utils::normalizeString($this->product()->name)
204            . '__' . Utils::normalizeString($this->name);
205        return strtolower($tableName);
206    }
207
208
209    /** Create secondary data tables for list types. */
210    private function createListDataTable(Datastore $db)
211    {
212        $stmt = $db->prepare('CREATE TABLE ' . $this->dataTableName(). ' ('
213            . Utils::primaryKeyColumnDeclaration($db->driver(), 'col_id') . ', '
214            . 'col_sample_id INTEGER REFERENCES ' . $this->product()->dataTableName() . '(col_id) ON DELETE CASCADE)'
215        );
216        $db->execute($stmt);
217    }
218
219    /** Create secondary data tables for map types. */
220    private function createMapDataTable(Datastore $db)
221    {
222        $stmt = $db->prepare('CREATE TABLE ' . $this->dataTableName(). ' ('
223            . Utils::primaryKeyColumnDeclaration($db->driver(), 'col_id') . ', '
224            . 'col_sample_id INTEGER REFERENCES ' . $this->product()->dataTableName() . '(col_id) ON DELETE CASCADE, '
225            . 'col_key ' . Utils::sqlStringType($db->driver()) . ' NOT NULL)'
226        );
227        $db->execute($stmt);
228    }
229
230    /** Drop secondary data tables for non-scalar types. */
231    private function dropDataTable(Datastore $db)
232    {
233        $stmt = $db->prepare('DROP TABLE ' . $this->dataTableName());
234        $db->execute($stmt);
235    }
236}
237
238?>
239