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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ package iceberg
import com.typesafe.scalalogging.LazyLogging
import org.apache.iceberg.catalog.{Catalog, TableIdentifier}
import org.apache.iceberg.expressions.Expressions
import org.apache.iceberg.types.{Type, TypeUtil}
import org.apache.iceberg.types.Types.NestedField
import org.apache.iceberg.{PartitionSpec, UpdateSchema}
import org.geotools.api.feature.`type`.AttributeDescriptor
import org.geotools.feature.simple.SimpleFeatureTypeBuilder
import org.locationtech.geomesa.fs.storage.core.StorageCatalog.CatalogUpdate
import org.locationtech.geomesa.fs.storage.core.parquet.BloomFilterConfig
import org.locationtech.geomesa.fs.storage.core.parquet.schema.GeometrySchema.GeometryEncoding
import org.locationtech.geomesa.fs.storage.core.schema.ColumnName
import org.locationtech.geomesa.fs.storage.core.schemes.PartitionSchemeFactory
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
Expand All @@ -34,6 +36,7 @@ import org.locationtech.jts.geom.{Geometry, Point}
class IcebergSchemaEvolution(catalog: Catalog, tableId: TableIdentifier) extends CatalogUpdate with LazyLogging {

import IcebergSchemaEvolution.{attributeProperty, bloomFilterKeys, colsFor}
import org.locationtech.geomesa.utils.geotools.RichAttributeDescriptors.RichAttributeDescriptor

import scala.collection.JavaConverters._

Expand Down Expand Up @@ -70,21 +73,41 @@ class IcebergSchemaEvolution(catalog: Catalog, tableId: TableIdentifier) extends
SimpleFeatureTypes.encodeType(schema.sft))
}

val existingIsGeom = classOf[Geometry].isAssignableFrom(existing.getType.getBinding)
val updateIsGeom = classOf[Geometry].isAssignableFrom(update.getType.getBinding)

val tx = table.newTransaction()

if (classOf[Geometry].isAssignableFrom(existing.getType.getBinding)) {
if (existingIsGeom || updateIsGeom) {
// we don't need to make any actual column changes, just validate that the op is allowed
if (existing.getType.getBinding == classOf[Point] || update.getType.getBinding != classOf[Geometry]) {
if (!existingIsGeom || !updateIsGeom) {
throw new UnsupportedOperationException(
s"Attribute '${existing.getLocalName}' can not be changed from ${existing.getType.getBinding.getSimpleName} " +
s"to ${update.getType.getBinding.getSimpleName}: geometry attributes can't be converted to or from " +
"non-geometry types")
} else if (existing.getType.getBinding != update.getType.getBinding &&
(existing.getType.getBinding == classOf[Point] || update.getType.getBinding != classOf[Geometry])) {
throw new UnsupportedOperationException(
s"Attribute '${existing.getLocalName}' can not be changed from ${existing.getType.getBinding} " +
s"to ${update.getType.getBinding.getSimpleName}: the only supported geometry change is widening non-point types " +
s"to mixed Geometry")
s"Attribute '${existing.getLocalName}' can not be changed from ${existing.getType.getBinding.getSimpleName} " +
s"to ${update.getType.getBinding.getSimpleName}: the only supported geometry change is widening non-point " +
"types to mixed Geometry")
}
// the stored data is always wkb, so the encoding can't be changed
update.getEncoding.foreach { encoding =>
if (GeometryEncoding(encoding) != GeometryEncoding.GeoParquetWkb) {
throw new UnsupportedOperationException(
s"Attribute '${existing.getLocalName}' can not be changed to encoding '$encoding': " +
"only WKB encoding is supported for geometry types")
}
}
} else {
// assertion: only geometry types create more than 1 column, so we only need to deal with .head
val column = IcebergSchemaEvolution.colsFor(update).head
val updateSchema = tx.updateSchema()
walkColumnUpdates(null, column, schema.schema.findField(column.name()), updateSchema)
val existingColumn = schema.schema.findField(column.name())
val path = FieldPath(existing.getLocalName, column.name())
checkNullabilityUpdates(path, column.isOptional, existingColumn.isOptional, updateSchema)
walkTypeUpdates(path, column.`type`(), existingColumn.`type`(), updateSchema)
updateSchema.commit()
}

Expand All @@ -94,28 +117,67 @@ class IcebergSchemaEvolution(catalog: Catalog, tableId: TableIdentifier) extends
}
}

