diff --git a/shortPath.go b/shortPath.go index 9bc734f..4513beb 100644 --- a/shortPath.go +++ b/shortPath.go @@ -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)) diff --git a/shortPath_test.go b/shortPath_test.go new file mode 100644 index 0000000..82365bb --- /dev/null +++ b/shortPath_test.go @@ -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) +}