Utility function to read database schema from an .sql file
336291
private function db_read_schema($schemafile)
    {
        $lines       = file($schemafile);
        $table_block = false;
        $schema      = array();
        $keywords    = array('PRIMARY','KEY','INDEX','UNIQUE','CONSTRAINT','REFERENCES','FOREIGN');

        foreach ($lines as $line) {
            if (preg_match('/^\s*create table ([\S]+)/i', $line, $m)) {
                $table_name = explode('.', $m[1]);
                $table_name = end($table_name);
                $table_name = preg_replace('/[`"\[\]]/', '', $table_name);
            }
            else if ($table_name && ($line = trim($line))) {
                if ($line == 'GO' || $line[0] == ')' || $line[strlen($line)-1] == ';') {
                    $table_name = null;
                }
                else {
                    $items = explode(' ', $line);
                    $col   = $items[0];
                    $col   = preg_replace('/[`"\[\]]/', '', $col);

                    if (!in_array(strtoupper($col), $keywords)) {
                        $type = strtolower($items[1]);
                        $type = preg_replace('/[^a-zA-Z0-9()]/', '', $type);

                        $schema[$table_name][$col] = $type;
                    }
                }
            }
        }

        return $schema;
    }
400368
async function fetchDatabaseSchemas (client, schemaNames, jsonSchemas, messages) {
  const currentDbStructure = await pgInfo({
    client: client,
    schemas: schemaNames
  })

  const expectedDbStructure = await relationize({
    source: {
      schemas: jsonSchemas
    }
  })

  return {
    currentDbStructure,
    expectedDbStructure
  }
}
1189143
public static boolean dumpDatabaseSchemaToFile( DatabaseContext ctx, File file )
	{
		log.info( "Dumping database schema to file " + file.getAbsolutePath() );

		DatabaseDescriptionInspector inspector = new DatabaseDescriptionInspector();
		DatabaseDescription dbDesc = inspector.getDatabaseDescription( ctx.db, ctx.dbh );

		Gson gson = new Gson();
		String json = gson.toJson( dbDesc );
		try
		{
			PrintWriter writer;
			writer = new PrintWriter( file );
			writer.print( json );
			writer.close();

			return true;
		}
		catch( FileNotFoundException e )
		{
			e.printStackTrace();

			return false;
		}
	}
42067
def DumpCurrentSchema(cursor):
  """"""
  cursor.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
                 "WHERE table_schema = (SELECT DATABASE())")
  defs = []
  for table, in sorted(cursor.fetchall()):
    cursor.execute("SHOW CREATE TABLE `{}`".format(table))
    rows = cursor.fetchall()
    defs.append(rows[0][1])

  return "\n\n".join(defs)
1074589
def as_sql(self, compiler, connection):  # pylint: disable=arguments-differ
        """"""
        sql, params = super().as_sql(compiler, connection)
        params.append(self.path)
        return sql, params
