Skip to content

Commit 4a84792

Browse files
committed
docs: examples for wiki
1 parent 73f8cb4 commit 4a84792

11 files changed

Lines changed: 525 additions & 4 deletions

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/.idea/
22
/vendor/
33
/test/unit/_coverage/
4-
composer.phar
4+
/docs
5+
/composer.phar

example/01-quick-start.php

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?php
2+
use Gt\Database\Result\Row;
3+
4+
chdir(dirname(__DIR__));
5+
require "vendor/autoload.php";
6+
require __DIR__ . "/bootstrap.php";
7+
8+
[$workspace, $queryPath, $databasePath] = createExampleWorkspace("01-quick-start");
9+
10+
try {
11+
$db = createExampleDatabase($queryPath, $databasePath);
12+
$db->executeSql(implode("\n", [
13+
"create table product(",
14+
"\tid integer primary key autoincrement,",
15+
"\tname text not null,",
16+
"\tprice decimal(10,2) not null",
17+
")",
18+
]));
19+
20+
writeSqlQuery($queryPath, "product", "insert", implode("\n", [
21+
"insert into product(name, price)",
22+
"values(:name, :price)",
23+
]));
24+
writeSqlQuery($queryPath, "product", "getById", implode("\n", [
25+
"select id, name, price",
26+
"from product",
27+
"where id = ?",
28+
]));
29+
writeSqlQuery($queryPath, "product", "getAll", implode("\n", [
30+
"select id, name, price",
31+
"from product",
32+
"order by id",
33+
]));
34+
writeSqlQuery($queryPath, "product", "raisePrices", implode("\n", [
35+
"update product",
36+
"set price = price + :delta",
37+
]));
38+
writeSqlQuery($queryPath, "product", "removeOverPrice", implode("\n", [
39+
"delete from product",
40+
"where price > :maxPrice",
41+
]));
42+
43+
$firstId = $db->insert("product/insert", [
44+
"name" => "Keyboard",
45+
"price" => 59.99,
46+
]);
47+
$db->insert("product/insert", [
48+
"name" => "Mouse",
49+
"price" => 19.99,
50+
]);
51+
$db->insert("product/insert", [
52+
"name" => "Monitor",
53+
"price" => 249.99,
54+
]);
55+
56+
$firstProduct = $db->fetch("product/getById", (int)$firstId);
57+
printf("Inserted first product: %s (#%d)\n", $firstProduct->name, $firstProduct->id);
58+
59+
$allProducts = $db->fetchAll("product/getAll");
60+
/** @var Row $row */
61+
foreach($allProducts as $row) {
62+
printf("Product: %-10s Price: %.2f\n", $row->name, $row->getFloat("price"));
63+
}
64+
65+
$updatedRows = $db->update("product/raisePrices", ["delta" => 5.00]);
66+
echo "Rows updated: $updatedRows\n";
67+
68+
$deletedRows = $db->delete("product/removeOverPrice", ["maxPrice" => 200]);
69+
echo "Rows deleted: $deletedRows\n";
70+
}
71+
finally {
72+
removeDirectory($workspace);
73+
}

