// CleanTables, drop tables if stored chainID is different from the given one & store new chainID
// if the chainID is the same, do nothing
178272
func (db *SQLDB) CleanTables(chainID, burrowVersion string) error {

	if chainID == "" {
		return fmt.Errorf("error CHAIN ID cannot by empty")
	}

	cleanQueries := db.DBAdapter.CleanDBQueries()

	var savedChainID, savedBurrowVersion, query string
	savedRows := 0

	// Read chainID
	query = cleanQueries.SelectChainIDQry
	if err := db.DB.QueryRow(query).Scan(&savedRows, &savedChainID, &savedBurrowVersion); err != nil {
		db.Log.Info("msg", "Error selecting CHAIN ID", "err", err, "query", query)
		return err
	}

	switch {
	// Must be empty or one row
	case savedRows != 0 && savedRows != 1:
		return fmt.Errorf("error multiple CHAIN ID returned")

	// First database access
	case savedRows == 0:
		// Save new values and exit
		query = cleanQueries.InsertChainIDQry
		if _, err := db.DB.Exec(query, chainID, burrowVersion); err != nil {
			db.Log.Info("msg", "Error inserting CHAIN ID", "err", err, "query", query)
			return err
		}
		return nil

	// if data equals previous version exit
	case savedChainID == chainID:
		return nil

	// clean database
	default:
		var tx *sql.Tx
		var err error
		var tableName string
		tables := make([]string, 0)

		// Begin tx
		if tx, err = db.DB.Begin(); err != nil {
			db.Log.Info("msg", "Error beginning transaction", "err", err)
			return err
		}
		defer tx.Rollback()

		// Delete chainID
		query := cleanQueries.DeleteChainIDQry
		if _, err = tx.Exec(query); err != nil {
			db.Log.Info("msg", "Error deleting CHAIN ID", "err", err, "query", query)
			return err
		}

		// Insert chainID
		query = cleanQueries.InsertChainIDQry
		if _, err := tx.Exec(query, chainID, burrowVersion); err != nil {
			db.Log.Info("msg", "Error inserting CHAIN ID", "err", err, "query", query)
			return err
		}

		// Load Tables
		query = cleanQueries.SelectDictionaryQry
		rows, err := tx.Query(query)
		if err != nil {
			db.Log.Info("msg", "error querying dictionary", "err", err, "query", query)
			return err
		}
		defer rows.Close()

		for rows.Next() {

			if err = rows.Scan(&tableName); err != nil {
				db.Log.Info("msg", "error scanning table structure", "err", err)
				return err
			}

			if err = rows.Err(); err != nil {
				db.Log.Info("msg", "error scanning table structure", "err", err)
				return err
			}
			tables = append(tables, tableName)
		}

		// Delete Dictionary
		query = cleanQueries.DeleteDictionaryQry
		if _, err = tx.Exec(query); err != nil {
			db.Log.Info("msg", "Error deleting dictionary", "err", err, "query", query)
			return err
		}

		// Delete Log
		query = cleanQueries.DeleteLogQry
		if _, err = tx.Exec(query); err != nil {
			db.Log.Info("msg", "Error deleting log", "err", err, "query", query)
			return err
		}
		// Drop database tables
		for _, tableName = range tables {
			query = db.DBAdapter.DropTableQuery(tableName)
			if _, err = tx.Exec(query); err != nil {
				// if error == table does not exists, continue
				if !db.DBAdapter.ErrorEquals(err, types.SQLErrorTypeUndefinedTable) {
					db.Log.Info("msg", "error dropping tables", "err", err, "value", tableName, "query", query)
					return err
				}
			}
		}

		// Commit
		if err = tx.Commit(); err != nil {
			db.Log.Info("msg", "Error commiting transaction", "err", err)
			return err
		}

		return nil
	}
}
1370143
func (kv *keyValue) Wipe() error {
	if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".rows"); err != nil {
		return err
	}
	if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".meta"); err != nil {
		return err
	}
	return kv.finalize()
}
1140184
func (engine *Engine) DropTables(beans ...interface{}) error {
	session := engine.NewSession()
	defer session.Close()

	err := session.Begin()
	if err != nil {
		return err
	}

	for _, bean := range beans {
		err = session.dropTable(bean)
		if err != nil {
			session.Rollback()
			return err
		}
	}
	return session.Commit()
}
603666
func (db *PGStore) cleanup(interval time.Duration, quit <-chan struct{}, done chan<- struct{}) {
	ticker := time.NewTicker(interval)

	defer func() {
		ticker.Stop()
	}()

	for {
		select {
		case <-quit:
			// Handle the quit signal.
			done <- struct{}{}
			return
		case <-ticker.C:
			// Delete expired sessions on each tick.
			err := db.deleteExpired()
			if err != nil {
				log.Printf("pgstore: unable to delete expired sessions: %v", err)
			}
		}
	}
}
677137
func (flf *fileLedgerFactory) ChainIDs() []string {
	chainIDs, err := flf.blkstorageProvider.List()
	if err != nil {
		logger.Panic(err)
	}
	return chainIDs
}
882144
func cleanupIptablesLeftovers(ipt utiliptables.Interface) (encounteredError bool) {
	// Unlink the iptables chains created by ipvs Proxier
	for _, jc := range iptablesJumpChain {
		args := []string{
			"-m", "comment", "--comment", jc.comment,
			"-j", string(jc.to),
		}
		if err := ipt.DeleteRule(jc.table, jc.from, args...); err != nil {
			if !utiliptables.IsNotFoundError(err) {
				klog.Errorf("Error removing iptables rules in ipvs proxier: %v", err)
				encounteredError = true
			}
		}
	}

	// Flush and remove all of our chains. Flushing all chains before removing them also removes all links between chains first.
	for _, ch := range iptablesChains {
		if err := ipt.FlushChain(ch.table, ch.chain); err != nil {
			if !utiliptables.IsNotFoundError(err) {
				klog.Errorf("Error removing iptables rules in ipvs proxier: %v", err)
				encounteredError = true
			}
		}
	}

	// Remove all of our chains.
	for _, ch := range iptablesChains {
		if err := ipt.DeleteChain(ch.table, ch.chain); err != nil {
			if !utiliptables.IsNotFoundError(err) {
				klog.Errorf("Error removing iptables rules in ipvs proxier: %v", err)
				encounteredError = true
			}
		}
	}

	return encounteredError
}
169806
func (p *Postgres) RunCleaner(interval, expire time.Duration) {
	cleanFunc := func() {
		affectedRows, err := p.CleanExpiredRows(expire)
		if err != nil {
			p.Log.Warning("postgres: cleaning old rows failed: %s", err)
		} else if affectedRows != 0 {
			p.Log.Debug("postgres: cleaned up %d rows", affectedRows)
		}
	}

	for range time.Tick(interval) {
		cleanFunc()
	}
}
1287194
func (c *ChainInfo) Remove() error {
	// Ignore errors - This could mean the chains were never set up
	if c.Table == Nat {
		c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name)
		c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8", "-j", c.Name)
		c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "-j", c.Name) // Created in versions <= 0.1.6

		c.Prerouting(Delete)
		c.Output(Delete)
	}
	Raw("-t", string(c.Table), "-F", c.Name)
	Raw("-t", string(c.Table), "-X", c.Name)
	return nil
}
1061982
func (txn *Txn) DeleteAll(table, index string, args ...interface{}) (int, error) {
	if !txn.write {
		return 0, fmt.Errorf("cannot delete in read-only transaction")
	}

	// Get all the objects
	iter, err := txn.Get(table, index, args...)
	if err != nil {
		return 0, err
	}

	// Put them into a slice so there are no safety concerns while actually
	// performing the deletes
	var objs []interface{}
	for {
		obj := iter.Next()
		if obj == nil {
			break
		}

		objs = append(objs, obj)
	}

	// Do the deletes
	num := 0
	for _, obj := range objs {
		if err := txn.Delete(table, obj); err != nil {
			return num, err
		}
		num++
	}
	return num, nil
}
307422
func (tx *tx) delete(table, id string) error {
	n := tx.lookup(table, indexID, id)
	if n == nil {
		return ErrNotExist
	}

	err := tx.memDBTx.Delete(table, n)
	if err == nil {
		tx.changelist = append(tx.changelist, n.EventDelete())
	}
	return err
}
904940
func RestoreTable(tx Tx, table string, newObjects []api.StoreObject) error {
	checkType := func(by By) error {
		return nil
	}
	var oldObjects []api.StoreObject
	appendResult := func(o api.StoreObject) {
		oldObjects = append(oldObjects, o)
	}

	err := tx.find(table, All, checkType, appendResult)
	if err != nil {
		return nil
	}

	updated := make(map[string]struct{})

	for _, o := range newObjects {
		objectID := o.GetID()
		if existing := tx.lookup(table, indexID, objectID); existing != nil {
			if err := tx.update(table, o); err != nil {
				return err
			}
			updated[objectID] = struct{}{}
		} else {
			if err := tx.create(table, o); err != nil {
				return err
			}
		}
	}
	for _, o := range oldObjects {
		objectID := o.GetID()
		if _, ok := updated[objectID]; !ok {
			if err := tx.delete(table, objectID); err != nil {
				return err
			}
		}
	}
	return nil
}
207311
func (st *Store) Cleanup() {
	st.db.Delete(&gormSession{tableName: st.opts.TableName}, "expires_at <= ?", gorm.NowFunc())
}
1180381
func (tc *TransactionContext) Cleanup() {
	//tc.InfoSchema = nil; we cannot do it now, because some operation like handleFieldList depend on this.
	tc.DirtyDB = nil
	tc.Binlog = nil
	tc.History = nil
	tc.TableDeltaMap = nil
}
912648
func CleanAllTriremeACLs() error {
	ipt, err := iptablesctrl.NewInstance(fqconfig.NewFilterQueueWithDefaults(), constants.LocalServer, &runtime.Configuration{})
	if err != nil {
		return fmt.Errorf("unable to initialize cleaning iptables controller:  %s", err)
	}

	return ipt.CleanUp()
}
1040674
func (d *distrib) Clean() error {
	for _, c := range d.caches {
		c.Clean()
	}
	return nil
}
155933
func (s *EventStore) Clear(ctx context.Context) error {
	if err := s.session.DB(s.dbName(ctx)).C("events").DropCollection(); err != nil {
		return eh.EventStoreError{
			BaseErr:   err,
			Err:       ErrCouldNotClearDB,
			Namespace: eh.NamespaceFromContext(ctx),
		}
	}
	return nil
}
821580
func (s *LDBStore) CleanGCIndex() error {
	s.lock.Lock()
	defer s.lock.Unlock()

	batch := leveldb.Batch{}

	var okEntryCount uint64
	var totalEntryCount uint64

	// throw out all gc indices, we will rebuild from cleaned index
	it := s.db.NewIterator()
	it.Seek([]byte{keyGCIdx})
	var gcDeletes int
	for it.Valid() {
		rowType, _ := parseIdxKey(it.Key())
		if rowType != keyGCIdx {
			break
		}
		batch.Delete(it.Key())
		gcDeletes++
		it.Next()
	}
	log.Debug("gc", "deletes", gcDeletes)
	if err := s.db.Write(&batch); err != nil {
		return err
	}
	batch.Reset()

	it.Release()

	// corrected po index pointer values
	var poPtrs [256]uint64

	// set to true if chunk count not on 4096 iteration boundary
	var doneIterating bool

	// last key index in previous iteration
	lastIdxKey := []byte{keyIndex}

	// counter for debug output
	var cleanBatchCount int

	// go through all key index entries
	for !doneIterating {
		cleanBatchCount++
		var idxs []dpaDBIndex
		var chunkHashes [][]byte
		var pos []uint8
		it := s.db.NewIterator()

		it.Seek(lastIdxKey)

		// 4096 is just a nice number, don't look for any hidden meaning here...
		var i int
		for i = 0; i < 4096; i++ {

			// this really shouldn't happen unless database is empty
			// but let's keep it to be safe
			if !it.Valid() {
				doneIterating = true
				break
			}

			// if it's not keyindex anymore we're done iterating
			rowType, chunkHash := parseIdxKey(it.Key())
			if rowType != keyIndex {
				doneIterating = true
				break
			}

			// decode the retrieved index
			var idx dpaDBIndex
			err := decodeIndex(it.Value(), &idx)
			if err != nil {
				return fmt.Errorf("corrupt index: %v", err)
			}
			po := s.po(chunkHash)
			lastIdxKey = it.Key()

			// if we don't find the data key, remove the entry
			// if we find it, add to the array of new gc indices to create
			dataKey := getDataKey(idx.Idx, po)
			_, err = s.db.Get(dataKey)
			if err != nil {
				log.Warn("deleting inconsistent index (missing data)", "key", chunkHash)
				batch.Delete(it.Key())
			} else {
				idxs = append(idxs, idx)
				chunkHashes = append(chunkHashes, chunkHash)
				pos = append(pos, po)
				okEntryCount++
				if idx.Idx > poPtrs[po] {
					poPtrs[po] = idx.Idx
				}
			}
			totalEntryCount++
			it.Next()
		}
		it.Release()

		// flush the key index corrections
		err := s.db.Write(&batch)
		if err != nil {
			return err
		}
		batch.Reset()

		// add correct gc indices
		for i, okIdx := range idxs {
			gcIdxKey := getGCIdxKey(&okIdx)
			gcIdxData := getGCIdxValue(&okIdx, pos[i], chunkHashes[i])
			batch.Put(gcIdxKey, gcIdxData)
			log.Trace("clean ok", "key", chunkHashes[i], "gcKey", gcIdxKey, "gcData", gcIdxData)
		}

		// flush them
		err = s.db.Write(&batch)
		if err != nil {
			return err
		}
		batch.Reset()

		log.Debug("clean gc index pass", "batch", cleanBatchCount, "checked", i, "kept", len(idxs))
	}

	log.Debug("gc cleanup entries", "ok", okEntryCount, "total", totalEntryCount, "batchlen", batch.Len())

	// lastly add updated entry count
	var entryCount [8]byte
	binary.BigEndian.PutUint64(entryCount[:], okEntryCount)
	batch.Put(keyEntryCnt, entryCount[:])

	// and add the new po index pointers
	var poKey [2]byte
	poKey[0] = keyDistanceCnt
	for i, poPtr := range poPtrs {
		poKey[1] = uint8(i)
		if poPtr == 0 {
			batch.Delete(poKey[:])
		} else {
			var idxCount [8]byte
			binary.BigEndian.PutUint64(idxCount[:], poPtr)
			batch.Put(poKey[:], idxCount[:])
		}
	}

	// if you made it this far your harddisk has survived. Congratulations
	return s.db.Write(&batch)
}