-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path01-readme-examples.php
More file actions
409 lines (350 loc) · 11.4 KB
/
01-readme-examples.php
File metadata and controls
409 lines (350 loc) · 11.4 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
<?php
/**
* Examples from README.md
*
* This file demonstrates the main features shown in the README documentation.
* All examples are designed to work across MySQL, PostgreSQL, and SQLite.
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\PdoDb;
use tommyknocker\pdodb\helpers\Db;
// Initialize database connection
$config = require __DIR__ . '/../config.sqlite.php';
$db = new PdoDb('sqlite', $config);
echo "=== README Examples Demo ===\n";
echo "Driver: " . getCurrentDriver($db) . "\n\n";
// Clean up and recreate tables
recreateTable($db, 'users', [
'id' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
'name' => 'TEXT NOT NULL',
'email' => 'TEXT UNIQUE',
'age' => 'INTEGER',
'status' => 'TEXT DEFAULT "active"',
'meta' => 'TEXT',
'tags' => 'TEXT',
'created_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP',
'updated_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP'
]);
recreateTable($db, 'orders', [
'id' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
'user_id' => 'INTEGER NOT NULL',
'amount' => 'REAL NOT NULL',
'created_at' => 'DATETIME DEFAULT CURRENT_TIMESTAMP'
]);
echo "1. Basic CRUD Operations\n";
echo "------------------------\n";
// Insert single row
$userId = $db->find()->table('users')->insert([
'name' => 'Alice',
'age' => 30,
'email' => 'alice@example.com',
'created_at' => Db::now()
]);
echo "Inserted user ID: $userId\n";
// Insert multiple rows
$insertedCount = $db->find()->table('users')->insertMulti([
['name' => 'Bob', 'age' => 25, 'email' => 'bob@example.com'],
['name' => 'Charlie', 'age' => 35, 'email' => 'charlie@example.com']
]);
echo "Inserted $insertedCount users\n";
// Update
$affected = $db->find()
->table('users')
->where('id', $userId)
->update([
'age' => Db::inc(), // Increment by 1
'updated_at' => Db::now()
]);
echo "Updated $affected rows\n";
// Select
$user = $db->find()
->from('users')
->select(['id', 'name', 'email', 'age'])
->where('id', $userId)
->getOne();
echo "User: " . json_encode($user) . "\n";
echo "\n2. Filtering and Joining\n";
echo "-------------------------\n";
// WHERE conditions
$users = $db->find()
->from('users')
->where('status', 'active')
->andWhere('age', 18, '>')
->andWhere(Db::like('email', '%@example.com'))
->get();
echo "Found " . count($users) . " active users over 18\n";
// Add some orders
$db->find()->table('orders')->insertMulti([
['user_id' => $userId, 'amount' => 150.50],
['user_id' => $userId, 'amount' => 200.75],
['user_id' => $userId + 1, 'amount' => 99.99] // Bob's ID
]);
// JOIN with aggregation using helper functions
$stats = $db->find()
->from('users AS u')
->select(['u.id', 'u.name', 'total' => Db::sum('o.amount')])
->leftJoin('orders AS o', 'o.user_id = u.id')
->groupBy('u.id', 'u.name')
->having(Db::sum('o.amount'), 100, '>')
->orderBy('total', 'DESC')
->get();
echo "Users with orders > 100: " . count($stats) . "\n";
echo "\n3. JSON Operations\n";
echo "-----------------\n";
// Insert JSON data
$jsonUserId = $db->find()->table('users')->insert([
'name' => 'John',
'meta' => Db::jsonObject(['city' => 'NYC', 'age' => 30, 'verified' => true]),
'tags' => Db::jsonArray('php', 'mysql', 'docker')
]);
echo "Inserted user with JSON data: $jsonUserId\n";
// Query JSON
$adults = $db->find()
->from('users')
->where(Db::jsonPath('meta', ['age'], '>', 25))
->get();
echo "Users with age > 25 in JSON: " . count($adults) . "\n";
// JSON contains
$phpDevs = $db->find()
->from('users')
->where(Db::jsonContains('tags', 'php'))
->get();
echo "Users with 'php' tag: " . count($phpDevs) . "\n";
// Extract JSON values
$withCity = $db->find()
->from('users')
->select([
'id',
'name',
'city' => Db::jsonGet('meta', ['city']),
'age' => Db::jsonGet('meta', ['age'])
])
->where(Db::jsonExists('meta', ['city']))
->get();
echo "Users with city in JSON: " . count($withCity) . "\n";
echo "\n4. Transactions\n";
echo "---------------\n";
$db->startTransaction();
try {
$newUserId = $db->find()->table('users')->insert(['name' => 'Transaction User']);
$db->find()->table('orders')->insert(['user_id' => $newUserId, 'amount' => 100]);
$db->commit();
echo "Transaction committed successfully\n";
} catch (\Throwable $e) {
$db->rollBack();
echo "Transaction rolled back: " . $e->getMessage() . "\n";
}
echo "\n5. Raw Queries\n";
echo "--------------\n";
// Raw query
$users = $db->rawQuery(
'SELECT * FROM users WHERE age > :age',
['age' => 25]
);
echo "Raw query returned " . count($users) . " users\n";
// Using helper functions where possible
$db->find()
->table('users')
->where('id', $userId)
->update([
'age' => Db::raw('age + :inc', ['inc' => 5]), // No helper for arithmetic
'name' => Db::concat('name', '_updated') // Using CONCAT helper
]);
echo "Updated user with helper functions\n";
echo "\n6. Complex Conditions\n";
echo "---------------------\n";
// Nested OR conditions
$users = $db->find()
->from('users')
->where('status', 'active')
->andWhere('age', 18, '>')
->orWhere('email', 'alice@example.com')
->get();
echo "Complex condition query returned " . count($users) . " users\n";
// Subquery using QueryBuilder methods
$users = $db->find()
->from('users')
->whereIn('id', function($query) {
$query->from('orders')
->select('user_id')
->where('amount', 100, '>');
})
->get();
echo "Subquery returned " . count($users) . " users\n";
echo "\n7. Callback Subqueries (New Feature)\n";
echo "------------------------------------\n";
// Using callbacks for subqueries
$users = $db->find()
->from('users')
->where('id', function($q) {
$q->from('orders')
->select('user_id')
->where('amount', 100, '>');
}, 'IN')
->get();
echo "Callback subquery returned " . count($users) . " users\n";
echo "\n8. Helper Functions\n";
echo "------------------\n";
// Date helpers
$today = $db->find()
->from('users')
->select([
'name',
'created_date' => Db::curDate(),
'created_time' => Db::curTime()
])
->where('id', $userId)
->getOne();
echo "Date helpers: " . json_encode($today) . "\n";
// Math helpers
$db->find()
->table('users')
->where('id', $userId)
->update([
'age' => Db::mod('age', 10) // age % 10
]);
echo "Updated age with modulo\n";
echo "\n9. Error Handling Examples\n";
echo "---------------------------\n";
// Demonstrate exception handling
try {
// This will work fine
$users = $db->find()->from('users')->get();
echo "Successfully retrieved " . count($users) . " users\n";
// Try to insert duplicate email (will cause constraint violation)
$db->find()->table('users')->insert([
'name' => 'Duplicate User',
'email' => 'alice@example.com', // This email already exists
'age' => 25
]);
} catch (\tommyknocker\pdodb\exceptions\ConstraintViolationException $e) {
echo "Constraint violation caught: " . $e->getMessage() . "\n";
echo "Constraint: " . $e->getConstraintName() . "\n";
echo "Table: " . $e->getTableName() . "\n";
echo "Retryable: " . ($e->isRetryable() ? 'Yes' : 'No') . "\n";
} catch (\tommyknocker\pdodb\exceptions\DatabaseException $e) {
echo "Database error caught: " . $e->getMessage() . "\n";
echo "Driver: " . $e->getDriver() . "\n";
echo "Category: " . $e->getCategory() . "\n";
}
// Demonstrate error context
try {
// Try invalid query
$db->find()->from('nonexistent_table')->get();
} catch (\tommyknocker\pdodb\exceptions\QueryException $e) {
echo "Query error caught: " . $e->getMessage() . "\n";
echo "Query: " . $e->getQuery() . "\n";
echo "Context: " . json_encode($e->getContext()) . "\n";
}
echo "\n10. Advanced JSON Operations\n";
echo "-----------------------------\n";
// JSON length and type
$jsonUsers = $db->find()
->from('users')
->select([
'id',
'name',
'tag_count' => Db::jsonLength('tags'),
'tags_type' => Db::jsonType('tags')
])
->where(Db::jsonLength('tags'), 2, '>')
->get();
echo "Users with more than 2 tags: " . count($jsonUsers) . "\n";
// JSON ordering
$sortedByAge = $db->find()
->from('users')
->orderBy(Db::jsonGet('meta', ['age']), 'DESC')
->where(Db::jsonExists('meta', ['age']))
->get();
echo "Users sorted by JSON age: " . count($sortedByAge) . "\n";
echo "\n11. Query Analysis Examples\n";
echo "---------------------------\n";
// Get SQL without execution
$query = $db->find()
->table('users')
->where('age', 25, '>')
->andWhere('status', 'active')
->toSQL();
echo "Generated SQL: " . $query['sql'] . "\n";
echo "Parameters: " . json_encode($query['params']) . "\n";
// Table structure analysis
$structure = $db->find()->table('users')->describe();
echo "Table structure columns: " . count($structure) . "\n";
echo "\n12. Connection Management\n";
echo "------------------------\n";
// Test timeout methods
$currentTimeout = $db->getTimeout();
echo "Current timeout: {$currentTimeout} seconds\n";
// Set new timeout
$db->setTimeout(30);
echo "New timeout set to: " . $db->getTimeout() . " seconds\n";
// Test ping
$isAlive = $db->ping();
echo "Database connection alive: " . ($isAlive ? 'Yes' : 'No') . "\n";
echo "\n13. Batch Processing (New Feature)\n";
echo "-----------------------------------\n";
// Process data in batches
$batchCount = 0;
$totalProcessed = 0;
foreach ($db->find()->from('users')->orderBy('id')->batch(2) as $batch) {
$batchCount++;
$totalProcessed += count($batch);
echo "Batch {$batchCount}: Processing " . count($batch) . " users\n";
}
echo "Processed {$totalProcessed} users in {$batchCount} batches\n";
// Process one record at a time
$processedCount = 0;
foreach ($db->find()
->from('users')
->where('status', 'active')
->orderBy('id')
->each(3) as $user) {
$processedCount++;
// Process individual user
}
echo "Processed {$processedCount} active users individually\n";
echo "\n14. Bulk Operations\n";
echo "-------------------\n";
// UPSERT example (works differently on SQLite)
try {
$upsertResult = $db->find()->table('users')->onDuplicate([
'age' => Db::inc(),
'updated_at' => Db::now()
])->insert([
'email' => 'upsert@example.com',
'name' => 'Upsert User',
'age' => 30
]);
echo "UPSERT result: " . $upsertResult . "\n";
} catch (\Exception $e) {
// SQLite doesn't support ON DUPLICATE KEY UPDATE, so we'll do a manual upsert
$existing = $db->find()
->from('users')
->where('email', 'upsert@example.com')
->getOne();
if ($existing) {
$db->find()
->table('users')
->where('email', 'upsert@example.com')
->update([
'age' => Db::inc(),
'updated_at' => Db::now()
]);
echo "Updated existing user\n";
} else {
$db->find()->table('users')->insert([
'email' => 'upsert@example.com',
'name' => 'Upsert User',
'age' => 30
]);
echo "Inserted new user\n";
}
}
// Check if user exists after upsert
$exists = $db->find()
->from('users')
->where('email', 'upsert@example.com')
->exists();
echo "User exists after upsert: " . ($exists ? 'Yes' : 'No') . "\n";
echo "\n=== Demo Complete ===\n";