diff --git a/dialect_postgres.go b/dialect_postgres.go index 738c6a158..d6f403684 100644 --- a/dialect_postgres.go +++ b/dialect_postgres.go @@ -1093,6 +1093,19 @@ func (db *postgres) GetTables() ([]*core.Table, error) { return tables, nil } + +func getIndexColName(indexdef string) []string { + var colNames []string + + cs := strings.Split(indexdef, "(") + for _, v := range strings.Split(strings.Split(cs[1], ")")[0], ",") { + colNames = append(colNames, strings.Split(strings.TrimLeft(v, " "), " ")[0]) + } + + return colNames +} + + func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) { args := []interface{}{tableName} s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE tablename=$1") @@ -1126,8 +1139,7 @@ func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) } else { indexType = core.IndexType } - cs := strings.Split(indexdef, "(") - colNames = strings.Split(cs[1][0:len(cs[1])-1], ",") + colNames = getIndexColName(indexdef) var isRegular bool if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { newIdxName := indexName[5+len(tableName):] diff --git a/dialect_postgres_test.go b/dialect_postgres_test.go index 6e6c44bbe..06c79ca49 100644 --- a/dialect_postgres_test.go +++ b/dialect_postgres_test.go @@ -6,6 +6,7 @@ import ( "github.com/go-xorm/core" "github.com/jackc/pgx/stdlib" + "github.com/stretchr/testify/assert" ) func TestParsePostgres(t *testing.T) { @@ -84,3 +85,37 @@ func TestParsePgx(t *testing.T) { } } + +func TestGetIndexColName(t *testing.T) { + t.Run("Index", func(t *testing.T) { + s := "CREATE INDEX test2_mm_idx ON test2 (major);" + colNames := getIndexColName(s) + assert.Equal(t, []string{"major"}, colNames) + }) + + t.Run("Multicolumn indexes", func(t *testing.T) { + s := "CREATE INDEX test2_mm_idx ON test2 (major, minor);" + colNames := getIndexColName(s) + assert.Equal(t, []string{"major", "minor"}, colNames) + }) + + t.Run("Indexes and ORDER BY", func(t *testing.T) { + s := "CREATE INDEX test2_mm_idx ON test2 (major NULLS FIRST, minor DESC NULLS LAST);" + colNames := getIndexColName(s) + assert.Equal(t, []string{"major", "minor"}, colNames) + }) + + t.Run("Combining Multiple Indexes", func(t *testing.T) { + s := "CREATE INDEX test2_mm_cm_idx ON public.test2 USING btree (major, minor) WHERE ((major <> 5) AND (minor <> 6))" + colNames := getIndexColName(s) + assert.Equal(t, []string{"major", "minor"}, colNames) + }) + + t.Run("unique", func(t *testing.T) { + s := "CREATE UNIQUE INDEX test2_mm_uidx ON test2 (major);" + colNames := getIndexColName(s) + assert.Equal(t, []string{"major"}, colNames) + }) + + t.Run("Indexes on Expressions", func(t *testing.T) {}) +}