-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathplayground-db.php
114 lines (104 loc) · 2.43 KB
/
playground-db.php
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
<?php
// phpcs:ignoreFile WordPress.DB.DirectDatabaseQuery.DirectQuery
namespace WordPress\Playground;
defined('ABSPATH') || exit;
/**
* Escape an array of values for use in a SQL query.
*
* @param array $array The array of values to escape.
* @return string The escaped values, separated by commas.
*/
function escape_array($array)
{
global $wpdb;
$escaped = array();
foreach ($array as $value) {
if (is_numeric($value)) {
$escaped[] = $wpdb->prepare('%d', $value);
} else {
$escaped[] = $wpdb->prepare('%s', str_replace("\n", "\\n", $value));
}
}
return implode(',', $escaped);
}
/**
* Create a database dump and add it to a zip archive.
*
* @param ZipArchive $zip The zip archive to add the database dump to.
*/
function zip_database($zip)
{
global $wpdb;
$tables = get_db_tables();
$sql_dump = array();
foreach ($tables as $table) {
array_push(
$sql_dump,
sprintf(
"DROP TABLE IF EXISTS %s;",
$wpdb->quote_identifier($table)
),
dump_db_schema($table)
);
}
foreach ($tables as $table) {
$records = $wpdb->get_results(
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
sprintf('SELECT * FROM %s', $wpdb->quote_identifier($table)),
ARRAY_A
);
if ($wpdb->last_error) {
error_log($wpdb->last_error);
continue;
}
foreach ($records as $record) {
array_push(
$sql_dump,
sprintf(
'INSERT INTO %1$s VALUES (%2$s);',
$wpdb->quote_identifier($table),
escape_array(array_values($record))
)
);
}
}
$zip->addFile('schema/_Schema.sql', implode("\n", $sql_dump));
}
/**
* Get a list of all the tables in the database.
*
* @return array The list of tables in the database.
*/
function get_db_tables()
{
global $wpdb;
$tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
return apply_filters(
'playground_db_tables',
array_column($tables, 0)
);
}
/**
* Get the schema for a database table.
*
* @param string $table The name of the table to get the schema for.
* @return string The schema for the table.
*/
function dump_db_schema($table)
{
global $wpdb;
$schema = $wpdb->get_row(
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
sprintf('SHOW CREATE TABLE %s', $wpdb->quote_identifier($table)),
ARRAY_A
);
if ($wpdb->last_error) {
error_log($wpdb->last_error);
return '';
}
if (!isset($schema['Create Table'])) {
return '';
}
// A query needs to be on a single line
return preg_replace("/\r?\n/", "", $schema['Create Table']);
}