Generates the properties for the specified table.
@param \yii\db\TableSchema $table the table schema
@return array the generated properties (property => type)
@since 2.0.6
481259
protected function generateProperties($table)
    {
        $properties = [];
        foreach ($table->columns as $column) {
            $columnPhpType = $column->phpType;
            if ($columnPhpType === 'integer') {
                $type = 'int';
            } elseif ($columnPhpType === 'boolean') {
                $type = 'bool';
            } else {
                $type = $columnPhpType;
            }
            $properties[$column->name] = [
                'type' => $type,
                'name' => $column->name,
                'comment' => $column->comment,
            ];
        }

        return $properties;
    }
124391
protected function _getFields(Table $table)
    {
        $fields = explode(',', $this->args[1]);
        foreach ($fields as $field) {
            if (!$table->hasField($field)) {
                $this->abort(sprintf('Table `%s` is missing the field `%s`.', $table->table(), $field));
            }
        }

        return $fields;
    }
83931
public function getColumns($table)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');
        
        $query = $this->utility()->showColumns($table);
        $results = $this->query($query, $this->getBinds());
        
        $columns = array();
        foreach ($results as $column) {
            $key = null;
            if ($column['pk'] == 1) {
                $key = 'PRI';
            }
            
            $columns[] = array(
                'Field'     => $column['name'],
                'Type'      => $column['type'],
                'Default'   => $column['dflt_value'],
                'Null'      => $column['notnull'] != 1,
                'Key'       => $key);
        }
        
        return $columns;
    }
910922
public function getCreateTableSql($table)
    {
        $table = $this->buildRealTableName($table);
        return $this->getSchema()->getCreateTableSql($table);
    }
1325695
public function getDefaultValuesFields(Table $table)
    {
        return $table->getFields()->filter(function (Field $field) {
            return $field->getDefault() !== null;
        });
    }
