|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Automattic\WP_CLI\SQLite; |
| 4 | + |
| 5 | +use WP_CLI; |
| 6 | +use PDO; |
| 7 | +use WP_SQLite_Translator; |
| 8 | + |
| 9 | +/** |
| 10 | + * Class Tables |
| 11 | + * Handles listing tables in the SQLite database. |
| 12 | + */ |
| 13 | +class Tables extends Base { |
| 14 | + |
| 15 | + protected $translator; |
| 16 | + protected $args = array(); |
| 17 | + protected $is_stdout = false; |
| 18 | + |
| 19 | + public function __construct() { |
| 20 | + $this->load_dependencies(); |
| 21 | + $this->translator = new WP_SQLite_Translator(); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Get the PDO instance. |
| 26 | + * |
| 27 | + * @return PDO |
| 28 | + */ |
| 29 | + protected function get_pdo() { |
| 30 | + return $this->translator->get_pdo(); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Lists all tables in the SQLite database. |
| 35 | + * |
| 36 | + * @param string|null $pattern Optional wildcard pattern to filter tables. |
| 37 | + * @param array $assoc_args Associative array of options. |
| 38 | + * @return void |
| 39 | + */ |
| 40 | + public function run($pattern = null, $assoc_args = []) { |
| 41 | + $pdo = $this->get_pdo(); |
| 42 | + |
| 43 | + // Get all tables |
| 44 | + $stmt = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"); |
| 45 | + $tables = $stmt->fetchAll(PDO::FETCH_COLUMN); |
| 46 | + |
| 47 | + // Filter tables if wildcard pattern is provided |
| 48 | + if ($pattern) { |
| 49 | + $sql_pattern = str_replace('?', '_', $pattern); |
| 50 | + $sql_pattern = str_replace('*', '%', $sql_pattern); |
| 51 | + |
| 52 | + $tables = array_filter($tables, function($table) use ($pattern) { |
| 53 | + return fnmatch($pattern, $table, FNM_CASEFOLD); |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + // Remove system tables |
| 58 | + $tables_to_exclude = array('_mysql_data_types_cache'); |
| 59 | + $tables = array_diff($tables, $tables_to_exclude); |
| 60 | + |
| 61 | + if (empty($tables)) { |
| 62 | + if ($pattern) { |
| 63 | + WP_CLI::error("No tables found matching: " . $pattern); |
| 64 | + } else { |
| 65 | + WP_CLI::error("No tables found in the database."); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + $format = \WP_CLI\Utils\get_flag_value( $assoc_args, 'format' ); |
| 70 | + |
| 71 | + if ( 'csv' === $format ) { |
| 72 | + WP_CLI::line( implode( ',', $tables ) ); |
| 73 | + } else { |
| 74 | + foreach ( $tables as $table ) { |
| 75 | + WP_CLI::line( $table ); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments