Walk thought schemas and define structure of associated tables.

@throws SchemaException
@throws DBALException
422220
protected function renderModels()
    {
        foreach ($this->schemas as $schema) {
            /**
             * Attention, this method will request table schema from DBAL and will empty it's state
             * so schema can define it from ground zero!
             */
            $table = $this->requestTable(
                $schema->getTable(),
                $schema->getDatabase(),
                true,
                true
            );

            //Render table schema
            $table = $schema->declareTable($table);

            //Working with indexes
            foreach ($schema->getIndexes() as $index) {
                $table->index($index->getColumns())->unique($index->isUnique());
                $table->index($index->getColumns())->setName($index->getName());
            }

            /*
             * Attention, this is critical section:
             *
             * In order to work efficiently (like for real), ORM does require every table
             * to have 1 and only 1 primary key, this is crucial for things like in memory
             * cache, transaction command priority pipeline, multiple queue commands for one entity
             * and etc.
             *
             * It is planned to support user defined PKs in a future using unique indexes and record
             * schema.
             *
             * You are free to select any name for PK field.
             */
            if (count($table->getPrimaryKeys()) !== 1) {
                throw new SchemaException(
                    "Every record must have singular primary key (primary, bigPrimary types)"
                );
            }

            //And put it back :)
            $this->pushTable($table);
        }
    }
1229236
public List<SchemaName> getSchemas() throws SQLException {
        final List<SchemaName> list = new ArrayList<>();
        try (ResultSet results = databaseMetadata.getSchemas()) {
            if (results != null) {
                bind(results, SchemaName.class, list);
            }
        }
        return list;
    }
58038
protected function scanDatabase()
	{
		if ($this->isConnected()) {
			$tables = $this->doctrine->listTableNames();

			foreach ($tables as $table) {
				$schTable = $this->doctrine->listTableDetails($table);

				$this->tables[$table] = $this->getTableFields($schTable);
			}
		}
	}
1113488
public function addSchema(string $schema) : void
    {
        $work = $schema;
        if ($work{0} != '/') {
            $work = getcwd()."/$work";
        }
        if (!file_exists($work)) {
            $this->notice("`\"$schema\"` for `{$this->database}` not found, skipping.");
            return;
        }
        $this->schemas[] = file_get_contents($work);
        $this->success("Loaded $schema.");
    }
1085966
public function addColumn(Column $column)
    {
        if ($this->hasColumn($column->getName())) {
            throw SchemaException::tableColumnAlreadyExists($this->getName(), $column->getName());
        }

        $this->columns[$column->getName()] = $column;
    }
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});
        }
    }
687194
public void open() throws DBException
    {
        super.open();
        Iterator<BaseTable> iterator = this.getTables();
        while (iterator.hasNext())
        {
            BaseTable table = iterator.next();
            if ((table != null) && (table != this.getNextTable()))
            {
                table.open();
            }
        }
    }
1219853
public void prepareTables() throws Exception
    {
        Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI());

        try (Connection conn = xaConnectionManager.getConnection();)
        {
            Files.walk(ddlPath, 1)
                    .filter(path -> !Files.isDirectory(path)
                            && (path.toString().endsWith("ddl")
                            || path.toString().endsWith("idx")))
                    .forEach(path -> {
                try
                {
                    RunScript.execute(conn, Files.newBufferedReader(path));
                }
                catch (Exception e)
                {
                    throw new RuntimeException("Exception at table initialization", e);
                }
            });
        }
    }
974195
private void registerInternal(JMFSchema schema) {
    schemaTable.set((HashedArray.Element)schema);
    Object assoc = schema.getJMFType().getAssociation();
    if (assoc != null)
      associations.put(assoc, schema);
  }
