forked from codeigniter4/settings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseHandler.php
More file actions
357 lines (302 loc) · 11.2 KB
/
DatabaseHandler.php
File metadata and controls
357 lines (302 loc) · 11.2 KB
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<?php
declare(strict_types=1);
namespace CodeIgniter\Settings\Handlers;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\I18n\Time;
use CodeIgniter\Settings\Config\Settings;
use RuntimeException;
/**
* Provides database persistence for Settings.
* Uses ArrayHandler for storage to minimize database calls.
*/
class DatabaseHandler extends ArrayHandler
{
/**
* The DB connection for the Settings.
*/
private readonly BaseConnection $db;
/**
* The Query Builder for the Settings table.
*/
private readonly BaseBuilder $builder;
/**
* Array of contexts that have been stored.
*
* @var list<null>|list<string>
*/
private array $hydrated = [];
private readonly Settings $config;
/**
* Stores the configured database table.
*/
public function __construct()
{
$this->config = config('Settings');
$this->db = db_connect($this->config->database['group']);
$this->builder = $this->db->table($this->config->database['table']);
$this->setupDeferredWrites($this->config->database['deferWrites'] ?? false);
}
/**
* Checks whether this handler has a value set.
*/
public function has(string $class, string $property, ?string $context = null): bool
{
$this->hydrate($context);
return $this->hasStored($class, $property, $context);
}
/**
* Attempt to retrieve a value from the database.
* To boost performance, all of the values are
* read and stored the first call for each contexts
* and then retrieved from storage.
*
* @return mixed
*/
public function get(string $class, string $property, ?string $context = null)
{
return $this->getStored($class, $property, $context);
}
/**
* Stores values into the database for later retrieval.
*
* @param mixed $value
*
* @throws RuntimeException For database failures
*/
public function set(string $class, string $property, $value = null, ?string $context = null): void
{
if ($this->deferWrites) {
$this->markPending($class, $property, $value, $context);
} else {
$this->persist($class, $property, $value, $context);
}
// Update storage after persistence check
$this->setStored($class, $property, $value, $context);
}
/**
* Persists a single property to the database.
*
* @param mixed $value
*
* @throws RuntimeException For database failures
*/
private function persist(string $class, string $property, $value, ?string $context): void
{
$time = Time::now()->format('Y-m-d H:i:s');
$type = gettype($value);
$prepared = $this->prepareValue($value);
// If it was stored then we need to update
if ($this->has($class, $property, $context)) {
$result = $this->builder
->where('class', $class)
->where('key', $property)
->where('context', $context)
->update([
'value' => $prepared,
'type' => $type,
'context' => $context,
'updated_at' => $time,
]);
// ...otherwise insert it
} else {
$result = $this->builder
->insert([
'class' => $class,
'key' => $property,
'value' => $prepared,
'type' => $type,
'context' => $context,
'created_at' => $time,
'updated_at' => $time,
]);
}
if ($result !== true) {
throw new RuntimeException($this->db->error()['message'] ?? 'Error writing to the database.');
}
}
/**
* Deletes the record from persistent storage, if found,
* and from the local cache.
*/
public function forget(string $class, string $property, ?string $context = null): void
{
$this->hydrate($context);
if ($this->deferWrites) {
$this->markPending($class, $property, null, $context, true);
} else {
$this->persistForget($class, $property, $context);
}
// Delete from local storage
$this->forgetStored($class, $property, $context);
}
/**
* Deletes a single property from the database.
*
* @throws RuntimeException For database failures
*/
private function persistForget(string $class, string $property, ?string $context): void
{
$result = $this->builder
->where('class', $class)
->where('key', $property)
->where('context', $context)
->delete();
if (! $result) {
throw new RuntimeException($this->db->error()['message'] ?? 'Error writing to the database.');
}
}
/**
* Deletes all records from persistent storage, if found,
* and from the local cache.
*/
public function flush(): void
{
$this->builder->truncate();
parent::flush();
}
/**
* Fetches values from the database in bulk to minimize calls.
* General (null) is always fetched once, contexts are fetched
* in their entirety for each new request.
*
* @throws RuntimeException For database failures
*/
private function hydrate(?string $context): void
{
// Check for completion
if (in_array($context, $this->hydrated, true)) {
return;
}
if ($context === null) {
$this->hydrated[] = null;
$query = $this->builder->where('context', null);
} else {
$query = $this->builder->where('context', $context);
// If general has not been hydrated we will do that at the same time
if (! in_array(null, $this->hydrated, true)) {
$this->hydrated[] = null;
$query->orWhere('context', null);
}
$this->hydrated[] = $context;
}
if (is_bool($result = $query->get())) {
throw new RuntimeException($this->db->error()['message'] ?? 'Error reading from database.');
}
foreach ($result->getResultObject() as $row) {
$this->setStored($row->class, $row->key, $this->parseValue($row->value, $row->type), $row->context);
}
}
/**
* Persists all pending properties to the database.
* Called automatically at the end of request via post_system
* event when deferWrites is enabled.
*/
public function persistPendingProperties(): void
{
if ($this->pendingProperties === []) {
return;
}
$time = Time::now()->format('Y-m-d H:i:s');
// Separate deletes from upserts and prepare for database operations
$deletes = [];
$upserts = [];
foreach ($this->pendingProperties as $info) {
if ($info['delete']) {
// Prepare delete row with correct database column names
$deletes[] = [
'class' => $info['class'],
'key' => $info['property'],
'context' => $info['context'],
];
} else {
// Prepare upsert row with correct database column names
$upserts[] = [
'class' => $info['class'],
'key' => $info['property'],
'value' => $this->prepareValue($info['value']),
'type' => gettype($info['value']),
'context' => $info['context'],
'created_at' => $time,
'updated_at' => $time,
];
}
}
try {
$this->db->transStart();
// Handle upserts: fetch existing records matching our pending data
if ($upserts !== []) {
// Build query to fetch only the specific records we need
$this->buildOrWhereConditions($upserts, 'class', 'key', 'context');
$existing = $this->builder->get()->getResultArray();
// Build a map of existing records for quick lookup
$existingMap = [];
foreach ($existing as $row) {
$key = $this->buildCompositeKey($row['class'], $row['key'], $row['context']);
$existingMap[$key] = $row['id'];
}
// Separate into inserts and updates
$inserts = [];
$updates = [];
foreach ($upserts as $row) {
$key = $this->buildCompositeKey($row['class'], $row['key'], $row['context']);
if (isset($existingMap[$key])) {
// Record exists - prepare for update
$updates[] = [
'id' => $existingMap[$key],
'value' => $row['value'],
'type' => $row['type'],
'updated_at' => $row['updated_at'],
];
} else {
// New record - prepare for insert
$inserts[] = $row;
}
}
// Batch insert new records
if ($inserts !== []) {
$this->builder->insertBatch($inserts);
}
// Batch update existing records
if ($updates !== []) {
$this->builder->updateBatch($updates, 'id');
}
}
// Batch delete all delete operations
if ($deletes !== []) {
$this->buildOrWhereConditions($deletes, 'class', 'key', 'context');
$this->builder->delete();
}
$this->db->transComplete();
if ($this->db->transStatus() === false) {
log_message('error', 'Failed to persist pending properties to database.');
}
$this->pendingProperties = [];
} catch (DatabaseException $e) {
log_message('error', 'Failed to persist pending properties: ' . $e->getMessage());
$this->pendingProperties = [];
}
}
/**
* Builds a composite key for lookup purposes.
*/
private function buildCompositeKey(string $class, string $key, ?string $context): string
{
return $class . '::' . $key . ($context === null ? '' : '::' . $context);
}
/**
* Builds OR WHERE conditions for multiple rows.
*/
private function buildOrWhereConditions(array $rows, string $classKey, string $keyKey, string $contextKey): void
{
foreach ($rows as $row) {
$this->builder->orGroupStart();
$this->builder
->where($classKey, $row[$classKey])
->where($keyKey, $row[$keyKey])
->where($contextKey, $row[$contextKey]);
$this->builder->groupEnd();
}
}
}