mapserver/tiledb/sqlite.go

112 lines
2.1 KiB
Go
Raw Normal View History

2019-01-14 14:38:26 +03:00
package tiledb
import (
2019-01-16 18:36:28 +03:00
"database/sql"
_ "github.com/mattn/go-sqlite3"
"github.com/sirupsen/logrus"
"mapserver/coords"
"time"
2019-01-14 14:38:26 +03:00
)
const migrateScript = `
create table if not exists tiles(
data blob,
mtime bigint,
2019-01-14 14:48:46 +03:00
layerid int,
2019-01-14 14:38:26 +03:00
x int,
y int,
zoom int,
2019-01-14 14:48:46 +03:00
primary key(x,y,zoom,layerid)
2019-01-14 14:38:26 +03:00
);
`
type Sqlite3Accessor struct {
db *sql.DB
filename string
}
func (db *Sqlite3Accessor) Migrate() error {
2019-01-16 18:36:28 +03:00
log.WithFields(logrus.Fields{"filename": db.filename}).Info("Migrating database")
start := time.Now()
_, err := db.db.Exec(migrateScript)
if err != nil {
return err
}
t := time.Now()
elapsed := t.Sub(start)
log.WithFields(logrus.Fields{"elapsed": elapsed}).Info("Migration completed")
2019-01-14 14:38:26 +03:00
2019-01-16 18:36:28 +03:00
return nil
2019-01-14 14:38:26 +03:00
}
2019-01-14 14:48:46 +03:00
const getTileQuery = `
select data,mtime from tiles t
where t.layerid = ?
and t.x = ?
and t.y = ?
and t.zoom = ?
`
2019-01-17 10:53:07 +03:00
func (db *Sqlite3Accessor) GetTile(pos coords.TileCoords) (*Tile, error) {
rows, err := db.db.Query(getTileQuery, pos.LayerId, pos.X, pos.Y, pos.Zoom)
2019-01-16 18:36:28 +03:00
if err != nil {
return nil, err
}
2019-01-17 10:01:48 +03:00
defer rows.Close()
2019-01-16 18:36:28 +03:00
if rows.Next() {
var data []byte
var mtime int64
err = rows.Scan(&data, &mtime)
if err != nil {
return nil, err
}
if data == nil {
return nil, nil
}
mb := Tile{
2019-01-18 11:13:37 +03:00
Pos: pos,
Data: data,
Mtime: mtime,
2019-01-16 18:36:28 +03:00
}
return &mb, nil
}
return nil, nil
2019-01-14 14:38:26 +03:00
}
2019-01-16 18:36:28 +03:00
const setTileQuery = `
2019-01-17 10:01:48 +03:00
insert or replace into tiles(x,y,zoom,layerid,data,mtime)
2019-01-16 18:36:28 +03:00
values(?, ?, ?, ?, ?, ?)
`
func (db *Sqlite3Accessor) SetTile(tile *Tile) error {
2019-01-17 18:32:36 +03:00
_, err := db.db.Exec(setTileQuery, tile.Pos.X, tile.Pos.Y, tile.Pos.Zoom, tile.Pos.LayerId, tile.Data, tile.Mtime)
return err
2019-01-14 14:38:26 +03:00
}
2019-01-17 13:20:03 +03:00
const removeTileQuery = `
delete from tiles
where x = ? and y = ? and zoom = ? and layerid = ?
`
func (db *Sqlite3Accessor) RemoveTile(pos coords.TileCoords) error {
_, err := db.db.Exec(removeTileQuery, pos.X, pos.Y, pos.Zoom, pos.LayerId)
return err
}
2019-01-14 14:38:26 +03:00
func NewSqliteAccessor(filename string) (*Sqlite3Accessor, error) {
db, err := sql.Open("sqlite3", filename)
if err != nil {
return nil, err
}
sq := &Sqlite3Accessor{db: db, filename: filename}
return sq, nil
}