1268356
public function showCreateTable(string $table):array{

		/** @noinspection SqlResolve */
		$def = $this->db->prepared('
			SELECT 
				RF.RDB$FIELD_POSITION AS "id", 
				TRIM(RF.RDB$FIELD_NAME) AS "name",
				(CASE F.RDB$FIELD_TYPE
					WHEN 7 THEN
						CASE F.RDB$FIELD_SUB_TYPE
							WHEN 0 THEN \'SMALLINT\'
							WHEN 1 THEN \'NUMERIC(\' || F.RDB$FIELD_PRECISION || \',\' || (-F.RDB$FIELD_SCALE) || \')\'
							WHEN 2 THEN \'DECIMAL(\' || F.RDB$FIELD_PRECISION || \',\' || (-F.RDB$FIELD_SCALE) || \')\'
						END
					WHEN 8 THEN
						CASE F.RDB$FIELD_SUB_TYPE
							WHEN 0 THEN \'INTEGER\'
							WHEN 1 THEN \'NUMERIC(\'  || F.RDB$FIELD_PRECISION || \',\' || (-F.RDB$FIELD_SCALE) || \')\'
							WHEN 2 THEN \'DECIMAL(\'  || F.RDB$FIELD_PRECISION || \',\' || (-F.RDB$FIELD_SCALE) || \')\'
						END
					WHEN 9 THEN \'QUAD\'
					WHEN 10 THEN \'FLOAT\'
					WHEN 12 THEN \'DATE\'
					WHEN 13 THEN \'TIME\'
					WHEN 14 THEN \'CHAR(\' || (TRUNC(F.RDB$FIELD_LENGTH / CH.RDB$BYTES_PER_CHARACTER)) || \') \'
					WHEN 16 THEN
						CASE F.RDB$FIELD_SUB_TYPE
							WHEN 0 THEN \'BIGINT\'
							WHEN 1 THEN \'NUMERIC(\' || F.RDB$FIELD_PRECISION || \', \' || (-F.RDB$FIELD_SCALE) || \')\'
							WHEN 2 THEN \'DECIMAL(\' || F.RDB$FIELD_PRECISION || \', \' || (-F.RDB$FIELD_SCALE) || \')\'
						END
					WHEN 27 THEN \'DOUBLE\'
					WHEN 35 THEN \'TIMESTAMP\'
					WHEN 37 THEN \'VARCHAR(\' || (TRUNC(F.RDB$FIELD_LENGTH / CH.RDB$BYTES_PER_CHARACTER)) || \')\'
					WHEN 40 THEN \'CSTRING\' || (TRUNC(F.RDB$FIELD_LENGTH / CH.RDB$BYTES_PER_CHARACTER)) || \')\'
					WHEN 45 THEN \'BLOB_ID\'
					WHEN 261 THEN \'BLOB SUB_TYPE \' || F.RDB$FIELD_SUB_TYPE
					ELSE \'RDB$FIELD_TYPE: \' || F.RDB$FIELD_TYPE || \'?\'
				END) AS "type",
				IIF(COALESCE(RF.RDB$NULL_FLAG, 0) = 0, NULL, \'NOT NULL\') AS "isnull",
				COALESCE(RF.RDB$DEFAULT_SOURCE, F.RDB$DEFAULT_SOURCE) AS "default",
				TRIM(CH.RDB$CHARACTER_SET_NAME) AS "charset",
				TRIM(DCO.RDB$COLLATION_NAME) AS "collation",
				TRIM(F.RDB$VALIDATION_SOURCE) AS "check",
				TRIM(RF.RDB$DESCRIPTION) AS "desc"
			FROM RDB$RELATION_FIELDS RF
				JOIN RDB$FIELDS F ON (F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
				LEFT OUTER JOIN RDB$CHARACTER_SETS CH ON (CH.RDB$CHARACTER_SET_ID = F.RDB$CHARACTER_SET_ID)
				LEFT OUTER JOIN RDB$COLLATIONS DCO ON ((DCO.RDB$COLLATION_ID = F.RDB$COLLATION_ID) AND (DCO.RDB$CHARACTER_SET_ID = F.RDB$CHARACTER_SET_ID))
			WHERE (RF.RDB$RELATION_NAME = ?) AND (COALESCE(RF.RDB$SYSTEM_FLAG, 0) = 0)
			ORDER BY RF.RDB$FIELD_POSITION
			', [$table]);

		/** @noinspection SqlResolve */
		$idx = $this->db->prepared('SELECT S.RDB$FIELD_POSITION AS "pos", S.RDB$FIELD_NAME AS "field", I.RDB$INDEX_ID AS "id", I.RDB$UNIQUE_FLAG AS "unique" FROM RDB$INDEX_SEGMENTS AS S, RDB$INDICES AS I WHERE S.RDB$INDEX_NAME = I.RDB$INDEX_NAME AND I.RDB$RELATION_NAME = ?', [$table]);

		$fields = [];
		if($def instanceof ResultInterface && $def->length > 0){

			foreach($def as $field){
				$index = $idx[$field->id]['id'] ?? false;

				if($index){
					$index = $index === 1 ? 'PRIMARY KEY' : 'UNIQUE'; // @todo
				}

				$fields[] = $this->fieldspec(trim($field->name), trim($field->type), null, null, null, $field->isnull !== 'NOT NULL', null, null, trim($field->default.$index));
			}

		}

		$this->db->prepared('RECREATE GLOBAL TEMPORARY TABLE TEMP$SQL_CREATE ("name" BLOB SUB_TYPE TEXT CHARACTER SET UTF8 NOT NULL, "create" BLOB SUB_TYPE TEXT CHARACTER SET UTF8 NOT NULL) ON COMMIT PRESERVE ROWS');

		$create = sprintf(/** @lang text */'CREATE TABLE %1$s (%2$s)', $this->quote($table), PHP_EOL.implode(','.PHP_EOL, $fields).PHP_EOL);

		/** @noinspection SqlResolve */
		$this->db->prepared('INSERT INTO TEMP$SQL_CREATE ("name", "create") VALUES (?, ?)', [$table, $create]);

		/** @noinspection SqlResolve */
		return ['SELECT "name" AS "Table", "create" AS "Create Table" FROM TEMP$SQL_CREATE'];
	}
282913
public function select($table)
	{
		$props = call_user_func(array($this->model_to, 'properties'));
		$i = 0;
		$properties = array();
		foreach ($props as $pk => $pv)
		{
			$properties[] = array($table.'.'.$pk, $table.'_c'.$i);
			$i++;
		}

		return $properties;
	}
739593
public function generateBehaviors($table)
    {
        $available = [
            [
                'name' => 'blameable',
                'attributes' => ['author_id', 'created_by', 'created_id'],
                'class' => \netis\crud\db\BlameableBehavior::className(),
                'optionName' => 'createdByAttribute',
            ],
            [
                'name' => 'blameable',
                'attributes' => ['editor_id', 'edited_by', 'updated_by', 'updated_id', 'last_editor_id'],
                'class' => \netis\crud\db\BlameableBehavior::className(),
                'optionName' => 'updatedByAttribute',
            ],
            [
                'name' => 'blameable',
                'attributes' => ['update_reason'],
                'class' => \netis\crud\db\BlameableBehavior::className(),
                'optionName' => 'updateNotesAttribute',
            ],
            [
                'name' => 'timestamp',
                'attributes' => ['created_on', 'created_at', 'create_at', 'created_date', 'date_created'],
                'class' => \netis\crud\db\TimestampBehavior::className(),
                'optionName' => 'createdAtAttribute',
            ],
            [
                'name' => 'timestamp',
                'attributes' => ['updated_on', 'updated_at', 'update_at', 'updated_date', 'date_updated'],
                'class' => \netis\crud\db\TimestampBehavior::className(),
                'optionName' => 'updatedAtAttribute',
            ],
            [
                'name' => 'toggable',
                'attributes' => [
                    'is_disabled', 'disabled', 'is_deleted', 'deleted', 'is_removed', 'removed', 'is_hidden', 'hidden',
                ],
                'class' => \netis\crud\db\ToggableBehavior::className(),
                'optionName' => 'disabledAttribute',
            ],
            [
                'name' => 'toggable',
                'attributes' => ['is_enabled', 'enabled', 'is_active', 'active', 'is_visible', 'visible'],
                'class' => \netis\crud\db\ToggableBehavior::className(),
                'optionName' => 'enabledAttribute',
            ],
            [
                'name' => 'sortable',
                'attributes' => ['display_order', 'sort_order'],
                'class' => \netis\crud\db\SortableBehavior::className(),
                'optionName' => 'attribute',
            ],
            [
                'name' => 'versioned',
                'attributes' => ['version'],
                // invalid behavior: doesn't have a class or optionName,
                // has to be turned into a method in the model template
            ],
        ];
        $behaviors = [
            'labels' => [
                'class' => \netis\crud\db\LabelsBehavior::className(),
                'options' => [
                    'attributes' => [$this->getLabelAttribute($table)],
                ],
            ],
        ];
        foreach ($table->columns as $column) {
            foreach ($available as $options) {
                if (in_array($column->name, $options['attributes'])) {
                    if (isset($options['class'])) {
                        $behaviors[$options['name']]['class']                           = $options['class'];
                        $behaviors[$options['name']]['options'][$options['optionName']] = $column->name;
                    } else {
                        $behaviors[$options['name']] = $column->name;
                    }
                    break;
                }
            }
        }
        return $behaviors;
    }
750403
public function get_fields(string $table = ''): ?array
  {
    if ( !empty($this->class_cfg) ){
      if ( $table ){
        return $this->class_cfg['arch'][$table] ?? null;
      }
      return $this->class_cfg['arch'];
    }
    return null;
  }
1168211
function generateTableSchema( $tableName, $table, $params )
    {
        return $this->generateTableSQL( $tableName, $table, $params, false, false );
    }
982406
public function createTable($table, $schema)
    {
        //
        $columnsArray = [];

        // loop throut schema
        foreach ($schema as $field => $attributes) {
            if (is_numeric($field) && is_string($attributes)) {
                $field = $attributes;
                $attributes = [];
            }

            //
            $column = $this->columnDefinition($attributes, false);

            //
            $columnsArray[] = "`{$field}` {$column}";
        }

        // implode
        $columns = implode(',', $columnsArray);

        // template sql to create table
        $sql = "CREATE TABLE `{$table}` ({$columns})";

        // return the sql
        return $sql;
    }
63298
public function generateUniqueRules($table)
    {
        $rules = [];
        $uniqueIndexes = $this->getDbConnection()->getSchema()->findUniqueIndexes($table);
        foreach ($uniqueIndexes as $uniqueColumns) {
            // Avoid validating auto incremental columns
            if ($this->isColumnAutoIncremental($table, $uniqueColumns)) {
                continue;
            }
            $attributesCount = count($uniqueColumns);

            if ($attributesCount == 1) {
                $rules[] = "[['" . $uniqueColumns[0] . "'], 'unique'],";
            } elseif ($attributesCount > 1) {
                $labels = array_intersect_key($this->generateLabels($table), array_flip($uniqueColumns));
                $lastLabel = array_pop($labels);
                $labels = implode(', ', $labels);
                $columnsList = implode("', '", $uniqueColumns);
                $rules[] = "[
                ['" . $columnsList . "'], 'unique', 'targetAttribute' => ['" . $columnsList . "'],
                'message' => Yii::t('app', 'The combination of {labels} and {lastLabel} has already been taken.', [
                    'labels' => '{$labels}',
                    'lastLabel' => '{$lastLabel}',
                ]),
            ],";
            }
        }

        return $rules;
    }
96627
public function actionCreate(string $table): int
    {
        $tables = [$table];
        if (strpos($table, ',') !== false) {
            $tables = explode(',', $table);
        }

        $migrationsGenerated = 0;
        foreach ($tables as $name) {
            $this->stdout(" > Generating create migration for table '{$name}' ...", Console::FG_YELLOW);

            $className = 'm' . gmdate('ymd_His') . '_create_table_' . $name;
            $file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');

            $generator = new Generator([
                'db' => $this->db,
                'view' => $this->view,
                'useTablePrefix' => $this->useTablePrefix,
                'templateFile' => $this->templateFile,
                'tableName' => $name,
                'className' => $className,
                'namespace' => $this->migrationNamespace,
                'generalSchema' => $this->generalSchema,
                'tableOptionsInit' => $this->tableOptionsInit,
                'tableOptions' => $this->tableOptions,
            ]);

            if ($generator->tableSchema === null) {
                $this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);

                return ExitCode::DATAERR;
            }

            if ($this->generateFile($file, $generator->generateMigration()) === false) {
                $this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);

                return ExitCode::SOFTWARE;
            }

            $migrationsGenerated++;

            $this->stdout("DONE!\n", Console::FG_GREEN);
            $this->stdout(" > Saved as '{$file}'\n");

            if ($this->fixHistory) {
                if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
                    $this->createMigrationHistoryTable();
                }

                $this->addMigrationHistory($className, $this->migrationNamespace);
            }

            $this->stdout("\n");
        }

        if ($migrationsGenerated) {
            $this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
            $this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
        } else {
            $this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
        }

        return ExitCode::OK;
    }
