Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.40% covered (success)
91.40%
404 / 442
75.00% covered (warning)
75.00%
18 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
Playground_DB_Importer
91.61% covered (success)
91.61%
404 / 441
75.00% covered (warning)
75.00%
18 / 24
166.83
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.48% covered (warning)
81.48%
66 / 81
0.00% covered (danger)
0.00%
0 / 1
21.29
 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_default
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
 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, DATA_TYPE, COLUMN_TYPE, COLUMN_DEFAULT, 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        $defaults       = array();
495
496        // Schema: COLUMN_NAME|DATA_TYPE|COLUMN_TYPE|COLUMN_DEFAULT|EXTRA
497        while ( $column = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
498            // Map by column name and MySQL type.
499            $mysql_map[ $column['COLUMN_NAME'] ] = $column['COLUMN_TYPE'];
500
501            // Take the default from the site's MySQL schema, not from SQLite. SQLite's can be invalid in MySQL.
502            $defaults[ $column['COLUMN_NAME'] ] = self::get_column_default( $column );
503
504            // Keep AUTO_INCREMENT only where the site's schema has it. A primary key like `id varchar(64)` has none,
505            // and MySQL rejects AUTO_INCREMENT on a non-integer column.
506            $auto_increment[ $column['COLUMN_NAME'] ] = false !== stripos( (string) $column['EXTRA'], 'auto_increment' );
507        }
508
509        // Tables like `'_wp_sqlite_*` do not have entries in the `_wp_sqlite_mysql_information_schema_columns` table.
510        // In this case, we return an empty map.
511        if ( empty( $mysql_map ) ) {
512            return array(
513                'map'            => array(),
514                'auto_increment' => 0,
515                'field_names'    => null,
516                'format'         => null,
517            );
518        }
519
520        // Get the "table info" of the table.
521        $query         = $this->prepare( 'PRAGMA TABLE_INFO(%s)', $table_name );
522        $results       = $this->db->query( $query );
523        $primary_count = 0;
524
525        if ( ! $results ) {
526            return new WP_Error( 'missing-table-info', 'Query error: missing table info' );
527        }
528
529        // Our map.
530        $map         = array();
531        $map_by_name = array();
532        $index       = 0;
533        $has_autoinc = true;
534        $formats     = array();
535        $field_names = array();
536
537        // Schema: cid|name|type|notnull|dflt_value|pk
538        while ( $column = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
539            $is_primary    = $column['pk'] >= 1;
540            $field_names[] = $column['name'];
541
542            if ( ! array_key_exists( $column['name'], $mysql_map ) ) {
543                return new WP_Error(
544                    'missing-column',
545                    sprintf( 'Query error: not a valid SQLite table "%s", missing column "%s"', $table_name, $column['name'] )
546                );
547            }
548
549            // Add map info.
550            $map[] = array(
551                'name'           => $column['name'],
552                'type'           => $mysql_map[ $column['name'] ],
553                'sqlite_type'    => $column['type'],
554                'not_null'       => (bool) $column['notnull'],
555                'default'        => $defaults[ $column['name'] ],
556                'primary'        => $is_primary,
557                'auto_increment' => $is_primary && $auto_increment[ $column['name'] ],
558            );
559
560            $map_by_name[ $column['name'] ] = $index;
561
562            if ( $is_primary ) {
563                ++$primary_count;
564            }
565
566            $formats[] = $this->sqlite_type_to_format( $column['type'] );
567            ++$index;
568        }
569
570        // If the primary key is not a single column, then there is not autoincrement.
571        if ( $primary_count !== 1 ) {
572            $has_autoinc = false;
573
574            foreach ( $map as $index => $column ) {
575                $map[ $index ]['auto_increment'] = false;
576            }
577        }
578
579        // Load the table's indices as MySQL defined them, with their real names and prefix lengths.
580        $schema_indexes = $this->get_schema_indexes( $table_name );
581        if ( $schema_indexes !== null ) {
582            $map = array_merge( $map, $schema_indexes );
583
584            return $this->finish_table_types_map( $table_name, $map, $has_autoinc, $field_names, $formats );
585        }
586
587        // Fall back to the SQLite indices, for databases without the MySQL index definitions.
588        $query   = $this->prepare( 'SELECT name, sql FROM sqlite_master WHERE type=\'index\' AND tbl_name=%s', $table_name );
589        $results = $this->db->query( $query );
590
591        if ( ! $results ) {
592            return new WP_Error( 'missing-table-indices', 'Query error: not a valid SQLite database' );
593        }
594
595        // Loop all indices.
596        // Schema: name|sql
597        while ( $column = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
598            // Some SQLite columns are not indexed. See https://sqlite.org/forum/info/f16f8ed8666c5e97
599            if ( $column['sql'] === null ) {
600                continue;
601            }
602
603            // Strip out the index definition.
604            // wp_comments__comment_approved_date_gmt|CREATE INDEX "wp_comments__comment_approved_date_gmt" ON "wp_comments" ("comment_approved", "comment_date_gmt")
605            $split_query = explode( '` ON `' . $table_name . '` ', $column['sql'] );
606            $real_name   = SQL_Generator::get_index_name( $column['name'] );
607            $new_index   = array(
608                'name'    => $real_name,
609                'type'    => ( strpos( $column['sql'], 'CREATE UNIQUE INDEX' ) === 0 ) ? 'UNIQUE' : 'KEY',
610                'columns' => $split_query[1],
611            );
612
613            if ( array_key_exists( $real_name, $map_by_name ) ) {
614                $index = $map_by_name[ $real_name ];
615
616                if ( $this->needs_191_limit( $map[ $index ] ) ) {
617                    // See wp_get_db_schema $max_index_length for more info about why '191' must be added.
618                    $new_index['columns'] = str_replace( '`)', '`(191))', $new_index['columns'] );
619                }
620            }
621
622            $map[] = $new_index;
623        }
624
625        return $this->finish_table_types_map( $table_name, $map, $has_autoinc, $field_names, $formats );
626    }
627
628    /**
629     * The table's indices from the MySQL index definitions the SQLite driver keeps.
630     *
631     * SQLite's own indices lose MySQL's prefix lengths, like TranslatePress's `original`(100) on a text column,
632     * and their names are rebuilt from `<table>__<index>`, which breaks on index names containing `__`.
633     *
634     * @param string $table_name The table name.
635     *
636     * @return array|null The index map entries, or null if the definitions aren't available.
637     */
638    private function get_schema_indexes( string $table_name ): ?array {
639        $query = $this->prepare( 'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=%s', self::SQLITE_INDEXES_TABLE );
640        if ( ! $this->db->querySingle( $query ) ) {
641            return null;
642        }
643
644        $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 );
645        $results = $this->db->query( $query );
646        if ( ! $results ) {
647            return null;
648        }
649
650        $indexes = array();
651        while ( $row = $results->fetchArray( SQLITE3_ASSOC ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
652            // The primary key is output from the columns.
653            if ( $row['INDEX_NAME'] === 'PRIMARY' ) {
654                continue;
655            }
656
657            $name = $row['INDEX_NAME'];
658            if ( ! isset( $indexes[ $name ] ) ) {
659                if ( in_array( strtoupper( (string) $row['INDEX_TYPE'] ), array( 'FULLTEXT', 'SPATIAL' ), true ) ) {
660                    $type = strtoupper( (string) $row['INDEX_TYPE'] );
661                } else {
662                    $type = ( (int) $row['NON_UNIQUE'] === 0 ) ? 'UNIQUE' : 'KEY';
663                }
664
665                $indexes[ $name ] = array(
666                    'name'    => $name,
667                    'type'    => $type,
668                    'columns' => array(),
669                );
670            }
671
672            // A spatial index has no prefix length. The SQLite driver reports one of 32.
673            $sub_part = 'SPATIAL' === $indexes[ $name ]['type'] ? null : $row['SUB_PART'];
674
675            $indexes[ $name ]['columns'][ (int) $row['SEQ_IN_INDEX'] ] = '`' . $row['COLUMN_NAME'] . '`' . ( $sub_part ? '(' . (int) $sub_part . ')' : '' );
676        }
677
678        // Keep the indices in creation order, and their columns in index order.
679        foreach ( $indexes as $name => $index ) {
680            ksort( $index['columns'] );
681            $indexes[ $name ]['columns'] = '(' . implode( ', ', $index['columns'] ) . ')';
682        }
683
684        return array_values( $indexes );
685    }
686
687    /**
688     * Apply the index hot fixes and build the table types map.
689     *
690     * @param string $table_name  The table name.
691     * @param array  $map         The columns and indices map.
692     * @param bool   $has_autoinc Whether the table has an AUTO_INCREMENT column.
693     * @param array  $field_names The field names.
694     * @param array  $formats     The field formats.
695     *
696     * @return array
697     */
698    private function finish_table_types_map( string $table_name, array $map, bool $has_autoinc, array $field_names, array $formats ): array {
699        // Hot fix: add the missing index sizes. The fixes are listed under the `wp_` prefix.
700        $map = $this->hot_fix_missing_indexes( 'wp_' . $this->get_input_table_name( $table_name ), $map );
701        $map = $this->fit_row_size( $map );
702
703        $auto_increment = 0;
704
705        if ( $has_autoinc ) {
706            $auto_increment = $this->get_table_autoincrement( $table_name );
707        }
708
709        return array(
710            'map'            => $map,
711            'auto_increment' => $auto_increment,
712            'field_names'    => '(`' . implode( '`,`', $field_names ) . '`)',
713            'format'         => '(' . implode( ',', $formats ) . ')',
714            'formats'        => $formats,
715            'columns'        => $field_names,
716            'geometry'       => $this->get_geometry_columns( $map ),
717        );
718    }
719
720    /**
721     * The table's spatial columns, by column position.
722     *
723     * @param array $map The columns and indices map.
724     *
725     * @return array
726     */
727    private function get_geometry_columns( array $map ): array {
728        $geometry = array();
729        $position = 0;
730
731        foreach ( $map as $column ) {
732            if ( ! array_key_exists( 'sqlite_type', $column ) ) {
733                continue;
734            }
735
736            $type = strtolower( (string) strtok( $column['type'], ' (' ) );
737
738            if ( in_array( $type, self::GEOMETRY_TYPES, true ) ) {
739                $geometry[ $position ] = array(
740                    'type'     => $type,
741                    'not_null' => ! empty( $column['not_null'] ),
742                );
743            }
744
745            ++$position;
746        }
747
748        return $geometry;
749    }
750
751    /**
752     * Turn the widest VARCHAR and VARBINARY columns into TEXT and BLOB until the row fits in MySQL.
753     *
754     * MySQL limits a row's columns, not counting TEXT and BLOB, to 65,535 bytes, and fails the restore with
755     * ERROR 1118 past that. SQLite has no such limit, so a table with many wide VARCHAR columns works there.
756     * Indexed columns are kept, since a TEXT column needs a prefix length to be indexed.
757     *
758     * @param array $map The columns and indices map.
759     *
760     * @return array
761     */
762    private function fit_row_size( array $map ): array {
763        $bytes_per_char = array(
764            'latin1'  => 1,
765            'utf8'    => 3,
766            'utf8mb3' => 3,
767        );
768        $charset        = strtolower( (string) ( $this->options['charset'] ?? 'latin1' ) );
769        $mb             = $bytes_per_char[ $charset ] ?? 4;
770        $indexed        = array();
771        $sizes          = array();
772        $nullable       = 0;
773
774        foreach ( $map as $column ) {
775            if ( ! array_key_exists( 'sqlite_type', $column ) ) {
776                preg_match_all( '/`([^`]+)`/', (string) ( $column['columns'] ?? '' ), $matches );
777                $indexed = array_merge( $indexed, $matches[1] );
778            }
779        }
780
781        foreach ( $map as $i => $column ) {
782            if ( ! array_key_exists( 'sqlite_type', $column ) ) {
783                continue;
784            }
785
786            $sizes[ $i ] = self::get_column_size( (string) $column['type'], $mb );
787            $nullable   += empty( $column['not_null'] ) ? 1 : 0;
788        }
789
790        $total = array_sum( array_column( $sizes, 'bytes' ) ) + (int) ceil( $nullable / 8 );
791
792        if ( $total <= self::MAX_ROW_SIZE ) {
793            return $map;
794        }
795
796        // Widest first.
797        uasort(
798            $sizes,
799            function ( $a, $b ) {
800                return $b['bytes'] <=> $a['bytes'];
801            }
802        );
803
804        foreach ( $sizes as $i => $size ) {
805            if ( $total <= self::MAX_ROW_SIZE ) {
806                break;
807            }
808
809            if ( null === $size['long_type'] || ! empty( $map[ $i ]['primary'] ) || in_array( $map[ $i ]['name'], $indexed, true ) ) {
810                continue;
811            }
812
813            $map[ $i ]['type'] = $size['long_type'];
814
815            // MySQL takes a TEXT or BLOB default only as an expression.
816            if ( isset( $map[ $i ]['default'] ) && 'NULL' !== strtoupper( (string) $map[ $i ]['default'] ) ) {
817                $map[ $i ]['default'] = '(' . $map[ $i ]['default'] . ')';
818            }
819
820            // A TEXT or BLOB column counts as 12 bytes, at most.
821            $total -= $size['bytes'] - 12;
822        }
823
824        return $map;
825    }
826
827    /**
828     * A column's DEFAULT clause value, from its row in the site's MySQL schema.
829     *
830     * SQLite's own default can be invalid in MySQL, which rejects the table with ERROR 1067:
831     * - The legacy SQLite translator gave NOT NULL text columns without a default `DEFAULT ''`,
832     *   like WPForms' `date_created_gmt datetime NOT NULL`.
833     * - The SQLite driver 2.2 stored a `bit` default as the string `'0'`, like Ninja Forms' `maintenance bit DEFAULT 0`.
834     *
835     * @param array $column The column's COLUMN_DEFAULT, DATA_TYPE, and EXTRA.
836     *
837     * @return string|null The default as SQL, or null when the column has none.
838     */
839    private static function get_column_default( array $column ): ?string {
840        $default = $column['COLUMN_DEFAULT'];
841
842        if ( null === $default ) {
843            return null;
844        }
845
846        $default = (string) $default;
847        $type    = strtolower( (string) $column['DATA_TYPE'] );
848
849        // An expression, like CURRENT_TIMESTAMP.
850        if ( false !== stripos( (string) $column['EXTRA'], 'DEFAULT_GENERATED' ) ) {
851            return $default;
852        }
853
854        // A bit literal, like b'0'.
855        if ( 'bit' === $type && preg_match( "/^b'[01]*'$/i", $default ) ) {
856            return $default;
857        }
858
859        $numeric = array( 'bit', 'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint', 'decimal', 'numeric', 'float', 'double', 'real' );
860
861        if ( in_array( $type, $numeric, true ) && is_numeric( $default ) ) {
862            return $default;
863        }
864
865        return "'" . str_replace( array( '\\', "'" ), array( '\\\\', "''" ), $default ) . "'";
866    }
867
868    /**
869     * A column's size in a MySQL row, and the TEXT or BLOB type it can become.
870     *
871     * @param string $type The MySQL column type, like `varchar(255)`.
872     * @param int    $mb   The bytes per character.
873     *
874     * @return array {
875     *     @type int         $bytes     The column's size, in bytes.
876     *     @type string|null $long_type The TEXT or BLOB type it can become, or null.
877     * }
878     */
879    private static function get_column_size( string $type, int $mb ): array {
880        $type   = strtolower( $type );
881        $length = preg_match( '/\((\d+)/', $type, $matches ) ? (int) $matches[1] : 1;
882        $name   = (string) strtok( $type, ' (' );
883        $fixed  = array(
884            'tinyint'   => 1,
885            'smallint'  => 2,
886            'mediumint' => 3,
887            'int'       => 4,
888            'integer'   => 4,
889            'bigint'    => 8,
890            'float'     => 4,
891            'double'    => 8,
892            'real'      => 8,
893            'date'      => 3,
894            'time'      => 6,
895            'year'      => 1,
896            'datetime'  => 8,
897            'timestamp' => 7,
898            'enum'      => 2,
899            'set'       => 8,
900            'bit'       => 8,
901            'decimal'   => 30,
902            'numeric'   => 30,
903        );
904
905        switch ( $name ) {
906            case 'varchar':
907                $bytes = $length * $mb;
908                return array(
909                    'bytes'     => $bytes + ( $bytes > 255 ? 2 : 1 ),
910                    'long_type' => $bytes > 65535 ? 'mediumtext' : 'text',
911                );
912            case 'varbinary':
913                return array(
914                    'bytes'     => $length + ( $length > 255 ? 2 : 1 ),
915                    'long_type' => 'blob',
916                );
917            case 'char':
918                return array(
919                    'bytes'     => $length * $mb,
920                    'long_type' => null,
921                );
922            case 'binary':
923                return array(
924                    'bytes'     => $length,
925                    'long_type' => null,
926                );
927        }
928
929        return array(
930            'bytes'     => $fixed[ $name ] ?? 12,
931            'long_type' => null,
932        );
933    }
934
935    /**
936     * Get the SQLite type to MySQL format.
937     *
938     * @param string $type The SQLite type.
939     *
940     * @return string
941     */
942    public function sqlite_type_to_format( string $type ): string {
943        switch ( $type ) {
944            case 'integer':
945                return '%d';
946            case 'real':
947                return '%f';
948            case 'text':
949                return '%s';
950            case 'blob':
951                return '%s';
952            case 'null':
953                return '%s';
954            default:
955                return '%s';
956        }
957    }
958
959    /**
960     * Check if the maximum index length of 191 must be added.
961     *
962     * @see wp_get_db_schema $max_index_length for more info.
963     *
964     * @param array $key_map The key map.
965     *
966     * @return bool
967     */
968    public function needs_191_limit( array $key_map ): bool {
969        if ( $key_map['sqlite_type'] !== 'text' ) {
970            return false;
971        }
972
973        // Check if the column type is a text type.
974        $ret = in_array( $key_map['type'], array( 'text', 'tinytext', 'mediumtext', 'longtext' ), true );
975
976        if ( $ret ) {
977            return $ret;
978        }
979
980        // Check if the string is of type varchar(255).
981        $matches = null;
982        preg_match( '/varchar\((\d+)\)/', $key_map['type'], $matches );
983
984        if ( isset( $matches[1] ) ) {
985            // The limit must be added only if the column length is greater than 191.
986            return (int) $matches[1] > 191;
987        }
988
989        return false;
990    }
991
992    /**
993     * Get the table autoincrement value.
994     *
995     * @param string $table_name The table name.
996     *
997     * @return int
998     */
999    private function get_table_autoincrement( $table_name ): int {
1000        $query = $this->prepare( 'SELECT seq from ' . self::SQLITE_SEQUENCE_TABLE . ' WHERE name=%s', $table_name );
1001
1002        return $this->db->querySingle( $query ) ?? 0;
1003    }
1004
1005    /**
1006     * Get an export random file name.
1007     *
1008     * @return string
1009     */
1010    public function get_tmp_file_name(): string {
1011        // A random string to avoid collisions.
1012        return 'sqlite-export-' . uniqid() . '.sql';
1013    }
1014
1015    /**
1016     * Prepare a query.
1017     *
1018     * @param string $query The query.
1019     * @param mixed  ...$args The arguments.
1020     *
1021     * @return string|void
1022     */
1023    private function prepare( $query, ...$args ) {
1024        global $wpdb;
1025
1026        $query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $query ), $args ) );
1027
1028        if ( is_string( $query ) ) {
1029            return $wpdb->remove_placeholder_escape( $query );
1030        }
1031    }
1032
1033    /**
1034     * Hot fix: add the missing index sizes. The default SQLite driver do not
1035     * generate index sizes and sometimes the indexes are not valid when made of
1036     * multiple text and integer columns and are more than 191 characters.
1037     *
1038     * Known columns are from WooCommerce.
1039     *
1040     * Example:
1041     * KEY `order_id_meta_key_meta_value` (`order_id`, `meta_key`, `meta_value`)
1042     *
1043     * should be:
1044     * KEY `order_id_meta_key_meta_value` (`order_id`,`meta_key`(100),`meta_value`(82))
1045     *
1046     * Once we have a better SQLite driver, we can remove this function.
1047     *
1048     * @param string $table_name The table name.
1049     * @param array  $map The columns map.
1050     *
1051     * @return array
1052     */
1053    public function hot_fix_missing_indexes( string $table_name, array $map ) {
1054        // Fix: the default SQLite driver do not generate save index sizes.
1055        $fix_map = array(
1056            'wp_wc_orders'                           => array(
1057                'customer_id_billing_email' => '(`customer_id`,`billing_email`(171))',
1058            ),
1059            'wp_wc_orders_meta'                      => array(
1060                'meta_key_value'               => '(`meta_key`(100),`meta_value`(82))',
1061                'order_id_meta_key_meta_value' => '(`order_id`,`meta_key`(100),`meta_value`(82))',
1062            ),
1063            'wp_woocommerce_downloadable_product_permissions' => array(
1064                'download_order_key_product' => '(`product_id`,`order_id`,`order_key`(16),`download_id`)',
1065            ),
1066            'wp_woocommerce_shipping_zone_locations' => array(
1067                'location_type_code' => '(`location_type`(10),`location_code`(20))',
1068            ),
1069            'wp_woocommerce_tax_rate_locations'      => array(
1070                'location_type_code' => '(`location_type`(10),`location_code`(20))',
1071            ),
1072        );
1073
1074        if ( ! array_key_exists( $table_name, $fix_map ) ) {
1075            // No fix for this table.
1076            return $map;
1077        }
1078
1079        foreach ( $map as $i => $column ) {
1080            if ( array_key_exists( $column['name'], $fix_map[ $table_name ] ) ) {
1081                // Hot fix: add the missing index sizes.
1082                $map[ $i ]['columns'] = $fix_map[ $table_name ][ $column['name'] ];
1083            }
1084        }
1085
1086        return $map;
1087    }
1088
1089    /**
1090     * Check if the table is valid.
1091     *
1092     * @param string $table_name The table name.
1093     *
1094     * @return bool
1095     */
1096    public function is_valid_table( string $table_name ): bool {
1097        // Skip SQLite internal tables.
1098        if ( $table_name === self::SQLITE_DATA_TYPES_TABLE || $table_name === self::SQLITE_SEQUENCE_TABLE ) {
1099            return false;
1100        }
1101
1102        // Skip WordPress internal tables.
1103        if ( strpos( $table_name, '_wp_sqlite' ) === 0 ) {
1104            return false;
1105        }
1106
1107        return true;
1108    }
1109}