private def walkColumnUpdates(parent: String, update: NestedField, existing: NestedField, op: UpdateSchema): Unit = {
if (existing == null) {
op.addColumn(parent, update.name(), update.`type`())
} else if (update.`type`() != existing.`type`()) {
val path = Option(parent).fold(update.name())(p => s"$p.${update.name()}")
if (update.`type`().isStructType && existing.`type`().isStructType) {
val updateStruct = update.`type`().asStructType()
val existingStruct = existing.`type`().asStructType()
updateStruct.fields().asScala.foreach { field =>
walkColumnUpdates(path, field, existingStruct.field(field.name()), op)
private def checkNullabilityUpdates(path: FieldPath, updateOptional: Boolean, existingOptional: Boolean, op: UpdateSchema): Unit = {
if (updateOptional && !existingOptional) {
op.makeColumnOptional(path.column)
} else if (!updateOptional && existingOptional) {
// existing data may contain nulls, so this isn't safe
throw path.error("can't be changed from optional to required")
}
}

// note: nested types are compared structurally, as the field ids of the update will not match the existing ids
// noinspection NoTailRecursionAnnotation
private def walkTypeUpdates(path: FieldPath, update: Type, existing: Type, op: UpdateSchema): Unit = {
if (update.isStructType && existing.isStructType) {
val updateStruct = update.asStructType()
val existingStruct = existing.asStructType()
updateStruct.fields().asScala.foreach { field =>
walkStructFields(path, field, existingStruct.field(field.name()), op)
}
existingStruct.fields().asScala.foreach { field =>
if (updateStruct.field(field.name()) == null) {
op.deleteColumn(s"${path.column}.${field.name()}")
}
existingStruct.fields().asScala.foreach { field =>
if (updateStruct.field(field.name()) == null) {
op.deleteColumn(s"$path.${field.name()}")
}
}
} else if (update.isListType && existing.isListType) {
val updateList = update.asListType()
val existingList = existing.asListType()
val element = path.element
checkNullabilityUpdates(element, updateList.isElementOptional, existingList.isElementOptional, op)
walkTypeUpdates(element, updateList.elementType(), existingList.elementType(), op)
} else if (update.isMapType && existing.isMapType) {
val updateMap = update.asMapType()
val existingMap = existing.asMapType()
if (!updateMap.keyType().isPrimitiveType || !existingMap.keyType().isPrimitiveType) {
// note: geomesa and avro maps always have primitive keys, so this shouldn't come up in practice
throw path.error("can't be updated, as only maps with primitive keys are supported")
} else if (updateMap.keyType() != existingMap.keyType()) {
throw path.error(s"can't change map keys from ${existingMap.keyType()} to ${updateMap.keyType()}")
}
val value = path.value
checkNullabilityUpdates(value, updateMap.isValueOptional, existingMap.isValueOptional, op)
walkTypeUpdates(value, updateMap.valueType(), existingMap.valueType(), op)
} else if (update.isPrimitiveType && existing.isPrimitiveType) {
if (update != existing) {
if (!TypeUtil.isPromotionAllowed(existing, update.asPrimitiveType())) {
throw path.error(s"can't be changed from $existing to $update: the only supported primitive type changes " +
"are widening int to long and float to double")
}
} else if (update.`type`().isPrimitiveType && existing.`type`().isPrimitiveType) {
op.updateColumn(path, update.`type`().asPrimitiveType())
} else {
throw new UnsupportedOperationException(
s"Attribute '$path' can't be changed from ${existing.`type`()} to ${update.`type`()}")
op.updateColumn(path.column, update.asPrimitiveType())
}
} else if (update != existing) {
throw path.error(s"can't be changed from $existing to $update")
}
}

private def walkStructFields(parent: FieldPath, update: NestedField, existing: NestedField, op: UpdateSchema): Unit = {
if (existing == null) {
op.addColumn(parent.column, update.name(), update.`type`())
} else {
val path = parent.field(update.name())
checkNullabilityUpdates(path, update.isOptional, existing.isOptional, op)
walkTypeUpdates(path, update.`type`(), existing.`type`(), op)
}
}

Expand Down Expand Up @@ -191,6 +253,23 @@ class IcebergSchemaEvolution(catalog: Catalog, tableId: TableIdentifier) extends
}
}
}

/**
* Path to a (possibly nested) field
*
* @param attribute top-level attribute name, used for error messages
* @param column iceberg column path, used for schema updates
* @param display user-facing description of the nested field, used for error messages
*/
private case class FieldPath(attribute: String, column: String, display: Option[String] = None) {
def field(name: String): FieldPath = FieldPath(attribute, s"$column.$name", Some(display.fold(name)(d => s"$d.$name")))
def element: FieldPath = FieldPath(attribute, s"$column.element", Some(s"${display.getOrElse("")}[element]"))
def value: FieldPath = FieldPath(attribute, s"$column.value", Some(s"${display.getOrElse("")}[value]"))
def error(msg: String): UnsupportedOperationException = {
val location = display.fold("")(d => s" (nested field '$d')")
new UnsupportedOperationException(s"Attribute '$attribute'$location $msg")
}
}
}

private object IcebergTableUpdate extends CatalogUpdate.TableUpdate {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,121 @@ class IcebergSchemaEvolutionTest extends SpecificationWithJUnit with BeforeAfter
}
}

