master
ブランチ master
LittleBeast / src / Std / Lib / Db / Sqlite / Integrity.php
8 KB、192行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib\Db\Sqlite;
39
40/**
41 * PRAGMA integrity_check(ツリー・フリーリスト・インデックスの確認)
42 */
43final class Integrity {
44 private array $used = [];
45 private array $msgs = [];
46
47 public function __construct(private Pager $pager, private Btree $bt, private Schema $schema) {}
48
49 /**
50 * @return array 問題のメッセージ(無ければ空)
51 */
52 public function check(): array {
53 if ($this->pager->nPages === 0) return [];
54 $this->tree(1, null);
55 foreach ($this->schema->tables as $t) {
56 if (($t['root'] ?? 0) > 1) $this->tree($t['root'], null);
57 }
58 foreach ($this->schema->indexes as $idx) $this->tree($idx['root'], $idx);
59 $this->freelist();
60 $lock = intdiv(0x40000000, $this->pager->pageSize) + 1;
61 for ($p = 1; $p <= $this->pager->nPages; $p++) {
62 if (!isset($this->used[$p]) && $p !== $lock) $this->msgs[] = "ページ{$p}は使われていません";
63 }
64 if (empty($this->msgs)) $this->indexes();
65 return array_slice($this->msgs, 0, 100);
66 }
67
68 private function mark(int $p, string $what): bool {
69 if ($p < 1 || $p > $this->pager->nPages) {
70 $this->msgs[] = "{$what}:不正なページ番号{$p}";
71 return false;
72 }
73 if (isset($this->used[$p])) {
74 $this->msgs[] = "ページ{$p}が2回使われています({$this->used[$p]}、{$what})";
75 return false;
76 }
77 $this->used[$p] = $what;
78 return true;
79 }
80
81 private function tree(int $root, ?array $idx): void {
82 $depths = [];
83 $this->page($root, $idx, null, null, 0, $depths, $root);
84 if (count(array_unique($depths)) > 1) $this->msgs[] = "ツリー{$root}:葉の深さが違います";
85 }
86
87 private function page(int $pgno, ?array $idx, mixed $lo, mixed $hi, int $depth, array &$depths, int $root): void {
88 if (!$this->mark($pgno, "ツリー{$root}")) return;
89 try {
90 $p = $this->bt->page($pgno);
91 } catch (\Throwable $e) {
92 $this->msgs[] = "ページ{$pgno}:".$e->getMessage();
93 return;
94 }
95 if ($p->isTable() !== ($idx === null)) {
96 $this->msgs[] = "ページ{$pgno}:ツリーの種類が違います";
97 return;
98 }
99 $n = count($p->cells);
100 if ($n === 0 && $pgno !== $root && $p->isLeaf()) $this->msgs[] = "ページ{$pgno}:空の葉";
101 $prev = $lo;
102 for ($i = 0; $i <= $n; $i++) {
103 $key = null;
104 if ($i < $n) {
105 try {
106 $key = $p->isTable() ? $p->keys[$i] : $this->bt->key($p, $i);
107 } catch (\Throwable $e) {
108 $this->msgs[] = "ページ{$pgno}のセル{$i}:".$e->getMessage();
109 continue;
110 }
111 $this->overflow($p, $i, $root);
112 }
113 if (!$p->isLeaf()) $this->page($i < $n ? $p->left[$i] : $p->right, $idx, $prev, $i < $n ? $key : $hi, $depth + 1, $depths, $root);
114 if ($i === $n) break;
115 if ($p->isTable()) {
116 if ($prev !== null && ($p->isLeaf() ? $key <= $prev : $key < $prev)) $this->msgs[] = "ページ{$pgno}のセル{$i}:rowidの順番";
117 if ($hi !== null && $key > $hi) $this->msgs[] = "ページ{$pgno}のセル{$i}:rowidが親より大きい";
118 } else {
119 if ($prev !== null && Record::compareKeys($key, $prev, $idx['colls'], $idx['desc']) <= 0) $this->msgs[] = "ページ{$pgno}のセル{$i}:キーの順番";
120 if ($hi !== null && Record::compareKeys($key, $hi, $idx['colls'], $idx['desc']) >= 0) $this->msgs[] = "ページ{$pgno}のセル{$i}:キーが親より大きい";
121 }
122 $prev = $key;
123 }
124 if ($p->isLeaf()) $depths[] = $depth;
125 }
126
127 private function overflow(Page $p, int $i, int $root): void {
128 if (!$p->isLeaf() && $p->isTable()) return;
129 $c = $p->cells[$i];
130 $pos = 0;
131 $len = Record::getVarint($c, $pos);
132 if ($p->isTable()) Record::getVarint($c, $pos);
133 $local = $this->bt->localSize($len, $p->isTable());
134 if ($len <= $local) return;
135 $next = unpack('N', $c, $pos + $local)[1];
136 $need = intdiv($len - $local + $this->pager->usable - 5, $this->pager->usable - 4);
137 for ($k = 0; $k < $need; $k++) {
138 if (!$this->mark($next, "オーバーフロー(ツリー{$root})")) return;
139 $next = unpack('N', $this->pager->read($next))[1];
140 }
141 if ($next !== 0) $this->msgs[] = "ツリー{$root}:オーバーフローが長過ぎます";
142 }
143
144 private function freelist(): void {
145 $t = $this->pager->hdr['freeTrunk'];
146 $count = 0;
147 while ($t !== 0) {
148 if (!$this->mark($t, 'フリーリスト')) return;
149 $count++;
150 $raw = $this->pager->read($t);
151 $n = unpack('N', $raw, 4)[1];
152 if ($n > intdiv($this->pager->usable, 4) - 2) {
153 $this->msgs[] = "フリーリストのページ{$t}:数が不正です";
154 return;
155 }
156 for ($i = 0; $i < $n; $i++) {
157 $this->mark(unpack('N', $raw, 8 + $i * 4)[1], 'フリーリスト');
158 $count++;
159 }
160 $t = unpack('N', $raw)[1];
161 }
162 if ($count !== $this->pager->hdr['freeCount']) $this->msgs[] = "フリーリストのページ数:{$count}(ヘッダー:{$this->pager->hdr['freeCount']})";
163 }
164
165 /** インデックスとテーブルの行が合っているか */
166 private function indexes(): void {
167 foreach ($this->schema->indexes as $idx) {
168 $t = $this->schema->tables[$idx['table']] ?? null;
169 if (!$t || isset($t['unsupported'])) continue;
170 $n = 0;
171 foreach ($this->bt->indexScan($idx) as $key) {
172 $n++;
173 $rowid = end($key);
174 $rec = $this->bt->get($t['root'], $rowid);
175 if ($rec === null) {
176 $this->msgs[] = "インデックス{$idx['name']}:行{$rowid}がテーブルにありません";
177 continue;
178 }
179 $vals = Record::decode($rec);
180 foreach ($idx['cols'] as $k => $ci) {
181 $v = $ci === $t['ipk'] ? $rowid : ($vals[$ci] ?? null);
182 if (Record::compare($v, $key[$k], 'BINARY') !== 0 && $vals[$ci] !== null) {
183 $this->msgs[] = "インデックス{$idx['name']}:行{$rowid}の値が違います";
184 break;
185 }
186 }
187 }
188 $rows = $this->bt->count($t['root']);
189 if ($n !== $rows) $this->msgs[] = "インデックス{$idx['name']}:{$n}行(テーブルは{$rows}行)";
190 }
191 }
192}