-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathhelpers.php
More file actions
295 lines (266 loc) · 9.56 KB
/
helpers.php
File metadata and controls
295 lines (266 loc) · 9.56 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
<?php
use tommyknocker\pdodb\PdoDb;
/**
* Helper functions for examples to work across different database dialects
*/
/**
* Get database configuration based on environment or default to SQLite
*/
function getExampleConfig(): array
{
$driver = mb_strtolower(getenv('PDODB_DRIVER') ?: 'sqlite', 'UTF-8');
// Map driver names to config file names
$configFileMap = [
'oci' => 'oracle',
'sqlsrv' => 'sqlsrv',
];
$configFileName = $configFileMap[$driver] ?? $driver;
// For CI environments, use environment variables directly
if ($driver === 'sqlsrv') {
$dbUser = getenv('PDODB_USERNAME');
$dbPass = getenv('PDODB_PASSWORD');
$dbHost = getenv('PDODB_HOST') ?: 'localhost';
$dbPort = getenv('PDODB_PORT') ?: '1433';
$dbName = getenv('PDODB_DATABASE') ?: 'testdb';
// If environment variables are set (CI), use them
if ($dbUser !== false && $dbPass !== false) {
return [
'driver' => 'sqlsrv',
'host' => $dbHost,
'port' => (int)$dbPort,
'username' => $dbUser,
'password' => $dbPass,
'dbname' => $dbName,
'trust_server_certificate' => true,
'encrypt' => true,
];
}
}
// For MySQL/MariaDB CI environments, check for PDODB_USERNAME and PDODB_PASSWORD
if ($driver === 'mysql' || $driver === 'mariadb') {
$dbUser = getenv('PDODB_USERNAME');
$dbPass = getenv('PDODB_PASSWORD');
$dbHost = getenv('PDODB_HOST') ?: 'localhost';
$dbPort = getenv('PDODB_PORT') ?: '3306';
$dbName = getenv('PDODB_DATABASE') ?: 'testdb';
$dbCharset = getenv('PDODB_CHARSET') ?: 'utf8mb4';
// If environment variables are set (CI), use them
if ($dbUser !== false && $dbPass !== false) {
return [
'driver' => $driver,
'host' => $dbHost,
'port' => (int)$dbPort,
'username' => $dbUser,
'password' => $dbPass,
'dbname' => $dbName,
'charset' => $dbCharset,
];
}
}
// For Oracle CI environments, check for PDODB_USERNAME and PDODB_PASSWORD
if ($driver === 'oci') {
$dbUser = getenv('PDODB_USERNAME');
$dbPass = getenv('PDODB_PASSWORD');
$dbHost = getenv('PDODB_HOST') ?: 'localhost';
$dbPort = getenv('PDODB_PORT') ?: '1521';
$dbName = getenv('PDODB_DATABASE') ?: 'XE';
$serviceName = getenv('PDODB_SERVICE_NAME') ?: getenv('PDODB_SID') ?: 'XEPDB1';
$dbCharset = getenv('PDODB_CHARSET') ?: 'UTF8';
// If environment variables are set (CI), use them
if ($dbUser !== false && $dbPass !== false) {
return [
'driver' => 'oci',
'host' => $dbHost,
'port' => (int)$dbPort,
'username' => $dbUser,
'password' => $dbPass,
'dbname' => $dbName,
'service_name' => $serviceName,
'charset' => $dbCharset,
'normalize_row_keys' => true,
];
}
}
$configFile = __DIR__ . "/config.{$configFileName}.php";
if (!file_exists($configFile)) {
// Fallback to generic config.php or SQLite
if (file_exists(__DIR__ . '/config.php')) {
$config = require __DIR__ . '/config.php';
return $config[$driver] ?? $config['sqlite'];
}
// Ultimate fallback
return ['driver' => 'sqlite', 'path' => ':memory:'];
}
return require $configFile;
}
/**
* Create a PdoDb instance for examples with unified error handling
*
* @throws \Throwable if connection fails
*/
function createExampleDb(): PdoDb
{
$config = getExampleConfig();
$driver = $config['driver'];
unset($config['driver']);
try {
return new PdoDb($driver, $config);
} catch (\Throwable $e) {
echo "⚠️ Connection failed: {$e->getMessage()}\n";
echo " (Check your database server and config settings)\n";
exit(1);
}
}
/**
* Create a PdoDb instance with custom config and unified error handling
*
* @param string $driver Database driver
* @param array $config Database configuration
* @return PdoDb
*/
function createPdoDbWithErrorHandling(string $driver, array $config): PdoDb
{
try {
return new PdoDb($driver, $config);
} catch (\Throwable $e) {
echo "⚠️ Connection failed: {$e->getMessage()}\n";
echo " (Check your database server and config settings)\n";
exit(1);
}
}
/**
* Drop table if exists and create new one using Schema Builder
* Handles foreign key constraints properly for each database
*
* This function uses the library's Schema Builder API (Yii2-style fluent API)
* to demonstrate proper cross-dialect DDL operations.
*
* Usage with fluent API (recommended):
* $schema = $db->schema();
* recreateTable($db, 'users', [
* 'id' => $schema->primaryKey(),
* 'name' => $schema->text()->notNull(),
* 'email' => $schema->text()->unique(),
* ]);
*/
function recreateTable(PdoDb $db, string $tableName, array $columns, array $options = []): void
{
$connection = $db->connection;
if ($connection === null) {
throw new RuntimeException('Database connection not initialized');
}
$driver = $connection->getDriverName();
$schema = $db->schema();
// Disable foreign key checks for MySQL/MariaDB
if ($driver === 'mysql' || $driver === 'mariadb') {
$db->rawQuery("SET FOREIGN_KEY_CHECKS=0");
}
// For MSSQL, drop foreign key constraints before dropping table
if ($driver === 'sqlsrv') {
// Get all foreign key constraints referencing this table
$fkQuery = "
SELECT
fk.name AS fk_name,
OBJECT_SCHEMA_NAME(fk.parent_object_id) AS schema_name,
OBJECT_NAME(fk.parent_object_id) AS table_name
FROM sys.foreign_keys fk
WHERE OBJECT_NAME(fk.referenced_object_id) = '$tableName'
";
$fks = $db->rawQuery($fkQuery);
foreach ($fks as $fk) {
$fkTable = $fk['table_name'];
$fkName = $fk['fk_name'];
try {
// Use schema API to drop foreign key
$schema->dropForeignKey($fkName, $fkTable);
} catch (\Exception $e) {
// If schema API fails, fall back to raw SQL
$schemaName = $fk['schema_name'] ?? 'dbo';
$connection->query("ALTER TABLE [{$schemaName}].[{$fkTable}] DROP CONSTRAINT [{$fkName}]");
}
}
// Also drop foreign keys defined in this table
$fkQuery2 = "
SELECT
fk.name AS fk_name
FROM sys.foreign_keys fk
WHERE OBJECT_NAME(fk.parent_object_id) = '$tableName'
";
$fks2 = $db->rawQuery($fkQuery2);
foreach ($fks2 as $fk) {
$fkName = $fk['fk_name'];
try {
// Use schema API to drop foreign key
$schema->dropForeignKey($fkName, $tableName);
} catch (\Exception $e) {
// If schema API fails, fall back to raw SQL
$connection->query("ALTER TABLE [{$tableName}] DROP CONSTRAINT [{$fkName}]");
}
}
}
// Drop table using schema API
$schema->dropTableIfExists($tableName);
// Create table using schema API (columns should use fluent API: $schema->primaryKey(), $schema->text()->notNull(), etc.)
$schema->createTable($tableName, $columns, $options);
// Re-enable foreign key checks for MySQL/MariaDB
if ($driver === 'mysql' || $driver === 'mariadb') {
$db->rawQuery("SET FOREIGN_KEY_CHECKS=1");
}
}
/**
* Get current database driver name
*/
function getCurrentDriver(PdoDb $db): string
{
$connection = $db->connection;
if ($connection === null) {
return 'unknown';
}
return $connection->getDriverName();
}
/**
* Set environment variables from database configuration for CLI commands
*
* This function ensures that CLI commands can access the same database configuration
* that was used to create the PdoDb instance. It reads the configuration array
* and sets all necessary PDODB_* environment variables.
*
* @param array<string, mixed> $config Database configuration array
*/
function setEnvFromConfig(array $config): void
{
if (isset($config['driver'])) {
putenv('PDODB_DRIVER=' . $config['driver']);
}
if (isset($config['host'])) {
putenv('PDODB_HOST=' . $config['host']);
}
if (isset($config['port'])) {
putenv('PDODB_PORT=' . (string)$config['port']);
}
if (isset($config['username'])) {
putenv('PDODB_USERNAME=' . $config['username']);
}
if (isset($config['password'])) {
putenv('PDODB_PASSWORD=' . $config['password']);
}
if (isset($config['database'])) {
putenv('PDODB_DATABASE=' . $config['database']);
}
if (isset($config['dbname'])) {
putenv('PDODB_DATABASE=' . $config['dbname']);
}
if (isset($config['charset'])) {
putenv('PDODB_CHARSET=' . $config['charset']);
}
if (isset($config['path'])) {
putenv('PDODB_PATH=' . $config['path']);
}
// Oracle-specific
if (isset($config['service_name'])) {
putenv('PDODB_SERVICE_NAME=' . $config['service_name']);
}
if (isset($config['sid'])) {
putenv('PDODB_SID=' . $config['sid']);
}
}