"update attribute options without changing columns" in {
withCatalog { catalog =>
val before = WithClose(catalog.load(sft.getTypeName))(_.table.schema())
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("name:String:index=true"))
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("*geom:Point:srid=4326"))
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("dtg:Date:foo=bar"))
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().sameSchema(before) must beTrue
storage.sft.getDescriptor("name").getUserData.get("index") mustEqual "true"
storage.sft.getDescriptor("dtg").getUserData.get("foo") mustEqual "bar"
storage.sft.getGeometryDescriptor.getLocalName mustEqual "geom"
testQuery(storage, storage.sft, "INCLUDE", null, features)
}
}
}

"update list and map columns" in {
val sft = SimpleFeatureTypes.createType("collections", "names:List[String],counts:Map[String,Int],dtg:Date,*geom:Point:srid=4326")
WithClose(StorageCatalog(newPath())) { catalog =>
WithClose(catalog.create(sft, Seq("day"))) { _ => }
val before = WithClose(catalog.load(sft.getTypeName))(_.table.schema())
// no-op updates of list/map types shouldn't fail, even though the field ids won't match
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("names:List[String]:foo=bar"))
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("counts:Map[String,Int]"))
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().sameSchema(before) must beTrue
storage.sft.getDescriptor("names").getUserData.get("foo") mustEqual "bar"
}
// widen the element and value types
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("counts:Map[String,Long]"))
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.sft.getDescriptor("counts").getMapTypes() mustEqual (classOf[String], classOf[java.lang.Long])
}
val beforeInvalid = WithClose(catalog.load(sft.getTypeName))(s => (s.table.schema(), SimpleFeatureTypes.encodeType(s.sft)))
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("counts:Map[Int,Long]")) must
throwAn[UnsupportedOperationException]
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("counts:Map[String,Int]")) must
throwAn[UnsupportedOperationException]
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("names:List[Int]")) must
throwAn[UnsupportedOperationException]
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().sameSchema(beforeInvalid._1) must beTrue
SimpleFeatureTypes.encodeType(storage.sft) mustEqual beforeInvalid._2
}
}
}