639289
@Override
	public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception {
		int indexCounter = 0;

		// generate the class name that represents the table
		String classTableName = getTableClassName(entity.getSimpleName());

		FindIndexesVisitor indexVisitor = new FindIndexesVisitor();
		List<? extends AnnotationMirror> annotationMirrors = entity.getElement().getAnnotationMirrors();
		for (AnnotationMirror annotationMirror : annotationMirrors) {
			Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = annotationMirror
					.getElementValues();

			if (BindSqlType.class.getName().equals(annotationMirror.getAnnotationType().toString())) {
				for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValues
						.entrySet()) {
					// The 'entry.getKey()' here is the annotation attribute
					// name.
					String key = entry.getKey().getSimpleName().toString();
					entry.getValue().accept(indexVisitor, key);
				}
			}
		}

		PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
		String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, classTableName);
		classBuilder = TypeSpec.classBuilder(classTableName).addModifiers(Modifier.PUBLIC)
				.addSuperinterface(SQLiteTable.class);

		BindTypeContext context = new BindTypeContext(classBuilder, TypeUtility.typeName(packageName, classTableName),
				Modifier.STATIC, Modifier.PRIVATE);

		// javadoc for class
		classBuilder.addJavadoc("<p>");
		classBuilder.addJavadoc("\nEntity <code>$L</code> is associated to table <code>$L</code>\n",
				entity.getSimpleName(), entity.getTableName());
		classBuilder.addJavadoc("This class represents table associated to entity.\n");
		classBuilder.addJavadoc("</p>\n");
		JavadocUtility.generateJavadocGeneratedBy(classBuilder);
		classBuilder.addJavadoc(" @see $T\n", TypeUtility.className(entity.getName()));

		{
			// @formatter:off
			// table_name
			FieldSpec fieldSpec = FieldSpec
					.builder(String.class, "TABLE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
					.initializer("\"$L\"", entity.getTableName())
					.addJavadoc("Costant represents typeName of table $L\n", entity.getTableName()).build();
			classBuilder.addField(fieldSpec);
			// @formatter:on
		}

		StringBuilder bufferTable = new StringBuilder();
		StringBuilder bufferForeignKey = new StringBuilder();
		// shared between create table and drop table
		StringBuilder bufferIndexesCreate = new StringBuilder();
		StringBuilder bufferDropTable = new StringBuilder();
		StringBuilder bufferIndexesDrop = new StringBuilder();

		bufferTable.append("CREATE TABLE " + entity.getTableName());
		// define column typeName set

		String separator = "";
		bufferTable.append(" (");

		// for each column, that need to be persisted on table
		for (SQLProperty item : entity.getCollection()) {
			bufferTable.append(separator);
			bufferTable.append(item.columnName);
			bufferTable.append(" " + SQLTransformer.columnTypeAsString(item));

			switch (item.columnType) {
			case PRIMARY_KEY:
			case PRIMARY_KEY_UNMANGED:
				bufferTable.append(" PRIMARY KEY");
				if (!item.isType(String.class) && item.columnType == ColumnType.PRIMARY_KEY) {
					bufferTable.append(" AUTOINCREMENT");
				}
				bufferTable.append(" NOT NULL");
				break;
			case UNIQUE:
				bufferTable.append(" UNIQUE");
				break;
			case INDEXED:
				bufferIndexesCreate.append(String.format(" CREATE INDEX idx_%s_%s ON %s(%s);", entity.getTableName(),
						item.columnName, entity.getTableName(), item.columnName));
				bufferIndexesDrop.append(
						String.format(" DROP INDEX IF EXISTS idx_%s_%s;", entity.getTableName(), item.columnName));
				break;
			case STANDARD:
				break;
			}

			boolean nullable = item.isNullable();

			// if it is not primary key and it is not nullable, then add not
			// null
			if (!nullable && !(item.columnType == ColumnType.PRIMARY_KEY
					|| item.columnType == ColumnType.PRIMARY_KEY_UNMANGED)) {
				bufferTable.append(" NOT NULL");
			}

			// foreign key
			String foreignClassName = item.foreignParentClassName;
			if (item.isForeignKey()) {
				SQLiteEntity reference = model.getEntity(foreignClassName);

				if (reference == null) {
					// check if we have a DAO associated into DataSource
					// definition
					boolean found = false;
					for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
						if (daoDefinition.getEntityClassName().equals(foreignClassName)) {
							found = true;
						}
					}

					if (!found) {
						throw new NoDaoElementFound(schema, TypeUtility.className(foreignClassName));
					} else {
						throw new InvalidBeanTypeException(item, foreignClassName);
					}
				}

				// foreign key can ben used only with column type
				// long/Long
				if (!TypeUtility.isTypeIncludedIn(item.getPropertyType().getTypeName(), Long.class, Long.TYPE,
						String.class)) {
					throw new InvalidForeignKeyTypeException(item);
				}

				bufferForeignKey.append(", FOREIGN KEY(" + item.columnName + ") REFERENCES " + reference.getTableName()
						+ "(" + reference.getPrimaryKey().columnName + ")");

				if (item.onDeleteAction != ForeignKeyAction.NO_ACTION) {
					bufferForeignKey.append(" ON DELETE " + item.onDeleteAction.toString().replaceAll("_", " "));
				}

				if (item.onUpdateAction != ForeignKeyAction.NO_ACTION) {
					bufferForeignKey.append(" ON UPDATE " + item.onUpdateAction.toString().replaceAll("_", " "));
				}

				// INSERT as dependency only if reference is another entity.
				// Same entity can not be own dependency.
				if (!entity.equals(reference)) {
					entity.referedEntities.add(reference);
				}

			}

			separator = ", ";
		}

		// add foreign key
		bufferTable.append(bufferForeignKey.toString());		
		
				
		// add multicolumn indexes (UNIQUE)
		{
			Triple<String, String, String> multiIndexes = buldIndexes(entity, indexVisitor.getUniqueIndexes(), true,
					indexCounter);
			
			// add constraint unique (if present)
			bufferTable.append(multiIndexes.value2);
			// close the table definition
			bufferTable.append(");");
			
			if (!StringUtils.isEmpty(multiIndexes.value0)) {
				bufferTable.append(multiIndexes.value0 + ";");
				bufferIndexesDrop.append(multiIndexes.value1 + ";");
			}						
		}
		
		// add indexes creation one table
				if (bufferIndexesCreate.length() > 0) {
					bufferTable.append(bufferIndexesCreate.toString());
				}

		// add multicolumn indexes (NOT UNIQUE)
		{
			Pair<String, String> multiIndexes = buldIndexes(entity, indexVisitor.getNotUniqueIndexes(), false,
					indexCounter);
			if (!StringUtils.isEmpty(multiIndexes.value0)) {
				bufferTable.append(multiIndexes.value0 + ";");
				bufferIndexesDrop.append(multiIndexes.value1 + ";");
			}
		}
				
		

		{
			// create table SQL
			// @formatter:off
			FieldSpec.Builder fieldSpec = FieldSpec.builder(String.class, "CREATE_TABLE_SQL")
					.addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC);
			// @formatter:on

			// @formatter:off
			fieldSpec.addJavadoc("<p>\nDDL to create table $L\n</p>\n", entity.getTableName());
			fieldSpec.addJavadoc("\n<pre>$L</pre>\n", bufferTable.toString());
			// @formatter:on

			classBuilder.addField(fieldSpec.initializer("$S", bufferTable.toString()).build());
		}

		// drop table SQL
		// index does not need to be dropped, they are automatically detroyed
		// with tables
		if (bufferIndexesDrop.length() > 0) {
			bufferDropTable.append(bufferIndexesDrop.toString());
		}

		bufferDropTable.append("DROP TABLE IF EXISTS " + entity.getTableName() + ";");

		{
			// @formatter:off
			FieldSpec fieldSpec = FieldSpec.builder(String.class, "DROP_TABLE_SQL")
					.addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC)
					.initializer("$S", bufferDropTable.toString())
					.addJavadoc("<p>\nDDL to drop table $L\n</p>\n", entity.getTableName())
					.addJavadoc("\n<pre>$L</pre>\n", bufferDropTable.toString()).build();
			// @formatter:on
			classBuilder.addField(fieldSpec);
		}

		// define column typeName set
		for (ModelProperty item : entity.getCollection()) {
			item.accept(this);
		}

		ManagedPropertyPersistenceHelper.generateFieldPersistance(context, entity.getCollection(), PersistType.BYTE,
				true, Modifier.STATIC, Modifier.PUBLIC);

		model.sqlForCreate.add(bufferTable.toString());
		model.sqlForDrop.add(bufferDropTable.toString());

		generateColumnsArray(entity);

		TypeSpec typeSpec = classBuilder.build();
		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);

	}
