From 3cfaf9c059b1de8fa8e5318f3360a2e509ca64d8 Mon Sep 17 00:00:00 2001 From: Thomas Rudin Date: Fri, 22 Feb 2019 19:26:52 +0100 Subject: [PATCH] count(*) before fetch in postgres map --- server/db/postgres/initialblocks.go | 63 ++++++++++++++++++++++------- server/db/postgres/sql.go | 11 +++++ 2 files changed, 60 insertions(+), 14 deletions(-) diff --git a/server/db/postgres/initialblocks.go b/server/db/postgres/initialblocks.go index da14484..05801ba 100644 --- a/server/db/postgres/initialblocks.go +++ b/server/db/postgres/initialblocks.go @@ -16,6 +16,31 @@ const ( SETTING_LAST_Y_BLOCK = "last_y_block" ) +func (this *PostgresAccessor) countBlocks(x1, y1, z1, x2, y2, z2 int) (int, error) { + rows, err := this.db.Query(getBlockCountByInitialTileQuery, + x1, y1, z1, x2, y2, z2, + ) + + if err != nil { + return 0, err + } + + defer rows.Close() + + for rows.Next() { + var count int + + err = rows.Scan(&count) + if err != nil { + return 0, err + } + + return count, nil + } + + return 0, nil +} + // x -> 0 ... 256 //zoom/mapblock-width @@ -131,34 +156,44 @@ func (this *PostgresAccessor) FindNextInitialBlocks(s settings.Settings, layers } } - rows, err := this.db.Query(getBlocksByInitialTileQuery, - minX, minY, minZ, maxX, maxY, maxZ, - ) + count, err := this.countBlocks(minX, minY, minZ, maxX, maxY, maxZ) if err != nil { return nil, err } - defer rows.Close() blocks := make([]*db.Block, 0) var lastmtime int64 - for rows.Next() { - var posx, posy, posz int - var data []byte - var mtime int64 + if count > 0 { + + rows, err := this.db.Query(getBlocksByInitialTileQuery, + minX, minY, minZ, maxX, maxY, maxZ, + ) - err = rows.Scan(&posx, &posy, &posz, &data, &mtime) if err != nil { return nil, err } - if mtime > lastmtime { - lastmtime = mtime - } + defer rows.Close() - mb := convertRows(posx, posy, posz, data, mtime) - blocks = append(blocks, mb) + for rows.Next() { + var posx, posy, posz int + var data []byte + var mtime int64 + + err = rows.Scan(&posx, &posy, &posz, &data, &mtime) + if err != nil { + return nil, err + } + + if mtime > lastmtime { + lastmtime = mtime + } + + mb := convertRows(posx, posy, posz, data, mtime) + blocks = append(blocks, mb) + } } s.SetInt(SETTING_LAST_LAYER, lastlayer) diff --git a/server/db/postgres/sql.go b/server/db/postgres/sql.go index 37cb594..e3509cf 100644 --- a/server/db/postgres/sql.go +++ b/server/db/postgres/sql.go @@ -11,6 +11,17 @@ and b.posy <= $5 and b.posz <= $6 ` +const getBlockCountByInitialTileQuery = ` +select count(*) +from blocks b +where b.posx >= $1 +and b.posy >= $2 +and b.posz >= $3 +and b.posx <= $4 +and b.posy <= $5 +and b.posz <= $6 +` + const getBlocksByMtimeQuery = ` select posx,posy,posz,data,mtime from blocks b