1135556
final public function columns($table=null) {
      $this->connection();
      $schema = $this->schema ? "{$this->schema}." : '';
      $table  = $table ?: $this->table;
      $table  = explode('.',$table);
      $table  = $table[count($table)-1];



      if($this->driver=='dblib')//FreeTDS
         $sql = "";
      if($this->driver=='4d')
         $sql = "";
      if($this->driver=='pgsql') {
         $schema = $this->schema?  "AND table_schema = '{$this->schema}'":'';
         $sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '{$table}' {$schema};";
      }
      if($this->driver=='sybase')
         $sql = "SELECT sc.name AS column_name FROM syscolumns sc INNER JOIN sysobjects so ON sc.id = so.id WHERE so.name = '{$table}'";
      if($this->driver=='firebird')
         $sql = "SELECT RDB$FIELD_NAME AS column_name FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME='{$table}';";
      if($this->driver=='sqlite')
         $sql = "PRAGMA {$schema}table_info({$table});";
      if($this->driver=='mssql'||$this->driver=='sqlsrv')
         $sql = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{$table}'";
      if($this->driver=='informix')
         $sql = "SELECT colname AS column_name FROM systables AS a JOIN syscolumns AS b ON a.tabid=b.tabid WHERE tabname='{$table}';";
      if($this->driver=='ibm')
         $sql = "DESCRIBE TABLE {$table}";
      if($this->driver=='mysql' || $this->driver=='oci' || $this->driver=='odbc' || $this->driver=='cubrid')
         $sql = "DESCRIBE {$schema}{$table}";

      if($this->driver=='dblib')//FreeTDS
         $field = '';
      if($this->driver=='4d')
         $field = '';
      if($this->driver=='mysql')
         $field = 'Field';
      if($this->driver=='cubrid')
         $field = 'tables_in_demodb';
      if($this->driver=='sqlite')
         $field = 'name';
      if($this->driver=='mssql'||$this->driver=='sqlsrv'||$this->driver=='informix'||$this->driver=='ibm'||$this->driver=='firebird'||$this->driver=='sybase'||$this->driver=='pgsql'||$this->driver=='oci'||$this->driver=='odbc'||$this->driver=='mssql')
         $field = 'column_name';

      try {
         $stmt = $this->id_conn->prepare($sql);
         $stmt->execute();
         $stmt->setFetchMode(constant('\PDO::FETCH_ASSOC'));

         $this->columnsData = [];
         while ($row = $stmt->fetch()) {
            $this->columnsData[] = $row[$field];
         }
      } catch (\PDOException $e) {
         die("Error: " . $e->getMessage() . "<br/>");
      }

      return $this->columnsData;
   }
