Prints current database schema (according sqlalchemy database model)::

            ./manage.py sqla:schema [name]
777532
def command_schema(self, name=None):
        '''
        
        '''
        meta_name = table_name = None
        if name:
            if isinstance(self.metadata, MetaData):
                table_name = name
            elif '.' in name:
                meta_name, table_name = name.split('.', 1)
            else:
                meta_name = name

        def _print_metadata_schema(metadata):
            if table_name is None:
                for table in metadata.sorted_tables:
                    print(self._schema(table))
            else:
                try:
                    table = metadata.tables[table_name]
                except KeyError:
                    sys.exit('Table {} is not found'.format(name))
                print(self._schema(table))

        if isinstance(self.metadata, MetaData):
            _print_metadata_schema(self.metadata)
        else:
            for current_meta_name, metadata in self.metadata.items():
                if meta_name not in (current_meta_name, None):
                    continue
                _print_metadata_schema(metadata)
1163914
def schema(self):
        
        schema = "%s %s %s %s('%s'" % (
            self.name,
            self.data_type,
            self.index_type,
            self.key_type,
            self.index_name,
        )
        if self.includes is not None:
            schema += ", ["
            schema += ", ".join(("'%s'" % i for i in self.includes))
            schema += "]"
        return schema + ")"
409043
def _schema_getter(self, db):
        """"""
        # Change DB connection if needed
        if self.database != db:
            self.change_db(db)
        schema_dict = {tbl: self.get_schema(tbl) for tbl in self.tables}

        schema_lst = []
        for table, schema in schema_dict.items():
            for col in schema:
                col.insert(0, table)
                schema_lst.append(col)
        return schema_lst
1224266
def create_schema(self, schema_name):
        
        try:
            self.cursor.execute('CREATE SCHEMA %s' % schema_name)
        except Exception as e:
            raise e
        finally:
            self.db.commit()
300766
def show_schemas(schemaname):
    

    ecode = 0
    try:
        schemas = {}
        schema_dir = os.path.join(contexts['anchore_config']['pkg_dir'], 'schemas')
        for f in os.listdir(schema_dir):
            sdata = {}
            try:
                with open(os.path.join(schema_dir, f), 'r') as FH:
                    sdata = json.loads(FH.read())
            except:
                anchore_print_err('found schema file but failed to parse: ' + os.path.join(schema_dir, f))

            if sdata and (not schemaname or f in schemaname):
                schemas[f] = sdata

        if not schemas:
            anchore_print_err("no specified schemas were found to show")
        else:
            anchore_print(json.dumps(schemas, indent=4))

    except Exception as err:
        anchore_print_err('operation failed')
        ecode = 1

    sys.exit(ecode)
772591
private void createSchemaOnDb() {
        StringBuilder sql = new StringBuilder();
        sql.append(topology.getSqlgGraph().getSqlDialect().createSchemaStatement(this.name));
        if (this.sqlgGraph.getSqlDialect().needsSemicolon()) {
            sql.append(";");
        }
        if (logger.isDebugEnabled()) {
            logger.debug(sql.toString());
        }
        Connection conn = this.sqlgGraph.tx().getConnection();
        try (Statement stmt = conn.createStatement()) {
            stmt.execute(sql.toString());
        } catch (SQLException e) {
            logger.error("schema creation failed " + this.sqlgGraph.toString(), e);
            throw new RuntimeException(e);
        }
    }
568751
def attr_name(self):
        ""
        return self.schema.name if self.schema else self.field.name
1002629
def schema(self):
        
        schema = _helpers._get_sub_prop(self._properties, ["load", "schema", "fields"])
        if schema is None:
            return
        return [SchemaField.from_api_repr(field) for field in schema]
1296256
def fieldmap(self):
        '''
        
        '''
        if hasattr(self, '_sql_fieldmap') and self._sql_fieldmap:
            fieldmap = self._sql_fieldmap
        else:
            fieldmap = defaultdict(str)
            fields = copy(self.fields)
            for field, opts in fields.iteritems():
                field_id = opts.get('what')
                if field_id is not None:
                    fieldmap[field_id] = field
            self._sql_fieldmap = fieldmap
        return fieldmap
315907
private String translateSchema(String schemaName) throws SQLException {

        if (useSchemaDefault && schemaName != null
                && schemaName.length() == 0) {
            ResultSet rs = executeSelect("SYSTEM_SCHEMAS", "IS_DEFAULT=TRUE");

            if (rs.next()) {
                return rs.getString(1);
            }

            return schemaName;
        }

        return schemaName;
    }
1206024
public function getCurrentDatabase()
    {
        if ($this->currentDatabase === null) {
            $compiler = $this->connection->schemaCompiler();
            $result = $compiler->currentDatabase($this->connection->getDSN());

            if (is_array($result)) {
                $this->currentDatabase = $this->connection->column($result['sql'], $result['params']);
            } else {
                $this->currentDatabase = $result;
            }
        }

        return $this->currentDatabase;
    }
229764
def table(self, name, database=None):
        
        qualified_name = self._fully_qualified_name(name, database)
        schema = self._get_table_schema(qualified_name)
        node = self.table_class(qualified_name, schema, self)
        return self.table_expr_class(node)
