summaryrefslogtreecommitdiffstats
path: root/library/Director/Data/Db/DbObjectStore.php
blob: bc69b5ad41853b032c2eeb70862849a580e09e1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<?php

namespace Icinga\Module\Director\Data\Db;

use Icinga\Module\Director\Db;
use Icinga\Module\Director\Db\Branch\Branch;
use Icinga\Module\Director\Db\Branch\BranchActivity;
use Icinga\Module\Director\Db\Branch\BranchedObject;
use Icinga\Module\Director\Db\Branch\MergeErrorDeleteMissingObject;
use Icinga\Module\Director\Db\Branch\MergeErrorModificationForMissingObject;
use Icinga\Module\Director\Db\Branch\MergeErrorRecreateOnMerge;
use Icinga\Module\Director\Db\DbUtil;
use Icinga\Module\Director\Objects\IcingaObject;
use Ramsey\Uuid\UuidInterface;

/**
 * Loader for Icinga/DbObjects
 *
 * Is aware of branches and prefetching. I would prefer to see a StoreInterface,
 * with one of the above wrapping the other. But for now, this helps to clean things
 * up
 */
class DbObjectStore
{
    /** @var Db */
    protected $connection;

    /** @var ?Branch */
    protected $branch;

    public function __construct(Db $connection, Branch $branch = null)
    {
        $this->connection = $connection;
        $this->branch = $branch;
    }

    /**
     * @param $tableName
     * @param UuidInterface $uuid
     * @return DbObject|null
     * @throws \Icinga\Exception\NotFoundError
     */
    public function load($tableName, UuidInterface $uuid)
    {
        $branchedObject = BranchedObject::load($this->connection, $tableName, $uuid, $this->branch);
        $object = $branchedObject->getBranchedDbObject($this->connection);
        if ($object === null) {
            return null;
        }

        $object->setBeingLoadedFromDb();

        return $object;
    }

    /**
     * @param string $tableName
     * @param string $arrayIdx
     * @return DbObject[]|IcingaObject[]
     * @throws MergeErrorRecreateOnMerge
     * @throws MergeErrorDeleteMissingObject
     * @throws MergeErrorModificationForMissingObject
     */
    public function loadAll($tableName, $arrayIdx = 'uuid')
    {
        $db = $this->connection->getDbAdapter();
        $class = DbObjectTypeRegistry::classByType($tableName);
        $query = $db->select()->from($tableName)->order($arrayIdx);
        $result = [];
        foreach ($db->fetchAll($query) as $row) {
            $row->uuid = DbUtil::binaryResult($row->uuid);
            $result[$row->uuid] = $class::create((array) $row, $this->connection);
            $result[$row->uuid]->setBeingLoadedFromDb();
        }
        if ($this->branch && $this->branch->isBranch()) {
            $query = $db->select()
                ->from(BranchActivity::DB_TABLE)
                ->where('branch_uuid = ?', $this->connection->quoteBinary($this->branch->getUuid()->getBytes()))
                ->order('timestamp_ns ASC');
            $rows = $db->fetchAll($query);
            foreach ($rows as $row) {
                $activity = BranchActivity::fromDbRow($row);
                if ($activity->getObjectTable() !== $tableName) {
                    continue;
                }
                $uuid = $activity->getObjectUuid();
                $binaryUuid = $uuid->getBytes();

                $exists = isset($result[$binaryUuid]);
                if ($activity->isActionCreate()) {
                    if ($exists) {
                        throw new MergeErrorRecreateOnMerge($activity);
                    } else {
                        $new = $activity->createDbObject($this->connection);
                        $new->setBeingLoadedFromDb();
                        $result[$binaryUuid] = $new;
                    }
                } elseif ($activity->isActionDelete()) {
                    if ($exists) {
                        unset($result[$binaryUuid]);
                    } else {
                        throw new MergeErrorDeleteMissingObject($activity);
                    }
                } else {
                    if ($exists) {
                        $activity->applyToDbObject($result[$binaryUuid])->setBeingLoadedFromDb();
                    } else {
                        throw new MergeErrorModificationForMissingObject($activity);
                    }
                }
            }
        }

        if ($arrayIdx === 'uuid') {
            return $result;
        }

        $indexedResult = [];
        foreach ($result as $object) {
            $indexedResult[$object->get($arrayIdx)] = $object;
        }

        return $indexedResult;
    }

    public function exists($tableName, UuidInterface $uuid)
    {
        return BranchedObject::exists($this->connection, $tableName, $uuid, $this->branch->getUuid());
    }

    public function store(DbObject $object)
    {
        if ($this->branch && $this->branch->isBranch()) {
            $activity = BranchActivity::forDbObject($object, $this->branch);
            $this->connection->runFailSafeTransaction(function () use ($activity) {
                $activity->store($this->connection);
                BranchedObject::withActivity($activity, $this->connection)->store($this->connection);
            });

            return true;
        } else {
            return $object->store($this->connection);
        }
    }

    public function delete(DbObject $object)
    {
        if ($this->branch && $this->branch->isBranch()) {
            $activity = BranchActivity::deleteObject($object, $this->branch);
            $this->connection->runFailSafeTransaction(function () use ($activity) {
                $activity->store($this->connection);
                BranchedObject::load(
                    $this->connection,
                    $activity->getObjectTable(),
                    $activity->getObjectUuid(),
                    $this->branch
                )->delete($this->connection);
            });
            return true;
        }

        return $object->delete();
    }

    public function getBranch()
    {
        return $this->branch;
    }
}