example/02-parameter-binding.php

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
chdir(dirname(__DIR__));
4+
require "vendor/autoload.php";
5+
require __DIR__ . "/bootstrap.php";
6+
7+
[$workspace, $queryPath, $databasePath] = createExampleWorkspace("02-parameter-binding");
8+
9+
try {
10+
$db = createExampleDatabase($queryPath, $databasePath);
11+
$db->executeSql(implode("\n", [
12+
"create table purchase(",
13+
"\tid integer primary key autoincrement,",
14+
"\tcustomer text not null,",
15+
"\ttotal decimal(10,2) not null,",
16+
"\tplacedAt text not null,",
17+
"\tisPaid integer not null",
18+
")",
19+
]));
20+
21+
writeSqlQuery($queryPath, "purchase", "insert", implode("\n", [
22+
"insert into purchase(customer, total, placedAt, isPaid)",
23+
"values(:customer, :total, :placedAt, :isPaid)",
24+
]));
25+
writeSqlQuery($queryPath, "purchase", "findById", "select * from purchase where id = ?");
26+
writeSqlQuery($queryPath, "purchase", "findByCustomer", implode("\n", [
27+
"select * from purchase",
28+
"where customer = :customer and isPaid = :isPaid",
29+
]));
30+
writeSqlQuery($queryPath, "purchase", "listByIds", implode("\n", [
31+
"select id, customer from purchase",
32+
"where id in (:idList)",
33+
"order by :orderBy",
34+
"limit :limit offset :offset",
35+
]));
36+
37+
$db->insert("purchase/insert", [
38+
"customer" => "alice",
39+
"total" => 12.99,
40+
"placedAt" => new DateTimeImmutable("2026-01-01 10:30:00"),
41+
"isPaid" => true,
42+
]);
43+
$db->insert("purchase/insert", [
44+
"customer" => "bob",
45+
"total" => 42.00,
46+
"placedAt" => new DateTimeImmutable("2026-01-02 09:00:00"),
47+
"isPaid" => false,
48+
]);
49+
$db->insert("purchase/insert", [
50+
"customer" => "alice",
51+
"total" => 5.75,
52+
"placedAt" => new DateTimeImmutable("2026-01-03 16:20:00"),
53+
"isPaid" => true,
54+
]);
55+
56+
$first = $db->fetch("purchase/findById", 1);
57+
echo "Question-mark binding -> customer #1: {$first->customer}\n";
58+
59+
$alicePaid = $db->fetchAll("purchase/findByCustomer", [
60+
"customer" => "alice",
61+
"isPaid" => true,
62+
]);
63+
echo "Named placeholders -> paid rows for alice: " . count($alicePaid) . "\n";
64+
65+
$subset = $db->fetchAll("purchase/listByIds", [
66+
"idList" => [1, 2, 3],
67+
"orderBy" => "id desc",
68+
"limit" => 2,
69+
"offset" => 0,
70+
]);
71+
foreach($subset as $row) {
72+
echo "Special bindings row: {$row->id} {$row->customer}\n";
73+
}
74+
}
75+
finally {
76+
removeDirectory($workspace);
77+
}

example/03-type-safe-getters.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
chdir(dirname(__DIR__));
4+
require "vendor/autoload.php";
5+
require __DIR__ . "/bootstrap.php";
6+
7+
[$workspace, $queryPath, $databasePath] = createExampleWorkspace("03-type-safe-getters");
8+
9+
try {
10+
$db = createExampleDatabase($queryPath, $databasePath);
11+
$db->executeSql(implode("\n", [
12+
"create table metric(",
13+
"\tid integer primary key autoincrement,",
14+
"\tname text not null,",
15+
"\tisHealthy integer not null,",
16+
"\tcounter integer not null,",
17+
"\tratio float not null,",
18+
"\trecordedAt integer not null",
19+
")",
20+
]));
21+
22+
$db->executeSql(implode("\n", [
23+
"insert into metric(name, isHealthy, counter, ratio, recordedAt)",
24+
"values",
25+
"('api', 1, 200, 0.98, strftime('%s', '2026-02-01 00:00:00')),",
26+
"('jobs', 0, 12, 0.31, strftime('%s', '2026-02-01 00:05:00'))",
27+
]));
28+
29+
writeSqlQuery($queryPath, "metric", "getHealthByName", "select isHealthy from metric where name = ?");
30+
writeSqlQuery($queryPath, "metric", "getAllCounters", "select counter from metric order by id");
31+
writeSqlQuery($queryPath, "metric", "getRatioByName", "select ratio from metric where name = ?");
32+
writeSqlQuery($queryPath, "metric", "getLatestTime", "select recordedAt from metric order by recordedAt desc limit 1");
33+
writeSqlQuery($queryPath, "metric", "getRowByName", "select * from metric where name = ?");
34+
35+
$isApiHealthy = $db->fetchBool("metric/getHealthByName", "api");
36+
$counters = $db->fetchAllInt("metric/getAllCounters");
37+
$jobsRatio = $db->fetchFloat("metric/getRatioByName", "jobs");
38+
$latestTime = $db->fetchDateTime("metric/getLatestTime");
39+
$row = $db->fetch("metric/getRowByName", "api");
40+
41+
echo "fetchBool: " . ($isApiHealthy ? "true" : "false") . "\n";
42+
echo "fetchAllInt: " . implode(", ", $counters) . "\n";
43+
echo "fetchFloat: $jobsRatio\n";
44+
echo "fetchDateTime: " . $latestTime->format(DATE_ATOM) . "\n";
45+
echo "Row getters: name={$row->getString("name")} counter={$row->getInt("counter")}\n";
46+
}
47+
finally {
48+
removeDirectory($workspace);
49+
}

