mirror of
https://bitbucket.org/s_l_teichmann/mtsatellite
synced 2024-11-08 19:20:25 +01:00
76 lines
1.3 KiB
Go
76 lines
1.3 KiB
Go
// Copyright 2014 by Sascha L. Teichmann
|
|
// Use of this source code is governed by the MIT license
|
|
// that can be found in the LICENSE file.
|
|
|
|
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"os"
|
|
|
|
"bitbucket.org/s_l_teichmann/mtredisalize/common"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
const (
|
|
fetchSql = "SELECT pos, data FROM blocks"
|
|
)
|
|
|
|
type SQLiteBlockProducer struct {
|
|
db *sql.DB
|
|
rows *sql.Rows
|
|
splitter common.KeySplitter
|
|
}
|
|
|
|
func NewSQLiteBlockProducer(path string, splitter common.KeySplitter) (sbp *SQLiteBlockProducer, err error) {
|
|
|
|
// check if we can stat it -> exists.
|
|
if _, err = os.Stat(path); err != nil {
|
|
return
|
|
}
|
|
|
|
var db *sql.DB
|
|
if db, err = sql.Open("sqlite3", path); err != nil {
|
|
return
|
|
}
|
|
|
|
var rows *sql.Rows
|
|
if rows, err = db.Query(fetchSql); err != nil {
|
|
db.Close()
|
|
return
|
|
}
|
|
|
|
sbp = &SQLiteBlockProducer{
|
|
db: db,
|
|
rows: rows,
|
|
splitter: splitter}
|
|
|
|
return
|
|
}
|
|
|
|
func (sbp *SQLiteBlockProducer) Next(block *Block) (err error) {
|
|
if sbp.rows == nil {
|
|
err = NoMoreBlocksErr
|
|
return
|
|
}
|
|
if sbp.rows.Next() {
|
|
var key int64
|
|
if err = sbp.rows.Scan(&key, &block.Data); err == nil {
|
|
block.Coord = sbp.splitter(key)
|
|
}
|
|
} else {
|
|
sbp.rows.Close()
|
|
sbp.rows = nil
|
|
err = NoMoreBlocksErr
|
|
}
|
|
return
|
|
}
|
|
|
|
func (sbp *SQLiteBlockProducer) Close() error {
|
|
if sbp.rows != nil {
|
|
sbp.rows.Close()
|
|
}
|
|
return sbp.db.Close()
|
|
}
|