Shows the tables in the given MySQL database (if exists)

    CLI Example:

    .. code-block:: bash

        salt '*' mysql.db_tables 'database'
763338
def db_tables(name, **connection_args):
    '''
    
    '''
    if not db_exists(name, **connection_args):
        log.info('Database \'%s\' does not exist', name)
        return False

    dbc = _connect(**connection_args)
    if dbc is None:
        return []
    cur = dbc.cursor()
    s_name = quote_identifier(name)
    # identifiers cannot be used as values
    qry = 'SHOW TABLES IN {0}'.format(s_name)
    try:
        _execute(cur, qry)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return []

    ret = []
    results = cur.fetchall()
    for table in results:
        ret.append(table[0])
    log.debug(ret)
    return ret
813276
def init_from_database(self, conn, database, table_name):
        
        info = conn.query('SHOW TABLE STATUS FROM `{database}` WHERE name="{table_name}"'.format(
            table_name=table_name, database=database), as_dict=True).fetchone()
        if info is None:
            if table_name == '~log':
                logger.warning('Could not create the ~log table')
                return
            else:
                raise DataJointError('The table `{database}`.`{table_name}` is not defined.'.format(
                    table_name=table_name, database=database))
        self.table_info = {k.lower(): v for k, v in info.items()}

        cur = conn.query(
            'SHOW FULL COLUMNS FROM `{table_name}` IN `{database}`'.format(
                table_name=table_name, database=database), as_dict=True)

        attributes = cur.fetchall()

        rename_map = {
            'Field': 'name',
            'Type': 'type',
            'Null': 'nullable',
            'Default': 'default',
            'Key': 'in_key',
            'Comment': 'comment'}

        fields_to_drop = ('Privileges', 'Collation')

        # rename and drop attributes
        attributes = [{rename_map[k] if k in rename_map else k: v
                       for k, v in x.items() if k not in fields_to_drop}
                      for x in attributes]

        numeric_types = {
            ('float', False): np.float64,
            ('float', True): np.float64,
            ('double', False): np.float64,
            ('double', True): np.float64,
            ('tinyint', False): np.int64,
            ('tinyint', True): np.int64,
            ('smallint', False): np.int64,
            ('smallint', True): np.int64,
            ('mediumint', False): np.int64,
            ('mediumint', True): np.int64,
            ('int', False): np.int64,
            ('int', True): np.int64,
            ('bigint', False): np.int64,
            ('bigint', True): np.uint64}

        sql_literals = ['CURRENT_TIMESTAMP']

        # additional attribute properties
        for attr in attributes:
            # process external attributes
            split_comment = attr['comment'].split(':')
            attr['is_external'] = len(split_comment) >= 3 and split_comment[1].startswith('external')
            if attr['is_external']:
                attr['comment'] = ':'.join(split_comment[2:])
                attr['type'] = split_comment[1]

            attr['nullable'] = (attr['nullable'] == 'YES')
            attr['in_key'] = (attr['in_key'] == 'PRI')
            attr['autoincrement'] = bool(re.search(r'auto_increment', attr['Extra'], flags=re.IGNORECASE))
            attr['type'] = re.sub(r'int\(\d+\)', 'int', attr['type'], count=1)   # strip size off integers
            attr['numeric'] = bool(re.match(r'(tiny|small|medium|big)?int|decimal|double|float', attr['type']))
            attr['string'] = bool(re.match(r'(var)?char|enum|date|year|time|timestamp', attr['type']))
            attr['is_blob'] = attr['is_external'] or bool(re.match(r'(tiny|medium|long)?blob', attr['type']))
            attr['database'] = database

            if attr['string'] and attr['default'] is not None and attr['default'] not in sql_literals:
                attr['default'] = '"%s"' % attr['default']

            if attr['nullable']:   # nullable fields always default to null
                attr['default'] = 'null'

            attr['sql_expression'] = None
            if not (attr['numeric'] or attr['string'] or attr['is_blob']):
                raise DataJointError('Unsupported field type {field} in `{database}`.`{table_name}`'.format(
                    field=attr['type'], database=database, table_name=table_name))
            attr.pop('Extra')

            # fill out dtype. All floats and non-nullable integers are turned into specific dtypes
            attr['dtype'] = object
            if attr['numeric']:
                is_integer = bool(re.match(r'(tiny|small|medium|big)?int', attr['type']))
                is_float = bool(re.match(r'(double|float)', attr['type']))
                if is_integer and not attr['nullable'] or is_float:
                    is_unsigned = bool(re.match('\sunsigned', attr['type'], flags=re.IGNORECASE))
                    t = attr['type']
                    t = re.sub(r'\(.*\)', '', t)    # remove parentheses
                    t = re.sub(r' unsigned$', '', t)   # remove unsigned
                    assert (t, is_unsigned) in numeric_types, 'dtype not found for type %s' % t
                    attr['dtype'] = numeric_types[(t, is_unsigned)]
        self.attributes = OrderedDict([(q['name'], Attribute(**q)) for q in attributes])

        # Read and tabulate secondary indexes
        keys = defaultdict(dict)
        for item in conn.query('SHOW KEYS FROM `{db}`.`{tab}`'.format(db=database, tab=table_name), as_dict=True):
            if item['Key_name'] != 'PRIMARY':
                keys[item['Key_name']][item['Seq_in_index']] = dict(
                    column=item['Column_name'],
                    unique=(item['Non_unique'] == 0),
                    nullable=item['Null'].lower() == 'yes')
        self.indexes = {
            tuple(item[k]['column'] for k in sorted(item.keys())):
                dict(unique=item[1]['unique'],
                     nullable=any(v['nullable'] for v in item.values()))
            for item in keys.values()}
