Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 130 additions & 16 deletions db/queries/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -513,14 +513,135 @@ func InsertBlockRangesBatchComposite(ctx context.Context, db DBQuerier, mtreeTab
}

// isNumericType reports whether a column of this type (format_type output)
// goes through trim_scale(). Arrays do not: trim_scale(numeric[]) does not
// exist.
// is wrapped in trim_scale(). The type must be numeric or decimal itself, with
// or without a typmod: a type whose name only starts with these words, such
// as an enum, has no trim_scale(). Arrays are not wrapped either:
// trim_scale(numeric[]) does not exist.
func isNumericType(colType string) bool {
lower := strings.ToLower(strings.TrimSpace(colType))
if strings.HasSuffix(lower, "[]") {
return false
}
return strings.HasPrefix(lower, "numeric") || strings.HasPrefix(lower, "decimal")
if i := strings.IndexByte(lower, '('); i >= 0 {
lower = strings.TrimSpace(lower[:i])
}
return lower == "numeric" || lower == "decimal"
}

// NumericColumns returns the set of the columns that are wrapped in
// trim_scale(), by the column types of a table (format_type output). It
// returns nil when there are no column types.
func NumericColumns(colTypes map[string]string) map[string]bool {
if len(colTypes) == 0 {
return nil
}
cols := make(map[string]bool)
for col, colType := range colTypes {
if isNumericType(colType) {
cols[col] = true
}
}
return cols
}

// ColExpr returns the SQL expression that stands for one column wherever ACE
// reads its value: in the row hash and in the row fetch. The hash and the
// fetch must take a column in the same form. Otherwise two rows could hash
// the same and still be reported as different when their block is fetched
// for another reason, or the reverse.
//
// A scalar numeric or decimal column is wrapped in trim_scale(), so 1.50 and
// 1.5 are the same value. An array is not, because trim_scale(numeric[])
// does not exist.
//
// col is the column name, not quoted. tableAlias may be empty; the column is
// then not qualified. colType is pg_catalog.format_type output; an empty type
// gives the plain column.
func ColExpr(tableAlias, col, colType string) string {
ref := pgx.Identifier{col}.Sanitize()
if tableAlias != "" {
ref = tableAlias + "." + ref
}
if isNumericType(colType) {
ref = fmt.Sprintf("trim_scale(%s)", ref)
}
return ref
}

// FetchColExpr returns the expression for one column in a diff row fetch,
// without a name. It starts from the expression of the row hash, so a
// fetched value is the value that was hashed. Then it casts to ::TEXT the
// columns the driver cannot scan without loss: arrays, json, bytea and any
// type the driver would give as an opaque Go struct (geometric, network,
// range, enum, xml, ...). Postgres parses its own text form on repair, so
// text values round-trip for every type without per-type conversion code.
//
// An empty or unknown type is cast to ::TEXT here, while the row hash takes
// the plain column for it. Both forms print the same text inside ROW(), so
// the fetched value is still the hashed value.
//
// col is the column name, not quoted. tableAlias may be empty.
func FetchColExpr(tableAlias, col, colType string) string {
expr := ColExpr(tableAlias, col, colType)
if NeedsTextCast(colType) {
expr += "::TEXT"
}
return expr
}

// SelectColExpr returns the SELECT-list entry for one column of a diff row
// fetch: the fetch expression, named after the column when it is more than
// the plain column. Rows are read by the names of the result columns, so the
// name must not change. Every row fetch of the diff engines must use it, so
// that diff reports do not depend on the engine and stay repairable.
func SelectColExpr(tableAlias, col, colType string) string {
expr := FetchColExpr(tableAlias, col, colType)
if expr == ColExpr(tableAlias, col, "") {
return expr
}
return expr + " AS " + pgx.Identifier{col}.Sanitize()
}

// NeedsTextCast reports whether a diff row fetch must cast the column to
// ::TEXT for its value to round-trip through a diff report.
func NeedsTextCast(colType string) bool {
return strings.HasSuffix(colType, "[]") ||
strings.Contains(strings.ToLower(colType), "json") ||
strings.Contains(strings.ToLower(colType), "bytea") ||
!IsKnownScalarType(colType)
}