1284561
function schema (args) {
    // get args object
    args = requireValidOptionalObject(args)
    // get colunmn and index information from database
    return Promise.all([
        this.mysql().query(sql.describe(this)),
        this.mysql().query(sql.showCreateTable(this)),
        this.mysql().query(sql.showIndexes(this)),
    ])
    // build schema from database response
    .then(res => {
        // get columns and indexes from describe and show index queries
        var columns = res[0][0]
        var createTable = res[1][0]
        var indexes = res[2][0]
        // schema data
        var schema = {
            columns: {},
            indexes: [],
        }
        // get first and only create table record
        createTable = _.get(createTable, "[0]['Create Table']", '')
        // get engine and charset from create table sql
        var engine = createTable.match(/ENGINE=(\w+)/)
        schema.engine = engine && engine[1] || ''
        var charset = createTable.match(/DEFAULT CHARSET=(\w+)/)
        schema.charset = charset && charset[1] || ''
        // build column data
        _.each(columns, dbColumn => {
            var column = schema.columns[dbColumn.Field] = {}
            // check unsigned
            if (dbColumn.Type.match(/unsigned$/)) {
                column.unsigned = true
                dbColumn.Type = dbColumn.Type.replace(/ unsigned/, '')
            }
            // char id column
            if (dbColumn.Type === 'char(32)') {
                // model must not be set for binary ids
                assert.ok(this.binaryIds === false, 'binaryIds must be disabled for char id columns')
                // set type
                column.type = 'id'
            }
            // binary id column
            else if (dbColumn.Type === 'binary(16)') {
                // model must be set for binary ids
                assert.ok(this.binaryIds === true, 'binaryIds must be enabled for binary id columns')
                // set type
                column.type = 'id'
            }
            // all other column types
            else  {
                // require valid type
                assert.ok(sql.columnTypesInverse[dbColumn.Type], 'unrecognized column type '+dbColumn.Type)
                // map database to internal type
                column.type = sql.columnTypesInverse[dbColumn.Type]
            }
            // is column nullable
            if (dbColumn.Null === 'NO') {
                column.null = false
            }
            // set default if not null
            if (dbColumn.Default) {
                column.default = dbColumn.Default
                // convert boolean
                if (column.type === 'boolean') {
                    column.default = column.default === '1' ? true : false
                }
            }
        })
        // map of indexes by key name since keys may cover multiple columns
        var indexesByKey = {}
        // build map of indexes by key name
        _.each(indexes, dbIndex => {
            // create entry for index if it does not already exist
            if (!indexesByKey[dbIndex.Key_name]) {
                indexesByKey[dbIndex.Key_name] = {
                    columns: {}
                }
            }
            // get entry for index
            var index = indexesByKey[dbIndex.Key_name]
            // add column with sequence in index
            index.columns[dbIndex.Column_name] = parseInt(dbIndex.Seq_in_index)
            // add unique flag if true
            if (dbIndex.Non_unique === '0') {
                index.unique = true
            }
        })
        // add indexes to schema
        _.each(indexesByKey, (index, name) => {
            var indexColumns = _.keys(index.columns)
            // multi-column index
            if (indexColumns.length > 1) {
                // sort index columns by the Seq_in_index value - these may
                // always be in order so this may not be needed
                indexColumns = _.sortBy(indexColumns, indexColumn => index.columns[indexColumn])
                // create schema index entry
                var schemaIndex = {
                    columns: indexColumns,
                }
                // set unique flag
                if (index.unique) {
                    schemaIndex.unique = true
                }
                // add index to schema
                schema.indexes.push(schemaIndex)
            }
            // single column index
            else {
                // get first and only column
                var indexColumn = indexColumns[0]
                // PRIMARY KEY
                if (name === 'PRIMARY') {
                    schema.columns[indexColumn].primary = true
                }
                // unique index
                else if (index.unique) {
                    schema.columns[indexColumn].unique = true
                }
                // non-unique index
                else {
                    schema.columns[indexColumn].index = true
                }
            }
        })
        // resolve with schema
        return schema
    })
    .catch(err => {
        // reject on anything besides a table does not exist error
        // if table does not exist resolve with undefined
        if (err.errno !== 1146) {
            throw err
        }
    })
}
153806
def process_schema(doc, resource, df):
    """"""
    from rowgenerators import SourceError
    from requests.exceptions import ConnectionError

    from metapack.cli.core import extract_path_name, alt_col_name, type_map
    from tableintuit import TypeIntuiter
    from rowgenerators.generator.python import PandasDataframeSource
    from appurl import parse_app_url

    try:
        doc['Schema']
    except KeyError:
        doc.new_section('Schema', ['DataType', 'Altname', 'Description'])

    schema_name = resource.get_value('schema', resource.get_value('name'))

    schema_term = doc.find_first(term='Table', value=schema_name, section='Schema')

    if schema_term:
        logger.info("Found table for '{}'; skipping".format(schema_name))
        return

    path, name = extract_path_name(resource.url)

    logger.info("Processing {}".format(resource.url))

    si = PandasDataframeSource(parse_app_url(resource.url), df, cache=doc._cache, )

    try:
        ti = TypeIntuiter().run(si)
    except SourceError as e:
        logger.warn("Failed to process '{}'; {}".format(path, e))
        return
    except ConnectionError as e:
        logger.warn("Failed to download '{}'; {}".format(path, e))
        return

    table = doc['Schema'].new_term('Table', schema_name)

    logger.info("Adding table '{}' to metatab schema".format(schema_name))

    for i, c in enumerate(ti.to_rows()):
        raw_alt_name = alt_col_name(c['header'], i)
        alt_name = raw_alt_name if raw_alt_name != c['header'] else ''

        t = table.new_child('Column', c['header'],
                            datatype=type_map.get(c['resolved_type'], c['resolved_type']),
                            altname=alt_name,
                            description=df[c['header']].description \
                                        if hasattr(df, 'description') and df[c['header']].description else ''
                            )

    return table
727124
def _read_schema(self):
        """"""
        cache_filename = os.path.join(
            CACHE_ROOT, "%s.smt" % self._representation)
        log.info("Attempting to read local schema at %s" % cache_filename)
        try:
            if time.time() - os.stat(cache_filename).st_mtime > CACHE_EXPIRY:
                log.warning("Cache expired, re-pulling")
                self._pull_schema_definition(cache_filename)
        except OSError:
            log.warning("Local schema not found. Pulling from web.")
            self._pull_schema_definition(cache_filename)
        else:
            log.info("Success")

        return cache_filename