451532
public function setupDatabaseTables()
    {
        $logger = $this->getLogger();
        $database = $this->getDatabase();

        $databaseHandle = $database->getDatabaseConnection();
        $tableDefinition = $database->getTableDefinition();

        $tables = array_keys($tableDefinition);
        foreach ($tables as $tableName) {
            $logger->writeln('<info>Table "' . $tableName . '"</info>');

            $statement = $databaseHandle->prepare('SHOW TABLES LIKE :table');
            $statement->bindParam(':table', $tableName, \PDO::PARAM_STR);
            $statement->execute();

            if ($statement->rowCount() == 1) {
                $logger->writeln('<info>=> Exists. Skip it</info>');
                continue;
            }

            // Table does not exists. Try to create it
            $createTableResult = $databaseHandle->query($tableDefinition[$tableName]);

            if ($createTableResult === false) {
                $databaseError = $databaseHandle->errorInfo();
                $message = 'Table "%s" could not be created. %s (%s)';
                $message = sprintf($message, $tableName, $databaseError[2], $databaseError[1]);
                throw new \Exception($message, 1398100879);

            } else {
                $logger->writeln('<info>Not exists. Created</info>');
            }
        }

        return true;
    }
712103
public function showSchemaInSimpleTable()
    {
        //change connection if provide
        if ($this->option('c')) {
            $this->schema->setConnection($this->option('c'));
            $this->schema->switchWrapper();
        }

        if (!count($this->schema->databaseWrapper->getTables())) {
            $this->warn('Database does not contain any table');
            return false;
        }
        $headers = ['Table Name', 'Rows'];
        $body = [];
        foreach ($this->schema->databaseWrapper->getSchema() as $key => $value) {
            $body[] = [ $key,   $value['rowsCount']];
        }
        $this->table($headers, $body);
    }
86627
public function getTables($dbName='') {
        $sql    = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES ';
        $result = $this->query($sql);
        $info   =   array();
        foreach ($result as $key => $val) {
            $info[$key] = current($val);
        }
        return $info;
    }
939407
def show_tables():
    
    _State.connection()
    _State.reflect_metadata()
    metadata = _State.metadata

    response = select('name, sql from sqlite_master where type="table"')

    return {row['name']: row['sql'] for row in response}