func IsKnownScalarType(colType string) bool {
// colType is pg_catalog.format_type output. Strip the typmod so
// "numeric(10,2)" and "timestamp(3) with time zone" match their base
// names, then require an exact match: prefix matching mistook types that
// merely start like a scalar ("daterange" for "date") for the scalar
// itself, so they were never cast to ::TEXT and reached diff reports as
// unrepairable Go-formatted structs.
base := colType
if i := strings.IndexByte(base, '('); i >= 0 {
if j := strings.IndexByte(base[i:], ')'); j >= 0 {
base = strings.TrimSpace(base[:i] + base[i+j+1:])
}
}

switch base {
case "character varying", "character", "text",
"integer", "bigint", "smallint",
"numeric", "decimal", "real", "double precision",
"boolean",
"bytea",
"json", "jsonb",
"uuid",
"date",
"timestamp without time zone", "timestamp with time zone",
// "time with time zone" (timetz) is deliberately absent: it is not
// registered in the pgx v5 default type map, so it cannot be scanned
// into *interface{} and must be cast to ::TEXT by the diff layer.
"time without time zone":
return true
}
return false
}

// RowHashExpr returns a SQL expression for the sha256 hash of one row, as a
Expand All @@ -529,11 +650,11 @@ func isNumericType(colType string) bool {
// a leaf could differ while every row hash matches, and the diff would not
// fetch the rows of that block.
//
// The row is encoded as ROW(col1, col2, ...)::text. This text is unambiguous:
// a NULL prints as nothing, an empty string as "", and a value with a comma,
// a quote, a parenthesis, a backslash or a space is quoted. Numeric and
// decimal columns go through trim_scale(), so 1.50 and 1.5 give the same
// hash.
// The row is encoded as ROW(col1, col2, ...)::text, each column in the form
// that the row fetch also uses. This text is unambiguous: a NULL prints as
// nothing, an empty string as "", and a value with a comma, a quote, a
// parenthesis, a backslash or a space is quoted. Numeric and decimal columns
// are wrapped in trim_scale(), so 1.50 and 1.5 give the same hash.
//
// The text is converted to UTF8 before it is hashed, so nodes with different
// database encodings give the same hash for the same row. sha256 works on
Expand All @@ -548,14 +669,7 @@ func RowHashExpr(tableAlias string, allCols []string, colTypes map[string]string
}
exprs := make([]string, len(allCols))
for i, col := range allCols {
ref := pgx.Identifier{col}.Sanitize()
if tableAlias != "" {
ref = tableAlias + "." + ref
}
if colTypes != nil && isNumericType(colTypes[col]) {
ref = fmt.Sprintf("trim_scale(%s)", ref)
}
exprs[i] = ref
exprs[i] = ColExpr(tableAlias, col, colTypes[col])
}
// ROW() is not a function call, so the limit of 100 arguments does not
// apply to it.
Expand Down
138 changes: 138 additions & 0 deletions db/queries/queries_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
"testing"
"text/template"
"time"

"github.com/stretchr/testify/require"
)

type mockRow struct {
Expand Down Expand Up @@ -434,6 +436,116 @@ func TestRowHashExpr(t *testing.T) {
})
}

func TestColExpr(t *testing.T) {
tests := []struct {
alias, col, colType string
want string
}{
{"", "id", "integer", `"id"`},
{"_tbl_", "id", "integer", `_tbl_."id"`},
{"", "Name", "text", `"Name"`},
{"", `we"ird`, "text", `"we""ird"`},
{"", "price", "numeric(10,2)", `trim_scale("price")`},
{"_tbl_", "price", "DECIMAL", `trim_scale(_tbl_."price")`},
// trim_scale has no array variant.
{"", "prices", "numeric[]", `"prices"`},
// Unknown type: the plain column.
{"", "c", "", `"c"`},
}
for _, tt := range tests {
t.Run(tt.alias+"."+tt.col+":"+tt.colType, func(t *testing.T) {
if got := ColExpr(tt.alias, tt.col, tt.colType); got != tt.want {
t.Errorf("ColExpr(%q, %q, %q) = %q, want %q", tt.alias, tt.col, tt.colType, got, tt.want)
}
})
}
}