326574
@Override
    public void describe(Schema schema) {
        pojoBinding.describe(schema.createTable(tableName), schema);
    }
335728
private function processTableDefinition()
    {
        // Table setting in scheme always (!) overrides manual set table definition
        if (! empty($this->scheme['table'])) {
            $this->table = $this->scheme['table'];
        }
        
        // Look for table name when there was none set by a scheme
        if (empty($this->table) && ! empty($this->definition['table'])) {
            $this->table = $this->definition['table'];
        }
        
        // Still no table? Time to complain about it with an exception
        if (empty($this->table)) {
            Throw new QueryBuilderException('QueryBuilder needs a table name. Provide tablename by setting "table" element in your query definition or provide a Scheme with a set table element.<br><br><small>Send QueryBuilder definition:</small><pre>' . print_r($this->definition, true) . '</pre>');
        }
        
        // Is our table an array, which means that it is a QueryBuilder definition?
        if (is_array($this->table)) {
            
            // Build this sql string
            $this->table = $this->checkSubquery($this->table);
        }
        
        // Alias setting in scheme always (!) overrides manual set alias definition
        if (! empty($this->scheme['alias'])) {
            $this->alias = $this->scheme['alias'];
        }
        
        // No alias until here but set in definition?
        if (empty($this->alias) && ! empty($this->definition['alias'])) {
            $this->alias = $this->definition['alias'];
        }
    }
