Repository navigation
Expand file tree
/
Copy pathSQLiteFeatureContext.php
More file actions
436 lines (389 loc) · 13.6 KB
/
Copy pathSQLiteFeatureContext.php
File metadata and controls
436 lines (389 loc) · 13.6 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php
namespace Automattic\WP_CLI\SQLite;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use WP_CLI\Tests\Context\FeatureContext as WPCLIFeatureContext;
use PDO;
use Exception;
class SQLiteFeatureContext extends WPCLIFeatureContext implements Context {
private $db;
private $comment_injection_table_name;
/**
* @Given /^a SQL dump file named "([^"]*)" with content:$/
*/
public function aSqlDumpFileNamedWithContent( $filename, PyStringNode $content ) {
$this->create_file( $filename, $content );
}
/**
* @Then /^the SQLite database should contain a table named "([^"]*)"$/
*/
public function theSqliteDatabaseShouldContainATableNamed( $table_name ) {
$this->connectToDatabase();
$stmt = $this->db->prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name=?" );
$stmt->execute( [ $table_name ] );
$row = $stmt->fetch();
if ( ! $row ) {
throw new Exception( "Table '$table_name' not found in the database." );
}
}
/**
* @Then /^the SQLite database should not contain a table named "([^"]*)"$/
*/
public function theSqliteDatabaseShouldNotContainATableNamed( $table_name ) {
$this->connectToDatabase();
$stmt = $this->db->prepare( "SELECT name FROM sqlite_master WHERE type='table' AND name=?" );
$stmt->execute( [ $table_name ] );
$row = $stmt->fetch();
if ( $row ) {
throw new Exception( "Table '$table_name' was found in the database but should not exist." );
}
}
/**
* @Then /^the "([^"]*)" should contain a row with name "([^"]*)"$/
* @Then /^the "([^"]*)" should contain a row with name:$/
*/
public function theTableShouldContainARowWithName( $table_name, $name ) {
$this->connectToDatabase();
$stmt = $this->db->prepare( "SELECT * FROM $table_name WHERE name=?" );
$stmt->execute( [ $name ] );
$row = $stmt->fetch();
if ( ! $row ) {
throw new Exception( "Row with name '$name' not found in table '$table_name'." );
}
}
/**
* @Then /^the SQLite database should contain the imported data$/
*/
public function theSqliteDatabaseShouldContainTheImportedData() {
$this->connectToDatabase();
$result = $this->db->query( "SELECT name FROM sqlite_master WHERE type='table'" );
$tables = $result->fetchAll( PDO::FETCH_COLUMN );
if ( empty( $tables ) ) {
throw new Exception( 'No tables found in the database after import.' );
}
}
/**
* @Then /^the file "([^"]*)" should exist$/
*/
public function theFileShouldExist( $filename ) {
$full_path = $this->variables['RUN_DIR'] . '/' . $filename;
if ( ! file_exists( $full_path ) ) {
throw new Exception( "File does not exist: $full_path" );
}
}
private function connectToDatabase() {
if ( ! $this->db ) {
// Prefer the configured path without booting WordPress: the
// target may be a fresh import without WP tables installed.
$result = $this->proc( 'wp config get DB_PATH' )->run();
$db_file = trim( $result->stdout );
if ( '' === $db_file || 0 === strpos( $db_file, 'Error:' ) ) {
// Fall back to a full boot so the drop-in resolves FQDB.
$result = $this->proc( 'wp eval \'echo defined( "FQDB" ) ? FQDB : ""; \'' )->run_check();
$db_file = trim( $result->stdout );
}
if ( ! is_file( $db_file ) ) {
throw new Exception( 'The WordPress SQLite database does not exist.' );
}
$this->db = new PDO( 'sqlite:' . $db_file );
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
}
/**
* Create a file with given filename and content.
*
* @param string $filename
* @param string|PyStringNode $content
*/
protected function create_file( $filename, $content ) {
$content = $this->replace_variables( (string) $content );
$run_dir = $this->variables['RUN_DIR'];
if ( strpos( $filename, '/' ) !== false ) {
$subdir = dirname( $filename );
$run_dir .= "/$subdir";
if ( ! is_dir( $run_dir ) ) {
mkdir( $run_dir, 0777, true );
}
}
$full_path = $run_dir . '/' . basename( $filename );
file_put_contents( $full_path, $content );
}
/**
* @Given /^the SQLite database contains some sample data$/
*/
public function theSqliteDatabaseContainsSomeSampleData() {
$this->connectToDatabase();
$this->db->exec(
"
INSERT OR REPLACE INTO wp_posts (
ID, post_title, post_content, post_excerpt, to_ping, pinged,
post_content_filtered, post_type, post_status
)
VALUES (
1, 'Sample Post', 'This is a sample post content.', '', '', '', '', 'post', 'publish'
);
"
);
// Insert or update sample data in wp_users
$this->db->exec(
"
INSERT OR REPLACE INTO wp_users (ID, user_login, user_pass, user_nicename, user_email)
VALUES (1, 'testuser', 'password_hash', 'Test User', 'testuser@example.com');
"
);
// Insert or update sample data in wp_options
$this->db->exec(
"
INSERT OR REPLACE INTO wp_options (option_id, option_name, option_value, autoload)
VALUES
(1, 'siteurl', 'http://example.com', 'yes'),
(2, 'blogname', 'Test Blog', 'yes'),
(3, 'blogdescription', 'Just another WordPress site', 'yes'),
(4, 'users_can_register', '0', 'yes'),
(5, 'admin_email', 'admin@example.com', 'yes'),
(6, 'start_of_week', '1', 'yes'),
(7, 'use_balanceTags', '0', 'yes'),
(8, 'use_smilies', '1', 'yes'),
(9, 'require_name_email', '1', 'yes'),
(10, 'comments_notify', '1', 'yes');
"
);
}
/**
* @Then /^the file "([^"]*)" should contain:$/
*/
public function theFileShouldContain( $filename, PyStringNode $content ) {
$full_path = $this->variables['RUN_DIR'] . '/' . $filename;
$file_content = file_get_contents( $full_path );
if ( strpos( $file_content, (string) $content ) === false ) {
throw new Exception( "File does not contain expected content:\n" . $content );
}
}
/**
* @Then /^the file "([^"]*)" should not contain:$/
*/
public function theFileShouldNotContain( $filename, PyStringNode $content ) {
$full_path = $this->variables['RUN_DIR'] . '/' . $filename;
$file_content = file_get_contents( $full_path );
if ( strpos( $file_content, (string) $content ) !== false ) {
throw new Exception( "File contains unexpected content:\n" . $content );
}
}
/**
* @Given /^the SQLite database contains a serialized settings option with a NUL byte separator$/
*/
public function theSqliteDatabaseContainsASerializedSettingsOptionWithANulByteSeparator() {
$this->connectToDatabase();
$serialized_settings = array(
'layout' => 'full-width',
'breadcrumb-separator' => "\0" . '0bb',
'global-color-palette' => array(
'palette' => array(
'#ffffff',
'#000000',
'#0170b9',
),
),
);
$this->db->exec( "DELETE FROM wp_options WHERE option_name = 'serialized-theme-settings'" );
$stmt = $this->db->prepare(
'
INSERT INTO wp_options (option_name, option_value, autoload)
VALUES (:option_name, :option_value, :autoload)
'
);
$stmt->execute(
array(
':option_name' => 'serialized-theme-settings',
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- WordPress options store PHP-serialized values.
':option_value' => serialize( $serialized_settings ),
':autoload' => 'yes',
)
);
}
/**
* @Then /^the serialized settings option should preserve the NUL byte and color palette$/
*/
public function theSerializedSettingsOptionShouldPreserveTheNulByteAndColorPalette() {
$this->connectToDatabase();
$stmt = $this->db->prepare( "SELECT option_value FROM wp_options WHERE option_name = 'serialized-theme-settings'" );
$stmt->execute();
$option_value = $stmt->fetchColumn();
if ( false === $option_value ) {
throw new Exception( 'The serialized settings option was not found.' );
}
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- Verifies WordPress PHP-serialized option data round-trips.
$settings = unserialize( $option_value );
if ( ! is_array( $settings ) ) {
throw new Exception( 'The serialized settings option did not unserialize to an array.' );
}
if ( "\0" . '0bb' !== $settings['breadcrumb-separator'] ) {
throw new Exception( 'The settings breadcrumb separator did not preserve its leading NUL byte.' );
}
if ( ! isset( $settings['global-color-palette']['palette'][2] ) || '#0170b9' !== $settings['global-color-palette']['palette'][2] ) {
throw new Exception( 'The settings global color palette was not preserved.' );
}
}
/**
* @Given /^the SQLite database contains an option with SQL string escape bytes$/
*/
public function theSqliteDatabaseContainsAnOptionWithSqlStringEscapeBytes() {
$this->connectToDatabase();
$this->db->exec( "DELETE FROM wp_options WHERE option_name = 'sql-string-escape-bytes'" );
$stmt = $this->db->prepare(
'
INSERT INTO wp_options (option_name, option_value, autoload)
VALUES (:option_name, :option_value, :autoload)
'
);
$stmt->execute(
array(
':option_name' => 'sql-string-escape-bytes',
':option_value' => "quote' backslash\\ nul\0 newline\n carriage\r ctrlz\x1a end",
':autoload' => 'yes',
)
);
}
/**
* @Then /^the SQL string escape bytes should be preserved$/
*/
public function theSqlStringEscapeBytesShouldBePreserved() {
$this->connectToDatabase();
$stmt = $this->db->prepare( "SELECT option_value FROM wp_options WHERE option_name = 'sql-string-escape-bytes'" );
$stmt->execute();
$value = $stmt->fetchColumn();
$expected = "quote' backslash\\ nul\0 newline\n carriage\r ctrlz\x1a end";
if ( $expected !== $value ) {
throw new Exception(
sprintf(
"SQL string escape bytes were not preserved.\nExpected hex: %s\nActual hex: %s",
bin2hex( $expected ),
bin2hex( $value )
)
);
}
}
/**
* @Given /^the SQLite database contains a test table with alphanumeric string hash values$/
*/
public function theSqliteDatabaseContainsATestTableWithAlphanumericStringHashValues() {
$this->create_file(
'test_export_alphanumeric_string_setup.sql',
"
DROP TABLE IF EXISTS test_export_alphanumeric_string;
CREATE TABLE test_export_alphanumeric_string (
id INTEGER PRIMARY KEY,
hash_value TEXT
);
INSERT INTO test_export_alphanumeric_string (id, hash_value) VALUES (1, '123e99');
"
);
$this->wpcli_tests_invoke_proc(
$this->proc( 'wp sqlite import test_export_alphanumeric_string_setup.sql' ),
'run'
);
}
/**
* @Given /^the SQLite database contains a table with a backtick in its name$/
*/
public function theSqliteDatabaseContainsATableWithABacktickInItsName() {
$this->create_file(
'test_export_identifier_setup.sql',
"
DROP TABLE IF EXISTS `test``table`;
CREATE TABLE `test``table` (id INTEGER PRIMARY KEY, value TEXT);
INSERT INTO `test``table` (id, value) VALUES (1, 'Test value');
"
);
$this->wpcli_tests_invoke_proc(
$this->proc( 'wp sqlite import test_export_identifier_setup.sql' ),
'run'
);
}
/**
* @Given /^the SQLite database contains a table with a comment injection name$/
*/
public function theSqliteDatabaseContainsATableWithACommentInjectionName() {
$this->connectToDatabase();
$this->comment_injection_table_name = "safe`\nDROP TABLE IF EXISTS wp_users; --\rtable";
$quoted_table_name = '"' . str_replace( '"', '""', $this->comment_injection_table_name ) . '"';
$this->db->exec( "CREATE TABLE $quoted_table_name (id INTEGER PRIMARY KEY, value TEXT)" );
$this->db->exec( "INSERT INTO $quoted_table_name (id, value) VALUES (1, 'Test value')" );
}
/**
* @When /^I export the table with a comment injection name$/
*/
public function iExportTheTableWithACommentInjectionName() {
$this->wpcli_tests_invoke_proc(
$this->proc(
sprintf(
'wp sqlite --enable-ast-driver export test_export_comment.sql --tables=%s',
escapeshellarg( $this->comment_injection_table_name )
)
),
'run'
);
}
/**
* @Given /^the SQLite database contains an option with a double quote$/
*/
public function theSqliteDatabaseContainsAnOptionWithADoubleQuote() {
$this->connectToDatabase();
$this->db->exec( "DELETE FROM wp_options WHERE option_name = 'double-quote-option'" );
$stmt = $this->db->prepare(
'
INSERT INTO wp_options (option_name, option_value, autoload)
VALUES (:option_name, :option_value, :autoload)
'
);
$stmt->execute(
array(
':option_name' => 'double-quote-option',
':option_value' => 'say "hello" backslash\\ end',
':autoload' => 'yes',
)
);
}
/**
* @Then /^the double quote option should be escaped and preserved$/
*/
public function theDoubleQuoteOptionShouldBeEscapedAndPreserved() {
$this->connectToDatabase();
$stmt = $this->db->prepare( "SELECT option_value FROM wp_options WHERE option_name = 'double-quote-option'" );
$stmt->execute();
$value = $stmt->fetchColumn();
$expected = 'say "hello" backslash\\ end';
if ( $expected !== $value ) {
throw new Exception(
sprintf(
'Double quote option was not preserved. Expected %s, got %s.',
var_export( $expected, true ),
var_export( $value, true )
)
);
}
}
/**
* @Then /^every INSERT in the file "([^"]*)" should be on a single line$/
*/
public function everyInsertInTheFileShouldBeOnASingleLine( $filename ) {
$full_path = $this->variables['RUN_DIR'] . '/' . $filename;
$lines = file( $full_path, FILE_IGNORE_NEW_LINES );
if ( false === $lines ) {
throw new Exception( "Could not read file: $full_path" );
}
$insert_count = 0;
foreach ( $lines as $line ) {
if ( 0 !== strpos( ltrim( $line ), 'INSERT INTO' ) ) {
continue;
}
++$insert_count;
if ( ';' !== substr( rtrim( $line ), -1 ) ) {
throw new Exception( "INSERT statement spans multiple lines: $line" );
}
}
if ( 0 === $insert_count ) {
throw new Exception( "No INSERT statements found in file: $full_path" );
}
}
}