Returns SQL scripts for dropping existed old JCR tables.
510773
protected Collection<String> getOldTablesDroppingScripts()
   {
      List<String> scripts = new ArrayList<String>();

      scripts.add("DROP TABLE " + valueTableName + "_OLD");
      scripts.add("DROP TABLE " + refTableName + "_OLD");
      scripts.add("DROP TABLE " + itemTableName + "_OLD");

      return scripts;
   }
1355514
def _purge_jobs(timestamp):
    '''
    
    '''
    with _get_serv() as cursor:
        try:
            sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
            cursor.execute(sql, (timestamp,))
            cursor.execute('COMMIT')
        except psycopg2.DatabaseError as err:
            error = err.args
            sys.stderr.write(six.text_type(error))
            cursor.execute("ROLLBACK")
            raise err

        try:
            sql = 'delete from salt_returns where alter_time < %s'
            cursor.execute(sql, (timestamp,))
            cursor.execute('COMMIT')
        except psycopg2.DatabaseError as err:
            error = err.args
            sys.stderr.write(six.text_type(error))
            cursor.execute("ROLLBACK")
            raise err

        try:
            sql = 'delete from salt_events where alter_time < %s'
            cursor.execute(sql, (timestamp,))
            cursor.execute('COMMIT')
        except psycopg2.DatabaseError as err:
            error = err.args
            sys.stderr.write(six.text_type(error))
            cursor.execute("ROLLBACK")
            raise err

    return True
781783
def get_new_oids(self):
        '''
        
        '''
        table = self.lconfig.get('table')
        _oid = self.lconfig.get('_oid')
        if is_array(_oid):
            _oid = _oid[0]  # get the db column, not the field alias
        last_id = self.container.get_last_field(field='_oid')
        ids = []
        if last_id:
            try:  # try to convert to integer... if not, assume unicode value
                last_id = float(last_id)
                where = "%s.%s > %s" % (table, _oid, last_id)
            except (TypeError, ValueError):
                where = "%s.%s > '%s'" % (table, _oid, last_id)
            ids = self.sql_get_oids(where)
        return ids