"update nullability of nested fields" in {
withCatalog { catalog =>
val countPath = "json.count"
WithClose(catalog.load(sft.getTypeName))(_.table.schema().findField(countPath).isRequired must beTrue)
val optionalType =
"""{"type":"record","name":"properties","fields":[{"name":"count","type":["null","int"]},{"name":"name","type":"string"}]}"""
catalog.update(sft.getTypeName).columns().update(
SimpleFeatureTypes.createDescriptor(s"json:String:json=true:json-schema='$optionalType'"))
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().findField(countPath).isOptional must beTrue
storage.sft.getDescriptor("json").getJsonSchema() must beSome(optionalType)
}
// optional -> required isn't allowed, as existing data may contain nulls
val before = WithClose(catalog.load(sft.getTypeName))(s => (s.table.schema(), SimpleFeatureTypes.encodeType(s.sft)))
catalog.update(sft.getTypeName).columns().update(
SimpleFeatureTypes.createDescriptor(s"json:String:json=true:json-schema='$structuralType'")) must
throwAn[UnsupportedOperationException]
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().sameSchema(before._1) must beTrue
SimpleFeatureTypes.encodeType(storage.sft) mustEqual before._2
}
}
}

"update nullability of list elements" in {
val requiredList = """{"type":"array","items":"string"}"""
val optionalList = """{"type":"array","items":["null","string"]}"""
val sft = SimpleFeatureTypes.createType("nullable-lists",
s"tags:String:json=true:json-schema='$requiredList',dtg:Date,*geom:Point:srid=4326")
WithClose(StorageCatalog(newPath())) { catalog =>
WithClose(catalog.create(sft, Seq("day"))) { _ => }
WithClose(catalog.load(sft.getTypeName))(_.table.schema().findField("tags").`type`().asListType().isElementRequired must beTrue)
catalog.update(sft.getTypeName).columns().update(
SimpleFeatureTypes.createDescriptor(s"tags:String:json=true:json-schema='$optionalList'"))
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().findField("tags").`type`().asListType().isElementOptional must beTrue
}
catalog.update(sft.getTypeName).columns().update(
SimpleFeatureTypes.createDescriptor(s"tags:String:json=true:json-schema='$requiredList'")) must
throwAn[UnsupportedOperationException]
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().findField("tags").`type`().asListType().isElementOptional must beTrue
storage.sft.getDescriptor("tags").getJsonSchema() must beSome(optionalList)
}
}
}

"reject invalid geometry updates" in {
withCatalog { catalog =>
val before = WithClose(catalog.load(sft.getTypeName))(s => (s.table.schema(), SimpleFeatureTypes.encodeType(s.sft)))
foreach(Seq("name:Point:srid=4326", "geom:String", "geom:LineString:srid=4326", "*geom:Point:srid=4326:encoding=native")) { spec =>
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor(spec)) must
throwAn[UnsupportedOperationException]
}
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().sameSchema(before._1) must beTrue
SimpleFeatureTypes.encodeType(storage.sft) mustEqual before._2
testQuery(storage, storage.sft, "INCLUDE", null, features)
}
// explicit wkb encoding is fine
catalog.update(sft.getTypeName).columns().update(SimpleFeatureTypes.createDescriptor("*geom:Point:srid=4326:encoding=wkb"))
WithClose(catalog.load(sft.getTypeName)) { storage =>
storage.table.schema().sameSchema(before._1) must beTrue
testQuery(storage, storage.sft, "INCLUDE", null, features)
}
}
}

"change the partition spec" in {
withCatalog { catalog =>
catalog.update(sft.getTypeName).table().setPartitions(Seq("z2:bits=4", "month"))
Expand Down
Loading