974063
public void addDBDefinitionFile(InputStream schemaStream) throws IOException
    {
        _torqueSchemata.put("schema"+_torqueSchemata.size()+".xml",
                            readStreamCompressed(schemaStream));
    }
449597
function Schema(model) {
        var _this = this;
        /**
         * List of generated schemas.
         */
        this.schemas = {};
        this.model = model;
        var models = model.database().models();
        Object.keys(models).forEach(function (name) { _this.one(models[name]); });
    }
670210
@Override
	public Schema schema() {
		Schema schema = new Schema();
		schema.addField("query-plan", Type.VARCHAR(500));
		return schema;
	}
1341615
def add_schema(self, database, schema):
        
        self.schemas.add((_lower(database), _lower(schema)))
1104581
public function initTablesList(array $schemas = null) : void
    {
        $dbName = $this->db->getDbName();

        if (!empty($_SESSION['databases'][$dbName]['tables'])) {
            $this->tables = $_SESSION['databases'][$dbName]['tables'];
            return;
        }

        static::initSessionStorage($dbName);

        $this->addAdditionTables();

        if ($this->db->getDBDriver() === 'pgsql') {
            $_SESSION['databases'][$dbName]['tables']
                = $this->tables
                = array_merge($this->tables, $this->getPostgresTables($schemas));
        } elseif ($this->db->getDBDriver() === 'mysql') {
            $_SESSION['databases'][$dbName]['tables']
                = $this->tables
                = array_merge($this->tables, $this->getMysqlTables($dbName));
        }

        if (!$this->tables) {
            throw new PDOConnectionException('Не удалось получить список таблиц');
        }
    }