1717
1818package org .apache .spark .sql
1919
20- import java .io .{ByteArrayOutputStream , CharArrayWriter , DataOutputStream }
20+ import java .io .{ByteArrayOutputStream , CharArrayWriter , DataOutputStream , File }
21+ import java .util .UUID
2122
2223import scala .annotation .varargs
2324import scala .collection .JavaConverters ._
@@ -39,7 +40,7 @@ import org.apache.spark.rdd.RDD
3940import org .apache .spark .scheduler .RepeatableIterator
4041import org .apache .spark .sql .catalyst .{CatalystTypeConverters , InternalRow , QueryPlanningTracker , ScalaReflection , TableIdentifier }
4142import org .apache .spark .sql .catalyst .analysis ._
42- import org .apache .spark .sql .catalyst .catalog .HiveTableRelation
43+ import org .apache .spark .sql .catalyst .catalog .{ CatalogStorageFormat , CatalogTable , CatalogTableType , HiveTableRelation }
4344import org .apache .spark .sql .catalyst .encoders ._
4445import org .apache .spark .sql .catalyst .expressions ._
4546import org .apache .spark .sql .catalyst .json .{JacksonGenerator , JSONOptions }
@@ -3798,6 +3799,30 @@ class Dataset[T] private[sql](
37983799 this
37993800 }
38003801
3802+ def persistWithTempTable (): DataFrame = {
3803+ persistWithTempTable(UUID .randomUUID().toString.replace('-' , '_' ))
3804+ }
3805+
3806+ def persistWithTempTable (tableName : String ): DataFrame = sparkSession.withActive {
3807+ val sessionPath = sparkSession.sessionState.catalog.sessionPath
3808+ val table =
3809+ CatalogTable (
3810+ TableIdentifier (tableName),
3811+ CatalogTableType .TEMPORARY ,
3812+ CatalogStorageFormat .empty.copy(
3813+ locationUri = Some (sessionPath.suffix(File .separator + tableName).toUri)),
3814+ StructType (Nil ),
3815+ provider = Some (sparkSession.sessionState.conf.defaultDataSourceName))
3816+
3817+ CreateDataSourceTableAsSelectCommand (
3818+ table,
3819+ SaveMode .ErrorIfExists ,
3820+ logicalPlan,
3821+ logicalPlan.output.map(_.name)).run(sparkSession)
3822+
3823+ sparkSession.table(tableName)
3824+ }
3825+
38013826 /**
38023827 * Persist this Dataset with the default storage level (`MEMORY_AND_DISK`).
38033828 *
0 commit comments