example/04-dynamic-bindings.php

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php
2+
3+
chdir(dirname(__DIR__));
4+
require "vendor/autoload.php";
5+
require __DIR__ . "/bootstrap.php";
6+
7+
[$workspace, $queryPath, $databasePath] = createExampleWorkspace("04-dynamic-bindings");
8+
9+
try {
10+
$db = createExampleDatabase($queryPath, $databasePath);
11+
$db->executeSql(implode("\n", [
12+
"create table purchase(",
13+
"\tid integer primary key,",
14+
"\tcustomerId text not null,",
15+
"\tproductId integer not null,",
16+
"\tcreatedAt text not null",
17+
")",
18+
]));
19+
20+
writeSqlQuery($queryPath, "purchase", "bulkInsert", implode("\n", [
21+
"insert into purchase(id, customerId, productId, createdAt)",
22+
"values (?, ?, ?, ?)",
23+
]));
24+
writeSqlQuery($queryPath, "purchase", "findIn", implode("\n", [
25+
"select id, customerId from purchase",
26+
"where id in (:__dynamicIn)",
27+
"order by :orderBy",
28+
"limit :limit offset :offset",
29+
]));
30+
writeSqlQuery($queryPath, "purchase", "findByPairs", implode("\n", [
31+
"select id, customerId, productId from purchase",
32+
"where :__dynamicOr",
33+
"order by id",
34+
]));
35+
36+
$db->insert("purchase/bulkInsert", 1, "cust_1", 100, "2026-01-01");
37+
$db->insert("purchase/bulkInsert", 2, "cust_2", 101, "2026-01-02");
38+
$db->insert("purchase/bulkInsert", 3, "cust_2", 102, "2026-01-03");
39+
$db->insert("purchase/bulkInsert", 4, "cust_3", 103, "2026-01-04");
40+
41+
$dynamicInRows = $db->fetchAll("purchase/findIn", [
42+
"__dynamicIn" => [1, 3, 4],
43+
"orderBy" => "id desc",
44+
"limit" => 10,
45+
"offset" => 0,
46+
]);
47+
echo "Dynamic IN results:\n";
48+
foreach($dynamicInRows as $row) {
49+
echo "{$row->id} {$row->customerId}\n";
50+
}
51+
52+
$dynamicOrRows = $db->fetchAll("purchase/findByPairs", [
53+
"__dynamicOr" => [
54+
["customerId" => "cust_2", "productId" => 101],
55+
["customerId" => "cust_3", "productId" => 103],
56+
],
57+
]);
58+
echo "Dynamic OR results:\n";
59+
foreach($dynamicOrRows as $row) {
60+
echo "{$row->id} {$row->customerId} {$row->productId}\n";
61+
}
62+
}
63+
finally {
64+
removeDirectory($workspace);
65+
}