1167039
def index_name(model, *field_names, **kwargs):
    
    if not len(field_names):
        raise ValueError("At least one field name required")
    using = kwargs.pop('using', DEFAULT_DB_ALIAS)
    if len(kwargs):
        raise ValueError("The only supported keyword argument is 'using'")

    existing_fields = {field.name: field for field in model._meta.fields}
    fields = [existing_fields[name] for name in field_names
              if name in existing_fields]

    if len(fields) != len(field_names):
        unfound_names = set(field_names) - {field.name for field in fields}
        raise ValueError("Fields do not exist: " + ",".join(unfound_names))
    column_names = tuple(field.column for field in fields)
    list_sql = get_list_sql(column_names)

    with connections[using].cursor() as cursor:
        cursor.execute(
            """SELECT `INDEX_NAME`, `SEQ_IN_INDEX`, `COLUMN_NAME`
               FROM INFORMATION_SCHEMA.STATISTICS
               WHERE TABLE_SCHEMA = DATABASE() AND
                     TABLE_NAME = %s AND
                     COLUMN_NAME IN {list_sql}
               ORDER BY `INDEX_NAME`, `SEQ_IN_INDEX` ASC
            """.format(list_sql=list_sql),
            (model._meta.db_table,) + column_names,
        )
        indexes = defaultdict(list)
        for index_name, _, column_name in cursor.fetchall():
            indexes[index_name].append(column_name)

    indexes_by_columns = {tuple(v): k for k, v in indexes.items()}
    try:
        return indexes_by_columns[column_names]
    except KeyError:
        raise KeyError("There is no index on (" + ",".join(field_names) + ")")
145943
def create_db_schema(cls, cur, schema_name):
        
        create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
        cur.execute(create_schema_script)
560543
def database_current_migration(self):
        
        # If the table doesn't even exist, return None.
        if not self.migration_table.exists(self.session.bind):
            return None

        # Also return None if self.migration_data is None.
        if self.migration_data is None:
            return None

        return self.migration_data.version
1094152
def create_tables(self):
        
        cdir = os.path.dirname( os.path.realpath(__file__) )
        
        # table schemas -------------------------------------
        schema = os.path.join(cdir,"data","partsmaster.sql")
        if self.debug:
            print(self.hdr,"parts master schema is ",schema)
        
        self.populate(schema)
        
        schema = os.path.join(cdir,"data","approvedmfg.sql")
        if self.debug:
            print(self.hdr,"approved mfg list schema is ",schema)
        
        self.populate(schema)
        
        schema = os.path.join(cdir,"data","attachment.sql")
        if self.debug:
            print(self.hdr,"attachment schema is ",schema)
        
        self.populate(schema)

        schema = os.path.join(cdir,"data","bom.sql")
        if self.debug:
            print(self.hdr,"bill of materials schema is ",schema)
        
        self.populate(schema)
        
        return
153517
def get_sql_for_new_models(apps=None, using=DEFAULT_DB_ALIAS):
    
    connection = connections[using]
    
    # Get a list of already installed *models* so that references work right.
    tables = connection.introspection.table_names()
    seen_models = connection.introspection.installed_models(tables)
    created_models = set()
    pending_references = {}
    
    if apps:
        apps = [models.get_app(a) for a in apps]
    else:
        apps = models.get_apps()
    
    # Build the manifest of apps and models that are to be synchronized
    all_models = [
        (app.__name__.split('.')[-2], [
            m
            for m in models.get_models(app, include_auto_created=True)
            if router.allow_syncdb(using, m)
        ])
        for app in apps
    ]
    
    def model_installed(model):
        opts = model._meta
        converter = connection.introspection.table_name_converter
        db_table_in = (converter(opts.db_table) in tables)
        auto_create_in = (
            opts.auto_created and
            converter(opts.auto_created._meta.db_table) in tables
        )
        return not (db_table_in or auto_create_in)
    
    manifest = SortedDict(
        (app_name, filter(model_installed, model_list))
        for app_name, model_list in all_models
    )
    
    statements = []
    sql = None
    for app_name, model_list in manifest.items():
        for model in model_list:
            # Create the model's database table, if it doesn't already exist.
            sql, references = connection.creation.sql_create_model(
                model,
                no_style(),
                seen_models
            )
            
            seen_models.add(model)
            created_models.add(model)
            statements.append("### New Model: %s.%s" % (
                app_name,
                str(model).replace("'>", "").split(".")[-1]
            ))
            
            for refto, refs in references.items():
                pending_references.setdefault(refto, []).extend(refs)
                if refto in seen_models:
                    sql.extend(
                        connection.creation.sql_for_pending_references(
                            refto,
                            no_style(),
                            pending_references
                        )
                    )
            
            sql.extend(
                connection.creation.sql_for_pending_references(
                    model,
                    no_style(),
                    pending_references
                )
            )
            statements.extend(sql)
    
    custom_sql = None
    for app_name, model_list in manifest.items():
        for model in model_list:
            if model in created_models:
                custom_sql = custom_sql_for_model(
                    model,
                    no_style(),
                    connection
                )
                
                if custom_sql:
                    statements.extend(custom_sql)
    
    index_sql = None
    for app_name, model_list in manifest.items():
        for model in model_list:
            if model in created_models:
                index_sql = connection.creation.sql_indexes_for_model(
                    model,
                    no_style()
                )
                
                if index_sql:
                    statements.extend(index_sql)
    
    return statements