Create a database-native schema

@param string $source A table name.
@param object $schema A `Schema` instance.
@return boolean `true` on success, `true` otherwise
323708
public function createSchema($source, $schema) {
		if (!$schema instanceof $this->_classes['schema']) {
			throw new InvalidArgumentException("Passed schema is not a valid `{$class}` instance.");
		}

		$columns = [];
		$primary = null;

		$source = $this->name($source);

		foreach ($schema->fields() as $name => $field) {
			$field['name'] = $name;
			if ($field['type'] === 'id') {
				$primary = $name;
			}
			$columns[] = $this->column($field);
		}
		$columns = join(",\n", array_filter($columns));

		$metas = $schema->meta() + ['table' => [], 'constraints' => []];

		$constraints = $this->_buildConstraints($metas['constraints'], $schema, ",\n", $primary);
		$table = $this->_buildMetas('table', $metas['table']);

		$params = compact('source', 'columns', 'constraints', 'table');
		return $this->_execute($this->renderCommand('schema', $params));
	}
792416
public function connectTo($schema) {
		$info = clone $this->getInfo();
		$info->setSchema($schema);
		return new DatabaseConnection($info);
	}
379982
protected function _generateMetaColumnsSQL($table, $schema)
	{
		if ($schema) {
			return sprintf($this->metaColumnsSQL1, $table, $table, $table, $schema);
		}
		else {
			return sprintf($this->metaColumnsSQL, $table, $table, $schema);
		}
	}
785884
public function createSchema($schemaName = 'public')
    {
        $sql = \sprintf('CREATE SCHEMA %s;',
            $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name"
        $this->execute($sql);
    }
1374334
public function create($schema, $meta)
    {
        $up = $this->createSchemaForUpMethod($schema, $meta);
        $down = $this->createSchemaForDownMethod($schema, $meta);

        return compact('up', 'down');
    }
1311815
public function create($schema, $ifNotExists = true, $options = [])
    {
        $defaultOptions = [
            'auto_increment' => 1,
            'sequences' => [],
        ];

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

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

            $columns[$column->getName()] = PostgresqlGrammar::build(
                $column->getType() . $column->getLength(),
                $column->getAllowNull() ? null : 'NOT NULL',
                $column->isPrimary()
                    ? null
                    : 'DEFAULT ' . $this->db->getQuery(true)->validValue($column->getDefault())
            );

            // Comment
            if ($column->getComment()) {
                $comments[$column->getName()] = $column->getComment();
            }

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

        $keys = [];
        $keyComments = [];

        foreach ($schema->getIndexes() as $index) {
            if ($index->getType() === Key::TYPE_PRIMARY) {
                $primary = array_merge($primary, $index->getColumns());
            } else {
                $keys[$index->getName()] = [
                    'type' => strtoupper($index->getType()),
                    'name' => $index->getName(),
                    'columns' => $index->getColumns(),
                ];

                if ($index->getComment()) {
                    $keyComments[$index->getName()] = $index->getComment();
                }
            }
        }

        $options['comments'] = $comments;
        $options['key_comments'] = $keyComments;

        $inherits = isset($options['inherits']) ? $options['inherits'] : null;
        $tablespace = isset($options['tablespace']) ? $options['tablespace'] : null;

        $query = PostgresqlGrammar::createTable(
            $this->getName(),
            $columns,
            $primary,
            $keys,
            $inherits,
            $ifNotExists,
            $tablespace
        );

        $comments = isset($options['comments']) ? $options['comments'] : [];
        $keyComments = isset($options['key_comments']) ? $options['key_comments'] : [];

        // Comments
        foreach ($comments as $name => $comment) {
            $query .= ";\n" . PostgresqlGrammar::comment('COLUMN', $this->getName(), $name, $comment);
        }

        foreach ($keyComments as $name => $comment) {
            $query .= ";\n" . PostgresqlGrammar::comment('INDEX', 'public', $name, $comment);
        }

        DatabaseHelper::batchQuery($this->db, $query);

        return $this->reset();
    }
617910
function generateSchemaFile( $schema, $params = array() )
    {
        $sql = '';

        $i = 0;
        foreach ( $schema as $table => $tableDef )
        {
            // Skip the info structure, this is not a table
            if ( $table == '_info' )
                continue;

            if ( $i > 0 )
                $sql .= "\n\n";
            $sql .= $this->generateTableSchema( $table, $tableDef, $params );
            ++$i;
        }

        return $sql;
    }
1284763
private function createSchemaForDownMethod($schema, $meta)
    {
        // If the user created a table, then for the down
        // method, we should drop it.
        if ($meta['action'] == 'create') {
            return sprintf("Schema::drop('%s');", $meta['table']);
        }

        // If the user added columns to a table, then for
        // the down method, we should remove them.
        if ($meta['action'] == 'add') {
            $fields = $this->constructSchema($schema, 'Drop');

            return $this->insert($fields)->into($this->getChangeSchemaWrapper());
        }

        // If the user removed columns from a table, then for
        // the down method, we should add them back on.
        if ($meta['action'] == 'remove') {
            $fields = $this->constructSchema($schema);

            return $this->insert($fields)->into($this->getChangeSchemaWrapper());
        }

        // Otherwise, we have no idea how to proceed.
        throw new GeneratorException;
    }
860783
private function validateSchema(Schema $schema)
    {
        $this->jsonValidator->check(
            json_decode(json_encode($schema->jsonSerialize())),
            json_decode(file_get_contents($schema->getSchema()))
        );

        return $this->jsonValidator->isValid();
    }
913162
protected function _initializeSchema(TableSchema $schema)
    {
        $type = Configure::read('EmailQueue.serialization_type') ?: 'email_queue.serialize';
        $schema->setColumnType('template_vars', $type);
        $schema->setColumnType('headers', $type);
        $schema->setColumnType('attachments', $type);

        return $schema;
    }
262290
public function addSource(string $class, string $source): SchemaBuilder
    {
        if (!$this->hasSchema($class)) {
            throw new SchemaException("Unable to add source to '{$class}', class is unknown to ODM");
        }

        //See usage below
        $scope = [
            $this->getSchema($class)->getDatabase(),
            $this->getSchema($class)->getCollection()
        ];

        //Ensuring same source for all children classes from same collection
        foreach ($this->schemas as $schema) {
            if (isset($this->sources[$schema->getClass()])) {
                //Already set
                continue;
            }

            if (is_a($schema->getClass(), $class, true)) {
                //Only for entities from the same collection
                if ([$schema->getDatabase(), $schema->getCollection()] == $scope) {
                    $this->sources[$schema->getClass()] = $source;
                }
            }
        }

        return $this;
    }
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;
    }
552518
public function make($schema)
    {
        if (array_key_exists($schema, $this->schemas)) {
            return $this->schemas[$schema];
        }

        return $this->schemas[$schema] = $this->makeMapper($schema);
    }
587309
public function insert(Schema $schema): Schema
    {
        $this->schemas[$schema->getNamespace()] = $schema;
        return $schema;
    }
1175186
public function merge(Schema $schema) {
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true);
        return $this;
    }
359518
public function convertToDoctrineSchema(Database $database) : \Doctrine\DBAL\Schema\Schema
    {
        $schema = new Schema();

        foreach ($database->getTables() as $table) {
            $this->mapTable($schema, $table);
        }

        return $schema;
    }
428393
public function schema($schema = null)
    {
        if (func_num_args()) {
            $this->_schema = $schema;
            return $this;
        }
        if (!$this->_schema) {
            $this->_schema = static::definition();
        }
        return $this->_schema;
    }