zeroshade commented on code in PR #246: URL: https://github.com/apache/iceberg-go/pull/246#discussion_r1932844716
########## catalog/sql/sql.go: ########## @@ -0,0 +1,712 @@ +// 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 + +import ( + "context" + "database/sql" + "errors" + "fmt" + "maps" + "path" + "slices" + "strings" + "sync" + _ "unsafe" + + "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/uptrace/bun" + "github.com/uptrace/bun/dialect/feature" + "github.com/uptrace/bun/dialect/mssqldialect" + "github.com/uptrace/bun/dialect/mysqldialect" + "github.com/uptrace/bun/dialect/oracledialect" + "github.com/uptrace/bun/dialect/pgdialect" + "github.com/uptrace/bun/dialect/sqlitedialect" + "github.com/uptrace/bun/extra/bundebug" + "github.com/uptrace/bun/schema" +) + +type SupportedDialect string + +const ( + Postgres SupportedDialect = "postgres" + MySQL SupportedDialect = "mysql" + SQLite SupportedDialect = "sqlite" + MSSQL SupportedDialect = "mssql" + Oracle SupportedDialect = "oracle" +) + +const ( + DialectKey = "sql.dialect" + DriverKey = "sql.driver" + initCatalogTablesKey = "init_catalog_tables" +) + +func init() { + catalog.Register("sql", catalog.RegistrarFunc(func(name string, p iceberg.Properties) (c catalog.Catalog, err error) { + driver, ok := p[DriverKey] + if !ok { + return nil, errors.New("must provide driver to pass to sql.Open") + } + + dialect := strings.ToLower(p[DialectKey]) + if dialect == "" { + return nil, errors.New("must provide sql dialect to use") + } + + uri := strings.TrimPrefix(p.Get("uri", ""), "sql://") + sqldb, err := sql.Open(driver, uri) + if err != nil { + return nil, err + } + + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("failed to create SQL catalog: %v", r) + } + }() + + return NewCatalog(p.Get(name, "sql"), sqldb, SupportedDialect(dialect), p) + })) +} + +var ( + _ catalog.Catalog = (*Catalog)(nil) +) + +var ( + minimalNamespaceProps = iceberg.Properties{"exists": "true"} + + dialects = map[SupportedDialect]schema.Dialect{} + dialectMx sync.Mutex +) + +func createDialect(d SupportedDialect) schema.Dialect { + switch d { + case Postgres: + return pgdialect.New() + case MySQL: + return mysqldialect.New() + case SQLite: + return sqlitedialect.New() + case MSSQL: + return mssqldialect.New() + case Oracle: + return oracledialect.New() + default: + panic("unsupported sql dialect") + } +} + +func getDialect(d SupportedDialect) schema.Dialect { + dialectMx.Lock() + defer dialectMx.Unlock() + ret, ok := dialects[d] + if !ok { + ret = createDialect(d) + dialects[d] = ret + } + return ret +} + +type sqlIcebergTable struct { + bun.BaseModel `bun:"table:iceberg_tables"` + + CatalogName string `bun:",pk"` + TableNamespace string `bun:",pk"` + TableName string `bun:",pk"` + MetadataLocation sql.NullString + PreviousMetadataLocation sql.NullString +} + +type sqlIcebergNamespaceProps struct { + bun.BaseModel `bun:"table:iceberg_namespace_properties"` + + CatalogName string `bun:",pk"` + Namespace string `bun:",pk"` + PropertyKey string `bun:",pk"` + PropertyValue sql.NullString +} + +func withReadTx[R any](ctx context.Context, db *bun.DB, fn func(context.Context, bun.Tx) (R, error)) (result R, err error) { + db.RunInTx(ctx, &sql.TxOptions{ReadOnly: true}, func(ctx context.Context, tx bun.Tx) error { + result, err = fn(ctx, tx) + return err + }) + return +} + +func withWriteTx(ctx context.Context, db *bun.DB, fn func(context.Context, bun.Tx) error) error { + return db.RunInTx(ctx, &sql.TxOptions{Isolation: sql.LevelLinearizable}, func(ctx context.Context, tx bun.Tx) error { + return fn(ctx, tx) + }) +} + +type Catalog struct { + db *bun.DB + name string + props iceberg.Properties +} + +// NewCatalog creates a new sql-based catalog using the provided sql.DB handle to perform any queries. +// +// The dialect parameter determines the SQL dialect to use for query generation and must be one of the +// supported dialects, i.e. one of the exported SupportedDialect values. The separation here allows for +// the use of different drivers/databases provided they support the chosen sql dialect (e.g. if a particular +// database supports the MySQL dialect, then the database can still be used with this catalog even though +// it's not explicitly implemented). +// +// If the "init_catalog_tables" property is set to "true", then creating the catalog will also attempt to +// to verify whether the necessary tables (iceberg_tables and iceberg_namespace_properties) exist, creating +// them if they do not already exist. +// +// The environment variable ICEBERG_SQL_DEBUG can be set to automatically log the sql queries to the terminal: +// - ICEBERG_SQL_DEBUG=1 logs only failed queries +// - ICEBERG_SQL_DEBUG=2 logs all queries +// +// All interactions with the db are performed within transactions to ensure atomicity and transactional isolation +// of catalog changes. +func NewCatalog(name string, db *sql.DB, dialect SupportedDialect, props iceberg.Properties) (*Catalog, error) { + cat := &Catalog{db: bun.NewDB(db, getDialect(dialect)), name: name, props: props} + + cat.db.AddQueryHook(bundebug.NewQueryHook( + bundebug.WithEnabled(false), + // ICEBERG_SQL_DEBUG=1 logs only failed queries + // ICEBERG_SQL_DEBUG=2 log all queries + bundebug.FromEnv("ICEBERG_SQL_DEBUG"))) + + if cat.props.GetBool(initCatalogTablesKey, true) { + return cat, cat.ensureTablesExist() + } + + return cat, nil +} + +func (c *Catalog) Name() string { return c.name } + +func (c *Catalog) CatalogType() catalog.Type { + return catalog.SQL +} + +func (c *Catalog) CreateSQLTables(ctx context.Context) error { + _, err := c.db.NewCreateTable().Model((*sqlIcebergTable)(nil)). + IfNotExists().Exec(ctx) + if err != nil { + return err + } + + _, err = c.db.NewCreateTable().Model((*sqlIcebergNamespaceProps)(nil)). + IfNotExists().Exec(ctx) + return err +} + +func (c *Catalog) DropSQLTables(ctx context.Context) error { + _, err := c.db.NewDropTable().Model((*sqlIcebergTable)(nil)). + IfExists().Exec(ctx) + if err != nil { + return err + } + + _, err = c.db.NewDropTable().Model((*sqlIcebergNamespaceProps)(nil)). + IfExists().Exec(ctx) + return err +} + +func (c *Catalog) ensureTablesExist() error { + return c.CreateSQLTables(context.Background()) +} + +func (c *Catalog) namespaceExists(ctx context.Context, ns string) (bool, error) { + return withReadTx(ctx, c.db, func(ctx context.Context, tx bun.Tx) (bool, error) { + exists, err := tx.NewSelect().Model((*sqlIcebergTable)(nil)). + Where("catalog_name = ?", c.name). + Where("table_namespace = ?", ns). + Limit(1).Exists(ctx) + if err != nil { + return false, err + } + if exists { + return true, nil + } + + return tx.NewSelect().Model((*sqlIcebergNamespaceProps)(nil)). + Where("catalog_name = ?", c.name).Where("namespace = ?", ns). + Limit(1).Exists(ctx) + }) +} + +func (c *Catalog) getDefaultWarehouseLocation(ctx context.Context, nsname, tableName string) (string, error) { + dbprops, err := c.LoadNamespaceProperties(ctx, strings.Split(nsname, ".")) + if err != nil { + return "", err + } + + if dblocation := dbprops.Get("location", ""); dblocation != "" { + return path.Join(dblocation, tableName), nil + } + + if warehousepath := c.props.Get("warehouse", ""); warehousepath != "" { + return warehousepath + "/" + path.Join(nsname+".db", tableName), nil + } + + return "", errors.New("no default path set, please specify a location when creating a table") +} + +func (c *Catalog) resolveTableLocation(ctx context.Context, loc, nsname, tablename string) (string, error) { + if len(loc) == 0 { + return c.getDefaultWarehouseLocation(ctx, nsname, tablename) + } + + return strings.TrimSuffix(loc, "/"), nil +} + +func checkValidNamespace(ident table.Identifier) error { + if len(ident) < 1 { + return fmt.Errorf("%w: empty namespace identifier", catalog.ErrNoSuchNamespace) + } + return nil +} + +func (c *Catalog) CreateTable(ctx context.Context, ident table.Identifier, sc *iceberg.Schema, opts ...catalog.CreateTableOpt) (*table.Table, error) { + var cfg internal.CreateTableCfg + for _, opt := range opts { + opt(&cfg) + } + + nsIdent := catalog.NamespaceFromIdent(ident) + tblIdent := catalog.TableNameFromIdent(ident) + ns := strings.Join(nsIdent, ".") + exists, err := c.namespaceExists(ctx, ns) + if err != nil { + return nil, err + } + + if !exists { + return nil, fmt.Errorf("%w: %s", catalog.ErrNoSuchNamespace, ns) + } + + loc, err := c.resolveTableLocation(ctx, cfg.Location, ns, tblIdent) + if err != nil { + return nil, err + } + + metadataLocation := internal.GetMetadataLoc(loc, 0) + metadata, err := table.NewMetadata(sc, cfg.PartitionSpec, cfg.SortOrder, loc, cfg.Properties) + if err != nil { + return nil, err + } + + if err := internal.WriteMetadata(metadata, metadataLocation, c.props); err != nil { + return nil, err + } + + err = withWriteTx(ctx, c.db, func(ctx context.Context, tx bun.Tx) error { + _, err := tx.NewInsert().Model(&sqlIcebergTable{ + CatalogName: c.name, + TableNamespace: ns, + TableName: tblIdent, + MetadataLocation: sql.NullString{String: metadataLocation, Valid: true}, + }).Exec(ctx) + + if err != nil { + return fmt.Errorf("failed to create table: %w", err) + } + return nil + }) + + if err != nil { + return nil, err + } + + return c.LoadTable(ctx, ident, cfg.Properties) +} + +func (c *Catalog) CommitTable(ctx context.Context, tbl *table.Table, reqs []table.Requirement, updates []table.Update) (table.Metadata, string, error) { + panic("commit table not implemented for SQLCatalog") Review Comment: that's the pattern we've been doing so far. if it would be preferable to have the unimplemented methods return a `NotYetImplemented` error, then I can change all of them (for all the catalogs) in a follow up PR rather than increase the size of this PR. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org