1044039
protected function buildHeaders(Table $table)
	{
		//Generate each row
		$rows = array();

		foreach ( $table->getHeaderRows() as $row )
		{
			//Build the cells for each row
			$cells = array();

			foreach ( $row as $cell )
			{
				$cells[] = $this->headerCell($cell);
			}

			$rows[] = $this->headerRow($row, $cells);
		}

		return $rows;
	}
244884
public function getTableColumns(string $table): array
    {
        $schemaTable = self::SCHEMA_COLUMN;

        $where[] = "TABLE_NAME = '{$table}'";
        $where[] = "TABLE_SCHEMA = '{$this->db}'";
        $where   = !empty($where) ? ' WHERE ' . implode(' AND ', $where) : null;

        $querySql = "SELECT `COLUMN_NAME` as `name`,`DATA_TYPE` as `type`,`CHARACTER_MAXIMUM_LENGTH` as `length`,`COLUMN_DEFAULT` as `default` ,`COLUMN_KEY` as `key`,`IS_NULLABLE` as `nullable`,`COLUMN_TYPE` as `column_type`,`COLUMN_COMMENT` as `column_comment` FROM {$schemaTable} {$where}";
        $this->dbHandler->prepare($querySql);
        $this->dbHandler->execute([]);
        $columns = $this->dbHandler->fetch();

        return !empty($columns) ? $columns : [];
    }
376876
protected function parseSchemaAndTable($table)
    {
        $table = explode('.', $table);

        if (is_array($schema = $this->connection->getConfig('schema'))) {
            if (in_array($table[0], $schema)) {
                return [array_shift($table), implode('.', $table)];
            }

            $schema = head($schema);
        }

        return [$schema ?: 'public', implode('.', $table)];
    }