from DatabaseLiaison
485340
public boolean changeColumn (Connection conn, String table, String column, String type,
                                 Boolean nullable, Boolean unique, String defaultValue)
        throws SQLException
    {
        String defStr = expandDefinition(type, nullable != null ? nullable : false,
                                         unique != null ? unique : false, defaultValue);

        executeQuery(conn, "ALTER TABLE " + tableSQL(table) + " CHANGE " +
                     columnSQL(column) + " " + columnSQL(column) + " " + defStr);
        log("Database column '" + column + "' of table '" + table + "' modified to have " +
            "definition '" + defStr + "'.");
        return true;
    }
818993
private void checkJdbcSupport(DatabaseMetaData metaData) throws SQLException {

        if (_getGeneratedKeys && !metaData.supportsGetGeneratedKeys()) {
            throw new ControlException("The database does not support getGeneratedKeys.");
        }

        if (_batchUpdate && !metaData.supportsBatchUpdates()) {
            throw new ControlException("The database does not support batchUpdates.");
        }

        if (_scrollType != JdbcControl.ScrollType.DRIVER_DEFAULT
                && !metaData.supportsResultSetConcurrency(_scrollType.getType(), _scrollType.getConcurrencyType())) {
            throw new ControlException("The database does not support the ResultSet concurrecy type: " + _scrollType.toString());
        }

        if (_holdability != JdbcControl.HoldabilityType.DRIVER_DEFAULT
                && !metaData.supportsResultSetHoldability(_holdability.getHoldability())) {
            throw new ControlException("The database does not support the ResultSet holdability type: " + _holdability.toString());
        }
    }
