Fix short path algorithm to not skip many ids

This commit is contained in:
Jan-Lukas Else 2021-11-13 23:33:21 +01:00
parent 55ef904286
commit 99980cb461
2 changed files with 44 additions and 2 deletions

View File

@ -3,6 +3,8 @@ package main
import (
"database/sql"
"errors"
"github.com/mattn/go-sqlite3"
)
func (db *database) shortenPath(p string) (string, error) {
@ -15,9 +17,11 @@ func (db *database) shortenPath(p string) (string, error) {
return spi.(string), nil
}
// Insert in case it isn't shortened yet
_, err := db.exec("insert or ignore into shortpath (path) values (@path)", sql.Named("path", p))
_, err := db.exec("insert or rollback into shortpath (path) values (@path)", sql.Named("path", p))
if err != nil {
return nil, err
if no, ok := err.(sqlite3.Error); !ok || no.Code != sqlite3.ErrConstraint {
return nil, err
}
}
// Query short path
row, err := db.queryRow("select printf('/s/%x', id) from shortpath where path = @path", sql.Named("path", p))

38
shortPath_test.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_shortenPath(t *testing.T) {
app := &goBlog{
cfg: &config{
Db: &configDb{
File: filepath.Join(t.TempDir(), "test.db"),
},
},
}
_ = app.initDatabase(false)
db := app.db
res1, err := db.shortenPath("/a")
require.NoError(t, err)
db.spc.Delete("/a")
res2, err := db.shortenPath("/a")
require.NoError(t, err)
res3, err := db.shortenPath("/b")
require.NoError(t, err)
assert.Equal(t, res1, res2)
assert.Equal(t, "/s/1", res1)
assert.NotEqual(t, res1, res3)
assert.Equal(t, "/s/2", res3)
}