func (p *Postgres) CleanExpiredRows(expire time.Duration) (int64, error) {
	cleanOldRows := `DELETE FROM kite.kite WHERE updated_at < (now() at time zone 'utc') - ((INTERVAL '1 second') * $1)`
	rows, err := p.DB.Exec(cleanOldRows, int64(expire/time.Second))
	if err != nil {
		return 0, err
	}
	return rows.RowsAffected()
}
CleanExpiredRows deletes rows that are at least "expire" duration old. So if
say an expire duration of 10 second is given, it will delete all rows that
were updated 10 seconds ago
package kontrol
import (
	"database/sql"
	"errors"
	"fmt"
	"net/url"
	"strings"
	"time"
	"github.com/hashicorp/go-version"
	sq "github.com/lann/squirrel"
	"github.com/lib/pq"
	"github.com/koding/kite"
	kontrolprotocol "github.com/koding/kite/kontrol/protocol"
	"github.com/koding/kite/protocol"
	"github.com/koding/multiconfig"
)
var (
	ErrQueryFieldsEmpty = errors.New("all query fields are empty")
	ErrNoKeyFound       = errors.New("no key pair found")
)
type PostgresConfig struct {
	Host           string `default:"localhost"`
	Port           int    `default:"5432"`
	Username       string `required:"true"`
	Password       string
	DBName         string `required:"true" `
	ConnectTimeout int    `default:"20"`
}
type Postgres struct {
	DB  *sql.DB
	Log kite.Logger
}
var (
	_ Storage        = (*Postgres)(nil)
	_ KeyPairStorage = (*Postgres)(nil)
)
func NewPostgres(conf *PostgresConfig, log kite.Logger) *Postgres {
	if conf == nil {
		conf = new(PostgresConfig)
		envLoader := &multiconfig.EnvironmentLoader{Prefix: "kontrol_postgres"}
		configLoader := multiconfig.MultiLoader(
			&multiconfig.TagLoader{}, envLoader,
		)
		if err := configLoader.Load(conf); err != nil {
			fmt.Println("Valid environment variables are: ")
			envLoader.PrintEnvs(conf)
			panic(err)
		}
		err := multiconfig.MultiValidator(&multiconfig.RequiredValidator{}).Validate(conf)
		if err != nil {
			fmt.Println("Valid environment variables are: ")
			envLoader.PrintEnvs(conf)
			panic(err)
		}
	}
	connString := fmt.Sprintf(
		"host=%s port=%d dbname=%s user=%s password=%s sslmode=disable connect_timeout=%d",
		conf.Host, conf.Port, conf.DBName, conf.Username, conf.Password, conf.ConnectTimeout,
	)
	db, err := sql.Open("postgres", connString)
	if err != nil {
		panic(err)
	}
	p := &Postgres{
		DB:  db,
		Log: log,
	}
	cleanInterval := 120 * time.Second  
	go p.RunCleaner(cleanInterval, KeyTTL)
	return p
}
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()
	}
}