1123279
public void blankExistingTables() {
        Connection connection = null;
        Statement s = null;
        try {
            connection = SQLUtility.getDefaultConnection(m_serverConfig);
            List<String> existingTables = getExistingTables(connection);
            List<String> fedoraTables = getFedoraTables();
            s = connection.createStatement();
            for (String origTableName: existingTables) {
                String tableName = origTableName.toUpperCase();
                if (fedoraTables.contains(tableName)
                        && !tableName.startsWith("RI")) {
                    System.out.println("Cleaning up table: " + origTableName);
                    try {
                        s.executeUpdate("DELETE FROM " + origTableName);
                    } catch (Exception lle) {
                        System.err.println(lle.getMessage());
                        System.err.flush();
                    }
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("DB error while blanking existing tables",
                                       e);
        } finally {
            try {
            	if (s != null) {
            		s.close();
            		s = null;
            	}
                connection.close();
            } catch (Exception e) {
            }
        }
    }
296815
def clean_and_split_sql(sql: str) -> List[str]:
    
    sql_tokens: List[str] = []
    for token in sql.strip().split():
        token = token.replace('"', "'").replace("%", "")
        if token.endswith("(") and len(token) > 1:
            sql_tokens.extend(split_table_and_column_names(token[:-1]))
            sql_tokens.extend(split_table_and_column_names(token[-1]))
        else:
            sql_tokens.extend(split_table_and_column_names(token))
    return sql_tokens
889633
def sql_reset(app, style, connection):
    ""
    return sql_delete(app, style, connection) + sql_all(app, style, connection)
1301024
@Override
    public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
668122
public static DBCleanerTool getRepositoryDBCleaner(Connection jdbcConn, RepositoryEntry rEntry)
      throws DBCleanException
   {
      SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

      WorkspaceEntry wsEntry = rEntry.getWorkspaceEntries().get(0);

      boolean multiDb = getMultiDbParameter(wsEntry);
      if (multiDb)
      {
         throw new DBCleanException(
            "It is not possible to create cleaner with common connection for multi database repository configuration");
      }

      String dialect = resolveDialect(jdbcConn, wsEntry);
      boolean autoCommit = dialect.startsWith(DialectConstants.DB_DIALECT_SYBASE);

      DBCleaningScripts scripts = DBCleaningScriptsFactory.prepareScripts(dialect, rEntry);

      return new DBCleanerTool(jdbcConn, autoCommit, scripts.getCleaningScripts(), scripts.getCommittingScripts(),
         scripts.getRollbackingScripts());
   }
1125953
def deleted_ids
      sql = <<-DR.squish
        SELECT object_id
        FROM rails_redshift_replicator_deleted_ids
        WHERE source_table = '#{replicable.source_table}'
      DR
      ActiveRecord::Base.connection.execute(sql).map{ |r| r['object_id'] }
    end
876324
protected Collection<String> getDBInitializationScripts() throws DBCleanException
   {
      String dbScripts;
      try
      {
         dbScripts = DBInitializerHelper.prepareScripts(wsEntry, dialect);
      }
      catch (IOException e)
      {
         throw new DBCleanException(e);
      }
      catch (RepositoryConfigurationException e)
      {
         throw new DBCleanException(e);
      }

      List<String> scripts = new ArrayList<String>();
      for (String query : JDBCUtils.splitWithSQLDelimiter(dbScripts))
      {
         if (query.contains(itemTableName + "_SEQ") || query.contains(itemTableName + "_NEXT_VAL"))
         {
            continue;
         }
         scripts.add(JDBCUtils.cleanWhitespaces(query));
      }

      scripts.add(DBInitializerHelper.getRootNodeInitializeScript(itemTableName, multiDb));

      return scripts;
   }
752403
private function dropObsoleteRoutines(): void
  {
    // Make a lookup table from routine name to source.
    $lookup = [];
    foreach ($this->sources as $source)
    {
      $lookup[$source['routine_name']] = $source;
    }

    // Drop all routines not longer in sources.
    foreach ($this->rdbmsOldMetadata as $old_routine)
    {
      if (!isset($lookup[$old_routine['routine_name']]))
      {
        $this->io->logInfo('Dropping %s <dbo>%s</dbo>',
                           strtolower($old_routine['routine_type']),
                           $old_routine['routine_name']);

        DataLayer::dropRoutine($old_routine['routine_type'], $old_routine['routine_name']);
      }
    }
  }
1026607
protected Collection<String> getFKAddingScripts()
   {
      List<String> scripts = new ArrayList<String>();

      String constraintName =
         "JCR_FK_" + itemTableSuffix + "_PARENT FOREIGN KEY(PARENT_ID) REFERENCES " + itemTableName + "(ID)";
      scripts.add("ALTER TABLE " + itemTableName + " ADD CONSTRAINT " + constraintName);

      return scripts;
   }
789665
protected function getTableMigrationOldTablesColumns($output, $tableName, $new, $old)
    {
        if (empty($old['tables'][$tableName]['columns'])) {
            return $output;
        }
        foreach ($old['tables'][$tableName]['columns'] as $oldColumnName => $oldColumnData) {
            if (!isset($new['tables'][$tableName]['columns'][$oldColumnName])) {
                $output[] = $this->getColumnRemove($tableName, $oldColumnName);
            }
        }

        return $output;
    }
1026147
def drop(self, table):
        
        existing_tables = self.tables
        if isinstance(table, (list, set, tuple)):
            for t in table:
                self._drop(t, existing_tables)
        else:
            self._drop(table, existing_tables)
        return table
69765
def get_alter_table_sql(self, diff):
        
        sql = []

        for column_diff in diff.changed_columns.values():
            if self.is_unchanged_binary_column(column_diff):
                continue

            old_column_name = column_diff.old_column_name
            column = column_diff.column

            if any([column_diff.has_changed('type'),
                    column_diff.has_changed('precision'),
                    column_diff.has_changed('scale'),
                    column_diff.has_changed('fixed')]):
                query = 'ALTER ' + old_column_name + ' TYPE ' + self.get_sql_type_declaration(column.to_dict())
                sql.append('ALTER TABLE ' + diff.name + ' ' + query)

            if column_diff.has_changed('default') or column_diff.has_changed('type'):
                if column.get_default() is None:
                    default_clause = ' DROP DEFAULT'
                else:
                    default_clause = ' SET' + self.get_default_value_declaration_sql(column.to_dict())

                query = 'ALTER ' + old_column_name + default_clause
                sql.append('ALTER TABLE ' + diff.name + ' ' + query)

            if column_diff.has_changed('notnull'):
                op = 'DROP'
                if column.get_notnull():
                    op = 'SET'

                query = 'ALTER ' + old_column_name + ' ' + op + ' NOT NULL'
                sql.append('ALTER TABLE ' + diff.name + ' ' + query)

            if column_diff.has_changed('autoincrement'):
                if column.get_autoincrement():
                    seq_name = self.get_identity_sequence_name(diff.name, old_column_name)

                    sql.append('CREATE SEQUENCE ' + seq_name)
                    sql.append('SELECT setval(\'' + seq_name + '\', '
                               '(SELECT MAX(' + old_column_name + ') FROM ' + diff.name + '))')
                    query = 'ALTER ' + old_column_name + ' SET DEFAULT nextval(\'' + seq_name + '\')'
                    sql.append('ALTER TABLE ' + diff.name + ' ' + query)
                else:
                    query = 'ALTER ' + old_column_name + ' DROP DEFAULT'
                    sql.append('ALTER TABLE ' + diff.name + ' ' + query)

            if column_diff.has_changed('length'):
                query = 'ALTER ' + old_column_name + ' TYPE ' + self.get_sql_type_declaration(column.to_dict())
                sql.append('ALTER TABLE ' + diff.name + ' ' + query)

        for old_column_name, column in diff.renamed_columns.items():
            sql.append('ALTER TABLE ' + diff.name + ' '
                       'RENAME COLUMN ' + old_column_name + ' TO ' + column.get_name())

        return sql
973608
def get_jids():
    '''
    
    '''
    conn = _get_conn()
    cur = conn.cursor()
    sql = '''SELECT ''' \
          '''jid, tgt_type, cmd, tgt, kwargs, ret, username, arg, fun ''' \
          '''FROM jids'''
    if __opts__['keep_jobs'] != 0:
        sql = sql + " WHERE started > NOW() - INTERVAL '" \
                + six.text_type(__opts__['keep_jobs']) + "' HOUR"

    cur.execute(sql)
    ret = {}
    data = cur.fetchone()
    while data:
        data_dict = _build_dict(data)
        ret[data_dict["jid"]] = \
            _format_jid_instance(data_dict["jid"], data_dict)
        data = cur.fetchone()
    cur.close()
    conn.close()
    return ret
25185
def delete_tables_partitions(self, ds):
        """"""
        from ambry.orm import Code, Column, Table, Partition, ColumnStat, Process

        ssq = self.session.query

        ssq(Process).filter(Process.d_vid == ds.vid).delete()
        ssq(Code).filter(Code.d_vid == ds.vid).delete()
        ssq(ColumnStat).filter(ColumnStat.d_vid == ds.vid).delete()
        ssq(Column).filter(Column.d_vid == ds.vid).delete()
        ssq(Partition).filter(Partition.d_vid == ds.vid).delete()

        for source in ds.sources:
            source._dest_table = None

        ssq(Table).filter(Table.d_vid == ds.vid).delete()