// The row hash must take each column in the same form as the row fetch.
func TestRowHashExprUsesColExpr(t *testing.T) {
cols := []string{"id", "price", "prices", "Name"}
colTypes := map[string]string{"id": "integer", "price": "numeric", "prices": "numeric[]", "Name": "text"}
got, err := RowHashExpr("_tbl_", cols, colTypes)
if err != nil {
t.Fatalf("RowHashExpr() error = %v", err)
}
exprs := make([]string, len(cols))
for i, c := range cols {
exprs[i] = ColExpr("_tbl_", c, colTypes[c])
}
want := "sha256(convert_to(ROW(" + strings.Join(exprs, ", ") + ")::text, 'UTF8'))"
if got != want {
t.Errorf("RowHashExpr() = %q, want %q", got, want)
}
}

// Complex and unknown types are fetched as ::TEXT so their Postgres text form
// round-trips through the diff report; known scalars stay native. A scalar
// numeric is wrapped in trim_scale, as in the row hash.
func TestSelectColExpr(t *testing.T) {
tests := []struct {
colType string
want string
}{
{"integer", `"c"`},
{"timestamp without time zone", `"c"`},
{"timestamp(3) with time zone", `"c"`},
{"numeric(10,2)", `trim_scale("c") AS "c"`},
{"numeric", `trim_scale("c") AS "c"`},
{"numeric(10,2)[]", `"c"::TEXT AS "c"`},
{"date", `"c"`},
{"uuid", `"c"`},
{"integer[]", `"c"::TEXT AS "c"`},
{"jsonb", `"c"::TEXT AS "c"`},
{"bytea", `"c"::TEXT AS "c"`},
{"point", `"c"::TEXT AS "c"`},
{"int4range", `"c"::TEXT AS "c"`},
// "daterange" must not be mistaken for "date" (nor "datemultirange",
// nor a UDT that happens to share a scalar's name as a prefix).
{"daterange", `"c"::TEXT AS "c"`},
{"datemultirange", `"c"::TEXT AS "c"`},
{"date_status_enum", `"c"::TEXT AS "c"`},
{"mood_enum", `"c"::TEXT AS "c"`},
{"xml", `"c"::TEXT AS "c"`},
{"bit(8)", `"c"::TEXT AS "c"`},
{"inet", `"c"::TEXT AS "c"`},
{"time with time zone", `"c"::TEXT AS "c"`},
}
for _, tt := range tests {
t.Run(tt.colType, func(t *testing.T) {
require.Equal(t, tt.want, SelectColExpr("", "c", tt.colType))
})
}

// A qualified column must still give a result column with the name of the
// column, and the name must be quoted.
qualified := []struct {
colType string
want string
}{
{"integer", `t."Name"`},
{"numeric", `trim_scale(t."Name") AS "Name"`},
{"jsonb", `t."Name"::TEXT AS "Name"`},
}
for _, tt := range qualified {
t.Run("qualified/"+tt.colType, func(t *testing.T) {
require.Equal(t, tt.want, SelectColExpr("t", "Name", tt.colType))
})
}
}

// The fetch must start from the expression of the row hash: a fetched value
// is then the value that was hashed.
func TestFetchColExprStartsFromColExpr(t *testing.T) {
for _, colType := range []string{"integer", "text", "numeric", "numeric(12,4)", "DECIMAL", "numeric[]", "jsonb", "inet", ""} {
t.Run(colType, func(t *testing.T) {
hashExpr := ColExpr("_tbl_", "c", colType)
require.True(t, strings.HasPrefix(FetchColExpr("_tbl_", "c", colType), hashExpr),
"FetchColExpr must start with %q", hashExpr)
})
}
}