120686
def main():
    

    DATABASE.load_contents()

    continue_flag = False

    while not continue_flag:
        DATABASE.print_contents()
        try:
            command = raw_input(">>> ")
            for stmnt_unformated in sqlparse.parse(command):
                statement = sqlparse.parse(
                    sqlparse.format(
                        str(
                            stmnt_unformated
                        ),
                        reindent=True
                    )
                )[0]
                type = statement.tokens[0]

                if str(type).lower() == "drop":
                    if str(statement.tokens[2]).lower() == "table":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        table.rows = []
                        table.store_contents()
                        DATABASE.delete_table(tablename)
                        DATABASE.store_contents()
                    else:
                        raise Exception(
                            "Invalid Syntax of DROP TABLE t"
                        )
                elif str(type).lower() == "truncate":
                    if str(statement.tokens[2]).lower() == "table":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        table.rows = []
                        table.store_contents()
                    else:
                        raise Exception(
                            "Invalid Syntax of TRUNCATE TABLE t"
                        )
                elif str(type).lower() == "delete":
                    if str(statement.tokens[2]).lower() == "from":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        whereclause = statement.tokens[6]
                        if str(whereclause.tokens[0]).lower() == "where":
                            comparison = whereclause.tokens[2]
                            key = str(comparison.tokens[0])
                            value = int(str(comparison.tokens[4]))
                            table.delete_row(key, value)
                            table.store_contents()
                        else:
                            raise Exception(
                                "Invalid Syntax of DELETE FROM t where k = v"
                            )

                    else:
                        raise Exception(
                            "Invalid Syntax of DELETE FROM t WHERE k = v"
                        )
                elif str(type).lower() == "insert":
                    if str(statement.tokens[2]).lower() == "into":
                        tablename = str(statement.tokens[4])
                        table = DATABASE.get_table(tablename)
                        if str(statement.tokens[6]).lower() == "values":
                            parenthesis = statement.tokens[8]
                            idlist = parenthesis.tokens[1]
                            values_list = map(
                                lambda x: int(str(x)),
                                idlist.get_identifiers()
                            )
                            table.put_row_raw(values_list)
                            table.store_contents()
                        else:
                            raise Exception(
                                "Invalid Syntax of INSERT INTO t VALUES (v...)"
                            )
                    else:
                        raise Exception(
                            "Invalid Syntax of INSERT INTO t VALUES (v...)"
                        )
                elif str(type).lower() == "create":
                    if str(statement.tokens[2]).lower() == "table":
                        sublist = list(statement.tokens[4].get_sublists())
                        tablename = str(sublist[0])
                        garbage = str(sublist[1])
                        column_list = map(
                            lambda x: x.strip(" ()",).split()[0],
                            garbage.split(",")
                        )
                        DATABASE.create_table_raw(
                            tablename=tablename,
                            columns=column_list[:],
                        )
                        DATABASE.store_contents()
                elif str(type).lower() == "select":
                    col_list_or_single = statement.tokens[2]
                    if "," not in str(col_list_or_single):
                        if str(col_list_or_single) == "*":
                            column_list = ['*']
                        else:
                            column_list = [str(col_list_or_single)]
                    else:
                        column_list = map(
                            lambda x: str(x),
                            col_list_or_single.get_identifiers()
                        )
                    if str(statement.tokens[4]).lower() == "from":
                        tab_list_or_single = statement.tokens[6]
                        if "," not in str(tab_list_or_single):
                            table_list = [str(tab_list_or_single)]
                        else:
                            table_list = map(
                                lambda x: str(x),
                                tab_list_or_single.get_identifiers()
                            )
                        cross_columns = reduce(
                            lambda x, y: x + y,
                            map(
                                lambda x: DATABASE.get_table(
                                    x
                                ).get_column_list_prefixed(),
                                table_list
                            )
                        )
                        cross_table = parthsql.Table(
                            name="temp",
                            columns=cross_columns,
                            rows=[]
                        )
                        for i in itertools.product(
                            *map(
                                lambda x: DATABASE.get_table(x).get_all_rows(),
                                table_list
                            )
                        ):
                            cross_table.put_row_raw(
                                reduce(
                                    lambda x, y: x + y,
                                    i
                                )
                            )

                        if len(statement.tokens) >= 9:
                            whereclause = statement.tokens[8]
                            if str(whereclause.tokens[0]).lower() == "where":
                                comparison = whereclause.tokens[2]
                                key = str(comparison.tokens[0])
                                try:
                                    value = int(str(comparison.tokens[4]))
                                    cross_table.invert_delete_row(key, value)
                                except:
                                    value = str(comparison.tokens[4])
                                    cross_table.invert_delete_row2(key, value)
                            else:
                                raise Exception(
                                    "Invalid Syntax of DELETE FROM t where k = v"
                                )

                        if "*" in column_list:
                            cross_table.print_contents()
                        else:
                            temp_list = []
                            for i in column_list:
                                temp_list.append(cross_table.get_column(i))
                            print "\t\t\t".join(column_list)
                            for i in zip(*(temp_list)):
                                print "\t\t\t".join(map(str, i))
                    else:
                        raise Exception(
                            "Invalid Syntax of SELECT c... FROM t... WHERE k = v"
                        )
                else:
                    raise Exception(
                        "Unsupported Operation"
                    )
        except ValueError:
            print("¯\_(ツ)_/¯")
        except IOError:
            print("¯\_(ツ)_/¯")
        except IndexError:
            print("¯\_(ツ)_/¯")
        except AttributeError:
            print("¯\_(ツ)_/¯")
        except Exception, e:
            print e.message
697615
@Override
   public SqlStatement[] generateStatements(final Database database) {
      final Collection<SqlStatement> statements = new ArrayList<SqlStatement>();
      // MySQL and PostgreSQL only need the normal DROP INDEX statement.
      if (!(database instanceof MySQLDatabase) && !(database instanceof PostgresDatabase)) {
         final DropSpatialIndexStatement dropSpatialIndex = new DropSpatialIndexStatement(
               this.indexName, this.catalogName, this.schemaName, this.tableName);
         statements.add(dropSpatialIndex);
      }

      // GeoDB doesn't use a tradition index structure so don't issue the normal DROP INDEX
      // statement.
      if (!(database instanceof DerbyDatabase) && !(database instanceof H2Database)) {
         final DropIndexStatement dropIndex = new DropIndexStatement(this.indexName,
               this.catalogName, this.schemaName, this.tableName, null);
         statements.add(dropIndex);
      }
      return statements.toArray(new SqlStatement[statements.size()]);
   }
1148760
public static void sqldatabase(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
    zeroArgumentFunctionCall(buf, "current_database()", "database", parsedArgs);
  }
996299
public List<String> getDatabaseDdl(String instanceId, String databaseId) {
    // [START getDatabaseDdl]
    List<String> statementsInDb = dbAdminClient.getDatabaseDdl(instanceId, databaseId);
    // [END getDatabaseDdl]
    return statementsInDb;
  }
