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 (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
|
"github.com/mattn/go-sqlite3"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (db *database) shortenPath(p string) (string, error) {
|
func (db *database) shortenPath(p string) (string, error) {
|
||||||
|
@ -15,9 +17,11 @@ func (db *database) shortenPath(p string) (string, error) {
|
||||||
return spi.(string), nil
|
return spi.(string), nil
|
||||||
}
|
}
|
||||||
// Insert in case it isn't shortened yet
|
// 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 err != nil {
|
||||||
return nil, err
|
if no, ok := err.(sqlite3.Error); !ok || no.Code != sqlite3.ErrConstraint {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Query short path
|
// Query short path
|
||||||
row, err := db.queryRow("select printf('/s/%x', id) from shortpath where path = @path", sql.Named("path", p))
|
row, err := db.queryRow("select printf('/s/%x', id) from shortpath where path = @path", sql.Named("path", p))
|
||||||
|
|
|
@ -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