This is an automated email from the ASF dual-hosted git repository.
laskoviymishka 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 b6050faa3 feat(catalog)!: support isolated FileIO registries (#2612)
b6050faa3 is described below
commit b6050faa333a8e016f8f1d8ba1e934c19ab9d0ca
Author: Vu <[email protected]>
AuthorDate: Thu Nov 19 14:22:47 2026 +0100
feat(catalog)!: support isolated FileIO registries (#2612)
---
catalog/dynamodb/tables.go | 4 +-
catalog/glue/glue.go | 23 +--
catalog/glue/io_registry_test.go | 254 ++++++++++++++++++++++++++++++++++
catalog/glue/options.go | 10 ++
catalog/hadoop/hadoop.go | 21 ++-
catalog/hadoop/io_registry_test.go | 119 ++++++++++++++++
catalog/{glue => hadoop}/options.go | 39 ++----
catalog/hadoop/tables.go | 5 +-
catalog/hive/hive.go | 17 ++-
catalog/hive/io_registry_test.go | 221 +++++++++++++++++++++++++++++
catalog/hive/options.go | 10 ++
catalog/hive/update_view.go | 7 +-
catalog/internal/io_registry.go | 45 ++++++
catalog/internal/io_registry_test.go | 98 +++++++++++++
catalog/internal/update_stage_test.go | 5 +-
catalog/internal/utils.go | 22 ++-
catalog/sql/io_registry_test.go | 250 +++++++++++++++++++++++++++++++++
catalog/{glue => sql}/options.go | 39 ++----
catalog/sql/sql.go | 27 ++--
catalog/sql/update_view.go | 2 +-
view/io_registry_test.go | 202 +++++++++++++++++++++++++++
view/view.go | 16 ++-
view/write_metadata.go | 28 +++-
website/src/api.md | 8 ++
website/src/configuration.md | 30 +++-
website/src/releases.md | 1 +
26 files changed, 1388 insertions(+), 115 deletions(-)
diff --git a/catalog/dynamodb/tables.go b/catalog/dynamodb/tables.go
index 09b2e608e..7b4f93871 100644
--- a/catalog/dynamodb/tables.go
+++ b/catalog/dynamodb/tables.go
@@ -105,7 +105,7 @@ func (c *Catalog) CreateTable(ctx context.Context, ident
table.Identifier, schem
if _, err := c.loadNamespace(ctx, catalog.NamespaceFromIdent(ident));
err != nil {
return nil, err
}
- staged, err := internal.CreateStagedTable(ctx, c.props,
c.namespaceLocationProperties, ident, schema, opts...)
+ staged, err := internal.CreateStagedTable(ctx, c.props,
c.namespaceLocationProperties, ident, schema, nil, opts...)
if err != nil {
return nil, err
}
@@ -230,7 +230,7 @@ func (c *Catalog) CommitTable(ctx context.Context, ident
table.Identifier, requi
return nil, "", err
}
}
- staged, err := internal.UpdateAndStageTable(ctx, c.props, current,
ident, requirements, updates, c)
+ staged, err := internal.UpdateAndStageTable(ctx, c.props, current,
ident, requirements, updates, c, nil)
if err != nil {
return nil, "", err
}
diff --git a/catalog/glue/glue.go b/catalog/glue/glue.go
index 4e65ac4bf..3b8b55fd6 100644
--- a/catalog/glue/glue.go
+++ b/catalog/glue/glue.go
@@ -168,6 +168,8 @@ type Catalog struct {
// reporter builds and caches the catalog's metrics reporter once, so
it is
// constructed per-catalog rather than per table load. Released by
Close.
reporter metrics.CachedReporter
+
+ ioRegistry *io.Registry
}
// NewCatalog creates a new instance of glue.Catalog with the given options.
@@ -201,11 +203,12 @@ func NewCatalog(opts ...Option) (*Catalog, error) {
}
cat := &Catalog{
- name: glueOps.name,
- glueSvc: glue.NewFromConfig(glueOps.awsConfig),
- catalogId: catalogId,
- awsCfg: &glueOps.awsConfig,
- props: iceberg.Properties(glueOps.awsProperties),
+ name: glueOps.name,
+ glueSvc: glue.NewFromConfig(glueOps.awsConfig),
+ catalogId: catalogId,
+ awsCfg: &glueOps.awsConfig,
+ props: iceberg.Properties(glueOps.awsProperties),
+ ioRegistry: glueOps.ioRegistry,
}
// Resolve the metrics reporter once, up front. CachedReporter caches
the
@@ -323,7 +326,7 @@ func (c *Catalog) CreateTable(ctx context.Context,
identifier table.Identifier,
// metrics-reporter-impl already failed there — no per-op guard is
needed
// before mutating the catalog, and the trailing LoadTable reuses the
cached
// reporter.
- staged, err := internal.CreateStagedTable(ctx, c.props,
c.namespacePropsFn(db), identifier, schema, opts...)
+ staged, err := internal.CreateStagedTable(ctx, c.props,
c.namespacePropsFn(db), identifier, schema, c.ioRegistry, opts...)
if err != nil {
return nil, err
}
@@ -473,7 +476,7 @@ func (c *Catalog) commitS3TablesTable(ctx context.Context,
database, tableName s
copy(stagedOpts, opts)
stagedOpts = append(stagedOpts, catalog.WithLocation(managedLocation))
- staged, err := internal.CreateStagedTable(ctx, c.props,
c.LoadNamespaceProperties, identifier, schema, stagedOpts...)
+ staged, err := internal.CreateStagedTable(ctx, c.props,
c.LoadNamespaceProperties, identifier, schema, c.ioRegistry, stagedOpts...)
if err != nil {
return err
}
@@ -522,7 +525,7 @@ func (c *Catalog) RegisterTable(ctx context.Context,
identifier table.Identifier
ctx,
[]string{tableName},
metadataLocation,
- io.LoadFSFunc(c.props, metadataLocation),
+ internal.LoadFSFuncWithRegistry(c.ioRegistry, c.props,
metadataLocation),
c,
table.WithScanPlanningIOProperties(c.props),
)
@@ -567,7 +570,7 @@ func (c *Catalog) CommitTable(ctx context.Context,
identifier table.Identifier,
}
// Create a staging table with the updates applied
- staged, err := internal.UpdateAndStageTable(ctx, c.props, current,
identifier, requirements, updates, c)
+ staged, err := internal.UpdateAndStageTable(ctx, c.props, current,
identifier, requirements, updates, c, c.ioRegistry)
if err != nil {
return nil, "", err
}
@@ -1124,7 +1127,7 @@ func (c *Catalog) convertGlueToIceberg(ctx
context.Context, glueTable *types.Tab
utils.WithAWSConfig(ctx, c.awsCfg),
TableIdentifier(database, tableName),
metadataLocation,
- io.LoadFSFunc(c.props, metadataLocation),
+ internal.LoadFSFuncWithRegistry(c.ioRegistry, c.props,
metadataLocation),
c,
table.WithMetricsReporter(reporter),
table.WithScanPlanningIOProperties(c.props),
diff --git a/catalog/glue/io_registry_test.go b/catalog/glue/io_registry_test.go
new file mode 100644
index 000000000..060c47c80
--- /dev/null
+++ b/catalog/glue/io_registry_test.go
@@ -0,0 +1,254 @@
+// 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.
+
+package glue
+
+import (
+ "context"
+ "errors"
+ "net/url"
+ "os"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/table"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsglue "github.com/aws/aws-sdk-go-v2/service/glue"
+ "github.com/aws/aws-sdk-go-v2/service/glue/types"
+ "github.com/stretchr/testify/mock"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGlueLoadTableWithIsolatedIORegistry(t *testing.T) {
+ const scheme = "glue-private-registry"
+ const metadataLocation = scheme + "://bucket/table/metadata.json"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) { return fs, nil }))
+ contents, err :=
os.ReadFile("../../table/testdata/TableMetadataV2Valid.json")
+ require.NoError(t, err)
+ require.NoError(t, fs.WriteFile(t.Context(), metadataLocation,
contents))
+ client := &mockGlueClient{}
+ client.On("GetTable", mock.Anything, mock.Anything,
mock.Anything).Return(&awsglue.GetTableOutput{Table: &types.Table{
+ Name: aws.String("tbl"), DatabaseName: aws.String("db"),
TableType: aws.String(glueTableType),
+ Parameters: map[string]string{tableParamTableType:
glueTypeIceberg, tableParamMetadataLocation: metadataLocation},
+ }}, nil).Once()
+ cat, err := NewCatalog(WithAWSConfig(aws.Config{Region: "us-east-1"}),
WithIORegistry(registry))
+ require.NoError(t, err)
+ cat.glueSvc = client
+ tbl, err := cat.LoadTable(t.Context(), TableIdentifier("db", "tbl"))
+ require.NoError(t, err)
+ loaded, err := tbl.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loaded)
+ _, err = iceio.LoadFS(t.Context(), nil, metadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
+
+func TestGlueRegisterTableUsesScopedIORegistry(t *testing.T) {
+ const scheme = "glue-register-private"
+ const metadataLocation = scheme +
"://bucket/table/metadata/v1.metadata.json"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ contents, err :=
os.ReadFile("../../table/testdata/TableMetadataV2Valid.json")
+ require.NoError(t, err)
+ require.NoError(t, fs.WriteFile(t.Context(), metadataLocation,
contents))
+
+ client := &mockGlueClient{}
+ client.On("CreateTable", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.CreateTableOutput{}, nil).Once()
+ client.On("GetTable", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.GetTableOutput{Table: &types.Table{
+ Name: aws.String("tbl"), DatabaseName:
aws.String("db"), TableType: aws.String(glueTableType),
+ Parameters: map[string]string{tableParamTableType:
glueTypeIceberg, tableParamMetadataLocation: metadataLocation},
+ }}, nil).Once()
+
+ cat, err := NewCatalog(WithAWSConfig(aws.Config{Region: "us-east-1"}),
WithIORegistry(registry))
+ require.NoError(t, err)
+ cat.glueSvc = client
+ registered, err := cat.RegisterTable(t.Context(), TableIdentifier("db",
"tbl"), metadataLocation)
+ require.NoError(t, err)
+ loadedFS, err := registered.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loadedFS)
+ _, err = iceio.LoadFS(t.Context(), nil, metadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
+
+func TestGlueCatalogsWithSameSchemeStayIsolated(t *testing.T) {
+ const scheme = "glue-shared-scheme"
+ const metadataLocation = scheme + "://bucket/table/metadata.json"
+ contents, err :=
os.ReadFile("../../table/testdata/TableMetadataV2Valid.json")
+ require.NoError(t, err)
+
+ filesystems := []*iceio.MemFS{iceio.NewMemFS(), iceio.NewMemFS()}
+ catalogs := make([]*Catalog, len(filesystems))
+ clients := make([]*mockGlueClient, len(filesystems))
+ for i, fs := range filesystems {
+ registry := &iceio.Registry{}
+ require.NoError(t, registry.Register(scheme,
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ require.NoError(t, fs.WriteFile(t.Context(), metadataLocation,
contents))
+
+ client := &mockGlueClient{}
+ client.On("GetTable", mock.Anything, mock.Anything,
mock.Anything).Return(&awsglue.GetTableOutput{Table: &types.Table{
+ Name: aws.String("tbl"), DatabaseName:
aws.String("db"), TableType: aws.String(glueTableType),
+ Parameters: map[string]string{tableParamTableType:
glueTypeIceberg, tableParamMetadataLocation: metadataLocation},
+ }}, nil).Once()
+ cat, err := NewCatalog(WithAWSConfig(aws.Config{Region:
"us-east-1"}), WithIORegistry(registry))
+ require.NoError(t, err)
+ cat.glueSvc = client
+ catalogs[i] = cat
+ clients[i] = client
+ }
+
+ // Load after both catalogs exist. A shared/global factory would route
+ // both loads to one filesystem even though the URI scheme is identical.
+ for i, cat := range catalogs {
+ tbl, err := cat.LoadTable(t.Context(), TableIdentifier("db",
"tbl"))
+ require.NoError(t, err)
+ loaded, err := tbl.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, filesystems[i], loaded)
+ require.NotSame(t, filesystems[1-i], loaded)
+ clients[i].AssertExpectations(t)
+ }
+}
+
+func TestGlueCreateAndCommitTableUseCatalogIORegistry(t *testing.T) {
+ const scheme = "glue-create-commit-registry"
+ const warehouse = scheme + "://bucket/warehouse"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+
+ cat, err := NewCatalog(
+ WithAWSConfig(aws.Config{Region: "us-east-1"}),
+ WithAWSProperties(AWSProperties{"warehouse": warehouse}),
+ WithIORegistry(registry),
+ )
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, cat.Close()) })
+ client := &mockGlueClient{}
+ cat.glueSvc = client
+
+ identifier := TableIdentifier("db", "tbl")
+ var glueTable types.Table
+ client.On("GetDatabase", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.GetDatabaseOutput{Database:
&types.Database{Name: aws.String("db")}}, nil).Once()
+ client.On("CreateTable", mock.Anything, mock.Anything, mock.Anything).
+ Run(func(args mock.Arguments) {
+ input := args.Get(1).(*awsglue.CreateTableInput)
+ glueTable = types.Table{
+ Name: aws.String("tbl"), DatabaseName:
aws.String("db"),
+ TableType: aws.String(glueTableType),
VersionId: aws.String("1"),
+ Parameters: input.TableInput.Parameters,
+ StorageDescriptor:
input.TableInput.StorageDescriptor,
+ }
+ }).Return(&awsglue.CreateTableOutput{}, nil).Once()
+ client.On("GetTable", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.GetTableOutput{Table: &glueTable}, nil).Twice()
+ client.On("UpdateTable", mock.Anything, mock.Anything, mock.Anything).
+ Run(func(args mock.Arguments) {
+ input := args.Get(1).(*awsglue.UpdateTableInput)
+ glueTable.Parameters = input.TableInput.Parameters
+ glueTable.StorageDescriptor =
input.TableInput.StorageDescriptor
+ }).Return(&awsglue.UpdateTableOutput{}, nil).Once()
+
+ schema := iceberg.NewSchema(1, iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int32})
+ created, err := cat.CreateTable(t.Context(), identifier, schema)
+ require.NoError(t, err)
+ loadedFS, err := created.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loadedFS)
+
+ _, updatedLocation, err := cat.CommitTable(t.Context(), identifier,
nil, []table.Update{
+ table.NewSetPropertiesUpdate(iceberg.Properties{"committed":
"true"}),
+ })
+ require.NoError(t, err)
+ require.NotEqual(t, created.MetadataLocation(), updatedLocation)
+ metadataFile, err := fs.Open(t.Context(), updatedLocation)
+ require.NoError(t, err)
+ require.NoError(t, metadataFile.Close())
+ _, err = iceio.LoadFS(t.Context(), nil, updatedLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
+
+type trackingGlueRegistryFS struct {
+ *iceio.MemFS
+ removed []string
+}
+
+func (fs *trackingGlueRegistryFS) Remove(ctx context.Context, path string)
error {
+ fs.removed = append(fs.removed, path)
+
+ return fs.MemFS.Remove(ctx, path)
+}
+
+func TestGlueS3TablesCleanupUsesCatalogIORegistry(t *testing.T) {
+ const scheme = "glue-s3tables-cleanup-registry"
+ const managedLocation = scheme + "://bucket/table"
+ registry := &iceio.Registry{}
+ fs := &trackingGlueRegistryFS{MemFS: iceio.NewMemFS()}
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+
+ cat, err := NewCatalog(WithAWSConfig(aws.Config{Region: "us-east-1"}),
WithIORegistry(registry))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, cat.Close()) })
+ client := &mockGlueClient{}
+ cat.glueSvc = client
+ client.On("GetDatabase", mock.Anything, mock.Anything, mock.Anything).
+ Return(federatedDatabaseOutput("aws:s3tables"), nil).Once()
+ client.On("CreateTable", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.CreateTableOutput{}, nil).Once()
+ client.On("GetTable", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.GetTableOutput{Table: &types.Table{
+ Name: aws.String("tbl"), DatabaseName:
aws.String("db"), VersionId: aws.String("1"),
+ StorageDescriptor: &types.StorageDescriptor{Location:
aws.String(managedLocation)},
+ }}, nil).Once()
+ var metadataLocation string
+ client.On("UpdateTable", mock.Anything, mock.Anything, mock.Anything).
+ Run(func(args mock.Arguments) {
+ input := args.Get(1).(*awsglue.UpdateTableInput)
+ metadataLocation =
input.TableInput.Parameters[tableParamMetadataLocation]
+ }).Return((*awsglue.UpdateTableOutput)(nil), errors.New("update
failed")).Once()
+ client.On("DeleteTable", mock.Anything, mock.Anything, mock.Anything).
+ Return(&awsglue.DeleteTableOutput{}, nil).Once()
+
+ schema := iceberg.NewSchema(1, iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int32})
+ _, err = cat.CreateTable(t.Context(), TableIdentifier("db", "tbl"),
schema)
+ require.ErrorContains(t, err, "update failed")
+ require.NotEmpty(t, metadataLocation)
+ require.Equal(t, []string{metadataLocation}, fs.removed)
+ _, err = fs.Open(t.Context(), metadataLocation)
+ require.Error(t, err)
+ _, err = iceio.LoadFS(t.Context(), nil, metadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
diff --git a/catalog/glue/options.go b/catalog/glue/options.go
index 180f9cf85..2d9f0ca40 100644
--- a/catalog/glue/options.go
+++ b/catalog/glue/options.go
@@ -18,6 +18,7 @@
package glue
import (
+ "github.com/apache/iceberg-go/io"
"github.com/aws/aws-sdk-go-v2/aws"
)
@@ -45,8 +46,17 @@ func WithAWSProperties(props AWSProperties) Option {
}
}
+// WithIORegistry selects the FileIO factories used by this Glue catalog.
+// A nil registry uses the global default. The registry is shared, not copied,
+// so subsequent Register and Unregister calls affect this catalog.
+func WithIORegistry(registry *io.Registry) Option {
+ return func(o *options) { o.ioRegistry = registry }
+}
+
type options struct {
name string
awsConfig aws.Config
awsProperties AWSProperties
+
+ ioRegistry *io.Registry
}
diff --git a/catalog/hadoop/hadoop.go b/catalog/hadoop/hadoop.go
index 24c8774f3..82afda140 100644
--- a/catalog/hadoop/hadoop.go
+++ b/catalog/hadoop/hadoop.go
@@ -39,6 +39,7 @@ import (
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/catalog"
+ "github.com/apache/iceberg-go/catalog/internal"
"github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/metrics"
"github.com/apache/iceberg-go/table"
@@ -191,6 +192,8 @@ type Catalog struct {
// reporter builds and caches the catalog's metrics reporter once, so
it is
// constructed per-catalog rather than per table load. Released by
Close.
reporter metrics.CachedReporter
+
+ ioRegistry *io.Registry
}
// NewCatalog creates a new Hadoop catalog rooted at the given warehouse path.
@@ -200,7 +203,18 @@ type Catalog struct {
// is not created on construction; it is created implicitly by the first
CreateNamespace
// call. When using other schemes, the property `allow-unsafe-commits` must be
set to
// true since custom schemes and blob filesystems do not have the same
atomicity guarantees.
-func NewCatalog(ctx context.Context, name, warehouse string, props
iceberg.Properties) (*Catalog, error) {
+//
+// Pass WithIORegistry(registry) to use a catalog-specific filesystem registry.
+// A nil or omitted registry uses global FileIO; a non-nil empty registry does
+// not fall back to built-in schemes. The registry is shared, not copied, and
+// subsequent registry changes affect future table FileIO resolutions. The
+// warehouse filesystem is resolved once during construction.
+func NewCatalog(ctx context.Context, name, warehouse string, props
iceberg.Properties, opts ...Option) (*Catalog, error) {
+ var config catalogOptions
+ for _, opt := range opts {
+ opt(&config)
+ }
+
if warehouse == "" {
return nil, errors.New("hadoop catalog requires a warehouse
path")
}
@@ -247,7 +261,7 @@ func NewCatalog(ctx context.Context, name, warehouse
string, props iceberg.Prope
// every later operation. Keep the caller's values, but not its
cancellation
// or deadline, for the lifetime of the catalog. The original context is
// checked before and after initialization so canceled setup still
fails.
- filesystem, err := io.LoadFS(context.WithoutCancel(ctx), props,
warehouse)
+ filesystem, err :=
internal.LoadFSWithRegistry(context.WithoutCancel(ctx), config.ioRegistry,
props, warehouse)
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, fmt.Errorf("hadoop catalog: failed to load
filesystem: %w", ctxErr)
}
@@ -264,9 +278,10 @@ func NewCatalog(ctx context.Context, name, warehouse
string, props iceberg.Prope
name: name,
warehouse: warehouse,
isLocal: isLocal,
- // filesystem is resolved dynamically from the IO registry
based on the warehouse scheme
+ // Retain the warehouse filesystem selected during construction.
filesystem: hadoopFs,
props: props,
+ ioRegistry: config.ioRegistry,
}
// Resolve the metrics reporter once, up front. CachedReporter caches
the
diff --git a/catalog/hadoop/io_registry_test.go
b/catalog/hadoop/io_registry_test.go
new file mode 100644
index 000000000..44bcdf9ec
--- /dev/null
+++ b/catalog/hadoop/io_registry_test.go
@@ -0,0 +1,119 @@
+// 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.
+
+package hadoop
+
+import (
+ "context"
+ "net/url"
+ "sync/atomic"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/stretchr/testify/require"
+)
+
+func TestHadoopConstructorUsesIsolatedIORegistry(t *testing.T) {
+ registry := &iceio.Registry{}
+ fs := &stubHadoopCatalogFS{}
+ require.NoError(t, registry.Register("hadoop-isolated",
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+
+ cat, err := NewCatalog(t.Context(), "test",
"hadoop-isolated://bucket/warehouse",
+ iceberg.Properties{"allow-unsafe-commits": "true"},
WithIORegistry(registry))
+ require.NoError(t, err)
+ require.Same(t, fs, cat.filesystem)
+ require.Same(t, registry, cat.ioRegistry)
+
+ _, err = iceio.LoadFS(t.Context(), nil,
"hadoop-isolated://bucket/warehouse")
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+func TestHadoopEmptyRegistryCannotUseGlobalLocalBackend(t *testing.T) {
+ _, err := NewCatalog(t.Context(), "test", t.TempDir(), nil,
WithIORegistry(&iceio.Registry{}))
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+func TestHadoopRegistryUsedForTableCreateAndLoad(t *testing.T) {
+ registry := &iceio.Registry{}
+ var calls atomic.Int32
+ require.NoError(t, registry.Register("", func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ calls.Add(1)
+
+ return iceio.LocalFS{}, nil
+ }))
+ cat, err := NewCatalog(t.Context(), "test", t.TempDir(), nil,
WithIORegistry(registry))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, cat.Close()) })
+ require.NoError(t, cat.CreateNamespace(t.Context(), []string{"db"},
nil))
+ schema := iceberg.NewSchema(1, iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int32, Required: true})
+ created, err := cat.CreateTable(t.Context(), []string{"db", "tbl"},
schema)
+ require.NoError(t, err)
+ initial := calls.Load()
+ fs, err := created.FS(t.Context())
+ require.NoError(t, err)
+ require.IsType(t, iceio.LocalFS{}, fs)
+ require.Greater(t, calls.Load(), initial)
+ initial = calls.Load()
+ loaded, err := cat.LoadTable(t.Context(), []string{"db", "tbl"})
+ require.NoError(t, err)
+ require.Greater(t, calls.Load(), initial)
+ require.Equal(t, created.MetadataLocation(), loaded.MetadataLocation())
+
+ registry.Unregister("")
+ require.NoError(t, cat.CreateNamespace(t.Context(), []string{"other"},
nil),
+ "warehouse operations keep the filesystem opened by the
constructor")
+ _, err = loaded.FS(t.Context())
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound,
+ "table filesystem lookups use the current scoped registry")
+ _, err = cat.LoadTable(t.Context(), []string{"db", "tbl"})
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+// identifiedHadoopCatalogFS has a non-zero-sized value: distinct zero-sized
+// structs may legally have identical pointer addresses in Go.
+type identifiedHadoopCatalogFS struct {
+ *stubHadoopCatalogFS
+ id int
+}
+
+func TestHadoopCatalogsWithSameSchemeStayIsolated(t *testing.T) {
+ const warehouse = "hadoop-shared-scheme://bucket/warehouse"
+ filesystems := []*identifiedHadoopCatalogFS{
+ {stubHadoopCatalogFS: &stubHadoopCatalogFS{}, id: 1},
+ {stubHadoopCatalogFS: &stubHadoopCatalogFS{}, id: 2},
+ }
+ catalogs := make([]*Catalog, len(filesystems))
+
+ for i, fs := range filesystems {
+ registry := &iceio.Registry{}
+ require.NoError(t, registry.Register("hadoop-shared-scheme",
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ cat, err := NewCatalog(t.Context(), "test", warehouse,
+ iceberg.Properties{"allow-unsafe-commits": "true"},
WithIORegistry(registry))
+ require.NoError(t, err)
+ catalogs[i] = cat
+ }
+
+ for i, cat := range catalogs {
+ require.Same(t, filesystems[i], cat.filesystem)
+ require.NotSame(t, filesystems[1-i], cat.filesystem)
+ }
+}
diff --git a/catalog/glue/options.go b/catalog/hadoop/options.go
similarity index 56%
copy from catalog/glue/options.go
copy to catalog/hadoop/options.go
index 180f9cf85..304128bdc 100644
--- a/catalog/glue/options.go
+++ b/catalog/hadoop/options.go
@@ -15,38 +15,19 @@
// specific language governing permissions and limitations
// under the License.
-package glue
+package hadoop
-import (
- "github.com/aws/aws-sdk-go-v2/aws"
-)
+import "github.com/apache/iceberg-go/io"
-type AWSProperties map[string]string
+type Option func(*catalogOptions)
-type Option func(*options)
-
-// WithName sets the logical name of this Glue catalog.
-func WithName(name string) Option {
- return func(o *options) {
- o.name = name
- }
-}
-
-// WithAWSConfig sets the AWS configuration for the catalog.
-func WithAWSConfig(cfg aws.Config) Option {
- return func(o *options) {
- o.awsConfig = cfg
- }
-}
-
-func WithAWSProperties(props AWSProperties) Option {
- return func(o *options) {
- o.awsProperties = props
- }
+type catalogOptions struct {
+ ioRegistry *io.Registry
}
-type options struct {
- name string
- awsConfig aws.Config
- awsProperties AWSProperties
+// WithIORegistry selects the FileIO factories used by this Hadoop catalog.
+// A nil registry uses the global default. The registry is shared, not copied,
+// so subsequent Register and Unregister calls affect this catalog.
+func WithIORegistry(registry *io.Registry) Option {
+ return func(o *catalogOptions) { o.ioRegistry = registry }
}
diff --git a/catalog/hadoop/tables.go b/catalog/hadoop/tables.go
index 492f42a3a..d00338369 100644
--- a/catalog/hadoop/tables.go
+++ b/catalog/hadoop/tables.go
@@ -30,7 +30,6 @@ import (
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/catalog"
"github.com/apache/iceberg-go/catalog/internal"
- "github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/table"
"github.com/apache/iceberg-go/table/maintenance"
"github.com/google/uuid"
@@ -121,7 +120,7 @@ func (c *Catalog) CreateTable(ctx context.Context, ident
table.Identifier, sc *i
ident,
metadata,
metaPath,
- io.LoadFSFunc(c.props, metaPath),
+ internal.LoadFSFuncWithRegistry(c.ioRegistry, c.props,
metaPath),
c,
table.WithMetricsReporter(reporter),
table.WithScanPlanningIOProperties(c.props),
@@ -146,7 +145,7 @@ func (c *Catalog) loadTable(ctx context.Context, ident
table.Identifier) (*table
}
tbl, err := table.NewFromLocation(
- ctx, ident, metaPath, io.LoadFSFunc(c.props, metaPath), c,
+ ctx, ident, metaPath,
internal.LoadFSFuncWithRegistry(c.ioRegistry, c.props, metaPath), c,
table.WithMetricsReporter(reporter),
table.WithScanPlanningIOProperties(c.props),
)
diff --git a/catalog/hive/hive.go b/catalog/hive/hive.go
index ae214cffa..c62cab357 100644
--- a/catalog/hive/hive.go
+++ b/catalog/hive/hive.go
@@ -29,7 +29,6 @@ import (
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/catalog"
"github.com/apache/iceberg-go/catalog/internal"
- "github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/metrics"
"github.com/apache/iceberg-go/table"
"github.com/apache/iceberg-go/table/maintenance"
@@ -197,7 +196,7 @@ func (c *Catalog) LoadTable(ctx context.Context, identifier
table.Identifier) (*
ctx,
identifier,
metadataLocation,
- io.LoadFSFunc(c.opts.props, metadataLocation),
+ internal.LoadFSFuncWithRegistry(c.opts.ioRegistry,
c.opts.props, metadataLocation),
c,
table.WithMetricsReporter(reporter),
table.WithScanPlanningIOProperties(c.opts.props),
@@ -228,7 +227,7 @@ func (c *Catalog) CreateTable(ctx context.Context,
identifier table.Identifier,
return nil, fmt.Errorf("%w: %s.%s",
catalog.ErrViewAlreadyExists, database, tableName)
}
- staged, err := internal.CreateStagedTable(ctx, c.opts.props,
c.LoadNamespaceProperties, identifier, schema, opts...)
+ staged, err := internal.CreateStagedTable(ctx, c.opts.props,
c.LoadNamespaceProperties, identifier, schema, c.opts.ioRegistry, opts...)
if err != nil {
return nil, err
}
@@ -290,7 +289,7 @@ func (c *Catalog) RegisterTable(ctx context.Context,
identifier table.Identifier
ctx,
identifier,
metadataLocation,
- io.LoadFSFunc(c.opts.props, metadataLocation),
+ internal.LoadFSFuncWithRegistry(c.opts.ioRegistry,
c.opts.props, metadataLocation),
c,
table.WithMetricsReporter(reporter),
table.WithScanPlanningIOProperties(c.opts.props),
@@ -378,7 +377,7 @@ func (c *Catalog) CreateView(ctx context.Context,
identifier table.Identifier, v
maps.Copy(ioProps, cfg.Properties)
}
- createdView, err := view.CreateViewFromVersion(ctx, identifier,
freshSchema, version, loc, ioProps, cfg.Properties)
+ createdView, err := view.CreateViewFromVersion(ctx, identifier,
freshSchema, version, loc, ioProps, cfg.Properties,
view.WithIORegistry(c.opts.ioRegistry))
if err != nil {
return nil, err
}
@@ -607,7 +606,7 @@ func (c *Catalog) CommitTable(ctx context.Context,
identifier table.Identifier,
return nil, "", err
}
current, err = table.NewFromLocation(
- ctx, identifier, metadataLoc,
io.LoadFSFunc(c.opts.props, metadataLoc), c,
+ ctx, identifier, metadataLoc,
internal.LoadFSFuncWithRegistry(c.opts.ioRegistry, c.opts.props, metadataLoc),
c,
table.WithScanPlanningIOProperties(c.opts.props),
)
if err != nil {
@@ -615,7 +614,7 @@ func (c *Catalog) CommitTable(ctx context.Context,
identifier table.Identifier,
}
}
- staged, err := internal.UpdateAndStageTable(ctx, c.opts.props, current,
identifier, requirements, updates, c)
+ staged, err := internal.UpdateAndStageTable(ctx, c.opts.props, current,
identifier, requirements, updates, c, c.opts.ioRegistry)
if err != nil {
return nil, "", err
}
@@ -751,7 +750,7 @@ func (c *Catalog) LoadView(ctx context.Context, identifier
table.Identifier) (*v
ctx,
identifier,
metadataLocation,
- io.LoadFSFunc(c.opts.props, metadataLocation),
+ internal.LoadFSFuncWithRegistry(c.opts.ioRegistry,
c.opts.props, metadataLocation),
)
}
@@ -784,7 +783,7 @@ func (c *Catalog) DropView(ctx context.Context, identifier
table.Identifier) err
return fmt.Errorf("failed to drop view %s.%s: %w", database,
viewName, err)
}
- fs, err := io.LoadFS(ctx, c.opts.props, metadataLocation)
+ fs, err := internal.LoadFSWithRegistry(ctx, c.opts.ioRegistry,
c.opts.props, metadataLocation)
if err != nil {
return fmt.Errorf("failed to load filesystem for view metadata:
%w", err)
}
diff --git a/catalog/hive/io_registry_test.go b/catalog/hive/io_registry_test.go
new file mode 100644
index 000000000..bced928f4
--- /dev/null
+++ b/catalog/hive/io_registry_test.go
@@ -0,0 +1,221 @@
+// 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.
+
+package hive
+
+import (
+ "context"
+ "net/url"
+ "os"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/apache/iceberg-go/catalog"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/table"
+ "github.com/apache/iceberg-go/view"
+ "github.com/beltran/gohive/hive_metastore"
+ "github.com/stretchr/testify/mock"
+ "github.com/stretchr/testify/require"
+)
+
+func TestHiveIsolatedIORegistry(t *testing.T) {
+ const scheme = "hive-private-registry"
+ const metadataLocation = scheme + "://bucket/table/metadata.json"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) { return fs, nil }))
+ contents, err :=
os.ReadFile("../../table/testdata/TableMetadataV2Valid.json")
+ require.NoError(t, err)
+ require.NoError(t, fs.WriteFile(t.Context(), metadataLocation,
contents))
+ client := &mockHiveClient{}
+ client.On("GetTable", mock.Anything, "db",
"tbl").Return(&hive_metastore.Table{DbName: "db", TableName: "tbl", TableType:
TableTypeExternalTable, Parameters: map[string]string{TableTypeKey:
TableTypeIceberg, MetadataLocationKey: metadataLocation}}, nil).Once()
+ cat := NewCatalogWithClient(client, iceberg.Properties{"storage-key":
"secret"}, WithIORegistry(registry))
+ tbl, err := cat.LoadTable(t.Context(), TableIdentifier("db", "tbl"))
+ require.NoError(t, err)
+ loaded, err := tbl.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loaded)
+ _, err = iceio.LoadFS(t.Context(), nil, metadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.On("GetDatabase", mock.Anything,
"db").Return(&hive_metastore.Database{Name: "db"}, nil).Once()
+ client.On("GetTable", mock.Anything, "db", "view").Return(nil,
errNoSuchObject).Twice()
+ client.On("CreateTable", mock.Anything,
mock.Anything).Return(nil).Once()
+ version, err := view.NewVersionFromSQL(1, 0, view.Representation{SQL:
"SELECT 1", Dialect: "hive"}, table.Identifier{"db"})
+ require.NoError(t, err)
+ schema := iceberg.NewSchema(1, iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int32, Required: true})
+ created, err := cat.CreateView(t.Context(), TableIdentifier("db",
"view"), version, schema, catalog.WithViewLocation(scheme+"://bucket/view"))
+ require.NoError(t, err)
+ file, err := fs.Open(t.Context(), created.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+ require.NotContains(t, created.Properties(), "storage-key")
+
+ // Loading and dropping views must also use the scoped registry.
+ hiveView := constructHiveViewTable("db", "view",
scheme+"://bucket/view",
+ created.MetadataLocation(), schema, "SELECT 1", nil)
+ client.On("GetTable", mock.Anything, "db", "view").Return(hiveView,
nil).Twice()
+ loadedView, err := cat.LoadView(t.Context(), TableIdentifier("db",
"view"))
+ require.NoError(t, err)
+ require.Equal(t, created.MetadataLocation(),
loadedView.MetadataLocation())
+ client.On("DropTable", mock.Anything, "db", "view",
false).Return(nil).Once()
+ require.NoError(t, cat.DropView(t.Context(), TableIdentifier("db",
"view")))
+ _, err = fs.Open(t.Context(), created.MetadataLocation())
+ require.Error(t, err, "dropping a view must remove metadata through the
scoped registry")
+ client.AssertExpectations(t)
+}
+
+func TestHiveRegisterTableUsesScopedIORegistry(t *testing.T) {
+ const scheme = "hive-register-private"
+ const metadataLocation = scheme +
"://bucket/table/metadata/v1.metadata.json"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ contents, err :=
os.ReadFile("../../table/testdata/TableMetadataV2Valid.json")
+ require.NoError(t, err)
+ require.NoError(t, fs.WriteFile(t.Context(), metadataLocation,
contents))
+
+ client := &mockHiveClient{}
+ client.On("GetDatabase", mock.Anything,
"db").Return(&hive_metastore.Database{Name: "db"}, nil).Once()
+ client.On("GetTable", mock.Anything, "db", "tbl").Return(nil,
errNoSuchObject).Twice()
+ client.On("CreateTable", mock.Anything,
mock.Anything).Return(nil).Once()
+ client.On("GetTable", mock.Anything, "db",
"tbl").Return(&hive_metastore.Table{
+ DbName: "db", TableName: "tbl", TableType:
TableTypeExternalTable,
+ Parameters: map[string]string{TableTypeKey: TableTypeIceberg,
MetadataLocationKey: metadataLocation},
+ }, nil).Once()
+
+ cat := NewCatalogWithClient(client, nil, WithIORegistry(registry))
+ tbl, err := cat.RegisterTable(t.Context(), TableIdentifier("db",
"tbl"), metadataLocation)
+ require.NoError(t, err)
+ loadedFS, err := tbl.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loadedFS)
+ _, err = iceio.LoadFS(t.Context(), nil, metadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
+
+func TestHiveCommitTableUsesScopedIORegistry(t *testing.T) {
+ const scheme = "hive-commit-private"
+ location := scheme + "://bucket/table"
+ metadataLocation := location + "/metadata/v1.metadata.json"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ writeHivePurgeTableMetadata(t, fs, location, metadataLocation, nil)
+
+ client := &mockHiveClient{}
+ expectImmediateTableLock(client, 1)
+ client.On("GetTable", mock.Anything, "test_database", "test_table").
+ Return(hivePurgeTable(metadataLocation, location), nil).Once()
+ client.On("AlterTable", mock.Anything, "test_database", "test_table",
+ mock.AnythingOfType("*hive_metastore.Table")).Return(nil).Once()
+
+ cat := NewCatalogWithClient(client, nil, WithIORegistry(registry))
+ _, updatedMetadataLocation, err := cat.CommitTable(t.Context(),
+ TableIdentifier("test_database", "test_table"), nil,
+
[]table.Update{table.NewSetPropertiesUpdate(iceberg.Properties{"changed":
"true"})})
+ require.NoError(t, err)
+ require.NotEqual(t, metadataLocation, updatedMetadataLocation)
+ file, err := fs.Open(t.Context(), updatedMetadataLocation)
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+ _, err = iceio.LoadFS(t.Context(), nil, updatedMetadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
+
+func TestHiveCatalogsWithSameSchemeStayIsolated(t *testing.T) {
+ const scheme = "hive-shared-scheme"
+ const metadataLocation = scheme + "://bucket/table/metadata.json"
+ contents, err :=
os.ReadFile("../../table/testdata/TableMetadataV2Valid.json")
+ require.NoError(t, err)
+
+ filesystems := []*iceio.MemFS{iceio.NewMemFS(), iceio.NewMemFS()}
+ catalogs := make([]*Catalog, len(filesystems))
+ clients := make([]*mockHiveClient, len(filesystems))
+ for i, fs := range filesystems {
+ registry := &iceio.Registry{}
+ require.NoError(t, registry.Register(scheme,
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ require.NoError(t, fs.WriteFile(t.Context(), metadataLocation,
contents))
+
+ client := &mockHiveClient{}
+ client.On("GetTable", mock.Anything, "db",
"tbl").Return(&hive_metastore.Table{
+ DbName: "db", TableName: "tbl", TableType:
TableTypeExternalTable,
+ Parameters: map[string]string{TableTypeKey:
TableTypeIceberg, MetadataLocationKey: metadataLocation},
+ }, nil).Once()
+ catalogs[i] = NewCatalogWithClient(client, nil,
WithIORegistry(registry))
+ clients[i] = client
+ }
+
+ // Both catalogs have the same URI scheme and live at the same time.
+ // Each must resolve its own factory, even after the other is created.
+ for i, cat := range catalogs {
+ tbl, err := cat.LoadTable(t.Context(), TableIdentifier("db",
"tbl"))
+ require.NoError(t, err)
+ loaded, err := tbl.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, filesystems[i], loaded)
+ require.NotSame(t, filesystems[1-i], loaded)
+ clients[i].AssertExpectations(t)
+ }
+}
+
+func TestHiveUpdateViewUsesScopedIORegistry(t *testing.T) {
+ const scheme = "hive-view-update-registry"
+ const location = scheme + "://bucket/view"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+
+ ident := table.Identifier{"db", "view"}
+ schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int32})
+ version := &view.Version{Representations: []view.Representation{
+ view.NewRepresentation(view.Representation{SQL: "SELECT 1",
Dialect: "hive"}),
+ }}
+ created, err := view.CreateViewFromVersion(t.Context(), ident, schema,
version, location, nil, iceberg.Properties{}, view.WithIORegistry(registry))
+ require.NoError(t, err)
+
+ client := &mockHiveClient{}
+ wrappedClient := &viewUpdateTestClient{mockHiveClient: client, renewal:
&viewRenewalTestClient{}}
+ cat := NewCatalogWithClient(wrappedClient, nil,
WithIORegistry(registry))
+ old := constructHiveViewTable("db", "view", location,
created.MetadataLocation(), schema, "SELECT 1", nil)
+ expectImmediateTableLock(client, 1)
+ client.On("GetTable", mock.Anything, "db", "view").Return(old,
nil).Once()
+ client.On("AlterTable", mock.Anything, "db", "view",
mock.AnythingOfType("*hive_metastore.Table")).Return(nil).Once()
+
+ updated, err := cat.UpdateView(t.Context(), ident, nil, []view.Update{
+ view.NewSetPropertiesUpdate(iceberg.Properties{"comment":
"updated"}),
+ })
+ require.NoError(t, err)
+ require.Equal(t, "updated", updated.Properties().Get("comment", ""))
+
+ file, err := fs.Open(t.Context(), updated.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+ _, err = iceio.LoadFS(t.Context(), nil, updated.MetadataLocation())
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ client.AssertExpectations(t)
+}
diff --git a/catalog/hive/options.go b/catalog/hive/options.go
index a9a4bb69b..9fa0d70ab 100644
--- a/catalog/hive/options.go
+++ b/catalog/hive/options.go
@@ -22,6 +22,7 @@ import (
"time"
"github.com/apache/iceberg-go"
+ "github.com/apache/iceberg-go/io"
)
const (
@@ -80,6 +81,8 @@ type HiveOptions struct {
Warehouse string
props iceberg.Properties
+ ioRegistry *io.Registry
+
// Lock configuration for atomic commits
LockMinWaitTime time.Duration
LockMaxWaitTime time.Duration
@@ -182,6 +185,13 @@ func WithName(name string) Option {
}
}
+// WithIORegistry selects the FileIO factories used by this Hive catalog.
+// A nil registry uses the global default. The registry is shared, not copied,
+// so subsequent Register and Unregister calls affect this catalog.
+func WithIORegistry(registry *io.Registry) Option {
+ return func(o *HiveOptions) { o.ioRegistry = registry }
+}
+
// WithURI sets the Thrift URI for the Hive Metastore.
func WithURI(uri string) Option {
return func(o *HiveOptions) {
diff --git a/catalog/hive/update_view.go b/catalog/hive/update_view.go
index 27f3e731e..842c57f6b 100644
--- a/catalog/hive/update_view.go
+++ b/catalog/hive/update_view.go
@@ -25,7 +25,7 @@ import (
"maps"
"github.com/apache/iceberg-go/catalog"
- icebergio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/catalog/internal"
"github.com/apache/iceberg-go/table"
"github.com/apache/iceberg-go/view"
)
@@ -90,7 +90,8 @@ func (c *Catalog) UpdateView(ctx context.Context, ident
table.Identifier, requir
if err != nil {
return nil, err
}
- current, err := view.NewFromLocation(ctx, ident, oldLocation,
icebergio.LoadFSFunc(c.opts.props, oldLocation))
+ current, err := view.NewFromLocation(ctx, ident, oldLocation,
+ internal.LoadFSFuncWithRegistry(c.opts.ioRegistry,
c.opts.props, oldLocation))
if err != nil {
return nil, err
}
@@ -124,7 +125,7 @@ func (c *Catalog) UpdateView(ctx context.Context, ident
table.Identifier, requir
ioProps = make(map[string]string)
}
maps.Copy(ioProps, metadata.Properties())
- metadataLocation, fs, err := view.WriteMetadata(ctx, metadata.Metadata,
ioProps)
+ metadataLocation, fs, err := view.WriteMetadata(ctx, metadata.Metadata,
ioProps, view.WithIORegistry(c.opts.ioRegistry))
if err != nil {
return nil, err
}
diff --git a/catalog/internal/io_registry.go b/catalog/internal/io_registry.go
new file mode 100644
index 000000000..6734bb68b
--- /dev/null
+++ b/catalog/internal/io_registry.go
@@ -0,0 +1,45 @@
+// 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.
+
+package internal
+
+import (
+ "context"
+
+ icebergio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/table"
+)
+
+// LoadFSWithRegistry uses the global FileIO registry when registry is nil.
+// A non-nil (including empty) registry is strictly isolated.
+func LoadFSWithRegistry(ctx context.Context, registry *icebergio.Registry,
props map[string]string, location string) (icebergio.IO, error) {
+ if registry == nil {
+ return icebergio.LoadFS(ctx, props, location)
+ }
+
+ return registry.LoadFS(ctx, props, location)
+}
+
+// LoadFSFuncWithRegistry creates a lazy FileIO loader bound to the selected
registry.
+// Choosing the loader here prevents later table reads from reverting to the
global registry.
+func LoadFSFuncWithRegistry(registry *icebergio.Registry, props
map[string]string, location string) table.FSysF {
+ if registry == nil {
+ return icebergio.LoadFSFunc(props, location)
+ }
+
+ return registry.LoadFSFunc(props, location)
+}
diff --git a/catalog/internal/io_registry_test.go
b/catalog/internal/io_registry_test.go
new file mode 100644
index 000000000..2a01ce965
--- /dev/null
+++ b/catalog/internal/io_registry_test.go
@@ -0,0 +1,98 @@
+// 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.
+
+package internal
+
+import (
+ "context"
+ "net/url"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/table"
+ "github.com/stretchr/testify/require"
+)
+
+func TestRegistryIsUsedForStagedAndUpdatedMetadata(t *testing.T) {
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register("isolated-staging",
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+
+ props := iceberg.Properties{"warehouse":
"isolated-staging://bucket/warehouse"}
+ ident := table.Identifier{"db", "tbl"}
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Required: true, Type:
iceberg.PrimitiveTypes.Int32,
+ })
+ nsprops := func(context.Context, table.Identifier) (iceberg.Properties,
error) { return nil, nil }
+
+ staged, err := CreateStagedTable(t.Context(), props, nsprops, ident,
schema, registry)
+ require.NoError(t, err)
+ loaded, err := staged.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loaded)
+ require.NoError(t, WriteMetadata(t.Context(), staged.Table))
+
+ f, err := fs.Open(t.Context(), staged.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, f.Close())
+
+ updated, err := UpdateAndStageTable(
+ t.Context(), props, staged.Table, ident, nil, nil, nil,
registry,
+ )
+ require.NoError(t, err)
+ loaded, err = updated.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, fs, loaded)
+ require.NoError(t, WriteMetadata(t.Context(), updated.Table))
+
+ _, err = iceio.LoadFS(t.Context(), props, updated.MetadataLocation())
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+func TestLoadFSWithRegistryDistinguishesNilFromEmpty(t *testing.T) {
+ global, err := LoadFSWithRegistry(t.Context(), nil, nil,
"file:///metadata.json")
+ require.NoError(t, err)
+ require.IsType(t, iceio.LocalFS{}, global)
+
+ _, err = LoadFSWithRegistry(t.Context(), &iceio.Registry{}, nil,
"file:///metadata.json")
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+
+ _, err = LoadFSFuncWithRegistry(&iceio.Registry{}, nil,
"file:///metadata.json")(t.Context())
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+func TestConfiguredRegistryRemainsLive(t *testing.T) {
+ registry := &iceio.Registry{}
+ const location = "registry-live://bucket/metadata.json"
+ _, err := LoadFSWithRegistry(t.Context(), registry, nil, location)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register("registry-live",
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ loaded, err := LoadFSWithRegistry(t.Context(), registry, nil, location)
+ require.NoError(t, err)
+ require.Same(t, fs, loaded)
+
+ registry.Unregister("registry-live")
+ _, err = LoadFSWithRegistry(t.Context(), registry, nil, location)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
diff --git a/catalog/internal/update_stage_test.go
b/catalog/internal/update_stage_test.go
index c62631bd8..091985692 100644
--- a/catalog/internal/update_stage_test.go
+++ b/catalog/internal/update_stage_test.go
@@ -54,6 +54,7 @@ func TestUpdateAndStageTableRejectsInvalidMetadataLocation(t
*testing.T) {
nil,
nil,
nil,
+ nil,
)
require.Error(t, err)
require.Nil(t, staged)
@@ -86,6 +87,7 @@ func
TestUpdateAndStageTableRejectsEmptyMetadataLocationForExistingTable(t *test
nil,
nil,
nil,
+ nil,
)
require.Error(t, err)
require.Nil(t, staged)
@@ -145,7 +147,7 @@ func TestUpdateAndStageTableClassifiesFailures(t
*testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- staged, err := UpdateAndStageTable(t.Context(), nil,
tt.current, table.Identifier{"db", "tbl"}, tt.reqs, tt.updates, nil)
+ staged, err := UpdateAndStageTable(t.Context(), nil,
tt.current, table.Identifier{"db", "tbl"}, tt.reqs, tt.updates, nil, nil)
require.Nil(t, staged)
for _, want := range tt.want {
require.ErrorIs(t, err, want)
@@ -169,6 +171,7 @@ func TestUpdateAndStageTableUsesVersionZeroForCreate(t
*testing.T) {
nil,
[]table.Update{table.NewSetLocationUpdate("file:///tmp/table")},
nil,
+ nil,
)
require.NoError(t, err)
require.Equal(t, 0, ParseMetadataVersion(staged.MetadataLocation()))
diff --git a/catalog/internal/utils.go b/catalog/internal/utils.go
index 4fc67cb0f..beaba4543 100644
--- a/catalog/internal/utils.go
+++ b/catalog/internal/utils.go
@@ -94,8 +94,14 @@ func UpdateTableMetadata(base table.Metadata, updates
[]table.Update, metadataLo
return table.UpdateTableMetadata(base, updates, metadataLoc)
}
-func CreateStagedTable(ctx context.Context, catprops iceberg.Properties,
nspropsFn GetNamespacePropsFn, ident table.Identifier, sc *iceberg.Schema, opts
...catalog.CreateTableOpt) (table.StagedTable, error) {
- return createStagedTable(ctx, catprops, nspropsFn, ident, "", sc,
opts...)
+// CreateStagedTable stages table metadata using a catalog-scoped FileIO
registry.
+// A nil registry selects the process-wide default.
+func CreateStagedTable(
+ ctx context.Context, catprops iceberg.Properties, nspropsFn
GetNamespacePropsFn,
+ ident table.Identifier, sc *iceberg.Schema, registry
*icebergio.Registry,
+ opts ...catalog.CreateTableOpt,
+) (table.StagedTable, error) {
+ return createStagedTable(ctx, catprops, nspropsFn, ident, "", sc,
registry, opts...)
}
// CreateStagedTableWithNamespaceKey creates a staged table using namespaceKey
@@ -108,9 +114,10 @@ func CreateStagedTableWithNamespaceKey(
ident table.Identifier,
namespaceKey string,
sc *iceberg.Schema,
+ registry *icebergio.Registry,
opts ...catalog.CreateTableOpt,
) (table.StagedTable, error) {
- return createStagedTable(ctx, catprops, nspropsFn, ident, namespaceKey,
sc, opts...)
+ return createStagedTable(ctx, catprops, nspropsFn, ident, namespaceKey,
sc, registry, opts...)
}
func createStagedTable(
@@ -120,6 +127,7 @@ func createStagedTable(
ident table.Identifier,
namespaceKey string,
sc *iceberg.Schema,
+ registry *icebergio.Registry,
opts ...catalog.CreateTableOpt,
) (table.StagedTable, error) {
if len(ident) < 2 {
@@ -172,7 +180,7 @@ func createStagedTable(
ident,
metadata,
metadataLoc,
- icebergio.LoadFSFunc(ioProps, metadataLoc),
+ LoadFSFuncWithRegistry(registry, ioProps, metadataLoc),
nil,
),
}, nil
@@ -293,8 +301,8 @@ func RejectUnlessConflict(err error) error {
// UpdateAndStageTable applies updates to the current table without writing
// anything. Every error it returns matches table.ErrCommitRejected unless it
-// matches table.ErrCommitFailed.
-func UpdateAndStageTable(ctx context.Context, catprops iceberg.Properties,
current *table.Table, ident table.Identifier, reqs []table.Requirement, updates
[]table.Update, cat table.CatalogIO) (_ *table.StagedTable, err error) {
+// matches table.ErrCommitFailed. A nil registry uses the default FileIO
registry.
+func UpdateAndStageTable(ctx context.Context, catprops iceberg.Properties,
current *table.Table, ident table.Identifier, reqs []table.Requirement, updates
[]table.Update, cat table.CatalogIO, registry *icebergio.Registry) (_
*table.StagedTable, err error) {
defer func() { err = RejectUnlessConflict(err) }()
var (
@@ -351,7 +359,7 @@ func UpdateAndStageTable(ctx context.Context, catprops
iceberg.Properties, curre
ident,
updated,
newLocation,
- icebergio.LoadFSFunc(ioProps, newLocation),
+ LoadFSFuncWithRegistry(registry, ioProps, newLocation),
cat,
),
}, nil
diff --git a/catalog/sql/io_registry_test.go b/catalog/sql/io_registry_test.go
new file mode 100644
index 000000000..812bb0f18
--- /dev/null
+++ b/catalog/sql/io_registry_test.go
@@ -0,0 +1,250 @@
+// 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.
+
+package sql_test
+
+import (
+ "context"
+ "database/sql"
+ "io/fs"
+ "net/url"
+ "path/filepath"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ "github.com/apache/iceberg-go/catalog"
+ sqlcat "github.com/apache/iceberg-go/catalog/sql"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/apache/iceberg-go/table"
+ "github.com/apache/iceberg-go/view"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+ "github.com/uptrace/bun/driver/sqliteshim"
+)
+
+func TestSQLCatalogIORegistriesAreIsolated(t *testing.T) {
+ const scheme = "sql-private-registry"
+ globalFS := iceio.NewMemFS()
+ iceio.Register(scheme, func(context.Context, *url.URL,
map[string]string) (iceio.IO, error) {
+ return globalFS, nil
+ })
+ t.Cleanup(func() { iceio.Unregister(scheme) })
+
+ type catalogCase struct {
+ cat *sqlcat.Catalog
+ fs *iceio.MemFS
+ }
+ cases := make([]catalogCase, 2)
+
+ for i := range cases {
+ fs := iceio.NewMemFS()
+ registry := &iceio.Registry{}
+ require.NoError(t, registry.Register(scheme,
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+
+ db, err := sql.Open(sqliteshim.ShimName,
filepath.Join(t.TempDir(), "catalog.db"))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, db.Close()) })
+
+ cat, err := sqlcat.NewCatalog(t.Context(), "isolated", db,
sqlcat.SQLite,
+ iceberg.Properties{"warehouse": scheme +
"://bucket/warehouse"},
+ sqlcat.WithIORegistry(registry))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, cat.Close()) })
+ cases[i] = catalogCase{cat: cat, fs: fs}
+ }
+
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32,
Required: true,
+ })
+ for i, tc := range cases {
+ ident := []string{"db", "table_" + uuid.NewString()}
+ require.NoError(t, tc.cat.CreateNamespace(t.Context(),
[]string{"db"}, nil))
+
+ created, err := tc.cat.CreateTable(t.Context(), ident, schema)
+ require.NoError(t, err)
+ loaded, err := tc.cat.LoadTable(t.Context(), ident)
+ require.NoError(t, err)
+
+ for _, tbl := range []*table.Table{created, loaded} {
+ got, err := tbl.FS(t.Context())
+ require.NoError(t, err)
+ require.Same(t, tc.fs, got)
+ }
+
+ metadataFile, err := tc.fs.Open(t.Context(),
created.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, metadataFile.Close())
+ _, err = cases[1-i].fs.Open(t.Context(),
created.MetadataLocation())
+ require.Error(t, err)
+
+ defaultFS, err := iceio.LoadFS(t.Context(), nil,
created.MetadataLocation())
+ require.NoError(t, err)
+ require.Same(t, globalFS, defaultFS)
+ _, err = globalFS.Open(t.Context(), created.MetadataLocation())
+ require.ErrorIs(t, err, fs.ErrNotExist)
+
+ // CommitTable stages and writes new metadata, not just the
initial create.
+ _, updatedLocation, err := tc.cat.CommitTable(t.Context(),
ident, nil,
+
[]table.Update{table.NewSetPropertiesUpdate(iceberg.Properties{"updated":
"true"})})
+ require.NoError(t, err)
+ require.NotEqual(t, created.MetadataLocation(), updatedLocation)
+ newMetadata, err := tc.fs.Open(t.Context(), updatedLocation)
+ require.NoError(t, err)
+ require.NoError(t, newMetadata.Close())
+ _, err = globalFS.Open(t.Context(), updatedLocation)
+ require.ErrorIs(t, err, fs.ErrNotExist)
+ }
+}
+
+func TestSQLCatalogMissingScopedSchemeDoesNotPublishTable(t *testing.T) {
+ ctx := t.Context()
+ warehouse := (&url.URL{Scheme: "file", Path:
filepath.ToSlash(t.TempDir())}).String()
+ db, err := sql.Open(sqliteshim.ShimName, filepath.Join(t.TempDir(),
"catalog.db"))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, db.Close()) })
+
+ registry := &iceio.Registry{}
+ cat, err := sqlcat.NewCatalog(ctx, "isolated", db, sqlcat.SQLite,
+ iceberg.Properties{"warehouse": warehouse},
sqlcat.WithIORegistry(registry))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, cat.Close()) })
+ require.NoError(t, cat.CreateNamespace(ctx, []string{"db"}, nil))
+
+ ident := table.Identifier{"db", "tbl"}
+ schema := iceberg.NewSchema(1,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int32})
+ _, err = cat.CreateTable(ctx, ident, schema)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound, "an empty registry
must not use the global file scheme")
+ exists, err := cat.CheckTableExists(ctx, ident)
+ require.NoError(t, err)
+ require.False(t, exists, "a failed metadata write must not publish a
catalog entry")
+
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register("file", func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ created, err := cat.CreateTable(ctx, ident, schema)
+ require.NoError(t, err)
+ metadata, err := fs.Open(ctx, created.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, metadata.Close())
+}
+
+func TestSQLViewUsesCatalogIOPropertiesWithIsolatedRegistry(t *testing.T) {
+ const scheme = "sql-view-private-registry"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ var seen map[string]string
+ require.NoError(t, registry.Register(scheme, func(_ context.Context, _
*url.URL, props map[string]string) (iceio.IO, error) {
+ seen = props
+
+ return fs, nil
+ }))
+
+ db, err := sql.Open(sqliteshim.ShimName, filepath.Join(t.TempDir(),
"views.db"))
+ require.NoError(t, err)
+ defer db.Close()
+
+ cat, err := sqlcat.NewCatalog(t.Context(), "isolated", db,
sqlcat.SQLite,
+ iceberg.Properties{
+ "warehouse": scheme + "://bucket/warehouse",
+ "storage-secret": "catalog-only",
+ sqlcat.SchemaVersionKey: sqlcat.SchemaVersionV1,
+ },
+ sqlcat.WithIORegistry(registry),
+ )
+ require.NoError(t, err)
+ defer cat.Close()
+
+ ident := []string{"db", "orders_view"}
+ require.NoError(t, cat.CreateNamespace(t.Context(), []string{"db"},
nil))
+ schema := iceberg.NewSchema(1, iceberg.NestedField{
+ ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32,
Required: true,
+ })
+ version := &view.Version{Representations: []view.Representation{
+ view.NewRepresentation(view.Representation{SQL: "SELECT 1",
Dialect: "spark"}),
+ view.NewRepresentation(view.Representation{SQL: "SELECT 1",
Dialect: "trino"}),
+ }}
+ _, err = cat.CreateView(t.Context(), ident, version, schema,
+ catalog.WithViewProperties(iceberg.Properties{"view-prop":
"persisted"}))
+ require.NoError(t, err)
+ require.Equal(t, "catalog-only", seen["storage-secret"])
+
+ loaded, err := cat.LoadView(t.Context(), ident)
+ require.NoError(t, err)
+ require.Equal(t, "persisted", loaded.Properties()["view-prop"])
+ require.NotContains(t, loaded.Properties(), "storage-secret")
+ require.Equal(t, version.Representations,
loaded.Metadata().CurrentVersion().Representations)
+ require.Equal(t, "isolated",
loaded.Metadata().CurrentVersion().DefaultCatalog)
+ require.Empty(t, version.DefaultCatalog, "catalog defaults must not
modify the caller's version")
+ updated, err := cat.UpdateView(t.Context(), ident, nil, []view.Update{
+ view.NewSetPropertiesUpdate(iceberg.Properties{"updated":
"true"}),
+ })
+ require.NoError(t, err)
+ require.Equal(t, "true", updated.Properties()["updated"])
+ require.Equal(t, "catalog-only", seen["storage-secret"], "view metadata
updates must use the catalog registry")
+ require.NoError(t, cat.DropView(t.Context(), ident))
+}
+
+type trackingRegistryFS struct {
+ *iceio.MemFS
+ removed []string
+}
+
+func (fs *trackingRegistryFS) Remove(ctx context.Context, path string) error {
+ fs.removed = append(fs.removed, path)
+
+ return fs.MemFS.Remove(ctx, path)
+}
+
+func TestSQLViewCollisionCleanupUsesViewIOProperties(t *testing.T) {
+ const scheme = "sql-view-cleanup-registry"
+ registry := &iceio.Registry{}
+ fs := &trackingRegistryFS{MemFS: iceio.NewMemFS()}
+ var seen []string
+ require.NoError(t, registry.Register(scheme, func(_ context.Context, _
*url.URL, props map[string]string) (iceio.IO, error) {
+ seen = append(seen, props["storage-token"])
+
+ return fs, nil
+ }))
+ db, err := sql.Open(sqliteshim.ShimName, filepath.Join(t.TempDir(),
"cleanup.db"))
+ require.NoError(t, err)
+ defer db.Close()
+ cat, err := sqlcat.NewCatalog(t.Context(), "test", db, sqlcat.SQLite,
+ iceberg.Properties{"warehouse": scheme + "://bucket/warehouse",
"storage-token": "catalog", sqlcat.SchemaVersionKey: sqlcat.SchemaVersionV1},
+ sqlcat.WithIORegistry(registry))
+ require.NoError(t, err)
+ defer cat.Close()
+ require.NoError(t, cat.CreateNamespace(t.Context(), []string{"db"},
nil))
+ schema := iceberg.NewSchema(1, iceberg.NestedField{ID: 1, Name: "id",
Type: iceberg.PrimitiveTypes.Int32, Required: true})
+ ident := []string{"db", "view"}
+ version := &view.Version{Representations: []view.Representation{
+ view.NewRepresentation(view.Representation{SQL: "SELECT 1",
Dialect: "spark"}),
+ }}
+ props := catalog.WithViewProperties(iceberg.Properties{"storage-token":
"view"})
+ _, err = cat.CreateView(t.Context(), ident, version, schema, props)
+ require.NoError(t, err)
+ seen = nil
+ _, err = cat.CreateView(t.Context(), ident, version, schema, props)
+ require.Error(t, err)
+ require.Equal(t, []string{"view", "view"}, seen)
+ require.Len(t, fs.removed, 1)
+ _, err = fs.Open(t.Context(), fs.removed[0])
+ require.Error(t, err)
+}
diff --git a/catalog/glue/options.go b/catalog/sql/options.go
similarity index 56%
copy from catalog/glue/options.go
copy to catalog/sql/options.go
index 180f9cf85..96f46b09b 100644
--- a/catalog/glue/options.go
+++ b/catalog/sql/options.go
@@ -15,38 +15,19 @@
// specific language governing permissions and limitations
// under the License.
-package glue
+package sql
-import (
- "github.com/aws/aws-sdk-go-v2/aws"
-)
+import "github.com/apache/iceberg-go/io"
-type AWSProperties map[string]string
+type Option func(*catalogOptions)
-type Option func(*options)
-
-// WithName sets the logical name of this Glue catalog.
-func WithName(name string) Option {
- return func(o *options) {
- o.name = name
- }
-}
-
-// WithAWSConfig sets the AWS configuration for the catalog.
-func WithAWSConfig(cfg aws.Config) Option {
- return func(o *options) {
- o.awsConfig = cfg
- }
-}
-
-func WithAWSProperties(props AWSProperties) Option {
- return func(o *options) {
- o.awsProperties = props
- }
+type catalogOptions struct {
+ ioRegistry *io.Registry
}
-type options struct {
- name string
- awsConfig aws.Config
- awsProperties AWSProperties
+// WithIORegistry selects the FileIO factories used by this SQL catalog.
+// A nil registry uses the global default. The registry is shared, not copied,
+// so subsequent Register and Unregister calls affect this catalog.
+func WithIORegistry(registry *io.Registry) Option {
+ return func(o *catalogOptions) { o.ioRegistry = registry }
}
diff --git a/catalog/sql/sql.go b/catalog/sql/sql.go
index d176aaa6c..a8047bc50 100644
--- a/catalog/sql/sql.go
+++ b/catalog/sql/sql.go
@@ -561,6 +561,8 @@ type Catalog struct {
// path) and must therefore close it in Close. It stays false for
handles
// supplied to NewCatalog, which remain owned by the caller.
ownsDB bool
+
+ ioRegistry *io.Registry
}
// isV0 reports whether the catalog is operating against a legacy V0 schema
that
@@ -593,13 +595,20 @@ func (c *Catalog) isV0() bool { return c.schemaVersion ==
schemaV0 }
// The driver's default applies when the DSN sets none: mattn waits 5000ms,
while modernc does not wait, so
// CreateTable, CreateView and the other operations that retry on a lock
conflict give up after about 310ms and the
// rest fail at once. NewCatalog does not mutate connection settings on the
caller-owned db.
-func NewCatalog(ctx context.Context, name string, db *sql.DB, dialect
SupportedDialect, props iceberg.Properties) (*Catalog, error) {
+//
+// WithIORegistry selects a catalog-scoped FileIO registry. The default is the
+// global registry.
+func NewCatalog(ctx context.Context, name string, db *sql.DB, dialect
SupportedDialect, props iceberg.Properties, opts ...Option) (*Catalog, error) {
d, err := getDialect(dialect)
if err != nil {
return nil, err
}
- cat := &Catalog{db: bun.NewDB(db, d), name: name, props: props}
+ var config catalogOptions
+ for _, opt := range opts {
+ opt(&config)
+ }
+ cat := &Catalog{db: bun.NewDB(db, d), name: name, props: props,
ioRegistry: config.ioRegistry}
cat.db = cat.db.WithQueryHook(bundebug.NewQueryHook(
bundebug.WithEnabled(false),
@@ -996,7 +1005,7 @@ func (c *Catalog) CreateTable(ctx context.Context, ident
table.Identifier, sc *i
}
staged, err := internal.CreateStagedTableWithNamespaceKey(
- ctx, c.props, c.LoadNamespaceProperties, ident, ns, sc, opts...)
+ ctx, c.props, c.LoadNamespaceProperties, ident, ns, sc,
c.ioRegistry, opts...)
if err != nil {
return nil, err
}
@@ -1068,7 +1077,7 @@ func (c *Catalog) CommitTable(ctx context.Context, ident
table.Identifier, reqs
return nil, "", err
}
- staged, err := internal.UpdateAndStageTable(ctx, c.props, current,
ident, reqs, updates, c)
+ staged, err := internal.UpdateAndStageTable(ctx, c.props, current,
ident, reqs, updates, c, c.ioRegistry)
if err != nil {
return nil, "", err
}
@@ -1208,7 +1217,7 @@ func (c *Catalog) LoadTable(ctx context.Context,
identifier table.Identifier) (*
ctx,
identifier,
result.MetadataLocation.String,
- io.LoadFSFunc(c.props, result.MetadataLocation.String),
+ internal.LoadFSFuncWithRegistry(c.ioRegistry, c.props,
result.MetadataLocation.String),
c,
table.WithMetricsReporter(reporter),
table.WithScanPlanningIOProperties(c.props),
@@ -1867,7 +1876,7 @@ func (c *Catalog) CreateView(ctx context.Context,
identifier table.Identifier, v
version.DefaultCatalog = c.name
}
- createdView, err := view.CreateViewFromVersion(ctx, identifier, schema,
version, loc, ioProps, cfg.Properties)
+ createdView, err := view.CreateViewFromVersion(ctx, identifier, schema,
version, loc, ioProps, cfg.Properties, view.WithIORegistry(c.ioRegistry))
if err != nil {
return nil, err
}
@@ -1906,7 +1915,7 @@ func (c *Catalog) CreateView(ctx context.Context,
identifier table.Identifier, v
err = collisionErr
}
}
- loadFS := io.LoadFSFunc(ioProps, metadataLocation)
+ loadFS := internal.LoadFSFuncWithRegistry(c.ioRegistry,
ioProps, metadataLocation)
if cleanupErr := removeUncommittedMetadata(ctx,
metadataLocation, loadFS); cleanupErr != nil {
err = errors.Join(err, cleanupErr)
}
@@ -1983,7 +1992,7 @@ func (c *Catalog) DropView(ctx context.Context,
identifier table.Identifier) err
}
if metadataLocation != "" {
- fs, err := io.LoadFS(ctx, c.props, metadataLocation)
+ fs, err := internal.LoadFSWithRegistry(ctx, c.ioRegistry,
c.props, metadataLocation)
if err != nil {
return err
}
@@ -2065,7 +2074,7 @@ func (c *Catalog) LoadView(ctx context.Context,
identifier table.Identifier) (*v
return nil, fmt.Errorf("%w: %s, metadata location is missing",
catalog.ErrNoSuchView, identifier)
}
- loadedView, err := view.NewFromLocation(ctx, identifier,
v.MetadataLocation.String, io.LoadFSFunc(c.props, v.MetadataLocation.String))
+ loadedView, err := view.NewFromLocation(ctx, identifier,
v.MetadataLocation.String, internal.LoadFSFuncWithRegistry(c.ioRegistry,
c.props, v.MetadataLocation.String))
if err != nil {
return nil, err
}
diff --git a/catalog/sql/update_view.go b/catalog/sql/update_view.go
index 9af9f6b8b..03d48e94b 100644
--- a/catalog/sql/update_view.go
+++ b/catalog/sql/update_view.go
@@ -69,7 +69,7 @@ func (c *Catalog) UpdateView(ctx context.Context, ident
table.Identifier, requir
ioProps = make(map[string]string)
}
maps.Copy(ioProps, metadata.Properties())
- metadataLocation, fs, err := view.WriteMetadata(ctx, metadata.Metadata,
ioProps)
+ metadataLocation, fs, err := view.WriteMetadata(ctx, metadata.Metadata,
ioProps, view.WithIORegistry(c.ioRegistry))
if err != nil {
return nil, err
}
diff --git a/view/io_registry_test.go b/view/io_registry_test.go
new file mode 100644
index 000000000..fd8c01814
--- /dev/null
+++ b/view/io_registry_test.go
@@ -0,0 +1,202 @@
+// 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.
+
+package view
+
+import (
+ "context"
+ "net/url"
+ "testing"
+
+ "github.com/apache/iceberg-go"
+ iceio "github.com/apache/iceberg-go/io"
+ "github.com/stretchr/testify/require"
+)
+
+func TestCreateViewWithIsolatedIORegistry(t *testing.T) {
+ const scheme = "isolated-view-registry"
+ filesystems := []*iceio.MemFS{iceio.NewMemFS(), iceio.NewMemFS()}
+ registries := []*iceio.Registry{{}, {}}
+
+ for i, registry := range registries {
+ fs := filesystems[i]
+ require.NoError(t, registry.Register(scheme,
func(context.Context, *url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ }
+
+ for i, registry := range registries {
+ created, err := CreateView(
+ t.Context(), "test", []string{"db", "orders"},
+ newTestSchema(0), Representation{SQL: "SELECT 1",
Dialect: "spark"},
+ []string{"db"}, scheme+"://bucket/view", nil,
WithIORegistry(registry),
+ )
+ require.NoError(t, err)
+ require.NotNil(t, created)
+
+ file, err := filesystems[i].Open(t.Context(),
created.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+
+ _, err = filesystems[1-i].Open(t.Context(),
created.MetadataLocation())
+ require.Error(t, err, "the other catalog's filesystem must not
see this view")
+
+ _, err = iceio.LoadFS(t.Context(), nil,
created.MetadataLocation())
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+ }
+}
+
+func TestCreateViewWithSeparateIOPropertiesAndRegistry(t *testing.T) {
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ var seen map[string]string
+ require.NoError(t, registry.Register("isolated-view-properties", func(_
context.Context, _ *url.URL, props map[string]string) (iceio.IO, error) {
+ seen = props
+
+ return fs, nil
+ }))
+
+ created, err := CreateViewWithIOProperties(
+ t.Context(), "test", []string{"db", "orders"},
+ newTestSchema(0), Representation{SQL: "SELECT 1", Dialect:
"spark"},
+ []string{"db"}, "isolated-view-properties://bucket/view",
+ iceberg.Properties{"storage-only": "token"},
+ iceberg.Properties{"persisted": "value"},
WithIORegistry(registry),
+ )
+ require.NoError(t, err)
+ require.Equal(t, "token", seen["storage-only"])
+ require.Equal(t, "value", created.Properties()["persisted"])
+ require.NotContains(t, created.Properties(), "storage-only")
+}
+
+func TestCreateViewWithEmptyRegistryDoesNotFallBackToGlobal(t *testing.T) {
+ _, err := CreateView(
+ t.Context(), "test", []string{"db", "orders"},
+ newTestSchema(0), Representation{SQL: "SELECT 1", Dialect:
"spark"},
+ []string{"db"}, "file:///tmp/view-registry-no-fallback", nil,
WithIORegistry(&iceio.Registry{}),
+ )
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+// TestWriteMetadataUsesIsolatedRegistry directly exercises metadata writes,
+// not just the view-creation wrapper. Storage-only settings must reach FileIO
+// without becoming persisted view properties.
+func TestWriteMetadataUsesIsolatedRegistry(t *testing.T) {
+ const scheme = "isolated-view-metadata-write"
+ ctx := t.Context()
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ var storageProps map[string]string
+ require.NoError(t, registry.Register(scheme, func(_ context.Context, _
*url.URL, props map[string]string) (iceio.IO, error) {
+ storageProps = props
+
+ return fs, nil
+ }))
+ created, err := CreateView(
+ ctx, "test", []string{"db", "view"}, newTestSchema(0),
+ Representation{SQL: "SELECT 1", Dialect: "spark"},
+ []string{"db"}, scheme+"://bucket/view",
iceberg.Properties{"persisted": "yes"},
+ WithIORegistry(registry),
+ )
+ require.NoError(t, err)
+
+ metadataLocation, writeFS, err := WriteMetadata(ctx, created.Metadata(),
+ iceberg.Properties{"storage-token": "private"},
WithIORegistry(registry))
+ require.NoError(t, err)
+ require.NotEqual(t, created.MetadataLocation(), metadataLocation)
+ require.Same(t, fs, writeFS)
+ require.Equal(t, "private", storageProps["storage-token"])
+ require.Equal(t, "yes", created.Properties()["persisted"])
+ require.NotContains(t, created.Properties(), "storage-token")
+ file, err := fs.Open(ctx, metadataLocation)
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+ _, err = iceio.LoadFS(ctx, nil, metadataLocation)
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
+
+// TestViewMetadataIORegistryIsLive guards the supplied registry pointer
+// against being copied or silently replaced by the global registry.
+func TestViewMetadataIORegistryIsLive(t *testing.T) {
+ const scheme = "isolated-view-registry-live"
+ ctx := t.Context()
+ registry := &iceio.Registry{}
+ ident := []string{"db", "view"}
+ representation := Representation{SQL: "SELECT 1", Dialect: "spark"}
+ location := scheme + "://bucket/view"
+
+ _, err := CreateView(ctx, "test", ident, newTestSchema(0),
+ representation, []string{"db"}, location, nil,
WithIORegistry(registry))
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ created, err := CreateView(ctx, "test", ident, newTestSchema(0),
+ representation, []string{"db"}, location, nil,
WithIORegistry(registry))
+ require.NoError(t, err)
+ file, err := fs.Open(ctx, created.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, file.Close())
+
+ registry.Unregister(scheme)
+ _, _, err = WriteMetadata(ctx, created.Metadata(), nil,
WithIORegistry(registry))
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound,
+ "unregistering the private scheme must not fall back to the
global registry")
+ file, err = fs.Open(ctx, created.MetadataLocation())
+ require.NoError(t, err, "failed new metadata writes must not remove an
existing view")
+ require.NoError(t, file.Close())
+}
+
+func TestCreateViewFromVersionPreservesMetadataWithIsolatedRegistry(t
*testing.T) {
+ const scheme = "isolated-view-version"
+ registry := &iceio.Registry{}
+ fs := iceio.NewMemFS()
+ require.NoError(t, registry.Register(scheme, func(context.Context,
*url.URL, map[string]string) (iceio.IO, error) {
+ return fs, nil
+ }))
+ version, err := NewVersion(7, 3, []Representation{
+ NewRepresentation(Representation{SQL: "SELECT 1", Dialect:
"trino"}),
+ NewRepresentation(Representation{SQL: "SELECT 1", Dialect:
"spark"}),
+ }, []string{"original_ns"},
+ WithDefaultViewCatalog("prod"),
+ WithVersionSummary(VersionSummary{"engine-version": "467"}),
+ WithTimestampMS(1234),
+ )
+ require.NoError(t, err)
+ created, err := CreateViewFromVersion(
+ t.Context(), []string{"db", "v"}, newTestSchema(0), version,
+ scheme+"://bucket/view", iceberg.Properties{"storage-only":
"secret"},
+ iceberg.Properties{"view-property": "stored"},
WithIORegistry(registry),
+ )
+ require.NoError(t, err)
+ got := created.CurrentVersion()
+ require.Equal(t, version.Representations, got.Representations)
+ require.Equal(t, "prod", got.DefaultCatalog)
+ require.Equal(t, version.DefaultNamespace, got.DefaultNamespace)
+ require.Equal(t, int64(1234), got.TimestampMS)
+ require.Equal(t, "467", got.Summary["engine-version"])
+ require.Equal(t, "stored", created.Properties()["view-property"])
+ require.NotContains(t, created.Properties(), "storage-only")
+ require.Equal(t, int64(7), version.VersionID)
+ f, err := fs.Open(t.Context(), created.MetadataLocation())
+ require.NoError(t, err)
+ require.NoError(t, f.Close())
+ _, err = iceio.LoadFS(t.Context(), nil, created.MetadataLocation())
+ require.ErrorIs(t, err, iceio.ErrIOSchemeNotFound)
+}
diff --git a/view/view.go b/view/view.go
index 6af6db9d3..a94ed648c 100644
--- a/view/view.go
+++ b/view/view.go
@@ -134,6 +134,9 @@ func NewFromLocation(
// Note: This function only supports creating new views with format version 1.
// It does not support updating existing view metadata.
// representation holds both SQL text and its dialect.
+// WithIORegistry selects the FileIO registry for the metadata write.
+// props configures FileIO and is also persisted in the view metadata. Use
+// CreateViewWithIOProperties to keep storage credentials out of view metadata.
func CreateView(
ctx context.Context,
catalogName string,
@@ -143,13 +146,15 @@ func CreateView(
defaultNS table.Identifier,
loc string,
props iceberg.Properties,
+ opts ...MetadataIOOption,
) (*View, error) {
- return CreateViewWithIOProperties(ctx, catalogName, viewIdent, schema,
representation, defaultNS, loc, props, props)
+ return CreateViewWithIOProperties(ctx, catalogName, viewIdent, schema,
representation, defaultNS, loc, props, props, opts...)
}
// CreateViewWithIOProperties creates a view using ioProps to configure the
// filesystem and metadataProps as the properties persisted in view metadata.
-// representation holds both SQL text and its dialect.
+// representation holds both SQL text and its dialect. WithIORegistry
optionally
+// selects the registry used by the write without changing persisted metadata.
func CreateViewWithIOProperties(
ctx context.Context,
catalogName string,
@@ -160,6 +165,7 @@ func CreateViewWithIOProperties(
loc string,
ioProps iceberg.Properties,
metadataProps iceberg.Properties,
+ opts ...MetadataIOOption,
) (*View, error) {
viewVersion, err := NewVersionFromSQL(
InitialVersionID,
@@ -172,12 +178,13 @@ func CreateViewWithIOProperties(
return nil, err
}
- return CreateViewFromVersion(ctx, viewIdent, schema, viewVersion, loc,
ioProps, metadataProps)
+ return CreateViewFromVersion(ctx, viewIdent, schema, viewVersion, loc,
ioProps, metadataProps, opts...)
}
// CreateViewFromVersion creates a view whose first version is version, kept as
// given apart from its IDs. A nil default namespace defaults to the view's
// namespace, a nil summary to the engine name, and a zero timestamp to now.
+// WithIORegistry affects only filesystem resolution for the metadata write.
func CreateViewFromVersion(
ctx context.Context,
viewIdent table.Identifier,
@@ -186,6 +193,7 @@ func CreateViewFromVersion(
loc string,
ioProps iceberg.Properties,
metadataProps iceberg.Properties,
+ opts ...MetadataIOOption,
) (*View, error) {
if version == nil {
return nil, fmt.Errorf("%w: view version is required",
ErrInvalidViewMetadata)
@@ -215,7 +223,7 @@ func CreateViewFromVersion(
return nil, err
}
- metadataLocation, _, err := WriteMetadata(ctx, viewMD.Metadata, ioProps)
+ metadataLocation, _, err := WriteMetadata(ctx, viewMD.Metadata,
ioProps, opts...)
if err != nil {
return nil, err
}
diff --git a/view/write_metadata.go b/view/write_metadata.go
index 1d73f55ab..48d2b5a17 100644
--- a/view/write_metadata.go
+++ b/view/write_metadata.go
@@ -32,6 +32,20 @@ import (
"github.com/google/uuid"
)
+// MetadataIOOption configures the filesystem used to write view metadata.
+// This is distinct from Option, which configures a loaded View.
+type MetadataIOOption func(*metadataIOOptions)
+
+type metadataIOOptions struct {
+ registry *icebergio.Registry
+}
+
+// WithIORegistry uses a catalog-scoped FileIO registry to write view metadata.
+// A nil registry uses the process-wide default. The registry is shared, not
copied.
+func WithIORegistry(registry *icebergio.Registry) MetadataIOOption {
+ return func(o *metadataIOOptions) { o.registry = registry }
+}
+
// WriteMetadata writes a new view metadata file and returns its location and
// filesystem. The directory comes from table.WriteMetadataPathKey, or defaults
// to <view location>/metadata. Each file has a fresh view-<uuid>.metadata.json
@@ -41,7 +55,13 @@ import (
// cancellation. After a successful write, the caller owns publication and may
// use the returned filesystem to remove the file after a confirmed failed
// commit. A commit with an unknown outcome must retain the file.
-func WriteMetadata(ctx context.Context, metadata Metadata, ioProps
iceberg.Properties) (string, icebergio.WriteFileIO, error) {
+// WithIORegistry selects an isolated filesystem for this write.
+func WriteMetadata(ctx context.Context, metadata Metadata, ioProps
iceberg.Properties, opts ...MetadataIOOption) (string, icebergio.WriteFileIO,
error) {
+ var config metadataIOOptions
+ for _, opt := range opts {
+ opt(&config)
+ }
+
if err := ctx.Err(); err != nil {
return "", nil, err
}
@@ -59,7 +79,11 @@ func WriteMetadata(ctx context.Context, metadata Metadata,
ioProps iceberg.Prope
if err != nil {
return "", nil, fmt.Errorf("failed to marshal view metadata:
%w", err)
}
- fs, err := icebergio.LoadFS(ctx, ioProps, location)
+ loadFS := icebergio.LoadFS
+ if config.registry != nil {
+ loadFS = config.registry.LoadFS
+ }
+ fs, err := loadFS(ctx, ioProps, location)
if err != nil {
return "", nil, fmt.Errorf("failed to load filesystem for view
metadata: %w", err)
}
diff --git a/website/src/api.md b/website/src/api.md
index c496f55d8..72c39ae95 100644
--- a/website/src/api.md
+++ b/website/src/api.md
@@ -887,6 +887,14 @@ v.Properties() // iceberg.Properties
`view.New(ident, meta, metadataLocation)` constructs a view from
already-loaded metadata; `view.NewFromLocation(ctx, ident, metadataLocation,
fsysFactory)` loads metadata from disk or object storage.
+Pass `view.WithIORegistry(registry)` to `view.CreateView`,
+`view.CreateViewWithIOProperties`, `view.CreateViewFromVersion`, or
+`view.WriteMetadata` to use isolated FileIO. For `view.NewFromLocation`,
+pass a filesystem factory from the registry. The IO-properties helpers
+keep filesystem configuration (`ioProps`) separate from persisted view
+properties (`metadataProps`). See
+[FileIO configuration](./configuration.md#file-system-credentials).
+
## Iceberg ↔ Arrow types
When iceberg-go converts an Iceberg schema to Arrow (e.g. for the scanner
output) or vice versa, the type mapping is:
diff --git a/website/src/configuration.md b/website/src/configuration.md
index b1499eca4..47c16cd37 100644
--- a/website/src/configuration.md
+++ b/website/src/configuration.md
@@ -231,6 +231,7 @@ Source:
[`catalog/hive/options.go`](https://github.com/apache/iceberg-go/blob/ma
- `WithURI(uri string)` - Thrift URI for the Hive Metastore (e.g.
`thrift://127.0.0.1:9083`).
- `WithWarehouse(warehouse string)`
- `WithProperties(props iceberg.Properties)`
+- `WithIORegistry(registry *io.Registry)` - use a catalog-scoped FileIO
registry.
Lock-check catalog properties (passed via `WithProperties` / `catalog.Load`
props):
@@ -250,16 +251,18 @@ Source:
[`catalog/glue/options.go`](https://github.com/apache/iceberg-go/blob/ma
- `WithAWSConfig(cfg aws.Config)` - AWS SDK v2 config; respects the AWS
default credential chain.
- `WithAWSProperties(props AWSProperties)` - catalog properties, such as
`glue.id` and the `s3.*` FileIO keys. `NewCatalog` ignores the `glue.region`,
endpoint, credential, and retry keys; only `catalog.Load` reads them.
+- `WithIORegistry(registry *io.Registry)` - use a catalog-scoped FileIO
registry.
### SQL (`catalog/sql`)
-The SQL catalog has no functional-option surface. Construct it with
`NewCatalog`:
+Pass `sqlcat.WithIORegistry(registry)` to `NewCatalog` to select isolated
FileIO:
```go
db, _ := sql.Open(sqliteshim.ShimName, "file:catalog.db")
+registry := io.NewRegistry() // copy currently registered global schemes
cat, err := sqlcat.NewCatalog(ctx, "default", db, sqlcat.SQLite,
iceberg.Properties{
"warehouse": "file:///tmp/warehouse",
-})
+}, sqlcat.WithIORegistry(registry)) // omit option for global FileIO
```
Supported dialects: `sqlcat.Postgres`, `sqlcat.MySQL`, `sqlcat.SQLite`,
`sqlcat.MSSQL`, `sqlcat.Oracle` (`catalog/sql/sql.go:50`).
@@ -446,7 +449,7 @@ Cloud schemes (`s3`, `gs`, `abfs`, etc.) are registered
only when the matching b
`io.GetRegisteredSchemes()` returns the current scheme list;
`io.Unregister(scheme)` removes one.
-To register schemes at runtime without changing other users of the same
process, create an independent registry (catalogs and `view.CreateView` still
resolve through the default registry):
+To register schemes at runtime without changing other users of the same
process, create an independent registry:
```go
registry := io.NewRegistry()
@@ -458,6 +461,27 @@ fs, err := registry.LoadFS(ctx, props, "myfs://bucket/key")
`io.NewRegistry()` copies schemes already registered globally (including
blank-imported cloud backends) but keeps later registrations independent.
`registry.Clone()` makes an isolated copy of another registry.
`registry.Names()` lists the schemes registered in that instance.
`registry.LoadFSFunc()` is the lazy factory equivalent. Global `io.LoadFS()`
and `io.LoadFSFunc()` continue using the default registry.
+Pass the catalog's `WithIORegistry(registry)` option to `NewCatalog` in
+Glue, Hadoop, Hive, REST, or SQL. For direct view metadata creation or
+writes, pass `view.WithIORegistry(registry)` to the view helper.
+Omitting the option or passing nil uses the global registry. An empty
+non-nil registry has no registered schemes. A catalog-scoped registry does
+not affect `catalog.Load`, which uses the global registry with the built-in
+catalog registrars.
+
+The catalog holds the supplied registry, so registering or unregistering a
+scheme affects future FileIO resolutions. Hadoop opens its warehouse
+filesystem during construction and reuses it for warehouse operations.
+Use `registry.Clone()` to give another catalog its own set of schemes.
+
+View metadata creation accepts the same scoped registry option, but reading
+view metadata via `view.NewFromLocation` uses the filesystem factory explicitly
+passed by the caller. A catalog's own load and update methods supply their
+scoped factory. Passing credentials in `ioProps` configures the filesystem;
+only `metadataProps` are persisted in the view metadata.
+
+These FileIO options do not select a KMS implementation.
`encryption.KMSRegistry` is separate; no catalog encryption path currently
loads a KMS client.
+
### Catalog type registry
Register a custom catalog type with
[`catalog.Register`](https://github.com/apache/iceberg-go/blob/main/catalog/registry.go):
diff --git a/website/src/releases.md b/website/src/releases.md
index ee099a1d4..3bfa5ece7 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -42,6 +42,7 @@ Per-release notes (highlights, breaking changes,
contributors) are published on
### Unreleased compatibility notes
+- **Catalog and view FileIO may use isolated registries.** Glue, Hadoop, Hive
and SQL accept `WithIORegistry`, as REST already does. `hadoop.NewCatalog`,
`sql.NewCatalog`, `view.CreateView`, `view.CreateViewWithIOProperties`,
`view.CreateViewFromVersion` and `view.WriteMetadata` now take a trailing
variadic option. Existing calls still compile. Function values assigned to a
type with the old signature need a wrapper that calls the function without
options. The default remains the global [...]
- **`RowDelta.Commit` can be called once per builder.** A second `Commit` on
the same `RowDelta` now returns an error wrapping `table.ErrInvalidOperation`
and stages nothing, even if the first call failed, as `RewriteFiles.Commit`
does. Previously, calling `Commit` again after a failed first call could
succeed, and calling it again after a successful one staged the builder's files
a second time. Create a new builder with `Transaction.NewRowDelta` for each
commit.
- **Data-file replacements now reject concurrent deletes.** Commits staged
through `ReplaceDataFiles`, `ReplaceDataFilesByPath`, `ReplaceFiles`, or
rewrite operations can return `table.ErrConflictingDeleteFiles` when a
concurrent position delete targets a replaced file or any concurrent equality
delete is added. Compaction on tables with streaming equality deletes may see
additional conflicts.
- **Orphan cleanup now rejects `gc.enabled=false`.** `DeleteOrphanFiles`,
`PlanOrphanFiles`, `ExecuteOrphanCleanup`, and dry runs now return an error
before filesystem access. The `iceberg clean-orphan-files` command is also
affected.