Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.09% covered (success)
92.09%
163 / 177
75.00% covered (warning)
75.00%
15 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
SQL_Generator
92.09% covered (success)
92.09%
163 / 177
75.00% covered (warning)
75.00%
15 / 20
70.29
0.00% covered (danger)
0.00%
0 / 1
 __destruct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 comment
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 nl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 output
62.50% covered (warning)
62.50%
5 / 8
0.00% covered (danger)
0.00%
0 / 1
6.32
 var_assignment
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 var
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 header
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 start
81.40% covered (warning)
81.40%
35 / 43
0.00% covered (danger)
0.00%
0 / 1
7.32
 end
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 start_table
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
8
 start_table_inserts
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 table_insert
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 end_table_inserts
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 get_index_name
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_column
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
15.05
 get_dump
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_current_table
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 start_table_creation
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 end_table_creation
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 reset
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
3.01
1<?php
2/**
3 * SQL_Generator file.
4 *
5 * @package wpcomsh
6 */
7
8namespace Imports;
9
10use WP_Error;
11
12/**
13 * Generate a SQL file from metadata.
14 */
15class SQL_Generator {
16    /**
17     * Target size for batched INSERTs. A single large row is sent on its own.
18     */
19    private const MAX_INSERT_BYTES = 1048576;
20
21    const OUTPUT_TYPE_FILE   = 0;
22    const OUTPUT_TYPE_STRING = 1;
23    const OUTPUT_TYPE_STDOUT = 2;
24
25    const DEFAULT_CHARSET   = 'utf8mb4';
26    const DEFAULT_COLLATION = 'utf8mb4_unicode_520_ci';
27
28    /**
29     * The output type.
30     *
31     * @var int
32     */
33    private int $output_mode = self::OUTPUT_TYPE_STRING;
34
35    /**
36     * The output file.
37     *
38     * @var string|resource|null
39     */
40    private $output_handle = '';
41
42    /**
43     * The current table.
44     *
45     * @var ?string
46     */
47    private $current_table = null;
48
49    /**
50     * Bytes written for the current INSERT.
51     *
52     * @var int
53     */
54    private $current_insert_bytes = 0;
55
56    /**
57     * Whether the dump has started.
58     *
59     * @var bool
60     */
61    private $started = false;
62
63    /**
64     * Whether to use transactions.
65     *
66     * @var bool
67     */
68    private $transaction = true;
69
70    /**
71     * The collation.
72     *
73     * @var ?string
74     */
75    private $collation = null;
76
77    /**
78     * The collation.
79     *
80     * @var string
81     */
82    private $charset = self::DEFAULT_CHARSET;
83
84    /**
85     * SQL_Generator destructor.
86     */
87    public function __destruct() {
88        $this->reset();
89    }
90
91    /**
92     * MySQL `--` comment.
93     *
94     * @param string $comment The comment.
95     *
96     * @return void
97     */
98    public function comment( string $comment ) {
99        $this->output( "-- {$comment}" );
100    }
101
102    /**
103     * An empty line.
104     *
105     * @return void
106     */
107    public function nl() {
108        $this->output();
109    }
110
111    /**
112     * An SQL query.
113     *
114     * @param string $query The query.
115     * @param bool   $nl    Whether to add a new line at the end.
116     *
117     * @return void
118     */
119    public function output( string $query = '', $nl = true ) {
120        if ( $nl ) {
121            $query .= "\n";
122        }
123
124        if ( $this->output_mode === self::OUTPUT_TYPE_STDOUT ) {
125            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
126            echo $query;
127        } elseif ( $this->output_mode === self::OUTPUT_TYPE_STRING ) {
128            $this->output_handle .= $query;
129        } elseif ( $this->output_mode === self::OUTPUT_TYPE_FILE ) {
130            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
131            fwrite( $this->output_handle, $query );
132        }
133    }
134
135    /**
136     * A variable assignment.
137     *
138     * @param string $variable The variable name.
139     * @param string $value    The variable value.
140     * @param int    $version  The MySQL version when the variable was introduced.
141     *
142     * @return void
143     *
144     * @see https://dev.mysql.com/doc/refman/8.2/en/set-variable.html
145     */
146    public function var_assignment( string $variable, string $value, int $version = 40101 ) {
147        $this->output( "/*!{$version} SET {$variable}={$value} */;" );
148    }
149
150    /**
151     * A SET statement.
152     *
153     * @param string $content The SET statement content.
154     * @param int    $version The MySQL version when the statement was introduced.
155     *
156     * @see https://dev.mysql.com/doc/refman/8.2/en/set-statement.html
157     */
158    public function var( string $content, int $version = 40101 ) {
159        $this->output( "/*!{$version} {$content} */;" );
160    }
161
162    /**
163     * A three-line comment header.
164     *
165     * @param string $title The title.
166     *
167     * @return void
168     */
169    public function header( $title ) {
170        $this->comment( '' );
171        $this->comment( $title );
172        $this->comment( '' );
173        $this->nl();
174    }
175
176    /**
177     * Start the dump. This should be called before any other methods.
178     *
179     * @param array $options The options.
180     *
181     * @return bool|WP_Error
182     */
183    public function start( $options = array() ) {
184        $defaults = array(
185            'charset'     => self::DEFAULT_CHARSET,
186            'collation'   => null,
187            'output_file' => null,
188            'output_mode' => self::OUTPUT_TYPE_STRING,
189            'transaction' => true,
190        );
191
192        $options = wp_parse_args( $options, $defaults );
193
194        // Reset the output.
195        $this->reset();
196
197        $this->output_mode = $options['output_mode'];
198
199        if ( $this->output_mode === self::OUTPUT_TYPE_STDOUT ) {
200            $this->output_handle = null;
201        } elseif ( $this->output_mode === self::OUTPUT_TYPE_STRING ) {
202            $this->output_handle = '';
203        } elseif ( $this->output_mode === self::OUTPUT_TYPE_FILE ) {
204            if ( is_dir( $options['output_file'] ) ) {
205                return new WP_Error( 'output-open-error', 'Output file is a directory.' );
206            }
207
208            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
209            $file_handle = fopen( $options['output_file'], 'a' );
210
211            if ( $file_handle === false ) {
212                return new WP_Error( 'output-open-error', 'Error opening output file.' );
213            }
214
215            $this->output_handle = $file_handle;
216        }
217
218        $this->started     = true;
219        $this->transaction = $options['transaction'];
220        $this->collation   = $options['collation'];
221        $this->charset     = $options['charset'];
222
223        // Start the dump header.
224        $this->header( 'Playground SQLite MySQL dump' );
225
226        $this->output( 'SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";' );
227
228        if ( $this->transaction ) {
229            $this->output( 'START TRANSACTION;' );
230        }
231
232        $this->output( 'SET time_zone = "+00:00";' );
233        $this->nl();
234
235        // Various MySQL settings.
236        $this->var_assignment( '@OLD_CHARACTER_SET_CLIENT', '@@CHARACTER_SET_CLIENT' );
237        $this->var_assignment( '@OLD_CHARACTER_SET_RESULTS', '@@CHARACTER_SET_RESULTS' );
238        $this->var_assignment( '@OLD_COLLATION_CONNECTION', '@@COLLATION_CONNECTION ' );
239        $this->var( 'SET NAMES ' . $this->charset );
240        $this->var_assignment( '@OLD_TIME_ZONE', '@@TIME_ZONE', 40103 );
241        $this->var_assignment( 'TIME_ZONE', '\'+00:00\'', 40103 );
242        $this->var_assignment( '@OLD_UNIQUE_CHECKS', '@@UNIQUE_CHECKS, UNIQUE_CHECKS=0', 40014 );
243        $this->var_assignment( '@OLD_FOREIGN_KEY_CHECKS', '@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0', 40014 );
244        $this->var_assignment( '@OLD_SQL_MODE', '@@SQL_MODE, SQL_MODE=\'NO_AUTO_VALUE_ON_ZERO\'' );
245        $this->var_assignment( '@OLD_SQL_NOTES', '@@SQL_NOTES, SQL_NOTES=0', 40111 );
246        $this->nl();
247
248        return true;
249    }
250
251    /**
252     * End the dump. This should be called after all other methods.
253     */
254    public function end() {
255        // Not started, return.
256        if ( ! $this->started ) {
257            return;
258        }
259
260        if ( $this->transaction ) {
261            // End transaction.
262            $this->output( 'COMMIT;' );
263        }
264
265        // Various MySQL settings.
266        $this->var_assignment( 'TIME_ZONE', '@OLD_TIME_ZONE', 40103 );
267        $this->var_assignment( 'SQL_MODE', '@OLD_SQL_MODE' );
268        $this->var_assignment( 'FOREIGN_KEY_CHECKS', '@OLD_FOREIGN_KEY_CHECKS', 40014 );
269        $this->var_assignment( 'UNIQUE_CHECKS', '@OLD_UNIQUE_CHECKS', 40014 );
270        $this->var_assignment( 'CHARACTER_SET_CLIENT', '@OLD_CHARACTER_SET_CLIENT' );
271        $this->var_assignment( 'CHARACTER_SET_RESULTS', '@OLD_CHARACTER_SET_RESULTS' );
272        $this->var_assignment( 'COLLATION_CONNECTION', '@OLD_COLLATION_CONNECTION' );
273        $this->var_assignment( 'SQL_NOTES', '@OLD_SQL_NOTES', 40111 );
274        $this->nl();
275        $this->comment( 'Dump completed on ' . gmdate( 'Y-m-d H:i:s' ) );
276    }
277
278    /**
279     * Create a table.
280     *
281     * @param string $table_name     The table name.
282     * @param array  $types_map      The types map.
283     * @param int    $auto_increment The auto increment value.
284     * @param bool   $add_drop       Whether to add a DROP TABLE statement.
285     *
286     * @return void
287     */
288    public function start_table( string $table_name, array $types_map, int $auto_increment, bool $add_drop = true ) {
289        $this->start_table_creation( $table_name, $add_drop );
290
291        $indexes      = array();
292        $columns      = array();
293        $primary_keys = array();
294
295        // Output the columns.
296        foreach ( $types_map as $column ) {
297            if ( in_array( $column['type'], array( 'UNIQUE', 'KEY', 'FULLTEXT' ), true ) ) {
298                $indexes[] = $column;
299
300                continue;
301            }
302
303            $columns[] = $this->get_column( $column['name'], $column );
304
305            // Save up the PRIMARY column for later.
306            if ( $column['primary'] ) {
307                $primary_keys[] = '`' . $column['name'] . '`';
308                continue;
309            }
310        }
311
312        if ( count( $primary_keys ) ) {
313            // Add the PRIMARY KEY
314            $columns[] = 'PRIMARY KEY (' . implode( ',', $primary_keys ) . ')';
315        }
316
317        foreach ( $indexes as $index ) {
318            $index_list = $index['columns'];
319            $key_type   = $index['type'] === 'KEY' ? 'KEY' : $index['type'] . ' KEY';
320
321            // Output the keys.
322            $columns[] = "{$key_type} `{$index['name']}` {$index_list}";
323        }
324
325        if ( count( $columns ) > 0 ) {
326            $columns[0] = '  ' . $columns[0];
327            $this->output( implode( ",\n  ", $columns ) );
328        }
329
330        $this->end_table_creation( $table_name, $auto_increment );
331    }
332
333    /**
334     * Start table inserts. Disable keys.
335     *
336     * @return void
337     */
338    public function start_table_inserts() {
339        if ( ! $this->current_table ) {
340            return;
341        }
342
343        $this->header( "Dumping data for table `{$this->current_table}`" );
344        $this->output( "LOCK TABLES `{$this->current_table}` WRITE;" );
345        $this->var( "ALTER TABLE `{$this->current_table}` DISABLE KEYS", 40000 );
346
347        $this->current_insert_bytes = 0;
348    }
349
350    /**
351     * Generate an INSERT statement.
352     *
353     * @param string $field_names The field names.
354     * @param string $data        The data.
355     *
356     * @return void
357     */
358    public function table_insert( string $field_names, string $data ) {
359        if ( ! $this->current_table ) {
360            return;
361        }
362
363        // Include the separator before the row and the semicolon that ends the statement.
364        $row_bytes = strlen( $data );
365        if ( $this->current_insert_bytes > 0 && $this->current_insert_bytes + $row_bytes + 3 > self::MAX_INSERT_BYTES ) {
366            $this->output( ';' );
367            $this->current_insert_bytes = 0;
368        }
369
370        if ( $this->current_insert_bytes === 0 ) {
371            $header = "INSERT INTO `{$this->current_table}` {$field_names} VALUES";
372            $this->output( $header );
373            $this->current_insert_bytes = strlen( $header ) + 1;
374        } else {
375            $this->output( ',' );
376            $this->current_insert_bytes += 2;
377        }
378
379        $this->output( $data, false );
380
381        $this->current_insert_bytes += $row_bytes;
382    }
383
384    /**
385     * End table inserts. Enable keys.
386     *
387     * @return void
388     */
389    public function end_table_inserts() {
390        if ( ! $this->current_table ) {
391            return;
392        }
393
394        if ( $this->current_insert_bytes > 0 ) {
395            $this->output( ';' );
396        }
397
398        $this->var( "ALTER TABLE `{$this->current_table}` ENABLE KEYS", 40000 );
399        $this->output( 'UNLOCK TABLES;' );
400        $this->nl();
401
402        $this->current_insert_bytes = 0;
403    }
404
405    /**
406     * Get the real index name, from the SQLite index name.
407     *
408     * @param string $index_name The index name.
409     *
410     * @return string
411     */
412    public static function get_index_name( string $index_name ): string {
413        if ( strlen( $index_name ) < 4 ) {
414            return '';
415        }
416
417        $real_names = explode( '__', $index_name );
418
419        if ( count( $real_names ) === 2 ) {
420            return $real_names[1];
421        }
422
423        return '';
424    }
425
426    /**
427     * Get a column definition for the CREATE statement.
428     *
429     * @param string $name   The column name.
430     * @param array  $column The column definition.
431     *
432     * @return string
433     */
434    public function get_column( string $name, array $column ): string {
435        if ( $name === '' || ! array_key_exists( 'type', $column ) || ! array_key_exists( 'sqlite_type', $column ) ) {
436            return '';
437        }
438
439        $ret = "`{$name}` {$column['type']}";
440
441        if ( null !== $this->collation && $column['sqlite_type'] === 'text' && $column['type'] !== 'datetime' ) {
442            $ret .= ' COLLATE ' . $this->collation;
443        }
444
445        if ( array_key_exists( 'not_null', $column ) && $column['not_null'] ) {
446            $ret .= ' NOT NULL';
447        }
448
449        $is_auto_increment = array_key_exists( 'auto_increment', $column ) && $column['auto_increment'];
450
451        if ( $is_auto_increment ) {
452            $ret .= ' AUTO_INCREMENT';
453        }
454
455        if ( ! $is_auto_increment && array_key_exists( 'default', $column ) && $column['default'] !== null ) {
456            $default = $column['default'];
457
458            if ( $column['sqlite_type'] === 'integer' ) {
459                // Force an integer. The default value is a string.
460                $default = (int) $default;
461            }
462
463            $ret .= ' DEFAULT ' . $default;
464        }
465
466        return $ret;
467    }
468
469    /**
470     * Get the dump.
471     *
472     * @return string
473     */
474    public function get_dump(): string {
475        if ( $this->output_mode === self::OUTPUT_TYPE_STRING ) {
476            return $this->output_handle;
477        }
478
479        return '';
480    }
481
482    /**
483     * Get current table.
484     *
485     * @return string|null
486     */
487    public function get_current_table(): ?string {
488        return $this->current_table;
489    }
490
491    /**
492     * Start a table.
493     *
494     * @param string $table_name The table name.
495     * @param bool   $add_drop   Whether to add a DROP TABLE statement.
496     *
497     * @return void
498     */
499    private function start_table_creation( string $table_name, bool $add_drop = true ) {
500        $this->current_table = $table_name;
501        $this->header( "Table structure for table `{$table_name}`" );
502
503        if ( $add_drop ) {
504            $this->output( "DROP TABLE IF EXISTS `{$table_name}`;" );
505        }
506
507        $this->var_assignment( '@saved_cs_client', '@@character_set_client' );
508        $this->var_assignment( 'character_set_client', 'utf8' );
509        $this->output( "CREATE TABLE `{$table_name}` (" );
510    }
511
512    /**
513     * End table creation.
514     *
515     * @param string $table_name     The table name.
516     * @param int    $auto_increment The auto increment value.
517     *
518     * @return void
519     */
520    private function end_table_creation( string $table_name, int $auto_increment ) {
521        $end = ') ENGINE=InnoDB';
522
523        if ( $auto_increment ) {
524            $end .= ' AUTO_INCREMENT=' . ( $auto_increment + 1 );
525        }
526
527        $end .= ' CHARSET=' . $this->charset;
528
529        if ( null !== $this->collation ) {
530            $end .= ' COLLATE=' . $this->collation;
531        }
532
533        $this->output( $end . ';' );
534
535        $this->var_assignment( 'character_set_client', '@saved_cs_client' );
536        $this->nl();
537
538        $this->start_table_inserts();
539    }
540
541    /**
542     * Reset the generator.
543     */
544    private function reset() {
545        if ( $this->output_mode === self::OUTPUT_TYPE_FILE && $this->output_handle ) {
546            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
547            fclose( $this->output_handle );
548        }
549
550        $this->charset              = self::DEFAULT_CHARSET;
551        $this->collation            = null;
552        $this->current_insert_bytes = 0;
553        $this->current_table        = null;
554        $this->output_handle        = '';
555        $this->output_mode          = self::OUTPUT_TYPE_STRING;
556        $this->started              = false;
557        $this->transaction          = true;
558    }
559}