Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.10% covered (success)
91.10%
389 / 427
73.91% covered (warning)
73.91%
17 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Playground_DB_Importer
91.31% covered (success)
91.31%
389 / 426
73.91% covered (warning)
73.91%
17 / 23
159.97
0.00% covered (danger)
0.00%
0 / 1
 generate_sql
78.79% covered (warning)
78.79%
26 / 33
0.00% covered (danger)
0.00%
0 / 1
9.77
 parse_database
73.17% covered (warning)
73.17%
30 / 41
0.00% covered (danger)
0.00%
0 / 1
22.58
 check_database_integrity
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 generate_inserts
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
6.02
 prepare_row
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 get_geometry_value
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
8
 is_wkb
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 get_input_prefix
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
 get_input_table_name
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_output_table_name
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_table_types_map
81.01% covered (warning)
81.01%
64 / 79
0.00% covered (danger)
0.00%
0 / 1
21.47
 get_schema_indexes
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
11
 finish_table_types_map
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 get_geometry_columns
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 fit_row_size
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
14
 get_column_size
100.00% covered (success)
100.00%
49 / 49
100.00% covered (success)
100.00%
1 / 1
9
 sqlite_type_to_format
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
7.29
 needs_191_limit
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 get_table_autoincrement
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_tmp_file_name
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 prepare
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 hot_fix_missing_indexes
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
4
 is_valid_table
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Playground_DB_Importer file.
4 *
5 * @package wpcomsh
6 */
7
8namespace Imports;
9
10require_once __DIR__ . '/class-sql-generator.php';
11
12use SQLite3;
13use WP_Error;
14
15/**
16 * Parses a Playground SQLite database file and generate a SQL file.
17 */
18class Playground_DB_Importer {
19    /**
20     * Name of the table where SQLite map the internal types to the MySQL types.
21     */
22    public const SQLITE_DATA_TYPES_TABLE = '_wp_sqlite_mysql_information_schema_columns';
23
24    /**
25     * Name of the table where SQLite store the autoincrement value.
26     */
27    public const SQLITE_SEQUENCE_TABLE = 'sqlite_sequence';
28
29    /**
30     * Name of the table where SQLite stores the MySQL index definitions.
31     */
32    public const SQLITE_INDEXES_TABLE = '_wp_sqlite_mysql_information_schema_statistics';
33
34    /**
35     * The most bytes MySQL allows in a row, not counting TEXT and BLOB columns.
36     */
37    private const MAX_ROW_SIZE = 65535;
38
39    /**
40     * MySQL's spatial column types.
41     */
42    private const GEOMETRY_TYPES = array( 'geometry', 'point', 'linestring', 'polygon', 'multipoint', 'multilinestring', 'multipolygon', 'geometrycollection', 'geomcollection' );
43
44    /**
45     * The database connection.
46     *
47     * @var ?SQLite3
48     */
49    private ?SQLite3 $db;
50
51    /**
52     * The options.
53     *
54     * @var array
55     */
56    private array $options = array();
57
58    /**
59     * Generate a .sql file from a Playground SQLite database file.
60     *
61     * @param string $database_file_path The database file path.
62     * @param array  $options {
63     *     An array of options.
64     *
65     *     @type bool   $all_tables     Generate all tables, not only core. Defaults to true.
66     *     @type string $charset        The charset to use for the generated SQL. Defaults to 'latin1'.
67     *     @type string $collation      The collation to use for the generated SQL. Defaults to null.
68     *     @type array  $exclude_tables A list of tables to exclude from the generated SQL.
69     *     @type string $output_file    The output file path. If not set, a temporary file will be used.
70     *     @type int    $output_mode    Output mode. Defaults to SQL_Generator::OUTPUT_TYPE_STRING.
71     *     @type string $output_prefix  The generated tables prefix.
72     *     @type string $prefix         The input tables prefix, usually the backup's `$table_prefix`. Used when the
73     *                                  database has that prefix's options table; otherwise it's detected. Defaults to `wp_`.
74     *     @type string $tmp_prefix     The temporary tables prefix.
75     *     @type bool   $tmp_tables     Whether to generate temporary tables instead of TRANSACTION. Defaults to false.
76     * }
77     *
78     * @return string|WP_Error
79     */
80    public function generate_sql( string $database_file_path, $options = array() ) {
81        global $wpdb;
82
83        $defaults = array(
84            'all_tables'     => true,
85            'charset'        => 'latin1',
86            'collation'      => null,
87            'exclude_tables' => array(),
88            'output_file'    => null,
89            'output_mode'    => SQL_Generator::OUTPUT_TYPE_STRING,
90            'output_prefix'  => $wpdb->prefix,
91            'prefix'         => 'wp_',
92            'tmp_prefix'     => 'tmp_',
93            'tmp_tables'     => false,
94        );
95
96        $this->options = wp_parse_args( $options, $defaults );
97
98        // Bail if the file doesn't exist.
99        if ( ! is_file( $database_file_path ) || ! is_readable( $database_file_path ) ) {
100            return new WP_Error( 'database-file-not-exists', 'Database file not exists' );
101        }
102
103        // Bail if the file is empty.
104        if ( filesize( $database_file_path ) <= 0 ) {
105            return new WP_Error( 'database-file-empty', 'Database file is empty' );
106        }
107
108        // Set the output file.
109        if ( $this->options['output_mode'] === SQL_Generator::OUTPUT_TYPE_FILE ) {
110            // If the output file is not set, then use a temporary file.
111            if ( empty( $this->options['output_file'] ) ) {
112                $this->options['output_file'] = trailingslashit( sys_get_temp_dir() ) . $this->get_tmp_file_name();
113            }
114        } else {
115            $this->options['output_file'] = null;
116        }
117
118        try {
119            // Try to open the database file.
120            $this->db = new SQLite3( $database_file_path, SQLITE3_OPEN_READONLY );
121
122            $this->options['prefix'] = $this->get_input_prefix( (string) $this->options['prefix'] );
123
124            $ret = $this->parse_database();
125
126            $this->db->close();
127
128            if ( is_wp_error( $ret ) ) {
129                return $ret;
130            }
131
132            // Return the file path if the output mode is file.
133            if ( $this->options['output_mode'] === SQL_Generator::OUTPUT_TYPE_FILE ) {
134                return $this->options['output_file'];
135            }
136
137            // Return the SQL string.
138            return $ret;
139        } catch ( \Exception $e ) {
140            $this->db = null;
141
142            return new WP_Error( 'sqlite-open-error', $e->getMessage() );
143        }
144    }
145
146    /**
147     * Parse the database and load data.
148     *
149     * @return string|WP_Error
150     */
151    private function parse_database() {
152        global $wpdb;
153
154        if ( ! $this->db ) {
155            return new WP_Error( 'no-database-connection', 'No database connection.' );
156        }
157
158        // Check if the bind table and the sequence table exist.
159        $valid_db = $this->check_database_integrity();
160
161        if ( is_wp_error( $valid_db ) ) {
162            return $valid_db;
163        }
164
165        $core_tables = array_flip( $wpdb->tables );
166        $results     = $this->db->query( 'SELECT name FROM sqlite_master WHERE type=\'table\'' );
167
168        if ( ! $results ) {
169            return new WP_Error( 'no-database-master-schema', 'Query error: can\'t read database schema.' );
170        }
171
172        $generator = new SQL_Generator();
173        $excluded  = is_array( $this->options['exclude_tables'] ) ? $this->options['exclude_tables'] : array();
174
175        if ( $this->options['tmp_tables'] ) {
176            $this->options['transaction'] = false;
177        }
178
179        $started = $generator->start( $this->options );
180
181        if ( is_wp_error( $started ) ) {
182            return $started;
183        }
184
185        // Check if the table exists in the core tables list.
186        while ( $table = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
187            $table_name = $this->get_input_table_name( $table['name'] );
188
189            // This is not a core table. Skip if all tables needed.
190            if ( ! $this->options['all_tables'] && ! array_key_exists( $table_name, $core_tables ) ) {
191                continue;
192            }
193
194            // SQLite internal tables. Skip.
195            if ( ! $this->is_valid_table( $table_name ) ) {
196                continue;
197            }
198
199            // An excluded table. Skip.
200            if ( in_array( $table_name, $excluded, true ) ) {
201                // Remove the table from the excluded list.
202                unset( $excluded[ $table_name ] );
203
204                continue;
205            }
206
207            // Get the type map.
208            $types_map = $this->get_table_types_map( $table['name'] );
209
210            if ( is_wp_error( $types_map ) ) {
211                return $types_map;
212            } elseif ( empty( $types_map['map'] ) ) {
213                continue;
214            }
215
216            // Force a temporary table name if needed.
217            $output_table = $this->get_output_table_name( $table_name );
218
219            $generator->start_table( $output_table, $types_map['map'], $types_map['auto_increment'] );
220            $this->generate_inserts( $generator, $table['name'], $types_map );
221            $generator->end_table_inserts();
222
223            if ( ! $this->options['all_tables'] ) {
224                // Remove the table from the core tables list.
225                unset( $core_tables[ $table_name ] );
226            }
227        }
228
229        if ( ! $this->options['all_tables'] ) {
230            // If the core tables list is not empty, then there are missing tables.
231            if ( ! empty( $core_tables ) ) {
232                return new WP_Error( 'missing-tables', 'Query error: missing tables.' );
233            }
234        }
235
236        $generator->end();
237
238        // Found all the tables, return the SQL.
239        return $generator->get_dump();
240    }
241
242    /**
243     * Check the database integrity.
244     *
245     * The `_mysql_data_types_cache` and `sqlite_sequence` tables must exist.
246     *
247     * @return bool|WP_Error
248     */
249    private function check_database_integrity() {
250        // Check if the bind table and the sequence table exist.
251        $query = $this->prepare(
252            'SELECT COUNT(*) FROM sqlite_master WHERE type=%s AND (name=%s OR name=%s)',
253            'table',
254            self::SQLITE_DATA_TYPES_TABLE,
255            self::SQLITE_SEQUENCE_TABLE
256        );
257        $count = $this->db->querySingle( $query );
258
259        if ( $count !== 2 ) {
260            // Not a real WordPress SQLite database.
261            return new WP_Error( 'not-valid-sqlite-file', 'Query error: not a valid SQLite database' );
262        }
263
264        return true;
265    }
266
267    /**
268     * Generate the table inserts.
269     *
270     * @param SQL_Generator $generator  The SQL generator.
271     * @param string        $table_name The table name.
272     * @param array         $types_map  The table types map.
273     *
274     * @return void|WP_Error
275     */
276    private function generate_inserts( SQL_Generator $generator, string $table_name, array $types_map ) {
277        $select = '*';
278
279        // Read spatial values as BLOBs. As text, SQLite stops at the first NUL byte, and MySQL's binary geometry starts with one.
280        if ( ! empty( $types_map['geometry'] ) ) {
281            $fields = array();
282
283            foreach ( $types_map['columns'] as $i => $name ) {
284                $quoted   = '"' . str_replace( '"', '""', $name ) . '"';
285                $fields[] = isset( $types_map['geometry'][ $i ] ) ? "CAST({$quoted} AS BLOB) AS {$quoted}" : $quoted;
286            }
287
288            $select = implode( ', ', $fields );
289        }
290
291        $entries = $this->db->query( "SELECT {$select} FROM {$table_name}" );
292
293        if ( ! $entries ) {
294            return new WP_Error( 'missing-table', 'Query error: can\'t read source entry.' );
295        }
296
297        while ( $entry = $entries->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
298            $generator->table_insert( $types_map['field_names'], $this->prepare_row( $types_map['formats'], array_values( $entry ), $types_map['geometry'] ) );
299        }
300    }
301
302    /**
303     * Format a row's values for an INSERT, keeping NULL as NULL.
304     *
305     * `wpdb::prepare()` writes NULL as `''`, which MySQL stores as `0` in a number column or as `''`. Two
306     * of those in a UNIQUE index, like Borlabs Cookie's or MailPoet's nullable unique columns, collide
307     * and fail the restore with a duplicate entry error.
308     *
309     * @param string[] $formats  The format of each column.
310     * @param array    $values   The row's values, in column order.
311     * @param array    $geometry The spatial columns' types and nullability, by column position.
312     *
313     * @return string
314     */
315    private function prepare_row( array $formats, array $values, array $geometry = array() ): string {
316        $placeholders = array();
317        $args         = array();
318
319        foreach ( $values as $i => $value ) {
320            if ( isset( $geometry[ $i ] ) ) {
321                $placeholders[] = $this->get_geometry_value( $value, $geometry[ $i ]['type'], $geometry[ $i ]['not_null'] );
322                continue;
323            }
324
325            if ( null === $value ) {
326                $placeholders[] = 'NULL';
327                continue;
328            }
329
330            $placeholders[] = $formats[ $i ] ?? '%s';
331            $args[]         = $value;
332        }
333
334        $row = '(' . implode( ',', $placeholders ) . ')';
335
336        return empty( $args ) ? $row : (string) $this->prepare( $row, $args );
337    }
338
339    /**
340     * Write a spatial value as MySQL geometry.
341     *
342     * SQLite has no spatial types, so a `POINT` or `GEOMETRY` column holds whatever text the site wrote: WKT like
343     * `POINT(1 2)`, MySQL's own binary geometry (an SRID, then WKB) from a site pulled from MySQL, plain WKB, or
344     * an empty string. MySQL only takes its binary form, and fails the restore on anything else with ERROR 1416.
345     * WKT and WKB are converted, and a value that isn't geometry becomes NULL, or an empty-as-possible geometry
346     * of the column's type if the column is NOT NULL.
347     *
348     * @param mixed  $value    The SQLite value.
349     * @param string $type     The column's MySQL type, like `point`.
350     * @param bool   $not_null Whether the column is NOT NULL.
351     *
352     * @return string The SQL expression.
353     */
354    private function get_geometry_value( $value, string $type, bool $not_null ): string {
355        if ( null !== $value && '' !== $value ) {
356            $value = (string) $value;
357
358            if ( preg_match( '/^\s*(SRID=(\d+);)?\s*((MULTI)?(POINT|LINESTRING|POLYGON)|GEOM(ETRY)?COLLECTION)\s*(\(|EMPTY)/i', $value, $matches ) ) {
359                $wkt = $matches[1] ? substr( ltrim( $value ), strlen( $matches[1] ) ) : $value;
360
361                return (string) $this->prepare( 'ST_GeomFromText(%s, %d)', trim( $wkt ), (int) ( $matches[2] ?? 0 ) );
362            }
363
364            // MySQL's binary geometry: a 4-byte SRID, then WKB.
365            if ( self::is_wkb( substr( $value, 4 ) ) ) {
366                return '0x' . bin2hex( $value );
367            }
368
369            if ( self::is_wkb( $value ) ) {
370                return 'ST_GeomFromWKB(0x' . bin2hex( $value ) . ')';
371            }
372        }
373
374        if ( ! $not_null ) {
375            return 'NULL';
376        }
377
378        $empty = array(
379            'linestring'      => 'LINESTRING(0 0,0 0)',
380            'polygon'         => 'POLYGON((0 0,0 0,0 0,0 0))',
381            'multipoint'      => 'MULTIPOINT(0 0)',
382            'multilinestring' => 'MULTILINESTRING((0 0,0 0))',
383            'multipolygon'    => 'MULTIPOLYGON(((0 0,0 0,0 0,0 0)))',
384        );
385
386        return "ST_GeomFromText('" . ( $empty[ $type ] ?? 'POINT(0 0)' ) . "')";
387    }
388
389    /**
390     * Whether a value starts like WKB: a byte order of 0 or 1, then a geometry type from 1 to 7.
391     *
392     * @param string $value The value.
393     *
394     * @return bool
395     */
396    private static function is_wkb( string $value ): bool {
397        if ( strlen( $value ) < 9 || ! in_array( $value[0], array( "\x00", "\x01" ), true ) ) {
398            return false;
399        }
400
401        $type = unpack( "\x01" === $value[0] ? 'V' : 'N', substr( $value, 1, 4 ) )[1];
402
403        return $type >= 1 && $type <= 7;
404    }
405
406    /**
407     * Get the prefix of the database's WordPress tables.
408     *
409     * Studio sites pulled from a site that uses another table prefix, like `wpx_`, keep it. The
410     * requested prefix is used when its options table holds a site URL. Otherwise, the prefix of the
411     * options table that does is used, preferring `wp_`.
412     *
413     * @param string $requested_prefix The prefix to use when its options table exists.
414     *
415     * @return string
416     */
417    private function get_input_prefix( string $requested_prefix ): string {
418        $prefixes = array();
419        $results  = $this->db->query( "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%options'" );
420
421        while ( $results && $table = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
422            $table_name = $table['name'];
423            $prefix     = substr( $table_name, 0, -strlen( 'options' ) );
424
425            // Only a WordPress options table holds a site URL. Other tables return false here.
426            $query = $this->prepare( 'SELECT COUNT(*) FROM "' . str_replace( '"', '""', $table_name ) . '" WHERE option_name = %s', 'siteurl' );
427
428            if ( @$this->db->querySingle( $query ) > 0 ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
429                $prefixes[] = $prefix;
430            }
431        }
432
433        foreach ( array( $requested_prefix, 'wp_' ) as $prefix ) {
434            if ( in_array( $prefix, $prefixes, true ) ) {
435                return $prefix;
436            }
437        }
438
439        return count( $prefixes ) === 1 ? $prefixes[0] : $requested_prefix;
440    }
441
442    /**
443     * Get the input table name without the prefix.
444     *
445     * @param string $table_name The table name.
446     *
447     * @return string
448     */
449    private function get_input_table_name( string $table_name ): string {
450        return substr( $table_name, 0, strlen( $this->options['prefix'] ) ) === $this->options['prefix'] ?
451            substr( $table_name, strlen( $this->options['prefix'] ) ) :
452            $table_name;
453    }
454
455    /**
456     * Get the output table name.
457     *
458     * @param string $table_name The table name.
459     *
460     * @return string
461     */
462    private function get_output_table_name( string $table_name ): string {
463        // Add the temporary prefix, if needed.
464        $prefix = $this->options['tmp_tables'] ? $this->options['tmp_prefix'] : '';
465
466        // Add the output prefix, if needed.
467        $prefix .= $this->options['output_prefix'] ? $this->options['output_prefix'] : '';
468
469        return $prefix . $table_name;
470    }
471
472    /**
473     * Get the table types map.
474     *
475     * @param string $table_name The table name.
476     *
477     * @return array|WP_Error
478     */
479    private function get_table_types_map( string $table_name ) {
480        if ( ! $this->db ) {
481            return new WP_Error( 'no-database-connection', 'No database connection.' );
482        }
483
484        // Get the "type map" of the table.
485        $query   = $this->prepare( 'SELECT COLUMN_NAME, COLUMN_TYPE, EXTRA from ' . self::SQLITE_DATA_TYPES_TABLE . ' where `TABLE_NAME`=%s;', $table_name );
486        $results = $this->db->query( $query );
487
488        if ( ! $results ) {
489            return new WP_Error( 'missing-types-cache', 'Query error: missing data types cache' );
490        }
491
492        $mysql_map      = array();
493        $auto_increment = array();
494
495        // Schema: COLUMN_NAME|COLUMN_TYPE|EXTRA
496        while ( $column = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
497            // Map by column name and MySQL type.
498            $mysql_map[ $column['COLUMN_NAME'] ] = $column['COLUMN_TYPE'];
499
500            // Keep AUTO_INCREMENT only where the site's schema has it. A primary key like `id varchar(64)` has none,
501            // and MySQL rejects AUTO_INCREMENT on a non-integer column.
502            $auto_increment[ $column['COLUMN_NAME'] ] = false !== stripos( (string) $column['EXTRA'], 'auto_increment' );
503        }
504
505        // Tables like `'_wp_sqlite_*` do not have entries in the `_wp_sqlite_mysql_information_schema_columns` table.
506        // In this case, we return an empty map.
507        if ( empty( $mysql_map ) ) {
508            return array(
509                'map'            => array(),
510                'auto_increment' => 0,
511                'field_names'    => null,
512                'format'         => null,
513            );
514        }
515
516        // Get the "table info" of the table.
517        $query         = $this->prepare( 'PRAGMA TABLE_INFO(%s)', $table_name );
518        $results       = $this->db->query( $query );
519        $primary_count = 0;
520
521        if ( ! $results ) {
522            return new WP_Error( 'missing-table-info', 'Query error: missing table info' );
523        }
524
525        // Our map.
526        $map         = array();
527        $map_by_name = array();
528        $index       = 0;
529        $has_autoinc = true;
530        $formats     = array();
531        $field_names = array();
532
533        // Schema: cid|name|type|notnull|dflt_value|pk
534        while ( $column = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
535            $is_primary    = $column['pk'] >= 1;
536            $field_names[] = $column['name'];
537
538            if ( ! array_key_exists( $column['name'], $mysql_map ) ) {
539                return new WP_Error(
540                    'missing-column',
541                    sprintf( 'Query error: not a valid SQLite table "%s", missing column "%s"', $table_name, $column['name'] )
542                );
543            }
544
545            // Add map info.
546            $map[] = array(
547                'name'           => $column['name'],
548                'type'           => $mysql_map[ $column['name'] ],
549                'sqlite_type'    => $column['type'],
550                'not_null'       => (bool) $column['notnull'],
551                'default'        => $column['dflt_value'],
552                'primary'        => $is_primary,
553                'auto_increment' => $is_primary && $auto_increment[ $column['name'] ],
554            );
555
556            $map_by_name[ $column['name'] ] = $index;
557
558            if ( $is_primary ) {
559                ++$primary_count;
560            }
561
562            $formats[] = $this->sqlite_type_to_format( $column['type'] );
563            ++$index;
564        }
565
566        // If the primary key is not a single column, then there is not autoincrement.
567        if ( $primary_count !== 1 ) {
568            $has_autoinc = false;
569
570            foreach ( $map as $index => $column ) {
571                $map[ $index ]['auto_increment'] = false;
572            }
573        }
574
575        // Load the table's indices as MySQL defined them, with their real names and prefix lengths.
576        $schema_indexes = $this->get_schema_indexes( $table_name );
577        if ( $schema_indexes !== null ) {
578            $map = array_merge( $map, $schema_indexes );
579
580            return $this->finish_table_types_map( $table_name, $map, $has_autoinc, $field_names, $formats );
581        }
582
583        // Fall back to the SQLite indices, for databases without the MySQL index definitions.
584        $query   = $this->prepare( 'SELECT name, sql FROM sqlite_master WHERE type=\'index\' AND tbl_name=%s', $table_name );
585        $results = $this->db->query( $query );
586
587        if ( ! $results ) {
588            return new WP_Error( 'missing-table-indices', 'Query error: not a valid SQLite database' );
589        }
590
591        // Loop all indices.
592        // Schema: name|sql
593        while ( $column = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
594            // Some SQLite columns are not indexed. See https://sqlite.org/forum/info/f16f8ed8666c5e97
595            if ( $column['sql'] === null ) {
596                continue;
597            }
598
599            // Strip out the index definition.
600            // wp_comments__comment_approved_date_gmt|CREATE INDEX "wp_comments__comment_approved_date_gmt" ON "wp_comments" ("comment_approved", "comment_date_gmt")
601            $split_query = explode( '` ON `' . $table_name . '` ', $column['sql'] );
602            $real_name   = SQL_Generator::get_index_name( $column['name'] );
603            $new_index   = array(
604                'name'    => $real_name,
605                'type'    => ( strpos( $column['sql'], 'CREATE UNIQUE INDEX' ) === 0 ) ? 'UNIQUE' : 'KEY',
606                'columns' => $split_query[1],
607            );
608
609            if ( array_key_exists( $real_name, $map_by_name ) ) {
610                $index = $map_by_name[ $real_name ];
611
612                if ( $this->needs_191_limit( $map[ $index ] ) ) {
613                    // See wp_get_db_schema $max_index_length for more info about why '191' must be added.
614                    $new_index['columns'] = str_replace( '`)', '`(191))', $new_index['columns'] );
615                }
616            }
617
618            $map[] = $new_index;
619        }
620
621        return $this->finish_table_types_map( $table_name, $map, $has_autoinc, $field_names, $formats );
622    }
623
624    /**
625     * The table's indices from the MySQL index definitions the SQLite driver keeps.
626     *
627     * SQLite's own indices lose MySQL's prefix lengths, like TranslatePress's `original`(100) on a text column,
628     * and their names are rebuilt from `<table>__<index>`, which breaks on index names containing `__`.
629     *
630     * @param string $table_name The table name.
631     *
632     * @return array|null The index map entries, or null if the definitions aren't available.
633     */
634    private function get_schema_indexes( string $table_name ): ?array {
635        $query = $this->prepare( 'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=%s', self::SQLITE_INDEXES_TABLE );
636        if ( ! $this->db->querySingle( $query ) ) {
637            return null;
638        }
639
640        $query   = $this->prepare( 'SELECT INDEX_NAME, NON_UNIQUE, SEQ_IN_INDEX, COLUMN_NAME, SUB_PART, INDEX_TYPE FROM ' . self::SQLITE_INDEXES_TABLE . ' WHERE TABLE_NAME=%s ORDER BY rowid', $table_name );
641        $results = $this->db->query( $query );
642        if ( ! $results ) {
643            return null;
644        }
645
646        $indexes = array();
647        while ( $row = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
648            // The primary key is output from the columns.
649            if ( $row['INDEX_NAME'] === 'PRIMARY' ) {
650                continue;
651            }
652
653            $name = $row['INDEX_NAME'];
654            if ( ! isset( $indexes[ $name ] ) ) {
655                if ( in_array( strtoupper( (string) $row['INDEX_TYPE'] ), array( 'FULLTEXT', 'SPATIAL' ), true ) ) {
656                    $type = strtoupper( (string) $row['INDEX_TYPE'] );
657                } else {
658                    $type = ( (int) $row['NON_UNIQUE'] === 0 ) ? 'UNIQUE' : 'KEY';
659                }
660
661                $indexes[ $name ] = array(
662                    'name'    => $name,
663                    'type'    => $type,
664                    'columns' => array(),
665                );
666            }
667
668            // A spatial index has no prefix length. The SQLite driver reports one of 32.
669            $sub_part = 'SPATIAL' === $indexes[ $name ]['type'] ? null : $row['SUB_PART'];
670
671            $indexes[ $name ]['columns'][ (int) $row['SEQ_IN_INDEX'] ] = '`' . $row['COLUMN_NAME'] . '`' . ( $sub_part ? '(' . (int) $sub_part . ')' : '' );
672        }
673
674        // Keep the indices in creation order, and their columns in index order.
675        foreach ( $indexes as $name => $index ) {
676            ksort( $index['columns'] );
677            $indexes[ $name ]['columns'] = '(' . implode( ', ', $index['columns'] ) . ')';
678        }
679
680        return array_values( $indexes );
681    }
682
683    /**
684     * Apply the index hot fixes and build the table types map.
685     *
686     * @param string $table_name  The table name.
687     * @param array  $map         The columns and indices map.
688     * @param bool   $has_autoinc Whether the table has an AUTO_INCREMENT column.
689     * @param array  $field_names The field names.
690     * @param array  $formats     The field formats.
691     *
692     * @return array
693     */
694    private function finish_table_types_map( string $table_name, array $map, bool $has_autoinc, array $field_names, array $formats ): array {
695        // Hot fix: add the missing index sizes. The fixes are listed under the `wp_` prefix.
696        $map = $this->hot_fix_missing_indexes( 'wp_' . $this->get_input_table_name( $table_name ), $map );
697        $map = $this->fit_row_size( $map );
698
699        $auto_increment = 0;
700
701        if ( $has_autoinc ) {
702            $auto_increment = $this->get_table_autoincrement( $table_name );
703        }
704
705        return array(
706            'map'            => $map,
707            'auto_increment' => $auto_increment,
708            'field_names'    => '(`' . implode( '`,`', $field_names ) . '`)',
709            'format'         => '(' . implode( ',', $formats ) . ')',
710            'formats'        => $formats,
711            'columns'        => $field_names,
712            'geometry'       => $this->get_geometry_columns( $map ),
713        );
714    }
715
716    /**
717     * The table's spatial columns, by column position.
718     *
719     * @param array $map The columns and indices map.
720     *
721     * @return array
722     */
723    private function get_geometry_columns( array $map ): array {
724        $geometry = array();
725        $position = 0;
726
727        foreach ( $map as $column ) {
728            if ( ! array_key_exists( 'sqlite_type', $column ) ) {
729                continue;
730            }
731
732            $type = strtolower( (string) strtok( $column['type'], ' (' ) );
733
734            if ( in_array( $type, self::GEOMETRY_TYPES, true ) ) {
735                $geometry[ $position ] = array(
736                    'type'     => $type,
737                    'not_null' => ! empty( $column['not_null'] ),
738                );
739            }
740
741            ++$position;
742        }
743
744        return $geometry;
745    }
746
747    /**
748     * Turn the widest VARCHAR and VARBINARY columns into TEXT and BLOB until the row fits in MySQL.
749     *
750     * MySQL limits a row's columns, not counting TEXT and BLOB, to 65,535 bytes, and fails the restore with
751     * ERROR 1118 past that. SQLite has no such limit, so a table with many wide VARCHAR columns works there.
752     * Indexed columns are kept, since a TEXT column needs a prefix length to be indexed.
753     *
754     * @param array $map The columns and indices map.
755     *
756     * @return array
757     */
758    private function fit_row_size( array $map ): array {
759        $bytes_per_char = array(
760            'latin1'  => 1,
761            'utf8'    => 3,
762            'utf8mb3' => 3,
763        );
764        $charset        = strtolower( (string) ( $this->options['charset'] ?? 'latin1' ) );
765        $mb             = $bytes_per_char[ $charset ] ?? 4;
766        $indexed        = array();
767        $sizes          = array();
768        $nullable       = 0;
769
770        foreach ( $map as $column ) {
771            if ( ! array_key_exists( 'sqlite_type', $column ) ) {
772                preg_match_all( '/`([^`]+)`/', (string) ( $column['columns'] ?? '' ), $matches );
773                $indexed = array_merge( $indexed, $matches[1] );
774            }
775        }
776
777        foreach ( $map as $i => $column ) {
778            if ( ! array_key_exists( 'sqlite_type', $column ) ) {
779                continue;
780            }
781
782            $sizes[ $i ] = self::get_column_size( (string) $column['type'], $mb );
783            $nullable   += empty( $column['not_null'] ) ? 1 : 0;
784        }
785
786        $total = array_sum( array_column( $sizes, 'bytes' ) ) + (int) ceil( $nullable / 8 );
787
788        if ( $total <= self::MAX_ROW_SIZE ) {
789            return $map;
790        }
791
792        // Widest first.
793        uasort(
794            $sizes,
795            function ( $a, $b ) {
796                return $b['bytes'] <=> $a['bytes'];
797            }
798        );
799
800        foreach ( $sizes as $i => $size ) {
801            if ( $total <= self::MAX_ROW_SIZE ) {
802                break;
803            }
804
805            if ( null === $size['long_type'] || ! empty( $map[ $i ]['primary'] ) || in_array( $map[ $i ]['name'], $indexed, true ) ) {
806                continue;
807            }
808
809            $map[ $i ]['type'] = $size['long_type'];
810
811            // MySQL takes a TEXT or BLOB default only as an expression.
812            if ( isset( $map[ $i ]['default'] ) && 'NULL' !== strtoupper( (string) $map[ $i ]['default'] ) ) {
813                $map[ $i ]['default'] = '(' . $map[ $i ]['default'] . ')';
814            }
815
816            // A TEXT or BLOB column counts as 12 bytes, at most.
817            $total -= $size['bytes'] - 12;
818        }
819
820        return $map;
821    }
822
823    /**
824     * A column's size in a MySQL row, and the TEXT or BLOB type it can become.
825     *
826     * @param string $type The MySQL column type, like `varchar(255)`.
827     * @param int    $mb   The bytes per character.
828     *
829     * @return array {
830     *     @type int         $bytes     The column's size, in bytes.
831     *     @type string|null $long_type The TEXT or BLOB type it can become, or null.
832     * }
833     */
834    private static function get_column_size( string $type, int $mb ): array {
835        $type   = strtolower( $type );
836        $length = preg_match( '/\((\d+)/', $type, $matches ) ? (int) $matches[1] : 1;
837        $name   = (string) strtok( $type, ' (' );
838        $fixed  = array(
839            'tinyint'   => 1,
840            'smallint'  => 2,
841            'mediumint' => 3,
842            'int'       => 4,
843            'integer'   => 4,
844            'bigint'    => 8,
845            'float'     => 4,
846            'double'    => 8,
847            'real'      => 8,
848            'date'      => 3,
849            'time'      => 6,
850            'year'      => 1,
851            'datetime'  => 8,
852            'timestamp' => 7,
853            'enum'      => 2,
854            'set'       => 8,
855            'bit'       => 8,
856            'decimal'   => 30,
857            'numeric'   => 30,
858        );
859
860        switch ( $name ) {
861            case 'varchar':
862                $bytes = $length * $mb;
863                return array(
864                    'bytes'     => $bytes + ( $bytes > 255 ? 2 : 1 ),
865                    'long_type' => $bytes > 65535 ? 'mediumtext' : 'text',
866                );
867            case 'varbinary':
868                return array(
869                    'bytes'     => $length + ( $length > 255 ? 2 : 1 ),
870                    'long_type' => 'blob',
871                );
872            case 'char':
873                return array(
874                    'bytes'     => $length * $mb,
875                    'long_type' => null,
876                );
877            case 'binary':
878                return array(
879                    'bytes'     => $length,
880                    'long_type' => null,
881                );
882        }
883
884        return array(
885            'bytes'     => $fixed[ $name ] ?? 12,
886            'long_type' => null,
887        );
888    }
889
890    /**
891     * Get the SQLite type to MySQL format.
892     *
893     * @param string $type The SQLite type.
894     *
895     * @return string
896     */
897    public function sqlite_type_to_format( string $type ): string {
898        switch ( $type ) {
899            case 'integer':
900                return '%d';
901            case 'real':
902                return '%f';
903            case 'text':
904                return '%s';
905            case 'blob':
906                return '%s';
907            case 'null':
908                return '%s';
909            default:
910                return '%s';
911        }
912    }
913
914    /**
915     * Check if the maximum index length of 191 must be added.
916     *
917     * @see wp_get_db_schema $max_index_length for more info.
918     *
919     * @param array $key_map The key map.
920     *
921     * @return bool
922     */
923    public function needs_191_limit( array $key_map ): bool {
924        if ( $key_map['sqlite_type'] !== 'text' ) {
925            return false;
926        }
927
928        // Check if the column type is a text type.
929        $ret = in_array( $key_map['type'], array( 'text', 'tinytext', 'mediumtext', 'longtext' ), true );
930
931        if ( $ret ) {
932            return $ret;
933        }
934
935        // Check if the string is of type varchar(255).
936        $matches = null;
937        preg_match( '/varchar\((\d+)\)/', $key_map['type'], $matches );
938
939        if ( isset( $matches[1] ) ) {
940            // The limit must be added only if the column length is greater than 191.
941            return (int) $matches[1] > 191;
942        }
943
944        return false;
945    }
946
947    /**
948     * Get the table autoincrement value.
949     *
950     * @param string $table_name The table name.
951     *
952     * @return int
953     */
954    private function get_table_autoincrement( $table_name ): int {
955        $query = $this->prepare( 'SELECT seq from ' . self::SQLITE_SEQUENCE_TABLE . ' WHERE name=%s', $table_name );
956
957        return $this->db->querySingle( $query ) ?? 0;
958    }
959
960    /**
961     * Get an export random file name.
962     *
963     * @return string
964     */
965    public function get_tmp_file_name(): string {
966        // A random string to avoid collisions.
967        return 'sqlite-export-' . uniqid() . '.sql';
968    }
969
970    /**
971     * Prepare a query.
972     *
973     * @param string $query The query.
974     * @param mixed  ...$args The arguments.
975     *
976     * @return string|void
977     */
978    private function prepare( $query, ...$args ) {
979        global $wpdb;
980
981        $query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $query ), $args ) );
982
983        if ( is_string( $query ) ) {
984            return $wpdb->remove_placeholder_escape( $query );
985        }
986    }
987
988    /**
989     * Hot fix: add the missing index sizes. The default SQLite driver do not
990     * generate index sizes and sometimes the indexes are not valid when made of
991     * multiple text and integer columns and are more than 191 characters.
992     *
993     * Known columns are from WooCommerce.
994     *
995     * Example:
996     * KEY `order_id_meta_key_meta_value` (`order_id`, `meta_key`, `meta_value`)
997     *
998     * should be:
999     * KEY `order_id_meta_key_meta_value` (`order_id`,`meta_key`(100),`meta_value`(82))
1000     *
1001     * Once we have a better SQLite driver, we can remove this function.
1002     *
1003     * @param string $table_name The table name.
1004     * @param array  $map The columns map.
1005     *
1006     * @return array
1007     */
1008    public function hot_fix_missing_indexes( string $table_name, array $map ) {
1009        // Fix: the default SQLite driver do not generate save index sizes.
1010        $fix_map = array(
1011            'wp_wc_orders'                           => array(
1012                'customer_id_billing_email' => '(`customer_id`,`billing_email`(171))',
1013            ),
1014            'wp_wc_orders_meta'                      => array(
1015                'meta_key_value'               => '(`meta_key`(100),`meta_value`(82))',
1016                'order_id_meta_key_meta_value' => '(`order_id`,`meta_key`(100),`meta_value`(82))',
1017            ),
1018            'wp_woocommerce_downloadable_product_permissions' => array(
1019                'download_order_key_product' => '(`product_id`,`order_id`,`order_key`(16),`download_id`)',
1020            ),
1021            'wp_woocommerce_shipping_zone_locations' => array(
1022                'location_type_code' => '(`location_type`(10),`location_code`(20))',
1023            ),
1024            'wp_woocommerce_tax_rate_locations'      => array(
1025                'location_type_code' => '(`location_type`(10),`location_code`(20))',
1026            ),
1027        );
1028
1029        if ( ! array_key_exists( $table_name, $fix_map ) ) {
1030            // No fix for this table.
1031            return $map;
1032        }
1033
1034        foreach ( $map as $i => $column ) {
1035            if ( array_key_exists( $column['name'], $fix_map[ $table_name ] ) ) {
1036                // Hot fix: add the missing index sizes.
1037                $map[ $i ]['columns'] = $fix_map[ $table_name ][ $column['name'] ];
1038            }
1039        }
1040
1041        return $map;
1042    }
1043
1044    /**
1045     * Check if the table is valid.
1046     *
1047     * @param string $table_name The table name.
1048     *
1049     * @return bool
1050     */
1051    public function is_valid_table( string $table_name ): bool {
1052        // Skip SQLite internal tables.
1053        if ( $table_name === self::SQLITE_DATA_TYPES_TABLE || $table_name === self::SQLITE_SEQUENCE_TABLE ) {
1054            return false;
1055        }
1056
1057        // Skip WordPress internal tables.
1058        if ( strpos( $table_name, '_wp_sqlite' ) === 0 ) {
1059            return false;
1060        }
1061
1062        return true;
1063    }
1064}