1254569
def sql(self, sql, *params):
        """"""
        self.ops.append(self.migrator.sql(sql, *params))
1228730
def tables(self, db_id, schema, substr, force_refresh='false'):
        """"""
        db_id = int(db_id)
        force_refresh = force_refresh.lower() == 'true'
        schema = utils.js_string_to_python(schema)
        substr = utils.js_string_to_python(substr)
        database = db.session.query(models.Database).filter_by(id=db_id).one()

        if schema:
            table_names = database.all_table_names_in_schema(
                schema=schema, force=force_refresh,
                cache=database.table_cache_enabled,
                cache_timeout=database.table_cache_timeout)
            view_names = database.all_view_names_in_schema(
                schema=schema, force=force_refresh,
                cache=database.table_cache_enabled,
                cache_timeout=database.table_cache_timeout)
        else:
            table_names = database.all_table_names_in_database(
                cache=True, force=False, cache_timeout=24 * 60 * 60)
            view_names = database.all_view_names_in_database(
                cache=True, force=False, cache_timeout=24 * 60 * 60)
        table_names = security_manager.accessible_by_user(database, table_names, schema)
        view_names = security_manager.accessible_by_user(database, view_names, schema)

        if substr:
            table_names = [tn for tn in table_names if substr in tn]
            view_names = [vn for vn in view_names if substr in vn]

        if not schema and database.default_schemas:
            def get_schema(tbl_or_view_name):
                return tbl_or_view_name.split('.')[0] if '.' in tbl_or_view_name else None

            user_schema = g.user.email.split('@')[0]
            valid_schemas = set(database.default_schemas + [user_schema])

            table_names = [tn for tn in table_names if get_schema(tn) in valid_schemas]
            view_names = [vn for vn in view_names if get_schema(vn) in valid_schemas]

        max_items = config.get('MAX_TABLE_NAMES') or len(table_names)
        total_items = len(table_names) + len(view_names)
        max_tables = len(table_names)
        max_views = len(view_names)
        if total_items and substr:
            max_tables = max_items * len(table_names) // total_items
            max_views = max_items * len(view_names) // total_items

        table_options = [{'value': tn, 'label': tn}
                         for tn in table_names[:max_tables]]
        table_options.extend([{'value': vn, 'label': '[view] {}'.format(vn)}
                              for vn in view_names[:max_views]])
        payload = {
            'tableLength': len(table_names) + len(view_names),
            'options': table_options,
        }
        return json_success(json.dumps(payload))
758348
def load_schema(schema):
    
    with repo.Repo.db:
        repo.Repo.db.executescript(schema)
164310
function getSchema(connection) {
  return runQuery(SCHEMA_SQL_V1, connection)
    .then(queryResult => formatSchemaQueryResults(queryResult))
    .catch(() =>
      runQuery(SCHEMA_SQL_V0, connection).then(queryResult =>
        formatSchemaQueryResults(queryResult)
      )
    );
}
115324
def load_schema(file_or_fp):
    
    fp = open(file_or_fp, 'r') if isinstance(file_or_fp, str) else file_or_fp
    obj = json.load(fp)
    schema = Schema(obj)
    return schema
1374431
void loadSchema(Reader reader, Database db, DdlProceduresToLoad whichProcs)
            throws VoltCompiler.VoltCompilerException {
        int currLineNo = 1;

        DDLStatement stmt = getNextStatement(reader, m_compiler, currLineNo);
        while (stmt != null) {
            // Some statements are processed by VoltDB and the rest are handled by HSQL.
            processVoltDBStatements(db, whichProcs, stmt);
            stmt = getNextStatement(reader, m_compiler, stmt.endLineNo);
        }

        try {
            reader.close();
        } catch (IOException e) {
            throw m_compiler.new VoltCompilerException("Error closing schema file");
        }

        // process extra classes
        m_tracker.addExtraClasses(m_classMatcher.getMatchedClassList());
        // possibly save some memory
        m_classMatcher.clear();
    }
145943
def create_db_schema(cls, cur, schema_name):
        
        create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
        cur.execute(create_schema_script)
763545
public static String getSqlFile(String fileName) {
		String file = "/jk/sql/".concat(fileName);
		logger.debug("Loading sql file: ", file);
		return readFile(file);
	}
692009
def getSchema(cls):
        
        schema = []
        for name, atr in cls.__attributes__:
            atr = atr.__get__(None, cls)
            if isinstance(atr, SQLAttribute):
                schema.append((name, atr))
        cls.getSchema = staticmethod(lambda schema=schema: schema)
        return schema