mirror of https://github.com/jlelse/GoBlog
Fix short path algorithm to not skip many ids
This commit is contained in:
parent
55ef904286
commit
99980cb461
|
@ -3,6 +3,8 @@ package main
|
|||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
|
||||
"github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func (db *database) shortenPath(p string) (string, error) {
|
||||
|
@ -15,10 +17,12 @@ 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 {
|
||||
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))
|
||||
if err != nil {
|
||||
|
|
|
@ -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)
|
||||
}
|
Loading…
Reference in New Issue