Sets up an tables and sequences for a Schema
@chainable
325391
public function initialize($schema, $table=null)
    {
        $mapper = $this->_mapper($schema);
        $table = $table ? $this->_connection($schema)->table($table) : $mapper->table();

        $sequencePool = $this->_connection($schema)->sequencePool();
        $sequencePool->initialize();

        $columns = array();

        // build a map of properties to create
        foreach ($schema->properties() as $prop) {
            $columns[$prop->name] = $prop->type;

            // reset sequences as we go
            if (property_exists($prop->type, 'sequence')) {
                $sequencePool->delete($mapper->sequenceName($prop));
            }
        }

        $table->create($columns);

        return $this;
    }
240493
public function create($schema, $ifNotExists = true, $options = [])
    {
        $defaultOptions = [
            'auto_increment' => 1,
            'engine' => 'InnoDB',
            'charset' => 'utf8mb4',
            'collate' => 'utf8mb4_unicode_ci'
        ];

        $options = array_merge($defaultOptions, $options);
        $schema = $this->callSchema($schema);
        $columns = [];
        $primary = [];

        foreach ($schema->getColumns() as $column) {
            $column = $this->prepareColumn($column);

            $columns[$column->getName()] = MysqlGrammar::build(
                $column->getType() . $column->getLength(),
                $column->getSigned() ? '' : 'UNSIGNED',
                $column->getAllowNull() ? '' : 'NOT NULL',
                $column->getDefault() !== false
                    ? 'DEFAULT ' . $this->db->getQuery(true)->validValue($column->getDefault())
                    : '',
                $column->getAutoIncrement() ? 'AUTO_INCREMENT' : '',
                $column->getComment() ? 'COMMENT ' . $this->db->quote($column->getComment()) : '',
                $column->getSuffix()
            );

            // Primary
            if ($column->isPrimary()) {
                $primary[] = $column->getName();
            }
        }

        $keys = [];

        foreach ($schema->getIndexes() as $index) {
            $name = $index->getName();
            $keys[$name] = [
                'type' => $index->getType(),
                'name' => $name,
                'columns' => $index->getColumns(),
                'comment' => $index->getComment() ? 'COMMENT ' . $this->db->quote($index->getComment()) : '',
            ];
        }

        $query = MysqlGrammar::createTable(
            $this->getName(),
            $columns,
            $primary,
            $keys,
            $options['auto_increment'],
            $ifNotExists,
            $options['engine'],
            $options['charset'],
            $options['collate']
        );

        $this->db->setQuery($query)->execute();

        return $this->reset();
    }
1192529
function SqliteSchemaSyncer( db, schema ) {
    this.db = db;
    this.schema = {};
    this.toSync = {};
    this.analyzed = {};
    if ( schema ) {
        this.toSync = schema;
        if ( this.toSync ) {
            for ( var k in this.toSync ) {
                if (this.toSync.hasOwnProperty(k) ) {
                    var value = this.toSync[k];
                    delete this.toSync[k];
                    this.toSync[k.toLowerCase()] = value;
                }
            }
        }
    }
}
528907
def build_sequence(item, context)
      sequence = item.middleware.middleware_dependencies.map do |child_item|
        build_sequence(child_item.set_parent(item), context)
      end

      dedup_sequence([*sequence, item].flatten)
    end
350774
function () {
            if (!this.__schemaDataset) {
                var ds = this.db.from(this.table), self = this;
                return this.__createTable().chain(function () {
                    return (self.__schemaDataset = ds);
                });
            } else {
                return when(this.__schemaDataset);
            }
        }
403315
def schema():
    
    tables = orca.list_tables()
    cols = {t: orca.get_table(t).columns for t in tables}
    steps = orca.list_steps()
    injectables = orca.list_injectables()
    broadcasts = orca.list_broadcasts()

    return jsonify(
        tables=tables, columns=cols, steps=steps, injectables=injectables,
        broadcasts=broadcasts)
65629
public function setTables($tables) {
		foreach($tables as $key=>$value) {
			if (is_numeric($key)) {
				$this->tables[] = $value;
			}
			else {
				$this->tables[] = $key;
				$this->columns[$key] = $value;
			}
		}
		$this->cacheTables = true;
	}
