Esempio n. 1
0
// NewMysqlCache connects to a MySQL database and returns an item satisifying
// both the ItemCache and FixityDB interfaces.
func NewMysqlCache(dial string) (*msqlCache, error) {
	db, err := migration.OpenWith(
		"mysql",
		dial,
		mysqlMigrations,
		mysqlVersioning.Get,
		mysqlVersioning.Set)
	if err != nil {
		log.Printf("Open Mysql: %s", err.Error())
		return nil, err
	}
	return &msqlCache{db: db}, nil
}
Esempio n. 2
0
func LockDBAndMigrate(logger lager.Logger, sqlDriver string, sqlDataSource string) (db.Conn, error) {
	var err error
	var dbLockConn db.Conn
	var dbConn db.Conn

	for {
		dbLockConn, err = db.WrapWithError(sql.Open(sqlDriver, sqlDataSource))
		if err != nil {
			if strings.Contains(err.Error(), " dial ") {
				logger.Error("failed-to-open-db-retrying", err)
				time.Sleep(5 * time.Second)
				continue
			}
			return nil, err
		}

		break
	}

	lockName := crc32.ChecksumIEEE([]byte(sqlDriver + sqlDataSource))

	for {
		_, err = dbLockConn.Exec(`select pg_advisory_lock($1)`, lockName)
		if err != nil {
			logger.Error("failed-to-acquire-lock-retrying", err)
			time.Sleep(5 * time.Second)
			continue
		}

		logger.Info("migration-lock-acquired")

		migrations := Translogrifier(logger, Migrations)
		dbConn, err = db.WrapWithError(migration.OpenWith(sqlDriver, sqlDataSource, migrations, safeGetVersion, safeSetVersion))
		if err != nil {
			logger.Fatal("failed-to-run-migrations", err)
		}

		_, err = dbLockConn.Exec(`select pg_advisory_unlock($1)`, lockName)
		if err != nil {
			logger.Error("failed-to-release-lock", err)
		}

		dbLockConn.Close()
		break
	}

	return dbConn, nil
}
Esempio n. 3
0
func New(filename string, buffer int, maintanence int) (*Queue, error) {
	db, err := migration.OpenWith("sqlite3", filename,
		[]migration.Migrator{
			func(tx migration.LimitedTx) error {
				_, err := tx.Exec(`
               CREATE table simple_queue (
                 id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                 tube text NOT NULL,
                 priority INTEGERT DEFAULT 0,
                 created INTEGER NOT NULL,
                 modified INTEGER NOT NULL,
                 state INTEGER NOT NULL,
                 data text NOT NULL,
                 ttr INTEGER NOT NULL
               )`)
				return err
			},
			func(tx migration.LimitedTx) error {
				_, err := tx.Exec(`CREATE INDEX simple_queue_tube_idx ON simple_queue(tube)`)
				return err
			},
		},
		defaultGetVersion,
		defaultSetVersion)

	if err != nil {
		return nil, err
	}

	q := &Queue{
		db:     db,
		wait:   make(chan struct{}, buffer),
		exit:   make(chan struct{}),
		ticker: time.NewTicker(time.Second * time.Duration(maintanence)),
	}

	go q.maintanence()

	return q, nil
}