Skip to content

Instantly share code, notes, and snippets.

@AoJ
Created August 4, 2020 07:33
Show Gist options
  • Save AoJ/adea281e8f11c2f58e0ab432dcf9081a to your computer and use it in GitHub Desktop.
Save AoJ/adea281e8f11c2f58e0ab432dcf9081a to your computer and use it in GitHub Desktop.
Spark - dump sql create into files
mkdir /tmp/sqltables
spark2-shell
val dbname = "some_db"
val targetdir = "/tmp/sqltables"
spark.sql(s"show tables in `${dbname}`").collect.foreach(r => {
  import scala.util.{Try,Success,Failure}
  import reflect.io.File
  val db = r.getString(0)
  val table = r.getString(1)
  val sql = s"show create table `${db}`.`${table}`"
  println(s"INFO: db: ${db}, table: ${table}, sql: ${sql}")
  Try(spark.sql(sql).first.getString(0)) match {
    case Success(craetetable) =>
      File(s"${targetdir}/${db}.${table}.sql").writeAll(craetetable)
    case Failure(e) =>
      println(s"ERROR: can't call sql: ${sql}")
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment