获取表字段

@param string $table 表名
@param mixed $tablePrefix 表前缀，不传则获取配置中配置的前缀
@param int $filter 0 获取表字段详细信息数组 1获取字段以,号相隔组成的字符串

@return mixed
540649
public function getDbFields($table, $tablePrefix = null, $filter = 0)
    {
        static $dbFieldCache = [];

        is_null($tablePrefix) && $tablePrefix = $this->tablePrefix;
        if ($filter == 1 && Cml::$debug) return '*'; //debug模式时直接返回*
        $table = strtolower($tablePrefix . $table);

        $info = false;

        if (isset($dbFieldCache[$table])) {
            $info = $dbFieldCache[$table];
        } else {
            Config::get('db_fields_cache') && $info = \Cml\simpleFileCache($this->conf['master']['dbname'] . '.' . $table);
            if (!$info || Cml::$debug) {
                $this->currentQueryIsMaster = false;
                $stmt = $this->prepare("SHOW COLUMNS FROM $table", $this->rlink, false);
                $this->execute($stmt, false);
                $info = [];
                while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                    $info[$row['Field']] = [
                        'name' => $row['Field'],
                        'type' => $row['Type'],
                        'notnull' => (bool)($row['Null'] === ''), // not null is empty, null is yes
                        'default' => $row['Default'],
                        'primary' => (strtolower($row['Key']) == 'pri'),
                        'autoinc' => (strtolower($row['Extra']) == 'auto_increment'),
                    ];
                }

                count($info) > 0 && \Cml\simpleFileCache($this->conf['master']['dbname'] . '.' . $table, $info);
            }
            $dbFieldCache[$table] = $info;
        }

        if ($filter) {
            if (count($info) > 0) {
                $info = implode('`,`', array_keys($info));
                $info = '`' . $info . '`';
            } else {
                return '*';
            }
        }
        return $info;
    }
453487
public static function stripPrefix($table, $prefix = null)
    {
        $prefix = $prefix ?: Ioc::getDatabase()->getPrefix();

        $num = strlen($prefix);

        if (substr($table, 0, $num) == $prefix) {
            $table = '#__' . substr($table, $num);
        }

        return $table;
    }
61614
public function deleteRows($table, $filters = null)
    {
        Argument::i()
            //Argument 1 must be a string
            ->test(1, 'string')
            //Argument 2 must be a string or array
            ->test(2, 'array', 'string');
        
        $query = $this->delete($table);
        
        //array('post_id=%s AND post_title IN %s', 123, array('asd'));
        if (is_array($filters)) {
            //can be array of arrays
            if (is_array($filters[0])) {
                foreach ($filters as $i => $filter) {
                    if (is_array($filters)) {
                        $format = array_shift($filter);
                        
                        //reindex filters
                        $filter = array_values($filter);
                        
                        //bind filters
                        foreach ($filter as $i => $value) {
                            $filter[$i] = $this->bind($value);
                        }
                        
                        //combine
                        $query->where(vsprintf($format, $filter));
                    }
                }
            } else {
                $format = array_shift($filters);
                
                //reindex filters
                $filters = array_values($filters);
                
                //bind filters
                foreach ($filters as $i => $value) {
                    $filters[$i] = $this->bind($value);
                }
                
                //combine
                $query->where(vsprintf($format, $filters));
            }
        } else {
            $query->where($filters);
        }
        
        //run the query
        $this->query($query, $this->getBinds());
        
        //trigger event
        $this->trigger('sql-delete', $table, $filters);
        
        return $this;
    }
837112
public function PrefixTable($Table) {
      $Prefix = $this->Database->DatabasePrefix;
      
      if ($Prefix != '' && substr($Table, 0, strlen($Prefix)) != $Prefix)
         $Table = $Prefix.$Table;

      return $Table;
   }
1185691
public static function fieldsKey($table, $filter="id") {

        try {
            $row = (array) self::findRow("select * from ".$table, "assoc");
            // remove array element base on filter if _none_ no filter
            if (strtolower($filter)!="_none_") {
                // default is to filter id field
                unset($row[$filter]);
            }
            return array_keys($row);
        } catch (Exception $e) {
            echo $e->getTraceAsString();
        }        
    }
422424
public void filterTable(String filter) {

        m_container.removeAllContainerFilters();
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(filter)) {
            m_container.addContainerFilter(
                new Or(
                    new SimpleStringFilter(PROP_NAME, filter, true, false),
                    new SimpleStringFilter(PROP_DESCRIPTION, filter, true, false)));
        }
        if ((getValue() != null) & !((Set<CmsUUID>)getValue()).isEmpty()) {
            setCurrentPageFirstItemId(((Set<CmsUUID>)getValue()).iterator().next());
        }
    }
1355326
private function parseFilters(TableInterface $table, Request $request)
    {
        $filters = [];

        $queryParams = $request->get($table->getFormId());

        foreach ($table->getAllFilters() as $filter) {
            if (isset($queryParams[$filter->getName()])) {
                $searchParamRaw = trim($queryParams[$filter->getName()]);
                if ($searchParamRaw != '') {
                    $filters[$filter->getName()] = $searchParamRaw;
                }
            }
        }

        return $filters;
    }
1113449
public function getPrimary(string $prefix, string $table): ?string
    {
        $name = $prefix . $table;
        if (array_key_exists($name, $this->primaryKeys)) {
            return $this->primaryKeys[$name];
        }

        if (!$this->hasTable($name)) {
            throw new DriverException(
                "Unable to fetch table primary key, no such table '{$name}' exists"
            );
        }

        $this->primaryKeys[$name] = $this->getSchema($table, $prefix)->getPrimaryKeys();
        if (count($this->primaryKeys[$name]) === 1) {
            //We do support only single primary key
            $this->primaryKeys[$name] = $this->primaryKeys[$name][0];
        } else {
            $this->primaryKeys[$name] = null;
        }

        return $this->primaryKeys[$name];
    }
249935
public function count($filter = null)
    {
        try {
            return $this->select('COUNT(*)', $filter)->fetchColumn();
        } catch (\PDOException $e) {
            throw new StorageException($e->getMessage());
        }
    }
635449
public static function getInstanceAndRunMapDbAndTable($table = null, $tablePrefix = null)
    {
        return self::getInstance($table, $tablePrefix)->mapDbAndTable();
    }
486615
public function getFilter($column, $filter = null)
    {
        if (null === $filter) {
            return $this->filters[$column] ?? null;
        }
        return $this->filters[$column][$filter] ?? null;
    }
901652
public function getPrefix($table = null)
    {
        $prefix = $this->_socket->getPrefix();

        return $table ? $prefix.$table : $prefix;
    }
805835
public function tablePrefix($action = null, $prefix = null) {
		$db = $this->_getConnection();
		$config = $db->config();
		$database = $config['database'];
		if (!empty($this->params['database'])) {
			$database = $this->params['database'];
		}

		while (!$action || !in_array($action, ['A', 'R'], true)) {
			$action = $this->in('Add or remove?', ['A', 'R']);
		}

		while (!$prefix) {
			$prefix = $this->in('Please select prefix:');
		}

		$space = "\n";
		if ($action === 'R') {
			$length = mb_strlen($prefix) + 1;
			$script = <<<SQL
SELECT  CONCAT('RENAME TABLE `$database`.`', table_name, '` TO `$database`.`', SUBSTR(table_name, $length), '`;$space') AS statement
FROM    information_schema.tables AS tb
WHERE   table_schema = '$database'
AND     table_name LIKE '$prefix%'
AND     `TABLE_TYPE` = 'BASE TABLE';
SQL;
		} else {
			$script = <<<SQL
SELECT  CONCAT('RENAME TABLE `$database`.`', table_name, '` TO `$database`.`$prefix', table_name, '`;$space') AS statement
FROM    information_schema.tables AS tb
WHERE   table_schema = '$database'
AND     table_name NOT LIKE '$prefix%'
AND     `TABLE_TYPE` = 'BASE TABLE';
SQL;
		}

		/** @var \Cake\Database\Statement\StatementDecorator $res */
		$res = $db->query($script);
		if (!$res->count()) {
			$this->abort('Nothing to do...');
		}

		$script = '';
		foreach ($res as $r) {
			$script .= $r['statement'];
			$this->out($r['statement'], 1, Shell::VERBOSE);
		}

		if (!$this->param('dry-run')) {
			$continue = $this->in($res->count() . ' tables will be altered.', ['Y', 'N'], 'N');
			if (strtoupper($continue) !== 'Y') {
				$this->abort('Aborted!');
			}
		}

		if (!$this->params['dry-run']) {
			$db->query($script);
		} else {
			$this->out($script);
		}
		$this->out('Done :)');
	}
1005646
public function getQueryFields($usePrefix = false, $prefix = '')
    {
        $fields = $this->fields;

        if ($usePrefix) {
            $prefix = (empty($prefix) ? $this->getTable() : $prefix);
            $fields = array();
            foreach ($this->fields as $field) {
                $fields[] = $prefix . '.' . $field;
            }
        }

        return implode(', ', $fields);
    }
1064098
public function getTable($withPrefix = true)
    {
        if (is_null($this->table)) {
            $classBasename = (new \ReflectionClass($this))->getShortName();
            $this->setTable(strtolower($classBasename));
        }

        if ($withPrefix) {
            return $this->getPrefix() . $this->table;
        }

        return $this->table;
    }
503561
public function erase($filter = null) {
		$filter = $this->queryParser->prepareFilter($filter, $this->dbsType, $this->db);
		if (!$filter) {
			if ($this->emit('beforeerase')===false)
				return false;
			if ($this->fieldConf) {
				// clear all m:m references
				foreach($this->fieldConf as $key => $conf)
					if (isset($conf['has-many']) &&
						$conf['has-many']['hasRel']=='has-many') {
						$rel = $this->getRelInstance(null, array(
							'db'=>$this->db,
							'table'=>$this->mmTable($conf['has-many'],$key)));
						$id = $this->get($conf['has-many']['relPK'],true);
						$rel->erase(array($conf['has-many']['relField'].' = ?', $id));
					}
			}
			$this->mapper->erase();
			$this->emit('aftererase');
		} elseif($filter)
			$this->mapper->erase($filter);
		return true;
	}
463898
public function getTableRows(
        $tableSpecId,
        array $filter = [],
        array $sortBy = [],
        $offset = 0,
        $limit = 10,
        array $options = []
    ) {
        $t = new \Tripod\Timer();
        $t->start();

        $options = array_merge(
            [
                'returnCursor' => false,
                'includeCount' => true,
                'documentType' => '\Tripod\Mongo\Documents\Tables'
            ],
            $options
        );

        $filter['_id.' . _ID_TYPE] = $tableSpecId;

        $collection = $this->getConfigInstance()->getCollectionForTable(
            $this->storeName,
            $tableSpecId,
            $this->readPreference
        );

        $findOptions = [];
        if (!empty($limit)) {
            $findOptions['skip'] = (int) $offset;
            $findOptions['limit'] = (int) $limit;
        }
        if (isset($sortBy)) {
            $findOptions['sort'] = $sortBy;
        }

        $results = $collection->find($filter, $findOptions);

        if ($options['includeCount']) {
            $count = $collection->count($filter);
        } else {
            $count = -1;
        }


        $results->setTypeMap(['root' => $options['documentType'], 'document' => 'array', 'array' => 'array']);

        $t->stop();
        $this->timingLog(
            MONGO_TABLE_ROWS,
            ['duration' => $t->result(), 'query' => $filter, 'collection' => TABLE_ROWS_COLLECTION]
        );
        $this->getStat()->timer(MONGO_TABLE_ROWS . ".$tableSpecId", $t->result());

        return [
            'head' => [
                'count' => $count,
                'offset' => $offset,
                'limit' => $limit
            ],
            'results' => $options['returnCursor'] ? $results : $results->toArray()
        ];
    }