# Walkthrough for the blog "Hudi Writes Apache Iceberg V3 Tables on AWS".
# Run inside the pyspark shell started with the command in the blog (Glue catalog settings and HoodieCatalog
# included), after replacing <bucket>/<prefix> and <glue_db>:
#   exec(open("demo.py").read())
# Every printed block matches a step in the blog.

BASE = "s3://<bucket>/<prefix>/tables"
DB = "<glue_db>"   # the Glue database named by spark.hadoop.xtable.iceberg.namespace

# --- trips_mor: DataFrame API, Merge-on-Read, Iceberg format version 3 ---------------------------------------------
options = {
    "hoodie.table.name": "trips_mor",
    "hoodie.datasource.write.recordkey.field": "key",
    "hoodie.datasource.write.partitionpath.field": "region",
    "hoodie.datasource.write.table.type": "MERGE_ON_READ",
    # write the table as an Iceberg table, at format version 3 (the default)
    "hoodie.table.format": "ICEBERG",
    # write an update as a deletion vector on the old file plus the new row
    "hoodie.write.updates.as.deletes.and.inserts": "true",
    # write the Iceberg field IDs into every Parquet file, for readers such as DuckDB
    "hoodie.avro.write.support.class": "org.apache.xtable.hudi.extensions.HoodieAvroWriteSupportWithFieldIds",
    "hoodie.client.init.callback.classes": "org.apache.xtable.hudi.extensions.AddFieldIdsClientInitCallback",
    "hoodie.datasource.write.row.writer.enable": "false",
}


def write(rows, operation):
    (spark.createDataFrame(rows, "key string, region string, rider string, fare double")
       .write.format("hudi").options(**options)
       .option("hoodie.datasource.write.operation", operation)
       .mode("append").save(f"{BASE}/trips_mor"))


def files(name):
    spark.sql(f"SELECT content, file_format, partition.region, record_count FROM glue.{DB}.{name}.files").show()


print("\n### DataFrame: create the table")
write([("t1", "us", "alice", 12.5), ("t2", "us", "bob", 20.0), ("t3", "us", "carol", 8.0),
       ("t4", "eu", "dave", 15.0), ("t5", "eu", "erin", 30.0), ("t6", "eu", "frank", 9.5)], "insert")
spark.sql(f"SELECT key, region, rider, fare, _row_id FROM glue.{DB}.trips_mor ORDER BY key").show()

print("\n### DataFrame: update and insert")
write([("t2", "us", "bob", 22.0), ("t5", "eu", "erin", 31.0), ("t7", "eu", "grace", 18.0)], "upsert")
spark.sql(f"SELECT key, region, rider, fare, _row_id FROM glue.{DB}.trips_mor ORDER BY key").show()
files("trips_mor")

print("\n### DataFrame: delete")
write([("t3", "us", "carol", 8.0), ("t6", "eu", "frank", 9.5)], "delete")
spark.sql(f"SELECT key, region, rider, fare FROM glue.{DB}.trips_mor ORDER BY key").show()

# --- trips_cow: Spark SQL, Copy-on-Write, Iceberg format version 2 ------------------------------------------------
print("\n### Spark SQL: create, insert, update, merge into, delete")
spark.sql("CREATE DATABASE IF NOT EXISTS hudi_sql")
spark.sql(f"""
  CREATE TABLE hudi_sql.trips_cow (key STRING, rider STRING, fare DOUBLE, region STRING)
  USING hudi
  PARTITIONED BY (region)
  LOCATION '{BASE}/trips_cow'
  TBLPROPERTIES (
    primaryKey = 'key',
    type = 'cow',
    'hoodie.table.format' = 'ICEBERG',
    'hoodie.table.format.iceberg.format.version' = '2'
  )""")
spark.sql("""INSERT INTO hudi_sql.trips_cow VALUES
  ('t1', 'alice', 12.5, 'us'), ('t2', 'bob', 20.0, 'us'), ('t3', 'carol', 8.0, 'us'),
  ('t4', 'dave', 15.0, 'eu'), ('t5', 'erin', 30.0, 'eu'), ('t6', 'frank', 9.5, 'eu')""")
spark.sql("UPDATE hudi_sql.trips_cow SET fare = 22.0 WHERE key = 't2'")
spark.sql("""
  MERGE INTO hudi_sql.trips_cow t
  USING (SELECT 't5' AS key, 'erin' AS rider, 31.0 AS fare, 'eu' AS region
         UNION ALL SELECT 't7', 'grace', 18.0, 'eu') s
  ON t.key = s.key
  WHEN MATCHED THEN UPDATE SET *
  WHEN NOT MATCHED THEN INSERT *""")
spark.sql("DELETE FROM hudi_sql.trips_cow WHERE key IN ('t3', 't6')")
spark.sql(f"SELECT key, region, rider, fare FROM glue.{DB}.trips_cow ORDER BY key").show()
spark.sql(f"SELECT snapshot_id, operation FROM glue.{DB}.trips_cow.snapshots ORDER BY committed_at").show()

# --- table services on trips_mor ------------------------------------------------------------------------------------
print("\n### Compaction folds the deletion vectors into new base files")
# table services write data files too, so they take the same three field ID options
fid = ",".join(f"{k}={options[k]}" for k in (
    "hoodie.avro.write.support.class", "hoodie.client.init.callback.classes", "hoodie.datasource.write.row.writer.enable"))
# compaction is scheduled after 5 delta commits by default; this table has 3
spark.sql(f"""CALL run_compaction(op => 'scheduleAndExecute', path => '{BASE}/trips_mor',
             options => 'hoodie.compact.inline.max.delta.commits=1,{fid}')""").show(truncate=False)
files("trips_mor")

print("\n### Clustering, and the Iceberg history of trips_mor")
spark.sql(f"CALL run_clustering(path => '{BASE}/trips_mor', options => '{fid}')").show(truncate=False)
spark.sql(f"""SELECT snapshot_id, operation, summary['added-data-files'] AS added_files,
             summary['deleted-data-files'] AS removed_files, summary['added-delete-files'] AS added_dvs,
             summary['total-records'] AS total_records
             FROM glue.{DB}.trips_mor.snapshots ORDER BY committed_at""").show(truncate=False)

print("\n### Spark: time travel to the first snapshot of trips_mor")
first = spark.sql(f"SELECT snapshot_id FROM glue.{DB}.trips_mor.snapshots ORDER BY committed_at LIMIT 1").first()[0]
spark.sql(f"SELECT key, region, rider, fare FROM glue.{DB}.trips_mor VERSION AS OF {first} ORDER BY key").show()

print("\n### Hudi incremental query: rows of the commits completed after the first Iceberg snapshot")
begin = spark.sql(f"""SELECT date_format(committed_at, 'yyyyMMddHHmmssSSS')
                      FROM glue.{DB}.trips_mor.snapshots WHERE snapshot_id = {first}""").first()[0]
(spark.read.format("hudi").option("hoodie.datasource.query.type", "incremental")
    .option("hoodie.datasource.read.begin.instanttime", begin).load(f"{BASE}/trips_mor")
    .select("_hoodie_commit_time", "key", "rider", "fare").orderBy("key").show(truncate=False))

print("\n### Iceberg row lineage: rows changed since the insert (sequence number 1)")
spark.sql(f"""SELECT key, rider, fare, _row_id, _last_updated_sequence_number
             FROM glue.{DB}.trips_mor WHERE _last_updated_sequence_number > 1 ORDER BY key""").show()
