Make sure table stub is valid as a pilosa.Index name (#2306)

We use part of the dax.TableName in the pilosa.Index.Name.
This just ensure that we don't let invalid characters get through.
This commit is contained in:
Travis Turner 2022-11-19 20:54:37 -06:00 committed by GitHub
parent 875c7492fe
commit 10e8aa5c45
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 2 deletions

View file

@ -3,6 +3,7 @@ package dax
import (
"crypto/rand"
"fmt"
"regexp"
"strings"
"time"
@ -177,8 +178,9 @@ func (t *Table) CreateID() (TableID, error) {
//
// In order to avoid creating an ID with a double underscore, we remove all
// underscores from the original table name (because that's what we use in
// TableKey as a delimiter).
stub := strings.ReplaceAll(string(t.Name), "_", "")
// TableKey as a delimiter). In addition to that, we remove any other
// characters which are not valid as a pilosa indes name.
stub := regexp.MustCompile(`[^a-z0-9-]+`).ReplaceAllString(strings.ToLower(string(t.Name)), "")
if len(stub) > 10 {
stub = stub[:10]
}

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"sort"
"strings"
"testing"
"time"
@ -208,6 +209,55 @@ func TestTable(t *testing.T) {
})
t.Run("Table", func(t *testing.T) {
// CleanStub makes sure that the portion of the dax.TableName that we
// use in the pilosa.Index.Name is actually valid.
t.Run("CleanStub", func(t *testing.T) {
tests := []struct {
name dax.TableName
expStub string
}{
{
name: "",
expStub: "",
},
{
name: "foo",
expStub: "foo",
},
{
name: "AbCdEfG1234",
expStub: "abcdefg123",
},
{
name: "foo_bar_",
expStub: "foobar",
},
{
name: "!!!!!!!",
expStub: "",
},
{
name: "long1234567890",
expStub: "long123456",
},
{
name: "&&&&&&&&&&&&&&valid_stuff",
expStub: "validstuff",
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
n := dax.NewTable(test.name)
assert.Empty(t, n.ID)
n.CreateID()
parts := strings.Split(string(n.ID), "_")
assert.Equal(t, test.expStub, parts[0])
})
}
})
t.Run("RandomID", func(t *testing.T) {
n := dax.NewTable(tableName)
assert.Empty(t, n.ID)