169028
def listTables(self, dbName=None):
        
        if dbName is None:
            dbName = self.currentDatabase()
        iter = self._jcatalog.listTables(dbName).toLocalIterator()
        tables = []
        while iter.hasNext():
            jtable = iter.next()
            tables.append(Table(
                name=jtable.name(),
                database=jtable.database(),
                description=jtable.description(),
                tableType=jtable.tableType(),
                isTemporary=jtable.isTemporary()))
        return tables
977770
def tables(self):
        
        select = ("SELECT name FROM sqlite_master",)
        query = self.execute(*select)
        result = query.fetchall()

        # Filter first column from rows.
        return [row[0] for row in result]
1295232
def create_tables(database):
    ''''''
    logging.getLogger(__name__).debug("Creating missing database tables")
    database.connect()
    database.create_tables([User,
                            Group,
                            UserToGroup,
                            GroupToCapability,
                            Capability], safe=True)
254172
final public function showTables()
	{
		$q = $this->query('SHOW TABLES');
		$q->execute();
		return $q->fetchAll(self::FETCH_COLUMN);
	}
84885
def info(self):
        
        t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table')
        all_tables = t['name'].tolist()
        print('\nDatabase path: {} \nSQL path: {}\n'.format(self.dbpath, self.sqlpath))
        print('Database Inventory')
        print('==================')
        for table in ['sources'] + [t for t in all_tables if
                                    t not in ['sources', 'sqlite_sequence']]:
            x = self.query('select count() from {}'.format(table), fmt='array', fetch='one')
            if x is None: continue
            print('{}: {}'.format(table.upper(), x[0]))
721754
public static function database_dump_structure($dump_directory) {
	if (is_dir($dump_directory) == false) {
		$exception = bootstrap::get_library('exception');
		throw new $exception('directory not found');
	}
	
	$mysql = bootstrap::get_library('mysql');
	
	$tables = $mysql::select($mysql::AS_ARRAY, "SHOW TABLES;");
	foreach ($tables as $table) {
		$table_name = current($table);
		
		$drop = "DROP TABLE IF EXISTS `".$table_name."`;";
		$dump = $mysql::select($mysql::AS_ROW, "SHOW CREATE TABLE `%s`;", $table_name);
		
		// structure should be w/o references to data
		$dump = $dump['Create Table'];
		$dump = preg_replace('{ AUTO_INCREMENT=[0-9]+}i', '', $dump);
		
		$full_dump = $drop."\n\n".$dump.";\n";
		file_put_contents($dump_directory.'/'.$table_name.'.sql', $full_dump);
	}
}
1155501
def all_databases(client, exclude=['local']):
	
	return (
		client[db_name]
		for db_name in client.list_database_names()
		if db_name not in exclude
	)
414666
def getDatabases(self):
        
        cur = self._conn.cursor()
        cur.execute("""SHOW DATABASES;""")
        rows = cur.fetchall()
        if rows:
            return [row[0] for row in rows]
        else:
            return []
33039
private static function _get_databases(): ?databases
  {
    if ( self::check() ){
      if ( !self::$databases_obj && ($db = self::_get_db()) ){
        self::$databases_obj = new databases($db);
      }
      return self::$databases_obj;
    }
    return null;
  }
547141
def create_table_sql(cls, db):
        '''
        
        '''
        parts = ['CREATE TABLE IF NOT EXISTS `%s`.`%s` AS `%s`.`%s`' % (db.db_name, cls.table_name(), db.db_name,
                                                                        cls.engine.main_model.table_name())]
        engine_str = cls.engine.create_table_sql(db)
        parts.append(engine_str)
        return ' '.join(parts)
257472
def show_tables(self, format='json'):
        ''''''

        query = 'SHOW TABLES'
        payload = self._payload_builder(query, format) 	

        response = self.execute_query(payload) 

        return response