You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by ze...@apache.org on 2025/03/04 23:04:11 UTC
(iceberg-go) branch main updated: ci(golangci-lint) :Add golangci linter (#315)
This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git
The following commit(s) were added to refs/heads/main by this push:
new ba883bd ci(golangci-lint) :Add golangci linter (#315)
ba883bd is described below
commit ba883bdb1d26cc8ea0505e3910ffee0f9c74f315
Author: Dao Thanh Tung <tt...@accountancy.smu.edu.sg>
AuthorDate: Tue Mar 4 23:04:05 2025 +0000
ci(golangci-lint) :Add golangci linter (#315)
From the feedback
https://github.com/apache/iceberg-go/pull/306#discussion_r1960205322,
I'm adding golangci-lint in GIthub Action CI. There are many different
linters but I'm just adding the most basic one. We can definitely add
more if needed
I have not run golangci-lint with `--fix` argument. I plan to get it
flagged out in the PR as a form of testing. Let me know if we want to
commit the changes after fixing
---------
Signed-off-by: dttung2905 <tt...@accountancy.smu.edu.sg>
---
.github/workflows/go-ci.yml | 7 +-
.golangci.yml | 26 ++
catalog/catalog.go | 3 +
catalog/glue/glue.go | 17 +-
catalog/glue/glue_test.go | 18 +-
catalog/internal/utils.go | 4 +-
catalog/registry.go | 2 +
catalog/registry_test.go | 12 +-
catalog/rest/rest.go | 39 +-
catalog/rest/rest_internal_test.go | 6 +-
catalog/rest/rest_test.go | 9 +
catalog/sql/sql.go | 28 +-
catalog/sql/sql_test.go | 102 +++---
cmd/iceberg/main.go | 1 +
cmd/iceberg/output_test.go | 12 +-
config/config.go | 3 +-
config/config_test.go | 12 +-
exprs.go | 22 +-
exprs_test.go | 230 ++++++++----
internal/avro_schemas.go | 26 +-
internal/mock_fs.go | 6 +
io/blob.go | 11 +-
io/gcs.go | 1 +
io/io.go | 6 +
io/local.go | 5 +-
literals.go | 87 ++++-
literals_test.go | 520 ++++++++++++++++++---------
manifest.go | 78 ++++
manifest_test.go | 14 +-
partitions.go | 8 +-
partitions_test.go | 60 ++--
predicates.go | 2 +
schema.go | 54 ++-
schema_test.go | 29 +-
table/arrow_scanner.go | 37 +-
table/arrow_utils.go | 41 ++-
table/arrow_utils_test.go | 118 ++++---
table/evaluators.go | 19 +-
table/evaluators_test.go | 705 ++++++++++++++++++++++++-------------
table/internal/parquet_files.go | 18 +-
table/internal/utils.go | 3 +
table/metadata.go | 28 +-
table/metadata_internal_test.go | 19 +-
table/name_mapping.go | 5 +
table/name_mapping_test.go | 63 ++--
table/refs.go | 4 +-
table/requirements.go | 18 +-
table/scanner.go | 19 +-
table/snapshots.go | 9 +-
table/snapshots_test.go | 2 +
table/sorting.go | 7 +-
table/substrait/substrait.go | 17 +-
table/substrait/substrait_test.go | 18 +-
table/table.go | 3 +
table/updates.go | 13 +
transforms.go | 34 +-
transforms_test.go | 3 +-
types.go | 34 +-
types_test.go | 41 +--
utils.go | 11 +
utils/context.go | 1 +
visitors.go | 15 +
visitors_test.go | 87 +++--
63 files changed, 2030 insertions(+), 822 deletions(-)
diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml
index 7ef5b07..4c38957 100644
--- a/.github/workflows/go-ci.yml
+++ b/.github/workflows/go-ci.yml
@@ -48,10 +48,15 @@ jobs:
with:
go-version: ${{ matrix.go }}
cache: true
- cache-dependency-path: go.sum
+ cache-dependency-path: go.sum
- name: Install staticcheck
if: matrix.go == '1.23.6'
run: go install honnef.co/go/tools/cmd/staticcheck@v0.6.0
+ - name: Run golangci-lint
+ uses: golangci/golangci-lint-action@v6
+ with:
+ version: v1.64.5
+ args: --timeout=10m
- name: Lint
run: staticcheck ./...
- name: Run tests
diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000..bdab05c
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,26 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+---
+linters:
+ disable-all: true
+ enable:
+ - gofmt
+ - goimports
+ - nlreturn
+ - perfsprint
+ - gofumpt
+ - misspell
\ No newline at end of file
diff --git a/catalog/catalog.go b/catalog/catalog.go
index bc04a6d..a241110 100644
--- a/catalog/catalog.go
+++ b/catalog/catalog.go
@@ -108,6 +108,7 @@ func ToIdentifier(ident ...string) table.Identifier {
if ident[0] == "" {
return nil
}
+
return table.Identifier(strings.Split(ident[0], "."))
}
@@ -163,6 +164,7 @@ func checkForOverlap(removals []string, updates iceberg.Properties) error {
if len(overlap) > 0 {
return fmt.Errorf("conflict between removals and updates for keys: %v", overlap)
}
+
return nil
}
@@ -196,5 +198,6 @@ func getUpdatedPropsAndUpdateSummary(currentProps iceberg.Properties, removals [
Updated: updated,
Missing: iceberg.Difference(removals, removed),
}
+
return updatedProps, summary, nil
}
diff --git a/catalog/glue/glue.go b/catalog/glue/glue.go
index 5b9cb0e..ae6abba 100644
--- a/catalog/glue/glue.go
+++ b/catalog/glue/glue.go
@@ -65,9 +65,7 @@ const (
RetryMode = "glue.retry-mode"
)
-var (
- _ catalog.Catalog = (*Catalog)(nil)
-)
+var _ catalog.Catalog = (*Catalog)(nil)
func init() {
catalog.Register("glue", catalog.RegistrarFunc(func(ctx context.Context, _ string, props iceberg.Properties) (catalog.Catalog, error) {
@@ -161,6 +159,7 @@ func (c *Catalog) ListTables(ctx context.Context, namespace table.Identifier) it
database, err := identifierToGlueDatabase(namespace)
if err != nil {
yield(table.Identifier{}, err)
+
return
}
@@ -173,6 +172,7 @@ func (c *Catalog) ListTables(ctx context.Context, namespace table.Identifier) it
page, err := paginator.NextPage(ctx)
if err != nil {
yield(table.Identifier{}, fmt.Errorf("failed to list tables in namespace %s: %w", database, err))
+
return
}
@@ -357,7 +357,6 @@ func (c *Catalog) CreateNamespace(ctx context.Context, namespace table.Identifie
params := &glue.CreateDatabaseInput{CatalogId: c.catalogId, DatabaseInput: databaseInput}
_, err = c.glueSvc.CreateDatabase(ctx, params)
-
if err != nil {
return fmt.Errorf("failed to create database %s: %w", database, err)
}
@@ -375,6 +374,7 @@ func (c *Catalog) CheckNamespaceExists(ctx context.Context, namespace table.Iden
if err != nil {
return false, err
}
+
return true, nil
}
@@ -431,8 +431,8 @@ func getUpdatedPropsAndUpdateSummary(currentProps iceberg.Properties, removals [
// UpdateNamespaceProperties updates the properties of an Iceberg namespace in the Glue catalog.
// The removals list contains the keys to remove, and the updates map contains the keys and values to update.
func (c *Catalog) UpdateNamespaceProperties(ctx context.Context, namespace table.Identifier,
- removals []string, updates iceberg.Properties) (catalog.PropertiesUpdateSummary, error) {
-
+ removals []string, updates iceberg.Properties,
+) (catalog.PropertiesUpdateSummary, error) {
databaseName, err := identifierToGlueDatabase(namespace)
if err != nil {
return catalog.PropertiesUpdateSummary{}, err
@@ -466,7 +466,7 @@ func (c *Catalog) ListNamespaces(ctx context.Context, parent table.Identifier) (
}
if parent != nil {
- return nil, fmt.Errorf("hierarchical namespace is not supported")
+ return nil, errors.New("hierarchical namespace is not supported")
}
var icebergNamespaces []table.Identifier
@@ -503,6 +503,7 @@ func (c *Catalog) getTable(ctx context.Context, database, tableName string) (*ty
if errors.Is(err, &types.EntityNotFoundException{}) {
return nil, fmt.Errorf("failed to get table %s.%s: %w", database, tableName, catalog.ErrNoSuchTable)
}
+
return nil, fmt.Errorf("failed to get table %s.%s: %w", database, tableName, err)
}
@@ -520,6 +521,7 @@ func (c *Catalog) getDatabase(ctx context.Context, databaseName string) (*types.
if errors.Is(err, &types.EntityNotFoundException{}) {
return nil, fmt.Errorf("failed to get namespace %s: %w", databaseName, catalog.ErrNoSuchNamespace)
}
+
return nil, fmt.Errorf("failed to get namespace %s: %w", databaseName, err)
}
@@ -564,6 +566,7 @@ func filterTableListByType(database string, tableList []types.Table, tableType s
}
filtered = append(filtered, TableIdentifier(database, aws.ToString(tbl.Name)))
}
+
return filtered
}
diff --git a/catalog/glue/glue_test.go b/catalog/glue/glue_test.go
index 2c6516f..a13d825 100644
--- a/catalog/glue/glue_test.go
+++ b/catalog/glue/glue_test.go
@@ -20,7 +20,6 @@ package glue
import (
"context"
"errors"
- "fmt"
"os"
"testing"
@@ -40,46 +39,55 @@ type mockGlueClient struct {
func (m *mockGlueClient) CreateTable(ctx context.Context, params *glue.CreateTableInput, optFns ...func(*glue.Options)) (*glue.CreateTableOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.CreateTableOutput), args.Error(1)
}
func (m *mockGlueClient) GetTable(ctx context.Context, params *glue.GetTableInput, optFns ...func(*glue.Options)) (*glue.GetTableOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.GetTableOutput), args.Error(1)
}
func (m *mockGlueClient) GetTables(ctx context.Context, params *glue.GetTablesInput, optFns ...func(*glue.Options)) (*glue.GetTablesOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.GetTablesOutput), args.Error(1)
}
func (m *mockGlueClient) DeleteTable(ctx context.Context, params *glue.DeleteTableInput, optFns ...func(*glue.Options)) (*glue.DeleteTableOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.DeleteTableOutput), args.Error(1)
}
func (m *mockGlueClient) GetDatabase(ctx context.Context, params *glue.GetDatabaseInput, optFns ...func(*glue.Options)) (*glue.GetDatabaseOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.GetDatabaseOutput), args.Error(1)
}
func (m *mockGlueClient) GetDatabases(ctx context.Context, params *glue.GetDatabasesInput, optFns ...func(*glue.Options)) (*glue.GetDatabasesOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.GetDatabasesOutput), args.Error(1)
}
func (m *mockGlueClient) CreateDatabase(ctx context.Context, params *glue.CreateDatabaseInput, optFns ...func(*glue.Options)) (*glue.CreateDatabaseOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.CreateDatabaseOutput), args.Error(1)
}
func (m *mockGlueClient) DeleteDatabase(ctx context.Context, params *glue.DeleteDatabaseInput, optFns ...func(*glue.Options)) (*glue.DeleteDatabaseOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.DeleteDatabaseOutput), args.Error(1)
}
func (m *mockGlueClient) UpdateDatabase(ctx context.Context, params *glue.UpdateDatabaseInput, optFns ...func(*glue.Options)) (*glue.UpdateDatabaseOutput, error) {
args := m.Called(ctx, params, optFns)
+
return args.Get(0).(*glue.UpdateDatabaseOutput), args.Error(1)
}
@@ -90,6 +98,7 @@ var testIcebergGlueTable1 = types.Table{
metadataLocationPropsKey: "s3://test-bucket/test_table/metadata/abc123-123.metadata.json",
},
}
+
var testIcebergGlueTable2 = types.Table{
Name: aws.String("test_table2"),
Parameters: map[string]string{
@@ -105,6 +114,7 @@ var testIcebergGlueTable3 = types.Table{
metadataLocationPropsKey: "s3://test-bucket/test_table/metadata/abc789-789.metadata.json",
},
}
+
var testIcebergGlueTable4 = types.Table{
Name: aws.String("test_table4"),
Parameters: map[string]string{
@@ -112,6 +122,7 @@ var testIcebergGlueTable4 = types.Table{
metadataLocationPropsKey: "s3://test-bucket/test_table/metadata/abc123-789.metadata.json",
},
}
+
var testIcebergGlueTable5 = types.Table{
Name: aws.String("test_table5"),
Parameters: map[string]string{
@@ -259,7 +270,7 @@ func TestGlueListTablesError(t *testing.T) {
mockGlueSvc.On("GetTables", mock.Anything, &glue.GetTablesInput{
DatabaseName: aws.String("test_database"),
NextToken: aws.String("token1"),
- }, mock.Anything).Return(&glue.GetTablesOutput{}, fmt.Errorf("token expired")).Once()
+ }, mock.Anything).Return(&glue.GetTablesOutput{}, errors.New("token expired")).Once()
glueCatalog := &Catalog{
glueSvc: mockGlueSvc,
@@ -272,6 +283,7 @@ func TestGlueListTablesError(t *testing.T) {
for tbl, err := range iter {
if err != nil {
lastErr = err
+
break
}
tbls = append(tbls, tbl)
@@ -284,6 +296,7 @@ func TestGlueListTablesError(t *testing.T) {
mockGlueSvc.AssertExpectations(t)
}
+
func TestGlueListNamespaces(t *testing.T) {
assert := require.New(t)
@@ -415,7 +428,6 @@ func TestGlueCheckNamespaceExists(t *testing.T) {
exists, err := glueCatalog.CheckNamespaceExists(context.TODO(), DatabaseIdentifier("test_namespace"))
assert.NoError(err)
assert.True(exists)
-
}
func TestGlueCheckNamespaceNotExists(t *testing.T) {
diff --git a/catalog/internal/utils.go b/catalog/internal/utils.go
index 9b5e7bd..94c1bc7 100644
--- a/catalog/internal/utils.go
+++ b/catalog/internal/utils.go
@@ -20,6 +20,7 @@ package internal
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"github.com/apache/iceberg-go"
@@ -48,7 +49,7 @@ func WriteMetadata(ctx context.Context, metadata table.Metadata, loc string, pro
wfs, ok := fs.(io.WriteFileIO)
if !ok {
- return fmt.Errorf("filesystem IO does not support writing")
+ return errors.New("filesystem IO does not support writing")
}
out, err := wfs.Create(loc)
@@ -57,5 +58,6 @@ func WriteMetadata(ctx context.Context, metadata table.Metadata, loc string, pro
}
defer out.Close()
+
return json.NewEncoder(out).Encode(metadata)
}
diff --git a/catalog/registry.go b/catalog/registry.go
index bf24e83..58b921a 100644
--- a/catalog/registry.go
+++ b/catalog/registry.go
@@ -35,6 +35,7 @@ type registry map[string]Registrar
func (r registry) getKeys() []string {
regMutex.Lock()
defer regMutex.Unlock()
+
return slices.Collect(maps.Keys(r))
}
@@ -48,6 +49,7 @@ func (r registry) get(catalogType string) (Registrar, bool) {
regMutex.Lock()
defer regMutex.Unlock()
reg, ok := r[catalogType]
+
return reg, ok
}
diff --git a/catalog/registry_test.go b/catalog/registry_test.go
index df1d29f..5bf7d67 100644
--- a/catalog/registry_test.go
+++ b/catalog/registry_test.go
@@ -45,6 +45,7 @@ func TestCatalogRegistry(t *testing.T) {
catalog.Register("foobar", catalog.RegistrarFunc(func(ctx context.Context, s string, p iceberg.Properties) (catalog.Catalog, error) {
assert.Equal(t, "foobar", s)
assert.Equal(t, "baz", p.Get("foo", ""))
+
return nil, nil
}))
@@ -63,6 +64,7 @@ func TestCatalogRegistry(t *testing.T) {
catalog.Register("foobar", catalog.RegistrarFunc(func(ctx context.Context, s string, p iceberg.Properties) (catalog.Catalog, error) {
assert.Equal(t, "not found", s)
assert.Equal(t, "baz", p.Get("foo", ""))
+
return nil, nil
}))
@@ -74,12 +76,14 @@ func TestCatalogRegistry(t *testing.T) {
assert.Equal(t, "not found", s)
assert.Equal(t, "foobar://helloworld", p.Get("uri", ""))
assert.Equal(t, "baz", p.Get("foo", ""))
+
return nil, nil
}))
c, err = catalog.Load(ctx, "not found", iceberg.Properties{
"uri": "foobar://helloworld",
- "foo": "baz"})
+ "foo": "baz",
+ })
assert.Nil(t, c)
assert.NoError(t, err)
@@ -113,6 +117,7 @@ func TestCatalogWithEmptyName(t *testing.T) {
assert.Equal(t, "http://localhost:8181/", props.Get("uri", ""))
assert.Equal(t, "default-credential", props.Get("credential", ""))
assert.Equal(t, "/default/warehouse", props.Get("warehouse", ""))
+
return nil, nil
}))
c, err := catalog.Load(ctx, "", nil)
@@ -126,7 +131,6 @@ func TestCatalogWithEmptyName(t *testing.T) {
"mock",
}, catalog.GetRegisteredCatalogs())
catalog.Unregister("mock")
-
}
func TestCatalogLoadInvalidURI(t *testing.T) {
@@ -189,11 +193,11 @@ func TestRegistryFromConfig(t *testing.T) {
assert.Equal(t, "foobar", c.(*rest.Catalog).Name())
assert.Equal(t, "catalog_name", params.Get("warehouse"))
- c, err = catalog.Load(ctx, "foobar", iceberg.Properties{"warehouse": "overriden"})
+ c, err = catalog.Load(ctx, "foobar", iceberg.Properties{"warehouse": "overridden"})
assert.NoError(t, err)
assert.IsType(t, &rest.Catalog{}, c)
assert.Equal(t, "foobar", c.(*rest.Catalog).Name())
- assert.Equal(t, "overriden", params.Get("warehouse"))
+ assert.Equal(t, "overridden", params.Get("warehouse"))
srv.Close()
diff --git a/catalog/rest/rest.go b/catalog/rest/rest.go
index 55950d4..1950dfb 100644
--- a/catalog/rest/rest.go
+++ b/catalog/rest/rest.go
@@ -45,9 +45,7 @@ import (
"github.com/aws/aws-sdk-go-v2/config"
)
-var (
- _ catalog.Catalog = (*Catalog)(nil)
-)
+var _ catalog.Catalog = (*Catalog)(nil)
const (
pageSizeKey contextKey = "page_size"
@@ -129,6 +127,7 @@ func (t *commitTableResponse) UnmarshalJSON(b []byte) (err error) {
}
t.Metadata, err = table.ParseMetadataBytes(t.RawMetadata)
+
return
}
@@ -146,6 +145,7 @@ func (t *loadTableResponse) UnmarshalJSON(b []byte) (err error) {
}
t.Metadata, err = table.ParseMetadataBytes(t.RawMetadata)
+
return
}
@@ -183,6 +183,7 @@ func (o oauthErrorResponse) Error() string {
if o.ErrURI != "" {
msg += " (" + o.ErrURI + ")"
}
+
return msg
}
@@ -290,6 +291,7 @@ func doDelete[T any](ctx context.Context, baseURI *url.URL, path []string, cl *h
func doHead(ctx context.Context, baseURI *url.URL, path []string, cl *http.Client, override map[int]error) error {
_, err := do[struct{}](ctx, http.MethodHead, baseURI, path, cl, override, true)
+
return err
}
@@ -343,6 +345,7 @@ func handleNon200(rsp *http.Response, override map[int]error) error {
if override != nil {
if err, ok := override[rsp.StatusCode]; ok {
e.wrapping = err
+
return e
}
}
@@ -410,6 +413,7 @@ func fromProps(props iceberg.Properties) *options {
}
}
}
+
return o
}
@@ -436,6 +440,7 @@ func toProps(o *options) iceberg.Properties {
if o.authUri != nil {
setIf(keyAuthUrl, o.authUri.String())
}
+
return props
}
@@ -487,6 +492,7 @@ func (r *Catalog) init(ctx context.Context, ops *options, uri string) error {
r.baseURI = r.baseURI.JoinPath(ops.prefix)
}
r.props = toProps(ops)
+
return nil
}
@@ -632,6 +638,7 @@ func checkValidNamespace(ident table.Identifier) error {
if len(ident) < 1 {
return fmt.Errorf("%w: empty namespace identifier", catalog.ErrNoSuchNamespace)
}
+
return nil
}
@@ -658,6 +665,7 @@ func (r *Catalog) ListTables(ctx context.Context, namespace table.Identifier) it
tables, nextPageToken, err := r.listTablesPage(ctx, namespace, pageToken, pageSize)
if err != nil {
yield(table.Identifier{}, err)
+
return
}
for _, tbl := range tables {
@@ -701,8 +709,8 @@ func (r *Catalog) listTablesPage(ctx context.Context, namespace table.Identifier
for i, id := range rsp.Identifiers {
out[i] = append(id.Namespace, id.Name)
}
- return out, rsp.NextPageToken, nil
+ return out, rsp.NextPageToken, nil
}
func splitIdentForPath(ident table.Identifier) (string, string, error) {
@@ -791,6 +799,7 @@ func (r *Catalog) CommitTable(ctx context.Context, tbl *table.Table, requirement
config := maps.Clone(r.props)
maps.Copy(config, ret.Metadata.Properties())
+
return ret.Metadata, ret.MetadataLoc, nil
}
@@ -807,7 +816,8 @@ func (r *Catalog) RegisterTable(ctx context.Context, identifier table.Identifier
ret, err := doPost[payload, loadTableResponse](ctx, r.baseURI, []string{"namespaces", ns, "tables", tbl},
payload{Name: tbl, MetadataLoc: metadataLoc}, r.cl, map[int]error{
- http.StatusNotFound: catalog.ErrNoSuchNamespace, http.StatusConflict: catalog.ErrTableAlreadyExists})
+ http.StatusNotFound: catalog.ErrNoSuchNamespace, http.StatusConflict: catalog.ErrTableAlreadyExists,
+ })
if err != nil {
return nil, err
}
@@ -815,6 +825,7 @@ func (r *Catalog) RegisterTable(ctx context.Context, identifier table.Identifier
config := maps.Clone(r.props)
maps.Copy(config, ret.Metadata.Properties())
maps.Copy(config, ret.Config)
+
return r.tableFromResponse(ctx, identifier, ret.Metadata, ret.MetadataLoc, config)
}
@@ -927,7 +938,9 @@ func (r *Catalog) CreateNamespace(ctx context.Context, namespace table.Identifie
_, err := doPost[map[string]any, struct{}](ctx, r.baseURI, []string{"namespaces"},
map[string]any{"namespace": namespace, "properties": props}, r.cl, map[int]error{
- http.StatusNotFound: catalog.ErrNoSuchNamespace, http.StatusConflict: catalog.ErrNamespaceAlreadyExists})
+ http.StatusNotFound: catalog.ErrNoSuchNamespace, http.StatusConflict: catalog.ErrNamespaceAlreadyExists,
+ })
+
return err
}
@@ -982,8 +995,8 @@ func (r *Catalog) LoadNamespaceProperties(ctx context.Context, namespace table.I
}
func (r *Catalog) UpdateNamespaceProperties(ctx context.Context, namespace table.Identifier,
- removals []string, updates iceberg.Properties) (catalog.PropertiesUpdateSummary, error) {
-
+ removals []string, updates iceberg.Properties,
+) (catalog.PropertiesUpdateSummary, error) {
if err := checkValidNamespace(namespace); err != nil {
return catalog.PropertiesUpdateSummary{}, err
}
@@ -994,6 +1007,7 @@ func (r *Catalog) UpdateNamespaceProperties(ctx context.Context, namespace table
}
ns := strings.Join(namespace, namespaceSeparator)
+
return doPost[payload, catalog.PropertiesUpdateSummary](ctx, r.baseURI, []string{"namespaces", ns, "properties"},
payload{Remove: removals, Updates: updates}, r.cl, map[int]error{http.StatusNotFound: catalog.ErrNoSuchNamespace})
}
@@ -1009,6 +1023,7 @@ func (r *Catalog) CheckNamespaceExists(ctx context.Context, namespace table.Iden
if errors.Is(err, catalog.ErrNoSuchNamespace) {
return false, nil
}
+
return false, err
}
@@ -1026,8 +1041,10 @@ func (r *Catalog) CheckTableExists(ctx context.Context, identifier table.Identif
if errors.Is(err, catalog.ErrNoSuchTable) {
return false, nil
}
+
return false, err
}
+
return true, nil
}
@@ -1040,6 +1057,7 @@ func (r *Catalog) ListViews(ctx context.Context, namespace table.Identifier) ite
views, nextPageToken, err := r.listViewsPage(ctx, namespace, pageToken, pageSize)
if err != nil {
yield(table.Identifier{}, err)
+
return
}
for _, view := range views {
@@ -1085,6 +1103,7 @@ func (r *Catalog) listViewsPage(ctx context.Context, namespace table.Identifier,
for i, id := range rsp.Identifiers {
out[i] = append(id.Namespace, id.Name)
}
+
return out, rsp.NextPageToken, nil
}
@@ -1092,6 +1111,7 @@ func (r *Catalog) getPageSize(ctx context.Context) int {
if pageSize, ok := ctx.Value(pageSizeKey).(int); ok {
return pageSize
}
+
return defaultPageSize
}
@@ -1107,6 +1127,7 @@ func (r *Catalog) DropView(ctx context.Context, identifier table.Identifier) err
_, err = doDelete[struct{}](ctx, r.baseURI, []string{"namespaces", ns, "views", view}, r.cl,
map[int]error{http.StatusNotFound: catalog.ErrNoSuchView})
+
return err
}
@@ -1122,7 +1143,9 @@ func (r *Catalog) CheckViewExists(ctx context.Context, identifier table.Identifi
if errors.Is(err, catalog.ErrNoSuchView) {
return false, nil
}
+
return false, err
}
+
return true, nil
}
diff --git a/catalog/rest/rest_internal_test.go b/catalog/rest/rest_internal_test.go
index 0a2e6f1..af3517e 100644
--- a/catalog/rest/rest_internal_test.go
+++ b/catalog/rest/rest_internal_test.go
@@ -35,7 +35,8 @@ func TestAuthHeader(t *testing.T) {
mux.HandleFunc("/v1/config", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{
- "defaults": map[string]any{}, "overrides": map[string]any{}})
+ "defaults": map[string]any{}, "overrides": map[string]any{},
+ })
})
mux.HandleFunc("/v1/oauth/tokens", func(w http.ResponseWriter, req *http.Request) {
@@ -81,7 +82,8 @@ func TestAuthUriHeader(t *testing.T) {
mux.HandleFunc("/v1/config", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{
- "defaults": map[string]any{}, "overrides": map[string]any{}})
+ "defaults": map[string]any{}, "overrides": map[string]any{},
+ })
})
mux.HandleFunc("/auth-token-url", func(w http.ResponseWriter, req *http.Request) {
diff --git a/catalog/rest/rest_test.go b/catalog/rest/rest_test.go
index 6962f60..b587318 100644
--- a/catalog/rest/rest_test.go
+++ b/catalog/rest/rest_test.go
@@ -346,6 +346,7 @@ func (r *RestCatalogSuite) TestListTablesPrefixed200() {
r.Require().NoError(lastErr)
r.Equal([]table.Identifier{{"examples", "fooshare"}}, tbls)
}
+
func (r *RestCatalogSuite) TestListTablesPagination() {
defaultPageSize := 20
namespace := "accounting"
@@ -428,6 +429,7 @@ func (r *RestCatalogSuite) TestListTablesPagination() {
}, tbls)
r.Require().NoError(lastErr)
}
+
func (r *RestCatalogSuite) TestListTablesPaginationErrorOnSubsequentPage() {
namespace := "accounting"
r.mux.HandleFunc("/v1/namespaces/"+namespace+"/tables", func(w http.ResponseWriter, req *http.Request) {
@@ -454,6 +456,7 @@ func (r *RestCatalogSuite) TestListTablesPaginationErrorOnSubsequentPage() {
},
"next-page-token": "token1",
})
+
return
}
@@ -467,6 +470,7 @@ func (r *RestCatalogSuite) TestListTablesPaginationErrorOnSubsequentPage() {
"code": 404,
},
})
+
return
}
@@ -482,6 +486,7 @@ func (r *RestCatalogSuite) TestListTablesPaginationErrorOnSubsequentPage() {
for tbl, err := range iter {
if err != nil {
lastErr = err
+
break
}
tbls = append(tbls, tbl)
@@ -497,6 +502,7 @@ func (r *RestCatalogSuite) TestListTablesPaginationErrorOnSubsequentPage() {
r.Error(lastErr)
r.ErrorContains(lastErr, "Token expired or invalid")
}
+
func (r *RestCatalogSuite) TestListTables404() {
namespace := "examples"
r.mux.HandleFunc("/v1/namespaces/"+namespace+"/tables", func(w http.ResponseWriter, req *http.Request) {
@@ -1690,6 +1696,7 @@ func (r *RestCatalogSuite) TestListViewsPaginationErrorOnSubsequentPage() {
},
"next-page-token": "token1",
})
+
return
}
@@ -1703,6 +1710,7 @@ func (r *RestCatalogSuite) TestListViewsPaginationErrorOnSubsequentPage() {
"code": 404,
},
})
+
return
}
@@ -1718,6 +1726,7 @@ func (r *RestCatalogSuite) TestListViewsPaginationErrorOnSubsequentPage() {
for view, err := range iter {
if err != nil {
lastErr = err
+
break
}
views = append(views, view)
diff --git a/catalog/sql/sql.go b/catalog/sql/sql.go
index 657576b..54c4ca6 100644
--- a/catalog/sql/sql.go
+++ b/catalog/sql/sql.go
@@ -90,9 +90,7 @@ func init() {
}))
}
-var (
- _ catalog.Catalog = (*Catalog)(nil)
-)
+var _ catalog.Catalog = (*Catalog)(nil)
var (
minimalNamespaceProps = iceberg.Properties{"exists": "true"}
@@ -126,6 +124,7 @@ func getDialect(d SupportedDialect) schema.Dialect {
ret = createDialect(d)
dialects[d] = ret
}
+
return ret
}
@@ -151,8 +150,10 @@ type sqlIcebergNamespaceProps struct {
func withReadTx[R any](ctx context.Context, db *bun.DB, fn func(context.Context, bun.Tx) (R, error)) (result R, err error) {
db.RunInTx(ctx, &sql.TxOptions{ReadOnly: true}, func(ctx context.Context, tx bun.Tx) error {
result, err = fn(ctx, tx)
+
return err
})
+
return
}
@@ -217,6 +218,7 @@ func (c *Catalog) CreateSQLTables(ctx context.Context) error {
_, err = c.db.NewCreateTable().Model((*sqlIcebergNamespaceProps)(nil)).
IfNotExists().Exec(ctx)
+
return err
}
@@ -229,6 +231,7 @@ func (c *Catalog) DropSQLTables(ctx context.Context) error {
_, err = c.db.NewDropTable().Model((*sqlIcebergNamespaceProps)(nil)).
IfExists().Exec(ctx)
+
return err
}
@@ -284,6 +287,7 @@ func checkValidNamespace(ident table.Identifier) error {
if len(ident) < 1 {
return fmt.Errorf("%w: empty namespace identifier", catalog.ErrNoSuchNamespace)
}
+
return nil
}
@@ -327,13 +331,12 @@ func (c *Catalog) CreateTable(ctx context.Context, ident table.Identifier, sc *i
TableName: tblIdent,
MetadataLocation: sql.NullString{String: metadataLocation, Valid: true},
}).Exec(ctx)
-
if err != nil {
return fmt.Errorf("failed to create table: %w", err)
}
+
return nil
})
-
if err != nil {
return nil, err
}
@@ -367,6 +370,7 @@ func (c *Catalog) LoadTable(ctx context.Context, identifier table.Identifier, pr
if err != nil {
return nil, fmt.Errorf("error encountered loading table %s: %w", identifier, err)
}
+
return t, nil
})
if err != nil {
@@ -384,6 +388,7 @@ func (c *Catalog) LoadTable(ctx context.Context, identifier table.Identifier, pr
if err != nil {
return nil, err
}
+
return table.NewFromLocation(identifier, result.MetadataLocation.String, iofs)
}
@@ -409,6 +414,7 @@ func (c *Catalog) DropTable(ctx context.Context, identifier table.Identifier) er
if n == 0 {
return fmt.Errorf("%w: %s", catalog.ErrNoSuchTable, identifier)
}
+
return nil
})
}
@@ -462,6 +468,7 @@ func (c *Catalog) RenameTable(ctx context.Context, from, to table.Identifier) (*
if n == 0 {
return fmt.Errorf("%w: %s", catalog.ErrNoSuchTable, from)
}
+
return nil
})
if err != nil {
@@ -490,6 +497,7 @@ func (c *Catalog) CreateNamespace(ctx context.Context, namespace table.Identifie
}
nsToCreate := strings.Join(namespace, ".")
+
return withWriteTx(ctx, c.db, func(ctx context.Context, tx bun.Tx) error {
toInsert := make([]sqlIcebergNamespaceProps, 0, len(props))
for k, v := range props {
@@ -505,6 +513,7 @@ func (c *Catalog) CreateNamespace(ctx context.Context, namespace table.Identifie
if err != nil {
return fmt.Errorf("error inserting namespace properties for namespace '%s': %w", namespace, err)
}
+
return nil
})
}
@@ -533,6 +542,7 @@ func (c *Catalog) DropNamespace(ctx context.Context, namespace table.Identifier)
if err != nil {
return err
}
+
break // there is already at least a table
}
@@ -547,6 +557,7 @@ func (c *Catalog) DropNamespace(ctx context.Context, namespace table.Identifier)
if err != nil {
return fmt.Errorf("error deleting namespace '%s': %w", namespace, err)
}
+
return nil
})
}
@@ -579,6 +590,7 @@ func (c *Catalog) LoadNamespaceProperties(ctx context.Context, namespace table.I
for _, p := range props {
result[p.PropertyKey] = p.PropertyValue.String
}
+
return result, nil
})
}
@@ -590,6 +602,7 @@ func (c *Catalog) ListTables(ctx context.Context, namespace table.Identifier) it
yield(table.Identifier{}, err)
}
}
+
return func(yield func(table.Identifier, error) bool) {
for _, t := range tables {
if !yield(t, nil) {
@@ -617,6 +630,7 @@ func (c *Catalog) listTablesAll(ctx context.Context, namespace table.Identifier)
Where("catalog_name = ?", c.name).
Where("table_namespace = ?", ns).
Scan(ctx)
+
return tables, err
})
if err != nil {
@@ -627,6 +641,7 @@ func (c *Catalog) listTablesAll(ctx context.Context, namespace table.Identifier)
for i, t := range tables {
ret[i] = append(strings.Split(t.TableNamespace, "."), t.TableName)
}
+
return ret, nil
}
@@ -660,6 +675,7 @@ func (c *Catalog) ListNamespaces(ctx context.Context, parent table.Identifier) (
}
err = c.db.ScanRows(ctx, rows, &namespaces)
+
return namespaces, err
})
if err != nil {
@@ -670,6 +686,7 @@ func (c *Catalog) ListNamespaces(ctx context.Context, parent table.Identifier) (
for i, n := range namespaces {
ret[i] = strings.Split(n, ".")
}
+
return ret, nil
}
@@ -692,6 +709,7 @@ func (c *Catalog) UpdateNamespaceProperties(ctx context.Context, namespace table
}
nsToUpdate := strings.Join(namespace, ".")
+
return summary, withWriteTx(ctx, c.db, func(ctx context.Context, tx bun.Tx) error {
var m *sqlIcebergNamespaceProps
if len(removals) > 0 {
diff --git a/catalog/sql/sql_test.go b/catalog/sql/sql_test.go
index c79a5e0..760d26e 100644
--- a/catalog/sql/sql_test.go
+++ b/catalog/sql/sql_test.go
@@ -37,56 +37,62 @@ import (
"github.com/uptrace/bun/driver/sqliteshim"
)
-var (
- tableSchemaNested = iceberg.NewSchemaWithIdentifiers(1,
- []int{1},
- iceberg.NestedField{
- ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: false},
- iceberg.NestedField{
- ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true},
- iceberg.NestedField{
- ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false},
- iceberg.NestedField{
- ID: 4, Name: "qux", Required: true, Type: &iceberg.ListType{
- ElementID: 5, Element: iceberg.PrimitiveTypes.String, ElementRequired: true}},
- iceberg.NestedField{
- ID: 6, Name: "quux",
- Type: &iceberg.MapType{
- KeyID: 7,
- KeyType: iceberg.PrimitiveTypes.String,
- ValueID: 8,
- ValueType: &iceberg.MapType{
- KeyID: 9,
- KeyType: iceberg.PrimitiveTypes.String,
- ValueID: 10,
- ValueType: iceberg.PrimitiveTypes.Int32,
- ValueRequired: true,
- },
+var tableSchemaNested = iceberg.NewSchemaWithIdentifiers(1,
+ []int{1},
+ iceberg.NestedField{
+ ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true,
+ },
+ iceberg.NestedField{
+ ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 4, Name: "qux", Required: true, Type: &iceberg.ListType{
+ ElementID: 5, Element: iceberg.PrimitiveTypes.String, ElementRequired: true,
+ },
+ },
+ iceberg.NestedField{
+ ID: 6, Name: "quux",
+ Type: &iceberg.MapType{
+ KeyID: 7,
+ KeyType: iceberg.PrimitiveTypes.String,
+ ValueID: 8,
+ ValueType: &iceberg.MapType{
+ KeyID: 9,
+ KeyType: iceberg.PrimitiveTypes.String,
+ ValueID: 10,
+ ValueType: iceberg.PrimitiveTypes.Int32,
ValueRequired: true,
},
- Required: true},
- iceberg.NestedField{
- ID: 11, Name: "location", Type: &iceberg.ListType{
- ElementID: 12, Element: &iceberg.StructType{
- FieldList: []iceberg.NestedField{
- {ID: 13, Name: "latitude", Type: iceberg.PrimitiveTypes.Float32, Required: false},
- {ID: 14, Name: "longitude", Type: iceberg.PrimitiveTypes.Float32, Required: false},
- },
- },
- ElementRequired: true},
- Required: true},
- iceberg.NestedField{
- ID: 15,
- Name: "person",
- Type: &iceberg.StructType{
+ ValueRequired: true,
+ },
+ Required: true,
+ },
+ iceberg.NestedField{
+ ID: 11, Name: "location", Type: &iceberg.ListType{
+ ElementID: 12, Element: &iceberg.StructType{
FieldList: []iceberg.NestedField{
- {ID: 16, Name: "name", Type: iceberg.PrimitiveTypes.String, Required: false},
- {ID: 17, Name: "age", Type: iceberg.PrimitiveTypes.Int32, Required: true},
+ {ID: 13, Name: "latitude", Type: iceberg.PrimitiveTypes.Float32, Required: false},
+ {ID: 14, Name: "longitude", Type: iceberg.PrimitiveTypes.Float32, Required: false},
},
},
- Required: false,
+ ElementRequired: true,
+ },
+ Required: true,
+ },
+ iceberg.NestedField{
+ ID: 15,
+ Name: "person",
+ Type: &iceberg.StructType{
+ FieldList: []iceberg.NestedField{
+ {ID: 16, Name: "name", Type: iceberg.PrimitiveTypes.String, Required: false},
+ {ID: 17, Name: "age", Type: iceberg.PrimitiveTypes.Int32, Required: true},
+ },
},
- )
+ Required: false,
+ },
)
func TestCreateSQLCatalogNoDriverDialect(t *testing.T) {
@@ -112,6 +118,7 @@ func randomString(n int) string {
for range n {
b.WriteByte(letters[rand.IntN(len(letters))])
}
+
return b.String()
}
@@ -129,6 +136,7 @@ func hiearchicalNamespaceName() string {
prefix := "my-iceberg-ns-"
tag1 := randomString(randomLen)
tag2 := randomString(randomLen)
+
return strings.Join([]string{prefix + tag1, prefix + tag2}, ".")
}
@@ -140,13 +148,15 @@ type SqliteCatalogTestSuite struct {
func (s *SqliteCatalogTestSuite) randomTableIdentifier() table.Identifier {
dbname, tablename := databaseName(), tableName()
- s.Require().NoError(os.MkdirAll(filepath.Join(s.warehouse, dbname+".db", tablename, "metadata"), 0755))
+ s.Require().NoError(os.MkdirAll(filepath.Join(s.warehouse, dbname+".db", tablename, "metadata"), 0o755))
+
return table.Identifier{dbname, tablename}
}
func (s *SqliteCatalogTestSuite) randomHierarchicalIdentifier() table.Identifier {
hierarchicalNsName, tableName := hiearchicalNamespaceName(), tableName()
- s.Require().NoError(os.MkdirAll(filepath.Join(s.warehouse, hierarchicalNsName+".db", tableName, "metadata"), 0755))
+ s.Require().NoError(os.MkdirAll(filepath.Join(s.warehouse, hierarchicalNsName+".db", tableName, "metadata"), 0o755))
+
return strings.Split(hierarchicalNsName+"."+tableName, ".")
}
diff --git a/cmd/iceberg/main.go b/cmd/iceberg/main.go
index 31845ee..4fe987e 100644
--- a/cmd/iceberg/main.go
+++ b/cmd/iceberg/main.go
@@ -364,6 +364,7 @@ func properties(ctx context.Context, output Output, cat catalog.Catalog, args pr
if args.propname == "" {
output.DescribeProperties(props)
+
return
}
diff --git a/cmd/iceberg/output_test.go b/cmd/iceberg/output_test.go
index 01dcebf..8a79d0c 100644
--- a/cmd/iceberg/output_test.go
+++ b/cmd/iceberg/output_test.go
@@ -30,7 +30,8 @@ var testArgs = []struct {
meta string
expected string
}{
- {`{
+ {
+ `{
"format-version": 2,
"table-uuid": "9c12d441-03fe-4693-9a96-a0705ddf69c1",
"location": "s3://bucket/test/location",
@@ -83,8 +84,10 @@ key | value
----------------------------------
read.split.target.size | 134217728
-`},
- {`{
+`,
+ },
+ {
+ `{
"format-version": 2,
"table-uuid": "9c12d441-03fe-4693-9a96-a0705ddf69c1",
"location": "s3://bucket/test/location",
@@ -174,7 +177,8 @@ key | value
----------------------------------
read.split.target.size | 134217728
-`},
+`,
+ },
}
func TestDescribeTable(t *testing.T) {
diff --git a/config/config.go b/config/config.go
index ef10d2f..d4cf88a 100644
--- a/config/config.go
+++ b/config/config.go
@@ -49,7 +49,6 @@ func LoadConfig(configPath string) []byte {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil
-
}
path = filepath.Join(homeDir, cfgFile)
}
@@ -57,6 +56,7 @@ func LoadConfig(configPath string) []byte {
if err != nil {
return nil
}
+
return file
}
@@ -70,6 +70,7 @@ func ParseConfig(file []byte, catalogName string) *CatalogConfig {
if !ok {
return nil
}
+
return &res
}
diff --git a/config/config_test.go b/config/config_test.go
index 4abae4b..c176b63 100644
--- a/config/config_test.go
+++ b/config/config_test.go
@@ -41,7 +41,8 @@ catalog:
warehouse: catalog_name
`), "default", nil},
// default catalog
- {[]byte(`
+ {
+ []byte(`
catalog:
default:
type: rest
@@ -56,9 +57,11 @@ catalog:
Output: "text",
Credential: "client-id:client-secret",
Warehouse: "catalog_name",
- }},
+ },
+ },
// custom catalog
- {[]byte(`
+ {
+ []byte(`
catalog:
custom-catalog:
type: rest
@@ -73,7 +76,8 @@ catalog:
Output: "text",
Credential: "client-id:client-secret",
Warehouse: "catalog_name",
- }},
+ },
+ },
}
func TestParseConfig(t *testing.T) {
diff --git a/exprs.go b/exprs.go
index 32ecc62..ed2bc8d 100644
--- a/exprs.go
+++ b/exprs.go
@@ -134,6 +134,7 @@ func (AlwaysTrue) Op() Operation { return OpTrue }
func (AlwaysTrue) Negate() BooleanExpression { return AlwaysFalse{} }
func (AlwaysTrue) Equals(other BooleanExpression) bool {
_, ok := other.(AlwaysTrue)
+
return ok
}
@@ -145,6 +146,7 @@ func (AlwaysFalse) Op() Operation { return OpFalse }
func (AlwaysFalse) Negate() BooleanExpression { return AlwaysTrue{} }
func (AlwaysFalse) Equals(other BooleanExpression) bool {
_, ok := other.(AlwaysFalse)
+
return ok
}
@@ -184,6 +186,7 @@ func (n NotExpr) Equals(other BooleanExpression) bool {
if !ok {
return false
}
+
return n.child.Equals(rhs.child)
}
@@ -224,6 +227,7 @@ func NewAnd(left, right BooleanExpression, addl ...BooleanExpression) BooleanExp
for _, a := range addl {
folded = newAnd(folded, a)
}
+
return folded
}
@@ -284,6 +288,7 @@ func NewOr(left, right BooleanExpression, addl ...BooleanExpression) BooleanExpr
for _, a := range addl {
folded = newOr(folded, a)
}
+
return folded
}
@@ -457,6 +462,7 @@ func (b *boundRef[T]) PosPath() []int {
inner = inner.inner
out = append(out, inner.pos)
}
+
return out
}
@@ -510,11 +516,13 @@ func (b *boundRef[T]) evalToLiteral(st structLike) Optional[Literal] {
if !lit.Type().Equals(b.field.Type) {
lit, _ = lit.To(b.field.Type)
}
+
return Optional[Literal]{Val: lit, Valid: true}
}
func (b *boundRef[T]) evalIsNull(st structLike) bool {
v := b.eval(st)
+
return !v.Valid
}
@@ -755,8 +763,10 @@ type BoundLiteralPredicate interface {
}
func newBoundLiteralPredicate[T LiteralType](op Operation, term BoundTerm, lit Literal) BoundPredicate {
- return &boundLiteralPredicate[T]{op: op, term: term.(bound[T]),
- lit: lit.(TypedLiteral[T])}
+ return &boundLiteralPredicate[T]{
+ op: op, term: term.(bound[T]),
+ lit: lit.(TypedLiteral[T]),
+ }
}
func createBoundLiteralPredicate(op Operation, term BoundTerm, lit Literal) (BoundPredicate, error) {
@@ -791,6 +801,7 @@ func createBoundLiteralPredicate(op Operation, term BoundTerm, lit Literal) (Bou
case UUIDType:
return newBoundLiteralPredicate[uuid.UUID](op, term, finalLit), nil
}
+
return nil, fmt.Errorf("%w: could not create bound literal predicate for term type %s",
ErrInvalidArgument, term.Type())
}
@@ -981,14 +992,17 @@ func (bsp *boundSetPredicate[T]) Equals(other BooleanExpression) bool {
func (bsp *boundSetPredicate[T]) Op() Operation { return bsp.op }
func (bsp *boundSetPredicate[T]) Negate() BooleanExpression {
- return &boundSetPredicate[T]{op: bsp.op.Negate(), term: bsp.term,
- lits: bsp.lits}
+ return &boundSetPredicate[T]{
+ op: bsp.op.Negate(), term: bsp.term,
+ lits: bsp.lits,
+ }
}
func (bsp *boundSetPredicate[T]) Term() BoundTerm { return bsp.term }
func (bsp *boundSetPredicate[T]) Ref() BoundReference { return bsp.term.Ref() }
func (bsp *boundSetPredicate[T]) String() string {
return fmt.Sprintf("Bound%s(term=%s, {%v})", bsp.op, bsp.term, bsp.lits.Members())
}
+
func (bsp *boundSetPredicate[T]) AsUnbound(r Reference, lits []Literal) UnboundPredicate {
litSet := newLiteralSet(lits...)
if litSet.Len() == 1 {
diff --git a/exprs_test.go b/exprs_test.go
index 3ea5257..1bb9c3f 100644
--- a/exprs_test.go
+++ b/exprs_test.go
@@ -35,6 +35,7 @@ func (ExprA) Op() iceberg.Operation { return iceberg.OpFalse }
func (ExprA) Negate() iceberg.BooleanExpression { return ExprB{} }
func (ExprA) Equals(o iceberg.BooleanExpression) bool {
_, ok := o.(ExprA)
+
return ok
}
@@ -45,6 +46,7 @@ func (ExprB) Op() iceberg.Operation { return iceberg.OpTrue }
func (ExprB) Negate() iceberg.BooleanExpression { return ExprA{} }
func (ExprB) Equals(o iceberg.BooleanExpression) bool {
_, ok := o.(ExprB)
+
return ok
}
@@ -67,13 +69,17 @@ func TestUnaryExpr(t *testing.T) {
})
sc := iceberg.NewSchema(1, iceberg.NestedField{
- ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Int32})
+ ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Int32,
+ })
sc2 := iceberg.NewSchema(1, iceberg.NestedField{
- ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Float64})
+ ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Float64,
+ })
sc3 := iceberg.NewSchema(1, iceberg.NestedField{
- ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Int32, Required: true})
+ ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Int32, Required: true,
+ })
sc4 := iceberg.NewSchema(1, iceberg.NestedField{
- ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Float32, Required: true})
+ ID: 2, Name: "a", Type: iceberg.PrimitiveTypes.Float32, Required: true,
+ })
t.Run("isnull and notnull", func(t *testing.T) {
t.Run("bind", func(t *testing.T) {
@@ -475,27 +481,39 @@ func TestBoolExprEQ(t *testing.T) {
tests := []struct {
exp, testexpra, testexprb iceberg.BooleanExpression
}{
- {iceberg.NewAnd(ExprA{}, ExprB{}),
+ {
+ iceberg.NewAnd(ExprA{}, ExprB{}),
iceberg.NewAnd(ExprA{}, ExprB{}),
- iceberg.NewOr(ExprA{}, ExprB{})},
- {iceberg.NewOr(ExprA{}, ExprB{}),
iceberg.NewOr(ExprA{}, ExprB{}),
- iceberg.NewAnd(ExprA{}, ExprB{})},
- {iceberg.NewAnd(ExprA{}, ExprB{}),
+ },
+ {
+ iceberg.NewOr(ExprA{}, ExprB{}),
+ iceberg.NewOr(ExprA{}, ExprB{}),
+ iceberg.NewAnd(ExprA{}, ExprB{}),
+ },
+ {
+ iceberg.NewAnd(ExprA{}, ExprB{}),
iceberg.NewAnd(ExprB{}, ExprA{}),
- iceberg.NewOr(ExprB{}, ExprA{})},
- {iceberg.NewOr(ExprA{}, ExprB{}),
iceberg.NewOr(ExprB{}, ExprA{}),
- iceberg.NewAnd(ExprB{}, ExprA{})},
+ },
+ {
+ iceberg.NewOr(ExprA{}, ExprB{}),
+ iceberg.NewOr(ExprB{}, ExprA{}),
+ iceberg.NewAnd(ExprB{}, ExprA{}),
+ },
{iceberg.NewNot(ExprA{}), iceberg.NewNot(ExprA{}), ExprB{}},
{ExprA{}, ExprA{}, ExprB{}},
{ExprB{}, ExprB{}, ExprA{}},
- {iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
+ {
iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
- iceberg.IsIn(iceberg.Reference("not_foo"), "hello", "world")},
- {iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
- iceberg.IsIn(iceberg.Reference("foo"), "goodbye", "world")},
+ iceberg.IsIn(iceberg.Reference("not_foo"), "hello", "world"),
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
+ iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
+ iceberg.IsIn(iceberg.Reference("foo"), "goodbye", "world"),
+ },
}
for i, tt := range tests {
@@ -513,16 +531,26 @@ func TestBoolExprNegate(t *testing.T) {
{iceberg.NewAnd(ExprA{}, ExprB{}), iceberg.NewOr(ExprB{}, ExprA{})},
{iceberg.NewOr(ExprB{}, ExprA{}), iceberg.NewAnd(ExprA{}, ExprB{})},
{iceberg.NewNot(ExprA{}), ExprA{}},
- {iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
- iceberg.NotIn(iceberg.Reference("foo"), "hello", "world")},
- {iceberg.NotIn(iceberg.Reference("foo"), "hello", "world"),
- iceberg.IsIn(iceberg.Reference("foo"), "hello", "world")},
- {iceberg.GreaterThan(iceberg.Reference("foo"), int32(5)),
- iceberg.LessThanEqual(iceberg.Reference("foo"), int32(5))},
- {iceberg.LessThan(iceberg.Reference("foo"), int32(5)),
- iceberg.GreaterThanEqual(iceberg.Reference("foo"), int32(5))},
- {iceberg.EqualTo(iceberg.Reference("foo"), int32(5)),
- iceberg.NotEqualTo(iceberg.Reference("foo"), int32(5))},
+ {
+ iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
+ iceberg.NotIn(iceberg.Reference("foo"), "hello", "world"),
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("foo"), "hello", "world"),
+ iceberg.IsIn(iceberg.Reference("foo"), "hello", "world"),
+ },
+ {
+ iceberg.GreaterThan(iceberg.Reference("foo"), int32(5)),
+ iceberg.LessThanEqual(iceberg.Reference("foo"), int32(5)),
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("foo"), int32(5)),
+ iceberg.GreaterThanEqual(iceberg.Reference("foo"), int32(5)),
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("foo"), int32(5)),
+ iceberg.NotEqualTo(iceberg.Reference("foo"), int32(5)),
+ },
{ExprA{}, ExprB{}},
}
@@ -554,10 +582,14 @@ func TestExprFolding(t *testing.T) {
tests := []struct {
lhs, rhs iceberg.BooleanExpression
}{
- {iceberg.NewAnd(ExprA{}, ExprB{}, ExprA{}),
- iceberg.NewAnd(iceberg.NewAnd(ExprA{}, ExprB{}), ExprA{})},
- {iceberg.NewOr(ExprA{}, ExprB{}, ExprA{}),
- iceberg.NewOr(iceberg.NewOr(ExprA{}, ExprB{}), ExprA{})},
+ {
+ iceberg.NewAnd(ExprA{}, ExprB{}, ExprA{}),
+ iceberg.NewAnd(iceberg.NewAnd(ExprA{}, ExprB{}), ExprA{}),
+ },
+ {
+ iceberg.NewOr(ExprA{}, ExprB{}, ExprA{}),
+ iceberg.NewOr(iceberg.NewOr(ExprA{}, ExprB{}), ExprA{}),
+ },
{iceberg.NewNot(iceberg.NewNot(ExprA{})), ExprA{}},
}
@@ -636,54 +668,100 @@ func TestToString(t *testing.T) {
e iceberg.BooleanExpression
expected string
}{
- {iceberg.NewAnd(null, nan),
- "And(left=IsNull(term=Reference(name='a')), right=IsNaN(term=Reference(name='g')))"},
- {iceberg.NewOr(null, nan),
- "Or(left=IsNull(term=Reference(name='a')), right=IsNaN(term=Reference(name='g')))"},
- {iceberg.NewNot(null),
- "Not(child=IsNull(term=Reference(name='a')))"},
+ {
+ iceberg.NewAnd(null, nan),
+ "And(left=IsNull(term=Reference(name='a')), right=IsNaN(term=Reference(name='g')))",
+ },
+ {
+ iceberg.NewOr(null, nan),
+ "Or(left=IsNull(term=Reference(name='a')), right=IsNaN(term=Reference(name='g')))",
+ },
+ {
+ iceberg.NewNot(null),
+ "Not(child=IsNull(term=Reference(name='a')))",
+ },
{iceberg.AlwaysTrue{}, "AlwaysTrue()"},
{iceberg.AlwaysFalse{}, "AlwaysFalse()"},
- {boundNull,
- "BoundIsNull(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)))"},
- {boundNull.Negate(),
- "BoundNotNull(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)))"},
- {boundNan,
- "BoundIsNaN(term=BoundReference(field=7: g: optional float, accessor=Accessor(position=6, inner=<nil>)))"},
- {boundNan.Negate(),
- "BoundNotNaN(term=BoundReference(field=7: g: optional float, accessor=Accessor(position=6, inner=<nil>)))"},
- {equal,
- "Equal(term=Reference(name='c'), literal=a)"},
- {equal.Negate(),
- "NotEqual(term=Reference(name='c'), literal=a)"},
- {grtequal,
- "GreaterThanEqual(term=Reference(name='a'), literal=a)"},
- {grtequal.Negate(),
- "LessThan(term=Reference(name='a'), literal=a)"},
- {greater,
- "GreaterThan(term=Reference(name='a'), literal=a)"},
- {greater.Negate(),
- "LessThanEqual(term=Reference(name='a'), literal=a)"},
- {startsWith,
- "StartsWith(term=Reference(name='b'), literal=foo)"},
- {startsWith.Negate(),
- "NotStartsWith(term=Reference(name='b'), literal=foo)"},
- {boundEqual,
- "BoundEqual(term=BoundReference(field=3: c: optional string, accessor=Accessor(position=2, inner=<nil>)), literal=a)"},
- {boundEqual.Negate(),
- "BoundNotEqual(term=BoundReference(field=3: c: optional string, accessor=Accessor(position=2, inner=<nil>)), literal=a)"},
- {boundGreater,
- "BoundGreaterThan(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)"},
- {boundGreater.Negate(),
- "BoundLessThanEqual(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)"},
- {boundGrtEqual,
- "BoundGreaterThanEqual(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)"},
- {boundGrtEqual.Negate(),
- "BoundLessThan(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)"},
- {boundStarts,
- "BoundStartsWith(term=BoundReference(field=2: b: optional string, accessor=Accessor(position=1, inner=<nil>)), literal=foo)"},
- {boundStarts.Negate(),
- "BoundNotStartsWith(term=BoundReference(field=2: b: optional string, accessor=Accessor(position=1, inner=<nil>)), literal=foo)"},
+ {
+ boundNull,
+ "BoundIsNull(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)))",
+ },
+ {
+ boundNull.Negate(),
+ "BoundNotNull(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)))",
+ },
+ {
+ boundNan,
+ "BoundIsNaN(term=BoundReference(field=7: g: optional float, accessor=Accessor(position=6, inner=<nil>)))",
+ },
+ {
+ boundNan.Negate(),
+ "BoundNotNaN(term=BoundReference(field=7: g: optional float, accessor=Accessor(position=6, inner=<nil>)))",
+ },
+ {
+ equal,
+ "Equal(term=Reference(name='c'), literal=a)",
+ },
+ {
+ equal.Negate(),
+ "NotEqual(term=Reference(name='c'), literal=a)",
+ },
+ {
+ grtequal,
+ "GreaterThanEqual(term=Reference(name='a'), literal=a)",
+ },
+ {
+ grtequal.Negate(),
+ "LessThan(term=Reference(name='a'), literal=a)",
+ },
+ {
+ greater,
+ "GreaterThan(term=Reference(name='a'), literal=a)",
+ },
+ {
+ greater.Negate(),
+ "LessThanEqual(term=Reference(name='a'), literal=a)",
+ },
+ {
+ startsWith,
+ "StartsWith(term=Reference(name='b'), literal=foo)",
+ },
+ {
+ startsWith.Negate(),
+ "NotStartsWith(term=Reference(name='b'), literal=foo)",
+ },
+ {
+ boundEqual,
+ "BoundEqual(term=BoundReference(field=3: c: optional string, accessor=Accessor(position=2, inner=<nil>)), literal=a)",
+ },
+ {
+ boundEqual.Negate(),
+ "BoundNotEqual(term=BoundReference(field=3: c: optional string, accessor=Accessor(position=2, inner=<nil>)), literal=a)",
+ },
+ {
+ boundGreater,
+ "BoundGreaterThan(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)",
+ },
+ {
+ boundGreater.Negate(),
+ "BoundLessThanEqual(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)",
+ },
+ {
+ boundGrtEqual,
+ "BoundGreaterThanEqual(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)",
+ },
+ {
+ boundGrtEqual.Negate(),
+ "BoundLessThan(term=BoundReference(field=1: a: optional string, accessor=Accessor(position=0, inner=<nil>)), literal=a)",
+ },
+ {
+ boundStarts,
+ "BoundStartsWith(term=BoundReference(field=2: b: optional string, accessor=Accessor(position=1, inner=<nil>)), literal=foo)",
+ },
+ {
+ boundStarts.Negate(),
+ "BoundNotStartsWith(term=BoundReference(field=2: b: optional string, accessor=Accessor(position=1, inner=<nil>)), literal=foo)",
+ },
}
for _, tt := range tests {
diff --git a/internal/avro_schemas.go b/internal/avro_schemas.go
index 92365f8..e260747 100644
--- a/internal/avro_schemas.go
+++ b/internal/avro_schemas.go
@@ -29,27 +29,14 @@ func NullableSchema(schema avro.Schema) avro.Schema {
}))
}
-var (
- // for x := range 24 {
- // math.Floor(math.Log10(math.Abs(math.Pow(2, float64(8*x-1)-1))))
- // }
- // maxPrecision = [...]int{-1, 2, 4, 6, 9, 11, 14, 16, 18, 21,
- // 23, 26, 28, 31, 33, 35, 38, 40, 43, 45, 47, 50, 52, 55}
- // for p := range 40 {
- // for pos := range 24 {
- // if p > maxPrecision[pos] {
- // requiredLength[p] = pos-1
- // break
- // }
- // }
- // }
- requiredLength = [...]int{1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5,
- 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12,
- 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17}
-)
+var requiredLength = [...]int{
+ 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5,
+ 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12,
+ 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17,
+}
// DecimalRequiredBytes returns the required number of bytes to store a
-// decimal value of the given precision. If the precision is outside of
+// decimal value of the given precision. If the precision is outside
// the range (0, 40], this returns -1 as it is invalid.
func DecimalRequiredBytes(precision int) int {
if precision <= 0 || precision >= 40 {
@@ -395,6 +382,7 @@ func NewManifestFileSchema(version int) (avro.Schema, error) {
}
key := fmt.Sprintf("manifest_list_file_v%d", version)
+
return AvroSchemaCache.Get(key), nil
}
diff --git a/internal/mock_fs.go b/internal/mock_fs.go
index 75ceb42..20b84f8 100644
--- a/internal/mock_fs.go
+++ b/internal/mock_fs.go
@@ -32,11 +32,13 @@ type MockFS struct {
func (m *MockFS) Open(name string) (io.File, error) {
args := m.Called(name)
+
return args.Get(0).(io.File), args.Error(1)
}
func (m *MockFS) Create(name string) (io.FileWriter, error) {
args := m.Called(name)
+
return args.Get(0).(io.FileWriter), args.Error(1)
}
@@ -54,6 +56,7 @@ type MockFSReadFile struct {
func (m *MockFSReadFile) ReadFile(name string) ([]byte, error) {
args := m.Called(name)
+
return args.Get(0).([]byte), args.Error(1)
}
@@ -76,6 +79,7 @@ func (m *MockFile) Close() error {
return errors.New("already closed")
}
m.closed = true
+
return nil
}
@@ -83,6 +87,7 @@ func (m *MockFile) ReadAt(p []byte, off int64) (n int, err error) {
if m.closed {
return 0, errors.New("already closed")
}
+
return m.Contents.ReadAt(p, off)
}
@@ -90,5 +95,6 @@ func (m *MockFile) Seek(offset int64, whence int) (n int64, err error) {
if m.closed {
return 0, errors.New("already closed")
}
+
return m.Contents.Seek(offset, whence)
}
diff --git a/io/blob.go b/io/blob.go
index 42bb3c1..0b09d5d 100644
--- a/io/blob.go
+++ b/io/blob.go
@@ -93,9 +93,7 @@ func (bfs *blobFileIO) Open(path string) (File, error) {
return nil, &fs.PathError{Op: "open", Path: path, Err: fs.ErrInvalid}
}
- var (
- key, name = path, filepath.Base(path)
- )
+ key, name := path, filepath.Base(path)
r, err := bfs.NewReader(bfs.ctx, key, nil)
if err != nil {
@@ -107,6 +105,7 @@ func (bfs *blobFileIO) Open(path string) (File, error) {
func (bfs *blobFileIO) Remove(name string) error {
name = bfs.preprocess(name)
+
return bfs.Bucket.Delete(bfs.ctx, name)
}
@@ -116,6 +115,7 @@ func (bfs *blobFileIO) Create(name string) (FileWriter, error) {
func (bfs *blobFileIO) WriteFile(name string, content []byte) error {
name = bfs.preprocess(name)
+
return bfs.Bucket.WriteAll(bfs.ctx, name, content, nil)
}
@@ -138,6 +138,7 @@ func (io *blobFileIO) NewWriter(ctx context.Context, path string, overwrite bool
if err != nil {
return nil, &fs.PathError{Op: "new writer", Path: path, Err: err}
}
+
return nil, &fs.PathError{Op: "new writer", Path: path, Err: fs.ErrInvalid}
}
}
@@ -145,9 +146,11 @@ func (io *blobFileIO) NewWriter(ctx context.Context, path string, overwrite bool
if err != nil {
return nil, err
}
+
return &blobWriteFile{
Writer: bw,
- name: path},
+ name: path,
+ },
nil
}
diff --git a/io/gcs.go b/io/gcs.go
index d7da24b..8f462d1 100644
--- a/io/gcs.go
+++ b/io/gcs.go
@@ -46,6 +46,7 @@ func ParseGCSConfig(props map[string]string) *gcsblob.Options {
if path := props[GCSKeyPath]; path != "" {
o = append(o, option.WithCredentialsFile(path))
}
+
return &gcsblob.Options{
ClientOptions: o,
}
diff --git a/io/io.go b/io/io.go
index 277f06e..6731875 100644
--- a/io/io.go
+++ b/io/io.go
@@ -128,6 +128,7 @@ func FS(fsys fs.FS) IO {
if _, ok := fsys.(fs.ReadFileFS); ok {
return readFileFS{ioFS{fsys, nil}}
}
+
return ioFS{fsys, nil}
}
@@ -155,6 +156,7 @@ func (r readFileFS) ReadFile(name string) ([]byte, error) {
if !ok {
return nil, errMissingReadFile
}
+
return rfs.ReadFile(name)
}
@@ -187,6 +189,7 @@ func (f ioFS) Remove(name string) error {
if !ok {
return errMissingRemove
}
+
return r.Remove(name)
}
@@ -210,6 +213,7 @@ func (f ioFile) Seek(offset int64, whence int) (int64, error) {
if !ok {
return 0, errMissingSeek
}
+
return s.Seek(offset, whence)
}
@@ -218,6 +222,7 @@ func (f ioFile) ReadAt(p []byte, off int64) (n int, err error) {
if !ok {
return 0, errMissingReadAt
}
+
return r.ReadAt(p, off)
}
@@ -256,6 +261,7 @@ func inferFileIOFromSchema(ctx context.Context, path string, props map[string]st
default:
return nil, fmt.Errorf("IO for file '%s' not implemented", path)
}
+
return createBlobFS(ctx, bucket, parsed.Host), nil
}
diff --git a/io/local.go b/io/local.go
index 962f0d4..ff4e1cb 100644
--- a/io/local.go
+++ b/io/local.go
@@ -33,14 +33,15 @@ func (LocalFS) Open(name string) (File, error) {
func (LocalFS) Create(name string) (FileWriter, error) {
filename := strings.TrimPrefix(name, "file://")
- if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil {
+ if err := os.MkdirAll(filepath.Dir(filename), 0o777); err != nil {
return nil, err
}
+
return os.Create(filename)
}
func (LocalFS) WriteFile(name string, content []byte) error {
- return os.WriteFile(strings.TrimPrefix(name, "file://"), content, 0777)
+ return os.WriteFile(strings.TrimPrefix(name, "file://"), content, 0o777)
}
func (LocalFS) Remove(name string) error {
diff --git a/literals.go b/literals.go
index cd89e63..06ac8de 100644
--- a/literals.go
+++ b/literals.go
@@ -110,6 +110,7 @@ func NewLiteral[T LiteralType](val T) Literal {
func getComparator[T LiteralType]() Comparator[T] {
var z T
+
return NewLiteral(z).(TypedLiteral[T]).Comparator()
}
@@ -129,30 +130,37 @@ func LiteralFromBytes(typ Type, data []byte) (Literal, error) {
case BooleanType:
var v BoolLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case Int32Type:
var v Int32Literal
err := v.UnmarshalBinary(data)
+
return v, err
case Int64Type:
var v Int64Literal
err := v.UnmarshalBinary(data)
+
return v, err
case Float32Type:
var v Float32Literal
err := v.UnmarshalBinary(data)
+
return v, err
case Float64Type:
var v Float64Literal
err := v.UnmarshalBinary(data)
+
return v, err
case StringType:
var v StringLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case BinaryType:
var v BinaryLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case FixedType:
if len(data) != t.Len() {
@@ -165,26 +173,32 @@ func LiteralFromBytes(typ Type, data []byte) (Literal, error) {
}
var v FixedLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case DecimalType:
v := DecimalLiteral{Scale: t.scale}
err := v.UnmarshalBinary(data)
+
return v, err
case DateType:
var v DateLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case TimeType:
var v TimeLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case TimestampType, TimestampTzType:
var v TimestampLiteral
err := v.UnmarshalBinary(data)
+
return v, err
case UUIDType:
var v UUIDLiteral
err := v.UnmarshalBinary(data)
+
return v, err
}
@@ -251,6 +265,7 @@ func (ab aboveMaxLiteral[T]) To(t Type) (Literal, error) {
if ab.Type().Equals(t) {
return ab, nil
}
+
return nil, fmt.Errorf("%w: cannot change type of AboveMax%sLiteral",
ErrBadCast, reflect.TypeOf(T(0)).String())
}
@@ -294,6 +309,7 @@ func (bm belowMinLiteral[T]) To(t Type) (Literal, error) {
if bm.Type().Equals(t) {
return bm, nil
}
+
return nil, fmt.Errorf("%w: cannot change type of BelowMin%sLiteral",
ErrBadCast, reflect.TypeOf(T(0)).String())
}
@@ -346,8 +362,10 @@ func (BoolLiteral) Comparator() Comparator[bool] {
if v2 {
return 0
}
+
return 1
}
+
return -1
}
}
@@ -360,6 +378,7 @@ func (b BoolLiteral) To(t Type) (Literal, error) {
case BooleanType:
return b, nil
}
+
return nil, fmt.Errorf("%w: BoolLiteral to %s", ErrBadCast, t)
}
@@ -367,15 +386,14 @@ func (b BoolLiteral) Equals(l Literal) bool {
return literalEq(b, l)
}
-var (
- falseBin, trueBin = [1]byte{0x0}, [1]byte{0x1}
-)
+var falseBin, trueBin = [1]byte{0x0}, [1]byte{0x1}
func (b BoolLiteral) MarshalBinary() (data []byte, err error) {
// stored as 0x00 for false, and anything non-zero for True
if b {
return trueBin[:], nil
}
+
return falseBin[:], nil
}
@@ -385,6 +403,7 @@ func (b *BoolLiteral) UnmarshalBinary(data []byte) error {
return fmt.Errorf("%w: expected at least 1 byte for bool", ErrInvalidBinSerialization)
}
*b = data[0] != 0
+
return nil
}
@@ -421,6 +440,7 @@ func (i Int32Literal) To(t Type) (Literal, error) {
if err != nil {
return nil, fmt.Errorf("%w: failed to cast to DecimalType: %s", ErrBadCast, err.Error())
}
+
return DecimalLiteral{Val: out, Scale: t.scale}, nil
}
@@ -451,6 +471,7 @@ func (i Int32Literal) MarshalBinary() (data []byte, err error) {
// stored as 4 bytes in little endian order
data = make([]byte, 4)
binary.LittleEndian.PutUint32(data, uint32(i))
+
return
}
@@ -462,6 +483,7 @@ func (i *Int32Literal) UnmarshalBinary(data []byte) error {
}
*i = Int32Literal(binary.LittleEndian.Uint32(data))
+
return nil
}
@@ -479,6 +501,7 @@ func (i Int64Literal) To(t Type) (Literal, error) {
} else if math.MinInt32 > i {
return Int32BelowMinLiteral(), nil
}
+
return Int32Literal(i), nil
case Int64Type:
return i, nil
@@ -503,6 +526,7 @@ func (i Int64Literal) To(t Type) (Literal, error) {
if err != nil {
return nil, fmt.Errorf("%w: failed to cast to DecimalType: %s", ErrBadCast, err.Error())
}
+
return DecimalLiteral{Val: out, Scale: t.scale}, nil
}
@@ -533,6 +557,7 @@ func (i Int64Literal) MarshalBinary() (data []byte, err error) {
// stored as 8 byte little-endian
data = make([]byte, 8)
binary.LittleEndian.PutUint64(data, uint64(i))
+
return
}
@@ -543,6 +568,7 @@ func (i *Int64Literal) UnmarshalBinary(data []byte) error {
ErrInvalidBinSerialization, len(data))
}
*i = Int64Literal(binary.LittleEndian.Uint64(data))
+
return nil
}
@@ -563,6 +589,7 @@ func (f Float32Literal) To(t Type) (Literal, error) {
if err != nil {
return nil, err
}
+
return DecimalLiteral{Val: v, Scale: t.scale}, nil
}
@@ -577,6 +604,7 @@ func (f Float32Literal) MarshalBinary() (data []byte, err error) {
// stored as 4 bytes little endian
data = make([]byte, 4)
binary.LittleEndian.PutUint32(data, math.Float32bits(float32(f)))
+
return
}
@@ -587,6 +615,7 @@ func (f *Float32Literal) UnmarshalBinary(data []byte) error {
ErrInvalidBinSerialization, len(data))
}
*f = Float32Literal(math.Float32frombits(binary.LittleEndian.Uint32(data)))
+
return nil
}
@@ -604,6 +633,7 @@ func (f Float64Literal) To(t Type) (Literal, error) {
} else if -math.MaxFloat32 > f {
return Float32BelowMinLiteral(), nil
}
+
return Float32Literal(f), nil
case Float64Type:
return f, nil
@@ -612,6 +642,7 @@ func (f Float64Literal) To(t Type) (Literal, error) {
if err != nil {
return nil, err
}
+
return DecimalLiteral{Val: v, Scale: t.scale}, nil
}
@@ -626,6 +657,7 @@ func (f Float64Literal) MarshalBinary() (data []byte, err error) {
// stored as 8 bytes little endian
data = make([]byte, 8)
binary.LittleEndian.PutUint64(data, math.Float64bits(float64(f)))
+
return
}
@@ -636,6 +668,7 @@ func (f *Float64Literal) UnmarshalBinary(data []byte) error {
ErrInvalidBinSerialization, len(data))
}
*f = Float64Literal(math.Float64frombits(binary.LittleEndian.Uint64(data)))
+
return nil
}
@@ -646,15 +679,19 @@ func (d DateLiteral) Type() Type { return PrimitiveTypes.Date }
func (d DateLiteral) Value() Date { return Date(d) }
func (d DateLiteral) String() string {
t := Date(d).ToTime()
+
return t.Format("2006-01-02")
}
+
func (d DateLiteral) To(t Type) (Literal, error) {
switch t.(type) {
case DateType:
return d, nil
}
+
return nil, fmt.Errorf("%w: DateLiteral to %s", ErrBadCast, t)
}
+
func (d DateLiteral) Equals(other Literal) bool {
return literalEq(d, other)
}
@@ -666,6 +703,7 @@ func (d DateLiteral) MarshalBinary() (data []byte, err error) {
// stored as 4 byte little endian
data = make([]byte, 4)
binary.LittleEndian.PutUint32(data, uint32(d))
+
return
}
@@ -676,6 +714,7 @@ func (d *DateLiteral) UnmarshalBinary(data []byte) error {
ErrInvalidBinSerialization, len(data))
}
*d = DateLiteral(binary.LittleEndian.Uint32(data))
+
return nil
}
@@ -686,16 +725,19 @@ func (t TimeLiteral) Type() Type { return PrimitiveTypes.Time }
func (t TimeLiteral) Value() Time { return Time(t) }
func (t TimeLiteral) String() string {
tm := time.UnixMicro(int64(t)).UTC()
+
return tm.Format("15:04:05.000000")
}
+
func (t TimeLiteral) To(typ Type) (Literal, error) {
switch typ.(type) {
case TimeType:
return t, nil
}
- return nil, fmt.Errorf("%w: TimeLiteral to %s", ErrBadCast, typ)
+ return nil, fmt.Errorf("%w: TimeLiteral to %s", ErrBadCast, typ)
}
+
func (t TimeLiteral) Equals(other Literal) bool {
return literalEq(t, other)
}
@@ -704,6 +746,7 @@ func (t TimeLiteral) MarshalBinary() (data []byte, err error) {
// stored as 8 byte little-endian
data = make([]byte, 8)
binary.LittleEndian.PutUint64(data, uint64(t))
+
return
}
@@ -714,6 +757,7 @@ func (t *TimeLiteral) UnmarshalBinary(data []byte) error {
ErrInvalidBinSerialization, len(data))
}
*t = TimeLiteral(binary.LittleEndian.Uint64(data))
+
return nil
}
@@ -724,8 +768,10 @@ func (t TimestampLiteral) Type() Type { return PrimitiveTyp
func (t TimestampLiteral) Value() Timestamp { return Timestamp(t) }
func (t TimestampLiteral) String() string {
tm := Timestamp(t).ToTime()
+
return tm.Format("2006-01-02 15:04:05.000000")
}
+
func (t TimestampLiteral) To(typ Type) (Literal, error) {
switch typ.(type) {
case TimestampType:
@@ -735,8 +781,10 @@ func (t TimestampLiteral) To(typ Type) (Literal, error) {
case DateType:
return DateLiteral(Timestamp(t).ToDate()), nil
}
+
return nil, fmt.Errorf("%w: TimestampLiteral to %s", ErrBadCast, typ)
}
+
func (t TimestampLiteral) Equals(other Literal) bool {
return literalEq(t, other)
}
@@ -748,6 +796,7 @@ func (t TimestampLiteral) MarshalBinary() (data []byte, err error) {
// stored as 8 byte little endian
data = make([]byte, 8)
binary.LittleEndian.PutUint64(data, uint64(t))
+
return
}
@@ -758,6 +807,7 @@ func (t *TimestampLiteral) UnmarshalBinary(data []byte) error {
ErrInvalidBinSerialization, len(data))
}
*t = TimestampLiteral(binary.LittleEndian.Uint64(data))
+
return nil
}
@@ -799,6 +849,7 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: casting '%s' to %s",
errors.Join(ErrBadCast, err), s, typ)
}
+
return Float32Literal(n), nil
case Float64Type:
n, err := strconv.ParseFloat(string(s), 64)
@@ -806,6 +857,7 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: casting '%s' to %s",
errors.Join(ErrBadCast, err), s, typ)
}
+
return Float64Literal(n), nil
case DateType:
tm, err := time.Parse("2006-01-02", string(s))
@@ -813,6 +865,7 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: casting '%s' to %s - %s",
ErrBadCast, s, typ, err.Error())
}
+
return DateLiteral(tm.Truncate(24*time.Hour).Unix() / int64((time.Hour * 24).Seconds())), nil
case TimeType:
val, err := arrow.Time64FromString(string(s), arrow.Microsecond)
@@ -846,6 +899,7 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: casting '%s' to %s - %s",
ErrBadCast, s, typ, err.Error())
}
+
return UUIDLiteral(val), nil
case DecimalType:
n, err := decimal128.FromString(string(s), int32(t.precision), int32(t.scale))
@@ -853,6 +907,7 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: casting '%s' to %s - %s",
ErrBadCast, s, typ, err.Error())
}
+
return DecimalLiteral{Val: n, Scale: t.scale}, nil
case BooleanType:
val, err := strconv.ParseBool(string(s))
@@ -860,6 +915,7 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: casting '%s' to %s - %s",
ErrBadCast, s, typ, err.Error())
}
+
return BoolLiteral(val), nil
case BinaryType:
return BinaryLiteral(s), nil
@@ -868,8 +924,10 @@ func (s StringLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: cast '%s' to %s - wrong length",
ErrBadCast, s, t)
}
+
return FixedLiteral(s), nil
}
+
return nil, fmt.Errorf("%w: StringLiteral to %s", ErrBadCast, typ)
}
@@ -881,6 +939,7 @@ func (s StringLiteral) MarshalBinary() (data []byte, err error) {
// stored as UTF-8 bytes without length
// avoid copying by just returning a slice of the raw bytes
data = unsafe.Slice(unsafe.StringData(string(s)), len(s))
+
return
}
@@ -889,6 +948,7 @@ func (s *StringLiteral) UnmarshalBinary(data []byte) error {
// avoid copy, but this means that the passed in slice is being given
// to the literal for ownership
*s = StringLiteral(unsafe.String(unsafe.SliceData(data), len(data)))
+
return nil
}
@@ -908,6 +968,7 @@ func (b BinaryLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: cannot convert BinaryLiteral to UUID",
errors.Join(ErrBadCast, err))
}
+
return UUIDLiteral(val), nil
case FixedType:
if len(b) == t.len {
@@ -922,6 +983,7 @@ func (b BinaryLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: BinaryLiteral to %s", ErrBadCast, typ)
}
+
func (b BinaryLiteral) Equals(other Literal) bool {
rhs, ok := other.(BinaryLiteral)
if !ok {
@@ -934,12 +996,14 @@ func (b BinaryLiteral) Equals(other Literal) bool {
func (b BinaryLiteral) MarshalBinary() (data []byte, err error) {
// stored directly as is
data = b
+
return
}
func (b *BinaryLiteral) UnmarshalBinary(data []byte) error {
// stored directly as is
*b = BinaryLiteral(data)
+
return nil
}
@@ -957,6 +1021,7 @@ func (f FixedLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: cannot convert FixedLiteral to UUID - %s",
ErrBadCast, err.Error())
}
+
return UUIDLiteral(val), nil
case FixedType:
if len(f) == t.len {
@@ -972,6 +1037,7 @@ func (f FixedLiteral) To(typ Type) (Literal, error) {
return nil, fmt.Errorf("%w: FixedLiteral[%d] to %s",
ErrBadCast, len(f), typ)
}
+
func (f FixedLiteral) Equals(other Literal) bool {
rhs, ok := other.(FixedLiteral)
if !ok {
@@ -984,12 +1050,14 @@ func (f FixedLiteral) Equals(other Literal) bool {
func (f FixedLiteral) MarshalBinary() (data []byte, err error) {
// stored directly as is
data = f
+
return
}
func (f *FixedLiteral) UnmarshalBinary(data []byte) error {
// stored directly as is
*f = FixedLiteral(data)
+
return nil
}
@@ -1011,6 +1079,7 @@ func (u UUIDLiteral) To(typ Type) (Literal, error) {
case FixedType:
if len(u) == t.len {
v, _ := uuid.UUID(u).MarshalBinary()
+
return FixedLiteral(v), nil
}
@@ -1018,11 +1087,13 @@ func (u UUIDLiteral) To(typ Type) (Literal, error) {
ErrBadCast, typ, len(u), t.len)
case BinaryType:
v, _ := uuid.UUID(u).MarshalBinary()
+
return BinaryLiteral(v), nil
}
return nil, fmt.Errorf("%w: UUIDLiteral to %s", ErrBadCast, typ)
}
+
func (u UUIDLiteral) Equals(other Literal) bool {
rhs, ok := other.(UUIDLiteral)
if !ok {
@@ -1043,6 +1114,7 @@ func (u *UUIDLiteral) UnmarshalBinary(data []byte) error {
return err
}
*u = UUIDLiteral(out)
+
return nil
}
@@ -1123,16 +1195,19 @@ func (d DecimalLiteral) Equals(other Literal) bool {
if err != nil {
return false
}
+
return d.Val == rescaled
}
func (d DecimalLiteral) Increment() Literal {
d.Val = d.Val.Add(decimal128.FromU64(1))
+
return d
}
func (d DecimalLiteral) Decrement() Literal {
d.Val = d.Val.Sub(decimal128.FromU64(1))
+
return d
}
@@ -1149,6 +1224,7 @@ func (d DecimalLiteral) MarshalBinary() (data []byte, err error) {
}
data[len(data)-1] += 1
}
+
return
}
@@ -1157,12 +1233,14 @@ func (d *DecimalLiteral) UnmarshalBinary(data []byte) error {
// big-endian values using the minimum number of bytes
if len(data) == 0 {
d.Val = decimal128.Num{}
+
return nil
}
if int8(data[0]) >= 0 {
// not negative
d.Val = decimal128.FromBigInt((&big.Int{}).SetBytes(data))
+
return nil
}
@@ -1175,5 +1253,6 @@ func (d *DecimalLiteral) UnmarshalBinary(data []byte) error {
value := (&big.Int{}).SetBytes(out)
d.Val = decimal128.FromBigInt(value.Neg(value))
+
return nil
}
diff --git a/literals_test.go b/literals_test.go
index 4dbb7f2..96c6606 100644
--- a/literals_test.go
+++ b/literals_test.go
@@ -75,12 +75,18 @@ func TestIntToDecimalConversion(t *testing.T) {
ty iceberg.DecimalType
val iceberg.Decimal
}{
- {iceberg.DecimalTypeOf(9, 0),
- iceberg.Decimal{Val: decimal128.FromI64(34), Scale: 0}},
- {iceberg.DecimalTypeOf(9, 2),
- iceberg.Decimal{Val: decimal128.FromI64(3400), Scale: 2}},
- {iceberg.DecimalTypeOf(9, 4),
- iceberg.Decimal{Val: decimal128.FromI64(340000), Scale: 4}},
+ {
+ iceberg.DecimalTypeOf(9, 0),
+ iceberg.Decimal{Val: decimal128.FromI64(34), Scale: 0},
+ },
+ {
+ iceberg.DecimalTypeOf(9, 2),
+ iceberg.Decimal{Val: decimal128.FromI64(3400), Scale: 2},
+ },
+ {
+ iceberg.DecimalTypeOf(9, 4),
+ iceberg.Decimal{Val: decimal128.FromI64(340000), Scale: 4},
+ },
}
for _, tt := range tests {
@@ -128,12 +134,18 @@ func TestInt64Conversions(t *testing.T) {
{iceberg.Int64Literal(19709), iceberg.NewLiteral(iceberg.Date(19709))},
{iceberg.Int64Literal(51661919000), iceberg.NewLiteral(iceberg.Time(51661919000))},
{iceberg.Int64Literal(1647305201), iceberg.NewLiteral(iceberg.Timestamp(1647305201))},
- {iceberg.Int64Literal(34),
- iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(34), Scale: 0})},
- {iceberg.Int64Literal(34),
- iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(3400), Scale: 2})},
- {iceberg.Int64Literal(34),
- iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(340000), Scale: 4})},
+ {
+ iceberg.Int64Literal(34),
+ iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(34), Scale: 0}),
+ },
+ {
+ iceberg.Int64Literal(34),
+ iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(3400), Scale: 2}),
+ },
+ {
+ iceberg.Int64Literal(34),
+ iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(340000), Scale: 4}),
+ },
}
for _, tt := range tests {
@@ -171,12 +183,18 @@ func TestFloatConversions(t *testing.T) {
to iceberg.Literal
}{
{iceberg.Float32Literal(34.5), iceberg.NewLiteral(float64(34.5))},
- {iceberg.Float32Literal(34.56),
- iceberg.NewLiteral(iceberg.Decimal{Val: n1, Scale: 1})},
- {iceberg.Float32Literal(34.56),
- iceberg.NewLiteral(iceberg.Decimal{Val: n2, Scale: 2})},
- {iceberg.Float32Literal(34.56),
- iceberg.NewLiteral(iceberg.Decimal{Val: n3, Scale: 4})},
+ {
+ iceberg.Float32Literal(34.56),
+ iceberg.NewLiteral(iceberg.Decimal{Val: n1, Scale: 1}),
+ },
+ {
+ iceberg.Float32Literal(34.56),
+ iceberg.NewLiteral(iceberg.Decimal{Val: n2, Scale: 2}),
+ },
+ {
+ iceberg.Float32Literal(34.56),
+ iceberg.NewLiteral(iceberg.Decimal{Val: n3, Scale: 4}),
+ },
}
for _, tt := range tests {
@@ -198,12 +216,18 @@ func TestFloat64Conversions(t *testing.T) {
to iceberg.Literal
}{
{iceberg.Float64Literal(34.5), iceberg.NewLiteral(float32(34.5))},
- {iceberg.Float64Literal(34.56),
- iceberg.NewLiteral(iceberg.Decimal{Val: n1, Scale: 1})},
- {iceberg.Float64Literal(34.56),
- iceberg.NewLiteral(iceberg.Decimal{Val: n2, Scale: 2})},
- {iceberg.Float64Literal(34.56),
- iceberg.NewLiteral(iceberg.Decimal{Val: n3, Scale: 4})},
+ {
+ iceberg.Float64Literal(34.56),
+ iceberg.NewLiteral(iceberg.Decimal{Val: n1, Scale: 1}),
+ },
+ {
+ iceberg.Float64Literal(34.56),
+ iceberg.NewLiteral(iceberg.Decimal{Val: n2, Scale: 2}),
+ },
+ {
+ iceberg.Float64Literal(34.56),
+ iceberg.NewLiteral(iceberg.Decimal{Val: n3, Scale: 4}),
+ },
}
for _, tt := range tests {
@@ -354,15 +378,23 @@ func TestStringLiteralConversion(t *testing.T) {
from iceberg.StringLiteral
to iceberg.Literal
}{
- {iceberg.StringLiteral("2017-08-18"),
- iceberg.NewLiteral(iceberg.Date(arrow.Date32FromTime(tm)))},
- {iceberg.StringLiteral("14:21:01.919"),
- iceberg.NewLiteral(iceberg.Time(51661919000))},
- {iceberg.StringLiteral("2017-08-18T14:21:01.919234"),
- iceberg.NewLiteral(iceberg.Timestamp(1503066061919234))},
+ {
+ iceberg.StringLiteral("2017-08-18"),
+ iceberg.NewLiteral(iceberg.Date(arrow.Date32FromTime(tm))),
+ },
+ {
+ iceberg.StringLiteral("14:21:01.919"),
+ iceberg.NewLiteral(iceberg.Time(51661919000)),
+ },
+ {
+ iceberg.StringLiteral("2017-08-18T14:21:01.919234"),
+ iceberg.NewLiteral(iceberg.Timestamp(1503066061919234)),
+ },
{iceberg.StringLiteral(expected.String()), iceberg.NewLiteral(expected)},
- {iceberg.StringLiteral("34.560"),
- iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(34560), Scale: 3})},
+ {
+ iceberg.StringLiteral("34.560"),
+ iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(34560), Scale: 3}),
+ },
{iceberg.StringLiteral("true"), iceberg.NewLiteral(true)},
{iceberg.StringLiteral("True"), iceberg.NewLiteral(true)},
{iceberg.StringLiteral("false"), iceberg.NewLiteral(false)},
@@ -411,11 +443,15 @@ func TestLiteralIdentityConversions(t *testing.T) {
{iceberg.NewLiteral(int64(340000000)), iceberg.PrimitiveTypes.Int64},
{iceberg.NewLiteral(float32(34.11)), iceberg.PrimitiveTypes.Float32},
{iceberg.NewLiteral(float64(3.5028235e38)), iceberg.PrimitiveTypes.Float64},
- {iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(3455), Scale: 2}),
- iceberg.DecimalTypeOf(9, 2)},
+ {
+ iceberg.NewLiteral(iceberg.Decimal{Val: decimal128.FromI64(3455), Scale: 2}),
+ iceberg.DecimalTypeOf(9, 2),
+ },
{iceberg.NewLiteral(iceberg.Date(19079)), iceberg.PrimitiveTypes.Date},
- {iceberg.NewLiteral(iceberg.Timestamp(1503091261919234)),
- iceberg.PrimitiveTypes.Timestamp},
+ {
+ iceberg.NewLiteral(iceberg.Timestamp(1503091261919234)),
+ iceberg.PrimitiveTypes.Timestamp,
+ },
{iceberg.NewLiteral("abc"), iceberg.PrimitiveTypes.String},
{iceberg.NewLiteral(uuid.New()), iceberg.PrimitiveTypes.UUID},
{fixedLit, iceberg.FixedTypeOf(3)},
@@ -737,38 +773,73 @@ func TestUnmarshalBinary(t *testing.T) {
{iceberg.PrimitiveTypes.Bool, []byte{0x0}, iceberg.BoolLiteral(false)},
{iceberg.PrimitiveTypes.Bool, []byte{0x1}, iceberg.BoolLiteral(true)},
{iceberg.PrimitiveTypes.Int32, []byte{0xd2, 0x04, 0x00, 0x00}, iceberg.Int32Literal(1234)},
- {iceberg.PrimitiveTypes.Int64, []byte{0xd2, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.Int64Literal(1234)},
+ {
+ iceberg.PrimitiveTypes.Int64,
+ []byte{0xd2, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.Int64Literal(1234),
+ },
{iceberg.PrimitiveTypes.Float32, []byte{0x00, 0x00, 0x90, 0xc0}, iceberg.Float32Literal(-4.5)},
- {iceberg.PrimitiveTypes.Float64, []byte{0x8d, 0x97, 0x6e, 0x12, 0x83, 0xc0, 0xf3, 0x3f},
- iceberg.Float64Literal(1.2345)},
+ {
+ iceberg.PrimitiveTypes.Float64,
+ []byte{0x8d, 0x97, 0x6e, 0x12, 0x83, 0xc0, 0xf3, 0x3f},
+ iceberg.Float64Literal(1.2345),
+ },
{iceberg.PrimitiveTypes.Date, []byte{0xe8, 0x03, 0x00, 0x00}, iceberg.DateLiteral(1000)},
{iceberg.PrimitiveTypes.Date, []byte{0xd2, 0x04, 0x00, 0x00}, iceberg.DateLiteral(1234)},
- {iceberg.PrimitiveTypes.Time, []byte{0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.TimeLiteral(10000)},
- {iceberg.PrimitiveTypes.Time, []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
- iceberg.TimeLiteral(100000000000)},
- {iceberg.PrimitiveTypes.TimestampTz, []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(400000)},
- {iceberg.PrimitiveTypes.TimestampTz, []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(100000000000)},
- {iceberg.PrimitiveTypes.Timestamp, []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(400000)},
- {iceberg.PrimitiveTypes.Timestamp, []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(100000000000)},
+ {
+ iceberg.PrimitiveTypes.Time,
+ []byte{0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.TimeLiteral(10000),
+ },
+ {
+ iceberg.PrimitiveTypes.Time,
+ []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
+ iceberg.TimeLiteral(100000000000),
+ },
+ {
+ iceberg.PrimitiveTypes.TimestampTz,
+ []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(400000),
+ },
+ {
+ iceberg.PrimitiveTypes.TimestampTz,
+ []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(100000000000),
+ },
+ {
+ iceberg.PrimitiveTypes.Timestamp,
+ []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(400000),
+ },
+ {
+ iceberg.PrimitiveTypes.Timestamp,
+ []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(100000000000),
+ },
{iceberg.PrimitiveTypes.String, []byte("ABC"), iceberg.StringLiteral("ABC")},
{iceberg.PrimitiveTypes.String, []byte("foo"), iceberg.StringLiteral("foo")},
- {iceberg.PrimitiveTypes.UUID,
+ {
+ iceberg.PrimitiveTypes.UUID,
[]byte{0xf7, 0x9c, 0x3e, 0x09, 0x67, 0x7c, 0x4b, 0xbd, 0xa4, 0x79, 0x3f, 0x34, 0x9c, 0xb7, 0x85, 0xe7},
- iceberg.UUIDLiteral(uuid.UUID{0xf7, 0x9c, 0x3e, 0x09, 0x67, 0x7c, 0x4b, 0xbd, 0xa4, 0x79, 0x3f, 0x34, 0x9c, 0xb7, 0x85, 0xe7})},
+ iceberg.UUIDLiteral(uuid.UUID{0xf7, 0x9c, 0x3e, 0x09, 0x67, 0x7c, 0x4b, 0xbd, 0xa4, 0x79, 0x3f, 0x34, 0x9c, 0xb7, 0x85, 0xe7}),
+ },
{iceberg.FixedTypeOf(3), []byte("foo"), iceberg.FixedLiteral([]byte("foo"))},
{iceberg.PrimitiveTypes.Binary, []byte("foo"), iceberg.BinaryLiteral([]byte("foo"))},
- {iceberg.DecimalTypeOf(5, 2), []byte{0x30, 0x39},
- iceberg.DecimalLiteral{Scale: 2, Val: decimal128.FromU64(12345)}},
- {iceberg.DecimalTypeOf(7, 4), []byte{0x12, 0xd6, 0x87},
- iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromU64(1234567)}},
- {iceberg.DecimalTypeOf(7, 4), []byte{0xff, 0xed, 0x29, 0x79},
- iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromI64(-1234567)}},
+ {
+ iceberg.DecimalTypeOf(5, 2),
+ []byte{0x30, 0x39},
+ iceberg.DecimalLiteral{Scale: 2, Val: decimal128.FromU64(12345)},
+ },
+ {
+ iceberg.DecimalTypeOf(7, 4),
+ []byte{0x12, 0xd6, 0x87},
+ iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromU64(1234567)},
+ },
+ {
+ iceberg.DecimalTypeOf(7, 4),
+ []byte{0xff, 0xed, 0x29, 0x79},
+ iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromI64(-1234567)},
+ },
}
for _, tt := range tests {
@@ -790,45 +861,80 @@ func TestRoundTripLiteralBinary(t *testing.T) {
{iceberg.PrimitiveTypes.Bool, []byte{0x0}, iceberg.BoolLiteral(false)},
{iceberg.PrimitiveTypes.Bool, []byte{0x1}, iceberg.BoolLiteral(true)},
{iceberg.PrimitiveTypes.Int32, []byte{0xd2, 0x04, 0x00, 0x00}, iceberg.Int32Literal(1234)},
- {iceberg.PrimitiveTypes.Int64, []byte{0xd2, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.Int64Literal(1234)},
+ {
+ iceberg.PrimitiveTypes.Int64,
+ []byte{0xd2, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.Int64Literal(1234),
+ },
{iceberg.PrimitiveTypes.Float32, []byte{0x00, 0x00, 0x90, 0xc0}, iceberg.Float32Literal(-4.5)},
{iceberg.PrimitiveTypes.Float32, []byte{0x19, 0x04, 0x9e, 0x3f}, iceberg.Float32Literal(1.2345)},
- {iceberg.PrimitiveTypes.Float64, []byte{0x8d, 0x97, 0x6e, 0x12, 0x83, 0xc0, 0xf3, 0x3f},
- iceberg.Float64Literal(1.2345)},
+ {
+ iceberg.PrimitiveTypes.Float64,
+ []byte{0x8d, 0x97, 0x6e, 0x12, 0x83, 0xc0, 0xf3, 0x3f},
+ iceberg.Float64Literal(1.2345),
+ },
{iceberg.PrimitiveTypes.Date, []byte{0xe8, 0x03, 0x00, 0x00}, iceberg.DateLiteral(1000)},
{iceberg.PrimitiveTypes.Date, []byte{0xd2, 0x04, 0x00, 0x00}, iceberg.DateLiteral(1234)},
- {iceberg.PrimitiveTypes.Time, []byte{0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.TimeLiteral(10000)},
- {iceberg.PrimitiveTypes.Time, []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
- iceberg.TimeLiteral(100000000000)},
- {iceberg.PrimitiveTypes.TimestampTz, []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(400000)},
- {iceberg.PrimitiveTypes.TimestampTz, []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(100000000000)},
- {iceberg.PrimitiveTypes.Timestamp, []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(400000)},
- {iceberg.PrimitiveTypes.Timestamp, []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
- iceberg.TimestampLiteral(100000000000)},
+ {
+ iceberg.PrimitiveTypes.Time,
+ []byte{0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.TimeLiteral(10000),
+ },
+ {
+ iceberg.PrimitiveTypes.Time,
+ []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
+ iceberg.TimeLiteral(100000000000),
+ },
+ {
+ iceberg.PrimitiveTypes.TimestampTz,
+ []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(400000),
+ },
+ {
+ iceberg.PrimitiveTypes.TimestampTz,
+ []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(100000000000),
+ },
+ {
+ iceberg.PrimitiveTypes.Timestamp,
+ []byte{0x80, 0x1a, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(400000),
+ },
+ {
+ iceberg.PrimitiveTypes.Timestamp,
+ []byte{0x00, 0xe8, 0x76, 0x48, 0x17, 0x00, 0x00, 0x00},
+ iceberg.TimestampLiteral(100000000000),
+ },
{iceberg.PrimitiveTypes.String, []byte("ABC"), iceberg.StringLiteral("ABC")},
{iceberg.PrimitiveTypes.String, []byte("foo"), iceberg.StringLiteral("foo")},
- {iceberg.PrimitiveTypes.UUID,
+ {
+ iceberg.PrimitiveTypes.UUID,
[]byte{0xf7, 0x9c, 0x3e, 0x09, 0x67, 0x7c, 0x4b, 0xbd, 0xa4, 0x79, 0x3f, 0x34, 0x9c, 0xb7, 0x85, 0xe7},
- iceberg.UUIDLiteral(uuid.UUID{0xf7, 0x9c, 0x3e, 0x09, 0x67, 0x7c, 0x4b, 0xbd, 0xa4, 0x79, 0x3f, 0x34, 0x9c, 0xb7, 0x85, 0xe7})},
+ iceberg.UUIDLiteral(uuid.UUID{0xf7, 0x9c, 0x3e, 0x09, 0x67, 0x7c, 0x4b, 0xbd, 0xa4, 0x79, 0x3f, 0x34, 0x9c, 0xb7, 0x85, 0xe7}),
+ },
{iceberg.FixedTypeOf(3), []byte("foo"), iceberg.FixedLiteral([]byte("foo"))},
{iceberg.PrimitiveTypes.Binary, []byte("foo"), iceberg.BinaryLiteral([]byte("foo"))},
- {iceberg.DecimalTypeOf(5, 2), []byte{0x30, 0x39},
- iceberg.DecimalLiteral{Scale: 2, Val: decimal128.FromU64(12345)}},
+ {
+ iceberg.DecimalTypeOf(5, 2),
+ []byte{0x30, 0x39},
+ iceberg.DecimalLiteral{Scale: 2, Val: decimal128.FromU64(12345)},
+ },
// decimal on 3-bytes to test that we use the minimum number of bytes and not a power of 2
// 1234567 is 00010010|11010110|10000111 in binary
// 00010010 -> 18, 11010110 -> 214, 10000111 -> 135
- {iceberg.DecimalTypeOf(7, 4), []byte{0x12, 0xd6, 0x87},
- iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromU64(1234567)}},
+ {
+ iceberg.DecimalTypeOf(7, 4),
+ []byte{0x12, 0xd6, 0x87},
+ iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromU64(1234567)},
+ },
// negative decimal to test two's complement
// -1234567 is 11101101|00101001|01111001 in binary
// 11101101 -> 237, 00101001 -> 41, 01111001 -> 121
- {iceberg.DecimalTypeOf(7, 4), []byte{0xed, 0x29, 0x79},
- iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromI64(-1234567)}},
+ {
+ iceberg.DecimalTypeOf(7, 4),
+ []byte{0xed, 0x29, 0x79},
+ iceberg.DecimalLiteral{Scale: 4, Val: decimal128.FromI64(-1234567)},
+ },
// test empty byte in decimal
// 11 is 00001011 in binary
// 00001011 -> 11
@@ -857,99 +963,181 @@ func TestLargeDecimalRoundTrip(t *testing.T) {
b []byte
val string
}{
- {iceberg.DecimalTypeOf(38, 21),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x18, 0x30, 0x73, 0xb9, 0x1e,
- 0x7e, 0xa2, 0xb3, 0x6a, 0x83},
- "12345678912345678.123456789123456789123"},
- {iceberg.DecimalTypeOf(38, 22),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x16, 0xbb, 0x01, 0x2f,
- 0x4c, 0xc3, 0x2b, 0x42, 0x29, 0x22},
- "1234567891234567.1234567891234567891234"},
- {iceberg.DecimalTypeOf(38, 23),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x0a, 0x42, 0xa1, 0xad,
- 0xe5, 0x2b, 0x33, 0x15, 0x9b, 0x59},
- "123456789123456.12345678912345678912345"},
- {iceberg.DecimalTypeOf(38, 24),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe8, 0xa2, 0xbb, 0xe9, 0x67,
- 0xba, 0x86, 0x77, 0xd8, 0x11, 0x80},
- "12345678912345.123456789123456789123456"},
- {iceberg.DecimalTypeOf(38, 25),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe5, 0x6b, 0x3a, 0xd2, 0x78,
- 0xdd, 0x04, 0xc8, 0x70, 0xaf, 0x07},
- "1234567891234.1234567891234567891234567"},
- {iceberg.DecimalTypeOf(38, 26),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xcd, 0x85, 0xc5, 0x03, 0x38, 0x37,
- 0x3c, 0x38, 0x66, 0xd6, 0x4e},
- "123456789123.12345678912345678912345678"},
- {iceberg.DecimalTypeOf(38, 27),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0x31, 0x46, 0xfd, 0xc7, 0x79,
- 0xca, 0x39, 0x7c, 0x04, 0x5f, 0x15},
- "12345678912.123456789123456789123456789"},
- {iceberg.DecimalTypeOf(38, 28),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x10, 0x52, 0x01, 0x72, 0x11, 0xda,
- 0x08, 0x5b, 0x08, 0x2b, 0xb6, 0xd3},
- "1234567891.1234567891234567891234567891"},
- {iceberg.DecimalTypeOf(38, 29),
- []byte{0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x18, 0x5b, 0x37, 0xc1,
- 0x78, 0x0b, 0x91, 0xb5, 0x24, 0x40},
- "123456789.12345678912345678912345678912"},
- {iceberg.DecimalTypeOf(38, 30),
- []byte{0x09, 0x49, 0xb0, 0xed, 0x1e, 0xdf, 0x80, 0x03, 0x47, 0x3b,
- 0x16, 0x9b, 0xf1, 0x13, 0x6a, 0x83},
- "12345678.123456789123456789123456789123"},
- {iceberg.DecimalTypeOf(38, 31),
- []byte{0x09, 0x49, 0xb0, 0x96, 0x2b, 0xac, 0x29, 0x64, 0x28, 0x70,
- 0x36, 0x29, 0xea, 0xc2, 0x29, 0x22},
- "1234567.1234567891234567891234567891234"},
- {iceberg.DecimalTypeOf(38, 32),
- []byte{0x09, 0x49, 0xad, 0xae, 0xe3, 0x68, 0xe7, 0x4f, 0xb5, 0x14,
- 0xbc, 0xdc, 0x2b, 0x95, 0x9b, 0x59},
- "123456.12345678912345678912345678912345"},
- {iceberg.DecimalTypeOf(38, 33),
- []byte{0x09, 0x49, 0x95, 0x94, 0x3e, 0x35, 0x93, 0xde, 0xb9, 0x2e,
- 0xef, 0x53, 0xb3, 0xd8, 0x11, 0x80},
- "12345.123456789123456789123456789123456"},
- {iceberg.DecimalTypeOf(38, 34),
- []byte{0x09, 0x48, 0xd5, 0xd7, 0x90, 0x78, 0xdf, 0x08, 0x1a, 0xf6,
- 0x43, 0x09, 0x06, 0x70, 0xaf, 0x07},
- "1234.1234567891234567891234567891234567"},
- {iceberg.DecimalTypeOf(38, 35),
- []byte{0x09, 0x43, 0x45, 0x82, 0x85, 0xc7, 0x56, 0x66, 0x24, 0x4d,
- 0x16, 0x82, 0x40, 0x66, 0xd6, 0x4e},
- "123.12345678912345678912345678912345678"},
- {iceberg.DecimalTypeOf(21, 16),
+ {
+ iceberg.DecimalTypeOf(38, 21),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x18, 0x30, 0x73, 0xb9, 0x1e,
+ 0x7e, 0xa2, 0xb3, 0x6a, 0x83,
+ },
+ "12345678912345678.123456789123456789123",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 22),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x16, 0xbb, 0x01, 0x2f,
+ 0x4c, 0xc3, 0x2b, 0x42, 0x29, 0x22,
+ },
+ "1234567891234567.1234567891234567891234",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 23),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x0a, 0x42, 0xa1, 0xad,
+ 0xe5, 0x2b, 0x33, 0x15, 0x9b, 0x59,
+ },
+ "123456789123456.12345678912345678912345",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 24),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe8, 0xa2, 0xbb, 0xe9, 0x67,
+ 0xba, 0x86, 0x77, 0xd8, 0x11, 0x80,
+ },
+ "12345678912345.123456789123456789123456",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 25),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe5, 0x6b, 0x3a, 0xd2, 0x78,
+ 0xdd, 0x04, 0xc8, 0x70, 0xaf, 0x07,
+ },
+ "1234567891234.1234567891234567891234567",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 26),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xcd, 0x85, 0xc5, 0x03, 0x38, 0x37,
+ 0x3c, 0x38, 0x66, 0xd6, 0x4e,
+ },
+ "123456789123.12345678912345678912345678",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 27),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0x31, 0x46, 0xfd, 0xc7, 0x79,
+ 0xca, 0x39, 0x7c, 0x04, 0x5f, 0x15,
+ },
+ "12345678912.123456789123456789123456789",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 28),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x10, 0x52, 0x01, 0x72, 0x11, 0xda,
+ 0x08, 0x5b, 0x08, 0x2b, 0xb6, 0xd3,
+ },
+ "1234567891.1234567891234567891234567891",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 29),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xf7, 0x13, 0xe9, 0x18, 0x5b, 0x37, 0xc1,
+ 0x78, 0x0b, 0x91, 0xb5, 0x24, 0x40,
+ },
+ "123456789.12345678912345678912345678912",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 30),
+ []byte{
+ 0x09, 0x49, 0xb0, 0xed, 0x1e, 0xdf, 0x80, 0x03, 0x47, 0x3b,
+ 0x16, 0x9b, 0xf1, 0x13, 0x6a, 0x83,
+ },
+ "12345678.123456789123456789123456789123",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 31),
+ []byte{
+ 0x09, 0x49, 0xb0, 0x96, 0x2b, 0xac, 0x29, 0x64, 0x28, 0x70,
+ 0x36, 0x29, 0xea, 0xc2, 0x29, 0x22,
+ },
+ "1234567.1234567891234567891234567891234",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 32),
+ []byte{
+ 0x09, 0x49, 0xad, 0xae, 0xe3, 0x68, 0xe7, 0x4f, 0xb5, 0x14,
+ 0xbc, 0xdc, 0x2b, 0x95, 0x9b, 0x59,
+ },
+ "123456.12345678912345678912345678912345",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 33),
+ []byte{
+ 0x09, 0x49, 0x95, 0x94, 0x3e, 0x35, 0x93, 0xde, 0xb9, 0x2e,
+ 0xef, 0x53, 0xb3, 0xd8, 0x11, 0x80,
+ },
+ "12345.123456789123456789123456789123456",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 34),
+ []byte{
+ 0x09, 0x48, 0xd5, 0xd7, 0x90, 0x78, 0xdf, 0x08, 0x1a, 0xf6,
+ 0x43, 0x09, 0x06, 0x70, 0xaf, 0x07,
+ },
+ "1234.1234567891234567891234567891234567",
+ },
+ {
+ iceberg.DecimalTypeOf(38, 35),
+ []byte{
+ 0x09, 0x43, 0x45, 0x82, 0x85, 0xc7, 0x56, 0x66, 0x24, 0x4d,
+ 0x16, 0x82, 0x40, 0x66, 0xd6, 0x4e,
+ },
+ "123.12345678912345678912345678912345678",
+ },
+ {
+ iceberg.DecimalTypeOf(21, 16),
[]byte{0x06, 0xb1, 0x3a, 0xe3, 0xc4, 0x4e, 0x94, 0xaf, 0x07},
- "12345.1234567891234567"},
- {iceberg.DecimalTypeOf(22, 17),
+ "12345.1234567891234567",
+ },
+ {
+ iceberg.DecimalTypeOf(22, 17),
[]byte{0x42, 0xec, 0x4c, 0xe5, 0xab, 0x11, 0xce, 0xd6, 0x4e},
- "12345.12345678912345678"},
- {iceberg.DecimalTypeOf(23, 18),
+ "12345.12345678912345678",
+ },
+ {
+ iceberg.DecimalTypeOf(23, 18),
[]byte{0x02, 0x9d, 0x3b, 0x00, 0xf8, 0xae, 0xb2, 0x14, 0x5f, 0x15},
- "12345.123456789123456789"},
- {iceberg.DecimalTypeOf(24, 19),
+ "12345.123456789123456789",
+ },
+ {
+ iceberg.DecimalTypeOf(24, 19),
[]byte{0x1a, 0x24, 0x4e, 0x09, 0xb6, 0xd2, 0xf4, 0xcb, 0xb6, 0xd3},
- "12345.1234567891234567891"},
- {iceberg.DecimalTypeOf(25, 20),
+ "12345.1234567891234567891",
+ },
+ {
+ iceberg.DecimalTypeOf(25, 20),
[]byte{0x01, 0x05, 0x6b, 0x0c, 0x61, 0x24, 0x3d, 0x8f, 0xf5, 0x24, 0x40},
- "12345.12345678912345678912"},
- {iceberg.DecimalTypeOf(26, 21),
+ "12345.12345678912345678912",
+ },
+ {
+ iceberg.DecimalTypeOf(26, 21),
[]byte{0x0a, 0x36, 0x2e, 0x7b, 0xcb, 0x6a, 0x67, 0x9f, 0x93, 0x6a, 0x83},
- "12345.123456789123456789123"},
- {iceberg.DecimalTypeOf(27, 22),
+ "12345.123456789123456789123",
+ },
+ {
+ iceberg.DecimalTypeOf(27, 22),
[]byte{0x66, 0x1d, 0xd0, 0xd5, 0xf2, 0x28, 0x0c, 0x3b, 0xc2, 0x29, 0x22},
- "12345.1234567891234567891234"},
- {iceberg.DecimalTypeOf(28, 23),
+ "12345.1234567891234567891234",
+ },
+ {
+ iceberg.DecimalTypeOf(28, 23),
[]byte{0x03, 0xfd, 0x2a, 0x28, 0x5b, 0x75, 0x90, 0x7a, 0x55, 0x95, 0x9b, 0x59},
- "12345.12345678912345678912345"},
- {iceberg.DecimalTypeOf(29, 24),
+ "12345.12345678912345678912345",
+ },
+ {
+ iceberg.DecimalTypeOf(29, 24),
[]byte{0x27, 0xe3, 0xa5, 0x93, 0x92, 0x97, 0xa4, 0xc7, 0x57, 0xd8, 0x11, 0x80},
- "12345.123456789123456789123456"},
- {iceberg.DecimalTypeOf(30, 25),
+ "12345.123456789123456789123456",
+ },
+ {
+ iceberg.DecimalTypeOf(30, 25),
[]byte{0x01, 0x8e, 0xe4, 0x77, 0xc3, 0xb9, 0xec, 0x6f, 0xc9, 0x6e, 0x70, 0xaf, 0x07},
- "12345.1234567891234567891234567"},
- {iceberg.DecimalTypeOf(31, 26),
+ "12345.1234567891234567891234567",
+ },
+ {
+ iceberg.DecimalTypeOf(31, 26),
[]byte{0x0f, 0x94, 0xec, 0xad, 0xa5, 0x43, 0x3c, 0x5d, 0xde, 0x50, 0x66, 0xd6, 0x4e},
- "12345.12345678912345678912345678"},
+ "12345.12345678912345678912345678",
+ },
}
for _, tt := range tests {
diff --git a/manifest.go b/manifest.go
index 6eea875..25dada1 100644
--- a/manifest.go
+++ b/manifest.go
@@ -87,46 +87,55 @@ func NewManifestV1Builder(path string, length int64, partitionSpecID int32, adde
func (b *ManifestV1Builder) PartitionType(st *StructType) *ManifestV1Builder {
b.m.partitionType = st
+
return b
}
func (b *ManifestV1Builder) AddedFiles(cnt int32) *ManifestV1Builder {
b.m.AddedFilesCount = &cnt
+
return b
}
func (b *ManifestV1Builder) ExistingFiles(cnt int32) *ManifestV1Builder {
b.m.ExistingFilesCount = &cnt
+
return b
}
func (b *ManifestV1Builder) DeletedFiles(cnt int32) *ManifestV1Builder {
b.m.DeletedFilesCount = &cnt
+
return b
}
func (b *ManifestV1Builder) AddedRows(cnt int64) *ManifestV1Builder {
b.m.AddedRowsCount = &cnt
+
return b
}
func (b *ManifestV1Builder) ExistingRows(cnt int64) *ManifestV1Builder {
b.m.ExistingRowsCount = &cnt
+
return b
}
func (b *ManifestV1Builder) DeletedRows(cnt int64) *ManifestV1Builder {
b.m.DeletedRowsCount = &cnt
+
return b
}
func (b *ManifestV1Builder) Partitions(p []FieldSummary) *ManifestV1Builder {
b.m.PartitionList = &p
+
return b
}
func (b *ManifestV1Builder) KeyMetadata(km []byte) *ManifestV1Builder {
b.m.Key = km
+
return b
}
@@ -149,6 +158,7 @@ type fallbackManifestFileV1 struct {
func (f *fallbackManifestFileV1) toManifest() *manifestFileV1 {
f.manifestFileV1.AddedSnapshotID = *f.AddedSnapshotID
+
return &f.manifestFileV1
}
@@ -175,6 +185,7 @@ func (m *manifestFileV1) PartitionSpecID() int32 { return m.SpecID }
func (m *manifestFileV1) ManifestContent() ManifestContent {
return ManifestContentData
}
+
func (m *manifestFileV1) SnapshotID() int64 {
return m.AddedSnapshotID
}
@@ -183,6 +194,7 @@ func (m *manifestFileV1) AddedDataFiles() int32 {
if m.AddedFilesCount == nil {
return 0
}
+
return *m.AddedFilesCount
}
@@ -190,6 +202,7 @@ func (m *manifestFileV1) ExistingDataFiles() int32 {
if m.ExistingFilesCount == nil {
return 0
}
+
return *m.ExistingFilesCount
}
@@ -197,6 +210,7 @@ func (m *manifestFileV1) DeletedDataFiles() int32 {
if m.DeletedFilesCount == nil {
return 0
}
+
return *m.DeletedFilesCount
}
@@ -204,6 +218,7 @@ func (m *manifestFileV1) AddedRows() int64 {
if m.AddedRowsCount == nil {
return 0
}
+
return *m.AddedRowsCount
}
@@ -211,6 +226,7 @@ func (m *manifestFileV1) ExistingRows() int64 {
if m.ExistingRowsCount == nil {
return 0
}
+
return *m.ExistingRowsCount
}
@@ -218,6 +234,7 @@ func (m *manifestFileV1) DeletedRows() int64 {
if m.DeletedRowsCount == nil {
return 0
}
+
return *m.DeletedRowsCount
}
@@ -236,6 +253,7 @@ func (m *manifestFileV1) Partitions() []FieldSummary {
if m.PartitionList == nil {
return nil
}
+
return *m.PartitionList
}
@@ -272,51 +290,61 @@ func NewManifestV2Builder(path string, length int64, partitionSpecID int32, cont
func (b *ManifestV2Builder) PartitionSchema(st *StructType) *ManifestV2Builder {
b.m.partitionType = st
+
return b
}
func (b *ManifestV2Builder) SequenceNum(num, minSeqNum int64) *ManifestV2Builder {
b.m.SeqNumber, b.m.MinSeqNumber = num, minSeqNum
+
return b
}
func (b *ManifestV2Builder) AddedFiles(cnt int32) *ManifestV2Builder {
b.m.AddedFilesCount = cnt
+
return b
}
func (b *ManifestV2Builder) ExistingFiles(cnt int32) *ManifestV2Builder {
b.m.ExistingFilesCount = cnt
+
return b
}
func (b *ManifestV2Builder) DeletedFiles(cnt int32) *ManifestV2Builder {
b.m.DeletedFilesCount = cnt
+
return b
}
func (b *ManifestV2Builder) AddedRows(cnt int64) *ManifestV2Builder {
b.m.AddedRowsCount = cnt
+
return b
}
func (b *ManifestV2Builder) ExistingRows(cnt int64) *ManifestV2Builder {
b.m.ExistingRowsCount = cnt
+
return b
}
func (b *ManifestV2Builder) DeletedRows(cnt int64) *ManifestV2Builder {
b.m.DeletedRowsCount = cnt
+
return b
}
func (b *ManifestV2Builder) Partitions(p []FieldSummary) *ManifestV2Builder {
b.m.PartitionList = &p
+
return b
}
func (b *ManifestV2Builder) KeyMetadata(km []byte) *ManifestV2Builder {
b.m.Key = km
+
return b
}
@@ -393,6 +421,7 @@ func (m *manifestFileV2) Partitions() []FieldSummary {
if m.PartitionList == nil {
return nil
}
+
return *m.PartitionList
}
@@ -420,6 +449,7 @@ func getFieldIDMap(sc avro.Schema) (map[string]int, map[int]avro.LogicalType) {
return f
}
}
+
return nil
}
@@ -443,6 +473,7 @@ func getFieldIDMap(sc avro.Schema) (map[string]int, map[int]avro.LogicalType) {
}
}
}
+
return result, logicalTypes
}
@@ -479,6 +510,7 @@ func fetchManifestEntries(m ManifestFile, fs iceio.IO, discardDeleted bool) ([]M
if f.Type().Type() == avro.Union {
isFallback = true
}
+
break
}
}
@@ -603,6 +635,7 @@ func ReadManifestList(in io.Reader) ([]ManifestFile, error) {
if f.Type().Type() == avro.Union {
fallbackAddedSnapshot = true
}
+
break
}
}
@@ -738,6 +771,7 @@ func (p *partitionFieldStats[T]) toSummary() FieldSummary {
func (p *partitionFieldStats[T]) update(value any) {
if value == nil {
p.containsNull = true
+
return
}
@@ -753,11 +787,13 @@ func (p *partitionFieldStats[T]) update(value any) {
case float32:
if math.IsNaN(float64(f)) {
p.containsNan = true
+
return
}
case float64:
if math.IsNaN(f) {
p.containsNan = true
+
return
}
}
@@ -798,6 +834,7 @@ func constructPartitionSummaries(spec PartitionSpec, schema *Schema, partitions
for i, stat := range fieldStats {
summaries[i] = stat.toSummary()
}
+
return summaries, nil
}
@@ -874,6 +911,7 @@ func NewManifestWriter(version int, out io.Writer, spec PartitionSpec, schema *S
ocf.WithCodec(ocf.Deflate))
w.writer = enc
+
return w, err
}
@@ -887,6 +925,7 @@ func (w *ManifestWriter) Close() error {
}
w.closed = true
+
return w.writer.Close()
}
@@ -999,16 +1038,19 @@ func (w *ManifestWriter) addEntry(entry ManifestEntry) error {
func (w *ManifestWriter) Add(entry ManifestEntry) error {
w.reusedEntry.wrap(EntryStatusADDED, w.snapshotID, entry.SequenceNum(), nil, entry.DataFile())
+
return w.addEntry(w.reusedEntry)
}
func (w *ManifestWriter) Delete(entry ManifestEntry) error {
w.reusedEntry.wrap(EntryStatusDELETED, w.snapshotID, entry.SequenceNum(), entry.FileSequenceNum(), entry.DataFile())
+
return w.addEntry(w.reusedEntry)
}
func (w *ManifestWriter) Existing(entry ManifestEntry) error {
w.reusedEntry.wrap(EntryStatusEXISTING, w.snapshotID, entry.SequenceNum(), entry.FileSequenceNum(), entry.DataFile())
+
return w.addEntry(w.reusedEntry)
}
@@ -1075,6 +1117,7 @@ func (m *ManifestListWriter) init(meta map[string][]byte) error {
}
m.writer = enc
+
return nil
}
@@ -1253,6 +1296,7 @@ func avroColMapToMap[K comparable, V any](c *[]colMap[K, V]) map[K]V {
for _, data := range *c {
out[data.Key] = data.Value
}
+
return out
}
@@ -1265,6 +1309,7 @@ func mapToAvroColMap[K comparable, V any](m map[K]V) *[]colMap[K, V] {
for k, v := range m {
out = append(out, colMap[K, V]{Key: k, Value: v})
}
+
return &out
}
@@ -1287,11 +1332,13 @@ func avroPartitionData(input map[string]any, nameToID map[string]int, logicalTyp
default:
out[k] = v
}
+
continue
}
}
out[k] = v
}
+
return out
}
@@ -1355,6 +1402,7 @@ func (d *dataFile) FilePath() string { return d.Path }
func (d *dataFile) FileFormat() FileFormat { return d.Format }
func (d *dataFile) Partition() map[string]any {
d.initializeMapData()
+
return d.PartitionData
}
@@ -1363,36 +1411,43 @@ func (d *dataFile) FileSizeBytes() int64 { return d.FileSize }
func (d *dataFile) ColumnSizes() map[int]int64 {
d.initializeMapData()
+
return d.colSizeMap
}
func (d *dataFile) ValueCounts() map[int]int64 {
d.initializeMapData()
+
return d.valCntMap
}
func (d *dataFile) NullValueCounts() map[int]int64 {
d.initializeMapData()
+
return d.nullCntMap
}
func (d *dataFile) NaNValueCounts() map[int]int64 {
d.initializeMapData()
+
return d.nanCntMap
}
func (d *dataFile) DistinctValueCounts() map[int]int64 {
d.initializeMapData()
+
return d.distinctCntMap
}
func (d *dataFile) LowerBoundValues() map[int][]byte {
d.initializeMapData()
+
return d.lowerBoundMap
}
func (d *dataFile) UpperBoundValues() map[int][]byte {
d.initializeMapData()
+
return d.upperBoundMap
}
@@ -1400,6 +1455,7 @@ func (d *dataFile) KeyMetadata() []byte {
if d.Key == nil {
return nil
}
+
return *d.Key
}
@@ -1407,6 +1463,7 @@ func (d *dataFile) SplitOffsets() []int64 {
if d.Splits == nil {
return nil
}
+
return *d.Splits
}
@@ -1414,6 +1471,7 @@ func (d *dataFile) EqualityFieldIDs() []int {
if d.EqualityIDs == nil {
return nil
}
+
return *d.EqualityIDs
}
@@ -1457,6 +1515,7 @@ type fallbackManifestEntryV1 struct {
func (f *fallbackManifestEntryV1) toEntry() *manifestEntryV1 {
f.manifestEntryV1.Snapshot = *f.Snapshot
+
return &f.manifestEntryV1
}
@@ -1469,6 +1528,7 @@ func (m *manifestEntryV1) SequenceNum() int64 {
if m.SeqNum == nil {
return 0
}
+
return *m.SeqNum
}
@@ -1488,6 +1548,7 @@ func (m *manifestEntryV1) wrap(status ManifestEntryStatus, snapshotID int64, seq
m.FileSeqNum = fileSeqNum
m.Data = datafile
+
return m
}
@@ -1513,12 +1574,14 @@ func NewManifestEntryV2Builder(status ManifestEntryStatus, snapshotID int64, dat
// SequenceNum sets the sequence number for the manifest entry.
func (b *ManifestEntryV2Builder) SequenceNum(num int64) *ManifestEntryV2Builder {
b.m.SeqNum = &num
+
return b
}
// FileSequenceNum sets the file sequence number for the manifest entry.
func (b *ManifestEntryV2Builder) FileSequenceNum(num int64) *ManifestEntryV2Builder {
b.m.FileSeqNum = &num
+
return b
}
@@ -1559,6 +1622,7 @@ func (m *manifestEntryV2) SnapshotID() int64 {
if m.Snapshot == nil {
return 0
}
+
return *m.Snapshot
}
@@ -1566,6 +1630,7 @@ func (m *manifestEntryV2) SequenceNum() int64 {
if m.SeqNum == nil {
return 0
}
+
return *m.SeqNum
}
@@ -1586,6 +1651,7 @@ func (m *manifestEntryV2) wrap(status ManifestEntryStatus, snapshotID int64, seq
m.FileSeqNum = fileSeqNum
m.Data = datafile
+
return m
}
@@ -1647,72 +1713,84 @@ func NewDataFileBuilder(
// BlockSizeInBytes sets the block size in bytes for the data file. Deprecated in v2.
func (b *DataFileBuilder) BlockSizeInBytes(size int64) *DataFileBuilder {
b.d.BlockSizeInBytes = size
+
return b
}
// ColumnSizes sets the column sizes for the data file.
func (b *DataFileBuilder) ColumnSizes(sizes map[int]int64) *DataFileBuilder {
b.d.ColSizes = mapToAvroColMap(sizes)
+
return b
}
// ValueCounts sets the value counts for the data file.
func (b *DataFileBuilder) ValueCounts(counts map[int]int64) *DataFileBuilder {
b.d.ValCounts = mapToAvroColMap(counts)
+
return b
}
// NullValueCounts sets the null value counts for the data file.
func (b *DataFileBuilder) NullValueCounts(counts map[int]int64) *DataFileBuilder {
b.d.NullCounts = mapToAvroColMap(counts)
+
return b
}
// NaNValueCounts sets the NaN value counts for the data file.
func (b *DataFileBuilder) NaNValueCounts(counts map[int]int64) *DataFileBuilder {
b.d.NaNCounts = mapToAvroColMap(counts)
+
return b
}
// DistinctValueCounts sets the distinct value counts for the data file.
func (b *DataFileBuilder) DistinctValueCounts(counts map[int]int64) *DataFileBuilder {
b.d.DistinctCounts = mapToAvroColMap(counts)
+
return b
}
// LowerBoundValues sets the lower bound values for the data file.
func (b *DataFileBuilder) LowerBoundValues(bounds map[int][]byte) *DataFileBuilder {
b.d.LowerBounds = mapToAvroColMap(bounds)
+
return b
}
// UpperBoundValues sets the upper bound values for the data file.
func (b *DataFileBuilder) UpperBoundValues(bounds map[int][]byte) *DataFileBuilder {
b.d.UpperBounds = mapToAvroColMap(bounds)
+
return b
}
// KeyMetadata sets the key metadata for the data file.
func (b *DataFileBuilder) KeyMetadata(key []byte) *DataFileBuilder {
b.d.Key = &key
+
return b
}
// SplitOffsets sets the split offsets for the data file.
func (b *DataFileBuilder) SplitOffsets(offsets []int64) *DataFileBuilder {
b.d.Splits = &offsets
+
return b
}
// EqualityFieldIDs sets the equality field ids for the data file.
func (b *DataFileBuilder) EqualityFieldIDs(ids []int) *DataFileBuilder {
b.d.EqualityIDs = &ids
+
return b
}
// SortOrderID sets the sort order id for the data file.
func (b *DataFileBuilder) SortOrderID(id int) *DataFileBuilder {
b.d.SortOrder = &id
+
return b
}
diff --git a/manifest_test.go b/manifest_test.go
index bf3515d..6eb68c9 100644
--- a/manifest_test.go
+++ b/manifest_test.go
@@ -43,7 +43,8 @@ var (
ContainsNull: true, ContainsNaN: &falseBool,
LowerBound: &[]byte{0x01, 0x00, 0x00, 0x00},
UpperBound: &[]byte{0x02, 0x00, 0x00, 0x00},
- }}).Build()}
+ }}).Build(),
+ }
manifestFileRecordsV2 = []ManifestFile{
NewManifestV2Builder("/home/iceberg/warehouse/nyc/taxis_partitioned/metadata/0125c686-8aa6-4502-bdcc-b6d17ca41a3b-m0.avro",
@@ -60,7 +61,8 @@ var (
ContainsNaN: &falseBool,
LowerBound: &[]byte{0x01, 0x00, 0x00, 0x00},
UpperBound: &[]byte{0x02, 0x00, 0x00, 0x00},
- }}).Build()}
+ }}).Build(),
+ }
entrySnapshotID int64 = 8744736658442914487
intZero = 0
@@ -416,7 +418,7 @@ func (m *ManifestTestSuite) writeManifestEntries() {
manifestEntryV2Recs[i] = rec
}
- var partitionSpec = NewPartitionSpecID(1,
+ partitionSpec := NewPartitionSpecID(1,
PartitionField{FieldID: 1000, SourceID: 1, Name: "VendorID", Transform: IdentityTransform{}},
PartitionField{FieldID: 1001, SourceID: 2, Name: "tpep_pickup_datetime", Transform: IdentityTransform{}})
@@ -446,7 +448,8 @@ func (m *ManifestTestSuite) TestManifestEntriesV1() {
mockfs.Test(m.T())
mockfs.On("Open", manifest.FilePath()).Return(&internal.MockFile{
- Contents: bytes.NewReader(m.v1ManifestEntries.Bytes())}, nil)
+ Contents: bytes.NewReader(m.v1ManifestEntries.Bytes()),
+ }, nil)
defer mockfs.AssertExpectations(m.T())
entries, err := manifest.FetchEntries(&mockfs, false)
m.Require().NoError(err)
@@ -646,7 +649,8 @@ func (m *ManifestTestSuite) TestManifestEntriesV2() {
mockfs.Test(m.T())
mockfs.On("Open", manifest.FilePath()).Return(&internal.MockFile{
- Contents: bytes.NewReader(m.v2ManifestEntries.Bytes())}, nil)
+ Contents: bytes.NewReader(m.v2ManifestEntries.Bytes()),
+ }, nil)
defer mockfs.AssertExpectations(m.T())
entries, err := manifest.FetchEntries(&mockfs, false)
m.Require().NoError(err)
diff --git a/partitions.go b/partitions.go
index 5bb0660..84f2727 100644
--- a/partitions.go
+++ b/partitions.go
@@ -92,6 +92,7 @@ func NewPartitionSpec(fields ...PartitionField) PartitionSpec {
func NewPartitionSpecID(id int, fields ...PartitionField) PartitionSpec {
ret := PartitionSpec{id: id, fields: fields}
ret.initialize()
+
return ret
}
@@ -128,6 +129,7 @@ func (ps PartitionSpec) MarshalJSON() ([]byte, error) {
if ps.fields == nil {
ps.fields = []PartitionField{}
}
+
return json.Marshal(struct {
ID int `json:"spec-id"`
Fields []PartitionField `json:"fields"`
@@ -146,14 +148,14 @@ func (ps *PartitionSpec) UnmarshalJSON(b []byte) error {
ps.id, ps.fields = aux.ID, aux.Fields
ps.initialize()
+
return nil
}
func (ps *PartitionSpec) initialize() {
ps.sourceIdToFields = make(map[int][]PartitionField)
for _, f := range ps.fields {
- ps.sourceIdToFields[f.SourceID] =
- append(ps.sourceIdToFields[f.SourceID], f)
+ ps.sourceIdToFields[f.SourceID] = append(ps.sourceIdToFields[f.SourceID], f)
}
}
@@ -206,6 +208,7 @@ func (ps *PartitionSpec) LastAssignedFieldID() int {
id = f.FieldID
}
}
+
return id
}
@@ -235,6 +238,7 @@ func (ps *PartitionSpec) PartitionType(schema *Schema) *StructType {
Required: false,
})
}
+
return &StructType{FieldList: nestedFields}
}
diff --git a/partitions_test.go b/partitions_test.go
index fda7b86..9055531 100644
--- a/partitions_test.go
+++ b/partitions_test.go
@@ -31,7 +31,8 @@ func TestPartitionSpec(t *testing.T) {
bucket := iceberg.BucketTransform{NumBuckets: 4}
idField1 := iceberg.PartitionField{
- SourceID: 3, FieldID: 1001, Name: "id", Transform: bucket}
+ SourceID: 3, FieldID: 1001, Name: "id", Transform: bucket,
+ }
spec1 := iceberg.NewPartitionSpec(idField1)
assert.Zero(t, spec1.ID())
@@ -46,7 +47,8 @@ func TestPartitionSpec(t *testing.T) {
// only differs by PartitionField FieldID
idField2 := iceberg.PartitionField{
- SourceID: 3, FieldID: 1002, Name: "id", Transform: bucket}
+ SourceID: 3, FieldID: 1002, Name: "id", Transform: bucket,
+ }
spec2 := iceberg.NewPartitionSpec(idField2)
assert.False(t, spec1.Equals(spec2))
@@ -85,10 +87,14 @@ func TestSerializeUnpartitionedSpec(t *testing.T) {
func TestSerializePartitionSpec(t *testing.T) {
spec := iceberg.NewPartitionSpecID(3,
- iceberg.PartitionField{SourceID: 1, FieldID: 1000,
- Transform: iceberg.TruncateTransform{Width: 19}, Name: "str_truncate"},
- iceberg.PartitionField{SourceID: 2, FieldID: 1001,
- Transform: iceberg.BucketTransform{NumBuckets: 25}, Name: "int_bucket"},
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1000,
+ Transform: iceberg.TruncateTransform{Width: 19}, Name: "str_truncate",
+ },
+ iceberg.PartitionField{
+ SourceID: 2, FieldID: 1001,
+ Transform: iceberg.BucketTransform{NumBuckets: 25}, Name: "int_bucket",
+ },
)
data, err := json.Marshal(spec)
@@ -120,14 +126,22 @@ func TestSerializePartitionSpec(t *testing.T) {
func TestPartitionType(t *testing.T) {
spec := iceberg.NewPartitionSpecID(3,
- iceberg.PartitionField{SourceID: 1, FieldID: 1000,
- Transform: iceberg.TruncateTransform{Width: 19}, Name: "str_truncate"},
- iceberg.PartitionField{SourceID: 2, FieldID: 1001,
- Transform: iceberg.BucketTransform{NumBuckets: 25}, Name: "int_bucket"},
- iceberg.PartitionField{SourceID: 3, FieldID: 1002,
- Transform: iceberg.IdentityTransform{}, Name: "bool_identity"},
- iceberg.PartitionField{SourceID: 1, FieldID: 1003,
- Transform: iceberg.VoidTransform{}, Name: "str_void"},
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1000,
+ Transform: iceberg.TruncateTransform{Width: 19}, Name: "str_truncate",
+ },
+ iceberg.PartitionField{
+ SourceID: 2, FieldID: 1001,
+ Transform: iceberg.BucketTransform{NumBuckets: 25}, Name: "int_bucket",
+ },
+ iceberg.PartitionField{
+ SourceID: 3, FieldID: 1002,
+ Transform: iceberg.IdentityTransform{}, Name: "bool_identity",
+ },
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1003,
+ Transform: iceberg.VoidTransform{}, Name: "str_void",
+ },
)
expected := &iceberg.StructType{
@@ -155,12 +169,18 @@ func TestPartitionSpecToPath(t *testing.T) {
iceberg.NestedField{ID: 3, Name: "int", Type: iceberg.PrimitiveTypes.Int32, Required: true})
spec := iceberg.NewPartitionSpecID(3,
- iceberg.PartitionField{SourceID: 1, FieldID: 1000,
- Transform: iceberg.TruncateTransform{Width: 19}, Name: "my#str%bucket"},
- iceberg.PartitionField{SourceID: 2, FieldID: 1001,
- Transform: iceberg.IdentityTransform{}, Name: "other str+bucket"},
- iceberg.PartitionField{SourceID: 3, FieldID: 1002,
- Transform: iceberg.BucketTransform{NumBuckets: 25}, Name: "my!int:bucket"})
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1000,
+ Transform: iceberg.TruncateTransform{Width: 19}, Name: "my#str%bucket",
+ },
+ iceberg.PartitionField{
+ SourceID: 2, FieldID: 1001,
+ Transform: iceberg.IdentityTransform{}, Name: "other str+bucket",
+ },
+ iceberg.PartitionField{
+ SourceID: 3, FieldID: 1002,
+ Transform: iceberg.BucketTransform{NumBuckets: 25}, Name: "my!int:bucket",
+ })
record := partitionRecord{"my+str", "( )", int32(10)}
// both partition field names and values should be URL encoded, with spaces
diff --git a/predicates.go b/predicates.go
index 24ace71..3b4fa00 100644
--- a/predicates.go
+++ b/predicates.go
@@ -57,6 +57,7 @@ func IsIn[T LiteralType](t UnboundTerm, vals ...T) BooleanExpression {
for _, v := range vals {
lits = append(lits, NewLiteral(v))
}
+
return SetPredicate(OpIn, t, lits)
}
@@ -72,6 +73,7 @@ func NotIn[T LiteralType](t UnboundTerm, vals ...T) BooleanExpression {
for _, v := range vals {
lits = append(lits, NewLiteral(v))
}
+
return SetPredicate(OpNotIn, t, lits)
}
diff --git a/schema.go b/schema.go
index 50d347c..6fbdf67 100644
--- a/schema.go
+++ b/schema.go
@@ -63,6 +63,7 @@ func NewSchemaWithIdentifiers(id int, identifierIDs []int, fields ...NestedField
s.lazyIDToParent = sync.OnceValues(func() (map[int]int, error) {
return IndexParents(s)
})
+
return s
}
@@ -74,6 +75,7 @@ func (s *Schema) String() string {
b.WriteString(f.String())
}
b.WriteString("\n}")
+
return b.String()
}
@@ -89,6 +91,7 @@ func (s *Schema) lazyNameToID() (map[string]int, error) {
}
s.nameToID.Store(&idx)
+
return idx, nil
}
@@ -104,6 +107,7 @@ func (s *Schema) lazyIDToField() (map[int]NestedField, error) {
}
s.idToField.Store(&idx)
+
return idx, nil
}
@@ -119,6 +123,7 @@ func (s *Schema) lazyIDToName() (map[int]string, error) {
}
s.idToName.Store(&idx)
+
return idx, nil
}
@@ -139,6 +144,7 @@ func (s *Schema) lazyNameToIDLower() (map[string]int, error) {
}
s.nameToIDLower.Store(&out)
+
return out, nil
}
@@ -154,6 +160,7 @@ func (s *Schema) lazyIdToAccessor() (map[int]accessor, error) {
}
s.idToAccessor.Store(&idx)
+
return idx, nil
}
@@ -167,6 +174,7 @@ func (s *Schema) Field(i int) NestedField { return s.fields[i] }
func (s *Schema) Fields() []NestedField { return slices.Clone(s.fields) }
func (s *Schema) FieldIDs() []int {
idx, _ := s.lazyNameToID()
+
return slices.Collect(maps.Values(idx))
}
@@ -191,6 +199,7 @@ func (s *Schema) UnmarshalJSON(b []byte) error {
if s.IdentifierFieldIDs == nil {
s.IdentifierFieldIDs = []int{}
}
+
return nil
}
@@ -200,6 +209,7 @@ func (s *Schema) MarshalJSON() ([]byte, error) {
}
type Alias Schema
+
return json.Marshal(struct {
Type string `json:"type"`
Fields []NestedField `json:"fields"`
@@ -213,6 +223,7 @@ func (s *Schema) MarshalJSON() ([]byte, error) {
func (s *Schema) FindColumnName(fieldID int) (string, bool) {
idx, _ := s.lazyIDToName()
col, ok := idx[fieldID]
+
return col, ok
}
@@ -251,6 +262,7 @@ func (s *Schema) FindFieldByNameCaseInsensitive(name string) (NestedField, bool)
func (s *Schema) FindFieldByID(id int) (NestedField, bool) {
idx, _ := s.lazyIDToField()
f, ok := idx[id]
+
return f, ok
}
@@ -294,6 +306,7 @@ func (s *Schema) accessorForField(id int) (accessor, bool) {
}
acc, ok := idx[id]
+
return acc, ok
}
@@ -325,6 +338,7 @@ func (s *Schema) Equals(other *Schema) bool {
// in this schema.
func (s *Schema) HighestFieldID() int {
id, _ := Visit[int](s, findLastFieldID{})
+
return id
}
@@ -453,6 +467,7 @@ type SchemaVisitorPerPrimitiveType[T any] interface {
func Visit[T any](sc *Schema, visitor SchemaVisitor[T]) (res T, err error) {
if sc == nil {
err = fmt.Errorf("%w: cannot visit nil schema", ErrInvalidArgument)
+
return
}
@@ -588,6 +603,7 @@ func visitField[T any](f NestedField, visitor SchemaVisitor[T]) T {
return perPrimitive.VisitFixed(t)
}
}
+
return visitor.Primitive(typ.(PrimitiveType))
}
}
@@ -604,6 +620,7 @@ type PreOrderSchemaVisitor[T any] interface {
func PreOrderVisit[T any](sc *Schema, visitor PreOrderSchemaVisitor[T]) (res T, err error) {
if sc == nil {
err = fmt.Errorf("%w: cannot visit nil schema", ErrInvalidArgument)
+
return
}
@@ -685,17 +702,20 @@ func (i *indexByID) Struct(StructType, []map[int]NestedField) map[int]NestedFiel
func (i *indexByID) Field(field NestedField, _ map[int]NestedField) map[int]NestedField {
i.index[field.ID] = field
+
return i.index
}
func (i *indexByID) List(list ListType, _ map[int]NestedField) map[int]NestedField {
i.index[list.ElementID] = list.ElementField()
+
return i.index
}
func (i *indexByID) Map(mapType MapType, _, _ map[int]NestedField) map[int]NestedField {
i.index[mapType.KeyID] = mapType.KeyField()
i.index[mapType.ValueID] = mapType.ValueField()
+
return i.index
}
@@ -723,6 +743,7 @@ func IndexByName(schema *Schema) (map[string]int, error) {
return indexer.ByName(), nil
}
+
return map[string]int{}, nil
}
@@ -738,6 +759,7 @@ func IndexNameByID(schema *Schema) (map[int]string, error) {
if _, err := Visit[map[string]int](schema, indexer); err != nil {
return nil, err
}
+
return indexer.ByID(), nil
}
@@ -754,12 +776,14 @@ func (i *indexByName) ByID() map[int]string {
for k, v := range i.index {
idToName[v] = k
}
+
return idToName
}
func (i *indexByName) ByName() map[string]int {
i.combinedIndex = maps.Clone(i.shortNameId)
maps.Copy(i.combinedIndex, i.index)
+
return i.combinedIndex
}
@@ -792,17 +816,20 @@ func (i *indexByName) Struct(StructType, []map[string]int) map[string]int {
func (i *indexByName) Field(field NestedField, _ map[string]int) map[string]int {
i.addField(field.Name, field.ID)
+
return i.index
}
func (i *indexByName) List(list ListType, _ map[string]int) map[string]int {
i.addField(list.ElementField().Name, list.ElementID)
+
return i.index
}
func (i *indexByName) Map(mapType MapType, _, _ map[string]int) map[string]int {
i.addField(mapType.KeyField().Name, mapType.KeyID)
i.addField(mapType.ValueField().Name, mapType.ValueID)
+
return i.index
}
@@ -833,8 +860,10 @@ func (i *indexByName) AfterField(field NestedField) {
// PruneColumns visits a schema pruning any columns which do not exist in the
// provided selected set. Parent fields of a selected child will be retained.
func PruneColumns(schema *Schema, selected map[int]Void, selectFullTypes bool) (*Schema, error) {
- result, err := Visit(schema, &pruneColVisitor{selected: selected,
- fullTypes: selectFullTypes})
+ result, err := Visit(schema, &pruneColVisitor{
+ selected: selected,
+ fullTypes: selectFullTypes,
+ })
if err != nil {
return nil, err
}
@@ -923,6 +952,7 @@ func (p *pruneColVisitor) Field(field NestedField, fieldResult Type) Type {
panic(fmt.Errorf("%w: cannot explicitly project List or Map types, %d:%s of type %s was selected",
ErrInvalidSchema, field.ID, field.Name, field.Type))
}
+
return typ
}
@@ -943,6 +973,7 @@ func (p *pruneColVisitor) List(list ListType, elemResult Type) Type {
_, ok = list.Element.(*StructType)
if list.Element != nil && ok {
projected := p.projectSelectedStruct(elemResult)
+
return p.projectList(&list, projected)
}
@@ -975,6 +1006,7 @@ func (p *pruneColVisitor) Map(mapType MapType, keyResult, valueResult Type) Type
_, ok = mapType.ValueType.(*StructType)
if mapType.ValueType != nil && ok {
projected := p.projectSelectedStruct(valueResult)
+
return p.projectMap(&mapType, projected)
}
@@ -1005,8 +1037,10 @@ func (*pruneColVisitor) projectList(listType *ListType, elementResult Type) *Lis
return listType
}
- return &ListType{ElementID: listType.ElementID, Element: elementResult,
- ElementRequired: listType.ElementRequired}
+ return &ListType{
+ ElementID: listType.ElementID, Element: elementResult,
+ ElementRequired: listType.ElementRequired,
+ }
}
func (*pruneColVisitor) projectMap(mapType *MapType, valueResult Type) *MapType {
@@ -1052,6 +1086,7 @@ func IndexParents(schema *Schema) (map[int]int, error) {
idToParent: make(map[int]int),
idStack: make([]int, 0),
}
+
return Visit(schema, indexer)
}
@@ -1091,6 +1126,7 @@ func (i *indexParents) Field(NestedField, map[int]int) map[int]int {
func (i *indexParents) List(list ListType, _ map[int]int) map[int]int {
i.idToParent[list.ElementID] = i.idStack[len(i.idStack)-1]
+
return i.idToParent
}
@@ -1098,6 +1134,7 @@ func (i *indexParents) Map(mapType MapType, _, _ map[int]int) map[int]int {
parent := i.idStack[len(i.idStack)-1]
i.idToParent[mapType.KeyID] = parent
i.idToParent[mapType.ValueID] = parent
+
return i.idToParent
}
@@ -1123,6 +1160,7 @@ func (buildPosAccessors) Struct(st StructType, fieldResults []map[int]accessor)
result[f.ID] = accessor{pos: pos}
}
}
+
return result
}
@@ -1154,6 +1192,7 @@ type setFreshIDs struct {
func (s *setFreshIDs) getAndInc(currentID int) int {
next := s.nextIDFunc()
s.oldIdToNew[currentID] = next
+
return next
}
@@ -1172,6 +1211,7 @@ func (s *setFreshIDs) Struct(st StructType, fieldResults []func() Type) Type {
Required: f.Required,
}
}
+
return &StructType{FieldList: newFields}
}
@@ -1181,6 +1221,7 @@ func (s *setFreshIDs) Field(_ NestedField, fieldResult func() Type) Type {
func (s *setFreshIDs) List(list ListType, elemResult func() Type) Type {
elemID := s.getAndInc(list.ElementID)
+
return &ListType{
ElementID: elemID,
Element: elemResult(),
@@ -1191,6 +1232,7 @@ func (s *setFreshIDs) List(list ListType, elemResult func() Type) Type {
func (s *setFreshIDs) Map(mapType MapType, keyResult, valueResult func() Type) Type {
keyID := s.getAndInc(mapType.KeyID)
valueID := s.getAndInc(mapType.ValueID)
+
return &MapType{
KeyID: keyID,
ValueID: valueID,
@@ -1212,6 +1254,7 @@ func AssignFreshSchemaIDs(sc *Schema, nextID func() int) (*Schema, error) {
var id int = 0
nextID = func() int {
id++
+
return id
}
}
@@ -1253,11 +1296,13 @@ type PartnerAccessor[P any] interface {
func VisitSchemaWithPartner[T, P any](sc *Schema, partner P, visitor SchemaWithPartnerVisitor[T, P], accessor PartnerAccessor[P]) (res T, err error) {
if sc == nil {
err = fmt.Errorf("%w: cannot visit nil schema", ErrInvalidArgument)
+
return
}
if visitor == nil || accessor == nil {
err = fmt.Errorf("%w: cannot visit with nil visitor or accessor", ErrInvalidArgument)
+
return
}
@@ -1273,6 +1318,7 @@ func VisitSchemaWithPartner[T, P any](sc *Schema, partner P, visitor SchemaWithP
}()
structPartner := accessor.SchemaPartner(partner)
+
return visitor.Schema(sc, partner, visitStructWithPartner(sc.AsStruct(), structPartner, visitor, accessor)), nil
}
diff --git a/schema_test.go b/schema_test.go
index d080b9f..f264bcf 100644
--- a/schema_test.go
+++ b/schema_test.go
@@ -32,14 +32,19 @@ var (
tableSchemaNested = iceberg.NewSchemaWithIdentifiers(1,
[]int{1},
iceberg.NestedField{
- ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: false},
+ ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: false,
+ },
iceberg.NestedField{
- ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true},
+ ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true,
+ },
iceberg.NestedField{
- ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false},
+ ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false,
+ },
iceberg.NestedField{
ID: 4, Name: "qux", Required: true, Type: &iceberg.ListType{
- ElementID: 5, Element: iceberg.PrimitiveTypes.String, ElementRequired: true}},
+ ElementID: 5, Element: iceberg.PrimitiveTypes.String, ElementRequired: true,
+ },
+ },
iceberg.NestedField{
ID: 6, Name: "quux",
Type: &iceberg.MapType{
@@ -55,7 +60,8 @@ var (
},
ValueRequired: true,
},
- Required: true},
+ Required: true,
+ },
iceberg.NestedField{
ID: 11, Name: "location", Type: &iceberg.ListType{
ElementID: 12, Element: &iceberg.StructType{
@@ -64,8 +70,10 @@ var (
{ID: 14, Name: "longitude", Type: iceberg.PrimitiveTypes.Float32, Required: false},
},
},
- ElementRequired: true},
- Required: true},
+ ElementRequired: true,
+ },
+ Required: true,
+ },
iceberg.NestedField{
ID: 15,
Name: "person",
@@ -519,7 +527,8 @@ func TestPruneColumnsEmptyStruct(t *testing.T) {
assert.True(t, sc.Equals(iceberg.NewSchema(0,
iceberg.NestedField{
- ID: 15, Name: "person", Type: &iceberg.StructType{}, Required: false})))
+ ID: 15, Name: "person", Type: &iceberg.StructType{}, Required: false,
+ })))
}
func TestPruneColumnsEmptyStructFull(t *testing.T) {
@@ -532,7 +541,8 @@ func TestPruneColumnsEmptyStructFull(t *testing.T) {
assert.True(t, sc.Equals(iceberg.NewSchema(0,
iceberg.NestedField{
- ID: 15, Name: "person", Type: &iceberg.StructType{}, Required: false})))
+ ID: 15, Name: "person", Type: &iceberg.StructType{}, Required: false,
+ })))
}
func TestPruneColumnsStructInMap(t *testing.T) {
@@ -645,6 +655,7 @@ func TestAssignFreshSchemaIDs(t *testing.T) {
startID := 100
sc, err := iceberg.AssignFreshSchemaIDs(tableSchemaNested, func() int {
startID++
+
return startID
})
require.NoError(t, err)
diff --git a/table/arrow_scanner.go b/table/arrow_scanner.go
index 1a2cfcf..58285dd 100644
--- a/table/arrow_scanner.go
+++ b/table/arrow_scanner.go
@@ -41,8 +41,10 @@ const (
ScanOptionArrowUseLargeTypes = "arrow.use_large_types"
)
-type positionDeletes = []*arrow.Chunked
-type perFilePosDeletes = map[string]positionDeletes
+type (
+ positionDeletes = []*arrow.Chunked
+ perFilePosDeletes = map[string]positionDeletes
+)
func readAllDeleteFiles(ctx context.Context, fs iceio.IO, tasks []FileScanTask, concurrency int) (perFilePosDeletes, error) {
var (
@@ -79,6 +81,7 @@ func readAllDeleteFiles(ctx context.Context, fs iceio.IO, tasks []FileScanTask,
if deletes != nil {
perFileChan <- deletes
}
+
return err
})
}
@@ -142,6 +145,7 @@ func readDeletes(ctx context.Context, fs iceio.IO, dataFile iceberg.DataFile) (m
results[v] = filtered.(*compute.ChunkedDatum).Value
}
+
return results, nil
}
@@ -156,6 +160,7 @@ func combinePositionalDeletes(mem memory.Allocator, deletes set[int64], start, e
bldr.Append(i)
}
}
+
return bldr.NewArray()
}
@@ -163,6 +168,7 @@ type recProcessFn func(arrow.Record) (arrow.Record, error)
func processPositionalDeletes(ctx context.Context, deletes set[int64]) recProcessFn {
nextIdx, mem := int64(0), compute.GetAllocator(ctx)
+
return func(r arrow.Record) (arrow.Record, error) {
defer r.Release()
@@ -265,12 +271,14 @@ func (as *arrowScan) prepareToRead(ctx context.Context, file iceberg.DataFile) (
fileSchema, colIndices, err := rdr.PrunedSchema(ids)
if err != nil {
rdr.Close()
+
return nil, nil, nil, err
}
iceSchema, err := ArrowSchemaToIceberg(fileSchema, false, nil)
if err != nil {
rdr.Close()
+
return nil, nil, nil, err
}
@@ -303,6 +311,7 @@ func (as *arrowScan) getRecordFilter(ctx context.Context, fileSchema *iceberg.Sc
}
ctx = exprs.WithExtensionIDSet(ctx, exprs.NewExtensionSetDefault(*extSet))
+
return filterRecords(ctx, recordFilter), false, nil
}
@@ -316,8 +325,8 @@ func (as *arrowScan) processRecords(
rdr internal.FileReader,
columns []int,
pipeline []recProcessFn,
- out chan<- enumeratedRecord) (err error) {
-
+ out chan<- enumeratedRecord,
+) (err error) {
var (
testRowGroups any
recRdr array.RecordReader
@@ -345,7 +354,8 @@ func (as *arrowScan) processRecords(
for recRdr.Next() {
if prev != nil {
out <- enumeratedRecord{Record: internal.Enumerated[arrow.Record]{
- Value: prev, Index: idx, Last: false}, Task: task}
+ Value: prev, Index: idx, Last: false,
+ }, Task: task}
idx++
}
@@ -362,7 +372,8 @@ func (as *arrowScan) processRecords(
if prev != nil {
out <- enumeratedRecord{Record: internal.Enumerated[arrow.Record]{
- Value: prev, Index: idx, Last: true}, Task: task}
+ Value: prev, Index: idx, Last: true,
+ }, Task: task}
}
if recRdr.Err() != nil && recRdr.Err() != io.EOF {
@@ -419,7 +430,9 @@ func (as *arrowScan) recordsFromTask(ctx context.Context, task internal.Enumerat
return err
}
out <- enumeratedRecord{Task: task, Record: internal.Enumerated[arrow.Record]{
- Value: array.NewRecord(emptySchema, nil, 0), Index: 0, Last: true}}
+ Value: array.NewRecord(emptySchema, nil, 0), Index: 0, Last: true,
+ }}
+
return
}
@@ -429,10 +442,12 @@ func (as *arrowScan) recordsFromTask(ctx context.Context, task internal.Enumerat
pipeline = append(pipeline, func(r arrow.Record) (arrow.Record, error) {
defer r.Release()
+
return ToRequestedSchema(ctx, as.projectedSchema, iceSchema, r, false, false, as.useLargeTypes)
})
err = as.processRecords(ctx, task, iceSchema, rdr, colIndices, pipeline, out)
+
return
}
@@ -470,6 +485,7 @@ func createIterator(ctx context.Context, numWorkers uint, records <-chan enumera
}, enumeratedRecord{Task: internal.Enumerated[FileScanTask]{Index: -1}})
totalRowCount := int64(0)
+
return func(yield func(arrow.Record, error) bool) {
defer func() {
for rec := range sequenced {
@@ -493,6 +509,7 @@ func createIterator(ctx context.Context, numWorkers uint, records <-chan enumera
if err := context.Cause(ctx); err != nil {
yield(nil, err)
}
+
return
case enum, ok := <-sequenced:
if !ok {
@@ -501,6 +518,7 @@ func createIterator(ctx context.Context, numWorkers uint, records <-chan enumera
if enum.Err != nil {
yield(nil, enum.Err)
+
return
}
@@ -508,6 +526,7 @@ func createIterator(ctx context.Context, numWorkers uint, records <-chan enumera
if rowLimit > 0 {
if totalRowCount >= rowLimit {
rec.Release()
+
return
} else if totalRowCount+rec.NumRows() > rowLimit {
defer rec.Release()
@@ -559,6 +578,7 @@ func (as *arrowScan) recordBatchesFromTasksAndDeletes(ctx context.Context, tasks
if err := as.recordsFromTask(ctx, task, records,
deletesPerFile[task.Value.File.FilePath()]); err != nil {
cancel(err)
+
return
}
}
@@ -569,7 +589,8 @@ func (as *arrowScan) recordBatchesFromTasksAndDeletes(ctx context.Context, tasks
go func() {
for i, t := range tasks {
taskChan <- internal.Enumerated[FileScanTask]{
- Value: t, Index: i, Last: i == len(tasks)-1}
+ Value: t, Index: i, Last: i == len(tasks)-1,
+ }
}
close(taskChan)
diff --git a/table/arrow_utils.go b/table/arrow_utils.go
index 490dac0..4ff4b9f 100644
--- a/table/arrow_utils.go
+++ b/table/arrow_utils.go
@@ -65,6 +65,7 @@ func recoverError(err *error) {
func VisitArrowSchema[T any](sc *arrow.Schema, visitor ArrowSchemaVisitor[T]) (res T, err error) {
if sc == nil {
err = fmt.Errorf("%w: cannot visit nil arrow schema", iceberg.ErrInvalidArgument)
+
return
}
@@ -217,6 +218,7 @@ func (hasIDs) Field(f arrow.Field, result bool) bool {
func (hasIDs) List(dt arrow.ListLikeType, elem bool) bool {
elemField := dt.ElemField()
+
return elem && getFieldID(elemField) != nil
}
@@ -253,6 +255,7 @@ func (c convertToIceberg) Field(field arrow.Field, result iceberg.NestedField) i
result.Required = !field.Nullable
result.Name = field.Name
+
return result
}
@@ -284,9 +287,7 @@ func (c convertToIceberg) Map(m *arrow.MapType, keyResult, valueResult iceberg.N
}
}
-var (
- utcAliases = []string{"UTC", "+00:00", "Etc/UTC", "Z"}
-)
+var utcAliases = []string{"UTC", "+00:00", "Etc/UTC", "Z"}
func (c convertToIceberg) Primitive(dt arrow.DataType) (result iceberg.NestedField) {
switch dt := dt.(type) {
@@ -294,11 +295,13 @@ func (c convertToIceberg) Primitive(dt arrow.DataType) (result iceberg.NestedFie
if _, ok := dt.ValueType.(arrow.NestedType); ok {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
+
return c.Primitive(dt.ValueType)
case *arrow.RunEndEncodedType:
if _, ok := dt.Encoded().(arrow.NestedType); ok {
panic(fmt.Errorf("%w: unsupported arrow type for conversion - %s", iceberg.ErrInvalidSchema, dt))
}
+
return c.Primitive(dt.Encoded())
case *arrow.BooleanType:
result.Type = iceberg.PrimitiveTypes.Bool
@@ -357,8 +360,10 @@ func (c convertToIceberg) Primitive(dt arrow.DataType) (result iceberg.NestedFie
}
func ArrowTypeToIceberg(dt arrow.DataType, downcastNsTimestamp bool) (iceberg.Type, error) {
- sc := arrow.NewSchema([]arrow.Field{{Type: dt,
- Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"})}}, nil)
+ sc := arrow.NewSchema([]arrow.Field{{
+ Type: dt,
+ Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}),
+ }}, nil)
out, err := VisitArrowSchema(sc, convertToIceberg{
downcastTimestamp: downcastNsTimestamp,
@@ -409,6 +414,7 @@ func ArrowSchemaToIceberg(sc *arrow.Schema, downcastNsTimestamp bool, nameMappin
}
schemaWithoutIDs := iceberg.NewSchema(0, withoutIDs.Type.(*iceberg.StructType).FieldList...)
+
return ApplyNameMapping(schemaWithoutIDs, nameMapping)
default:
return nil, fmt.Errorf("%w: arrow schema does not have field-ids and no name mapping provided",
@@ -428,6 +434,7 @@ func (convertToSmallTypes) Struct(_ *arrow.StructType, results []arrow.Field) ar
func (convertToSmallTypes) Field(field arrow.Field, fieldResult arrow.Field) arrow.Field {
field.Type = fieldResult.Type
+
return field
}
@@ -470,6 +477,7 @@ type convertToArrow struct {
func (c convertToArrow) Schema(_ *iceberg.Schema, result arrow.Field) arrow.Field {
result.Metadata = arrow.MetadataFrom(c.metadata)
+
return result
}
@@ -492,6 +500,7 @@ func (c convertToArrow) Field(field iceberg.NestedField, result arrow.Field) arr
}
result.Name, result.Nullable = field.Name, !field.Required
+
return result
}
@@ -500,12 +509,14 @@ func (c convertToArrow) List(list iceberg.ListType, elemResult arrow.Field) arro
if c.useLargeTypes {
return arrow.Field{Type: arrow.LargeListOfField(elemField)}
}
+
return arrow.Field{Type: arrow.ListOfField(elemField)}
}
func (c convertToArrow) Map(m iceberg.MapType, keyResult, valResult arrow.Field) arrow.Field {
keyField := c.Field(m.KeyField(), keyResult)
valField := c.Field(m.ValueField(), valResult)
+
return arrow.Field{Type: arrow.MapOfWithMetadata(keyField.Type, keyField.Metadata,
valField.Type, valField.Metadata)}
}
@@ -518,7 +529,8 @@ func (c convertToArrow) VisitFixed(f iceberg.FixedType) arrow.Field {
func (c convertToArrow) VisitDecimal(d iceberg.DecimalType) arrow.Field {
return arrow.Field{Type: &arrow.Decimal128Type{
- Precision: int32(d.Precision()), Scale: int32(d.Scale())}}
+ Precision: int32(d.Precision()), Scale: int32(d.Scale()),
+ }}
}
func (c convertToArrow) VisitBoolean() arrow.Field {
@@ -561,6 +573,7 @@ func (c convertToArrow) VisitString() arrow.Field {
if c.useLargeTypes {
return arrow.Field{Type: arrow.BinaryTypes.LargeString}
}
+
return arrow.Field{Type: arrow.BinaryTypes.String}
}
@@ -568,6 +581,7 @@ func (c convertToArrow) VisitBinary() arrow.Field {
if c.useLargeTypes {
return arrow.Field{Type: arrow.BinaryTypes.LargeBinary}
}
+
return arrow.Field{Type: arrow.BinaryTypes.Binary}
}
@@ -580,8 +594,10 @@ func (c convertToArrow) VisitUUID() arrow.Field {
// is true, then each field of the schema will contain a metadata key PARQUET:field_id set to
// the field id from the iceberg schema.
func SchemaToArrowSchema(sc *iceberg.Schema, metadata map[string]string, includeFieldIDs, useLargeTypes bool) (*arrow.Schema, error) {
- top, err := iceberg.Visit(sc, convertToArrow{metadata: metadata,
- includeFieldIDs: includeFieldIDs, useLargeTypes: useLargeTypes})
+ top, err := iceberg.Visit(sc, convertToArrow{
+ metadata: metadata,
+ includeFieldIDs: includeFieldIDs, useLargeTypes: useLargeTypes,
+ })
if err != nil {
return nil, err
}
@@ -634,6 +650,7 @@ func (a arrowAccessor) ListElementPartner(partnerList arrow.Array) arrow.Array {
if l, ok := partnerList.(array.ListLike); ok {
return l.ListValues()
}
+
return nil
}
@@ -641,6 +658,7 @@ func (a arrowAccessor) MapKeyPartner(partnerMap arrow.Array) arrow.Array {
if m, ok := partnerMap.(*array.Map); ok {
return m.Keys()
}
+
return nil
}
@@ -648,6 +666,7 @@ func (a arrowAccessor) MapValuePartner(partnerMap arrow.Array) arrow.Array {
if m, ok := partnerMap.(*array.Map); ok {
return m.Items()
}
+
return nil
}
@@ -655,6 +674,7 @@ func retOrPanic[T any](v T, err error) T {
if err != nil {
panic(err)
}
+
return v
}
@@ -675,6 +695,7 @@ func (a *arrowProjectionVisitor) castIfNeeded(field iceberg.NestedField, vals ar
typ, ok := fileField.Type.(iceberg.PrimitiveType)
if !ok {
vals.Retain()
+
return vals
}
@@ -724,6 +745,7 @@ func (a *arrowProjectionVisitor) castIfNeeded(field iceberg.NestedField, vals ar
}
}
vals.Retain()
+
return vals
}
@@ -810,6 +832,7 @@ func (a *arrowProjectionVisitor) List(listType iceberg.ListType, listArr arrow.A
data := array.NewData(outType, arr.Len(), arr.Data().Buffers(),
[]arrow.ArrayData{valArr.Data()}, arr.NullN(), arr.Data().Offset())
defer data.Release()
+
return array.MakeFromData(data)
}
@@ -838,6 +861,7 @@ func (a *arrowProjectionVisitor) Map(m iceberg.MapType, mapArray, keyResult, val
newData := array.NewData(mapType, arr.Len(), arr.Data().Buffers(),
[]arrow.ArrayData{childData}, arr.NullN(), arr.Offset())
defer newData.Release()
+
return array.NewMapData(newData)
}
@@ -865,5 +889,6 @@ func ToRequestedSchema(ctx context.Context, requested, fileSchema *iceberg.Schem
st.Release()
out := array.RecordFromStructArray(result.(*array.Struct), nil)
result.Release()
+
return out, nil
}
diff --git a/table/arrow_utils_test.go b/table/arrow_utils_test.go
index 058721d..844cec2 100644
--- a/table/arrow_utils_test.go
+++ b/table/arrow_utils_test.go
@@ -105,7 +105,8 @@ func TestArrowToIceberg(t *testing.T) {
{ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: false, Doc: "foo doc"},
{ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true},
{ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false},
- }}, true, ""},
+ },
+ }, true, ""},
{arrow.ListOfField(arrow.Field{
Name: "element",
Type: arrow.PrimitiveTypes.Int32,
@@ -136,19 +137,27 @@ func TestArrowToIceberg(t *testing.T) {
Element: iceberg.PrimitiveTypes.Int32,
ElementRequired: true,
}, false, ""},
- {arrow.MapOfWithMetadata(arrow.PrimitiveTypes.Int32,
- fieldIDMeta("1"),
- arrow.BinaryTypes.String, fieldIDMeta("2")),
+ {
+ arrow.MapOfWithMetadata(arrow.PrimitiveTypes.Int32,
+ fieldIDMeta("1"),
+ arrow.BinaryTypes.String, fieldIDMeta("2")),
&iceberg.MapType{
KeyID: 1, KeyType: iceberg.PrimitiveTypes.Int32,
ValueID: 2, ValueType: iceberg.PrimitiveTypes.String, ValueRequired: false,
- }, true, ""},
- {&arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int32,
- ValueType: arrow.BinaryTypes.String}, iceberg.PrimitiveTypes.String, false, ""},
- {&arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int32,
- ValueType: arrow.PrimitiveTypes.Int32}, iceberg.PrimitiveTypes.Int32, false, ""},
- {&arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int64,
- ValueType: arrow.PrimitiveTypes.Float64}, iceberg.PrimitiveTypes.Float64, false, ""},
+ }, true, "",
+ },
+ {&arrow.DictionaryType{
+ IndexType: arrow.PrimitiveTypes.Int32,
+ ValueType: arrow.BinaryTypes.String,
+ }, iceberg.PrimitiveTypes.String, false, ""},
+ {&arrow.DictionaryType{
+ IndexType: arrow.PrimitiveTypes.Int32,
+ ValueType: arrow.PrimitiveTypes.Int32,
+ }, iceberg.PrimitiveTypes.Int32, false, ""},
+ {&arrow.DictionaryType{
+ IndexType: arrow.PrimitiveTypes.Int64,
+ ValueType: arrow.PrimitiveTypes.Float64,
+ }, iceberg.PrimitiveTypes.Float64, false, ""},
{arrow.RunEndEncodedOf(arrow.PrimitiveTypes.Int32, arrow.BinaryTypes.String), iceberg.PrimitiveTypes.String, false, ""},
{arrow.RunEndEncodedOf(arrow.PrimitiveTypes.Int32, arrow.PrimitiveTypes.Float64), iceberg.PrimitiveTypes.Float64, false, ""},
{arrow.RunEndEncodedOf(arrow.PrimitiveTypes.Int32, arrow.PrimitiveTypes.Int16), iceberg.PrimitiveTypes.Int32, false, ""},
@@ -181,43 +190,62 @@ func TestArrowSchemaToIceberg(t *testing.T) {
err string
}{
{"simple", arrow.NewSchema([]arrow.Field{
- {Name: "foo", Nullable: true, Type: arrow.BinaryTypes.String,
- Metadata: fieldIDMeta("1")},
- {Name: "bar", Nullable: false, Type: arrow.PrimitiveTypes.Int32,
- Metadata: fieldIDMeta("2")},
- {Name: "baz", Nullable: true, Type: arrow.FixedWidthTypes.Boolean,
- Metadata: fieldIDMeta("3")},
+ {
+ Name: "foo", Nullable: true, Type: arrow.BinaryTypes.String,
+ Metadata: fieldIDMeta("1"),
+ },
+ {
+ Name: "bar", Nullable: false, Type: arrow.PrimitiveTypes.Int32,
+ Metadata: fieldIDMeta("2"),
+ },
+ {
+ Name: "baz", Nullable: true, Type: arrow.FixedWidthTypes.Boolean,
+ Metadata: fieldIDMeta("3"),
+ },
}, nil), `table {
1: foo: optional string
2: bar: required int
3: baz: optional boolean
}`, ""},
{"nested", arrow.NewSchema([]arrow.Field{
- {Name: "qux", Nullable: false, Metadata: fieldIDMeta("4"),
+ {
+ Name: "qux", Nullable: false, Metadata: fieldIDMeta("4"),
Type: arrow.ListOfField(arrow.Field{
Name: "element",
Type: arrow.BinaryTypes.String,
Metadata: fieldIDMeta("5"),
- })},
- {Name: "quux", Nullable: false, Metadata: fieldIDMeta("6"),
+ }),
+ },
+ {
+ Name: "quux", Nullable: false, Metadata: fieldIDMeta("6"),
Type: arrow.MapOfWithMetadata(arrow.BinaryTypes.String, fieldIDMeta("7"),
arrow.MapOfWithMetadata(arrow.BinaryTypes.String, fieldIDMeta("9"),
- arrow.PrimitiveTypes.Int32, fieldIDMeta("10")), fieldIDMeta("8"))},
- {Name: "location", Nullable: false, Metadata: fieldIDMeta("11"),
+ arrow.PrimitiveTypes.Int32, fieldIDMeta("10")), fieldIDMeta("8")),
+ },
+ {
+ Name: "location", Nullable: false, Metadata: fieldIDMeta("11"),
Type: arrow.ListOfField(
arrow.Field{
Name: "element", Metadata: fieldIDMeta("12"),
Type: arrow.StructOf(
- arrow.Field{Name: "latitude", Nullable: true,
- Type: arrow.PrimitiveTypes.Float32, Metadata: fieldIDMeta("13")},
- arrow.Field{Name: "longitude", Nullable: true,
- Type: arrow.PrimitiveTypes.Float32, Metadata: fieldIDMeta("14")},
- )})},
- {Name: "person", Nullable: true, Metadata: fieldIDMeta("15"),
+ arrow.Field{
+ Name: "latitude", Nullable: true,
+ Type: arrow.PrimitiveTypes.Float32, Metadata: fieldIDMeta("13"),
+ },
+ arrow.Field{
+ Name: "longitude", Nullable: true,
+ Type: arrow.PrimitiveTypes.Float32, Metadata: fieldIDMeta("14"),
+ },
+ ),
+ }),
+ },
+ {
+ Name: "person", Nullable: true, Metadata: fieldIDMeta("15"),
Type: arrow.StructOf(
arrow.Field{Name: "name", Type: arrow.BinaryTypes.String, Nullable: true, Metadata: fieldIDMeta("16")},
arrow.Field{Name: "age", Type: arrow.PrimitiveTypes.Int32, Metadata: fieldIDMeta("17")},
- )},
+ ),
+ },
}, nil), `table {
4: qux: required list<string>
6: quux: required map<string, map<string, int>>
@@ -251,14 +279,19 @@ func makeID(v int) *int { return &v }
var (
icebergSchemaNested = iceberg.NewSchema(0,
iceberg.NestedField{
- ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: true},
+ ID: 1, Name: "foo", Type: iceberg.PrimitiveTypes.String, Required: true,
+ },
iceberg.NestedField{
- ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true},
+ ID: 2, Name: "bar", Type: iceberg.PrimitiveTypes.Int32, Required: true,
+ },
iceberg.NestedField{
- ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false},
+ ID: 3, Name: "baz", Type: iceberg.PrimitiveTypes.Bool, Required: false,
+ },
iceberg.NestedField{
ID: 4, Name: "qux", Required: true, Type: &iceberg.ListType{
- ElementID: 5, Element: iceberg.PrimitiveTypes.String, ElementRequired: false}},
+ ElementID: 5, Element: iceberg.PrimitiveTypes.String, ElementRequired: false,
+ },
+ },
iceberg.NestedField{
ID: 6, Name: "quux",
Type: &iceberg.MapType{
@@ -274,7 +307,8 @@ var (
},
ValueRequired: false,
},
- Required: true},
+ Required: true,
+ },
iceberg.NestedField{
ID: 11, Name: "location", Type: &iceberg.ListType{
ElementID: 12, Element: &iceberg.StructType{
@@ -283,8 +317,10 @@ var (
{ID: 14, Name: "longitude", Type: iceberg.PrimitiveTypes.Float32, Required: true},
},
},
- ElementRequired: false},
- Required: true},
+ ElementRequired: false,
+ },
+ Required: true,
+ },
iceberg.NestedField{
ID: 15,
Name: "person",
@@ -365,8 +401,10 @@ func TestArrowSchemaWithNameMapping(t *testing.T) {
{FieldID: makeID(1), Names: []string{"foo"}},
{FieldID: makeID(2), Names: []string{"bar"}},
{FieldID: makeID(3), Names: []string{"baz"}},
- {FieldID: makeID(4), Names: []string{"qux"},
- Fields: []table.MappedField{{FieldID: makeID(5), Names: []string{"element"}}}},
+ {
+ FieldID: makeID(4), Names: []string{"qux"},
+ Fields: []table.MappedField{{FieldID: makeID(5), Names: []string{"element"}}},
+ },
{FieldID: makeID(6), Names: []string{"quux"}, Fields: []table.MappedField{
{FieldID: makeID(7), Names: []string{"key"}},
{FieldID: makeID(8), Names: []string{"value"}, Fields: []table.MappedField{
@@ -473,7 +511,6 @@ func ArrowRecordWithAllTimestampPrec(mem memory.Allocator) arrow.Record {
"timestamptz_s_0000": "2023-03-01T19:25:00Z"
}
]`))
-
if err != nil {
panic(err)
}
@@ -522,7 +559,8 @@ func TestToRequestedSchema(t *testing.T) {
Name: "element", Type: arrow.PrimitiveTypes.Int32, Nullable: false,
Metadata: arrow.NewMetadata([]string{table.ArrowParquetFieldIDKey}, []string{"2"}),
}),
- Metadata: arrow.NewMetadata([]string{table.ArrowParquetFieldIDKey}, []string{"1"})},
+ Metadata: arrow.NewMetadata([]string{table.ArrowParquetFieldIDKey}, []string{"1"}),
+ },
}, nil)
bldr := array.NewRecordBuilder(mem, schema)
diff --git a/table/evaluators.go b/table/evaluators.go
index e8b6bda..acee1c3 100644
--- a/table/evaluators.go
+++ b/table/evaluators.go
@@ -60,6 +60,7 @@ type manifestEvalVisitor struct {
func (m *manifestEvalVisitor) Eval(manifest iceberg.ManifestFile) (bool, error) {
if parts := manifest.Partitions(); len(parts) > 0 {
m.partitionFields = parts
+
return iceberg.VisitExpr(m.partitionFilter, m)
}
@@ -240,6 +241,7 @@ func (m *manifestEvalVisitor) VisitNotNull(term iceberg.BoundTerm) bool {
func getCmp[T iceberg.LiteralType](b iceberg.TypedLiteral[T]) func(iceberg.Literal, iceberg.Literal) int {
cmp := b.Comparator()
+
return func(l1, l2 iceberg.Literal) int {
return cmp(l1.(iceberg.TypedLiteral[T]).Value(), l2.(iceberg.TypedLiteral[T]).Value())
}
@@ -482,9 +484,7 @@ func (m *manifestEvalVisitor) VisitNotStartsWith(term iceberg.BoundTerm, lit ice
panic(err)
}
- var (
- prefix, lowerBound, upperBound string
- )
+ var prefix, lowerBound, upperBound string
if val, ok := lit.(iceberg.TypedLiteral[string]); ok {
prefix = val.Value()
lowerBound, upperBound = lower.(iceberg.TypedLiteral[string]).Value(), upper.(iceberg.TypedLiteral[string]).Value()
@@ -664,8 +664,8 @@ func (m *metricsEvaluator) isNan(v iceberg.Literal) bool {
}
func newInclusiveMetricsEvaluator(s *iceberg.Schema, expr iceberg.BooleanExpression,
- caseSensitive bool, includeEmptyFiles bool) (func(iceberg.DataFile) (bool, error), error) {
-
+ caseSensitive bool, includeEmptyFiles bool,
+) (func(iceberg.DataFile) (bool, error), error) {
rewritten, err := iceberg.RewriteNotExpr(expr)
if err != nil {
return nil, err
@@ -684,8 +684,8 @@ func newInclusiveMetricsEvaluator(s *iceberg.Schema, expr iceberg.BooleanExpress
}
func newParquetRowGroupStatsEvaluator(fileSchema *iceberg.Schema, expr iceberg.BooleanExpression,
- includeEmptyFiles bool) (func(*metadata.RowGroupMetaData, []int) (bool, error), error) {
-
+ includeEmptyFiles bool,
+) (func(*metadata.RowGroupMetaData, []int) (bool, error), error) {
rewritten, err := iceberg.RewriteNotExpr(expr)
if err != nil {
return nil, err
@@ -764,6 +764,7 @@ func (m *inclusiveMetricsEval) mayContainNull(fieldID int) bool {
}
_, ok := m.nullCounts[fieldID]
+
return ok
}
@@ -780,6 +781,7 @@ func (m *inclusiveMetricsEval) VisitIsNull(t iceberg.BoundTerm) bool {
if cnt, exists := m.nullCounts[fieldID]; exists && cnt == 0 {
return rowsCannotMatch
}
+
return rowsMightMatch
}
@@ -790,6 +792,7 @@ func (m *inclusiveMetricsEval) VisitNotNull(t iceberg.BoundTerm) bool {
if m.containsNullsOnly(fieldID) {
return rowsCannotMatch
}
+
return rowsMightMatch
}
@@ -803,6 +806,7 @@ func (m *inclusiveMetricsEval) VisitIsNan(t iceberg.BoundTerm) bool {
if m.containsNullsOnly(fieldID) {
return rowsCannotMatch
}
+
return rowsMightMatch
}
@@ -812,6 +816,7 @@ func (m *inclusiveMetricsEval) VisitNotNan(t iceberg.BoundTerm) bool {
if m.containsNansOnly(fieldID) {
return rowsCannotMatch
}
+
return rowsMightMatch
}
diff --git a/table/evaluators_test.go b/table/evaluators_test.go
index a543e93..83e5e72 100644
--- a/table/evaluators_test.go
+++ b/table/evaluators_test.go
@@ -32,7 +32,6 @@ const (
)
func TestManifestEvaluator(t *testing.T) {
-
var (
IntMin, IntMax = []byte{byte(IntMinValue), 0x00, 0x00, 0x00}, []byte{byte(IntMaxValue), 0x00, 0x00, 0x00}
StringMin, StringMax = []byte("a"), []byte("z")
@@ -43,32 +42,58 @@ func TestManifestEvaluator(t *testing.T) {
NanTrue, NanFalse = true, false
testSchema = iceberg.NewSchema(1,
- iceberg.NestedField{ID: 1, Name: "id",
- Type: iceberg.PrimitiveTypes.Int32, Required: true},
- iceberg.NestedField{ID: 2, Name: "all_nulls_missing_nan",
- Type: iceberg.PrimitiveTypes.String, Required: false},
- iceberg.NestedField{ID: 3, Name: "some_nulls",
- Type: iceberg.PrimitiveTypes.String, Required: false},
- iceberg.NestedField{ID: 4, Name: "no_nulls",
- Type: iceberg.PrimitiveTypes.String, Required: false},
- iceberg.NestedField{ID: 5, Name: "float",
- Type: iceberg.PrimitiveTypes.Float32, Required: false},
- iceberg.NestedField{ID: 6, Name: "all_nulls_double",
- Type: iceberg.PrimitiveTypes.Float64, Required: false},
- iceberg.NestedField{ID: 7, Name: "all_nulls_no_nans",
- Type: iceberg.PrimitiveTypes.Float32, Required: false},
- iceberg.NestedField{ID: 8, Name: "all_nans",
- Type: iceberg.PrimitiveTypes.Float64, Required: false},
- iceberg.NestedField{ID: 9, Name: "both_nan_and_null",
- Type: iceberg.PrimitiveTypes.Float32, Required: false},
- iceberg.NestedField{ID: 10, Name: "no_nan_or_null",
- Type: iceberg.PrimitiveTypes.Float64, Required: false},
- iceberg.NestedField{ID: 11, Name: "all_nulls_missing_nan_float",
- Type: iceberg.PrimitiveTypes.Float32, Required: false},
- iceberg.NestedField{ID: 12, Name: "all_same_value_or_null",
- Type: iceberg.PrimitiveTypes.String, Required: false},
- iceberg.NestedField{ID: 13, Name: "no_nulls_same_value_a",
- Type: iceberg.PrimitiveTypes.Binary, Required: false},
+ iceberg.NestedField{
+ ID: 1, Name: "id",
+ Type: iceberg.PrimitiveTypes.Int32, Required: true,
+ },
+ iceberg.NestedField{
+ ID: 2, Name: "all_nulls_missing_nan",
+ Type: iceberg.PrimitiveTypes.String, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 3, Name: "some_nulls",
+ Type: iceberg.PrimitiveTypes.String, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 4, Name: "no_nulls",
+ Type: iceberg.PrimitiveTypes.String, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 5, Name: "float",
+ Type: iceberg.PrimitiveTypes.Float32, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 6, Name: "all_nulls_double",
+ Type: iceberg.PrimitiveTypes.Float64, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 7, Name: "all_nulls_no_nans",
+ Type: iceberg.PrimitiveTypes.Float32, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 8, Name: "all_nans",
+ Type: iceberg.PrimitiveTypes.Float64, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 9, Name: "both_nan_and_null",
+ Type: iceberg.PrimitiveTypes.Float32, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 10, Name: "no_nan_or_null",
+ Type: iceberg.PrimitiveTypes.Float64, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 11, Name: "all_nulls_missing_nan_float",
+ Type: iceberg.PrimitiveTypes.Float32, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 12, Name: "all_same_value_or_null",
+ Type: iceberg.PrimitiveTypes.String, Required: false,
+ },
+ iceberg.NestedField{
+ ID: 13, Name: "no_nulls_same_value_a",
+ Type: iceberg.PrimitiveTypes.Binary, Required: false,
+ },
)
)
@@ -293,203 +318,387 @@ func TestManifestEvaluator(t *testing.T) {
expect bool
msg string
}{
- {iceberg.NewNot(iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25))),
- true, "should read: not(false)"},
- {iceberg.NewNot(iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMinValue-25))),
- false, "should skip: not(true)"},
- {iceberg.NewAnd(
- iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
- iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMinValue-30))),
- false, "should skip: and(false, true)"},
- {iceberg.NewAnd(
- iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
- iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+1))),
- false, "should skip: and(false, false)"},
- {iceberg.NewAnd(
- iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMinValue-25)),
- iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue))),
- true, "should read: and(true, true)"},
- {iceberg.NewOr(
- iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
- iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+1))),
- false, "should skip: or(false, false)"},
- {iceberg.NewOr(
- iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
- iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue-19))),
- true, "should read: or(false, true)"},
- {iceberg.LessThan(iceberg.Reference("some_nulls"), "1"), false,
- "should not read: id range below lower bound"},
- {iceberg.LessThan(iceberg.Reference("some_nulls"), "b"), true,
- "should read: lower bound in range"},
- {iceberg.LessThan(iceberg.Reference("float"), 15.50), true,
- "should read: lower bound in range"},
- {iceberg.LessThan(iceberg.Reference("no_nan_or_null"), 15.50), true,
- "should read: lower bound in range"},
- {iceberg.LessThanEqual(iceberg.Reference("no_nulls_same_value_a"), "a"), true,
- "should read: lower bound in range"},
- {iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)), false,
- "should not read: id range below lower bound (5 < 30)"},
- {iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue)), false,
- "should not read: id range below lower bound (30 is not < 30)"},
- {iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue+1)), true,
- "should read: one possible id"},
- {iceberg.LessThan(iceberg.Reference("id"), int32(IntMaxValue)), true,
- "should read: many possible ids"},
- {iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue-25)), false,
- "should not read: id range below lower bound (5 < 30)"},
- {iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue-1)), false,
- "should not read: id range below lower bound 29 < 30"},
- {iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue)), true,
- "should read: one possible id"},
- {iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMaxValue)), true,
- "should read: many possible ids"},
- {iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue+6)), false,
- "should not read: id range above upper bound (85 < 79)"},
- {iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue)), false,
- "should not read: id range above upper bound (79 is not > 79)"},
- {iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue-1)), true,
- "should read: one possible id"},
- {iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue-4)), true,
- "should read: many possible ids"},
- {iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+6)), false,
- "should not read: id range is above upper bound (85 < 79)"},
- {iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+1)), false,
- "should not read: id range above upper bound (80 > 79)"},
- {iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue)), true,
- "should read: one possible id"},
- {iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue)), true,
- "should read: many possible ids"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-25)), false,
- "should not read: id below lower bound"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-1)), false,
- "should not read: id below lower bound"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue)), true,
- "should read: id equal to lower bound"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue-4)), true,
- "should read: id between lower and upper bounds"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue)), true,
- "should read: id equal to upper bound"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+1)), false,
- "should not read: id above upper bound"},
- {iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+6)), false,
- "should not read: id above upper bound"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMinValue-25)), true,
- "should read: id below lower bound"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMinValue-1)), true,
- "should read: id below lower bound"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMinValue)), true,
- "should read: id equal to lower bound"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue-4)), true,
- "should read: id between lower and upper bounds"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue)), true,
- "should read: id equal to upper bound"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue+1)), true,
- "should read: id above upper bound"},
- {iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue+6)), true,
- "should read: id above upper bound"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-25))), true,
- "should read: id below lower bound"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-1))), true,
- "should read: id below lower bound"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue))), true,
- "should read: id equal to lower bound"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue-4))), true,
- "should read: id between lower and upper bounds"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue))), true,
- "should read: id equal to upper bound"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+1))), true,
- "should read: id above upper bound"},
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+6))), true,
- "should read: id above upper bound"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMinValue-25), IntMinValue-24), false,
- "should not read: id below lower bound (5 < 30, 6 < 30)"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMinValue-2), IntMinValue-1), false,
- "should not read: id below lower bound (28 < 30, 29 < 30)"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMinValue-1), IntMinValue), true,
- "should read: id equal to lower bound (30 == 30)"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue-4), IntMaxValue-3), true,
- "should read: id between lower and upper bounds (30 < 75 < 79, 30 < 76 < 79)"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue), IntMaxValue+1), true,
- "should read: id equal to upper bound (79 == 79)"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue+1), IntMaxValue+2), false,
- "should not read: id above upper bound (80 > 79, 81 > 79)"},
- {iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue+6), IntMaxValue+7), false,
- "should not read: id above upper bound (85 > 79, 86 > 79)"},
- {iceberg.IsIn(iceberg.Reference("all_nulls_missing_nan"), "abc", "def"), false,
- "should skip: in on all nulls column"},
- {iceberg.IsIn(iceberg.Reference("some_nulls"), "abc", "def"), true,
- "should read: in on some nulls column"},
- {iceberg.IsIn(iceberg.Reference("no_nulls"), "abc", "def"), true,
- "should read: in on no nulls column"},
- {iceberg.IsIn(iceberg.Reference("no_nulls_same_value_a"), "a", "b"), true,
- "should read: in on no nulls column"},
- {iceberg.IsIn(iceberg.Reference("float"), 0, -5.5), true,
- "should read: float equal to lower bound"},
- {iceberg.IsIn(iceberg.Reference("no_nan_or_null"), 0, -5.5), true,
- "should read: float equal to lower bound"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMinValue-25), IntMinValue-24), true,
- "should read: id below lower bound (5 < 30, 6 < 30)"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMinValue-2), IntMinValue-1), true,
- "should read: id below lower bound (28 < 30, 29 < 30)"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMinValue-1), IntMinValue), true,
- "should read: id equal to lower bound (30 == 30)"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue-4), IntMaxValue-3), true,
- "should read: id between lower and upper bounds (30 < 75 < 79, 30 < 76 < 79)"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue), IntMaxValue+1), true,
- "should read: id equal to upper bound (79 == 79)"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue+1), IntMaxValue+2), true,
- "should read: id above upper bound (80 > 79, 81 > 79)"},
- {iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue+6), IntMaxValue+7), true,
- "should read: id above upper bound (85 > 79, 86 > 79)"},
- {iceberg.NotIn(iceberg.Reference("all_nulls_missing_nan"), "abc", "def"), true,
- "should read: notIn on all nulls column"},
- {iceberg.NotIn(iceberg.Reference("some_nulls"), "abc", "def"), true,
- "should read: notIn on some nulls column"},
- {iceberg.NotIn(iceberg.Reference("no_nulls"), "abc", "def"), true,
- "should read: notIn on no nulls column"},
- {iceberg.StartsWith(iceberg.Reference("some_nulls"), "a"), true,
- "should read: range matches"},
- {iceberg.StartsWith(iceberg.Reference("some_nulls"), "aa"), true,
- "should read: range matches"},
- {iceberg.StartsWith(iceberg.Reference("some_nulls"), "dddd"), true,
- "should read: range matches"},
- {iceberg.StartsWith(iceberg.Reference("some_nulls"), "z"), true,
- "should read: range matches"},
- {iceberg.StartsWith(iceberg.Reference("no_nulls"), "a"), true,
- "should read: range matches"},
- {iceberg.StartsWith(iceberg.Reference("some_nulls"), "zzzz"), false,
- "should skip: range doesn't match"},
- {iceberg.StartsWith(iceberg.Reference("some_nulls"), "1"), false,
- "should skip: range doesn't match"},
- {iceberg.StartsWith(iceberg.Reference("no_nulls_same_value_a"), "a"), true,
- "should read: all values start with the prefix"},
- {iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "a"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "aa"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "dddd"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "z"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("no_nulls"), "a"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "zzzz"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "1"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("all_same_value_or_null"), "a"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("all_same_value_or_null"), "aa"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("all_same_value_or_null"), "A"), true,
- "should read: range matches"},
+ {
+ iceberg.NewNot(iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25))),
+ true, "should read: not(false)",
+ },
+ {
+ iceberg.NewNot(iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMinValue-25))),
+ false, "should skip: not(true)",
+ },
+ {
+ iceberg.NewAnd(
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMinValue-30))),
+ false, "should skip: and(false, true)",
+ },
+ {
+ iceberg.NewAnd(
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+1))),
+ false, "should skip: and(false, false)",
+ },
+ {
+ iceberg.NewAnd(
+ iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMinValue-25)),
+ iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue))),
+ true, "should read: and(true, true)",
+ },
+ {
+ iceberg.NewOr(
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+1))),
+ false, "should skip: or(false, false)",
+ },
+ {
+ iceberg.NewOr(
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)),
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue-19))),
+ true, "should read: or(false, true)",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("some_nulls"), "1"), false,
+ "should not read: id range below lower bound",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("some_nulls"), "b"), true,
+ "should read: lower bound in range",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("float"), 15.50), true,
+ "should read: lower bound in range",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("no_nan_or_null"), 15.50), true,
+ "should read: lower bound in range",
+ },
+ {
+ iceberg.LessThanEqual(iceberg.Reference("no_nulls_same_value_a"), "a"), true,
+ "should read: lower bound in range",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue-25)), false,
+ "should not read: id range below lower bound (5 < 30)",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue)), false,
+ "should not read: id range below lower bound (30 is not < 30)",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMinValue+1)), true,
+ "should read: one possible id",
+ },
+ {
+ iceberg.LessThan(iceberg.Reference("id"), int32(IntMaxValue)), true,
+ "should read: many possible ids",
+ },
+ {
+ iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue-25)), false,
+ "should not read: id range below lower bound (5 < 30)",
+ },
+ {
+ iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue-1)), false,
+ "should not read: id range below lower bound 29 < 30",
+ },
+ {
+ iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMinValue)), true,
+ "should read: one possible id",
+ },
+ {
+ iceberg.LessThanEqual(iceberg.Reference("id"), int32(IntMaxValue)), true,
+ "should read: many possible ids",
+ },
+ {
+ iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue+6)), false,
+ "should not read: id range above upper bound (85 < 79)",
+ },
+ {
+ iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue)), false,
+ "should not read: id range above upper bound (79 is not > 79)",
+ },
+ {
+ iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue-1)), true,
+ "should read: one possible id",
+ },
+ {
+ iceberg.GreaterThan(iceberg.Reference("id"), int32(IntMaxValue-4)), true,
+ "should read: many possible ids",
+ },
+ {
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+6)), false,
+ "should not read: id range is above upper bound (85 < 79)",
+ },
+ {
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue+1)), false,
+ "should not read: id range above upper bound (80 > 79)",
+ },
+ {
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue)), true,
+ "should read: one possible id",
+ },
+ {
+ iceberg.GreaterThanEqual(iceberg.Reference("id"), int32(IntMaxValue)), true,
+ "should read: many possible ids",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-25)), false,
+ "should not read: id below lower bound",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-1)), false,
+ "should not read: id below lower bound",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue)), true,
+ "should read: id equal to lower bound",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue-4)), true,
+ "should read: id between lower and upper bounds",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue)), true,
+ "should read: id equal to upper bound",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+1)), false,
+ "should not read: id above upper bound",
+ },
+ {
+ iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+6)), false,
+ "should not read: id above upper bound",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMinValue-25)), true,
+ "should read: id below lower bound",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMinValue-1)), true,
+ "should read: id below lower bound",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMinValue)), true,
+ "should read: id equal to lower bound",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue-4)), true,
+ "should read: id between lower and upper bounds",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue)), true,
+ "should read: id equal to upper bound",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue+1)), true,
+ "should read: id above upper bound",
+ },
+ {
+ iceberg.NotEqualTo(iceberg.Reference("id"), int32(IntMaxValue+6)), true,
+ "should read: id above upper bound",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-25))), true,
+ "should read: id below lower bound",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue-1))), true,
+ "should read: id below lower bound",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMinValue))), true,
+ "should read: id equal to lower bound",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue-4))), true,
+ "should read: id between lower and upper bounds",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue))), true,
+ "should read: id equal to upper bound",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+1))), true,
+ "should read: id above upper bound",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("id"), int32(IntMaxValue+6))), true,
+ "should read: id above upper bound",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMinValue-25), IntMinValue-24), false,
+ "should not read: id below lower bound (5 < 30, 6 < 30)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMinValue-2), IntMinValue-1), false,
+ "should not read: id below lower bound (28 < 30, 29 < 30)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMinValue-1), IntMinValue), true,
+ "should read: id equal to lower bound (30 == 30)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue-4), IntMaxValue-3), true,
+ "should read: id between lower and upper bounds (30 < 75 < 79, 30 < 76 < 79)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue), IntMaxValue+1), true,
+ "should read: id equal to upper bound (79 == 79)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue+1), IntMaxValue+2), false,
+ "should not read: id above upper bound (80 > 79, 81 > 79)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("id"), int32(IntMaxValue+6), IntMaxValue+7), false,
+ "should not read: id above upper bound (85 > 79, 86 > 79)",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("all_nulls_missing_nan"), "abc", "def"), false,
+ "should skip: in on all nulls column",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("some_nulls"), "abc", "def"), true,
+ "should read: in on some nulls column",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("no_nulls"), "abc", "def"), true,
+ "should read: in on no nulls column",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("no_nulls_same_value_a"), "a", "b"), true,
+ "should read: in on no nulls column",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("float"), 0, -5.5), true,
+ "should read: float equal to lower bound",
+ },
+ {
+ iceberg.IsIn(iceberg.Reference("no_nan_or_null"), 0, -5.5), true,
+ "should read: float equal to lower bound",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMinValue-25), IntMinValue-24), true,
+ "should read: id below lower bound (5 < 30, 6 < 30)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMinValue-2), IntMinValue-1), true,
+ "should read: id below lower bound (28 < 30, 29 < 30)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMinValue-1), IntMinValue), true,
+ "should read: id equal to lower bound (30 == 30)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue-4), IntMaxValue-3), true,
+ "should read: id between lower and upper bounds (30 < 75 < 79, 30 < 76 < 79)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue), IntMaxValue+1), true,
+ "should read: id equal to upper bound (79 == 79)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue+1), IntMaxValue+2), true,
+ "should read: id above upper bound (80 > 79, 81 > 79)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("id"), int32(IntMaxValue+6), IntMaxValue+7), true,
+ "should read: id above upper bound (85 > 79, 86 > 79)",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("all_nulls_missing_nan"), "abc", "def"), true,
+ "should read: notIn on all nulls column",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("some_nulls"), "abc", "def"), true,
+ "should read: notIn on some nulls column",
+ },
+ {
+ iceberg.NotIn(iceberg.Reference("no_nulls"), "abc", "def"), true,
+ "should read: notIn on no nulls column",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("some_nulls"), "a"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("some_nulls"), "aa"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("some_nulls"), "dddd"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("some_nulls"), "z"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("no_nulls"), "a"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("some_nulls"), "zzzz"), false,
+ "should skip: range doesn't match",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("some_nulls"), "1"), false,
+ "should skip: range doesn't match",
+ },
+ {
+ iceberg.StartsWith(iceberg.Reference("no_nulls_same_value_a"), "a"), true,
+ "should read: all values start with the prefix",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "a"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "aa"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "dddd"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "z"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("no_nulls"), "a"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "zzzz"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("some_nulls"), "1"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("all_same_value_or_null"), "a"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("all_same_value_or_null"), "aa"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("all_same_value_or_null"), "A"), true,
+ "should read: range matches",
+ },
// Iceberg does not implement SQL 3-way boolean logic, so the choice of an
// all null column matching is by definition in order to surface more values
// to the query engine to allow it to make its own decision
- {iceberg.NotStartsWith(iceberg.Reference("all_nulls_missing_nan"), "A"), true,
- "should read: range matches"},
- {iceberg.NotStartsWith(iceberg.Reference("no_nulls_same_value_a"), "a"), false,
- "should not read: all values start with the prefix"},
+ {
+ iceberg.NotStartsWith(iceberg.Reference("all_nulls_missing_nan"), "A"), true,
+ "should read: range matches",
+ },
+ {
+ iceberg.NotStartsWith(iceberg.Reference("no_nulls_same_value_a"), "a"), false,
+ "should not read: all values start with the prefix",
+ },
}
for _, tt := range tests {
@@ -525,54 +734,72 @@ func (*ProjectionTestSuite) emptySpec() iceberg.PartitionSpec {
func (*ProjectionTestSuite) idSpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 1, FieldID: 1000,
- Transform: iceberg.IdentityTransform{}, Name: "id_part"},
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1000,
+ Transform: iceberg.IdentityTransform{}, Name: "id_part",
+ },
)
}
func (*ProjectionTestSuite) bucketSpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 2, FieldID: 1000,
- Transform: iceberg.BucketTransform{NumBuckets: 16}, Name: "data_bucket"},
+ iceberg.PartitionField{
+ SourceID: 2, FieldID: 1000,
+ Transform: iceberg.BucketTransform{NumBuckets: 16}, Name: "data_bucket",
+ },
)
}
func (*ProjectionTestSuite) daySpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 4, FieldID: 1000,
- Transform: iceberg.DayTransform{}, Name: "date"},
- iceberg.PartitionField{SourceID: 3, FieldID: 1001,
- Transform: iceberg.DayTransform{}, Name: "ddate"},
+ iceberg.PartitionField{
+ SourceID: 4, FieldID: 1000,
+ Transform: iceberg.DayTransform{}, Name: "date",
+ },
+ iceberg.PartitionField{
+ SourceID: 3, FieldID: 1001,
+ Transform: iceberg.DayTransform{}, Name: "ddate",
+ },
)
}
func (*ProjectionTestSuite) hourSpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 4, FieldID: 1000,
- Transform: iceberg.HourTransform{}, Name: "hour"},
+ iceberg.PartitionField{
+ SourceID: 4, FieldID: 1000,
+ Transform: iceberg.HourTransform{}, Name: "hour",
+ },
)
}
func (*ProjectionTestSuite) truncateStrSpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 2, FieldID: 1000,
- Transform: iceberg.TruncateTransform{Width: 2}, Name: "data_trunc"},
+ iceberg.PartitionField{
+ SourceID: 2, FieldID: 1000,
+ Transform: iceberg.TruncateTransform{Width: 2}, Name: "data_trunc",
+ },
)
}
func (*ProjectionTestSuite) truncateIntSpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 1, FieldID: 1000,
- Transform: iceberg.TruncateTransform{Width: 10}, Name: "id_trunc"},
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1000,
+ Transform: iceberg.TruncateTransform{Width: 10}, Name: "id_trunc",
+ },
)
}
func (*ProjectionTestSuite) idAndBucketSpec() iceberg.PartitionSpec {
return iceberg.NewPartitionSpec(
- iceberg.PartitionField{SourceID: 1, FieldID: 1000,
- Transform: iceberg.IdentityTransform{}, Name: "id_part"},
- iceberg.PartitionField{SourceID: 2, FieldID: 1001,
- Transform: iceberg.BucketTransform{NumBuckets: 16}, Name: "data_bucket"},
+ iceberg.PartitionField{
+ SourceID: 1, FieldID: 1000,
+ Transform: iceberg.IdentityTransform{}, Name: "id_part",
+ },
+ iceberg.PartitionField{
+ SourceID: 2, FieldID: 1001,
+ Transform: iceberg.BucketTransform{NumBuckets: 16}, Name: "data_bucket",
+ },
)
}
diff --git a/table/internal/parquet_files.go b/table/internal/parquet_files.go
index c128f5b..0afa44f 100644
--- a/table/internal/parquet_files.go
+++ b/table/internal/parquet_files.go
@@ -19,6 +19,7 @@ package internal
import (
"context"
+ "errors"
"fmt"
"slices"
"strconv"
@@ -128,6 +129,7 @@ type manifestVisitor[T any] interface {
func visitParquetManifest[T any](manifest *pqarrow.SchemaManifest, visitor manifestVisitor[T]) (res T, err error) {
if manifest == nil {
err = fmt.Errorf("%w: cannot visit nil manifest", iceberg.ErrInvalidArgument)
+
return
}
@@ -142,6 +144,7 @@ func visitParquetManifest[T any](manifest *pqarrow.SchemaManifest, visitor manif
res := visitManifestField(f, visitor)
results[i] = visitor.Field(f, res)
}
+
return visitor.Manifest(manifest, results), nil
}
@@ -159,6 +162,7 @@ func visitParquetManifestStruct[T any](field pqarrow.SchemaField, visitor manife
func visitManifestList[T any](field pqarrow.SchemaField, visitor manifestVisitor[T]) T {
elemField := field.Children[0]
res := visitManifestField(elemField, visitor)
+
return visitor.List(field, res)
}
@@ -273,6 +277,7 @@ func (p *pruneParquetSchema) Struct(field pqarrow.SchemaField, children []arrow.
} else {
result := *field.Field
result.Type = arrow.StructOf(selected...)
+
return result
}
}
@@ -297,14 +302,16 @@ func (p *pruneParquetSchema) Field(field pqarrow.SchemaField, result arrow.Field
if _, ok := field.Field.Type.(*arrow.StructType); ok {
result := *field.Field
result.Type = p.projectSelectedStruct(result.Type)
+
return result
}
if !field.IsLeaf() {
- panic(fmt.Errorf("cannot explicitly project list or map types"))
+ panic(errors.New("cannot explicitly project list or map types"))
}
p.indices = append(p.indices, field.ColIndex)
+
return *field.Field
}
@@ -314,6 +321,7 @@ func (p *pruneParquetSchema) List(field pqarrow.SchemaField, elemResult arrow.Fi
if elemResult.Type != nil {
result := *field.Field
result.Type = p.projectList(field.Field.Type.(arrow.ListLikeType), elemResult.Type)
+
return result
}
@@ -329,14 +337,16 @@ func (p *pruneParquetSchema) List(field pqarrow.SchemaField, elemResult arrow.Fi
result := *field.Field
projected := p.projectSelectedStruct(elemResult.Type)
result.Type = p.projectList(field.Field.Type.(arrow.ListLikeType), projected)
+
return result
}
if !field.Children[0].IsLeaf() {
- panic(fmt.Errorf("cannot explicitly project list or map types"))
+ panic(errors.New("cannot explicitly project list or map types"))
}
p.indices = append(p.indices, field.Children[0].ColIndex)
+
return *field.Field
}
@@ -346,6 +356,7 @@ func (p *pruneParquetSchema) Map(field pqarrow.SchemaField, keyResult, valResult
if valResult.Type != nil {
result := *field.Field
result.Type = p.projectMap(field.Field.Type.(*arrow.MapType), valResult.Type)
+
return result
}
@@ -365,6 +376,7 @@ func (p *pruneParquetSchema) Map(field pqarrow.SchemaField, keyResult, valResult
result := *field.Field
projected := p.projectSelectedStruct(valResult.Type)
result.Type = p.projectMap(field.Field.Type.(*arrow.MapType), projected)
+
return result
}
@@ -374,6 +386,7 @@ func (p *pruneParquetSchema) Map(field pqarrow.SchemaField, keyResult, valResult
p.indices = append(p.indices, field.Children[0].Children[0].ColIndex)
p.indices = append(p.indices, field.Children[0].Children[1].ColIndex)
+
return *field.Field
}
@@ -411,6 +424,7 @@ func (p *pruneParquetSchema) projectList(listType arrow.ListLikeType, elemResult
}
n := listType.(*arrow.FixedSizeListType).Len()
+
return arrow.FixedSizeListOfField(n, origField)
}
diff --git a/table/internal/utils.go b/table/internal/utils.go
index 6efc1bc..2a1c261 100644
--- a/table/internal/utils.go
+++ b/table/internal/utils.go
@@ -37,6 +37,7 @@ func (pq *pqueue[T]) Len() int { return len(pq.queue) }
func (pq *pqueue[T]) Less(i, j int) bool {
return pq.compare(pq.queue[i], pq.queue[j])
}
+
func (pq *pqueue[T]) Swap(i, j int) {
pq.queue[i], pq.queue[j] = pq.queue[j], pq.queue[i]
}
@@ -52,6 +53,7 @@ func (pq *pqueue[T]) Pop() any {
item := old[n-1]
old[n-1] = nil
pq.queue = old[0 : n-1]
+
return item
}
@@ -72,5 +74,6 @@ func MakeSequencedChan[T any](bufferSize uint, source <-chan T, comesAfter, isNe
}
}
}()
+
return out
}
diff --git a/table/metadata.go b/table/metadata.go
index 43a348c..a5cb877 100644
--- a/table/metadata.go
+++ b/table/metadata.go
@@ -275,6 +275,7 @@ func (b *MetadataBuilder) AddSnapshot(snapshot *Snapshot) (*MetadataBuilder, err
b.lastUpdatedMS = snapshot.TimestampMs
b.lastSequenceNumber = &snapshot.SequenceNumber
b.snapshotList = append(b.snapshotList, *snapshot)
+
return b, nil
}
@@ -332,6 +333,7 @@ func (b *MetadataBuilder) SetCurrentSchemaID(currentSchemaID int) (*MetadataBuil
b.updates = append(b.updates, NewSetCurrentSchemaUpdate(currentSchemaID))
b.currentSchemaID = currentSchemaID
+
return b, nil
}
@@ -343,7 +345,7 @@ func (b *MetadataBuilder) SetDefaultSortOrderID(defaultSortOrderID int) (*Metada
if !slices.ContainsFunc(b.updates, func(u Update) bool {
return u.Action() == addSortOrderAction && u.(*addSortOrderUpdate).SortOrder.OrderID == defaultSortOrderID
}) {
- return nil, fmt.Errorf("can't set default sort order to last added with no added sort orders")
+ return nil, errors.New("can't set default sort order to last added with no added sort orders")
}
}
@@ -357,6 +359,7 @@ func (b *MetadataBuilder) SetDefaultSortOrderID(defaultSortOrderID int) (*Metada
b.updates = append(b.updates, NewSetDefaultSortOrderUpdate(defaultSortOrderID))
b.defaultSortOrderID = defaultSortOrderID
+
return b, nil
}
@@ -368,7 +371,7 @@ func (b *MetadataBuilder) SetDefaultSpecID(defaultSpecID int) (*MetadataBuilder,
if !slices.ContainsFunc(b.updates, func(u Update) bool {
return u.Action() == addPartionSpecAction && u.(*addPartitionSpecUpdate).Spec.ID() == defaultSpecID
}) {
- return nil, fmt.Errorf("can't set default spec to last added with no added partition specs")
+ return nil, errors.New("can't set default spec to last added with no added partition specs")
}
}
@@ -382,6 +385,7 @@ func (b *MetadataBuilder) SetDefaultSpecID(defaultSpecID int) (*MetadataBuilder,
b.updates = append(b.updates, NewSetDefaultSpecUpdate(defaultSpecID))
b.defaultSpecID = defaultSpecID
+
return b, nil
}
@@ -401,6 +405,7 @@ func (b *MetadataBuilder) SetFormatVersion(formatVersion int) (*MetadataBuilder,
b.updates = append(b.updates, NewUpgradeFormatVersionUpdate(formatVersion))
b.formatVersion = formatVersion
+
return b, nil
}
@@ -411,6 +416,7 @@ func (b *MetadataBuilder) SetLoc(loc string) (*MetadataBuilder, error) {
b.updates = append(b.updates, NewSetLocationUpdate(loc))
b.loc = loc
+
return b, nil
}
@@ -421,6 +427,7 @@ func (b *MetadataBuilder) SetProperties(props iceberg.Properties) (*MetadataBuil
b.updates = append(b.updates, NewSetPropertiesUpdate(props))
maps.Copy(b.props, props)
+
return b, nil
}
@@ -432,6 +439,7 @@ func WithMaxRefAgeMs(maxRefAgeMs int64) setSnapshotRefOption {
return fmt.Errorf("%w: maxRefAgeMs %d, must be > 0", iceberg.ErrInvalidArgument, maxRefAgeMs)
}
ref.MaxRefAgeMs = &maxRefAgeMs
+
return nil
}
}
@@ -442,6 +450,7 @@ func WithMaxSnapshotAgeMs(maxSnapshotAgeMs int64) setSnapshotRefOption {
return fmt.Errorf("%w: maxSnapshotAgeMs %d, must be > 0", iceberg.ErrInvalidArgument, maxSnapshotAgeMs)
}
ref.MaxSnapshotAgeMs = &maxSnapshotAgeMs
+
return nil
}
}
@@ -452,6 +461,7 @@ func WithMinSnapshotsToKeep(minSnapshotsToKeep int) setSnapshotRefOption {
return fmt.Errorf("%w: minSnapshotsToKeep %d, must be > 0", iceberg.ErrInvalidArgument, minSnapshotsToKeep)
}
ref.MinSnapshotsToKeep = &minSnapshotsToKeep
+
return nil
}
}
@@ -510,6 +520,7 @@ func (b *MetadataBuilder) SetSnapshotRef(
}
b.refs[name] = ref
+
return b, nil
}
@@ -520,6 +531,7 @@ func (b *MetadataBuilder) SetUUID(uuid uuid.UUID) (*MetadataBuilder, error) {
b.updates = append(b.updates, NewAssignUUIDUpdate(uuid))
b.uuid = uuid
+
return b, nil
}
@@ -639,6 +651,7 @@ func maxBy[S ~[]E, E any](elems S, extract func(e E) int) int {
for _, e := range elems {
m = max(m, extract(e))
}
+
return m
}
@@ -765,7 +778,6 @@ func (c *commonMetadata) Equals(other *commonMetadata) bool {
c.DefaultSpecID == other.DefaultSpecID && c.DefaultSortOrderID == other.DefaultSortOrderID &&
slices.Equal(c.SnapshotLog, other.SnapshotLog) && slices.Equal(c.MetadataLog, other.MetadataLog) &&
sliceEqualHelper(c.SortOrderList, other.SortOrderList)
-
}
func (c *commonMetadata) TableUUID() uuid.UUID { return c.UUID }
@@ -796,6 +808,7 @@ func (c *commonMetadata) PartitionSpec() iceberg.PartitionSpec {
return s
}
}
+
return *iceberg.UnpartitionedSpec
}
@@ -807,6 +820,7 @@ func (c *commonMetadata) SnapshotByID(id int64) *Snapshot {
return &c.SnapshotList[i]
}
}
+
return nil
}
@@ -814,6 +828,7 @@ func (c *commonMetadata) SnapshotByName(name string) *Snapshot {
if ref, ok := c.SnapshotRefs[name]; ok {
return c.SnapshotByID(ref.SnapshotID)
}
+
return nil
}
@@ -821,6 +836,7 @@ func (c *commonMetadata) CurrentSnapshot() *Snapshot {
if c.CurrentSnapshotID == nil {
return nil
}
+
return c.SnapshotByID(*c.CurrentSnapshotID)
}
@@ -831,6 +847,7 @@ func (c *commonMetadata) SortOrder() SortOrder {
return s
}
}
+
return UnsortedSortOrder
}
@@ -968,7 +985,8 @@ func (m *metadataV1) preValidate() {
if len(m.Specs) == 0 {
m.Specs = []iceberg.PartitionSpec{
- iceberg.NewPartitionSpec(m.Partition...)}
+ iceberg.NewPartitionSpec(m.Partition...),
+ }
m.DefaultSpecID = m.Specs[0].ID()
}
@@ -999,6 +1017,7 @@ func (m *metadataV1) UnmarshalJSON(b []byte) error {
}
m.preValidate()
+
return m.validate()
}
@@ -1041,6 +1060,7 @@ func (m *metadataV2) UnmarshalJSON(b []byte) error {
}
m.preValidate()
+
return m.validate()
}
diff --git a/table/metadata_internal_test.go b/table/metadata_internal_test.go
index 44aa037..00c6c03 100644
--- a/table/metadata_internal_test.go
+++ b/table/metadata_internal_test.go
@@ -508,7 +508,9 @@ func TestNewMetadataWithExplicitV1Format(t *testing.T) {
Fields: []SortField{{
SourceID: 10,
Transform: iceberg.IdentityTransform{},
- Direction: SortASC, NullOrder: NullsLast}}}
+ Direction: SortASC, NullOrder: NullsLast,
+ }},
+ }
actual, err := NewMetadata(schema, &partitionSpec, sortOrder, "s3://some_v1_location/", iceberg.Properties{"format-version": "1"})
require.NoError(t, err)
@@ -525,7 +527,9 @@ func TestNewMetadataWithExplicitV1Format(t *testing.T) {
OrderID: 1,
Fields: []SortField{{
SourceID: 1, Transform: iceberg.IdentityTransform{},
- Direction: SortASC, NullOrder: NullsLast}}}
+ Direction: SortASC, NullOrder: NullsLast,
+ }},
+ }
lastPartitionID := 1000
expected := &metadataV1{
@@ -566,7 +570,9 @@ func TestNewMetadataV2Format(t *testing.T) {
Fields: []SortField{{
SourceID: 10,
Transform: iceberg.IdentityTransform{},
- Direction: SortASC, NullOrder: NullsLast}}}
+ Direction: SortASC, NullOrder: NullsLast,
+ }},
+ }
tableUUID := uuid.New()
@@ -585,7 +591,9 @@ func TestNewMetadataV2Format(t *testing.T) {
OrderID: 1,
Fields: []SortField{{
SourceID: 1, Transform: iceberg.IdentityTransform{},
- Direction: SortASC, NullOrder: NullsLast}}}
+ Direction: SortASC, NullOrder: NullsLast,
+ }},
+ }
lastPartitionID := 1000
expected := &metadataV2{
@@ -602,7 +610,8 @@ func TestNewMetadataV2Format(t *testing.T) {
SortOrderList: []SortOrder{expectedSortOrder},
DefaultSortOrderID: 1,
FormatVersion: 2,
- }}
+ },
+ }
assert.Truef(t, expected.Equals(actual), "expected: %s\ngot: %s", expected, actual)
}
diff --git a/table/name_mapping.go b/table/name_mapping.go
index b71b7d3..dae5a37 100644
--- a/table/name_mapping.go
+++ b/table/name_mapping.go
@@ -60,6 +60,7 @@ func (m *MappedField) String() string {
}
bldr.WriteByte(')')
+
return bldr.String()
}
@@ -74,6 +75,7 @@ func (nm NameMapping) String() string {
bldr.WriteByte('\n')
}
bldr.WriteByte(']')
+
return bldr.String()
}
@@ -86,6 +88,7 @@ type NameMappingVisitor[S, T any] interface {
func VisitNameMapping[S, T any](obj NameMapping, visitor NameMappingVisitor[S, T]) (res S, err error) {
if obj == nil {
err = fmt.Errorf("%w: cannot visit nil NameMapping", iceberg.ErrInvalidArgument)
+
return
}
@@ -230,6 +233,7 @@ func (nameMapProjectVisitor) mappedFieldID(mapped *MappedField, name string) int
if f.FieldID != nil {
return *f.FieldID
}
+
return -1
}
}
@@ -262,6 +266,7 @@ func (n *nameMapProjectVisitor) Map(m iceberg.MapType, mapPartner *MappedField,
keyID := n.mappedFieldID(mapPartner, "key")
valID := n.mappedFieldID(mapPartner, "value")
+
return iceberg.NestedField{
Type: &iceberg.MapType{
KeyID: keyID,
diff --git a/table/name_mapping_test.go b/table/name_mapping_test.go
index bbef128..c8f928b 100644
--- a/table/name_mapping_test.go
+++ b/table/name_mapping_test.go
@@ -26,32 +26,32 @@ import (
"github.com/stretchr/testify/require"
)
-var (
- tableNameMappingNested = table.NameMapping{
- {FieldID: makeID(1), Names: []string{"foo"}},
- {FieldID: makeID(2), Names: []string{"bar"}},
- {FieldID: makeID(3), Names: []string{"baz"}},
- {FieldID: makeID(4), Names: []string{"qux"},
- Fields: []table.MappedField{{FieldID: makeID(5), Names: []string{"element"}}}},
- {FieldID: makeID(6), Names: []string{"quux"}, Fields: []table.MappedField{
- {FieldID: makeID(7), Names: []string{"key"}},
- {FieldID: makeID(8), Names: []string{"value"}, Fields: []table.MappedField{
- {FieldID: makeID(9), Names: []string{"key"}},
- {FieldID: makeID(10), Names: []string{"value"}},
- }},
+var tableNameMappingNested = table.NameMapping{
+ {FieldID: makeID(1), Names: []string{"foo"}},
+ {FieldID: makeID(2), Names: []string{"bar"}},
+ {FieldID: makeID(3), Names: []string{"baz"}},
+ {
+ FieldID: makeID(4), Names: []string{"qux"},
+ Fields: []table.MappedField{{FieldID: makeID(5), Names: []string{"element"}}},
+ },
+ {FieldID: makeID(6), Names: []string{"quux"}, Fields: []table.MappedField{
+ {FieldID: makeID(7), Names: []string{"key"}},
+ {FieldID: makeID(8), Names: []string{"value"}, Fields: []table.MappedField{
+ {FieldID: makeID(9), Names: []string{"key"}},
+ {FieldID: makeID(10), Names: []string{"value"}},
}},
- {FieldID: makeID(11), Names: []string{"location"}, Fields: []table.MappedField{
- {FieldID: makeID(12), Names: []string{"element"}, Fields: []table.MappedField{
- {FieldID: makeID(13), Names: []string{"latitude"}},
- {FieldID: makeID(14), Names: []string{"longitude"}},
- }},
+ }},
+ {FieldID: makeID(11), Names: []string{"location"}, Fields: []table.MappedField{
+ {FieldID: makeID(12), Names: []string{"element"}, Fields: []table.MappedField{
+ {FieldID: makeID(13), Names: []string{"latitude"}},
+ {FieldID: makeID(14), Names: []string{"longitude"}},
}},
- {FieldID: makeID(15), Names: []string{"person"}, Fields: []table.MappedField{
- {FieldID: makeID(16), Names: []string{"name"}},
- {FieldID: makeID(17), Names: []string{"age"}},
- }},
- }
-)
+ }},
+ {FieldID: makeID(15), Names: []string{"person"}, Fields: []table.MappedField{
+ {FieldID: makeID(16), Names: []string{"name"}},
+ {FieldID: makeID(17), Names: []string{"age"}},
+ }},
+}
func TestJsonMappedField(t *testing.T) {
tests := []struct {
@@ -59,10 +59,14 @@ func TestJsonMappedField(t *testing.T) {
str string
exp table.MappedField
}{
- {"simple", `{"field-id": 1, "names": ["id", "record_id"]}`,
- table.MappedField{FieldID: makeID(1), Names: []string{"id", "record_id"}}},
- {"with null fields", `{"field-id": 1, "names": ["id", "record_id"], "fields": null}`,
- table.MappedField{FieldID: makeID(1), Names: []string{"id", "record_id"}}},
+ {
+ "simple", `{"field-id": 1, "names": ["id", "record_id"]}`,
+ table.MappedField{FieldID: makeID(1), Names: []string{"id", "record_id"}},
+ },
+ {
+ "with null fields", `{"field-id": 1, "names": ["id", "record_id"], "fields": null}`,
+ table.MappedField{FieldID: makeID(1), Names: []string{"id", "record_id"}},
+ },
{"no names", `{"field-id": 1, "names": []}`, table.MappedField{FieldID: makeID(1), Names: []string{}}},
}
@@ -141,5 +145,6 @@ func TestNameMappingToString(t *testing.T) {
{FieldID: makeID(3), Names: []string{"location"}, Fields: []table.MappedField{
{FieldID: makeID(4), Names: []string{"lat", "latitude"}},
{FieldID: makeID(5), Names: []string{"long", "longitude"}},
- }}}.String())
+ }},
+ }.String())
}
diff --git a/table/refs.go b/table/refs.go
index f0eb697..7e84737 100644
--- a/table/refs.go
+++ b/table/refs.go
@@ -33,9 +33,7 @@ const (
TagRef RefType = "tag"
)
-var (
- ErrInvalidRefType = errors.New("invalid snapshot ref type, should be 'branch' or 'tag'")
-)
+var ErrInvalidRefType = errors.New("invalid snapshot ref type, should be 'branch' or 'tag'")
// SnapshotRef represents the reference information for a specific snapshot
type SnapshotRef struct {
diff --git a/table/requirements.go b/table/requirements.go
index 5a4b883..57cac63 100644
--- a/table/requirements.go
+++ b/table/requirements.go
@@ -18,6 +18,7 @@
package table
import (
+ "errors"
"fmt"
"github.com/google/uuid"
@@ -61,7 +62,7 @@ func AssertCreate() Requirement {
func (a *assertCreate) Validate(meta Metadata) error {
if meta != nil {
- return fmt.Errorf("Table already exists")
+ return errors.New("Table already exists")
}
return nil
@@ -82,7 +83,7 @@ func AssertTableUUID(uuid uuid.UUID) Requirement {
func (a *assertTableUuid) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
if meta.TableUUID() != a.UUID {
@@ -111,13 +112,14 @@ func AssertRefSnapshotID(ref string, id *int64) Requirement {
func (a *assertRefSnapshotID) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
var r *SnapshotRef
for name, ref := range meta.Refs() {
if name == a.Ref {
r = &ref
+
break
}
}
@@ -152,7 +154,7 @@ func AssertLastAssignedFieldID(id int) Requirement {
func (a *assertLastAssignedFieldId) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
if meta.LastColumnID() != a.LastAssignedFieldID {
@@ -178,7 +180,7 @@ func AssertCurrentSchemaID(id int) Requirement {
func (a *assertCurrentSchemaId) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
if meta.CurrentSchema().ID != a.CurrentSchemaID {
@@ -204,7 +206,7 @@ func AssertLastAssignedPartitionID(id int) Requirement {
func (a *assertLastAssignedPartitionId) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
if *meta.LastPartitionSpecID() != a.LastAssignedPartitionID {
@@ -230,7 +232,7 @@ func AssertDefaultSpecID(id int) Requirement {
func (a *assertDefaultSpecId) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
if meta.DefaultPartitionSpec() != a.DefaultSpecID {
@@ -256,7 +258,7 @@ func AssertDefaultSortOrderID(id int) Requirement {
func (a *assertDefaultSortOrderId) Validate(meta Metadata) error {
if meta == nil {
- return fmt.Errorf("requirement failed: current table metadata does not exist")
+ return errors.New("requirement failed: current table metadata does not exist")
}
if meta.DefaultSortOrder() != a.DefaultSortOrderID {
diff --git a/table/scanner.go b/table/scanner.go
index 0b8c2f1..c0eaf93 100644
--- a/table/scanner.go
+++ b/table/scanner.go
@@ -20,6 +20,7 @@ package table
import (
"cmp"
"context"
+ "errors"
"fmt"
"iter"
"slices"
@@ -45,6 +46,7 @@ func (k *keyDefaultMap[K, V]) Get(key K) V {
k.mx.RLock()
if v, ok := k.data[key]; ok {
k.mx.RUnlock()
+
return v
}
@@ -54,6 +56,7 @@ func (k *keyDefaultMap[K, V]) Get(key K) V {
v := k.defaultFactory(key)
k.data[key] = v
+
return v
}
@@ -72,6 +75,7 @@ func newKeyDefaultMapWrapErr[K comparable, V any](factory func(K) (V, error)) *k
if err != nil {
panic(err)
}
+
return v
},
}
@@ -116,12 +120,13 @@ func getPartitionRecord(dataFile iceberg.DataFile, partitionType *iceberg.Struct
for i, f := range partitionType.FieldList {
out[i] = partitionData[f.Name]
}
+
return out
}
func openManifest(io io.IO, manifest iceberg.ManifestFile,
- partitionFilter, metricsEval func(iceberg.DataFile) (bool, error)) ([]iceberg.ManifestEntry, error) {
-
+ partitionFilter, metricsEval func(iceberg.DataFile) (bool, error),
+) ([]iceberg.ManifestEntry, error) {
entries, err := manifest.FetchEntries(io, true)
if err != nil {
return nil, err
@@ -164,6 +169,7 @@ type Scan struct {
func (scan *Scan) UseRowLimit(n int64) *Scan {
out := *scan
out.limit = n
+
return &out
}
@@ -188,6 +194,7 @@ func (scan *Scan) Snapshot() *Snapshot {
if scan.snapshotID != nil {
return scan.metadata.SnapshotByID(*scan.snapshotID)
}
+
return scan.metadata.CurrentSnapshot()
}
@@ -203,6 +210,7 @@ func (scan *Scan) Projection() (*iceberg.Schema, error) {
for _, schema := range scan.metadata.Schemas() {
if schema.ID == *snap.SchemaID {
curSchema = schema
+
break
}
}
@@ -219,11 +227,13 @@ func (scan *Scan) Projection() (*iceberg.Schema, error) {
func (scan *Scan) buildPartitionProjection(specID int) (iceberg.BooleanExpression, error) {
project := newInclusiveProjection(scan.metadata.CurrentSchema(),
scan.metadata.PartitionSpecs()[specID], true)
+
return project(scan.rowFilter)
}
func (scan *Scan) buildManifestEvaluator(specID int) (func(iceberg.ManifestFile) (bool, error), error) {
spec := scan.metadata.PartitionSpecs()[specID]
+
return newManifestEvaluator(spec, scan.metadata.CurrentSchema(),
scan.partitionFilters.Get(specID), scan.caseSensitive)
}
@@ -257,6 +267,7 @@ func minSequenceNum(manifests []iceberg.ManifestFile) int64 {
n = min(n, m.MinSequenceNum())
}
}
+
return n
}
@@ -305,6 +316,7 @@ func (scan *Scan) fetchPartitionSpecFilteredManifests() ([]iceberg.ManifestFile,
manifestList = slices.DeleteFunc(manifestList, func(mf iceberg.ManifestFile) bool {
eval := manifestEvaluators.Get(int(mf.PartitionSpecID()))
use, err := eval(mf)
+
return !use || err != nil
})
@@ -356,12 +368,13 @@ func (scan *Scan) collectManifestEntries(
case iceberg.EntryContentPosDeletes:
entries.addPositionalDeleteEntry(e)
case iceberg.EntryContentEqDeletes:
- return fmt.Errorf("iceberg-go does not yet support equality deletes")
+ return errors.New("iceberg-go does not yet support equality deletes")
default:
return fmt.Errorf("%w: unknown DataFileContent type (%s): %s",
ErrInvalidMetadata, df.ContentType(), e)
}
}
+
return nil
})
}
diff --git a/table/snapshots.go b/table/snapshots.go
index c880d7d..d06bc24 100644
--- a/table/snapshots.go
+++ b/table/snapshots.go
@@ -49,6 +49,7 @@ func ValidOperation(s string) (Operation, error) {
case "append", "replace", "overwrite", "delete":
return Operation(s), nil
}
+
return "", fmt.Errorf("%w: found '%s'", ErrInvalidOperation, s)
}
@@ -68,6 +69,7 @@ func (s *Summary) String() string {
data, _ := json.Marshal(s.Properties)
out += ", " + string(data)
}
+
return out
}
@@ -108,6 +110,7 @@ func (s *Summary) UnmarshalJSON(b []byte) (err error) {
delete(alias, operationKey)
s.Properties = alias
+
return nil
}
@@ -134,9 +137,7 @@ type Snapshot struct {
}
func (s Snapshot) String() string {
- var (
- op, parent, schema string
- )
+ var op, parent, schema string
if s.Summary != nil {
op = s.Summary.String() + ": "
@@ -147,6 +148,7 @@ func (s Snapshot) String() string {
if s.SchemaID != nil {
schema = ", schema_id=" + strconv.Itoa(*s.SchemaID)
}
+
return fmt.Sprintf("%sid=%d%s%s, sequence_number=%d, timestamp_ms=%d, manifest_list=%s",
op, s.SnapshotID, parent, schema, s.SequenceNumber, s.TimestampMs, s.ManifestList)
}
@@ -179,6 +181,7 @@ func (s Snapshot) Manifests(fio io.IO) ([]iceberg.ManifestFile, error) {
return nil, fmt.Errorf("could not open manifest file: %w", err)
}
defer f.Close()
+
return iceberg.ReadManifestList(f)
}
diff --git a/table/snapshots_test.go b/table/snapshots_test.go
index 6a101a5..5be91b2 100644
--- a/table/snapshots_test.go
+++ b/table/snapshots_test.go
@@ -29,6 +29,7 @@ import (
func Snapshot() table.Snapshot {
parentID := int64(19)
manifest, schemaid := "s3:/a/b/c.avro", 3
+
return table.Snapshot{
SnapshotID: 25,
ParentSnapshotID: &parentID,
@@ -45,6 +46,7 @@ func Snapshot() table.Snapshot {
func SnapshotWithProperties() table.Snapshot {
parentID := int64(19)
manifest, schemaid := "s3:/a/b/c.avro", 3
+
return table.Snapshot{
SnapshotID: 25,
ParentSnapshotID: &parentID,
diff --git a/table/sorting.go b/table/sorting.go
index e510439..1ae9f05 100644
--- a/table/sorting.go
+++ b/table/sorting.go
@@ -64,6 +64,7 @@ func (s *SortField) String() string {
if _, ok := s.Transform.(iceberg.IdentityTransform); ok {
return fmt.Sprintf("%d %s %s", s.SourceID, s.Direction, s.NullOrder)
}
+
return fmt.Sprintf("%s(%d) %s %s", s.Transform, s.SourceID, s.Direction, s.NullOrder)
}
@@ -81,12 +82,13 @@ func (s *SortField) MarshalJSON() ([]byte, error) {
}
type Alias SortField
+
return json.Marshal((*Alias)(s))
}
func (s *SortField) UnmarshalJSON(b []byte) error {
type Alias SortField
- var aux = struct {
+ aux := struct {
TransformString string `json:"transform"`
*Alias
}{
@@ -152,6 +154,7 @@ func (s SortOrder) String() string {
b.WriteByte('\n')
}
b.WriteByte(']')
+
return b.String()
}
@@ -166,6 +169,7 @@ func (s *SortOrder) UnmarshalJSON(b []byte) error {
if len(s.Fields) == 0 {
s.Fields = []SortField{}
s.OrderID = 0
+
return nil
}
@@ -208,5 +212,6 @@ func AssignFreshSortOrderIDsWithID(sortOrder SortOrder, old, fresh *iceberg.Sche
NullOrder: field.NullOrder,
})
}
+
return SortOrder{OrderID: sortOrderID, Fields: fields}, nil
}
diff --git a/table/substrait/substrait.go b/table/substrait/substrait.go
index 550e328..f5ce210 100644
--- a/table/substrait/substrait.go
+++ b/table/substrait/substrait.go
@@ -60,13 +60,16 @@ func ConvertExpr(schema *iceberg.Schema, e iceberg.BooleanExpression, caseSensit
reg := expr.NewEmptyExtensionRegistry(collection)
bldr := expr.ExprBuilder{Reg: reg, BaseSchema: types.NewRecordTypeFromStruct(base.Struct)}
- b, err := iceberg.VisitExpr(e, &toSubstraitExpr{bldr: bldr, schema: schema,
- caseSensitive: caseSensitive})
+ b, err := iceberg.VisitExpr(e, &toSubstraitExpr{
+ bldr: bldr, schema: schema,
+ caseSensitive: caseSensitive,
+ })
if err != nil {
return nil, nil, err
}
out, err := b.BuildExpr()
+
return ®, out, err
}
@@ -108,6 +111,7 @@ func getNullability(required bool) types.Nullability {
if required {
return types.NullabilityRequired
}
+
return types.NullabilityNullable
}
@@ -153,9 +157,7 @@ func (convertToSubstrait) VisitString() types.Type { return &types.StringTy
func (convertToSubstrait) VisitBinary() types.Type { return &types.BinaryType{} }
func (convertToSubstrait) VisitUUID() types.Type { return &types.UUIDType{} }
-var (
- _ iceberg.SchemaVisitorPerPrimitiveType[types.Type] = (*convertToSubstrait)(nil)
-)
+var _ iceberg.SchemaVisitorPerPrimitiveType[types.Type] = (*convertToSubstrait)(nil)
var (
boolURI = extensions.SubstraitDefaultURIPrefix + "functions_boolean.yaml"
@@ -233,6 +235,7 @@ func toDecimalLiteral(v iceberg.DecimalLiteral) expr.Literal {
Value: byts,
Precision: int32(v.Type().(*iceberg.DecimalType).Precision()),
}, false)
+
return result
}
@@ -258,6 +261,7 @@ func toSubstraitLiteral(typ iceberg.Type, lit iceberg.Literal) expr.Literal {
if typ.Equals(iceberg.PrimitiveTypes.TimestampTz) {
return toPrimitiveSubstraitLiteral(types.TimestampTz(lit))
}
+
return toPrimitiveSubstraitLiteral(types.Timestamp(lit))
case iceberg.DateLiteral:
return toPrimitiveSubstraitLiteral(types.Date(lit))
@@ -284,6 +288,7 @@ func toSubstraitLiteralSet(typ iceberg.Type, lits []iceberg.Literal) expr.ListLi
for i, l := range lits {
out[i] = toSubstraitLiteral(typ, l)
}
+
return out
}
@@ -304,11 +309,13 @@ func (t *toSubstraitExpr) getRef(ref iceberg.BoundReference) expr.Reference {
next := expr.NewStructFieldRef(int32(p))
cur.Child, cur = next, next
}
+
return out
}
func (t *toSubstraitExpr) makeSetFunc(id extensions.ID, term iceberg.BoundTerm, lits iceberg.Set[iceberg.Literal]) expr.Builder {
val := toSubstraitLiteralSet(term.Type(), lits.Members())
+
return t.bldr.ScalarFunc(id).Args(t.bldr.RootRef(t.getRef(term.Ref())),
t.bldr.Literal(expr.NewNestedLiteral(val, false)))
}
diff --git a/table/substrait/substrait_test.go b/table/substrait/substrait_test.go
index 8b849ff..2a5de0a 100644
--- a/table/substrait/substrait_test.go
+++ b/table/substrait/substrait_test.go
@@ -111,12 +111,18 @@ func TestExprs(t *testing.T) {
{iceberg.LessThan(ref, "hello"), tableSchemaSimple, "lt(.field(0) => string?, string(hello)) => boolean?"},
{iceberg.StartsWith(ref, "he"), tableSchemaSimple, "starts_with(.field(0) => string?, string(he)) => boolean?"},
{iceberg.NotStartsWith(ref, "he"), tableSchemaSimple, "not(starts_with(.field(0) => string?, string(he)) => boolean?) => boolean?"},
- {iceberg.NewAnd(iceberg.EqualTo(ref, "hello"), iceberg.IsNull(ref)), tableSchemaSimple,
- "and(equal(.field(0) => string?, string(hello)) => boolean?, is_null(.field(0) => string?) => boolean) => boolean?"},
- {iceberg.NewOr(iceberg.EqualTo(ref, "hello"), iceberg.IsNull(ref)), tableSchemaSimple,
- "or(equal(.field(0) => string?, string(hello)) => boolean?, is_null(.field(0) => string?) => boolean) => boolean?"},
- {iceberg.NewNot(iceberg.EqualTo(ref, "hello")), tableSchemaSimple,
- "not(equal(.field(0) => string?, string(hello)) => boolean?) => boolean?"},
+ {
+ iceberg.NewAnd(iceberg.EqualTo(ref, "hello"), iceberg.IsNull(ref)), tableSchemaSimple,
+ "and(equal(.field(0) => string?, string(hello)) => boolean?, is_null(.field(0) => string?) => boolean) => boolean?",
+ },
+ {
+ iceberg.NewOr(iceberg.EqualTo(ref, "hello"), iceberg.IsNull(ref)), tableSchemaSimple,
+ "or(equal(.field(0) => string?, string(hello)) => boolean?, is_null(.field(0) => string?) => boolean) => boolean?",
+ },
+ {
+ iceberg.NewNot(iceberg.EqualTo(ref, "hello")), tableSchemaSimple,
+ "not(equal(.field(0) => string?, string(hello)) => boolean?) => boolean?",
+ },
}
for _, tt := range tests {
diff --git a/table/table.go b/table/table.go
index ac9cd2b..753e33a 100644
--- a/table/table.go
+++ b/table/table.go
@@ -58,6 +58,7 @@ func (t Table) Schemas() map[int]*iceberg.Schema {
for _, s := range t.metadata.Schemas() {
m[s.ID] = s
}
+
return m
}
@@ -149,6 +150,7 @@ func (t Table) Scan(opts ...ScanOption) *Scan {
}
s.partitionFilters = newKeyDefaultMapWrapErr(s.buildPartitionProjection)
+
return s
}
@@ -184,5 +186,6 @@ func NewFromLocation(ident Identifier, metalocation string, fsys io.IO) (*Table,
return nil, err
}
}
+
return New(ident, meta, metalocation, fsys), nil
}
diff --git a/table/updates.go b/table/updates.go
index 7b09a0f..74f3ff7 100644
--- a/table/updates.go
+++ b/table/updates.go
@@ -68,6 +68,7 @@ func NewAssignUUIDUpdate(uuid uuid.UUID) Update {
func (u *assignUUIDUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetUUID(u.UUID)
+
return err
}
@@ -87,6 +88,7 @@ func NewUpgradeFormatVersionUpdate(formatVersion int) Update {
func (u *upgradeFormatVersionUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetFormatVersion(u.FormatVersion)
+
return err
}
@@ -111,6 +113,7 @@ func NewAddSchemaUpdate(schema *iceberg.Schema, lastColumnID int, initial bool)
func (u *addSchemaUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.AddSchema(u.Schema, u.LastColumnID, u.initial)
+
return err
}
@@ -130,6 +133,7 @@ func NewSetCurrentSchemaUpdate(id int) Update {
func (u *setCurrentSchemaUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetCurrentSchemaID(u.SchemaID)
+
return err
}
@@ -152,6 +156,7 @@ func NewAddPartitionSpecUpdate(spec *iceberg.PartitionSpec, initial bool) Update
func (u *addPartitionSpecUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.AddPartitionSpec(u.Spec, u.initial)
+
return err
}
@@ -171,6 +176,7 @@ func NewSetDefaultSpecUpdate(id int) Update {
func (u *setDefaultSpecUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetDefaultSpecID(u.SpecID)
+
return err
}
@@ -193,6 +199,7 @@ func NewAddSortOrderUpdate(sortOrder *SortOrder, initial bool) Update {
func (u *addSortOrderUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.AddSortOrder(u.SortOrder, u.initial)
+
return err
}
@@ -212,6 +219,7 @@ func NewSetDefaultSortOrderUpdate(id int) Update {
func (u *setDefaultSortOrderUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetDefaultSortOrderID(u.SortOrderID)
+
return err
}
@@ -230,6 +238,7 @@ func NewAddSnapshotUpdate(snapshot *Snapshot) Update {
func (u *addSnapshotUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.AddSnapshot(u.Snapshot)
+
return err
}
@@ -282,6 +291,7 @@ func (u *setSnapshotRefUpdate) Apply(builder *MetadataBuilder) error {
u.RefType,
opts...,
)
+
return err
}
@@ -300,6 +310,7 @@ func NewSetLocationUpdate(loc string) Update {
func (u *setLocationUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetLoc(u.Location)
+
return err
}
@@ -319,6 +330,7 @@ func NewSetPropertiesUpdate(updates iceberg.Properties) *setPropertiesUpdate {
func (u *setPropertiesUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.SetProperties(u.Updates)
+
return err
}
@@ -339,6 +351,7 @@ func NewRemovePropertiesUpdate(removals []string) Update {
func (u *removePropertiesUpdate) Apply(builder *MetadataBuilder) error {
_, err := builder.RemoveProperties(u.Removals)
+
return err
}
diff --git a/transforms.go b/transforms.go
index 71614a0..3066ea7 100644
--- a/transforms.go
+++ b/transforms.go
@@ -47,6 +47,7 @@ func ParseTransform(s string) (Transform, error) {
}
n, _ := strconv.Atoi(matches[1])
+
return BucketTransform{NumBuckets: n}, nil
case strings.HasPrefix(s, "truncate"):
matches := regexFromBrackets.FindStringSubmatch(s)
@@ -55,6 +56,7 @@ func ParseTransform(s string) (Transform, error) {
}
n, _ := strconv.Atoi(matches[1])
+
return TruncateTransform{Width: n}, nil
default:
switch s {
@@ -105,6 +107,7 @@ func (IdentityTransform) ResultType(t Type) Type { return t }
func (IdentityTransform) Equals(other Transform) bool {
_, ok := other.(IdentityTransform)
+
return ok
}
@@ -161,6 +164,7 @@ func (VoidTransform) ResultType(t Type) Type { return t }
func (VoidTransform) Equals(other Transform) bool {
_, ok := other.(VoidTransform)
+
return ok
}
@@ -198,6 +202,7 @@ func hashHelperInt[T ~int32 | ~int64](v any) uint32 {
)
binary.LittleEndian.PutUint64(b, val)
+
return murmur3.Sum32(b)
}
@@ -242,7 +247,8 @@ func (t BucketTransform) Apply(value Optional[Literal]) Optional[Literal] {
return Optional[Literal]{
Valid: true,
- Val: Int32Literal((int32(hash) & math.MaxInt32) % int32(t.NumBuckets))}
+ Val: Int32Literal((int32(hash) & math.MaxInt32) % int32(t.NumBuckets)),
+ }
}
func (t BucketTransform) Transformer(src Type) func(any) Optional[int32] {
@@ -264,6 +270,7 @@ func (t BucketTransform) Transformer(src Type) func(any) Optional[int32] {
case DecimalType:
h = func(v any) uint32 {
b, _ := DecimalLiteral(v.(Decimal)).MarshalBinary()
+
return murmur3.Sum32(b)
}
case StringType, FixedType, BinaryType:
@@ -273,6 +280,7 @@ func (t BucketTransform) Transformer(src Type) func(any) Optional[int32] {
}
str := v.(string)
+
return murmur3.Sum32(unsafe.Slice(unsafe.StringData(str), len(str)))
}
case UUIDType:
@@ -282,6 +290,7 @@ func (t BucketTransform) Transformer(src Type) func(any) Optional[int32] {
}
u := v.(uuid.UUID)
+
return murmur3.Sum32(u[:])
}
}
@@ -293,7 +302,8 @@ func (t BucketTransform) Transformer(src Type) func(any) Optional[int32] {
return Optional[int32]{
Valid: true,
- Val: int32((int32(h(v)) & math.MaxInt32) % int32(t.NumBuckets))}
+ Val: int32((int32(h(v)) & math.MaxInt32) % int32(t.NumBuckets)),
+ }
}
}
@@ -318,6 +328,7 @@ func (t BucketTransform) Project(name string, pred BoundPredicate) (UnboundPredi
if p.Op() != OpEQ {
break
}
+
return p.AsUnbound(Reference(name), transformLiteral(transformer, p.Literal())), nil
case BoundSetPredicate:
if p.Op() != OpIn {
@@ -361,6 +372,7 @@ func (t TruncateTransform) Transformer(src Type) (func(any) any, error) {
}
val := v.(int32)
+
return val - (val % int32(t.Width))
}, nil
case Int64Type:
@@ -370,6 +382,7 @@ func (t TruncateTransform) Transformer(src Type) (func(any) any, error) {
}
val := v.(int64)
+
return val - (val % int64(t.Width))
}, nil
case StringType, BinaryType:
@@ -385,6 +398,7 @@ func (t TruncateTransform) Transformer(src Type) (func(any) any, error) {
}, nil
case DecimalType:
bigWidth := big.NewInt(int64(t.Width))
+
return func(v any) any {
if v == nil {
return nil
@@ -396,6 +410,7 @@ func (t TruncateTransform) Transformer(src Type) (func(any) any, error) {
applied := (&big.Int{}).Mod(unscaled, bigWidth)
applied.Add(applied, bigWidth).Mod(applied, bigWidth)
val.Val = decimal128.FromBigInt(unscaled.Sub(unscaled, applied))
+
return val
}, nil
}
@@ -538,6 +553,7 @@ func (YearTransform) ResultType(Type) Type { return PrimitiveTypes.Int32 }
func (YearTransform) Equals(other Transform) bool {
_, ok := other.(YearTransform)
+
return ok
}
@@ -614,6 +630,7 @@ func (MonthTransform) ResultType(Type) Type { return PrimitiveTypes.Int32 }
func (MonthTransform) Equals(other Transform) bool {
_, ok := other.(MonthTransform)
+
return ok
}
@@ -626,11 +643,11 @@ func (MonthTransform) Transformer(src Type) (func(any) Optional[int32], error) {
}
d := v.(Date).ToTime()
+
return Optional[int32]{
Valid: true,
Val: int32((d.Year()-epochTM.Year())*12 + (int(d.Month()) - int(epochTM.Month()))),
}
-
}, nil
case TimestampType, TimestampTzType:
return func(v any) Optional[int32] {
@@ -639,11 +656,11 @@ func (MonthTransform) Transformer(src Type) (func(any) Optional[int32], error) {
}
d := v.(Timestamp).ToTime()
+
return Optional[int32]{
Valid: true,
Val: int32((d.Year()-epochTM.Year())*12 + (int(d.Month()) - int(epochTM.Month()))),
}
-
}, nil
}
@@ -669,6 +686,7 @@ func (MonthTransform) Apply(value Optional[Literal]) (out Optional[Literal]) {
out.Valid = true
out.Val = Int32Literal(int32((tm.Year()-epochTM.Year())*12 + (int(tm.Month()) - int(epochTM.Month()))))
+
return
}
@@ -676,6 +694,7 @@ func (t MonthTransform) ToHumanStr(val any) string {
switch v := val.(type) {
case int32:
tm := epochTM.AddDate(0, int(v), 0)
+
return tm.Format("2006-01")
default:
return "null"
@@ -699,6 +718,7 @@ func (DayTransform) ResultType(Type) Type { return PrimitiveTypes.Date }
func (DayTransform) Equals(other Transform) bool {
_, ok := other.(DayTransform)
+
return ok
}
@@ -743,6 +763,7 @@ func (DayTransform) Apply(value Optional[Literal]) (out Optional[Literal]) {
case TimestampLiteral:
out.Valid, out.Val = true, Int32Literal(Timestamp(v).ToDate())
}
+
return
}
@@ -750,6 +771,7 @@ func (DayTransform) ToHumanStr(val any) string {
switch v := val.(type) {
case int32:
tm := epochTM.AddDate(0, 0, int(v))
+
return tm.Format("2006-01-02")
default:
return "null"
@@ -773,6 +795,7 @@ func (HourTransform) ResultType(Type) Type { return PrimitiveTypes.Int32 }
func (HourTransform) Equals(other Transform) bool {
_, ok := other.(HourTransform)
+
return ok
}
@@ -780,6 +803,7 @@ func (HourTransform) Transformer(src Type) (func(any) Optional[int32], error) {
switch src.(type) {
case TimestampType, TimestampTzType:
const factor = int64(time.Hour / time.Microsecond)
+
return func(v any) Optional[int32] {
if v == nil {
return Optional[int32]{}
@@ -814,6 +838,7 @@ func (HourTransform) ToHumanStr(val any) string {
switch v := val.(type) {
case int32:
tm := epochTM.Add(time.Duration(v) * time.Hour)
+
return tm.Format("2006-01-02-15")
default:
return "null"
@@ -887,6 +912,7 @@ func wrapTransformFn[T LiteralType](fn func(any) any) func(any) Optional[T] {
if out == nil {
return Optional[T]{}
}
+
return Optional[T]{Valid: true, Val: out.(T)}
}
}
diff --git a/transforms_test.go b/transforms_test.go
index 837cf26..3e7a6d5 100644
--- a/transforms_test.go
+++ b/transforms_test.go
@@ -118,7 +118,8 @@ func TestToHumanString(t *testing.T) {
{iceberg.IdentityTransform{}, nil, "null"},
{iceberg.TruncateTransform{Width: 1}, []byte{0x00, 0x01, 0x02, 0x03}, "AAECAw=="},
{iceberg.TruncateTransform{Width: 1}, iceberg.Decimal{
- Val: decVal, Scale: 2}, "14.21"},
+ Val: decVal, Scale: 2,
+ }, "14.21"},
{iceberg.TruncateTransform{Width: 1}, int32(123), "123"},
{iceberg.TruncateTransform{Width: 1}, int64(123), "123"},
{iceberg.TruncateTransform{Width: 1}, "foo", "foo"},
diff --git a/types.go b/types.go
index 7330e95..ea93007 100644
--- a/types.go
+++ b/types.go
@@ -41,6 +41,7 @@ func (p Properties) Get(key, defVal string) string {
if v, ok := p[key]; ok {
return v
}
+
return defVal
}
@@ -50,8 +51,10 @@ func (p Properties) GetBool(key string, defVal bool) bool {
if err != nil {
return defVal
}
+
return b
}
+
return defVal
}
@@ -61,8 +64,10 @@ func (p Properties) GetInt(key string, defVal int) int {
if err != nil {
return defVal
}
+
return int(i)
}
+
return defVal
}
@@ -89,6 +94,7 @@ func (t *typeIFace) MarshalJSON() ([]byte, error) {
if nested, ok := t.Type.(NestedType); ok {
return json.Marshal(nested)
}
+
return []byte(`"` + t.Type.Type() + `"`), nil
}
@@ -144,6 +150,7 @@ func (t *typeIFace) UnmarshalJSON(b []byte) error {
return fmt.Errorf("%w: unrecognized field type", ErrInvalidSchema)
}
}
+
return nil
}
@@ -183,6 +190,7 @@ func optOrReq(required bool) string {
if required {
return "required"
}
+
return "optional"
}
@@ -208,6 +216,7 @@ func (n *NestedField) Equals(other NestedField) bool {
func (n NestedField) MarshalJSON() ([]byte, error) {
type Alias NestedField
+
return json.Marshal(struct {
Type *typeIFace `json:"type"`
*Alias
@@ -251,6 +260,7 @@ func (s *StructType) Fields() []NestedField { return s.FieldList }
func (s *StructType) MarshalJSON() ([]byte, error) {
type Alias StructType
+
return json.Marshal(struct {
Type string `json:"type"`
*Alias
@@ -292,6 +302,7 @@ type ListType struct {
func (l *ListType) MarshalJSON() ([]byte, error) {
type Alias ListType
+
return json.Marshal(struct {
Type string `json:"type"`
*Alias
@@ -339,6 +350,7 @@ func (l *ListType) UnmarshalJSON(b []byte) error {
l.ElementID = aux.ID
l.Element = aux.Elem.Type
l.ElementRequired = aux.Req
+
return nil
}
@@ -352,14 +364,17 @@ type MapType struct {
func (m *MapType) MarshalJSON() ([]byte, error) {
type Alias MapType
+
return json.Marshal(struct {
Type string `json:"type"`
*Alias
KeyType *typeIFace `json:"key"`
ValueType *typeIFace `json:"value"`
- }{Type: m.Type(), Alias: (*Alias)(m),
+ }{
+ Type: m.Type(), Alias: (*Alias)(m),
KeyType: &typeIFace{m.KeyType},
- ValueType: &typeIFace{m.ValueType}})
+ ValueType: &typeIFace{m.ValueType},
+ })
}
func (m *MapType) Equals(other Type) bool {
@@ -421,6 +436,7 @@ func (m *MapType) UnmarshalJSON(b []byte) error {
} else {
m.ValueRequired = *aux.ValueReq
}
+
return nil
}
@@ -485,6 +501,7 @@ type BooleanType struct{}
func (BooleanType) Equals(other Type) bool {
_, ok := other.(BooleanType)
+
return ok
}
@@ -497,6 +514,7 @@ type Int32Type struct{}
func (Int32Type) Equals(other Type) bool {
_, ok := other.(Int32Type)
+
return ok
}
@@ -509,6 +527,7 @@ type Int64Type struct{}
func (Int64Type) Equals(other Type) bool {
_, ok := other.(Int64Type)
+
return ok
}
@@ -521,6 +540,7 @@ type Float32Type struct{}
func (Float32Type) Equals(other Type) bool {
_, ok := other.(Float32Type)
+
return ok
}
@@ -533,6 +553,7 @@ type Float64Type struct{}
func (Float64Type) Equals(other Type) bool {
_, ok := other.(Float64Type)
+
return ok
}
@@ -553,6 +574,7 @@ type DateType struct{}
func (DateType) Equals(other Type) bool {
_, ok := other.(DateType)
+
return ok
}
@@ -571,6 +593,7 @@ type TimeType struct{}
func (TimeType) Equals(other Type) bool {
_, ok := other.(TimeType)
+
return ok
}
@@ -586,6 +609,7 @@ func (t Timestamp) ToTime() time.Time {
func (t Timestamp) ToDate() Date {
tm := time.UnixMicro(int64(t)).UTC()
+
return Date(tm.Truncate(24*time.Hour).Unix() / int64((time.Hour * 24).Seconds()))
}
@@ -595,6 +619,7 @@ type TimestampType struct{}
func (TimestampType) Equals(other Type) bool {
_, ok := other.(TimestampType)
+
return ok
}
@@ -608,6 +633,7 @@ type TimestampTzType struct{}
func (TimestampTzType) Equals(other Type) bool {
_, ok := other.(TimestampTzType)
+
return ok
}
@@ -619,6 +645,7 @@ type StringType struct{}
func (StringType) Equals(other Type) bool {
_, ok := other.(StringType)
+
return ok
}
@@ -630,6 +657,7 @@ type UUIDType struct{}
func (UUIDType) Equals(other Type) bool {
_, ok := other.(UUIDType)
+
return ok
}
@@ -641,6 +669,7 @@ type BinaryType struct{}
func (BinaryType) Equals(other Type) bool {
_, ok := other.(BinaryType)
+
return ok
}
@@ -702,6 +731,7 @@ func PromoteType(fileType, readType Type) (Type, error) {
if t.precision <= rt.precision && t.scale <= rt.scale {
return readType, nil
}
+
return nil, fmt.Errorf("%w: cannot reduce precision from %s to %s",
ErrResolve, fileType, readType)
}
diff --git a/types_test.go b/types_test.go
index abe233f..2caf657 100644
--- a/types_test.go
+++ b/types_test.go
@@ -48,7 +48,7 @@ func TestTypesBasic(t *testing.T) {
for _, tt := range tests {
t.Run(tt.expected, func(t *testing.T) {
- var data = `{
+ data := `{
"id": 1,
"name": "test",
"type": "` + tt.expected + `",
@@ -170,22 +170,20 @@ func TestMapType(t *testing.T) {
assert.True(t, typ.Equals(&actual))
}
-var (
- NonParameterizedTypes = []iceberg.Type{
- iceberg.PrimitiveTypes.Bool,
- iceberg.PrimitiveTypes.Int32,
- iceberg.PrimitiveTypes.Int64,
- iceberg.PrimitiveTypes.Float32,
- iceberg.PrimitiveTypes.Float64,
- iceberg.PrimitiveTypes.Date,
- iceberg.PrimitiveTypes.Time,
- iceberg.PrimitiveTypes.Timestamp,
- iceberg.PrimitiveTypes.TimestampTz,
- iceberg.PrimitiveTypes.String,
- iceberg.PrimitiveTypes.Binary,
- iceberg.PrimitiveTypes.UUID,
- }
-)
+var NonParameterizedTypes = []iceberg.Type{
+ iceberg.PrimitiveTypes.Bool,
+ iceberg.PrimitiveTypes.Int32,
+ iceberg.PrimitiveTypes.Int64,
+ iceberg.PrimitiveTypes.Float32,
+ iceberg.PrimitiveTypes.Float64,
+ iceberg.PrimitiveTypes.Date,
+ iceberg.PrimitiveTypes.Time,
+ iceberg.PrimitiveTypes.Timestamp,
+ iceberg.PrimitiveTypes.TimestampTz,
+ iceberg.PrimitiveTypes.String,
+ iceberg.PrimitiveTypes.Binary,
+ iceberg.PrimitiveTypes.UUID,
+}
func TestNonParameterizedTypeEquality(t *testing.T) {
for i, in := range NonParameterizedTypes {
@@ -225,9 +223,12 @@ func TestTypeStrings(t *testing.T) {
},
}, "struct<1: required_field: required string (this is a doc), 2: optional_field: required int>"},
{&iceberg.ListType{
- ElementID: 22, Element: iceberg.PrimitiveTypes.String}, "list<string>"},
- {&iceberg.MapType{KeyID: 19, KeyType: iceberg.PrimitiveTypes.String, ValueID: 25, ValueType: iceberg.PrimitiveTypes.Float64},
- "map<string, double>"},
+ ElementID: 22, Element: iceberg.PrimitiveTypes.String,
+ }, "list<string>"},
+ {
+ &iceberg.MapType{KeyID: 19, KeyType: iceberg.PrimitiveTypes.String, ValueID: 25, ValueType: iceberg.PrimitiveTypes.Float64},
+ "map<string, double>",
+ },
}
for _, tt := range tests {
diff --git a/utils.go b/utils.go
index 7807acb..b35b768 100644
--- a/utils.go
+++ b/utils.go
@@ -34,6 +34,7 @@ func init() {
for _, dep := range info.Deps {
if strings.HasPrefix(dep.Path, "github.com/apache/iceberg-go") {
version = dep.Version
+
break
}
}
@@ -53,6 +54,7 @@ func max[T cmp.Ordered](vals ...T) T {
out = v
}
}
+
return out
}
@@ -89,6 +91,7 @@ func (a *accessor) Get(s structLike) any {
inner = inner.inner
val = val.(structLike).Get(inner.pos)
}
+
return val
}
@@ -110,6 +113,7 @@ func newLiteralSet(vals ...Literal) Set[Literal] {
for _, v := range vals {
s.addliteral(v)
}
+
return s
}
@@ -137,15 +141,18 @@ func (l literalSet) Contains(lit Literal) bool {
if !ok {
return false
}
+
return lit.Equals(v.orig)
case FixedLiteral:
v, ok := l[maphash.Bytes(lzseed, []byte(lit))]
if !ok {
return false
}
+
return lit.Equals(v.orig)
default:
_, ok := l[lit]
+
return ok
}
}
@@ -159,6 +166,7 @@ func (l literalSet) Members() []Literal {
result = append(result, v.orig)
}
}
+
return result
}
@@ -167,6 +175,7 @@ func (l literalSet) Equals(other Set[Literal]) bool {
if !ok {
return false
}
+
return maps.EqualFunc(l, rhs, func(v1, v2 struct{ orig Literal }) bool {
switch {
case v1.orig == nil:
@@ -194,6 +203,7 @@ func (l literalSet) All(fn func(Literal) bool) bool {
return false
}
}
+
return true
}
@@ -210,5 +220,6 @@ func Difference(a, b []string) []string {
diff = append(diff, item)
}
}
+
return diff
}
diff --git a/utils/context.go b/utils/context.go
index eacf80b..bcab851 100644
--- a/utils/context.go
+++ b/utils/context.go
@@ -36,5 +36,6 @@ func GetAwsConfig(ctx context.Context) *aws.Config {
if v := ctx.Value(awsctxkey{}); v != nil {
return v.(*aws.Config)
}
+
return nil
}
diff --git a/visitors.go b/visitors.go
index f93c75a..3debc2e 100644
--- a/visitors.go
+++ b/visitors.go
@@ -88,12 +88,15 @@ func visitBoolExpr[T any](e BooleanExpression, visitor BooleanExprVisitor[T]) T
return visitor.VisitTrue()
case AndExpr:
left, right := visitBoolExpr(e.left, visitor), visitBoolExpr(e.right, visitor)
+
return visitor.VisitAnd(left, right)
case OrExpr:
left, right := visitBoolExpr(e.left, visitor), visitBoolExpr(e.right, visitor)
+
return visitor.VisitOr(left, right)
case NotExpr:
child := visitBoolExpr(e.child, visitor)
+
return visitor.VisitNot(child)
case UnboundPredicate:
return visitor.VisitUnbound(e)
@@ -158,19 +161,24 @@ func (*bindVisitor) VisitFalse() BooleanExpression { return AlwaysFalse{} }
func (*bindVisitor) VisitNot(child BooleanExpression) BooleanExpression {
return NewNot(child)
}
+
func (*bindVisitor) VisitAnd(left, right BooleanExpression) BooleanExpression {
return NewAnd(left, right)
}
+
func (*bindVisitor) VisitOr(left, right BooleanExpression) BooleanExpression {
return NewOr(left, right)
}
+
func (b *bindVisitor) VisitUnbound(pred UnboundPredicate) BooleanExpression {
expr, err := pred.Bind(b.schema, b.caseSensitive)
if err != nil {
panic(err)
}
+
return expr
}
+
func (*bindVisitor) VisitBound(pred BoundPredicate) BooleanExpression {
panic(fmt.Errorf("%w: found already bound predicate: %s", ErrInvalidArgument, pred))
}
@@ -194,6 +202,7 @@ type exprEvaluator struct {
func (e *exprEvaluator) Eval(st structLike) (bool, error) {
e.st = st
+
return VisitExpr(e.bound, e)
}
@@ -231,12 +240,14 @@ func (e *exprEvaluator) VisitIsNan(term BoundTerm) bool {
if !v.Valid {
break
}
+
return math.IsNaN(float64(v.Val))
case Float64Type:
v := term.(bound[float64]).eval(e.st)
if !v.Valid {
break
}
+
return math.IsNaN(v.Val)
}
@@ -408,6 +419,7 @@ func ExtractFieldIDs(expr BooleanExpression) ([]int, error) {
}
out := make([]int, 0, len(res))
+
return slices.AppendSeq(out, maps.Keys(res)), nil
}
@@ -427,11 +439,13 @@ func (expressionFieldIDs) VisitNot(child map[int]struct{}) map[int]struct{} {
func (expressionFieldIDs) VisitAnd(left, right map[int]struct{}) map[int]struct{} {
maps.Insert(left, maps.All(right))
+
return left
}
func (expressionFieldIDs) VisitOr(left, right map[int]struct{}) map[int]struct{} {
maps.Insert(left, maps.All(right))
+
return left
}
@@ -482,6 +496,7 @@ func (c columnNameTranslator) VisitBound(pred BoundPredicate) BooleanExpression
if pred.Op() == OpIsNull {
return AlwaysTrue{}
}
+
return AlwaysFalse{}
}
diff --git a/visitors_test.go b/visitors_test.go
index cd93a60..ed18b48 100644
--- a/visitors_test.go
+++ b/visitors_test.go
@@ -35,36 +35,43 @@ type ExampleVisitor struct {
func (e *ExampleVisitor) VisitTrue() []string {
e.visitHistory = append(e.visitHistory, "TRUE")
+
return e.visitHistory
}
func (e *ExampleVisitor) VisitFalse() []string {
e.visitHistory = append(e.visitHistory, "FALSE")
+
return e.visitHistory
}
func (e *ExampleVisitor) VisitNot([]string) []string {
e.visitHistory = append(e.visitHistory, "NOT")
+
return e.visitHistory
}
func (e *ExampleVisitor) VisitAnd(_, _ []string) []string {
e.visitHistory = append(e.visitHistory, "AND")
+
return e.visitHistory
}
func (e *ExampleVisitor) VisitOr(_, _ []string) []string {
e.visitHistory = append(e.visitHistory, "OR")
+
return e.visitHistory
}
func (e *ExampleVisitor) VisitUnbound(pred iceberg.UnboundPredicate) []string {
e.visitHistory = append(e.visitHistory, strings.ToUpper(pred.Op().String()))
+
return e.visitHistory
}
func (e *ExampleVisitor) VisitBound(pred iceberg.BoundPredicate) []string {
e.visitHistory = append(e.visitHistory, strings.ToUpper(pred.Op().String()))
+
return e.visitHistory
}
@@ -82,71 +89,85 @@ func (e *FooBoundExprVisitor) VisitUnbound(pred iceberg.UnboundPredicate) []stri
func (e *FooBoundExprVisitor) VisitIn(iceberg.BoundTerm, iceberg.Set[iceberg.Literal]) []string {
e.visitHistory = append(e.visitHistory, "IN")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitNotIn(iceberg.BoundTerm, iceberg.Set[iceberg.Literal]) []string {
e.visitHistory = append(e.visitHistory, "NOT_IN")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitIsNan(iceberg.BoundTerm) []string {
e.visitHistory = append(e.visitHistory, "IS_NAN")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitNotNan(iceberg.BoundTerm) []string {
e.visitHistory = append(e.visitHistory, "NOT_NAN")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitIsNull(iceberg.BoundTerm) []string {
e.visitHistory = append(e.visitHistory, "IS_NULL")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitNotNull(iceberg.BoundTerm) []string {
e.visitHistory = append(e.visitHistory, "NOT_NULL")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitEqual(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "EQUAL")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitNotEqual(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "NOT_EQUAL")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitGreaterEqual(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "GREATER_THAN_OR_EQUAL")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitGreater(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "GREATER_THAN")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitLessEqual(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "LESS_THAN_OR_EQUAL")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitLess(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "LESS_THAN")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitStartsWith(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "STARTS_WITH")
+
return e.visitHistory
}
func (e *FooBoundExprVisitor) VisitNotStartsWith(iceberg.BoundTerm, iceberg.Literal) []string {
e.visitHistory = append(e.visitHistory, "NOT_STARTS_WITH")
+
return e.visitHistory
}
@@ -219,9 +240,11 @@ func TestBoundBoolExprVisitor(t *testing.T) {
}{
{iceberg.NewAnd(iceberg.IsIn(iceberg.Reference("foo"), "foo", "bar"),
iceberg.IsIn(iceberg.Reference("bar"), int32(1), int32(2))), []string{"IN", "IN", "AND"}},
- {iceberg.NewOr(iceberg.NewNot(iceberg.IsIn(iceberg.Reference("foo"), "foo", "bar")),
- iceberg.NewNot(iceberg.IsIn(iceberg.Reference("bar"), int32(1), int32(2)))),
- []string{"IN", "NOT", "IN", "NOT", "OR"}},
+ {
+ iceberg.NewOr(iceberg.NewNot(iceberg.IsIn(iceberg.Reference("foo"), "foo", "bar")),
+ iceberg.NewNot(iceberg.IsIn(iceberg.Reference("bar"), int32(1), int32(2)))),
+ []string{"IN", "NOT", "IN", "NOT", "OR"},
+ },
{iceberg.EqualTo(iceberg.Reference("bar"), int32(1)), []string{"EQUAL"}},
{iceberg.NotEqualTo(iceberg.Reference("foo"), "foo"), []string{"NOT_EQUAL"}},
{iceberg.AlwaysTrue{}, []string{"TRUE"}},
@@ -265,13 +288,20 @@ func rowOf(vals ...any) rowTester {
}
var testSchema = iceberg.NewSchema(1,
- iceberg.NestedField{ID: 13, Name: "x",
- Type: iceberg.PrimitiveTypes.Int32, Required: true},
- iceberg.NestedField{ID: 14, Name: "y",
- Type: iceberg.PrimitiveTypes.Float64, Required: true},
- iceberg.NestedField{ID: 15, Name: "z",
- Type: iceberg.PrimitiveTypes.Int32},
- iceberg.NestedField{ID: 16, Name: "s1",
+ iceberg.NestedField{
+ ID: 13, Name: "x",
+ Type: iceberg.PrimitiveTypes.Int32, Required: true,
+ },
+ iceberg.NestedField{
+ ID: 14, Name: "y",
+ Type: iceberg.PrimitiveTypes.Float64, Required: true,
+ },
+ iceberg.NestedField{
+ ID: 15, Name: "z",
+ Type: iceberg.PrimitiveTypes.Int32,
+ },
+ iceberg.NestedField{
+ ID: 16, Name: "s1",
Type: &iceberg.StructType{
FieldList: []iceberg.NestedField{{
ID: 17, Name: "s2", Required: true,
@@ -292,7 +322,8 @@ var testSchema = iceberg.NewSchema(1,
}},
},
}},
- }},
+ },
+ },
iceberg.NestedField{ID: 21, Name: "s5", Type: &iceberg.StructType{
FieldList: []iceberg.NestedField{{
ID: 22, Name: "s6", Required: true, Type: &iceberg.StructType{
@@ -580,19 +611,29 @@ func TestRewriteNot(t *testing.T) {
tests := []struct {
expr, expected iceberg.BooleanExpression
}{
- {iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("x"), 34.56)),
- iceberg.NotEqualTo(iceberg.Reference("x"), 34.56)},
- {iceberg.NewNot(iceberg.NotEqualTo(iceberg.Reference("x"), 34.56)),
- iceberg.EqualTo(iceberg.Reference("x"), 34.56)},
- {iceberg.NewNot(iceberg.IsIn(iceberg.Reference("x"), 34.56, 23.45)),
- iceberg.NotIn(iceberg.Reference("x"), 34.56, 23.45)},
- {iceberg.NewNot(iceberg.NewAnd(
- iceberg.EqualTo(iceberg.Reference("x"), 34.56), iceberg.EqualTo(iceberg.Reference("y"), 34.56))),
+ {
+ iceberg.NewNot(iceberg.EqualTo(iceberg.Reference("x"), 34.56)),
+ iceberg.NotEqualTo(iceberg.Reference("x"), 34.56),
+ },
+ {
+ iceberg.NewNot(iceberg.NotEqualTo(iceberg.Reference("x"), 34.56)),
+ iceberg.EqualTo(iceberg.Reference("x"), 34.56),
+ },
+ {
+ iceberg.NewNot(iceberg.IsIn(iceberg.Reference("x"), 34.56, 23.45)),
+ iceberg.NotIn(iceberg.Reference("x"), 34.56, 23.45),
+ },
+ {
+ iceberg.NewNot(iceberg.NewAnd(
+ iceberg.EqualTo(iceberg.Reference("x"), 34.56), iceberg.EqualTo(iceberg.Reference("y"), 34.56))),
iceberg.NewOr(
- iceberg.NotEqualTo(iceberg.Reference("x"), 34.56), iceberg.NotEqualTo(iceberg.Reference("y"), 34.56))},
- {iceberg.NewNot(iceberg.NewOr(
- iceberg.EqualTo(iceberg.Reference("x"), 34.56), iceberg.EqualTo(iceberg.Reference("y"), 34.56))),
- iceberg.NewAnd(iceberg.NotEqualTo(iceberg.Reference("x"), 34.56), iceberg.NotEqualTo(iceberg.Reference("y"), 34.56))},
+ iceberg.NotEqualTo(iceberg.Reference("x"), 34.56), iceberg.NotEqualTo(iceberg.Reference("y"), 34.56)),
+ },
+ {
+ iceberg.NewNot(iceberg.NewOr(
+ iceberg.EqualTo(iceberg.Reference("x"), 34.56), iceberg.EqualTo(iceberg.Reference("y"), 34.56))),
+ iceberg.NewAnd(iceberg.NotEqualTo(iceberg.Reference("x"), 34.56), iceberg.NotEqualTo(iceberg.Reference("y"), 34.56)),
+ },
{iceberg.NewNot(iceberg.AlwaysFalse{}), iceberg.AlwaysTrue{}},
{iceberg.NewNot(iceberg.AlwaysTrue{}), iceberg.AlwaysFalse{}},
}