func TestIsNumericType(t *testing.T) {
tests := []struct {
colType string
Expand All @@ -455,6 +567,10 @@ func TestIsNumericType(t *testing.T) {
{"numeric[]", false},
{"numeric(10,2)[]", false},
{"DECIMAL[]", false},
// A type whose name only starts like numeric, such as an enum.
{"numeric_level", false},
{"decimal_kind", false},
{"numericx", false},
}

for _, tt := range tests {
Expand All @@ -466,6 +582,28 @@ func TestIsNumericType(t *testing.T) {
}
}

func TestNumericColumns(t *testing.T) {
got := NumericColumns(map[string]string{
"id": "integer",
"price": "numeric(10,2)",
"amount": "DECIMAL",
"prices": "numeric[]",
"note": "text",
})
want := map[string]bool{"price": true, "amount": true}
if len(got) != len(want) {
t.Fatalf("NumericColumns() = %v, want %v", got, want)
}
for col := range want {
if !got[col] {
t.Errorf("NumericColumns() = %v, want %v", got, want)
}
}
if got := NumericColumns(nil); got != nil {
t.Errorf("NumericColumns(nil) = %v, want nil", got)
}
}

// A block with no lower bound reaches the max-value queries with no start key.
// They must then look at the whole table, not compare the key with NULL.
func TestGetMaxValOpenStart(t *testing.T) {
Expand Down
48 changes: 48 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,54 @@

All notable changes to ACE will be captured in this document. This project follows semantic versioning; the latest changes appear first.

## [Unreleased]

### Added
- Diff reports have a `format_version` field. `table-repair` and
`table-rerun` refuse a report with a version they do not know. A report
from an earlier ACE has no such field and is read as version 0.
- `table-repair` and `table-rerun` read the numeric values of a version 0
report in the current form, without trailing zeros. The stale check of a
repair plan then finds their keys on the target, and the rerun counts a
row that the report holds under two keys once.

### Changed
- **A numeric value in a diff report has no trailing zeros.** The row fetch
now reads a numeric column with `trim_scale()`, as the row hash does, so
the report shows `7.5`, not `7.50`. Repair writes this form: a `numeric`
column without a fixed scale gets the value without the trailing zeros on
the target. A column with a fixed scale, such as `numeric(10,2)`, is not
affected.

### Fixed
- **`table-rerun` reported rows it could not find in the report as
differences with no row to show.** It matched the rows it read to the
report by a printed key, so a key that prints in another form, such as a
numeric key `1.50` in a report from an earlier ACE, did not match, and a
row deleted on both nodes was counted too. The rerun now matches rows to
the report by key position, and a row deleted on both nodes is not a
difference: the nodes agree on it.
- **`table-rerun` dropped rows with a uuid, numeric or time key.** It read
the rows of the nodes in another form than the report, so the keys did
not match. It then reported such a row as a difference with no row to
show.
- **The stale check of a repair plan was skipped for numeric and uuid
keys.** With `allow_stale_repairs: false`, repair overwrote such a row
even when it had changed after the diff. The check now reads the keys in
the form of the report.
- **A numeric primary key stored with another scale on two nodes was
reported as two rows.** The diff reported the row `1.50` on one node and
the row `1.5` on the other as a row missing on each node, so a repair plan
applied the rules for missing rows to them, for example a `delete` rule.
Now they are one row.
- **`table-diff` and the mtree commands failed on a column of an enum whose
name starts with `numeric` or `decimal`.** ACE took such a type for a
numeric type and wrapped the column in `trim_scale()`, which does not
exist for it. Now only `numeric` and `decimal` themselves are numeric
types. A column of a domain over numeric whose name starts with these words
is not wrapped in `trim_scale()` any more, so a Merkle tree of such a table
must be built again.

## [v3.0.0]

> **⚠️ This release has breaking changes. Read Breaking Change and
Expand Down
Loading
Loading