628529
def _set_table(table_name):
    
    _State.connection()
    _State.reflect_metadata()
    _State.table = sqlalchemy.Table(table_name, _State.metadata,
                                    extend_existing=True)

    if list(_State.table.columns.keys()) == []:
        _State.table_pending = True
    else:
        _State.table_pending = False
1212272
function  toTableArrays(sbiTable)  {
	var  tbName = sbiTable.name,
		 tables = [];
	addTable( tbName, tables );

	if (sbiTable.join)  {
		var  joinTables = sbiTable.join;
		for (var i in joinTables)
			addTable( joinTables[i].table, tables );
	}

	return  tables;
}
588679
function (values, schema, options, callback) {
    var newValues = {}
        , errors = []
        , modelList = find(schema)
        , val;

    for (var model in modelList) {
        if (_.isArray(modelList[model])) {

            if (values === undefined) {
                val = undefined;
            }
            else {
                val = values[model];
            }

            // Empty array defined in schema
            if (_.isEmpty(modelList[model])) {
                if (val) {
                    newValues[model] = val;
                }
            }
            else {
                // Set value to empty array if empty given
                if (val == undefined) {
                    if (options && options.partial == true) {
                        // Do nothing
                    }
                    else {
                        newValues[model] = [];
                    }
                }
                else {
                    // Sub model defined in schema
                    for (var thisSubSchema in modelList[model]) {
                        if (_.isArray(val)) {
                            for (var thisValue in val) {

                                // Check if type array or plain array
                                if (typeof val[thisValue] == "object") {
                                    modelCompare(val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors = _.union(errors, err);
                                        }
                                        if (data !== null) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                                else {
                                    rulesMatch(thisValue, val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors.push(err);
                                        }
                                        if (data !== undefined) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            modelCompare(val, modelList[model][thisSubSchema], options, function (err, data) {
                                if (err) {
                                    errors = _.union(errors, err);
                                }
                                if (data !== null) {
                                    newValues[model] = data;
                                }
                            });
                        }
                    }
                }
            }
        } else {
            // Check for definition of {} in model to allow any data for this node without validation
            if (_.isEmpty(modelList[model])) {
                for (var index in values) {
                    var filter = new RegExp("^" + model);
                    if (index.match(filter)) {
                        newValues[index] = values[index];
                    }
                }
            }
            else {
                if (values === undefined) {
                    val = undefined;
                }
                else {
                    val = values[model];
                }

                rulesMatch(model, val, modelList[model], options, function (err, data) {
                    if (err) {
                        errors.push(err);
                    }
                    if (data !== undefined) {
                        newValues[model] = data;
                    }
                });
            }
        }
    }

    if (_.isEmpty(errors)) {
        errors = null;
    }
    else {
        errors = {name: 'ValidationError', err: errors};
    }
    if (_.isEmpty(newValues)) {
        newValues = null;
    }
    callback(errors, newValues);
}
1220245
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'):
    '''
    
    '''

    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    chain_check = __salt__['nftables.check_chain'](table, name, family=family)
    if chain_check['result'] is True:
        ret['result'] = True
        ret['comment'] = ('nftables {0} chain is already exist in {1} table for {2}'
                          .format(name, table, family))
        return ret

    res = __salt__['nftables.new_chain'](
            table,
            name,
            table_type=table_type,
            hook=hook,
            priority=priority,
            family=family
    )

    if res['result'] is True:
        ret['changes'] = {'locale': name}
        ret['result'] = True
        ret['comment'] = ('nftables {0} chain in {1} table create success for {2}'
                          .format(name, table, family))
        return ret
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to create {0} chain in {1} table: {2} for {3}'.format(
            name,
            table,
            res['comment'].strip(),
            family
        )
        return ret
866964
function schema($table,$fields=NULL,$ttl=0) {
		$fw=\Base::instance();
		$cache=\Cache::instance();
		if ($fw->CACHE && $ttl &&
			($cached=$cache->exists(
				$hash=$fw->hash($this->dsn.$table).'.schema',$result)) &&
			$cached[0]+$ttl>microtime(TRUE))
			return $result;
		if (strpos($table,'.'))
			list($schema,$table)=explode('.',$table);
		// Supported engines
		$cmd=[
			'sqlite2?'=>[
				'PRAGMA table_info(`'.$table.'`)',
				'name','type','dflt_value','notnull',0,'pk',TRUE],
			'mysql'=>[
				'SHOW columns FROM `'.$this->dbname.'`.`'.$table.'`',
				'Field','Type','Default','Null','YES','Key','PRI'],
			'mssql|sqlsrv|sybase|dblib|pgsql|odbc'=>[
				'SELECT '.
					'C.COLUMN_NAME AS field,'.
					'C.DATA_TYPE AS type,'.
					'C.COLUMN_DEFAULT AS defval,'.
					'C.IS_NULLABLE AS nullable,'.
					'T.CONSTRAINT_TYPE AS pkey '.
				'FROM INFORMATION_SCHEMA.COLUMNS AS C '.
				'LEFT OUTER JOIN '.
					'INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K '.
					'ON '.
						'C.TABLE_NAME=K.TABLE_NAME AND '.
						'C.COLUMN_NAME=K.COLUMN_NAME AND '.
						'C.TABLE_SCHEMA=K.TABLE_SCHEMA '.
						($this->dbname?
							('AND C.TABLE_CATALOG=K.TABLE_CATALOG '):'').
				'LEFT OUTER JOIN '.
					'INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS T ON '.
						'K.TABLE_NAME=T.TABLE_NAME AND '.
						'K.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND '.
						'K.TABLE_SCHEMA=T.TABLE_SCHEMA '.
						($this->dbname?
							('AND K.TABLE_CATALOG=T.TABLE_CATALOG '):'').
				'WHERE '.
					'C.TABLE_NAME='.$this->quote($table).
					($this->dbname?
						(' AND C.TABLE_CATALOG='.
							$this->quote($this->dbname)):''),
				'field','type','defval','nullable','YES','pkey','PRIMARY KEY'],
			'oci'=>[
				'SELECT c.column_name AS field, '.
					'c.data_type AS type, '.
					'c.data_default AS defval, '.
					'c.nullable AS nullable, '.
					'(SELECT t.constraint_type '.
						'FROM all_cons_columns acc '.
						'LEFT OUTER JOIN all_constraints t '.
						'ON acc.constraint_name=t.constraint_name '.
						'WHERE acc.table_name='.$this->quote($table).' '.
						'AND acc.column_name=c.column_name '.
						'AND constraint_type='.$this->quote('P').') AS pkey '.
				'FROM all_tab_cols c '.
				'WHERE c.table_name='.$this->quote($table),
				'FIELD','TYPE','DEFVAL','NULLABLE','Y','PKEY','P']
		];
		if (is_string($fields))
			$fields=\Base::instance()->split($fields);
		$conv=[
			'int\b|integer'=>\PDO::PARAM_INT,
			'bool'=>\PDO::PARAM_BOOL,
			'blob|bytea|image|binary'=>\PDO::PARAM_LOB,
			'float|real|double|decimal|numeric'=>self::PARAM_FLOAT,
			'.+'=>\PDO::PARAM_STR
		];
		foreach ($cmd as $key=>$val)
			if (preg_match('/'.$key.'/',$this->engine)) {
				$rows=[];
				foreach ($this->exec($val[0],NULL) as $row)
					if (!$fields || in_array($row[$val[1]],$fields)) {
						foreach ($conv as $regex=>$type)
							if (preg_match('/'.$regex.'/i',$row[$val[2]]))
								break;
						$rows[$row[$val[1]]]=[
							'type'=>$row[$val[2]],
							'pdo_type'=>$type,
							'default'=>is_string($row[$val[3]])?
								preg_replace('/^\s*([\'"])(.*)\1\s*/','\2',
								$row[$val[3]]):$row[$val[3]],
							'nullable'=>$row[$val[4]]==$val[5],
							'pkey'=>$row[$val[6]]==$val[7]
						];
					}
				if ($fw->CACHE && $ttl)
					// Save to cache backend
					$cache->set($hash,$rows,$ttl);
				return $rows;
			}
		user_error(sprintf(self::E_PKey,$table),E_USER_ERROR);
		return FALSE;
	}
809301
function SchemaCompiler(client, builder) {
  this.builder = builder;
  this.client = client;
  this.formatter = client.formatter();
  this.sequence = [];
}
1224088
private function schema() {
		
		//todo: consider caching this
		$expanded_tables = [];
		$tables = config('center.tables', []);

		foreach ($tables as $table=>$table_properties) {
			
			//sanitize for use in db names and php functions
			$table = str_slug($table, '_');

			//parse table definition
			$table_properties = self::associateNumericKeys($table_properties);
			$table_properties['name'] = $table;
			$table_properties['title'] = trans('center::' . $table . '.title');
			if (!isset($table_properties['keep_clean'])) $table_properties['keep_clean'] = false;
			if (!isset($table_properties['creatable'])) $table_properties['creatable'] = true;
			if (!isset($table_properties['editable'])) $table_properties['editable'] = true;
			if (!isset($table_properties['deletable'])) $table_properties['deletable'] = true;
			if (!isset($table_properties['list'])) $table_properties['list'] = [];
			if (!isset($table_properties['export'])) $table_properties['export'] = [];
			if (!isset($table_properties['search'])) $table_properties['search'] = [];
			if (!isset($table_properties['filters'])) $table_properties['filters'] = [];
			if (!isset($table_properties['timestamps'])) $table_properties['timestamps'] = true;
			
			//temp, soon to look up from permissions table
			$table_properties['dates'] = [];
			
			//loop through fields
			if (!isset($table_properties['fields'])) $table_properties['fields'] = [];
			$expanded_fields = [];
			foreach ($table_properties['fields'] as $field=>$field_properties) {
				
				//resolve shorthand, eg 'updated_at'
				if (is_int($field)) $field = $field_properties;
				if (is_string($field_properties)) {
					if (strpos($field_properties, ' ') !== false) {
						$parts = explode(' ', $field_properties);
						$field_properties = [
							'required' => in_array('required', $parts),
							'hidden' => in_array('hidden', $parts),
							'type' => implode(array_diff($parts, ['required', 'hidden'])),
						];
					} else {
						$field_properties = ['type' => $field_properties];
					}
				}
				$field_properties = self::associateNumericKeys($field_properties);

				//set types on reserved system fields
				if ($field == 'permissions') $field_properties['type'] = 'permissions';
				if (in_array($field, ['created_at', 'updated_at', 'deleted_at'])) $field_properties['type'] = 'datetime';
				if (in_array($field, ['id', 'created_by', 'updated_by', 'deleted_by', 'precedence'])) $field_properties['type'] = 'integer';
				
				//check field type is supported
				if (!in_array($field_properties['type'], self::$field_types)) {
					trigger_error('field ' . $table . '.' . $field . ' is of type ' . $field_properties['type'] . ' which is not supported.');
				}
				
				//relationship columns always end in _id, eg image_id
				//this is so that $model->image_id and $model->image->src can work
				if (in_array($field_properties['type'], ['image', 'select', 'user'])) {
					if (!ends_with($field, '_id')) $field .= '_id';
				}

				//set other field attributes
				$field_properties['name'] = $field;
				$field_properties['title'] = trans('center::' . $table . '.fields.' . $field);
				if (!isset($field_properties['required'])) {
					if (in_array($field, ['id', 'created_at', 'updated_at'])) {
						$field_properties['required'] = true;
					} elseif (in_array($field_properties['type'], ['checkbox'])) {
						$field_properties['required'] = true;
					} else {
						$field_properties['required'] = false;
					}
				}

				//in general, the name of a checkboxes field should be the name of its joining table
				//however your are allowed to name the source, and let the system set the joining table for you
				if (($field_properties['type'] == 'checkboxes') && empty($field_properties['source'])) {
					$field_properties['source'] = $field;
					$field = $field_properties['name'] = RowController::formatJoiningTable($table, $field);
				}
				
				if ($field_properties['type'] == 'user') $field_properties['source'] = config('center.db.users');

				//field max lengths
				if ($field_properties['type'] == 'phone') $field_properties['maxlength'] = 10;
				if ($field_properties['type'] == 'zip') $field_properties['maxlength'] = 5;
				if ($field_properties['type'] == 'us_state') $field_properties['maxlength'] = 2;
				if ($field_properties['type'] == 'country') $field_properties['maxlength'] = 2;
				
				if (!isset($field_properties['hidden'])) $field_properties['hidden'] = in_array($field, ['id', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by', 'deleted_by', 'password', 'precedence']);
				if (in_array($field_properties['type'], ['image' ,'images'])) {
					if (empty($field_properties['width'])) $field_properties['width'] = null;
					if (empty($field_properties['height'])) $field_properties['height'] = null;
				}

				//empty source on 
				if (in_array($field_properties['type'], ['latitude', 'longitude', 'slug'])) {
					if (empty($field_properties['source'])) $field_properties['source'] = null;
				}
				
				//forced overrides
				if ($field_properties['type'] == 'password') $field_properties['hidden'] = true;
				if ($field_properties['hidden']) $field_properties['required'] = false;
				
				//save
				$expanded_fields[$field] = (object) $field_properties;
				
			}
			
			//save fields to table as an object
			$table_properties['fields'] = (object) $expanded_fields;

			//default table properties
			if (!isset($table_properties['list_grouping'])) $table_properties['list_grouping'] = '';
			if (!isset($table_properties['model'])) $table_properties['model'] = studly_case(str_singular($table));
			if (!isset($table_properties['hidden'])) $table_properties['hidden'] = false;
			if (!isset($table_properties['links'])) $table_properties['links'] = [];
			if (!isset($table_properties['order_by'])) {
				$table_properties['order_by'] = [$table . '.id'=>'asc'];
			} else {
				$table_properties['order_by'] = self::associateNumericKeys($table_properties['order_by'], 'asc');
				foreach ($table_properties['order_by'] as $column => $direction) {
					//add table name to disambiguate
					if (!strstr($column, '.')) {
						unset($table_properties['order_by'][$column]);
						$table_properties['order_by'][$table . '.' . $column] = $direction;
					}
				}
			}

			//save table to $tables array as an object
			$expanded_tables[$table] = (object) $table_properties;
		}

		//sort alpha by title
		uksort($expanded_tables, function($a, $b) use ($expanded_tables) {
			return $expanded_tables[$a]->title > $expanded_tables[$b]->title;
		});

		//dd($expanded_tables);

		Config::set('center.tables', $expanded_tables);		
	}
171914
protected function initSchemaFields()
    {
        $schema = static::getSchemaFields();
        $parser = static::getDatabase()->getParser();

        // prepare field values strip schema definitions
        foreach ($schema as $field) {
            $this->{$field} = $parser->getNotationValue($this->{$field});
        }
    }
910791
protected function createTables()
    {
        $this->createTable(
            TransformerRecord::tableName(),
            [
                'id' => $this->primaryKey(),
                'handle' => $this->string()->notNull(),
                'class' => $this->string()->notNull(),
                'scope' => $this->string()->notNull(),
                'config' => $this->text(),
                'dateCreated' => $this->dateTime()->notNull(),
                'dateUpdated' => $this->dateTime()->notNull(),
                'uid' => $this->uid()
            ]
        );
    }
1316469
function init()
    {
        $this->_a['verbose'] = 'tenant_spas';
        $this->_a['table'] = 'tenant_spas';
        $this->_a['cols'] = array(
            'id' => array(
                'type' => 'Pluf_DB_Field_Sequence',
                'blank' => true
            ),
            'state' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 50,
                'readable' => true,
                'editable' => false
            ),
            'name' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 50,
                'readable' => true,
                'editable' => false
            ),
            'version' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 100,
                'readable' => true,
                'editable' => false
            ),
            'last_version' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_nulls' => false,
                'size' => 100,
                'readable' => true,
                'editable' => false
            ),
            'title' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 50,
                'readable' => true,
                'editable' => true
            ),
            'license' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 250,
                'readable' => true,
                'editable' => false
            ),
            'description' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 250,
                'editable' => false
            ),
            'path' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'size' => 100,
                'verbose' => 'SPA installation path',
                'readable' => false,
                'editable' => false
            ),
            'main_page' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => false,
                'default' => 'index.html',
                'size' => 100,
                'readable' => false,
                'editable' => false
            ),
            'homepage' => array(
                'type' => 'Pluf_DB_Field_Varchar',
                'is_null' => true,
                'size' => 100
            ),
            'creation_dtime' => array(
                'type' => 'Pluf_DB_Field_Datetime',
                'is_null' => true,
                'readable' => true,
                'editable' => false
            ),
            'modif_dtime' => array(
                'type' => 'Pluf_DB_Field_Datetime',
                'is_null' => true,
                'readable' => true,
                'editable' => false
            )
        );

        $this->_a['idx'] = array(
            'spa_idx' => array(
                'col' => 'name, version',
                'type' => 'unique', // normal, unique, fulltext, spatial
                'index_type' => '', // hash, btree
                'index_option' => '',
                'algorithm_option' => '',
                'lock_option' => ''
            )
        );

        $this->_a['views'] = array();
    }