example/05-database-migrations.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
use Gt\Database\Connection\Settings;
3+
use Gt\Database\Migration\Migrator;
4+
5+
chdir(dirname(__DIR__));
6+
require "vendor/autoload.php";
7+
require __DIR__ . "/bootstrap.php";
8+
9+
[$workspace, $queryPath, $databasePath] = createExampleWorkspace("05-database-migrations");
10+
11+
try {
12+
$migrationPath = "$queryPath/_migration";
13+
mkdir($migrationPath, 0775, true);
14+
15+
file_put_contents("$migrationPath/0001-create-user.sql", implode("\n", [
16+
"create table user(",
17+
"\tid integer primary key autoincrement,",
18+
"\temail text not null",
19+
")",
20+
]));
21+
file_put_contents("$migrationPath/0002-add-created-at.sql", implode("\n", [
22+
"alter table user add createdAt text",
23+
]));
24+
25+
$baseSettings = new Settings(
26+
$queryPath,
27+
Settings::DRIVER_SQLITE,
28+
$databasePath
29+
);
30+
$db = createExampleDatabase($queryPath, $databasePath);
31+
$migrator = new Migrator($baseSettings, $migrationPath);
32+
$migrator->createMigrationTable();
33+
34+
$migrationFiles = $migrator->getMigrationFileList();
35+
$migrator->checkFileListOrder($migrationFiles);
36+
$migrator->checkIntegrity($migrationFiles, $migrator->getMigrationCount());
37+
$migrator->performMigration($migrationFiles, $migrator->getMigrationCount());
38+
39+
$db->executeSql("insert into user(email, createdAt) values(?, datetime('now'))", [
40+
"dev@example.com",
41+
]);
42+
$result = $db->executeSql("select id, email, createdAt from user limit 1");
43+
$row = $result->fetch();
44+
echo "Migrated row: {$row->id} {$row->email} {$row->createdAt}\n";
45+
}
46+
finally {
47+
removeDirectory($workspace);
48+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
use Gt\Database\Connection\Settings;
3+
use Gt\Database\Database;
4+
5+
chdir(dirname(__DIR__));
6+
require "vendor/autoload.php";
7+
require __DIR__ . "/bootstrap.php";
8+
9+
$workspace = implode(DIRECTORY_SEPARATOR, [
10+
sys_get_temp_dir(),
11+
"phpgt-database-06-multiple-connections-" . uniqid(),
12+
]);
13+
14+
try {
15+
$catalogQueryPath = "$workspace/catalog-query";
16+
$analyticsQueryPath = "$workspace/analytics-query";
17+
$catalogDbPath = "$workspace/catalog.sqlite";
18+
$analyticsDbPath = "$workspace/analytics.sqlite";
19+
20+
mkdir($catalogQueryPath, 0775, true);
21+
mkdir($analyticsQueryPath, 0775, true);
22+
23+
writeSqlQuery($catalogQueryPath, "product", "insert", "insert into product(name) values(?)");
24+
writeSqlQuery($catalogQueryPath, "product", "count", "select count(*) from product");
25+
writeSqlQuery($analyticsQueryPath, "event", "insert", "insert into event(action) values(?)");
26+
writeSqlQuery($analyticsQueryPath, "event", "count", "select count(*) from event");
27+
28+
$catalogSettings = (new Settings(
29+
$catalogQueryPath,
30+
Settings::DRIVER_SQLITE,
31+
$catalogDbPath
32+
))->withConnectionName("catalog");
33+
34+
$analyticsSettings = (new Settings(
35+
$analyticsQueryPath,
36+
Settings::DRIVER_SQLITE,
37+
$analyticsDbPath
38+
))->withConnectionName("analytics");
39+
40+
$db = new Database($catalogSettings, $analyticsSettings);
41+
42+
$db->executeSql("create table product(id integer primary key autoincrement, name text)", [], "catalog");
43+
$db->executeSql("create table event(id integer primary key autoincrement, action text)", [], "analytics");
44+
45+
$catalog = $db->queryCollection("product", "catalog");
46+
$analytics = $db->queryCollection("event", "analytics");
47+
48+
$catalog->insert("insert", "Keyboard");
49+
$catalog->insert("insert", "Mouse");
50+
echo "Catalog count: " . $catalog->fetchInt("count") . "\n";
51+
52+
$analytics->insert("insert", "login");
53+
echo "Analytics count: " . $analytics->fetchInt("count") . "\n";
54+
}
55+
finally {
56+
removeDirectory($workspace);
57+
}

0 commit comments

Comments
 (0)