1360864
@InterfaceAudience.Private
    public Database getDatabase(String name, boolean mustExist) {
        synchronized (lockDatabases) {
            if (options.isReadOnly())
                mustExist = true;
            Database db = databases.get(name);
            if (db == null) {
                if (!isValidDatabaseName(name))
                    throw new IllegalArgumentException("Invalid database name: " + name);
                String path = pathForDatabaseNamed(name);
                if (path == null)
                    return null;
                db = new Database(path, name, this, options.isReadOnly());
                if (mustExist && !db.exists()) {
                    Log.i(Database.TAG, "mustExist is true and db (%s) does not exist", name);
                    return null;
                }
                db.setName(name);
                databases.put(name, db);
            }
            Log.v(Log.TAG_DATABASE, "getDatabase() %s %s", this, db);
            return db;
        }
    }
1199638
private Referenceable getDatabaseReference(String clusterName, String databaseName) throws Exception {
        LOG.debug("Getting reference for database {}", databaseName);
        String typeName = HiveDataTypes.HIVE_DB.getName();

        return getEntityReference(typeName, getDBQualifiedName(clusterName, databaseName));
    }
285971
public Database getDatabase(String strDBName, int iDatabaseType, Map<String, Object> properties)
    {
        if ((strDBName == null) || (strDBName.length() == 0))
            return null;
        Database database = this.getDatabaseList(iDatabaseType).get(strDBName);
        if (database == null)
        {
            if ((properties != null)
            	&& (DBConstants.FALSE.equals(properties.get(DBConstants.CREATE_DB_IF_NOT_FOUND)))
            	&& (Environment.DATABASE_DOESNT_EXIST == ((Environment)m_databaseOwner.getEnvironment()).getCachedDatabaseProperties(strDBName)))
            		return null;	// Hey, if the database doesn't exist, don't try again.
            if (iDatabaseType != DBConstants.SCREEN)
                database = this.makeDatabase(iDatabaseType);    // BaseDatabase not found, open it!
            else
                database = new BaseDatabase();                  // Special case: A screen database
            if (database != null)
                database.init(m_databaseOwner, strDBName, iDatabaseType & DBConstants.TABLE_MASK, properties); // init it!
            if (database != null)
            {
                try   {
                    ((BaseDatabase)database).open();    // open it!
                } catch (DBException ex) {
                    database.free();
                    database = null;    // Failure on db open
                    if ((ex.getErrorCode() == DBConstants.DB_NOT_FOUND)
                		&& (properties != null)
                        && (DBConstants.FALSE.equals(properties.get(DBConstants.CREATE_DB_IF_NOT_FOUND))))
                    {	// If the db doesn't exist, cache the name so I won't try this (expensive) operation again
                        ((Environment)m_databaseOwner.getEnvironment()).cacheDatabaseProperties(strDBName, Environment.DATABASE_DOESNT_EXIST);
                    }
                }
            }
        }
        return database;
    }
250942
protected void readDatabaseConfig() {

        m_databaseKeys = new ArrayList<String>();
        m_databaseProperties = new HashMap<String, Properties>();

        FileInputStream input = null;
        File childResource = null;

        List<String> databaseKeys = new ArrayList<String>();
        Map<String, Properties> databaseProperties = new HashMap<String, Properties>();

        try {
            File databaseSetupFolder = new File(m_webAppRfsPath + FOLDER_SETUP + FOLDER_DATABASE);

            File[] childResources = databaseSetupFolder.listFiles();

            // collect all possible db configurations
            if (childResources != null) {
                for (int i = 0; i < childResources.length; i++) {
                    childResource = childResources[i];
                    if (childResource.exists() && childResource.isDirectory() && childResource.canRead()) {
                        databaseKeys.add(childResource.getName().trim());
                    }
                }
            }

            // create the properties with all possible configurations
            if (databaseSetupFolder.exists()) {
                for (String key : databaseKeys) {
                    String dbDir = m_webAppRfsPath + CmsSetupBean.FOLDER_SETUP + "database" + File.separatorChar + key;
                    String configPath = dbDir + File.separatorChar + "database.properties";
                    try {
                        input = new FileInputStream(new File(configPath));
                        Properties databaseProps = new Properties();
                        databaseProps.load(input);
                        databaseProperties.put(key, databaseProps);
                    } catch (Exception e) {
                        System.err.println(e.toString());
                        e.printStackTrace(System.err);
                        continue;
                    }
                }
            }

            // add the properties and the keys to the memeber variables if all needed files exist
            if (childResources != null) {
                for (int i = 0; i < childResources.length; i++) {
                    childResource = childResources[i];
                    if (childResource.exists() && childResource.isDirectory() && childResource.canRead()) {
                        String dataBasekey = childResource.getName().trim();
                        Properties props = databaseProperties.get(dataBasekey);
                        if (checkFilesExists(REQUIRED_SQL_DB_SETUP_FILES, childResource)) {
                            m_databaseKeys.add(childResource.getName().trim());
                            m_databaseProperties.put(dataBasekey, props);
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.toString());
            e.printStackTrace(System.err);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                // noop
            }
        }
    }
615399
static List<String> getAllTables(String database, Statement stmt) throws SQLException {
        List<String> table = new ArrayList<>();
        ResultSet rs;
        rs = stmt.executeQuery("SHOW TABLE STATUS FROM `" + database + "`;");
        while ( rs.next() ) {
            table.add(rs.getString("Name"));
        }
        return table;
    }
355802
public void init(DatabaseOwner databaseOwner, String strDbName, int iDatabaseType, Map<String, Object> properties)
    {
        m_databaseOwner = databaseOwner;
        m_strDbName = strDbName;
        m_iDatabaseType = iDatabaseType;
        m_vTableList = new Vector<BaseTable>();
        m_iMasterSlave = RecordOwner.MASTER | RecordOwner.SLAVE;
        m_bAutosequenceSupport = true;
        if (m_properties == null)
            m_properties = new Hashtable<String,Object>();
        if (properties != null)
        	m_properties.putAll(properties);

        m_databaseOwner.addDatabase(this);
    }
763338
def db_tables(name, **connection_args):
    '''
    
    '''
    if not db_exists(name, **connection_args):
        log.info('Database \'%s\' does not exist', name)
        return False

    dbc = _connect(**connection_args)
    if dbc is None:
        return []
    cur = dbc.cursor()
    s_name = quote_identifier(name)
    # identifiers cannot be used as values
    qry = 'SHOW TABLES IN {0}'.format(s_name)
    try:
        _execute(cur, qry)
    except MySQLdb.OperationalError as exc:
        err = 'MySQL Error {0}: {1}'.format(*exc.args)
        __context__['mysql.error'] = err
        log.error(err)
        return []

    ret = []
    results = cur.fetchall()
    for table in results:
        ret.append(table[0])
    log.debug(ret)
    return ret
647453
private void executeJdbcStatements(Connection connection, String configName, String statements, String description) {
        Statement stmt = createStatement(configName, connection);
        try {
            log.debug("Executing statement [" + description + "]");
            
            List<String> stmtsToExecute = Stream.of(statements.split(";"))
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
            
            if ( log.isTraceEnabled()) {
                log.trace("These statements will be executed:");
                stmtsToExecute.forEach(s -> log.trace("Statement: [" + s + "]"));
            }
            
            for ( String currentStatement : stmtsToExecute) {
                stmt.execute(currentStatement);
                log.trace("Executing statement: " + currentStatement + " OK!");
            }
            
        } catch (SQLException e) {
            throw new ChorusException(
                    String.format("Failed while executing statement [%s] on database + %s [%s]", description, configName, e.toString(), e)
            );
        }
    }
215096
protected String checkForMariaDb(DatabaseMetaData databaseMetaData, String databaseName) {
    try {
      String databaseProductVersion = databaseMetaData.getDatabaseProductVersion();
      if (databaseProductVersion != null && databaseProductVersion.toLowerCase().contains("mariadb")) {
        return MARIA_DB_PRODUCT_NAME;
      }
    } catch (SQLException ignore) {
    }

    try {
      String driverName = databaseMetaData.getDriverName();
      if (driverName != null && driverName.toLowerCase().contains("mariadb")) {
        return MARIA_DB_PRODUCT_NAME;
      }
    } catch (SQLException ignore) {
    }

    String metaDataClassName = databaseMetaData.getClass().getName();
    if (metaDataClassName != null && metaDataClassName.toLowerCase().contains("mariadb")) {
      return MARIA_DB_PRODUCT_NAME;
    }

    return databaseName;
  }
2205
@Override
    public DataSet executeStatement(String stmt) throws JdbcServerException {
        log.info("Received execute statement request: " + stmt);
        Message response = handleMessageAndCheckResponse(JdbcMessage.execute(stmt));
        return dataSetCreator.createDataSet(response, getMessageType(response));
    }
1138694
def sql_json(self):
        """"""
        async_ = request.form.get('runAsync') == 'true'
        sql = request.form.get('sql')
        database_id = request.form.get('database_id')
        schema = request.form.get('schema') or None
        template_params = json.loads(
            request.form.get('templateParams') or '{}')
        limit = int(request.form.get('queryLimit', 0))
        if limit < 0:
            logging.warning(
                'Invalid limit of {} specified. Defaulting to max limit.'.format(limit))
            limit = 0
        limit = limit or app.config.get('SQL_MAX_ROW')

        session = db.session()
        mydb = session.query(models.Database).filter_by(id=database_id).first()

        if not mydb:
            json_error_response(
                'Database with id {} is missing.'.format(database_id))

        rejected_tables = security_manager.rejected_datasources(sql, mydb, schema)
        if rejected_tables:
            return json_error_response(
                security_manager.get_table_access_error_msg(rejected_tables),
                link=security_manager.get_table_access_link(rejected_tables),
                status=403)
        session.commit()

        select_as_cta = request.form.get('select_as_cta') == 'true'
        tmp_table_name = request.form.get('tmp_table_name')
        if select_as_cta and mydb.force_ctas_schema:
            tmp_table_name = '{}.{}'.format(
                mydb.force_ctas_schema,
                tmp_table_name,
            )

        client_id = request.form.get('client_id') or utils.shortid()[:10]
        query = Query(
            database_id=int(database_id),
            sql=sql,
            schema=schema,
            select_as_cta=select_as_cta,
            start_time=now_as_float(),
            tab_name=request.form.get('tab'),
            status=QueryStatus.PENDING if async_ else QueryStatus.RUNNING,
            sql_editor_id=request.form.get('sql_editor_id'),
            tmp_table_name=tmp_table_name,
            user_id=g.user.get_id() if g.user else None,
            client_id=client_id,
        )
        session.add(query)
        session.flush()
        query_id = query.id
        session.commit()  # shouldn't be necessary
        if not query_id:
            raise Exception(_('Query record was not created as expected.'))
        logging.info('Triggering query_id: {}'.format(query_id))

        try:
            template_processor = get_template_processor(
                database=query.database, query=query)
            rendered_query = template_processor.process_template(
                query.sql,
                **template_params)
        except Exception as e:
            return json_error_response(
                'Template rendering failed: {}'.format(utils.error_msg_from_exception(e)))

        # set LIMIT after template processing
        limits = [mydb.db_engine_spec.get_limit_from_sql(rendered_query), limit]
        query.limit = min(lim for lim in limits if lim is not None)

        # Async request.
        if async_:
            logging.info('Running query on a Celery worker')
            # Ignore the celery future object and the request may time out.
            try:
                sql_lab.get_sql_results.delay(
                    query_id,
                    rendered_query,
                    return_results=False,
                    store_results=not query.select_as_cta,
                    user_name=g.user.username if g.user else None,
                    start_time=now_as_float())
            except Exception as e:
                logging.exception(e)
                msg = _(
                    'Failed to start remote query on a worker. '
                    'Tell your administrator to verify the availability of '
                    'the message queue.')
                query.status = QueryStatus.FAILED
                query.error_message = msg
                session.commit()
                return json_error_response('{}'.format(msg))

            resp = json_success(json.dumps(
                {'query': query.to_dict()}, default=utils.json_int_dttm_ser,
                ignore_nan=True), status=202)
            session.commit()
            return resp

        # Sync request.
        try:
            timeout = config.get('SQLLAB_TIMEOUT')
            timeout_msg = (
                f'The query exceeded the {timeout} seconds timeout.')
            with utils.timeout(seconds=timeout,
                               error_message=timeout_msg):
                # pylint: disable=no-value-for-parameter
                data = sql_lab.get_sql_results(
                    query_id,
                    rendered_query,
                    return_results=True,
                    user_name=g.user.username if g.user else None)
            payload = json.dumps(
                data,
                default=utils.pessimistic_json_iso_dttm_ser,
                ignore_nan=True,
                encoding=None,
            )
        except Exception as e:
            logging.exception(e)
            return json_error_response('{}'.format(e))
        if data.get('status') == QueryStatus.FAILED:
            return json_error_response(payload=data)
        return json_success(payload)